text
stringlengths 54
60.6k
|
---|
<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "private/qdeclarativedebugserver_p.h"
#include "private/qdeclarativedebugservice_p.h"
#include "private/qdeclarativedebugservice_p_p.h"
#include "private/qdeclarativeengine_p.h"
#include <QtCore/QDir>
#include <QtCore/QPluginLoader>
#include <QtCore/QStringList>
#include <private/qobject_p.h>
#include <private/qapplication_p.h>
QT_BEGIN_NAMESPACE
/*
QDeclarativeDebug Protocol (Version 1):
handshake:
1. Client sends
"QDeclarativeDebugServer" 0 version pluginNames
version: an int representing the highest protocol version the client knows
pluginNames: plugins available on client side
2. Server sends
"QDeclarativeDebugClient" 0 version pluginNames
version: an int representing the highest protocol version the client & server know
pluginNames: plugins available on server side. plugins both in the client and server message are enabled.
client plugin advertisement
1. Client sends
"QDeclarativeDebugServer" 1 pluginNames
server plugin advertisement
1. Server sends
"QDeclarativeDebugClient" 1 pluginNames
plugin communication:
Everything send with a header different to "QDeclarativeDebugServer" is sent to the appropriate plugin.
*/
const int protocolVersion = 1;
class QDeclarativeDebugServerPrivate : public QObjectPrivate
{
Q_DECLARE_PUBLIC(QDeclarativeDebugServer)
public:
QDeclarativeDebugServerPrivate();
void advertisePlugins();
QDeclarativeDebugServerConnection *connection;
QHash<QString, QDeclarativeDebugService *> plugins;
QStringList clientPlugins;
bool gotHello;
QString waitingForMsgFromService;
private:
// private slot
void _q_deliverMessage(const QString &serviceName, const QByteArray &message);
static QDeclarativeDebugServerConnection *loadConnectionPlugin(const QString &pluginName);
};
QDeclarativeDebugServerPrivate::QDeclarativeDebugServerPrivate() :
connection(0),
gotHello(false)
{
}
void QDeclarativeDebugServerPrivate::advertisePlugins()
{
if (!gotHello)
return;
QByteArray message;
{
QDataStream out(&message, QIODevice::WriteOnly);
out << QString(QLatin1String("QDeclarativeDebugClient")) << 1 << plugins.keys();
}
connection->send(message);
}
QDeclarativeDebugServerConnection *QDeclarativeDebugServerPrivate::loadConnectionPlugin(
const QString &pluginName)
{
QStringList pluginCandidates;
const QStringList paths = QCoreApplication::libraryPaths();
foreach (const QString &libPath, paths) {
const QDir dir(libPath + QLatin1String("/qmltooling"));
if (dir.exists()) {
QStringList plugins(dir.entryList(QDir::Files));
foreach (const QString &pluginPath, plugins) {
if (QFileInfo(pluginPath).fileName().contains(pluginName))
pluginCandidates << dir.absoluteFilePath(pluginPath);
}
}
}
foreach (const QString &pluginPath, pluginCandidates) {
QPluginLoader loader(pluginPath);
if (!loader.load()) {
continue;
}
QDeclarativeDebugServerConnection *connection = 0;
if (QObject *instance = loader.instance())
connection = qobject_cast<QDeclarativeDebugServerConnection*>(instance);
if (connection)
return connection;
loader.unload();
}
return 0;
}
bool QDeclarativeDebugServer::hasDebuggingClient() const
{
Q_D(const QDeclarativeDebugServer);
return d->connection
&& d->connection->isConnected()
&& d->gotHello;
}
QDeclarativeDebugServer *QDeclarativeDebugServer::instance()
{
static bool commandLineTested = false;
static QDeclarativeDebugServer *server = 0;
if (!commandLineTested) {
commandLineTested = true;
QApplicationPrivate *appD = static_cast<QApplicationPrivate*>(QObjectPrivate::get(qApp));
#ifndef QDECLARATIVE_NO_DEBUG_PROTOCOL
// ### remove port definition when protocol is changed
int port = 0;
bool block = false;
bool ok = false;
// format: qmljsdebugger=port:3768[,block] OR qmljsdebugger=ost[,block]
if (!appD->qmljsDebugArgumentsString().isEmpty()) {
if (!QDeclarativeEnginePrivate::qml_debugging_enabled) {
const QString message =
QString::fromAscii("QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
"Debugging has not been enabled.").arg(
appD->qmljsDebugArgumentsString());
qWarning("%s", qPrintable(message));
return 0;
}
QString pluginName;
if (appD->qmljsDebugArgumentsString().indexOf(QLatin1String("port:")) == 0) {
int separatorIndex = appD->qmljsDebugArgumentsString().indexOf(QLatin1Char(','));
port = appD->qmljsDebugArgumentsString().mid(5, separatorIndex - 5).toInt(&ok);
pluginName = QLatin1String("qmldbg_tcp");
} else if (appD->qmljsDebugArgumentsString().contains(QLatin1String("ost"))) {
pluginName = QLatin1String("qmldbg_ost");
ok = true;
}
block = appD->qmljsDebugArgumentsString().contains(QLatin1String("block"));
if (ok) {
server = new QDeclarativeDebugServer();
QDeclarativeDebugServerConnection *connection
= QDeclarativeDebugServerPrivate::loadConnectionPlugin(pluginName);
if (connection) {
server->d_func()->connection = connection;
connection->setServer(server);
connection->setPort(port, block);
} else {
qWarning() << QString::fromAscii("QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
"Remote debugger plugin has not been found.").arg(appD->qmljsDebugArgumentsString());
}
} else {
qWarning(QString::fromAscii("QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
"Format is -qmljsdebugger=port:<port>[,block]").arg(
appD->qmljsDebugArgumentsString()).toAscii().constData());
}
}
#else
if (!appD->qmljsDebugArgumentsString().isEmpty()) {
qWarning(QString::fromAscii("QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
"QtDeclarative is not configured for debugging.").arg(
appD->qmljsDebugArgumentsString()).toAscii().constData());
}
#endif
}
return server;
}
QDeclarativeDebugServer::QDeclarativeDebugServer()
: QObject(*(new QDeclarativeDebugServerPrivate))
{
}
void QDeclarativeDebugServer::receiveMessage(const QByteArray &message)
{
Q_D(QDeclarativeDebugServer);
QDataStream in(message);
if (!d->gotHello) {
QString name;
int op;
in >> name >> op;
if (name != QLatin1String("QDeclarativeDebugServer")
|| op != 0) {
qWarning("QDeclarativeDebugServer: Invalid hello message");
d->connection->disconnect();
return;
}
int version;
in >> version >> d->clientPlugins;
// Send the hello answer immediately, since it needs to arrive before
// the plugins below start sending messages.
QByteArray helloAnswer;
{
QDataStream out(&helloAnswer, QIODevice::WriteOnly);
out << QString(QLatin1String("QDeclarativeDebugClient")) << 0 << protocolVersion << d->plugins.keys();
}
d->connection->send(helloAnswer);
d->gotHello = true;
QHash<QString, QDeclarativeDebugService*>::Iterator iter = d->plugins.begin();
for (; iter != d->plugins.end(); ++iter) {
QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::Unavailable;
if (d->clientPlugins.contains(iter.key()))
newStatus = QDeclarativeDebugService::Enabled;
iter.value()->d_func()->status = newStatus;
iter.value()->statusChanged(newStatus);
}
qWarning("QDeclarativeDebugServer: Connection established");
} else {
QString debugServer(QLatin1String("QDeclarativeDebugServer"));
QString name;
in >> name;
if (name == debugServer) {
int op = -1;
in >> op;
if (op == 1) {
// Service Discovery
QStringList oldClientPlugins = d->clientPlugins;
in >> d->clientPlugins;
QHash<QString, QDeclarativeDebugService*>::Iterator iter = d->plugins.begin();
for (; iter != d->plugins.end(); ++iter) {
const QString pluginName = iter.key();
QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::Unavailable;
if (d->clientPlugins.contains(pluginName))
newStatus = QDeclarativeDebugService::Enabled;
if (oldClientPlugins.contains(pluginName)
!= d->clientPlugins.contains(pluginName)) {
iter.value()->d_func()->status = newStatus;
iter.value()->statusChanged(newStatus);
}
}
} else {
qWarning("QDeclarativeDebugServer: Invalid control message %d", op);
}
} else {
QByteArray message;
in >> message;
if (d->waitingForMsgFromService == name) {
// deliver directly so that it is delivered before waitForMessage is returning.
d->_q_deliverMessage(name, message);
d->waitingForMsgFromService.clear();
} else {
// deliver message in next event loop run.
// Fixes the case that the service does start it's own event loop ...,
// but the networking code doesn't deliver any new messages because readyRead
// hasn't returned.
QMetaObject::invokeMethod(this, "_q_deliverMessage", Qt::QueuedConnection,
Q_ARG(QString, name),
Q_ARG(QByteArray, message));
}
}
}
}
void QDeclarativeDebugServerPrivate::_q_deliverMessage(const QString &serviceName, const QByteArray &message)
{
QHash<QString, QDeclarativeDebugService *>::Iterator iter = plugins.find(serviceName);
if (iter == plugins.end()) {
qWarning() << "QDeclarativeDebugServer: Message received for missing plugin" << serviceName;
} else {
(*iter)->messageReceived(message);
}
}
QList<QDeclarativeDebugService*> QDeclarativeDebugServer::services() const
{
const Q_D(QDeclarativeDebugServer);
return d->plugins.values();
}
QStringList QDeclarativeDebugServer::serviceNames() const
{
const Q_D(QDeclarativeDebugServer);
return d->plugins.keys();
}
bool QDeclarativeDebugServer::addService(QDeclarativeDebugService *service)
{
Q_D(QDeclarativeDebugServer);
if (!service || d->plugins.contains(service->name()))
return false;
d->plugins.insert(service->name(), service);
d->advertisePlugins();
QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::Unavailable;
if (d->clientPlugins.contains(service->name()))
newStatus = QDeclarativeDebugService::Enabled;
service->d_func()->status = newStatus;
service->statusChanged(newStatus);
return true;
}
bool QDeclarativeDebugServer::removeService(QDeclarativeDebugService *service)
{
Q_D(QDeclarativeDebugServer);
if (!service || !d->plugins.contains(service->name()))
return false;
d->plugins.remove(service->name());
d->advertisePlugins();
QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::NotConnected;
service->d_func()->server = 0;
service->d_func()->status = newStatus;
service->statusChanged(newStatus);
return true;
}
void QDeclarativeDebugServer::sendMessage(QDeclarativeDebugService *service,
const QByteArray &message)
{
Q_D(QDeclarativeDebugServer);
QByteArray msg;
{
QDataStream out(&msg, QIODevice::WriteOnly);
out << service->name() << message;
}
d->connection->send(msg);
}
bool QDeclarativeDebugServer::waitForMessage(QDeclarativeDebugService *service)
{
Q_D(QDeclarativeDebugServer);
if (!service
|| !d->plugins.contains(service->name())
|| !d->waitingForMsgFromService.isEmpty())
return false;
d->waitingForMsgFromService = service->name();
do {
d->connection->waitForMessage();
} while (!d->waitingForMsgFromService.isEmpty());
return true;
}
QT_END_NAMESPACE
#include "moc_qdeclarativedebugserver_p.cpp"
<commit_msg>DeclarativeDebug: Clear service name when returning from waitForMessage<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "private/qdeclarativedebugserver_p.h"
#include "private/qdeclarativedebugservice_p.h"
#include "private/qdeclarativedebugservice_p_p.h"
#include "private/qdeclarativeengine_p.h"
#include <QtCore/QDir>
#include <QtCore/QPluginLoader>
#include <QtCore/QStringList>
#include <private/qobject_p.h>
#include <private/qapplication_p.h>
QT_BEGIN_NAMESPACE
/*
QDeclarativeDebug Protocol (Version 1):
handshake:
1. Client sends
"QDeclarativeDebugServer" 0 version pluginNames
version: an int representing the highest protocol version the client knows
pluginNames: plugins available on client side
2. Server sends
"QDeclarativeDebugClient" 0 version pluginNames
version: an int representing the highest protocol version the client & server know
pluginNames: plugins available on server side. plugins both in the client and server message are enabled.
client plugin advertisement
1. Client sends
"QDeclarativeDebugServer" 1 pluginNames
server plugin advertisement
1. Server sends
"QDeclarativeDebugClient" 1 pluginNames
plugin communication:
Everything send with a header different to "QDeclarativeDebugServer" is sent to the appropriate plugin.
*/
const int protocolVersion = 1;
class QDeclarativeDebugServerPrivate : public QObjectPrivate
{
Q_DECLARE_PUBLIC(QDeclarativeDebugServer)
public:
QDeclarativeDebugServerPrivate();
void advertisePlugins();
QDeclarativeDebugServerConnection *connection;
QHash<QString, QDeclarativeDebugService *> plugins;
QStringList clientPlugins;
bool gotHello;
QString waitingForMsgFromService;
bool waitingForMsgSucceeded;
private:
// private slot
void _q_deliverMessage(const QString &serviceName, const QByteArray &message);
static QDeclarativeDebugServerConnection *loadConnectionPlugin(const QString &pluginName);
};
QDeclarativeDebugServerPrivate::QDeclarativeDebugServerPrivate() :
connection(0),
gotHello(false),
waitingForMsgSucceeded(false)
{
}
void QDeclarativeDebugServerPrivate::advertisePlugins()
{
if (!gotHello)
return;
QByteArray message;
{
QDataStream out(&message, QIODevice::WriteOnly);
out << QString(QLatin1String("QDeclarativeDebugClient")) << 1 << plugins.keys();
}
connection->send(message);
}
QDeclarativeDebugServerConnection *QDeclarativeDebugServerPrivate::loadConnectionPlugin(
const QString &pluginName)
{
QStringList pluginCandidates;
const QStringList paths = QCoreApplication::libraryPaths();
foreach (const QString &libPath, paths) {
const QDir dir(libPath + QLatin1String("/qmltooling"));
if (dir.exists()) {
QStringList plugins(dir.entryList(QDir::Files));
foreach (const QString &pluginPath, plugins) {
if (QFileInfo(pluginPath).fileName().contains(pluginName))
pluginCandidates << dir.absoluteFilePath(pluginPath);
}
}
}
foreach (const QString &pluginPath, pluginCandidates) {
QPluginLoader loader(pluginPath);
if (!loader.load()) {
continue;
}
QDeclarativeDebugServerConnection *connection = 0;
if (QObject *instance = loader.instance())
connection = qobject_cast<QDeclarativeDebugServerConnection*>(instance);
if (connection)
return connection;
loader.unload();
}
return 0;
}
bool QDeclarativeDebugServer::hasDebuggingClient() const
{
Q_D(const QDeclarativeDebugServer);
return d->connection
&& d->connection->isConnected()
&& d->gotHello;
}
QDeclarativeDebugServer *QDeclarativeDebugServer::instance()
{
static bool commandLineTested = false;
static QDeclarativeDebugServer *server = 0;
if (!commandLineTested) {
commandLineTested = true;
QApplicationPrivate *appD = static_cast<QApplicationPrivate*>(QObjectPrivate::get(qApp));
#ifndef QDECLARATIVE_NO_DEBUG_PROTOCOL
// ### remove port definition when protocol is changed
int port = 0;
bool block = false;
bool ok = false;
// format: qmljsdebugger=port:3768[,block] OR qmljsdebugger=ost[,block]
if (!appD->qmljsDebugArgumentsString().isEmpty()) {
if (!QDeclarativeEnginePrivate::qml_debugging_enabled) {
const QString message =
QString::fromAscii("QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
"Debugging has not been enabled.").arg(
appD->qmljsDebugArgumentsString());
qWarning("%s", qPrintable(message));
return 0;
}
QString pluginName;
if (appD->qmljsDebugArgumentsString().indexOf(QLatin1String("port:")) == 0) {
int separatorIndex = appD->qmljsDebugArgumentsString().indexOf(QLatin1Char(','));
port = appD->qmljsDebugArgumentsString().mid(5, separatorIndex - 5).toInt(&ok);
pluginName = QLatin1String("qmldbg_tcp");
} else if (appD->qmljsDebugArgumentsString().contains(QLatin1String("ost"))) {
pluginName = QLatin1String("qmldbg_ost");
ok = true;
}
block = appD->qmljsDebugArgumentsString().contains(QLatin1String("block"));
if (ok) {
server = new QDeclarativeDebugServer();
QDeclarativeDebugServerConnection *connection
= QDeclarativeDebugServerPrivate::loadConnectionPlugin(pluginName);
if (connection) {
server->d_func()->connection = connection;
connection->setServer(server);
connection->setPort(port, block);
} else {
qWarning() << QString::fromAscii("QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
"Remote debugger plugin has not been found.").arg(appD->qmljsDebugArgumentsString());
}
} else {
qWarning(QString::fromAscii("QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
"Format is -qmljsdebugger=port:<port>[,block]").arg(
appD->qmljsDebugArgumentsString()).toAscii().constData());
}
}
#else
if (!appD->qmljsDebugArgumentsString().isEmpty()) {
qWarning(QString::fromAscii("QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
"QtDeclarative is not configured for debugging.").arg(
appD->qmljsDebugArgumentsString()).toAscii().constData());
}
#endif
}
return server;
}
QDeclarativeDebugServer::QDeclarativeDebugServer()
: QObject(*(new QDeclarativeDebugServerPrivate))
{
}
void QDeclarativeDebugServer::receiveMessage(const QByteArray &message)
{
Q_D(QDeclarativeDebugServer);
QDataStream in(message);
if (!d->gotHello) {
QString name;
int op;
in >> name >> op;
if (name != QLatin1String("QDeclarativeDebugServer")
|| op != 0) {
qWarning("QDeclarativeDebugServer: Invalid hello message");
d->connection->disconnect();
return;
}
int version;
in >> version >> d->clientPlugins;
// Send the hello answer immediately, since it needs to arrive before
// the plugins below start sending messages.
QByteArray helloAnswer;
{
QDataStream out(&helloAnswer, QIODevice::WriteOnly);
out << QString(QLatin1String("QDeclarativeDebugClient")) << 0 << protocolVersion << d->plugins.keys();
}
d->connection->send(helloAnswer);
d->gotHello = true;
QHash<QString, QDeclarativeDebugService*>::Iterator iter = d->plugins.begin();
for (; iter != d->plugins.end(); ++iter) {
QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::Unavailable;
if (d->clientPlugins.contains(iter.key()))
newStatus = QDeclarativeDebugService::Enabled;
iter.value()->d_func()->status = newStatus;
iter.value()->statusChanged(newStatus);
}
qWarning("QDeclarativeDebugServer: Connection established");
} else {
QString debugServer(QLatin1String("QDeclarativeDebugServer"));
QString name;
in >> name;
if (name == debugServer) {
int op = -1;
in >> op;
if (op == 1) {
// Service Discovery
QStringList oldClientPlugins = d->clientPlugins;
in >> d->clientPlugins;
QHash<QString, QDeclarativeDebugService*>::Iterator iter = d->plugins.begin();
for (; iter != d->plugins.end(); ++iter) {
const QString pluginName = iter.key();
QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::Unavailable;
if (d->clientPlugins.contains(pluginName))
newStatus = QDeclarativeDebugService::Enabled;
if (oldClientPlugins.contains(pluginName)
!= d->clientPlugins.contains(pluginName)) {
iter.value()->d_func()->status = newStatus;
iter.value()->statusChanged(newStatus);
}
}
} else {
qWarning("QDeclarativeDebugServer: Invalid control message %d", op);
}
} else {
QByteArray message;
in >> message;
if (d->waitingForMsgFromService == name) {
// deliver directly so that it is delivered before waitForMessage is returning.
d->_q_deliverMessage(name, message);
d->waitingForMsgSucceeded = true;
} else {
// deliver message in next event loop run.
// Fixes the case that the service does start it's own event loop ...,
// but the networking code doesn't deliver any new messages because readyRead
// hasn't returned.
QMetaObject::invokeMethod(this, "_q_deliverMessage", Qt::QueuedConnection,
Q_ARG(QString, name),
Q_ARG(QByteArray, message));
}
}
}
}
void QDeclarativeDebugServerPrivate::_q_deliverMessage(const QString &serviceName, const QByteArray &message)
{
QHash<QString, QDeclarativeDebugService *>::Iterator iter = plugins.find(serviceName);
if (iter == plugins.end()) {
qWarning() << "QDeclarativeDebugServer: Message received for missing plugin" << serviceName;
} else {
(*iter)->messageReceived(message);
}
}
QList<QDeclarativeDebugService*> QDeclarativeDebugServer::services() const
{
const Q_D(QDeclarativeDebugServer);
return d->plugins.values();
}
QStringList QDeclarativeDebugServer::serviceNames() const
{
const Q_D(QDeclarativeDebugServer);
return d->plugins.keys();
}
bool QDeclarativeDebugServer::addService(QDeclarativeDebugService *service)
{
Q_D(QDeclarativeDebugServer);
if (!service || d->plugins.contains(service->name()))
return false;
d->plugins.insert(service->name(), service);
d->advertisePlugins();
QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::Unavailable;
if (d->clientPlugins.contains(service->name()))
newStatus = QDeclarativeDebugService::Enabled;
service->d_func()->status = newStatus;
service->statusChanged(newStatus);
return true;
}
bool QDeclarativeDebugServer::removeService(QDeclarativeDebugService *service)
{
Q_D(QDeclarativeDebugServer);
if (!service || !d->plugins.contains(service->name()))
return false;
d->plugins.remove(service->name());
d->advertisePlugins();
QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::NotConnected;
service->d_func()->server = 0;
service->d_func()->status = newStatus;
service->statusChanged(newStatus);
return true;
}
void QDeclarativeDebugServer::sendMessage(QDeclarativeDebugService *service,
const QByteArray &message)
{
Q_D(QDeclarativeDebugServer);
QByteArray msg;
{
QDataStream out(&msg, QIODevice::WriteOnly);
out << service->name() << message;
}
d->connection->send(msg);
}
bool QDeclarativeDebugServer::waitForMessage(QDeclarativeDebugService *service)
{
Q_D(QDeclarativeDebugServer);
if (!service
|| !d->plugins.contains(service->name())
|| !d->waitingForMsgFromService.isEmpty())
return false;
d->waitingForMsgSucceeded = false;
d->waitingForMsgFromService = service->name();
do {
d->connection->waitForMessage();
} while (!d->waitingForMsgSucceeded);
d->waitingForMsgFromService.clear();
return true;
}
QT_END_NAMESPACE
#include "moc_qdeclarativedebugserver_p.cpp"
<|endoftext|> |
<commit_before>#include "MainFrame.hpp"
#include "misc_ui.hpp"
#include <wx/accel.h>
#include <wx/utils.h>
#include "AboutDialog.hpp"
namespace Slic3r { namespace GUI {
wxBEGIN_EVENT_TABLE(MainFrame, wxFrame)
wxEND_EVENT_TABLE()
MainFrame::MainFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
: MainFrame(title, pos, size, nullptr) {}
MainFrame::MainFrame(const wxString& title, const wxPoint& pos, const wxSize& size, std::shared_ptr<Settings> _gui_config)
: wxFrame(NULL, wxID_ANY, title, pos, size), loaded(false),
tabpanel(nullptr), controller(nullptr), plater(nullptr), gui_config(_gui_config), preset_editor_tabs(std::map<wxWindowID, PresetEditor*>())
{
// Set icon to either the .ico if windows or png for everything else.
if (the_os == OS::Windows)
this->SetIcon(wxIcon(var("Slic3r.ico"), wxBITMAP_TYPE_ICO));
else
this->SetIcon(wxIcon(var("Slic3r_128px.png"), wxBITMAP_TYPE_PNG));
this->init_tabpanel();
this->init_menubar();
wxToolTip::SetAutoPop(TOOLTIP_TIMER);
// initialize status bar
this->statusbar = new ProgressStatusBar(this, -1);
this->statusbar->SetStatusText("Version $Slic3r::VERSION - Remember to check for updates at http://slic3r.org/");
this->SetStatusBar(this->statusbar);
this->loaded = 1;
// Initialize layout
{
wxSizer* sizer = new wxBoxSizer(wxVERTICAL);
sizer->Add(this->tabpanel, 1, wxEXPAND);
sizer->SetSizeHints(this);
this->Fit();
this->SetMinSize(wxSize(760, 490));
this->SetSize(this->GetMinSize());
wxTheApp->SetTopWindow(this);
this->Show();
this->Layout();
}
/*
# declare events
EVT_CLOSE($self, sub {
my (undef, $event) = @_;
if ($event->CanVeto) {
if (!$self->{plater}->prompt_unsaved_changes) {
$event->Veto;
return;
}
if ($self->{controller} && $self->{controller}->printing) {
my $confirm = Wx::MessageDialog->new($self, "You are currently printing. Do you want to stop printing and continue anyway?",
'Unfinished Print', wxICON_QUESTION | wxYES_NO | wxNO_DEFAULT);
if ($confirm->ShowModal == wxID_NO) {
$event->Veto;
return;
}
}
}
# save window size
wxTheApp->save_window_pos($self, "main_frame");
# propagate event
$event->Skip;
});
*/
}
/// Private initialization function for the main frame tab panel.
void MainFrame::init_tabpanel()
{
this->tabpanel = new wxAuiNotebook(this, -1, wxDefaultPosition, wxDefaultSize, wxAUI_NB_TOP);
auto panel = this->tabpanel;
panel->Bind(wxEVT_AUINOTEBOOK_PAGE_CHANGED, ([=](wxAuiNotebookEvent& e)
{
auto tabpanel = this->tabpanel;
// TODO: trigger processing for activation event
if (tabpanel->GetSelection() > 1) {
tabpanel->SetWindowStyle(tabpanel->GetWindowStyleFlag() | wxAUI_NB_CLOSE_ON_ACTIVE_TAB);
} else if (this->gui_config->show_host == false && tabpanel->GetSelection() == 1) {
tabpanel->SetWindowStyle(tabpanel->GetWindowStyleFlag() | wxAUI_NB_CLOSE_ON_ACTIVE_TAB);
} else {
tabpanel->SetWindowStyle(tabpanel->GetWindowStyleFlag() | ~wxAUI_NB_CLOSE_ON_ACTIVE_TAB);
}
}), panel->GetId());
panel->Bind(wxEVT_AUINOTEBOOK_PAGE_CLOSE, ([=](wxAuiNotebookEvent& e)
{
if (typeid(panel) == typeid(Slic3r::GUI::PresetEditor)) {
wxDELETE(this->preset_editor_tabs[panel->GetId()]);
}
wxTheApp->CallAfter([=] { this->tabpanel->SetSelection(0); });
}), panel->GetId());
this->plater = new Slic3r::GUI::Plater(panel, _("Plater"), gui_config);
this->controller = new Slic3r::GUI::Controller(panel, _("Controller"));
panel->AddPage(this->plater, this->plater->GetName());
if (this->gui_config->show_host) panel->AddPage(this->controller, this->controller->GetName());
}
void MainFrame::init_menubar()
{
wxMenu* menuFile = new wxMenu();
{
append_menu_item(menuFile, _(L"Open STL/OBJ/AMF/3MF…"), _("Open a model"), [=](wxCommandEvent& e) { if (this->plater != nullptr) this->plater->add();}, wxID_ANY, "brick_add.png", "Ctrl+O");
}
wxMenu* menuPlater = new wxMenu();
{
}
wxMenu* menuObject = new wxMenu();
{
}
wxMenu* menuSettings = new wxMenu();
{
}
wxMenu* menuView = new wxMenu();
{
}
wxMenu* menuWindow = new wxMenu();
{
}
wxMenu* menuHelp = new wxMenu();
{
// TODO: Reimplement config wizard
//menuHelp->AppendSeparator();
append_menu_item(menuHelp, _("Slic3r &Website"), _("Open the Slic3r website in your browser"), [=](wxCommandEvent& e)
{
wxLaunchDefaultBrowser("http://www.slic3r.org");
});
append_menu_item(menuHelp, _("Check for &Updates..."), _("Check for new Slic3r versions"), [=](wxCommandEvent& e)
{
check_version(true);
});
append_menu_item(menuHelp, _("Slic3r &Manual"), _("Open the Slic3r manual in your browser"), [=](wxCommandEvent& e)
{
wxLaunchDefaultBrowser("http://manual.slic3r.org/");
});
append_menu_item(menuHelp, _("&About Slic3r"), _("Show about dialog"), [=](wxCommandEvent& e)
{
auto about = new AboutDialog(nullptr);
about->ShowModal();
about->Destroy();
}, wxID_ABOUT);
}
wxMenuBar* menubar = new wxMenuBar();
menubar->Append(menuFile, _("&File"));
menubar->Append(menuPlater, _("&Plater"));
menubar->Append(menuObject, _("&Object"));
menubar->Append(menuSettings, _("&Settings"));
menubar->Append(menuView, _("&View"));
menubar->Append(menuWindow, _("&Window"));
menubar->Append(menuHelp, _("&Help"));
this->SetMenuBar(menubar);
}
}} // Namespace Slic3r::GUI
<commit_msg>Properly pull slic3r version string from libslic3r<commit_after>#include "MainFrame.hpp"
#include "misc_ui.hpp"
#include <wx/accel.h>
#include <wx/utils.h>
#include "AboutDialog.hpp"
#include "libslic3r.h"
namespace Slic3r { namespace GUI {
wxBEGIN_EVENT_TABLE(MainFrame, wxFrame)
wxEND_EVENT_TABLE()
MainFrame::MainFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
: MainFrame(title, pos, size, nullptr) {}
MainFrame::MainFrame(const wxString& title, const wxPoint& pos, const wxSize& size, std::shared_ptr<Settings> _gui_config)
: wxFrame(NULL, wxID_ANY, title, pos, size), loaded(false),
tabpanel(nullptr), controller(nullptr), plater(nullptr), gui_config(_gui_config), preset_editor_tabs(std::map<wxWindowID, PresetEditor*>())
{
// Set icon to either the .ico if windows or png for everything else.
if (the_os == OS::Windows)
this->SetIcon(wxIcon(var("Slic3r.ico"), wxBITMAP_TYPE_ICO));
else
this->SetIcon(wxIcon(var("Slic3r_128px.png"), wxBITMAP_TYPE_PNG));
this->init_tabpanel();
this->init_menubar();
wxToolTip::SetAutoPop(TOOLTIP_TIMER);
// initialize status bar
// we call SetStatusBar() here because MainFrame is the direct owner.
this->statusbar = new ProgressStatusBar(this, -1);
wxString welcome_text {_("Version SLIC3R_VERSION_REPLACE - Remember to check for updates at http://slic3r.org/")};
welcome_text.Replace("SLIC3R_VERSION_REPLACE", wxString(SLIC3R_VERSION));
this->statusbar->SetStatusText(welcome_text);
this->SetStatusBar(this->statusbar);
this->loaded = 1;
// Initialize layout
{
wxSizer* sizer = new wxBoxSizer(wxVERTICAL);
sizer->Add(this->tabpanel, 1, wxEXPAND);
sizer->SetSizeHints(this);
this->Fit();
this->SetMinSize(wxSize(760, 490));
this->SetSize(this->GetMinSize());
wxTheApp->SetTopWindow(this);
this->Show();
this->Layout();
}
/*
# declare events
EVT_CLOSE($self, sub {
my (undef, $event) = @_;
if ($event->CanVeto) {
if (!$self->{plater}->prompt_unsaved_changes) {
$event->Veto;
return;
}
if ($self->{controller} && $self->{controller}->printing) {
my $confirm = Wx::MessageDialog->new($self, "You are currently printing. Do you want to stop printing and continue anyway?",
'Unfinished Print', wxICON_QUESTION | wxYES_NO | wxNO_DEFAULT);
if ($confirm->ShowModal == wxID_NO) {
$event->Veto;
return;
}
}
}
# save window size
wxTheApp->save_window_pos($self, "main_frame");
# propagate event
$event->Skip;
});
*/
}
/// Private initialization function for the main frame tab panel.
void MainFrame::init_tabpanel()
{
this->tabpanel = new wxAuiNotebook(this, -1, wxDefaultPosition, wxDefaultSize, wxAUI_NB_TOP);
auto panel = this->tabpanel;
panel->Bind(wxEVT_AUINOTEBOOK_PAGE_CHANGED, ([=](wxAuiNotebookEvent& e)
{
auto tabpanel = this->tabpanel;
// TODO: trigger processing for activation event
if (tabpanel->GetSelection() > 1) {
tabpanel->SetWindowStyle(tabpanel->GetWindowStyleFlag() | wxAUI_NB_CLOSE_ON_ACTIVE_TAB);
} else if (this->gui_config->show_host == false && tabpanel->GetSelection() == 1) {
tabpanel->SetWindowStyle(tabpanel->GetWindowStyleFlag() | wxAUI_NB_CLOSE_ON_ACTIVE_TAB);
} else {
tabpanel->SetWindowStyle(tabpanel->GetWindowStyleFlag() | ~wxAUI_NB_CLOSE_ON_ACTIVE_TAB);
}
}), panel->GetId());
panel->Bind(wxEVT_AUINOTEBOOK_PAGE_CLOSE, ([=](wxAuiNotebookEvent& e)
{
if (typeid(panel) == typeid(Slic3r::GUI::PresetEditor)) {
wxDELETE(this->preset_editor_tabs[panel->GetId()]);
}
wxTheApp->CallAfter([=] { this->tabpanel->SetSelection(0); });
}), panel->GetId());
this->plater = new Slic3r::GUI::Plater(panel, _("Plater"), gui_config);
this->controller = new Slic3r::GUI::Controller(panel, _("Controller"));
panel->AddPage(this->plater, this->plater->GetName());
if (this->gui_config->show_host) panel->AddPage(this->controller, this->controller->GetName());
}
void MainFrame::init_menubar()
{
wxMenu* menuFile = new wxMenu();
{
append_menu_item(menuFile, _(L"Open STL/OBJ/AMF/3MF…"), _("Open a model"), [=](wxCommandEvent& e) { if (this->plater != nullptr) this->plater->add();}, wxID_ANY, "brick_add.png", "Ctrl+O");
}
wxMenu* menuPlater = new wxMenu();
{
}
wxMenu* menuObject = new wxMenu();
{
}
wxMenu* menuSettings = new wxMenu();
{
}
wxMenu* menuView = new wxMenu();
{
}
wxMenu* menuWindow = new wxMenu();
{
}
wxMenu* menuHelp = new wxMenu();
{
// TODO: Reimplement config wizard
//menuHelp->AppendSeparator();
append_menu_item(menuHelp, _("Slic3r &Website"), _("Open the Slic3r website in your browser"), [=](wxCommandEvent& e)
{
wxLaunchDefaultBrowser("http://www.slic3r.org");
});
append_menu_item(menuHelp, _("Check for &Updates..."), _("Check for new Slic3r versions"), [=](wxCommandEvent& e)
{
check_version(true);
});
append_menu_item(menuHelp, _("Slic3r &Manual"), _("Open the Slic3r manual in your browser"), [=](wxCommandEvent& e)
{
wxLaunchDefaultBrowser("http://manual.slic3r.org/");
});
append_menu_item(menuHelp, _("&About Slic3r"), _("Show about dialog"), [=](wxCommandEvent& e)
{
auto about = new AboutDialog(nullptr);
about->ShowModal();
about->Destroy();
}, wxID_ABOUT);
}
wxMenuBar* menubar = new wxMenuBar();
menubar->Append(menuFile, _("&File"));
menubar->Append(menuPlater, _("&Plater"));
menubar->Append(menuObject, _("&Object"));
menubar->Append(menuSettings, _("&Settings"));
menubar->Append(menuView, _("&View"));
menubar->Append(menuWindow, _("&Window"));
menubar->Append(menuHelp, _("&Help"));
this->SetMenuBar(menubar);
}
}} // Namespace Slic3r::GUI
<|endoftext|> |
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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.
//
// A brpc based redis-server. Currently just implement set and
// get, but it's sufficient that you can get the idea how to
// implement brpc::RedisCommandHandler.
#include <brpc/server.h>
#include <brpc/redis.h>
#include <butil/crc32c.h>
#include <butil/strings/string_split.h>
#include <gflags/gflags.h>
#include <unordered_map>
class RedisServiceImpl : public brpc::RedisService {
public:
bool Set(const std::string& key, const std::string& value) {
int slot = butil::crc32c::Value(key.c_str(), key.size()) % kHashSlotNum;
_mutex[slot].lock();
_map[slot][key] = value;
_mutex[slot].unlock();
return true;
}
bool Get(const std::string& key, std::string* value) {
int slot = butil::crc32c::Value(key.c_str(), key.size()) % kHashSlotNum;
_mutex[slot].lock();
auto it = _map[slot].find(key);
if (it == _map[slot].end()) {
_mutex[slot].unlock();
return false;
}
*value = it->second;
_mutex[slot].unlock();
return true;
}
private:
const static int kHashSlotNum = 32;
std::unordered_map<std::string, std::string> _map[kHashSlotNum];
butil::Mutex _mutex[kHashSlotNum];
};
class GetCommandHandler : public brpc::RedisCommandHandler {
public:
GetCommandHandler(RedisServiceImpl* rsimpl)
: _rsimpl(rsimpl) {}
brpc::RedisCommandHandler::Result Run(int size, const char* args[],
brpc::RedisReply* output,
bool is_last) override {
if (size <= 1) {
output->SetError("ERR wrong number of arguments for 'get' command");
return brpc::RedisCommandHandler::OK;
}
const std::string key(args[1]);
std::string value;
if (_rsimpl->Get(key, &value)) {
output->SetString(value);
} else {
output->SetNullString();
}
return brpc::RedisCommandHandler::OK;
}
private:
RedisServiceImpl* _rsimpl;
};
class SetCommandHandler : public brpc::RedisCommandHandler {
public:
SetCommandHandler(RedisServiceImpl* rsimpl)
: _rsimpl(rsimpl) {}
brpc::RedisCommandHandler::Result Run(int size, const char* args[],
brpc::RedisReply* output,
bool is_last) override {
if (size <= 2) {
output->SetError("ERR wrong number of arguments for 'set' command");
return brpc::RedisCommandHandler::OK;
}
const std::string key(args[1]);
const std::string value(args[2]);
_rsimpl->Set(key, value);
output->SetStatus("OK");
return brpc::RedisCommandHandler::OK;
}
private:
RedisServiceImpl* _rsimpl;
};
int main(int argc, char* argv[]) {
google::ParseCommandLineFlags(&argc, &argv, true);
RedisServiceImpl* rsimpl = new RedisServiceImpl;
rsimpl->AddCommandHandler("get", new GetCommandHandler(rsimpl));
rsimpl->AddCommandHandler("set", new SetCommandHandler(rsimpl));
brpc::Server server;
brpc::ServerOptions server_options;
server_options.redis_service = rsimpl;
if (server.Start(6379, &server_options) != 0) {
LOG(ERROR) << "Fail to start server";
return -1;
}
server.RunUntilAskedToQuit();
return 0;
}
<commit_msg>redis_server_protocol: update redis-server<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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.
//
// A brpc based redis-server. Currently just implement set and
// get, but it's sufficient that you can get the idea how to
// implement brpc::RedisCommandHandler.
#include <brpc/server.h>
#include <brpc/redis.h>
#include <butil/crc32c.h>
#include <butil/strings/string_split.h>
#include <gflags/gflags.h>
#include <unordered_map>
class RedisServiceImpl : public brpc::RedisService {
public:
bool Set(const std::string& key, const std::string& value) {
int slot = butil::crc32c::Value(key.c_str(), key.size()) % kHashSlotNum;
_mutex[slot].lock();
_map[slot][key] = value;
_mutex[slot].unlock();
return true;
}
bool Get(const std::string& key, std::string* value) {
int slot = butil::crc32c::Value(key.c_str(), key.size()) % kHashSlotNum;
_mutex[slot].lock();
auto it = _map[slot].find(key);
if (it == _map[slot].end()) {
_mutex[slot].unlock();
return false;
}
*value = it->second;
_mutex[slot].unlock();
return true;
}
private:
const static int kHashSlotNum = 32;
std::unordered_map<std::string, std::string> _map[kHashSlotNum];
butil::Mutex _mutex[kHashSlotNum];
};
class GetCommandHandler : public brpc::RedisCommandHandler {
public:
GetCommandHandler(RedisServiceImpl* rsimpl)
: _rsimpl(rsimpl) {}
brpc::RedisCommandHandler::Result Run(const std::vector<const char*>& args,
brpc::RedisReply* output,
bool is_last) override {
if (args.size() <= 1) {
output->SetError("ERR wrong number of arguments for 'get' command");
return brpc::RedisCommandHandler::OK;
}
const std::string key(args[1]);
std::string value;
if (_rsimpl->Get(key, &value)) {
output->SetString(value);
} else {
output->SetNullString();
}
return brpc::RedisCommandHandler::OK;
}
private:
RedisServiceImpl* _rsimpl;
};
class SetCommandHandler : public brpc::RedisCommandHandler {
public:
SetCommandHandler(RedisServiceImpl* rsimpl)
: _rsimpl(rsimpl) {}
brpc::RedisCommandHandler::Result Run(const std::vector<const char*>& args,
brpc::RedisReply* output,
bool is_last) override {
if (args.size() <= 2) {
output->SetError("ERR wrong number of arguments for 'set' command");
return brpc::RedisCommandHandler::OK;
}
const std::string key(args[1]);
const std::string value(args[2]);
_rsimpl->Set(key, value);
output->SetStatus("OK");
return brpc::RedisCommandHandler::OK;
}
private:
RedisServiceImpl* _rsimpl;
};
int main(int argc, char* argv[]) {
google::ParseCommandLineFlags(&argc, &argv, true);
RedisServiceImpl* rsimpl = new RedisServiceImpl;
rsimpl->AddCommandHandler("get", new GetCommandHandler(rsimpl));
rsimpl->AddCommandHandler("set", new SetCommandHandler(rsimpl));
brpc::Server server;
brpc::ServerOptions server_options;
server_options.redis_service = rsimpl;
if (server.Start(6379, &server_options) != 0) {
LOG(ERROR) << "Fail to start server";
return -1;
}
server.RunUntilAskedToQuit();
return 0;
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "GlobalContext.hpp"
#include "Variable.hpp"
#include "Utils.hpp"
#include "VisitorUtils.hpp"
#include "Type.hpp"
#include "mangling.hpp"
#include "ast/GetConstantValue.hpp"
using namespace eddic;
GlobalContext::GlobalContext(Platform platform) : Context(NULL), platform(platform) {
Val zero = 0;
variables["_mem_start"] = std::make_shared<Variable>("_mem_start", INT, Position(PositionType::GLOBAL, "_mem_start"), zero);
variables["_mem_last"] = std::make_shared<Variable>("_mem_last", INT, Position(PositionType::GLOBAL, "_mem_last"), zero);
//In order to not display a warning
variables["_mem_start"]->add_reference();
variables["_mem_last"]->add_reference();
defineStandardFunctions();
}
std::unordered_map<std::string, std::shared_ptr<Variable>> GlobalContext::getVariables(){
return variables;
}
std::shared_ptr<Variable> GlobalContext::addVariable(const std::string& variable, std::shared_ptr<const Type> type){
//Only global array have no value, other types have all values
assert(type->is_array());
Position position(PositionType::GLOBAL, variable);
return variables[variable] = std::make_shared<Variable>(variable, type, position);
}
std::shared_ptr<Variable> GlobalContext::generate_variable(const std::string&, std::shared_ptr<const Type>){
eddic_unreachable("Cannot generate global variable");
}
std::shared_ptr<Variable> GlobalContext::addVariable(const std::string& variable, std::shared_ptr<const Type> type, ast::Value& value){
auto val = visit(ast::GetConstantValue(), value);
if(type->is_const()){
Position position(PositionType::CONST);
return variables[variable] = std::make_shared<Variable>(variable, type, position, val);
}
Position position(PositionType::GLOBAL, variable);
return variables[variable] = std::make_shared<Variable>(variable, type, position, val);
}
Function& GlobalContext::add_function(std::shared_ptr<const Type> ret, const std::string& name, const std::string& mangled_name){
m_functions.emplace(std::piecewise_construct, std::forward_as_tuple(mangled_name), std::forward_as_tuple(ret, name, mangled_name));
return m_functions.at(mangled_name);
}
Function& GlobalContext::getFunction(const std::string& function){
eddic_assert(exists(function), "The function must exists");
return m_functions.at(function);
}
bool GlobalContext::exists(const std::string& function) const {
return m_functions.find(function) != m_functions.end();
}
void GlobalContext::add_struct(std::shared_ptr<Struct> struct_){
m_structs[struct_->name] = struct_;
}
bool GlobalContext::struct_exists(const std::string& struct_) const {
return m_structs.find(struct_) != m_structs.end();
}
bool GlobalContext::struct_exists(std::shared_ptr<const Type> type) const {
if(type->is_pointer()){
type = type->data_type();
}
eddic_assert(type->is_custom_type() || type->is_template_type(), "This type has no corresponding struct");
auto struct_name = type->mangle();
return struct_exists(struct_name);
}
std::shared_ptr<Struct> GlobalContext::get_struct(const std::string& struct_name) const {
auto it = m_structs.find(struct_name);
if(it == m_structs.end()){
return nullptr;
} else {
return it->second;
}
}
std::shared_ptr<Struct> GlobalContext::get_struct(std::shared_ptr<const Type> type) const {
if(!type){
return nullptr;
}
if(type->is_pointer()){
type = type->data_type();
}
eddic_assert(type->is_custom_type() || type->is_template_type(), "This type has no corresponding struct");
auto struct_name = type->mangle();
return get_struct(struct_name);
}
int GlobalContext::member_offset(std::shared_ptr<const Struct> struct_, const std::string& member) const {
int offset = 0;
for(auto& m : struct_->members){
if(m->name == member){
return offset;
}
offset += m->type->size(platform);
}
eddic_unreachable("The member is not part of the struct");
}
std::shared_ptr<const Type> GlobalContext::member_type(std::shared_ptr<const Struct> struct_, int offset) const {
int current_offset = 0;
std::shared_ptr<Member> member = nullptr;
for(auto& m : struct_->members){
member = m;
if(offset <= current_offset){
return member->type;
}
current_offset += m->type->size(platform);
}
return member->type;
}
int GlobalContext::self_size_of_struct(std::shared_ptr<const Struct> struct_) const {
int struct_size = 0;
for(auto& m : struct_->members){
struct_size += m->type->size(platform);
}
return struct_size;
}
int GlobalContext::total_size_of_struct(std::shared_ptr<const Struct> struct_) const {
int total = self_size_of_struct(struct_);
while(struct_->parent_type){
struct_ = get_struct(struct_->parent_type);
total += self_size_of_struct(struct_);
}
return total;
}
bool GlobalContext::is_recursively_nested(std::shared_ptr<const Struct> struct_, unsigned int left) const {
if(left == 0){
return true;
}
for(auto& m : struct_->members){
auto type = m->type;
if(type->is_structure()){
if(is_recursively_nested(get_struct(type), left - 1)){
return true;
}
}
}
return false;
}
bool GlobalContext::is_recursively_nested(std::shared_ptr<const Struct> struct_) const {
return is_recursively_nested(struct_, 100);
}
void GlobalContext::addReference(const std::string& function){
++(getFunction(function).references());
}
void GlobalContext::removeReference(const std::string& function){
--(getFunction(function).references());
}
int GlobalContext::referenceCount(const std::string& function){
return getFunction(function).references();
}
void GlobalContext::addPrintFunction(const std::string& function, std::shared_ptr<const Type> parameterType){
auto& printFunction = add_function(VOID, "print", function);
printFunction.standard() = true;
printFunction.parameters().emplace_back("a", parameterType);
}
void GlobalContext::defineStandardFunctions(){
auto& printLineFunction = add_function(VOID, "print", "_F7println");
printLineFunction.standard() = true;
//print string
addPrintFunction("_F5printS", STRING);
addPrintFunction("_F7printlnS", STRING);
//print integer
addPrintFunction("_F5printI", INT);
addPrintFunction("_F7printlnI", INT);
//print char
addPrintFunction("_F5printC", CHAR);
addPrintFunction("_F7printlnC", CHAR);
//print float
addPrintFunction("_F5printF", FLOAT);
addPrintFunction("_F7printlnF", FLOAT);
auto& read_char_function = add_function(CHAR, "read_char", "_F9read_char");
read_char_function.standard() = true;
//alloc function
auto& allocFunction = add_function(new_pointer_type(INT), "alloc", "_F5allocI");
allocFunction.standard() = true;
allocFunction.parameters().emplace_back("a", INT);
//free function
auto& freeFunction = add_function(VOID, "free", "_F4freePI");
freeFunction.standard() = true;
freeFunction.parameters().emplace_back("a", INT);
//time function
auto& timeFunction = add_function(VOID, "time", "_F4timeAI");
timeFunction.standard() = true;
timeFunction.parameters().emplace_back("a", new_array_type(INT));
//duration function
auto& durationFunction = add_function(VOID, "duration", "_F8durationAIAI");
durationFunction.standard() = true;
durationFunction.parameters().emplace_back("a", new_array_type(INT));
durationFunction.parameters().emplace_back("b", new_array_type(INT));
}
const GlobalContext::FunctionMap& GlobalContext::functions() const {
return m_functions;
}
Platform GlobalContext::target_platform() const {
return platform;
}
statistics& GlobalContext::stats(){
return m_statistics;
}
<commit_msg>Use nullptr rather than NULL<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "GlobalContext.hpp"
#include "Variable.hpp"
#include "Utils.hpp"
#include "VisitorUtils.hpp"
#include "Type.hpp"
#include "mangling.hpp"
#include "ast/GetConstantValue.hpp"
using namespace eddic;
GlobalContext::GlobalContext(Platform platform) : Context(nullptr), platform(platform) {
Val zero = 0;
variables["_mem_start"] = std::make_shared<Variable>("_mem_start", INT, Position(PositionType::GLOBAL, "_mem_start"), zero);
variables["_mem_last"] = std::make_shared<Variable>("_mem_last", INT, Position(PositionType::GLOBAL, "_mem_last"), zero);
//In order to not display a warning
variables["_mem_start"]->add_reference();
variables["_mem_last"]->add_reference();
defineStandardFunctions();
}
std::unordered_map<std::string, std::shared_ptr<Variable>> GlobalContext::getVariables(){
return variables;
}
std::shared_ptr<Variable> GlobalContext::addVariable(const std::string& variable, std::shared_ptr<const Type> type){
//Only global array have no value, other types have all values
assert(type->is_array());
Position position(PositionType::GLOBAL, variable);
return variables[variable] = std::make_shared<Variable>(variable, type, position);
}
std::shared_ptr<Variable> GlobalContext::generate_variable(const std::string&, std::shared_ptr<const Type>){
eddic_unreachable("Cannot generate global variable");
}
std::shared_ptr<Variable> GlobalContext::addVariable(const std::string& variable, std::shared_ptr<const Type> type, ast::Value& value){
auto val = visit(ast::GetConstantValue(), value);
if(type->is_const()){
Position position(PositionType::CONST);
return variables[variable] = std::make_shared<Variable>(variable, type, position, val);
}
Position position(PositionType::GLOBAL, variable);
return variables[variable] = std::make_shared<Variable>(variable, type, position, val);
}
Function& GlobalContext::add_function(std::shared_ptr<const Type> ret, const std::string& name, const std::string& mangled_name){
m_functions.emplace(std::piecewise_construct, std::forward_as_tuple(mangled_name), std::forward_as_tuple(ret, name, mangled_name));
return m_functions.at(mangled_name);
}
Function& GlobalContext::getFunction(const std::string& function){
eddic_assert(exists(function), "The function must exists");
return m_functions.at(function);
}
bool GlobalContext::exists(const std::string& function) const {
return m_functions.find(function) != m_functions.end();
}
void GlobalContext::add_struct(std::shared_ptr<Struct> struct_){
m_structs[struct_->name] = struct_;
}
bool GlobalContext::struct_exists(const std::string& struct_) const {
return m_structs.find(struct_) != m_structs.end();
}
bool GlobalContext::struct_exists(std::shared_ptr<const Type> type) const {
if(type->is_pointer()){
type = type->data_type();
}
eddic_assert(type->is_custom_type() || type->is_template_type(), "This type has no corresponding struct");
auto struct_name = type->mangle();
return struct_exists(struct_name);
}
std::shared_ptr<Struct> GlobalContext::get_struct(const std::string& struct_name) const {
auto it = m_structs.find(struct_name);
if(it == m_structs.end()){
return nullptr;
} else {
return it->second;
}
}
std::shared_ptr<Struct> GlobalContext::get_struct(std::shared_ptr<const Type> type) const {
if(!type){
return nullptr;
}
if(type->is_pointer()){
type = type->data_type();
}
eddic_assert(type->is_custom_type() || type->is_template_type(), "This type has no corresponding struct");
auto struct_name = type->mangle();
return get_struct(struct_name);
}
int GlobalContext::member_offset(std::shared_ptr<const Struct> struct_, const std::string& member) const {
int offset = 0;
for(auto& m : struct_->members){
if(m->name == member){
return offset;
}
offset += m->type->size(platform);
}
eddic_unreachable("The member is not part of the struct");
}
std::shared_ptr<const Type> GlobalContext::member_type(std::shared_ptr<const Struct> struct_, int offset) const {
int current_offset = 0;
std::shared_ptr<Member> member = nullptr;
for(auto& m : struct_->members){
member = m;
if(offset <= current_offset){
return member->type;
}
current_offset += m->type->size(platform);
}
return member->type;
}
int GlobalContext::self_size_of_struct(std::shared_ptr<const Struct> struct_) const {
int struct_size = 0;
for(auto& m : struct_->members){
struct_size += m->type->size(platform);
}
return struct_size;
}
int GlobalContext::total_size_of_struct(std::shared_ptr<const Struct> struct_) const {
int total = self_size_of_struct(struct_);
while(struct_->parent_type){
struct_ = get_struct(struct_->parent_type);
total += self_size_of_struct(struct_);
}
return total;
}
bool GlobalContext::is_recursively_nested(std::shared_ptr<const Struct> struct_, unsigned int left) const {
if(left == 0){
return true;
}
for(auto& m : struct_->members){
auto type = m->type;
if(type->is_structure()){
if(is_recursively_nested(get_struct(type), left - 1)){
return true;
}
}
}
return false;
}
bool GlobalContext::is_recursively_nested(std::shared_ptr<const Struct> struct_) const {
return is_recursively_nested(struct_, 100);
}
void GlobalContext::addReference(const std::string& function){
++(getFunction(function).references());
}
void GlobalContext::removeReference(const std::string& function){
--(getFunction(function).references());
}
int GlobalContext::referenceCount(const std::string& function){
return getFunction(function).references();
}
void GlobalContext::addPrintFunction(const std::string& function, std::shared_ptr<const Type> parameterType){
auto& printFunction = add_function(VOID, "print", function);
printFunction.standard() = true;
printFunction.parameters().emplace_back("a", parameterType);
}
void GlobalContext::defineStandardFunctions(){
auto& printLineFunction = add_function(VOID, "print", "_F7println");
printLineFunction.standard() = true;
//print string
addPrintFunction("_F5printS", STRING);
addPrintFunction("_F7printlnS", STRING);
//print integer
addPrintFunction("_F5printI", INT);
addPrintFunction("_F7printlnI", INT);
//print char
addPrintFunction("_F5printC", CHAR);
addPrintFunction("_F7printlnC", CHAR);
//print float
addPrintFunction("_F5printF", FLOAT);
addPrintFunction("_F7printlnF", FLOAT);
auto& read_char_function = add_function(CHAR, "read_char", "_F9read_char");
read_char_function.standard() = true;
//alloc function
auto& allocFunction = add_function(new_pointer_type(INT), "alloc", "_F5allocI");
allocFunction.standard() = true;
allocFunction.parameters().emplace_back("a", INT);
//free function
auto& freeFunction = add_function(VOID, "free", "_F4freePI");
freeFunction.standard() = true;
freeFunction.parameters().emplace_back("a", INT);
//time function
auto& timeFunction = add_function(VOID, "time", "_F4timeAI");
timeFunction.standard() = true;
timeFunction.parameters().emplace_back("a", new_array_type(INT));
//duration function
auto& durationFunction = add_function(VOID, "duration", "_F8durationAIAI");
durationFunction.standard() = true;
durationFunction.parameters().emplace_back("a", new_array_type(INT));
durationFunction.parameters().emplace_back("b", new_array_type(INT));
}
const GlobalContext::FunctionMap& GlobalContext::functions() const {
return m_functions;
}
Platform GlobalContext::target_platform() const {
return platform;
}
statistics& GlobalContext::stats(){
return m_statistics;
}
<|endoftext|> |
<commit_before>#include "iotsa.h"
#include "iotsaCapabilities.h"
#include "iotsaConfigFile.h"
#include <ArduinoJWT.h>
#include <ArduinoJson.h>
#define IFDEBUGX if(1)
// Static method to check whether a string exactly matches a Json object,
// or is included in the Json object if it is an array.
static bool stringContainedIn(const char *wanted, JsonVariant& got) {
if (got.is<char*>()) {
return strcmp(wanted, got.as<const char *>()) == 0;
}
if (!got.is<JsonArray>()) {
return false;
}
JsonArray& gotArray = got.as<JsonArray>();
for(size_t i=0; i<gotArray.size(); i++) {
const char *gotItem = gotArray[i];
if (strcmp(gotItem, wanted) == 0) {
return true;
}
}
return false;
}
// Get a scope indicator from a JSON variant
static IotsaCapabilityObjectScope getRightFrom(const JsonVariant& arg) {
if (!arg.is<char*>()) return IOTSA_SCOPE_NONE;
const char *argStr = arg.as<char*>();
if (strcmp(argStr, "self") == 0) return IOTSA_SCOPE_SELF;
if (strcmp(argStr, "descendant-or-self") == 0) return IOTSA_SCOPE_FULL;
if (strcmp(argStr, "descendant") == 0) return IOTSA_SCOPE_CHILD;
if (strcmp(argStr, "child") == 0) return IOTSA_SCOPE_CHILD;
return IOTSA_SCOPE_NONE;
}
bool IotsaCapability::allows(const char *_obj, IotsaApiOperation verb) {
IotsaCapabilityObjectScope scope = scopes[int(verb)];
int matchLength = obj.length();
switch(scope) {
case IOTSA_SCOPE_NONE:
break;
case IOTSA_SCOPE_SELF:
if (strcmp(obj.c_str(), _obj) == 0)
return true;
break;
case IOTSA_SCOPE_FULL:
if (strncmp(obj.c_str(), _obj, matchLength) == 0) {
char nextCh = _obj[matchLength];
if (nextCh == '\0' || nextCh == '/')
return true;
}
break;
case IOTSA_SCOPE_CHILD:
if (strncmp(obj.c_str(), _obj, matchLength) == 0) {
char nextCh = _obj[matchLength];
if (nextCh == '/')
return true;
}
break;
}
// See if there is a next capabiliy we can check, otherwise we don't have permission.
if (next) return next->allows(_obj, verb);
return false;
}
IotsaCapabilityMod::IotsaCapabilityMod(IotsaApplication &_app, IotsaAuthenticationProvider& _chain)
: IotsaAuthMod(_app),
capabilities(NULL),
#ifdef IOTSA_WITH_API
api(this, _app, this),
#endif
chain(_chain),
trustedIssuer(""),
issuerKey("")
{
configLoad();
}
#ifdef IOTSA_WITH_WEB
void
IotsaCapabilityMod::handler() {
String _trustedIssuer = server->arg("trustedIssuer");
String _issuerKey = server->arg("issuerKey");
if (_trustedIssuer != "" || _issuerKey != "") {
if (!iotsaConfig.inConfigurationMode()) {
server->send(403, "text/plain", "403 Forbidden, not in configuration mode");
return;
}
if (needsAuthentication("capabilities")) return;
if (_trustedIssuer != "") trustedIssuer = _trustedIssuer;
if (_issuerKey != "") issuerKey = _issuerKey;
configSave();
server->send(200, "text/plain", "ok\r\n");
return;
}
String message = "<html><head><title>Capability Authority</title></head><body><h1>Capability Authority</h1>";
if (!iotsaConfig.inConfigurationMode())
message += "<p><em>Note:</em> You must be in configuration mode to be able to change issuer or key.</p>";
message += "<form method='get'>Issuer: <input name='trustedIssuer' value='";
message += htmlEncode(trustedIssuer);
message += "'><br>Current shared key is secret, but length is ";
message += String(issuerKey.length());
message += ".<br>New key: <input name='issuerKey'><br><input type='Submit'></form></body></html>";
server->send(200, "text/html", message);
}
String IotsaCapabilityMod::info() {
String message = "<p>Capabilities enabled.";
message += " See <a href=\"/capabilities\">/capabilities</a> to change settings.";
message += "</p>";
return message;
}
#endif // IOTSA_WITH_WEB
#ifdef IOTSA_WITH_API
bool IotsaCapabilityMod::getHandler(const char *path, JsonObject& reply) {
if (strcmp(path, "/api/capabilities") != 0) return false;
reply["trustedIssuer"] = trustedIssuer;
reply["has_issuerKey"] = (issuerKey.length() > 0);
return true;
}
bool IotsaCapabilityMod::putHandler(const char *path, const JsonVariant& request, JsonObject& reply) {
if (strcmp(path, "/api/capabilities") != 0) return false;
if (!iotsaConfig.inConfigurationMode()) return false;
bool anyChanged = false;
JsonObject& reqObj = request.as<JsonObject>();
if (reqObj.containsKey("trustedIssuer")) {
trustedIssuer = reqObj.get<String>("trustedIssuer");
anyChanged = true;
}
if (reqObj.containsKey("issuerKey")) {
issuerKey = reqObj.get<String>("issuerKey");
anyChanged = true;
}
if (anyChanged) {
configSave();
}
return anyChanged;
}
bool IotsaCapabilityMod::postHandler(const char *path, const JsonVariant& request, JsonObject& reply) {
return false;
}
#endif // IOTSA_WITH_API
void IotsaCapabilityMod::setup() {
configLoad();
}
void IotsaCapabilityMod::serverSetup() {
#ifdef IOTSA_WITH_WEB
server->on("/capabilities", std::bind(&IotsaCapabilityMod::handler, this));
#endif
#ifdef IOTSA_WITH_API
api.setup("/api/capabilities", true, true, false);
name = "capabilities";
#endif
}
void IotsaCapabilityMod::configLoad() {
IotsaConfigFileLoad cf("/config/capabilities.cfg");
cf.get("issuer", trustedIssuer, "");
cf.get("key", issuerKey, "");
}
void IotsaCapabilityMod::configSave() {
IotsaConfigFileSave cf("/config/capabilities.cfg");
cf.put("issuer", trustedIssuer);
cf.put("key", issuerKey);
IotsaSerial.print("Saved capabilities.cfg, issuer=");
IotsaSerial.print(trustedIssuer);
IotsaSerial.print(", key length=");
IotsaSerial.println(issuerKey.length());
}
void IotsaCapabilityMod::loop() {
}
bool IotsaCapabilityMod::allows(const char *obj, IotsaApiOperation verb) {
#ifdef IOTSA_WITH_HTTP_OR_HTTPS
loadCapabilitiesFromRequest();
#endif
#ifdef IOTSA_WITH_COAP
// Need to load capability from coap headers, somehow...
#endif
if (capabilities) {
if (capabilities->allows(obj, verb)) {
IFDEBUGX IotsaSerial.print("Capability allows operation on ");
IFDEBUGX IotsaSerial.println(obj);
return true;
}
IFDEBUGX IotsaSerial.print("Capability does NOT allow operation on ");
IFDEBUGX IotsaSerial.println(obj);
}
// If no rights fall back to username/password authentication
return chain.allows(obj, verb);
}
bool IotsaCapabilityMod::allows(const char *right) {
// If no rights fall back to username/password authentication
return chain.allows(right);
}
#ifdef IOTSA_WITH_HTTP_OR_HTTPS
void IotsaCapabilityMod::loadCapabilitiesFromRequest() {
// Free old capabilities
IotsaCapability **cpp;
for (cpp=&capabilities; *cpp; cpp=&(*cpp)->next) free(*cpp);
capabilities = NULL;
// Check that we can load and verify capabilities
if (trustedIssuer == "" || issuerKey == "") return;
// Load the bearer token from the request
if (!server->hasHeader("Authorization")) {
IFDEBUGX Serial.println("No authorization header in request");
return;
}
String authHeader = server->header("Authorization");
if (!authHeader.startsWith("Bearer ")) {
IFDEBUGX Serial.println("No bearer token in request");
return;
}
String token = authHeader.substring(7);
// Decode the bearer token
ArduinoJWT decoder(issuerKey);
String payload;
bool ok = decoder.decodeJWT(token, payload);
// If decode returned false the token wasn't signed with the correct key.
if (!ok) {
IFDEBUGX IotsaSerial.println("Did not decode correctly with key");
return;
}
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(payload);
// check that issuer matches
String issuer = root["iss"];
if (issuer != trustedIssuer) {
IFDEBUGX IotsaSerial.print("Issuer did not match, wtd=");
IFDEBUGX IotsaSerial.print(trustedIssuer);
IFDEBUGX IotsaSerial.print(", got=");
IFDEBUGX IotsaSerial.println(issuer);
return;
}
if (root.containsKey("aud")) {
JsonVariant audience = root["aud"];
String myFullName = iotsaConfig.hostName + ".local";
#ifdef IOTSA_WITH_HTTPS
String myUrl = "https://" + myFullName;
#else
String myUrl = "http://" + myFullName;
#endif
if (audience != "*" && audience != myFullName && audience != myUrl) {
IFDEBUGX IotsaSerial.print("Audience did not match, wtd=");
IFDEBUGX IotsaSerial.print(myFullName);
IFDEBUGX IotsaSerial.print(", got=");
IFDEBUGX IotsaSerial.println(audience.as<String>());
return;
}
}
const char *obj = root.get<char*>("obj");
IotsaCapabilityObjectScope get = getRightFrom(root["get"]);
IotsaCapabilityObjectScope put = getRightFrom(root["put"]);
IotsaCapabilityObjectScope post = getRightFrom(root["post"]);
IFDEBUGX IotsaSerial.print("capability for ");
IFDEBUGX IotsaSerial.print(obj);
IFDEBUGX IotsaSerial.print(", get=");
IFDEBUGX IotsaSerial.print(int(get));
IFDEBUGX IotsaSerial.print(", put=");
IFDEBUGX IotsaSerial.print(int(put));
IFDEBUGX IotsaSerial.print(", post=");
IFDEBUGX IotsaSerial.print(int(post));
IFDEBUGX IotsaSerial.println(" loaded");
capabilities = new IotsaCapability(obj, get, put, post);
}
#endif // IOTSA_WITH_HTTP_OR_HTTPS<commit_msg>commented out unused static function<commit_after>#include "iotsa.h"
#include "iotsaCapabilities.h"
#include "iotsaConfigFile.h"
#include <ArduinoJWT.h>
#include <ArduinoJson.h>
#define IFDEBUGX if(1)
#if 0
// Static method to check whether a string exactly matches a Json object,
// or is included in the Json object if it is an array.
static bool stringContainedIn(const char *wanted, JsonVariant& got) {
if (got.is<char*>()) {
return strcmp(wanted, got.as<const char *>()) == 0;
}
if (!got.is<JsonArray>()) {
return false;
}
JsonArray& gotArray = got.as<JsonArray>();
for(size_t i=0; i<gotArray.size(); i++) {
const char *gotItem = gotArray[i];
if (strcmp(gotItem, wanted) == 0) {
return true;
}
}
return false;
}
#endif
// Get a scope indicator from a JSON variant
static IotsaCapabilityObjectScope getRightFrom(const JsonVariant& arg) {
if (!arg.is<char*>()) return IOTSA_SCOPE_NONE;
const char *argStr = arg.as<char*>();
if (strcmp(argStr, "self") == 0) return IOTSA_SCOPE_SELF;
if (strcmp(argStr, "descendant-or-self") == 0) return IOTSA_SCOPE_FULL;
if (strcmp(argStr, "descendant") == 0) return IOTSA_SCOPE_CHILD;
if (strcmp(argStr, "child") == 0) return IOTSA_SCOPE_CHILD;
return IOTSA_SCOPE_NONE;
}
bool IotsaCapability::allows(const char *_obj, IotsaApiOperation verb) {
IotsaCapabilityObjectScope scope = scopes[int(verb)];
int matchLength = obj.length();
switch(scope) {
case IOTSA_SCOPE_NONE:
break;
case IOTSA_SCOPE_SELF:
if (strcmp(obj.c_str(), _obj) == 0)
return true;
break;
case IOTSA_SCOPE_FULL:
if (strncmp(obj.c_str(), _obj, matchLength) == 0) {
char nextCh = _obj[matchLength];
if (nextCh == '\0' || nextCh == '/')
return true;
}
break;
case IOTSA_SCOPE_CHILD:
if (strncmp(obj.c_str(), _obj, matchLength) == 0) {
char nextCh = _obj[matchLength];
if (nextCh == '/')
return true;
}
break;
}
// See if there is a next capabiliy we can check, otherwise we don't have permission.
if (next) return next->allows(_obj, verb);
return false;
}
IotsaCapabilityMod::IotsaCapabilityMod(IotsaApplication &_app, IotsaAuthenticationProvider& _chain)
: IotsaAuthMod(_app),
capabilities(NULL),
#ifdef IOTSA_WITH_API
api(this, _app, this),
#endif
chain(_chain),
trustedIssuer(""),
issuerKey("")
{
configLoad();
}
#ifdef IOTSA_WITH_WEB
void
IotsaCapabilityMod::handler() {
String _trustedIssuer = server->arg("trustedIssuer");
String _issuerKey = server->arg("issuerKey");
if (_trustedIssuer != "" || _issuerKey != "") {
if (!iotsaConfig.inConfigurationMode()) {
server->send(403, "text/plain", "403 Forbidden, not in configuration mode");
return;
}
if (needsAuthentication("capabilities")) return;
if (_trustedIssuer != "") trustedIssuer = _trustedIssuer;
if (_issuerKey != "") issuerKey = _issuerKey;
configSave();
server->send(200, "text/plain", "ok\r\n");
return;
}
String message = "<html><head><title>Capability Authority</title></head><body><h1>Capability Authority</h1>";
if (!iotsaConfig.inConfigurationMode())
message += "<p><em>Note:</em> You must be in configuration mode to be able to change issuer or key.</p>";
message += "<form method='get'>Issuer: <input name='trustedIssuer' value='";
message += htmlEncode(trustedIssuer);
message += "'><br>Current shared key is secret, but length is ";
message += String(issuerKey.length());
message += ".<br>New key: <input name='issuerKey'><br><input type='Submit'></form></body></html>";
server->send(200, "text/html", message);
}
String IotsaCapabilityMod::info() {
String message = "<p>Capabilities enabled.";
message += " See <a href=\"/capabilities\">/capabilities</a> to change settings.";
message += "</p>";
return message;
}
#endif // IOTSA_WITH_WEB
#ifdef IOTSA_WITH_API
bool IotsaCapabilityMod::getHandler(const char *path, JsonObject& reply) {
if (strcmp(path, "/api/capabilities") != 0) return false;
reply["trustedIssuer"] = trustedIssuer;
reply["has_issuerKey"] = (issuerKey.length() > 0);
return true;
}
bool IotsaCapabilityMod::putHandler(const char *path, const JsonVariant& request, JsonObject& reply) {
if (strcmp(path, "/api/capabilities") != 0) return false;
if (!iotsaConfig.inConfigurationMode()) return false;
bool anyChanged = false;
JsonObject& reqObj = request.as<JsonObject>();
if (reqObj.containsKey("trustedIssuer")) {
trustedIssuer = reqObj.get<String>("trustedIssuer");
anyChanged = true;
}
if (reqObj.containsKey("issuerKey")) {
issuerKey = reqObj.get<String>("issuerKey");
anyChanged = true;
}
if (anyChanged) {
configSave();
}
return anyChanged;
}
bool IotsaCapabilityMod::postHandler(const char *path, const JsonVariant& request, JsonObject& reply) {
return false;
}
#endif // IOTSA_WITH_API
void IotsaCapabilityMod::setup() {
configLoad();
}
void IotsaCapabilityMod::serverSetup() {
#ifdef IOTSA_WITH_WEB
server->on("/capabilities", std::bind(&IotsaCapabilityMod::handler, this));
#endif
#ifdef IOTSA_WITH_API
api.setup("/api/capabilities", true, true, false);
name = "capabilities";
#endif
}
void IotsaCapabilityMod::configLoad() {
IotsaConfigFileLoad cf("/config/capabilities.cfg");
cf.get("issuer", trustedIssuer, "");
cf.get("key", issuerKey, "");
}
void IotsaCapabilityMod::configSave() {
IotsaConfigFileSave cf("/config/capabilities.cfg");
cf.put("issuer", trustedIssuer);
cf.put("key", issuerKey);
IotsaSerial.print("Saved capabilities.cfg, issuer=");
IotsaSerial.print(trustedIssuer);
IotsaSerial.print(", key length=");
IotsaSerial.println(issuerKey.length());
}
void IotsaCapabilityMod::loop() {
}
bool IotsaCapabilityMod::allows(const char *obj, IotsaApiOperation verb) {
#ifdef IOTSA_WITH_HTTP_OR_HTTPS
loadCapabilitiesFromRequest();
#endif
#ifdef IOTSA_WITH_COAP
// Need to load capability from coap headers, somehow...
#endif
if (capabilities) {
if (capabilities->allows(obj, verb)) {
IFDEBUGX IotsaSerial.print("Capability allows operation on ");
IFDEBUGX IotsaSerial.println(obj);
return true;
}
IFDEBUGX IotsaSerial.print("Capability does NOT allow operation on ");
IFDEBUGX IotsaSerial.println(obj);
}
// If no rights fall back to username/password authentication
return chain.allows(obj, verb);
}
bool IotsaCapabilityMod::allows(const char *right) {
// If no rights fall back to username/password authentication
return chain.allows(right);
}
#ifdef IOTSA_WITH_HTTP_OR_HTTPS
void IotsaCapabilityMod::loadCapabilitiesFromRequest() {
// Free old capabilities
IotsaCapability **cpp;
for (cpp=&capabilities; *cpp; cpp=&(*cpp)->next) free(*cpp);
capabilities = NULL;
// Check that we can load and verify capabilities
if (trustedIssuer == "" || issuerKey == "") return;
// Load the bearer token from the request
if (!server->hasHeader("Authorization")) {
IFDEBUGX Serial.println("No authorization header in request");
return;
}
String authHeader = server->header("Authorization");
if (!authHeader.startsWith("Bearer ")) {
IFDEBUGX Serial.println("No bearer token in request");
return;
}
String token = authHeader.substring(7);
// Decode the bearer token
ArduinoJWT decoder(issuerKey);
String payload;
bool ok = decoder.decodeJWT(token, payload);
// If decode returned false the token wasn't signed with the correct key.
if (!ok) {
IFDEBUGX IotsaSerial.println("Did not decode correctly with key");
return;
}
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(payload);
// check that issuer matches
String issuer = root["iss"];
if (issuer != trustedIssuer) {
IFDEBUGX IotsaSerial.print("Issuer did not match, wtd=");
IFDEBUGX IotsaSerial.print(trustedIssuer);
IFDEBUGX IotsaSerial.print(", got=");
IFDEBUGX IotsaSerial.println(issuer);
return;
}
if (root.containsKey("aud")) {
JsonVariant audience = root["aud"];
String myFullName = iotsaConfig.hostName + ".local";
#ifdef IOTSA_WITH_HTTPS
String myUrl = "https://" + myFullName;
#else
String myUrl = "http://" + myFullName;
#endif
if (audience != "*" && audience != myFullName && audience != myUrl) {
IFDEBUGX IotsaSerial.print("Audience did not match, wtd=");
IFDEBUGX IotsaSerial.print(myFullName);
IFDEBUGX IotsaSerial.print(", got=");
IFDEBUGX IotsaSerial.println(audience.as<String>());
return;
}
}
const char *obj = root.get<char*>("obj");
IotsaCapabilityObjectScope get = getRightFrom(root["get"]);
IotsaCapabilityObjectScope put = getRightFrom(root["put"]);
IotsaCapabilityObjectScope post = getRightFrom(root["post"]);
IFDEBUGX IotsaSerial.print("capability for ");
IFDEBUGX IotsaSerial.print(obj);
IFDEBUGX IotsaSerial.print(", get=");
IFDEBUGX IotsaSerial.print(int(get));
IFDEBUGX IotsaSerial.print(", put=");
IFDEBUGX IotsaSerial.print(int(put));
IFDEBUGX IotsaSerial.print(", post=");
IFDEBUGX IotsaSerial.print(int(post));
IFDEBUGX IotsaSerial.println(" loaded");
capabilities = new IotsaCapability(obj, get, put, post);
}
#endif // IOTSA_WITH_HTTP_OR_HTTPS<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2012 J-P Nurmi <[email protected]>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*/
#include "ircmessagedecoder_p.h"
#include "irccodecplugin.h"
#include <QCoreApplication>
#include <QPluginLoader>
#include <QStringList>
#include <QDebug>
#include <QMap>
#include <QDir>
extern "C" {
int IsUTF8Text(const char* utf8, int len);
}
typedef QMap<QByteArray, IrcCodecPlugin*> IrcCodecPluginMap;
Q_GLOBAL_STATIC(IrcCodecPluginMap, irc_codec_plugins)
static QByteArray irc_plugin_key = qgetenv("COMMUNI_CODEC_PLUGIN");
COMMUNI_EXPORT void irc_set_codec_plugin(const QByteArray& key)
{
irc_plugin_key = key;
}
IrcMessageDecoder::IrcMessageDecoder()
{
d.fallback = QTextCodec::codecForName("ISO-8859-15");
}
IrcMessageDecoder::~IrcMessageDecoder()
{
}
QByteArray IrcMessageDecoder::encoding() const
{
return d.fallback->name();
}
void IrcMessageDecoder::setEncoding(const QByteArray& encoding)
{
if (QTextCodec::availableCodecs().contains(encoding))
d.fallback = QTextCodec::codecForName(encoding);
}
QString IrcMessageDecoder::decode(const QByteArray& data) const
{
// TODO: not thread safe
static QByteArray pluginKey;
static bool initialized = false;
if (!initialized) {
pluginKey = const_cast<IrcMessageDecoder*>(this)->initialize();
initialized = true;
}
QTextCodec* codec = 0;
if (IsUTF8Text(data, data.length())) {
codec = QTextCodec::codecForName("UTF-8");
} else {
QByteArray name = d.fallback->name();
IrcCodecPlugin* plugin = irc_codec_plugins()->value(pluginKey);
if (plugin)
name = plugin->codecForData(data);
codec = QTextCodec::codecForName(name);
}
if (!codec)
codec = d.fallback;
Q_ASSERT(codec);
return codec->toUnicode(data);
}
QByteArray IrcMessageDecoder::initialize()
{
bool loaded = loadPlugins();
QByteArray pluginKey = irc_plugin_key;
if (!pluginKey.isEmpty() && !irc_codec_plugins()->contains(pluginKey)) {
qWarning() << "IrcMessageDecoder:" << pluginKey << "plugin not loaded";
if (loaded)
qWarning() << "IrcMessageDecoder: available plugins:" << irc_codec_plugins()->keys();
}
if (!loaded)
qWarning() << "IrcMessageDecoder: no plugins available";
if (pluginKey.isEmpty() && !irc_codec_plugins()->isEmpty())
pluginKey = irc_codec_plugins()->keys().first();
return pluginKey;
}
#if defined(Q_OS_WIN)
#define COMMUNI_PATH_SEPARATOR ';'
#else
#define COMMUNI_PATH_SEPARATOR ':'
#endif
static QStringList pluginPaths()
{
QStringList paths = QCoreApplication::libraryPaths();
const QByteArray env = qgetenv("COMMUNI_PLUGIN_PATH");
if (!env.isEmpty()) {
foreach(const QString & path, QFile::decodeName(env).split(COMMUNI_PATH_SEPARATOR, QString::SkipEmptyParts)) {
QString canonicalPath = QDir(path).canonicalPath();
if (!canonicalPath.isEmpty() && !paths.contains(canonicalPath))
paths += canonicalPath;
}
}
return paths;
}
bool IrcMessageDecoder::loadPlugins()
{
foreach(QObject* instance, QPluginLoader::staticInstances()) {
IrcCodecPlugin* plugin = qobject_cast<IrcCodecPlugin*>(instance);
if (plugin)
irc_codec_plugins()->insert(plugin->key(), plugin);
}
foreach(const QString & path, pluginPaths()) {
QDir dir(path);
if (!dir.cd("communi"))
continue;
foreach(const QFileInfo & file, dir.entryInfoList(QDir::Files)) {
QPluginLoader loader(file.absoluteFilePath());
IrcCodecPlugin* plugin = qobject_cast<IrcCodecPlugin*>(loader.instance());
if (plugin)
irc_codec_plugins()->insert(plugin->key(), plugin);
}
}
return !irc_codec_plugins()->isEmpty();
}
<commit_msg>IrcMessageDecoder: add some debug output (when COMMUNI_DEBUG=1)<commit_after>/*
* Copyright (C) 2008-2012 J-P Nurmi <[email protected]>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*/
#include "ircmessagedecoder_p.h"
#include "irccodecplugin.h"
#include <QCoreApplication>
#include <QPluginLoader>
#include <QStringList>
#include <QDebug>
#include <QMap>
#include <QDir>
extern "C" {
int IsUTF8Text(const char* utf8, int len);
}
typedef QMap<QByteArray, IrcCodecPlugin*> IrcCodecPluginMap;
Q_GLOBAL_STATIC(IrcCodecPluginMap, irc_codec_plugins)
static QByteArray irc_plugin_key = qgetenv("COMMUNI_CODEC_PLUGIN");
COMMUNI_EXPORT void irc_set_codec_plugin(const QByteArray& key)
{
irc_plugin_key = key;
}
IrcMessageDecoder::IrcMessageDecoder()
{
d.fallback = QTextCodec::codecForName("ISO-8859-15");
}
IrcMessageDecoder::~IrcMessageDecoder()
{
}
QByteArray IrcMessageDecoder::encoding() const
{
return d.fallback->name();
}
void IrcMessageDecoder::setEncoding(const QByteArray& encoding)
{
if (QTextCodec::availableCodecs().contains(encoding))
d.fallback = QTextCodec::codecForName(encoding);
}
QString IrcMessageDecoder::decode(const QByteArray& data) const
{
// TODO: not thread safe
static QByteArray pluginKey;
static bool initialized = false;
if (!initialized) {
pluginKey = const_cast<IrcMessageDecoder*>(this)->initialize();
initialized = true;
}
QTextCodec* codec = 0;
if (IsUTF8Text(data, data.length())) {
codec = QTextCodec::codecForName("UTF-8");
} else {
QByteArray name = d.fallback->name();
IrcCodecPlugin* plugin = irc_codec_plugins()->value(pluginKey);
if (plugin)
name = plugin->codecForData(data);
codec = QTextCodec::codecForName(name);
}
if (!codec)
codec = d.fallback;
Q_ASSERT(codec);
return codec->toUnicode(data);
}
QByteArray IrcMessageDecoder::initialize()
{
bool loaded = loadPlugins();
QByteArray pluginKey = irc_plugin_key;
if (!pluginKey.isEmpty() && !irc_codec_plugins()->contains(pluginKey)) {
qWarning() << "IrcMessageDecoder:" << pluginKey << "plugin not loaded";
if (loaded)
qWarning() << "IrcMessageDecoder: available plugins:" << irc_codec_plugins()->keys();
}
if (!loaded)
qWarning() << "IrcMessageDecoder: no plugins available";
if (pluginKey.isEmpty() && !irc_codec_plugins()->isEmpty())
pluginKey = irc_codec_plugins()->keys().first();
return pluginKey;
}
#if defined(Q_OS_WIN)
#define COMMUNI_PATH_SEPARATOR ';'
#else
#define COMMUNI_PATH_SEPARATOR ':'
#endif
static QStringList pluginPaths()
{
QStringList paths = QCoreApplication::libraryPaths();
const QByteArray env = qgetenv("COMMUNI_PLUGIN_PATH");
if (!env.isEmpty()) {
foreach(const QString & path, QFile::decodeName(env).split(COMMUNI_PATH_SEPARATOR, QString::SkipEmptyParts)) {
QString canonicalPath = QDir(path).canonicalPath();
if (!canonicalPath.isEmpty() && !paths.contains(canonicalPath))
paths += canonicalPath;
}
}
static bool dbg = qgetenv("COMMUNI_DEBUG").toInt();
if (dbg) qDebug() << "IrcMessageDecoder: plugin paths:" << paths;
return paths;
}
bool IrcMessageDecoder::loadPlugins()
{
static bool dbg = qgetenv("COMMUNI_DEBUG").toInt();
foreach(QObject* instance, QPluginLoader::staticInstances()) {
IrcCodecPlugin* plugin = qobject_cast<IrcCodecPlugin*>(instance);
if (plugin) {
irc_codec_plugins()->insert(plugin->key(), plugin);
if (dbg) qDebug() << "IrcMessageDecoder: loaded static plugin:" << plugin->key();
}
}
foreach(const QString & path, pluginPaths()) {
QDir dir(path);
if (!dir.cd("communi"))
continue;
foreach(const QFileInfo & file, dir.entryInfoList(QDir::Files)) {
QPluginLoader loader(file.absoluteFilePath());
IrcCodecPlugin* plugin = qobject_cast<IrcCodecPlugin*>(loader.instance());
if (plugin) {
irc_codec_plugins()->insert(plugin->key(), plugin);
if (dbg) qDebug() << "IrcMessageDecoder: loaded dynamic plugin:" << plugin->key() << file.fileName();
}
}
}
return !irc_codec_plugins()->isEmpty();
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef DLL_LAYER_TRAITS_HPP
#define DLL_LAYER_TRAITS_HPP
#include "tmp.hpp"
#include "decay_type.hpp"
#include "sparsity_method.hpp"
namespace dll {
template<typename Desc>
struct dyn_rbm;
template<typename Desc>
struct conv_rbm;
template<typename Desc>
struct conv_rbm_mp;
template<typename Desc>
struct mp_layer_3d;
template<typename Desc>
struct avgp_layer_3d;
/*!
* \brief Type Traits to get information on RBM type
*/
template<typename RBM>
struct layer_traits {
using rbm_t = RBM;
/*!
* \brief Indicates if the RBM is convolutional
*/
static constexpr bool is_convolutional(){
return cpp::is_specialization_of<conv_rbm, rbm_t>::value
|| cpp::is_specialization_of<conv_rbm_mp, rbm_t>::value;
}
/*!
* \brief Indicates if this layer is a RBM layer.
*/
static constexpr bool is_rbm_layer(){
return !is_pooling_layer();
}
/*!
* \brief Indicates if this layer is a pooling layer.
*/
static constexpr bool is_pooling_layer(){
return cpp::is_specialization_of<mp_layer_3d, rbm_t>::value
|| cpp::is_specialization_of<avgp_layer_3d, rbm_t>::value;
}
template<cpp_enable_if_cst(layer_traits<rbm_t>::is_rbm_layer())>
static constexpr bool pretrain_last(){
//Softmax unit should not be pretrained
return rbm_t::hidden_unit != unit_type::SOFTMAX;
}
template<cpp_disable_if_cst(layer_traits<rbm_t>::is_rbm_layer())>
static constexpr bool pretrain_last(){
//if the pooling layer is the last, we spare the time to activate the previous layer by not training it
//since training pooling layer is a nop, that doesn't change anything
return false;
}
/*!
* \brief Indicates if the RBM is dynamic
*/
static constexpr bool is_dynamic(){
return cpp::is_specialization_of<dyn_rbm, rbm_t>::value;
}
/*!
* \brief Indicates if the RBM is convolutional and has probabilistic max
* pooling
*/
static constexpr bool has_probabilistic_max_pooling(){
return cpp::is_specialization_of<conv_rbm_mp, rbm_t>::value;
}
static constexpr std::size_t input_size(){
return rbm_t::input_size();
}
static constexpr std::size_t output_size(){
return rbm_t::output_size();
}
static constexpr std::size_t batch_size(){
return detail::get_value_l<dll::batch_size<1>, typename rbm_t::desc::parameters>::value;
}
static constexpr bool has_momentum(){
return rbm_t::desc::parameters::template contains<momentum>();
}
static constexpr bool is_parallel(){
return rbm_t::desc::parameters::template contains<parallel>();
}
static constexpr bool is_verbose(){
return rbm_t::desc::parameters::template contains<verbose>();
}
static constexpr bool has_shuffle(){
return rbm_t::desc::parameters::template contains<shuffle>();
}
static constexpr bool is_dbn_only(){
return rbm_t::desc::parameters::template contains<dbn_only>();
}
static constexpr bool is_memory(){
return rbm_t::desc::parameters::template contains<memory>();
}
static constexpr bool has_sparsity(){
return sparsity_method() != dll::sparsity_method::NONE;
}
static constexpr dll::sparsity_method sparsity_method(){
return detail::get_value_l<sparsity<dll::sparsity_method::NONE>, typename rbm_t::desc::parameters>::value;
}
static constexpr enum dll::bias_mode bias_mode(){
return detail::get_value_l<bias<dll::bias_mode::SIMPLE>, typename rbm_t::desc::parameters>::value;
}
static constexpr decay_type decay(){
return detail::get_value_l<weight_decay<decay_type::NONE>, typename rbm_t::desc::parameters>::value;
}
static constexpr bool init_weights(){
return rbm_t::desc::parameters::template contains<dll::init_weights>();
}
static constexpr bool free_energy(){
return rbm_t::desc::parameters::template contains<dll::free_energy>();
}
};
template<typename RBM, cpp::enable_if_u<layer_traits<RBM>::is_dynamic()> = cpp::detail::dummy>
std::size_t get_batch_size(const RBM& rbm){
return rbm.batch_size;
}
template<typename RBM, cpp::disable_if_u<layer_traits<RBM>::is_dynamic()> = cpp::detail::dummy>
constexpr std::size_t get_batch_size(const RBM&){
return layer_traits<RBM>::batch_size();
}
template<typename RBM, cpp::enable_if_u<layer_traits<RBM>::is_dynamic()> = cpp::detail::dummy>
std::size_t num_visible(const RBM& rbm){
return rbm.num_visible;
}
template<typename RBM, cpp::disable_if_u<layer_traits<RBM>::is_dynamic()> = cpp::detail::dummy>
constexpr std::size_t num_visible(const RBM&){
return RBM::desc::num_visible;
}
template<typename RBM, cpp::enable_if_u<layer_traits<RBM>::is_dynamic()> = cpp::detail::dummy>
std::size_t num_hidden(const RBM& rbm){
return rbm.num_hidden;
}
template<typename RBM, cpp::disable_if_u<layer_traits<RBM>::is_dynamic()> = cpp::detail::dummy>
constexpr std::size_t num_hidden(const RBM&){
return RBM::desc::num_hidden;
}
template<typename RBM, cpp::disable_if_u<layer_traits<RBM>::is_dynamic()> = cpp::detail::dummy>
constexpr std::size_t output_size(const RBM&){
return layer_traits<RBM>::output_size();
}
template<typename RBM, cpp::enable_if_u<layer_traits<RBM>::is_dynamic()> = cpp::detail::dummy>
std::size_t output_size(const RBM& rbm){
return rbm.num_hidden;
}
template<typename RBM, cpp::enable_if_u<layer_traits<RBM>::is_dynamic()> = cpp::detail::dummy>
std::size_t input_size(const RBM& rbm){
return rbm.num_visible;
}
template<typename RBM, cpp::disable_if_u<layer_traits<RBM>::is_dynamic()> = cpp::detail::dummy>
constexpr std::size_t input_size(const RBM&){
return layer_traits<RBM>::input_size();
}
} //end of dll namespace
#endif
<commit_msg>New traits: is_transform_layer<commit_after>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef DLL_LAYER_TRAITS_HPP
#define DLL_LAYER_TRAITS_HPP
#include "tmp.hpp"
#include "decay_type.hpp"
#include "sparsity_method.hpp"
namespace dll {
template<typename Desc>
struct dyn_rbm;
template<typename Desc>
struct conv_rbm;
template<typename Desc>
struct conv_rbm_mp;
template<typename Desc>
struct mp_layer_3d;
template<typename Desc>
struct avgp_layer_3d;
template<typename Desc>
struct binarize_layer;
/*!
* \brief Type Traits to get information on RBM type
*/
template<typename RBM>
struct layer_traits {
using rbm_t = RBM;
/*!
* \brief Indicates if the RBM is convolutional
*/
static constexpr bool is_convolutional(){
return cpp::is_specialization_of<conv_rbm, rbm_t>::value
|| cpp::is_specialization_of<conv_rbm_mp, rbm_t>::value;
}
/*!
* \brief Indicates if this layer is a RBM layer.
*/
static constexpr bool is_rbm_layer(){
return !(is_pooling_layer() || is_transform_layer());
}
/*!
* \brief Indicates if this layer is a pooling layer.
*/
static constexpr bool is_pooling_layer(){
return cpp::is_specialization_of<mp_layer_3d, rbm_t>::value
|| cpp::is_specialization_of<avgp_layer_3d, rbm_t>::value;
}
/*!
* \brief Indicates if this layer is a transformation layer.
*/
static constexpr bool is_transform_layer(){
return cpp::is_specialization_of<binarize_layer, rbm_t>::value;
}
/*!
* \brief Indicates if this layer should be trained if it is the last layer.
*/
template<cpp_enable_if_cst(layer_traits<rbm_t>::is_rbm_layer())>
static constexpr bool pretrain_last(){
//Softmax unit should not be pretrained
return rbm_t::hidden_unit != unit_type::SOFTMAX;
}
template<cpp_disable_if_cst(layer_traits<rbm_t>::is_rbm_layer())>
static constexpr bool pretrain_last(){
//if the pooling layer is the last, we spare the time to activate the previous layer by not training it
//since training pooling layer is a nop, that doesn't change anything
return false;
}
/*!
* \brief Indicates if the RBM is dynamic
*/
static constexpr bool is_dynamic(){
return cpp::is_specialization_of<dyn_rbm, rbm_t>::value;
}
/*!
* \brief Indicates if the RBM is convolutional and has probabilistic max
* pooling
*/
static constexpr bool has_probabilistic_max_pooling(){
return cpp::is_specialization_of<conv_rbm_mp, rbm_t>::value;
}
static constexpr std::size_t input_size(){
return rbm_t::input_size();
}
static constexpr std::size_t output_size(){
return rbm_t::output_size();
}
static constexpr std::size_t batch_size(){
return detail::get_value_l<dll::batch_size<1>, typename rbm_t::desc::parameters>::value;
}
static constexpr bool has_momentum(){
return rbm_t::desc::parameters::template contains<momentum>();
}
static constexpr bool is_parallel(){
return rbm_t::desc::parameters::template contains<parallel>();
}
static constexpr bool is_verbose(){
return rbm_t::desc::parameters::template contains<verbose>();
}
static constexpr bool has_shuffle(){
return rbm_t::desc::parameters::template contains<shuffle>();
}
static constexpr bool is_dbn_only(){
return rbm_t::desc::parameters::template contains<dbn_only>();
}
static constexpr bool is_memory(){
return rbm_t::desc::parameters::template contains<memory>();
}
static constexpr bool has_sparsity(){
return sparsity_method() != dll::sparsity_method::NONE;
}
static constexpr dll::sparsity_method sparsity_method(){
return detail::get_value_l<sparsity<dll::sparsity_method::NONE>, typename rbm_t::desc::parameters>::value;
}
static constexpr enum dll::bias_mode bias_mode(){
return detail::get_value_l<bias<dll::bias_mode::SIMPLE>, typename rbm_t::desc::parameters>::value;
}
static constexpr decay_type decay(){
return detail::get_value_l<weight_decay<decay_type::NONE>, typename rbm_t::desc::parameters>::value;
}
static constexpr bool init_weights(){
return rbm_t::desc::parameters::template contains<dll::init_weights>();
}
static constexpr bool free_energy(){
return rbm_t::desc::parameters::template contains<dll::free_energy>();
}
};
template<typename RBM, cpp::enable_if_u<layer_traits<RBM>::is_dynamic()> = cpp::detail::dummy>
std::size_t get_batch_size(const RBM& rbm){
return rbm.batch_size;
}
template<typename RBM, cpp::disable_if_u<layer_traits<RBM>::is_dynamic()> = cpp::detail::dummy>
constexpr std::size_t get_batch_size(const RBM&){
return layer_traits<RBM>::batch_size();
}
template<typename RBM, cpp::enable_if_u<layer_traits<RBM>::is_dynamic()> = cpp::detail::dummy>
std::size_t num_visible(const RBM& rbm){
return rbm.num_visible;
}
template<typename RBM, cpp::disable_if_u<layer_traits<RBM>::is_dynamic()> = cpp::detail::dummy>
constexpr std::size_t num_visible(const RBM&){
return RBM::desc::num_visible;
}
template<typename RBM, cpp::enable_if_u<layer_traits<RBM>::is_dynamic()> = cpp::detail::dummy>
std::size_t num_hidden(const RBM& rbm){
return rbm.num_hidden;
}
template<typename RBM, cpp::disable_if_u<layer_traits<RBM>::is_dynamic()> = cpp::detail::dummy>
constexpr std::size_t num_hidden(const RBM&){
return RBM::desc::num_hidden;
}
template<typename RBM, cpp::disable_if_u<layer_traits<RBM>::is_dynamic()> = cpp::detail::dummy>
constexpr std::size_t output_size(const RBM&){
return layer_traits<RBM>::output_size();
}
template<typename RBM, cpp::enable_if_u<layer_traits<RBM>::is_dynamic()> = cpp::detail::dummy>
std::size_t output_size(const RBM& rbm){
return rbm.num_hidden;
}
template<typename RBM, cpp::enable_if_u<layer_traits<RBM>::is_dynamic()> = cpp::detail::dummy>
std::size_t input_size(const RBM& rbm){
return rbm.num_visible;
}
template<typename RBM, cpp::disable_if_u<layer_traits<RBM>::is_dynamic()> = cpp::detail::dummy>
constexpr std::size_t input_size(const RBM&){
return layer_traits<RBM>::input_size();
}
} //end of dll namespace
#endif
<|endoftext|> |
<commit_before>// Copyright 2015, Christopher J. Foster and the other displaz contributors.
// Use of this code is governed by the BSD-style license found in LICENSE.txt
#include "HookFormatter.h"
#include "IpcChannel.h"
#include "PointViewerMainWindow.h"
HookFormatter::HookFormatter(PointViewerMainWindow* getPayload, QByteArray hookSpec,
QByteArray hookPayload, QObject* parent)
: QObject(parent),
m_hookSpec(hookSpec),
m_hookPayload(hookPayload),
m_getPayload(getPayload)
{
connect(this, SIGNAL(sendIpcMessage(QByteArray)), parent, SLOT(sendMessage(QByteArray)));
connect(parent, SIGNAL(disconnected()), this, SLOT(channelDisconnected()));
}
/// Get payload and dispatch signal to IpcChannel
void HookFormatter::hookActivated()
{
QByteArray hookPayload = m_getPayload->hookPayload(m_hookPayload);
QByteArray message = m_hookSpec + " " + hookPayload + "\n";
emit sendIpcMessage(message);
}
<commit_msg>Resolve Coverity UMR - HookFormatter::m_eventId uninitialised<commit_after>// Copyright 2015, Christopher J. Foster and the other displaz contributors.
// Use of this code is governed by the BSD-style license found in LICENSE.txt
#include "HookFormatter.h"
#include "IpcChannel.h"
#include "PointViewerMainWindow.h"
HookFormatter::HookFormatter(PointViewerMainWindow* getPayload, QByteArray hookSpec,
QByteArray hookPayload, QObject* parent)
: QObject(parent),
m_hookSpec(hookSpec),
m_hookPayload(hookPayload),
m_getPayload(getPayload),
m_eventId(0)
{
connect(this, SIGNAL(sendIpcMessage(QByteArray)), parent, SLOT(sendMessage(QByteArray)));
connect(parent, SIGNAL(disconnected()), this, SLOT(channelDisconnected()));
}
/// Get payload and dispatch signal to IpcChannel
void HookFormatter::hookActivated()
{
QByteArray hookPayload = m_getPayload->hookPayload(m_hookPayload);
QByteArray message = m_hookSpec + " " + hookPayload + "\n";
emit sendIpcMessage(message);
}
<|endoftext|> |
<commit_before>//https://code.google.com/p/nya-engine/
#include "log.h"
#include "stdout_log.h"
namespace nya_log
{
namespace { log_base *default_log=0; }
log_base &no_log()
{
static log_base l;
return l;
}
void set_log(log_base *l)
{
default_log=l;
}
log_base &log(const char *tag)
{
if(!tag)
tag="general";
if(!default_log)
{
static stdout_log stdlog;
stdlog.set_tag(tag);
return stdlog;
}
default_log->set_tag(tag);
return *default_log;
}
}
<commit_msg>fixed no_log because static variables destructs in uncontrollable order<commit_after>//https://code.google.com/p/nya-engine/
#include "log.h"
#include "stdout_log.h"
namespace nya_log
{
namespace { log_base *default_log=0; }
log_base &no_log()
{
static log_base *l=new log_base();
return *l;
}
void set_log(log_base *l) { default_log=l; }
log_base &log(const char *tag)
{
if(!tag)
tag="general";
if(!default_log)
{
static stdout_log stdlog;
stdlog.set_tag(tag);
return stdlog;
}
default_log->set_tag(tag);
return *default_log;
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
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 "SceneGraphManager.h"
#include "SceneGraph.h"
namespace crown
{
//-----------------------------------------------------------------------------
SceneGraphManager::SceneGraphManager()
: m_graphs(default_allocator())
{
}
//-----------------------------------------------------------------------------
SceneGraphManager::~SceneGraphManager()
{
}
//-----------------------------------------------------------------------------
SceneGraph* SceneGraphManager::create_scene_graph()
{
uint32_t index = m_graphs.size();
SceneGraph* sg = CE_NEW(default_allocator(), SceneGraph)(index);
m_graphs.push_back(sg);
return sg;
}
//-----------------------------------------------------------------------------
void SceneGraphManager::destroy_scene_graph(SceneGraph* sg)
{
CE_ASSERT_NOT_NULL(sg);
m_graphs[sg->m_index] = m_graphs[m_graphs.size() - 1];
m_graphs.pop_back();
CE_DELETE(default_allocator(), sg);
}
//-----------------------------------------------------------------------------
void SceneGraphManager::update()
{
for (uint32_t i = 0; i < m_graphs.size(); i++)
{
m_graphs[i]->update();
}
}
} // namespace crown
<commit_msg>Fix destroying scene graphs<commit_after>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
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 "SceneGraphManager.h"
#include "SceneGraph.h"
namespace crown
{
//-----------------------------------------------------------------------------
SceneGraphManager::SceneGraphManager()
: m_graphs(default_allocator())
{
}
//-----------------------------------------------------------------------------
SceneGraphManager::~SceneGraphManager()
{
}
//-----------------------------------------------------------------------------
SceneGraph* SceneGraphManager::create_scene_graph()
{
uint32_t index = m_graphs.size();
SceneGraph* sg = CE_NEW(default_allocator(), SceneGraph)(index);
m_graphs.push_back(sg);
return sg;
}
//-----------------------------------------------------------------------------
void SceneGraphManager::destroy_scene_graph(SceneGraph* sg)
{
CE_ASSERT_NOT_NULL(sg);
m_graphs[sg->m_index] = m_graphs[m_graphs.size() - 1];
m_graphs[sg->m_index]->m_index = sg->m_index;
m_graphs.pop_back();
CE_DELETE(default_allocator(), sg);
}
//-----------------------------------------------------------------------------
void SceneGraphManager::update()
{
for (uint32_t i = 0; i < m_graphs.size(); i++)
{
m_graphs[i]->update();
}
}
} // namespace crown
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2008 Renato Araujo Oliveira Filho <[email protected]>
Copyright (c) 2000-2009 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLESPixelFormat.h"
#include "OgreRoot.h"
#include "OgreRenderSystem.h"
#include "OgreBitwise.h"
namespace Ogre {
GLenum GLESPixelUtil::getGLOriginFormat(PixelFormat mFormat)
{
switch (mFormat)
{
case PF_A8:
return GL_ALPHA;
case PF_L8:
case PF_L16:
case PF_FLOAT16_R:
case PF_FLOAT32_R:
return GL_LUMINANCE;
case PF_BYTE_LA:
case PF_SHORT_GR:
case PF_FLOAT16_GR:
case PF_FLOAT32_GR:
return GL_LUMINANCE_ALPHA;
// PVR compressed formats
case PF_PVR_RGB2:
return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
case PF_PVR_RGB4:
return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
case PF_PVR_RGBA2:
return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
case PF_PVR_RGBA4:
return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
case PF_R3G3B2:
case PF_R5G6B5:
case PF_FLOAT16_RGB:
case PF_FLOAT32_RGB:
case PF_SHORT_RGB:
return GL_RGB;
case PF_X8R8G8B8:
case PF_A8R8G8B8:
case PF_B8G8R8A8:
case PF_A1R5G5B5:
case PF_A4R4G4B4:
case PF_A2R10G10B10:
// This case in incorrect, swaps R & B channels
// return GL_BGRA;
case PF_X8B8G8R8:
case PF_A8B8G8R8:
case PF_A2B10G10R10:
case PF_FLOAT16_RGBA:
case PF_FLOAT32_RGBA:
case PF_SHORT_RGBA:
return GL_RGBA;
#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
// Formats are in native endian, so R8G8B8 on little endian is
// BGR, on big endian it is RGB.
case PF_R8G8B8:
return GL_RGB;
case PF_B8G8R8:
return 0;
#else
case PF_R8G8B8:
return 0;
case PF_B8G8R8:
return GL_RGB;
#endif
case PF_DXT1:
case PF_DXT3:
case PF_DXT5:
case PF_B5G6R5:
default:
return 0;
}
}
GLenum GLESPixelUtil::getGLOriginDataType(PixelFormat mFormat)
{
switch (mFormat)
{
case PF_A8:
case PF_L8:
case PF_R8G8B8:
case PF_B8G8R8:
case PF_BYTE_LA:
case PF_PVR_RGB2:
case PF_PVR_RGB4:
case PF_PVR_RGBA2:
case PF_PVR_RGBA4:
return GL_UNSIGNED_BYTE;
case PF_R5G6B5:
case PF_B5G6R5:
return GL_UNSIGNED_SHORT_5_6_5;
case PF_L16:
return GL_UNSIGNED_SHORT;
#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
case PF_X8B8G8R8:
case PF_A8B8G8R8:
return GL_UNSIGNED_INT_8_8_8_8_REV;
case PF_X8R8G8B8:
case PF_A8R8G8B8:
return GL_UNSIGNED_INT_8_8_8_8_REV;
case PF_B8G8R8A8:
return GL_UNSIGNED_BYTE;
case PF_R8G8B8A8:
return GL_UNSIGNED_BYTE;
#else
case PF_X8B8G8R8:
case PF_A8B8G8R8:
case PF_X8R8G8B8:
case PF_A8R8G8B8:
return GL_UNSIGNED_BYTE;
case PF_B8G8R8A8:
case PF_R8G8B8A8:
return 0;
#endif
case PF_FLOAT32_R:
case PF_FLOAT32_GR:
case PF_FLOAT32_RGB:
case PF_FLOAT32_RGBA:
return GL_FLOAT;
case PF_SHORT_RGBA:
case PF_SHORT_RGB:
case PF_SHORT_GR:
return GL_UNSIGNED_SHORT;
case PF_A2R10G10B10:
case PF_A2B10G10R10:
case PF_FLOAT16_R:
case PF_FLOAT16_GR:
case PF_FLOAT16_RGB:
case PF_FLOAT16_RGBA:
case PF_R3G3B2:
case PF_A1R5G5B5:
case PF_A4R4G4B4:
// TODO not supported
default:
return 0;
}
}
GLenum GLESPixelUtil::getGLInternalFormat(PixelFormat fmt, bool hwGamma)
{
switch (fmt)
{
case PF_L8:
return GL_LUMINANCE;
case PF_A8:
return GL_ALPHA;
case PF_BYTE_LA:
return GL_LUMINANCE_ALPHA;
case PF_PVR_RGB2:
return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
case PF_PVR_RGB4:
return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
case PF_PVR_RGBA2:
return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
case PF_PVR_RGBA4:
return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
case PF_R8G8B8:
case PF_B8G8R8:
case PF_X8B8G8R8:
case PF_X8R8G8B8:
// DJR - Commenting this out resolves texture problems on iPhone
// if (!hwGamma)
// {
// return GL_RGB;
// }
case PF_A8R8G8B8:
case PF_B8G8R8A8:
if (!hwGamma)
{
return GL_RGBA;
}
case PF_A4L4:
case PF_L16:
case PF_A4R4G4B4:
case PF_R3G3B2:
case PF_A1R5G5B5:
case PF_R5G6B5:
case PF_B5G6R5:
case PF_A2R10G10B10:
case PF_A2B10G10R10:
case PF_FLOAT16_R:
case PF_FLOAT16_RGB:
case PF_FLOAT16_GR:
case PF_FLOAT16_RGBA:
case PF_FLOAT32_R:
case PF_FLOAT32_GR:
case PF_FLOAT32_RGB:
case PF_FLOAT32_RGBA:
case PF_SHORT_RGBA:
case PF_SHORT_RGB:
case PF_SHORT_GR:
case PF_DXT1:
case PF_DXT3:
case PF_DXT5:
default:
return 0;
}
}
GLenum GLESPixelUtil::getClosestGLInternalFormat(PixelFormat mFormat,
bool hwGamma)
{
GLenum format = getGLInternalFormat(mFormat, hwGamma);
if (format==0)
{
if (hwGamma)
{
// TODO not supported
return 0;
}
else
{
return GL_RGBA;
}
}
else
{
return format;
}
}
PixelFormat GLESPixelUtil::getClosestOGREFormat(GLenum fmt)
{
switch (fmt)
{
case GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG:
return PF_PVR_RGB2;
case GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:
return PF_PVR_RGBA2;
case GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG:
return PF_PVR_RGB4;
case GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:
return PF_PVR_RGBA4;
case GL_LUMINANCE:
return PF_L8;
case GL_ALPHA:
return PF_A8;
case GL_LUMINANCE_ALPHA:
return PF_BYTE_LA;
case GL_RGB:
return PF_X8R8G8B8;
case GL_RGBA:
return PF_A8R8G8B8;
#ifdef GL_BGRA
case GL_BGRA:
#endif
// return PF_X8B8G8R8;
default:
//TODO: not supported
return PF_A8R8G8B8;
};
}
size_t GLESPixelUtil::getMaxMipmaps(size_t width, size_t height, size_t depth,
PixelFormat format)
{
size_t count = 0;
do {
if (width > 1)
{
width = width / 2;
}
if (height > 1)
{
height = height / 2;
}
if (depth > 1)
{
depth = depth / 2;
}
/*
NOT needed, compressed formats will have mipmaps up to 1x1
if(PixelUtil::isValidExtent(width, height, depth, format))
count ++;
else
break;
*/
count++;
} while (!(width == 1 && height == 1 && depth == 1));
return count;
}
size_t GLESPixelUtil::optionalPO2(size_t value)
{
const RenderSystemCapabilities *caps =
Root::getSingleton().getRenderSystem()->getCapabilities();
if (caps->hasCapability(RSC_NON_POWER_OF_2_TEXTURES))
{
return value;
}
else
{
return Bitwise::firstPO2From((uint32)value);
}
}
PixelBox* GLESPixelUtil::convertToGLformat(const PixelBox &data,
GLenum *outputFormat)
{
GLenum glFormat = GLESPixelUtil::getGLOriginFormat(data.format);
if (glFormat != 0)
{
// format already supported
return OGRE_NEW PixelBox(data);
}
PixelBox *converted = 0;
if (data.format == PF_R8G8B8)
{
// Convert BGR -> RGB
converted->format = PF_B8G8R8;
*outputFormat = GL_RGB;
converted = OGRE_NEW PixelBox(data);
uint32 *data = (uint32 *) converted->data;
for (uint i = 0; i < converted->getWidth() * converted->getHeight(); i++)
{
uint32 *color = data;
*color = (*color & 0x000000ff) << 16 |
(*color & 0x0000FF00) |
(*color & 0x00FF0000) >> 16;
data += 1;
}
}
return converted;
}
}
<commit_msg>Didn't mean to check this in, PVR texture support isn't finished yet. Commenting it out for now<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2008 Renato Araujo Oliveira Filho <[email protected]>
Copyright (c) 2000-2009 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLESPixelFormat.h"
#include "OgreRoot.h"
#include "OgreRenderSystem.h"
#include "OgreBitwise.h"
namespace Ogre {
GLenum GLESPixelUtil::getGLOriginFormat(PixelFormat mFormat)
{
switch (mFormat)
{
case PF_A8:
return GL_ALPHA;
case PF_L8:
case PF_L16:
case PF_FLOAT16_R:
case PF_FLOAT32_R:
return GL_LUMINANCE;
case PF_BYTE_LA:
case PF_SHORT_GR:
case PF_FLOAT16_GR:
case PF_FLOAT32_GR:
return GL_LUMINANCE_ALPHA;
// PVR compressed formats
// case PF_PVR_RGB2:
// return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
// case PF_PVR_RGB4:
// return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
// case PF_PVR_RGBA2:
// return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
// case PF_PVR_RGBA4:
// return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
case PF_R3G3B2:
case PF_R5G6B5:
case PF_FLOAT16_RGB:
case PF_FLOAT32_RGB:
case PF_SHORT_RGB:
return GL_RGB;
case PF_X8R8G8B8:
case PF_A8R8G8B8:
case PF_B8G8R8A8:
case PF_A1R5G5B5:
case PF_A4R4G4B4:
case PF_A2R10G10B10:
// This case in incorrect, swaps R & B channels
// return GL_BGRA;
case PF_X8B8G8R8:
case PF_A8B8G8R8:
case PF_A2B10G10R10:
case PF_FLOAT16_RGBA:
case PF_FLOAT32_RGBA:
case PF_SHORT_RGBA:
return GL_RGBA;
#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
// Formats are in native endian, so R8G8B8 on little endian is
// BGR, on big endian it is RGB.
case PF_R8G8B8:
return GL_RGB;
case PF_B8G8R8:
return 0;
#else
case PF_R8G8B8:
return 0;
case PF_B8G8R8:
return GL_RGB;
#endif
case PF_DXT1:
case PF_DXT3:
case PF_DXT5:
case PF_B5G6R5:
default:
return 0;
}
}
GLenum GLESPixelUtil::getGLOriginDataType(PixelFormat mFormat)
{
switch (mFormat)
{
case PF_A8:
case PF_L8:
case PF_R8G8B8:
case PF_B8G8R8:
case PF_BYTE_LA:
// case PF_PVR_RGB2:
// case PF_PVR_RGB4:
// case PF_PVR_RGBA2:
// case PF_PVR_RGBA4:
return GL_UNSIGNED_BYTE;
case PF_R5G6B5:
case PF_B5G6R5:
return GL_UNSIGNED_SHORT_5_6_5;
case PF_L16:
return GL_UNSIGNED_SHORT;
#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
case PF_X8B8G8R8:
case PF_A8B8G8R8:
return GL_UNSIGNED_INT_8_8_8_8_REV;
case PF_X8R8G8B8:
case PF_A8R8G8B8:
return GL_UNSIGNED_INT_8_8_8_8_REV;
case PF_B8G8R8A8:
return GL_UNSIGNED_BYTE;
case PF_R8G8B8A8:
return GL_UNSIGNED_BYTE;
#else
case PF_X8B8G8R8:
case PF_A8B8G8R8:
case PF_X8R8G8B8:
case PF_A8R8G8B8:
return GL_UNSIGNED_BYTE;
case PF_B8G8R8A8:
case PF_R8G8B8A8:
return 0;
#endif
case PF_FLOAT32_R:
case PF_FLOAT32_GR:
case PF_FLOAT32_RGB:
case PF_FLOAT32_RGBA:
return GL_FLOAT;
case PF_SHORT_RGBA:
case PF_SHORT_RGB:
case PF_SHORT_GR:
return GL_UNSIGNED_SHORT;
case PF_A2R10G10B10:
case PF_A2B10G10R10:
case PF_FLOAT16_R:
case PF_FLOAT16_GR:
case PF_FLOAT16_RGB:
case PF_FLOAT16_RGBA:
case PF_R3G3B2:
case PF_A1R5G5B5:
case PF_A4R4G4B4:
// TODO not supported
default:
return 0;
}
}
GLenum GLESPixelUtil::getGLInternalFormat(PixelFormat fmt, bool hwGamma)
{
switch (fmt)
{
case PF_L8:
return GL_LUMINANCE;
case PF_A8:
return GL_ALPHA;
case PF_BYTE_LA:
return GL_LUMINANCE_ALPHA;
// case PF_PVR_RGB2:
// return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
// case PF_PVR_RGB4:
// return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
// case PF_PVR_RGBA2:
// return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
// case PF_PVR_RGBA4:
// return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
case PF_R8G8B8:
case PF_B8G8R8:
case PF_X8B8G8R8:
case PF_X8R8G8B8:
// DJR - Commenting this out resolves texture problems on iPhone
// if (!hwGamma)
// {
// return GL_RGB;
// }
case PF_A8R8G8B8:
case PF_B8G8R8A8:
if (!hwGamma)
{
return GL_RGBA;
}
case PF_A4L4:
case PF_L16:
case PF_A4R4G4B4:
case PF_R3G3B2:
case PF_A1R5G5B5:
case PF_R5G6B5:
case PF_B5G6R5:
case PF_A2R10G10B10:
case PF_A2B10G10R10:
case PF_FLOAT16_R:
case PF_FLOAT16_RGB:
case PF_FLOAT16_GR:
case PF_FLOAT16_RGBA:
case PF_FLOAT32_R:
case PF_FLOAT32_GR:
case PF_FLOAT32_RGB:
case PF_FLOAT32_RGBA:
case PF_SHORT_RGBA:
case PF_SHORT_RGB:
case PF_SHORT_GR:
case PF_DXT1:
case PF_DXT3:
case PF_DXT5:
default:
return 0;
}
}
GLenum GLESPixelUtil::getClosestGLInternalFormat(PixelFormat mFormat,
bool hwGamma)
{
GLenum format = getGLInternalFormat(mFormat, hwGamma);
if (format==0)
{
if (hwGamma)
{
// TODO not supported
return 0;
}
else
{
return GL_RGBA;
}
}
else
{
return format;
}
}
PixelFormat GLESPixelUtil::getClosestOGREFormat(GLenum fmt)
{
switch (fmt)
{
// case GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG:
// return PF_PVR_RGB2;
// case GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:
// return PF_PVR_RGBA2;
// case GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG:
// return PF_PVR_RGB4;
// case GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:
// return PF_PVR_RGBA4;
case GL_LUMINANCE:
return PF_L8;
case GL_ALPHA:
return PF_A8;
case GL_LUMINANCE_ALPHA:
return PF_BYTE_LA;
case GL_RGB:
return PF_X8R8G8B8;
case GL_RGBA:
return PF_A8R8G8B8;
#ifdef GL_BGRA
case GL_BGRA:
#endif
// return PF_X8B8G8R8;
default:
//TODO: not supported
return PF_A8R8G8B8;
};
}
size_t GLESPixelUtil::getMaxMipmaps(size_t width, size_t height, size_t depth,
PixelFormat format)
{
size_t count = 0;
do {
if (width > 1)
{
width = width / 2;
}
if (height > 1)
{
height = height / 2;
}
if (depth > 1)
{
depth = depth / 2;
}
/*
NOT needed, compressed formats will have mipmaps up to 1x1
if(PixelUtil::isValidExtent(width, height, depth, format))
count ++;
else
break;
*/
count++;
} while (!(width == 1 && height == 1 && depth == 1));
return count;
}
size_t GLESPixelUtil::optionalPO2(size_t value)
{
const RenderSystemCapabilities *caps =
Root::getSingleton().getRenderSystem()->getCapabilities();
if (caps->hasCapability(RSC_NON_POWER_OF_2_TEXTURES))
{
return value;
}
else
{
return Bitwise::firstPO2From((uint32)value);
}
}
PixelBox* GLESPixelUtil::convertToGLformat(const PixelBox &data,
GLenum *outputFormat)
{
GLenum glFormat = GLESPixelUtil::getGLOriginFormat(data.format);
if (glFormat != 0)
{
// format already supported
return OGRE_NEW PixelBox(data);
}
PixelBox *converted = 0;
if (data.format == PF_R8G8B8)
{
// Convert BGR -> RGB
converted->format = PF_B8G8R8;
*outputFormat = GL_RGB;
converted = OGRE_NEW PixelBox(data);
uint32 *data = (uint32 *) converted->data;
for (uint i = 0; i < converted->getWidth() * converted->getHeight(); i++)
{
uint32 *color = data;
*color = (*color & 0x000000ff) << 16 |
(*color & 0x0000FF00) |
(*color & 0x00FF0000) >> 16;
data += 1;
}
}
return converted;
}
}
<|endoftext|> |
<commit_before>/* StartingGateMission.cpp -- Implementation of StartingGateMission class
Copyright (C) 2014 Tushar Pankaj
This file is part of San Diego Robotics 101 Robosub.
San Diego Robotics 101 Robosub 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.
San Diego Robotics 101 Robosub 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 San Diego Robotics 101 Robosub. If not, see
<http://www.gnu.org/licenses/>. */
#include <iostream>
#include <string>
#include <vector>
#include <opencv2/opencv.hpp>
#include "Robot.hpp"
#include "Logger.hpp"
#include "Contour.hpp"
#include "Circle.hpp"
#include "Rectangle.hpp"
#include "ContourDetector.hpp"
#include "Mission.hpp"
#include "StartingGateMission.hpp"
StartingGateMission::StartingGateMission(Robot * robot_ptr):Mission(robot_ptr)
{
mission_name = "Starting Gate Mission";
}
void StartingGateMission::run()
{
robot->get_logger()->write("Running mission " + mission_name,
Logger::MESSAGE);
//cv::Mat image = cv::imread("/tmp/starting_gate.png");
cv::Mat image;
while (true) {
image = robot->get_forward_camera()->get_image();
ContourDetector::Params detector_params;
detector_params.filter_by_hue = true;
detector_params.min_hue = 100;
detector_params.max_hue = 150;
detector_params.max_canny = 50;
detector_params.filter_with_blur = false;
ContourDetector detector(detector_params);
std::vector < Contour > contours = detector.detect(image);
if (contours.empty()) {
robot->get_logger()->write("No contours found",
Logger::WARNING);
continue;
}
std::vector < Rectangle > filtered_rectangles =
filter_rectangles(contours);
if (filtered_rectangles.empty()) {
robot->get_logger()->
write("No filtered rectangles found",
Logger::WARNING);
continue;
}
std::vector < cv::Point2f > centroids =
find_centroids(filtered_rectangles);
/*for (uint i = 0; i < centroids.size(); i++)
cv::circle(image, centroids.at(i), 5,
cv::Scalar(0, 0, 0)); */
double angular_displacement = find_angular_displacement(centroids, cv::Point2f((float)image.rows / 2.0, (float)image.cols / 2.0));
robot->get_serial()->get_tx_packet()->set_rot_z(angular_displacement);
robot->get_logger()->write("StartingGateMission angular displacement is " + std::to_string(angular_displacement) + " degrees", Logger::VERBOSE);
}
}
std::vector < Circle > StartingGateMission::contours_to_circles(std::vector <
Contour >
contours)
{
std::vector < Circle > circles;
for (uint i = 0; i < contours.size(); i++)
circles.push_back(Circle(contours.at(i).get_points()));
return circles;
}
std::vector < Rectangle >
StartingGateMission::contours_to_rectangles(std::vector < Contour >
contours)
{
std::vector < Rectangle > rectangles;
for (uint i = 0; i < contours.size(); i++)
rectangles.push_back(Rectangle(contours.at(i).get_points()));
return rectangles;
}
std::vector < Rectangle > StartingGateMission::filter_rectangles(std::vector <
Contour >
detected_contours)
{
std::vector < Circle > detected_enclosing_circles =
contours_to_circles(detected_contours);
std::vector < Rectangle > detected_bounding_rectangles =
contours_to_rectangles(detected_contours);
std::vector < Rectangle > filtered_rectangles;
for (uint i = 0; i < detected_contours.size(); i++) // Filter out circular contours and filter on aspect ratio
{
if (detected_bounding_rectangles.at(i).get_area_ratio() <
detected_enclosing_circles.at(i).get_area_ratio()
&& detected_bounding_rectangles.at(i).get_aspect_ratio() <
0.2)
filtered_rectangles.push_back
(detected_bounding_rectangles.at(i));
}
return filtered_rectangles;
}
std::vector < cv::Point2f > StartingGateMission::find_centroids(std::vector <
Rectangle >
rectangles)
{
cv::Mat data = cv::Mat::zeros(rectangles.size(), 2, CV_32F);
for (uint i = 0; i < rectangles.size(); i++) {
data.at < float >(i, 0) = rectangles.at(i).get_center().x;
data.at < float >(i, 1) = rectangles.at(i).get_center().y;
}
int K = 2;
cv::Mat best_labels;
cv::TermCriteria criteria =
cv::TermCriteria(cv::TermCriteria::COUNT, 10, 1.0);
int attempts = 3;
int flags = cv::KMEANS_PP_CENTERS;
cv::Mat centroids;
cv::kmeans(data, K, best_labels, criteria, attempts, flags, centroids);
std::vector < cv::Point2f > centroids_vector;
for (int i = 0; i < centroids.rows; i++)
centroids_vector.push_back(cv::Point2f
(centroids.at < float >(i, 0),
centroids.at < float >(i, 1)));
return centroids_vector;
}
double StartingGateMission::find_angular_displacement(std::vector <
cv::Point2f > centroids, cv::Point2f image_center)
{
cv::Point2f centroids_average = cv::Point2f(0.0, 0.0);
for (uint i = 0; i < centroids.size(); i++)
centroids_average += centroids.at(i);
centroids_average.x /= centroids.size();
centroids_average.y /= centroids.size();
return robot->get_forward_camera()->pixels_to_angle((image_center - centroids_average).x);
}
<commit_msg>Fixed incorrect rotation direction convention<commit_after>/* StartingGateMission.cpp -- Implementation of StartingGateMission class
Copyright (C) 2014 Tushar Pankaj
This file is part of San Diego Robotics 101 Robosub.
San Diego Robotics 101 Robosub 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.
San Diego Robotics 101 Robosub 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 San Diego Robotics 101 Robosub. If not, see
<http://www.gnu.org/licenses/>. */
#include <iostream>
#include <string>
#include <vector>
#include <opencv2/opencv.hpp>
#include "Robot.hpp"
#include "Logger.hpp"
#include "Contour.hpp"
#include "Circle.hpp"
#include "Rectangle.hpp"
#include "ContourDetector.hpp"
#include "Mission.hpp"
#include "StartingGateMission.hpp"
StartingGateMission::StartingGateMission(Robot * robot_ptr):Mission(robot_ptr)
{
mission_name = "Starting Gate Mission";
}
void StartingGateMission::run()
{
robot->get_logger()->write("Running mission " + mission_name,
Logger::MESSAGE);
//cv::Mat image = cv::imread("/tmp/starting_gate.png");
cv::Mat image;
while (true) {
image = robot->get_forward_camera()->get_image();
ContourDetector::Params detector_params;
detector_params.filter_by_hue = true;
detector_params.min_hue = 100;
detector_params.max_hue = 150;
detector_params.max_canny = 50;
detector_params.filter_with_blur = false;
ContourDetector detector(detector_params);
std::vector < Contour > contours = detector.detect(image);
if (contours.empty()) {
robot->get_logger()->write("No contours found",
Logger::WARNING);
continue;
}
std::vector < Rectangle > filtered_rectangles =
filter_rectangles(contours);
if (filtered_rectangles.empty()) {
robot->get_logger()->
write("No filtered rectangles found",
Logger::WARNING);
continue;
}
std::vector < cv::Point2f > centroids =
find_centroids(filtered_rectangles);
/*for (uint i = 0; i < centroids.size(); i++)
cv::circle(image, centroids.at(i), 5,
cv::Scalar(0, 0, 0)); */
double angular_displacement = find_angular_displacement(centroids, cv::Point2f((float)image.rows / 2.0, (float)image.cols / 2.0));
robot->get_serial()->get_tx_packet()->set_rot_z(angular_displacement);
robot->get_logger()->write("StartingGateMission angular displacement is " + std::to_string(angular_displacement) + " degrees", Logger::VERBOSE);
}
}
std::vector < Circle > StartingGateMission::contours_to_circles(std::vector <
Contour >
contours)
{
std::vector < Circle > circles;
for (uint i = 0; i < contours.size(); i++)
circles.push_back(Circle(contours.at(i).get_points()));
return circles;
}
std::vector < Rectangle >
StartingGateMission::contours_to_rectangles(std::vector < Contour >
contours)
{
std::vector < Rectangle > rectangles;
for (uint i = 0; i < contours.size(); i++)
rectangles.push_back(Rectangle(contours.at(i).get_points()));
return rectangles;
}
std::vector < Rectangle > StartingGateMission::filter_rectangles(std::vector <
Contour >
detected_contours)
{
std::vector < Circle > detected_enclosing_circles =
contours_to_circles(detected_contours);
std::vector < Rectangle > detected_bounding_rectangles =
contours_to_rectangles(detected_contours);
std::vector < Rectangle > filtered_rectangles;
for (uint i = 0; i < detected_contours.size(); i++) // Filter out circular contours and filter on aspect ratio
{
if (detected_bounding_rectangles.at(i).get_area_ratio() <
detected_enclosing_circles.at(i).get_area_ratio()
&& detected_bounding_rectangles.at(i).get_aspect_ratio() <
0.2)
filtered_rectangles.push_back
(detected_bounding_rectangles.at(i));
}
return filtered_rectangles;
}
std::vector < cv::Point2f > StartingGateMission::find_centroids(std::vector <
Rectangle >
rectangles)
{
cv::Mat data = cv::Mat::zeros(rectangles.size(), 2, CV_32F);
for (uint i = 0; i < rectangles.size(); i++) {
data.at < float >(i, 0) = rectangles.at(i).get_center().x;
data.at < float >(i, 1) = rectangles.at(i).get_center().y;
}
int K = 2;
cv::Mat best_labels;
cv::TermCriteria criteria =
cv::TermCriteria(cv::TermCriteria::COUNT, 10, 1.0);
int attempts = 3;
int flags = cv::KMEANS_PP_CENTERS;
cv::Mat centroids;
cv::kmeans(data, K, best_labels, criteria, attempts, flags, centroids);
std::vector < cv::Point2f > centroids_vector;
for (int i = 0; i < centroids.rows; i++)
centroids_vector.push_back(cv::Point2f
(centroids.at < float >(i, 0),
centroids.at < float >(i, 1)));
return centroids_vector;
}
double StartingGateMission::find_angular_displacement(std::vector <
cv::Point2f > centroids, cv::Point2f image_center)
{
cv::Point2f centroids_average = cv::Point2f(0.0, 0.0);
for (uint i = 0; i < centroids.size(); i++)
centroids_average += centroids.at(i);
centroids_average.x /= centroids.size();
centroids_average.y /= centroids.size();
return robot->get_forward_camera()->pixels_to_angle((centroids_average = image_center).x);
}
<|endoftext|> |
<commit_before>#ifndef LIBPORT_UNIT_TEST_HH
# define LIBPORT_UNIT_TEST_HH
// See documentation on:
// https://core.gostai.com/projects/common/wiki/BoostUnit
# define BOOST_TEST_DYN_LINK
# include <boost/test/unit_test.hpp>
namespace libport
{
using boost::unit_test::test_suite;
}
// Fwd for the entry point function the user must implement
libport::test_suite*
init_test_suite();
namespace libport
{
bool _init_test_suite()
{
boost::unit_test::framework::master_test_suite().add(init_test_suite());
return true;
}
}
int
main(int argc, char** argv)
{
return ::boost::unit_test::unit_test_main(
libport::_init_test_suite, argc, argv);
}
#endif
<commit_msg>Do not assume boost is dynamic.<commit_after>#ifndef LIBPORT_UNIT_TEST_HH
# define LIBPORT_UNIT_TEST_HH
// See documentation on:
// https://core.gostai.com/projects/common/wiki/BoostUnit
# ifndef BOOST_STATIC
# define BOOST_TEST_DYN_LINK
# endif
# include <boost/config.hpp>
# include <boost/test/detail/config.hpp>
# include <boost/test/unit_test.hpp>
namespace libport
{
using boost::unit_test::test_suite;
}
// Fwd for the entry point function the user must implement
libport::test_suite*
init_test_suite();
// FIXME: Boost unit-test has a different API depending on whether
// it's static or dynamic (the first defines main, the later doesn't).
// Boost defines BOOST_TEST_DYN_LINK to use the dynamic API, but
// unfortunately it seems it's not available for us to test and switch
// our own API accordingly. For now, we manually define BOOST_STATIC
// on architectures where boost is static. Our m4 macro should define
// it automagically.
# ifndef BOOST_STATIC
namespace libport
{
bool _init_test_suite()
{
boost::unit_test::framework::master_test_suite().add(init_test_suite());
return true;
}
}
int
main(int argc, char** argv)
{
return ::boost::unit_test::unit_test_main(
libport::_init_test_suite, argc, argv);
}
# else
libport::test_suite* init_unit_test_suite(int, char**)
{
return init_test_suite();
}
# endif
#endif
<|endoftext|> |
<commit_before>#include "iteration/group/group_source_iteration.h"
#include <memory>
#include "iteration/updater/tests/source_updater_mock.h"
#include "quadrature/calculators/tests/spherical_harmonic_moments_mock.h"
#include "convergence/tests/final_checker_mock.h"
#include "solver/group/tests/single_group_solver_mock.h"
#include "system/moments/tests/spherical_harmonic_mock.h"
#include "system/solution/tests/mpi_group_angular_solution_mock.h"
#include "system/system.h"
#include "test_helpers/gmock_wrapper.h"
namespace {
using namespace bart;
using ::testing::Return, ::testing::Pointee, ::testing::Ref;
using ::testing::Sequence, ::testing::_;
template <typename DimensionWrapper>
class IterationGroupSourceIterationTest : public ::testing::Test {
public:
static constexpr int dim = DimensionWrapper::value;
using TestGroupIterator = iteration::group::GroupSourceIteration<dim>;
using GroupSolver = solver::group::SingleGroupSolverMock;
using ConvergenceChecker = convergence::FinalCheckerMock<system::moments::MomentVector>;
using MomentCalculator = quadrature::calculators::SphericalHarmonicMomentsMock<dim>;
using GroupSolution = system::solution::MPIGroupAngularSolutionMock;
using SourceUpdater = iteration::updater::SourceUpdaterMock;
using Moments = system::moments::SphericalHarmonicMock;
// Test object
std::unique_ptr<TestGroupIterator> test_iterator_ptr_;
// Mock dependency objects
std::unique_ptr<GroupSolver> single_group_solver_ptr_;
std::unique_ptr<ConvergenceChecker> convergence_checker_ptr_;
std::unique_ptr<MomentCalculator> moment_calculator_ptr_;
std::shared_ptr<GroupSolution> group_solution_ptr_;
std::unique_ptr<SourceUpdater> source_updater_ptr_;
// Supporting objects
system::System test_system;
// Observing pointers
GroupSolver* single_group_obs_ptr_ = nullptr;
ConvergenceChecker* convergence_checker_obs_ptr_ = nullptr;
MomentCalculator* moment_calculator_obs_ptr_ = nullptr;
SourceUpdater* source_updater_obs_ptr_ = nullptr;
Moments* moments_obs_ptr_ = nullptr;
// Test parameters
const int total_groups = 2;
const std::array<int, 2> iterations_by_group{2,3};
void SetUp() override;
};
TYPED_TEST_CASE(IterationGroupSourceIterationTest, bart::testing::AllDimensions);
template <typename DimensionWrapper>
void IterationGroupSourceIterationTest<DimensionWrapper>::SetUp() {
single_group_solver_ptr_ = std::make_unique<GroupSolver>();
single_group_obs_ptr_ = single_group_solver_ptr_.get();
convergence_checker_ptr_ = std::make_unique<ConvergenceChecker>();
convergence_checker_obs_ptr_ = convergence_checker_ptr_.get();
moment_calculator_ptr_ = std::make_unique<MomentCalculator>();
moment_calculator_obs_ptr_ = moment_calculator_ptr_.get();
group_solution_ptr_ = std::make_shared<GroupSolution>();
source_updater_ptr_ = std::make_unique<SourceUpdater>();
source_updater_obs_ptr_ = source_updater_ptr_.get();
test_system.current_moments = std::make_unique<Moments>();
moments_obs_ptr_ = dynamic_cast<Moments*>(test_system.current_moments.get());
test_iterator_ptr_ = std::make_unique<TestGroupIterator>(
std::move(single_group_solver_ptr_),
std::move(convergence_checker_ptr_),
std::move(moment_calculator_ptr_),
group_solution_ptr_,
std::move(source_updater_ptr_)
);
}
TYPED_TEST(IterationGroupSourceIterationTest, Constructor) {
using GroupSolver = solver::group::SingleGroupSolverMock;
using ConvergenceChecker = convergence::FinalCheckerMock<system::moments::MomentVector>;
using MomentCalculator = quadrature::calculators::SphericalHarmonicMomentsMock<this->dim>;
using SourceUpdater = iteration::updater::SourceUpdaterMock;
auto single_group_test_ptr = dynamic_cast<GroupSolver*>(
this->test_iterator_ptr_->group_solver_ptr());
auto convergence_checker_test_ptr = dynamic_cast<ConvergenceChecker*>(
this->test_iterator_ptr_->convergence_checker_ptr());
auto moment_calculator_test_ptr = dynamic_cast<MomentCalculator*>(
this->test_iterator_ptr_->moment_calculator_ptr());
auto source_updater_test_ptr = dynamic_cast<SourceUpdater*>(
this->test_iterator_ptr_->source_updater_ptr());
EXPECT_NE(nullptr, single_group_test_ptr);
EXPECT_NE(nullptr, convergence_checker_test_ptr);
EXPECT_NE(nullptr, moment_calculator_test_ptr);
EXPECT_EQ(2, this->group_solution_ptr_.use_count());
EXPECT_EQ(this->group_solution_ptr_.get(),
this->test_iterator_ptr_->group_solution_ptr().get());
EXPECT_NE(nullptr, source_updater_test_ptr);
}
TYPED_TEST(IterationGroupSourceIterationTest, Iterate) {
// Objects to support testing
/* Moment Vectors. These will be returned by the MomentCalculator, based on
* group and iteration. It is important to ensure that the correct values
* are being checked for convergence. All entries in each vector will be set
* to a unique value, 10*group + iteration. */
std::map<int, std::vector<system::moments::MomentVector>> calculated_moments;
system::moments::MomentVector zero_moment(5);
for (int group = 0; group < this->total_groups; ++group) {
calculated_moments[group] = {};
for (int it = 0; it < this->iterations_by_group[group]; ++it) {
system::moments::MomentVector new_moment(5);
new_moment = (group * 10 + it);
calculated_moments.at(group).push_back(new_moment);
}
}
EXPECT_CALL(*this->moments_obs_ptr_, total_groups())
.WillOnce(Return(this->total_groups));
Sequence s;
for (int group = 0; group < this->total_groups; ++group) {
EXPECT_CALL(*this->single_group_obs_ptr_, SolveGroup(
group,
Ref(this->test_system),
Ref(*this->group_solution_ptr_)))
.Times(this->iterations_by_group[group]);
for (int it = 0; it < this->iterations_by_group[group]; ++it) {
EXPECT_CALL(*this->moment_calculator_obs_ptr_, CalculateMoment(
this->group_solution_ptr_.get(), group, 0, 0))
//_, group, 0, 0))
.InSequence(s)
.WillOnce(Return(calculated_moments.at(group).at(it)));
convergence::Status status;
if ((it + 1) == this->iterations_by_group[group])
status.is_complete = true;
status.iteration_number = it + 1;
if (it == 0) {
EXPECT_CALL(*this->convergence_checker_obs_ptr_, CheckFinalConvergence(
calculated_moments.at(group).at(it),
zero_moment))
.InSequence(s)
.WillOnce(Return(status));
} else {
EXPECT_CALL(*this->convergence_checker_obs_ptr_, CheckFinalConvergence(
calculated_moments.at(group).at(it),
calculated_moments.at(group).at(it - 1)))
.InSequence(s)
.WillOnce(Return(status));
}
}
}
this->test_iterator_ptr_->Iterate(this->test_system);
}
} // namespace<commit_msg>added expectations for UpdateScatteringSource calls<commit_after>#include "iteration/group/group_source_iteration.h"
#include <memory>
#include "iteration/updater/tests/source_updater_mock.h"
#include "quadrature/calculators/tests/spherical_harmonic_moments_mock.h"
#include "convergence/tests/final_checker_mock.h"
#include "solver/group/tests/single_group_solver_mock.h"
#include "system/moments/tests/spherical_harmonic_mock.h"
#include "system/solution/tests/mpi_group_angular_solution_mock.h"
#include "system/system.h"
#include "test_helpers/gmock_wrapper.h"
namespace {
using namespace bart;
using ::testing::Return, ::testing::Pointee, ::testing::Ref;
using ::testing::Sequence, ::testing::_;
template <typename DimensionWrapper>
class IterationGroupSourceIterationTest : public ::testing::Test {
public:
static constexpr int dim = DimensionWrapper::value;
using TestGroupIterator = iteration::group::GroupSourceIteration<dim>;
using GroupSolver = solver::group::SingleGroupSolverMock;
using ConvergenceChecker = convergence::FinalCheckerMock<system::moments::MomentVector>;
using MomentCalculator = quadrature::calculators::SphericalHarmonicMomentsMock<dim>;
using GroupSolution = system::solution::MPIGroupAngularSolutionMock;
using SourceUpdater = iteration::updater::SourceUpdaterMock;
using Moments = system::moments::SphericalHarmonicMock;
// Test object
std::unique_ptr<TestGroupIterator> test_iterator_ptr_;
// Mock dependency objects
std::unique_ptr<GroupSolver> single_group_solver_ptr_;
std::unique_ptr<ConvergenceChecker> convergence_checker_ptr_;
std::unique_ptr<MomentCalculator> moment_calculator_ptr_;
std::shared_ptr<GroupSolution> group_solution_ptr_;
std::unique_ptr<SourceUpdater> source_updater_ptr_;
// Supporting objects
system::System test_system;
// Observing pointers
GroupSolver* single_group_obs_ptr_ = nullptr;
ConvergenceChecker* convergence_checker_obs_ptr_ = nullptr;
MomentCalculator* moment_calculator_obs_ptr_ = nullptr;
SourceUpdater* source_updater_obs_ptr_ = nullptr;
Moments* moments_obs_ptr_ = nullptr;
// Test parameters
const int total_groups = 2;
const int total_angles = 3;
const std::array<int, 2> iterations_by_group{2,3};
void SetUp() override;
};
TYPED_TEST_CASE(IterationGroupSourceIterationTest, bart::testing::AllDimensions);
template <typename DimensionWrapper>
void IterationGroupSourceIterationTest<DimensionWrapper>::SetUp() {
single_group_solver_ptr_ = std::make_unique<GroupSolver>();
single_group_obs_ptr_ = single_group_solver_ptr_.get();
convergence_checker_ptr_ = std::make_unique<ConvergenceChecker>();
convergence_checker_obs_ptr_ = convergence_checker_ptr_.get();
moment_calculator_ptr_ = std::make_unique<MomentCalculator>();
moment_calculator_obs_ptr_ = moment_calculator_ptr_.get();
group_solution_ptr_ = std::make_shared<GroupSolution>();
source_updater_ptr_ = std::make_unique<SourceUpdater>();
source_updater_obs_ptr_ = source_updater_ptr_.get();
test_system.current_moments = std::make_unique<Moments>();
moments_obs_ptr_ = dynamic_cast<Moments*>(test_system.current_moments.get());
test_iterator_ptr_ = std::make_unique<TestGroupIterator>(
std::move(single_group_solver_ptr_),
std::move(convergence_checker_ptr_),
std::move(moment_calculator_ptr_),
group_solution_ptr_,
std::move(source_updater_ptr_)
);
}
TYPED_TEST(IterationGroupSourceIterationTest, Constructor) {
using GroupSolver = solver::group::SingleGroupSolverMock;
using ConvergenceChecker = convergence::FinalCheckerMock<system::moments::MomentVector>;
using MomentCalculator = quadrature::calculators::SphericalHarmonicMomentsMock<this->dim>;
using SourceUpdater = iteration::updater::SourceUpdaterMock;
auto single_group_test_ptr = dynamic_cast<GroupSolver*>(
this->test_iterator_ptr_->group_solver_ptr());
auto convergence_checker_test_ptr = dynamic_cast<ConvergenceChecker*>(
this->test_iterator_ptr_->convergence_checker_ptr());
auto moment_calculator_test_ptr = dynamic_cast<MomentCalculator*>(
this->test_iterator_ptr_->moment_calculator_ptr());
auto source_updater_test_ptr = dynamic_cast<SourceUpdater*>(
this->test_iterator_ptr_->source_updater_ptr());
EXPECT_NE(nullptr, single_group_test_ptr);
EXPECT_NE(nullptr, convergence_checker_test_ptr);
EXPECT_NE(nullptr, moment_calculator_test_ptr);
EXPECT_EQ(2, this->group_solution_ptr_.use_count());
EXPECT_EQ(this->group_solution_ptr_.get(),
this->test_iterator_ptr_->group_solution_ptr().get());
EXPECT_NE(nullptr, source_updater_test_ptr);
}
TYPED_TEST(IterationGroupSourceIterationTest, Iterate) {
// Objects to support testing
/* Moment Vectors. These will be returned by the MomentCalculator, based on
* group and iteration. It is important to ensure that the correct values
* are being checked for convergence. All entries in each vector will be set
* to a unique value, 10*group + iteration. */
std::map<int, std::vector<system::moments::MomentVector>> calculated_moments;
system::moments::MomentVector zero_moment(5);
for (int group = 0; group < this->total_groups; ++group) {
calculated_moments[group] = {};
for (int it = 0; it < this->iterations_by_group[group]; ++it) {
system::moments::MomentVector new_moment(5);
new_moment = (group * 10 + it);
calculated_moments.at(group).push_back(new_moment);
}
}
EXPECT_CALL(*this->moments_obs_ptr_, total_groups())
.WillOnce(Return(this->total_groups));
EXPECT_CALL(*this->group_solution_ptr_, total_angles())
.WillOnce(Return(this->total_angles));
Sequence s;
for (int group = 0; group < this->total_groups; ++group) {
EXPECT_CALL(*this->single_group_obs_ptr_, SolveGroup(
group,
Ref(this->test_system),
Ref(*this->group_solution_ptr_)))
.Times(this->iterations_by_group[group]);
for (int it = 0; it < this->iterations_by_group[group]; ++it) {
EXPECT_CALL(*this->moment_calculator_obs_ptr_, CalculateMoment(
this->group_solution_ptr_.get(), group, 0, 0))
//_, group, 0, 0))
.InSequence(s)
.WillOnce(Return(calculated_moments.at(group).at(it)));
convergence::Status status;
if ((it + 1) == this->iterations_by_group[group])
status.is_complete = true;
status.iteration_number = it + 1;
if (it == 0) {
EXPECT_CALL(*this->convergence_checker_obs_ptr_, CheckFinalConvergence(
calculated_moments.at(group).at(it),
zero_moment))
.InSequence(s)
.WillOnce(Return(status));
} else {
EXPECT_CALL(*this->convergence_checker_obs_ptr_, CheckFinalConvergence(
calculated_moments.at(group).at(it),
calculated_moments.at(group).at(it - 1)))
.InSequence(s)
.WillOnce(Return(status));
}
for (int angle = 0; angle < this->total_angles; ++angle) {
EXPECT_CALL(*this->source_updater_obs_ptr_, UpdateScatteringSource(
Ref(this->test_system), group, angle));
}
}
}
this->test_iterator_ptr_->Iterate(this->test_system);
}
} // namespace<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <fstream>
#include "lib/store.hpp"
#include "lib/graph.hpp"
void store::save(const Graph& g, const std::string filename) {
std::ofstream fs(filename);
for (auto& v : g.list) {
fs << *v.get() << std::endl;
}
}
Graph store::load(const std::string filename) {
Graph g;
std::ifstream fs(filename);
// fs >>
return std::move(g);
}
<commit_msg>Add some TODOs<commit_after>#include <iostream>
#include <string>
#include <fstream>
#include "lib/store.hpp"
#include "lib/graph.hpp"
void store::save(const Graph& g, const std::string filename) {
std::ofstream fs(filename);
for (auto& v : g.list) {
fs << *v.get() << std::endl;
}
}
Graph store::load(const std::string filename) {
Graph g;
std::ifstream fs(filename);
// fs >>
// TODO - figure out what to do with this
return std::move(g);
}
<|endoftext|> |
<commit_before>// Steer TRD QA train for Reconstruction (Clusterizer, Tracking and PID).
//
// Usage:
// run.C(optList, files, nev, first, runNo, ocdb_uri, grp_uri)
//
// optList : "ALL" [default] or one/more of the following:
// "EFF" : TRD Tracking Efficiency
// "EFFC" : TRD Tracking Efficiency Combined (barrel + stand alone) - only in case of simulations
// "MULT" : TRD single track selection
// "RES" : TRD tracking Resolution
// "CLRES": clusters Resolution
// "CAL" : TRD calibration
// "ALGN" : TRD alignment
// "PID" : TRD PID - pion efficiency
// "PIDR" : TRD PID - reference data
// "V0" : monitor V0 performance for use in TRD PID calibration
// "DET" : Basic TRD Detector checks
// ****** SPECIAL OPTIONS **********
// "NOFR" : Data set does not have AliESDfriends.root
// "NOMC" : Data set does not have Monte Carlo Informations (default have MC),
//
// files : the list of ESD files to be processed [default AliESds.root from cwd]
// nev : number of events to be processed [default all]
// first : first event to process [default 0]
// runNo : run number [default 0]
// ocdb_uri : OCDB location [default local, $ALICE_ROOT]. In case of AliEn the syntax should be of the form
// alien://folder=/alice/data/2010/OCDB?user=username?cacheF=yourDirectory?cacheS=yourSize
// grp_uri : GRP/GRP/Data location [default cwd]. In case of AliEn the syntax should be of the form
// alien://folder=/alice/data/2010/OCDB?user=username?cacheF=yourDirectory?cacheS=yourSize
// In compiled mode :
// Don't forget to load first the libraries
// gSystem->Load("libMemStat.so")
// gSystem->Load("libMemStatGui.so")
// gSystem->Load("libANALYSIS.so")
// gSystem->Load("libANALYSISalice.so")
// gSystem->Load("libTENDER.so");
// gSystem->Load("libPWG1.so");
// gSystem->Load("libNetx.so") ;
// gSystem->Load("libRAliEn.so");
//
// Authors:
// Alex Bercuci ([email protected])
// Markus Fasel ([email protected])
#if ! defined (__CINT__) || defined (__MAKECINT__)
//#ifndef __CINT__
#include <Riostream.h>
#include "TStopwatch.h"
#include "TMemStat.h"
#include "TMemStatViewerGUI.h"
#include "TROOT.h"
#include "TClass.h"
#include "TSystem.h"
#include "TError.h"
#include "TChain.h"
#include "TGrid.h"
#include "TAlienCollection.h"
#include "TGridCollection.h"
#include "TGridResult.h"
#include "TGeoGlobalMagField.h"
#include "AliMagF.h"
#include "AliTracker.h"
#include "AliLog.h"
#include "AliCDBManager.h"
#include "AliGRPManager.h"
#include "AliGeomManager.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"
#include "AliMCEventHandler.h"
#include "AliESDInputHandler.h"
#include "TRD/AliTRDtrackerV1.h"
#include "TRD/AliTRDcalibDB.h"
#include "PWG1/TRD/macros/AliTRDperformanceTrain.h"
#include "PWG1/TRD/macros/AddTRDcheckESD.C"
#include "PWG1/TRD/macros/AddTRDinfoGen.C"
#include "PWG1/TRD/macros/AddTRDcheckDET.C"
#include "PWG1/TRD/macros/AddTRDefficiency.C"
#include "PWG1/TRD/macros/AddTRDresolution.C"
#include "PWG1/TRD/macros/AddTRDcheckPID.C"
#endif
#include "macros/AliTRDperformanceTrain.h"
Bool_t MEM = kFALSE;
TChain* MakeChainLST(const char* filename = 0x0);
TChain* MakeChainXML(const char* filename = 0x0);
void run(Char_t *optList="ALL", const Char_t *files=0x0, Long64_t nev=1234567890, Long64_t first = 0, Int_t runNo=0, const Char_t *ocdb_uri="local://$ALICE_ROOT/OCDB", const Char_t *grp_uri=Form("local://%s", gSystem->pwd()))
{
TMemStat *mem = 0x0;
if(MEM){
if(gSystem->Load("libMemStat.so")<0) return;
if(gSystem->Load("libMemStatGui.so")<0) return;
mem = new TMemStat("new, gnubuildin");
mem->AddStamp("Start");
}
TStopwatch timer;
timer.Start();
// VERY GENERAL SETTINGS
//AliLog::SetGlobalLogLevel(AliLog::kError);
gStyle->SetOptStat(0);
if(gSystem->Load("libANALYSIS.so")<0) return;
if(gSystem->Load("libANALYSISalice.so")<0) return;
if(gSystem->Load("libTENDER.so")<0) return;
if(gSystem->Load("libPWG1.so")<0) return;
Bool_t fHasMCdata = HasReadMCData(optList);
Bool_t fHasFriends = HasReadFriendData(optList);
// INITIALIZATION OF RUNNING ENVIRONMENT
// initialize OCDB manager
// AliCDBManager *cdbManager = AliCDBManager::Instance();
// cdbManager->SetDefaultStorage(ocdb_uri);
// if(!cdbManager->IsDefaultStorageSet()){
// Error("run.C", "Error setting OCDB.");
// return;
// }
// cdbManager->SetRun(runNo);
// cdbManager->SetSpecificStorage("GRP/GRP/Data", grp_uri);
// cdbManager->SetCacheFlag(kFALSE);
// cdbManager->Print();
// // initialize magnetic field from the GRP manager.
// AliGRPManager grpMan;
// if(!grpMan.ReadGRPEntry()) return;
// if(!grpMan.SetMagField()) return;
// //AliRunInfo *runInfo = grpMan.GetRunInfo();
// AliGeomManager::LoadGeometry();
// DEFINE DATA CHAIN
TChain *chain = 0x0;
if(!files) chain = MakeChainLST();
else{
TString fn(files);
if(fn.EndsWith("xml")) chain = MakeChainXML(files);
else chain = MakeChainLST(files);
}
if(!chain) return;
chain->Lookup();
chain->GetListOfFiles()->Print();
Int_t nfound=(Int_t)chain->GetEntries();
printf("\tENTRIES FOUND [%d] REQUESTED [%d]\n", nfound, nev>nfound?nfound:nev);
// BUILD ANALYSIS MANAGER
AliAnalysisManager *mgr = new AliAnalysisManager("TRD Reconstruction Performance & Calibration");
AliESDInputHandlerRP *esdH(NULL);
mgr->SetInputEventHandler(esdH = new AliESDInputHandlerRP);
esdH->SetReadFriends(kTRUE);
esdH->SetActiveBranches("ESDfriend");
AliMCEventHandler *mcH(NULL);
if(fHasMCdata) mgr->SetMCtruthEventHandler(mcH = new AliMCEventHandler());
//mgr->SetDebugLevel(10);
mgr->SetSkipTerminate(kTRUE);
gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/AddTrainPerformanceTRD.C");
if(!AddTrainPerformanceTRD(optList)) {
Error("run.C", "Error loading TRD train.");
return;
}
if (!mgr->InitAnalysis()) return;
// verbosity
printf("\tRUNNING TRAIN FOR TASKS:\n");
TObjArray *taskList=mgr->GetTasks();
for(Int_t itask=0; itask<taskList->GetEntries(); itask++){
AliAnalysisTask *task=(AliAnalysisTask*)taskList->At(itask);
printf(" %s [%s]\n", task->GetName(), task->GetTitle());
}
//mgr->PrintStatus();
mgr->StartAnalysis("local", chain, nev, first);
timer.Stop();
timer.Print();
// verbosity
printf("\tCLEANING TASK LIST:\n");
mgr->GetTasks()->Delete();
if(mcH) delete mcH;
delete esdH;
delete chain;
if(MEM) delete mem;
if(MEM) TMemStatViewerGUI::ShowGUI();
}
//____________________________________________
TChain* MakeChainLST(const char* filename)
{
// Create the chain
TChain* chain = new TChain("esdTree");
if(!filename){
chain->Add(Form("%s/AliESDs.root", gSystem->pwd()));
return chain;
}
// read ESD files from the input list.
ifstream in;
in.open(filename);
TString esdfile;
while(in.good()) {
in >> esdfile;
if (!esdfile.Contains("root")) continue; // protection
chain->Add(esdfile.Data());
}
in.close();
return chain;
}
//____________________________________________
TChain* MakeChainXML(const char* xmlfile)
{
if (!TFile::Open(xmlfile)) {
Error("MakeChainXML", Form("No file %s was found", xmlfile));
return 0x0;
}
if(gSystem->Load("libNetx.so")<0) return 0x0;
if(gSystem->Load("libRAliEn.so")<0) return 0x0;
TGrid::Connect("alien://") ;
TGridCollection *collection = (TGridCollection*) TAlienCollection::Open(xmlfile);
if (!collection) {
Error("MakeChainXML", Form("No collection found in %s", xmlfile)) ;
return 0x0;
}
//collection->CheckIfOnline();
TGridResult* result = collection->GetGridResult("",0 ,0);
if(!result->GetEntries()){
Error("MakeChainXML", Form("No entries found in %s", xmlfile)) ;
return 0x0;
}
// Makes the ESD chain
TChain* chain = new TChain("esdTree");
for (Int_t idx = 0; idx < result->GetEntries(); idx++) {
chain->Add(result->GetKey(idx, "turl"));
}
return chain;
}
<commit_msg>simplified parameter list<commit_after>// Steer TRD QA train for Reconstruction (Clusterizer, Tracking and PID).
//
// Usage:
// run.C(optList, files, nev, first, runNo, ocdb_uri, grp_uri)
//
// optList : "ALL" [default] or one/more of the following:
// "EFF" : TRD Tracking Efficiency
// "EFFC" : TRD Tracking Efficiency Combined (barrel + stand alone) - only in case of simulations
// "MULT" : TRD single track selection
// "RES" : TRD tracking Resolution
// "CLRES": clusters Resolution
// "CAL" : TRD calibration
// "ALGN" : TRD alignment
// "PID" : TRD PID - pion efficiency
// "PIDR" : TRD PID - reference data
// "V0" : monitor V0 performance for use in TRD PID calibration
// "DET" : Basic TRD Detector checks
// ****** SPECIAL OPTIONS **********
// "NOFR" : Data set does not have AliESDfriends.root
// "NOMC" : Data set does not have Monte Carlo Informations (default have MC),
//
// files : the list of ESD files to be processed [default AliESds.root from cwd]
// nev : number of events to be processed [default all]
// first : first event to process [default 0]
// runNo : run number [default 0]
// ocdb_uri : OCDB location [default local, $ALICE_ROOT]. In case of AliEn the syntax should be of the form
// alien://folder=/alice/data/2010/OCDB?user=username?cacheF=yourDirectory?cacheS=yourSize
// grp_uri : GRP/GRP/Data location [default cwd]. In case of AliEn the syntax should be of the form
// alien://folder=/alice/data/2010/OCDB?user=username?cacheF=yourDirectory?cacheS=yourSize
// In compiled mode :
// Don't forget to load first the libraries
// gSystem->Load("libMemStat.so")
// gSystem->Load("libMemStatGui.so")
// gSystem->Load("libANALYSIS.so")
// gSystem->Load("libANALYSISalice.so")
// gSystem->Load("libTENDER.so");
// gSystem->Load("libPWG1.so");
// gSystem->Load("libNetx.so") ;
// gSystem->Load("libRAliEn.so");
//
// Authors:
// Alex Bercuci ([email protected])
// Markus Fasel ([email protected])
#if ! defined (__CINT__) || defined (__MAKECINT__)
//#ifndef __CINT__
#include <Riostream.h>
#include "TStopwatch.h"
#include "TMemStat.h"
#include "TMemStatViewerGUI.h"
#include "TROOT.h"
#include "TClass.h"
#include "TSystem.h"
#include "TError.h"
#include "TChain.h"
#include "TGrid.h"
#include "TAlienCollection.h"
#include "TGridCollection.h"
#include "TGridResult.h"
#include "TGeoGlobalMagField.h"
#include "AliMagF.h"
#include "AliTracker.h"
#include "AliLog.h"
#include "AliCDBManager.h"
#include "AliGRPManager.h"
#include "AliGeomManager.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"
#include "AliMCEventHandler.h"
#include "AliESDInputHandler.h"
#include "TRD/AliTRDtrackerV1.h"
#include "TRD/AliTRDcalibDB.h"
#include "PWG1/TRD/macros/AliTRDperformanceTrain.h"
#include "PWG1/TRD/macros/AddTRDcheckESD.C"
#include "PWG1/TRD/macros/AddTRDinfoGen.C"
#include "PWG1/TRD/macros/AddTRDcheckDET.C"
#include "PWG1/TRD/macros/AddTRDefficiency.C"
#include "PWG1/TRD/macros/AddTRDresolution.C"
#include "PWG1/TRD/macros/AddTRDcheckPID.C"
#endif
#include "macros/AliTRDperformanceTrain.h"
Bool_t MEM = kFALSE;
TChain* MakeChainLST(const char* filename = 0x0);
TChain* MakeChainXML(const char* filename = 0x0);
void run(Char_t *optList="ALL", const Char_t *files=0x0, Long64_t nev=1234567890, Long64_t first = 0)
{
TMemStat *mem = 0x0;
if(MEM){
if(gSystem->Load("libMemStat.so")<0) return;
if(gSystem->Load("libMemStatGui.so")<0) return;
mem = new TMemStat("new, gnubuildin");
mem->AddStamp("Start");
}
TStopwatch timer;
timer.Start();
// VERY GENERAL SETTINGS
//AliLog::SetGlobalLogLevel(AliLog::kError);
gStyle->SetOptStat(0);
if(gSystem->Load("libANALYSIS.so")<0) return;
if(gSystem->Load("libANALYSISalice.so")<0) return;
if(gSystem->Load("libTENDER.so")<0) return;
if(gSystem->Load("libPWG1.so")<0) return;
Bool_t fHasMCdata = HasReadMCData(optList);
Bool_t fHasFriends = HasReadFriendData(optList);
// DEFINE DATA CHAIN
TChain *chain = 0x0;
if(!files) chain = MakeChainLST();
else{
TString fn(files);
if(fn.EndsWith("xml")) chain = MakeChainXML(files);
else chain = MakeChainLST(files);
}
if(!chain) return;
chain->Lookup();
chain->GetListOfFiles()->Print();
Int_t nfound=(Int_t)chain->GetEntries();
printf("\tENTRIES FOUND [%d] REQUESTED [%d]\n", nfound, nev>nfound?nfound:nev);
// BUILD ANALYSIS MANAGER
AliAnalysisManager *mgr = new AliAnalysisManager("TRD Reconstruction Performance & Calibration");
AliESDInputHandlerRP *esdH(NULL);
mgr->SetInputEventHandler(esdH = new AliESDInputHandlerRP);
esdH->SetReadFriends(kTRUE);
esdH->SetActiveBranches("ESDfriend");
AliMCEventHandler *mcH(NULL);
if(fHasMCdata) mgr->SetMCtruthEventHandler(mcH = new AliMCEventHandler());
//mgr->SetDebugLevel(10);
mgr->SetSkipTerminate(kTRUE);
gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/AddTrainPerformanceTRD.C");
if(!AddTrainPerformanceTRD(optList)) {
Error("run.C", "Error loading TRD train.");
return;
}
if (!mgr->InitAnalysis()) return;
// verbosity
printf("\tRUNNING TRAIN FOR TASKS:\n");
TObjArray *taskList=mgr->GetTasks();
for(Int_t itask=0; itask<taskList->GetEntries(); itask++){
AliAnalysisTask *task=(AliAnalysisTask*)taskList->At(itask);
printf(" %s [%s]\n", task->GetName(), task->GetTitle());
}
//mgr->PrintStatus();
mgr->StartAnalysis("local", chain, nev, first);
timer.Stop();
timer.Print();
// verbosity
printf("\tCLEANING TASK LIST:\n");
mgr->GetTasks()->Delete();
if(mcH) delete mcH;
delete esdH;
delete chain;
if(MEM) delete mem;
if(MEM) TMemStatViewerGUI::ShowGUI();
}
//____________________________________________
TChain* MakeChainLST(const char* filename)
{
// Create the chain
TChain* chain = new TChain("esdTree");
if(!filename){
chain->Add(Form("%s/AliESDs.root", gSystem->pwd()));
return chain;
}
// read ESD files from the input list.
ifstream in;
in.open(filename);
TString esdfile;
while(in.good()) {
in >> esdfile;
if (!esdfile.Contains("root")) continue; // protection
chain->Add(esdfile.Data());
}
in.close();
return chain;
}
//____________________________________________
TChain* MakeChainXML(const char* xmlfile)
{
if (!TFile::Open(xmlfile)) {
Error("MakeChainXML", Form("No file %s was found", xmlfile));
return 0x0;
}
if(gSystem->Load("libNetx.so")<0) return 0x0;
if(gSystem->Load("libRAliEn.so")<0) return 0x0;
TGrid::Connect("alien://") ;
TGridCollection *collection = (TGridCollection*) TAlienCollection::Open(xmlfile);
if (!collection) {
Error("MakeChainXML", Form("No collection found in %s", xmlfile)) ;
return 0x0;
}
//collection->CheckIfOnline();
TGridResult* result = collection->GetGridResult("",0 ,0);
if(!result->GetEntries()){
Error("MakeChainXML", Form("No entries found in %s", xmlfile)) ;
return 0x0;
}
// Makes the ESD chain
TChain* chain = new TChain("esdTree");
for (Int_t idx = 0; idx < result->GetEntries(); idx++) {
chain->Add(result->GetKey(idx, "turl"));
}
return chain;
}
<|endoftext|> |
<commit_before>#ifndef LIB_MART_COMMON_GUARD_NW_UNIX_H
#define LIB_MART_COMMON_GUARD_NW_UNIX_H
/**
* unix.h (mart-netlib)
*
* Copyright (C) 2019: Michael Balszun <[email protected]>
*
* This software may be modified and distributed under the terms
* of the MIT license. See either the LICENSE file in the library's root
* directory or http://opensource.org/licenses/MIT for details.
*
* @author: Michael Balszun <[email protected]>
* @brief: This file provides a simple unix doamin socket implementation
*
*/
#include "port_layer.hpp"
#include <im_str/im_str.hpp>
#include <mart-common/utils.h>
#include <filesystem>
#include <string_view>
#include "detail/dgram_socket_base.hpp"
namespace mart::nw {
// classes related to the unix sockets protocol in general
namespace un {
class endpoint {
public:
using abi_endpoint_type = mart::nw::socks::port_layer::SockaddrUn;
constexpr endpoint() noexcept = default;
endpoint( mba::im_zstr path ) noexcept
: _addr( std::move( path ) )
{
}
explicit endpoint( std::string_view path ) noexcept
: _addr( path )
{
}
explicit endpoint( const std::filesystem::path& path ) noexcept
// TODO use "native()" on platforms that use u8 encoding natively
: _addr( std::string_view( path.u8string() ) )
{
}
explicit endpoint( const abi_endpoint_type& path ) noexcept
: endpoint( std::string_view( path.path() ) )
{
}
mba::im_zstr asString() const noexcept { return _addr; }
mba::im_zstr toStringEx() const noexcept { return _addr; }
abi_endpoint_type toSockAddrUn() const noexcept { return abi_endpoint_type( _addr.data(), _addr.size() ); }
// for use in generic contexts
abi_endpoint_type toSockAddr() const noexcept { return toSockAddrUn(); }
friend bool operator==( const endpoint& l, const endpoint& r ) noexcept { return l._addr == r._addr; }
friend bool operator!=( const endpoint& l, const endpoint& r ) noexcept { return l._addr != r._addr; }
friend bool operator<( const endpoint& l, const endpoint& r ) noexcept { return l._addr < r._addr; }
private:
mba::im_zstr _addr{};
};
} // namespace un
} // namespace mart::nw
namespace mart::nw::socks::detail {
extern template class DgramSocket<mart::nw::un::endpoint>;
}
namespace mart::nw {
// classes related to the unix sockets protocol in general
namespace un {
using Socket = mart::nw::socks::detail::DgramSocket<endpoint>;
}
} // namespace mart::nw
#endif<commit_msg>[netlib] Fix c++20 compatibility issue with paths<commit_after>#ifndef LIB_MART_COMMON_GUARD_NW_UNIX_H
#define LIB_MART_COMMON_GUARD_NW_UNIX_H
/**
* unix.h (mart-netlib)
*
* Copyright (C) 2019: Michael Balszun <[email protected]>
*
* This software may be modified and distributed under the terms
* of the MIT license. See either the LICENSE file in the library's root
* directory or http://opensource.org/licenses/MIT for details.
*
* @author: Michael Balszun <[email protected]>
* @brief: This file provides a simple unix doamin socket implementation
*
*/
#include "port_layer.hpp"
#include <im_str/im_str.hpp>
#include <mart-common/utils.h>
#include <filesystem>
#include <string_view>
#include "detail/dgram_socket_base.hpp"
namespace mart::nw {
// classes related to the unix sockets protocol in general
namespace un {
class endpoint {
public:
using abi_endpoint_type = mart::nw::socks::port_layer::SockaddrUn;
constexpr endpoint() noexcept = default;
endpoint( mba::im_zstr path ) noexcept
: _addr( std::move( path ) )
{
}
explicit endpoint( std::string_view path ) noexcept
: _addr( path )
{
}
explicit endpoint( const std::filesystem::path& path ) noexcept
// TODO use "native()" on platforms that use u8 encoding natively
: _addr( std::string_view( path.string() ) )
{
}
explicit endpoint( const abi_endpoint_type& path ) noexcept
: endpoint( std::string_view( path.path() ) )
{
}
mba::im_zstr asString() const noexcept { return _addr; }
mba::im_zstr toStringEx() const noexcept { return _addr; }
abi_endpoint_type toSockAddrUn() const noexcept { return abi_endpoint_type( _addr.data(), _addr.size() ); }
// for use in generic contexts
abi_endpoint_type toSockAddr() const noexcept { return toSockAddrUn(); }
friend bool operator==( const endpoint& l, const endpoint& r ) noexcept { return l._addr == r._addr; }
friend bool operator!=( const endpoint& l, const endpoint& r ) noexcept { return l._addr != r._addr; }
friend bool operator<( const endpoint& l, const endpoint& r ) noexcept { return l._addr < r._addr; }
private:
mba::im_zstr _addr{};
};
} // namespace un
} // namespace mart::nw
namespace mart::nw::socks::detail {
extern template class DgramSocket<mart::nw::un::endpoint>;
}
namespace mart::nw {
// classes related to the unix sockets protocol in general
namespace un {
using Socket = mart::nw::socks::detail::DgramSocket<endpoint>;
}
} // namespace mart::nw
#endif<|endoftext|> |
<commit_before>/*
* This file is part of otf2xx (https://github.com/tud-zih-energy/otf2xx)
* otf2xx - A wrapper for the Open Trace Format 2 library
*
* Copyright (c) 2013-2016, Technische Universität Dresden, Germany
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef INCLUDE_OTF2XX_EXCEPTION_HPP
#define INCLUDE_OTF2XX_EXCEPTION_HPP
#include <otf2/OTF2_ErrorCodes.h>
#include <sstream>
#include <stdexcept>
#include <string>
namespace otf2
{
struct exception : std::runtime_error
{
explicit exception(const std::string& arg) : std::runtime_error(arg)
{
}
};
namespace detail
{
template <typename Arg, typename... Args>
class make_exception
{
public:
void operator()(std::stringstream& msg, Arg arg, Args... args)
{
msg << arg;
make_exception<Args...>()(msg, args...);
}
};
template <typename Arg>
class make_exception<Arg>
{
public:
void operator()(std::stringstream& msg, Arg arg)
{
msg << arg;
}
};
}
template <typename... Args>
inline void make_exception(Args... args)
{
std::stringstream msg;
detail::make_exception<Args...>()(msg, args...);
throw exception(msg.str());
}
template <typename... Args>
void inline check(OTF2_ErrorCode code, Args... args)
{
if (code != OTF2_SUCCESS)
{
make_exception(args...);
}
}
} // namespace otf2
#endif // INCLUDE_OTF2XX_EXCEPTION_HPP
<commit_msg>manually cherry-picking from @flamefire 's PR<commit_after>/*
* This file is part of otf2xx (https://github.com/tud-zih-energy/otf2xx)
* otf2xx - A wrapper for the Open Trace Format 2 library
*
* Copyright (c) 2013-2016, Technische Universität Dresden, Germany
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef INCLUDE_OTF2XX_EXCEPTION_HPP
#define INCLUDE_OTF2XX_EXCEPTION_HPP
#include <otf2/OTF2_ErrorCodes.h>
#include <sstream>
#include <stdexcept>
#include <string>
namespace otf2
{
struct exception : std::runtime_error
{
explicit exception(const std::string& arg) : std::runtime_error(arg)
{
}
};
namespace detail
{
template <typename Arg, typename... Args>
class make_exception
{
public:
void operator()(std::stringstream& msg, Arg&& arg, Args&&... args)
{
msg << std::forward<Arg>(arg);
make_exception<Args...>()(msg, std::forward<Args>(args)...);
}
};
template <typename Arg>
class make_exception<Arg>
{
public:
void operator()(std::stringstream& msg, Arg&& arg)
{
msg << std::forward<Arg>(arg);
}
};
} // namespace detail
template <typename... Args>
[[noreturn]] inline void make_exception(Args&&... args)
{
std::stringstream msg;
detail::make_exception<Args...>()(msg, std::forward<Args>(args)...);
throw exception(msg.str());
}
template <typename... Args>
inline void make_otf2_exception(OTF2_ErrorCode code, Args&&... args)
{
make_exception(OTF2_Error_GetName(code), ": ", OTF2_Error_GetDescription(code), "\n",
std::forward<Args>(args)...);
}
template <typename... Args>
void inline check(OTF2_ErrorCode code, Args&&... args)
{
if (code != OTF2_SUCCESS)
{
make_otf2_exception(code, std::forward<Args>(args)...);
}
}
} // namespace otf2
#endif // INCLUDE_OTF2XX_EXCEPTION_HPP
<|endoftext|> |
<commit_before>///
/// @file Wheel.hpp
/// @brief Classes and structs related to wheel factorization.
///
/// Copyright (C) 2017 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef WHEEL_HPP
#define WHEEL_HPP
#include "config.hpp"
#include "pmath.hpp"
#include "primesieve_error.hpp"
#include <stdint.h>
#include <cassert>
#include <string>
namespace primesieve {
/// The WheelInit data structure is used to calculate the
/// first multiple >= start of each sieving prime
///
struct WheelInit
{
uint8_t nextMultipleFactor;
uint8_t wheelIndex;
};
extern const WheelInit wheel30Init[30];
extern const WheelInit wheel210Init[210];
/// The WheelElement data structure is used to skip multiples
/// of small primes using wheel factorization
///
struct WheelElement
{
/// Bitmask used to unset the bit corresponding to the current
/// multiple of a SievingPrime object
uint8_t unsetBit;
/// Factor used to calculate the next multiple of a sieving prime
/// that is not divisible by any of the wheel factors
uint8_t nextMultipleFactor;
/// Overflow needed to correct the next multiple index
/// (due to sievingPrime = prime / 30)
uint8_t correct;
/// Used to calculate the next wheel index:
/// wheelIndex += next;
int8_t next;
};
extern const WheelElement wheel30[8*8];
extern const WheelElement wheel210[48*8];
/// Sieving primes are used to cross-off multiples (of itself).
/// Each SievingPrime object contains a sieving prime and the
/// position of its next multiple within the SieveOfEratosthenes
/// array (i.e. multipleIndex) and a wheelIndex.
///
class SievingPrime
{
public:
enum
{
MAX_MULTIPLEINDEX = (1 << 23) - 1,
MAX_WHEELINDEX = (1 << (32 - 23)) - 1
};
SievingPrime() { }
SievingPrime(uint_t sievingPrime,
uint_t multipleIndex,
uint_t wheelIndex)
{
set(multipleIndex, wheelIndex);
sievingPrime_ = (uint32_t) sievingPrime;
}
uint_t getSievingPrime() const
{
return sievingPrime_;
}
uint_t getMultipleIndex() const
{
return indexes_ & MAX_MULTIPLEINDEX;
}
uint_t getWheelIndex() const
{
return indexes_ >> 23;
}
void setMultipleIndex(uint_t multipleIndex)
{
assert(multipleIndex <= MAX_MULTIPLEINDEX);
indexes_ = (uint32_t)(indexes_ | multipleIndex);
}
void setWheelIndex(uint_t wheelIndex)
{
assert(wheelIndex <= MAX_WHEELINDEX);
indexes_ = (uint32_t)(wheelIndex << 23);
}
void set(uint_t multipleIndex,
uint_t wheelIndex)
{
assert(multipleIndex <= MAX_MULTIPLEINDEX);
assert(wheelIndex <= MAX_WHEELINDEX);
indexes_ = (uint32_t)(multipleIndex | (wheelIndex << 23));
}
void set(uint_t sievingPrime,
uint_t multipleIndex,
uint_t wheelIndex)
{
set(multipleIndex, wheelIndex);
sievingPrime_ = (uint32_t) sievingPrime;
}
private:
/// multipleIndex = 23 least significant bits of indexes_
/// wheelIndex = 9 most significant bits of indexes_
uint32_t indexes_;
uint32_t sievingPrime_;
};
/// The Bucket data structure is used to store sieving primes.
/// @see http://www.ieeta.pt/~tos/software/prime_sieve.html
/// The Bucket class is designed as a singly linked list, once there
/// is no more space in the current Bucket a new Bucket node is
/// allocated.
///
class Bucket
{
public:
Bucket() { reset(); }
SievingPrime* begin() { return &sievingPrimes_[0]; }
SievingPrime* last() { return &sievingPrimes_[config::BUCKETSIZE - 1]; }
SievingPrime* end() { return prime_; }
Bucket* next() { return next_; }
bool hasNext() const { return next_ != nullptr; }
bool empty() { return begin() == end(); }
void reset() { prime_ = begin(); }
void setNext(Bucket* next)
{
next_ = next;
}
/// Store a sieving prime in the bucket
/// @return false if the bucket is full else true
///
bool store(uint_t sievingPrime,
uint_t multipleIndex,
uint_t wheelIndex)
{
prime_->set(sievingPrime, multipleIndex, wheelIndex);
return prime_++ != last();
}
private:
SievingPrime* prime_;
Bucket* next_;
SievingPrime sievingPrimes_[config::BUCKETSIZE];
};
/// The abstract WheelFactorization class is used skip multiples
/// of small primes in the sieve of Eratosthenes. The EratSmall,
/// EratMedium and EratBig classes are derived from
/// WheelFactorization.
///
template <uint_t MODULO, uint_t SIZE, const WheelInit* INIT, const WheelElement* WHEEL>
class WheelFactorization
{
public:
/// Add a new sieving prime to the sieving algorithm.
/// Calculate the first multiple > segmentLow of prime and the
/// position within the SieveOfEratosthenes array of that multiple
/// and its wheel index. When done store the sieving prime.
///
void addSievingPrime(uint_t prime, uint64_t segmentLow)
{
segmentLow += 6;
// calculate the first multiple (of prime) > segmentLow
uint64_t quotient = segmentLow / prime + 1;
uint64_t multiple = prime * quotient;
// prime not needed for sieving
if (multiple > stop_ ||
multiple < segmentLow)
return;
// ensure multiple >= prime * prime
if (quotient < prime)
{
multiple = isquare<uint64_t>(prime);
quotient = prime;
}
// calculate the next multiple of prime that is not
// divisible by any of the wheel's factors
uint64_t nextMultipleFactor = INIT[quotient % MODULO].nextMultipleFactor;
uint64_t nextMultiple = prime * nextMultipleFactor;
if (nextMultiple > stop_ - multiple)
return;
nextMultiple += multiple - segmentLow;
uint_t multipleIndex = (uint_t)(nextMultiple / NUMBERS_PER_BYTE);
uint_t wheelIndex = wheelOffsets_[prime % NUMBERS_PER_BYTE] + INIT[quotient % MODULO].wheelIndex;
storeSievingPrime(prime, multipleIndex, wheelIndex);
}
protected:
WheelFactorization(uint64_t stop, uint_t sieveSize) :
stop_(stop)
{
uint_t maxSieveSize = SievingPrime::MAX_MULTIPLEINDEX + 1;
if (sieveSize > maxSieveSize)
throw primesieve_error("WheelFactorization: sieveSize must be <= " + std::to_string(maxSieveSize));
}
virtual ~WheelFactorization()
{ }
virtual void storeSievingPrime(uint_t, uint_t, uint_t) = 0;
static uint_t getMaxFactor()
{
return WHEEL[0].nextMultipleFactor;
}
/// Cross-off the current multiple of sievingPrime
/// and calculate its next multiple
///
static void unsetBit(byte_t* sieve, uint_t sievingPrime, uint_t* multipleIndex, uint_t* wheelIndex)
{
sieve[*multipleIndex] &= WHEEL[*wheelIndex].unsetBit;
*multipleIndex += WHEEL[*wheelIndex].nextMultipleFactor * sievingPrime;
*multipleIndex += WHEEL[*wheelIndex].correct;
*wheelIndex += WHEEL[*wheelIndex].next;
}
private:
static const uint_t wheelOffsets_[30];
uint64_t stop_;
};
template <uint_t MODULO, uint_t SIZE, const WheelInit* INIT, const WheelElement* WHEEL>
const uint_t
WheelFactorization<MODULO, SIZE, INIT, WHEEL>::wheelOffsets_[30] =
{
0, SIZE * 7, 0, 0, 0, 0,
0, SIZE * 0, 0, 0, 0, SIZE * 1,
0, SIZE * 2, 0, 0, 0, SIZE * 3,
0, SIZE * 4, 0, 0, 0, SIZE * 5,
0, 0, 0, 0, 0, SIZE * 6
};
/// 3rd wheel, skips multiples of 2, 3 and 5
typedef WheelFactorization<30, 8, wheel30Init, wheel30> Modulo30Wheel_t;
/// 4th wheel, skips multiples of 2, 3, 5 and 7
typedef WheelFactorization<210, 48, wheel210Init, wheel210> Modulo210Wheel_t;
} // namespace
#endif
<commit_msg>Refactor<commit_after>///
/// @file Wheel.hpp
/// @brief Classes and structs related to wheel factorization.
///
/// Copyright (C) 2017 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef WHEEL_HPP
#define WHEEL_HPP
#include "config.hpp"
#include "pmath.hpp"
#include "primesieve_error.hpp"
#include <stdint.h>
#include <cassert>
#include <string>
namespace primesieve {
/// The WheelInit data structure is used to calculate the
/// first multiple >= start of each sieving prime
///
struct WheelInit
{
uint8_t nextMultipleFactor;
uint8_t wheelIndex;
};
extern const WheelInit wheel30Init[30];
extern const WheelInit wheel210Init[210];
/// The WheelElement data structure is used to skip multiples
/// of small primes using wheel factorization
///
struct WheelElement
{
/// Bitmask used to unset the bit corresponding to the current
/// multiple of a SievingPrime object
uint8_t unsetBit;
/// Factor used to calculate the next multiple of a sieving prime
/// that is not divisible by any of the wheel factors
uint8_t nextMultipleFactor;
/// Overflow needed to correct the next multiple index
/// (due to sievingPrime = prime / 30)
uint8_t correct;
/// Used to calculate the next wheel index:
/// wheelIndex += next;
int8_t next;
};
extern const WheelElement wheel30[8*8];
extern const WheelElement wheel210[48*8];
/// Sieving primes are used to cross-off multiples.
/// Each SievingPrime object contains a sieving prime and the
/// position of its next multiple within the SieveOfEratosthenes
/// array (i.e. multipleIndex) and a wheelIndex.
///
class SievingPrime
{
public:
enum
{
MAX_MULTIPLEINDEX = (1 << 23) - 1,
MAX_WHEELINDEX = (1 << (32 - 23)) - 1
};
SievingPrime() { }
SievingPrime(uint_t sievingPrime,
uint_t multipleIndex,
uint_t wheelIndex)
{
set(multipleIndex, wheelIndex);
sievingPrime_ = (uint32_t) sievingPrime;
}
void set(uint_t multipleIndex,
uint_t wheelIndex)
{
assert(multipleIndex <= MAX_MULTIPLEINDEX);
assert(wheelIndex <= MAX_WHEELINDEX);
indexes_ = (uint32_t) (multipleIndex | (wheelIndex << 23));
}
void set(uint_t sievingPrime,
uint_t multipleIndex,
uint_t wheelIndex)
{
set(multipleIndex, wheelIndex);
sievingPrime_ = (uint32_t) sievingPrime;
}
uint_t getSievingPrime() const
{
return sievingPrime_;
}
uint_t getMultipleIndex() const
{
return indexes_ & MAX_MULTIPLEINDEX;
}
uint_t getWheelIndex() const
{
return indexes_ >> 23;
}
void setMultipleIndex(uint_t multipleIndex)
{
assert(multipleIndex <= MAX_MULTIPLEINDEX);
indexes_ = (uint32_t) (indexes_ | multipleIndex);
}
void setWheelIndex(uint_t wheelIndex)
{
assert(wheelIndex <= MAX_WHEELINDEX);
indexes_ = (uint32_t) (wheelIndex << 23);
}
private:
/// multipleIndex = 23 least significant bits of indexes_
/// wheelIndex = 9 most significant bits of indexes_
uint32_t indexes_;
uint32_t sievingPrime_;
};
/// The Bucket data structure is used to store sieving primes.
/// @see http://www.ieeta.pt/~tos/software/prime_sieve.html
/// The Bucket class is designed as a singly linked list, once there
/// is no more space in the current Bucket a new Bucket node is
/// allocated.
///
class Bucket
{
public:
Bucket() { reset(); }
SievingPrime* begin() { return &sievingPrimes_[0]; }
SievingPrime* last() { return &sievingPrimes_[config::BUCKETSIZE - 1]; }
SievingPrime* end() { return prime_; }
Bucket* next() { return next_; }
bool hasNext() const { return next_ != nullptr; }
bool empty() { return begin() == end(); }
void reset() { prime_ = begin(); }
void setNext(Bucket* next)
{
next_ = next;
}
/// Store a sieving prime in the bucket
/// @return false if the bucket is full else true
///
bool store(uint_t sievingPrime,
uint_t multipleIndex,
uint_t wheelIndex)
{
prime_->set(sievingPrime, multipleIndex, wheelIndex);
return prime_++ != last();
}
private:
SievingPrime* prime_;
Bucket* next_;
SievingPrime sievingPrimes_[config::BUCKETSIZE];
};
/// The abstract WheelFactorization class is used skip multiples
/// of small primes in the sieve of Eratosthenes. The EratSmall,
/// EratMedium and EratBig classes are derived from
/// WheelFactorization.
///
template <uint_t MODULO, uint_t SIZE, const WheelInit* INIT, const WheelElement* WHEEL>
class WheelFactorization
{
public:
/// Add a new sieving prime to the sieving algorithm.
/// Calculate the first multiple > segmentLow of prime and the
/// position within the SieveOfEratosthenes array of that multiple
/// and its wheel index. When done store the sieving prime.
///
void addSievingPrime(uint_t prime, uint64_t segmentLow)
{
segmentLow += 6;
// calculate the first multiple (of prime) > segmentLow
uint64_t quotient = segmentLow / prime + 1;
uint64_t multiple = prime * quotient;
// prime not needed for sieving
if (multiple > stop_ ||
multiple < segmentLow)
return;
// ensure multiple >= prime * prime
if (quotient < prime)
{
multiple = isquare<uint64_t>(prime);
quotient = prime;
}
// calculate the next multiple of prime that is not
// divisible by any of the wheel's factors
uint64_t nextMultipleFactor = INIT[quotient % MODULO].nextMultipleFactor;
uint64_t nextMultiple = prime * nextMultipleFactor;
if (nextMultiple > stop_ - multiple)
return;
nextMultiple += multiple - segmentLow;
uint_t multipleIndex = (uint_t)(nextMultiple / NUMBERS_PER_BYTE);
uint_t wheelIndex = wheelOffsets_[prime % NUMBERS_PER_BYTE] + INIT[quotient % MODULO].wheelIndex;
storeSievingPrime(prime, multipleIndex, wheelIndex);
}
protected:
WheelFactorization(uint64_t stop, uint_t sieveSize) :
stop_(stop)
{
uint_t maxSieveSize = SievingPrime::MAX_MULTIPLEINDEX + 1;
if (sieveSize > maxSieveSize)
throw primesieve_error("WheelFactorization: sieveSize must be <= " + std::to_string(maxSieveSize));
}
virtual ~WheelFactorization()
{ }
virtual void storeSievingPrime(uint_t, uint_t, uint_t) = 0;
static uint_t getMaxFactor()
{
return WHEEL[0].nextMultipleFactor;
}
/// Cross-off the current multiple of sievingPrime
/// and calculate its next multiple
///
static void unsetBit(byte_t* sieve, uint_t sievingPrime, uint_t* multipleIndex, uint_t* wheelIndex)
{
sieve[*multipleIndex] &= WHEEL[*wheelIndex].unsetBit;
*multipleIndex += WHEEL[*wheelIndex].nextMultipleFactor * sievingPrime;
*multipleIndex += WHEEL[*wheelIndex].correct;
*wheelIndex += WHEEL[*wheelIndex].next;
}
private:
static const uint_t wheelOffsets_[30];
uint64_t stop_;
};
template <uint_t MODULO, uint_t SIZE, const WheelInit* INIT, const WheelElement* WHEEL>
const uint_t
WheelFactorization<MODULO, SIZE, INIT, WHEEL>::wheelOffsets_[30] =
{
0, SIZE * 7, 0, 0, 0, 0,
0, SIZE * 0, 0, 0, 0, SIZE * 1,
0, SIZE * 2, 0, 0, 0, SIZE * 3,
0, SIZE * 4, 0, 0, 0, SIZE * 5,
0, 0, 0, 0, 0, SIZE * 6
};
/// 3rd wheel, skips multiples of 2, 3 and 5
typedef WheelFactorization<30, 8, wheel30Init, wheel30> Modulo30Wheel_t;
/// 4th wheel, skips multiples of 2, 3, 5 and 7
typedef WheelFactorization<210, 48, wheel210Init, wheel210> Modulo210Wheel_t;
} // namespace
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2016, Shubham Batra (https://www.github.com/batrashubham)
* 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 "KinectFaceMat.h"
cv::Rect* getHDfaceRect()
{
/******** To be implemented later *********/
return nullptr;
}
cv::Rect* getSDFaceRect(IBodyFrameReader* _body_reader, IFaceFrameReader* _face_reader[],
IFaceFrameSource* _face_source[], int& trackedFaces, HRESULT faceReaderinit, HRESULT bodyReaderInit)
{
cv::Rect faceRect[BODY_COUNT];
HRESULT hr;
if (SUCCEEDED(faceReaderinit) && SUCCEEDED(bodyReaderInit)) {
IBody* Bodies[BODY_COUNT] = { 0 };
if (_body_reader != nullptr)
{
IBodyFrame* BodyFrame = nullptr;
hr = _body_reader->AcquireLatestFrame(&BodyFrame);
if (SUCCEEDED(hr))
{
hr = BodyFrame->GetAndRefreshBodyData(BODY_COUNT, Bodies);
}
SafeRelease(BodyFrame);
}
bool gotBodyData = SUCCEEDED(hr);
// iterate through each face reader
for (int iFace = 0; iFace < BODY_COUNT; ++iFace)
{
// fetch the latest face frame from current reader
IFaceFrame* frame = nullptr;
hr = _face_reader[iFace]->AcquireLatestFrame(&frame);
BOOLEAN isFaceTracked = false;
if (SUCCEEDED(hr) && nullptr != frame)
{
// check if a valid face is tracked in this face frame
hr = frame->get_IsTrackingIdValid(&isFaceTracked);
}
if (SUCCEEDED(hr))
{
if (isFaceTracked)
{
IFaceFrameResult* FaceFrameResult = nullptr;
RectI faceBox = { 0 };
PointF facePoints[FacePointType::FacePointType_Count];
hr = frame->get_FaceFrameResult(&FaceFrameResult);
// ensure FaceFrameResult contains data before trying to access it
if (SUCCEEDED(hr) && FaceFrameResult != nullptr)
{
hr = FaceFrameResult->get_FaceBoundingBoxInColorSpace(&faceBox);
if (SUCCEEDED(hr))
{
hr = FaceFrameResult->GetFacePointsInColorSpace(FacePointType::FacePointType_Count, facePoints);
}
if (SUCCEEDED(hr)) {
//gives the number of faces tracked
trackedFaces++;
}
//Set the values of corresponding cv::Rect
faceRect[iFace].x = faceBox.Left;
faceRect[iFace].y = faceBox.Top;
faceRect[iFace].width = faceBox.Right - faceBox.Left;
faceRect[iFace].height = faceBox.Bottom - faceBox.Top;
}
SafeRelease(FaceFrameResult);
}
else
{
// face tracking is not valid - attempt to fix the issue
// a valid body is required to perform this step
if (gotBodyData)
{
// check if the corresponding body is tracked
// if this is true then update the face frame source to track this body
IBody* Body = Bodies[iFace];
if (Body != nullptr)
{
BOOLEAN isTracked = false;
hr = Body->get_IsTracked(&isTracked);
UINT64 bodyTId;
if (SUCCEEDED(hr) && isTracked)
{
// get the tracking ID of this body
hr = Body->get_TrackingId(&bodyTId);
if (SUCCEEDED(hr))
{
// update the face frame source with the tracking ID
_face_source[iFace]->put_TrackingId(bodyTId);
}
}
}
}
}
}
SafeRelease(frame);
}
if (gotBodyData)
{
for (int i = 0; i < _countof(Bodies); ++i)
{
SafeRelease(Bodies[i]);
}
}
}
return faceRect;
}
<commit_msg>Fixed KinectFaceMat (now tracks multiple faces)<commit_after>/*
* Copyright (C) 2016, Shubham Batra (https://www.github.com/batrashubham)
* 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 "KinectFaceMat.h"
cv::Rect faceRects[BODY_COUNT];
cv::Rect* getHDfaceRect()
{
/******** To be implemented later *********/
return nullptr;
}
cv::Rect* getSDFaceRect(IBodyFrameReader* _body_reader, IFaceFrameReader* _face_reader[],
IFaceFrameSource* _face_source[], int& trackedFaces, HRESULT faceReaderinit, HRESULT bodyReaderInit)
{
HRESULT hResult;
if (SUCCEEDED(faceReaderinit) && SUCCEEDED(bodyReaderInit)) {
IBodyFrame* pBodyFrame = nullptr;
hResult = _body_reader->AcquireLatestFrame(&pBodyFrame);
if (SUCCEEDED(hResult)) {
IBody* pBody[BODY_COUNT] = { 0 };
hResult = pBodyFrame->GetAndRefreshBodyData(BODY_COUNT, pBody);
if (SUCCEEDED(hResult)) {
for (int count = 0; count < BODY_COUNT; count++) {
BOOLEAN bTracked = false;
hResult = pBody[count]->get_IsTracked(&bTracked);
if (SUCCEEDED(hResult) && bTracked) {
/*// Joint
Joint joint[JointType::JointType_Count];
hResult = pBody[count]->GetJoints( JointType::JointType_Count, joint );
if( SUCCEEDED( hResult ) ){
for( int type = 0; type < JointType::JointType_Count; type++ ){
ColorSpacePoint colorSpacePoint = { 0 };
pCoordinateMapper->MapCameraPointToColorSpace( joint[type].Position, &colorSpacePoint );
int x = static_cast<int>( colorSpacePoint.X );
int y = static_cast<int>( colorSpacePoint.Y );
if( ( x >= 0 ) && ( x < width ) && ( y >= 0 ) && ( y < height ) ){
cv::circle( bufferMat, cv::Point( x, y ), 5, static_cast<cv::Scalar>( color[count] ), -1, CV_AA );
}
}
}*/
// Set TrackingID to Detect Face
UINT64 trackingId = _UI64_MAX;
hResult = pBody[count]->get_TrackingId(&trackingId);
if (SUCCEEDED(hResult)) {
_face_source[count]->put_TrackingId(trackingId);
}
}
}
}
for (int count = 0; count < BODY_COUNT; count++) {
SafeRelease(pBody[count]);
}
}
SafeRelease(pBodyFrame);
for (int iFace = 0; iFace < BODY_COUNT; iFace++) {
IFaceFrame* pFaceFrame = nullptr;
hResult = _face_reader[iFace]->AcquireLatestFrame(&pFaceFrame);
if (SUCCEEDED(hResult) && pFaceFrame != nullptr) {
BOOLEAN bFaceTracked = false;
hResult = pFaceFrame->get_IsTrackingIdValid(&bFaceTracked);
if (SUCCEEDED(hResult) && bFaceTracked) {
IFaceFrameResult* pFaceResult = nullptr;
hResult = pFaceFrame->get_FaceFrameResult(&pFaceResult);
if (SUCCEEDED(hResult) && pFaceResult != nullptr) {
RectI faceBox;
hResult = pFaceResult->get_FaceBoundingBoxInColorSpace(&faceBox);
if (SUCCEEDED(hResult)) {
trackedFaces++;
faceRects[iFace].x = faceBox.Left;
faceRects[iFace].y = faceBox.Top;
faceRects[iFace].width = faceBox.Right - faceBox.Left;
faceRects[iFace].height = faceBox.Bottom - faceBox.Top;
}
}
SafeRelease(pFaceResult);
}
}
SafeRelease(pFaceFrame);
}
}
return faceRects;
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: webconninfo.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: ihi $ $Date: 2007-11-26 16:40:29 $
*
* 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_svx.hxx"
#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif
// include ---------------------------------------------------------------
#ifndef _SVX_DIALMGR_HXX
#include <svx/dialmgr.hxx>
#endif
#ifndef _SVX_DIALOGS_HRC
#include <svx/dialogs.hrc>
#endif
#include <com/sun/star/task/UrlRecord.hpp>
#include <com/sun/star/task/XPasswordContainer.hpp>
#include <com/sun/star/task/XMasterPasswordHandling.hpp>
#include <comphelper/processfactory.hxx>
#include <svtools/docpasswdrequest.hxx>
#include "webconninfo.hxx"
#include "webconninfo.hrc"
using namespace ::com::sun::star;
//........................................................................
namespace svx
{
//........................................................................
// class PasswordTable ---------------------------------------------------
PasswordTable::PasswordTable( Window* pParent, const ResId& rResId ) :
SvxSimpleTable( pParent, rResId )
{
SetWindowBits( GetStyle() | WB_NOINITIALSELECTION );
}
void PasswordTable::InsertHeaderItem( USHORT nColumn, const String& rText, HeaderBarItemBits nBits )
{
GetTheHeaderBar()->InsertItem( nColumn, rText, 0, nBits );
}
void PasswordTable::ResetTabs()
{
SetTabs();
}
void PasswordTable::Resort( bool bForced )
{
USHORT nColumn = GetSelectedCol();
if ( 0 == nColumn || bForced ) // only the first column is sorted
{
HeaderBarItemBits nBits = GetTheHeaderBar()->GetItemBits(1);
BOOL bUp = ( ( nBits & HIB_UPARROW ) == HIB_UPARROW );
SvSortMode eMode = SortAscending;
if ( bUp )
{
nBits &= ~HIB_UPARROW;
nBits |= HIB_DOWNARROW;
eMode = SortDescending;
}
else
{
nBits &= ~HIB_DOWNARROW;
nBits |= HIB_UPARROW;
}
GetTheHeaderBar()->SetItemBits( 1, nBits );
SvTreeList* pListModel = GetModel();
pListModel->SetSortMode( eMode );
pListModel->Resort();
}
}
// class WebConnectionInfoDialog -----------------------------------------
// -----------------------------------------------------------------------
WebConnectionInfoDialog::WebConnectionInfoDialog( Window* pParent ) :
ModalDialog( pParent, SVX_RES( RID_SVXDLG_WEBCONNECTION_INFO ) )
,m_aNeverShownFI ( this, SVX_RES( FI_NEVERSHOWN ) )
,m_aPasswordsLB ( this, SVX_RES( LB_PASSWORDS ) )
,m_aRemoveBtn ( this, SVX_RES( PB_REMOVE ) )
,m_aRemoveAllBtn ( this, SVX_RES( PB_REMOVEALL ) )
,m_aChangeBtn ( this, SVX_RES( PB_CHANGE ) )
,m_aButtonsFL ( this, SVX_RES( FL_BUTTONS ) )
,m_aCloseBtn ( this, SVX_RES( PB_CLOSE ) )
,m_aHelpBtn ( this, SVX_RES( PB_HELP ) )
{
static long aStaticTabs[]= { 3, 0, 150, 250 };
m_aPasswordsLB.SetTabs( aStaticTabs );
m_aPasswordsLB.InsertHeaderItem( 1, SVX_RESSTR( STR_WEBSITE ),
HIB_LEFT | HIB_VCENTER | HIB_FIXEDPOS | HIB_CLICKABLE | HIB_UPARROW );
m_aPasswordsLB.InsertHeaderItem( 2, SVX_RESSTR( STR_USERNAME ),
HIB_LEFT | HIB_VCENTER | HIB_FIXEDPOS );
m_aPasswordsLB.ResetTabs();
FreeResource();
m_aPasswordsLB.SetHeaderBarClickHdl( LINK( this, WebConnectionInfoDialog, HeaderBarClickedHdl ) );
m_aRemoveBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, RemovePasswordHdl ) );
m_aRemoveAllBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, RemoveAllPasswordsHdl ) );
m_aChangeBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, ChangePasswordHdl ) );
// one button too small for its text?
sal_Int32 i = 0;
long nBtnTextWidth = 0;
Window* pButtons[] = { &m_aRemoveBtn, &m_aRemoveAllBtn, &m_aChangeBtn };
Window** pButton = pButtons;
const sal_Int32 nBCount = sizeof( pButtons ) / sizeof( pButtons[ 0 ] );
for ( ; i < nBCount; ++i, ++pButton )
{
long nTemp = (*pButton)->GetCtrlTextWidth( (*pButton)->GetText() );
if ( nTemp > nBtnTextWidth )
nBtnTextWidth = nTemp;
}
nBtnTextWidth = nBtnTextWidth * 115 / 100; // a little offset
long nButtonWidth = m_aRemoveBtn.GetSizePixel().Width();
if ( nBtnTextWidth > nButtonWidth )
{
// so make the buttons broader and its control in front of it smaller
long nDelta = nBtnTextWidth - nButtonWidth;
pButton = pButtons;
for ( i = 0; i < nBCount; ++i, ++pButton )
{
Point aNewPos = (*pButton)->GetPosPixel();
if ( &m_aRemoveAllBtn == (*pButton) )
aNewPos.X() += nDelta;
else if ( &m_aChangeBtn == (*pButton) )
aNewPos.X() -= nDelta;
Size aNewSize = (*pButton)->GetSizePixel();
aNewSize.Width() += nDelta;
(*pButton)->SetPosSizePixel( aNewPos, aNewSize );
}
}
FillPasswordList();
m_aRemoveBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, RemovePasswordHdl ) );
m_aRemoveAllBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, RemoveAllPasswordsHdl ) );
m_aChangeBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, ChangePasswordHdl ) );
m_aPasswordsLB.SetSelectHdl( LINK( this, WebConnectionInfoDialog, EntrySelectedHdl ) );
m_aRemoveBtn.Enable( FALSE );
m_aChangeBtn.Enable( FALSE );
HeaderBarClickedHdl( NULL );
}
// -----------------------------------------------------------------------
WebConnectionInfoDialog::~WebConnectionInfoDialog()
{
}
// -----------------------------------------------------------------------
IMPL_LINK( WebConnectionInfoDialog, HeaderBarClickedHdl, SvxSimpleTable*, pTable )
{
m_aPasswordsLB.Resort( NULL == pTable );
return 0;
}
// -----------------------------------------------------------------------
void WebConnectionInfoDialog::FillPasswordList()
{
try
{
uno::Reference< task::XMasterPasswordHandling > xMasterPasswd(
comphelper::getProcessServiceFactory()->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.PasswordContainer" ) ) ),
uno::UNO_QUERY );
if ( xMasterPasswd.is() && xMasterPasswd->isPersistentStoringAllowed() )
{
uno::Reference< task::XPasswordContainer > xPasswdContainer( xMasterPasswd, uno::UNO_QUERY_THROW );
uno::Reference< task::XInteractionHandler > xInteractionHandler(
comphelper::getProcessServiceFactory()->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.InteractionHandler" ) ) ),
uno::UNO_QUERY_THROW );
uno::Sequence< task::UrlRecord > aURLEntries = xPasswdContainer->getAllPersistent( xInteractionHandler );
sal_Int32 nCount = 0;
for ( sal_Int32 nURLInd = 0; nURLInd < aURLEntries.getLength(); nURLInd++ )
for ( sal_Int32 nUserInd = 0; nUserInd < aURLEntries[nURLInd].UserList.getLength(); nUserInd++ )
{
::rtl::OUString aUIEntry( aURLEntries[nURLInd].Url );
aUIEntry += ::rtl::OUString::valueOf( (sal_Unicode)'\t' );
aUIEntry += aURLEntries[nURLInd].UserList[nUserInd].UserName;
SvLBoxEntry* pEntry = m_aPasswordsLB.InsertEntry( aUIEntry );
pEntry->SetUserData( (void*)(nCount++) );
}
}
}
catch( uno::Exception& )
{}
}
// -----------------------------------------------------------------------
IMPL_LINK( WebConnectionInfoDialog, RemovePasswordHdl, PushButton*, EMPTYARG )
{
try
{
uno::Reference< task::XPasswordContainer > xPasswdContainer(
comphelper::getProcessServiceFactory()->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.PasswordContainer" ) ) ),
uno::UNO_QUERY_THROW );
uno::Reference< task::XInteractionHandler > xInteractionHandler(
comphelper::getProcessServiceFactory()->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.InteractionHandler" ) ) ),
uno::UNO_QUERY_THROW );
SvLBoxEntry* pEntry = m_aPasswordsLB.GetCurEntry();
if ( pEntry )
{
::rtl::OUString aURL = m_aPasswordsLB.GetEntryText( pEntry, 0 );
::rtl::OUString aUserName = m_aPasswordsLB.GetEntryText( pEntry, 1 );
xPasswdContainer->removePersistent( aURL, aUserName );
m_aPasswordsLB.RemoveEntry( pEntry );
}
}
catch( uno::Exception& )
{}
return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( WebConnectionInfoDialog, RemoveAllPasswordsHdl, PushButton*, EMPTYARG )
{
try
{
uno::Reference< task::XPasswordContainer > xPasswdContainer(
comphelper::getProcessServiceFactory()->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.PasswordContainer" ) ) ),
uno::UNO_QUERY_THROW );
// should the master password be requested before?
xPasswdContainer->removeAllPersistent();
m_aPasswordsLB.Clear();
}
catch( uno::Exception& )
{}
return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( WebConnectionInfoDialog, ChangePasswordHdl, PushButton*, EMPTYARG )
{
try
{
uno::Reference< task::XPasswordContainer > xPasswdContainer(
comphelper::getProcessServiceFactory()->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.PasswordContainer" ) ) ),
uno::UNO_QUERY_THROW );
uno::Reference< task::XInteractionHandler > xInteractionHandler(
comphelper::getProcessServiceFactory()->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.InteractionHandler" ) ) ),
uno::UNO_QUERY_THROW );
SvLBoxEntry* pEntry = m_aPasswordsLB.GetCurEntry();
if ( pEntry )
{
::rtl::OUString aURL = m_aPasswordsLB.GetEntryText( pEntry, 0 );
::rtl::OUString aUserName = m_aPasswordsLB.GetEntryText( pEntry, 1 );
RequestDocumentPassword* pPasswordRequest = new RequestDocumentPassword(
task::PasswordRequestMode_PASSWORD_CREATE,
aURL );
uno::Reference< task::XInteractionRequest > rRequest( pPasswordRequest );
xInteractionHandler->handle( rRequest );
if ( pPasswordRequest->isPassword() )
{
String aNewPass = pPasswordRequest->getPassword();
uno::Sequence< ::rtl::OUString > aPasswd( 1 );
aPasswd[0] = aNewPass;
xPasswdContainer->addPersistent( aURL, aUserName, aPasswd, xInteractionHandler );
}
}
}
catch( uno::Exception& )
{}
return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( WebConnectionInfoDialog, EntrySelectedHdl, void*, EMPTYARG )
{
SvLBoxEntry* pEntry = m_aPasswordsLB.GetCurEntry();
if ( !pEntry )
{
m_aRemoveBtn.Enable( FALSE );
m_aChangeBtn.Enable( FALSE );
}
else
{
m_aRemoveBtn.Enable( TRUE );
m_aChangeBtn.Enable( TRUE );
}
return 0;
}
//........................................................................
} // namespace svx
//........................................................................
<commit_msg>INTEGRATION: CWS changefileheader (1.2.196); FILE MERGED 2008/04/01 12:48:24 thb 1.2.196.2: #i85898# Stripping all external header guards 2008/03/31 14:20:09 rt 1.2.196.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: webconninfo.cxx,v $
* $Revision: 1.3 $
*
* 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_svx.hxx"
#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif
// include ---------------------------------------------------------------
#include <svx/dialmgr.hxx>
#ifndef _SVX_DIALOGS_HRC
#include <svx/dialogs.hrc>
#endif
#include <com/sun/star/task/UrlRecord.hpp>
#include <com/sun/star/task/XPasswordContainer.hpp>
#include <com/sun/star/task/XMasterPasswordHandling.hpp>
#include <comphelper/processfactory.hxx>
#include <svtools/docpasswdrequest.hxx>
#include "webconninfo.hxx"
#include "webconninfo.hrc"
using namespace ::com::sun::star;
//........................................................................
namespace svx
{
//........................................................................
// class PasswordTable ---------------------------------------------------
PasswordTable::PasswordTable( Window* pParent, const ResId& rResId ) :
SvxSimpleTable( pParent, rResId )
{
SetWindowBits( GetStyle() | WB_NOINITIALSELECTION );
}
void PasswordTable::InsertHeaderItem( USHORT nColumn, const String& rText, HeaderBarItemBits nBits )
{
GetTheHeaderBar()->InsertItem( nColumn, rText, 0, nBits );
}
void PasswordTable::ResetTabs()
{
SetTabs();
}
void PasswordTable::Resort( bool bForced )
{
USHORT nColumn = GetSelectedCol();
if ( 0 == nColumn || bForced ) // only the first column is sorted
{
HeaderBarItemBits nBits = GetTheHeaderBar()->GetItemBits(1);
BOOL bUp = ( ( nBits & HIB_UPARROW ) == HIB_UPARROW );
SvSortMode eMode = SortAscending;
if ( bUp )
{
nBits &= ~HIB_UPARROW;
nBits |= HIB_DOWNARROW;
eMode = SortDescending;
}
else
{
nBits &= ~HIB_DOWNARROW;
nBits |= HIB_UPARROW;
}
GetTheHeaderBar()->SetItemBits( 1, nBits );
SvTreeList* pListModel = GetModel();
pListModel->SetSortMode( eMode );
pListModel->Resort();
}
}
// class WebConnectionInfoDialog -----------------------------------------
// -----------------------------------------------------------------------
WebConnectionInfoDialog::WebConnectionInfoDialog( Window* pParent ) :
ModalDialog( pParent, SVX_RES( RID_SVXDLG_WEBCONNECTION_INFO ) )
,m_aNeverShownFI ( this, SVX_RES( FI_NEVERSHOWN ) )
,m_aPasswordsLB ( this, SVX_RES( LB_PASSWORDS ) )
,m_aRemoveBtn ( this, SVX_RES( PB_REMOVE ) )
,m_aRemoveAllBtn ( this, SVX_RES( PB_REMOVEALL ) )
,m_aChangeBtn ( this, SVX_RES( PB_CHANGE ) )
,m_aButtonsFL ( this, SVX_RES( FL_BUTTONS ) )
,m_aCloseBtn ( this, SVX_RES( PB_CLOSE ) )
,m_aHelpBtn ( this, SVX_RES( PB_HELP ) )
{
static long aStaticTabs[]= { 3, 0, 150, 250 };
m_aPasswordsLB.SetTabs( aStaticTabs );
m_aPasswordsLB.InsertHeaderItem( 1, SVX_RESSTR( STR_WEBSITE ),
HIB_LEFT | HIB_VCENTER | HIB_FIXEDPOS | HIB_CLICKABLE | HIB_UPARROW );
m_aPasswordsLB.InsertHeaderItem( 2, SVX_RESSTR( STR_USERNAME ),
HIB_LEFT | HIB_VCENTER | HIB_FIXEDPOS );
m_aPasswordsLB.ResetTabs();
FreeResource();
m_aPasswordsLB.SetHeaderBarClickHdl( LINK( this, WebConnectionInfoDialog, HeaderBarClickedHdl ) );
m_aRemoveBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, RemovePasswordHdl ) );
m_aRemoveAllBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, RemoveAllPasswordsHdl ) );
m_aChangeBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, ChangePasswordHdl ) );
// one button too small for its text?
sal_Int32 i = 0;
long nBtnTextWidth = 0;
Window* pButtons[] = { &m_aRemoveBtn, &m_aRemoveAllBtn, &m_aChangeBtn };
Window** pButton = pButtons;
const sal_Int32 nBCount = sizeof( pButtons ) / sizeof( pButtons[ 0 ] );
for ( ; i < nBCount; ++i, ++pButton )
{
long nTemp = (*pButton)->GetCtrlTextWidth( (*pButton)->GetText() );
if ( nTemp > nBtnTextWidth )
nBtnTextWidth = nTemp;
}
nBtnTextWidth = nBtnTextWidth * 115 / 100; // a little offset
long nButtonWidth = m_aRemoveBtn.GetSizePixel().Width();
if ( nBtnTextWidth > nButtonWidth )
{
// so make the buttons broader and its control in front of it smaller
long nDelta = nBtnTextWidth - nButtonWidth;
pButton = pButtons;
for ( i = 0; i < nBCount; ++i, ++pButton )
{
Point aNewPos = (*pButton)->GetPosPixel();
if ( &m_aRemoveAllBtn == (*pButton) )
aNewPos.X() += nDelta;
else if ( &m_aChangeBtn == (*pButton) )
aNewPos.X() -= nDelta;
Size aNewSize = (*pButton)->GetSizePixel();
aNewSize.Width() += nDelta;
(*pButton)->SetPosSizePixel( aNewPos, aNewSize );
}
}
FillPasswordList();
m_aRemoveBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, RemovePasswordHdl ) );
m_aRemoveAllBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, RemoveAllPasswordsHdl ) );
m_aChangeBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, ChangePasswordHdl ) );
m_aPasswordsLB.SetSelectHdl( LINK( this, WebConnectionInfoDialog, EntrySelectedHdl ) );
m_aRemoveBtn.Enable( FALSE );
m_aChangeBtn.Enable( FALSE );
HeaderBarClickedHdl( NULL );
}
// -----------------------------------------------------------------------
WebConnectionInfoDialog::~WebConnectionInfoDialog()
{
}
// -----------------------------------------------------------------------
IMPL_LINK( WebConnectionInfoDialog, HeaderBarClickedHdl, SvxSimpleTable*, pTable )
{
m_aPasswordsLB.Resort( NULL == pTable );
return 0;
}
// -----------------------------------------------------------------------
void WebConnectionInfoDialog::FillPasswordList()
{
try
{
uno::Reference< task::XMasterPasswordHandling > xMasterPasswd(
comphelper::getProcessServiceFactory()->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.PasswordContainer" ) ) ),
uno::UNO_QUERY );
if ( xMasterPasswd.is() && xMasterPasswd->isPersistentStoringAllowed() )
{
uno::Reference< task::XPasswordContainer > xPasswdContainer( xMasterPasswd, uno::UNO_QUERY_THROW );
uno::Reference< task::XInteractionHandler > xInteractionHandler(
comphelper::getProcessServiceFactory()->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.InteractionHandler" ) ) ),
uno::UNO_QUERY_THROW );
uno::Sequence< task::UrlRecord > aURLEntries = xPasswdContainer->getAllPersistent( xInteractionHandler );
sal_Int32 nCount = 0;
for ( sal_Int32 nURLInd = 0; nURLInd < aURLEntries.getLength(); nURLInd++ )
for ( sal_Int32 nUserInd = 0; nUserInd < aURLEntries[nURLInd].UserList.getLength(); nUserInd++ )
{
::rtl::OUString aUIEntry( aURLEntries[nURLInd].Url );
aUIEntry += ::rtl::OUString::valueOf( (sal_Unicode)'\t' );
aUIEntry += aURLEntries[nURLInd].UserList[nUserInd].UserName;
SvLBoxEntry* pEntry = m_aPasswordsLB.InsertEntry( aUIEntry );
pEntry->SetUserData( (void*)(nCount++) );
}
}
}
catch( uno::Exception& )
{}
}
// -----------------------------------------------------------------------
IMPL_LINK( WebConnectionInfoDialog, RemovePasswordHdl, PushButton*, EMPTYARG )
{
try
{
uno::Reference< task::XPasswordContainer > xPasswdContainer(
comphelper::getProcessServiceFactory()->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.PasswordContainer" ) ) ),
uno::UNO_QUERY_THROW );
uno::Reference< task::XInteractionHandler > xInteractionHandler(
comphelper::getProcessServiceFactory()->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.InteractionHandler" ) ) ),
uno::UNO_QUERY_THROW );
SvLBoxEntry* pEntry = m_aPasswordsLB.GetCurEntry();
if ( pEntry )
{
::rtl::OUString aURL = m_aPasswordsLB.GetEntryText( pEntry, 0 );
::rtl::OUString aUserName = m_aPasswordsLB.GetEntryText( pEntry, 1 );
xPasswdContainer->removePersistent( aURL, aUserName );
m_aPasswordsLB.RemoveEntry( pEntry );
}
}
catch( uno::Exception& )
{}
return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( WebConnectionInfoDialog, RemoveAllPasswordsHdl, PushButton*, EMPTYARG )
{
try
{
uno::Reference< task::XPasswordContainer > xPasswdContainer(
comphelper::getProcessServiceFactory()->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.PasswordContainer" ) ) ),
uno::UNO_QUERY_THROW );
// should the master password be requested before?
xPasswdContainer->removeAllPersistent();
m_aPasswordsLB.Clear();
}
catch( uno::Exception& )
{}
return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( WebConnectionInfoDialog, ChangePasswordHdl, PushButton*, EMPTYARG )
{
try
{
uno::Reference< task::XPasswordContainer > xPasswdContainer(
comphelper::getProcessServiceFactory()->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.PasswordContainer" ) ) ),
uno::UNO_QUERY_THROW );
uno::Reference< task::XInteractionHandler > xInteractionHandler(
comphelper::getProcessServiceFactory()->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.InteractionHandler" ) ) ),
uno::UNO_QUERY_THROW );
SvLBoxEntry* pEntry = m_aPasswordsLB.GetCurEntry();
if ( pEntry )
{
::rtl::OUString aURL = m_aPasswordsLB.GetEntryText( pEntry, 0 );
::rtl::OUString aUserName = m_aPasswordsLB.GetEntryText( pEntry, 1 );
RequestDocumentPassword* pPasswordRequest = new RequestDocumentPassword(
task::PasswordRequestMode_PASSWORD_CREATE,
aURL );
uno::Reference< task::XInteractionRequest > rRequest( pPasswordRequest );
xInteractionHandler->handle( rRequest );
if ( pPasswordRequest->isPassword() )
{
String aNewPass = pPasswordRequest->getPassword();
uno::Sequence< ::rtl::OUString > aPasswd( 1 );
aPasswd[0] = aNewPass;
xPasswdContainer->addPersistent( aURL, aUserName, aPasswd, xInteractionHandler );
}
}
}
catch( uno::Exception& )
{}
return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( WebConnectionInfoDialog, EntrySelectedHdl, void*, EMPTYARG )
{
SvLBoxEntry* pEntry = m_aPasswordsLB.GetCurEntry();
if ( !pEntry )
{
m_aRemoveBtn.Enable( FALSE );
m_aChangeBtn.Enable( FALSE );
}
else
{
m_aRemoveBtn.Enable( TRUE );
m_aChangeBtn.Enable( TRUE );
}
return 0;
}
//........................................................................
} // namespace svx
//........................................................................
<|endoftext|> |
<commit_before>#pragma once
#include <vector>
#include <algorithm>
#include <stdexcept>
namespace helene
{
namespace detail
{
}
template <class T, class Allocator = std::allocator<T>>
class stable_vector
{
typedef std::vector<T, Allocator> vector_type;
public:
typedef typename vector_type::size_type size_type;
public:
size_type
add(const T& value)
{
// check for vacant position
if(erased_.size())
{
const auto vacant_index = erased_.back();
erased_.pop_back();
new(&data_[vacant_index]) T(value);
return vacant_index;
}
const auto new_index = size();
data_.push_back(value);
return new_index;
}
// access with bounds checking
T&
at(size_type index)
{
if(std::find(erased_.begin(), erased_.end(), index) != erased_.end())
{
throw std::out_of_range("access of deleted element");
}
return data_.at(index);
}
// access with bounds checking
const T&
at(size_type index) const
{
if(std::find(erased_.cbegin(), erased_.cend(), index) != erased_.cend())
{
throw std::out_of_range("access of deleted element");
}
return data_.at(index);
}
void
erase(size_type index)
{
(&data_[index])->~T();
erased_.push_back(index);
}
T& operator[](size_type n)
{
return data_[n];
}
size_type
size() const
{
return data_.size() - erased_.size();
}
private:
vector_type data_;
std::vector<size_type, Allocator> erased_;
};
} // namespace helene
<commit_msg>Add const unchecked element access operator[]. modified: include/stable_container.hpp<commit_after>#pragma once
#include <vector>
#include <algorithm>
#include <stdexcept>
namespace helene
{
namespace detail
{
}
template <class T, class Allocator = std::allocator<T>>
class stable_vector
{
typedef std::vector<T, Allocator> vector_type;
public:
typedef typename vector_type::size_type size_type;
public:
size_type
add(const T& value)
{
// check for vacant position
if(erased_.size())
{
const auto vacant_index = erased_.back();
erased_.pop_back();
new(&data_[vacant_index]) T(value);
return vacant_index;
}
const auto new_index = size();
data_.push_back(value);
return new_index;
}
// access with bounds checking
T&
at(size_type index)
{
if(std::find(erased_.begin(), erased_.end(), index) != erased_.end())
{
throw std::out_of_range("access of deleted element");
}
return data_.at(index);
}
// access with bounds checking
const T&
at(size_type index) const
{
if(std::find(erased_.cbegin(), erased_.cend(), index) != erased_.cend())
{
throw std::out_of_range("access of deleted element");
}
return data_.at(index);
}
void
erase(size_type index)
{
(&data_[index])->~T();
erased_.push_back(index);
}
T& operator[](size_type n)
{
return data_[n];
}
const T& operator[](size_type n) const
{
return data_[n];
}
size_type
size() const
{
return data_.size() - erased_.size();
}
private:
vector_type data_;
std::vector<size_type, Allocator> erased_;
};
} // namespace helene
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: dbaexchange.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: fs $ $Date: 2001-03-27 14:38:28 $
*
* 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 EXPRESS 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 _SVX_DBAEXCHANGE_HXX_
#include "dbaexchange.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _COM_SUN_STAR_SDB_COMMANDTYPE_HPP_
#include <com/sun/star/sdb/CommandType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_
#include <com/sun/star/sdb/XSQLQueryComposerFactory.hpp>
#endif
#ifndef _SVX_FMPROP_HRC
#include "fmprop.hrc"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _SOT_FORMATS_HXX
#include <sot/formats.hxx>
#endif
#ifndef _SOT_EXCHANGE_HXX
#include <sot/exchange.hxx>
#endif
//........................................................................
namespace svx
{
//........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::datatransfer;
using namespace ::svxform;
//====================================================================
//= OColumnTransferable
//====================================================================
//--------------------------------------------------------------------
OColumnTransferable::OColumnTransferable(const ::rtl::OUString& _rDatasource, const sal_Int32 _nCommandType,
const ::rtl::OUString& _rCommand, const ::rtl::OUString& _rFieldName, sal_Int32 _nFormats)
:m_nFormatFlags(_nFormats)
{
implConstruct(_rDatasource, _nCommandType, _rCommand, _rFieldName);
}
//--------------------------------------------------------------------
OColumnTransferable::OColumnTransferable(const Reference< XPropertySet >& _rxForm,
const ::rtl::OUString& _rFieldName, sal_Int32 _nFormats)
:m_nFormatFlags(_nFormats)
{
OSL_ENSURE(_rxForm.is(), "OColumnTransferable::OColumnTransferable: invalid form!");
// collect the necessary information from the form
::rtl::OUString sCommand;
sal_Int32 nCommandType = CommandType::TABLE;
::rtl::OUString sDatasource;
sal_Bool bTryToParse = sal_True;
try
{
_rxForm->getPropertyValue(FM_PROP_COMMANDTYPE) >>= nCommandType;
_rxForm->getPropertyValue(FM_PROP_COMMAND) >>= sCommand;
_rxForm->getPropertyValue(FM_PROP_DATASOURCE) >>= sDatasource;
bTryToParse = ::cppu::any2bool(_rxForm->getPropertyValue(FM_PROP_ESCAPE_PROCESSING));
}
catch(Exception&)
{
OSL_ENSURE(sal_False, "OColumnTransferable::OColumnTransferable: could not collect essential data source attributes !");
}
// If the data source is an SQL-statement and simple enough (means "select <field list> from <table> where ....")
// we are able to fake the drag information we are about to create.
if (bTryToParse)
{
try
{
// need a query composer for this
Reference< XSQLQueryComposerFactory > xComposerFac;
_rxForm->getPropertyValue(FM_PROP_ACTIVE_CONNECTION) >>= xComposerFac;
Reference< XSQLQueryComposer > xComposer;
if (xComposerFac.is())
xComposer = xComposerFac->createQueryComposer();
if (xComposer.is())
{
::rtl::OUString sActivaeCommand;
_rxForm->getPropertyValue(FM_PROP_ACTIVECOMMAND) >>= sActivaeCommand;
xComposer->setQuery(sActivaeCommand);
Reference< XTablesSupplier > xSupTab(xComposer, UNO_QUERY);
if(xSupTab.is())
{
Reference< XNameAccess > xNames = xSupTab->getTables();
if (xNames.is())
{
Sequence< ::rtl::OUString > aTables = xNames->getElementNames();
if (1 == aTables.getLength())
{
sCommand = aTables[0];
nCommandType = CommandType::TABLE;
}
}
}
}
}
catch(Exception&)
{
OSL_ENSURE(sal_False, "OColumnTransferable::OColumnTransferable: could not collect essential data source attributes (part two) !");
}
}
implConstruct(sDatasource, nCommandType, sCommand, _rFieldName);
}
//--------------------------------------------------------------------
void OColumnTransferable::implConstruct(const ::rtl::OUString& _rDatasource, const sal_Int32 _nCommandType,
const ::rtl::OUString& _rCommand, const ::rtl::OUString& _rFieldName)
{
const sal_Unicode cSeparator = sal_Unicode(11);
const ::rtl::OUString sSeparator(&cSeparator, 1);
m_sCompatibleFormat = ::rtl::OUString();
m_sCompatibleFormat += _rDatasource;
m_sCompatibleFormat += sSeparator;
m_sCompatibleFormat += _rCommand;
m_sCompatibleFormat += sSeparator;
sal_Unicode cCommandType;
switch (_nCommandType)
{
case CommandType::TABLE:
cCommandType = '0';
break;
case CommandType::QUERY:
cCommandType = '1';
break;
default:
cCommandType = '2';
break;
}
m_sCompatibleFormat += ::rtl::OUString(&cCommandType, 1);
m_sCompatibleFormat += sSeparator;
m_sCompatibleFormat += _rFieldName;
}
//--------------------------------------------------------------------
void OColumnTransferable::AddSupportedFormats()
{
if (CTF_CONTROL_EXCHANGE & m_nFormatFlags)
AddFormat(SOT_FORMATSTR_ID_SBA_CTRLDATAEXCHANGE);
if (CTF_FIELD_DESCRIPTOR & m_nFormatFlags)
AddFormat(SOT_FORMATSTR_ID_SBA_FIELDDATAEXCHANGE);
}
//--------------------------------------------------------------------
sal_Bool OColumnTransferable::GetData( const DataFlavor& _rFlavor )
{
switch (SotExchange::GetFormat(_rFlavor))
{
case SOT_FORMATSTR_ID_SBA_FIELDDATAEXCHANGE:
case SOT_FORMATSTR_ID_SBA_CTRLDATAEXCHANGE:
return SetString(m_sCompatibleFormat, _rFlavor);
}
return sal_False;
}
//--------------------------------------------------------------------
sal_Bool OColumnTransferable::canExtractColumnDescriptor(const DataFlavorExVector& _rFlavors, sal_Int32 _nFormats)
{
sal_Bool bFieldFormat = 0 != (_nFormats & CTF_FIELD_DESCRIPTOR);
sal_Bool bControlFormat = 0 != (_nFormats & CTF_CONTROL_EXCHANGE);
for ( DataFlavorExVector::const_iterator aCheck = _rFlavors.begin();
aCheck != _rFlavors.end();
++aCheck
)
{
if (bFieldFormat && (SOT_FORMATSTR_ID_SBA_FIELDDATAEXCHANGE == aCheck->mnSotId))
return sal_True;
if (bControlFormat && (SOT_FORMATSTR_ID_SBA_CTRLDATAEXCHANGE == aCheck->mnSotId))
return sal_True;
}
return sal_False;
}
//--------------------------------------------------------------------
sal_Bool OColumnTransferable::extractColumnDescriptor(const TransferableDataHelper& _rData,
::rtl::OUString& _rDatasource, sal_Int32& _nCommandType, ::rtl::OUString& _rCommand, ::rtl::OUString& _rFieldName)
{
// check if we have a format we can use ....
SotFormatStringId nRecognizedFormat = 0;
if (_rData.HasFormat(SOT_FORMATSTR_ID_SBA_FIELDDATAEXCHANGE))
nRecognizedFormat = SOT_FORMATSTR_ID_SBA_FIELDDATAEXCHANGE;
if (_rData.HasFormat(SOT_FORMATSTR_ID_SBA_CTRLDATAEXCHANGE))
nRecognizedFormat = SOT_FORMATSTR_ID_SBA_CTRLDATAEXCHANGE;
if (!nRecognizedFormat)
return sal_False;
String sFieldDescription;
const_cast<TransferableDataHelper&>(_rData).GetString(nRecognizedFormat, sFieldDescription);
const sal_Unicode cSeparator = sal_Unicode(11);
_rDatasource = sFieldDescription.GetToken(0, cSeparator);
_rCommand = sFieldDescription.GetToken(1, cSeparator);
_nCommandType = sFieldDescription.GetToken(2, cSeparator).ToInt32();
_rFieldName = sFieldDescription.GetToken(3, cSeparator);
return sal_True;
}
//====================================================================
//= ORowsetTransferable
//====================================================================
//--------------------------------------------------------------------
// ORowsetTransferable::ORowsetTransferable(const String& _rDatasource, const String& _rName,
// ObjectType _eObject, const IntArray* _pSelectionList)
// {
// }
//........................................................................
} // namespace svx
//........................................................................
/*************************************************************************
* history:
* $Log: not supported by cvs2svn $
* Revision 1.1 2001/03/26 15:05:04 fs
* initial checkin - helper classes for data access related DnD
*
*
* Revision 1.0 23.03.01 12:59:54 fs
************************************************************************/
<commit_msg>added a data access descriptor format<commit_after>/*************************************************************************
*
* $RCSfile: dbaexchange.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: fs $ $Date: 2001-04-11 12:40:59 $
*
* 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 EXPRESS 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 _SVX_DBAEXCHANGE_HXX_
#include "dbaexchange.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _COM_SUN_STAR_SDB_COMMANDTYPE_HPP_
#include <com/sun/star/sdb/CommandType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_
#include <com/sun/star/sdb/XSQLQueryComposerFactory.hpp>
#endif
#ifndef _SVX_FMPROP_HRC
#include "fmprop.hrc"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _SOT_FORMATS_HXX
#include <sot/formats.hxx>
#endif
#ifndef _SOT_EXCHANGE_HXX
#include <sot/exchange.hxx>
#endif
#ifndef _COMPHELPER_PROPERTSETINFO_HXX_
#include <comphelper/propertysetinfo.hxx>
#endif
//........................................................................
namespace svx
{
//........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::datatransfer;
using namespace ::svxform;
using namespace ::comphelper;
//====================================================================
//= OColumnTransferable
//====================================================================
//--------------------------------------------------------------------
OColumnTransferable::OColumnTransferable(const ::rtl::OUString& _rDatasource, const sal_Int32 _nCommandType,
const ::rtl::OUString& _rCommand, const ::rtl::OUString& _rFieldName, sal_Int32 _nFormats)
:m_nFormatFlags(_nFormats)
{
implConstruct(_rDatasource, _nCommandType, _rCommand, _rFieldName);
}
//--------------------------------------------------------------------
OColumnTransferable::OColumnTransferable(const Reference< XPropertySet >& _rxForm,
const ::rtl::OUString& _rFieldName, const Reference< XPropertySet >& _rxColumn, sal_Int32 _nFormats)
:m_nFormatFlags(_nFormats)
{
OSL_ENSURE(_rxForm.is(), "OColumnTransferable::OColumnTransferable: invalid form!");
// collect the necessary information from the form
::rtl::OUString sCommand;
sal_Int32 nCommandType = CommandType::TABLE;
::rtl::OUString sDatasource;
sal_Bool bTryToParse = sal_True;
try
{
_rxForm->getPropertyValue(FM_PROP_COMMANDTYPE) >>= nCommandType;
_rxForm->getPropertyValue(FM_PROP_COMMAND) >>= sCommand;
_rxForm->getPropertyValue(FM_PROP_DATASOURCE) >>= sDatasource;
bTryToParse = ::cppu::any2bool(_rxForm->getPropertyValue(FM_PROP_ESCAPE_PROCESSING));
}
catch(Exception&)
{
OSL_ENSURE(sal_False, "OColumnTransferable::OColumnTransferable: could not collect essential data source attributes !");
}
// If the data source is an SQL-statement and simple enough (means "select <field list> from <table> where ....")
// we are able to fake the drag information we are about to create.
if (bTryToParse)
{
try
{
// need a query composer for this
Reference< XSQLQueryComposerFactory > xComposerFac;
_rxForm->getPropertyValue(FM_PROP_ACTIVE_CONNECTION) >>= xComposerFac;
Reference< XSQLQueryComposer > xComposer;
if (xComposerFac.is())
xComposer = xComposerFac->createQueryComposer();
if (xComposer.is())
{
::rtl::OUString sActivaeCommand;
_rxForm->getPropertyValue(FM_PROP_ACTIVECOMMAND) >>= sActivaeCommand;
xComposer->setQuery(sActivaeCommand);
Reference< XTablesSupplier > xSupTab(xComposer, UNO_QUERY);
if(xSupTab.is())
{
Reference< XNameAccess > xNames = xSupTab->getTables();
if (xNames.is())
{
Sequence< ::rtl::OUString > aTables = xNames->getElementNames();
if (1 == aTables.getLength())
{
sCommand = aTables[0];
nCommandType = CommandType::TABLE;
}
}
}
}
}
catch(Exception&)
{
OSL_ENSURE(sal_False, "OColumnTransferable::OColumnTransferable: could not collect essential data source attributes (part two) !");
}
}
implConstruct(sDatasource, nCommandType, sCommand, _rFieldName);
if (_rxColumn.is() && ((m_nFormatFlags & CTF_COLUMN_DESCRIPTOR) == CTF_COLUMN_DESCRIPTOR))
m_aDescriptor[daColumnObject] <<= _rxColumn;
}
//--------------------------------------------------------------------
sal_uInt32 OColumnTransferable::getDescriptorFormatId()
{
static sal_uInt32 s_nFormat = (sal_uInt32)-1;
if ((sal_uInt32)-1 == s_nFormat)
{
s_nFormat = SotExchange::RegisterFormatName(String::CreateFromAscii("svxform.ColumnDescriptorTransfer"));
OSL_ENSURE((sal_uInt32)-1 != s_nFormat, "OColumnTransferable::getDescriptorFormatId: bad exchange id!");
}
return s_nFormat;
}
//--------------------------------------------------------------------
void OColumnTransferable::implConstruct(const ::rtl::OUString& _rDatasource, const sal_Int32 _nCommandType,
const ::rtl::OUString& _rCommand, const ::rtl::OUString& _rFieldName)
{
const sal_Unicode cSeparator = sal_Unicode(11);
const ::rtl::OUString sSeparator(&cSeparator, 1);
m_sCompatibleFormat = ::rtl::OUString();
m_sCompatibleFormat += _rDatasource;
m_sCompatibleFormat += sSeparator;
m_sCompatibleFormat += _rCommand;
m_sCompatibleFormat += sSeparator;
sal_Unicode cCommandType;
switch (_nCommandType)
{
case CommandType::TABLE:
cCommandType = '0';
break;
case CommandType::QUERY:
cCommandType = '1';
break;
default:
cCommandType = '2';
break;
}
m_sCompatibleFormat += ::rtl::OUString(&cCommandType, 1);
m_sCompatibleFormat += sSeparator;
m_sCompatibleFormat += _rFieldName;
m_aDescriptor.clear();
if ((m_nFormatFlags & CTF_COLUMN_DESCRIPTOR) == CTF_COLUMN_DESCRIPTOR)
{
m_aDescriptor[daDataSource] <<= _rDatasource;
m_aDescriptor[daCommand] <<= _rCommand;
m_aDescriptor[daCommandType] <<= _nCommandType;
m_aDescriptor[daColumnName] <<= _rFieldName;
}
}
//--------------------------------------------------------------------
void OColumnTransferable::AddSupportedFormats()
{
if (CTF_CONTROL_EXCHANGE & m_nFormatFlags)
AddFormat(SOT_FORMATSTR_ID_SBA_CTRLDATAEXCHANGE);
if (CTF_FIELD_DESCRIPTOR & m_nFormatFlags)
AddFormat(SOT_FORMATSTR_ID_SBA_FIELDDATAEXCHANGE);
if (CTF_COLUMN_DESCRIPTOR & m_nFormatFlags)
AddFormat(getDescriptorFormatId());
}
//--------------------------------------------------------------------
sal_Bool OColumnTransferable::GetData( const DataFlavor& _rFlavor )
{
const sal_uInt32 nFormatId = SotExchange::GetFormat(_rFlavor);
switch (nFormatId)
{
case SOT_FORMATSTR_ID_SBA_FIELDDATAEXCHANGE:
case SOT_FORMATSTR_ID_SBA_CTRLDATAEXCHANGE:
return SetString(m_sCompatibleFormat, _rFlavor);
}
if (nFormatId == getDescriptorFormatId())
return SetAny( makeAny( m_aDescriptor.createPropertyValueSequence() ), _rFlavor );
return sal_False;
}
//--------------------------------------------------------------------
sal_Bool OColumnTransferable::canExtractColumnDescriptor(const DataFlavorExVector& _rFlavors, sal_Int32 _nFormats)
{
sal_Bool bFieldFormat = 0 != (_nFormats & CTF_FIELD_DESCRIPTOR);
sal_Bool bControlFormat = 0 != (_nFormats & CTF_CONTROL_EXCHANGE);
sal_Bool bDescriptorFormat = 0 != (_nFormats & CTF_COLUMN_DESCRIPTOR);
for ( DataFlavorExVector::const_iterator aCheck = _rFlavors.begin();
aCheck != _rFlavors.end();
++aCheck
)
{
if (bFieldFormat && (SOT_FORMATSTR_ID_SBA_FIELDDATAEXCHANGE == aCheck->mnSotId))
return sal_True;
if (bControlFormat && (SOT_FORMATSTR_ID_SBA_CTRLDATAEXCHANGE == aCheck->mnSotId))
return sal_True;
if (bDescriptorFormat && (getDescriptorFormatId() == aCheck->mnSotId))
return sal_True;
}
return sal_False;
}
//--------------------------------------------------------------------
ODataAccessDescriptor OColumnTransferable::extractColumnDescriptor(const TransferableDataHelper& _rData)
{
if (_rData.HasFormat(getDescriptorFormatId()))
{
// the object has a real descriptor object (not just the old compatible format)
// extract the any from the transferable
DataFlavor aFlavor;
#ifdef _DEBUG
sal_Bool bSuccess =
#endif
SotExchange::GetFormatDataFlavor(getDescriptorFormatId(), aFlavor);
OSL_ENSURE(bSuccess, "OColumnTransferable::extractColumnDescriptor: invalid data format (no flavor)!");
Any aDescriptor = _rData.GetAny(aFlavor);
// extract the property value sequence
Sequence< PropertyValue > aDescriptorProps;
#ifdef _DEBUG
bSuccess =
#endif
aDescriptor >>= aDescriptorProps;
OSL_ENSURE(bSuccess, "OColumnTransferable::extractColumnDescriptor: invalid clipboard format!");
// build the real descriptor
return ODataAccessDescriptor(aDescriptorProps);
}
// only the old (compatible) format exists -> use the other extract method ...
::rtl::OUString sDatasource, sCommand, sFieldName;
sal_Int32 nCommandType = CommandType::COMMAND;
ODataAccessDescriptor aDescriptor;
if (extractColumnDescriptor(_rData, sDatasource, nCommandType, sCommand, sFieldName))
{
// and build an own descriptor
aDescriptor[daDataSource] <<= sDatasource;
aDescriptor[daCommand] <<= sCommand;
aDescriptor[daCommandType] <<= nCommandType;
aDescriptor[daColumnName] <<= sFieldName;
}
return aDescriptor;
}
//--------------------------------------------------------------------
sal_Bool OColumnTransferable::extractColumnDescriptor(const TransferableDataHelper& _rData,
::rtl::OUString& _rDatasource, sal_Int32& _nCommandType, ::rtl::OUString& _rCommand, ::rtl::OUString& _rFieldName)
{
if (_rData.HasFormat(getDescriptorFormatId()))
{
ODataAccessDescriptor aDescriptor = extractColumnDescriptor(_rData);
aDescriptor[daDataSource] >>= _rDatasource;
aDescriptor[daCommand] >>= _rCommand;
aDescriptor[daCommandType] >>= _nCommandType;
aDescriptor[daColumnName] >>= _rFieldName;
return sal_True;
}
// check if we have a (string) format we can use ....
SotFormatStringId nRecognizedFormat = 0;
if (_rData.HasFormat(SOT_FORMATSTR_ID_SBA_FIELDDATAEXCHANGE))
nRecognizedFormat = SOT_FORMATSTR_ID_SBA_FIELDDATAEXCHANGE;
if (_rData.HasFormat(SOT_FORMATSTR_ID_SBA_CTRLDATAEXCHANGE))
nRecognizedFormat = SOT_FORMATSTR_ID_SBA_CTRLDATAEXCHANGE;
if (!nRecognizedFormat)
return sal_False;
String sFieldDescription;
const_cast<TransferableDataHelper&>(_rData).GetString(nRecognizedFormat, sFieldDescription);
const sal_Unicode cSeparator = sal_Unicode(11);
_rDatasource = sFieldDescription.GetToken(0, cSeparator);
_rCommand = sFieldDescription.GetToken(1, cSeparator);
_nCommandType = sFieldDescription.GetToken(2, cSeparator).ToInt32();
_rFieldName = sFieldDescription.GetToken(3, cSeparator);
return sal_True;
}
//====================================================================
//= ORowsetTransferable
//====================================================================
//--------------------------------------------------------------------
// ORowsetTransferable::ORowsetTransferable(const String& _rDatasource, const String& _rName,
// ObjectType _eObject, const IntArray* _pSelectionList)
// {
// }
//........................................................................
} // namespace svx
//........................................................................
/*************************************************************************
* history:
* $Log: not supported by cvs2svn $
* Revision 1.2 2001/03/27 14:38:28 fs
* swap the order in which the clipboard formats are added
*
* Revision 1.1 2001/03/26 15:05:04 fs
* initial checkin - helper classes for data access related DnD
*
*
* Revision 1.0 23.03.01 12:59:54 fs
************************************************************************/
<|endoftext|> |
<commit_before>#pragma once
#include <staticjson/error.hpp>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <unordered_map>
namespace staticjson
{
struct NonMobile
{
NonMobile() {}
~NonMobile() {}
NonMobile(const NonMobile&) = delete;
NonMobile(NonMobile&&) = delete;
NonMobile& operator=(const NonMobile&) = delete;
NonMobile& operator=(NonMobile&&) = delete;
};
typedef unsigned int SizeType;
class IHandler
{
public:
IHandler() {}
virtual ~IHandler();
virtual bool Null() = 0;
virtual bool Bool(bool) = 0;
virtual bool Int(int) = 0;
virtual bool Uint(unsigned) = 0;
virtual bool Int64(std::int64_t) = 0;
virtual bool Uint64(std::uint64_t) = 0;
virtual bool Double(double) = 0;
virtual bool String(const char*, SizeType, bool) = 0;
virtual bool StartObject() = 0;
virtual bool Key(const char*, SizeType, bool) = 0;
virtual bool EndObject(SizeType) = 0;
virtual bool StartArray() = 0;
virtual bool EndArray(SizeType) = 0;
virtual bool RawNumber() { return true; }
virtual void prepare_for_reuse() = 0;
};
class NullableHandler;
class BaseHandler : public IHandler, private NonMobile
{
friend class NullableHandler;
protected:
std::unique_ptr<ErrorBase> the_error;
bool parsed = false;
protected:
bool set_out_of_range(const char* actual_type);
bool set_type_mismatch(const char* actual_type);
virtual void reset() {}
public:
BaseHandler() {}
virtual ~BaseHandler();
virtual std::string type_name() const = 0;
virtual bool Null() override { return set_type_mismatch("null"); }
virtual bool Bool(bool) override { return set_type_mismatch("bool"); }
virtual bool Int(int) override { return set_type_mismatch("int"); }
virtual bool Uint(unsigned) override { return set_type_mismatch("unsigned"); }
virtual bool Int64(std::int64_t) override { return set_type_mismatch("int64_t"); }
virtual bool Uint64(std::uint64_t) override { return set_type_mismatch("uint64_t"); }
virtual bool Double(double) override { return set_type_mismatch("double"); }
virtual bool String(const char*, SizeType, bool) override
{
return set_type_mismatch("string");
}
virtual bool StartObject() override { return set_type_mismatch("object"); }
virtual bool Key(const char*, SizeType, bool) override { return set_type_mismatch("object"); }
virtual bool EndObject(SizeType) override { return set_type_mismatch("object"); }
virtual bool StartArray() override { return set_type_mismatch("array"); }
virtual bool EndArray(SizeType) override { return set_type_mismatch("array"); }
virtual bool has_error() const { return bool(the_error); }
virtual bool reap_error(ErrorStack& errs)
{
if (!the_error)
return false;
errs.push(the_error.release());
return true;
}
bool is_parsed() const { return parsed; }
void prepare_for_reuse() override
{
the_error.reset();
parsed = false;
reset();
}
virtual bool write(IHandler* output) const = 0;
};
struct Flags
{
static const unsigned Default = 0x0, AllowDuplicateKey = 0x1, Optional = 0x2, IgnoreRead = 0x4,
IgnoreWrite = 0x8, DisallowUnknownKey = 0x16;
};
// Forward declaration
template <class T>
class Handler;
class ObjectHandler : public BaseHandler
{
protected:
struct FlaggedHandler
{
std::unique_ptr<BaseHandler> handler;
unsigned flags;
};
protected:
std::unordered_map<std::string, FlaggedHandler> internals;
FlaggedHandler* current = nullptr;
std::string current_name;
int depth = 0;
unsigned flags = Flags::Default;
protected:
bool precheck(const char* type);
bool postcheck(bool success);
void set_missing_required(const std::string& name);
void reset() override;
public:
ObjectHandler();
~ObjectHandler();
std::string type_name() const override;
virtual bool Null() override;
virtual bool Bool(bool) override;
virtual bool Int(int) override;
virtual bool Uint(unsigned) override;
virtual bool Int64(std::int64_t) override;
virtual bool Uint64(std::uint64_t) override;
virtual bool Double(double) override;
virtual bool String(const char*, SizeType, bool) override;
virtual bool StartObject() override;
virtual bool Key(const char*, SizeType, bool) override;
virtual bool EndObject(SizeType) override;
virtual bool StartArray() override;
virtual bool EndArray(SizeType) override;
virtual bool reap_error(ErrorStack&) override;
virtual bool write(IHandler* output) const override;
unsigned get_flags() const { return flags; }
void set_flags(unsigned f) { flags = f; }
template <class T>
void add_property(const std::string& name, T* pointer, unsigned flags_ = Flags::Default)
{
FlaggedHandler fh;
fh.handler.reset(new Handler<T>(pointer));
fh.flags = flags_;
internals.emplace(name, std::move(fh));
}
};
template <class T>
class Handler : public ObjectHandler
{
public:
explicit Handler(T* t) { t->staticjson_init(this); }
};
}<commit_msg>Use map instead of hash map<commit_after>#pragma once
#include <staticjson/error.hpp>
#include <cstddef>
#include <cstdint>
#include <map>
#include <memory>
namespace staticjson
{
struct NonMobile
{
NonMobile() {}
~NonMobile() {}
NonMobile(const NonMobile&) = delete;
NonMobile(NonMobile&&) = delete;
NonMobile& operator=(const NonMobile&) = delete;
NonMobile& operator=(NonMobile&&) = delete;
};
typedef unsigned int SizeType;
class IHandler
{
public:
IHandler() {}
virtual ~IHandler();
virtual bool Null() = 0;
virtual bool Bool(bool) = 0;
virtual bool Int(int) = 0;
virtual bool Uint(unsigned) = 0;
virtual bool Int64(std::int64_t) = 0;
virtual bool Uint64(std::uint64_t) = 0;
virtual bool Double(double) = 0;
virtual bool String(const char*, SizeType, bool) = 0;
virtual bool StartObject() = 0;
virtual bool Key(const char*, SizeType, bool) = 0;
virtual bool EndObject(SizeType) = 0;
virtual bool StartArray() = 0;
virtual bool EndArray(SizeType) = 0;
virtual bool RawNumber() { return true; }
virtual void prepare_for_reuse() = 0;
};
class NullableHandler;
class BaseHandler : public IHandler, private NonMobile
{
friend class NullableHandler;
protected:
std::unique_ptr<ErrorBase> the_error;
bool parsed = false;
protected:
bool set_out_of_range(const char* actual_type);
bool set_type_mismatch(const char* actual_type);
virtual void reset() {}
public:
BaseHandler() {}
virtual ~BaseHandler();
virtual std::string type_name() const = 0;
virtual bool Null() override { return set_type_mismatch("null"); }
virtual bool Bool(bool) override { return set_type_mismatch("bool"); }
virtual bool Int(int) override { return set_type_mismatch("int"); }
virtual bool Uint(unsigned) override { return set_type_mismatch("unsigned"); }
virtual bool Int64(std::int64_t) override { return set_type_mismatch("int64_t"); }
virtual bool Uint64(std::uint64_t) override { return set_type_mismatch("uint64_t"); }
virtual bool Double(double) override { return set_type_mismatch("double"); }
virtual bool String(const char*, SizeType, bool) override
{
return set_type_mismatch("string");
}
virtual bool StartObject() override { return set_type_mismatch("object"); }
virtual bool Key(const char*, SizeType, bool) override { return set_type_mismatch("object"); }
virtual bool EndObject(SizeType) override { return set_type_mismatch("object"); }
virtual bool StartArray() override { return set_type_mismatch("array"); }
virtual bool EndArray(SizeType) override { return set_type_mismatch("array"); }
virtual bool has_error() const { return bool(the_error); }
virtual bool reap_error(ErrorStack& errs)
{
if (!the_error)
return false;
errs.push(the_error.release());
return true;
}
bool is_parsed() const { return parsed; }
void prepare_for_reuse() override
{
the_error.reset();
parsed = false;
reset();
}
virtual bool write(IHandler* output) const = 0;
};
struct Flags
{
static const unsigned Default = 0x0, AllowDuplicateKey = 0x1, Optional = 0x2, IgnoreRead = 0x4,
IgnoreWrite = 0x8, DisallowUnknownKey = 0x16;
};
// Forward declaration
template <class T>
class Handler;
class ObjectHandler : public BaseHandler
{
protected:
struct FlaggedHandler
{
std::unique_ptr<BaseHandler> handler;
unsigned flags;
};
protected:
std::map<std::string, FlaggedHandler> internals;
FlaggedHandler* current = nullptr;
std::string current_name;
int depth = 0;
unsigned flags = Flags::Default;
protected:
bool precheck(const char* type);
bool postcheck(bool success);
void set_missing_required(const std::string& name);
void reset() override;
public:
ObjectHandler();
~ObjectHandler();
std::string type_name() const override;
virtual bool Null() override;
virtual bool Bool(bool) override;
virtual bool Int(int) override;
virtual bool Uint(unsigned) override;
virtual bool Int64(std::int64_t) override;
virtual bool Uint64(std::uint64_t) override;
virtual bool Double(double) override;
virtual bool String(const char*, SizeType, bool) override;
virtual bool StartObject() override;
virtual bool Key(const char*, SizeType, bool) override;
virtual bool EndObject(SizeType) override;
virtual bool StartArray() override;
virtual bool EndArray(SizeType) override;
virtual bool reap_error(ErrorStack&) override;
virtual bool write(IHandler* output) const override;
unsigned get_flags() const { return flags; }
void set_flags(unsigned f) { flags = f; }
template <class T>
void add_property(const std::string& name, T* pointer, unsigned flags_ = Flags::Default)
{
FlaggedHandler fh;
fh.handler.reset(new Handler<T>(pointer));
fh.flags = flags_;
internals.emplace(name, std::move(fh));
}
};
template <class T>
class Handler : public ObjectHandler
{
public:
explicit Handler(T* t) { t->staticjson_init(this); }
};
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: codegen.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-03-29 11:48: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): _______________________________________
*
*
************************************************************************/
#include <svtools/sbx.hxx>
#include "sbcomp.hxx"
#pragma hdrstop
#include "image.hxx"
// nInc ist die Inkrementgroesse der Puffer
SbiCodeGen::SbiCodeGen( SbModule& r, SbiParser* p, short nInc )
: rMod( r ), aCode( p, nInc )
{
pParser = p;
bStmnt = FALSE;
nLine = 0;
nCol = 0;
nForLevel = 0;
}
USHORT SbiCodeGen::GetPC()
{
return aCode.GetSize();
}
// Statement merken
void SbiCodeGen::Statement()
{
bStmnt = TRUE;
nLine = pParser->GetLine();
nCol = pParser->GetCol1();
// #29955 Information der for-Schleifen-Ebene
// in oberen Byte der Spalte speichern
nCol = (nCol & 0xff) + 0x100 * nForLevel;
}
// Anfang eines Statements markieren
void SbiCodeGen::GenStmnt()
{
if( bStmnt )
{
bStmnt = FALSE;
Gen( _STMNT, nLine, nCol );
}
}
// Die Gen-Routinen returnen den Offset des 1. Operanden,
// damit Jumps dort ihr Backchain versenken koennen
USHORT SbiCodeGen::Gen( SbiOpcode eOpcode )
{
#ifndef PRODUCT
if( eOpcode < SbOP0_START || eOpcode > SbOP0_END )
pParser->Error( SbERR_INTERNAL_ERROR, "OPCODE1" );
#endif
GenStmnt();
aCode += (UINT8) eOpcode;
return GetPC();
}
USHORT SbiCodeGen::Gen( SbiOpcode eOpcode, UINT16 nOpnd )
{
#ifndef PRODUCT
if( eOpcode < SbOP1_START || eOpcode > SbOP1_END )
pParser->Error( SbERR_INTERNAL_ERROR, "OPCODE2" );
#endif
GenStmnt();
aCode += (UINT8) eOpcode;
USHORT n = GetPC();
aCode += nOpnd;
return n;
}
USHORT SbiCodeGen::Gen( SbiOpcode eOpcode, UINT16 nOpnd1, UINT16 nOpnd2 )
{
#ifndef PRODUCT
if( eOpcode < SbOP2_START || eOpcode > SbOP2_END )
pParser->Error( SbERR_INTERNAL_ERROR, "OPCODE3" );
#endif
GenStmnt();
aCode += (UINT8) eOpcode;
USHORT n = GetPC();
aCode += nOpnd1;
aCode += nOpnd2;
return n;
}
// Abspeichern des erzeugten Images im Modul
void SbiCodeGen::Save()
{
SbiImage* p = new SbiImage;
if( !p )
{
SbERR_NO_MEMORY; return;
}
rMod.StartDefinitions();
// OPTION BASE-Wert:
p->nDimBase = pParser->nBase;
// OPTION EXPLICIT-Flag uebernehmen
if( pParser->bExplicit )
p->SetFlag( SBIMG_EXPLICIT );
int nIfaceCount = 0;
if( pParser->bClassModule )
{
p->SetFlag( SBIMG_CLASSMODULE );
pCLASSFAC->AddClassModule( &rMod );
nIfaceCount = pParser->aIfaceVector.size();
if( nIfaceCount )
{
if( !rMod.pClassData )
rMod.pClassData = new SbClassData;
for( int i = 0 ; i < nIfaceCount ; i++ )
{
const String& rIfaceName = pParser->aIfaceVector[i];
SbxVariable* pIfaceVar = new SbxVariable( SbxVARIANT );
pIfaceVar->SetName( rIfaceName );
SbxArray* pIfaces = rMod.pClassData->mxIfaces;
pIfaces->Insert( pIfaceVar, pIfaces->Count() );
}
}
}
else
{
pCLASSFAC->RemoveClassModule( &rMod );
}
if( pParser->bText )
p->SetFlag( SBIMG_COMPARETEXT );
// GlobalCode-Flag
if( pParser->HasGlobalCode() )
p->SetFlag( SBIMG_INITCODE );
// Die Entrypoints:
for( SbiSymDef* pDef = pParser->aPublics.First(); pDef;
pDef = pParser->aPublics.Next() )
{
SbiProcDef* pProc = pDef->GetProcDef();
if( pProc && pProc->IsDefined() )
{
String aProcName = pProc->GetName();
String aIfaceProcName;
String aIfaceName;
USHORT nPassCount = 1;
if( nIfaceCount )
{
int nPropPrefixFound =
aProcName.Search( String( RTL_CONSTASCII_USTRINGPARAM("Property ") ) );
String aPureProcName = aProcName;
String aPropPrefix;
if( nPropPrefixFound == 0 )
{
aPropPrefix = aProcName.Copy( 0, 13 ); // 13 == Len( "Property ?et " )
aPureProcName = aProcName.Copy( 13 );
}
for( int i = 0 ; i < nIfaceCount ; i++ )
{
const String& rIfaceName = pParser->aIfaceVector[i];
int nFound = aPureProcName.Search( rIfaceName );
if( nFound == 0 && '_' == aPureProcName.GetChar( rIfaceName.Len() ) )
{
if( nPropPrefixFound == 0 )
aIfaceProcName += aPropPrefix;
aIfaceProcName += aPureProcName.Copy( rIfaceName.Len() + 1 );
aIfaceName = rIfaceName;
nPassCount = 2;
break;
}
}
}
SbMethod* pMeth;
for( USHORT nPass = 0 ; nPass < nPassCount ; nPass++ )
{
if( nPass == 1 )
aProcName = aIfaceProcName;
PropertyMode ePropMode = pProc->getPropertyMode();
if( ePropMode != PROPERTY_MODE_NONE )
{
SbxDataType ePropType;
switch( ePropMode )
{
case PROPERTY_MODE_GET:
ePropType = pProc->GetType();
break;
case PROPERTY_MODE_LET:
{
// type == type of first parameter
ePropType = SbxVARIANT; // Default
SbiSymPool* pPool = &pProc->GetParams();
if( pPool->GetSize() > 1 )
{
SbiSymDef* pPar = pPool->Get( 1 );
if( pPar )
ePropType = pPar->GetType();
}
break;
}
case PROPERTY_MODE_SET:
ePropType = SbxOBJECT;
break;
}
String aPropName = pProc->GetPropName();
if( nPass == 1 )
aPropName = aPropName.Copy( aIfaceName.Len() + 1 );
SbProcedureProperty* pProcedureProperty =
rMod.GetProcedureProperty( aPropName, ePropType );
// rMod.GetProcedureProperty( pProc->GetPropName(), ePropType );
}
if( nPass == 1 )
{
SbIfaceMapperMethod* pMapperMeth =
rMod.GetIfaceMapperMethod( aProcName, pMeth );
}
else
{
pMeth = rMod.GetMethod( aProcName, pProc->GetType() );
// #110004
if( !pProc->IsPublic() )
pMeth->SetFlag( SBX_PRIVATE );
pMeth->nStart = pProc->GetAddr();
pMeth->nLine1 = pProc->GetLine1();
pMeth->nLine2 = pProc->GetLine2();
// Die Parameter:
SbxInfo* pInfo = pMeth->GetInfo();
String aHelpFile, aComment;
ULONG nHelpId = 0;
if( pInfo )
{
// Die Zusatzdaten retten
aHelpFile = pInfo->GetHelpFile();
aComment = pInfo->GetComment();
nHelpId = pInfo->GetHelpId();
}
// Und die Parameterliste neu aufbauen
pInfo = new SbxInfo( aHelpFile, nHelpId );
pInfo->SetComment( aComment );
SbiSymPool* pPool = &pProc->GetParams();
// Das erste Element ist immer der Funktionswert!
for( USHORT i = 1; i < pPool->GetSize(); i++ )
{
SbiSymDef* pPar = pPool->Get( i );
SbxDataType t = pPar->GetType();
if( !pPar->IsByVal() )
t = (SbxDataType) ( t | SbxBYREF );
if( pPar->GetDims() )
t = (SbxDataType) ( t | SbxARRAY );
// #33677 Optional-Info durchreichen
USHORT nFlags = SBX_READ;
if( pPar->IsOptional() )
nFlags |= SBX_OPTIONAL;
pInfo->AddParam( pPar->GetName(), t, nFlags );
UINT32 nUserData = 0;
USHORT nDefaultId = pPar->GetDefaultId();
if( nDefaultId )
nUserData |= nDefaultId;
if( pPar->IsParamArray() )
nUserData |= PARAM_INFO_PARAMARRAY;
if( nUserData )
{
SbxParamInfo* pParam = (SbxParamInfo*)pInfo->GetParam( i );
pParam->nUserData = nUserData;
}
}
pMeth->SetInfo( pInfo );
}
} // for( iPass...
}
}
// Der Code
p->AddCode( aCode.GetBuffer(), aCode.GetSize() );
// Der globale StringPool. 0 ist nicht belegt.
SbiStringPool* pPool = &pParser->aGblStrings;
USHORT nSize = pPool->GetSize();
p->MakeStrings( nSize );
USHORT i;
for( i = 1; i <= nSize; i++ )
p->AddString( pPool->Find( i ) );
// Typen einfuegen
USHORT nCount = pParser->rTypeArray->Count();
for (i = 0; i < nCount; i++)
p->AddType((SbxObject *)pParser->rTypeArray->Get(i));
// Insert enum objects
nCount = pParser->rEnumArray->Count();
for (i = 0; i < nCount; i++)
p->AddEnum((SbxObject *)pParser->rEnumArray->Get(i));
if( !p->IsError() )
rMod.pImage = p;
else
delete p;
rMod.EndDefinitions();
}
<commit_msg>INTEGRATION: CWS visibility03 (1.6.8); FILE MERGED 2005/04/06 15:23:45 mhu 1.6.8.2: RESYNC: (1.6-1.7); FILE MERGED 2005/03/24 18:01:17 mhu 1.6.8.1: #i45006# Adapted to moved sbx headers.<commit_after>/*************************************************************************
*
* $RCSfile: codegen.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2005-04-13 09:10:55 $
*
* 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 <sbx.hxx>
#include "sbcomp.hxx"
#pragma hdrstop
#include "image.hxx"
// nInc ist die Inkrementgroesse der Puffer
SbiCodeGen::SbiCodeGen( SbModule& r, SbiParser* p, short nInc )
: rMod( r ), aCode( p, nInc )
{
pParser = p;
bStmnt = FALSE;
nLine = 0;
nCol = 0;
nForLevel = 0;
}
USHORT SbiCodeGen::GetPC()
{
return aCode.GetSize();
}
// Statement merken
void SbiCodeGen::Statement()
{
bStmnt = TRUE;
nLine = pParser->GetLine();
nCol = pParser->GetCol1();
// #29955 Information der for-Schleifen-Ebene
// in oberen Byte der Spalte speichern
nCol = (nCol & 0xff) + 0x100 * nForLevel;
}
// Anfang eines Statements markieren
void SbiCodeGen::GenStmnt()
{
if( bStmnt )
{
bStmnt = FALSE;
Gen( _STMNT, nLine, nCol );
}
}
// Die Gen-Routinen returnen den Offset des 1. Operanden,
// damit Jumps dort ihr Backchain versenken koennen
USHORT SbiCodeGen::Gen( SbiOpcode eOpcode )
{
#ifndef PRODUCT
if( eOpcode < SbOP0_START || eOpcode > SbOP0_END )
pParser->Error( SbERR_INTERNAL_ERROR, "OPCODE1" );
#endif
GenStmnt();
aCode += (UINT8) eOpcode;
return GetPC();
}
USHORT SbiCodeGen::Gen( SbiOpcode eOpcode, UINT16 nOpnd )
{
#ifndef PRODUCT
if( eOpcode < SbOP1_START || eOpcode > SbOP1_END )
pParser->Error( SbERR_INTERNAL_ERROR, "OPCODE2" );
#endif
GenStmnt();
aCode += (UINT8) eOpcode;
USHORT n = GetPC();
aCode += nOpnd;
return n;
}
USHORT SbiCodeGen::Gen( SbiOpcode eOpcode, UINT16 nOpnd1, UINT16 nOpnd2 )
{
#ifndef PRODUCT
if( eOpcode < SbOP2_START || eOpcode > SbOP2_END )
pParser->Error( SbERR_INTERNAL_ERROR, "OPCODE3" );
#endif
GenStmnt();
aCode += (UINT8) eOpcode;
USHORT n = GetPC();
aCode += nOpnd1;
aCode += nOpnd2;
return n;
}
// Abspeichern des erzeugten Images im Modul
void SbiCodeGen::Save()
{
SbiImage* p = new SbiImage;
if( !p )
{
SbERR_NO_MEMORY; return;
}
rMod.StartDefinitions();
// OPTION BASE-Wert:
p->nDimBase = pParser->nBase;
// OPTION EXPLICIT-Flag uebernehmen
if( pParser->bExplicit )
p->SetFlag( SBIMG_EXPLICIT );
int nIfaceCount = 0;
if( pParser->bClassModule )
{
p->SetFlag( SBIMG_CLASSMODULE );
pCLASSFAC->AddClassModule( &rMod );
nIfaceCount = pParser->aIfaceVector.size();
if( nIfaceCount )
{
if( !rMod.pClassData )
rMod.pClassData = new SbClassData;
for( int i = 0 ; i < nIfaceCount ; i++ )
{
const String& rIfaceName = pParser->aIfaceVector[i];
SbxVariable* pIfaceVar = new SbxVariable( SbxVARIANT );
pIfaceVar->SetName( rIfaceName );
SbxArray* pIfaces = rMod.pClassData->mxIfaces;
pIfaces->Insert( pIfaceVar, pIfaces->Count() );
}
}
}
else
{
pCLASSFAC->RemoveClassModule( &rMod );
}
if( pParser->bText )
p->SetFlag( SBIMG_COMPARETEXT );
// GlobalCode-Flag
if( pParser->HasGlobalCode() )
p->SetFlag( SBIMG_INITCODE );
// Die Entrypoints:
for( SbiSymDef* pDef = pParser->aPublics.First(); pDef;
pDef = pParser->aPublics.Next() )
{
SbiProcDef* pProc = pDef->GetProcDef();
if( pProc && pProc->IsDefined() )
{
String aProcName = pProc->GetName();
String aIfaceProcName;
String aIfaceName;
USHORT nPassCount = 1;
if( nIfaceCount )
{
int nPropPrefixFound =
aProcName.Search( String( RTL_CONSTASCII_USTRINGPARAM("Property ") ) );
String aPureProcName = aProcName;
String aPropPrefix;
if( nPropPrefixFound == 0 )
{
aPropPrefix = aProcName.Copy( 0, 13 ); // 13 == Len( "Property ?et " )
aPureProcName = aProcName.Copy( 13 );
}
for( int i = 0 ; i < nIfaceCount ; i++ )
{
const String& rIfaceName = pParser->aIfaceVector[i];
int nFound = aPureProcName.Search( rIfaceName );
if( nFound == 0 && '_' == aPureProcName.GetChar( rIfaceName.Len() ) )
{
if( nPropPrefixFound == 0 )
aIfaceProcName += aPropPrefix;
aIfaceProcName += aPureProcName.Copy( rIfaceName.Len() + 1 );
aIfaceName = rIfaceName;
nPassCount = 2;
break;
}
}
}
SbMethod* pMeth;
for( USHORT nPass = 0 ; nPass < nPassCount ; nPass++ )
{
if( nPass == 1 )
aProcName = aIfaceProcName;
PropertyMode ePropMode = pProc->getPropertyMode();
if( ePropMode != PROPERTY_MODE_NONE )
{
SbxDataType ePropType;
switch( ePropMode )
{
case PROPERTY_MODE_GET:
ePropType = pProc->GetType();
break;
case PROPERTY_MODE_LET:
{
// type == type of first parameter
ePropType = SbxVARIANT; // Default
SbiSymPool* pPool = &pProc->GetParams();
if( pPool->GetSize() > 1 )
{
SbiSymDef* pPar = pPool->Get( 1 );
if( pPar )
ePropType = pPar->GetType();
}
break;
}
case PROPERTY_MODE_SET:
ePropType = SbxOBJECT;
break;
}
String aPropName = pProc->GetPropName();
if( nPass == 1 )
aPropName = aPropName.Copy( aIfaceName.Len() + 1 );
SbProcedureProperty* pProcedureProperty =
rMod.GetProcedureProperty( aPropName, ePropType );
// rMod.GetProcedureProperty( pProc->GetPropName(), ePropType );
}
if( nPass == 1 )
{
SbIfaceMapperMethod* pMapperMeth =
rMod.GetIfaceMapperMethod( aProcName, pMeth );
}
else
{
pMeth = rMod.GetMethod( aProcName, pProc->GetType() );
// #110004
if( !pProc->IsPublic() )
pMeth->SetFlag( SBX_PRIVATE );
pMeth->nStart = pProc->GetAddr();
pMeth->nLine1 = pProc->GetLine1();
pMeth->nLine2 = pProc->GetLine2();
// Die Parameter:
SbxInfo* pInfo = pMeth->GetInfo();
String aHelpFile, aComment;
ULONG nHelpId = 0;
if( pInfo )
{
// Die Zusatzdaten retten
aHelpFile = pInfo->GetHelpFile();
aComment = pInfo->GetComment();
nHelpId = pInfo->GetHelpId();
}
// Und die Parameterliste neu aufbauen
pInfo = new SbxInfo( aHelpFile, nHelpId );
pInfo->SetComment( aComment );
SbiSymPool* pPool = &pProc->GetParams();
// Das erste Element ist immer der Funktionswert!
for( USHORT i = 1; i < pPool->GetSize(); i++ )
{
SbiSymDef* pPar = pPool->Get( i );
SbxDataType t = pPar->GetType();
if( !pPar->IsByVal() )
t = (SbxDataType) ( t | SbxBYREF );
if( pPar->GetDims() )
t = (SbxDataType) ( t | SbxARRAY );
// #33677 Optional-Info durchreichen
USHORT nFlags = SBX_READ;
if( pPar->IsOptional() )
nFlags |= SBX_OPTIONAL;
pInfo->AddParam( pPar->GetName(), t, nFlags );
UINT32 nUserData = 0;
USHORT nDefaultId = pPar->GetDefaultId();
if( nDefaultId )
nUserData |= nDefaultId;
if( pPar->IsParamArray() )
nUserData |= PARAM_INFO_PARAMARRAY;
if( nUserData )
{
SbxParamInfo* pParam = (SbxParamInfo*)pInfo->GetParam( i );
pParam->nUserData = nUserData;
}
}
pMeth->SetInfo( pInfo );
}
} // for( iPass...
}
}
// Der Code
p->AddCode( aCode.GetBuffer(), aCode.GetSize() );
// Der globale StringPool. 0 ist nicht belegt.
SbiStringPool* pPool = &pParser->aGblStrings;
USHORT nSize = pPool->GetSize();
p->MakeStrings( nSize );
USHORT i;
for( i = 1; i <= nSize; i++ )
p->AddString( pPool->Find( i ) );
// Typen einfuegen
USHORT nCount = pParser->rTypeArray->Count();
for (i = 0; i < nCount; i++)
p->AddType((SbxObject *)pParser->rTypeArray->Get(i));
// Insert enum objects
nCount = pParser->rEnumArray->Count();
for (i = 0; i < nCount; i++)
p->AddEnum((SbxObject *)pParser->rEnumArray->Get(i));
if( !p->IsError() )
rMod.pImage = p;
else
delete p;
rMod.EndDefinitions();
}
<|endoftext|> |
<commit_before>#pragma once
#include <cassert>
#include <tudocomp/def.hpp>
#include <tudocomp/util/View.hpp>
namespace tdc {
/// \brief Contains a literal and its location in the input.
///
/// This structure is used by encoders to get a glimpse at the literals it will
/// receive. The encoder is given a stream of literals and their occurences in
/// the compressed text. This information can be used to initialize data
/// structures that can be used for efficient encoding, e.g. a Huffman tree
/// or a k-mer dictionary.
struct Literal {
/// The literal.
uliteral_t c;
/// The position of the literal in the input.
len_t pos;
};
class LiteralIterator {
};
/// \brief An empty literal iterator that yields no literals whatsoever.
class NoLiterals : LiteralIterator {
public:
/// \brief Constructor.
inline NoLiterals() {}
/// \brief Tests whether there are more literals in the stream.
/// \return \e true if there are more literals in the stream, \e false
/// otherwise.
inline bool has_next() const { return false; }
/// \brief Yields the next literal from the stream.
/// \return The next literal from the stream.
inline Literal next() { assert(false); return Literal{0, 0}; }
};
/// \brief A literal iterator that yields every character from a \ref View.
class ViewLiterals : LiteralIterator {
private:
View m_view;
len_t m_index;
public:
/// \brief Constructor.
///
/// \param view The view to iterate over.
inline ViewLiterals(View view) : m_view(view), m_index(0) {
}
/// \brief Tests whether there are more literals in the stream.
/// \return \e true if there are more literals in the stream, \e false
/// otherwise.
inline bool has_next() const {
return m_index < m_view.size();
}
/// \brief Yields the next literal from the stream.
/// \return The next literal from the stream.
inline Literal next() {
assert(has_next());
auto i = m_index++;
return Literal { uliteral_t(m_view[i]), i };
}
};
}
<commit_msg>Move NoLiterals impl to LiteralIterator base so the functions are declared in it<commit_after>#pragma once
#include <cassert>
#include <tudocomp/def.hpp>
#include <tudocomp/util/View.hpp>
namespace tdc {
/// \brief Contains a literal and its location in the input.
///
/// This structure is used by encoders to get a glimpse at the literals it will
/// receive. The encoder is given a stream of literals and their occurences in
/// the compressed text. This information can be used to initialize data
/// structures that can be used for efficient encoding, e.g. a Huffman tree
/// or a k-mer dictionary.
struct Literal {
/// The literal.
uliteral_t c;
/// The position of the literal in the input.
len_t pos;
};
class LiteralIterator {
/// \brief Tests whether there are more literals in the stream.
/// \return \e true if there are more literals in the stream, \e false
/// otherwise.
inline bool has_next() const { return false; }
/// \brief Yields the next literal from the stream.
/// \return The next literal from the stream.
inline Literal next() { assert(false); return Literal{0, 0}; }
};
/// \brief An empty literal iterator that yields no literals whatsoever.
class NoLiterals : LiteralIterator {
};
/// \brief A literal iterator that yields every character from a \ref View.
class ViewLiterals : LiteralIterator {
private:
View m_view;
len_t m_index;
public:
/// \brief Constructor.
///
/// \param view The view to iterate over.
inline ViewLiterals(View view) : m_view(view), m_index(0) {
}
/// \brief Tests whether there are more literals in the stream.
/// \return \e true if there are more literals in the stream, \e false
/// otherwise.
inline bool has_next() const {
return m_index < m_view.size();
}
/// \brief Yields the next literal from the stream.
/// \return The next literal from the stream.
inline Literal next() {
assert(has_next());
auto i = m_index++;
return Literal { uliteral_t(m_view[i]), i };
}
};
}
<|endoftext|> |
<commit_before>//
// Created by mwo on 28/05/17.
//
#include "MempoolStatus.h"
#include "rpccalls.h"
namespace xmreg
{
using namespace std;
void
MempoolStatus::set_blockchain_variables(MicroCore *_mcore,
Blockchain *_core_storage)
{
mcore = _mcore;
core_storage = _core_storage;
}
void
MempoolStatus::start_mempool_status_thread()
{
// to protect from deviation by zero below.
mempool_refresh_time = std::max<uint64_t>(1, mempool_refresh_time);
if (!is_running)
{
m_thread = boost::thread{[]()
{
try
{
uint64_t loop_index {0};
// so that network status is checked every minute
uint64_t loop_index_divider = std::max<uint64_t>(1, 60 / mempool_refresh_time);
while (true)
{
// we just query network status every minute. No sense
// to do it as frequently as getting mempool data.
if (loop_index % loop_index_divider == 0)
{
if (!MempoolStatus::read_network_info())
{
network_info local_copy = current_network_info;
cerr << " Cant read network info "<< endl;
local_copy.current = false;
current_network_info = local_copy;
}
else
{
cout << "Current network info read, ";
loop_index = 0;
}
}
if (MempoolStatus::read_mempool())
{
vector<mempool_tx> current_mempool_txs = get_mempool_txs();
cout << "mempool status txs: "
<< current_mempool_txs.size()
<< endl;
}
// when we reach top of the blockchain, update
// the emission amount every minute.
boost::this_thread::sleep_for(
boost::chrono::seconds(mempool_refresh_time));
++loop_index;
} // while (true)
}
catch (boost::thread_interrupted&)
{
cout << "Mempool status thread interrupted." << endl;
return;
}
}}; // m_thread = boost::thread{[]()
is_running = true;
} // if (!is_running)
}
bool
MempoolStatus::read_mempool()
{
rpccalls rpc {deamon_url};
string error_msg;
// we populate this variable instead of global mempool_txs
// mempool_txs will be changed only when this function completes.
// this ensures that we don't sent out partial mempool txs to
// other places.
vector<mempool_tx> local_copy_of_mempool_txs;
// get txs in the mempool
std::vector<tx_info> mempool_tx_info;
//std::vector<tx_info> pool_tx_info;
std::vector<spent_key_image_info> pool_key_image_info;
if (!mcore->get_mempool().get_transactions_and_spent_keys_info(
mempool_tx_info,
pool_key_image_info))
{
cerr << "Getting mempool failed " << endl;
return false;
}
// if dont have tx_blob member, construct tx
// from json obtained from the rpc call
uint64_t mempool_size_kB {0};
for (size_t i = 0; i < mempool_tx_info.size(); ++i)
{
// get transaction info of the tx in the mempool
const tx_info& _tx_info = mempool_tx_info.at(i);
transaction tx;
crypto::hash tx_hash;
crypto::hash tx_prefix_hash;
if (!parse_and_validate_tx_from_blob(
_tx_info.tx_blob, tx, tx_hash, tx_prefix_hash))
{
cerr << "Cant make tx from _tx_info.tx_blob" << endl;
return false;
}
mempool_size_kB += _tx_info.blob_size;
local_copy_of_mempool_txs.push_back(mempool_tx{});
mempool_tx& last_tx = local_copy_of_mempool_txs.back();
last_tx.tx_hash = tx_hash;
last_tx.tx = tx;
// key images of inputs
vector<txin_to_key> input_key_imgs;
// public keys and xmr amount of outputs
vector<pair<txout_to_key, uint64_t>> output_pub_keys;
// sum xmr in inputs and ouputs in the given tx
const array<uint64_t, 4>& sum_data = summary_of_in_out_rct(
tx, output_pub_keys, input_key_imgs);
double tx_size = static_cast<double>(_tx_info.blob_size)/1024.0;
double payed_for_kB = XMR_AMOUNT(_tx_info.fee) / tx_size;
last_tx.receive_time = _tx_info.receive_time;
last_tx.sum_outputs = sum_data[0];
last_tx.sum_inputs = sum_data[1];
last_tx.no_outputs = output_pub_keys.size();
last_tx.no_inputs = input_key_imgs.size();
last_tx.mixin_no = sum_data[2];
last_tx.num_nonrct_inputs = sum_data[3];
last_tx.fee_str = xmreg::xmr_amount_to_str(_tx_info.fee, "{:0.4f}", false);
last_tx.payed_for_kB_str = fmt::format("{:0.4f}", payed_for_kB);
last_tx.xmr_inputs_str = xmreg::xmr_amount_to_str(last_tx.sum_inputs , "{:0.3f}");
last_tx.xmr_outputs_str = xmreg::xmr_amount_to_str(last_tx.sum_outputs, "{:0.3f}");
last_tx.timestamp_str = xmreg::timestamp_to_str_gm(_tx_info.receive_time);
last_tx.txsize = fmt::format("{:0.2f}", tx_size);
last_tx.pID = '-';
crypto::hash payment_id;
crypto::hash8 payment_id8;
get_payment_id(tx, payment_id, payment_id8);
if (payment_id != null_hash)
last_tx.pID = 'l'; // legacy payment id
else if (payment_id8 != null_hash8)
last_tx.pID = 'e'; // encrypted payment id
else if (!get_additional_tx_pub_keys_from_extra(tx).empty())
{
// if multioutput tx have additional public keys,
// mark it so that it represents that it has at least
// one sub-address
last_tx.pID = 's';
}
// } // if (hex_to_pod(_tx_info.id_hash, mem_tx_hash))
} // for (size_t i = 0; i < mempool_tx_info.size(); ++i)
Guard lck (mempool_mutx);
// clear current mempool txs vector
// repopulate it with each execution of read_mempool()
// not very efficient but good enough for now.
mempool_no = local_copy_of_mempool_txs.size();
mempool_size = mempool_size_kB;
mempool_txs = std::move(local_copy_of_mempool_txs);
return true;
}
bool
MempoolStatus::read_network_info()
{
rpccalls rpc {deamon_url};
COMMAND_RPC_GET_INFO::response rpc_network_info;
if (!rpc.get_network_info(rpc_network_info))
return false;
uint64_t fee_estimated;
string error_msg;
if (!rpc.get_dynamic_per_kb_fee_estimate(
FEE_ESTIMATE_GRACE_BLOCKS,
fee_estimated, error_msg))
{
cerr << "rpc.get_dynamic_per_kb_fee_estimate failed" << endl;
return false;
}
(void) error_msg;
COMMAND_RPC_HARD_FORK_INFO::response rpc_hardfork_info;
if (!rpc.get_hardfork_info(rpc_hardfork_info))
return false;
network_info local_copy;
local_copy.status = network_info::get_status_uint(rpc_network_info.status);
local_copy.height = rpc_network_info.height;
local_copy.target_height = rpc_network_info.target_height;
local_copy.difficulty = rpc_network_info.difficulty;
local_copy.target = rpc_network_info.target;
local_copy.hash_rate = (rpc_network_info.difficulty/rpc_network_info.target);
local_copy.tx_count = rpc_network_info.tx_count;
local_copy.tx_pool_size = rpc_network_info.tx_pool_size;
local_copy.alt_blocks_count = rpc_network_info.alt_blocks_count;
local_copy.outgoing_connections_count = rpc_network_info.outgoing_connections_count;
local_copy.incoming_connections_count = rpc_network_info.incoming_connections_count;
local_copy.white_peerlist_size = rpc_network_info.white_peerlist_size;
local_copy.nettype = rpc_network_info.testnet ? cryptonote::network_type::TESTNET :
rpc_network_info.stagenet ? cryptonote::network_type::STAGENET : cryptonote::network_type::MAINNET;
local_copy.cumulative_difficulty = rpc_network_info.cumulative_difficulty;
local_copy.block_size_limit = rpc_network_info.block_size_limit;
local_copy.block_size_median = rpc_network_info.block_size_median;
local_copy.block_weight_limit = rpc_network_info.block_weight_limit;
local_copy.start_time = rpc_network_info.start_time;
strncpy(local_copy.block_size_limit_str, fmt::format("{:0.2f}",
static_cast<double>(
local_copy.block_size_limit ) / 2.0 / 1024.0).c_str(),
sizeof(local_copy.block_size_limit_str));
strncpy(local_copy.block_size_median_str, fmt::format("{:0.2f}",
static_cast<double>(
local_copy.block_size_median) / 1024.0).c_str(),
sizeof(local_copy.block_size_median_str));
epee::string_tools::hex_to_pod(rpc_network_info.top_block_hash,
local_copy.top_block_hash);
local_copy.fee_per_kb = fee_estimated;
local_copy.info_timestamp = static_cast<uint64_t>(std::time(nullptr));
local_copy.current_hf_version = rpc_hardfork_info.version;
local_copy.current = true;
current_network_info = local_copy;
return true;
}
vector<MempoolStatus::mempool_tx>
MempoolStatus::get_mempool_txs()
{
Guard lck (mempool_mutx);
return mempool_txs;
}
vector<MempoolStatus::mempool_tx>
MempoolStatus::get_mempool_txs(uint64_t no_of_tx)
{
Guard lck (mempool_mutx);
no_of_tx = std::min<uint64_t>(no_of_tx, mempool_txs.size());
return vector<mempool_tx>(mempool_txs.begin(), mempool_txs.begin() + no_of_tx);
}
bool
MempoolStatus::is_thread_running()
{
return is_running;
}
bf::path MempoolStatus::blockchain_path {"/home/mwo/.bitmonero/lmdb"};
string MempoolStatus::deamon_url {"http:://127.0.0.1:18081"};
cryptonote::network_type MempoolStatus::nettype {cryptonote::network_type::MAINNET};
atomic<bool> MempoolStatus::is_running {false};
boost::thread MempoolStatus::m_thread;
Blockchain* MempoolStatus::core_storage {nullptr};
xmreg::MicroCore* MempoolStatus::mcore {nullptr};
vector<MempoolStatus::mempool_tx> MempoolStatus::mempool_txs;
atomic<MempoolStatus::network_info> MempoolStatus::current_network_info;
atomic<uint64_t> MempoolStatus::mempool_no {0}; // no of txs
atomic<uint64_t> MempoolStatus::mempool_size {0}; // size in bytes.
uint64_t MempoolStatus::mempool_refresh_time {10};
mutex MempoolStatus::mempool_mutx;
}
<commit_msg>Fix for txpool: Failed to parse transaction from blob<commit_after>//
// Created by mwo on 28/05/17.
//
#include "MempoolStatus.h"
#include "rpccalls.h"
namespace xmreg
{
using namespace std;
void
MempoolStatus::set_blockchain_variables(MicroCore *_mcore,
Blockchain *_core_storage)
{
mcore = _mcore;
core_storage = _core_storage;
}
void
MempoolStatus::start_mempool_status_thread()
{
// to protect from deviation by zero below.
mempool_refresh_time = std::max<uint64_t>(1, mempool_refresh_time);
if (!is_running)
{
m_thread = boost::thread{[]()
{
try
{
uint64_t loop_index {0};
// so that network status is checked every minute
uint64_t loop_index_divider = std::max<uint64_t>(1, 60 / mempool_refresh_time);
while (true)
{
// we just query network status every minute. No sense
// to do it as frequently as getting mempool data.
if (loop_index % loop_index_divider == 0)
{
if (!MempoolStatus::read_network_info())
{
network_info local_copy = current_network_info;
cerr << " Cant read network info "<< endl;
local_copy.current = false;
current_network_info = local_copy;
}
else
{
cout << "Current network info read, ";
loop_index = 0;
}
}
if (MempoolStatus::read_mempool())
{
vector<mempool_tx> current_mempool_txs = get_mempool_txs();
cout << "mempool status txs: "
<< current_mempool_txs.size()
<< endl;
}
// when we reach top of the blockchain, update
// the emission amount every minute.
boost::this_thread::sleep_for(
boost::chrono::seconds(mempool_refresh_time));
++loop_index;
} // while (true)
}
catch (boost::thread_interrupted&)
{
cout << "Mempool status thread interrupted." << endl;
return;
}
}}; // m_thread = boost::thread{[]()
is_running = true;
} // if (!is_running)
}
bool
MempoolStatus::read_mempool()
{
rpccalls rpc {deamon_url};
string error_msg;
// we populate this variable instead of global mempool_txs
// mempool_txs will be changed only when this function completes.
// this ensures that we don't sent out partial mempool txs to
// other places.
vector<mempool_tx> local_copy_of_mempool_txs;
// get txs in the mempool
std::vector<tx_info> mempool_tx_info;
//std::vector<tx_info> pool_tx_info;
std::vector<spent_key_image_info> pool_key_image_info;
// get txpool from lmdb database instead of rpc call
if (!mcore->get_mempool().get_transactions_and_spent_keys_info(
mempool_tx_info,
pool_key_image_info))
{
cerr << "Getting mempool failed " << endl;
return false;
}
(void) pool_key_image_info;
// if dont have tx_blob member, construct tx
// from json obtained from the rpc call
uint64_t mempool_size_kB {0};
for (size_t i = 0; i < mempool_tx_info.size(); ++i)
{
// get transaction info of the tx in the mempool
const tx_info& _tx_info = mempool_tx_info.at(i);
transaction tx;
crypto::hash tx_hash;
crypto::hash tx_prefix_hash;
if (!parse_and_validate_tx_from_blob(
_tx_info.tx_blob, tx, tx_hash, tx_prefix_hash))
{
cerr << "Cant make tx from _tx_info.tx_blob" << endl;
return false;
}
mempool_size_kB += _tx_info.blob_size;
local_copy_of_mempool_txs.push_back(mempool_tx{});
mempool_tx& last_tx = local_copy_of_mempool_txs.back();
last_tx.tx_hash = tx_hash;
last_tx.tx = tx;
// key images of inputs
vector<txin_to_key> input_key_imgs;
// public keys and xmr amount of outputs
vector<pair<txout_to_key, uint64_t>> output_pub_keys;
// sum xmr in inputs and ouputs in the given tx
const array<uint64_t, 4>& sum_data = summary_of_in_out_rct(
tx, output_pub_keys, input_key_imgs);
double tx_size = static_cast<double>(_tx_info.blob_size)/1024.0;
double payed_for_kB = XMR_AMOUNT(_tx_info.fee) / tx_size;
last_tx.receive_time = _tx_info.receive_time;
last_tx.sum_outputs = sum_data[0];
last_tx.sum_inputs = sum_data[1];
last_tx.no_outputs = output_pub_keys.size();
last_tx.no_inputs = input_key_imgs.size();
last_tx.mixin_no = sum_data[2];
last_tx.num_nonrct_inputs = sum_data[3];
last_tx.fee_str = xmreg::xmr_amount_to_str(_tx_info.fee, "{:0.4f}", false);
last_tx.payed_for_kB_str = fmt::format("{:0.4f}", payed_for_kB);
last_tx.xmr_inputs_str = xmreg::xmr_amount_to_str(last_tx.sum_inputs , "{:0.3f}");
last_tx.xmr_outputs_str = xmreg::xmr_amount_to_str(last_tx.sum_outputs, "{:0.3f}");
last_tx.timestamp_str = xmreg::timestamp_to_str_gm(_tx_info.receive_time);
last_tx.txsize = fmt::format("{:0.2f}", tx_size);
last_tx.pID = '-';
crypto::hash payment_id;
crypto::hash8 payment_id8;
get_payment_id(tx, payment_id, payment_id8);
if (payment_id != null_hash)
last_tx.pID = 'l'; // legacy payment id
else if (payment_id8 != null_hash8)
last_tx.pID = 'e'; // encrypted payment id
else if (!get_additional_tx_pub_keys_from_extra(tx).empty())
{
// if multioutput tx have additional public keys,
// mark it so that it represents that it has at least
// one sub-address
last_tx.pID = 's';
}
// } // if (hex_to_pod(_tx_info.id_hash, mem_tx_hash))
} // for (size_t i = 0; i < mempool_tx_info.size(); ++i)
Guard lck (mempool_mutx);
// clear current mempool txs vector
// repopulate it with each execution of read_mempool()
// not very efficient but good enough for now.
mempool_no = local_copy_of_mempool_txs.size();
mempool_size = mempool_size_kB;
mempool_txs = std::move(local_copy_of_mempool_txs);
return true;
}
bool
MempoolStatus::read_network_info()
{
rpccalls rpc {deamon_url};
COMMAND_RPC_GET_INFO::response rpc_network_info;
if (!rpc.get_network_info(rpc_network_info))
return false;
uint64_t fee_estimated;
string error_msg;
if (!rpc.get_dynamic_per_kb_fee_estimate(
FEE_ESTIMATE_GRACE_BLOCKS,
fee_estimated, error_msg))
{
cerr << "rpc.get_dynamic_per_kb_fee_estimate failed" << endl;
return false;
}
(void) error_msg;
COMMAND_RPC_HARD_FORK_INFO::response rpc_hardfork_info;
if (!rpc.get_hardfork_info(rpc_hardfork_info))
return false;
network_info local_copy;
local_copy.status = network_info::get_status_uint(rpc_network_info.status);
local_copy.height = rpc_network_info.height;
local_copy.target_height = rpc_network_info.target_height;
local_copy.difficulty = rpc_network_info.difficulty;
local_copy.target = rpc_network_info.target;
local_copy.hash_rate = (rpc_network_info.difficulty/rpc_network_info.target);
local_copy.tx_count = rpc_network_info.tx_count;
local_copy.tx_pool_size = rpc_network_info.tx_pool_size;
local_copy.alt_blocks_count = rpc_network_info.alt_blocks_count;
local_copy.outgoing_connections_count = rpc_network_info.outgoing_connections_count;
local_copy.incoming_connections_count = rpc_network_info.incoming_connections_count;
local_copy.white_peerlist_size = rpc_network_info.white_peerlist_size;
local_copy.nettype = rpc_network_info.testnet ? cryptonote::network_type::TESTNET :
rpc_network_info.stagenet ? cryptonote::network_type::STAGENET : cryptonote::network_type::MAINNET;
local_copy.cumulative_difficulty = rpc_network_info.cumulative_difficulty;
local_copy.block_size_limit = rpc_network_info.block_size_limit;
local_copy.block_size_median = rpc_network_info.block_size_median;
local_copy.block_weight_limit = rpc_network_info.block_weight_limit;
local_copy.start_time = rpc_network_info.start_time;
strncpy(local_copy.block_size_limit_str, fmt::format("{:0.2f}",
static_cast<double>(
local_copy.block_size_limit ) / 2.0 / 1024.0).c_str(),
sizeof(local_copy.block_size_limit_str));
strncpy(local_copy.block_size_median_str, fmt::format("{:0.2f}",
static_cast<double>(
local_copy.block_size_median) / 1024.0).c_str(),
sizeof(local_copy.block_size_median_str));
epee::string_tools::hex_to_pod(rpc_network_info.top_block_hash,
local_copy.top_block_hash);
local_copy.fee_per_kb = fee_estimated;
local_copy.info_timestamp = static_cast<uint64_t>(std::time(nullptr));
local_copy.current_hf_version = rpc_hardfork_info.version;
local_copy.current = true;
current_network_info = local_copy;
return true;
}
vector<MempoolStatus::mempool_tx>
MempoolStatus::get_mempool_txs()
{
Guard lck (mempool_mutx);
return mempool_txs;
}
vector<MempoolStatus::mempool_tx>
MempoolStatus::get_mempool_txs(uint64_t no_of_tx)
{
Guard lck (mempool_mutx);
no_of_tx = std::min<uint64_t>(no_of_tx, mempool_txs.size());
return vector<mempool_tx>(mempool_txs.begin(), mempool_txs.begin() + no_of_tx);
}
bool
MempoolStatus::is_thread_running()
{
return is_running;
}
bf::path MempoolStatus::blockchain_path {"/home/mwo/.bitmonero/lmdb"};
string MempoolStatus::deamon_url {"http:://127.0.0.1:18081"};
cryptonote::network_type MempoolStatus::nettype {cryptonote::network_type::MAINNET};
atomic<bool> MempoolStatus::is_running {false};
boost::thread MempoolStatus::m_thread;
Blockchain* MempoolStatus::core_storage {nullptr};
xmreg::MicroCore* MempoolStatus::mcore {nullptr};
vector<MempoolStatus::mempool_tx> MempoolStatus::mempool_txs;
atomic<MempoolStatus::network_info> MempoolStatus::current_network_info;
atomic<uint64_t> MempoolStatus::mempool_no {0}; // no of txs
atomic<uint64_t> MempoolStatus::mempool_size {0}; // size in bytes.
uint64_t MempoolStatus::mempool_refresh_time {10};
mutex MempoolStatus::mempool_mutx;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/test/unit_test.hpp>
#include "utils/loading_shared_values.hh"
#include "utils/loading_cache.hh"
#include <seastar/core/file.hh>
#include <seastar/core/thread.hh>
#include <seastar/core/sstring.hh>
#include <seastar/core/reactor.hh>
#include <seastar/core/sleep.hh>
#include "seastarx.hh"
#include "tests/test-utils.hh"
#include "tmpdir.hh"
#include "log.hh"
#include <vector>
#include <numeric>
#include <random>
/// Get a random integer in the [0, max) range.
/// \param upper bound of the random value range
/// \return The uniformly distributed random integer from the [0, \ref max) range.
static int rand_int(int max) {
std::random_device rd; // only used once to initialise (seed) engine
std::mt19937 rng(rd()); // random-number engine used (Mersenne-Twister in this case)
std::uniform_int_distribution<int> uni(0, max - 1); // guaranteed unbiased
return uni(rng);
}
#include "disk-error-handler.hh"
thread_local disk_error_signal_type general_disk_error;
thread_local disk_error_signal_type commit_error;
static const sstring test_file_name = "loading_cache_test.txt";
static const sstring test_string = "1";
static bool file_prepared = false;
static constexpr int num_loaders = 1000;
static logging::logger test_logger("loading_cache_test");
static thread_local int load_count;
static const tmpdir& get_tmpdir() {
static thread_local tmpdir tmp;
return tmp;
}
static future<> prepare() {
if (file_prepared) {
return make_ready_future<>();
}
return open_file_dma((boost::filesystem::path(get_tmpdir().path) / test_file_name.c_str()).c_str(), open_flags::create | open_flags::wo).then([] (file f) {
return do_with(std::move(f), [] (file& f) {
return f.dma_write(0, test_string.c_str(), test_string.size() + 1).then([] (size_t s) {
BOOST_REQUIRE_EQUAL(s, test_string.size() + 1);
file_prepared = true;
});
});
});
}
static future<sstring> loader(const int& k) {
return open_file_dma((boost::filesystem::path(get_tmpdir().path) / test_file_name.c_str()).c_str(), open_flags::ro).then([] (file f) -> future<sstring> {
return do_with(std::move(f), [] (file& f) -> future<sstring> {
return f.dma_read_exactly<char>(0, test_string.size() + 1).then([] (auto buf) {
sstring str(buf.get());
BOOST_REQUIRE_EQUAL(str, test_string);
++load_count;
return make_ready_future<sstring>(std::move(str));
});
});
});
}
SEASTAR_TEST_CASE(test_loading_shared_values_parallel_loading_same_key) {
return seastar::async([] {
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_shared_values<int, sstring> shared_values;
std::list<typename utils::loading_shared_values<int, sstring>::entry_ptr> anchors_list;
prepare().get();
std::fill(ivec.begin(), ivec.end(), 0);
parallel_for_each(ivec, [&] (int& k) {
return shared_values.get_or_load(k, loader).then([&] (auto entry_ptr) {
anchors_list.emplace_back(std::move(entry_ptr));
});
}).get();
// "loader" must be called exactly once
BOOST_REQUIRE_EQUAL(load_count, 1);
BOOST_REQUIRE_EQUAL(shared_values.size(), 1);
anchors_list.clear();
});
}
SEASTAR_TEST_CASE(test_loading_shared_values_parallel_loading_different_keys) {
return seastar::async([] {
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_shared_values<int, sstring> shared_values;
std::list<typename utils::loading_shared_values<int, sstring>::entry_ptr> anchors_list;
prepare().get();
std::iota(ivec.begin(), ivec.end(), 0);
parallel_for_each(ivec, [&] (int& k) {
return shared_values.get_or_load(k, loader).then([&] (auto entry_ptr) {
anchors_list.emplace_back(std::move(entry_ptr));
});
}).get();
// "loader" must be called once for each key
BOOST_REQUIRE_EQUAL(load_count, num_loaders);
BOOST_REQUIRE_EQUAL(shared_values.size(), num_loaders);
anchors_list.clear();
});
}
SEASTAR_TEST_CASE(test_loading_shared_values_rehash) {
return seastar::async([] {
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_shared_values<int, sstring> shared_values;
std::list<typename utils::loading_shared_values<int, sstring>::entry_ptr> anchors_list;
prepare().get();
std::iota(ivec.begin(), ivec.end(), 0);
// verify that load factor is always in the (0.25, 0.75) range
for (int k = 0; k < num_loaders; ++k) {
shared_values.get_or_load(k, loader).then([&] (auto entry_ptr) {
anchors_list.emplace_back(std::move(entry_ptr));
}).get();
BOOST_REQUIRE_LE(shared_values.size(), 3 * shared_values.buckets_count() / 4);
}
BOOST_REQUIRE_GE(shared_values.size(), shared_values.buckets_count() / 4);
// minimum buckets count (by default) is 16, so don't check for less than 4 elements
for (int k = 0; k < num_loaders - 4; ++k) {
anchors_list.pop_back();
shared_values.rehash();
BOOST_REQUIRE_GE(shared_values.size(), shared_values.buckets_count() / 4);
}
anchors_list.clear();
});
}
SEASTAR_TEST_CASE(test_loading_shared_values_parallel_loading_explicit_eviction) {
return seastar::async([] {
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_shared_values<int, sstring> shared_values;
std::vector<typename utils::loading_shared_values<int, sstring>::entry_ptr> anchors_vec(num_loaders);
prepare().get();
std::iota(ivec.begin(), ivec.end(), 0);
parallel_for_each(ivec, [&] (int& k) {
return shared_values.get_or_load(k, loader).then([&] (auto entry_ptr) {
anchors_vec[k] = std::move(entry_ptr);
});
}).get();
int rand_key = rand_int(num_loaders);
BOOST_REQUIRE(shared_values.find(rand_key) != shared_values.end());
anchors_vec[rand_key] = nullptr;
BOOST_REQUIRE_MESSAGE(shared_values.find(rand_key) == shared_values.end(), format("explicit removal for key {} failed", rand_key));
anchors_vec.clear();
});
}
SEASTAR_TEST_CASE(test_loading_cache_loading_same_key) {
return seastar::async([] {
using namespace std::chrono;
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_cache<int, sstring> loading_cache(num_loaders, 1s, test_logger);
prepare().get();
std::fill(ivec.begin(), ivec.end(), 0);
parallel_for_each(ivec, [&] (int& k) {
return loading_cache.get_ptr(k, loader).discard_result();
}).get();
// "loader" must be called exactly once
BOOST_REQUIRE_EQUAL(load_count, 1);
BOOST_REQUIRE_EQUAL(loading_cache.size(), 1);
loading_cache.stop().get();
});
}
SEASTAR_TEST_CASE(test_loading_cache_loading_different_keys) {
return seastar::async([] {
using namespace std::chrono;
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_cache<int, sstring> loading_cache(num_loaders, 1s, test_logger);
prepare().get();
std::iota(ivec.begin(), ivec.end(), 0);
parallel_for_each(ivec, [&] (int& k) {
return loading_cache.get_ptr(k, loader).discard_result();
}).get();
BOOST_REQUIRE_EQUAL(load_count, num_loaders);
BOOST_REQUIRE_EQUAL(loading_cache.size(), num_loaders);
loading_cache.stop().get();
});
}
SEASTAR_TEST_CASE(test_loading_cache_loading_expiry_eviction) {
return seastar::async([] {
using namespace std::chrono;
utils::loading_cache<int, sstring> loading_cache(num_loaders, 20ms, test_logger);
prepare().get();
loading_cache.get_ptr(0, loader).discard_result().get();
BOOST_REQUIRE(loading_cache.find(0) != loading_cache.end());
// timers get delayed sometimes (especially in a debug mode)
constexpr int max_retry = 10;
int i = 0;
do_until(
[&] { return i++ > max_retry || loading_cache.find(0) == loading_cache.end(); },
[] { return sleep(40ms); }
).get();
BOOST_REQUIRE(loading_cache.find(0) == loading_cache.end());
loading_cache.stop().get();
});
}
SEASTAR_TEST_CASE(test_loading_cache_loading_reloading) {
return seastar::async([] {
using namespace std::chrono;
load_count = 0;
utils::loading_cache<int, sstring, utils::loading_cache_reload_enabled::yes> loading_cache(num_loaders, 100ms, 20ms, test_logger, loader);
prepare().get();
loading_cache.get_ptr(0, loader).discard_result().get();
sleep(60ms).get();
BOOST_REQUIRE_MESSAGE(load_count >= 2, format("load_count is {}", load_count));
loading_cache.stop().get();
});
}
SEASTAR_TEST_CASE(test_loading_cache_max_size_eviction) {
return seastar::async([] {
using namespace std::chrono;
load_count = 0;
utils::loading_cache<int, sstring> loading_cache(1, 1s, test_logger);
prepare().get();
for (int i = 0; i < num_loaders; ++i) {
loading_cache.get_ptr(i % 2, loader).discard_result().get();
}
BOOST_REQUIRE_EQUAL(load_count, num_loaders);
BOOST_REQUIRE_EQUAL(loading_cache.size(), 1);
loading_cache.stop().get();
});
}
SEASTAR_TEST_CASE(test_loading_cache_reload_during_eviction) {
return seastar::async([] {
using namespace std::chrono;
load_count = 0;
utils::loading_cache<int, sstring, utils::loading_cache_reload_enabled::yes> loading_cache(1, 100ms, 10ms, test_logger, loader);
prepare().get();
auto curr_time = lowres_clock::now();
int i = 0;
// this will cause reloading when values are being actively evicted due to the limited cache size
do_until(
[&] { return lowres_clock::now() - curr_time > 1s; },
[&] { return loading_cache.get_ptr(i++ % 2).discard_result(); }
).get();
BOOST_REQUIRE_EQUAL(loading_cache.size(), 1);
loading_cache.stop().get();
});
}<commit_msg>tests: loading_cache_test: make it more robust<commit_after>/*
* Copyright (C) 2017 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/test/unit_test.hpp>
#include "utils/loading_shared_values.hh"
#include "utils/loading_cache.hh"
#include <seastar/core/file.hh>
#include <seastar/core/thread.hh>
#include <seastar/core/sstring.hh>
#include <seastar/core/reactor.hh>
#include <seastar/core/sleep.hh>
#include <seastar/util/defer.hh>
#include "seastarx.hh"
#include "tests/test-utils.hh"
#include "tmpdir.hh"
#include "log.hh"
#include <vector>
#include <numeric>
#include <random>
/// Get a random integer in the [0, max) range.
/// \param upper bound of the random value range
/// \return The uniformly distributed random integer from the [0, \ref max) range.
static int rand_int(int max) {
std::random_device rd; // only used once to initialise (seed) engine
std::mt19937 rng(rd()); // random-number engine used (Mersenne-Twister in this case)
std::uniform_int_distribution<int> uni(0, max - 1); // guaranteed unbiased
return uni(rng);
}
#include "disk-error-handler.hh"
thread_local disk_error_signal_type general_disk_error;
thread_local disk_error_signal_type commit_error;
static const sstring test_file_name = "loading_cache_test.txt";
static const sstring test_string = "1";
static bool file_prepared = false;
static constexpr int num_loaders = 1000;
static logging::logger test_logger("loading_cache_test");
static thread_local int load_count;
static const tmpdir& get_tmpdir() {
static thread_local tmpdir tmp;
return tmp;
}
static future<> prepare() {
if (file_prepared) {
return make_ready_future<>();
}
return open_file_dma((boost::filesystem::path(get_tmpdir().path) / test_file_name.c_str()).c_str(), open_flags::create | open_flags::wo).then([] (file f) {
return do_with(std::move(f), [] (file& f) {
return f.dma_write(0, test_string.c_str(), test_string.size() + 1).then([] (size_t s) {
BOOST_REQUIRE_EQUAL(s, test_string.size() + 1);
file_prepared = true;
});
});
});
}
static future<sstring> loader(const int& k) {
return open_file_dma((boost::filesystem::path(get_tmpdir().path) / test_file_name.c_str()).c_str(), open_flags::ro).then([] (file f) -> future<sstring> {
return do_with(std::move(f), [] (file& f) -> future<sstring> {
return f.dma_read_exactly<char>(0, test_string.size() + 1).then([] (auto buf) {
sstring str(buf.get());
BOOST_REQUIRE_EQUAL(str, test_string);
++load_count;
return make_ready_future<sstring>(std::move(str));
});
});
});
}
SEASTAR_TEST_CASE(test_loading_shared_values_parallel_loading_same_key) {
return seastar::async([] {
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_shared_values<int, sstring> shared_values;
std::list<typename utils::loading_shared_values<int, sstring>::entry_ptr> anchors_list;
prepare().get();
std::fill(ivec.begin(), ivec.end(), 0);
parallel_for_each(ivec, [&] (int& k) {
return shared_values.get_or_load(k, loader).then([&] (auto entry_ptr) {
anchors_list.emplace_back(std::move(entry_ptr));
});
}).get();
// "loader" must be called exactly once
BOOST_REQUIRE_EQUAL(load_count, 1);
BOOST_REQUIRE_EQUAL(shared_values.size(), 1);
anchors_list.clear();
});
}
SEASTAR_TEST_CASE(test_loading_shared_values_parallel_loading_different_keys) {
return seastar::async([] {
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_shared_values<int, sstring> shared_values;
std::list<typename utils::loading_shared_values<int, sstring>::entry_ptr> anchors_list;
prepare().get();
std::iota(ivec.begin(), ivec.end(), 0);
parallel_for_each(ivec, [&] (int& k) {
return shared_values.get_or_load(k, loader).then([&] (auto entry_ptr) {
anchors_list.emplace_back(std::move(entry_ptr));
});
}).get();
// "loader" must be called once for each key
BOOST_REQUIRE_EQUAL(load_count, num_loaders);
BOOST_REQUIRE_EQUAL(shared_values.size(), num_loaders);
anchors_list.clear();
});
}
SEASTAR_TEST_CASE(test_loading_shared_values_rehash) {
return seastar::async([] {
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_shared_values<int, sstring> shared_values;
std::list<typename utils::loading_shared_values<int, sstring>::entry_ptr> anchors_list;
prepare().get();
std::iota(ivec.begin(), ivec.end(), 0);
// verify that load factor is always in the (0.25, 0.75) range
for (int k = 0; k < num_loaders; ++k) {
shared_values.get_or_load(k, loader).then([&] (auto entry_ptr) {
anchors_list.emplace_back(std::move(entry_ptr));
}).get();
BOOST_REQUIRE_LE(shared_values.size(), 3 * shared_values.buckets_count() / 4);
}
BOOST_REQUIRE_GE(shared_values.size(), shared_values.buckets_count() / 4);
// minimum buckets count (by default) is 16, so don't check for less than 4 elements
for (int k = 0; k < num_loaders - 4; ++k) {
anchors_list.pop_back();
shared_values.rehash();
BOOST_REQUIRE_GE(shared_values.size(), shared_values.buckets_count() / 4);
}
anchors_list.clear();
});
}
SEASTAR_TEST_CASE(test_loading_shared_values_parallel_loading_explicit_eviction) {
return seastar::async([] {
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_shared_values<int, sstring> shared_values;
std::vector<typename utils::loading_shared_values<int, sstring>::entry_ptr> anchors_vec(num_loaders);
prepare().get();
std::iota(ivec.begin(), ivec.end(), 0);
parallel_for_each(ivec, [&] (int& k) {
return shared_values.get_or_load(k, loader).then([&] (auto entry_ptr) {
anchors_vec[k] = std::move(entry_ptr);
});
}).get();
int rand_key = rand_int(num_loaders);
BOOST_REQUIRE(shared_values.find(rand_key) != shared_values.end());
anchors_vec[rand_key] = nullptr;
BOOST_REQUIRE_MESSAGE(shared_values.find(rand_key) == shared_values.end(), format("explicit removal for key {} failed", rand_key));
anchors_vec.clear();
});
}
SEASTAR_TEST_CASE(test_loading_cache_loading_same_key) {
return seastar::async([] {
using namespace std::chrono;
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_cache<int, sstring> loading_cache(num_loaders, 1s, test_logger);
auto stop_cache_reload = seastar::defer([&loading_cache] { loading_cache.stop().get(); });
prepare().get();
std::fill(ivec.begin(), ivec.end(), 0);
parallel_for_each(ivec, [&] (int& k) {
return loading_cache.get_ptr(k, loader).discard_result();
}).get();
// "loader" must be called exactly once
BOOST_REQUIRE_EQUAL(load_count, 1);
BOOST_REQUIRE_EQUAL(loading_cache.size(), 1);
});
}
SEASTAR_TEST_CASE(test_loading_cache_loading_different_keys) {
return seastar::async([] {
using namespace std::chrono;
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_cache<int, sstring> loading_cache(num_loaders, 1s, test_logger);
auto stop_cache_reload = seastar::defer([&loading_cache] { loading_cache.stop().get(); });
prepare().get();
std::iota(ivec.begin(), ivec.end(), 0);
parallel_for_each(ivec, [&] (int& k) {
return loading_cache.get_ptr(k, loader).discard_result();
}).get();
BOOST_REQUIRE_EQUAL(load_count, num_loaders);
BOOST_REQUIRE_EQUAL(loading_cache.size(), num_loaders);
});
}
SEASTAR_TEST_CASE(test_loading_cache_loading_expiry_eviction) {
return seastar::async([] {
using namespace std::chrono;
utils::loading_cache<int, sstring> loading_cache(num_loaders, 20ms, test_logger);
auto stop_cache_reload = seastar::defer([&loading_cache] { loading_cache.stop().get(); });
prepare().get();
loading_cache.get_ptr(0, loader).discard_result().get();
BOOST_REQUIRE(loading_cache.find(0) != loading_cache.end());
// timers get delayed sometimes (especially in a debug mode)
constexpr int max_retry = 10;
int i = 0;
do_until(
[&] { return i++ > max_retry || loading_cache.find(0) == loading_cache.end(); },
[] { return sleep(40ms); }
).get();
BOOST_REQUIRE(loading_cache.find(0) == loading_cache.end());
});
}
SEASTAR_TEST_CASE(test_loading_cache_loading_reloading) {
return seastar::async([] {
using namespace std::chrono;
load_count = 0;
utils::loading_cache<int, sstring, utils::loading_cache_reload_enabled::yes> loading_cache(num_loaders, 100ms, 20ms, test_logger, loader);
auto stop_cache_reload = seastar::defer([&loading_cache] { loading_cache.stop().get(); });
prepare().get();
loading_cache.get_ptr(0, loader).discard_result().get();
sleep(60ms).get();
BOOST_REQUIRE_MESSAGE(load_count >= 2, format("load_count is {}", load_count));
});
}
SEASTAR_TEST_CASE(test_loading_cache_max_size_eviction) {
return seastar::async([] {
using namespace std::chrono;
load_count = 0;
utils::loading_cache<int, sstring> loading_cache(1, 1s, test_logger);
auto stop_cache_reload = seastar::defer([&loading_cache] { loading_cache.stop().get(); });
prepare().get();
for (int i = 0; i < num_loaders; ++i) {
loading_cache.get_ptr(i % 2, loader).discard_result().get();
}
BOOST_REQUIRE_EQUAL(load_count, num_loaders);
BOOST_REQUIRE_EQUAL(loading_cache.size(), 1);
});
}
SEASTAR_TEST_CASE(test_loading_cache_reload_during_eviction) {
return seastar::async([] {
using namespace std::chrono;
load_count = 0;
utils::loading_cache<int, sstring, utils::loading_cache_reload_enabled::yes> loading_cache(1, 100ms, 10ms, test_logger, loader);
auto stop_cache_reload = seastar::defer([&loading_cache] { loading_cache.stop().get(); });
prepare().get();
auto curr_time = lowres_clock::now();
int i = 0;
// this will cause reloading when values are being actively evicted due to the limited cache size
do_until(
[&] { return lowres_clock::now() - curr_time > 1s; },
[&] { return loading_cache.get_ptr(i++ % 2).discard_result(); }
).get();
BOOST_REQUIRE_EQUAL(loading_cache.size(), 1);
});
}<|endoftext|> |
<commit_before>/***************************************************************************
msxml.cpp - XML Helper
-------------------
begin : sam mai 17 2003
copyright : (C) 2003 by Michael CATANZARITI
email : [email protected]
***************************************************************************/
/***************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* *
* This software is published under the terms of the Apache Software *
* License version 1.1, a copy of which has been included with this *
* distribution in the LICENSE.txt file. *
***************************************************************************/
#include <log4cxx/config.h>
#ifdef HAVE_MS_XML
#include <log4cxx/helpers/msxml.h>
#include <log4cxx/helpers/loglog.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(MsXMLDOMDocument)
IMPLEMENT_LOG4CXX_OBJECT(MsXMLDOMNodeList)
IMPLEMENT_LOG4CXX_OBJECT(MsXMLDOMNode)
IMPLEMENT_LOG4CXX_OBJECT(MsXMLDOMElement)
#define EXEC(stmt) { HRESULT hr = stmt; if (FAILED(hr)) throw DOMException(); }
// MsXMLDOMNode
MsXMLDOMNode::MsXMLDOMNode(MSXML::IXMLDOMNodePtr node)
: node(node)
{
}
XMLDOMNodeListPtr MsXMLDOMNode::getChildNodes()
{
MSXML::IXMLDOMNodeListPtr nodeList;
EXEC(node->get_childNodes(&nodeList));
return new MsXMLDOMNodeList(nodeList);
}
XMLDOMDocumentPtr MsXMLDOMNode::getOwnerDocument()
{
MSXML::IXMLDOMDocumentPtr document;
EXEC(node->get_ownerDocument(&document));
return new MsXMLDOMDocument(document);
}
// MsXMLDOMDocument
MsXMLDOMDocument::MsXMLDOMDocument(MSXML::IXMLDOMDocumentPtr document)
: document(document)
{
}
MsXMLDOMDocument::MsXMLDOMDocument()
{
HRESULT hRes;
hRes = document.CreateInstance(L"Msxml2.DOMDocument.3.0");
if (FAILED(hRes))
{
hRes = document.CreateInstance(L"Msxml2.DOMDocument.2.6");
if (FAILED(hRes))
{
hRes = document.CreateInstance(L"Msxml2.DOMDocument");
if (FAILED(hRes))
{
hRes = document.CreateInstance(L"Msxml.DOMDocument");
if (FAILED(hRes))
{
throw DOMException();
}
}
}
}
}
XMLDOMNodeListPtr MsXMLDOMDocument::getChildNodes()
{
MSXML::IXMLDOMNodeListPtr nodeList;
EXEC(document->get_childNodes(&nodeList));
return new MsXMLDOMNodeList(nodeList);
}
XMLDOMDocumentPtr MsXMLDOMDocument::getOwnerDocument()
{
return this;
}
void MsXMLDOMDocument::load(const String& fileName)
{
try
{
VARIANT_BOOL bSuccess = document->load(fileName.c_str());
if (!bSuccess)
{
MSXML::IXMLDOMParseErrorPtr parseError = document->parseError;
// fetch errorcode
long errorCode = parseError->errorCode;
// XML file not found
if (errorCode == INET_E_RESOURCE_NOT_FOUND)
{
LogLog::error(_T("Could not find [")+fileName+_T("]."));
}
else
{
_bstr_t reason = parseError->reason;
long line = parseError->line;
long linepos = parseError->linepos;
// remove \n or \r
int len = reason.length();
while(len > 0 && (((BSTR)reason)[len -1] == L'\n' ||
((BSTR)reason)[len -1] == L'\r'))
{
((BSTR)reason)[len -1] = L'\0';
len--;
}
USES_CONVERSION;
LOGLOG_ERROR(_T("Could not open [") << fileName << _T("] : ")
<< W2T((BSTR)reason) << _T("(line ") << line << _T(", column ")
<< linepos << _T(")"));
}
}
}
catch(_com_error&)
{
LogLog::error(_T("Could not open [")+fileName+_T("]."));
throw DOMException();
}
}
XMLDOMElementPtr MsXMLDOMDocument::getDocumentElement()
{
MSXML::IXMLDOMElementPtr element;
EXEC(document->get_documentElement(&element));
return new MsXMLDOMElement(element);
}
XMLDOMElementPtr MsXMLDOMDocument::getElementById(const String& tagName, const String& elementId)
{
MSXML::IXMLDOMElementPtr element;
try
{
MSXML::IXMLDOMNodeListPtr list = document->getElementsByTagName(tagName.c_str());
for (int t=0; t < list->length; t++)
{
MSXML::IXMLDOMNodePtr node = list->item[t];
MSXML::IXMLDOMNamedNodeMapPtr map= node->attributes;
MSXML::IXMLDOMNodePtr attrNode = map->getNamedItem(L"name");
_bstr_t nodeValue = attrNode->nodeValue;
USES_CONVERSION;
if (elementId == W2T((BSTR)nodeValue))
{
element = node;
break;
}
}
}
catch(_com_error&)
{
throw DOMException();
}
return new MsXMLDOMElement(element);
}
// MsXMLDOMElement
MsXMLDOMElement::MsXMLDOMElement(MSXML::IXMLDOMElementPtr element)
: element(element)
{
}
XMLDOMNodeListPtr MsXMLDOMElement::getChildNodes()
{
MSXML::IXMLDOMNodeListPtr nodeList;
EXEC(element->get_childNodes(&nodeList));
return new MsXMLDOMNodeList(nodeList);
}
XMLDOMDocumentPtr MsXMLDOMElement::getOwnerDocument()
{
MSXML::IXMLDOMDocumentPtr document;
EXEC(element->get_ownerDocument(&document));
return new MsXMLDOMDocument(document);
}
String MsXMLDOMElement::getTagName()
{
try
{
_bstr_t tagName = element->tagName;
USES_CONVERSION;
return W2T((BSTR)tagName);
}
catch(_com_error&)
{
throw DOMException();
}
}
String MsXMLDOMElement::getAttribute(const String& name)
{
try
{
_variant_t attribute = element->getAttribute(name.c_str());
if (attribute.vt == VT_NULL)
{
return String();
}
else
{
return (const TCHAR *)_bstr_t(attribute);
}
}
catch(_com_error&)
{
throw DOMException();
}
}
// MsXMLDOMNodeList
MsXMLDOMNodeList::MsXMLDOMNodeList(MSXML::IXMLDOMNodeListPtr nodeList)
: nodeList(nodeList)
{
}
int MsXMLDOMNodeList::getLength()
{
long length;
EXEC(nodeList->get_length(&length));
return (int)length;
}
XMLDOMNodePtr MsXMLDOMNodeList::item(int index)
{
try
{
MSXML::IXMLDOMNodePtr node = nodeList->item[index];
if (node->nodeType == MSXML::NODE_ELEMENT)
{
return new MsXMLDOMElement(MSXML::IXMLDOMElementPtr(node));
}
else
{
return new MsXMLDOMNode(node);
}
}
catch(_com_error&)
{
throw DOMException();
}
}
#endif<commit_msg>Added automatic COM Initialization Improved error management<commit_after>/***************************************************************************
msxml.cpp - XML Helper
-------------------
begin : sam mai 17 2003
copyright : (C) 2003 by Michael CATANZARITI
email : [email protected]
***************************************************************************/
/***************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* *
* This software is published under the terms of the Apache Software *
* License version 1.1, a copy of which has been included with this *
* distribution in the LICENSE.txt file. *
***************************************************************************/
#define _WIN32_DCOM
#include <log4cxx/config.h>
#ifdef HAVE_MS_XML
#include <log4cxx/helpers/msxml.h>
#include <log4cxx/helpers/loglog.h>
#include <objbase.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(MsXMLDOMDocument)
IMPLEMENT_LOG4CXX_OBJECT(MsXMLDOMNodeList)
IMPLEMENT_LOG4CXX_OBJECT(MsXMLDOMNode)
IMPLEMENT_LOG4CXX_OBJECT(MsXMLDOMElement)
#define EXEC(stmt) { HRESULT hr = stmt; if (FAILED(hr)) throw DOMException(); }
// MsXMLDOMNode
MsXMLDOMNode::MsXMLDOMNode(MSXML::IXMLDOMNodePtr node)
: node(node)
{
}
XMLDOMNodeListPtr MsXMLDOMNode::getChildNodes()
{
MSXML::IXMLDOMNodeListPtr nodeList;
EXEC(node->get_childNodes(&nodeList));
return new MsXMLDOMNodeList(nodeList);
}
XMLDOMDocumentPtr MsXMLDOMNode::getOwnerDocument()
{
MSXML::IXMLDOMDocumentPtr document;
EXEC(node->get_ownerDocument(&document));
return new MsXMLDOMDocument(document);
}
// MsXMLDOMDocument
MsXMLDOMDocument::MsXMLDOMDocument(MSXML::IXMLDOMDocumentPtr document)
: document(document)
{
::CoInitializeEx(0, COINIT_MULTITHREADED);
}
MsXMLDOMDocument::MsXMLDOMDocument()
{
::CoInitializeEx(0, COINIT_MULTITHREADED);
HRESULT hRes;
hRes = document.CreateInstance(L"Msxml2.DOMDocument.3.0");
if (FAILED(hRes))
{
hRes = document.CreateInstance(L"Msxml2.DOMDocument.2.6");
if (FAILED(hRes))
{
hRes = document.CreateInstance(L"Msxml2.DOMDocument");
if (FAILED(hRes))
{
hRes = document.CreateInstance(L"Msxml.DOMDocument");
if (FAILED(hRes))
{
throw DOMException();
}
}
}
}
}
MsXMLDOMDocument::~MsXMLDOMDocument()
{
document.Release();
::CoUninitialize();
}
XMLDOMNodeListPtr MsXMLDOMDocument::getChildNodes()
{
MSXML::IXMLDOMNodeListPtr nodeList;
EXEC(document->get_childNodes(&nodeList));
return new MsXMLDOMNodeList(nodeList);
}
XMLDOMDocumentPtr MsXMLDOMDocument::getOwnerDocument()
{
return this;
}
void MsXMLDOMDocument::load(const String& fileName)
{
try
{
VARIANT_BOOL bSuccess = document->load(fileName.c_str());
if (!bSuccess)
{
MSXML::IXMLDOMParseErrorPtr parseError = document->parseError;
// fetch errorcode
long errorCode = parseError->errorCode;
_bstr_t reason = parseError->reason;
long line = parseError->line;
long linepos = parseError->linepos;
// remove \n or \r
int len = reason.length();
while(len > 0 && (((BSTR)reason)[len -1] == L'\n' ||
((BSTR)reason)[len -1] == L'\r'))
{
((BSTR)reason)[len -1] = L'\0';
len--;
}
USES_CONVERSION;
LOGLOG_ERROR(_T("Could not open [") << fileName << _T("] : ")
<< W2T((BSTR)reason) << _T("(line ") << line << _T(", column ")
<< linepos << _T(")"));
}
}
catch(_com_error&)
{
LogLog::error(_T("Could not open [")+fileName+_T("]."));
throw DOMException();
}
}
XMLDOMElementPtr MsXMLDOMDocument::getDocumentElement()
{
MSXML::IXMLDOMElementPtr element;
EXEC(document->get_documentElement(&element));
return new MsXMLDOMElement(element);
}
XMLDOMElementPtr MsXMLDOMDocument::getElementById(const String& tagName, const String& elementId)
{
MSXML::IXMLDOMElementPtr element;
try
{
MSXML::IXMLDOMNodeListPtr list = document->getElementsByTagName(tagName.c_str());
for (int t=0; t < list->length; t++)
{
MSXML::IXMLDOMNodePtr node = list->item[t];
MSXML::IXMLDOMNamedNodeMapPtr map= node->attributes;
MSXML::IXMLDOMNodePtr attrNode = map->getNamedItem(L"name");
_bstr_t nodeValue = attrNode->nodeValue;
USES_CONVERSION;
if (elementId == W2T((BSTR)nodeValue))
{
element = node;
break;
}
}
}
catch(_com_error&)
{
throw DOMException();
}
return new MsXMLDOMElement(element);
}
// MsXMLDOMElement
MsXMLDOMElement::MsXMLDOMElement(MSXML::IXMLDOMElementPtr element)
: element(element)
{
}
XMLDOMNodeListPtr MsXMLDOMElement::getChildNodes()
{
MSXML::IXMLDOMNodeListPtr nodeList;
EXEC(element->get_childNodes(&nodeList));
return new MsXMLDOMNodeList(nodeList);
}
XMLDOMDocumentPtr MsXMLDOMElement::getOwnerDocument()
{
MSXML::IXMLDOMDocumentPtr document;
EXEC(element->get_ownerDocument(&document));
return new MsXMLDOMDocument(document);
}
String MsXMLDOMElement::getTagName()
{
try
{
_bstr_t tagName = element->tagName;
USES_CONVERSION;
return W2T((BSTR)tagName);
}
catch(_com_error&)
{
throw DOMException();
}
}
String MsXMLDOMElement::getAttribute(const String& name)
{
try
{
_variant_t attribute = element->getAttribute(name.c_str());
if (attribute.vt == VT_NULL)
{
return String();
}
else
{
return (const TCHAR *)_bstr_t(attribute);
}
}
catch(_com_error&)
{
throw DOMException();
}
}
// MsXMLDOMNodeList
MsXMLDOMNodeList::MsXMLDOMNodeList(MSXML::IXMLDOMNodeListPtr nodeList)
: nodeList(nodeList)
{
}
int MsXMLDOMNodeList::getLength()
{
long length;
EXEC(nodeList->get_length(&length));
return (int)length;
}
XMLDOMNodePtr MsXMLDOMNodeList::item(int index)
{
try
{
MSXML::IXMLDOMNodePtr node = nodeList->item[index];
if (node->nodeType == MSXML::NODE_ELEMENT)
{
return new MsXMLDOMElement(MSXML::IXMLDOMElementPtr(node));
}
else
{
return new MsXMLDOMNode(node);
}
}
catch(_com_error&)
{
throw DOMException();
}
}
#endif<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Daniel Nicoletti <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "utils.h"
#include <QTextStream>
using namespace Cutelyst;
QByteArray buildTableDivision(const QList<int> &columnsSize)
{
QByteArray buffer;
QTextStream out(&buffer, QIODevice::WriteOnly);
for (int i = 0; i < columnsSize.size(); ++i) {
if (i) {
out << "+";
} else {
out << ".";
}
out << QByteArray().fill('-', columnsSize[i] + 2).data();
}
out << "." << endl;
return buffer;
}
QByteArray Utils::buildTable(const QList<QStringList> &table, const QStringList &headers, const QString &title)
{
QList<int> columnsSize;
if (!headers.isEmpty()) {
Q_FOREACH (const QString &header, headers) {
columnsSize.append(header.size());
}
} else {
Q_FOREACH (const QStringList &rows, table) {
if (columnsSize.isEmpty()) {
Q_FOREACH (const QString &row, rows) {
columnsSize.append(row.size());
}
} else if (rows.size() != columnsSize.size()) {
qFatal("Incomplete table");
}
}
}
Q_FOREACH (const QStringList &row, table) {
if (row.size() > columnsSize.size()) {
qFatal("Incomplete table");
break;
}
for (int i = 0; i < row.size(); ++i) {
columnsSize[i] = qMax(columnsSize[i], row[i].size());
}
}
// printing
QByteArray buffer;
QTextStream out(&buffer, QIODevice::WriteOnly);
QByteArray div = buildTableDivision(columnsSize);
if (!title.isEmpty()) {
out << title << endl;
}
// Top line
out << div;
if (!headers.isEmpty()) {
// header titles
for (int i = 0; i < headers.size(); ++i) {
out << "| " << headers[i].leftJustified(columnsSize[i]) << ' ';
}
out << '|' << endl;
// header bottom line
out << div;
}
Q_FOREACH (const QStringList &row, table) {
// content table
for (int i = 0; i < row.size(); ++i) {
out << "| " << row[i].leftJustified(columnsSize[i]) << ' ';
}
out << '|' << endl;
}
// table bottom line
out << div;
return buffer;
}
<commit_msg>Use QTextStream setFieldWidth instad of leftJustify<commit_after>/*
* Copyright (C) 2015 Daniel Nicoletti <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "utils.h"
#include <QTextStream>
using namespace Cutelyst;
QByteArray buildTableDivision(const QList<int> &columnsSize)
{
QByteArray buffer;
QTextStream out(&buffer, QIODevice::WriteOnly);
for (int i = 0; i < columnsSize.size(); ++i) {
if (i) {
out << "+";
} else {
out << ".";
}
out << QByteArray().fill('-', columnsSize[i] + 2).data();
}
out << "." << endl;
return buffer;
}
QByteArray Utils::buildTable(const QList<QStringList> &table, const QStringList &headers, const QString &title)
{
QList<int> columnsSize;
if (!headers.isEmpty()) {
Q_FOREACH (const QString &header, headers) {
columnsSize.append(header.size());
}
} else {
Q_FOREACH (const QStringList &rows, table) {
if (columnsSize.isEmpty()) {
Q_FOREACH (const QString &row, rows) {
columnsSize.append(row.size());
}
} else if (rows.size() != columnsSize.size()) {
qFatal("Incomplete table");
}
}
}
Q_FOREACH (const QStringList &row, table) {
if (row.size() > columnsSize.size()) {
qFatal("Incomplete table");
break;
}
for (int i = 0; i < row.size(); ++i) {
columnsSize[i] = qMax(columnsSize[i], row[i].size());
}
}
// printing
QByteArray buffer;
QTextStream out(&buffer, QIODevice::WriteOnly);
out.setFieldAlignment(QTextStream::AlignLeft);
QByteArray div = buildTableDivision(columnsSize);
if (!title.isEmpty()) {
out << title << endl;
}
// Top line
out << div;
if (!headers.isEmpty()) {
// header titles
for (int i = 0; i < headers.size(); ++i) {
out << "| ";
out.setFieldWidth(columnsSize[i]);
out << headers[i];
out.setFieldWidth(0);
out << ' ';
}
out << '|' << endl;
// header bottom line
out << div;
}
Q_FOREACH (const QStringList &row, table) {
// content table
for (int i = 0; i < row.size(); ++i) {
out << "| ";
out.setFieldWidth(columnsSize[i]);
out << row[i];
out.setFieldWidth(0);
out << ' ';
}
out << '|' << endl;
}
// table bottom line
out << div;
return buffer;
}
<|endoftext|> |
<commit_before>
#pragma once
#include <string>
#include "NamedObject.hpp"
namespace werk
{
/**
* An abstract class that represents an action to be executed one or more
* times, but not in an ongoing fashion (should not execute indefinitely).
*
* Named to enable easier debugging.
*/
class Action : public NamedObject
{
public:
Action(const std::string &name) : NamedObject(name) { }
virtual void execute() = 0;
};
/**
* Do nothing action.
*/
class NullAction : public Action
{
public:
NullAction(const std::string &name) : Action(name) { }
void execute() override { }
};
/**
* An action that increments a counter every time it is executed. Very useful
* for testing, and appropriate where an entirely separate `Counter` would be
* inconvenient.
*/
template <typename T=uint64_t>
class CounterAction : public Action
{
public:
CounterAction(const std::string &name) : Action(name) { }
T count() const { return _count; }
void reset() const { _count = 0; }
void execute() override { _count += 1; }
private:
T _count = 0;
};
/**
* An action that resets a component (many components have a `void reset()` method).
*/
template <typename T>
class ResetAction : public Action
{
public:
ResetAction(const std::string &name, T &object) :
Action(name), _object(object) { }
void execute() override { _object.reset(); }
private:
T &_object;
};
}
<commit_msg>Implement PairAction and CompoundAction (closing #68)<commit_after>
#pragma once
#include <string>
#include <vector>
#include "NamedObject.hpp"
namespace werk
{
/**
* An abstract class that represents an action to be executed one or more
* times, but not in an ongoing fashion (should not execute indefinitely).
*
* Named to enable easier debugging.
*/
class Action : public NamedObject
{
public:
Action(const std::string &name) : NamedObject(name) { }
virtual void execute() = 0;
};
/**
* Do nothing action.
*/
class NullAction : public Action
{
public:
NullAction(const std::string &name) : Action(name) { }
void execute() override { }
};
/**
* An action that increments a counter every time it is executed. Very useful
* for testing, and appropriate where an entirely separate `Counter` would be
* inconvenient.
*/
template <typename T=uint64_t>
class CounterAction : public Action
{
public:
CounterAction(const std::string &name) : Action(name) { }
T count() const { return _count; }
void reset() const { _count = 0; }
void execute() override { _count += 1; }
private:
T _count = 0;
};
/**
* An action that executes a pair of other actions.
*/
class CompoundAction : public Action
{
public:
CompoundAction(const std::string &name) : Action(name) { }
std::vector<Action *> &actions() { return _actions; }
const std::vector<Action *> &actions() const { return _actions; }
void execute() override {
for (Action *action : _actions) {
action->execute();
}
}
private:
std::vector<Action *> _actions;
};
/**
* An action that executes a pair of other actions.
*/
class PairAction : public Action
{
public:
PairAction(const std::string &name, Action *action1, Action *action2) :
Action(name), _action1(action1), _action2(action2) { }
void execute() override {
_action1->execute();
_action2->execute();
}
private:
Action *_action1;
Action *_action2;
};
/**
* An action that resets a component (many components have a `void reset()` method).
*/
template <typename T>
class ResetAction : public Action
{
public:
ResetAction(const std::string &name, T &object) :
Action(name), _object(object) { }
void execute() override { _object.reset(); }
private:
T &_object;
};
}
<|endoftext|> |
<commit_before>//===------------------------- mutex.cpp ----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "mutex"
#include "limits"
#include "system_error"
#include "include/atomic_support.h"
#include "__undef_macros"
_LIBCPP_BEGIN_NAMESPACE_STD
#ifndef _LIBCPP_HAS_NO_THREADS
const defer_lock_t defer_lock = {};
const try_to_lock_t try_to_lock = {};
const adopt_lock_t adopt_lock = {};
mutex::~mutex()
{
__libcpp_mutex_destroy(&__m_);
}
void
mutex::lock()
{
int ec = __libcpp_mutex_lock(&__m_);
if (ec)
__throw_system_error(ec, "mutex lock failed");
}
bool
mutex::try_lock() _NOEXCEPT
{
return __libcpp_mutex_trylock(&__m_);
}
void
mutex::unlock() _NOEXCEPT
{
int ec = __libcpp_mutex_unlock(&__m_);
(void)ec;
_LIBCPP_ASSERT(ec == 0, "call to mutex::unlock failed");
}
// recursive_mutex
recursive_mutex::recursive_mutex()
{
int ec = __libcpp_recursive_mutex_init(&__m_);
if (ec)
__throw_system_error(ec, "recursive_mutex constructor failed");
}
recursive_mutex::~recursive_mutex()
{
int e = __libcpp_recursive_mutex_destroy(&__m_);
(void)e;
_LIBCPP_ASSERT(e == 0, "call to ~recursive_mutex() failed");
}
void
recursive_mutex::lock()
{
int ec = __libcpp_recursive_mutex_lock(&__m_);
if (ec)
__throw_system_error(ec, "recursive_mutex lock failed");
}
void
recursive_mutex::unlock() _NOEXCEPT
{
int e = __libcpp_recursive_mutex_unlock(&__m_);
(void)e;
_LIBCPP_ASSERT(e == 0, "call to recursive_mutex::unlock() failed");
}
bool
recursive_mutex::try_lock() _NOEXCEPT
{
return __libcpp_recursive_mutex_trylock(&__m_);
}
// timed_mutex
timed_mutex::timed_mutex()
: __locked_(false)
{
}
timed_mutex::~timed_mutex()
{
lock_guard<mutex> _(__m_);
}
void
timed_mutex::lock()
{
unique_lock<mutex> lk(__m_);
while (__locked_)
__cv_.wait(lk);
__locked_ = true;
}
bool
timed_mutex::try_lock() _NOEXCEPT
{
unique_lock<mutex> lk(__m_, try_to_lock);
if (lk.owns_lock() && !__locked_)
{
__locked_ = true;
return true;
}
return false;
}
void
timed_mutex::unlock() _NOEXCEPT
{
lock_guard<mutex> _(__m_);
__locked_ = false;
__cv_.notify_one();
}
// recursive_timed_mutex
recursive_timed_mutex::recursive_timed_mutex()
: __count_(0),
__id_(0)
{
}
recursive_timed_mutex::~recursive_timed_mutex()
{
lock_guard<mutex> _(__m_);
}
void
recursive_timed_mutex::lock()
{
__libcpp_thread_id id = __libcpp_thread_get_current_id();
unique_lock<mutex> lk(__m_);
if (__libcpp_thread_id_equal(id, __id_))
{
if (__count_ == numeric_limits<size_t>::max())
__throw_system_error(EAGAIN, "recursive_timed_mutex lock limit reached");
++__count_;
return;
}
while (__count_ != 0)
__cv_.wait(lk);
__count_ = 1;
__id_ = id;
}
bool
recursive_timed_mutex::try_lock() _NOEXCEPT
{
__libcpp_thread_id id = __libcpp_thread_get_current_id();
unique_lock<mutex> lk(__m_, try_to_lock);
if (lk.owns_lock() && (__count_ == 0 || __libcpp_thread_id_equal(id, __id_)))
{
if (__count_ == numeric_limits<size_t>::max())
return false;
++__count_;
__id_ = id;
return true;
}
return false;
}
void
recursive_timed_mutex::unlock() _NOEXCEPT
{
unique_lock<mutex> lk(__m_);
if (--__count_ == 0)
{
__id_ = 0;
lk.unlock();
__cv_.notify_one();
}
}
#endif // !_LIBCPP_HAS_NO_THREADS
// If dispatch_once_f ever handles C++ exceptions, and if one can get to it
// without illegal macros (unexpected macros not beginning with _UpperCase or
// __lowercase), and if it stops spinning waiting threads, then call_once should
// call into dispatch_once_f instead of here. Relevant radar this code needs to
// keep in sync with: 7741191.
#ifndef _LIBCPP_HAS_NO_THREADS
_LIBCPP_SAFE_STATIC static __libcpp_mutex_t mut = _LIBCPP_MUTEX_INITIALIZER;
_LIBCPP_SAFE_STATIC static __libcpp_condvar_t cv = _LIBCPP_CONDVAR_INITIALIZER;
#endif
void __call_once(volatile once_flag::_State_type& flag, void* arg,
void (*func)(void*))
{
#if defined(_LIBCPP_HAS_NO_THREADS)
if (flag == 0)
{
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
flag = 1;
func(arg);
flag = ~once_flag::_State_type(0);
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
flag = 0;
throw;
}
#endif // _LIBCPP_NO_EXCEPTIONS
}
#else // !_LIBCPP_HAS_NO_THREADS
__libcpp_mutex_lock(&mut);
while (flag == 1)
__libcpp_condvar_wait(&cv, &mut);
if (flag == 0)
{
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
__libcpp_relaxed_store(&flag, once_flag::_State_type(1));
__libcpp_mutex_unlock(&mut);
func(arg);
__libcpp_mutex_lock(&mut);
__libcpp_atomic_store(&flag, ~once_flag::_State_type(0),
_AO_Release);
__libcpp_mutex_unlock(&mut);
__libcpp_condvar_broadcast(&cv);
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
__libcpp_mutex_lock(&mut);
__libcpp_relaxed_store(&flag, once_flag::_State_type(0));
__libcpp_mutex_unlock(&mut);
__libcpp_condvar_broadcast(&cv);
throw;
}
#endif // _LIBCPP_NO_EXCEPTIONS
}
else
__libcpp_mutex_unlock(&mut);
#endif // !_LIBCPP_HAS_NO_THREADS
}
_LIBCPP_END_NAMESPACE_STD
<commit_msg>Fix r359229 which tried to fix r359159...<commit_after>//===------------------------- mutex.cpp ----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "mutex"
#include "limits"
#include "system_error"
#include "include/atomic_support.h"
#include "__undef_macros"
_LIBCPP_BEGIN_NAMESPACE_STD
#ifndef _LIBCPP_HAS_NO_THREADS
const defer_lock_t defer_lock = {};
const try_to_lock_t try_to_lock = {};
const adopt_lock_t adopt_lock = {};
mutex::~mutex() _NOEXCEPT
{
__libcpp_mutex_destroy(&__m_);
}
void
mutex::lock()
{
int ec = __libcpp_mutex_lock(&__m_);
if (ec)
__throw_system_error(ec, "mutex lock failed");
}
bool
mutex::try_lock() _NOEXCEPT
{
return __libcpp_mutex_trylock(&__m_);
}
void
mutex::unlock() _NOEXCEPT
{
int ec = __libcpp_mutex_unlock(&__m_);
(void)ec;
_LIBCPP_ASSERT(ec == 0, "call to mutex::unlock failed");
}
// recursive_mutex
recursive_mutex::recursive_mutex()
{
int ec = __libcpp_recursive_mutex_init(&__m_);
if (ec)
__throw_system_error(ec, "recursive_mutex constructor failed");
}
recursive_mutex::~recursive_mutex()
{
int e = __libcpp_recursive_mutex_destroy(&__m_);
(void)e;
_LIBCPP_ASSERT(e == 0, "call to ~recursive_mutex() failed");
}
void
recursive_mutex::lock()
{
int ec = __libcpp_recursive_mutex_lock(&__m_);
if (ec)
__throw_system_error(ec, "recursive_mutex lock failed");
}
void
recursive_mutex::unlock() _NOEXCEPT
{
int e = __libcpp_recursive_mutex_unlock(&__m_);
(void)e;
_LIBCPP_ASSERT(e == 0, "call to recursive_mutex::unlock() failed");
}
bool
recursive_mutex::try_lock() _NOEXCEPT
{
return __libcpp_recursive_mutex_trylock(&__m_);
}
// timed_mutex
timed_mutex::timed_mutex()
: __locked_(false)
{
}
timed_mutex::~timed_mutex()
{
lock_guard<mutex> _(__m_);
}
void
timed_mutex::lock()
{
unique_lock<mutex> lk(__m_);
while (__locked_)
__cv_.wait(lk);
__locked_ = true;
}
bool
timed_mutex::try_lock() _NOEXCEPT
{
unique_lock<mutex> lk(__m_, try_to_lock);
if (lk.owns_lock() && !__locked_)
{
__locked_ = true;
return true;
}
return false;
}
void
timed_mutex::unlock() _NOEXCEPT
{
lock_guard<mutex> _(__m_);
__locked_ = false;
__cv_.notify_one();
}
// recursive_timed_mutex
recursive_timed_mutex::recursive_timed_mutex()
: __count_(0),
__id_(0)
{
}
recursive_timed_mutex::~recursive_timed_mutex()
{
lock_guard<mutex> _(__m_);
}
void
recursive_timed_mutex::lock()
{
__libcpp_thread_id id = __libcpp_thread_get_current_id();
unique_lock<mutex> lk(__m_);
if (__libcpp_thread_id_equal(id, __id_))
{
if (__count_ == numeric_limits<size_t>::max())
__throw_system_error(EAGAIN, "recursive_timed_mutex lock limit reached");
++__count_;
return;
}
while (__count_ != 0)
__cv_.wait(lk);
__count_ = 1;
__id_ = id;
}
bool
recursive_timed_mutex::try_lock() _NOEXCEPT
{
__libcpp_thread_id id = __libcpp_thread_get_current_id();
unique_lock<mutex> lk(__m_, try_to_lock);
if (lk.owns_lock() && (__count_ == 0 || __libcpp_thread_id_equal(id, __id_)))
{
if (__count_ == numeric_limits<size_t>::max())
return false;
++__count_;
__id_ = id;
return true;
}
return false;
}
void
recursive_timed_mutex::unlock() _NOEXCEPT
{
unique_lock<mutex> lk(__m_);
if (--__count_ == 0)
{
__id_ = 0;
lk.unlock();
__cv_.notify_one();
}
}
#endif // !_LIBCPP_HAS_NO_THREADS
// If dispatch_once_f ever handles C++ exceptions, and if one can get to it
// without illegal macros (unexpected macros not beginning with _UpperCase or
// __lowercase), and if it stops spinning waiting threads, then call_once should
// call into dispatch_once_f instead of here. Relevant radar this code needs to
// keep in sync with: 7741191.
#ifndef _LIBCPP_HAS_NO_THREADS
_LIBCPP_SAFE_STATIC static __libcpp_mutex_t mut = _LIBCPP_MUTEX_INITIALIZER;
_LIBCPP_SAFE_STATIC static __libcpp_condvar_t cv = _LIBCPP_CONDVAR_INITIALIZER;
#endif
void __call_once(volatile once_flag::_State_type& flag, void* arg,
void (*func)(void*))
{
#if defined(_LIBCPP_HAS_NO_THREADS)
if (flag == 0)
{
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
flag = 1;
func(arg);
flag = ~once_flag::_State_type(0);
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
flag = 0;
throw;
}
#endif // _LIBCPP_NO_EXCEPTIONS
}
#else // !_LIBCPP_HAS_NO_THREADS
__libcpp_mutex_lock(&mut);
while (flag == 1)
__libcpp_condvar_wait(&cv, &mut);
if (flag == 0)
{
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
__libcpp_relaxed_store(&flag, once_flag::_State_type(1));
__libcpp_mutex_unlock(&mut);
func(arg);
__libcpp_mutex_lock(&mut);
__libcpp_atomic_store(&flag, ~once_flag::_State_type(0),
_AO_Release);
__libcpp_mutex_unlock(&mut);
__libcpp_condvar_broadcast(&cv);
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
__libcpp_mutex_lock(&mut);
__libcpp_relaxed_store(&flag, once_flag::_State_type(0));
__libcpp_mutex_unlock(&mut);
__libcpp_condvar_broadcast(&cv);
throw;
}
#endif // _LIBCPP_NO_EXCEPTIONS
}
else
__libcpp_mutex_unlock(&mut);
#endif // !_LIBCPP_HAS_NO_THREADS
}
_LIBCPP_END_NAMESPACE_STD
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: scriptinfo.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2004-04-27 13:42:22 $
*
* 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 _SCRIPTINFO_HXX
#define _SCRIPTINFO_HXX
#ifndef _SVSTDARR_HXX
#define _SVSTDARR_SHORTS
#define _SVSTDARR_BYTES
#define _SVSTDARR_USHORTS
#define _SVSTDARR_XUB_STRLEN
#include <svtools/svstdarr.hxx>
#endif
#ifndef _LANG_HXX
#include <tools/lang.hxx>
#endif
#include <list>
class SwWrongList;
class SwTxtNode;
class Point;
class MultiSelection;
typedef std::list< xub_StrLen > PositionList;
/*************************************************************************
* class SwScanner
* Hilfsklasse, die beim Spellen die Worte im gewuenschten Bereich
* nacheinander zur Verfuegung stellt.
*************************************************************************/
class SwScanner
{
XubString aWord;
const SwWrongList* pWrong;
const SwTxtNode& rNode;
xub_StrLen nEndPos;
xub_StrLen nBegin;
xub_StrLen nLen;
LanguageType aCurrLang;
USHORT nWordType;
BOOL bReverse;
BOOL bStart;
BOOL bIsOnlineSpell;
public:
SwScanner( const SwTxtNode& rNd, const SwWrongList* pWrng, USHORT nWordType,
xub_StrLen nStart, xub_StrLen nEnde, BOOL bRev, BOOL bOS );
// This next word function tries to find the language for the next word
// It should currently _not_ be used for spell checking, and works only for
// ! bReverse
BOOL NextWord();
BOOL NextWord( LanguageType aLang );
const XubString& GetWord() const { return aWord; }
xub_StrLen GetBegin() const { return nBegin; }
xub_StrLen GetEnd() const { return nBegin + nLen; }
xub_StrLen GetLen() const { return nLen; }
};
/*************************************************************************
* class SwScriptInfo
*
* encapsultes information about script changes
*************************************************************************/
class SwScriptInfo
{
private:
SvXub_StrLens aScriptChg;
SvBytes aScriptType;
SvXub_StrLens aDirChg;
SvBytes aDirType;
SvXub_StrLens aKashida;
SvXub_StrLens aCompChg;
SvXub_StrLens aCompLen;
SvXub_StrLens aHiddenChg;
SvBytes aCompType;
xub_StrLen nInvalidityPos;
BYTE nDefaultDir;
void UpdateBidiInfo( const String& rTxt );
public:
enum CompType { KANA, SPECIAL_LEFT, SPECIAL_RIGHT, NONE };
inline SwScriptInfo() : nInvalidityPos( 0 ), nDefaultDir( 0 ) {};
// determines script changes
void InitScriptInfo( const SwTxtNode& rNode, sal_Bool bRTL );
void InitScriptInfo( const SwTxtNode& rNode );
// set/get position from which data is invalid
inline void SetInvalidity( const xub_StrLen nPos );
inline xub_StrLen GetInvalidity() const { return nInvalidityPos; };
// get default direction for paragraph
inline BYTE GetDefaultDir() const { return nDefaultDir; };
// array operations, nCnt refers to array position
inline USHORT CountScriptChg() const;
inline xub_StrLen GetScriptChg( const USHORT nCnt ) const;
inline BYTE GetScriptType( const USHORT nCnt ) const;
inline USHORT CountDirChg() const;
inline xub_StrLen GetDirChg( const USHORT nCnt ) const;
inline BYTE GetDirType( const USHORT nCnt ) const;
inline USHORT CountKashida() const;
inline xub_StrLen GetKashida( const USHORT nCnt ) const;
inline USHORT CountCompChg() const;
inline xub_StrLen GetCompStart( const USHORT nCnt ) const;
inline xub_StrLen GetCompLen( const USHORT nCnt ) const;
inline BYTE GetCompType( const USHORT nCnt ) const;
inline USHORT CountHiddenChg() const;
inline xub_StrLen GetHiddenChg( const USHORT nCnt ) const;
static void SwScriptInfo::CalcHiddenRanges( const SwTxtNode& rNode,
MultiSelection& rHiddenMulti );
// "high" level operations, nPos refers to string position
xub_StrLen NextScriptChg( const xub_StrLen nPos ) const;
BYTE ScriptType( const xub_StrLen nPos ) const;
// Returns the position of the next direction level change.
// If bLevel is set, the position of the next level which is smaller
// than the level at position nPos is returned. This is required to
// obtain the end of a SwBidiPortion
xub_StrLen NextDirChg( const xub_StrLen nPos,
const BYTE* pLevel = 0 ) const;
BYTE DirType( const xub_StrLen nPos ) const;
BYTE CompType( const xub_StrLen nPos ) const;
/** Hidden text range information - static and non-version
@descr Determines if a given position is inside a hidden text range. The
static version tries to obtain a valid SwScriptInfo object
via the SwTxtNode, otherwise it calculates the values from scratch.
The non-static version uses the internally cached informatio
for the calculation.
@param rNode
The text node.
@param nPos
The given position that should be checked.
@param rnStartPos
Return parameter for the start position of the hidden range.
STRING_LEN if nPos is not inside a hidden range.
@param rnEndPos
Return parameter for the end position of the hidden range.
0 if nPos is not inside a hidden range.
@param rnEndPos
Return parameter that contains all the hidden text ranges. Optional.
@return
returns true if there are any hidden characters in this paragraph.
*/
static bool GetBoundsOfHiddenRange( const SwTxtNode& rNode, xub_StrLen nPos,
xub_StrLen& rnStartPos, xub_StrLen& rnEndPos,
PositionList* pList = 0 );
bool GetBoundsOfHiddenRange( xub_StrLen nPos, xub_StrLen& rnStartPos,
xub_StrLen& rnEndPos, PositionList* pList = 0 ) const;
static bool IsInHiddenRange( const SwTxtNode& rNode, xub_StrLen nPos );
/** Hidden text range information
@descr Takes a string and either deletes the hidden ranges or sets
a given character in place of the hidden characters.
@param rNode
The text node.
@param nPos
The string to modify.
@param cChar
The character that should replace the hidden characters.
*/
static USHORT MaskHiddenRanges( const SwTxtNode& rNode, XubString& rText,
const xub_StrLen nStt, const xub_StrLen nEnd,
const xub_Unicode cChar );
// examines the range [ nStart, nStart + nEnd ] if there are kanas
// returns start index of kana entry in array, otherwise USHRT_MAX
USHORT HasKana( xub_StrLen nStart, const xub_StrLen nEnd ) const;
// modifies the kerning array according to a given compress value
long Compress( long* pKernArray, xub_StrLen nIdx, xub_StrLen nLen,
const USHORT nCompress, const USHORT nFontHeight,
Point* pPoint = NULL ) const;
/** Performes a kashida justification on the kerning array
@descr Add some extra space for kashida justification to the
positions in the kerning array.
@param pKernArray
The printers kerning array. Optional.
@param pScrArray
The screen kerning array. Optional.
@param nIdx
Start referring to the paragraph.
@param nLen
The number of characters to be considered.
@param nSpace
The value which has to be added to a kashida opportunity.
@return The number of kashida opportunities in the given range
*/
USHORT KashidaJustify( long* pKernArray ,long* pScrArray,
xub_StrLen nIdx, xub_StrLen nLen,
USHORT nSpace = 0 ) const;
/** Checks if language is one of the 16 Arabic languages
@descr Checks if language is one of the 16 Arabic languages
@param aLang
The language which has to be checked.
@return Returns if the language is an Arabic language
*/
static BOOL IsArabicLanguage( LanguageType aLang );
/** Performes a thai justification on the kerning array
@descr Add some extra space for thai justification to the
positions in the kerning array.
@param rTxt
The String
@param pKernArray
The printers kerning array. Optional.
@param pScrArray
The screen kerning array. Optional.
@param nIdx
Start referring to the paragraph.
@param nLen
The number of characters to be considered.
@param nSpace
The value which has to be added to the cells.
@return The number of extra spaces in the given range
*/
static USHORT ThaiJustify( const XubString& rTxt, long* pKernArray,
long* pScrArray, xub_StrLen nIdx,
xub_StrLen nLen, USHORT nSpace = 0 );
static SwScriptInfo* GetScriptInfo( const SwTxtNode& rNode,
sal_Bool bAllowInvalid = sal_False );
static BYTE WhichFont( xub_StrLen nIdx, const String* pTxt, const SwScriptInfo* pSI );
};
inline void SwScriptInfo::SetInvalidity( const xub_StrLen nPos )
{
if ( nPos < nInvalidityPos )
nInvalidityPos = nPos;
};
inline USHORT SwScriptInfo::CountScriptChg() const { return aScriptChg.Count(); }
inline xub_StrLen SwScriptInfo::GetScriptChg( const USHORT nCnt ) const
{
ASSERT( nCnt < aScriptChg.Count(),"No ScriptChange today!");
return aScriptChg[ nCnt ];
}
inline BYTE SwScriptInfo::GetScriptType( const xub_StrLen nCnt ) const
{
ASSERT( nCnt < aScriptChg.Count(),"No ScriptType today!");
return aScriptType[ nCnt ];
}
inline USHORT SwScriptInfo::CountDirChg() const { return aDirChg.Count(); }
inline xub_StrLen SwScriptInfo::GetDirChg( const USHORT nCnt ) const
{
ASSERT( nCnt < aDirChg.Count(),"No DirChange today!");
return aDirChg[ nCnt ];
}
inline BYTE SwScriptInfo::GetDirType( const xub_StrLen nCnt ) const
{
ASSERT( nCnt < aDirChg.Count(),"No DirType today!");
return aDirType[ nCnt ];
}
inline USHORT SwScriptInfo::CountKashida() const { return aKashida.Count(); }
inline xub_StrLen SwScriptInfo::GetKashida( const USHORT nCnt ) const
{
ASSERT( nCnt < aKashida.Count(),"No Kashidas today!");
return aKashida[ nCnt ];
}
inline USHORT SwScriptInfo::CountCompChg() const { return aCompChg.Count(); };
inline xub_StrLen SwScriptInfo::GetCompStart( const USHORT nCnt ) const
{
ASSERT( nCnt < aCompChg.Count(),"No CompressionStart today!");
return aCompChg[ nCnt ];
}
inline xub_StrLen SwScriptInfo::GetCompLen( const USHORT nCnt ) const
{
ASSERT( nCnt < aCompChg.Count(),"No CompressionLen today!");
return aCompLen[ nCnt ];
}
inline BYTE SwScriptInfo::GetCompType( const USHORT nCnt ) const
{
ASSERT( nCnt < aCompChg.Count(),"No CompressionType today!");
return aCompType[ nCnt ];
}
inline USHORT SwScriptInfo::CountHiddenChg() const { return aHiddenChg.Count(); };
inline xub_StrLen SwScriptInfo::GetHiddenChg( const USHORT nCnt ) const
{
ASSERT( nCnt < aHiddenChg.Count(),"No HiddenChg today!");
return aHiddenChg[ nCnt ];
}
#endif
<commit_msg>INTEGRATION: CWS swqbugfixes02 (1.4.58); FILE MERGED 2004/06/09 07:06:15 fme 1.4.58.1: #i29968# Remove hidden text ranges from document before sending it<commit_after>/*************************************************************************
*
* $RCSfile: scriptinfo.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: kz $ $Date: 2004-06-29 08:08:37 $
*
* 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 _SCRIPTINFO_HXX
#define _SCRIPTINFO_HXX
#ifndef _SVSTDARR_HXX
#define _SVSTDARR_SHORTS
#define _SVSTDARR_BYTES
#define _SVSTDARR_USHORTS
#define _SVSTDARR_XUB_STRLEN
#include <svtools/svstdarr.hxx>
#endif
#ifndef _LANG_HXX
#include <tools/lang.hxx>
#endif
#include <list>
class SwWrongList;
class SwTxtNode;
class Point;
class MultiSelection;
typedef std::list< xub_StrLen > PositionList;
/*************************************************************************
* class SwScanner
* Hilfsklasse, die beim Spellen die Worte im gewuenschten Bereich
* nacheinander zur Verfuegung stellt.
*************************************************************************/
class SwScanner
{
XubString aWord;
const SwWrongList* pWrong;
const SwTxtNode& rNode;
xub_StrLen nEndPos;
xub_StrLen nBegin;
xub_StrLen nLen;
LanguageType aCurrLang;
USHORT nWordType;
BOOL bReverse;
BOOL bStart;
BOOL bIsOnlineSpell;
public:
SwScanner( const SwTxtNode& rNd, const SwWrongList* pWrng, USHORT nWordType,
xub_StrLen nStart, xub_StrLen nEnde, BOOL bRev, BOOL bOS );
// This next word function tries to find the language for the next word
// It should currently _not_ be used for spell checking, and works only for
// ! bReverse
BOOL NextWord();
BOOL NextWord( LanguageType aLang );
const XubString& GetWord() const { return aWord; }
xub_StrLen GetBegin() const { return nBegin; }
xub_StrLen GetEnd() const { return nBegin + nLen; }
xub_StrLen GetLen() const { return nLen; }
};
/*************************************************************************
* class SwScriptInfo
*
* encapsultes information about script changes
*************************************************************************/
class SwScriptInfo
{
private:
SvXub_StrLens aScriptChg;
SvBytes aScriptType;
SvXub_StrLens aDirChg;
SvBytes aDirType;
SvXub_StrLens aKashida;
SvXub_StrLens aCompChg;
SvXub_StrLens aCompLen;
SvXub_StrLens aHiddenChg;
SvBytes aCompType;
xub_StrLen nInvalidityPos;
BYTE nDefaultDir;
void UpdateBidiInfo( const String& rTxt );
public:
enum CompType { KANA, SPECIAL_LEFT, SPECIAL_RIGHT, NONE };
inline SwScriptInfo() : nInvalidityPos( 0 ), nDefaultDir( 0 ) {};
// determines script changes
void InitScriptInfo( const SwTxtNode& rNode, sal_Bool bRTL );
void InitScriptInfo( const SwTxtNode& rNode );
// set/get position from which data is invalid
inline void SetInvalidity( const xub_StrLen nPos );
inline xub_StrLen GetInvalidity() const { return nInvalidityPos; };
// get default direction for paragraph
inline BYTE GetDefaultDir() const { return nDefaultDir; };
// array operations, nCnt refers to array position
inline USHORT CountScriptChg() const;
inline xub_StrLen GetScriptChg( const USHORT nCnt ) const;
inline BYTE GetScriptType( const USHORT nCnt ) const;
inline USHORT CountDirChg() const;
inline xub_StrLen GetDirChg( const USHORT nCnt ) const;
inline BYTE GetDirType( const USHORT nCnt ) const;
inline USHORT CountKashida() const;
inline xub_StrLen GetKashida( const USHORT nCnt ) const;
inline USHORT CountCompChg() const;
inline xub_StrLen GetCompStart( const USHORT nCnt ) const;
inline xub_StrLen GetCompLen( const USHORT nCnt ) const;
inline BYTE GetCompType( const USHORT nCnt ) const;
inline USHORT CountHiddenChg() const;
inline xub_StrLen GetHiddenChg( const USHORT nCnt ) const;
static void SwScriptInfo::CalcHiddenRanges( const SwTxtNode& rNode,
MultiSelection& rHiddenMulti );
// "high" level operations, nPos refers to string position
xub_StrLen NextScriptChg( const xub_StrLen nPos ) const;
BYTE ScriptType( const xub_StrLen nPos ) const;
// Returns the position of the next direction level change.
// If bLevel is set, the position of the next level which is smaller
// than the level at position nPos is returned. This is required to
// obtain the end of a SwBidiPortion
xub_StrLen NextDirChg( const xub_StrLen nPos,
const BYTE* pLevel = 0 ) const;
BYTE DirType( const xub_StrLen nPos ) const;
BYTE CompType( const xub_StrLen nPos ) const;
//
// HIDDEN TEXT STUFF START
//
/** Hidden text range information - static and non-version
@descr Determines if a given position is inside a hidden text range. The
static version tries to obtain a valid SwScriptInfo object
via the SwTxtNode, otherwise it calculates the values from scratch.
The non-static version uses the internally cached informatio
for the calculation.
@param rNode
The text node.
@param nPos
The given position that should be checked.
@param rnStartPos
Return parameter for the start position of the hidden range.
STRING_LEN if nPos is not inside a hidden range.
@param rnEndPos
Return parameter for the end position of the hidden range.
0 if nPos is not inside a hidden range.
@param rnEndPos
Return parameter that contains all the hidden text ranges. Optional.
@return
returns true if there are any hidden characters in this paragraph.
*/
static bool GetBoundsOfHiddenRange( const SwTxtNode& rNode, xub_StrLen nPos,
xub_StrLen& rnStartPos, xub_StrLen& rnEndPos,
PositionList* pList = 0 );
bool GetBoundsOfHiddenRange( xub_StrLen nPos, xub_StrLen& rnStartPos,
xub_StrLen& rnEndPos, PositionList* pList = 0 ) const;
static bool IsInHiddenRange( const SwTxtNode& rNode, xub_StrLen nPos );
/** Hidden text attribute handling
@descr Takes a string and either deletes the hidden ranges or sets
a given character in place of the hidden characters.
@param rNode
The text node.
@param nPos
The string to modify.
@param cChar
The character that should replace the hidden characters.
@param bDel
If set, the hidden ranges will be deleted from the text node.
*/
static USHORT MaskHiddenRanges( const SwTxtNode& rNode, XubString& rText,
const xub_StrLen nStt, const xub_StrLen nEnd,
const xub_Unicode cChar );
/** Hidden text attribute handling
@descr Takes a SwTxtNode and deletes the hidden ranges from the node.
@param rNode
The text node.
*/
static void DeleteHiddenRanges( SwTxtNode& rNode );
//
// HIDDEN TEXT STUFF END
//
// examines the range [ nStart, nStart + nEnd ] if there are kanas
// returns start index of kana entry in array, otherwise USHRT_MAX
USHORT HasKana( xub_StrLen nStart, const xub_StrLen nEnd ) const;
// modifies the kerning array according to a given compress value
long Compress( long* pKernArray, xub_StrLen nIdx, xub_StrLen nLen,
const USHORT nCompress, const USHORT nFontHeight,
Point* pPoint = NULL ) const;
/** Performes a kashida justification on the kerning array
@descr Add some extra space for kashida justification to the
positions in the kerning array.
@param pKernArray
The printers kerning array. Optional.
@param pScrArray
The screen kerning array. Optional.
@param nIdx
Start referring to the paragraph.
@param nLen
The number of characters to be considered.
@param nSpace
The value which has to be added to a kashida opportunity.
@return The number of kashida opportunities in the given range
*/
USHORT KashidaJustify( long* pKernArray ,long* pScrArray,
xub_StrLen nIdx, xub_StrLen nLen,
USHORT nSpace = 0 ) const;
/** Checks if language is one of the 16 Arabic languages
@descr Checks if language is one of the 16 Arabic languages
@param aLang
The language which has to be checked.
@return Returns if the language is an Arabic language
*/
static BOOL IsArabicLanguage( LanguageType aLang );
/** Performes a thai justification on the kerning array
@descr Add some extra space for thai justification to the
positions in the kerning array.
@param rTxt
The String
@param pKernArray
The printers kerning array. Optional.
@param pScrArray
The screen kerning array. Optional.
@param nIdx
Start referring to the paragraph.
@param nLen
The number of characters to be considered.
@param nSpace
The value which has to be added to the cells.
@return The number of extra spaces in the given range
*/
static USHORT ThaiJustify( const XubString& rTxt, long* pKernArray,
long* pScrArray, xub_StrLen nIdx,
xub_StrLen nLen, USHORT nSpace = 0 );
static SwScriptInfo* GetScriptInfo( const SwTxtNode& rNode,
sal_Bool bAllowInvalid = sal_False );
static BYTE WhichFont( xub_StrLen nIdx, const String* pTxt, const SwScriptInfo* pSI );
};
inline void SwScriptInfo::SetInvalidity( const xub_StrLen nPos )
{
if ( nPos < nInvalidityPos )
nInvalidityPos = nPos;
};
inline USHORT SwScriptInfo::CountScriptChg() const { return aScriptChg.Count(); }
inline xub_StrLen SwScriptInfo::GetScriptChg( const USHORT nCnt ) const
{
ASSERT( nCnt < aScriptChg.Count(),"No ScriptChange today!");
return aScriptChg[ nCnt ];
}
inline BYTE SwScriptInfo::GetScriptType( const xub_StrLen nCnt ) const
{
ASSERT( nCnt < aScriptChg.Count(),"No ScriptType today!");
return aScriptType[ nCnt ];
}
inline USHORT SwScriptInfo::CountDirChg() const { return aDirChg.Count(); }
inline xub_StrLen SwScriptInfo::GetDirChg( const USHORT nCnt ) const
{
ASSERT( nCnt < aDirChg.Count(),"No DirChange today!");
return aDirChg[ nCnt ];
}
inline BYTE SwScriptInfo::GetDirType( const xub_StrLen nCnt ) const
{
ASSERT( nCnt < aDirChg.Count(),"No DirType today!");
return aDirType[ nCnt ];
}
inline USHORT SwScriptInfo::CountKashida() const { return aKashida.Count(); }
inline xub_StrLen SwScriptInfo::GetKashida( const USHORT nCnt ) const
{
ASSERT( nCnt < aKashida.Count(),"No Kashidas today!");
return aKashida[ nCnt ];
}
inline USHORT SwScriptInfo::CountCompChg() const { return aCompChg.Count(); };
inline xub_StrLen SwScriptInfo::GetCompStart( const USHORT nCnt ) const
{
ASSERT( nCnt < aCompChg.Count(),"No CompressionStart today!");
return aCompChg[ nCnt ];
}
inline xub_StrLen SwScriptInfo::GetCompLen( const USHORT nCnt ) const
{
ASSERT( nCnt < aCompChg.Count(),"No CompressionLen today!");
return aCompLen[ nCnt ];
}
inline BYTE SwScriptInfo::GetCompType( const USHORT nCnt ) const
{
ASSERT( nCnt < aCompChg.Count(),"No CompressionType today!");
return aCompType[ nCnt ];
}
inline USHORT SwScriptInfo::CountHiddenChg() const { return aHiddenChg.Count(); };
inline xub_StrLen SwScriptInfo::GetHiddenChg( const USHORT nCnt ) const
{
ASSERT( nCnt < aHiddenChg.Count(),"No HiddenChg today!");
return aHiddenChg[ nCnt ];
}
#endif
<|endoftext|> |
<commit_before>#include "PolyStatic.hpp"
#include <string>
#include <map>
#include <fstream>
namespace ps
{
namespace
{
struct ParseElement
{
virtual ParseElement *Clone() const = 0;
virtual ~ParseElement(){}
};
struct ScriptFile : public virtual ParseElement
{
std::string filename;
ScriptFile(std::string const&filename) : filename(filename) {}
virtual ScriptFile *Clone() const
{
return new ScriptFile(*this);
}
virtual ~ScriptFile(){}
};
struct Script : public virtual ParseElement
{
std::string script;
Script(std::string const &script) : script(script) {}
virtual Script *Clone() const
{
return new Script(*this);
}
virtual ~Script(){}
};
}
struct Parser::Impl
{
using elems_t = std::map<std::string, ParseElement *>;
elems_t elems;
ErrorHandler eh;
Impl() : eh([](Parser &, Error const &, bool w) -> bool { return w; })
{
}
Impl(Impl const &impl) : eh(impl.eh)
{
for(elems_t::const_iterator it = impl.elems.begin(); it != impl.elems.end(); ++it)
{
elems[it->first] = it->second->Clone();
}
}
~Impl()
{
for(elems_t::iterator it = elems.begin(); it != elems.end(); ++it)
{
delete it->second;
}
}
};
Parser::Parser() : impl(new Impl)
{
}
Parser::Parser(char const *script) : impl(new Impl)
{
impl->elems[""] = new Script(script);
}
Parser::Parser(Parser const &parser) : impl(new Impl(*parser.impl))
{
}
Parser::~Parser()
{
delete impl;
impl = 0;
}
void Parser::AddScriptFile(char const *scriptfilename)
{
RemoveScript(scriptfilename);
impl->elems[scriptfilename] = new ScriptFile(scriptfilename);
}
void Parser::AddScript(char const *scriptname, char const *contents)
{
RemoveScript(scriptname);
impl->elems[scriptname] = new Script(contents);
}
void Parser::RemoveScript(char const *scriptname)
{
Impl::elems_t e (impl->elems);
if(e.find(scriptname) != e.end())
{
delete e[scriptname];
e.erase(scriptname);
}
}
void Parser::SetErrorHandler(ErrorHandler &eh)
{
impl->eh = &eh;
}
struct Parser::Error::Impl
{
std::string msg, script;
unsigned lns, lne, cns, cne;
};
Parser::Error::Error() : impl(new Impl)
{
}
Parser::Error::~Error()
{
delete impl;
impl = 0;
}
char const *Parser::Error::ErrorString() const
{
return impl->msg.c_str();
}
char const *Parser::Error::ScriptName() const
{
return impl->script.c_str();
}
unsigned Parser::Error::LineNumberStart() const
{
return impl->lns;
}
unsigned Parser::Error::LineNumberEnd() const
{
return impl->lne;
}
unsigned Parser::Error::ColumnNumberStart() const
{
return impl->cns;
}
unsigned Parser::Error::ColumnNumberEnd() const
{
return impl->cne;
}
bool Parser::Parse()
{
return false;
}
}
<commit_msg>Fix deleting unique_ptr<commit_after>#include "PolyStatic.hpp"
#include <string>
#include <map>
#include <fstream>
namespace ps
{
namespace
{
struct ParseElement
{
virtual ParseElement *Clone() const = 0;
virtual ~ParseElement(){}
};
struct ScriptFile : public virtual ParseElement
{
std::string filename;
ScriptFile(std::string const&filename) : filename(filename) {}
virtual ScriptFile *Clone() const
{
return new ScriptFile(*this);
}
virtual ~ScriptFile(){}
};
struct Script : public virtual ParseElement
{
std::string script;
Script(std::string const &script) : script(script) {}
virtual Script *Clone() const
{
return new Script(*this);
}
virtual ~Script(){}
};
}
struct Parser::Impl
{
using elems_t = std::map<std::string, ParseElement *>;
elems_t elems;
ErrorHandler eh;
Impl() : eh([](Parser &, Error const &, bool w) -> bool { return w; })
{
}
Impl(Impl const &impl) : eh(impl.eh)
{
for(elems_t::const_iterator it = impl.elems.begin(); it != impl.elems.end(); ++it)
{
elems[it->first] = it->second->Clone();
}
}
~Impl()
{
for(elems_t::iterator it = elems.begin(); it != elems.end(); ++it)
{
delete it->second;
}
}
};
Parser::Parser() : impl(new Impl)
{
}
Parser::Parser(char const *script) : impl(new Impl)
{
impl->elems[""] = new Script(script);
}
Parser::Parser(Parser const &parser) : impl(new Impl(*parser.impl))
{
}
Parser::~Parser()
{
}
void Parser::AddScriptFile(char const *scriptfilename)
{
RemoveScript(scriptfilename);
impl->elems[scriptfilename] = new ScriptFile(scriptfilename);
}
void Parser::AddScript(char const *scriptname, char const *contents)
{
RemoveScript(scriptname);
impl->elems[scriptname] = new Script(contents);
}
void Parser::RemoveScript(char const *scriptname)
{
Impl::elems_t e (impl->elems);
if(e.find(scriptname) != e.end())
{
delete e[scriptname];
e.erase(scriptname);
}
}
void Parser::SetErrorHandler(ErrorHandler &eh)
{
impl->eh = &eh;
}
struct Parser::Error::Impl
{
std::string msg, script;
unsigned lns, lne, cns, cne;
};
Parser::Error::Error() : impl(new Impl)
{
}
Parser::Error::~Error()
{
}
char const *Parser::Error::ErrorString() const
{
return impl->msg.c_str();
}
char const *Parser::Error::ScriptName() const
{
return impl->script.c_str();
}
unsigned Parser::Error::LineNumberStart() const
{
return impl->lns;
}
unsigned Parser::Error::LineNumberEnd() const
{
return impl->lne;
}
unsigned Parser::Error::ColumnNumberStart() const
{
return impl->cns;
}
unsigned Parser::Error::ColumnNumberEnd() const
{
return impl->cne;
}
bool Parser::Parse()
{
return false;
}
}
<|endoftext|> |
<commit_before>#include <OpenGLTexture.h>
#include <TextureRef.h>
#include <Image.h>
#include <Surface.h>
#define GL_GLEXT_PROTOTYPES
#if defined __APPLE__
#include <OpenGLES/ES3/gl.h>
#include <OpenGLES/ES3/glext.h>
#elif (defined GL_ES)
#include <GLES3/gl3.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#else
#define GL_GLEXT_PROTOTYPES
#ifdef _WIN32
#include <GL/glew.h>
#include <windows.h>
#endif
#ifdef __ANDROID__
#include <GLES3/gl3.h>
#include <GLES3/gl3ext.h>
#else
#include <GL/gl.h>
#ifdef _WIN32
#include "glext.h"
#else
#include <GL/glext.h>
#endif
#endif
#endif
#if defined __APPLE__ || defined __ANDROID__
#ifndef GL_COMPRESSED_RGB_S3TC_DXT1_EXT
#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0
#endif
#ifndef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT
#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0
#endif
#ifndef GL_COMPRESSED_RED_RGTC1
#define GL_COMPRESSED_RED_RGTC1 0x8DBB
#endif
#ifndef GL_COMPRESSED_RG_RGTC2
#define GL_COMPRESSED_RG_RGTC2 0x8DBD
#endif
#endif
#include <cassert>
#include <iostream>
using namespace std;
using namespace canvas;
size_t OpenGLTexture::total_textures = 0;
vector<unsigned int> OpenGLTexture::freed_textures;
bool OpenGLTexture::global_init = false;
bool OpenGLTexture::has_tex_storage = false;
struct format_description_s {
GLenum internalFormat;
GLenum format;
GLenum type;
};
OpenGLTexture::OpenGLTexture(Surface & surface)
: Texture(surface.getLogicalWidth(), surface.getLogicalHeight(), surface.getActualWidth(), surface.getActualHeight(), surface.getMinFilter(), surface.getMagFilter(), surface.getTargetFormat(), 1) {
assert(getInternalFormat());
assert(getLogicalWidth() > 0);
assert(getLogicalHeight() > 0);
assert(getActualWidth() > 0);
assert(getActualHeight() > 0);
auto image = surface.createImage();
updateData(*image, 0, 0);
}
static format_description_s getFormatDescription(InternalFormat internal_format) {
switch (internal_format) {
case NO_FORMAT: return { 0, 0, 0 };
case R8: return { GL_R8, GL_RED, GL_UNSIGNED_BYTE };
case RG8: return { GL_RG8, GL_RG, GL_UNSIGNED_BYTE };
case RGB565: return { GL_RGB565, GL_RGB, GL_UNSIGNED_SHORT_5_6_5 };
case RGBA4: return { GL_RGBA4, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4 };
case RGBA8:
#if defined __APPLE__ || defined __ANDROID__
return { GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE };
#elif defined _WIN32
return { GL_RGBA8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV };
#else
// Linux (doesn't work for OpenGL ES)
return { GL_RGBA8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV };
#endif
case RGB8:
#if defined __APPLE__ || defined __ANDROID__
return { GL_RGB8, GL_RGBA, GL_UNSIGNED_BYTE };
#elif defined _WIN32
return { GL_RGB8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV };
#else
// Linux
return { GL_RGBA8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV };
#endif
// case RGB8_24: return GL_RGBA8;
case RED_RGTC1: return { GL_COMPRESSED_RED_RGTC1, GL_RG, 0 };
case RG_RGTC2: return { GL_COMPRESSED_RG_RGTC2, GL_RG, 0 };
case RGB_ETC1: return { GL_COMPRESSED_RGB8_ETC2, GL_RGB, 0 };
case RGB_DXT1: return { GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_RGB, 0 };
case RGBA_DXT5: return { GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_RGBA, 0 };
case LUMINANCE_ALPHA: return { GL_RG8, GL_RG, GL_UNSIGNED_BYTE };
case LA44: // pack luminance and alpha to single byte
return { GL_R8, GL_RED, GL_UNSIGNED_BYTE };
case R32F: return { GL_R32F, GL_RED, GL_FLOAT };
default:
break;
}
cerr << "unhandled format: " << int(internal_format) << endl;
assert(0);
return { 0, 0, 0 };
}
static GLenum getOpenGLFilterType(FilterMode mode) {
switch (mode) {
case NEAREST: return GL_NEAREST;
case LINEAR: return GL_LINEAR;
case LINEAR_MIPMAP_LINEAR: return GL_LINEAR_MIPMAP_LINEAR;
}
return 0;
}
void
OpenGLTexture::updateTextureData(const Image & image, unsigned int x, unsigned int y) {
unsigned int offset = 0;
unsigned int current_width = image.getWidth(), current_height = image.getHeight();
auto fd = getFormatDescription(getInternalFormat());
bool filled = false;
for (unsigned int level = 0; level < image.getLevels(); level++) {
size_t size = image.calculateOffset(level + 1) - image.calculateOffset(level);
cerr << "plain tex: f = " << int(getInternalFormat()) << ", x = " << x << ", y = " << y << ", l = " << (level+1) << "/" << image.getLevels() << ", w = " << current_width << ", h = " << current_height << ", size = " << size << ", offset = " << offset << endl;
assert(image.getData());
if (fd.type == 0) { // compressed
if (hasTexStorage() || is_data_initialized) {
glCompressedTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, fd.internalFormat, (GLsizei)size, image.getData() + offset);
} else {
glCompressedTexImage2D(GL_TEXTURE_2D, level, fd.internalFormat, current_width, current_height, 0, (GLsizei)size, image.getData() + offset);
}
} else if (hasTexStorage() || is_data_initialized) {
glTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, fd.format, fd.type, image.getData() + offset);
} else {
glTexImage2D(GL_TEXTURE_2D, level, fd.internalFormat, current_width, current_height, 0, fd.format, fd.type, image.getData() + offset);
filled = true;
}
offset += size;
current_width /= 2;
current_height /= 2;
x /= 2;
y /= 2;
}
if (filled) is_data_initialized = true;
}
void
OpenGLTexture::updateData(const Image & image, unsigned int x, unsigned int y) {
if (!global_init) {
global_init = true;
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
}
releaseTextures();
bool initialize = false;
if (!texture_id) {
initialize = true;
glGenTextures(1, &texture_id);
// cerr << "created texture id " << texture_id << " (total = " << total_textures << ")" << endl;
if (texture_id >= 1) total_textures++;
}
assert(texture_id >= 1);
glBindTexture(GL_TEXTURE_2D, texture_id);
bool has_mipmaps = getMinFilter() == LINEAR_MIPMAP_LINEAR;
if (initialize) {
if (hasTexStorage()) {
auto fd = getFormatDescription(getInternalFormat());
glTexStorage2D(GL_TEXTURE_2D, has_mipmaps ? getMipmapLevels() : 1, fd.internalFormat, getActualWidth(), getActualHeight());
}
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, getOpenGLFilterType(getMinFilter()));
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, getOpenGLFilterType(getMagFilter()));
if (x != 0 || y != 0 || image.getWidth() != getActualWidth() || image.getHeight() != getActualHeight()) {
int levels = has_mipmaps ? getMipmapLevels() : 1;
Image img(getInternalFormat(), getActualWidth(), getActualHeight(), levels);
updateTextureData(img, 0, 0);
}
}
if (image.getInternalFormat() == getInternalFormat() ||
(image.getInternalFormat() == RGB8 && getInternalFormat() == RGBA8)) {
updateTextureData(image, x, y);
} else {
cerr << "OpenGLTexture: doing online image conversion from " << int(image.getInternalFormat()) << " to " << int(getInternalFormat()) << " (SLOW)\n";
auto tmp_image = image.convert(getInternalFormat());
updateTextureData(*tmp_image, x, y);
}
// if the image has only one level, and mipmaps are needed, generate them
if (has_mipmaps && image.getLevels() == 1) {
need_mipmaps = true;
}
}
void
OpenGLTexture::generateMipmaps() {
if (need_mipmaps) {
if (getInternalFormat() != RGB_DXT1 && getInternalFormat() != RGB_ETC1 && getInternalFormat() != LA44 && getInternalFormat() != RED_RGTC1 && getInternalFormat() != RG_RGTC2) {
glGenerateMipmap(GL_TEXTURE_2D);
} else {
cerr << "unable to generate mipmaps for compressed texture!\n";
}
need_mipmaps = false;
}
}
void
OpenGLTexture::releaseTextures() {
if (!freed_textures.empty()) {
for (auto id : freed_textures) {
cerr << "deleting texture " << id << endl;
glDeleteTextures(1, &id);
}
freed_textures.clear();
}
}
TextureRef
OpenGLTexture::createTexture(unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, FilterMode min_filter, FilterMode mag_filter, InternalFormat _internal_format, unsigned int mipmap_levels) {
assert(_internal_format);
return TextureRef(_logical_width, _logical_height, _actual_width, _actual_height, new OpenGLTexture(_logical_width, _logical_height, _actual_width, _actual_height, min_filter, mag_filter, _internal_format, mipmap_levels));
}
TextureRef
OpenGLTexture::createTexture(Surface & surface) {
return TextureRef( surface.getLogicalWidth(),
surface.getLogicalHeight(),
surface.getActualWidth(),
surface.getActualHeight(),
new OpenGLTexture(surface)
);
}
<commit_msg>disable debug prints<commit_after>#include <OpenGLTexture.h>
#include <TextureRef.h>
#include <Image.h>
#include <Surface.h>
#define GL_GLEXT_PROTOTYPES
#if defined __APPLE__
#include <OpenGLES/ES3/gl.h>
#include <OpenGLES/ES3/glext.h>
#elif (defined GL_ES)
#include <GLES3/gl3.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#else
#define GL_GLEXT_PROTOTYPES
#ifdef _WIN32
#include <GL/glew.h>
#include <windows.h>
#endif
#ifdef __ANDROID__
#include <GLES3/gl3.h>
#include <GLES3/gl3ext.h>
#else
#include <GL/gl.h>
#ifdef _WIN32
#include "glext.h"
#else
#include <GL/glext.h>
#endif
#endif
#endif
#if defined __APPLE__ || defined __ANDROID__
#ifndef GL_COMPRESSED_RGB_S3TC_DXT1_EXT
#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0
#endif
#ifndef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT
#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0
#endif
#ifndef GL_COMPRESSED_RED_RGTC1
#define GL_COMPRESSED_RED_RGTC1 0x8DBB
#endif
#ifndef GL_COMPRESSED_RG_RGTC2
#define GL_COMPRESSED_RG_RGTC2 0x8DBD
#endif
#endif
#include <cassert>
#include <iostream>
using namespace std;
using namespace canvas;
size_t OpenGLTexture::total_textures = 0;
vector<unsigned int> OpenGLTexture::freed_textures;
bool OpenGLTexture::global_init = false;
bool OpenGLTexture::has_tex_storage = false;
struct format_description_s {
GLenum internalFormat;
GLenum format;
GLenum type;
};
OpenGLTexture::OpenGLTexture(Surface & surface)
: Texture(surface.getLogicalWidth(), surface.getLogicalHeight(), surface.getActualWidth(), surface.getActualHeight(), surface.getMinFilter(), surface.getMagFilter(), surface.getTargetFormat(), 1) {
assert(getInternalFormat());
assert(getLogicalWidth() > 0);
assert(getLogicalHeight() > 0);
assert(getActualWidth() > 0);
assert(getActualHeight() > 0);
auto image = surface.createImage();
updateData(*image, 0, 0);
}
static format_description_s getFormatDescription(InternalFormat internal_format) {
switch (internal_format) {
case NO_FORMAT: return { 0, 0, 0 };
case R8: return { GL_R8, GL_RED, GL_UNSIGNED_BYTE };
case RG8: return { GL_RG8, GL_RG, GL_UNSIGNED_BYTE };
case RGB565: return { GL_RGB565, GL_RGB, GL_UNSIGNED_SHORT_5_6_5 };
case RGBA4: return { GL_RGBA4, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4 };
case RGBA8:
#if defined __APPLE__ || defined __ANDROID__
return { GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE };
#elif defined _WIN32
return { GL_RGBA8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV };
#else
// Linux (doesn't work for OpenGL ES)
return { GL_RGBA8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV };
#endif
case RGB8:
#if defined __APPLE__ || defined __ANDROID__
return { GL_RGB8, GL_RGBA, GL_UNSIGNED_BYTE };
#elif defined _WIN32
return { GL_RGB8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV };
#else
// Linux
return { GL_RGBA8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV };
#endif
// case RGB8_24: return GL_RGBA8;
case RED_RGTC1: return { GL_COMPRESSED_RED_RGTC1, GL_RG, 0 };
case RG_RGTC2: return { GL_COMPRESSED_RG_RGTC2, GL_RG, 0 };
case RGB_ETC1: return { GL_COMPRESSED_RGB8_ETC2, GL_RGB, 0 };
case RGB_DXT1: return { GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_RGB, 0 };
case RGBA_DXT5: return { GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_RGBA, 0 };
case LUMINANCE_ALPHA: return { GL_RG8, GL_RG, GL_UNSIGNED_BYTE };
case LA44: // pack luminance and alpha to single byte
return { GL_R8, GL_RED, GL_UNSIGNED_BYTE };
case R32F: return { GL_R32F, GL_RED, GL_FLOAT };
default:
break;
}
cerr << "unhandled format: " << int(internal_format) << endl;
assert(0);
return { 0, 0, 0 };
}
static GLenum getOpenGLFilterType(FilterMode mode) {
switch (mode) {
case NEAREST: return GL_NEAREST;
case LINEAR: return GL_LINEAR;
case LINEAR_MIPMAP_LINEAR: return GL_LINEAR_MIPMAP_LINEAR;
}
return 0;
}
void
OpenGLTexture::updateTextureData(const Image & image, unsigned int x, unsigned int y) {
unsigned int offset = 0;
unsigned int current_width = image.getWidth(), current_height = image.getHeight();
auto fd = getFormatDescription(getInternalFormat());
bool filled = false;
for (unsigned int level = 0; level < image.getLevels(); level++) {
size_t size = image.calculateOffset(level + 1) - image.calculateOffset(level);
// cerr << "plain tex: f = " << int(getInternalFormat()) << ", x = " << x << ", y = " << y << ", l = " << (level+1) << "/" << image.getLevels() << ", w = " << current_width << ", h = " << current_height << ", size = " << size << ", offset = " << offset << endl;
assert(image.getData());
if (fd.type == 0) { // compressed
if (hasTexStorage() || is_data_initialized) {
glCompressedTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, fd.internalFormat, (GLsizei)size, image.getData() + offset);
} else {
glCompressedTexImage2D(GL_TEXTURE_2D, level, fd.internalFormat, current_width, current_height, 0, (GLsizei)size, image.getData() + offset);
}
} else if (hasTexStorage() || is_data_initialized) {
glTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, fd.format, fd.type, image.getData() + offset);
} else {
glTexImage2D(GL_TEXTURE_2D, level, fd.internalFormat, current_width, current_height, 0, fd.format, fd.type, image.getData() + offset);
filled = true;
}
offset += size;
current_width /= 2;
current_height /= 2;
x /= 2;
y /= 2;
}
if (filled) is_data_initialized = true;
}
void
OpenGLTexture::updateData(const Image & image, unsigned int x, unsigned int y) {
if (!global_init) {
global_init = true;
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
}
releaseTextures();
bool initialize = false;
if (!texture_id) {
initialize = true;
glGenTextures(1, &texture_id);
// cerr << "created texture id " << texture_id << " (total = " << total_textures << ")" << endl;
if (texture_id >= 1) total_textures++;
}
assert(texture_id >= 1);
glBindTexture(GL_TEXTURE_2D, texture_id);
bool has_mipmaps = getMinFilter() == LINEAR_MIPMAP_LINEAR;
if (initialize) {
if (hasTexStorage()) {
auto fd = getFormatDescription(getInternalFormat());
glTexStorage2D(GL_TEXTURE_2D, has_mipmaps ? getMipmapLevels() : 1, fd.internalFormat, getActualWidth(), getActualHeight());
}
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, getOpenGLFilterType(getMinFilter()));
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, getOpenGLFilterType(getMagFilter()));
if (x != 0 || y != 0 || image.getWidth() != getActualWidth() || image.getHeight() != getActualHeight()) {
int levels = has_mipmaps ? getMipmapLevels() : 1;
Image img(getInternalFormat(), getActualWidth(), getActualHeight(), levels);
updateTextureData(img, 0, 0);
}
}
if (image.getInternalFormat() == getInternalFormat() ||
(image.getInternalFormat() == RGB8 && getInternalFormat() == RGBA8)) {
updateTextureData(image, x, y);
} else {
cerr << "OpenGLTexture: doing online image conversion from " << int(image.getInternalFormat()) << " to " << int(getInternalFormat()) << " (SLOW)\n";
auto tmp_image = image.convert(getInternalFormat());
updateTextureData(*tmp_image, x, y);
}
// if the image has only one level, and mipmaps are needed, generate them
if (has_mipmaps && image.getLevels() == 1) {
need_mipmaps = true;
}
}
void
OpenGLTexture::generateMipmaps() {
if (need_mipmaps) {
if (getInternalFormat() != RGB_DXT1 && getInternalFormat() != RGB_ETC1 && getInternalFormat() != LA44 && getInternalFormat() != RED_RGTC1 && getInternalFormat() != RG_RGTC2) {
glGenerateMipmap(GL_TEXTURE_2D);
} else {
cerr << "unable to generate mipmaps for compressed texture!\n";
}
need_mipmaps = false;
}
}
void
OpenGLTexture::releaseTextures() {
if (!freed_textures.empty()) {
for (auto id : freed_textures) {
// cerr << "deleting texture " << id << endl;
glDeleteTextures(1, &id);
}
freed_textures.clear();
}
}
TextureRef
OpenGLTexture::createTexture(unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, FilterMode min_filter, FilterMode mag_filter, InternalFormat _internal_format, unsigned int mipmap_levels) {
assert(_internal_format);
return TextureRef(_logical_width, _logical_height, _actual_width, _actual_height, new OpenGLTexture(_logical_width, _logical_height, _actual_width, _actual_height, min_filter, mag_filter, _internal_format, mipmap_levels));
}
TextureRef
OpenGLTexture::createTexture(Surface & surface) {
return TextureRef( surface.getLogicalWidth(),
surface.getLogicalHeight(),
surface.getActualWidth(),
surface.getActualHeight(),
new OpenGLTexture(surface)
);
}
<|endoftext|> |
<commit_before>#include "FieldAccessor.h"
#include "JniLocalRef.h"
#include "ArgConverter.h"
#include "NativeScriptAssert.h"
#include "Util.h"
#include "V8GlobalHelpers.h"
#include <assert.h>
using namespace v8;
using namespace std;
using namespace tns;
void FieldAccessor::Init(JavaVM *jvm, ObjectManager *objectManager)
{
this->jvm = jvm;
this->objectManager = objectManager;
}
Local<Value> FieldAccessor::GetJavaField(const Local<Object>& target, FieldCallbackData *fieldData)
{
JEnv env;
auto isolate = Isolate::GetCurrent();
EscapableHandleScope handleScope(isolate);
Local<Value> fieldResult;
jweak targetJavaObject;
const auto& fieldTypeName = fieldData->signature;
auto isStatic = fieldData->isStatic;
auto isPrimitiveType = fieldTypeName.size() == 1;
auto isFieldArray = fieldTypeName[0] == '[';
if (fieldData->fid == nullptr)
{
auto fieldJniSig = isPrimitiveType
? fieldTypeName
: (isFieldArray
? fieldTypeName
: ("L" + fieldTypeName + ";"));
if (isStatic)
{
fieldData->clazz = env.FindClass(fieldData->declaringType);
fieldData->fid = env.GetStaticFieldID(fieldData->clazz, fieldData->name, fieldJniSig);
}
else
{
fieldData->clazz = env.FindClass(fieldData->declaringType);
fieldData->fid = env.GetFieldID(fieldData->clazz, fieldData->name, fieldJniSig);
}
}
if (!isStatic)
{
targetJavaObject = objectManager->GetJavaObjectByJsObject(target);
}
auto fieldId = fieldData->fid;
auto clazz = fieldData->clazz;
if (isPrimitiveType)
{
switch (fieldTypeName[0])
{
case 'Z': //bool
{
jboolean result;
if (isStatic)
{
result = env.GetStaticBooleanField(clazz, fieldId);
}
else
{
result = env.GetBooleanField(targetJavaObject, fieldId);
}
fieldResult = Boolean::New(isolate, (result == JNI_TRUE));
break;
}
case 'B': //byte
{
jbyte result;
if (isStatic)
{
result = env.GetStaticByteField(clazz, fieldId);
}
else
{
result = env.GetByteField(targetJavaObject, fieldId);
}
fieldResult = handleScope.Escape(Int32::New(isolate, result));
break;
}
case 'C': //char
{
jchar result;
if (isStatic)
{
result = env.GetStaticCharField(clazz, fieldId);
}
else
{
result = env.GetCharField(targetJavaObject, fieldId);
}
JniLocalRef str(env.NewString(&result, 1));
jboolean bol = true;
const char* resP = env.GetStringUTFChars(str, &bol);
fieldResult = handleScope.Escape(ConvertToV8String(resP, 1));
env.ReleaseStringUTFChars(str, resP);
break;
}
case 'S': //short
{
jshort result;
if (isStatic)
{
result = env.GetStaticShortField(clazz, fieldId);
}
else
{
result = env.GetShortField(targetJavaObject, fieldId);
}
fieldResult = handleScope.Escape(Int32::New(isolate, result));
break;
}
case 'I': //int
{
jint result;
if (isStatic)
{
result = env.GetStaticIntField(clazz, fieldId);
}
else
{
result = env.GetIntField(targetJavaObject, fieldId);
}
fieldResult = handleScope.Escape(Int32::New(isolate, result));
break;
}
case 'J': //long
{
jlong result;
if (isStatic)
{
result = env.GetStaticLongField(clazz, fieldId);
}
else
{
result = env.GetLongField(targetJavaObject, fieldId);
}
fieldResult = handleScope.Escape(ArgConverter::ConvertFromJavaLong(result));
break;
}
case 'F': //float
{
jfloat result;
if (isStatic)
{
result = env.GetStaticFloatField(clazz, fieldId);
}
else
{
result = env.GetFloatField(targetJavaObject, fieldId);
}
fieldResult = handleScope.Escape(Number::New(isolate, (double) result));
break;
}
case 'D': //double
{
jdouble result;
if (isStatic)
{
result = env.GetStaticDoubleField(clazz, fieldId);
}
else
{
result = env.GetDoubleField(targetJavaObject, fieldId);
}
fieldResult = handleScope.Escape(Number::New(isolate, result));
break;
}
default:
{
// TODO:
ASSERT_FAIL("Unknown field type");
break;
}
}
}
else
{
jobject result;
if (isStatic)
{
result = env.GetStaticObjectField(clazz, fieldId);
}
else
{
result = env.GetObjectField(targetJavaObject, fieldId);
}
if(result != nullptr) {
bool isString = fieldTypeName == "java/lang/String";
if (isString)
{
auto resultV8Value = ArgConverter::jstringToV8String((jstring)result);
fieldResult = handleScope.Escape(resultV8Value);
}
else
{
int javaObjectID = objectManager->GetOrCreateObjectId(result);
auto objectResult = objectManager->GetJsObjectByJavaObject(javaObjectID);
if (objectResult.IsEmpty())
{
objectResult = objectManager->CreateJSWrapper(javaObjectID, fieldTypeName, result);
}
fieldResult = handleScope.Escape(objectResult);
}
env.DeleteLocalRef(result);
}
else
{
fieldResult = handleScope.Escape(Null(isolate));
}
}
return fieldResult;
}
void FieldAccessor::SetJavaField(const Local<Object>& target, const Local<Value>& value, FieldCallbackData *fieldData)
{
JEnv env;
auto isolate = Isolate::GetCurrent();
HandleScope handleScope(isolate);
jweak targetJavaObject;
const auto& fieldTypeName = fieldData->signature;
auto isStatic = fieldData->isStatic;
auto isPrimitiveType = fieldTypeName.size() == 1;
auto isFieldArray = fieldTypeName[0] == '[';
if (fieldData->fid == nullptr)
{
auto fieldJniSig = isPrimitiveType
? fieldTypeName
: (isFieldArray
? fieldTypeName
: ("L" + fieldTypeName + ";"));
if (isStatic)
{
fieldData->clazz = env.FindClass(fieldData->declaringType);
assert(fieldData->clazz != nullptr);
fieldData->fid = env.GetStaticFieldID(fieldData->clazz, fieldData->name, fieldJniSig);
assert(fieldData->fid != nullptr);
}
else
{
fieldData->clazz = env.FindClass(fieldData->declaringType);
assert(fieldData->clazz != nullptr);
fieldData->fid = env.GetFieldID(fieldData->clazz, fieldData->name, fieldJniSig);
assert(fieldData->fid != nullptr);
}
}
if (!isStatic)
{
targetJavaObject = objectManager->GetJavaObjectByJsObject(target);
}
auto fieldId = fieldData->fid;
auto clazz = fieldData->clazz;
if (isPrimitiveType)
{
switch (fieldTypeName[0])
{
case 'Z': //bool
{
//TODO: validate value is a boolean before calling
if (isStatic)
{
env.SetStaticBooleanField(clazz, fieldId, value->BooleanValue());
}
else
{
env.SetBooleanField(targetJavaObject, fieldId, value->BooleanValue());
}
break;
}
case 'B': //byte
{
//TODO: validate value is a byte before calling
if (isStatic)
{
env.SetStaticByteField(clazz, fieldId, value->Int32Value());
}
else
{
env.SetByteField(targetJavaObject, fieldId, value->Int32Value());
}
break;
}
case 'C': //char
{
//TODO: validate value is a single char
String::Utf8Value stringValue(value->ToString());
JniLocalRef value(env.NewStringUTF(*stringValue));
const char* chars = env.GetStringUTFChars(value, 0);
if (isStatic)
{
env.SetStaticCharField(clazz, fieldId, chars[0]);
}
else
{
env.SetCharField(targetJavaObject, fieldId, chars[0]);
}
env.ReleaseStringUTFChars(value, chars);
break;
}
case 'S': //short
{
//TODO: validate value is a short before calling
if (isStatic)
{
env.SetStaticShortField(clazz, fieldId, value->Int32Value());
}
else
{
env.SetShortField(targetJavaObject, fieldId, value->Int32Value());
}
break;
}
case 'I': //int
{
//TODO: validate value is a int before calling
if (isStatic)
{
env.SetStaticIntField(clazz, fieldId, value->Int32Value());
}
else
{
env.SetIntField(targetJavaObject, fieldId, value->Int32Value());
}
break;
}
case 'J': //long
{
jlong longValue = static_cast<jlong>(ArgConverter::ConvertToJavaLong(value));
if (isStatic)
{
env.SetStaticLongField(clazz, fieldId, longValue);
}
else
{
env.SetLongField(targetJavaObject, fieldId, longValue);
}
break;
}
case 'F': //float
{
if (isStatic)
{
env.SetStaticFloatField(clazz, fieldId, static_cast<jfloat>(value->NumberValue()));
}
else
{
env.SetFloatField(targetJavaObject, fieldId, static_cast<jfloat>(value->NumberValue()));
}
break;
}
case 'D': //double
{
if (isStatic)
{
env.SetStaticDoubleField(clazz, fieldId, value->NumberValue());
}
else
{
env.SetDoubleField(targetJavaObject, fieldId, value->NumberValue());
}
break;
}
default:
{
// TODO:
ASSERT_FAIL("Unknown field type");
break;
}
}
}
else
{
bool isString = fieldTypeName == "java/lang/String";
jobject result = nullptr;
if(!value->IsNull()) {
if (isString)
{
//TODO: validate valie is a string;
String::Utf8Value stringValue(value);
result = env.NewStringUTF(*stringValue);
}
else
{
auto objectWithHiddenID = value->ToObject();
result =objectManager->GetJavaObjectByJsObject(objectWithHiddenID);
}
}
if (isStatic)
{
env.SetStaticObjectField(clazz, fieldId, result);
}
else
{
env.SetObjectField(targetJavaObject, fieldId, result);
}
if (isString)
{
env.DeleteLocalRef(result);
}
}
}
<commit_msg>fixed string conversion<commit_after>#include "FieldAccessor.h"
#include "JniLocalRef.h"
#include "ArgConverter.h"
#include "NativeScriptAssert.h"
#include "Util.h"
#include "V8GlobalHelpers.h"
#include <assert.h>
using namespace v8;
using namespace std;
using namespace tns;
void FieldAccessor::Init(JavaVM *jvm, ObjectManager *objectManager)
{
this->jvm = jvm;
this->objectManager = objectManager;
}
Local<Value> FieldAccessor::GetJavaField(const Local<Object>& target, FieldCallbackData *fieldData)
{
JEnv env;
auto isolate = Isolate::GetCurrent();
EscapableHandleScope handleScope(isolate);
Local<Value> fieldResult;
jweak targetJavaObject;
const auto& fieldTypeName = fieldData->signature;
auto isStatic = fieldData->isStatic;
auto isPrimitiveType = fieldTypeName.size() == 1;
auto isFieldArray = fieldTypeName[0] == '[';
if (fieldData->fid == nullptr)
{
auto fieldJniSig = isPrimitiveType
? fieldTypeName
: (isFieldArray
? fieldTypeName
: ("L" + fieldTypeName + ";"));
if (isStatic)
{
fieldData->clazz = env.FindClass(fieldData->declaringType);
fieldData->fid = env.GetStaticFieldID(fieldData->clazz, fieldData->name, fieldJniSig);
}
else
{
fieldData->clazz = env.FindClass(fieldData->declaringType);
fieldData->fid = env.GetFieldID(fieldData->clazz, fieldData->name, fieldJniSig);
}
}
if (!isStatic)
{
targetJavaObject = objectManager->GetJavaObjectByJsObject(target);
}
auto fieldId = fieldData->fid;
auto clazz = fieldData->clazz;
if (isPrimitiveType)
{
switch (fieldTypeName[0])
{
case 'Z': //bool
{
jboolean result;
if (isStatic)
{
result = env.GetStaticBooleanField(clazz, fieldId);
}
else
{
result = env.GetBooleanField(targetJavaObject, fieldId);
}
fieldResult = Boolean::New(isolate, (result == JNI_TRUE));
break;
}
case 'B': //byte
{
jbyte result;
if (isStatic)
{
result = env.GetStaticByteField(clazz, fieldId);
}
else
{
result = env.GetByteField(targetJavaObject, fieldId);
}
fieldResult = handleScope.Escape(Int32::New(isolate, result));
break;
}
case 'C': //char
{
jchar result;
if (isStatic)
{
result = env.GetStaticCharField(clazz, fieldId);
}
else
{
result = env.GetCharField(targetJavaObject, fieldId);
}
JniLocalRef str(env.NewString(&result, 1));
jboolean bol = true;
const char* resP = env.GetStringUTFChars(str, &bol);
fieldResult = handleScope.Escape(ConvertToV8String(resP, 1));
env.ReleaseStringUTFChars(str, resP);
break;
}
case 'S': //short
{
jshort result;
if (isStatic)
{
result = env.GetStaticShortField(clazz, fieldId);
}
else
{
result = env.GetShortField(targetJavaObject, fieldId);
}
fieldResult = handleScope.Escape(Int32::New(isolate, result));
break;
}
case 'I': //int
{
jint result;
if (isStatic)
{
result = env.GetStaticIntField(clazz, fieldId);
}
else
{
result = env.GetIntField(targetJavaObject, fieldId);
}
fieldResult = handleScope.Escape(Int32::New(isolate, result));
break;
}
case 'J': //long
{
jlong result;
if (isStatic)
{
result = env.GetStaticLongField(clazz, fieldId);
}
else
{
result = env.GetLongField(targetJavaObject, fieldId);
}
fieldResult = handleScope.Escape(ArgConverter::ConvertFromJavaLong(result));
break;
}
case 'F': //float
{
jfloat result;
if (isStatic)
{
result = env.GetStaticFloatField(clazz, fieldId);
}
else
{
result = env.GetFloatField(targetJavaObject, fieldId);
}
fieldResult = handleScope.Escape(Number::New(isolate, (double) result));
break;
}
case 'D': //double
{
jdouble result;
if (isStatic)
{
result = env.GetStaticDoubleField(clazz, fieldId);
}
else
{
result = env.GetDoubleField(targetJavaObject, fieldId);
}
fieldResult = handleScope.Escape(Number::New(isolate, result));
break;
}
default:
{
// TODO:
ASSERT_FAIL("Unknown field type");
break;
}
}
}
else
{
jobject result;
if (isStatic)
{
result = env.GetStaticObjectField(clazz, fieldId);
}
else
{
result = env.GetObjectField(targetJavaObject, fieldId);
}
if(result != nullptr) {
bool isString = fieldTypeName == "java/lang/String";
if (isString)
{
auto resultV8Value = ArgConverter::jstringToV8String((jstring)result);
fieldResult = handleScope.Escape(resultV8Value);
}
else
{
int javaObjectID = objectManager->GetOrCreateObjectId(result);
auto objectResult = objectManager->GetJsObjectByJavaObject(javaObjectID);
if (objectResult.IsEmpty())
{
objectResult = objectManager->CreateJSWrapper(javaObjectID, fieldTypeName, result);
}
fieldResult = handleScope.Escape(objectResult);
}
env.DeleteLocalRef(result);
}
else
{
fieldResult = handleScope.Escape(Null(isolate));
}
}
return fieldResult;
}
void FieldAccessor::SetJavaField(const Local<Object>& target, const Local<Value>& value, FieldCallbackData *fieldData)
{
JEnv env;
auto isolate = Isolate::GetCurrent();
HandleScope handleScope(isolate);
jweak targetJavaObject;
const auto& fieldTypeName = fieldData->signature;
auto isStatic = fieldData->isStatic;
auto isPrimitiveType = fieldTypeName.size() == 1;
auto isFieldArray = fieldTypeName[0] == '[';
if (fieldData->fid == nullptr)
{
auto fieldJniSig = isPrimitiveType
? fieldTypeName
: (isFieldArray
? fieldTypeName
: ("L" + fieldTypeName + ";"));
if (isStatic)
{
fieldData->clazz = env.FindClass(fieldData->declaringType);
assert(fieldData->clazz != nullptr);
fieldData->fid = env.GetStaticFieldID(fieldData->clazz, fieldData->name, fieldJniSig);
assert(fieldData->fid != nullptr);
}
else
{
fieldData->clazz = env.FindClass(fieldData->declaringType);
assert(fieldData->clazz != nullptr);
fieldData->fid = env.GetFieldID(fieldData->clazz, fieldData->name, fieldJniSig);
assert(fieldData->fid != nullptr);
}
}
if (!isStatic)
{
targetJavaObject = objectManager->GetJavaObjectByJsObject(target);
}
auto fieldId = fieldData->fid;
auto clazz = fieldData->clazz;
if (isPrimitiveType)
{
switch (fieldTypeName[0])
{
case 'Z': //bool
{
//TODO: validate value is a boolean before calling
if (isStatic)
{
env.SetStaticBooleanField(clazz, fieldId, value->BooleanValue());
}
else
{
env.SetBooleanField(targetJavaObject, fieldId, value->BooleanValue());
}
break;
}
case 'B': //byte
{
//TODO: validate value is a byte before calling
if (isStatic)
{
env.SetStaticByteField(clazz, fieldId, value->Int32Value());
}
else
{
env.SetByteField(targetJavaObject, fieldId, value->Int32Value());
}
break;
}
case 'C': //char
{
//TODO: validate value is a single char
String::Utf8Value stringValue(value->ToString());
JniLocalRef value(env.NewStringUTF(*stringValue));
const char* chars = env.GetStringUTFChars(value, 0);
if (isStatic)
{
env.SetStaticCharField(clazz, fieldId, chars[0]);
}
else
{
env.SetCharField(targetJavaObject, fieldId, chars[0]);
}
env.ReleaseStringUTFChars(value, chars);
break;
}
case 'S': //short
{
//TODO: validate value is a short before calling
if (isStatic)
{
env.SetStaticShortField(clazz, fieldId, value->Int32Value());
}
else
{
env.SetShortField(targetJavaObject, fieldId, value->Int32Value());
}
break;
}
case 'I': //int
{
//TODO: validate value is a int before calling
if (isStatic)
{
env.SetStaticIntField(clazz, fieldId, value->Int32Value());
}
else
{
env.SetIntField(targetJavaObject, fieldId, value->Int32Value());
}
break;
}
case 'J': //long
{
jlong longValue = static_cast<jlong>(ArgConverter::ConvertToJavaLong(value));
if (isStatic)
{
env.SetStaticLongField(clazz, fieldId, longValue);
}
else
{
env.SetLongField(targetJavaObject, fieldId, longValue);
}
break;
}
case 'F': //float
{
if (isStatic)
{
env.SetStaticFloatField(clazz, fieldId, static_cast<jfloat>(value->NumberValue()));
}
else
{
env.SetFloatField(targetJavaObject, fieldId, static_cast<jfloat>(value->NumberValue()));
}
break;
}
case 'D': //double
{
if (isStatic)
{
env.SetStaticDoubleField(clazz, fieldId, value->NumberValue());
}
else
{
env.SetDoubleField(targetJavaObject, fieldId, value->NumberValue());
}
break;
}
default:
{
// TODO:
ASSERT_FAIL("Unknown field type");
break;
}
}
}
else
{
bool isString = fieldTypeName == "java/lang/String";
jobject result = nullptr;
if(!value->IsNull()) {
if (isString)
{
//TODO: validate valie is a string;
result = ConvertToJavaString(value);
}
else
{
auto objectWithHiddenID = value->ToObject();
result =objectManager->GetJavaObjectByJsObject(objectWithHiddenID);
}
}
if (isStatic)
{
env.SetStaticObjectField(clazz, fieldId, result);
}
else
{
env.SetObjectField(targetJavaObject, fieldId, result);
}
if (isString)
{
env.DeleteLocalRef(result);
}
}
}
<|endoftext|> |
<commit_before>#include "OpenGLTexture.h"
#include "TextureRef.h"
#include "Image.h"
#include "Surface.h"
#define GL_GLEXT_PROTOTYPES
#if defined __APPLE__
#include <OpenGLES/ES3/gl.h>
#include <OpenGLES/ES3/glext.h>
#elif (defined GL_ES)
#include <GLES3/gl3.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#else
#define GL_GLEXT_PROTOTYPES
#ifdef _WIN32
#include <GL/glew.h>
#include <windows.h>
#endif
#ifdef ANDROID
#include <GLES3/gl3.h>
#include <GLES3/gl3ext.h>
#else
#include <GL/gl.h>
#ifdef _WIN32
#include "glext.h"
#else
#include <GL/glext.h>
#endif
#endif
#endif
#if defined __APPLE__ || defined ANDROID
#ifndef GL_COMPRESSED_RGB_S3TC_DXT1_EXT
#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0
#endif
#ifndef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT
#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0
#endif
#ifndef GL_COMPRESSED_RED_RGTC1
#define GL_COMPRESSED_RED_RGTC1 0x8DBB
#endif
#ifndef GL_COMPRESSED_RG_RGTC2
#define GL_COMPRESSED_RG_RGTC2 0x8DBD
#endif
#endif
#include <cassert>
#include <iostream>
using namespace std;
using namespace canvas;
size_t OpenGLTexture::total_textures = 0;
vector<unsigned int> OpenGLTexture::freed_textures;
bool OpenGLTexture::global_init = false;
OpenGLTexture::OpenGLTexture(Surface & surface)
: Texture(surface.getLogicalWidth(), surface.getLogicalHeight(), surface.getActualWidth(), surface.getActualHeight(), surface.getMinFilter(), surface.getMagFilter(), surface.getTargetFormat(), 1) {
assert(getInternalFormat());
auto image = surface.createImage();
updateData(*image, 0, 0);
}
static GLenum getOpenGLInternalFormat(InternalFormat internal_format) {
switch (internal_format) {
case R8: return GL_R8;
case RG8: return GL_RG8;
case RGB565: return GL_RGB565;
case RGBA4: return GL_RGBA4;
case RGBA8: return GL_RGBA8;
case RGB8: return GL_RGB8;
case RGB8_24: return GL_RGBA8;
case RED_RGTC1: return GL_COMPRESSED_RED_RGTC1;
case RG_RGTC2: return GL_COMPRESSED_RG_RGTC2;
case RGB_ETC1: return GL_COMPRESSED_RGB8_ETC2;
case RGB_DXT1: return GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
case RGBA_DXT5: return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
case LUMINANCE_ALPHA: return GL_RG8;
case LA44: return GL_R8; // pack luminance and alpha to single byte
case R32F: return GL_R32F;
}
assert(0);
return 0;
}
static GLenum getOpenGLFilterType(FilterMode mode) {
switch (mode) {
case NEAREST: return GL_NEAREST;
case LINEAR: return GL_LINEAR;
case LINEAR_MIPMAP_LINEAR: return GL_LINEAR_MIPMAP_LINEAR;
}
return 0;
}
void
OpenGLTexture::updateCompressedData(const Image & image, unsigned int x, unsigned int y) {
unsigned int offset = 0;
unsigned int current_width = image.getWidth(), current_height = image.getHeight();
GLenum format = getOpenGLInternalFormat(getInternalFormat());
for (unsigned int level = 0; level < image.getLevels(); level++) {
size_t size = image.calculateOffset(level + 1) - image.calculateOffset(level);
// cerr << "compressed tex: x = " << x << ", y = " << y << ", l = " << (level+1) << "/" << image.getLevels() << ", w = " << current_width << ", h = " << current_height << ", offset = " << offset << ", size = " << size << endl;
glCompressedTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, format, size, image.getData() + offset);
offset += size;
current_width /= 2;
current_height /= 2;
x /= 2;
y /= 2;
}
}
void
OpenGLTexture::updatePlainData(const Image & image, unsigned int x, unsigned int y) {
unsigned int offset = 0;
unsigned int current_width = image.getWidth(), current_height = image.getHeight();
GLenum format = getOpenGLInternalFormat(getInternalFormat());
for (unsigned int level = 0; level < image.getLevels(); level++) {
size_t size = image.calculateOffset(level + 1) - image.calculateOffset(level);
// cerr << "plain tex: x = " << x << ", y = " << y << ", l = " << (level+1) << "/" << image.getLevels() << ", w = " << current_width << ", h = " << current_height << ", size = " << size << ", offset = " << offset << endl;
if (getInternalFormat() == RGBA8) {
#if defined __APPLE__ || defined ANDROID
glTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, GL_RGBA, GL_UNSIGNED_BYTE, image.getData() + offset);
#else
glTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, image.getData() + offset);
// glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, tmp_image.getWidth(), height, GL_BGRA_EXT, GL_UNSIGNED_BYTE, image.getData());
#endif
} else if (getInternalFormat() == LA44) {
glTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, GL_RED, GL_UNSIGNED_BYTE, image.getData() + offset);
} else if (getInternalFormat() == RGB565) {
glTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, image.getData() + offset);
} else if (getInternalFormat() == R32F) {
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, current_width, current_height, GL_RED, GL_FLOAT, image.getData() + offset);
} else {
cerr << "unhandled format " << int(getInternalFormat()) << endl;
assert(0);
}
// glTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, getOpenGLInternalFormat(getInternalFormat()), size, image.getData() + offset);
offset += size;
current_width /= 2;
current_height /= 2;
x /= 2;
y /= 2;
}
}
void
OpenGLTexture::updateData(const Image & image, unsigned int x, unsigned int y) {
if (!global_init) {
global_init = true;
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
}
bool initialize = false;
if (!texture_id) {
initialize = true;
glGenTextures(1, &texture_id);
cerr << "created texture id " << texture_id << " (total = " << total_textures << ")" << endl;
if (texture_id >= 1) total_textures++;
}
assert(texture_id >= 1);
glBindTexture(GL_TEXTURE_2D, texture_id);
bool has_mipmaps = getMinFilter() == LINEAR_MIPMAP_LINEAR;
if (initialize) {
glTexStorage2D(GL_TEXTURE_2D, has_mipmaps ? getMipmapLevels() : 1, getOpenGLInternalFormat(getInternalFormat()), getActualWidth(), getActualHeight());
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, getOpenGLFilterType(getMinFilter()));
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, getOpenGLFilterType(getMagFilter()));
if (x != 0 || y != 0 || image.getWidth() != getActualWidth() || image.getHeight() != getActualHeight()) {
int levels = has_mipmaps ? getMipmapLevels() : 1;
if (getInternalFormat() == RGB_ETC1) {
Image img(ImageFormat::RGB_ETC1, getActualWidth(), getActualHeight(), levels);
updateCompressedData(img, 0, 0);
} else if (getInternalFormat() == RGB_DXT1) {
Image img(ImageFormat::RGB_DXT1, getActualWidth(), getActualHeight(), levels);
updateCompressedData(img, 0, 0);
} else if (getInternalFormat() == RGBA8) {
Image img(ImageFormat::RGBA32, getActualWidth(), getActualHeight(), levels);
updatePlainData(img, 0, 0);
} else if (getInternalFormat() == LA44) {
Image img(ImageFormat::LA44, getActualWidth(), getActualHeight(), levels);
updatePlainData(img, 0, 0);
} else if (getInternalFormat() == RGB565) {
Image img(ImageFormat::RGB565, getActualWidth(), getActualHeight(), levels);
updatePlainData(img, 0, 0);
} else if (getInternalFormat() == R32F) {
assert(levels == 1);
Image img(ImageFormat::FLOAT32, getActualWidth(), getActualHeight(), levels);
updatePlainData(img, 0, 0);
} else {
assert(0);
}
}
}
if (getInternalFormat() == R32F) {
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, image.getWidth(), image.getHeight(), GL_RED, GL_FLOAT, image.getData());
} else if (getInternalFormat() == R8) {
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, image.getWidth(), image.getHeight(), GL_RED, GL_UNSIGNED_BYTE, image.getData());
} else if (getInternalFormat() == LA44) {
auto tmp_image = image.convert(ImageFormat::LA44);
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, tmp_image->getWidth(), tmp_image->getHeight(), GL_RED, GL_UNSIGNED_BYTE, tmp_image->getData());
} else if (getInternalFormat() == LUMINANCE_ALPHA) {
if (image.getFormat() == ImageFormat::LA88) {
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, image.getWidth(), image.getHeight(), GL_RG, GL_UNSIGNED_BYTE, image.getData());
} else {
auto tmp_image = image.convert(ImageFormat::LA88);
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, tmp_image->getWidth(), tmp_image->getHeight(), GL_RG, GL_UNSIGNED_BYTE, tmp_image->getData());
}
} else if (getInternalFormat() == RGB565) {
auto tmp_image = image.convert(ImageFormat::RGB565);
updatePlainData(*tmp_image, x, y);
// glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, tmp_image->getWidth(), tmp_image->getHeight(), GL_RGB, GL_UNSIGNED_SHORT_5_6_5, tmp_image->getData());
} else if (getInternalFormat() == RGBA4) {
auto tmp_image = image.convert(ImageFormat::RGBA4);
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, tmp_image->getWidth(), tmp_image->getHeight(), GL_RGBA4, GL_UNSIGNED_SHORT_4_4_4_4, tmp_image->getData());
} else if (getInternalFormat() == RGB_ETC1) {
if (image.getFormat().getCompression() == ImageFormat::ETC1) {
updateCompressedData(image, x, y);
} else {
cerr << "WARNING: compression should be done in thread\n";
auto tmp_image = image.convert(ImageFormat::RGB_ETC1);
updateCompressedData(*tmp_image, x, y);
}
} else if (getInternalFormat() == RGB_DXT1) {
if (image.getFormat().getCompression() == ImageFormat::DXT1) {
updateCompressedData(image, x, y);
} else {
cerr << "WARNING: compression should be done in thread\n";
auto tmp_image = image.convert(ImageFormat::RGB_DXT1);
updateCompressedData(*tmp_image, x, y);
}
} else if (getInternalFormat() == RG_RGTC2) {
if (image.getFormat().getCompression() == ImageFormat::RGTC2) {
updateCompressedData(image, x, y);
} else {
cerr << "WARNING: compression should be done in thread\n";
auto tmp_image = image.convert(ImageFormat::RG_RGTC2);
updateCompressedData(*tmp_image, x, y);
}
} else {
updatePlainData(image, x, y);
}
if (has_mipmaps && image.getLevels() == 1) {
need_mipmaps = true;
}
glBindTexture(GL_TEXTURE_2D, 0);
}
void
OpenGLTexture::generateMipmaps() {
if (need_mipmaps) {
if (getInternalFormat() != RGB_DXT1 && getInternalFormat() != RGB_ETC1 && getInternalFormat() != LA44 && getInternalFormat() != RED_RGTC1 && getInternalFormat() != RG_RGTC2) {
glGenerateMipmap(GL_TEXTURE_2D);
} else {
cerr << "unable to generate mipmaps for compressed texture!\n";
}
need_mipmaps = false;
}
}
void
OpenGLTexture::releaseTextures() {
if (!freed_textures.empty()) {
cerr << "DELETING TEXTURES: " << OpenGLTexture::getFreedTextures().size() << "/" << OpenGLTexture::getNumTextures() << endl;
for (vector<unsigned int>::const_iterator it = freed_textures.begin(); it != freed_textures.end(); it++) {
GLuint texid = *it;
glDeleteTextures(1, &texid);
}
freed_textures.clear();
}
}
TextureRef
OpenGLTexture::createTexture(unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, FilterMode min_filter, FilterMode mag_filter, InternalFormat _internal_format, unsigned int mipmap_levels) {
assert(_internal_format);
return TextureRef(_logical_width, _logical_height, _actual_width, _actual_height, new OpenGLTexture(_logical_width, _logical_height, _actual_width, _actual_height, min_filter, mag_filter, _internal_format, mipmap_levels));
}
TextureRef
OpenGLTexture::createTexture(Surface & surface) {
return TextureRef( surface.getLogicalWidth(),
surface.getLogicalHeight(),
surface.getActualWidth(),
surface.getActualHeight(),
new OpenGLTexture(surface)
);
}
<commit_msg>add assert<commit_after>#include "OpenGLTexture.h"
#include "TextureRef.h"
#include "Image.h"
#include "Surface.h"
#define GL_GLEXT_PROTOTYPES
#if defined __APPLE__
#include <OpenGLES/ES3/gl.h>
#include <OpenGLES/ES3/glext.h>
#elif (defined GL_ES)
#include <GLES3/gl3.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#else
#define GL_GLEXT_PROTOTYPES
#ifdef _WIN32
#include <GL/glew.h>
#include <windows.h>
#endif
#ifdef ANDROID
#include <GLES3/gl3.h>
#include <GLES3/gl3ext.h>
#else
#include <GL/gl.h>
#ifdef _WIN32
#include "glext.h"
#else
#include <GL/glext.h>
#endif
#endif
#endif
#if defined __APPLE__ || defined ANDROID
#ifndef GL_COMPRESSED_RGB_S3TC_DXT1_EXT
#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0
#endif
#ifndef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT
#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0
#endif
#ifndef GL_COMPRESSED_RED_RGTC1
#define GL_COMPRESSED_RED_RGTC1 0x8DBB
#endif
#ifndef GL_COMPRESSED_RG_RGTC2
#define GL_COMPRESSED_RG_RGTC2 0x8DBD
#endif
#endif
#include <cassert>
#include <iostream>
using namespace std;
using namespace canvas;
size_t OpenGLTexture::total_textures = 0;
vector<unsigned int> OpenGLTexture::freed_textures;
bool OpenGLTexture::global_init = false;
OpenGLTexture::OpenGLTexture(Surface & surface)
: Texture(surface.getLogicalWidth(), surface.getLogicalHeight(), surface.getActualWidth(), surface.getActualHeight(), surface.getMinFilter(), surface.getMagFilter(), surface.getTargetFormat(), 1) {
assert(getInternalFormat());
auto image = surface.createImage();
updateData(*image, 0, 0);
}
static GLenum getOpenGLInternalFormat(InternalFormat internal_format) {
switch (internal_format) {
case R8: return GL_R8;
case RG8: return GL_RG8;
case RGB565: return GL_RGB565;
case RGBA4: return GL_RGBA4;
case RGBA8: return GL_RGBA8;
case RGB8: return GL_RGB8;
case RGB8_24: return GL_RGBA8;
case RED_RGTC1: return GL_COMPRESSED_RED_RGTC1;
case RG_RGTC2: return GL_COMPRESSED_RG_RGTC2;
case RGB_ETC1: return GL_COMPRESSED_RGB8_ETC2;
case RGB_DXT1: return GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
case RGBA_DXT5: return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
case LUMINANCE_ALPHA: return GL_RG8;
case LA44: return GL_R8; // pack luminance and alpha to single byte
case R32F: return GL_R32F;
}
assert(0);
return 0;
}
static GLenum getOpenGLFilterType(FilterMode mode) {
switch (mode) {
case NEAREST: return GL_NEAREST;
case LINEAR: return GL_LINEAR;
case LINEAR_MIPMAP_LINEAR: return GL_LINEAR_MIPMAP_LINEAR;
}
return 0;
}
void
OpenGLTexture::updateCompressedData(const Image & image, unsigned int x, unsigned int y) {
unsigned int offset = 0;
unsigned int current_width = image.getWidth(), current_height = image.getHeight();
GLenum format = getOpenGLInternalFormat(getInternalFormat());
for (unsigned int level = 0; level < image.getLevels(); level++) {
size_t size = image.calculateOffset(level + 1) - image.calculateOffset(level);
// cerr << "compressed tex: x = " << x << ", y = " << y << ", l = " << (level+1) << "/" << image.getLevels() << ", w = " << current_width << ", h = " << current_height << ", offset = " << offset << ", size = " << size << endl;
glCompressedTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, format, size, image.getData() + offset);
offset += size;
current_width /= 2;
current_height /= 2;
x /= 2;
y /= 2;
}
}
void
OpenGLTexture::updatePlainData(const Image & image, unsigned int x, unsigned int y) {
unsigned int offset = 0;
unsigned int current_width = image.getWidth(), current_height = image.getHeight();
GLenum format = getOpenGLInternalFormat(getInternalFormat());
for (unsigned int level = 0; level < image.getLevels(); level++) {
size_t size = image.calculateOffset(level + 1) - image.calculateOffset(level);
// cerr << "plain tex: x = " << x << ", y = " << y << ", l = " << (level+1) << "/" << image.getLevels() << ", w = " << current_width << ", h = " << current_height << ", size = " << size << ", offset = " << offset << endl;
if (getInternalFormat() == RGBA8) {
assert(image.getData());
#if defined __APPLE__ || defined ANDROID
glTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, GL_RGBA, GL_UNSIGNED_BYTE, image.getData() + offset);
#else
glTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, image.getData() + offset);
// glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, tmp_image.getWidth(), height, GL_BGRA_EXT, GL_UNSIGNED_BYTE, image.getData());
#endif
} else if (getInternalFormat() == LA44) {
glTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, GL_RED, GL_UNSIGNED_BYTE, image.getData() + offset);
} else if (getInternalFormat() == RGB565) {
glTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, image.getData() + offset);
} else if (getInternalFormat() == R32F) {
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, current_width, current_height, GL_RED, GL_FLOAT, image.getData() + offset);
} else {
cerr << "unhandled format " << int(getInternalFormat()) << endl;
assert(0);
}
// glTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, getOpenGLInternalFormat(getInternalFormat()), size, image.getData() + offset);
offset += size;
current_width /= 2;
current_height /= 2;
x /= 2;
y /= 2;
}
}
void
OpenGLTexture::updateData(const Image & image, unsigned int x, unsigned int y) {
if (!global_init) {
global_init = true;
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
}
bool initialize = false;
if (!texture_id) {
initialize = true;
glGenTextures(1, &texture_id);
cerr << "created texture id " << texture_id << " (total = " << total_textures << ")" << endl;
if (texture_id >= 1) total_textures++;
}
assert(texture_id >= 1);
glBindTexture(GL_TEXTURE_2D, texture_id);
bool has_mipmaps = getMinFilter() == LINEAR_MIPMAP_LINEAR;
if (initialize) {
glTexStorage2D(GL_TEXTURE_2D, has_mipmaps ? getMipmapLevels() : 1, getOpenGLInternalFormat(getInternalFormat()), getActualWidth(), getActualHeight());
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, getOpenGLFilterType(getMinFilter()));
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, getOpenGLFilterType(getMagFilter()));
if (x != 0 || y != 0 || image.getWidth() != getActualWidth() || image.getHeight() != getActualHeight()) {
int levels = has_mipmaps ? getMipmapLevels() : 1;
if (getInternalFormat() == RGB_ETC1) {
Image img(ImageFormat::RGB_ETC1, getActualWidth(), getActualHeight(), levels);
updateCompressedData(img, 0, 0);
} else if (getInternalFormat() == RGB_DXT1) {
Image img(ImageFormat::RGB_DXT1, getActualWidth(), getActualHeight(), levels);
updateCompressedData(img, 0, 0);
} else if (getInternalFormat() == RGBA8) {
Image img(ImageFormat::RGBA32, getActualWidth(), getActualHeight(), levels);
updatePlainData(img, 0, 0);
} else if (getInternalFormat() == LA44) {
Image img(ImageFormat::LA44, getActualWidth(), getActualHeight(), levels);
updatePlainData(img, 0, 0);
} else if (getInternalFormat() == RGB565) {
Image img(ImageFormat::RGB565, getActualWidth(), getActualHeight(), levels);
updatePlainData(img, 0, 0);
} else if (getInternalFormat() == R32F) {
assert(levels == 1);
Image img(ImageFormat::FLOAT32, getActualWidth(), getActualHeight(), levels);
updatePlainData(img, 0, 0);
} else {
assert(0);
}
}
}
if (getInternalFormat() == R32F) {
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, image.getWidth(), image.getHeight(), GL_RED, GL_FLOAT, image.getData());
} else if (getInternalFormat() == R8) {
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, image.getWidth(), image.getHeight(), GL_RED, GL_UNSIGNED_BYTE, image.getData());
} else if (getInternalFormat() == LA44) {
auto tmp_image = image.convert(ImageFormat::LA44);
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, tmp_image->getWidth(), tmp_image->getHeight(), GL_RED, GL_UNSIGNED_BYTE, tmp_image->getData());
} else if (getInternalFormat() == LUMINANCE_ALPHA) {
if (image.getFormat() == ImageFormat::LA88) {
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, image.getWidth(), image.getHeight(), GL_RG, GL_UNSIGNED_BYTE, image.getData());
} else {
auto tmp_image = image.convert(ImageFormat::LA88);
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, tmp_image->getWidth(), tmp_image->getHeight(), GL_RG, GL_UNSIGNED_BYTE, tmp_image->getData());
}
} else if (getInternalFormat() == RGB565) {
auto tmp_image = image.convert(ImageFormat::RGB565);
updatePlainData(*tmp_image, x, y);
// glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, tmp_image->getWidth(), tmp_image->getHeight(), GL_RGB, GL_UNSIGNED_SHORT_5_6_5, tmp_image->getData());
} else if (getInternalFormat() == RGBA4) {
auto tmp_image = image.convert(ImageFormat::RGBA4);
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, tmp_image->getWidth(), tmp_image->getHeight(), GL_RGBA4, GL_UNSIGNED_SHORT_4_4_4_4, tmp_image->getData());
} else if (getInternalFormat() == RGB_ETC1) {
if (image.getFormat().getCompression() == ImageFormat::ETC1) {
updateCompressedData(image, x, y);
} else {
cerr << "WARNING: compression should be done in thread\n";
auto tmp_image = image.convert(ImageFormat::RGB_ETC1);
updateCompressedData(*tmp_image, x, y);
}
} else if (getInternalFormat() == RGB_DXT1) {
if (image.getFormat().getCompression() == ImageFormat::DXT1) {
updateCompressedData(image, x, y);
} else {
cerr << "WARNING: compression should be done in thread\n";
auto tmp_image = image.convert(ImageFormat::RGB_DXT1);
updateCompressedData(*tmp_image, x, y);
}
} else if (getInternalFormat() == RG_RGTC2) {
if (image.getFormat().getCompression() == ImageFormat::RGTC2) {
updateCompressedData(image, x, y);
} else {
cerr << "WARNING: compression should be done in thread\n";
auto tmp_image = image.convert(ImageFormat::RG_RGTC2);
updateCompressedData(*tmp_image, x, y);
}
} else {
updatePlainData(image, x, y);
}
if (has_mipmaps && image.getLevels() == 1) {
need_mipmaps = true;
}
glBindTexture(GL_TEXTURE_2D, 0);
}
void
OpenGLTexture::generateMipmaps() {
if (need_mipmaps) {
if (getInternalFormat() != RGB_DXT1 && getInternalFormat() != RGB_ETC1 && getInternalFormat() != LA44 && getInternalFormat() != RED_RGTC1 && getInternalFormat() != RG_RGTC2) {
glGenerateMipmap(GL_TEXTURE_2D);
} else {
cerr << "unable to generate mipmaps for compressed texture!\n";
}
need_mipmaps = false;
}
}
void
OpenGLTexture::releaseTextures() {
if (!freed_textures.empty()) {
cerr << "DELETING TEXTURES: " << OpenGLTexture::getFreedTextures().size() << "/" << OpenGLTexture::getNumTextures() << endl;
for (vector<unsigned int>::const_iterator it = freed_textures.begin(); it != freed_textures.end(); it++) {
GLuint texid = *it;
glDeleteTextures(1, &texid);
}
freed_textures.clear();
}
}
TextureRef
OpenGLTexture::createTexture(unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, FilterMode min_filter, FilterMode mag_filter, InternalFormat _internal_format, unsigned int mipmap_levels) {
assert(_internal_format);
return TextureRef(_logical_width, _logical_height, _actual_width, _actual_height, new OpenGLTexture(_logical_width, _logical_height, _actual_width, _actual_height, min_filter, mag_filter, _internal_format, mipmap_levels));
}
TextureRef
OpenGLTexture::createTexture(Surface & surface) {
return TextureRef( surface.getLogicalWidth(),
surface.getLogicalHeight(),
surface.getActualWidth(),
surface.getActualHeight(),
new OpenGLTexture(surface)
);
}
<|endoftext|> |
<commit_before>#include <Render/Pipelining/Buffer/Renderbuffer.hh>
#include <utility>
namespace AGE
{
Renderbuffer::Renderbuffer(GLint width, GLint height, GLenum internal_format) :
_id(0),
_width(width),
_height(height),
_internal_format(internal_format)
{
glGenRenderbuffers(1, &_id);
bind();
glRenderbufferStorage(GL_RENDERBUFFER, _internal_format, _width, _height);
unbind();
}
Renderbuffer::Renderbuffer(Renderbuffer &&move) :
_id(move._id),
_width(move._width),
_height(move._height),
_internal_format(move._internal_format)
{
move._id = 0;
}
Renderbuffer::~Renderbuffer()
{
if (_id)
{
glDeleteRenderbuffers(1, &_id);
}
}
GLenum Renderbuffer::type() const
{
return (GL_RENDERBUFFER);
}
Renderbuffer const & Renderbuffer::bind() const
{
glBindRenderbuffer(GL_RENDERBUFFER, _id);
return (*this);
}
Renderbuffer const & Renderbuffer::unbind() const
{
glBindRenderbuffer(GL_RENDERBUFFER, 0);
return (*this);
}
IFramebufferStorage const & Renderbuffer::attachment(Framebuffer const &framebuffer, GLenum attach) const
{
bind();
glFramebufferRenderbuffer(framebuffer.type(), attach, GL_RENDERBUFFER, _id);
unbind();
return (*this);
}
}<commit_msg>unbind useless<commit_after>#include <Render/Pipelining/Buffer/Renderbuffer.hh>
#include <utility>
namespace AGE
{
Renderbuffer::Renderbuffer(GLint width, GLint height, GLenum internal_format) :
_id(0),
_width(width),
_height(height),
_internal_format(internal_format)
{
glGenRenderbuffers(1, &_id);
bind();
glRenderbufferStorage(GL_RENDERBUFFER, _internal_format, _width, _height);
unbind();
}
Renderbuffer::Renderbuffer(Renderbuffer &&move) :
_id(move._id),
_width(move._width),
_height(move._height),
_internal_format(move._internal_format)
{
move._id = 0;
}
Renderbuffer::~Renderbuffer()
{
if (_id)
{
glDeleteRenderbuffers(1, &_id);
}
}
GLenum Renderbuffer::type() const
{
return (GL_RENDERBUFFER);
}
Renderbuffer const & Renderbuffer::bind() const
{
glBindRenderbuffer(GL_RENDERBUFFER, _id);
return (*this);
}
Renderbuffer const & Renderbuffer::unbind() const
{
glBindRenderbuffer(GL_RENDERBUFFER, 0);
return (*this);
}
IFramebufferStorage const & Renderbuffer::attachment(Framebuffer const &framebuffer, GLenum attach) const
{
bind();
glFramebufferRenderbuffer(framebuffer.type(), attach, GL_RENDERBUFFER, _id);
return (*this);
}
}<|endoftext|> |
<commit_before>/**
*
* @file ESP8266WiFiMulti.cpp
* @date 16.05.2015
* @author Markus Sattler
*
* Copyright (c) 2015 Markus Sattler. All rights reserved.
* This file is part of the esp8266 core for Arduino environment.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "ESP8266WiFiMulti.h"
#include <limits.h>
#include <string.h>
ESP8266WiFiMulti::ESP8266WiFiMulti() {
}
ESP8266WiFiMulti::~ESP8266WiFiMulti() {
APlistClean();
}
bool ESP8266WiFiMulti::addAP(const char* ssid, const char *passphrase) {
return APlistAdd(ssid, passphrase);
}
wl_status_t ESP8266WiFiMulti::run(void) {
int8_t scanResult;
wl_status_t status = WiFi.status();
if(status == WL_DISCONNECTED || status == WL_NO_SSID_AVAIL || status == WL_IDLE_STATUS || status == WL_CONNECT_FAILED) {
ledState(1);
scanResult = WiFi.scanComplete();
if(scanResult == WIFI_SCAN_RUNNING) {
// scan is running
return WL_NO_SSID_AVAIL;
} else if(scanResult > 0) {
// scan done analyze
WifiAPlist_t bestNetwork { NULL, NULL };
int bestNetworkDb = INT_MIN;
uint8 bestBSSID[6];
int32_t bestChannel;
DEBUG_WIFI_MULTI("[WIFI] scan done\n");
delay(0);
if(scanResult <= 0) {
DEBUG_WIFI_MULTI("[WIFI] no networks found\n");
} else {
DEBUG_WIFI_MULTI("[WIFI] %d networks found\n", scanResult);
for(int8_t i = 0; i < scanResult; ++i) {
String ssid_scan;
int32_t rssi_scan;
uint8_t sec_scan;
uint8_t* BSSID_scan;
int32_t chan_scan;
bool hidden_scan;
WiFi.getNetworkInfo(i, ssid_scan, sec_scan, rssi_scan, BSSID_scan, chan_scan, hidden_scan);
bool known = false;
for(uint32_t x = 0; x < APlist.size(); x++) {
WifiAPlist_t entry = APlist[x];
if(ssid_scan == entry.ssid) { // SSID match
known = true;
if(rssi_scan > bestNetworkDb) { // best network
if(sec_scan == ENC_TYPE_NONE || entry.passphrase) { // check for passphrase if not open wlan
bestNetworkDb = rssi_scan;
bestChannel = chan_scan;
memcpy((void*) &bestNetwork, (void*) &entry, sizeof(bestNetwork));
memcpy((void*) &bestBSSID, (void*) BSSID_scan, sizeof(bestBSSID));
}
}
break;
}
}
if(known) {
DEBUG_WIFI_MULTI(" ---> ");
} else {
DEBUG_WIFI_MULTI(" ");
}
DEBUG_WIFI_MULTI(" %d: [%d][%02X:%02X:%02X:%02X:%02X:%02X] %s (%d) %c\n", i, chan_scan, BSSID_scan[0], BSSID_scan[1], BSSID_scan[2], BSSID_scan[3], BSSID_scan[4], BSSID_scan[5], ssid_scan.c_str(), rssi_scan, (sec_scan == ENC_TYPE_NONE) ? ' ' : '*');
delay(0);
}
}
// clean up ram
WiFi.scanDelete();
ledState(1);
DEBUG_WIFI_MULTI("\n\n");
delay(0);
if(bestNetwork.ssid) {
DEBUG_WIFI_MULTI("[WIFI] Connecting BSSID: %02X:%02X:%02X:%02X:%02X:%02X SSID: %s Channal: %d (%d)\n", bestBSSID[0], bestBSSID[1], bestBSSID[2], bestBSSID[3], bestBSSID[4], bestBSSID[5], bestNetwork.ssid, bestChannel, bestNetworkDb);
/*Serial.println("wifi.begin");
Serial.println(bestNetwork.ssid);
Serial.println(bestNetwork.passphrase);
Serial.println(bestChannel);
Serial.println("-------------");*/
WiFi.begin(bestNetwork.ssid, bestNetwork.passphrase, bestChannel, bestBSSID);
status = WiFi.status();
int s = 0;
// wait for connection or fail
while(status != WL_CONNECTED && status != WL_NO_SSID_AVAIL && status != WL_CONNECT_FAILED) {
delay(10);
s++;
status = WiFi.status();
if (s % 10 == 0) {
ledState(1);
if (s % 150 == 0)break;
}
}
if(status==WL_CONNECTED)ledState(2);
#ifdef DEBUG_ESP_WIFI
IPAddress ip;
uint8_t * mac;
switch(status) {
case WL_CONNECTED:
ip = WiFi.localIP();
mac = WiFi.BSSID();
DEBUG_WIFI_MULTI("[WIFI] Connecting done.\n");
DEBUG_WIFI_MULTI("[WIFI] SSID: %s\n", WiFi.SSID().c_str());
DEBUG_WIFI_MULTI("[WIFI] IP: %d.%d.%d.%d\n", ip[0], ip[1], ip[2], ip[3]);
DEBUG_WIFI_MULTI("[WIFI] MAC: %02X:%02X:%02X:%02X:%02X:%02X\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
DEBUG_WIFI_MULTI("[WIFI] Channel: %d\n", WiFi.channel());
break;
case WL_NO_SSID_AVAIL:
DEBUG_WIFI_MULTI("[WIFI] Connecting Failed AP not found.\n");
break;
case WL_CONNECT_FAILED:
DEBUG_WIFI_MULTI("[WIFI] Connecting Failed.\n");
break;
default:
DEBUG_WIFI_MULTI("[WIFI] Connecting Failed (%d).\n", status);
break;
}
#endif
} else {
ledState(3);
DEBUG_WIFI_MULTI("[WIFI] no matching wifi found!\n");
}
} else {
ledState(3);
// start scan
DEBUG_WIFI_MULTI("[WIFI] delete old wifi config...\n");
WiFi.disconnect();
DEBUG_WIFI_MULTI("[WIFI] start scan\n");
// scan wifi async mode
WiFi.scanNetworks(true);
}
}
return status;
}
// ##################################################################################
bool ESP8266WiFiMulti::APlistAdd(const char* ssid, const char *passphrase) {
WifiAPlist_t newAP;
if(!ssid || *ssid == 0x00 || strlen(ssid) > 31) {
// fail SSID to long or missing!
DEBUG_WIFI_MULTI("[WIFI][APlistAdd] no ssid or ssid to long\n");
return false;
}
if(passphrase && strlen(passphrase) > 63) {
// fail passphrase to long!
DEBUG_WIFI_MULTI("[WIFI][APlistAdd] passphrase to long\n");
return false;
}
newAP.ssid = strdup(ssid);
if(!newAP.ssid) {
DEBUG_WIFI_MULTI("[WIFI][APlistAdd] fail newAP.ssid == 0\n");
return false;
}
if(passphrase && *passphrase != 0x00) {
newAP.passphrase = strdup(passphrase);
if(!newAP.passphrase) {
DEBUG_WIFI_MULTI("[WIFI][APlistAdd] fail newAP.passphrase == 0\n");
free(newAP.ssid);
return false;
}
}
APlist.push_back(newAP);
DEBUG_WIFI_MULTI("[WIFI][APlistAdd] add SSID: %s\n", newAP.ssid);
return true;
}
void ESP8266WiFiMulti::APlistClean(void) {
for(uint32_t i = 0; i < APlist.size(); i++) {
WifiAPlist_t entry = APlist[i];
if(entry.ssid) {
free(entry.ssid);
}
if(entry.passphrase) {
free(entry.passphrase);
}
}
APlist.clear();
}
void ESP8266WiFiMulti::ledState(int i)
{
int j = 0;
switch (i)
{
case 1://接続中
Nefry.setLed(0x00, 0x4f, 0x00);
delay(50);
Nefry.setLed(0x00, 0x00, 0x00);
break;
case 2://接続完了
Nefry.setLed(0x00, 0xff, 0xff);
break;
case 3://接続失敗
for (j = 0; j < 4; j++) {
Nefry.setLed(0xff, 0x00, 0x00);
delay(50);
Nefry.setLed(0x00, 0x00, 0x00);
delay(50);
}
break;
default:
break;
}
}
<commit_msg>WriteModeへの移行と検索時間の延長<commit_after>/**
*
* @file ESP8266WiFiMulti.cpp
* @date 16.05.2015
* @author Markus Sattler
*
* Copyright (c) 2015 Markus Sattler. All rights reserved.
* This file is part of the esp8266 core for Arduino environment.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "ESP8266WiFiMulti.h"
#include <limits.h>
#include <string.h>
ESP8266WiFiMulti::ESP8266WiFiMulti() {
}
ESP8266WiFiMulti::~ESP8266WiFiMulti() {
APlistClean();
}
bool ESP8266WiFiMulti::addAP(const char* ssid, const char *passphrase) {
return APlistAdd(ssid, passphrase);
}
wl_status_t ESP8266WiFiMulti::run(void) {
int8_t scanResult;
wl_status_t status = WiFi.status();
if(status == WL_DISCONNECTED || status == WL_NO_SSID_AVAIL || status == WL_IDLE_STATUS || status == WL_CONNECT_FAILED) {
ledState(1);
scanResult = WiFi.scanComplete();
if(scanResult == WIFI_SCAN_RUNNING) {
// scan is running
return WL_NO_SSID_AVAIL;
} else if(scanResult > 0) {
// scan done analyze
WifiAPlist_t bestNetwork { NULL, NULL };
int bestNetworkDb = INT_MIN;
uint8 bestBSSID[6];
int32_t bestChannel;
DEBUG_WIFI_MULTI("[WIFI] scan done\n");
delay(0);
if(scanResult <= 0) {
DEBUG_WIFI_MULTI("[WIFI] no networks found\n");
} else {
DEBUG_WIFI_MULTI("[WIFI] %d networks found\n", scanResult);
for(int8_t i = 0; i < scanResult; ++i) {
String ssid_scan;
int32_t rssi_scan;
uint8_t sec_scan;
uint8_t* BSSID_scan;
int32_t chan_scan;
bool hidden_scan;
WiFi.getNetworkInfo(i, ssid_scan, sec_scan, rssi_scan, BSSID_scan, chan_scan, hidden_scan);
bool known = false;
for(uint32_t x = 0; x < APlist.size(); x++) {
WifiAPlist_t entry = APlist[x];
if(ssid_scan == entry.ssid) { // SSID match
known = true;
if(rssi_scan > bestNetworkDb) { // best network
if(sec_scan == ENC_TYPE_NONE || entry.passphrase) { // check for passphrase if not open wlan
bestNetworkDb = rssi_scan;
bestChannel = chan_scan;
memcpy((void*) &bestNetwork, (void*) &entry, sizeof(bestNetwork));
memcpy((void*) &bestBSSID, (void*) BSSID_scan, sizeof(bestBSSID));
}
}
break;
}
}
if(known) {
DEBUG_WIFI_MULTI(" ---> ");
} else {
DEBUG_WIFI_MULTI(" ");
}
DEBUG_WIFI_MULTI(" %d: [%d][%02X:%02X:%02X:%02X:%02X:%02X] %s (%d) %c\n", i, chan_scan, BSSID_scan[0], BSSID_scan[1], BSSID_scan[2], BSSID_scan[3], BSSID_scan[4], BSSID_scan[5], ssid_scan.c_str(), rssi_scan, (sec_scan == ENC_TYPE_NONE) ? ' ' : '*');
delay(0);
}
}
// clean up ram
WiFi.scanDelete();
ledState(1);
DEBUG_WIFI_MULTI("\n\n");
delay(0);
if(bestNetwork.ssid) {
DEBUG_WIFI_MULTI("[WIFI] Connecting BSSID: %02X:%02X:%02X:%02X:%02X:%02X SSID: %s Channal: %d (%d)\n", bestBSSID[0], bestBSSID[1], bestBSSID[2], bestBSSID[3], bestBSSID[4], bestBSSID[5], bestNetwork.ssid, bestChannel, bestNetworkDb);
/*Serial.println("wifi.begin");
Serial.println(bestNetwork.ssid);
Serial.println(bestNetwork.passphrase);
Serial.println(bestChannel);
Serial.println("-------------");*/
WiFi.begin(bestNetwork.ssid, bestNetwork.passphrase, bestChannel, bestBSSID);
status = WiFi.status();
int s = 0;
// wait for connection or fail
while(status != WL_CONNECTED && status != WL_NO_SSID_AVAIL && status != WL_CONNECT_FAILED) {
delay(10);
s++;
status = WiFi.status();
if (s % 10 == 0) {
ledState(1);
if (s % 250 == 0)break;
}
if (status == WL_CONNECTED)break;
Nefry.push_sw_();
}
if(status==WL_CONNECTED)ledState(2);
#ifdef DEBUG_ESP_WIFI
IPAddress ip;
uint8_t * mac;
switch(status) {
case WL_CONNECTED:
ip = WiFi.localIP();
mac = WiFi.BSSID();
DEBUG_WIFI_MULTI("[WIFI] Connecting done.\n");
DEBUG_WIFI_MULTI("[WIFI] SSID: %s\n", WiFi.SSID().c_str());
DEBUG_WIFI_MULTI("[WIFI] IP: %d.%d.%d.%d\n", ip[0], ip[1], ip[2], ip[3]);
DEBUG_WIFI_MULTI("[WIFI] MAC: %02X:%02X:%02X:%02X:%02X:%02X\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
DEBUG_WIFI_MULTI("[WIFI] Channel: %d\n", WiFi.channel());
break;
case WL_NO_SSID_AVAIL:
DEBUG_WIFI_MULTI("[WIFI] Connecting Failed AP not found.\n");
break;
case WL_CONNECT_FAILED:
DEBUG_WIFI_MULTI("[WIFI] Connecting Failed.\n");
break;
default:
DEBUG_WIFI_MULTI("[WIFI] Connecting Failed (%d).\n", status);
break;
}
#endif
} else {
ledState(3);
DEBUG_WIFI_MULTI("[WIFI] no matching wifi found!\n");
}
} else {
ledState(3);
// start scan
DEBUG_WIFI_MULTI("[WIFI] delete old wifi config...\n");
WiFi.disconnect();
DEBUG_WIFI_MULTI("[WIFI] start scan\n");
// scan wifi async mode
WiFi.scanNetworks(true);
}
}
return status;
}
// ##################################################################################
bool ESP8266WiFiMulti::APlistAdd(const char* ssid, const char *passphrase) {
WifiAPlist_t newAP;
if(!ssid || *ssid == 0x00 || strlen(ssid) > 31) {
// fail SSID to long or missing!
DEBUG_WIFI_MULTI("[WIFI][APlistAdd] no ssid or ssid to long\n");
return false;
}
if(passphrase && strlen(passphrase) > 63) {
// fail passphrase to long!
DEBUG_WIFI_MULTI("[WIFI][APlistAdd] passphrase to long\n");
return false;
}
newAP.ssid = strdup(ssid);
if(!newAP.ssid) {
DEBUG_WIFI_MULTI("[WIFI][APlistAdd] fail newAP.ssid == 0\n");
return false;
}
if(passphrase && *passphrase != 0x00) {
newAP.passphrase = strdup(passphrase);
if(!newAP.passphrase) {
DEBUG_WIFI_MULTI("[WIFI][APlistAdd] fail newAP.passphrase == 0\n");
free(newAP.ssid);
return false;
}
}
APlist.push_back(newAP);
DEBUG_WIFI_MULTI("[WIFI][APlistAdd] add SSID: %s\n", newAP.ssid);
return true;
}
void ESP8266WiFiMulti::APlistClean(void) {
for(uint32_t i = 0; i < APlist.size(); i++) {
WifiAPlist_t entry = APlist[i];
if(entry.ssid) {
free(entry.ssid);
}
if(entry.passphrase) {
free(entry.passphrase);
}
}
APlist.clear();
}
void ESP8266WiFiMulti::ledState(int i)
{
int j = 0;
switch (i)
{
case 1://接続中
Nefry.setLed(0x00, 0x4f, 0x00);
delay(50);
Nefry.setLed(0x00, 0x00, 0x00);
break;
case 2://接続完了
Nefry.setLed(0x00, 0xff, 0xff);
break;
case 3://接続失敗
for (j = 0; j < 4; j++) {
Nefry.setLed(0xff, 0x00, 0x00);
delay(50);
Nefry.setLed(0x00, 0x00, 0x00);
delay(50);
}
break;
default:
break;
}
}
<|endoftext|> |
<commit_before>//
// Copyright 2013 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "particles.h"
#include <far/ptexIndices.h>
#include <far/patchMap.h>
#ifdef OPENSUBDIV_HAS_TBB
#include <tbb/parallel_for.h>
#include <tbb/atomic.h>
tbb::atomic<int> g_tbbCounter;
class TbbUpdateKernel {
public:
TbbUpdateKernel(float speed,
STParticles::Position *positions,
float *velocities,
std::vector<STParticles::FaceInfo> const &adjacency,
OpenSubdiv::Osd::PatchCoord *patchCoords,
OpenSubdiv::Far::PatchMap const *patchMap) :
_speed(speed), _positions(positions), _velocities(velocities),
_adjacency(adjacency), _patchCoords(patchCoords), _patchMap(patchMap) {
}
void operator () (tbb::blocked_range<int> const &r) const {
for (int i = r.begin(); i < r.end(); ++i) {
STParticles::Position * p = _positions + i;
float *dp = _velocities + i*2;
// apply velocity
p->s += dp[0] * _speed;
p->t += dp[1] * _speed;
// make sure particles can't skip more than 1 face boundary at a time
assert((p->s>-2.0f) and (p->s<2.0f) and (p->t>-2.0f) and (p->t<2.0f));
// check if the particle is jumping a boundary
// note: a particle can jump 2 edges at a time (a "diagonal" jump)
// this is not treated here.
int edge = -1;
if (p->s >= 1.0f) edge = 1;
if (p->s <= 0.0f) edge = 3;
if (p->t >= 1.0f) edge = 2;
if (p->t <= 0.0f) edge = 0;
if (edge>=0) {
// warp the particle to the other side of the boundary
STParticles::WarpParticle(_adjacency, edge, p, dp);
}
assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));
// resolve particle positions into patch handles
OpenSubdiv::Far::PatchTable::PatchHandle const *handle =
_patchMap->FindPatch(p->ptexIndex, p->s, p->t);
if (handle) {
int index = g_tbbCounter.fetch_and_add(1);
_patchCoords[index] =
OpenSubdiv::Osd::PatchCoord(*handle, p->s, p->t);
}
}
}
private:
float _speed;
STParticles::Position *_positions;
float *_velocities;
std::vector<STParticles::FaceInfo> const &_adjacency;
OpenSubdiv::Osd::PatchCoord *_patchCoords;
OpenSubdiv::Far::PatchMap const *_patchMap;
};
#endif
#include <cassert>
STParticles::STParticles(Refiner const & refiner,
PatchTable const *patchTable,
int nParticles, bool centered) :
_speed(1.0f) {
OpenSubdiv::Far::PtexIndices ptexIndices(refiner);
// Create a far patch map
_patchMap = new OpenSubdiv::Far::PatchMap(*patchTable);
int nPtexFaces = ptexIndices.GetNumFaces();
srand(static_cast<int>(2147483647));
{ // initialize positions
_positions.resize(nParticles);
Position * pos = &_positions[0];
for (int i = 0; i < nParticles; ++i) {
pos->ptexIndex = (int)(((float)rand()/(float)RAND_MAX) * nPtexFaces);
pos->s = centered ? 0.5f : (float)rand()/(float)RAND_MAX;
pos->t = centered ? 0.5f : (float)rand()/(float)RAND_MAX;
++pos;
}
}
{ // initialize velocities
_velocities.resize(nParticles * 2);
for (int i = 0; i < nParticles; ++i) {
// initialize normalized random directions
float s = 2.0f*(float)rand()/(float)RAND_MAX - 1.0f,
t = 2.0f*(float)rand()/(float)RAND_MAX - 1.0f,
l = sqrtf(s*s+t*t);
_velocities[2*i ] = s / l;
_velocities[2*i+1] = t / l;
}
}
{ // initialize topology adjacency
_adjacency.resize(nPtexFaces);
OpenSubdiv::Far::TopologyLevel const & refBaseLevel = refiner.GetLevel(0);
int nfaces = refBaseLevel.GetNumFaces(),
adjfaces[4],
adjedges[4];
for (int face=0, ptexface=0; face<nfaces; ++face) {
OpenSubdiv::Far::ConstIndexArray fverts = refBaseLevel.GetFaceVertices(face);
if (fverts.size()==4) {
ptexIndices.GetAdjacency(refiner, face, 0, adjfaces, adjedges);
_adjacency[ptexface] = FaceInfo(adjfaces, adjedges, false);
++ptexface;
} else {
for (int vert=0; vert<fverts.size(); ++vert) {
ptexIndices.GetAdjacency(refiner, face, vert, adjfaces, adjedges);
_adjacency[ptexface+vert] =
FaceInfo(adjfaces, adjedges, true);
}
ptexface+=fverts.size();
}
}
}
//std::cout << *this;
}
inline void
FlipS(STParticles::Position * p, float * dp) {
p->s = 1.0f-p->s;
dp[0] = - dp[0];
}
inline void
FlipT(STParticles::Position * p, float * dp) {
p->t = 1.0f-p->t;
dp[1] = - dp[1];
}
inline void
SwapST(STParticles::Position * p, float * dp) {
std::swap(p->s, p->t);
std::swap(dp[0], dp[1]);
}
inline void
Rotate(int rot, STParticles::Position * p, float * dp) {
switch (rot & 3) {
default: return;
case 1: FlipS(p, dp); SwapST(p, dp); break;
case 2: FlipS(p, dp); FlipT(p, dp); break;
case 3: FlipT(p, dp); SwapST(p, dp); break;
}
assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));
}
inline void
Trim(STParticles::Position * p) {
if (p->s <0.0f) p->s = 1.0f + p->s;
if (p->s>=1.0f) p->s = p->s - 1.0f;
if (p->t <0.0f) p->t = 1.0f + p->t;
if (p->t>=1.0f) p->t = p->t - 1.0f;
assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));
}
inline void
Clamp(STParticles::Position * p) {
if (p->s<0.0f) {
p->s=0.0f;
} else if (p->s>1.0f) {
p->s=1.0f;
}
if (p->t<0.0f) {
p->t=0.0f;
} else if (p->t>1.0f) {
p->t=1.0f;
}
}
inline void
Bounce(int edge, STParticles::Position * p, float * dp) {
switch (edge) {
case 0: assert(p->t<=0.0f); p->t = -p->t; dp[1] = -dp[1]; break;
case 1: assert(p->s>=1.0f); p->s = 2.0f - p->s; dp[0] = -dp[0]; break;
case 2: assert(p->t>=1.0f); p->t = 2.0f - p->t; dp[1] = -dp[1]; break;
case 3: assert(p->s<=0.0f); p->s = -p->s; dp[0] = -dp[0]; break;
}
// because 'diagonal' cases aren't handled, stick particles to edges when
// if they cross 2 boundaries
Clamp(p);
assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));
}
void
STParticles::WarpParticle(std::vector<FaceInfo> const &adjacency,
int edge, Position * p, float * dp) {
assert(p->ptexIndex<(int)adjacency.size() and (edge>=0 and edge<4));
FaceInfo const & f = adjacency[p->ptexIndex];
int afid = f.adjface(edge),
aeid = f.adjedge(edge);
if (afid==-1) {
// boundary detected: bounce the particle
Bounce(edge, p, dp);
} else {
FaceInfo const & af = adjacency[afid];
int rot = edge - aeid + 2;
bool fIsSubface = f.isSubface(),
afIsSubface = af.isSubface();
if (fIsSubface != afIsSubface) {
// XXXX manuelk domain should be split properly
Bounce(edge, p, dp);
} else {
Trim(p);
Rotate(rot, p, dp);
p->ptexIndex = afid; // move particle to adjacent face
}
}
assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));
}
STParticles::~STParticles() {
delete _patchMap;
}
void
STParticles::Update(float deltaTime) {
if (fabs(GetSpeed()) < 0.001f) return;
float speed = GetSpeed() * std::max(0.001f, std::min(deltaTime, 0.5f));
_patchCoords.clear();
// XXX: this process should be parallelized.
#ifdef OPENSUBDIV_HAS_TBB
_patchCoords.resize((int)GetNumParticles());
TbbUpdateKernel kernel(speed, &_positions[0], &_velocities[0],
_adjacency, &_patchCoords[0], _patchMap);;
g_tbbCounter = 0;
tbb::blocked_range<int> range(0, GetNumParticles(), 256);
tbb::parallel_for(range, kernel);
_patchCoords.resize(g_tbbCounter);
#else
Position * p = &_positions[0];
float * dp = &_velocities[0];
for (int i=0; i<GetNumParticles(); ++i, ++p, dp+=2) {
// apply velocity
p->s += dp[0] * speed;
p->t += dp[1] * speed;
// make sure particles can't skip more than 1 face boundary at a time
assert((p->s>-2.0f) and (p->s<2.0f) and (p->t>-2.0f) and (p->t<2.0f));
// check if the particle is jumping a boundary
// note: a particle can jump 2 edges at a time (a "diagonal" jump)
// this is not treated here.
int edge = -1;
if (p->s >= 1.0f) edge = 1;
if (p->s <= 0.0f) edge = 3;
if (p->t >= 1.0f) edge = 2;
if (p->t <= 0.0f) edge = 0;
if (edge>=0) {
// warp the particle to the other side of the boundary
WarpParticle(_adjacency, edge, p, dp);
}
assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));
// resolve particle positions into patch handles
OpenSubdiv::Far::PatchTable::PatchHandle const *handle =
_patchMap->FindPatch(p->ptexIndex, p->s, p->t);
if (handle) {
_patchCoords.push_back(
OpenSubdiv::Osd::PatchCoord(*handle, p->s, p->t));
}
}
#endif
}
// Dump adjacency info
std::ostream & operator << (std::ostream & os,
STParticles::FaceInfo const & f) {
os << " adjface: " << f.adjfaces[0] << ' '
<< f.adjfaces[1] << ' '
<< f.adjfaces[2] << ' '
<< f.adjfaces[3]
<< " adjedge: " << f.adjedge(0) << ' '
<< f.adjedge(1) << ' '
<< f.adjedge(2) << ' '
<< f.adjedge(3)
<< " flags:";
if (f.flags == 0) {
os << " (none)";
} else {
if (f.isSubface()) {
std::cout << " subface";
}
}
os << std::endl;
return os;
}
std::ostream & operator << (std::ostream & os,
STParticles const & particles) {
for (int i=0; i<(int)particles._adjacency.size(); ++i) {
os << particles._adjacency[i];
}
return os;
}
<commit_msg>glEvalLimit: Fix an assertion failure when rand() takes RAND_MAX<commit_after>//
// Copyright 2013 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "particles.h"
#include <far/ptexIndices.h>
#include <far/patchMap.h>
#ifdef OPENSUBDIV_HAS_TBB
#include <tbb/parallel_for.h>
#include <tbb/atomic.h>
tbb::atomic<int> g_tbbCounter;
class TbbUpdateKernel {
public:
TbbUpdateKernel(float speed,
STParticles::Position *positions,
float *velocities,
std::vector<STParticles::FaceInfo> const &adjacency,
OpenSubdiv::Osd::PatchCoord *patchCoords,
OpenSubdiv::Far::PatchMap const *patchMap) :
_speed(speed), _positions(positions), _velocities(velocities),
_adjacency(adjacency), _patchCoords(patchCoords), _patchMap(patchMap) {
}
void operator () (tbb::blocked_range<int> const &r) const {
for (int i = r.begin(); i < r.end(); ++i) {
STParticles::Position * p = _positions + i;
float *dp = _velocities + i*2;
// apply velocity
p->s += dp[0] * _speed;
p->t += dp[1] * _speed;
// make sure particles can't skip more than 1 face boundary at a time
assert((p->s>-2.0f) and (p->s<2.0f) and (p->t>-2.0f) and (p->t<2.0f));
// check if the particle is jumping a boundary
// note: a particle can jump 2 edges at a time (a "diagonal" jump)
// this is not treated here.
int edge = -1;
if (p->s >= 1.0f) edge = 1;
if (p->s <= 0.0f) edge = 3;
if (p->t >= 1.0f) edge = 2;
if (p->t <= 0.0f) edge = 0;
if (edge>=0) {
// warp the particle to the other side of the boundary
STParticles::WarpParticle(_adjacency, edge, p, dp);
}
assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));
// resolve particle positions into patch handles
OpenSubdiv::Far::PatchTable::PatchHandle const *handle =
_patchMap->FindPatch(p->ptexIndex, p->s, p->t);
if (handle) {
int index = g_tbbCounter.fetch_and_add(1);
_patchCoords[index] =
OpenSubdiv::Osd::PatchCoord(*handle, p->s, p->t);
}
}
}
private:
float _speed;
STParticles::Position *_positions;
float *_velocities;
std::vector<STParticles::FaceInfo> const &_adjacency;
OpenSubdiv::Osd::PatchCoord *_patchCoords;
OpenSubdiv::Far::PatchMap const *_patchMap;
};
#endif
#include <cassert>
STParticles::STParticles(Refiner const & refiner,
PatchTable const *patchTable,
int nParticles, bool centered) :
_speed(1.0f) {
OpenSubdiv::Far::PtexIndices ptexIndices(refiner);
// Create a far patch map
_patchMap = new OpenSubdiv::Far::PatchMap(*patchTable);
int nPtexFaces = ptexIndices.GetNumFaces();
srand(static_cast<int>(2147483647));
{ // initialize positions
_positions.resize(nParticles);
Position * pos = &_positions[0];
for (int i = 0; i < nParticles; ++i) {
pos->ptexIndex = std::min(
(int)(((float)rand()/(float)RAND_MAX) * nPtexFaces), nPtexFaces-1);
pos->s = centered ? 0.5f : (float)rand()/(float)RAND_MAX;
pos->t = centered ? 0.5f : (float)rand()/(float)RAND_MAX;
++pos;
}
}
{ // initialize velocities
_velocities.resize(nParticles * 2);
for (int i = 0; i < nParticles; ++i) {
// initialize normalized random directions
float s = 2.0f*(float)rand()/(float)RAND_MAX - 1.0f,
t = 2.0f*(float)rand()/(float)RAND_MAX - 1.0f,
l = sqrtf(s*s+t*t);
_velocities[2*i ] = s / l;
_velocities[2*i+1] = t / l;
}
}
{ // initialize topology adjacency
_adjacency.resize(nPtexFaces);
OpenSubdiv::Far::TopologyLevel const & refBaseLevel = refiner.GetLevel(0);
int nfaces = refBaseLevel.GetNumFaces(),
adjfaces[4],
adjedges[4];
for (int face=0, ptexface=0; face<nfaces; ++face) {
OpenSubdiv::Far::ConstIndexArray fverts = refBaseLevel.GetFaceVertices(face);
if (fverts.size()==4) {
ptexIndices.GetAdjacency(refiner, face, 0, adjfaces, adjedges);
_adjacency[ptexface] = FaceInfo(adjfaces, adjedges, false);
++ptexface;
} else {
for (int vert=0; vert<fverts.size(); ++vert) {
ptexIndices.GetAdjacency(refiner, face, vert, adjfaces, adjedges);
_adjacency[ptexface+vert] =
FaceInfo(adjfaces, adjedges, true);
}
ptexface+=fverts.size();
}
}
}
//std::cout << *this;
}
inline void
FlipS(STParticles::Position * p, float * dp) {
p->s = 1.0f-p->s;
dp[0] = - dp[0];
}
inline void
FlipT(STParticles::Position * p, float * dp) {
p->t = 1.0f-p->t;
dp[1] = - dp[1];
}
inline void
SwapST(STParticles::Position * p, float * dp) {
std::swap(p->s, p->t);
std::swap(dp[0], dp[1]);
}
inline void
Rotate(int rot, STParticles::Position * p, float * dp) {
switch (rot & 3) {
default: return;
case 1: FlipS(p, dp); SwapST(p, dp); break;
case 2: FlipS(p, dp); FlipT(p, dp); break;
case 3: FlipT(p, dp); SwapST(p, dp); break;
}
assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));
}
inline void
Trim(STParticles::Position * p) {
if (p->s <0.0f) p->s = 1.0f + p->s;
if (p->s>=1.0f) p->s = p->s - 1.0f;
if (p->t <0.0f) p->t = 1.0f + p->t;
if (p->t>=1.0f) p->t = p->t - 1.0f;
assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));
}
inline void
Clamp(STParticles::Position * p) {
if (p->s<0.0f) {
p->s=0.0f;
} else if (p->s>1.0f) {
p->s=1.0f;
}
if (p->t<0.0f) {
p->t=0.0f;
} else if (p->t>1.0f) {
p->t=1.0f;
}
}
inline void
Bounce(int edge, STParticles::Position * p, float * dp) {
switch (edge) {
case 0: assert(p->t<=0.0f); p->t = -p->t; dp[1] = -dp[1]; break;
case 1: assert(p->s>=1.0f); p->s = 2.0f - p->s; dp[0] = -dp[0]; break;
case 2: assert(p->t>=1.0f); p->t = 2.0f - p->t; dp[1] = -dp[1]; break;
case 3: assert(p->s<=0.0f); p->s = -p->s; dp[0] = -dp[0]; break;
}
// because 'diagonal' cases aren't handled, stick particles to edges when
// if they cross 2 boundaries
Clamp(p);
assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));
}
void
STParticles::WarpParticle(std::vector<FaceInfo> const &adjacency,
int edge, Position * p, float * dp) {
assert(p->ptexIndex<(int)adjacency.size() and (edge>=0 and edge<4));
FaceInfo const & f = adjacency[p->ptexIndex];
int afid = f.adjface(edge),
aeid = f.adjedge(edge);
if (afid==-1) {
// boundary detected: bounce the particle
Bounce(edge, p, dp);
} else {
FaceInfo const & af = adjacency[afid];
int rot = edge - aeid + 2;
bool fIsSubface = f.isSubface(),
afIsSubface = af.isSubface();
if (fIsSubface != afIsSubface) {
// XXXX manuelk domain should be split properly
Bounce(edge, p, dp);
} else {
Trim(p);
Rotate(rot, p, dp);
p->ptexIndex = afid; // move particle to adjacent face
}
}
assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));
}
STParticles::~STParticles() {
delete _patchMap;
}
void
STParticles::Update(float deltaTime) {
if (fabs(GetSpeed()) < 0.001f) return;
float speed = GetSpeed() * std::max(0.001f, std::min(deltaTime, 0.5f));
_patchCoords.clear();
// XXX: this process should be parallelized.
#ifdef OPENSUBDIV_HAS_TBB
_patchCoords.resize((int)GetNumParticles());
TbbUpdateKernel kernel(speed, &_positions[0], &_velocities[0],
_adjacency, &_patchCoords[0], _patchMap);;
g_tbbCounter = 0;
tbb::blocked_range<int> range(0, GetNumParticles(), 256);
tbb::parallel_for(range, kernel);
_patchCoords.resize(g_tbbCounter);
#else
Position * p = &_positions[0];
float * dp = &_velocities[0];
for (int i=0; i<GetNumParticles(); ++i, ++p, dp+=2) {
// apply velocity
p->s += dp[0] * speed;
p->t += dp[1] * speed;
// make sure particles can't skip more than 1 face boundary at a time
assert((p->s>-2.0f) and (p->s<2.0f) and (p->t>-2.0f) and (p->t<2.0f));
// check if the particle is jumping a boundary
// note: a particle can jump 2 edges at a time (a "diagonal" jump)
// this is not treated here.
int edge = -1;
if (p->s >= 1.0f) edge = 1;
if (p->s <= 0.0f) edge = 3;
if (p->t >= 1.0f) edge = 2;
if (p->t <= 0.0f) edge = 0;
if (edge>=0) {
// warp the particle to the other side of the boundary
WarpParticle(_adjacency, edge, p, dp);
}
assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));
// resolve particle positions into patch handles
OpenSubdiv::Far::PatchTable::PatchHandle const *handle =
_patchMap->FindPatch(p->ptexIndex, p->s, p->t);
if (handle) {
_patchCoords.push_back(
OpenSubdiv::Osd::PatchCoord(*handle, p->s, p->t));
}
}
#endif
}
// Dump adjacency info
std::ostream & operator << (std::ostream & os,
STParticles::FaceInfo const & f) {
os << " adjface: " << f.adjfaces[0] << ' '
<< f.adjfaces[1] << ' '
<< f.adjfaces[2] << ' '
<< f.adjfaces[3]
<< " adjedge: " << f.adjedge(0) << ' '
<< f.adjedge(1) << ' '
<< f.adjedge(2) << ' '
<< f.adjedge(3)
<< " flags:";
if (f.flags == 0) {
os << " (none)";
} else {
if (f.isSubface()) {
std::cout << " subface";
}
}
os << std::endl;
return os;
}
std::ostream & operator << (std::ostream & os,
STParticles const & particles) {
for (int i=0; i<(int)particles._adjacency.size(); ++i) {
os << particles._adjacency[i];
}
return os;
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9n_mcs_scom.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2017,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#include "p9n_mcs_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>
using namespace fapi2;
constexpr uint64_t literal_0b0111 = 0b0111;
constexpr uint64_t literal_0 = 0;
constexpr uint64_t literal_1 = 1;
constexpr uint64_t literal_8 = 8;
constexpr uint64_t literal_25 = 25;
constexpr uint64_t literal_0b001111 = 0b001111;
constexpr uint64_t literal_0b0001100000000 = 0b0001100000000;
constexpr uint64_t literal_1350 = 1350;
constexpr uint64_t literal_1000 = 1000;
constexpr uint64_t literal_0b0000000000001000 = 0b0000000000001000;
fapi2::ReturnCode p9n_mcs_scom(const fapi2::Target<fapi2::TARGET_TYPE_MCS>& TGT0,
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1, const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT2,
const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& TGT3)
{
{
fapi2::ATTR_EC_Type l_chip_ec;
fapi2::ATTR_NAME_Type l_chip_id;
FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT2, l_chip_id));
FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT2, l_chip_ec));
fapi2::ATTR_CHIP_EC_FEATURE_HW398139_Type l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_HW398139, TGT2, l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139));
fapi2::ATTR_RISK_LEVEL_Type l_TGT1_ATTR_RISK_LEVEL;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_RISK_LEVEL, TGT1, l_TGT1_ATTR_RISK_LEVEL));
fapi2::ATTR_FREQ_PB_MHZ_Type l_TGT1_ATTR_FREQ_PB_MHZ;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_PB_MHZ, TGT1, l_TGT1_ATTR_FREQ_PB_MHZ));
fapi2::ATTR_MSS_FREQ_Type l_TGT3_ATTR_MSS_FREQ;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_MSS_FREQ, TGT3, l_TGT3_ATTR_MSS_FREQ));
uint64_t l_def_mn_freq_ratio = ((literal_1000 * l_TGT3_ATTR_MSS_FREQ) / l_TGT1_ATTR_FREQ_PB_MHZ);
fapi2::buffer<uint64_t> l_scom_buffer;
{
FAPI_TRY(fapi2::getScom( TGT0, 0x5010810ull, l_scom_buffer ));
l_scom_buffer.insert<46, 4, 60, uint64_t>(literal_0b0111 );
l_scom_buffer.insert<62, 1, 63, uint64_t>(literal_0 );
constexpr auto l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON = 0x1;
l_scom_buffer.insert<61, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON );
if ((l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139 == literal_1))
{
l_scom_buffer.insert<32, 7, 57, uint64_t>(literal_8 );
}
else if ((l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139 != literal_1))
{
l_scom_buffer.insert<32, 7, 57, uint64_t>(literal_25 );
}
if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
{
l_scom_buffer.insert<55, 6, 58, uint64_t>(literal_0b001111 );
}
if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
{
constexpr auto l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PREFETCH_PROMOTE_ON = 0x1;
l_scom_buffer.insert<63, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PREFETCH_PROMOTE_ON );
}
FAPI_TRY(fapi2::putScom(TGT0, 0x5010810ull, l_scom_buffer));
}
{
if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
{
FAPI_TRY(fapi2::getScom( TGT0, 0x5010811ull, l_scom_buffer ));
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_SYNC_ON = 0x1;
l_scom_buffer.insert<20, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_SYNC_ON );
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON = 0x1;
l_scom_buffer.insert<9, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON );
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_DROP_FP_DYN64_ACTIVE_ON = 0x1;
l_scom_buffer.insert<8, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_DROP_FP_DYN64_ACTIVE_ON );
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_OFF = 0x0;
l_scom_buffer.insert<7, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_OFF );
FAPI_TRY(fapi2::putScom(TGT0, 0x5010811ull, l_scom_buffer));
}
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x5010812ull, l_scom_buffer ));
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE1_DISABLE_FP_M_BIT_ON = 0x1;
l_scom_buffer.insert<10, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE1_DISABLE_FP_M_BIT_ON );
FAPI_TRY(fapi2::putScom(TGT0, 0x5010812ull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x5010813ull, l_scom_buffer ));
if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
{
if ((l_TGT1_ATTR_RISK_LEVEL == literal_0))
{
l_scom_buffer.insert<1, 13, 51, uint64_t>(literal_0b0001100000000 );
}
}
if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
{
if ((l_def_mn_freq_ratio <= literal_1350))
{
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_OFF = 0x0;
l_scom_buffer.insert<0, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_OFF );
}
else if ((l_def_mn_freq_ratio > literal_1350))
{
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_ON = 0x1;
l_scom_buffer.insert<0, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_ON );
}
}
if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
{
l_scom_buffer.insert<24, 16, 48, uint64_t>(literal_0b0000000000001000 );
}
FAPI_TRY(fapi2::putScom(TGT0, 0x5010813ull, l_scom_buffer));
}
};
fapi_try_exit:
return fapi2::current_err;
}
<commit_msg>dis spec ops dcbf HW414958<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9n_mcs_scom.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2017,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#include "p9n_mcs_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>
using namespace fapi2;
constexpr uint64_t literal_0b0111 = 0b0111;
constexpr uint64_t literal_0 = 0;
constexpr uint64_t literal_1 = 1;
constexpr uint64_t literal_8 = 8;
constexpr uint64_t literal_25 = 25;
constexpr uint64_t literal_0b001111 = 0b001111;
constexpr uint64_t literal_0b0000000000001000000 = 0b0000000000001000000;
constexpr uint64_t literal_0b0001100000000 = 0b0001100000000;
constexpr uint64_t literal_1350 = 1350;
constexpr uint64_t literal_1000 = 1000;
constexpr uint64_t literal_0b0000000000001000 = 0b0000000000001000;
fapi2::ReturnCode p9n_mcs_scom(const fapi2::Target<fapi2::TARGET_TYPE_MCS>& TGT0,
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1, const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT2,
const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& TGT3)
{
{
fapi2::ATTR_EC_Type l_chip_ec;
fapi2::ATTR_NAME_Type l_chip_id;
FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT2, l_chip_id));
FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT2, l_chip_ec));
fapi2::ATTR_CHIP_EC_FEATURE_HW398139_Type l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_HW398139, TGT2, l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139));
fapi2::ATTR_RISK_LEVEL_Type l_TGT1_ATTR_RISK_LEVEL;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_RISK_LEVEL, TGT1, l_TGT1_ATTR_RISK_LEVEL));
fapi2::ATTR_FREQ_PB_MHZ_Type l_TGT1_ATTR_FREQ_PB_MHZ;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_PB_MHZ, TGT1, l_TGT1_ATTR_FREQ_PB_MHZ));
fapi2::ATTR_MSS_FREQ_Type l_TGT3_ATTR_MSS_FREQ;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_MSS_FREQ, TGT3, l_TGT3_ATTR_MSS_FREQ));
uint64_t l_def_mn_freq_ratio = ((literal_1000 * l_TGT3_ATTR_MSS_FREQ) / l_TGT1_ATTR_FREQ_PB_MHZ);
fapi2::buffer<uint64_t> l_scom_buffer;
{
FAPI_TRY(fapi2::getScom( TGT0, 0x5010810ull, l_scom_buffer ));
l_scom_buffer.insert<46, 4, 60, uint64_t>(literal_0b0111 );
l_scom_buffer.insert<62, 1, 63, uint64_t>(literal_0 );
constexpr auto l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON = 0x1;
l_scom_buffer.insert<61, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON );
if ((l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139 == literal_1))
{
l_scom_buffer.insert<32, 7, 57, uint64_t>(literal_8 );
}
else if ((l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139 != literal_1))
{
l_scom_buffer.insert<32, 7, 57, uint64_t>(literal_25 );
}
if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
{
l_scom_buffer.insert<55, 6, 58, uint64_t>(literal_0b001111 );
}
if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
{
constexpr auto l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PREFETCH_PROMOTE_ON = 0x1;
l_scom_buffer.insert<63, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PREFETCH_PROMOTE_ON );
}
FAPI_TRY(fapi2::putScom(TGT0, 0x5010810ull, l_scom_buffer));
}
{
if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
{
FAPI_TRY(fapi2::getScom( TGT0, 0x5010811ull, l_scom_buffer ));
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_SYNC_ON = 0x1;
l_scom_buffer.insert<20, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_SYNC_ON );
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON = 0x1;
l_scom_buffer.insert<9, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON );
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_DROP_FP_DYN64_ACTIVE_ON = 0x1;
l_scom_buffer.insert<8, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_DROP_FP_DYN64_ACTIVE_ON );
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_OFF = 0x0;
l_scom_buffer.insert<7, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_OFF );
FAPI_TRY(fapi2::putScom(TGT0, 0x5010811ull, l_scom_buffer));
}
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x5010812ull, l_scom_buffer ));
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE1_DISABLE_FP_M_BIT_ON = 0x1;
l_scom_buffer.insert<10, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE1_DISABLE_FP_M_BIT_ON );
l_scom_buffer.insert<33, 19, 45, uint64_t>(literal_0b0000000000001000000 );
FAPI_TRY(fapi2::putScom(TGT0, 0x5010812ull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x5010813ull, l_scom_buffer ));
if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
{
if ((l_TGT1_ATTR_RISK_LEVEL == literal_0))
{
l_scom_buffer.insert<1, 13, 51, uint64_t>(literal_0b0001100000000 );
}
}
if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
{
if ((l_def_mn_freq_ratio <= literal_1350))
{
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_OFF = 0x0;
l_scom_buffer.insert<0, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_OFF );
}
else if ((l_def_mn_freq_ratio > literal_1350))
{
constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_ON = 0x1;
l_scom_buffer.insert<0, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_ON );
}
}
if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
{
l_scom_buffer.insert<24, 16, 48, uint64_t>(literal_0b0000000000001000 );
}
FAPI_TRY(fapi2::putScom(TGT0, 0x5010813ull, l_scom_buffer));
}
};
fapi_try_exit:
return fapi2::current_err;
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2012 QtHttpServer Project.
* 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 QtHttpServer 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 QTHTTPSERVER 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 "qhttpreply.h"
#include <QtNetwork/QNetworkCookie>
#include "qhttpconnection_p.h"
#include "qhttprequest.h"
#include <zlib.h>
class QHttpReply::Private : public QObject
{
Q_OBJECT
public:
Private(QHttpConnection *c, QHttpReply *parent);
public slots:
void close();
private:
QHttpReply *q;
static QHash<int, QByteArray> statusCodes;
public:
QHttpConnection *connection;
int status;
QHash<QByteArray, QByteArray> rawHeaders;
QList<QNetworkCookie> cookies;
QByteArray data;
};
QHash<int, QByteArray> QHttpReply::Private::statusCodes;
QHttpReply::Private::Private(QHttpConnection *c, QHttpReply *parent)
: QObject(parent)
, q(parent)
, connection(c)
, status(200)
{
if (statusCodes.isEmpty()) {
statusCodes.insert(100, "Continue");
statusCodes.insert(101, "Switching Protocols");
statusCodes.insert(200, "OK");
statusCodes.insert(201, "Created");
statusCodes.insert(202, "Accepted");
statusCodes.insert(203, "Non-Authoritative Information");
statusCodes.insert(204, "No Content");
statusCodes.insert(205, "Reset Content");
statusCodes.insert(206, "Partial Content");
statusCodes.insert(300, "Multiple Choices");
statusCodes.insert(301, "Moved Permanently");
statusCodes.insert(302, "Found");
statusCodes.insert(303, "See Other");
statusCodes.insert(304, "Not Modified");
statusCodes.insert(305, "Use Proxy");
statusCodes.insert(307, "Temporary Redirect");
statusCodes.insert(400, "Bad Request");
statusCodes.insert(401, "Unauthorized");
statusCodes.insert(402, "Payment Required");
statusCodes.insert(403, "Forbidden");
statusCodes.insert(404, "Not Found");
statusCodes.insert(405, "Method Not Allowed");
statusCodes.insert(406, "Not Acceptable");
statusCodes.insert(407, "Proxy Authentication Required");
statusCodes.insert(408, "Request Time-out");
statusCodes.insert(409, "Conflict");
statusCodes.insert(410, "Gone");
statusCodes.insert(411, "Length Required");
statusCodes.insert(412, "Precondition Failed");
statusCodes.insert(413, "Request Entity Too Large");
statusCodes.insert(414, "Request-URI Too Large");
statusCodes.insert(415, "Unsupported Media Type");
statusCodes.insert(416, "Requested range not satisfiable");
statusCodes.insert(417, "Expectation Failed");
statusCodes.insert(500, "Internal Server Error");
statusCodes.insert(501, "Not Implemented");
statusCodes.insert(502, "Bad Gateway");
statusCodes.insert(503, "Service Unavailable");
statusCodes.insert(504, "Gateway Time-out");
statusCodes.insert(505, "HTTP Version not supported");
}
q->setBuffer(&data);
q->open(QIODevice::WriteOnly);
}
void QHttpReply::Private::close()
{
connection->write("HTTP/1.1 ");
connection->write(QByteArray::number(status));
connection->write(" ");
connection->write(statusCodes.value(status));
connection->write("\r\n");
const QHttpRequest *request = connection->requestFor(q);
if (request && request->hasRawHeader("Accept-Encoding") && !rawHeaders.contains("Content-Encoding")) {
QList<QByteArray> acceptEncodings = request->rawHeader("Accept-Encoding").split(',');
if (acceptEncodings.contains("deflate")) {
z_stream z;
z.zalloc = NULL;
z.zfree = NULL;
z.opaque = NULL;
if (deflateInit(&z, Z_DEFAULT_COMPRESSION) == Z_OK) {
QByteArray newData;
unsigned char buf[1024];
z.avail_in = data.size();
z.next_in = reinterpret_cast<Bytef*>(data.data());
z.avail_out = 1024;
z.next_out = buf;
int ret = Z_OK;
while (ret == Z_OK) {
// qDebug() << Q_FUNC_INFO << __LINE__ << z.avail_in << z.avail_out;
ret = deflate(&z, Z_FINISH);
// qDebug() << Q_FUNC_INFO << __LINE__ << z.avail_in << z.avail_out << ret;
if (ret == Z_STREAM_END) {
newData.append((const char*)buf, 1024 - z.avail_out);
data = newData;
rawHeaders["Content-Encoding"] = "deflate";
rawHeaders["Content-Length"] = QString::number(data.length()).toUtf8();
// qDebug() << "END";
break;
} else if (ret != Z_OK) {
// qDebug() << Q_FUNC_INFO << __LINE__ << ret << z.msg;
}
if (z.avail_out == 0) {
newData.append((const char*)buf, 1024);
z.avail_out = 1024;
z.next_out = buf;
}
}
// qDebug() << Q_FUNC_INFO << __LINE__ << newData.length();
}
}
}
if (!rawHeaders.contains("Content-Length")) {
rawHeaders.insert("Content-Length", QString::number(data.length()).toUtf8());
}
foreach (const QByteArray &rawHeader, rawHeaders.keys()) {
connection->write(rawHeader);
connection->write(": ");
connection->write(rawHeaders.value(rawHeader));
connection->write("\r\n");
}
foreach (const QNetworkCookie &cookie, cookies) {
connection->write("Set-Cookie: ");
connection->write(cookie.toRawForm());
connection->write(";\r\n");
}
connection->write("\r\n");
connection->write(data);
q->deleteLater();
}
QHttpReply::QHttpReply(QHttpConnection *parent)
: QBuffer(parent)
, d(new Private(parent, this))
{
}
QHttpReply::~QHttpReply()
{
delete d;
}
int QHttpReply::status() const
{
return d->status;
}
void QHttpReply::setStatus(int status)
{
d->status = status;
}
bool QHttpReply::hasRawHeader(const QByteArray &headerName) const
{
return d->rawHeaders.contains(headerName);
}
//QVariant QHttpReply::header(KnownHeaders header) const
//{
// return QVariant();
//}
QByteArray QHttpReply::rawHeader(const QByteArray &headerName) const
{
return d->rawHeaders.value(headerName);
}
void QHttpReply::setRawHeader(const QByteArray &headerName, const QByteArray &value)
{
d->rawHeaders.insert(headerName, value);
}
QList<QByteArray> QHttpReply::rawHeaderList() const
{
return d->rawHeaders.keys();
}
const QList<QNetworkCookie> &QHttpReply::cookies() const
{
return d->cookies;
}
void QHttpReply::setCookies(const QList<QNetworkCookie> &cookies)
{
if (d->cookies == cookies) return;
d->cookies = cookies;
}
void QHttpReply::close()
{
QBuffer::close();
// QMetaObject::invokeMethod(d, "close", Qt::QueuedConnection);
d->close();
}
#include "qhttpreply.moc"
<commit_msg>fix a big memory leak<commit_after>/* Copyright (c) 2012 QtHttpServer Project.
* 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 QtHttpServer 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 QTHTTPSERVER 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 "qhttpreply.h"
#include <QtNetwork/QNetworkCookie>
#include "qhttpconnection_p.h"
#include "qhttprequest.h"
#include <zlib.h>
class QHttpReply::Private : public QObject
{
Q_OBJECT
public:
Private(QHttpConnection *c, QHttpReply *parent);
public slots:
void close();
private:
QHttpReply *q;
static QHash<int, QByteArray> statusCodes;
public:
QHttpConnection *connection;
int status;
QHash<QByteArray, QByteArray> rawHeaders;
QList<QNetworkCookie> cookies;
QByteArray data;
};
QHash<int, QByteArray> QHttpReply::Private::statusCodes;
QHttpReply::Private::Private(QHttpConnection *c, QHttpReply *parent)
: QObject(parent)
, q(parent)
, connection(c)
, status(200)
{
if (statusCodes.isEmpty()) {
statusCodes.insert(100, "Continue");
statusCodes.insert(101, "Switching Protocols");
statusCodes.insert(200, "OK");
statusCodes.insert(201, "Created");
statusCodes.insert(202, "Accepted");
statusCodes.insert(203, "Non-Authoritative Information");
statusCodes.insert(204, "No Content");
statusCodes.insert(205, "Reset Content");
statusCodes.insert(206, "Partial Content");
statusCodes.insert(300, "Multiple Choices");
statusCodes.insert(301, "Moved Permanently");
statusCodes.insert(302, "Found");
statusCodes.insert(303, "See Other");
statusCodes.insert(304, "Not Modified");
statusCodes.insert(305, "Use Proxy");
statusCodes.insert(307, "Temporary Redirect");
statusCodes.insert(400, "Bad Request");
statusCodes.insert(401, "Unauthorized");
statusCodes.insert(402, "Payment Required");
statusCodes.insert(403, "Forbidden");
statusCodes.insert(404, "Not Found");
statusCodes.insert(405, "Method Not Allowed");
statusCodes.insert(406, "Not Acceptable");
statusCodes.insert(407, "Proxy Authentication Required");
statusCodes.insert(408, "Request Time-out");
statusCodes.insert(409, "Conflict");
statusCodes.insert(410, "Gone");
statusCodes.insert(411, "Length Required");
statusCodes.insert(412, "Precondition Failed");
statusCodes.insert(413, "Request Entity Too Large");
statusCodes.insert(414, "Request-URI Too Large");
statusCodes.insert(415, "Unsupported Media Type");
statusCodes.insert(416, "Requested range not satisfiable");
statusCodes.insert(417, "Expectation Failed");
statusCodes.insert(500, "Internal Server Error");
statusCodes.insert(501, "Not Implemented");
statusCodes.insert(502, "Bad Gateway");
statusCodes.insert(503, "Service Unavailable");
statusCodes.insert(504, "Gateway Time-out");
statusCodes.insert(505, "HTTP Version not supported");
}
q->setBuffer(&data);
q->open(QIODevice::WriteOnly);
}
void QHttpReply::Private::close()
{
connection->write("HTTP/1.1 ");
connection->write(QByteArray::number(status));
connection->write(" ");
connection->write(statusCodes.value(status));
connection->write("\r\n");
const QHttpRequest *request = connection->requestFor(q);
if (request && request->hasRawHeader("Accept-Encoding") && !rawHeaders.contains("Content-Encoding")) {
QList<QByteArray> acceptEncodings = request->rawHeader("Accept-Encoding").split(',');
if (acceptEncodings.contains("deflate")) {
z_stream z;
z.zalloc = NULL;
z.zfree = NULL;
z.opaque = NULL;
if (deflateInit(&z, Z_DEFAULT_COMPRESSION) == Z_OK) {
QByteArray newData;
unsigned char buf[1024];
z.avail_in = data.size();
z.next_in = reinterpret_cast<Bytef*>(data.data());
z.avail_out = 1024;
z.next_out = buf;
int ret = Z_OK;
while (ret == Z_OK) {
// qDebug() << Q_FUNC_INFO << __LINE__ << z.avail_in << z.avail_out;
ret = deflate(&z, Z_FINISH);
// qDebug() << Q_FUNC_INFO << __LINE__ << z.avail_in << z.avail_out << ret;
if (ret == Z_STREAM_END) {
newData.append((const char*)buf, 1024 - z.avail_out);
data = newData;
rawHeaders["Content-Encoding"] = "deflate";
rawHeaders["Content-Length"] = QString::number(data.length()).toUtf8();
// qDebug() << "END";
break;
} else if (ret != Z_OK) {
// qDebug() << Q_FUNC_INFO << __LINE__ << ret << z.msg;
}
if (z.avail_out == 0) {
newData.append((const char*)buf, 1024);
z.avail_out = 1024;
z.next_out = buf;
}
}
deflateEnd(&z);
// qDebug() << Q_FUNC_INFO << __LINE__ << newData.length();
}
}
}
if (!rawHeaders.contains("Content-Length")) {
rawHeaders.insert("Content-Length", QString::number(data.length()).toUtf8());
}
foreach (const QByteArray &rawHeader, rawHeaders.keys()) {
connection->write(rawHeader);
connection->write(": ");
connection->write(rawHeaders.value(rawHeader));
connection->write("\r\n");
}
foreach (const QNetworkCookie &cookie, cookies) {
connection->write("Set-Cookie: ");
connection->write(cookie.toRawForm());
connection->write(";\r\n");
}
connection->write("\r\n");
connection->write(data);
q->deleteLater();
}
QHttpReply::QHttpReply(QHttpConnection *parent)
: QBuffer(parent)
, d(new Private(parent, this))
{
}
QHttpReply::~QHttpReply()
{
delete d;
}
int QHttpReply::status() const
{
return d->status;
}
void QHttpReply::setStatus(int status)
{
d->status = status;
}
bool QHttpReply::hasRawHeader(const QByteArray &headerName) const
{
return d->rawHeaders.contains(headerName);
}
//QVariant QHttpReply::header(KnownHeaders header) const
//{
// return QVariant();
//}
QByteArray QHttpReply::rawHeader(const QByteArray &headerName) const
{
return d->rawHeaders.value(headerName);
}
void QHttpReply::setRawHeader(const QByteArray &headerName, const QByteArray &value)
{
d->rawHeaders.insert(headerName, value);
}
QList<QByteArray> QHttpReply::rawHeaderList() const
{
return d->rawHeaders.keys();
}
const QList<QNetworkCookie> &QHttpReply::cookies() const
{
return d->cookies;
}
void QHttpReply::setCookies(const QList<QNetworkCookie> &cookies)
{
if (d->cookies == cookies) return;
d->cookies = cookies;
}
void QHttpReply::close()
{
QBuffer::close();
// QMetaObject::invokeMethod(d, "close", Qt::QueuedConnection);
d->close();
}
#include "qhttpreply.moc"
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include <sstream>
#include <engine/gfx/Shader.hpp>
using namespace std;
namespace
{
boost::expected<std::string, std::string>
load_shader_from_cstring_path(char const* path)
{
// Read the Vertex Shader code from the file
std::ifstream istream(path, std::ios::in);
std::stringstream sstream;
if (! istream.is_open()) {
return boost::make_unexpected("Error opening file at path '" + std::string{path} + "'");
}
std::string next_line = "";
while(std::getline(istream, next_line)) {
sstream << "\n" << next_line;
}
// explicit, dtor should do this.
istream.close();
return sstream.str();
}
} // ns anonymous
namespace engine
{
namespace gfx
{
boost::expected<GLuint, std::string>
compile_shader(char const* data, GLenum const type)
{
GLuint const handle = glCreateShader(type);
// TODO: move this into std::utils, something like std::vec::with_size() (also with_capacity())
auto vec_with_size = [](auto const size) {
std::vector<char> buffer;
buffer.resize(size);
return buffer;
};
// Compile Vertex Shader
glShaderSource(handle, 1, &data, nullptr);
glCompileShader(handle);
// Check Vertex Shader
GLint is_compiled = GL_FALSE;
glGetShaderiv(handle, GL_COMPILE_STATUS, &is_compiled);
if (is_compiled) {
return handle;
}
GLint InfoLogLength = 0;
glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &InfoLogLength);
if (0 > InfoLogLength) {
auto constexpr err = "Compiling shader failed and could not retrieve OpenGL Log info for object";
return boost::make_unexpected(err);
}
auto const buffer_size = InfoLogLength + 1; // +1 for null terminator character '\0'
auto buffer = vec_with_size(buffer_size);
glGetShaderInfoLog(handle, buffer_size, nullptr, buffer.data());
return boost::make_unexpected( std::string{buffer.cbegin(), buffer.cend()} );
}
template<typename T>
boost::expected<GLuint, std::string>
compile_shader(T const& data, GLenum const type)
{ return compile_shader(data.c_str(), type); }
boost::expected<GLuint, std::string>
LoadShaders(char const* vertex_file_path, char const* fragment_file_path)
{
// Create the shaders
#define ONLY_OK(VAR_DECL, V, expr) \
auto V = expr; \
if (! V) { return boost::make_unexpected(V.error()); } \
VAR_DECL = *V;
#define ONLY_OK_HELPER(VAR_DECL, V, expr) \
ONLY_OK(VAR_DECL, expected_##V, expr)
#define ONLY_IFOK_HELPER(VAR_DECL, to_concat, expr) \
ONLY_OK_HELPER(VAR_DECL, to_concat, expr)
#define DO_MONAD(VAR_DECL, expr) ONLY_IFOK_HELPER(VAR_DECL, __COUNTER__, expr)
// Read the Vertex Shader code from the file
DO_MONAD(auto vertex_shader_source, load_shader_from_cstring_path(vertex_file_path));
// Read the Fragment Shader code from the file
DO_MONAD(auto fragment_shader_source, load_shader_from_cstring_path(fragment_file_path));
DO_MONAD(GLuint const VertexShaderID, compile_shader(vertex_shader_source, GL_VERTEX_SHADER));
DO_MONAD(GLuint const FragmentShaderID, compile_shader(fragment_shader_source, GL_FRAGMENT_SHADER));
// Link the program
printf("Linking program\n");
GLuint const ProgramID = glCreateProgram();
if (0 == ProgramID) {
return boost::make_unexpected("GlCreateProgram returned 0.");
}
glAttachShader(ProgramID, VertexShaderID);
glAttachShader(ProgramID, FragmentShaderID);
glLinkProgram(ProgramID);
// Check the program
GLint Result;
glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result);
if (Result == GL_FALSE) {
printf("%s\n", "Linking the shader failed.");
}
GLint InfoLogLength;
glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength);
if ( InfoLogLength > 1 ) {
std::vector<char> ProgramErrorMessage(InfoLogLength+1);
glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]);
printf("there was an error.");
printf("%s\n", &ProgramErrorMessage[0]);
}
glDetachShader(ProgramID, VertexShaderID);
glDetachShader(ProgramID, FragmentShaderID);
glDeleteShader(VertexShaderID);
glDeleteShader(FragmentShaderID);
return ProgramID;
}
} // ns gfx
} // ns engine
<commit_msg>Some refactoring<commit_after>#include <stdio.h>
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include <sstream>
#include <engine/gfx/Shader.hpp>
namespace
{
// TODO: move to util function
boost::expected<std::string, std::string>
read_file(char const* path)
{
// Read the Vertex Shader code from the file
std::ifstream istream(path, std::ios::in);
std::stringstream sstream;
if (! istream.is_open()) {
return boost::make_unexpected("Error opening file at path '" + std::string{path} + "'");
}
std::string next_line = "";
while(std::getline(istream, next_line)) {
sstream << "\n" << next_line;
}
// explicit, dtor should do this.
istream.close();
return sstream.str();
}
inline bool
is_compiled(GLuint const handle)
{
GLint is_compiled = GL_FALSE;
glGetShaderiv(handle, GL_COMPILE_STATUS, &is_compiled);
return GL_FALSE != is_compiled;
}
inline void
gl_compile_shader(GLuint const handle, char const* source)
{
GLint *p_length = nullptr;
auto constexpr shader_count = 1; // We're only compiling one shader (in this function anyway).
glShaderSource(handle, 1, &source, p_length);
glCompileShader(handle);
}
} // ns anonymous
namespace engine
{
namespace gfx
{
// TODO: export as reusable fn
// also, make an abstraction over the source, not just vector<char>
inline std::string
retrieve_shader_log(GLuint const handle)
{
// We have to do a low-level dance to get the OpenGL shader logs.
//
// 1. Ask OpenGL how buffer space we need to retrieve the buffer.
// 2. Retrieve the data into our buffer.
// 3. Return the buffer.
// TODO: move this into std::utils, something like std::vec::with_size() (also with_capacity())
auto vec_with_size = [](auto const size) {
std::vector<char> buffer;
buffer.resize(size);
return buffer;
};
// Step 1
GLint log_length = 0;
glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &log_length);
if (0 > log_length) {
// fix this msg
return "Compiling shader failed and could not retrieve OpenGL Log info for object";
}
// Step 2
auto const buffer_size = log_length + 1; // +1 for null terminator character '\0'
auto buffer = vec_with_size(buffer_size);
glGetShaderInfoLog(handle, buffer_size, nullptr, buffer.data());
// Step 3
return std::string{buffer.cbegin(), buffer.cend()};
}
boost::expected<GLuint, std::string>
compile_shader(char const* data, GLenum const type)
{
GLuint const handle = glCreateShader(type);
gl_compile_shader(handle, data);
// Check Vertex Shader
if (true == is_compiled(handle)) {
return handle;
}
return boost::make_unexpected(retrieve_shader_log(handle));
}
template<typename T>
boost::expected<GLuint, std::string>
compile_shader(T const& data, GLenum const type)
{ return compile_shader(data.c_str(), type); }
boost::expected<GLuint, std::string>
LoadShaders(char const* vertex_file_path, char const* fragment_file_path)
{
// Create the shaders
#define ONLY_OK(VAR_DECL, V, expr) \
auto V = expr; \
if (! V) { return boost::make_unexpected(V.error()); } \
VAR_DECL = *V;
#define ONLY_OK_HELPER(VAR_DECL, V, expr) \
ONLY_OK(VAR_DECL, expected_##V, expr)
#define ONLY_IFOK_HELPER(VAR_DECL, to_concat, expr) \
ONLY_OK_HELPER(VAR_DECL, to_concat, expr)
#define DO_MONAD(VAR_DECL, expr) ONLY_IFOK_HELPER(VAR_DECL, __COUNTER__, expr)
// Read the Vertex Shader code from the file
DO_MONAD(auto vertex_shader_source, read_file(vertex_file_path));
// Read the Fragment Shader code from the file
DO_MONAD(auto fragment_shader_source, read_file(fragment_file_path));
DO_MONAD(GLuint const VertexShaderID, compile_shader(vertex_shader_source, GL_VERTEX_SHADER));
DO_MONAD(GLuint const FragmentShaderID, compile_shader(fragment_shader_source, GL_FRAGMENT_SHADER));
// Link the program
printf("Linking program\n");
GLuint const ProgramID = glCreateProgram();
if (0 == ProgramID) {
return boost::make_unexpected("GlCreateProgram returned 0.");
}
glAttachShader(ProgramID, VertexShaderID);
glAttachShader(ProgramID, FragmentShaderID);
glLinkProgram(ProgramID);
// Check the program
GLint Result;
glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result);
if (Result == GL_FALSE) {
printf("%s\n", "Linking the shader failed.");
}
GLint InfoLogLength;
glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength);
if ( InfoLogLength > 1 ) {
std::vector<char> ProgramErrorMessage(InfoLogLength+1);
glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]);
printf("there was an error.");
printf("%s\n", &ProgramErrorMessage[0]);
}
glDetachShader(ProgramID, VertexShaderID);
glDetachShader(ProgramID, FragmentShaderID);
glDeleteShader(VertexShaderID);
glDeleteShader(FragmentShaderID);
return ProgramID;
}
} // ns gfx
} // ns engine
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: xmlithlp.hxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: dvo $ $Date: 2001-07-09 20:10:43 $
*
* 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 _SW_XMLITHLP_HXX
#define _SW_XMLITHLP_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _XMLOFF_XMLEMENT_HXX
#include <xmloff/xmlement.hxx>
#endif
class SvxBorderLine;
struct SvXMLEnumMapEntry;
class SvXMLUnitConverter;
class Color;
enum SvxGraphicPosition;
namespace rtl { class OUString; }
/** Define various helper variables and functions for xmlimpit.cxx and
* xmlexpit.cxx. */
#define SVX_XML_BORDER_STYLE_NONE 0
#define SVX_XML_BORDER_STYLE_SOLID 1
#define SVX_XML_BORDER_STYLE_DOUBLE 2
#define SVX_XML_BORDER_WIDTH_THIN 0
#define SVX_XML_BORDER_WIDTH_MIDDLE 1
#define SVX_XML_BORDER_WIDTH_THICK 2
sal_Bool lcl_frmitems_parseXMLBorder( const ::rtl::OUString& rValue,
const SvXMLUnitConverter& rUnitConverter,
sal_Bool& rHasStyle, sal_uInt16& rStyle,
sal_Bool& rHasWidth, sal_uInt16& rWidth,
sal_uInt16& rNamedWidth,
sal_Bool& rHasColor, Color& rColor );
void lcl_frmitems_setXMLBorderWidth( SvxBorderLine& rLine,
sal_uInt16 nOutWidth, sal_uInt16 nInWidth,
sal_uInt16 nDistance );
void lcl_frmitems_setXMLBorderWidth( SvxBorderLine& rLine,
sal_uInt16 nWidth, sal_Bool bDouble );
sal_Bool lcl_frmitems_setXMLBorder( SvxBorderLine*& rpLine,
sal_Bool bHasStyle, sal_uInt16 nStyle,
sal_Bool bHasWidth, sal_uInt16 nWidth,
sal_uInt16 nNamedWidth,
sal_Bool bHasColor, const Color& rColor );
void lcl_frmitems_setXMLBorder( SvxBorderLine*& rpLine,
sal_uInt16 nWidth, sal_uInt16 nOutWidth,
sal_uInt16 nInWidth, sal_uInt16 nDistance );
void lcl_frmitems_MergeXMLHoriPos( SvxGraphicPosition& ePos,
SvxGraphicPosition eHori );
void lcl_frmitems_MergeXMLVertPos( SvxGraphicPosition& ePos,
SvxGraphicPosition eVert );
extern const sal_uInt16 aSBorderWidths[];
extern const sal_uInt16 aDBorderWidths[5*11];
extern const struct SvXMLEnumMapEntry psXML_BorderStyles[];
extern const struct SvXMLEnumMapEntry psXML_NamedBorderWidths[];
extern const struct SvXMLEnumMapEntry psXML_BrushRepeat[];
extern const struct SvXMLEnumMapEntry psXML_BrushHoriPos[];
extern const struct SvXMLEnumMapEntry psXML_BrushVertPos[];
extern const struct SvXMLEnumMapEntry psXML_BreakType[];
extern const struct SvXMLEnumMapEntry aXMLTableAlignMap[];
extern const struct SvXMLEnumMapEntry aXMLTableVAlignMap[];
#endif
<commit_msg>fixed header to include definition of enum SvxGraphicsPosition<commit_after>/*************************************************************************
*
* $RCSfile: xmlithlp.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: dvo $ $Date: 2001-07-12 14:42:19 $
*
* 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 _SW_XMLITHLP_HXX
#define _SW_XMLITHLP_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _XMLOFF_XMLEMENT_HXX
#include <xmloff/xmlement.hxx>
#endif
#ifndef _HINTIDS_HXX
#include "hintids.hxx" // for following include
#endif
#ifndef _SVX_BRSHITEM_HXX
#include <svx/brshitem.hxx> // for SvxGraphicsPosition
#endif
class SvxBorderLine;
struct SvXMLEnumMapEntry;
class SvXMLUnitConverter;
class Color;
namespace rtl { class OUString; }
/** Define various helper variables and functions for xmlimpit.cxx and
* xmlexpit.cxx. */
#define SVX_XML_BORDER_STYLE_NONE 0
#define SVX_XML_BORDER_STYLE_SOLID 1
#define SVX_XML_BORDER_STYLE_DOUBLE 2
#define SVX_XML_BORDER_WIDTH_THIN 0
#define SVX_XML_BORDER_WIDTH_MIDDLE 1
#define SVX_XML_BORDER_WIDTH_THICK 2
sal_Bool lcl_frmitems_parseXMLBorder( const ::rtl::OUString& rValue,
const SvXMLUnitConverter& rUnitConverter,
sal_Bool& rHasStyle, sal_uInt16& rStyle,
sal_Bool& rHasWidth, sal_uInt16& rWidth,
sal_uInt16& rNamedWidth,
sal_Bool& rHasColor, Color& rColor );
void lcl_frmitems_setXMLBorderWidth( SvxBorderLine& rLine,
sal_uInt16 nOutWidth, sal_uInt16 nInWidth,
sal_uInt16 nDistance );
void lcl_frmitems_setXMLBorderWidth( SvxBorderLine& rLine,
sal_uInt16 nWidth, sal_Bool bDouble );
sal_Bool lcl_frmitems_setXMLBorder( SvxBorderLine*& rpLine,
sal_Bool bHasStyle, sal_uInt16 nStyle,
sal_Bool bHasWidth, sal_uInt16 nWidth,
sal_uInt16 nNamedWidth,
sal_Bool bHasColor, const Color& rColor );
void lcl_frmitems_setXMLBorder( SvxBorderLine*& rpLine,
sal_uInt16 nWidth, sal_uInt16 nOutWidth,
sal_uInt16 nInWidth, sal_uInt16 nDistance );
void lcl_frmitems_MergeXMLHoriPos( SvxGraphicPosition& ePos,
SvxGraphicPosition eHori );
void lcl_frmitems_MergeXMLVertPos( SvxGraphicPosition& ePos,
SvxGraphicPosition eVert );
extern const sal_uInt16 aSBorderWidths[];
extern const sal_uInt16 aDBorderWidths[5*11];
extern const struct SvXMLEnumMapEntry psXML_BorderStyles[];
extern const struct SvXMLEnumMapEntry psXML_NamedBorderWidths[];
extern const struct SvXMLEnumMapEntry psXML_BrushRepeat[];
extern const struct SvXMLEnumMapEntry psXML_BrushHoriPos[];
extern const struct SvXMLEnumMapEntry psXML_BrushVertPos[];
extern const struct SvXMLEnumMapEntry psXML_BreakType[];
extern const struct SvXMLEnumMapEntry aXMLTableAlignMap[];
extern const struct SvXMLEnumMapEntry aXMLTableVAlignMap[];
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2010 - 2015 Leonid Kostrykin
*
* Chair of Medical Engineering (mediTEC)
* RWTH Aachen University
* Pauwelsstr. 20
* 52074 Aachen
* Germany
*
*/
#include <Carna/qt/Display.h>
#include <Carna/base/FrameRenderer.h>
#include <Carna/base/SpatialMovement.h>
#include <Carna/base/GLContext.h>
#include <Carna/base/Camera.h>
#include <Carna/base/Log.h>
#include <Carna/base/ProjectionControl.h>
#include <Carna/base/CameraControl.h>
#include <Carna/presets/MeshColorCodingStage.h>
#include <QGLContext>
#include <QMouseEvent>
#include <QWheelEvent>
namespace Carna
{
namespace qt
{
// ----------------------------------------------------------------------------------
// Display :: Details
// ----------------------------------------------------------------------------------
struct Display::Details
{
Details();
typedef base::QGLContextAdapter< QGLContext > GLContext;
std::unique_ptr< GLContext > glc;
std::unique_ptr< base::FrameRenderer > renderer;
bool glInitializationFinished;
ViewportMode vpMode;
base::Camera* cam;
base::Node* root;
std::unique_ptr< base::Aggregation< base::CameraControl > > camControl;
std::unique_ptr< base::Aggregation< base::ProjectionControl > > projControl;
bool mouseInteraction;
QPoint mousepos;
float radiansPerPixel;
float axialMovementSpeed;
presets::MeshColorCodingStage* mccs;
std::unique_ptr< base::SpatialMovement > spatialMovement;
void updateProjection( Display& );
bool fitSquare() const;
};
Display::Details::Details()
: glInitializationFinished( false )
, vpMode( fitAuto )
, cam( nullptr )
, root( nullptr )
, radiansPerPixel( DEFAULT_ROTATION_SPEED )
, axialMovementSpeed( DEFAULT_AXIAL_MOVEMENT_SPEED )
, mccs( nullptr )
{
}
void Display::Details::updateProjection( Display& display )
{
if( display.hasCamera() && display.hasProjectionControl() && display.width() > 0 && display.height() > 0 )
{
const unsigned int width = static_cast< unsigned int >( display. width() );
const unsigned int height = static_cast< unsigned int >( display.height() );
/* Update projection parameters.
*/
if( fitSquare() )
{
const unsigned int vpSize = std::min( width, height );
display.projectionControl().setViewportWidth ( vpSize );
display.projectionControl().setViewportHeight( vpSize );
}
else
{
display.projectionControl().setViewportWidth ( width );
display.projectionControl().setViewportHeight( height );
}
/* Fetch new projection matrix.
*/
base::math::Matrix4f projection;
display.projectionControl().updateProjection( projection );
display.camera().setProjection( projection );
/* Redraw if required.
*/
if( glInitializationFinished )
{
display.updateGL();
}
}
}
bool Display::Details::fitSquare() const
{
switch( vpMode )
{
case Display::fitSquare:
return true;
case Display::fitFrame:
return false;
case Display::fitAuto:
return projControl.get() != nullptr && projControl->get() != nullptr;
default:
CARNA_FAIL( "Unknown ViewportMode value." );
}
}
// ----------------------------------------------------------------------------------
// Display
// ----------------------------------------------------------------------------------
const float Display::DEFAULT_ROTATION_SPEED = 1e-2f;
const float Display::DEFAULT_AXIAL_MOVEMENT_SPEED = 1e+0f;
Display::Display( QWidget* parent )
: QGLWidget( parent )
, pimpl( new Details() )
{
}
Display::~Display()
{
if( pimpl->glc.get() != nullptr )
{
pimpl->glc->makeActive();
}
}
void Display::setViewportMode( ViewportMode vpMode )
{
if( vpMode != pimpl->vpMode )
{
pimpl->vpMode = vpMode;
if( pimpl->renderer.get() != nullptr )
{
resizeGL( width(), height() );
}
}
}
void Display::setCamera( base::Camera& cam )
{
pimpl->cam = &cam;
pimpl->updateProjection( *this );
if( hasCameraControl() )
{
cameraControl().setCamera( cam );
}
/* We will search the root node the first time we render the frame.
*/
pimpl->root = nullptr;
}
bool Display::hasCamera() const
{
return pimpl->cam != nullptr;
}
base::Camera& Display::camera()
{
return *pimpl->cam;
}
const base::Camera& Display::camera() const
{
return *pimpl->cam;
}
void Display::initializeGL()
{
CARNA_ASSERT( pimpl->glc.get() == nullptr );
pimpl->glc.reset( new Details::GLContext() );
}
void Display::resizeGL( int w, int h )
{
CARNA_ASSERT( pimpl->glc.get() != nullptr );
const unsigned int width = static_cast< unsigned int >( w );
const unsigned int height = static_cast< unsigned int >( h );
if( pimpl->renderer == nullptr )
{
pimpl->renderer.reset( new base::FrameRenderer( *pimpl->glc, width, height, pimpl->fitSquare() ) );
setupRenderer( *pimpl->renderer );
pimpl->mccs = pimpl->renderer->findStage< presets::MeshColorCodingStage >().get();
pimpl->updateProjection( *this );
pimpl->glInitializationFinished = true;
}
else
{
pimpl->renderer->reshape( width, height, pimpl->fitSquare() );
pimpl->updateProjection( *this );
}
}
void Display::paintGL()
{
CARNA_ASSERT( pimpl->renderer.get() != nullptr );
if( pimpl->cam == nullptr )
{
base::Log::instance().record( base::Log::debug, "Display has no camera but should render." );
}
else
{
if( pimpl->root == nullptr )
{
pimpl->root = &pimpl->cam->findRoot();
}
pimpl->renderer->render( *pimpl->cam, *pimpl->root );
}
}
void Display::setRotationSpeed( float radiansPerPixel )
{
pimpl->radiansPerPixel = radiansPerPixel;
}
void Display::setAxialMovementSpeed( float axialMovementSpeed )
{
pimpl->axialMovementSpeed = axialMovementSpeed;
}
void Display::mousePressEvent( QMouseEvent* ev )
{
/* First, try to pick object at clicked location.
*/
const base::Geometry* picked = nullptr;
if( pimpl->mccs != nullptr )
{
picked = pimpl->mccs->pick( ev->x(), ev->y() ).get();
}
/* Initiate camera rotation if nothing was picked.
*/
if( picked == nullptr )
{
pimpl->mousepos = ev->pos();
pimpl->mouseInteraction = true;
ev->accept();
}
else
if( pimpl->renderer != nullptr && hasCamera() && hasCameraControl() )
{
/* Picking was successful! Initiate spatial movement.
*/
base::Geometry& pickedGeometry = const_cast< base::Geometry& >( *picked );
pimpl->spatialMovement.reset
( new base::SpatialMovement( pickedGeometry, ev->x(), ev->y(), pimpl->renderer->viewport(), *pimpl->cam ) );
pimpl->mouseInteraction = true;
ev->accept();
}
}
void Display::mouseMoveEvent( QMouseEvent* ev )
{
if( pimpl->mouseInteraction )
{
if( pimpl->spatialMovement.get() == nullptr && hasCamera() && hasCameraControl() )
{
/* Camera rotation is going on.
*/
const int dx = ( ev->x() - pimpl->mousepos.x() );
const int dy = ( ev->y() - pimpl->mousepos.y() );
pimpl->mousepos = ev->pos();
if( dx != 0 || dy != 0 )
{
cameraControl().rotateHorizontally( dx * pimpl->radiansPerPixel );
cameraControl().rotateVertically ( dx * pimpl->radiansPerPixel );
updateGL();
ev->accept();
}
}
else
if( pimpl->spatialMovement.get() != nullptr )
{
/* Spatial movement is going on. Update it.
*/
if( pimpl->spatialMovement->update( ev->x(), ev->y() ) )
{
updateGL();
ev->accept();
}
}
}
}
void Display::mouseReleaseEvent( QMouseEvent* ev )
{
pimpl->mouseInteraction = false;
pimpl->spatialMovement.reset();
ev->accept();
}
void Display::wheelEvent( QWheelEvent* ev )
{
if( hasCamera() && hasCameraControl() )
{
cameraControl().moveAxially( ev->delta() * pimpl->axialMovementSpeed );
ev->accept();
}
}
void Display::setCameraControl( base::Aggregation< base::CameraControl >* camControl )
{
pimpl->camControl.reset( camControl );
if( hasCamera() )
{
cameraControl().setCamera( *pimpl->cam );
}
}
bool Display::hasCameraControl() const
{
return pimpl->camControl.get() != nullptr && pimpl->camControl->get() != nullptr;
}
base::CameraControl& Display::cameraControl()
{
CARNA_ASSERT( hasCameraControl() );
return **pimpl->camControl;
}
const base::CameraControl& Display::cameraControl() const
{
CARNA_ASSERT( hasCameraControl() );
return **pimpl->camControl;
}
void Display::setProjectionControl( base::Aggregation< base::ProjectionControl >* projControl )
{
pimpl->projControl.reset( projControl );
pimpl->updateProjection( *this );
}
bool Display::hasProjectionControl() const
{
return pimpl->projControl.get() != nullptr && pimpl->projControl->get() != nullptr;
}
base::ProjectionControl& Display::projectionControl()
{
CARNA_ASSERT( hasProjectionControl() );
return **pimpl->projControl;
}
const base::ProjectionControl& Display::projectionControl() const
{
CARNA_ASSERT( hasProjectionControl() );
return **pimpl->projControl;
}
bool Display::hasRenderer() const
{
return pimpl->renderer.get() != nullptr;
}
base::FrameRenderer& Display::renderer()
{
CARNA_ASSERT( hasRenderer() );
return *pimpl->renderer;
}
const base::FrameRenderer& Display::renderer() const
{
CARNA_ASSERT( hasRenderer() );
return *pimpl->renderer;
}
} // namespace Carna :: qt
} // namespace Carna
<commit_msg>added GL context sharing<commit_after>/*
* Copyright (C) 2010 - 2015 Leonid Kostrykin
*
* Chair of Medical Engineering (mediTEC)
* RWTH Aachen University
* Pauwelsstr. 20
* 52074 Aachen
* Germany
*
*/
#include <Carna/qt/Display.h>
#include <Carna/base/FrameRenderer.h>
#include <Carna/base/SpatialMovement.h>
#include <Carna/base/GLContext.h>
#include <Carna/base/Camera.h>
#include <Carna/base/Log.h>
#include <Carna/base/ProjectionControl.h>
#include <Carna/base/CameraControl.h>
#include <Carna/presets/MeshColorCodingStage.h>
#include <QGLContext>
#include <QMouseEvent>
#include <QWheelEvent>
#include <set>
namespace Carna
{
namespace qt
{
// ----------------------------------------------------------------------------------
// Display :: Details
// ----------------------------------------------------------------------------------
struct Display::Details
{
Details();
static std::set< const Display* > sharingDisplays;
static const Display* pickSharingDisplay();
typedef base::QGLContextAdapter< QGLContext > GLContext;
std::unique_ptr< GLContext > glc;
std::unique_ptr< base::FrameRenderer > renderer;
bool glInitializationFinished;
ViewportMode vpMode;
base::Camera* cam;
base::Node* root;
std::unique_ptr< base::Aggregation< base::CameraControl > > camControl;
std::unique_ptr< base::Aggregation< base::ProjectionControl > > projControl;
bool mouseInteraction;
QPoint mousepos;
float radiansPerPixel;
float axialMovementSpeed;
presets::MeshColorCodingStage* mccs;
std::unique_ptr< base::SpatialMovement > spatialMovement;
void updateProjection( Display& );
bool fitSquare() const;
};
std::set< const Display* > Display::Details::sharingDisplays = std::set< const Display* >();
Display::Details::Details()
: glInitializationFinished( false )
, vpMode( fitAuto )
, cam( nullptr )
, root( nullptr )
, radiansPerPixel( DEFAULT_ROTATION_SPEED )
, axialMovementSpeed( DEFAULT_AXIAL_MOVEMENT_SPEED )
, mccs( nullptr )
{
}
const Display* Display::Details::pickSharingDisplay()
{
if( sharingDisplays.empty() )
{
return nullptr;
}
else
{
return *sharingDisplays.begin();
}
}
void Display::Details::updateProjection( Display& display )
{
if( display.hasCamera() && display.hasProjectionControl() && display.width() > 0 && display.height() > 0 )
{
const unsigned int width = static_cast< unsigned int >( display. width() );
const unsigned int height = static_cast< unsigned int >( display.height() );
/* Update projection parameters.
*/
if( fitSquare() )
{
const unsigned int vpSize = std::min( width, height );
display.projectionControl().setViewportWidth ( vpSize );
display.projectionControl().setViewportHeight( vpSize );
}
else
{
display.projectionControl().setViewportWidth ( width );
display.projectionControl().setViewportHeight( height );
}
/* Fetch new projection matrix.
*/
base::math::Matrix4f projection;
display.projectionControl().updateProjection( projection );
display.camera().setProjection( projection );
/* Redraw if required.
*/
if( glInitializationFinished )
{
display.updateGL();
}
}
}
bool Display::Details::fitSquare() const
{
switch( vpMode )
{
case Display::fitSquare:
return true;
case Display::fitFrame:
return false;
case Display::fitAuto:
return projControl.get() != nullptr && projControl->get() != nullptr;
default:
CARNA_FAIL( "Unknown ViewportMode value." );
}
}
// ----------------------------------------------------------------------------------
// Display
// ----------------------------------------------------------------------------------
const float Display::DEFAULT_ROTATION_SPEED = 1e-2f;
const float Display::DEFAULT_AXIAL_MOVEMENT_SPEED = 1e+0f;
Display::Display( QWidget* parent )
: QGLWidget( parent, Details::pickSharingDisplay() )
, pimpl( new Details() )
{
Details::sharingDisplays.insert( this );
}
Display::~Display()
{
Details::sharingDisplays.erase( this );
if( pimpl->glc.get() != nullptr )
{
pimpl->glc->makeActive();
}
}
void Display::setViewportMode( ViewportMode vpMode )
{
if( vpMode != pimpl->vpMode )
{
pimpl->vpMode = vpMode;
if( pimpl->renderer.get() != nullptr )
{
resizeGL( width(), height() );
}
}
}
void Display::setCamera( base::Camera& cam )
{
pimpl->cam = &cam;
pimpl->updateProjection( *this );
if( hasCameraControl() )
{
cameraControl().setCamera( cam );
}
/* We will search the root node the first time we render the frame.
*/
pimpl->root = nullptr;
}
bool Display::hasCamera() const
{
return pimpl->cam != nullptr;
}
base::Camera& Display::camera()
{
return *pimpl->cam;
}
const base::Camera& Display::camera() const
{
return *pimpl->cam;
}
void Display::initializeGL()
{
CARNA_ASSERT( pimpl->glc.get() == nullptr );
pimpl->glc.reset( new Details::GLContext() );
}
void Display::resizeGL( int w, int h )
{
CARNA_ASSERT( pimpl->glc.get() != nullptr );
const unsigned int width = static_cast< unsigned int >( w );
const unsigned int height = static_cast< unsigned int >( h );
if( pimpl->renderer == nullptr )
{
pimpl->renderer.reset( new base::FrameRenderer( *pimpl->glc, width, height, pimpl->fitSquare() ) );
setupRenderer( *pimpl->renderer );
pimpl->mccs = pimpl->renderer->findStage< presets::MeshColorCodingStage >().get();
pimpl->updateProjection( *this );
pimpl->glInitializationFinished = true;
}
else
{
pimpl->renderer->reshape( width, height, pimpl->fitSquare() );
pimpl->updateProjection( *this );
}
}
void Display::paintGL()
{
CARNA_ASSERT( pimpl->renderer.get() != nullptr );
if( pimpl->cam == nullptr )
{
base::Log::instance().record( base::Log::debug, "Display has no camera but should render." );
}
else
{
if( pimpl->root == nullptr )
{
pimpl->root = &pimpl->cam->findRoot();
}
pimpl->renderer->render( *pimpl->cam, *pimpl->root );
}
}
void Display::setRotationSpeed( float radiansPerPixel )
{
pimpl->radiansPerPixel = radiansPerPixel;
}
void Display::setAxialMovementSpeed( float axialMovementSpeed )
{
pimpl->axialMovementSpeed = axialMovementSpeed;
}
void Display::mousePressEvent( QMouseEvent* ev )
{
/* First, try to pick object at clicked location.
*/
const base::Geometry* picked = nullptr;
if( pimpl->mccs != nullptr )
{
picked = pimpl->mccs->pick( ev->x(), ev->y() ).get();
}
/* Initiate camera rotation if nothing was picked.
*/
if( picked == nullptr )
{
pimpl->mousepos = ev->pos();
pimpl->mouseInteraction = true;
ev->accept();
}
else
if( pimpl->renderer != nullptr && hasCamera() && hasCameraControl() )
{
/* Picking was successful! Initiate spatial movement.
*/
base::Geometry& pickedGeometry = const_cast< base::Geometry& >( *picked );
pimpl->spatialMovement.reset
( new base::SpatialMovement( pickedGeometry, ev->x(), ev->y(), pimpl->renderer->viewport(), *pimpl->cam ) );
pimpl->mouseInteraction = true;
ev->accept();
}
}
void Display::mouseMoveEvent( QMouseEvent* ev )
{
if( pimpl->mouseInteraction )
{
if( pimpl->spatialMovement.get() == nullptr && hasCamera() && hasCameraControl() )
{
/* Camera rotation is going on.
*/
const int dx = ( ev->x() - pimpl->mousepos.x() );
const int dy = ( ev->y() - pimpl->mousepos.y() );
pimpl->mousepos = ev->pos();
if( dx != 0 || dy != 0 )
{
cameraControl().rotateHorizontally( dx * pimpl->radiansPerPixel );
cameraControl().rotateVertically ( dx * pimpl->radiansPerPixel );
updateGL();
ev->accept();
}
}
else
if( pimpl->spatialMovement.get() != nullptr )
{
/* Spatial movement is going on. Update it.
*/
if( pimpl->spatialMovement->update( ev->x(), ev->y() ) )
{
updateGL();
ev->accept();
}
}
}
}
void Display::mouseReleaseEvent( QMouseEvent* ev )
{
pimpl->mouseInteraction = false;
pimpl->spatialMovement.reset();
ev->accept();
}
void Display::wheelEvent( QWheelEvent* ev )
{
if( hasCamera() && hasCameraControl() )
{
cameraControl().moveAxially( ev->delta() * pimpl->axialMovementSpeed );
ev->accept();
}
}
void Display::setCameraControl( base::Aggregation< base::CameraControl >* camControl )
{
pimpl->camControl.reset( camControl );
if( hasCamera() )
{
cameraControl().setCamera( *pimpl->cam );
}
}
bool Display::hasCameraControl() const
{
return pimpl->camControl.get() != nullptr && pimpl->camControl->get() != nullptr;
}
base::CameraControl& Display::cameraControl()
{
CARNA_ASSERT( hasCameraControl() );
return **pimpl->camControl;
}
const base::CameraControl& Display::cameraControl() const
{
CARNA_ASSERT( hasCameraControl() );
return **pimpl->camControl;
}
void Display::setProjectionControl( base::Aggregation< base::ProjectionControl >* projControl )
{
pimpl->projControl.reset( projControl );
pimpl->updateProjection( *this );
}
bool Display::hasProjectionControl() const
{
return pimpl->projControl.get() != nullptr && pimpl->projControl->get() != nullptr;
}
base::ProjectionControl& Display::projectionControl()
{
CARNA_ASSERT( hasProjectionControl() );
return **pimpl->projControl;
}
const base::ProjectionControl& Display::projectionControl() const
{
CARNA_ASSERT( hasProjectionControl() );
return **pimpl->projControl;
}
bool Display::hasRenderer() const
{
return pimpl->renderer.get() != nullptr;
}
base::FrameRenderer& Display::renderer()
{
CARNA_ASSERT( hasRenderer() );
return *pimpl->renderer;
}
const base::FrameRenderer& Display::renderer() const
{
CARNA_ASSERT( hasRenderer() );
return *pimpl->renderer;
}
} // namespace Carna :: qt
} // namespace Carna
<|endoftext|> |
<commit_before>/*
* W.J. van der Laan 2011-2012
*/
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "init.h"
#include "ui_interface.h"
#include "qtipcserver.h"
#include <QApplication>
#include <QMessageBox>
#if QT_VERSION < 0x050000
#include <QTextCodec>
#endif
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>
#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif
// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static QSplashScreen *splashref;
static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & CClientUIInterface::MODAL);
// in case of modal message, use blocking connection to wait for user to click OK
QMetaObject::invokeMethod(guiref, "error",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(bool, modal));
}
else
{
LogPrintf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
}
}
static bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)
{
if(!guiref)
return false;
if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
static void ThreadSafeHandleURI(const std::string& strURI)
{
if(!guiref)
return;
QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(QString, QString::fromStdString(strURI)));
}
static void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));
QApplication::instance()->processEvents();
}
}
static void QueueShutdown()
{
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
/*
Translate string to current locale using Qt.
*/
static std::string Translate(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. NovaCoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
// Do this early as we don't want to bother initializing if we are just calling IPC
ipcScanRelay(argc, argv);
#if QT_VERSION < 0x050000
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
#endif
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Install global event filter that makes sure that long tooltips can be word-wrapped
app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
// Command-line options take precedence:
ParseParameters(argc, argv);
// ... then bitcoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
// This message can not be translated, as translation is not initialized yet
// (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory)
QMessageBox::critical(0, "NovaCoin",
QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
app.setOrganizationName("NovaCoin");
app.setOrganizationDomain("novacoin.su");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
app.setApplicationName("NovaCoin-Qt-testnet");
else
app.setApplicationName("NovaCoin-Qt");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale (e.g. "de_DE") from command line or use system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
QString lang = lang_territory;
// Convert to "de" only by truncating "_DE"
lang.truncate(lang_territory.lastIndexOf('_'));
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
if (translatorBase.load(lang, ":/translations/"))
app.installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
if (translator.load(lang_territory, ":/translations/"))
app.installTranslator(&translator);
// Subscribe to global signals from core
uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI);
uiInterface.InitMessage.connect(InitMessage);
uiInterface.QueueShutdown.connect(QueueShutdown);
uiInterface.Translate.connect(Translate);
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
GUIUtil::HelpMessageBox help;
help.showOrPrint();
return 1;
}
QSplashScreen splash(QPixmap(":/images/splash"), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
// Regenerate startup link, to fix links to old versions
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(true);
BitcoinGUI window;
guiref = &window;
if(AppInit2())
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
optionsModel.Upgrade(); // Must be done after AppInit2
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
WalletModel walletModel(pwalletMain, &optionsModel);
window.setClientModel(&clientModel);
window.setWalletModel(&walletModel);
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
// Place this here as guiref has to be defined if we don't want to lose URIs
ipcInit(argc, argv);
app.exec();
window.hide();
window.setClientModel(0);
window.setWalletModel(0);
guiref = 0;
}
// Shutdown the core and its threads, but don't exit Bitcoin-Qt here
Shutdown(NULL);
}
else
{
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST
<commit_msg>qDebug() message handler --> debug.log<commit_after>/*
* W.J. van der Laan 2011-2012
*/
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "init.h"
#include "ui_interface.h"
#include "qtipcserver.h"
#include <QApplication>
#include <QMessageBox>
#if QT_VERSION < 0x050000
#include <QTextCodec>
#endif
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>
#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif
// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static QSplashScreen *splashref;
static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & CClientUIInterface::MODAL);
// in case of modal message, use blocking connection to wait for user to click OK
QMetaObject::invokeMethod(guiref, "error",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(bool, modal));
}
else
{
LogPrintf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
}
}
static bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)
{
if(!guiref)
return false;
if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
static void ThreadSafeHandleURI(const std::string& strURI)
{
if(!guiref)
return;
QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(QString, QString::fromStdString(strURI)));
}
static void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));
QApplication::instance()->processEvents();
}
}
static void QueueShutdown()
{
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
/*
Translate string to current locale using Qt.
*/
static std::string Translate(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* qDebug() message handler --> debug.log */
#if QT_VERSION < 0x050000
void DebugMessageHandler(QtMsgType type, const char *msg)
{
const char *category = (type == QtDebugMsg) ? "qt" : NULL;
LogPrint(category, "GUI: %s\n", msg);
}
#else
void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString &msg)
{
Q_UNUSED(context);
const char *category = (type == QtDebugMsg) ? "qt" : NULL;
LogPrint(category, "GUI: %s\n", msg.toStdString());
}
#endif
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. NovaCoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
// Do this early as we don't want to bother initializing if we are just calling IPC
ipcScanRelay(argc, argv);
#if QT_VERSION < 0x050000
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
#endif
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Install global event filter that makes sure that long tooltips can be word-wrapped
app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
// Command-line options take precedence:
ParseParameters(argc, argv);
// ... then bitcoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
// This message can not be translated, as translation is not initialized yet
// (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory)
QMessageBox::critical(0, "NovaCoin",
QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
app.setOrganizationName("NovaCoin");
app.setOrganizationDomain("novacoin.su");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
app.setApplicationName("NovaCoin-Qt-testnet");
else
app.setApplicationName("NovaCoin-Qt");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale (e.g. "de_DE") from command line or use system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
QString lang = lang_territory;
// Convert to "de" only by truncating "_DE"
lang.truncate(lang_territory.lastIndexOf('_'));
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
if (translatorBase.load(lang, ":/translations/"))
app.installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
if (translator.load(lang_territory, ":/translations/"))
app.installTranslator(&translator);
// Subscribe to global signals from core
uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI);
uiInterface.InitMessage.connect(InitMessage);
uiInterface.QueueShutdown.connect(QueueShutdown);
uiInterface.Translate.connect(Translate);
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
GUIUtil::HelpMessageBox help;
help.showOrPrint();
return 1;
}
QSplashScreen splash(QPixmap(":/images/splash"), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
// Regenerate startup link, to fix links to old versions
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(true);
BitcoinGUI window;
guiref = &window;
if(AppInit2())
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
optionsModel.Upgrade(); // Must be done after AppInit2
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
WalletModel walletModel(pwalletMain, &optionsModel);
window.setClientModel(&clientModel);
window.setWalletModel(&walletModel);
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
// Place this here as guiref has to be defined if we don't want to lose URIs
ipcInit(argc, argv);
app.exec();
window.hide();
window.setClientModel(0);
window.setWalletModel(0);
guiref = 0;
}
// Shutdown the core and its threads, but don't exit Bitcoin-Qt here
Shutdown(NULL);
}
else
{
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <iostream>
#include "EasyCL.h"
using namespace std;
//#include "THClTensorRandom.h"
//extern void clnn_ClStorage_init(lua_State* L);
//extern void clnn_ClTensor_init(lua_State* L);
//extern void clnn_ClTensorMath_init(lua_State* L);
//extern void clnn_ClTensorOperator_init(lua_State* L);
extern "C" {
#include "lua.h"
#include "utils.h"
#include "luaT.h"
#include "THClGeneral.h"
int luaopen_libclnn( lua_State *L );
}
#define SET_DEVN_PROP(NAME) \
lua_pushnumber(L, prop.NAME); \
lua_setfield(L, -2, #NAME);
//extern "C" {
// static int clnn_getDeviceProperties(lua_State *L);
//}
static int clnn_getDeviceProperties(lua_State *L)
{
int device = (int)luaL_checknumber(L, 1)-1;
// switch context to given device so the call to cudaMemGetInfo is for the correct device
// int oldDevice;
// THCudaCheck(cudaGetDevice(&oldDevice));
// THCudaCheck(cudaSetDevice(device));
// struct cudaDeviceProp prop;
// THCudaCheck(cudaGetDeviceProperties(&prop, device));
lua_newtable(L);
// SET_DEVN_PROP(canMapHostMemory);
// SET_DEVN_PROP(clockRate);
// SET_DEVN_PROP(computeMode);
// SET_DEVN_PROP(deviceOverlap);
// SET_DEVN_PROP(integrated);
// SET_DEVN_PROP(kernelExecTimeoutEnabled);
// SET_DEVN_PROP(major);
// SET_DEVN_PROP(maxThreadsPerBlock);
// SET_DEVN_PROP(memPitch);
// SET_DEVN_PROP(minor);
// SET_DEVN_PROP(multiProcessorCount);
// SET_DEVN_PROP(regsPerBlock);
// SET_DEVN_PROP(sharedMemPerBlock);
// SET_DEVN_PROP(textureAlignment);
// SET_DEVN_PROP(totalConstMem);
// SET_DEVN_PROP(totalGlobalMem);
// SET_DEVN_PROP(warpSize);
// SET_DEVN_PROP(pciBusID);
// SET_DEVN_PROP(pciDeviceID);
// SET_DEVN_PROP(pciDomainID);
// SET_DEVN_PROP(maxTexture1D);
// SET_DEVN_PROP(maxTexture1DLinear);
// size_t freeMem;
// THCudaCheck(cudaMemGetInfo (&freeMem, NULL));
// lua_pushnumber(L, freeMem);
// lua_setfield(L, -2, "freeGlobalMem");
// lua_pushstring(L, prop.name);
// lua_setfield(L, -2, "name");
// restore context
// THCudaCheck(cudaSetDevice(oldDevice));
return 1;
}
//static int cutorch_getState(lua_State *L)
//{
// lua_getglobal(L, "cutorch");
// lua_getfield(L, -1, "_state");
// lua_remove(L, -2);
// return 1;
//}
const char *getDevicePropertiesName = "getDeviceProperties";
static const struct luaL_Reg clnn_stuff__ [] = {
// {"synchronize", cutorch_synchronize},
// {"getDevice", cutorch_getDevice},
// {"deviceReset", cutorch_deviceReset},
// {"getDeviceCount", cutorch_getDeviceCount},
{"getDeviceProperties", clnn_getDeviceProperties},
// {"getMemoryUsage", cutorch_getMemoryUsage},
// {"setDevice", cutorch_setDevice},
// {"seed", cutorch_seed},
// {"seedAll", cutorch_seedAll},
// {"initialSeed", cutorch_initialSeed},
// {"manualSeed", cutorch_manualSeed},
// {"manualSeedAll", cutorch_manualSeedAll},
// {"getRNGState", cutorch_getRNGState},
// {"setRNGState", cutorch_setRNGState},
// {"getState", cutorch_getState},
{NULL, NULL}
};
int luaopen_libclnn( lua_State *L ) {
printf("luaopen_libclnn called :-)\n");
cout << " try cout" << endl;
// luaL_setfuncs(L, clnn_stuff__, 0);
luaL_register(L, NULL, clnn_stuff__);
cout << "setfuncs done" << endl;
THClState* state = (THClState*)malloc(sizeof(THClState));
cout << "allocated THClState" << endl;
THClInit(state);
cout << "THClInit done" << endl;
// cltorch_ClStorage_init(L);
// cltorch_ClTensor_init(L);
// cltorch_ClTensorMath_init(L);
// cltorch_ClTensorOperator_init(L);
/* Store state in cutorch table. */
lua_pushlightuserdata(L, state);
lua_setfield(L, -2, "_state");
cout << "luaopen_libclnn done\n" << endl;
return 1;
}
<commit_msg>setfuncs works now<commit_after>#include <stdio.h>
#include <iostream>
#include "EasyCL.h"
using namespace std;
//#include "THClTensorRandom.h"
//extern void clnn_ClStorage_init(lua_State* L);
//extern void clnn_ClTensor_init(lua_State* L);
//extern void clnn_ClTensorMath_init(lua_State* L);
//extern void clnn_ClTensorOperator_init(lua_State* L);
extern "C" {
#include "lua.h"
#include "utils.h"
#include "luaT.h"
#include "THClGeneral.h"
int luaopen_libclnn( lua_State *L );
}
#define SET_DEVN_PROP(NAME) \
lua_pushnumber(L, prop.NAME); \
lua_setfield(L, -2, #NAME);
extern "C" {
static int clnn_getDeviceProperties(lua_State *L);
}
extern "C" {
static int clnn_getDeviceProperties(lua_State *L)
{
cout << "clnn_getDeviceProperties" << endl;
// int device = (int)luaL_checknumber(L, 1)-1;
// switch context to given device so the call to cudaMemGetInfo is for the correct device
// int oldDevice;
// THCudaCheck(cudaGetDevice(&oldDevice));
// THCudaCheck(cudaSetDevice(device));
// struct cudaDeviceProp prop;
// THCudaCheck(cudaGetDeviceProperties(&prop, device));
// lua_newtable(L);
// SET_DEVN_PROP(canMapHostMemory);
// SET_DEVN_PROP(clockRate);
// SET_DEVN_PROP(computeMode);
// SET_DEVN_PROP(deviceOverlap);
// SET_DEVN_PROP(integrated);
// SET_DEVN_PROP(kernelExecTimeoutEnabled);
// SET_DEVN_PROP(major);
// SET_DEVN_PROP(maxThreadsPerBlock);
// SET_DEVN_PROP(memPitch);
// SET_DEVN_PROP(minor);
// SET_DEVN_PROP(multiProcessorCount);
// SET_DEVN_PROP(regsPerBlock);
// SET_DEVN_PROP(sharedMemPerBlock);
// SET_DEVN_PROP(textureAlignment);
// SET_DEVN_PROP(totalConstMem);
// SET_DEVN_PROP(totalGlobalMem);
// SET_DEVN_PROP(warpSize);
// SET_DEVN_PROP(pciBusID);
// SET_DEVN_PROP(pciDeviceID);
// SET_DEVN_PROP(pciDomainID);
// SET_DEVN_PROP(maxTexture1D);
// SET_DEVN_PROP(maxTexture1DLinear);
// size_t freeMem;
// THCudaCheck(cudaMemGetInfo (&freeMem, NULL));
// lua_pushnumber(L, freeMem);
// lua_setfield(L, -2, "freeGlobalMem");
// lua_pushstring(L, prop.name);
// lua_setfield(L, -2, "name");
// restore context
// THCudaCheck(cudaSetDevice(oldDevice));
return 1;
}
}
//static int cutorch_getState(lua_State *L)
//{
// lua_getglobal(L, "cutorch");
// lua_getfield(L, -1, "_state");
// lua_remove(L, -2);
// return 1;
//}
//const char *getDevicePropertiesName = "getDeviceProperties";
static const struct luaL_Reg clnn_stuff__ [] = {
// {"synchronize", cutorch_synchronize},
// {"getDevice", cutorch_getDevice},
// {"deviceReset", cutorch_deviceReset},
// {"getDeviceCount", cutorch_getDeviceCount},
{"getDeviceProperties", clnn_getDeviceProperties},
// {"getMemoryUsage", cutorch_getMemoryUsage},
// {"setDevice", cutorch_setDevice},
// {"seed", cutorch_seed},
// {"seedAll", cutorch_seedAll},
// {"initialSeed", cutorch_initialSeed},
// {"manualSeed", cutorch_manualSeed},
// {"manualSeedAll", cutorch_manualSeedAll},
// {"getRNGState", cutorch_getRNGState},
// {"setRNGState", cutorch_setRNGState},
// {"getState", cutorch_getState},
{NULL, NULL}
};
struct luaL_Reg makeReg( const char *name, lua_CFunction fn ) {
struct luaL_Reg reg;
reg.name = name;
reg.func = fn;
cout << "reg.name" << reg.name <<endl;
return reg;
}
int luaopen_libclnn( lua_State *L ) {
printf("luaopen_libclnn called :-)\n");
cout << " try cout" << endl;
lua_newtable(L);
// struct luaL_Reg clnn_stuff[2];
// cout << "clnn_getDeviceProperties" << (long)clnn_getDeviceProperties << endl;
// clnn_stuff[0] = makeReg("getDeviceProperties", clnn_getDeviceProperties);
// clnn_stuff[0] = makeReg("", 0);
// clnn_stuff[1] = makeReg(NULL, NULL);
luaL_setfuncs(L, clnn_stuff__, 0);
// cout << "clnn_stuff[0]->name" << clnn_stuff[0].name << endl;
// luaL_register(L, NULL, clnn_stuff);
cout << "setfuncs done" << endl;
THClState* state = (THClState*)malloc(sizeof(THClState));
cout << "allocated THClState" << endl;
THClInit(state);
cout << "THClInit done" << endl;
// cltorch_ClStorage_init(L);
// cltorch_ClTensor_init(L);
// cltorch_ClTensorMath_init(L);
// cltorch_ClTensorOperator_init(L);
/* Store state in cutorch table. */
lua_pushlightuserdata(L, state);
lua_setfield(L, -2, "_state");
cout << "luaopen_libclnn done\n" << endl;
return 1;
}
<|endoftext|> |
<commit_before>#include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "util.h"
#include "init.h"
#include <QString>
#include <QDateTime>
#include <QDoubleValidator>
#include <QFont>
#include <QLineEdit>
#if QT_VERSION >= 0x050000
#include <QUrlQuery>
#else
#include <QUrl>
#endif
#include <QTextDocument> // For Qt::escape
#include <QAbstractItemView>
#include <QApplication>
#include <QClipboard>
#include <QFileDialog>
#include <QDesktopServices>
#include <QThread>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shlwapi.h"
#include "shlobj.h"
#include "shellapi.h"
#endif
namespace GUIUtil {
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont bitcoinAddressFont()
{
QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);
return font;
}
void setupAddressWidget(QLineEdit *widget, QWidget *parent)
{
widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
widget->setValidator(new BitcoinAddressValidator(parent));
widget->setFont(bitcoinAddressFont());
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
if(uri.scheme() != QString("hyper"))
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
rv.amount = 0;
#if QT_VERSION < 0x050000
QList<QPair<QString, QString> > items = uri.queryItems();
#else
QUrlQuery uriQuery(uri);
QList<QPair<QString, QString> > items = uriQuery.queryItems();
#endif
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if(!i->second.isEmpty())
{
if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if(out)
{
*out = rv;
}
return true;
}
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
// Convert hyper:// to hyper:
//
// Cannot handle this later, because hyper:// will cause Qt to see the part after // as host,
// which will lower-case it (and thus invalidate the address).
if(uri.startsWith("hyper:// "))
{
uri.replace(0, 11, "hyper:");
}
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
#if QT_VERSION < 0x050000
QString escaped = Qt::escape(str);
#else
QString escaped = str.toHtmlEscaped();
#endif
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item
QApplication::clipboard()->setText(selection.at(0).data(role).toString());
}
}
QString getSaveFileName(QWidget *parent, const QString &caption,
const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
#if QT_VERSION < 0x050000
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
#else
myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#endif
}
else
{
myDir = dir;
}
QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != QCoreApplication::instance()->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
if (!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
}
void openDebugLogfile()
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
/* Open debug.log with the associated application */
if (boost::filesystem::exists(pathDebug))
QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
QObject(parent), size_threshold(size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip))
{
// Prefix <qt/> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt/>" + HtmlEscape(tooltip, true);
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
#ifdef WIN32
boost::filesystem::path static StartupShortcutPath()
{
return GetSpecialFolderPath(CSIDL_STARTUP) / "Hyper.lnk";
}
bool GetStartOnSystemStartup()
{
// check for Bitcoin.lnk
return boost::filesystem::exists(StartupShortcutPath());
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
// If the shortcut exists already, remove it for updating
boost::filesystem::remove(StartupShortcutPath());
if (fAutoStart)
{
CoInitialize(NULL);
// Get a pointer to the IShellLink interface.
IShellLink* psl = NULL;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**>(&psl));
if (SUCCEEDED(hres))
{
// Get the current executable path
TCHAR pszExePath[MAX_PATH];
GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
TCHAR pszArgs[5] = TEXT("-min");
// Set the path to the shortcut target
psl->SetPath(pszExePath);
PathRemoveFileSpec(pszExePath);
psl->SetWorkingDirectory(pszExePath);
psl->SetShowCmd(SW_SHOWMINNOACTIVE);
psl->SetArguments(pszArgs);
// Query IShellLink for the IPersistFile interface for
// saving the shortcut in persistent storage.
IPersistFile* ppf = NULL;
hres = psl->QueryInterface(IID_IPersistFile,
reinterpret_cast<void**>(&ppf));
if (SUCCEEDED(hres))
{
WCHAR pwsz[MAX_PATH];
// Ensure that the string is ANSI.
MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(pwsz, TRUE);
ppf->Release();
psl->Release();
CoUninitialize();
return true;
}
psl->Release();
}
CoUninitialize();
return false;
}
return true;
}
#elif defined(LINUX)
// Follow the Desktop Application Autostart Spec:
// http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
boost::filesystem::path static GetAutostartDir()
{
namespace fs = boost::filesystem;
char* pszConfigHome = getenv("XDG_CONFIG_HOME");
if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
char* pszHome = getenv("HOME");
if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
return fs::path();
}
boost::filesystem::path static GetAutostartFilePath()
{
return GetAutostartDir() / "Hyper.desktop";
}
bool GetStartOnSystemStartup()
{
boost::filesystem::ifstream optionFile(GetAutostartFilePath());
if (!optionFile.good())
return false;
// Scan through file for "Hidden=true":
std::string line;
while (!optionFile.eof())
{
getline(optionFile, line);
if (line.find("Hidden") != std::string::npos &&
line.find("true") != std::string::npos)
return false;
}
optionFile.close();
return true;
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
if (!fAutoStart)
boost::filesystem::remove(GetAutostartFilePath());
else
{
char pszExePath[MAX_PATH+1];
memset(pszExePath, 0, sizeof(pszExePath));
if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
return false;
boost::filesystem::create_directories(GetAutostartDir());
boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
if (!optionFile.good())
return false;
// Write a bitcoin.desktop file to the autostart directory:
optionFile << "[Desktop Entry]\n";
optionFile << "Type=Application\n";
optionFile << "Name=Hyper\n";
optionFile << "Exec=" << pszExePath << " -min\n";
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
optionFile.close();
}
return true;
}
#else
// TODO: OSX startup stuff; see:
// https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
bool GetStartOnSystemStartup() { return false; }
bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
#endif
HelpMessageBox::HelpMessageBox(QWidget *parent) :
QMessageBox(parent)
{
header = tr("Hyper-Qt") + " " + tr("version") + " " +
QString::fromStdString(FormatFullVersion()) + "\n\n" +
tr("Usage:") + "\n" +
" Hyper-qt [" + tr("command-line options") + "] " + "\n";
coreOptions = QString::fromStdString(HelpMessage());
uiOptions = tr("UI options") + ":\n" +
" -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
" -min " + tr("Start minimized") + "\n" +
" -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
setWindowTitle(tr("Hyper-Qt"));
setTextFormat(Qt::PlainText);
// setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
setText(header + QString(QChar(0x2003)).repeated(50));
setDetailedText(coreOptions + "\n" + uiOptions);
}
void HelpMessageBox::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
fprintf(stdout, "%s", strUsage.toStdString().c_str());
}
void HelpMessageBox::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
} // namespace GUIUtil
<commit_msg>ToolTipToRichTextFilter::eventFilter Fix<commit_after>#include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "util.h"
#include "init.h"
#include <QString>
#include <QDateTime>
#include <QDoubleValidator>
#include <QFont>
#include <QLineEdit>
#if QT_VERSION >= 0x050000
#include <QUrlQuery>
#else
#include <QUrl>
#endif
#include <QTextDocument> // For Qt::escape
#include <QAbstractItemView>
#include <QApplication>
#include <QClipboard>
#include <QFileDialog>
#include <QDesktopServices>
#include <QThread>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shlwapi.h"
#include "shlobj.h"
#include "shellapi.h"
#endif
namespace GUIUtil {
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont bitcoinAddressFont()
{
QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);
return font;
}
void setupAddressWidget(QLineEdit *widget, QWidget *parent)
{
widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
widget->setValidator(new BitcoinAddressValidator(parent));
widget->setFont(bitcoinAddressFont());
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
if(uri.scheme() != QString("hyper"))
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
rv.amount = 0;
#if QT_VERSION < 0x050000
QList<QPair<QString, QString> > items = uri.queryItems();
#else
QUrlQuery uriQuery(uri);
QList<QPair<QString, QString> > items = uriQuery.queryItems();
#endif
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if(!i->second.isEmpty())
{
if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if(out)
{
*out = rv;
}
return true;
}
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
// Convert hyper:// to hyper:
//
// Cannot handle this later, because hyper:// will cause Qt to see the part after // as host,
// which will lower-case it (and thus invalidate the address).
if(uri.startsWith("hyper:// "))
{
uri.replace(0, 11, "hyper:");
}
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
#if QT_VERSION < 0x050000
QString escaped = Qt::escape(str);
#else
QString escaped = str.toHtmlEscaped();
#endif
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item
QApplication::clipboard()->setText(selection.at(0).data(role).toString());
}
}
QString getSaveFileName(QWidget *parent, const QString &caption,
const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
#if QT_VERSION < 0x050000
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
#else
myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#endif
}
else
{
myDir = dir;
}
QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != QCoreApplication::instance()->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
if (!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
}
void openDebugLogfile()
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
/* Open debug.log with the associated application */
if (boost::filesystem::exists(pathDebug))
QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
QObject(parent), size_threshold(size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt>") && !Qt::mightBeRichText(tooltip))
{
// Prefix <qt/> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt>" + HtmlEscape(tooltip, true) + "<qt/>";
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
#ifdef WIN32
boost::filesystem::path static StartupShortcutPath()
{
return GetSpecialFolderPath(CSIDL_STARTUP) / "Hyper.lnk";
}
bool GetStartOnSystemStartup()
{
// check for Bitcoin.lnk
return boost::filesystem::exists(StartupShortcutPath());
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
// If the shortcut exists already, remove it for updating
boost::filesystem::remove(StartupShortcutPath());
if (fAutoStart)
{
CoInitialize(NULL);
// Get a pointer to the IShellLink interface.
IShellLink* psl = NULL;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**>(&psl));
if (SUCCEEDED(hres))
{
// Get the current executable path
TCHAR pszExePath[MAX_PATH];
GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
TCHAR pszArgs[5] = TEXT("-min");
// Set the path to the shortcut target
psl->SetPath(pszExePath);
PathRemoveFileSpec(pszExePath);
psl->SetWorkingDirectory(pszExePath);
psl->SetShowCmd(SW_SHOWMINNOACTIVE);
psl->SetArguments(pszArgs);
// Query IShellLink for the IPersistFile interface for
// saving the shortcut in persistent storage.
IPersistFile* ppf = NULL;
hres = psl->QueryInterface(IID_IPersistFile,
reinterpret_cast<void**>(&ppf));
if (SUCCEEDED(hres))
{
WCHAR pwsz[MAX_PATH];
// Ensure that the string is ANSI.
MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(pwsz, TRUE);
ppf->Release();
psl->Release();
CoUninitialize();
return true;
}
psl->Release();
}
CoUninitialize();
return false;
}
return true;
}
#elif defined(LINUX)
// Follow the Desktop Application Autostart Spec:
// http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
boost::filesystem::path static GetAutostartDir()
{
namespace fs = boost::filesystem;
char* pszConfigHome = getenv("XDG_CONFIG_HOME");
if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
char* pszHome = getenv("HOME");
if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
return fs::path();
}
boost::filesystem::path static GetAutostartFilePath()
{
return GetAutostartDir() / "Hyper.desktop";
}
bool GetStartOnSystemStartup()
{
boost::filesystem::ifstream optionFile(GetAutostartFilePath());
if (!optionFile.good())
return false;
// Scan through file for "Hidden=true":
std::string line;
while (!optionFile.eof())
{
getline(optionFile, line);
if (line.find("Hidden") != std::string::npos &&
line.find("true") != std::string::npos)
return false;
}
optionFile.close();
return true;
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
if (!fAutoStart)
boost::filesystem::remove(GetAutostartFilePath());
else
{
char pszExePath[MAX_PATH+1];
memset(pszExePath, 0, sizeof(pszExePath));
if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
return false;
boost::filesystem::create_directories(GetAutostartDir());
boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
if (!optionFile.good())
return false;
// Write a bitcoin.desktop file to the autostart directory:
optionFile << "[Desktop Entry]\n";
optionFile << "Type=Application\n";
optionFile << "Name=Hyper\n";
optionFile << "Exec=" << pszExePath << " -min\n";
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
optionFile.close();
}
return true;
}
#else
// TODO: OSX startup stuff; see:
// https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
bool GetStartOnSystemStartup() { return false; }
bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
#endif
HelpMessageBox::HelpMessageBox(QWidget *parent) :
QMessageBox(parent)
{
header = tr("Hyper-Qt") + " " + tr("version") + " " +
QString::fromStdString(FormatFullVersion()) + "\n\n" +
tr("Usage:") + "\n" +
" Hyper-qt [" + tr("command-line options") + "] " + "\n";
coreOptions = QString::fromStdString(HelpMessage());
uiOptions = tr("UI options") + ":\n" +
" -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
" -min " + tr("Start minimized") + "\n" +
" -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
setWindowTitle(tr("Hyper-Qt"));
setTextFormat(Qt::PlainText);
// setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
setText(header + QString(QChar(0x2003)).repeated(50));
setDetailedText(coreOptions + "\n" + uiOptions);
}
void HelpMessageBox::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
fprintf(stdout, "%s", strUsage.toStdString().c_str());
}
void HelpMessageBox::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
} // namespace GUIUtil
<|endoftext|> |
<commit_before>#include "Anemometer.h"
#include <Arduino.h>
namespace SkyeTracker
{
Anemometer::Anemometer(int sensorPin)
{
_sensorPin = sensorPin;
}
Anemometer::~Anemometer()
{
}
// Wind speed in meters per second
float Anemometer::WindSpeed()
{
// Get a value between 0 and 1023 from the analog pin connected to the anemometer
double reading = analogRead(_sensorPin);
if (reading < 1 || reading > ADC_Resolution)
{
return 0;
}
// The constants used in this calculation are taken from
// https://github.com/G6EJD/ESP32-ADC-Accuracy-Improvement-function
// and improves the default ADC reading accuracy to within 1%.
double sensorVoltage = -0.000000000000016 * pow(reading, 4) +
0.000000000118171 * pow(reading, 3) - 0.000000301211691 * pow(reading, 2) +
0.001109019271794 * reading + 0.034143524634089;
// Convert voltage value to wind speed using range of max and min voltages and wind speed for the anemometer
if (sensorVoltage <= AnemometerVoltageMin)
{
// Check if voltage is below minimum value. If so, set wind speed to zero.
return 0;
}
else
{
// For voltages above minimum value, use the linear relationship to calculate wind speed.
return (sensorVoltage - AnemometerVoltageMin) * AnemometerWindSpeedMax / (AnemometerVoltageMax - AnemometerVoltageMin);
}
}
}
<commit_msg>use tab<commit_after>#include "Anemometer.h"
#include <Arduino.h>
namespace SkyeTracker
{
Anemometer::Anemometer(int sensorPin)
{
_sensorPin = sensorPin;
}
Anemometer::~Anemometer()
{
}
// Wind speed in meters per second
float Anemometer::WindSpeed()
{
// Get a value between 0 and 1023 from the analog pin connected to the anemometer
double reading = analogRead(_sensorPin);
if (reading < 1 || reading > ADC_Resolution)
{
return 0;
}
// The constants used in this calculation are taken from
// https://github.com/G6EJD/ESP32-ADC-Accuracy-Improvement-function
// and improves the default ADC reading accuracy to within 1%.
double sensorVoltage = -0.000000000000016 * pow(reading, 4) +
0.000000000118171 * pow(reading, 3) - 0.000000301211691 * pow(reading, 2) +
0.001109019271794 * reading + 0.034143524634089;
// Convert voltage value to wind speed using range of max and min voltages and wind speed for the anemometer
if (sensorVoltage <= AnemometerVoltageMin)
{
// Check if voltage is below minimum value. If so, set wind speed to zero.
return 0;
}
else
{
// For voltages above minimum value, use the linear relationship to calculate wind speed.
return (sensorVoltage - AnemometerVoltageMin) * AnemometerWindSpeedMax / (AnemometerVoltageMax - AnemometerVoltageMin);
}
}
}
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// winURLLoader.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "winURLLoader.h"
#include "Core/String/StringConverter.h"
#include "IO/Stream/MemoryStream.h"
#define VC_EXTRALEAN (1)
#define WIN32_LEAN_AND_MEAN (1)
#include <Windows.h>
#include <WinHttp.h>
namespace Oryol {
namespace _priv {
const std::chrono::seconds winURLLoader::connectionMaxAge{10};
//------------------------------------------------------------------------------
winURLLoader::winURLLoader() :
contentTypeString("Content-Type")
{
this->hSession = WinHttpOpen(NULL, // pwszUserAgent
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, // dwAccessType
WINHTTP_NO_PROXY_NAME, // pwszProxyName
WINHTTP_NO_PROXY_BYPASS, // pwszProxyByPass
0); // dwFlags
o_assert(NULL != this->hSession);
}
//------------------------------------------------------------------------------
winURLLoader::~winURLLoader() {
o_assert(NULL != this->hSession);
// close remaining connections
for (const auto& kvp : this->connections) {
WinHttpCloseHandle(kvp.Value().hConnection);
}
this->connections.Clear();
WinHttpCloseHandle(this->hSession);
this->hSession = NULL;
}
//------------------------------------------------------------------------------
void
winURLLoader::doWork() {
while (!this->requestQueue.Empty()) {
Ptr<HTTPProtocol::HTTPRequest> req = this->requestQueue.Dequeue();
if (!baseURLLoader::handleCancelled(req)) {
this->doOneRequest(req);
// transfer result to embedded ioRequest and set to handled
auto ioReq = req->GetIoRequest();
if (ioReq) {
auto httpResponse = req->GetResponse();
ioReq->SetStatus(httpResponse->GetStatus());
ioReq->SetStream(httpResponse->GetBody());
ioReq->SetErrorDesc(httpResponse->GetErrorDesc());
ioReq->SetHandled();
}
req->SetHandled();
}
}
this->garbageCollectConnections();
}
//------------------------------------------------------------------------------
void
winURLLoader::doOneRequest(const Ptr<HTTPProtocol::HTTPRequest>& req) {
// obtain a connection
HINTERNET hConn = this->obtainConnection(req->GetURL());
if (NULL != hConn) {
WideString method(HTTPMethod::ToWideString(req->GetMethod()));
WideString path(StringConverter::UTF8ToWide(req->GetURL().PathToEnd()));
// setup an HTTP request
HINTERNET hRequest = WinHttpOpenRequest(
hConn, // hConnect
method.AsCStr(), // pwszVerb
path.AsCStr(), // pwszObjectName
NULL, // pwszVersion (NULL == HTTP/1.1)
WINHTTP_NO_REFERER, // pwszReferrer
WINHTTP_DEFAULT_ACCEPT_TYPES, // pwszAcceptTypes
WINHTTP_FLAG_ESCAPE_PERCENT); // dwFlags
if (NULL != hRequest) {
// add request headers to the request
if (!req->GetRequestHeaders().Empty()) {
for (const auto& kvp : req->GetRequestHeaders()) {
this->stringBuilder.Clear();
this->stringBuilder.Append(kvp.Key());
this->stringBuilder.Append(": ");
this->stringBuilder.Append(kvp.Value());
this->stringBuilder.Append("\r\n");
}
// check if we need to add a Content-Type field:
if (req->GetBody().isValid() && req->GetBody()->GetContentType().IsValid()) {
this->stringBuilder.Append("Content-Type: ");
this->stringBuilder.Append(req->GetBody()->GetContentType().AsCStr());
this->stringBuilder.Append("\r\n");
}
// remove last CRLF
this->stringBuilder.PopBack();
this->stringBuilder.PopBack();
WideString reqHeaders(StringConverter::UTF8ToWide(this->stringBuilder.GetString()));
BOOL headerResult = WinHttpAddRequestHeaders(
hRequest,
reqHeaders.AsCStr(),
reqHeaders.Length(),
WINHTTP_ADDREQ_FLAG_ADD|WINHTTP_ADDREQ_FLAG_REPLACE);
o_assert(headerResult);
}
// do we have body-data?
const uint8* bodyDataPtr = WINHTTP_NO_REQUEST_DATA;
int32 bodySize = 0;
if (req->GetBody().isValid()) {
const Ptr<Stream>& bodyStream = req->GetBody();
bodySize = bodyStream->Size();
o_assert(bodySize > 0);
bodyStream->Open(OpenMode::ReadOnly);
bodyDataPtr = bodyStream->MapRead(nullptr);
}
// create a response object, no matter whether the
// send fails or not
Ptr<HTTPProtocol::HTTPResponse> httpResponse = HTTPProtocol::HTTPResponse::Create();
req->SetResponse(httpResponse);
// send the request
BOOL sendResult = WinHttpSendRequest(
hRequest, // hRequest
WINHTTP_NO_ADDITIONAL_HEADERS, // pwszHeaders
0, // dwHeadersLength
(LPVOID) bodyDataPtr, // lpOptional
bodySize, // dwOptionalLength
0, // dwTotoalLength
0); // dwContext
if (sendResult) {
// receive and process response
BOOL recvResult = WinHttpReceiveResponse(hRequest, NULL);
if (recvResult) {
// query the HTTP status code
DWORD dwStatusCode = 0;
DWORD dwTemp = sizeof(dwStatusCode);
WinHttpQueryHeaders(
hRequest,
WINHTTP_QUERY_STATUS_CODE|WINHTTP_QUERY_FLAG_NUMBER,
NULL,
&dwStatusCode,
&dwTemp,
NULL);
httpResponse->SetStatus((IOStatus::Code) dwStatusCode);
// query the response headers required data size
DWORD dwSize = 0;
WinHttpQueryHeaders(hRequest,
WINHTTP_QUERY_RAW_HEADERS_CRLF,
WINHTTP_HEADER_NAME_BY_INDEX,
NULL,
&dwSize,
WINHTTP_NO_HEADER_INDEX);
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
// and get the response headers
LPVOID headerBuffer = Memory::Alloc(dwSize);
BOOL headerResult = WinHttpQueryHeaders(
hRequest,
WINHTTP_QUERY_RAW_HEADERS_CRLF,
WINHTTP_HEADER_NAME_BY_INDEX,
headerBuffer,
&dwSize,
WINHTTP_NO_HEADER_INDEX);
o_assert(headerResult);
// convert from wide and split the header fields
this->stringBuilder.Set(StringConverter::WideToUTF8((const wchar_t*) headerBuffer, dwSize / sizeof(wchar_t)));
Memory::Free(headerBuffer);
Array<String> tokens;
this->stringBuilder.Tokenize("\r\n", tokens);
Map<String, String> fields;
fields.Reserve(tokens.Size());
for (const String& str : tokens) {
const int32 colonIndex = StringBuilder::FindFirstOf(str.AsCStr(), 0, EndOfString, ":");
if (colonIndex != InvalidIndex) {
String key(str.AsCStr(), 0, colonIndex);
String value(str.AsCStr(), colonIndex+2, EndOfString);
fields.Add(key, value);
}
}
httpResponse->SetResponseHeaders(fields);
}
else {
Log::Warn("winURLLoader: failed to extract response header fields!\n");
}
// extract body data
Ptr<MemoryStream> responseBodyStream = MemoryStream::Create();
responseBodyStream->SetURL(req->GetURL());
responseBodyStream->Open(OpenMode::WriteOnly);
DWORD bytesToRead = 0;
do {
// how much data available?
BOOL queryDataResult = WinHttpQueryDataAvailable(hRequest, &bytesToRead);
o_assert(queryDataResult);
if (dwSize > 0) {
uint8* dstPtr = responseBodyStream->MapWrite(bytesToRead);
o_assert(nullptr != dstPtr);
DWORD bytesRead = 0;
BOOL readDataResult = WinHttpReadData(hRequest, dstPtr, bytesToRead, &bytesRead);
o_assert(readDataResult);
o_assert(bytesRead == bytesToRead);
responseBodyStream->UnmapWrite();
}
}
while (bytesToRead > 0);
responseBodyStream->Close();
// extract the Content-Type response header field and set on responseBodyStream
if (httpResponse->GetResponseHeaders().Contains(this->contentTypeString)) {
ContentType contentType(httpResponse->GetResponseHeaders()[this->contentTypeString]);
responseBodyStream->SetContentType(contentType);
}
// ...and finally set the responseBodyStream on the httpResponse
httpResponse->SetBody(responseBodyStream);
// @todo: write error desc to httpResponse if something went wrong
}
else {
Log::Warn("winURLLoader: WinHttpReceiveResponse() failed for '%s'!\n", req->GetURL().AsCStr());
}
}
else {
/// @todo: better error reporting!
Log::Warn("winURLLoader: WinHttpSendRequest() failed for '%s'\n", req->GetURL().AsCStr());
}
// unmap the body data if necessary
if (req->GetBody().isValid()) {
req->GetBody()->Close();
}
// close the request object
WinHttpCloseHandle(hRequest);
}
else {
Log::Warn("winURLLoader: WinHttpOpenRequest() failed for '%s'\n", req->GetURL().AsCStr());
}
}
}
//------------------------------------------------------------------------------
HINTERNET
winURLLoader::obtainConnection(const URL& url) {
o_assert(NULL != this->hSession);
const String hostAndPort = url.HostAndPort();
if (this->connections.Contains(hostAndPort)) {
// connection was already established, refresh the timestamp
// and return the connection
connection& con = this->connections[hostAndPort];
con.timeStamp = std::chrono::steady_clock::now();
return con.hConnection;
}
else {
// new connection
connection con;
const WideString host = StringConverter::UTF8ToWide(url.Host());
const String portString = url.Port();
INTERNET_PORT port = INTERNET_DEFAULT_HTTP_PORT;
if (!portString.Empty()) {
port = StringConverter::FromString<int16>(portString);
}
con.hConnection = WinHttpConnect(this->hSession, // hSession
host.AsCStr(), // pswzServerName
port, // nServerPort
0); // dwReserved
if (NULL != con.hConnection) {
con.timeStamp = std::chrono::steady_clock::now();
this->connections.Add(hostAndPort, con);
return con.hConnection;
}
else {
Log::Warn("winURLLoader: failed to connect to '%s'\n", hostAndPort.AsCStr());
return NULL;
}
}
}
//------------------------------------------------------------------------------
void
winURLLoader::garbageCollectConnections() {
std::chrono::steady_clock::time_point curTime = std::chrono::steady_clock::now();
for (int32 i = this->connections.Size() - 1; i >= 0; i--) {
const String key = this->connections.KeyAtIndex(i);
const connection con = this->connections.ValueAtIndex(i);
std::chrono::seconds age = std::chrono::duration_cast<std::chrono::seconds>(curTime - con.timeStamp);
if (age > connectionMaxAge) {
o_assert(NULL != con.hConnection);
WinHttpCloseHandle(con.hConnection);
this->connections.EraseIndex(i);
}
}
}
} // namespace _priv
} // namespace Oryol
<commit_msg>Added some status output to winURLLoader<commit_after>//------------------------------------------------------------------------------
// winURLLoader.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "winURLLoader.h"
#include "Core/String/StringConverter.h"
#include "IO/Stream/MemoryStream.h"
#define VC_EXTRALEAN (1)
#define WIN32_LEAN_AND_MEAN (1)
#include <Windows.h>
#include <WinHttp.h>
namespace Oryol {
namespace _priv {
const std::chrono::seconds winURLLoader::connectionMaxAge{10};
//------------------------------------------------------------------------------
winURLLoader::winURLLoader() :
contentTypeString("Content-Type")
{
this->hSession = WinHttpOpen(NULL, // pwszUserAgent
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, // dwAccessType
WINHTTP_NO_PROXY_NAME, // pwszProxyName
WINHTTP_NO_PROXY_BYPASS, // pwszProxyByPass
0); // dwFlags
o_assert(NULL != this->hSession);
}
//------------------------------------------------------------------------------
winURLLoader::~winURLLoader() {
o_assert(NULL != this->hSession);
// close remaining connections
for (const auto& kvp : this->connections) {
WinHttpCloseHandle(kvp.Value().hConnection);
}
this->connections.Clear();
WinHttpCloseHandle(this->hSession);
this->hSession = NULL;
}
//------------------------------------------------------------------------------
void
winURLLoader::doWork() {
while (!this->requestQueue.Empty()) {
Ptr<HTTPProtocol::HTTPRequest> req = this->requestQueue.Dequeue();
if (!baseURLLoader::handleCancelled(req)) {
this->doOneRequest(req);
// transfer result to embedded ioRequest and set to handled
auto ioReq = req->GetIoRequest();
if (ioReq) {
auto httpResponse = req->GetResponse();
ioReq->SetStatus(httpResponse->GetStatus());
ioReq->SetStream(httpResponse->GetBody());
ioReq->SetErrorDesc(httpResponse->GetErrorDesc());
ioReq->SetHandled();
}
req->SetHandled();
}
}
this->garbageCollectConnections();
}
//------------------------------------------------------------------------------
void
winURLLoader::doOneRequest(const Ptr<HTTPProtocol::HTTPRequest>& req) {
Log::Info("winURLLoader::doOneRequest() start: %s\n", req->GetURL().AsCStr());
// obtain a connection
HINTERNET hConn = this->obtainConnection(req->GetURL());
if (NULL != hConn) {
WideString method(HTTPMethod::ToWideString(req->GetMethod()));
WideString path(StringConverter::UTF8ToWide(req->GetURL().PathToEnd()));
// setup an HTTP request
HINTERNET hRequest = WinHttpOpenRequest(
hConn, // hConnect
method.AsCStr(), // pwszVerb
path.AsCStr(), // pwszObjectName
NULL, // pwszVersion (NULL == HTTP/1.1)
WINHTTP_NO_REFERER, // pwszReferrer
WINHTTP_DEFAULT_ACCEPT_TYPES, // pwszAcceptTypes
WINHTTP_FLAG_ESCAPE_PERCENT); // dwFlags
if (NULL != hRequest) {
// add request headers to the request
if (!req->GetRequestHeaders().Empty()) {
for (const auto& kvp : req->GetRequestHeaders()) {
this->stringBuilder.Clear();
this->stringBuilder.Append(kvp.Key());
this->stringBuilder.Append(": ");
this->stringBuilder.Append(kvp.Value());
this->stringBuilder.Append("\r\n");
}
// check if we need to add a Content-Type field:
if (req->GetBody().isValid() && req->GetBody()->GetContentType().IsValid()) {
this->stringBuilder.Append("Content-Type: ");
this->stringBuilder.Append(req->GetBody()->GetContentType().AsCStr());
this->stringBuilder.Append("\r\n");
}
// remove last CRLF
this->stringBuilder.PopBack();
this->stringBuilder.PopBack();
WideString reqHeaders(StringConverter::UTF8ToWide(this->stringBuilder.GetString()));
BOOL headerResult = WinHttpAddRequestHeaders(
hRequest,
reqHeaders.AsCStr(),
reqHeaders.Length(),
WINHTTP_ADDREQ_FLAG_ADD|WINHTTP_ADDREQ_FLAG_REPLACE);
o_assert(headerResult);
}
// do we have body-data?
const uint8* bodyDataPtr = WINHTTP_NO_REQUEST_DATA;
int32 bodySize = 0;
if (req->GetBody().isValid()) {
const Ptr<Stream>& bodyStream = req->GetBody();
bodySize = bodyStream->Size();
o_assert(bodySize > 0);
bodyStream->Open(OpenMode::ReadOnly);
bodyDataPtr = bodyStream->MapRead(nullptr);
}
// create a response object, no matter whether the
// send fails or not
Ptr<HTTPProtocol::HTTPResponse> httpResponse = HTTPProtocol::HTTPResponse::Create();
req->SetResponse(httpResponse);
// send the request
BOOL sendResult = WinHttpSendRequest(
hRequest, // hRequest
WINHTTP_NO_ADDITIONAL_HEADERS, // pwszHeaders
0, // dwHeadersLength
(LPVOID) bodyDataPtr, // lpOptional
bodySize, // dwOptionalLength
0, // dwTotoalLength
0); // dwContext
if (sendResult) {
// receive and process response
BOOL recvResult = WinHttpReceiveResponse(hRequest, NULL);
if (recvResult) {
// query the HTTP status code
DWORD dwStatusCode = 0;
DWORD dwTemp = sizeof(dwStatusCode);
WinHttpQueryHeaders(
hRequest,
WINHTTP_QUERY_STATUS_CODE|WINHTTP_QUERY_FLAG_NUMBER,
NULL,
&dwStatusCode,
&dwTemp,
NULL);
httpResponse->SetStatus((IOStatus::Code) dwStatusCode);
// query the response headers required data size
DWORD dwSize = 0;
WinHttpQueryHeaders(hRequest,
WINHTTP_QUERY_RAW_HEADERS_CRLF,
WINHTTP_HEADER_NAME_BY_INDEX,
NULL,
&dwSize,
WINHTTP_NO_HEADER_INDEX);
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
// and get the response headers
LPVOID headerBuffer = Memory::Alloc(dwSize);
BOOL headerResult = WinHttpQueryHeaders(
hRequest,
WINHTTP_QUERY_RAW_HEADERS_CRLF,
WINHTTP_HEADER_NAME_BY_INDEX,
headerBuffer,
&dwSize,
WINHTTP_NO_HEADER_INDEX);
o_assert(headerResult);
// convert from wide and split the header fields
this->stringBuilder.Set(StringConverter::WideToUTF8((const wchar_t*) headerBuffer, dwSize / sizeof(wchar_t)));
Memory::Free(headerBuffer);
Array<String> tokens;
this->stringBuilder.Tokenize("\r\n", tokens);
Map<String, String> fields;
fields.Reserve(tokens.Size());
for (const String& str : tokens) {
const int32 colonIndex = StringBuilder::FindFirstOf(str.AsCStr(), 0, EndOfString, ":");
if (colonIndex != InvalidIndex) {
String key(str.AsCStr(), 0, colonIndex);
String value(str.AsCStr(), colonIndex+2, EndOfString);
fields.Add(key, value);
}
}
httpResponse->SetResponseHeaders(fields);
}
else {
Log::Warn("winURLLoader: failed to extract response header fields!\n");
}
// extract body data
Ptr<MemoryStream> responseBodyStream = MemoryStream::Create();
responseBodyStream->SetURL(req->GetURL());
responseBodyStream->Open(OpenMode::WriteOnly);
DWORD bytesToRead = 0;
do {
// how much data available?
BOOL queryDataResult = WinHttpQueryDataAvailable(hRequest, &bytesToRead);
o_assert(queryDataResult);
if (dwSize > 0) {
uint8* dstPtr = responseBodyStream->MapWrite(bytesToRead);
o_assert(nullptr != dstPtr);
DWORD bytesRead = 0;
BOOL readDataResult = WinHttpReadData(hRequest, dstPtr, bytesToRead, &bytesRead);
o_assert(readDataResult);
o_assert(bytesRead == bytesToRead);
responseBodyStream->UnmapWrite();
}
}
while (bytesToRead > 0);
responseBodyStream->Close();
// extract the Content-Type response header field and set on responseBodyStream
if (httpResponse->GetResponseHeaders().Contains(this->contentTypeString)) {
ContentType contentType(httpResponse->GetResponseHeaders()[this->contentTypeString]);
responseBodyStream->SetContentType(contentType);
}
// ...and finally set the responseBodyStream on the httpResponse
httpResponse->SetBody(responseBodyStream);
// @todo: write error desc to httpResponse if something went wrong
}
else {
Log::Warn("winURLLoader: WinHttpReceiveResponse() failed for '%s'!\n", req->GetURL().AsCStr());
}
}
else {
/// @todo: better error reporting!
Log::Warn("winURLLoader: WinHttpSendRequest() failed for '%s'\n", req->GetURL().AsCStr());
}
// unmap the body data if necessary
if (req->GetBody().isValid()) {
req->GetBody()->Close();
}
// close the request object
WinHttpCloseHandle(hRequest);
}
else {
Log::Warn("winURLLoader: WinHttpOpenRequest() failed for '%s'\n", req->GetURL().AsCStr());
}
}
Log::Info("winURLLoader::doOneRequest() end: %s\n", req->GetURL().AsCStr());
}
//------------------------------------------------------------------------------
HINTERNET
winURLLoader::obtainConnection(const URL& url) {
o_assert(NULL != this->hSession);
const String hostAndPort = url.HostAndPort();
if (this->connections.Contains(hostAndPort)) {
// connection was already established, refresh the timestamp
// and return the connection
connection& con = this->connections[hostAndPort];
con.timeStamp = std::chrono::steady_clock::now();
return con.hConnection;
}
else {
// new connection
connection con;
const WideString host = StringConverter::UTF8ToWide(url.Host());
const String portString = url.Port();
INTERNET_PORT port = INTERNET_DEFAULT_HTTP_PORT;
if (!portString.Empty()) {
port = StringConverter::FromString<int16>(portString);
}
con.hConnection = WinHttpConnect(this->hSession, // hSession
host.AsCStr(), // pswzServerName
port, // nServerPort
0); // dwReserved
if (NULL != con.hConnection) {
con.timeStamp = std::chrono::steady_clock::now();
this->connections.Add(hostAndPort, con);
return con.hConnection;
}
else {
Log::Warn("winURLLoader: failed to connect to '%s'\n", hostAndPort.AsCStr());
return NULL;
}
}
}
//------------------------------------------------------------------------------
void
winURLLoader::garbageCollectConnections() {
std::chrono::steady_clock::time_point curTime = std::chrono::steady_clock::now();
for (int32 i = this->connections.Size() - 1; i >= 0; i--) {
const String key = this->connections.KeyAtIndex(i);
const connection con = this->connections.ValueAtIndex(i);
std::chrono::seconds age = std::chrono::duration_cast<std::chrono::seconds>(curTime - con.timeStamp);
if (age > connectionMaxAge) {
o_assert(NULL != con.hConnection);
WinHttpCloseHandle(con.hConnection);
this->connections.EraseIndex(i);
}
}
}
} // namespace _priv
} // namespace Oryol
<|endoftext|> |
<commit_before>#include "gamelib/components/rendering/SpriteComponent.hpp"
#include "gamelib/core/res/ResourceManager.hpp"
#include "gamelib/core/rendering/RenderSystem.hpp"
#include "gamelib/properties/PropResource.hpp"
#include <SFML/Graphics/Vertex.hpp>
namespace gamelib
{
SpriteComponent::SpriteComponent() :
_ani(this)
{
registerResourceProperty(_props, "sprite", _sprite, PROP_METHOD(_sprite, change), this);
// Don't register these properties, because it can't be guaranteed after serializaion
// that these are loaded _after_ sprite is loaded and therefore overwrite the default
// values.
// That means these properties are unreliable and need extra code to work properly.
// TODO: Fix this
// _props.registerProperty("offset", _ani.ani.offset, 0, _ani.ani.length);
// _props.registerProperty("speed", _ani.ani.speed);
// props->registerProperty("length", ani.length);
}
bool SpriteComponent::_init()
{
if (!RenderComponent::_init())
return false;
if (!_ani._init())
return false;
_system->createNodeMesh(_handle, 4, sf::TriangleStrip);
_system->setNodeMeshSize(_handle, 0); // Don't render anything when no sprite is set
return true;
}
void SpriteComponent::_quit()
{
RenderComponent::_quit();
_ani._quit();
}
void SpriteComponent::setIndex(int index)
{
_ani.ani.setIndex(index);
_updateUV();
}
void SpriteComponent::change(const std::string& fname)
{
change(getSubsystem<ResourceManager>()->get(fname).as<SpriteResource>());
}
void SpriteComponent::change(SpriteResource::Handle sprite)
{
_sprite = sprite;
if (!_sprite)
{
_system->setNodeMeshSize(_handle, 0);
return;
}
_ani.ani = _sprite->ani;
if (_ani.ani.offset < 0)
_ani.ani.randomize();
sf::Vector2f vertices[] = {
sf::Vector2f(0, _sprite->rect.h),
sf::Vector2f(_sprite->rect.w, 0),
sf::Vector2f(_sprite->rect.w, _sprite->rect.h),
};
_system->setNodeOptions(_handle, nullptr, nullptr, nullptr, &_sprite->tex);
_system->updateNodeMesh(_handle, 3, 1, vertices);
_updateUV();
setOrigin(sprite->origin);
}
SpriteResource::Handle SpriteComponent::getSprite() const
{
return _sprite;
}
const std::string& SpriteComponent::getSpriteName() const
{
return _sprite.getResource()->getPath();
}
void SpriteComponent::_updateUV()
{
if (!_sprite)
return;
// Adding this to the tex coords will prevent the 1px border glitch (hopefully)
// https://gamedev.stackexchange.com/a/75244
// https://stackoverflow.com/questions/19611745/opengl-black-lines-in-between-tiles
constexpr float magic = 0.375;
const auto& rect = _sprite->rect;
auto tsize = _sprite->tex->getSize();
int x = rect.x + (int)_ani.ani.offset * rect.w;
int y = (rect.y + (int)(x / tsize.x) * rect.h) % tsize.y;
x = x % tsize.x;
sf::Vector2f uv[] = {
sf::Vector2f(x + magic, y + magic),
sf::Vector2f(x + magic, y + rect.h - magic),
sf::Vector2f(x + rect.w - magic, y + magic),
sf::Vector2f(x + rect.w - magic, y + rect.h - magic),
};
_system->updateNodeMesh(_handle, 4, 0, nullptr, uv);
}
}
<commit_msg>Implement missing functions<commit_after>#include "gamelib/components/rendering/SpriteComponent.hpp"
#include "gamelib/core/res/ResourceManager.hpp"
#include "gamelib/core/rendering/RenderSystem.hpp"
#include "gamelib/properties/PropResource.hpp"
#include <SFML/Graphics/Vertex.hpp>
namespace gamelib
{
SpriteComponent::SpriteComponent() :
_ani(this)
{
registerResourceProperty(_props, "sprite", _sprite, PROP_METHOD(_sprite, change), this);
// Don't register these properties, because it can't be guaranteed after serializaion
// that these are loaded _after_ sprite is loaded and therefore overwrite the default
// values.
// That means these properties are unreliable and need extra code to work properly.
// TODO: Fix this
// _props.registerProperty("offset", _ani.ani.offset, 0, _ani.ani.length);
// _props.registerProperty("speed", _ani.ani.speed);
// props->registerProperty("length", ani.length);
}
bool SpriteComponent::_init()
{
if (!RenderComponent::_init())
return false;
if (!_ani._init())
return false;
_system->createNodeMesh(_handle, 4, sf::TriangleStrip);
_system->setNodeMeshSize(_handle, 0); // Don't render anything when no sprite is set
return true;
}
void SpriteComponent::_quit()
{
RenderComponent::_quit();
_ani._quit();
}
void SpriteComponent::setIndex(int index)
{
_ani.ani.setIndex(index);
_updateUV();
}
void SpriteComponent::change(const std::string& fname)
{
change(getSubsystem<ResourceManager>()->get(fname).as<SpriteResource>());
}
void SpriteComponent::change(SpriteResource::Handle sprite)
{
_sprite = sprite;
if (!_sprite)
{
_system->setNodeMeshSize(_handle, 0);
return;
}
_ani.ani = _sprite->ani;
if (_ani.ani.offset < 0)
_ani.ani.randomize();
sf::Vector2f vertices[] = {
sf::Vector2f(0, _sprite->rect.h),
sf::Vector2f(_sprite->rect.w, 0),
sf::Vector2f(_sprite->rect.w, _sprite->rect.h),
};
_system->setNodeOptions(_handle, nullptr, nullptr, nullptr, &_sprite->tex);
_system->updateNodeMesh(_handle, 3, 1, vertices);
_updateUV();
setOrigin(sprite->origin);
}
SpriteResource::Handle SpriteComponent::getSprite() const
{
return _sprite;
}
const std::string& SpriteComponent::getSpriteName() const
{
return _sprite.getResource()->getPath();
}
void SpriteComponent::_updateUV()
{
if (!_sprite)
return;
// Adding this to the tex coords will prevent the 1px border glitch (hopefully)
// https://gamedev.stackexchange.com/a/75244
// https://stackoverflow.com/questions/19611745/opengl-black-lines-in-between-tiles
constexpr float magic = 0.375;
const auto& rect = _sprite->rect;
auto tsize = _sprite->tex->getSize();
int x = rect.x + (int)_ani.ani.offset * rect.w;
int y = (rect.y + (int)(x / tsize.x) * rect.h) % tsize.y;
x = x % tsize.x;
sf::Vector2f uv[] = {
sf::Vector2f(x + magic, y + magic),
sf::Vector2f(x + magic, y + rect.h - magic),
sf::Vector2f(x + rect.w - magic, y + magic),
sf::Vector2f(x + rect.w - magic, y + rect.h - magic),
};
_system->updateNodeMesh(_handle, 4, 0, nullptr, uv);
}
auto SpriteComponent::getAnimation() const -> const AnimationComponent&
{
return _ani;
}
auto SpriteComponent::getTexture() const -> TextureResource::Handle
{
return _sprite->tex;
}
}
<|endoftext|> |
<commit_before>#include "randomized.hpp"
#include "parallel.hpp"
#include "parallel.cpp"
#include <vector>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <atomic>
//TODO! usa una libreria migliore per random
/**
* Flip a coin until a head is found, then return the number of tails
*/
unsigned long int flipCoinsUntilHeads() {
unsigned long int tails = 0;
while (rand() % 2 == 0) {
tails++;
}
return tails;
}
unsigned long int produceAnEstimate(std::vector<unsigned long long int> const &addends) {
unsigned long int max_tails = 0;
unsigned int n = addends.size();
#pragma omp parallel
{
#pragma omp for
for (unsigned int i=0; i < n; i++) {
if (addends[i] != 0){
unsigned long int new_tails = flipCoinsUntilHeads();
// gcc version
#ifdef __GNUC__
{
// keep trying to write on max_tails if the new result is higher
while (1) {
unsigned long int curr_tails = max_tails;
if (new_tails > curr_tails) {
if (__sync_bool_compare_and_swap(&max_tails, curr_tails, new_tails)) {
break; // swap successful
};
} else {
break;
}
}
}
// not gcc/windows version -> "http://en.cppreference.com/w/cpp/atomic/atomic_compare_exchange"
#else
{
// TODO: compare_and_swap su windows?
#pragma omp critical (max_tails)
{
if (new_tails > max_tails) {
max_tails = new_tails;
}
}
}
#endif
}
}
}
return max_tails;
}
unsigned long long int randomizedSum(std::vector<unsigned long long int> &addends, unsigned int k, unsigned int a, unsigned int d) {
// Estimation
// run produce-an-estimate k times
std::vector<unsigned long int> estimates (k);
for (unsigned int i=0; i < k; i++) {
estimates[i] = produceAnEstimate(addends);
}
// apply formula to find m'
unsigned long int sum_of_estimates = 0;
for (unsigned long int e: estimates) {
sum_of_estimates += e;
}
double E = log(2) * ((double) sum_of_estimates / k);
unsigned long int m = exp(2) * exp(E) + d;
#ifdef DEBUG
// Alternative estimate (using approximate fit)
unsigned long int mm = pow(2.0, (double) sum_of_estimates / k -1 + 0.6667) + d;
unsigned long int actual = 0;
for (unsigned long long int addend: addends) {
if (addend != 0) {
actual++;
}
}
std::cout << "Estimate: " << m << std::endl;
std::cout << "Alternative: " << mm << std::endl;
std::cout << "Actual: " << actual << std::endl;
#endif
// Addition
// initialize space
unsigned long int red_size = m * a;
std::vector<unsigned long long int> reduced_vector (red_size, 0);
// memory marking
unsigned int n = addends.size();
#pragma omp parallel
{
#pragma omp for
for (unsigned int i=0; i < n; i++) {
if (addends[i] != 0) {
// keep trying to write on new vector
bool done = false;
while (!done) {
unsigned int index = rand() % red_size;
#ifdef __GNUC__
if (reduced_vector[index] == 0) {
if (__sync_bool_compare_and_swap(&reduced_vector[index], 0, addends[i])) {
done = true;
}
}
#else
// TODO: compare_and_swap su windows?
#pragma omp critical(reduced_vector)
{
if (reduced_vector[index] == 0) {
reduced_vector[index] = addends[i];
done = true;
}
}
#endif
}
}
}
}
// parallel sum
unsigned long long int sum = parallelSum(reduced_vector);
return sum;
}
<commit_msg>Added TRNG headers<commit_after>#include "randomized.hpp"
#include "parallel.hpp"
#include "parallel.cpp"
#include <vector>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <trng/yarn2.hpp>
#include <trng/uniform01_dist.hpp>
/**
* Flip a coin until a head is found, then return the number of tails
*/
unsigned long int flipCoinsUntilHeads() {
unsigned long int tails = 0;
while (rand() % 2 == 0) {
tails++;
}
return tails;
}
unsigned long int produceAnEstimate(std::vector<unsigned long long int> const &addends) {
unsigned long int max_tails = 0;
unsigned int n = addends.size();
#pragma omp parallel
{
#pragma omp for
for (unsigned int i=0; i < n; i++) {
if (addends[i] != 0){
unsigned long int new_tails = flipCoinsUntilHeads();
// gcc version
#ifdef __GNUC__
{
// keep trying to write on max_tails if the new result is higher
while (1) {
unsigned long int curr_tails = max_tails;
if (new_tails > curr_tails) {
if (__sync_bool_compare_and_swap(&max_tails, curr_tails, new_tails)) {
break; // swap successful
};
} else {
break;
}
}
}
// without gcc
#else
{
#pragma omp critical (max_tails)
{
if (new_tails > max_tails) {
max_tails = new_tails;
}
}
}
#endif
}
}
}
return max_tails;
}
unsigned long long int randomizedSum(std::vector<unsigned long long int> &addends, unsigned int k, unsigned int a, unsigned int d) {
// Estimation
// run produce-an-estimate k times
std::vector<unsigned long int> estimates (k);
for (unsigned int i=0; i < k; i++) {
estimates[i] = produceAnEstimate(addends);
}
// apply formula to find m'
unsigned long int sum_of_estimates = 0;
for (unsigned long int e: estimates) {
sum_of_estimates += e;
}
double E = log(2) * ((double) sum_of_estimates / k);
unsigned long int m = exp(2) * exp(E) + d;
#ifdef DEBUG
// Alternative estimate (using approximate fit)
unsigned long int mm = pow(2.0, (double) sum_of_estimates / k -1 + 0.6667) + d;
unsigned long int actual = 0;
for (unsigned long long int addend: addends) {
if (addend != 0) {
actual++;
}
}
std::cout << "Estimate: " << m << std::endl;
std::cout << "Alternative: " << mm << std::endl;
std::cout << "Actual: " << actual << std::endl;
#endif
// Addition
// initialize space
unsigned long int red_size = m * a;
std::vector<unsigned long long int> reduced_vector (red_size, 0);
// memory marking
unsigned int n = addends.size();
#pragma omp parallel
{
#pragma omp for
for (unsigned int i=0; i < n; i++) {
if (addends[i] != 0) {
// keep trying to write on new vector
bool done = false;
while (!done) {
unsigned int index = rand() % red_size;
// gcc version
#ifdef __GNUC__
if (reduced_vector[index] == 0) {
if (__sync_bool_compare_and_swap(&reduced_vector[index], 0, addends[i])) {
done = true;
}
}
// without gcc
#else
#pragma omp critical(reduced_vector)
{
if (reduced_vector[index] == 0) {
reduced_vector[index] = addends[i];
done = true;
}
}
#endif
}
}
}
}
// parallel sum
unsigned long long int sum = parallelSum(reduced_vector);
return sum;
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <float.h>
#ifdef WIN32
#include <windows.h>
#endif
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include "raytracing.h"
//temporary variables
//these are only used to illustrate
//a simple debug drawing. A ray
Vec3Df testRayOrigin;
Vec3Df testRayDestination;
Vec3Df testColor;
//use this function for any preprocessing of the mesh.
void init()
{
//load the mesh file
//please realize that not all OBJ files will successfully load.
//Nonetheless, if they come from Blender, they should, if they
//are exported as WavefrontOBJ.
//PLEASE ADAPT THE LINE BELOW TO THE FULL PATH OF THE dodgeColorTest.obj
//model, e.g., "C:/temp/myData/GraphicsIsFun/dodgeColorTest.obj",
//otherwise the application will not load properly
MyMesh.loadMesh(FILE_LOCATION, true);
MyMesh.computeVertexNormals();
//one first move: initialize the first light source
//at least ONE light source has to be in the scene!!!
//here, we set it to the current location of the camera
MyLightPositions.push_back(MyCameraPosition);
}
//return the color of your pixel.
Vec3Df performRayTracing(const Vec3Df & origin, const Vec3Df & dest)
{
int level = 0;
return trace(origin, dest, level);
// if(intersect(level, ray, max, &hit)) {
// Shade(level, hit, &color);
// }
// else
// color=BackgroundColor
//return Vec3Df(dest[0],dest[1],dest[2]);
}
Vec3Df trace(const Vec3Df & origin, const Vec3Df & dir, int level){
float depth = FLT_MAX;
Vec3Df color = Vec3Df(0, 0, 0);
for (int i = 0; i < MyMesh.triangles.size(); i++){
Triangle triangle = MyMesh.triangles.at(i);
Vertex v0 = MyMesh.vertices.at(triangle.v[0]);
Vertex v1 = MyMesh.vertices.at(triangle.v[1]);
Vertex v2 = MyMesh.vertices.at(triangle.v[2]);
Vec3Df N = Vec3Df(0, 0, 0);
Vec3Df intersection = rayTriangleIntersect(origin, dir, v0.p, v1.p, v2.p, depth, N);
if (!isNulVector(intersection)){
// save color and depth
color = shade(dir, intersection, level, i, N);
}
}
return color;
}
Vec3Df shade(const Vec3Df dir, const Vec3Df intersection, int level, int triangleIndex, const Vec3Df N){
Vec3Df color = Vec3Df(0, 0, 0);
Vec3Df lightDirection = Vec3Df(0, 0, 0);
//lightDirection = lightVector(intersection, origin);
color += diffuse(dir, N, triangleIndex);
color += ambient(dir, intersection, level, triangleIndex);
color += speculair(dir, intersection, level, triangleIndex);
return color;
}
Vec3Df diffuse(const Vec3Df lightSource, const Vec3Df normal, int triangleIndex){
Vec3Df color = Vec3Df(0, 0, 0);
unsigned int triMat = MyMesh.triangleMaterials.at(triangleIndex);
color = MyMesh.materials.at(triMat).Kd();
// diffuser = Kd * dot(lightsource, normal) * Od * Ld
// Od = object color
// Ld = lightSource color
//Vec3Df diffuser = color * (Vec3Df::dotProduct(lightSource, normal)) / pow(normal.getLength(), 2) * 1 * 1;
return color;
}
Vec3Df ambient(const Vec3Df dir, const Vec3Df intersection, int level, int triangleIndex){
Vec3Df color = Vec3Df(0, 0, 0);
unsigned int triMat = MyMesh.triangleMaterials.at(triangleIndex);
color = MyMesh.materials.at(triMat).Ka();
return color;
}
Vec3Df speculair(const Vec3Df dir, const Vec3Df intersection, int level, int triangleIndex){
Vec3Df color = Vec3Df(0, 0, 0);
unsigned int triMat = MyMesh.triangleMaterials.at(triangleIndex);
color = MyMesh.materials.at(triMat).Ks();
return color;
}
Vec3Df lightVector(const Vec3Df point, const Vec3Df lightPoint){
Vec3Df lightDir = Vec3Df(0, 0, 0);
lightDir = lightPoint - point;
return lightDir;
}
Vec3Df reflectionVector(const Vec3Df lightDirection, const Vec3Df normalVector) {
Vec3Df reflection = Vec3Df(0, 0, 0);
reflection = lightDirection - 2 * (Vec3Df::dotProduct(lightDirection, normalVector) / pow(normalVector.getLength(), 2))*normalVector;
return reflection;
}
// We can also add textures!
// The source of this function is:
// http://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/ray-triangle-intersection-geometric-solution
// Returns the point of intersection
Vec3Df rayTriangleIntersect(const Vec3Df &orig, const Vec3Df &dir, const Vec3Df v0, const Vec3Df v1, const Vec3Df v2, float &depth, Vec3Df &N)
{
Vec3Df nulVector = Vec3Df(0, 0, 0);
// compute plane's normal
Vec3Df v0v1 = v1 - v0;
Vec3Df v0v2 = v2 - v0;
// no need to normalize
N = Vec3Df::crossProduct(v0v1, v0v2); // N
// Step 1: finding P (the point where the ray intersects the plane)
// check if ray and plane are parallel ?
float NdotRayDirection = Vec3Df::dotProduct(N, dir);
if (fabs(NdotRayDirection) < 0.000000001) // almost 0
return nulVector; // they are parallel so they don't intersect !
// compute d parameter using equation 2 (d is the distance from the origin (0, 0, 0) to the plane)
float d = Vec3Df::dotProduct(N, v0);
// compute t (equation 3) (t is distance from the ray origin to P)
float t = (-Vec3Df::dotProduct(N, orig) + d) / NdotRayDirection;
// check if the triangle is in behind the ray
if (t < 0) return nulVector; // the triangle is behind
if (t > depth) return nulVector; // already have something closerby
// compute the intersection point P using equation 1
Vec3Df P = orig + t * dir;
// Step 2: inside-outside test
Vec3Df C; // vector perpendicular to triangle's plane
// edge 0
Vec3Df edge0 = v1 - v0;
Vec3Df vp0 = P - v0;
C = Vec3Df::crossProduct(edge0, vp0);
if (Vec3Df::dotProduct(N, C) < 0) return nulVector; // P is on the right side
// edge 1
Vec3Df edge1 = v2 - v1;
Vec3Df vp1 = P - v1;
C = Vec3Df::crossProduct(edge1, vp1);
if (Vec3Df::dotProduct(N, C) < 0) return nulVector; // P is on the right side
// edge 2
Vec3Df edge2 = v0 - v2;
Vec3Df vp2 = P - v2;
C = Vec3Df::crossProduct(edge2, vp2);
if (Vec3Df::dotProduct(N, C) < 0) return nulVector; // P is on the right side;
depth = t;
return P; // this is the intersectionpoint
}
//Shade(level, hit, &color){
// for each lightsource
// ComputeDirectLight(hit, &directColor);
// if(material reflects && (level < maxLevel))
// computeReflectedRay(hit, &reflectedray);
// Trace(level+1, reflectedRay, &reflectedColor);
// color = directColor + reflection * reflectedcolor + transmission * refractedColor;
//}
void yourDebugDraw()
{
//draw open gl debug stuff
//this function is called every frame
//let's draw the mesh
MyMesh.draw();
//let's draw the lights in the scene as points
glPushAttrib(GL_ALL_ATTRIB_BITS); //store all GL attributes
glDisable(GL_LIGHTING);
glColor3f(1, 1, 1);
glPointSize(10);
glBegin(GL_POINTS);
for (int i = 0; i<MyLightPositions.size(); ++i)
glVertex3fv(MyLightPositions[i].pointer());
glEnd();
glPopAttrib();//restore all GL attributes
//The Attrib commands maintain the state.
//e.g., even though inside the two calls, we set
//the color to white, it will be reset to the previous
//state after the pop.
//as an example: we draw the test ray, which is set by the keyboard function
glPushAttrib(GL_ALL_ATTRIB_BITS);
glDisable(GL_LIGHTING);
glBegin(GL_LINES);
glColor3f(testColor[0], testColor[1], testColor[2]);
glVertex3f(testRayOrigin[0], testRayOrigin[1], testRayOrigin[2]);
glColor3f(testColor[0], testColor[1], testColor[2]);
glVertex3f(testRayDestination[0], testRayDestination[1], testRayDestination[2]);
glEnd();
glPointSize(10);
glBegin(GL_POINTS);
glVertex3fv(MyLightPositions[0].pointer());
glEnd();
glPopAttrib();
//draw whatever else you want...
////glutSolidSphere(1,10,10);
////allows you to draw a sphere at the origin.
////using a glTranslate, it can be shifted to whereever you want
////if you produce a sphere renderer, this
////triangulated sphere is nice for the preview
}
//yourKeyboardFunc is used to deal with keyboard input.
//t is the character that was pressed
//x,y is the mouse position in pixels
//rayOrigin, rayDestination is the ray that is going in the view direction UNDERNEATH your mouse position.
//
//A few keys are already reserved:
//'L' adds a light positioned at the camera location to the MyLightPositions vector
//'l' modifies the last added light to the current
// camera position (by default, there is only one light, so move it with l)
// ATTENTION These lights do NOT affect the real-time rendering.
// You should use them for the raytracing.
//'r' calls the function performRaytracing on EVERY pixel, using the correct associated ray.
// It then stores the result in an image "result.ppm".
// Initially, this function is fast (performRaytracing simply returns
// the target of the ray - see the code above), but once you replaced
// this function and raytracing is in place, it might take a
// while to complete...
void yourKeyboardFunc(char t, int x, int y, const Vec3Df & rayOrigin, const Vec3Df & rayDestination)
{
//here, as an example, I use the ray to fill in the values for my upper global ray variable
//I use these variables in the debugDraw function to draw the corresponding ray.
//try it: Press a key, move the camera, see the ray that was launched as a line.
testRayOrigin = rayOrigin;
testRayDestination = rayDestination;
testColor = performRayTracing(rayOrigin, rayDestination);
std::cout << " The color from the ray is " << testColor[0] << "," << testColor[1] << "," << testColor[2] << std::endl;
// do here, whatever you want with the keyboard input t.
// Trace(0, ray, &color);
// PutPixel(x, y, color);
std::cout << t << " pressed! The mouse was in location " << x << "," << y << "!" << std::endl;
}
bool isNulVector(Vec3Df vector){
Vec3Df nullVector = Vec3Df(0, 0, 0);
return vector == nullVector;
}
// Pseudocode From slides
//RayTrace (view)
//{
// for (y=0; y<view.yres; ++y){
// for(x=0; x<view.xres; ++x){
// ComputeRay(x, y, view, &ray);
// Trace(0, ray, &color);
// PutPixel(x, y, color);
// }
// }
//}
//
//Trace( level, ray, &color){
// if(intersect(level, ray, max, &hit)) {
// Shade(level, hit, &color);
// }
// else
// color=BackgroundColor
//}
//
//Shade(level, hit, &color){
// for each lightsource
// ComputeDirectLight(hit, &directColor);
// if(material reflects && (level < maxLevel))
// computeReflectedRay(hit, &reflectedray);
// Trace(level+1, reflectedRay, &reflectedColor);
// color = directColor + reflection * reflectedcolor + transmission * refractedColor;
//}
<commit_msg>Added debug and formula of ambient shading<commit_after>#include <stdio.h>
#include <float.h>
#ifdef WIN32
#include <windows.h>
#endif
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include "raytracing.h"
//temporary variables
//these are only used to illustrate
//a simple debug drawing. A ray
Vec3Df testRayOrigin;
Vec3Df testRayDestination;
Vec3Df testColor;
//use this function for any preprocessing of the mesh.
void init()
{
//load the mesh file
//please realize that not all OBJ files will successfully load.
//Nonetheless, if they come from Blender, they should, if they
//are exported as WavefrontOBJ.
//PLEASE ADAPT THE LINE BELOW TO THE FULL PATH OF THE dodgeColorTest.obj
//model, e.g., "C:/temp/myData/GraphicsIsFun/dodgeColorTest.obj",
//otherwise the application will not load properly
MyMesh.loadMesh(FILE_LOCATION, true);
MyMesh.computeVertexNormals();
//one first move: initialize the first light source
//at least ONE light source has to be in the scene!!!
//here, we set it to the current location of the camera
MyLightPositions.push_back(MyCameraPosition);
}
//return the color of your pixel.
Vec3Df performRayTracing(const Vec3Df & origin, const Vec3Df & dest)
{
int level = 0;
return trace(origin, dest, level);
// if(intersect(level, ray, max, &hit)) {
// Shade(level, hit, &color);
// }
// else
// color=BackgroundColor
//return Vec3Df(dest[0],dest[1],dest[2]);
}
Vec3Df trace(const Vec3Df & origin, const Vec3Df & dir, int level){
float depth = FLT_MAX;
Vec3Df color = Vec3Df(0, 0, 0);
for (int i = 0; i < MyMesh.triangles.size(); i++){
Triangle triangle = MyMesh.triangles.at(i);
Vertex v0 = MyMesh.vertices.at(triangle.v[0]);
Vertex v1 = MyMesh.vertices.at(triangle.v[1]);
Vertex v2 = MyMesh.vertices.at(triangle.v[2]);
Vec3Df N = Vec3Df(0, 0, 0);
Vec3Df intersection = rayTriangleIntersect(origin, dir, v0.p, v1.p, v2.p, depth, N);
if (!isNulVector(intersection)){
// save color and depth
color = shade(dir, intersection, level, i, N);
}
}
return color;
}
Vec3Df shade(const Vec3Df dir, const Vec3Df intersection, int level, int triangleIndex, const Vec3Df N){
Vec3Df color = Vec3Df(0, 0, 0);
Vec3Df lightDirection = Vec3Df(0, 0, 0);
//lightDirection = lightVector(intersection, origin);
color += diffuse(dir, N, triangleIndex);
color += ambient(dir, intersection, level, triangleIndex);
color += speculair(dir, intersection, level, triangleIndex);
return color;
}
Vec3Df diffuse(const Vec3Df lightSource, const Vec3Df normal, int triangleIndex){
Vec3Df color = Vec3Df(0, 0, 0);
unsigned int triMat = MyMesh.triangleMaterials.at(triangleIndex);
color = MyMesh.materials.at(triMat).Kd();
// diffuser = Kd * dot(lightsource, normal) * Od * Ld
// Od = object color
// Ld = lightSource color
//Vec3Df diffuser = color * (Vec3Df::dotProduct(lightSource, normal)) / pow(normal.getLength(), 2) * 1 * 1;
return color;
}
Vec3Df ambient(const Vec3Df dir, const Vec3Df intersection, int level, int triangleIndex){
Vec3Df color = Vec3Df(0, 0, 0);
unsigned int triMat = MyMesh.triangleMaterials.at(triangleIndex);
// ambient = Ka * Ia
// where Ka is surface property, Ia is light property
Vec3Df ka = MyMesh.materials.at(triMat).Ka();
std::cout << "Mesh properties are : " << ka[0] << "," << ka[1] << "," << ka[2] << std::endl;
// the Ka mesh properties of cube.obj and wollahberggeit.obj are 0?
//color = MyMesh.materials.at(triMat).Ka();
return color;
}
Vec3Df speculair(const Vec3Df dir, const Vec3Df intersection, int level, int triangleIndex){
Vec3Df color = Vec3Df(0, 0, 0);
unsigned int triMat = MyMesh.triangleMaterials.at(triangleIndex);
color = MyMesh.materials.at(triMat).Ks();
return color;
}
Vec3Df lightVector(const Vec3Df point, const Vec3Df lightPoint){
Vec3Df lightDir = Vec3Df(0, 0, 0);
lightDir = lightPoint - point;
return lightDir;
}
Vec3Df reflectionVector(const Vec3Df lightDirection, const Vec3Df normalVector) {
Vec3Df reflection = Vec3Df(0, 0, 0);
reflection = lightDirection - 2 * (Vec3Df::dotProduct(lightDirection, normalVector) / pow(normalVector.getLength(), 2))*normalVector;
return reflection;
}
// We can also add textures!
// The source of this function is:
// http://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/ray-triangle-intersection-geometric-solution
// Returns the point of intersection
Vec3Df rayTriangleIntersect(const Vec3Df &orig, const Vec3Df &dir, const Vec3Df v0, const Vec3Df v1, const Vec3Df v2, float &depth, Vec3Df &N)
{
Vec3Df nulVector = Vec3Df(0, 0, 0);
// compute plane's normal
Vec3Df v0v1 = v1 - v0;
Vec3Df v0v2 = v2 - v0;
// no need to normalize
N = Vec3Df::crossProduct(v0v1, v0v2); // N
// Step 1: finding P (the point where the ray intersects the plane)
// check if ray and plane are parallel ?
float NdotRayDirection = Vec3Df::dotProduct(N, dir);
if (fabs(NdotRayDirection) < 0.000000001) // almost 0
return nulVector; // they are parallel so they don't intersect !
// compute d parameter using equation 2 (d is the distance from the origin (0, 0, 0) to the plane)
float d = Vec3Df::dotProduct(N, v0);
// compute t (equation 3) (t is distance from the ray origin to P)
float t = (-Vec3Df::dotProduct(N, orig) + d) / NdotRayDirection;
// check if the triangle is in behind the ray
if (t < 0) return nulVector; // the triangle is behind
if (t > depth) return nulVector; // already have something closerby
// compute the intersection point P using equation 1
Vec3Df P = orig + t * dir;
// Step 2: inside-outside test
Vec3Df C; // vector perpendicular to triangle's plane
// edge 0
Vec3Df edge0 = v1 - v0;
Vec3Df vp0 = P - v0;
C = Vec3Df::crossProduct(edge0, vp0);
if (Vec3Df::dotProduct(N, C) < 0) return nulVector; // P is on the right side
// edge 1
Vec3Df edge1 = v2 - v1;
Vec3Df vp1 = P - v1;
C = Vec3Df::crossProduct(edge1, vp1);
if (Vec3Df::dotProduct(N, C) < 0) return nulVector; // P is on the right side
// edge 2
Vec3Df edge2 = v0 - v2;
Vec3Df vp2 = P - v2;
C = Vec3Df::crossProduct(edge2, vp2);
if (Vec3Df::dotProduct(N, C) < 0) return nulVector; // P is on the right side;
depth = t;
return P; // this is the intersectionpoint
}
//Shade(level, hit, &color){
// for each lightsource
// ComputeDirectLight(hit, &directColor);
// if(material reflects && (level < maxLevel))
// computeReflectedRay(hit, &reflectedray);
// Trace(level+1, reflectedRay, &reflectedColor);
// color = directColor + reflection * reflectedcolor + transmission * refractedColor;
//}
void yourDebugDraw()
{
//draw open gl debug stuff
//this function is called every frame
//let's draw the mesh
MyMesh.draw();
//let's draw the lights in the scene as points
glPushAttrib(GL_ALL_ATTRIB_BITS); //store all GL attributes
glDisable(GL_LIGHTING);
glColor3f(1, 1, 1);
glPointSize(10);
glBegin(GL_POINTS);
for (int i = 0; i<MyLightPositions.size(); ++i)
glVertex3fv(MyLightPositions[i].pointer());
glEnd();
glPopAttrib();//restore all GL attributes
//The Attrib commands maintain the state.
//e.g., even though inside the two calls, we set
//the color to white, it will be reset to the previous
//state after the pop.
//as an example: we draw the test ray, which is set by the keyboard function
glPushAttrib(GL_ALL_ATTRIB_BITS);
glDisable(GL_LIGHTING);
glBegin(GL_LINES);
glColor3f(testColor[0], testColor[1], testColor[2]);
glVertex3f(testRayOrigin[0], testRayOrigin[1], testRayOrigin[2]);
glColor3f(testColor[0], testColor[1], testColor[2]);
glVertex3f(testRayDestination[0], testRayDestination[1], testRayDestination[2]);
glEnd();
glPointSize(10);
glBegin(GL_POINTS);
glVertex3fv(MyLightPositions[0].pointer());
glEnd();
glPopAttrib();
//draw whatever else you want...
////glutSolidSphere(1,10,10);
////allows you to draw a sphere at the origin.
////using a glTranslate, it can be shifted to whereever you want
////if you produce a sphere renderer, this
////triangulated sphere is nice for the preview
}
//yourKeyboardFunc is used to deal with keyboard input.
//t is the character that was pressed
//x,y is the mouse position in pixels
//rayOrigin, rayDestination is the ray that is going in the view direction UNDERNEATH your mouse position.
//
//A few keys are already reserved:
//'L' adds a light positioned at the camera location to the MyLightPositions vector
//'l' modifies the last added light to the current
// camera position (by default, there is only one light, so move it with l)
// ATTENTION These lights do NOT affect the real-time rendering.
// You should use them for the raytracing.
//'r' calls the function performRaytracing on EVERY pixel, using the correct associated ray.
// It then stores the result in an image "result.ppm".
// Initially, this function is fast (performRaytracing simply returns
// the target of the ray - see the code above), but once you replaced
// this function and raytracing is in place, it might take a
// while to complete...
void yourKeyboardFunc(char t, int x, int y, const Vec3Df & rayOrigin, const Vec3Df & rayDestination)
{
//here, as an example, I use the ray to fill in the values for my upper global ray variable
//I use these variables in the debugDraw function to draw the corresponding ray.
//try it: Press a key, move the camera, see the ray that was launched as a line.
testRayOrigin = rayOrigin;
testRayDestination = rayDestination;
testColor = performRayTracing(rayOrigin, rayDestination);
std::cout << " The color from the ray is " << testColor[0] << "," << testColor[1] << "," << testColor[2] << std::endl;
// do here, whatever you want with the keyboard input t.
// Trace(0, ray, &color);
// PutPixel(x, y, color);
std::cout << t << " pressed! The mouse was in location " << x << "," << y << "!" << std::endl;
}
bool isNulVector(Vec3Df vector){
Vec3Df nullVector = Vec3Df(0, 0, 0);
return vector == nullVector;
}
// Pseudocode From slides
//RayTrace (view)
//{
// for (y=0; y<view.yres; ++y){
// for(x=0; x<view.xres; ++x){
// ComputeRay(x, y, view, &ray);
// Trace(0, ray, &color);
// PutPixel(x, y, color);
// }
// }
//}
//
//Trace( level, ray, &color){
// if(intersect(level, ray, max, &hit)) {
// Shade(level, hit, &color);
// }
// else
// color=BackgroundColor
//}
//
//Shade(level, hit, &color){
// for each lightsource
// ComputeDirectLight(hit, &directColor);
// if(material reflects && (level < maxLevel))
// computeReflectedRay(hit, &reflectedray);
// Trace(level+1, reflectedRay, &reflectedColor);
// color = directColor + reflection * reflectedcolor + transmission * refractedColor;
//}
<|endoftext|> |
<commit_before>#include "vec3.hpp"
#include "mat4.hpp"
#include "Transform.hpp"
#include "Sphere.hpp"
#include "Plane.hpp"
#include <vector>
#include "zlib.h"
#include "png.h"
#include <stdint.h>
#include <memory>
#include "Sampling.hpp"
#include "Renderable.hpp"
#include "PerspectiveCamera.hpp"
#include "Image.hpp"
#include "Sample.hpp"
static const int SamplesPerPixel = 64;
static const int ImageWidth = 800;
static const int ImageHeight = 600;
static const int maxDepth = 5;
static int save_png_to_file(const char *path);
void readpng_version_info();
void generate_samples(std::vector<Sample>& samples, const RNG& rng);
vec3 brdf(const vec3& wo, const vec3& wi, const vec3& color)
{
return color * float(M_1_PI);
}
int main(int argc, char* argv[])
{
//Create the image
Image render(ImageWidth, ImageHeight);
//Samples
RNG rng;
std::vector<Sample> image_samples;
image_samples.reserve((ImageWidth) * (ImageHeight) * SamplesPerPixel);
//Generate image samples
generate_samples(image_samples, rng);
// Setup camera
Transform worldToCamera = Transform::lookat(vec3(0.0f, 0.0f, -200.0f), vec3(), vec3(0.0f, 1.0f, 0.0f));
float aspectRatio = render.getAspectRatio();
float hFOV = degreeToRadians(66.0f); //degrees
float vFOV = 2 * atan(tan(hFOV / 2) * aspectRatio);
float yScale = 1.0f / tan(vFOV / 2);
float xScale = yScale / aspectRatio;
float near = 0.1f; float far = 1000.0f;
float right = near / xScale;
float left = -right;
float top = -near / yScale;
float bottom = -top;
std::unique_ptr<Camera> cam( new PerspectiveCamera(inv(worldToCamera),worldToCamera, left, right, top, bottom,
near, far, float(ImageWidth), float(ImageHeight)));
//readpng_version_info();
// Setup scene
std::vector<std::shared_ptr<Renderable> > objects;
objects.reserve(10);
//Add a sphere
Transform transformSphere = Transform::translate(100.0, -100.0f, 150.0f);
std::shared_ptr<Sphere> sphere(new Sphere(transformSphere, inv(transformSphere), 100.0f));
std::shared_ptr<Material> whiteMat(new Material(vec3(1.0f, 1.0f, 1.0f)));
std::shared_ptr<Plane> plane(new Plane(vec3(0.0, 0.0f, 200.0f), vec3(0.0f, 0.0f, -1.0f))); //Back wall
std::shared_ptr<Plane> plane1(new Plane(vec3(0.0, 200.0f, 0.0f), vec3(0.0f, -1.0f, 0.0f))); //Ceiling
std::shared_ptr<Plane> plane2(new Plane(vec3(0.0, -200.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f))); //Floot
std::shared_ptr<Plane> plane3(new Plane(vec3(-200.0, 0.0f, 0.0f), vec3(1.0f, 0.0f, 0.0f))); //Left Wall
std::shared_ptr<Plane> plane4(new Plane(vec3(200.0, 0.0f, 0.0f), vec3(-1.0f, 0.0f, 0.0f))); //Right Wall
std::shared_ptr<Material> blueMat(new Material(vec3(0.0f, 0.0f, 1.0f)));
std::shared_ptr<Material> redMat(new Material(vec3(1.0f, 0.0f, 0.0f)));
std::shared_ptr<Material> greenMat(new Material(vec3(0.0f, 1.0f, 0.0f)));
objects.push_back(std::shared_ptr<Renderable>(new Renderable(sphere, whiteMat)));
objects.push_back(std::shared_ptr<Renderable>(new Renderable(plane, whiteMat)));
objects.push_back(std::shared_ptr<Renderable>(new Renderable(plane1, whiteMat)));
objects.push_back(std::shared_ptr<Renderable>(new Renderable(plane2, whiteMat)));
objects.push_back(std::shared_ptr<Renderable>(new Renderable(plane3, redMat)));
objects.push_back(std::shared_ptr<Renderable>(new Renderable(plane4, greenMat)));
std::shared_ptr<Intersection> intersection(new Intersection());
Intersection trueIntersection;
vec3 light(0.0, 190.0f, 100.0f);
bool hit;
unsigned int counter = 0;
float lightIntensity = 10000.0f;
unsigned int tnSamples = ImageWidth * ImageHeight * SamplesPerPixel;
for each(auto& sample in image_samples)
{
int numHit = 0;
Ray ray = cam->generateRay(sample.imageX, sample.imageY);
//fprintf(stderr, "Casting ray in dir: %f,%f,%f \n", ray.dir.x, ray.dir.y, ray.dir.z);
float tHit = std::numeric_limits<float>::infinity();
for each(auto& surf in objects)
{
float tObj = 0;
hit = surf->intersect(ray, &tObj, intersection);
if (hit == false) continue;
numHit += 1;
if (tObj < tHit)
{
trueIntersection = *intersection;
tHit = tObj;
}
}
if (numHit == 0)
{
//imag
render.addSample(sample, vec3());
continue;
}
//One bounce?
//fprintf(stderr, "Number of objects hit: %i\n", numHit);
vec3 L = normalize(light - trueIntersection.ls->p);
float d = (light - trueIntersection.ls->p).length(); d *= d;
float ndl = dot(trueIntersection.ls->n, L);
float lterm = std::max(ndl, 0.0f);
vec3 color = brdf(vec3(), vec3(), trueIntersection.material->getColor());
float rr = color.x * lterm * (lightIntensity / d);
float gg = color.y * lterm * (lightIntensity / d);
float bb = color.z * lterm * (lightIntensity / d);
vec3 dddd(1.0, 1.0f, 1.0f);
vec3 oldNorm = trueIntersection.ls->n;
vec3 oldColor = color;
for (int k = 0; k < maxDepth; ++k)
{
vec3 newRayDir = normalize(cosineSampleHemisphere(rng.nextFloat(), rng.nextFloat()));
float pdf = cosineHemispherePdf(abs(newRayDir.z), 0.0f);
vec3 n = trueIntersection.ls->n;
vec3 dpdu = trueIntersection.ls->dpdu;
vec3 last = normalize(cross(n, dpdu));
Transform world2Shading = Transform::worldToShading(n, dpdu, last);
Transform shading2World = inv(world2Shading);
newRayDir = shading2World.transformVector(newRayDir);
Ray newRay(trueIntersection.ls->p, newRayDir, tHit + 0.0001f);
float v = abs(dot(oldNorm, newRayDir));
dddd.x *= v * oldColor.x / pdf;
dddd.y *= v * oldColor.y / pdf;
dddd.z *= v * oldColor.z / pdf;
numHit = 0;
tHit = std::numeric_limits<float>::infinity();
for each(auto& surf in objects)
{
float tObj = 0;
hit = surf->intersect(newRay, &tObj, intersection);
if (hit == false) continue;
numHit += 1;
if (tObj < tHit)
{
trueIntersection = *intersection;
tHit = tObj;
}
}
if (numHit == 0)
{
break;
}
L = normalize(light - trueIntersection.ls->p);
d = (light - trueIntersection.ls->p).length(); d *= d;
vec3 norm = trueIntersection.ls->n;
ndl = dot(norm, L);
lterm = std::max(ndl, 0.0f);
color = brdf(vec3(), vec3(), trueIntersection.material->getColor());
rr += color.x * color.x * lterm * (lightIntensity / d) * dddd.x;
gg += color.y * color.y * lterm * (lightIntensity / d) * dddd.y;
bb += color.z * color.z * lterm * (lightIntensity / d) * dddd.z;
oldNorm = norm;
oldColor = color;
}
render.addSample(sample, vec3(rr, gg, bb));
++counter;
if (counter % 5000 == 0)
{
float progress = float(counter) / float(tnSamples);
progress *= 100.0f;
printf("We are on ray number %u counter and %f percent done\n", counter, progress);
}
}
render.saveImage("render.png");
}
//
//int save_png_to_file(const char *path)
//{
// FILE * fp;
// png_structp png_ptr = NULL;
// png_infop info_ptr = NULL;
// size_t x, y;
// png_byte ** row_pointers = NULL;
// /* "status" contains the return value of this function. At first
// it is set to a value which means 'failure'. When the routine
// has finished its work, it is set to a value which means
// 'success'. */
// int status = -1;
// /* The following number is set by trial and error only. I cannot
// see where it it is documented in the libpng manual.
// */
// int pixel_size = 3;
// int depth = 8;
//
// fp = fopen(path, "wb");
// if (!fp) {
// goto fopen_failed;
// }
//
// png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
// if (png_ptr == NULL) {
// goto png_create_write_struct_failed;
// }
//
// info_ptr = png_create_info_struct(png_ptr);
// if (info_ptr == NULL) {
// goto png_create_info_struct_failed;
// }
//
// /* Set up error handling. */
//
// if (setjmp(png_jmpbuf(png_ptr))) {
// goto png_failure;
// }
//
// /* Set image attributes. */
//
// png_set_IHDR(png_ptr,
// info_ptr,
// IMWIDTH,
// IMHEIGHT,
// depth,
// PNG_COLOR_TYPE_RGB,
// PNG_INTERLACE_NONE,
// PNG_COMPRESSION_TYPE_DEFAULT,
// PNG_FILTER_TYPE_DEFAULT);
//
// /* Initialize rows of PNG. */
//
// row_pointers = (png_bytepp)png_malloc(png_ptr, IMHEIGHT * sizeof(png_byte *));
// for (y = 0; y < IMHEIGHT; ++y) {
// png_byte *row =
// (png_bytep)png_malloc(png_ptr, sizeof(uint8_t) * IMWIDTH * pixel_size);
// row_pointers[y] = row;
// for (x = 0; x < IMWIDTH; ++x) {
// *row++ = g_red[y * IMWIDTH + x];
// *row++ = g_green[y * IMWIDTH + x];
// *row++ = g_blue[y * IMWIDTH + x];
// }
// }
//
// /* Write the image data to "fp". */
//
// png_init_io(png_ptr, fp);
// png_set_rows(png_ptr, info_ptr, row_pointers);
// png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
//
// /* The routine has successfully written the file, so we set
// "status" to a value which indicates success. */
//
// status = 0;
//
// for (y = 0; y < IMHEIGHT; y++) {
// png_free(png_ptr, row_pointers[y]);
// }
// png_free(png_ptr, row_pointers);
//
//png_failure:
//png_create_info_struct_failed:
// png_destroy_write_struct(&png_ptr, &info_ptr);
//png_create_write_struct_failed:
// fclose(fp);
//fopen_failed:
// return status;
//}
void readpng_version_info()
{
fprintf(stderr, " Compiled with libpng %s; using libpng %s.\n",
PNG_LIBPNG_VER_STRING, png_libpng_ver);
fprintf(stderr, " Compiled with zlib %s; using zlib %s.\n",
ZLIB_VERSION, zlib_version);
}
void generate_samples(std::vector<Sample>& samples, const RNG& rng)
{
std::vector<float> rawSamples;
rawSamples.reserve(SamplesPerPixel * 2);
int spp2 = SamplesPerPixel / 2;
for (int y = 0; y < ImageHeight + 1; ++y)
{
for (int x = 0; x < ImageWidth + 1; ++x)
{
stratified2D(spp2, spp2, true, rawSamples, rng);
for (int i = 0; i < SamplesPerPixel; ++i)
{
float tmpx = rawSamples[i * 2];
float tmpy = rawSamples[i * 2 + 1];
samples.push_back(Sample(tmpx + x, tmpy + y));
}
rawSamples.clear();
}
}
}<commit_msg>Commiting chagnges before branching to threading.<commit_after>#include "vec3.hpp"
#include "mat4.hpp"
#include "Transform.hpp"
#include "Sphere.hpp"
#include "Plane.hpp"
#include <vector>
#include "zlib.h"
#include "png.h"
#include <stdint.h>
#include <memory>
#include "Sampling.hpp"
#include "Renderable.hpp"
#include "PerspectiveCamera.hpp"
#include "Image.hpp"
#include "Sample.hpp"
static const int SamplesPerPixel = 4;
static const int ImageWidth = 800;
static const int ImageHeight = 600;
static const int maxDepth = 5;
static int save_png_to_file(const char *path);
void readpng_version_info();
void generate_samples(std::vector<Sample>& samples, const RNG& rng);
vec3 brdf(const vec3& wo, const vec3& wi, const vec3& color)
{
return color * float(M_1_PI);
}
int main(int argc, char* argv[])
{
//Create the image
Image render(ImageWidth, ImageHeight);
//Samples
RNG rng;
std::vector<Sample> image_samples;
image_samples.reserve((ImageWidth) * (ImageHeight) * SamplesPerPixel);
//Generate image samples
generate_samples(image_samples, rng);
// Setup camera
Transform worldToCamera = Transform::lookat(vec3(0.0f, 0.0f, -200.0f), vec3(), vec3(0.0f, 1.0f, 0.0f));
float aspectRatio = render.getAspectRatio();
float hFOV = degreeToRadians(66.0f); //degrees
float vFOV = 2 * atan(tan(hFOV / 2) * aspectRatio);
float yScale = 1.0f / tan(vFOV / 2);
float xScale = yScale / aspectRatio;
float near = 0.1f; float far = 1000.0f;
float right = near / xScale;
float left = -right;
float top = -near / yScale;
float bottom = -top;
std::unique_ptr<Camera> cam( new PerspectiveCamera(inv(worldToCamera),worldToCamera, left, right, top, bottom,
near, far, float(ImageWidth), float(ImageHeight)));
//readpng_version_info();
// Setup scene
std::vector<std::shared_ptr<Renderable> > objects;
objects.reserve(10);
//Add a sphere
Transform transformSphere = Transform::translate(100.0, -100.0f, 150.0f);
std::shared_ptr<Sphere> sphere(new Sphere(transformSphere, inv(transformSphere), 100.0f));
std::shared_ptr<Material> whiteMat(new Material(vec3(1.0f, 1.0f, 1.0f)));
std::shared_ptr<Plane> plane(new Plane(vec3(0.0, 0.0f, 200.0f), vec3(0.0f, 0.0f, -1.0f))); //Back wall
std::shared_ptr<Plane> plane1(new Plane(vec3(0.0, 200.0f, 0.0f), vec3(0.0f, -1.0f, 0.0f))); //Ceiling
std::shared_ptr<Plane> plane2(new Plane(vec3(0.0, -200.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f))); //Floot
std::shared_ptr<Plane> plane3(new Plane(vec3(-200.0, 0.0f, 0.0f), vec3(1.0f, 0.0f, 0.0f))); //Left Wall
std::shared_ptr<Plane> plane4(new Plane(vec3(200.0, 0.0f, 0.0f), vec3(-1.0f, 0.0f, 0.0f))); //Right Wall
std::shared_ptr<Material> blueMat(new Material(vec3(0.0f, 0.0f, 1.0f)));
std::shared_ptr<Material> redMat(new Material(vec3(1.0f, 0.0f, 0.0f)));
std::shared_ptr<Material> greenMat(new Material(vec3(0.0f, 1.0f, 0.0f)));
objects.push_back(std::shared_ptr<Renderable>(new Renderable(sphere, whiteMat)));
objects.push_back(std::shared_ptr<Renderable>(new Renderable(plane, whiteMat)));
objects.push_back(std::shared_ptr<Renderable>(new Renderable(plane1, whiteMat)));
objects.push_back(std::shared_ptr<Renderable>(new Renderable(plane2, whiteMat)));
objects.push_back(std::shared_ptr<Renderable>(new Renderable(plane3, redMat)));
objects.push_back(std::shared_ptr<Renderable>(new Renderable(plane4, greenMat)));
std::shared_ptr<Intersection> intersection(new Intersection());
Intersection trueIntersection;
vec3 light(0.0, 190.0f, 100.0f);
bool hit;
unsigned int counter = 0;
float lightIntensity = 10000.0f;
unsigned int tnSamples = ImageWidth * ImageHeight * SamplesPerPixel;
for each(auto& sample in image_samples)
{
int numHit = 0;
Ray ray = cam->generateRay(sample.imageX, sample.imageY);
//fprintf(stderr, "Casting ray in dir: %f,%f,%f \n", ray.dir.x, ray.dir.y, ray.dir.z);
float tHit = std::numeric_limits<float>::infinity();
for each(auto& surf in objects)
{
float tObj = 0;
hit = surf->intersect(ray, &tObj, intersection);
if (hit == false) continue;
numHit += 1;
if (tObj < tHit)
{
trueIntersection = *intersection;
tHit = tObj;
}
}
if (numHit == 0)
{
//imag
render.addSample(sample, vec3());
continue;
}
//One bounce?
//fprintf(stderr, "Number of objects hit: %i\n", numHit);
vec3 L = normalize(light - trueIntersection.ls->p);
float d = (light - trueIntersection.ls->p).length(); d *= d;
float ndl = dot(trueIntersection.ls->n, L);
float lterm = std::max(ndl, 0.0f);
vec3 color = brdf(vec3(), vec3(), trueIntersection.material->getColor());
float rr = color.x * lterm * (lightIntensity / d);
float gg = color.y * lterm * (lightIntensity / d);
float bb = color.z * lterm * (lightIntensity / d);
vec3 dddd(1.0, 1.0f, 1.0f);
vec3 oldNorm = trueIntersection.ls->n;
vec3 oldColor = color;
for (int k = 0; k < maxDepth; ++k)
{
vec3 newRayDir = normalize(cosineSampleHemisphere(rng.nextFloat(), rng.nextFloat()));
float pdf = cosineHemispherePdf(abs(newRayDir.z), 0.0f);
vec3 n = trueIntersection.ls->n;
vec3 dpdu = trueIntersection.ls->dpdu;
vec3 last = normalize(cross(n, dpdu));
Transform world2Shading = Transform::worldToShading(n, dpdu, last);
Transform shading2World = inv(world2Shading);
newRayDir = shading2World.transformVector(newRayDir);
Ray newRay(trueIntersection.ls->p, newRayDir, tHit + 0.0001f);
float v = abs(dot(oldNorm, newRayDir));
dddd.x *= v * oldColor.x / pdf;
dddd.y *= v * oldColor.y / pdf;
dddd.z *= v * oldColor.z / pdf;
numHit = 0;
tHit = std::numeric_limits<float>::infinity();
for each(auto& surf in objects)
{
float tObj = 0;
hit = surf->intersect(newRay, &tObj, intersection);
if (hit == false) continue;
numHit += 1;
if (tObj < tHit)
{
trueIntersection = *intersection;
tHit = tObj;
}
}
if (numHit == 0)
{
break;
}
L = normalize(light - trueIntersection.ls->p);
d = (light - trueIntersection.ls->p).length(); d *= d;
vec3 norm = trueIntersection.ls->n;
ndl = dot(norm, L);
lterm = std::max(ndl, 0.0f);
color = brdf(vec3(), vec3(), trueIntersection.material->getColor());
rr += color.x * color.x * lterm * (lightIntensity / d) * dddd.x;
gg += color.y * color.y * lterm * (lightIntensity / d) * dddd.y;
bb += color.z * color.z * lterm * (lightIntensity / d) * dddd.z;
oldNorm = norm;
oldColor = color;
}
render.addSample(sample, vec3(rr, gg, bb));
++counter;
if (counter % 5000 == 0)
{
float progress = float(counter) / float(tnSamples);
progress *= 100.0f;
printf("We are on ray number %u counter and %f percent done\n", counter, progress);
}
}
render.saveImage("render.png");
}
//
//int save_png_to_file(const char *path)
//{
// FILE * fp;
// png_structp png_ptr = NULL;
// png_infop info_ptr = NULL;
// size_t x, y;
// png_byte ** row_pointers = NULL;
// /* "status" contains the return value of this function. At first
// it is set to a value which means 'failure'. When the routine
// has finished its work, it is set to a value which means
// 'success'. */
// int status = -1;
// /* The following number is set by trial and error only. I cannot
// see where it it is documented in the libpng manual.
// */
// int pixel_size = 3;
// int depth = 8;
//
// fp = fopen(path, "wb");
// if (!fp) {
// goto fopen_failed;
// }
//
// png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
// if (png_ptr == NULL) {
// goto png_create_write_struct_failed;
// }
//
// info_ptr = png_create_info_struct(png_ptr);
// if (info_ptr == NULL) {
// goto png_create_info_struct_failed;
// }
//
// /* Set up error handling. */
//
// if (setjmp(png_jmpbuf(png_ptr))) {
// goto png_failure;
// }
//
// /* Set image attributes. */
//
// png_set_IHDR(png_ptr,
// info_ptr,
// IMWIDTH,
// IMHEIGHT,
// depth,
// PNG_COLOR_TYPE_RGB,
// PNG_INTERLACE_NONE,
// PNG_COMPRESSION_TYPE_DEFAULT,
// PNG_FILTER_TYPE_DEFAULT);
//
// /* Initialize rows of PNG. */
//
// row_pointers = (png_bytepp)png_malloc(png_ptr, IMHEIGHT * sizeof(png_byte *));
// for (y = 0; y < IMHEIGHT; ++y) {
// png_byte *row =
// (png_bytep)png_malloc(png_ptr, sizeof(uint8_t) * IMWIDTH * pixel_size);
// row_pointers[y] = row;
// for (x = 0; x < IMWIDTH; ++x) {
// *row++ = g_red[y * IMWIDTH + x];
// *row++ = g_green[y * IMWIDTH + x];
// *row++ = g_blue[y * IMWIDTH + x];
// }
// }
//
// /* Write the image data to "fp". */
//
// png_init_io(png_ptr, fp);
// png_set_rows(png_ptr, info_ptr, row_pointers);
// png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
//
// /* The routine has successfully written the file, so we set
// "status" to a value which indicates success. */
//
// status = 0;
//
// for (y = 0; y < IMHEIGHT; y++) {
// png_free(png_ptr, row_pointers[y]);
// }
// png_free(png_ptr, row_pointers);
//
//png_failure:
//png_create_info_struct_failed:
// png_destroy_write_struct(&png_ptr, &info_ptr);
//png_create_write_struct_failed:
// fclose(fp);
//fopen_failed:
// return status;
//}
void readpng_version_info()
{
fprintf(stderr, " Compiled with libpng %s; using libpng %s.\n",
PNG_LIBPNG_VER_STRING, png_libpng_ver);
fprintf(stderr, " Compiled with zlib %s; using zlib %s.\n",
ZLIB_VERSION, zlib_version);
}
void generate_samples(std::vector<Sample>& samples, const RNG& rng)
{
std::vector<float> rawSamples;
rawSamples.reserve(SamplesPerPixel * 2);
int spp2 = SamplesPerPixel / 2;
for (int y = 0; y < ImageHeight + 1; ++y)
{
for (int x = 0; x < ImageWidth + 1; ++x)
{
stratified2D(spp2, spp2, true, rawSamples, rng);
for (int i = 0; i < SamplesPerPixel; ++i)
{
float tmpx = rawSamples[i * 2];
float tmpy = rawSamples[i * 2 + 1];
samples.push_back(Sample(tmpx + x, tmpy + y));
}
rawSamples.clear();
}
}
}<|endoftext|> |
<commit_before>#include "DualExActor_Tests.h"
#include "cryptoTools/Network/Endpoint.h"
#include "Common.h"
#include "cryptoTools/Common/Defines.h"
#include "DualEx/DualExActor.h"
#include "cryptoTools/Network/Channel.h"
#include "cryptoTools/Common/Log.h"
#include "DebugCircuits.h"
//#include "MyAssert.h"
#include <array>
using namespace osuCrypto;
void DualExActor_BitAdder_Complete_Test_Impl()
{
u64 numExe = 32,
bucketSize = 4,
numOpened = 4,
psiSecParam = 40;
setThreadName("Actor1");
//InitDebugPrinting("..\\test.out");
Circuit c = AdderCircuit(4);
//NetworkManager netMgr0("127.0.0.1", 1212, 4, true);
//NetworkManager netMgr1("127.0.0.1", 1212, 4, false);
std::string name("ss");
IOService ios(0);
Endpoint ep0(ios, "localhost", 1212, EpMode::Server, name);
Endpoint ep1(ios, "localhost", 1212, EpMode::Server, name);
//Channel& recvChannel = ep1.addChannel(name, name);
//Channel& senderChannel = ep0.addChannel(name, name);
{
PRNG prng0(_mm_set_epi32(4253465, 3434565, 234435, 23987045));
PRNG prng1(prng0.get<block>());
BitVector input0(4);
*input0.data() = 2;
BitVector input1(4);
*input1.data() = 3;
BitVector expected(5);
*expected.data() = 5;
auto thrd = std::thread([&]() {
setThreadName("Actor0");
DualExActor actor0(c, Role::First, numExe, bucketSize, numOpened, psiSecParam, ep0);
Timer timer;
actor0.init(prng0, 4, 1, bucketSize, timer);
for (u64 i = 0; i < numExe; ++i)
{
BitVector output = actor0.execute(i, prng0, input0, timer);
for (u64 b = 0; b < expected.size(); ++b)
if (output[b] != expected[b])
{
//std::cout << input0 << " " << input1 << " " << expected << std::endl;
//std::cout << "but got " << output << std::endl;
throw UnitTestFail();
}
}
});
DualExActor actor1(c, Role::Second, numExe, bucketSize, numOpened, psiSecParam, ep1);
Timer timer;
actor1.init(prng1, 4, 1, bucketSize, timer);
for (u64 i = 0; i < numExe; ++i)
{
BitVector output = actor1.execute(i, prng1, input1, timer);
for (u64 b = 0; b < expected.size(); ++b)
if (output[b] != expected[b])
throw UnitTestFail();
}
thrd.join();
}
ep0.stop();
ep1.stop();
ios.stop();
}
void DualExActor_BitAdder_Concurrent_Test_Impl()
{
u64 numExe = 32,
bucketSize = 4,
numOpened = 4,
numConcurEvals = 4,
psiSecParam = 40;
setThreadName("Actor1");
//InitDebugPrinting("..\\test.out");
Circuit c = AdderCircuit(4);
std::string name("ss");
IOService ios(0);
Endpoint ep0(ios, "localhost", 1212, EpMode::Server, name);
Endpoint ep1(ios, "localhost", 1212, EpMode::Server, name);
//Channel& recvChannel = ep1.addChannel(name, name);
//Channel& senderChannel = ep0.addChannel(name, name);
{
PRNG prng0(_mm_set_epi32(4253465, 3434565, 234435, 23987045));
PRNG prng1(prng0.get<block>());
BitVector input0(4);
*input0.data() = 2;
BitVector input1(4);
*input1.data() = 3;
BitVector expected(5);
*expected.data() = 5;
auto thrd = std::thread([&]() {
setThreadName("Actor0");
DualExActor actor0(c, Role::First, numExe, bucketSize, numOpened, psiSecParam, ep0);
Timer timer;
actor0.init(prng0, 4, numConcurEvals, bucketSize, timer);
std::vector<std::thread> evalThreads(numConcurEvals);
for (u64 j = 0; j < numConcurEvals; ++j)
{
block seed = prng0.get<block>();
evalThreads[j] = std::thread([&, j, seed]() {
Timer timerj;
PRNG prng(seed);
for (u64 i = j; i < numExe; i += numConcurEvals)
{
BitVector output = actor0.execute(i, prng, input0, timerj);
for (u64 b = 0; b < expected.size(); ++b)
if (output[b] != expected[b])
throw UnitTestFail();
}
});
}
for (auto& evalThrd : evalThreads)
evalThrd.join();
});
DualExActor actor1(c, Role::Second, numExe, bucketSize, numOpened, psiSecParam, ep1);
Timer timer;
actor1.init(prng1, 4, numConcurEvals, bucketSize, timer);
std::vector<std::thread> evalThreads(numConcurEvals);
for (u64 j = 0; j < numConcurEvals; ++j)
{
block seed = prng1.get<block>();
evalThreads[j] = std::thread([&actor1, j, seed, numExe, numConcurEvals, &input1, &expected]() {
Timer timerj;
PRNG prng(seed);
for (u64 i = j; i < numExe; i += numConcurEvals)
{
BitVector output = actor1.execute(i, prng, input1, timerj);
for (u64 b = 0; b < expected.size(); ++b)
if (output[b] != expected[b])
throw UnitTestFail();
}
});
}
for (auto& evalThrd : evalThreads)
evalThrd.join();
thrd.join();
}
ep0.stop();
ep1.stop();
ios.stop();
}
<commit_msg>unit test fix<commit_after>#include "DualExActor_Tests.h"
#include "cryptoTools/Network/Endpoint.h"
#include "Common.h"
#include "cryptoTools/Common/Defines.h"
#include "DualEx/DualExActor.h"
#include "cryptoTools/Network/Channel.h"
#include "cryptoTools/Common/Log.h"
#include "DebugCircuits.h"
//#include "MyAssert.h"
#include <array>
using namespace osuCrypto;
void DualExActor_BitAdder_Complete_Test_Impl()
{
u64 numExe = 32,
bucketSize = 4,
numOpened = 4,
psiSecParam = 40;
setThreadName("Actor1");
//InitDebugPrinting("..\\test.out");
Circuit c = AdderCircuit(4);
//NetworkManager netMgr0("127.0.0.1", 1212, 4, true);
//NetworkManager netMgr1("127.0.0.1", 1212, 4, false);
std::string name("ss");
IOService ios(0);
Endpoint ep0(ios, "localhost", 1212, EpMode::Server, name);
Endpoint ep1(ios, "localhost", 1212, EpMode::Client, name);
//Channel& recvChannel = ep1.addChannel(name, name);
//Channel& senderChannel = ep0.addChannel(name, name);
{
PRNG prng0(_mm_set_epi32(4253465, 3434565, 234435, 23987045));
PRNG prng1(prng0.get<block>());
BitVector input0(4);
*input0.data() = 2;
BitVector input1(4);
*input1.data() = 3;
BitVector expected(5);
*expected.data() = 5;
auto thrd = std::thread([&]() {
setThreadName("Actor0");
DualExActor actor0(c, Role::First, numExe, bucketSize, numOpened, psiSecParam, ep0);
Timer timer;
actor0.init(prng0, 4, 1, bucketSize, timer);
for (u64 i = 0; i < numExe; ++i)
{
BitVector output = actor0.execute(i, prng0, input0, timer);
for (u64 b = 0; b < expected.size(); ++b)
if (output[b] != expected[b])
{
//std::cout << input0 << " " << input1 << " " << expected << std::endl;
//std::cout << "but got " << output << std::endl;
throw UnitTestFail();
}
}
});
DualExActor actor1(c, Role::Second, numExe, bucketSize, numOpened, psiSecParam, ep1);
Timer timer;
actor1.init(prng1, 4, 1, bucketSize, timer);
for (u64 i = 0; i < numExe; ++i)
{
BitVector output = actor1.execute(i, prng1, input1, timer);
for (u64 b = 0; b < expected.size(); ++b)
if (output[b] != expected[b])
throw UnitTestFail();
}
thrd.join();
}
ep0.stop();
ep1.stop();
ios.stop();
}
void DualExActor_BitAdder_Concurrent_Test_Impl()
{
u64 numExe = 32,
bucketSize = 4,
numOpened = 4,
numConcurEvals = 4,
psiSecParam = 40;
setThreadName("Actor1");
//InitDebugPrinting("..\\test.out");
Circuit c = AdderCircuit(4);
std::string name("ss");
IOService ios(0);
Endpoint ep0(ios, "localhost", 1212, EpMode::Server, name);
Endpoint ep1(ios, "localhost", 1212, EpMode::Client, name);
//Channel& recvChannel = ep1.addChannel(name, name);
//Channel& senderChannel = ep0.addChannel(name, name);
{
PRNG prng0(_mm_set_epi32(4253465, 3434565, 234435, 23987045));
PRNG prng1(prng0.get<block>());
BitVector input0(4);
*input0.data() = 2;
BitVector input1(4);
*input1.data() = 3;
BitVector expected(5);
*expected.data() = 5;
auto thrd = std::thread([&]() {
setThreadName("Actor0");
DualExActor actor0(c, Role::First, numExe, bucketSize, numOpened, psiSecParam, ep0);
Timer timer;
actor0.init(prng0, 4, numConcurEvals, bucketSize, timer);
std::vector<std::thread> evalThreads(numConcurEvals);
for (u64 j = 0; j < numConcurEvals; ++j)
{
block seed = prng0.get<block>();
evalThreads[j] = std::thread([&, j, seed]() {
Timer timerj;
PRNG prng(seed);
for (u64 i = j; i < numExe; i += numConcurEvals)
{
BitVector output = actor0.execute(i, prng, input0, timerj);
for (u64 b = 0; b < expected.size(); ++b)
if (output[b] != expected[b])
throw UnitTestFail();
}
});
}
for (auto& evalThrd : evalThreads)
evalThrd.join();
});
DualExActor actor1(c, Role::Second, numExe, bucketSize, numOpened, psiSecParam, ep1);
Timer timer;
actor1.init(prng1, 4, numConcurEvals, bucketSize, timer);
std::vector<std::thread> evalThreads(numConcurEvals);
for (u64 j = 0; j < numConcurEvals; ++j)
{
block seed = prng1.get<block>();
evalThreads[j] = std::thread([&actor1, j, seed, numExe, numConcurEvals, &input1, &expected]() {
Timer timerj;
PRNG prng(seed);
for (u64 i = j; i < numExe; i += numConcurEvals)
{
BitVector output = actor1.execute(i, prng, input1, timerj);
for (u64 b = 0; b < expected.size(); ++b)
if (output[b] != expected[b])
throw UnitTestFail();
}
});
}
for (auto& evalThrd : evalThreads)
evalThrd.join();
thrd.join();
}
}
<|endoftext|> |
<commit_before>// Copyright 2012-2013 Samplecount S.L.
//
// 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 "Methcla/Audio/Engine.hpp"
#include "Methcla/Audio/Group.hpp"
using namespace Methcla::Audio;
#define METHCLA_ASSERT_NODE_IS_BLANK(node) \
BOOST_ASSERT(node != nullptr); \
BOOST_ASSERT(node->m_parent == nullptr); \
BOOST_ASSERT(node->m_prev == nullptr); \
BOOST_ASSERT(node->m_next == nullptr); \
#define METHCLA_ASSERT_NODE_IS_LINKED(node) \
BOOST_ASSERT(m_first != nullptr); \
BOOST_ASSERT(m_last != nullptr); \
BOOST_ASSERT(node->m_prev != nullptr || node == m_first); \
BOOST_ASSERT(node->m_next != nullptr || node == m_last); \
BOOST_ASSERT(m_first != m_last || (m_first == node && node == m_last));
Group::Group(Environment& env, NodeId nodeId)
: Node(env, nodeId)
, m_first(nullptr)
, m_last(nullptr)
{
}
Group::~Group()
{
freeAll();
}
Group* Group::construct(Environment& env, NodeId nodeId)
{
return new (env.rtMem().alloc(sizeof(Group))) Group(env, nodeId);
}
void Group::doProcess(size_t numFrames)
{
Node* node = m_first;
while (node != nullptr) {
// Store pointer to next node because current node might be destroyed by done action after process.
Node* nextNode = node->m_next;
node->process(numFrames);
node = nextNode;
}
}
void Group::addToHead(Node* node)
{
assert(node != nullptr);
assert(node->parent() == nullptr);
assert(node->m_prev == nullptr);
assert(node->m_next == nullptr);
node->m_parent = this;
node->m_next = m_first;
if (m_first != nullptr) {
m_first->m_prev = node;
}
m_first = node;
if (m_last == nullptr) {
m_last = node;
}
}
void Group::addToTail(Node* node)
{
assert(node != nullptr);
assert(node->parent() == nullptr);
assert(node->m_prev == nullptr);
assert(node->m_next == nullptr);
node->m_parent = this;
node->m_prev = m_last;
if (m_last != nullptr) {
m_last->m_next = node;
}
m_last = node;
if (m_first == nullptr) {
m_first = node;
}
}
void Group::addBefore(Node* target, Node* node)
{
BOOST_ASSERT(target != nullptr);
BOOST_ASSERT(target->parent() == this);
METHCLA_ASSERT_NODE_IS_BLANK(node);
node->m_parent = this;
node->m_prev = target->m_prev;
target->m_prev = node;
node->m_next = target;
if (target == m_first) {
BOOST_ASSERT(node->m_prev == nullptr);
m_first = node;
} else {
BOOST_ASSERT(node->m_prev != nullptr);
node->m_prev->m_next = node;
}
METHCLA_ASSERT_NODE_IS_LINKED(node);
}
void Group::addAfter(Node* target, Node* node)
{
BOOST_ASSERT(target != nullptr);
BOOST_ASSERT(target->parent() == this);
METHCLA_ASSERT_NODE_IS_BLANK(node);
node->m_parent = this;
node->m_next = target->m_next;
target->m_next = node;
node->m_prev = target;
if (target == m_last) {
BOOST_ASSERT(node->m_next == nullptr);
m_last = node;
} else {
BOOST_ASSERT(node->m_next != nullptr);
node->m_next->m_prev = node;
}
METHCLA_ASSERT_NODE_IS_LINKED(node);
}
void Group::remove(Node* node)
{
assert(node != nullptr);
assert(node->parent() == this);
assert( (node == m_first && node == m_last && node->m_prev == nullptr && node->m_next == nullptr)
|| !((node->m_prev == nullptr) && (node->m_next == nullptr)) );
Node* prev = node->m_prev;
Node* next = node->m_next;
if (node == m_first)
{
assert( prev == nullptr );
m_first = next;
if (m_first != nullptr)
m_first->m_prev = nullptr;
}
else
{
prev->m_next = next;
}
if (node == m_last)
{
assert( next == nullptr );
m_last = prev;
if (m_last != nullptr)
m_last->m_next = nullptr;
}
else
{
next->m_prev = prev;
}
node->m_parent = nullptr;
node->m_prev = nullptr;
node->m_next = nullptr;
}
bool Group::isEmpty() const
{
return m_first == nullptr;
}
void Group::freeAll()
{
Node* node = m_first;
while (node != nullptr) {
// Store pointer to next node because current node might be destroyed by done action after process.
Node* nextNode = node->m_next;
node->free();
node = nextNode;
}
}
<commit_msg>Use BOOST_ASSERT instead of assert<commit_after>// Copyright 2012-2013 Samplecount S.L.
//
// 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 "Methcla/Audio/Engine.hpp"
#include "Methcla/Audio/Group.hpp"
using namespace Methcla::Audio;
#define METHCLA_ASSERT_NODE_IS_BLANK(node) \
BOOST_ASSERT(node != nullptr); \
BOOST_ASSERT(node->m_parent == nullptr); \
BOOST_ASSERT(node->m_prev == nullptr); \
BOOST_ASSERT(node->m_next == nullptr); \
#define METHCLA_ASSERT_NODE_IS_LINKED(node) \
BOOST_ASSERT(m_first != nullptr); \
BOOST_ASSERT(m_last != nullptr); \
BOOST_ASSERT(node->m_prev != nullptr || node == m_first); \
BOOST_ASSERT(node->m_next != nullptr || node == m_last); \
BOOST_ASSERT(m_first != m_last || (m_first == node && node == m_last));
Group::Group(Environment& env, NodeId nodeId)
: Node(env, nodeId)
, m_first(nullptr)
, m_last(nullptr)
{
}
Group::~Group()
{
freeAll();
}
Group* Group::construct(Environment& env, NodeId nodeId)
{
return new (env.rtMem().alloc(sizeof(Group))) Group(env, nodeId);
}
void Group::doProcess(size_t numFrames)
{
Node* node = m_first;
while (node != nullptr) {
// Store pointer to next node because current node might be destroyed by done action after process.
Node* nextNode = node->m_next;
node->process(numFrames);
node = nextNode;
}
}
void Group::addToHead(Node* node)
{
METHCLA_ASSERT_NODE_IS_BLANK(node);
node->m_parent = this;
node->m_next = m_first;
if (m_first != nullptr) {
m_first->m_prev = node;
}
m_first = node;
if (m_last == nullptr) {
m_last = node;
}
METHCLA_ASSERT_NODE_IS_LINKED(node);
}
void Group::addToTail(Node* node)
{
METHCLA_ASSERT_NODE_IS_BLANK(node);
node->m_parent = this;
node->m_prev = m_last;
if (m_last != nullptr) {
m_last->m_next = node;
}
m_last = node;
if (m_first == nullptr) {
m_first = node;
}
METHCLA_ASSERT_NODE_IS_LINKED(node);
}
void Group::addBefore(Node* target, Node* node)
{
BOOST_ASSERT(target != nullptr);
BOOST_ASSERT(target->parent() == this);
METHCLA_ASSERT_NODE_IS_BLANK(node);
node->m_parent = this;
node->m_prev = target->m_prev;
target->m_prev = node;
node->m_next = target;
if (target == m_first) {
BOOST_ASSERT(node->m_prev == nullptr);
m_first = node;
} else {
BOOST_ASSERT(node->m_prev != nullptr);
node->m_prev->m_next = node;
}
METHCLA_ASSERT_NODE_IS_LINKED(node);
}
void Group::addAfter(Node* target, Node* node)
{
BOOST_ASSERT(target != nullptr);
BOOST_ASSERT(target->parent() == this);
METHCLA_ASSERT_NODE_IS_BLANK(node);
node->m_parent = this;
node->m_next = target->m_next;
target->m_next = node;
node->m_prev = target;
if (target == m_last) {
BOOST_ASSERT(node->m_next == nullptr);
m_last = node;
} else {
BOOST_ASSERT(node->m_next != nullptr);
node->m_next->m_prev = node;
}
METHCLA_ASSERT_NODE_IS_LINKED(node);
}
void Group::remove(Node* node)
{
BOOST_ASSERT(node != nullptr);
BOOST_ASSERT(node->parent() == this);
BOOST_ASSERT( (node == m_first && node == m_last && node->m_prev == nullptr && node->m_next == nullptr)
|| !((node->m_prev == nullptr) && (node->m_next == nullptr)) );
if (node == m_first) {
BOOST_ASSERT(node->m_prev == nullptr);
m_first = node->m_next;
if (m_first != nullptr) {
m_first->m_prev = nullptr;
}
} else {
node->m_prev->m_next = node->m_next;
}
if (node == m_last) {
BOOST_ASSERT(node->m_next == nullptr);
m_last = node->m_prev;
if (m_last != nullptr) {
m_last->m_next = nullptr;
}
} else {
node->m_next->m_prev = node->m_prev;
}
node->m_parent = nullptr;
node->m_prev = nullptr;
node->m_next = nullptr;
}
bool Group::isEmpty() const
{
return m_first == nullptr;
}
void Group::freeAll()
{
Node* node = m_first;
while (node != nullptr) {
// Store pointer to next node because current node might be destroyed by done action after process.
Node* nextNode = node->m_next;
node->free();
node = nextNode;
}
}
<|endoftext|> |
<commit_before>#include <libdariadb/storage/memstorage.h>
#include <memory>
#include <unordered_map>
#include <stx/btree_map.h>
using namespace dariadb;
using namespace dariadb::storage;
/**
Map:
id ->
hash:
step-> Chunk{from,to,step,data_array}
*/
struct MemChunk {
Time from;
Time to;
Time step;
MeasArray values;
};
using MemChunk_Ptr = std::shared_ptr<MemChunk>;
using Step2Chunk = std::unordered_map<Time, MemChunk_Ptr>;
using Id2Step = stx::btree_map<Id, Step2Chunk>;
struct MemStorage::Private : public IMeasStorage {
Private(const MemStorage::Params &p) {}
virtual Time minTime() override { return Time(); }
virtual Time maxTime() override { return Time(); }
virtual bool minMaxTime(dariadb::Id id, dariadb::Time *minResult,
dariadb::Time *maxResult) override {
return false;
}
virtual void foreach (const QueryInterval &q, IReaderClb * clbk) override {}
virtual Id2Meas readTimePoint(const QueryTimePoint &q) override { return Id2Meas(); }
virtual Id2Meas currentValue(const IdArray &ids, const Flag &flag) override {
return Id2Meas();
}
append_result append(const MeasArray & values) {
return append_result();
}
append_result append(const Meas &value) override{
return append_result();
}
void flush() override{
}
void foreach(const QueryTimePoint &q, IReaderClb *clbk) override{
}
MeasList readInterval(const QueryInterval &q) override{
return MeasList{};
}
Id2Step _id2steps;
};
MemStorage::MemStorage(const MemStorage::Params &p) : _impl(new MemStorage::Private(p)) {}
MemStorage::~MemStorage() {
_impl = nullptr;
}
Time dariadb::storage::MemStorage::minTime() {
return _impl->minTime();
}
Time dariadb::storage::MemStorage::maxTime() {
return _impl->maxTime();
}
bool dariadb::storage::MemStorage::minMaxTime(dariadb::Id id, dariadb::Time *minResult,
dariadb::Time *maxResult) {
return _impl->minMaxTime(id,minResult, maxResult);
}
void dariadb::storage::MemStorage::foreach (const QueryInterval &q, IReaderClb * clbk) {
_impl->foreach(q, clbk);
}
Id2Meas dariadb::storage::MemStorage::readTimePoint(const QueryTimePoint &q) {
return _impl->readTimePoint(q);
}
Id2Meas dariadb::storage::MemStorage::currentValue(const IdArray &ids, const Flag &flag) {
return _impl->currentValue(ids, flag);
}
append_result dariadb::storage::MemStorage::append(const Meas &value){
return _impl->append(value);
}
void dariadb::storage::MemStorage::flush(){
_impl->flush();
}
<commit_msg>time track.<commit_after>#include <libdariadb/storage/memstorage.h>
#include <memory>
#include <unordered_map>
#include <stx/btree_map.h>
using namespace dariadb;
using namespace dariadb::storage;
/**
Map:
QueryId -> TimeTrack{ from,to,step MemChunkList[MemChunk{data}]}
*/
struct MemChunk {
static const size_t MAX_MEM_CHUNK_SIZE = 512;
std::array<Meas, MAX_MEM_CHUNK_SIZE> values;
};
using MemChunk_Ptr = std::shared_ptr<MemChunk>;
using MemChunkList = std::list<MemChunk_Ptr>;
struct TimeTrack {
TimeTrack(const Time _step, const Id _meas_id, const Time _from, const Time _to) {
step = _step;
meas_id = _meas_id;
from = _from;
to = _to;
}
Id meas_id;
Time step;
Time from;
Time to;
MemChunkList chunks;
};
using TimeTrack_ptr = std::shared_ptr<TimeTrack>;
using Id2Track = stx::btree_map<Id, TimeTrack_ptr>;
struct MemStorage::Private : public IMeasStorage {
Private(const MemStorage::Params &p) {}
virtual Time minTime() override { return Time(); }
virtual Time maxTime() override { return Time(); }
virtual bool minMaxTime(dariadb::Id id, dariadb::Time *minResult,
dariadb::Time *maxResult) override {
return false;
}
virtual void foreach (const QueryInterval &q, IReaderClb * clbk) override {}
virtual Id2Meas readTimePoint(const QueryTimePoint &q) override { return Id2Meas(); }
virtual Id2Meas currentValue(const IdArray &ids, const Flag &flag) override {
return Id2Meas();
}
append_result append(const MeasArray & values) {
return append_result();
}
append_result append(const Meas &value) override{
return append_result();
}
void flush() override{
}
void foreach(const QueryTimePoint &q, IReaderClb *clbk) override{
}
MeasList readInterval(const QueryInterval &q) override{
return MeasList{};
}
Id2Track _id2steps;
};
MemStorage::MemStorage(const MemStorage::Params &p) : _impl(new MemStorage::Private(p)) {}
MemStorage::~MemStorage() {
_impl = nullptr;
}
Time dariadb::storage::MemStorage::minTime() {
return _impl->minTime();
}
Time dariadb::storage::MemStorage::maxTime() {
return _impl->maxTime();
}
bool dariadb::storage::MemStorage::minMaxTime(dariadb::Id id, dariadb::Time *minResult,
dariadb::Time *maxResult) {
return _impl->minMaxTime(id,minResult, maxResult);
}
void dariadb::storage::MemStorage::foreach (const QueryInterval &q, IReaderClb * clbk) {
_impl->foreach(q, clbk);
}
Id2Meas dariadb::storage::MemStorage::readTimePoint(const QueryTimePoint &q) {
return _impl->readTimePoint(q);
}
Id2Meas dariadb::storage::MemStorage::currentValue(const IdArray &ids, const Flag &flag) {
return _impl->currentValue(ids, flag);
}
append_result dariadb::storage::MemStorage::append(const Meas &value){
return _impl->append(value);
}
void dariadb::storage::MemStorage::flush(){
_impl->flush();
}
<|endoftext|> |
<commit_before>#include "ipdb.h"
#include <cstdio>
#include <cstring>
#include <endian.h>
#include <fcntl.h>
#include <stdint.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdexcept>
IPDB::IPDB(const char* filename)
{
fd_ = open(filename, O_RDWR);
if (fd_<0) {
throw std::runtime_error(strerror(errno));
}
struct stat buf;
bzero(&buf, sizeof(buf));
if (fstat(fd_, &buf)<0) {
close(fd_);
throw std::runtime_error(strerror(errno));
}
size_ = buf.st_size;
m_ = mmap(0, size_, PROT_READ|PROT_WRITE, MAP_SHARED, fd_, 0);
if (!m_) {
close(fd_);
throw std::runtime_error(strerror(errno));
}
offset_ = be32toh(*(uint32_t*)m_);
}
IPDB::~IPDB()
{
if (m_&&munmap(m_, size_)<0) {
perror("munmap");
};
if (fd_>=0&&close(fd_)<0) {
perror("close");
}
}
std::string IPDB::Find(const std::string& ip) const
{
uint32_t nip = IP2Long(ip);
const char* index = (char*)m_ + 4;
uint32_t start = le32toh(*(uint32_t*)(index + (nip >> 24)*4));
const uint32_t* q = (uint32_t*)(index + 1024) + start*2;
const uint32_t* limit = (uint32_t*)((char*)m_ + offset_ - 1024);
for (; q<limit; q+=2) {
if (be32toh(*q) >= nip) {
uint32_t t = le32toh(*(q + 1));
uint32_t d_offset = t & 0x00FFFFFF;
uint8_t d_len = t >> 24;
const char* r = (char*)m_ + offset_ + d_offset - 1024;
return std::string(r, d_len);
}
}
throw std::runtime_error("invalid ip");
}
uint32_t IPDB::IP2Long(const std::string& ip) const
{
uint32_t nip = 0;
size_t prev = -1;
for (int i=0; i<4; i++) {
size_t pos = ip.find(".", prev+1);
if ((pos==-1&&i<3) || (pos!=-1&&i==3)) {
throw std::runtime_error("invalid ip");
}
pos = pos!=-1?pos:ip.length();
int x = stoi(ip.substr(prev+1, pos-prev-1));
if ((x&~0xFF)!=0) {
throw std::runtime_error("invalid ip");
}
nip <<= 8;
nip |= x & 0xFF;
prev = pos;
}
return nip;
}
<commit_msg>remove c++11 function<commit_after>#include "ipdb.h"
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <endian.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdexcept>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
IPDB::IPDB(const char* filename)
{
fd_ = open(filename, O_RDWR);
if (fd_<0) {
throw std::runtime_error(strerror(errno));
}
struct stat buf;
bzero(&buf, sizeof(buf));
if (fstat(fd_, &buf)<0) {
close(fd_);
throw std::runtime_error(strerror(errno));
}
size_ = buf.st_size;
m_ = mmap(0, size_, PROT_READ|PROT_WRITE, MAP_SHARED, fd_, 0);
if (!m_) {
close(fd_);
throw std::runtime_error(strerror(errno));
}
offset_ = be32toh(*(uint32_t*)m_);
}
IPDB::~IPDB()
{
if (m_&&munmap(m_, size_)<0) {
perror("munmap");
};
if (fd_>=0&&close(fd_)<0) {
perror("close");
}
}
std::string IPDB::Find(const std::string& ip) const
{
uint32_t nip = IP2Long(ip);
const char* index = (char*)m_ + 4;
uint32_t start = le32toh(*(uint32_t*)(index + (nip >> 24)*4));
const uint32_t* q = (uint32_t*)(index + 1024) + start*2;
const uint32_t* limit = (uint32_t*)((char*)m_ + offset_ - 1024);
for (; q<limit; q+=2) {
if (be32toh(*q) >= nip) {
uint32_t t = le32toh(*(q + 1));
uint32_t d_offset = t & 0x00FFFFFF;
uint8_t d_len = t >> 24;
const char* r = (char*)m_ + offset_ + d_offset - 1024;
return std::string(r, d_len);
}
}
throw std::runtime_error("invalid ip");
}
uint32_t IPDB::IP2Long(const std::string& ip) const
{
uint32_t nip = 0;
size_t prev = -1;
for (int i=0; i<4; i++) {
size_t pos = ip.find(".", prev+1);
if ((pos==-1&&i<3) || (pos!=-1&&i==3)) {
throw std::runtime_error("invalid ip");
}
pos = pos!=-1?pos:ip.length();
int x = atoi(ip.substr(prev+1, pos-prev-1).c_str());
if ((x&~0xFF)!=0) {
throw std::runtime_error("invalid ip");
}
nip <<= 8;
nip |= x & 0xFF;
prev = pos;
}
return nip;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2021 ASMlover. All rights reserved.
//
// ______ __ ___
// /\__ _\ /\ \ /\_ \
// \/_/\ \/ __ \_\ \ _____ ___\//\ \ __
// \ \ \ /'__`\ /'_` \/\ '__`\ / __`\\ \ \ /'__`\
// \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\ __/
// \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\
// \/_/\/__/\/_/\/__,_ /\ \ \/ \/___/ \/____/\/____/
// \ \_\
// \/_/
//
// 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 ofconditions 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 materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <iostream>
#include <Common/Colorful.hh>
#include <GC/MarkSweep.hh>
namespace Tadpole::GC {
MarkSweep::MarkSweep() noexcept {
}
MarkSweep::~MarkSweep() {
while (!objects_.empty()) {
auto* o = objects_.back();
objects_.pop_back();
reclaim_object(o);
}
}
void MarkSweep::collect() {
mark_from_roots();
sweep();
gc_threshold_ = std::max(std::min(gc_threshold_, kGCThresholdMin), objects_.size() * kGCFactor);
gc_threshold_ = Common::as_align(gc_threshold_, kGCAlign);
}
void MarkSweep::append_object(Object::BaseObject* o) {
if (objects_.size() >= gc_threshold_)
collect();
objects_.push_back(o);
}
void MarkSweep::mark_object(Object::BaseObject* o) {
if (o == nullptr || o->is_marked())
return;
#if defined(_TADPOLE_DEBUG_GC)
std::cout
<< Common::Colorful::fg::lightcyan
<< "[" << o << "] mark object: `" << o->stringify() << "`"
<< Common::Colorful::reset
<< std::endl;
#endif
o->set_marked(true);
worklist_.push_back(o);
}
sz_t MarkSweep::get_count() const {
return objects_.size();
}
sz_t MarkSweep::get_threshold() const {
return gc_threshold_;
}
void MarkSweep::set_threshold(sz_t threshold) {
gc_threshold_ = Common::as_align(threshold, kGCAlign);
}
void MarkSweep::mark() {
while (!worklist_.empty()) {
Object::BaseObject* o = worklist_.back();
worklist_.pop_back();
o->iter_children([this](Object::BaseObject* child) { mark_object(child); });
}
}
void MarkSweep::mark_from_roots() {
for (auto& r : roots_) {
r.second->iter_objects([this](Object::BaseObject* o) {
mark_object(o);
mark();
});
}
for (auto& s : interned_strings_) {
mark_object(s.second);
mark();
}
}
void MarkSweep::sweep() {
for (auto it = interned_strings_.begin(); it != interned_strings_.end();) {
if (!it->second->is_marked())
interned_strings_.erase(it++);
else
++it;
}
for (auto it = objects_.begin(); it != objects_.end();) {
if (!(*it)->is_marked()) {
reclaim_object(*it);
objects_.erase(it++);
}
else {
(*it)->set_marked(true);
++it;
}
}
}
void MarkSweep::reclaim_object(Object::BaseObject* o) {
#if defined(_TADPOLE_DEBUG_GC)
std::cout
<< Common::Colorful::fg::gray
<< "[" << o << "] reclaim object type: `" << o->type_asstr() << "`"
<< Common::Colorful::reset
<< std::endl;
#endif
delete o;
}
}
<commit_msg>:construction: chore(gc): updated the implementation of virtual methods<commit_after>// Copyright (c) 2021 ASMlover. All rights reserved.
//
// ______ __ ___
// /\__ _\ /\ \ /\_ \
// \/_/\ \/ __ \_\ \ _____ ___\//\ \ __
// \ \ \ /'__`\ /'_` \/\ '__`\ / __`\\ \ \ /'__`\
// \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\ __/
// \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\
// \/_/\/__/\/_/\/__,_ /\ \ \/ \/___/ \/____/\/____/
// \ \_\
// \/_/
//
// 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 ofconditions 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 materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <iostream>
#include <Common/Colorful.hh>
#include <GC/MarkSweep.hh>
namespace Tadpole::GC {
MarkSweep::MarkSweep() noexcept {
}
MarkSweep::~MarkSweep() {
while (!objects_.empty()) {
auto* o = objects_.back();
objects_.pop_back();
reclaim_object(o);
}
}
void MarkSweep::collect() {
mark_from_roots();
sweep();
gc_threshold_ = std::max(std::min(gc_threshold_, kGCThresholdMin), objects_.size() * kGCFactor);
gc_threshold_ = Common::as_align(gc_threshold_, kGCAlign);
}
void MarkSweep::append_object(Object::BaseObject* o) {
if (objects_.size() >= gc_threshold_)
collect();
objects_.push_back(o);
}
void MarkSweep::mark_object(Object::BaseObject* o) {
if (o == nullptr || o->is_marked())
return;
#if defined(_TADPOLE_DEBUG_GC)
std::cout
<< Common::Colorful::fg::lightcyan
<< "[" << o << "] mark object: `" << o->stringify() << "`"
<< Common::Colorful::reset
<< std::endl;
#endif
o->set_marked(true);
worklist_.push_back(o);
}
sz_t MarkSweep::get_count() const {
return objects_.size();
}
sz_t MarkSweep::get_threshold() const {
return gc_threshold_;
}
void MarkSweep::set_threshold(sz_t threshold) {
gc_threshold_ = Common::as_align(threshold, kGCAlign);
}
bool MarkSweep::is_enabled() const { return true; }
void MarkSweep::enable() {}
void MarkSweep::disable() {}
void MarkSweep::mark() {
while (!worklist_.empty()) {
Object::BaseObject* o = worklist_.back();
worklist_.pop_back();
o->iter_children([this](Object::BaseObject* child) { mark_object(child); });
}
}
void MarkSweep::mark_from_roots() {
for (auto& r : roots_) {
r.second->iter_objects([this](Object::BaseObject* o) {
mark_object(o);
mark();
});
}
for (auto& s : interned_strings_) {
mark_object(s.second);
mark();
}
}
void MarkSweep::sweep() {
for (auto it = interned_strings_.begin(); it != interned_strings_.end();) {
if (!it->second->is_marked())
interned_strings_.erase(it++);
else
++it;
}
for (auto it = objects_.begin(); it != objects_.end();) {
if (!(*it)->is_marked()) {
reclaim_object(*it);
objects_.erase(it++);
}
else {
(*it)->set_marked(true);
++it;
}
}
}
void MarkSweep::reclaim_object(Object::BaseObject* o) {
#if defined(_TADPOLE_DEBUG_GC)
std::cout
<< Common::Colorful::fg::gray
<< "[" << o << "] reclaim object type: `" << o->type_asstr() << "`"
<< Common::Colorful::reset
<< std::endl;
#endif
delete o;
}
}
<|endoftext|> |
<commit_before>// Copyright 2020 DeepMind Technologies Limited.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "pybind_utils.h" // controller
#include <dlfcn.h>
#include <string>
#include "dm_robotics/support/logging.h"
#include "absl/strings/substitute.h"
#include "dm_robotics/mujoco/mjlib.h"
#include "pybind11/pybind11.h" // pybind
namespace dm_robotics::internal {
namespace {
namespace py = pybind11;
constexpr char kDmControlMjModelClassName[] = "MjModel";
constexpr char kDmControlMjDataClassName[] = "MjData";
// Returns a ctypes module for use through pybind.
py::module GetCtypesModule() {
static PyObject* const ctypes_module_ptr = []() -> PyObject* {
py::module ctypes_module = py::module::import("ctypes");
PyObject* ctypes_module_ptr = ctypes_module.ptr();
Py_XINCREF(ctypes_module_ptr);
return ctypes_module_ptr;
}();
return py::reinterpret_borrow<py::module>(ctypes_module_ptr);
}
// Returns a pointer to the underlying object pointed to by `ctypes_obj`.
// Note that does not increment the reference count.
template <class T>
T* GetPointer(py::handle ctypes_obj) {
auto ctypes_module = GetCtypesModule();
return reinterpret_cast<T*>(
ctypes_module.attr("addressof")(ctypes_obj.attr("contents"))
.cast<std::uintptr_t>());
}
// Returns a pointer to a MuJoCo mjModel or mjData from the dm_control wrappers
// around these objects. The dm_control wrappers are such that the `ptr`
// attributes return a ctypes object bound to underlying MuJoCo native type.
//
// Raises a `RuntimeError` exception in Python if the handle does not contain a
// `ptr` attribute.
template <class T>
T* GetMujocoPointerFromDmControlWrapperHandle(py::handle dm_control_wrapper) {
if (!py::hasattr(dm_control_wrapper, "ptr")) {
RaiseRuntimeErrorWithMessage(
"GetMujocoPointerFromDmControlWrapperHandle: handle does not have a "
"`ptr` attribute. This function assumes that dm_control wrappers "
"around mjModel and mjData contain a `ptr` attribute with the MuJoCo "
"native type.");
}
return GetPointer<T>(dm_control_wrapper.attr("ptr"));
}
} // namespace
void RaiseRuntimeErrorWithMessage(absl::string_view message) {
PyErr_SetString(PyExc_RuntimeError, std::string(message).c_str());
throw py::error_already_set();
}
const MjLib* LoadMjLibFromDmControl() {
py::gil_scoped_acquire gil;
// Get the path to the DSO.
const py::module mjbindings(
py::module::import("dm_control.mujoco.wrapper.mjbindings"));
const std::string dso_path =
mjbindings.attr("mjlib").attr("_name").cast<std::string>();
// Create the MjLib object by dlopen'ing the DSO.
return new MjLib(dso_path, RTLD_NOW);
}
// Helper function for getting an mjModel object from a py::handle.
const mjModel* GetmjModelOrRaise(py::handle obj) {
const std::string class_name =
obj.attr("__class__").attr("__name__").cast<std::string>();
if (class_name != kDmControlMjModelClassName) {
RaiseRuntimeErrorWithMessage(absl::Substitute(
"GetmjModelOrRaise: the class name of the argument [$0] does not match "
"the expected dm_control type name for mjModel [$1].",
class_name, kDmControlMjModelClassName));
}
return GetMujocoPointerFromDmControlWrapperHandle<mjModel>(obj);
}
// Helper function for getting an mjData object from a py::handle.
const mjData* GetmjDataOrRaise(py::handle obj) {
const std::string class_name =
obj.attr("__class__").attr("__name__").cast<std::string>();
if (class_name != kDmControlMjDataClassName) {
RaiseRuntimeErrorWithMessage(absl::Substitute(
"GetmjDataOrRaise: the class name of the argument [$0] does not match "
"the expected dm_control type name for mjData [$1].",
class_name, kDmControlMjDataClassName));
}
return GetMujocoPointerFromDmControlWrapperHandle<mjData>(obj);
}
} // namespace dm_robotics::internal
<commit_msg>Use new MuJoCo python bindings to implement dm_control/mujoco.<commit_after>// Copyright 2020 DeepMind Technologies Limited.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "pybind_utils.h" // controller
#include <dlfcn.h>
#include <string>
#include "dm_robotics/support/logging.h"
#include "absl/strings/substitute.h"
#include "dm_robotics/mujoco/mjlib.h"
#include "pybind11/pybind11.h" // pybind
namespace dm_robotics::internal {
namespace {
namespace py = pybind11;
constexpr char kDmControlMjModelClassName[] = "MjModel";
constexpr char kDmControlMjDataClassName[] = "MjData";
// Returns a ctypes module for use through pybind.
py::module GetCtypesModule() {
static PyObject* const ctypes_module_ptr = []() -> PyObject* {
py::module ctypes_module = py::module::import("ctypes");
PyObject* ctypes_module_ptr = ctypes_module.ptr();
Py_XINCREF(ctypes_module_ptr);
return ctypes_module_ptr;
}();
return py::reinterpret_borrow<py::module>(ctypes_module_ptr);
}
// Returns a pointer to the underlying object pointed to by `ctypes_obj`.
// Note that does not increment the reference count.
template <class T>
T* GetPointer(py::handle mjwrapper_object) {
#ifdef DM_ROBOTICS_USE_NEW_MUJOCO_BINDINGS
return reinterpret_cast<T*>(
mjwrapper_object.attr("_address").cast<std::uintptr_t>());
#else
auto ctypes_module = GetCtypesModule();
return reinterpret_cast<T*>(
ctypes_module.attr("addressof")(mjwrapper_object.attr("contents"))
.cast<std::uintptr_t>());
#endif
}
// Returns a pointer to a MuJoCo mjModel or mjData from the dm_control wrappers
// around these objects. The dm_control wrappers are such that the `ptr`
// attributes return a ctypes object bound to underlying MuJoCo native type.
//
// Raises a `RuntimeError` exception in Python if the handle does not contain a
// `ptr` attribute.
template <class T>
T* GetMujocoPointerFromDmControlWrapperHandle(py::handle dm_control_wrapper) {
if (!py::hasattr(dm_control_wrapper, "ptr")) {
RaiseRuntimeErrorWithMessage(
"GetMujocoPointerFromDmControlWrapperHandle: handle does not have a "
"`ptr` attribute. This function assumes that dm_control wrappers "
"around mjModel and mjData contain a `ptr` attribute with the MuJoCo "
"native type.");
}
return GetPointer<T>(dm_control_wrapper.attr("ptr"));
}
} // namespace
void RaiseRuntimeErrorWithMessage(absl::string_view message) {
PyErr_SetString(PyExc_RuntimeError, std::string(message).c_str());
throw py::error_already_set();
}
const MjLib* LoadMjLibFromDmControl() {
py::gil_scoped_acquire gil;
// Get the path to the DSO.
const py::module mjbindings(
py::module::import("dm_control.mujoco.wrapper.mjbindings"));
const std::string dso_path =
mjbindings.attr("mjlib").attr("_name").cast<std::string>();
// Create the MjLib object by dlopen'ing the DSO.
return new MjLib(dso_path, RTLD_NOW);
}
// Helper function for getting an mjModel object from a py::handle.
const mjModel* GetmjModelOrRaise(py::handle obj) {
const std::string class_name =
obj.attr("__class__").attr("__name__").cast<std::string>();
if (class_name != kDmControlMjModelClassName) {
RaiseRuntimeErrorWithMessage(absl::Substitute(
"GetmjModelOrRaise: the class name of the argument [$0] does not match "
"the expected dm_control type name for mjModel [$1].",
class_name, kDmControlMjModelClassName));
}
return GetMujocoPointerFromDmControlWrapperHandle<mjModel>(obj);
}
// Helper function for getting an mjData object from a py::handle.
const mjData* GetmjDataOrRaise(py::handle obj) {
const std::string class_name =
obj.attr("__class__").attr("__name__").cast<std::string>();
if (class_name != kDmControlMjDataClassName) {
RaiseRuntimeErrorWithMessage(absl::Substitute(
"GetmjDataOrRaise: the class name of the argument [$0] does not match "
"the expected dm_control type name for mjData [$1].",
class_name, kDmControlMjDataClassName));
}
return GetMujocoPointerFromDmControlWrapperHandle<mjData>(obj);
}
} // namespace dm_robotics::internal
<|endoftext|> |
<commit_before><?hh //strict
namespace HHPack\Codegen\Example;
use HHPack\Codegen\{OutputNamespace, GeneratorName};
use HHPack\Codegen\Contract\{FileGeneratable, GeneratorProvider};
use HHPack\Codegen\HackUnit\{TestClassGenerator};
use HHPack\Codegen\Project\{PackageClassGenerator};
use function HHPack\Codegen\Cli\{define_generator, namespace_of, map_to};
final class Generators implements GeneratorProvider {
const LIB = 'HHPack\\Codegen\\Example';
const LIB_TEST = 'HHPack\\Codegen\\Example\\Test';
public function generators(
): Iterator<Pair<GeneratorName, FileGeneratable<string>>> {
yield define_generator("lib:class", "generate library class file.")
->mapTo(
namespace_of(static::LIB, 'example/src')
->map(PackageClassGenerator::class),
);
yield define_generator("lib:testclass", "generate test class file.")
->mapTo(
namespace_of(static::LIB_TEST, 'example/test')
->map(TestClassGenerator::class),
);
}
}
<commit_msg>fix unused types<commit_after><?hh //strict
namespace HHPack\Codegen\Example;
use HHPack\Codegen\{GeneratorName};
use HHPack\Codegen\Contract\{FileGeneratable, GeneratorProvider};
use HHPack\Codegen\HackUnit\{TestClassGenerator};
use HHPack\Codegen\Project\{PackageClassGenerator};
use function HHPack\Codegen\Cli\{define_generator, namespace_of};
final class Generators implements GeneratorProvider {
const LIB = 'HHPack\\Codegen\\Example';
const LIB_TEST = 'HHPack\\Codegen\\Example\\Test';
public function generators(
): Iterator<Pair<GeneratorName, FileGeneratable<string>>> {
yield define_generator("lib:class", "generate library class file.")
->mapTo(
namespace_of(static::LIB, 'example/src')
->map(PackageClassGenerator::class),
);
yield define_generator("lib:testclass", "generate test class file.")
->mapTo(
namespace_of(static::LIB_TEST, 'example/test')
->map(TestClassGenerator::class),
);
}
}
<|endoftext|> |
<commit_before>/*
This file is part of SWGANH. For more information, visit http://swganh.com
Copyright (c) 2006 - 2011 The SWG:ANH Team
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 "anh/network/soe/session.h"
#include <algorithm>
#include <glog/logging.h>
#include "anh/network/soe/server_interface.h"
#include "anh/network/soe/protocol_opcodes.h"
#include "anh/network/soe/packet_utilities.h"
using namespace anh;
using namespace anh::event_dispatcher;
using namespace anh::network;
using namespace anh::network::soe;
using namespace std;
Session::Session(boost::asio::ip::udp::endpoint remote_endpoint, ServerInterface* server)
: std::enable_shared_from_this<Session>()
, remote_endpoint_(remote_endpoint)
, connected_(false)
, server_(server)
, strand_(server->socket()->get_io_service())
, crc_seed_(0xDEADBABE)
, server_net_stats_(0, 0, 0, 0, 0, 0)
, last_acknowledged_sequence_(0)
, current_client_sequence_(0)
, next_client_sequence_(0)
, server_sequence_()
, outgoing_data_message_(0)
, incoming_fragmented_total_len_(0)
, incoming_fragmented_curr_len_(0)
, decompression_filter_(server_->max_receive_size())
, security_filter_(server_->max_receive_size())
{
server_sequence_ = 0;
}
Session::~Session(void)
{
Close();
LOG(WARNING) << "Session [" << connection_id_ << "] Closed.";
}
uint16_t Session::server_sequence() const {
return server_sequence_;
}
uint32_t Session::receive_buffer_size() const {
return receive_buffer_size_;
}
void Session::receive_buffer_size(uint32_t receive_buffer_size) {
receive_buffer_size_ = receive_buffer_size;
}
uint32_t Session::crc_length() const {
return crc_length_;
}
void Session::crc_length(uint32_t crc_length) {
crc_length_ = crc_length;
}
void Session::crc_seed(uint32_t crc_seed) {
crc_seed_ = crc_seed;
}
uint32_t Session::crc_seed() const {
return crc_seed_;
}
void Session::datachannel_handler(DatachannelHandler handler) {
datachannel_handler_ = make_shared<DatachannelHandler>(handler);
}
vector<shared_ptr<ByteBuffer>> Session::GetUnacknowledgedMessages() const {
vector<shared_ptr<ByteBuffer>> unacknowledged_messages;
for_each(
sent_messages_.begin(),
sent_messages_.end(),
[&unacknowledged_messages] (const SequencedMessageMap::value_type& i)
{
unacknowledged_messages.push_back(i.second);
});
return unacknowledged_messages;
}
void Session::Update() {
// Exit as quickly as possible if there is no work currently.
if (!connected_ || outgoing_data_messages_.empty()) {
return;
}
// Build up a list of data messages to process
uint32_t message_count = outgoing_data_messages_.unsafe_size();
list<shared_ptr<ByteBuffer>> process_list;
shared_ptr<ByteBuffer> tmp;
for (uint32_t i = 0; i < message_count; ++i) {
if (outgoing_data_messages_.try_pop(tmp)) {
process_list.push_back(tmp);
}
}
// Pack the message list into a single data channel payload and send it.
ByteBuffer data_channel_payload = PackDataChannelMessages(process_list);
// Split up the message if it's too big
// @note: in determining the max size 3 is the size of the soe header + the compression flag.
uint32_t max_data_channel_size = receive_buffer_size_ - crc_length_ - 3;
if (data_channel_payload.size() > max_data_channel_size) {
list<ByteBuffer> fragmented_message = SplitDataChannelMessage(
data_channel_payload,
max_data_channel_size);
for_each(fragmented_message.begin(), fragmented_message.end(), [this] (ByteBuffer& fragment) {
SendSequencedMessage_(&BuildFragmentedDataChannelHeader, move(fragment));
});
} else {
SendSequencedMessage_(&BuildDataChannelHeader, move(data_channel_payload));
}
}
void Session::SendMessage(ByteBuffer message) {
auto message_buffer = server_->AllocateBuffer();
message_buffer->swap(message);
outgoing_data_messages_.push(message_buffer);
}
void Session::Close(void)
{
if(connected_)
{
connected_ = false;
Disconnect disconnect(connection_id_);
auto buffer = server_->AllocateBuffer();
disconnect.serialize(*buffer);
SendSoePacket_(buffer);
server_->RemoveSession(shared_from_this());
}
}
void Session::HandleMessage(const std::shared_ptr<anh::ByteBuffer>& message)
{
auto session = this->shared_from_this();
strand_.post([=] ()
{
switch(message->peek<uint16_t>(true))
{
case CHILD_DATA_A: { ChildDataA child_data_a(*message); session->handleChildDataA_(child_data_a); break; }
case MULTI_PACKET: { MultiPacket multi_packet(*message); session->handleMultiPacket_(multi_packet); break; }
case DATA_FRAG_A: { DataFragA data_frag_a(*message); session->handleDataFragA_(data_frag_a); break; }
case ACK_A: { AckA ack_a(*message); session->handleAckA_(ack_a); break; }
case PING: { Ping ping(*message); session->handlePing_(ping); break; }
case NET_STATS_CLIENT: { NetStatsClient net_stats_client(*message); session->handleNetStatsClient_(net_stats_client); break; }
case OUT_OF_ORDER_A: { OutOfOrderA out_of_order_a(*message); session->handleOutOfOrderA_(out_of_order_a); break; }
case DISCONNECT: { Disconnect disconnect(*message); session->handleDisconnect_(disconnect); break; }
case SESSION_REQUEST: { SessionRequest session_request(*message); session->handleSessionRequest_(session_request); break; }
case FATAL_ERROR: { session->Close(); break; }
default:
if (message->peek<uint8_t>() != 0)
{
server_->HandleMessage(session, message);
}
else
{
LOG(WARNING) << "Unhandled SOE Opcode: " << std::hex << message->peek<uint16_t>(true)
<< "\n\n" << message;
}
}
});
}
void Session::HandleProtocolMessage(const std::shared_ptr<anh::ByteBuffer>& message)
{
auto session = this->shared_from_this();
strand_.post([=] ()
{
security_filter_(session, message);
if (connected())
{
crc_input_filter_(session, message);
decryption_filter_(session, message);
decompression_filter_(session, message);
}
HandleMessage(message);
});
}
void Session::SendSequencedMessage_(HeaderBuilder header_builder, ByteBuffer message) {
// Get the next sequence number
uint16_t message_sequence = server_sequence_++;
// Allocate a new packet
auto data_channel_message = server_->AllocateBuffer();
data_channel_message->append(header_builder(message_sequence));
data_channel_message->append(message);
// Send it over the wire
SendSoePacket_(data_channel_message);
// Store it for resending later if necessary
sent_messages_.push_back(make_pair(message_sequence, data_channel_message));
// If the data channel message is too big
uint32_t max_data_channel_size = receive_buffer_size_ - crc_length_ - 5;
}
void Session::handleSessionRequest_(SessionRequest& packet)
{
connection_id_ = packet.connection_id;
crc_length_ = packet.crc_length;
receive_buffer_size_ = packet.client_udp_buffer_size;
SessionResponse session_response(connection_id_, crc_seed_);
session_response.server_udp_buffer_size = server_->max_receive_size();
auto buffer = server_->AllocateBuffer();
session_response.serialize(*buffer);
// Directly put this on the wire, it requires no outgoing processing.
server_->SendTo(remote_endpoint_, buffer);
connected_ = true;
LOG(INFO) << "Created Session [" << connection_id_ << "] @ " << remote_endpoint_.address().to_string() << ":" << remote_endpoint_.port();
}
void Session::handleMultiPacket_(MultiPacket& packet)
{
VLOG(3) << "Handling MULTIPACKET";
std::for_each(packet.packets.begin(), packet.packets.end(), [=](anh::ByteBuffer& buffer) {
HandleMessage(make_shared<ByteBuffer>(buffer));
});
}
void Session::handleDisconnect_(Disconnect& packet)
{
VLOG(3) << "Handling DISCONNECT";
Close();
}
void Session::handlePing_(Ping& packet)
{
VLOG(3) << "Handling PING";
Ping pong;
auto buffer = server_->AllocateBuffer();
pong.serialize(*buffer);
SendSoePacket_(buffer);
}
void Session::handleNetStatsClient_(NetStatsClient& packet)
{
VLOG(3) << "Handling NET_STATS_CLIENT";
server_net_stats_.client_tick_count = packet.client_tick_count;
auto buffer = server_->AllocateBuffer();
server_net_stats_.serialize(*buffer);
SendSoePacket_(buffer);
}
void Session::handleChildDataA_(ChildDataA& packet)
{
VLOG(3) << "Handling CHILD_DATA_A";
if(!SequenceIsValid_(packet.sequence)) {
DLOG(WARNING) << "Invalid sequence: " << packet.sequence << "; Current sequence " << this->next_client_sequence_;
return;
}
AcknowledgeSequence_(packet.sequence);
std::for_each(packet.messages.begin(), packet.messages.end(), [this] (shared_ptr<ByteBuffer> message) {
server_->HandleMessage(this->shared_from_this(), message);
});
}
void Session::handleDataFragA_(DataFragA& packet)
{
VLOG(3) << "Handling DATA_FRAG_A";
if(!SequenceIsValid_(packet.sequence))
return;
AcknowledgeSequence_(packet.sequence);
// Continuing a frag
if(incoming_fragmented_total_len_ > 0)
{
incoming_fragmented_curr_len_ += packet.data.size();
incoming_fragmented_messages_.push_back(packet.data);
if(incoming_fragmented_total_len_ == incoming_fragmented_curr_len_)
{
// Send to translator.
incoming_fragmented_total_len_ = 0;
incoming_fragmented_curr_len_ = 0;
ByteBuffer full_packet;
std::for_each(
incoming_fragmented_messages_.cbegin(),
incoming_fragmented_messages_.cend(),
[&full_packet] (const ByteBuffer& buffer) {
full_packet.append(buffer);
}
);
ChildDataA child_data_a(full_packet);
handleChildDataA_(child_data_a);
incoming_fragmented_messages_.clear();
}
}
// Starting a new frag
else
{
incoming_fragmented_total_len_ = packet.data.read<uint16_t>();
incoming_fragmented_curr_len_ += packet.data.size();
incoming_fragmented_messages_.push_back(anh::ByteBuffer(packet.data.data()+2, packet.data.size()-2));
}
}
void Session::handleAckA_(AckA& packet)
{
VLOG(3) << "Handle ACK_A";
auto it = find_if(
sent_messages_.begin(),
sent_messages_.end(),
[this, &packet] (const SequencedMessageMap::value_type& message)
{
return (message.first == packet.sequence) ? true : false;
});
sent_messages_.erase(sent_messages_.begin(), it);
last_acknowledged_sequence_ = packet.sequence;
}
void Session::handleOutOfOrderA_(OutOfOrderA& packet)
{
VLOG(3) << "Handle OUT_OF_ORDER_A";
std::for_each(sent_messages_.begin(), sent_messages_.end(), [=](SequencedMessageMap::value_type& item) {
SendSoePacket_(item.second);
});
}
void Session::SendSoePacket_(const std::shared_ptr<anh::ByteBuffer>& message)
{
auto session = this->shared_from_this();
strand_.post([=] ()
{
compression_filter_(session, message);
encryption_filter_(session, message);
crc_output_filter_(session, message);
server_->SendTo(session->remote_endpoint(), message);
});
}
bool Session::SequenceIsValid_(const uint16_t& sequence)
{
if(next_client_sequence_ == sequence)
{
return true;
}
else
{
// Tell the client we have received an Out of Order sequence.
OutOfOrderA out_of_order(sequence);
auto buffer = server_->AllocateBuffer();
out_of_order.serialize(*buffer);
SendSoePacket_(buffer);
return false;
}
}
void Session::AcknowledgeSequence_(const uint16_t& sequence)
{
AckA ack(sequence);
auto buffer = server_->AllocateBuffer();
ack.serialize(*buffer);
SendSoePacket_(buffer);
next_client_sequence_ = sequence + 1;
current_client_sequence_ = sequence;
}
<commit_msg>Fixed an issue with object lifetime<commit_after>/*
This file is part of SWGANH. For more information, visit http://swganh.com
Copyright (c) 2006 - 2011 The SWG:ANH Team
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 "anh/network/soe/session.h"
#include <algorithm>
#include <glog/logging.h>
#include "anh/network/soe/server_interface.h"
#include "anh/network/soe/protocol_opcodes.h"
#include "anh/network/soe/packet_utilities.h"
using namespace anh;
using namespace anh::event_dispatcher;
using namespace anh::network;
using namespace anh::network::soe;
using namespace std;
Session::Session(boost::asio::ip::udp::endpoint remote_endpoint, ServerInterface* server)
: std::enable_shared_from_this<Session>()
, remote_endpoint_(remote_endpoint)
, connected_(false)
, server_(server)
, strand_(server->socket()->get_io_service())
, crc_seed_(0xDEADBABE)
, server_net_stats_(0, 0, 0, 0, 0, 0)
, last_acknowledged_sequence_(0)
, current_client_sequence_(0)
, next_client_sequence_(0)
, server_sequence_()
, outgoing_data_message_(0)
, incoming_fragmented_total_len_(0)
, incoming_fragmented_curr_len_(0)
, decompression_filter_(server_->max_receive_size())
, security_filter_(server_->max_receive_size())
{
server_sequence_ = 0;
}
Session::~Session(void)
{
Close();
LOG(WARNING) << "Session [" << connection_id_ << "] Closed.";
}
uint16_t Session::server_sequence() const {
return server_sequence_;
}
uint32_t Session::receive_buffer_size() const {
return receive_buffer_size_;
}
void Session::receive_buffer_size(uint32_t receive_buffer_size) {
receive_buffer_size_ = receive_buffer_size;
}
uint32_t Session::crc_length() const {
return crc_length_;
}
void Session::crc_length(uint32_t crc_length) {
crc_length_ = crc_length;
}
void Session::crc_seed(uint32_t crc_seed) {
crc_seed_ = crc_seed;
}
uint32_t Session::crc_seed() const {
return crc_seed_;
}
void Session::datachannel_handler(DatachannelHandler handler) {
datachannel_handler_ = make_shared<DatachannelHandler>(handler);
}
vector<shared_ptr<ByteBuffer>> Session::GetUnacknowledgedMessages() const {
vector<shared_ptr<ByteBuffer>> unacknowledged_messages;
for_each(
sent_messages_.begin(),
sent_messages_.end(),
[&unacknowledged_messages] (const SequencedMessageMap::value_type& i)
{
unacknowledged_messages.push_back(i.second);
});
return unacknowledged_messages;
}
void Session::Update() {
// Exit as quickly as possible if there is no work currently.
if (!connected_ || outgoing_data_messages_.empty()) {
return;
}
// Build up a list of data messages to process
uint32_t message_count = outgoing_data_messages_.unsafe_size();
list<shared_ptr<ByteBuffer>> process_list;
shared_ptr<ByteBuffer> tmp;
for (uint32_t i = 0; i < message_count; ++i) {
if (outgoing_data_messages_.try_pop(tmp)) {
process_list.push_back(tmp);
}
}
// Pack the message list into a single data channel payload and send it.
ByteBuffer data_channel_payload = PackDataChannelMessages(process_list);
// Split up the message if it's too big
// @note: in determining the max size 3 is the size of the soe header + the compression flag.
uint32_t max_data_channel_size = receive_buffer_size_ - crc_length_ - 3;
if (data_channel_payload.size() > max_data_channel_size) {
list<ByteBuffer> fragmented_message = SplitDataChannelMessage(
data_channel_payload,
max_data_channel_size);
for_each(fragmented_message.begin(), fragmented_message.end(), [this] (ByteBuffer& fragment) {
SendSequencedMessage_(&BuildFragmentedDataChannelHeader, move(fragment));
});
} else {
SendSequencedMessage_(&BuildDataChannelHeader, move(data_channel_payload));
}
}
void Session::SendMessage(ByteBuffer message) {
auto message_buffer = server_->AllocateBuffer();
message_buffer->swap(message);
outgoing_data_messages_.push(message_buffer);
}
void Session::Close(void)
{
if(connected_)
{
connected_ = false;
Disconnect disconnect(connection_id_);
auto buffer = server_->AllocateBuffer();
disconnect.serialize(*buffer);
SendSoePacket_(buffer);
server_->RemoveSession(shared_from_this());
}
}
void Session::HandleMessage(const std::shared_ptr<anh::ByteBuffer>& message)
{
auto session = shared_from_this();
strand_.post([=] ()
{
switch(message->peek<uint16_t>(true))
{
case CHILD_DATA_A: { ChildDataA child_data_a(*message); session->handleChildDataA_(child_data_a); break; }
case MULTI_PACKET: { MultiPacket multi_packet(*message); session->handleMultiPacket_(multi_packet); break; }
case DATA_FRAG_A: { DataFragA data_frag_a(*message); session->handleDataFragA_(data_frag_a); break; }
case ACK_A: { AckA ack_a(*message); session->handleAckA_(ack_a); break; }
case PING: { Ping ping(*message); session->handlePing_(ping); break; }
case NET_STATS_CLIENT: { NetStatsClient net_stats_client(*message); session->handleNetStatsClient_(net_stats_client); break; }
case OUT_OF_ORDER_A: { OutOfOrderA out_of_order_a(*message); session->handleOutOfOrderA_(out_of_order_a); break; }
case DISCONNECT: { Disconnect disconnect(*message); session->handleDisconnect_(disconnect); break; }
case SESSION_REQUEST: { SessionRequest session_request(*message); session->handleSessionRequest_(session_request); break; }
case FATAL_ERROR: { session->Close(); break; }
default:
if (message->peek<uint8_t>() != 0)
{
server_->HandleMessage(session, message);
}
else
{
LOG(WARNING) << "Unhandled SOE Opcode: " << std::hex << message->peek<uint16_t>(true)
<< "\n\n" << message;
}
}
});
}
void Session::HandleProtocolMessage(const std::shared_ptr<anh::ByteBuffer>& message)
{
auto session = shared_from_this();
strand_.post([=] ()
{
security_filter_(session, message);
if (connected())
{
crc_input_filter_(session, message);
decryption_filter_(session, message);
decompression_filter_(session, message);
}
HandleMessage(message);
});
}
void Session::SendSequencedMessage_(HeaderBuilder header_builder, ByteBuffer message) {
// Get the next sequence number
uint16_t message_sequence = server_sequence_++;
// Allocate a new packet
auto data_channel_message = server_->AllocateBuffer();
data_channel_message->append(header_builder(message_sequence));
data_channel_message->append(message);
// Send it over the wire
SendSoePacket_(data_channel_message);
// Store it for resending later if necessary
sent_messages_.push_back(make_pair(message_sequence, data_channel_message));
// If the data channel message is too big
uint32_t max_data_channel_size = receive_buffer_size_ - crc_length_ - 5;
}
void Session::handleSessionRequest_(SessionRequest& packet)
{
connection_id_ = packet.connection_id;
crc_length_ = packet.crc_length;
receive_buffer_size_ = packet.client_udp_buffer_size;
SessionResponse session_response(connection_id_, crc_seed_);
session_response.server_udp_buffer_size = server_->max_receive_size();
auto buffer = server_->AllocateBuffer();
session_response.serialize(*buffer);
// Directly put this on the wire, it requires no outgoing processing.
server_->SendTo(remote_endpoint_, buffer);
connected_ = true;
LOG(INFO) << "Created Session [" << connection_id_ << "] @ " << remote_endpoint_.address().to_string() << ":" << remote_endpoint_.port();
}
void Session::handleMultiPacket_(MultiPacket& packet)
{
VLOG(3) << "Handling MULTIPACKET";
std::for_each(packet.packets.begin(), packet.packets.end(), [=](anh::ByteBuffer& buffer) {
HandleMessage(make_shared<ByteBuffer>(buffer));
});
}
void Session::handleDisconnect_(Disconnect& packet)
{
VLOG(3) << "Handling DISCONNECT";
Close();
}
void Session::handlePing_(Ping& packet)
{
VLOG(3) << "Handling PING";
Ping pong;
auto buffer = server_->AllocateBuffer();
pong.serialize(*buffer);
SendSoePacket_(buffer);
}
void Session::handleNetStatsClient_(NetStatsClient& packet)
{
VLOG(3) << "Handling NET_STATS_CLIENT";
server_net_stats_.client_tick_count = packet.client_tick_count;
auto buffer = server_->AllocateBuffer();
server_net_stats_.serialize(*buffer);
SendSoePacket_(buffer);
}
void Session::handleChildDataA_(ChildDataA& packet)
{
VLOG(3) << "Handling CHILD_DATA_A";
if(!SequenceIsValid_(packet.sequence)) {
DLOG(WARNING) << "Invalid sequence: " << packet.sequence << "; Current sequence " << this->next_client_sequence_;
return;
}
AcknowledgeSequence_(packet.sequence);
std::for_each(packet.messages.begin(), packet.messages.end(), [this] (shared_ptr<ByteBuffer> message) {
server_->HandleMessage(this->shared_from_this(), message);
});
}
void Session::handleDataFragA_(DataFragA& packet)
{
VLOG(3) << "Handling DATA_FRAG_A";
if(!SequenceIsValid_(packet.sequence))
return;
AcknowledgeSequence_(packet.sequence);
// Continuing a frag
if(incoming_fragmented_total_len_ > 0)
{
incoming_fragmented_curr_len_ += packet.data.size();
incoming_fragmented_messages_.push_back(packet.data);
if(incoming_fragmented_total_len_ == incoming_fragmented_curr_len_)
{
// Send to translator.
incoming_fragmented_total_len_ = 0;
incoming_fragmented_curr_len_ = 0;
ByteBuffer full_packet;
std::for_each(
incoming_fragmented_messages_.cbegin(),
incoming_fragmented_messages_.cend(),
[&full_packet] (const ByteBuffer& buffer) {
full_packet.append(buffer);
}
);
ChildDataA child_data_a(full_packet);
handleChildDataA_(child_data_a);
incoming_fragmented_messages_.clear();
}
}
// Starting a new frag
else
{
incoming_fragmented_total_len_ = packet.data.read<uint16_t>();
incoming_fragmented_curr_len_ += packet.data.size();
incoming_fragmented_messages_.push_back(anh::ByteBuffer(packet.data.data()+2, packet.data.size()-2));
}
}
void Session::handleAckA_(AckA& packet)
{
VLOG(3) << "Handle ACK_A";
auto it = find_if(
sent_messages_.begin(),
sent_messages_.end(),
[this, &packet] (const SequencedMessageMap::value_type& message)
{
return (message.first == packet.sequence) ? true : false;
});
sent_messages_.erase(sent_messages_.begin(), it);
last_acknowledged_sequence_ = packet.sequence;
}
void Session::handleOutOfOrderA_(OutOfOrderA& packet)
{
VLOG(3) << "Handle OUT_OF_ORDER_A";
std::for_each(sent_messages_.begin(), sent_messages_.end(), [=](SequencedMessageMap::value_type& item) {
SendSoePacket_(item.second);
});
}
void Session::SendSoePacket_(const std::shared_ptr<anh::ByteBuffer>& message)
{
auto session = shared_from_this();
strand_.post([=] ()
{
compression_filter_(session, message);
encryption_filter_(session, message);
crc_output_filter_(session, message);
server_->SendTo(session->remote_endpoint(), message);
});
}
bool Session::SequenceIsValid_(const uint16_t& sequence)
{
if(next_client_sequence_ == sequence)
{
return true;
}
else
{
// Tell the client we have received an Out of Order sequence.
OutOfOrderA out_of_order(sequence);
auto buffer = server_->AllocateBuffer();
out_of_order.serialize(*buffer);
SendSoePacket_(buffer);
return false;
}
}
void Session::AcknowledgeSequence_(const uint16_t& sequence)
{
AckA ack(sequence);
auto buffer = server_->AllocateBuffer();
ack.serialize(*buffer);
SendSoePacket_(buffer);
next_client_sequence_ = sequence + 1;
current_client_sequence_ = sequence;
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "Logger.h"
#include <memory>
#include <locale> // wstring_convert
std::shared_ptr<spdlog::logger> getFallbackLogger()
{
constexpr const char *fallbackLoggerName = "Fallback_stderr";
spdlog::drop(fallbackLoggerName);
return spdlog::stderr_logger_mt(fallbackLoggerName);
}
void createLogger(std::string loggerName, spdlog::filename_t loggerFile)
{
try
{
spdlog::set_level(spdlog::level::debug);
spdlog::set_sync_mode();
Logger::logfile = spdlog::rotating_logger_mt(loggerName, loggerFile, 1024 * 1024 * 10, 3);
LOG_INFO("Synchronous logger created");
LOG_FLUSH();
}
catch (const spdlog::spdlog_ex& ex)
{
Logger::logfile = getFallbackLogger();
LOG_ERROR(std::string("Could not create regular logger! ") + ex.what());
}
}
// Do NOT call this function in dllmain.cpp!!!
// It creates new threads which is forbidden while attaching the dll
void switchToAsyncLogger(std::string loggerName, spdlog::filename_t loggerFile)
{
LOG_INFO("Switching to asynchronous logger...");
LOG_FLUSH();
Logger::logfile = nullptr;
spdlog::drop(loggerName);
try
{
spdlog::set_level(spdlog::level::debug);
spdlog::set_async_mode(131072, spdlog::async_overflow_policy::block_retry,
nullptr,
std::chrono::milliseconds(500));
Logger::logfile = spdlog::rotating_logger_mt(loggerName, loggerFile, 1024 * 1024 * 10, 3);
LOG_INFO("Switching to asynchronous logger done!");
}
catch (const spdlog::spdlog_ex& ex)
{
// Try creating the regular logger again. Might work.
try
{
createLogger(loggerName, loggerFile);
}
catch (const spdlog::spdlog_ex& ex)
{
Logger::logfile = getFallbackLogger();
LOG_ERROR(std::string("Could not create regular logger! ") + ex.what());
}
LOG_ERROR(std::string("Could not create asynchronous logger! ") + ex.what());
}
}
namespace Logger
{
// http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-closed.html#721
template<class I, class E, class S>
struct codecvt : std::codecvt<I, E, S>
{
~codecvt()
{ }
};
std::string w2s(const std::wstring &var)
{
static std::locale loc("");
auto &facet = std::use_facet<codecvt<wchar_t, char, std::mbstate_t>>(loc);
return std::wstring_convert<std::remove_reference<decltype(facet)>::type, wchar_t>(&facet).to_bytes(var);
}
std::wstring s2w(const std::string &var)
{
static std::locale loc("");
auto &facet = std::use_facet<codecvt<wchar_t, char, std::mbstate_t>>(loc);
return std::wstring_convert<std::remove_reference<decltype(facet)>::type, wchar_t>(&facet).from_bytes(var);
}
}
<commit_msg>utf conversions for linux<commit_after>#include "stdafx.h"
#include "Logger.h"
#include <memory>
#include <locale> // wstring_convert
#include <codecvt> // codecvt_utf8_utf16
std::shared_ptr<spdlog::logger> getFallbackLogger()
{
constexpr const char *fallbackLoggerName = "Fallback_stderr";
spdlog::drop(fallbackLoggerName);
return spdlog::stderr_logger_mt(fallbackLoggerName);
}
void createLogger(std::string loggerName, spdlog::filename_t loggerFile)
{
try
{
spdlog::set_level(spdlog::level::debug);
spdlog::set_sync_mode();
Logger::logfile = spdlog::rotating_logger_mt(loggerName, loggerFile, 1024 * 1024 * 10, 3);
LOG_INFO("Synchronous logger created");
LOG_FLUSH();
}
catch (const spdlog::spdlog_ex& ex)
{
Logger::logfile = getFallbackLogger();
LOG_ERROR(std::string("Could not create regular logger! ") + ex.what());
}
}
// Do NOT call this function in dllmain.cpp!!!
// It creates new threads which is forbidden while attaching the dll
void switchToAsyncLogger(std::string loggerName, spdlog::filename_t loggerFile)
{
LOG_INFO("Switching to asynchronous logger...");
LOG_FLUSH();
Logger::logfile = nullptr;
spdlog::drop(loggerName);
try
{
spdlog::set_level(spdlog::level::debug);
spdlog::set_async_mode(131072, spdlog::async_overflow_policy::block_retry,
nullptr,
std::chrono::milliseconds(500));
Logger::logfile = spdlog::rotating_logger_mt(loggerName, loggerFile, 1024 * 1024 * 10, 3);
LOG_INFO("Switching to asynchronous logger done!");
}
catch (const spdlog::spdlog_ex& ex)
{
// Try creating the regular logger again. Might work.
try
{
createLogger(loggerName, loggerFile);
}
catch (const spdlog::spdlog_ex& ex)
{
Logger::logfile = getFallbackLogger();
LOG_ERROR(std::string("Could not create regular logger! ") + ex.what());
}
LOG_ERROR(std::string("Could not create asynchronous logger! ") + ex.what());
}
}
namespace Logger
{
// http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-closed.html#721
template<class I, class E, class S>
struct codecvt : std::codecvt<I, E, S>
{
~codecvt()
{ }
};
std::string w2s(const std::wstring &var)
{
#ifdef _WIN32 // If it ain't broke, don't fix it
static std::locale loc("");
auto &facet = std::use_facet<codecvt<wchar_t, char, std::mbstate_t>>(loc);
return std::wstring_convert<std::remove_reference<decltype(facet)>::type, wchar_t>(&facet).to_bytes(var);
#else
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
return converter.to_bytes(var);
#endif
}
std::wstring s2w(const std::string &var)
{
#ifdef _WIN32 // If it ain't broke, don't fix it
static std::locale loc("");
auto &facet = std::use_facet<codecvt<wchar_t, char, std::mbstate_t>>(loc);
return std::wstring_convert<std::remove_reference<decltype(facet)>::type, wchar_t>(&facet).from_bytes(var);
#else
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
return converter.from_bytes(var);
#endif
}
}
<|endoftext|> |
<commit_before>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010 Belledonne Communications SARL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef registrardb_hh
#define registrardb_hh
#include <map>
#include <list>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <sofia-sip/sip.h>
#include "agent.hh"
#define AOR_KEY_SIZE 128
typedef struct extended_contact {
su_home_t home;
char *mSipUri;
float mQ;
time_t mExpireAt;
time_t mUpdatedTime;
char *mCallId;
uint32_t mCSeq;
char *mLineValueCopy;
char *mRoute;
char *mContactId;
void common_init(const char *contactId, const char *route, const char* callId, const char *lineValue){
mCallId=su_strdup(&home, callId);
if (lineValue) mLineValueCopy=su_strdup(&home,lineValue);
if (route) mRoute=su_strdup(&home,route);
mContactId=su_strdup(&home, contactId);
}
extended_contact(const sip_contact_t *sip_contact, const char *contactId, const char *route, const char *lineValue, int global_expire, const char *callId, uint32_t cseq, time_t updateTime):
mQ(0),mUpdatedTime(updateTime),mCallId(NULL),mCSeq(cseq),mLineValueCopy(NULL),mRoute(NULL),mContactId(NULL) {
su_home_init(&home);
const url_t *url=sip_contact->m_url;
const char * port = (url->url_port)? url->url_port : "5060";
if (url->url_params){
if (url->url_user) {
mSipUri=su_sprintf(&home, "<sip:%s@%s:%s;%s>", url->url_user, url->url_host, port, url->url_params);
} else {
mSipUri=su_sprintf(&home, "<sip:%s:%s;%s>", url->url_host, port, url->url_params);
}
} else {
if (url->url_user) {
mSipUri=su_sprintf(&home,"<sip:%s@%s:%s>", url->url_user, url->url_host, port);
} else {
mSipUri=su_sprintf(&home,"<sip:%s:%s>", url->url_host, port);
}
}
if (sip_contact->m_q){
mQ=atof(sip_contact->m_q);
}
if (sip_contact->m_expires){
mExpireAt=updateTime+atoi(sip_contact->m_expires);
} else {
mExpireAt=updateTime+global_expire;
}
common_init(contactId, route, callId, lineValue);
}
extended_contact(const char *sip_contact, const char *contactId, const char *route, const char *lineValue, long expireAt, float q, const char *callId, uint32_t cseq, time_t updateTime)
:mSipUri(NULL),mQ(q),mExpireAt(expireAt),mUpdatedTime(updateTime),
mCallId(NULL),mCSeq(cseq),mLineValueCopy(NULL),mRoute(NULL),mContactId(NULL){
su_home_init(&home);
mSipUri=su_strdup(&home, sip_contact);
common_init(contactId, route, callId, lineValue);
}
~extended_contact(){
su_home_destroy(&home);
}
} extended_contact;
class Record{
static void init();
void insertOrUpdateBinding(extended_contact *ec);
std::list<extended_contact *> mContacts;
static std::string sLineFieldName;
static int sMaxContacts;
public:
Record();
static sip_contact_t *extendedContactToSofia(su_home_t *home, extended_contact *ec, time_t now);
const sip_contact_t * getContacts(su_home_t *home, time_t now);
bool isInvalidRegister(const char *call_id, uint32_t cseq);
void clean(const sip_contact_t *sip, const char *call_id, uint32_t cseq, time_t time);
void clean(time_t time);
void bind(const sip_contact_t *contacts, const char* route, int globalExpire, const char *call_id, uint32_t cseq, time_t now);
void bind(const char *contact, const char* route, const char *transport, const char *lineValue, long expireAt, float q, const char *call_id, uint32_t cseq, time_t now);
void print();
int count(){return mContacts.size();}
std::list<extended_contact *> &getExtendedContacts() {return mContacts;}
static int getMaxContacts(){
if (sMaxContacts == -1) init();
return sMaxContacts;}
~Record();
};
class RegistrarDbListener : public StatFinishListener {
public:
~RegistrarDbListener(){}
virtual void onRecordFound(Record *r)=0;
virtual void onError()=0;
virtual void onInvalid(){/*let the registration timeout;*/};
};
/**
* A singleton class which holds records contact addresses associated with a from.
* Both local and remote storage implementations exist.
* It is used by the Registrar module.
**/
class RegistrarDb {
public:
static RegistrarDb *get(Agent *ag);
virtual void bind(const url_t* fromUrl, const sip_contact_t *sip_contact, const char * calld_id, uint32_t cs_seq, const char *route, int global_expire, RegistrarDbListener *listener)=0;
virtual void bind(const sip_t *sip, const char* route, int global_expire, RegistrarDbListener *listener)=0;
virtual void clear(const sip_t *sip, RegistrarDbListener *listener)=0;
virtual void fetch(const url_t *url, RegistrarDbListener *listener)=0;
protected:
int count_sip_contacts(const sip_contact_t *contact);
bool errorOnTooMuchContactInBind(const sip_contact_t *sip_contact, const char *key, RegistrarDbListener *listener);
static void defineKeyFromUrl(char *key, int len, const url_t *url);
RegistrarDb();
std::map<std::string,Record*> mRecords;
static RegistrarDb *sUnique;
unsigned long long int mTotalNumberOfAddRecords;
unsigned long long int mTotalNumberOfExpiredRecords;
};
#endif
<commit_msg>Remove unused.<commit_after>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010 Belledonne Communications SARL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef registrardb_hh
#define registrardb_hh
#include <map>
#include <list>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <sofia-sip/sip.h>
#include "agent.hh"
#define AOR_KEY_SIZE 128
typedef struct extended_contact {
su_home_t home;
char *mSipUri;
float mQ;
time_t mExpireAt;
time_t mUpdatedTime;
char *mCallId;
uint32_t mCSeq;
char *mLineValueCopy;
char *mRoute;
char *mContactId;
void common_init(const char *contactId, const char *route, const char* callId, const char *lineValue){
mCallId=su_strdup(&home, callId);
if (lineValue) mLineValueCopy=su_strdup(&home,lineValue);
if (route) mRoute=su_strdup(&home,route);
mContactId=su_strdup(&home, contactId);
}
extended_contact(const sip_contact_t *sip_contact, const char *contactId, const char *route, const char *lineValue, int global_expire, const char *callId, uint32_t cseq, time_t updateTime):
mQ(0),mUpdatedTime(updateTime),mCallId(NULL),mCSeq(cseq),mLineValueCopy(NULL),mRoute(NULL),mContactId(NULL) {
su_home_init(&home);
const url_t *url=sip_contact->m_url;
const char * port = (url->url_port)? url->url_port : "5060";
if (url->url_params){
if (url->url_user) {
mSipUri=su_sprintf(&home, "<sip:%s@%s:%s;%s>", url->url_user, url->url_host, port, url->url_params);
} else {
mSipUri=su_sprintf(&home, "<sip:%s:%s;%s>", url->url_host, port, url->url_params);
}
} else {
if (url->url_user) {
mSipUri=su_sprintf(&home,"<sip:%s@%s:%s>", url->url_user, url->url_host, port);
} else {
mSipUri=su_sprintf(&home,"<sip:%s:%s>", url->url_host, port);
}
}
if (sip_contact->m_q){
mQ=atof(sip_contact->m_q);
}
if (sip_contact->m_expires){
mExpireAt=updateTime+atoi(sip_contact->m_expires);
} else {
mExpireAt=updateTime+global_expire;
}
common_init(contactId, route, callId, lineValue);
}
extended_contact(const char *sip_contact, const char *contactId, const char *route, const char *lineValue, long expireAt, float q, const char *callId, uint32_t cseq, time_t updateTime)
:mSipUri(NULL),mQ(q),mExpireAt(expireAt),mUpdatedTime(updateTime),
mCallId(NULL),mCSeq(cseq),mLineValueCopy(NULL),mRoute(NULL),mContactId(NULL){
su_home_init(&home);
mSipUri=su_strdup(&home, sip_contact);
common_init(contactId, route, callId, lineValue);
}
~extended_contact(){
su_home_destroy(&home);
}
} extended_contact;
class Record{
static void init();
void insertOrUpdateBinding(extended_contact *ec);
std::list<extended_contact *> mContacts;
static std::string sLineFieldName;
static int sMaxContacts;
public:
Record();
static sip_contact_t *extendedContactToSofia(su_home_t *home, extended_contact *ec, time_t now);
const sip_contact_t * getContacts(su_home_t *home, time_t now);
bool isInvalidRegister(const char *call_id, uint32_t cseq);
void clean(const sip_contact_t *sip, const char *call_id, uint32_t cseq, time_t time);
void clean(time_t time);
void bind(const sip_contact_t *contacts, const char* route, int globalExpire, const char *call_id, uint32_t cseq, time_t now);
void bind(const char *contact, const char* route, const char *transport, const char *lineValue, long expireAt, float q, const char *call_id, uint32_t cseq, time_t now);
void print();
int count(){return mContacts.size();}
std::list<extended_contact *> &getExtendedContacts() {return mContacts;}
static int getMaxContacts(){
if (sMaxContacts == -1) init();
return sMaxContacts;}
~Record();
};
class RegistrarDbListener : public StatFinishListener {
public:
~RegistrarDbListener(){}
virtual void onRecordFound(Record *r)=0;
virtual void onError()=0;
virtual void onInvalid(){/*let the registration timeout;*/};
};
/**
* A singleton class which holds records contact addresses associated with a from.
* Both local and remote storage implementations exist.
* It is used by the Registrar module.
**/
class RegistrarDb {
public:
static RegistrarDb *get(Agent *ag);
virtual void bind(const url_t* fromUrl, const sip_contact_t *sip_contact, const char * calld_id, uint32_t cs_seq, const char *route, int global_expire, RegistrarDbListener *listener)=0;
virtual void bind(const sip_t *sip, const char* route, int global_expire, RegistrarDbListener *listener)=0;
virtual void clear(const sip_t *sip, RegistrarDbListener *listener)=0;
virtual void fetch(const url_t *url, RegistrarDbListener *listener)=0;
protected:
int count_sip_contacts(const sip_contact_t *contact);
bool errorOnTooMuchContactInBind(const sip_contact_t *sip_contact, const char *key, RegistrarDbListener *listener);
static void defineKeyFromUrl(char *key, int len, const url_t *url);
RegistrarDb();
std::map<std::string,Record*> mRecords;
static RegistrarDb *sUnique;
};
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2013-2016 Anton Kozhevnikov, Thomas Schulthess
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
// following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
// and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/** \file splindex.hpp
*
* \brief Contains definition of splindex_base and specialization of splindex classes.
*/
#ifndef __SPLINDEX_HPP__
#define __SPLINDEX_HPP__
#include <algorithm>
#include <vector>
#include <sstream>
#include <limits>
namespace sddk {
enum splindex_t
{
block,
block_cyclic
};
/// Base class for split index.
template <typename T>
class splindex_base
{
protected:
/// Rank of the block with local fraction of the global index.
int rank_{-1};
/// Number of ranks over which the global index is distributed.
int num_ranks_{-1};
/// size of the global index
T global_index_size_;
/// Default constructor.
splindex_base()
{
}
struct location_t
{
T local_index;
int rank;
location_t(T local_index__, int rank__)
: local_index(local_index__),
rank(rank__)
{
}
};
public:
inline int rank() const
{
return rank_;
}
inline int num_ranks() const
{
return num_ranks_;
}
inline T global_index_size() const
{
return global_index_size_;
}
static inline T block_size(T size__, int num_ranks__)
{
return size__ / num_ranks__ + std::min(T(1), size__ % num_ranks__);
}
};
template <splindex_t type, typename T = int>
class splindex : public splindex_base<T>
{
};
/// Specialization for the block distribution.
template <typename T>
class splindex<block, T> : public splindex_base<T>
{
private:
T block_size_;
void init(T global_index_size__, int num_ranks__, int rank__)
{
this->global_index_size_ = global_index_size__;
if (num_ranks__ < 0) {
std::stringstream s;
s << "wrong number of ranks: " << num_ranks__;
throw std::runtime_error(s.str());
}
this->num_ranks_ = num_ranks__;
if (rank__ < 0 || rank__ >= num_ranks__) {
std::stringstream s;
s << "wrong rank: " << rank__;
throw std::runtime_error(s.str());
}
this->rank_ = rank__;
block_size_ = this->block_size(global_index_size__, num_ranks__);
}
public:
/// Default constructor
splindex()
{
}
/// Constructor.
splindex(T global_index_size__, int num_ranks__, int rank__)
{
init(global_index_size__, num_ranks__, rank__);
}
/// Return "local index, rank" pair for a global index.
inline typename splindex_base<T>::location_t location(T idxglob__) const
{
assert(idxglob__ < this->global_index_size_);
int rank = int(idxglob__ / block_size_);
T idxloc = idxglob__ - rank * block_size_;
//return std::pair<T, int>(idxloc, rank);
return typename splindex_base<T>::location_t(idxloc, rank);
}
/// Return local size of the split index for an arbitrary rank.
inline T local_size(int rank__) const
{
assert(rank__ >= 0 && rank__ < this->num_ranks_);
int n = static_cast<int>(this->global_index_size_ / block_size_);
if (rank__ < n) {
return block_size_;
} else if (rank__ == n) {
return this->global_index_size_ - rank__ * block_size_;
} else {
return 0;
}
}
/// Return local size of the split index for a current rank.
inline T local_size() const
{
return local_size(this->rank_);
}
/// Return rank which holds the element with the given global index.
inline int local_rank(T idxglob__) const
{
return location(idxglob__).rank;
}
/// Return local index of the element for the rank which handles the given global index.
inline T local_index(T idxglob__) const
{
return location(idxglob__).local_index;
}
/// Return global index of an element by local index and rank.
inline T global_index(T idxloc__, int rank__) const
{
assert(rank__ >= 0 && rank__ < this->num_ranks_);
if (local_size(rank__) == 0)
return std::numeric_limits<T>::max();
assert(idxloc__ < local_size(rank__));
return rank__ * block_size_ + idxloc__;
}
inline T global_offset() const
{
return global_index(0, this->rank_);
}
inline T global_offset(int rank__) const
{
return global_index(0, rank__);
}
inline T operator[](T idxloc__) const
{
return global_index(idxloc__, this->rank_);
}
inline std::vector<T> offsets() const
{
std::vector<T> v(this->num_ranks_);
for (int i = 0; i < this->num_ranks_; i++) {
v[i] = global_offset(i);
}
return std::move(v);
}
inline std::vector<T> counts() const
{
std::vector<T> v(this->num_ranks_);
for (int i = 0; i < this->num_ranks_; i++) {
v[i] = local_size(i);
}
return std::move(v);
}
};
/// Specialization for the block-cyclic distribution.
template <typename T>
class splindex<block_cyclic, T> : public splindex_base<T>
{
private:
/// cyclic block size of the distribution
int block_size_{-1};
// Check and initialize variables.
void init(T global_index_size__, int num_ranks__, int rank__, int block_size__)
{
this->global_index_size_ = global_index_size__;
if (num_ranks__ < 0) {
std::stringstream s;
s << "wrong number of ranks: " << num_ranks__;
throw std::runtime_error(s.str());
}
this->num_ranks_ = num_ranks__;
if (rank__ < 0 || rank__ >= num_ranks__) {
std::stringstream s;
s << "wrong rank: " << rank__;
throw std::runtime_error(s.str());
}
this->rank_ = rank__;
if (block_size__ <= 0) {
std::stringstream s;
s << "wrong block size: " << block_size__;
throw std::runtime_error(s.str());
}
block_size_ = block_size__;
}
public:
/// Default constructor
splindex()
{
}
/// Constructor with implicit cyclic block size
splindex(T global_index_size__, int num_ranks__, int rank__, int bs__)
{
init(global_index_size__, num_ranks__, rank__, bs__);
}
/// Return "local index, rank" pair for a global index.
inline typename splindex_base<T>::location_t location(T idxglob__) const
{
assert(idxglob__ < this->global_index_size_);
/* number of full blocks */
T num_blocks = idxglob__ / block_size_;
/* local index */
T idxloc = (num_blocks / this->num_ranks_) * block_size_ + idxglob__ % block_size_;
/* corresponding rank */
int rank = static_cast<int>(num_blocks % this->num_ranks_);
return typename splindex_base<T>::location_t(idxloc, rank);
}
/// Return local size of the split index for an arbitrary rank.
inline T local_size(int rank__) const
{
assert(rank__ >= 0 && rank__ < this->num_ranks_);
/* number of full blocks */
T num_blocks = this->global_index_size_ / block_size_;
T n = (num_blocks / this->num_ranks_) * block_size_;
int rank_offs = static_cast<int>(num_blocks % this->num_ranks_);
if (rank__ < rank_offs) {
n += block_size_;
} else if (rank__ == rank_offs) {
n += this->global_index_size_ % block_size_;
}
return n;
}
/// Return local size of the split index for a current rank.
inline T local_size() const
{
return local_size(this->rank_);
}
/// Return rank which holds the element with the given global index.
inline int local_rank(T idxglob__) const
{
return location(idxglob__).rank;
}
/// Return local index of the element for the rank which handles the given global index.
inline T local_index(T idxglob__) const
{
return location(idxglob__).local_index;
}
inline T global_index(T idxloc__, int rank__) const
{
assert(rank__ >= 0 && rank__ < this->num_ranks_);
assert(idxloc__ < local_size(rank__));
T nb = idxloc__ / block_size_;
return (nb * this->num_ranks_ + rank__) * block_size_ + idxloc__ % block_size_;
}
inline T operator[](T idxloc__) const
{
return global_index(idxloc__, this->rank_);
}
};
} // namespace sddk
#endif // __SPLINDEX_HPP__
<commit_msg>new custom splindex<commit_after>// Copyright (c) 2013-2016 Anton Kozhevnikov, Thomas Schulthess
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
// following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
// and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/** \file splindex.hpp
*
* \brief Contains definition of splindex_base and specialization of splindex classes.
*/
#ifndef __SPLINDEX_HPP__
#define __SPLINDEX_HPP__
#include <algorithm>
#include <vector>
#include <sstream>
#include <limits>
namespace sddk {
enum splindex_t
{
block,
block_cyclic,
custom
};
/// Base class for split index.
template <typename T>
class splindex_base
{
protected:
/// Rank of the block with local fraction of the global index.
int rank_{-1};
/// Number of ranks over which the global index is distributed.
int num_ranks_{-1};
/// size of the global index
T global_index_size_;
/// Default constructor.
splindex_base()
{
}
struct location_t
{
T local_index;
int rank;
location_t(T local_index__, int rank__)
: local_index(local_index__)
, rank(rank__)
{
}
};
public:
inline int rank() const
{
return rank_;
}
inline int num_ranks() const
{
return num_ranks_;
}
inline T global_index_size() const
{
return global_index_size_;
}
static inline T block_size(T size__, int num_ranks__)
{
return size__ / num_ranks__ + std::min(T(1), size__ % num_ranks__);
}
};
template <splindex_t type, typename T = int>
class splindex : public splindex_base<T>
{
};
/// Specialization for the block distribution.
template <typename T>
class splindex<block, T> : public splindex_base<T>
{
private:
T block_size_;
void init(T global_index_size__, int num_ranks__, int rank__)
{
this->global_index_size_ = global_index_size__;
if (num_ranks__ < 0) {
std::stringstream s;
s << "wrong number of ranks: " << num_ranks__;
throw std::runtime_error(s.str());
}
this->num_ranks_ = num_ranks__;
if (rank__ < 0 || rank__ >= num_ranks__) {
std::stringstream s;
s << "wrong rank: " << rank__;
throw std::runtime_error(s.str());
}
this->rank_ = rank__;
block_size_ = this->block_size(global_index_size__, num_ranks__);
}
public:
/// Default constructor
splindex()
{
}
/// Constructor.
splindex(T global_index_size__, int num_ranks__, int rank__)
{
init(global_index_size__, num_ranks__, rank__);
}
/// Return "local index, rank" pair for a global index.
inline typename splindex_base<T>::location_t location(T idxglob__) const
{
assert(idxglob__ < this->global_index_size_);
int rank = int(idxglob__ / block_size_);
T idxloc = idxglob__ - rank * block_size_;
//return std::pair<T, int>(idxloc, rank);
return typename splindex_base<T>::location_t(idxloc, rank);
}
/// Return local size of the split index for an arbitrary rank.
inline T local_size(int rank__) const
{
assert(rank__ >= 0 && rank__ < this->num_ranks_);
int n = static_cast<int>(this->global_index_size_ / block_size_);
if (rank__ < n) {
return block_size_;
} else if (rank__ == n) {
return this->global_index_size_ - rank__ * block_size_;
} else {
return 0;
}
}
/// Return local size of the split index for a current rank.
inline T local_size() const
{
return local_size(this->rank_);
}
/// Return rank which holds the element with the given global index.
inline int local_rank(T idxglob__) const
{
return location(idxglob__).rank;
}
/// Return local index of the element for the rank which handles the given global index.
inline T local_index(T idxglob__) const
{
return location(idxglob__).local_index;
}
/// Return global index of an element by local index and rank.
inline T global_index(T idxloc__, int rank__) const
{
assert(rank__ >= 0 && rank__ < this->num_ranks_);
if (local_size(rank__) == 0)
return std::numeric_limits<T>::max();
assert(idxloc__ < local_size(rank__));
return rank__ * block_size_ + idxloc__;
}
inline T global_offset() const
{
return global_index(0, this->rank_);
}
inline T global_offset(int rank__) const
{
return global_index(0, rank__);
}
inline T operator[](T idxloc__) const
{
return global_index(idxloc__, this->rank_);
}
inline std::vector<T> offsets() const
{
std::vector<T> v(this->num_ranks_);
for (int i = 0; i < this->num_ranks_; i++) {
v[i] = global_offset(i);
}
return std::move(v);
}
inline std::vector<T> counts() const
{
std::vector<T> v(this->num_ranks_);
for (int i = 0; i < this->num_ranks_; i++) {
v[i] = local_size(i);
}
return std::move(v);
}
};
/// Specialization for the block-cyclic distribution.
template <typename T>
class splindex<block_cyclic, T> : public splindex_base<T>
{
private:
/// cyclic block size of the distribution
int block_size_{-1};
// Check and initialize variables.
void init(T global_index_size__, int num_ranks__, int rank__, int block_size__)
{
this->global_index_size_ = global_index_size__;
if (num_ranks__ < 0) {
std::stringstream s;
s << "wrong number of ranks: " << num_ranks__;
throw std::runtime_error(s.str());
}
this->num_ranks_ = num_ranks__;
if (rank__ < 0 || rank__ >= num_ranks__) {
std::stringstream s;
s << "wrong rank: " << rank__;
throw std::runtime_error(s.str());
}
this->rank_ = rank__;
if (block_size__ <= 0) {
std::stringstream s;
s << "wrong block size: " << block_size__;
throw std::runtime_error(s.str());
}
block_size_ = block_size__;
}
public:
/// Default constructor
splindex()
{
}
/// Constructor with implicit cyclic block size
splindex(T global_index_size__, int num_ranks__, int rank__, int bs__)
{
init(global_index_size__, num_ranks__, rank__, bs__);
}
/// Return "local index, rank" pair for a global index.
inline typename splindex_base<T>::location_t location(T idxglob__) const
{
assert(idxglob__ < this->global_index_size_);
/* number of full blocks */
T num_blocks = idxglob__ / block_size_;
/* local index */
T idxloc = (num_blocks / this->num_ranks_) * block_size_ + idxglob__ % block_size_;
/* corresponding rank */
int rank = static_cast<int>(num_blocks % this->num_ranks_);
return typename splindex_base<T>::location_t(idxloc, rank);
}
/// Return local size of the split index for an arbitrary rank.
inline T local_size(int rank__) const
{
assert(rank__ >= 0 && rank__ < this->num_ranks_);
/* number of full blocks */
T num_blocks = this->global_index_size_ / block_size_;
T n = (num_blocks / this->num_ranks_) * block_size_;
int rank_offs = static_cast<int>(num_blocks % this->num_ranks_);
if (rank__ < rank_offs) {
n += block_size_;
} else if (rank__ == rank_offs) {
n += this->global_index_size_ % block_size_;
}
return n;
}
/// Return local size of the split index for a current rank.
inline T local_size() const
{
return local_size(this->rank_);
}
/// Return rank which holds the element with the given global index.
inline int local_rank(T idxglob__) const
{
return location(idxglob__).rank;
}
/// Return local index of the element for the rank which handles the given global index.
inline T local_index(T idxglob__) const
{
return location(idxglob__).local_index;
}
inline T global_index(T idxloc__, int rank__) const
{
assert(rank__ >= 0 && rank__ < this->num_ranks_);
assert(idxloc__ < local_size(rank__));
T nb = idxloc__ / block_size_;
return (nb * this->num_ranks_ + rank__) * block_size_ + idxloc__ % block_size_;
}
inline T operator[](T idxloc__) const
{
return global_index(idxloc__, this->rank_);
}
};
/// Specialization for the block distribution.
template <typename T>
class splindex<custom, T> : public splindex_base<T>
{
private:
std::vector<std::vector<T>> global_index_;
std::vector<typename splindex_base<T>::location_t> locations_;
public:
/// Default constructor.
splindex()
{
}
/// Constructor with specific partitioning.
/** The idx_map vector is expected to be of global size and store global to local index mapping for
* consecutive order of ranks. */
splindex(T global_index_size__, int num_ranks__, int rank__, std::vector<T> idx_map__)
{
this->global_index_size_ = global_index_size__;
if (num_ranks__ < 0) {
std::stringstream s;
s << "wrong number of ranks: " << num_ranks__;
throw std::runtime_error(s.str());
}
this->num_ranks_ = num_ranks__;
if (rank__ < 0 || rank__ >= num_ranks__) {
std::stringstream s;
s << "wrong rank: " << rank__;
throw std::runtime_error(s.str());
}
this->rank_ = rank__;
for (T i = 0; i < global_index_size__; i++) {
if (idx_map__[i] == 0) {
global_index_.push_back(std::vector<T>());
}
global_index_.back().push_back(i);
}
for (int r = 0; r < num_ranks__; r++) {
for (int i = 0; i < local_size(r); i++) {
locations_.push_back(splindex_base<T>::location_t(i, r));
}
}
assert(static_cast<T>(locations_.size()) == global_index_size__);
}
inline T local_size(int rank__) const
{
assert(rank__ >= 0);
assert(rank__ < this->num_ranks_);
return static_cast<T>(global_index_[rank__].size());
}
inline T local_size() const
{
return local_size(this->rank_);
}
inline int local_rank(T idxglob__) const
{
return locations_[idxglob__].rank;
}
inline T local_index(T idxglob__) const
{
return locations_[idxglob__].local_index;
}
inline T global_index(T idxloc__, int rank__) const
{
return global_index_[rank__][idxloc__];
}
inline T operator[](T idxloc__) const
{
return global_index(idxloc__, this->rank_);
}
};
} // namespace sddk
#endif // __SPLINDEX_HPP__
<|endoftext|> |
<commit_before>// Piano Hero
// Copyright (c)2006 Nicholas Piegdon
// See license.txt for license information
#include "State_Playing.h"
#include "State_TrackSelection.h"
#include "version.h"
#include <string>
using namespace std;
#include "string_util.h"
#include "MenuLayout.h"
#include "TextWriter.h"
#include "libmidi\Midi.h"
#include "libmidi\MidiTrack.h"
#include "libmidi\MidiEvent.h"
#include "libmidi\MidiUtil.h"
#include "libmidi\MidiComm.h"
void PlayingState::ResetSong()
{
m_state.midi_out->Reset();
// NOTE: These should be moved to a configuration file
// along with ALL other "const static something" variables.
const static unsigned long long LeadIn = 6000000;
const static unsigned long long LeadOut = 2500000;
if (!m_state.midi) return;
m_state.midi->Reset(LeadIn, LeadOut);
m_notes = m_state.midi->Notes();
unsigned long long additional_time = m_state.midi->GetFirstNoteMicroseconds();
additional_time -= LeadIn;
Play(additional_time);
}
PlayingState::PlayingState(const SharedState &state)
: m_state(state), m_keyboard(0), m_first_update(true), m_paused(false)
{ }
void PlayingState::Init()
{
if (!m_state.midi) throw GameStateError("PlayingState: Init was passed a null MIDI!");
m_playback_speed = 100;
// This many microseconds of the song will
// be shown on the screen at once
const static unsigned long long DefaultShowDurationMicroseconds = 5000000;
m_show_duration = DefaultShowDurationMicroseconds;
m_keyboard = new KeyboardDisplay(KeyboardSize88, GetStateWidth() - 2*Layout::ScreenMarginX, CalcKeyboardHeight());
// Hide the mouse cursor while we're playing
ShowCursor(false);
ResetSong();
}
PlayingState::~PlayingState()
{
ShowCursor(true);
}
int PlayingState::CalcKeyboardHeight() const
{
// Start with the size of the screen
int height = GetStateHeight();
// Leave at least enough for a title bar and horizontal
// rule at the top
height -= Layout::ScreenMarginY;
// Allow another couple lines of text below the HR
height -= Layout::ButtonFontSize * 4;
return height;
}
void PlayingState::Play(unsigned long long delta_microseconds)
{
MidiEventListWithTrackId evs = m_state.midi->Update(delta_microseconds);
const size_t length = evs.size();
for (size_t i = 0; i < length; ++i)
{
const size_t &track_id = evs[i].first;
const MidiEvent &ev = evs[i].second;
// Draw refers to the keys lighting up (automatically) -- not necessarily
// the falling notes. The KeyboardDisplay object contains its own logic
// to decide how to draw the falling notes
bool draw = false;
bool play = false;
switch (m_state.track_properties[track_id].mode)
{
case ModeNotPlayed: draw = false; play = false; break;
case ModePlayedButHidden: draw = false; play = true; break;
case ModeYouPlay: draw = false; play = false; break;
case ModePlayedAutomatically: draw = true; play = true; break;
}
if (draw && ev.Type() == MidiEventType_NoteOn || ev.Type() == MidiEventType_NoteOff)
{
int vel = ev.NoteVelocity();
const string name = MidiEvent::NoteName(ev.NoteNumber());
m_keyboard->SetKeyActive(name, (vel > 0), m_state.track_properties[track_id].color);
}
if (play) m_state.midi_out->Write(ev);
}
}
void PlayingState::Update()
{
const unsigned long long current_microseconds = GetStateMilliseconds() * 1000;
unsigned long long delta_microseconds = static_cast<unsigned long long>(GetDeltaMilliseconds()) * 1000;
// The 100 term is really paired with the playback speed, but this
// formation is less likely to produce overflow errors.
delta_microseconds = (delta_microseconds / 100) * m_playback_speed;
if (m_paused) delta_microseconds = 0;
// Our delta milliseconds on the first frame after state start is extra
// long because we just reset the MIDI. By skipping the "Play" that
// update, we don't have an artificially fast-forwarded start.
if (!m_first_update)
{
Play(delta_microseconds);
}
m_first_update = false;
// Delete notes that are finished playing
unsigned long long cur_time = m_state.midi->GetSongPositionInMicroseconds();
for (TranslatedNoteSet::iterator i = m_notes.begin(); i != m_notes.end(); )
{
TranslatedNoteSet::iterator next = i;
++next;
if (i->end < cur_time) m_notes.erase(i);
i = next;
}
if (IsKeyPressed(KeyUp))
{
m_show_duration -= 250000;
if (m_show_duration < 250000) m_show_duration = 250000;
}
if (IsKeyPressed(KeyDown))
{
m_show_duration += 250000;
if (m_show_duration > 10000000) m_show_duration = 10000000;
}
if (IsKeyPressed(KeyLeft))
{
m_playback_speed -= 10;
if (m_playback_speed < 0) m_playback_speed = 0;
}
if (IsKeyPressed(KeyRight))
{
m_playback_speed += 10;
if (m_playback_speed > 400) m_playback_speed = 400;
}
if (IsKeyPressed(KeyEnter))
{
ResetSong();
m_keyboard->ResetActiveKeys();
}
if (IsKeyPressed(KeySpace))
{
m_paused = !m_paused;
}
if (IsKeyPressed(KeyEscape) || m_state.midi->GetSongPercentageComplete() >= 1.0)
{
ChangeState(new TrackSelectionState(m_state));
}
}
void PlayingState::Draw(HDC hdc) const
{
m_keyboard->Draw(hdc, Layout::ScreenMarginX, GetStateHeight() - CalcKeyboardHeight(), m_notes,
m_show_duration, m_state.midi->GetSongPositionInMicroseconds(), m_state.track_properties);
Layout::DrawTitle(hdc, m_state.song_title);
Layout::DrawHorizontalRule(hdc, GetStateWidth(), Layout::ScreenMarginY);
double non_zero_playback_speed = ( (m_playback_speed == 0) ? 0.1 : (m_playback_speed/100.0) );
unsigned long long tot_seconds = static_cast<unsigned long long>((m_state.midi->GetSongLengthInMicroseconds() / 100000.0) / non_zero_playback_speed);
unsigned long long cur_seconds = static_cast<unsigned long long>((m_state.midi->GetSongPositionInMicroseconds() / 100000.0) / non_zero_playback_speed);
int completion = static_cast<int>(m_state.midi->GetSongPercentageComplete() * 100.0);
unsigned int tot_min = static_cast<unsigned int>((tot_seconds/10) / 60);
unsigned int tot_sec = static_cast<unsigned int>((tot_seconds/10) % 60);
unsigned int tot_ten = static_cast<unsigned int>( tot_seconds%10 );
const wstring total_time = WSTRING(tot_min << L":" << setfill(L'0') << setw(2) << tot_sec << L"." << tot_ten);
unsigned int cur_min = static_cast<unsigned int>((cur_seconds/10) / 60);
unsigned int cur_sec = static_cast<unsigned int>((cur_seconds/10) % 60);
unsigned int cur_ten = static_cast<unsigned int>( cur_seconds%10 );
const wstring current_time = WSTRING(cur_min << L":" << setfill(L'0') << setw(2) << cur_sec << L"." << cur_ten);
const wstring percent_complete = WSTRING(L" (" << completion << L"%)");
int small_text_y = Layout::ScreenMarginY + Layout::SmallFontSize;
TextWriter stats1(Layout::ScreenMarginX, small_text_y, hdc, false, Layout::SmallFontSize);
stats1 << Text(L"Time: ", Gray) << current_time << L" / " << total_time << percent_complete << newline;
stats1 << Text(L"Speed: ", Gray) << m_playback_speed << L"%" << newline;
TextWriter stats2(Layout::ScreenMarginX + 220, small_text_y, hdc, false, Layout::SmallFontSize);
stats2 << Text(L"Events: ", Gray) << m_state.midi->AggregateEventCount() - m_state.midi->AggregateEventsRemain() << L" / " << m_state.midi->AggregateEventCount() << newline;
stats2 << Text(L"Notes: ", Gray) << m_state.midi->AggregateNoteCount() - m_state.midi->AggregateNotesRemain() << L" / " << m_state.midi->AggregateNoteCount() << newline;
}
<commit_msg>Early input device selection.<commit_after>// Piano Hero
// Copyright (c)2006 Nicholas Piegdon
// See license.txt for license information
#include "State_Playing.h"
#include "State_TrackSelection.h"
#include "version.h"
#include <string>
using namespace std;
#include "string_util.h"
#include "MenuLayout.h"
#include "TextWriter.h"
#include "libmidi\Midi.h"
#include "libmidi\MidiTrack.h"
#include "libmidi\MidiEvent.h"
#include "libmidi\MidiUtil.h"
#include "libmidi\MidiComm.h"
void PlayingState::ResetSong()
{
if (m_state.midi_out) m_state.midi_out->Reset();
// NOTE: These should be moved to a configuration file
// along with ALL other "const static something" variables.
const static unsigned long long LeadIn = 6000000;
const static unsigned long long LeadOut = 2500000;
if (!m_state.midi) return;
m_state.midi->Reset(LeadIn, LeadOut);
m_notes = m_state.midi->Notes();
unsigned long long additional_time = m_state.midi->GetFirstNoteMicroseconds();
additional_time -= LeadIn;
Play(additional_time);
}
PlayingState::PlayingState(const SharedState &state)
: m_state(state), m_keyboard(0), m_first_update(true), m_paused(false)
{ }
void PlayingState::Init()
{
if (!m_state.midi) throw GameStateError("PlayingState: Init was passed a null MIDI!");
m_playback_speed = 100;
// This many microseconds of the song will
// be shown on the screen at once
const static unsigned long long DefaultShowDurationMicroseconds = 5000000;
m_show_duration = DefaultShowDurationMicroseconds;
m_keyboard = new KeyboardDisplay(KeyboardSize88, GetStateWidth() - 2*Layout::ScreenMarginX, CalcKeyboardHeight());
// Hide the mouse cursor while we're playing
ShowCursor(false);
ResetSong();
}
PlayingState::~PlayingState()
{
ShowCursor(true);
}
int PlayingState::CalcKeyboardHeight() const
{
// Start with the size of the screen
int height = GetStateHeight();
// Leave at least enough for a title bar and horizontal
// rule at the top
height -= Layout::ScreenMarginY;
// Allow another couple lines of text below the HR
height -= Layout::ButtonFontSize * 4;
return height;
}
void PlayingState::Play(unsigned long long delta_microseconds)
{
MidiEventListWithTrackId evs = m_state.midi->Update(delta_microseconds);
const size_t length = evs.size();
for (size_t i = 0; i < length; ++i)
{
const size_t &track_id = evs[i].first;
const MidiEvent &ev = evs[i].second;
// Draw refers to the keys lighting up (automatically) -- not necessarily
// the falling notes. The KeyboardDisplay object contains its own logic
// to decide how to draw the falling notes
bool draw = false;
bool play = false;
switch (m_state.track_properties[track_id].mode)
{
case ModeNotPlayed: draw = false; play = false; break;
case ModePlayedButHidden: draw = false; play = true; break;
case ModeYouPlay: draw = false; play = false; break;
case ModePlayedAutomatically: draw = true; play = true; break;
}
if (draw && ev.Type() == MidiEventType_NoteOn || ev.Type() == MidiEventType_NoteOff)
{
int vel = ev.NoteVelocity();
const string name = MidiEvent::NoteName(ev.NoteNumber());
m_keyboard->SetKeyActive(name, (vel > 0), m_state.track_properties[track_id].color);
}
if (play && m_state.midi_out) m_state.midi_out->Write(ev);
}
}
void PlayingState::Update()
{
const unsigned long long current_microseconds = GetStateMilliseconds() * 1000;
unsigned long long delta_microseconds = static_cast<unsigned long long>(GetDeltaMilliseconds()) * 1000;
// The 100 term is really paired with the playback speed, but this
// formation is less likely to produce overflow errors.
delta_microseconds = (delta_microseconds / 100) * m_playback_speed;
if (m_paused) delta_microseconds = 0;
// Our delta milliseconds on the first frame after state start is extra
// long because we just reset the MIDI. By skipping the "Play" that
// update, we don't have an artificially fast-forwarded start.
if (!m_first_update)
{
Play(delta_microseconds);
}
m_first_update = false;
// Delete notes that are finished playing
unsigned long long cur_time = m_state.midi->GetSongPositionInMicroseconds();
for (TranslatedNoteSet::iterator i = m_notes.begin(); i != m_notes.end(); )
{
TranslatedNoteSet::iterator next = i;
++next;
if (i->end < cur_time) m_notes.erase(i);
i = next;
}
if (IsKeyPressed(KeyUp))
{
m_show_duration -= 250000;
if (m_show_duration < 250000) m_show_duration = 250000;
}
if (IsKeyPressed(KeyDown))
{
m_show_duration += 250000;
if (m_show_duration > 10000000) m_show_duration = 10000000;
}
if (IsKeyPressed(KeyLeft))
{
m_playback_speed -= 10;
if (m_playback_speed < 0) m_playback_speed = 0;
}
if (IsKeyPressed(KeyRight))
{
m_playback_speed += 10;
if (m_playback_speed > 400) m_playback_speed = 400;
}
if (IsKeyPressed(KeyEnter))
{
ResetSong();
m_keyboard->ResetActiveKeys();
}
if (IsKeyPressed(KeySpace))
{
m_paused = !m_paused;
}
if (IsKeyPressed(KeyEscape) || m_state.midi->GetSongPercentageComplete() >= 1.0)
{
ChangeState(new TrackSelectionState(m_state));
}
}
void PlayingState::Draw(HDC hdc) const
{
m_keyboard->Draw(hdc, Layout::ScreenMarginX, GetStateHeight() - CalcKeyboardHeight(), m_notes,
m_show_duration, m_state.midi->GetSongPositionInMicroseconds(), m_state.track_properties);
Layout::DrawTitle(hdc, m_state.song_title);
Layout::DrawHorizontalRule(hdc, GetStateWidth(), Layout::ScreenMarginY);
double non_zero_playback_speed = ( (m_playback_speed == 0) ? 0.1 : (m_playback_speed/100.0) );
unsigned long long tot_seconds = static_cast<unsigned long long>((m_state.midi->GetSongLengthInMicroseconds() / 100000.0) / non_zero_playback_speed);
unsigned long long cur_seconds = static_cast<unsigned long long>((m_state.midi->GetSongPositionInMicroseconds() / 100000.0) / non_zero_playback_speed);
int completion = static_cast<int>(m_state.midi->GetSongPercentageComplete() * 100.0);
unsigned int tot_min = static_cast<unsigned int>((tot_seconds/10) / 60);
unsigned int tot_sec = static_cast<unsigned int>((tot_seconds/10) % 60);
unsigned int tot_ten = static_cast<unsigned int>( tot_seconds%10 );
const wstring total_time = WSTRING(tot_min << L":" << setfill(L'0') << setw(2) << tot_sec << L"." << tot_ten);
unsigned int cur_min = static_cast<unsigned int>((cur_seconds/10) / 60);
unsigned int cur_sec = static_cast<unsigned int>((cur_seconds/10) % 60);
unsigned int cur_ten = static_cast<unsigned int>( cur_seconds%10 );
const wstring current_time = WSTRING(cur_min << L":" << setfill(L'0') << setw(2) << cur_sec << L"." << cur_ten);
const wstring percent_complete = WSTRING(L" (" << completion << L"%)");
int small_text_y = Layout::ScreenMarginY + Layout::SmallFontSize;
TextWriter stats1(Layout::ScreenMarginX, small_text_y, hdc, false, Layout::SmallFontSize);
stats1 << Text(L"Time: ", Gray) << current_time << L" / " << total_time << percent_complete << newline;
stats1 << Text(L"Speed: ", Gray) << m_playback_speed << L"%" << newline;
TextWriter stats2(Layout::ScreenMarginX + 220, small_text_y, hdc, false, Layout::SmallFontSize);
stats2 << Text(L"Events: ", Gray) << m_state.midi->AggregateEventCount() - m_state.midi->AggregateEventsRemain() << L" / " << m_state.midi->AggregateEventCount() << newline;
stats2 << Text(L"Notes: ", Gray) << m_state.midi->AggregateNoteCount() - m_state.midi->AggregateNotesRemain() << L" / " << m_state.midi->AggregateNoteCount() << newline;
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//////////////////////////////////////////////////////////////////////////////
// //
// The AliDAQ class is responsible for handling all the information about //
// Data Acquisition configuration. It defines the detector indexing, //
// the number of DDLs and LDCs per detector. //
// The number of LDCs per detector is used only in the simulation in order //
// to define the configuration of the dateStream application. Therefore the //
// numbers in the corresponding array can be changed without affecting the //
// rest of the aliroot code. //
// The equipment ID (DDL ID) is an integer (32-bit) number defined as: //
// Equipment ID = (detectorID << 8) + DDLIndex //
// where the detectorID is given by fgkDetectorName array and DDLIndex is //
// the index of the corresponding DDL inside the detector partition. //
// Due to DAQ/HLT limitations, the ddl indexes should be consequtive, or //
// at least without big gaps in between. //
// The sub-detector code use only this class in the simulation and reading //
// of the raw data. //
// //
// [email protected] 2006/06/09 //
// //
//////////////////////////////////////////////////////////////////////////////
#include <TClass.h>
#include <TString.h>
#include "AliDAQ.h"
#include "AliLog.h"
ClassImp(AliDAQ)
const char* AliDAQ::fgkDetectorName[AliDAQ::kNDetectors] = {
"ITSSPD",
"ITSSDD",
"ITSSSD",
"TPC",
"TRD",
"TOF",
"HMPID",
"PHOS",
"CPV",
"PMD",
"MUONTRK",
"MUONTRG",
"FMD",
"T0",
"VZERO", // Name to be changed to V0 ?
"ZDC",
"ACORDE",
"TRG",
"EMCAL",
"HLT"
};
Int_t AliDAQ::fgkNumberOfDdls[AliDAQ::kNDetectors] = {
20,
24,
16,
216,
18,
72,
20,
20,
10,
6,
20,
2,
3,
1,
1,
1,
1,
1,
24,
10
};
Float_t AliDAQ::fgkNumberOfLdcs[AliDAQ::kNDetectors] = {
4,
4,
4,
36,
3,
12,
4,
4,
2,
1,
4,
1,
1,
0.5,
0.5,
1,
1,
1,
4,
5
};
AliDAQ::AliDAQ(const AliDAQ& source) :
TObject(source)
{
// Copy constructor
// Nothing to be done
}
AliDAQ& AliDAQ::operator = (const AliDAQ& /* source */)
{
// Assignment operator
// Nothing to be done
return *this;
}
Int_t AliDAQ::DetectorID(const char *detectorName)
{
// Return the detector index
// corresponding to a given
// detector name
TString detStr = detectorName;
Int_t iDet;
for(iDet = 0; iDet < kNDetectors; iDet++) {
if (detStr.CompareTo(fgkDetectorName[iDet],TString::kIgnoreCase) == 0)
break;
}
if (iDet == kNDetectors) {
AliErrorClass(Form("Invalid detector name: %s !",detectorName));
return -1;
}
return iDet;
}
const char *AliDAQ::DetectorName(Int_t detectorID)
{
// Returns the name of particular
// detector identified by its index
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return "";
}
return fgkDetectorName[detectorID];
}
Int_t AliDAQ::DdlIDOffset(const char *detectorName)
{
// Returns the DDL ID offset
// for a given detector
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return -1;
return DdlIDOffset(detectorID);
}
Int_t AliDAQ::DdlIDOffset(Int_t detectorID)
{
// Returns the DDL ID offset
// for a given detector identified
// by its index
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return -1;
}
return (detectorID << 8);
}
const char *AliDAQ::DetectorNameFromDdlID(Int_t ddlID,Int_t &ddlIndex)
{
// Returns the detector name for
// a given DDL ID
ddlIndex = -1;
Int_t detectorID = DetectorIDFromDdlID(ddlID,ddlIndex);
if (detectorID < 0)
return "";
return DetectorName(detectorID);
}
Int_t AliDAQ::DetectorIDFromDdlID(Int_t ddlID,Int_t &ddlIndex)
{
// Returns the detector ID and
// the ddl index within the
// detector range for
// a given input DDL ID
Int_t detectorID = ddlID >> 8;
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return -1;
}
ddlIndex = ddlID & 0xFF;
if (ddlIndex >= fgkNumberOfDdls[detectorID]) {
AliErrorClass(Form("Invalid DDL index %d (%d -> %d) for detector %d",
ddlIndex,0,fgkNumberOfDdls[detectorID],detectorID));
ddlIndex = -1;
return -1;
}
return detectorID;
}
Int_t AliDAQ::DdlID(const char *detectorName, Int_t ddlIndex)
{
// Returns the DDL ID starting from
// the detector name and the DDL
// index inside the detector
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return -1;
return DdlID(detectorID,ddlIndex);
}
Int_t AliDAQ::DdlID(Int_t detectorID, Int_t ddlIndex)
{
// Returns the DDL ID starting from
// the detector ID and the DDL
// index inside the detector
Int_t ddlID = DdlIDOffset(detectorID);
if (ddlID < 0)
return -1;
if (ddlIndex >= fgkNumberOfDdls[detectorID]) {
AliErrorClass(Form("Invalid DDL index %d (%d -> %d) for detector %d",
ddlIndex,0,fgkNumberOfDdls[detectorID],detectorID));
return -1;
}
ddlID += ddlIndex;
return ddlID;
}
const char *AliDAQ::DdlFileName(const char *detectorName, Int_t ddlIndex)
{
// Returns the DDL file name
// (used in the simulation) starting from
// the detector name and the DDL
// index inside the detector
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return "";
return DdlFileName(detectorID,ddlIndex);
}
const char *AliDAQ::DdlFileName(Int_t detectorID, Int_t ddlIndex)
{
// Returns the DDL file name
// (used in the simulation) starting from
// the detector ID and the DDL
// index inside the detector
Int_t ddlID = DdlIDOffset(detectorID);
if (ddlID < 0)
return "";
if (ddlIndex >= fgkNumberOfDdls[detectorID]) {
AliErrorClass(Form("Invalid DDL index %d (%d -> %d) for detector %d",
ddlIndex,0,fgkNumberOfDdls[detectorID],detectorID));
return "";
}
ddlID += ddlIndex;
TString fileName = DetectorName(detectorID);
fileName += "_";
fileName += ddlID;
fileName += ".ddl";
return fileName.Data();
}
Int_t AliDAQ::NumberOfDdls(const char *detectorName)
{
// Returns the number of DDLs for
// a given detector
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return -1;
return NumberOfDdls(detectorID);
}
Int_t AliDAQ::NumberOfDdls(Int_t detectorID)
{
// Returns the number of DDLs for
// a given detector
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return -1;
}
return fgkNumberOfDdls[detectorID];
}
Float_t AliDAQ::NumberOfLdcs(const char *detectorName)
{
// Returns the number of DDLs for
// a given detector
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return -1;
return NumberOfLdcs(detectorID);
}
Float_t AliDAQ::NumberOfLdcs(Int_t detectorID)
{
// Returns the number of DDLs for
// a given detector
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return -1;
}
return fgkNumberOfLdcs[detectorID];
}
void AliDAQ::PrintConfig()
{
// Print the DAQ configuration
// for all the detectors
printf("====================================================================\n"
"| ALICE Data Acquisition Configuration |\n"
"====================================================================\n"
"| Detector ID | Detector Name | DDL Offset | # of DDLs | # of LDCs |\n"
"====================================================================\n");
for(Int_t iDet = 0; iDet < kNDetectors; iDet++) {
printf("|%11d |%13s |%10d |%9d |%9.1f |\n",
iDet,DetectorName(iDet),DdlIDOffset(iDet),NumberOfDdls(iDet),NumberOfLdcs(iDet));
}
printf("====================================================================\n");
}
<commit_msg>Using static TString to keep the name of the file<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//////////////////////////////////////////////////////////////////////////////
// //
// The AliDAQ class is responsible for handling all the information about //
// Data Acquisition configuration. It defines the detector indexing, //
// the number of DDLs and LDCs per detector. //
// The number of LDCs per detector is used only in the simulation in order //
// to define the configuration of the dateStream application. Therefore the //
// numbers in the corresponding array can be changed without affecting the //
// rest of the aliroot code. //
// The equipment ID (DDL ID) is an integer (32-bit) number defined as: //
// Equipment ID = (detectorID << 8) + DDLIndex //
// where the detectorID is given by fgkDetectorName array and DDLIndex is //
// the index of the corresponding DDL inside the detector partition. //
// Due to DAQ/HLT limitations, the ddl indexes should be consequtive, or //
// at least without big gaps in between. //
// The sub-detector code use only this class in the simulation and reading //
// of the raw data. //
// //
// [email protected] 2006/06/09 //
// //
//////////////////////////////////////////////////////////////////////////////
#include <TClass.h>
#include <TString.h>
#include "AliDAQ.h"
#include "AliLog.h"
ClassImp(AliDAQ)
const char* AliDAQ::fgkDetectorName[AliDAQ::kNDetectors] = {
"ITSSPD",
"ITSSDD",
"ITSSSD",
"TPC",
"TRD",
"TOF",
"HMPID",
"PHOS",
"CPV",
"PMD",
"MUONTRK",
"MUONTRG",
"FMD",
"T0",
"VZERO", // Name to be changed to V0 ?
"ZDC",
"ACORDE",
"TRG",
"EMCAL",
"HLT"
};
Int_t AliDAQ::fgkNumberOfDdls[AliDAQ::kNDetectors] = {
20,
24,
16,
216,
18,
72,
20,
20,
10,
6,
20,
2,
3,
1,
1,
1,
1,
1,
24,
10
};
Float_t AliDAQ::fgkNumberOfLdcs[AliDAQ::kNDetectors] = {
4,
4,
4,
36,
3,
12,
4,
4,
2,
1,
4,
1,
1,
0.5,
0.5,
1,
1,
1,
4,
5
};
AliDAQ::AliDAQ(const AliDAQ& source) :
TObject(source)
{
// Copy constructor
// Nothing to be done
}
AliDAQ& AliDAQ::operator = (const AliDAQ& /* source */)
{
// Assignment operator
// Nothing to be done
return *this;
}
Int_t AliDAQ::DetectorID(const char *detectorName)
{
// Return the detector index
// corresponding to a given
// detector name
TString detStr = detectorName;
Int_t iDet;
for(iDet = 0; iDet < kNDetectors; iDet++) {
if (detStr.CompareTo(fgkDetectorName[iDet],TString::kIgnoreCase) == 0)
break;
}
if (iDet == kNDetectors) {
AliErrorClass(Form("Invalid detector name: %s !",detectorName));
return -1;
}
return iDet;
}
const char *AliDAQ::DetectorName(Int_t detectorID)
{
// Returns the name of particular
// detector identified by its index
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return "";
}
return fgkDetectorName[detectorID];
}
Int_t AliDAQ::DdlIDOffset(const char *detectorName)
{
// Returns the DDL ID offset
// for a given detector
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return -1;
return DdlIDOffset(detectorID);
}
Int_t AliDAQ::DdlIDOffset(Int_t detectorID)
{
// Returns the DDL ID offset
// for a given detector identified
// by its index
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return -1;
}
return (detectorID << 8);
}
const char *AliDAQ::DetectorNameFromDdlID(Int_t ddlID,Int_t &ddlIndex)
{
// Returns the detector name for
// a given DDL ID
ddlIndex = -1;
Int_t detectorID = DetectorIDFromDdlID(ddlID,ddlIndex);
if (detectorID < 0)
return "";
return DetectorName(detectorID);
}
Int_t AliDAQ::DetectorIDFromDdlID(Int_t ddlID,Int_t &ddlIndex)
{
// Returns the detector ID and
// the ddl index within the
// detector range for
// a given input DDL ID
Int_t detectorID = ddlID >> 8;
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return -1;
}
ddlIndex = ddlID & 0xFF;
if (ddlIndex >= fgkNumberOfDdls[detectorID]) {
AliErrorClass(Form("Invalid DDL index %d (%d -> %d) for detector %d",
ddlIndex,0,fgkNumberOfDdls[detectorID],detectorID));
ddlIndex = -1;
return -1;
}
return detectorID;
}
Int_t AliDAQ::DdlID(const char *detectorName, Int_t ddlIndex)
{
// Returns the DDL ID starting from
// the detector name and the DDL
// index inside the detector
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return -1;
return DdlID(detectorID,ddlIndex);
}
Int_t AliDAQ::DdlID(Int_t detectorID, Int_t ddlIndex)
{
// Returns the DDL ID starting from
// the detector ID and the DDL
// index inside the detector
Int_t ddlID = DdlIDOffset(detectorID);
if (ddlID < 0)
return -1;
if (ddlIndex >= fgkNumberOfDdls[detectorID]) {
AliErrorClass(Form("Invalid DDL index %d (%d -> %d) for detector %d",
ddlIndex,0,fgkNumberOfDdls[detectorID],detectorID));
return -1;
}
ddlID += ddlIndex;
return ddlID;
}
const char *AliDAQ::DdlFileName(const char *detectorName, Int_t ddlIndex)
{
// Returns the DDL file name
// (used in the simulation) starting from
// the detector name and the DDL
// index inside the detector
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return "";
return DdlFileName(detectorID,ddlIndex);
}
const char *AliDAQ::DdlFileName(Int_t detectorID, Int_t ddlIndex)
{
// Returns the DDL file name
// (used in the simulation) starting from
// the detector ID and the DDL
// index inside the detector
Int_t ddlID = DdlIDOffset(detectorID);
if (ddlID < 0)
return "";
if (ddlIndex >= fgkNumberOfDdls[detectorID]) {
AliErrorClass(Form("Invalid DDL index %d (%d -> %d) for detector %d",
ddlIndex,0,fgkNumberOfDdls[detectorID],detectorID));
return "";
}
ddlID += ddlIndex;
static TString fileName;
fileName = DetectorName(detectorID);
fileName += "_";
fileName += ddlID;
fileName += ".ddl";
return fileName.Data();
}
Int_t AliDAQ::NumberOfDdls(const char *detectorName)
{
// Returns the number of DDLs for
// a given detector
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return -1;
return NumberOfDdls(detectorID);
}
Int_t AliDAQ::NumberOfDdls(Int_t detectorID)
{
// Returns the number of DDLs for
// a given detector
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return -1;
}
return fgkNumberOfDdls[detectorID];
}
Float_t AliDAQ::NumberOfLdcs(const char *detectorName)
{
// Returns the number of DDLs for
// a given detector
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return -1;
return NumberOfLdcs(detectorID);
}
Float_t AliDAQ::NumberOfLdcs(Int_t detectorID)
{
// Returns the number of DDLs for
// a given detector
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return -1;
}
return fgkNumberOfLdcs[detectorID];
}
void AliDAQ::PrintConfig()
{
// Print the DAQ configuration
// for all the detectors
printf("====================================================================\n"
"| ALICE Data Acquisition Configuration |\n"
"====================================================================\n"
"| Detector ID | Detector Name | DDL Offset | # of DDLs | # of LDCs |\n"
"====================================================================\n");
for(Int_t iDet = 0; iDet < kNDetectors; iDet++) {
printf("|%11d |%13s |%10d |%9d |%9.1f |\n",
iDet,DetectorName(iDet),DdlIDOffset(iDet),NumberOfDdls(iDet),NumberOfLdcs(iDet));
}
printf("====================================================================\n");
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: anytostring.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 02:27:17 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#if ! defined(INCLUDED_COMPHELPER_ANYTOSTRING_HXX)
#define INCLUDED_COMPHELPER_ANYTOSTRING_HXX
#ifndef _RTL_USTRING_HXX_
#include "rtl/ustring.hxx"
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include "com/sun/star/uno/Any.hxx"
#endif
#ifndef INCLUDED_COMPHELPERDLLAPI_H
#include "comphelper/comphelperdllapi.h"
#endif
namespace comphelper
{
/** Creates a STRING representation out of an ANY value.
@param value
ANY value
@return
STRING representation of given ANY value
*/
COMPHELPER_DLLPUBLIC ::rtl::OUString anyToString( ::com::sun::star::uno::Any const & value );
}
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.5.246); FILE MERGED 2008/04/01 15:05:18 thb 1.5.246.3: #i85898# Stripping all external header guards 2008/04/01 12:26:23 thb 1.5.246.2: #i85898# Stripping all external header guards 2008/03/31 12:19:27 rt 1.5.246.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: anytostring.hxx,v $
* $Revision: 1.6 $
*
* 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.
*
************************************************************************/
#if ! defined(INCLUDED_COMPHELPER_ANYTOSTRING_HXX)
#define INCLUDED_COMPHELPER_ANYTOSTRING_HXX
#include "rtl/ustring.hxx"
#include "com/sun/star/uno/Any.hxx"
#include "comphelper/comphelperdllapi.h"
namespace comphelper
{
/** Creates a STRING representation out of an ANY value.
@param value
ANY value
@return
STRING representation of given ANY value
*/
COMPHELPER_DLLPUBLIC ::rtl::OUString anyToString( ::com::sun::star::uno::Any const & value );
}
#endif
<|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Open the mesh and solution file given, create a new solution file,
// and copy all listed variables from the old solution to the new.
#include "libmesh/libmesh.h"
#include "libmesh/equation_systems.h"
#include "libmesh/mesh.h"
#include "libmesh/numeric_vector.h"
unsigned int dim = 2; // This gets overridden by most mesh formats
int main(int argc, char** argv)
{
using namespace libMesh;
LibMeshInit init(argc, argv);
Mesh mesh1(dim);
EquationSystems es1(mesh1);
std::cout << "Usage: " << argv[0]
<< " mesh oldsolution newsolution system1 variable1 [sys2 var2...]" << std::endl;
// We should have one system name for each variable name, and those
// get preceded by an even number of arguments.
libmesh_assert (!(argc % 2));
// We should have at least one system/variable pair following the
// initial arguments
libmesh_assert_greater_equal (argc, 6);
mesh1.read(argv[1]);
std::cout << "Loaded mesh " << argv[1] << std::endl;
Mesh mesh2(mesh1);
EquationSystems es2(mesh2);
es1.read(argv[2],
EquationSystems::READ_HEADER |
EquationSystems::READ_DATA |
EquationSystems::READ_ADDITIONAL_DATA |
EquationSystems::READ_BASIC_ONLY);
std::cout << "Loaded solution " << argv[2] << std::endl;
std::vector<unsigned int> old_sys_num((argc-4)/2),
new_sys_num((argc-4)/2),
old_var_num((argc-4)/2),
new_var_num((argc-4)/2);
std::vector<const System *> old_system((argc-4)/2);
std::vector<System *> new_system((argc-4)/2);
for (int argi = 4; argi < argc; argi += 2)
{
const char* sysname = argv[argi];
const char* varname = argv[argi+1];
const unsigned int pairnum = (argi-4)/2;
libmesh_assert(es1.has_system(sysname));
const System &old_sys = es1.get_system(sysname);
old_system[pairnum] = &old_sys;
old_sys_num[pairnum] = old_sys.number();
libmesh_assert(old_sys.has_variable(varname));
old_var_num[pairnum] = old_sys.variable_number(varname);
const Variable &variable = old_sys.variable(old_var_num[pairnum]);
std::string systype = old_sys.system_type();
System &new_sys = es2.add_system(systype, sysname);
new_system[pairnum] = &new_sys;
new_sys_num[pairnum] = new_sys.number();
new_var_num[pairnum] =
new_sys.add_variable(varname, variable.type(),
&variable.active_subdomains());
}
es2.init();
// A future version of this app should copy variables for
// non-solution vectors too.
// Copy over any nodal degree of freedom coefficients
MeshBase::const_node_iterator old_nit = mesh1.local_nodes_begin(),
new_nit = mesh2.local_nodes_begin();
const MeshBase::const_node_iterator old_nit_end = mesh1.local_nodes_end();
for (; old_nit != old_nit_end; ++old_nit, ++new_nit)
{
const Node* old_node = *old_nit;
const Node* new_node = *new_nit;
// Mesh::operator= hopefully preserved elem/node orderings...
libmesh_assert (*old_node == *new_node);
for (int argi = 4; argi < argc; argi += 2)
{
const unsigned int pairnum = (argi-4)/2;
const System &old_sys = *old_system[pairnum];
System &new_sys = *new_system[pairnum];
const unsigned int n_comp =
old_node->n_comp(old_sys_num[pairnum],old_var_num[pairnum]);
libmesh_assert_equal_to(n_comp,
new_node->n_comp(new_sys_num[pairnum],new_var_num[pairnum]));
for(unsigned int i=0; i<n_comp; i++)
{
const unsigned int
old_index = old_node->dof_number
(old_sys_num[pairnum], old_var_num[pairnum], i),
new_index = new_node->dof_number
(new_sys_num[pairnum], new_var_num[pairnum], i);
new_sys.solution->set(new_index,(*old_sys.solution)(old_index));
}
}
}
// Copy over any element degree of freedom coefficients
MeshBase::const_element_iterator old_eit = mesh1.active_local_elements_begin(),
new_eit = mesh2.active_local_elements_begin();
const MeshBase::const_element_iterator old_eit_end = mesh1.active_local_elements_end();
for (; old_eit != old_eit_end; ++old_eit, ++new_eit)
{
const Elem* old_elem = *old_eit;
const Elem* new_elem = *new_eit;
// Mesh::operator= hopefully preserved elem/node orderings...
libmesh_assert (*old_elem == *new_elem);
for (int argi = 4; argi < argc; argi += 2)
{
const unsigned int pairnum = (argi-4)/2;
const System &old_sys = *old_system[pairnum];
System &new_sys = *new_system[pairnum];
const unsigned int n_comp =
old_elem->n_comp(old_sys_num[pairnum],old_var_num[pairnum]);
libmesh_assert_equal_to(n_comp,
new_elem->n_comp(new_sys_num[pairnum],new_var_num[pairnum]));
for(unsigned int i=0; i<n_comp; i++)
{
const unsigned int
old_index = old_elem->dof_number
(old_sys_num[pairnum], old_var_num[pairnum], i),
new_index = new_elem->dof_number
(new_sys_num[pairnum], new_var_num[pairnum], i);
new_sys.solution->set(new_index,(*old_sys.solution)(old_index));
}
}
}
es2.write(argv[3], EquationSystems::WRITE_DATA);
return 0;
}
<commit_msg>dof_id_type fixes<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Open the mesh and solution file given, create a new solution file,
// and copy all listed variables from the old solution to the new.
#include "libmesh/libmesh.h"
#include "libmesh/equation_systems.h"
#include "libmesh/mesh.h"
#include "libmesh/numeric_vector.h"
unsigned int dim = 2; // This gets overridden by most mesh formats
int main(int argc, char** argv)
{
using namespace libMesh;
LibMeshInit init(argc, argv);
Mesh mesh1(dim);
EquationSystems es1(mesh1);
std::cout << "Usage: " << argv[0]
<< " mesh oldsolution newsolution system1 variable1 [sys2 var2...]" << std::endl;
// We should have one system name for each variable name, and those
// get preceded by an even number of arguments.
libmesh_assert (!(argc % 2));
// We should have at least one system/variable pair following the
// initial arguments
libmesh_assert_greater_equal (argc, 6);
mesh1.read(argv[1]);
std::cout << "Loaded mesh " << argv[1] << std::endl;
Mesh mesh2(mesh1);
EquationSystems es2(mesh2);
es1.read(argv[2],
EquationSystems::READ_HEADER |
EquationSystems::READ_DATA |
EquationSystems::READ_ADDITIONAL_DATA |
EquationSystems::READ_BASIC_ONLY);
std::cout << "Loaded solution " << argv[2] << std::endl;
std::vector<unsigned int> old_sys_num((argc-4)/2),
new_sys_num((argc-4)/2),
old_var_num((argc-4)/2),
new_var_num((argc-4)/2);
std::vector<const System *> old_system((argc-4)/2);
std::vector<System *> new_system((argc-4)/2);
for (int argi = 4; argi < argc; argi += 2)
{
const char* sysname = argv[argi];
const char* varname = argv[argi+1];
const unsigned int pairnum = (argi-4)/2;
libmesh_assert(es1.has_system(sysname));
const System &old_sys = es1.get_system(sysname);
old_system[pairnum] = &old_sys;
old_sys_num[pairnum] = old_sys.number();
libmesh_assert(old_sys.has_variable(varname));
old_var_num[pairnum] = old_sys.variable_number(varname);
const Variable &variable = old_sys.variable(old_var_num[pairnum]);
std::string systype = old_sys.system_type();
System &new_sys = es2.add_system(systype, sysname);
new_system[pairnum] = &new_sys;
new_sys_num[pairnum] = new_sys.number();
new_var_num[pairnum] =
new_sys.add_variable(varname, variable.type(),
&variable.active_subdomains());
}
es2.init();
// A future version of this app should copy variables for
// non-solution vectors too.
// Copy over any nodal degree of freedom coefficients
MeshBase::const_node_iterator old_nit = mesh1.local_nodes_begin(),
new_nit = mesh2.local_nodes_begin();
const MeshBase::const_node_iterator old_nit_end = mesh1.local_nodes_end();
for (; old_nit != old_nit_end; ++old_nit, ++new_nit)
{
const Node* old_node = *old_nit;
const Node* new_node = *new_nit;
// Mesh::operator= hopefully preserved elem/node orderings...
libmesh_assert (*old_node == *new_node);
for (int argi = 4; argi < argc; argi += 2)
{
const unsigned int pairnum = (argi-4)/2;
const System &old_sys = *old_system[pairnum];
System &new_sys = *new_system[pairnum];
const unsigned int n_comp =
old_node->n_comp(old_sys_num[pairnum],old_var_num[pairnum]);
libmesh_assert_equal_to(n_comp,
new_node->n_comp(new_sys_num[pairnum],new_var_num[pairnum]));
for(unsigned int i=0; i<n_comp; i++)
{
const dof_index_type
old_index = old_node->dof_number
(old_sys_num[pairnum], old_var_num[pairnum], i),
new_index = new_node->dof_number
(new_sys_num[pairnum], new_var_num[pairnum], i);
new_sys.solution->set(new_index,(*old_sys.solution)(old_index));
}
}
}
// Copy over any element degree of freedom coefficients
MeshBase::const_element_iterator old_eit = mesh1.active_local_elements_begin(),
new_eit = mesh2.active_local_elements_begin();
const MeshBase::const_element_iterator old_eit_end = mesh1.active_local_elements_end();
for (; old_eit != old_eit_end; ++old_eit, ++new_eit)
{
const Elem* old_elem = *old_eit;
const Elem* new_elem = *new_eit;
// Mesh::operator= hopefully preserved elem/node orderings...
libmesh_assert (*old_elem == *new_elem);
for (int argi = 4; argi < argc; argi += 2)
{
const unsigned int pairnum = (argi-4)/2;
const System &old_sys = *old_system[pairnum];
System &new_sys = *new_system[pairnum];
const unsigned int n_comp =
old_elem->n_comp(old_sys_num[pairnum],old_var_num[pairnum]);
libmesh_assert_equal_to(n_comp,
new_elem->n_comp(new_sys_num[pairnum],new_var_num[pairnum]));
for(unsigned int i=0; i<n_comp; i++)
{
const dof_index_type
old_index = old_elem->dof_number
(old_sys_num[pairnum], old_var_num[pairnum], i),
new_index = new_elem->dof_number
(new_sys_num[pairnum], new_var_num[pairnum], i);
new_sys.solution->set(new_index,(*old_sys.solution)(old_index));
}
}
}
es2.write(argv[3], EquationSystems::WRITE_DATA);
return 0;
}
<|endoftext|> |
<commit_before>// Vaca - Visual Application Components Abstraction
// Copyright (c) 2005-2009 David Capello
// 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 <Vaca/Vaca.h>
#include "../resource.h"
#include "md5.h"
#include "sha1.h"
using namespace Vaca;
//////////////////////////////////////////////////////////////////////
// MD5
static String MD5File(const String& fileName)
{
FILE* stream = _wfopen(fileName.c_str(), L"rb");
if (stream == NULL)
return String(L"Error loading file");
MD5_CTX md5;
MD5Init(&md5);
unsigned char buf[1024];
size_t len;
while ((len = fread(buf, 1, 1024, stream)))
MD5Update(&md5, buf, len);
fclose(stream);
unsigned char digest[16];
MD5Final(digest, &md5);
// transform "digest" to String
String res;
for(int c=0; c<16; ++c)
res += format_string(L"%02x", digest[c]);
return res;
}
//////////////////////////////////////////////////////////////////////
// SHA1
static String SHA1File(const String &fileName)
{
FILE* stream = _wfopen(fileName.c_str(), L"rb");
if (stream == NULL)
return String(L"Error loading file");
SHA1Context sha;
SHA1Reset(&sha);
unsigned char buf[1024];
size_t len;
while ((len = fread(buf, 1, 1024, stream)))
SHA1Input(&sha, buf, len);
fclose(stream);
uint8_t digest[20];
SHA1Result(&sha, digest);
// transform "digest" to String
String res;
for(int c=0; c<20; ++c)
res += format_string(L"%02x", digest[c]);
return res;
}
//////////////////////////////////////////////////////////////////////
class MainFrame : public Frame
{
Label m_helpLabel;
ListView m_filesList;
TextEdit m_md5Edit;
TextEdit m_shaEdit;
LinkLabel m_md5Label;
LinkLabel m_shaLabel;
public:
MainFrame()
: Frame(L"Hashing")
, m_helpLabel(L"Drop files to the list", this)
, m_filesList(this, ListView::Styles::Default +
ListView::Styles::SingleSelection +
Widget::Styles::AcceptFiles)
, m_md5Edit(L"", this, TextEdit::Styles::Default +
TextEdit::Styles::ReadOnly)
, m_shaEdit(L"", this, TextEdit::Styles::Default +
TextEdit::Styles::ReadOnly)
, m_md5Label(L"http://www.faqs.org/rfcs/rfc1321.html",
L"RFC 1321 - The MD5 Message-Digest Algorithm", this)
, m_shaLabel(L"http://www.faqs.org/rfcs/rfc3174.html",
L"RFC 3174 - US Secure Hash Algorithm 1 (SHA1)", this)
{
setLayout(Bix::parse(L"Y[%,f%,XY[%,fx%;%,fx%]]",
&m_helpLabel,
&m_filesList,
&m_md5Label, &m_md5Edit,
&m_shaLabel, &m_shaEdit));
// setup report view
m_filesList.setType(ListViewType::Report);
m_filesList.addColumn(L"Filename");
m_filesList.addColumn(L"MD5");
m_filesList.addColumn(L"SHA1");
// signals
m_filesList.DropFiles.connect(&MainFrame::onDropFilesInFilesList, this);
m_filesList.AfterSelect.connect(&MainFrame::onSelectFileInList, this);
// get the small image list from the system and put it in the ListView
m_filesList.setSmallImageList(System::getImageList(true));
}
private:
void onDropFilesInFilesList(DropFilesEvent& ev)
{
std::vector<String> files = ev.getFiles();
// m_filesList.removeAllItems();
// add items in the list
for (std::vector<String>::iterator
it = files.begin(); it != files.end(); ++it) {
// get the what image to use
int imageIndex = System::getFileImageIndex((*it), true);
// add the new item and hold its index
int itemIndex = m_filesList.addItem(file_name(*it), imageIndex);
// calculates the MD5 and SHA1 of the file
m_filesList.setItemText(itemIndex, MD5File(*it), 1);
m_filesList.setItemText(itemIndex, SHA1File(*it), 2);
}
// set preferred with for each column
int n = m_filesList.getColumnCount();
for (int i=0; i<n; ++i)
m_filesList.setPreferredColumnWidth(i, true);
}
void onSelectFileInList(ListViewEvent& ev)
{
int itemIndex = ev.getItemIndex();
if (itemIndex >= 0) {
m_md5Edit.setText(m_filesList.getItemText(itemIndex, 1));
m_shaEdit.setText(m_filesList.getItemText(itemIndex, 2));
}
}
};
//////////////////////////////////////////////////////////////////////
int VACA_MAIN()
{
Application app;
MainFrame frm;
frm.setIcon(ResourceId(IDI_VACA));
frm.setVisible(true);
app.run();
return 0;
}
<commit_msg>Fixed some compilation errors including std namespace for <cstdio><commit_after>// Vaca - Visual Application Components Abstraction
// Copyright (c) 2005-2009 David Capello
// 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 <Vaca/Vaca.h>
#include "../resource.h"
#include "md5.h"
#include "sha1.h"
#include <cstdio>
using namespace std;
using namespace Vaca;
//////////////////////////////////////////////////////////////////////
// MD5
static String MD5File(const String& fileName)
{
FILE* stream = _wfopen(fileName.c_str(), L"rb");
if (stream == NULL)
return String(L"Error loading file");
MD5_CTX md5;
MD5Init(&md5);
unsigned char buf[1024];
size_t len;
while ((len = fread(buf, 1, 1024, stream)))
MD5Update(&md5, buf, len);
fclose(stream);
unsigned char digest[16];
MD5Final(digest, &md5);
// transform "digest" to String
String res;
for(int c=0; c<16; ++c)
res += format_string(L"%02x", digest[c]);
return res;
}
//////////////////////////////////////////////////////////////////////
// SHA1
static String SHA1File(const String &fileName)
{
FILE* stream = _wfopen(fileName.c_str(), L"rb");
if (stream == NULL)
return String(L"Error loading file");
SHA1Context sha;
SHA1Reset(&sha);
unsigned char buf[1024];
size_t len;
while ((len = fread(buf, 1, 1024, stream)))
SHA1Input(&sha, buf, len);
fclose(stream);
uint8_t digest[20];
SHA1Result(&sha, digest);
// transform "digest" to String
String res;
for(int c=0; c<20; ++c)
res += format_string(L"%02x", digest[c]);
return res;
}
//////////////////////////////////////////////////////////////////////
class MainFrame : public Frame
{
Label m_helpLabel;
ListView m_filesList;
TextEdit m_md5Edit;
TextEdit m_shaEdit;
LinkLabel m_md5Label;
LinkLabel m_shaLabel;
public:
MainFrame()
: Frame(L"Hashing")
, m_helpLabel(L"Drop files to the list", this)
, m_filesList(this, ListView::Styles::Default +
ListView::Styles::SingleSelection +
Widget::Styles::AcceptFiles)
, m_md5Edit(L"", this, TextEdit::Styles::Default +
TextEdit::Styles::ReadOnly)
, m_shaEdit(L"", this, TextEdit::Styles::Default +
TextEdit::Styles::ReadOnly)
, m_md5Label(L"http://www.faqs.org/rfcs/rfc1321.html",
L"RFC 1321 - The MD5 Message-Digest Algorithm", this)
, m_shaLabel(L"http://www.faqs.org/rfcs/rfc3174.html",
L"RFC 3174 - US Secure Hash Algorithm 1 (SHA1)", this)
{
setLayout(Bix::parse(L"Y[%,f%,XY[%,fx%;%,fx%]]",
&m_helpLabel,
&m_filesList,
&m_md5Label, &m_md5Edit,
&m_shaLabel, &m_shaEdit));
// setup report view
m_filesList.setType(ListViewType::Report);
m_filesList.addColumn(L"Filename");
m_filesList.addColumn(L"MD5");
m_filesList.addColumn(L"SHA1");
// signals
m_filesList.DropFiles.connect(&MainFrame::onDropFilesInFilesList, this);
m_filesList.AfterSelect.connect(&MainFrame::onSelectFileInList, this);
// get the small image list from the system and put it in the ListView
m_filesList.setSmallImageList(System::getImageList(true));
}
private:
void onDropFilesInFilesList(DropFilesEvent& ev)
{
vector<String> files = ev.getFiles();
// Add items in the list
for (vector<String>::iterator
it = files.begin(); it != files.end(); ++it) {
// Get the what image to use
int imageIndex = System::getFileImageIndex((*it), true);
// add the new item and hold its index
int itemIndex = m_filesList.addItem(file_name(*it), imageIndex);
// calculates the MD5 and SHA1 of the file
m_filesList.setItemText(itemIndex, MD5File(*it), 1);
m_filesList.setItemText(itemIndex, SHA1File(*it), 2);
}
// set preferred with for each column
int n = m_filesList.getColumnCount();
for (int i=0; i<n; ++i)
m_filesList.setPreferredColumnWidth(i, true);
}
void onSelectFileInList(ListViewEvent& ev)
{
int itemIndex = ev.getItemIndex();
if (itemIndex >= 0) {
m_md5Edit.setText(m_filesList.getItemText(itemIndex, 1));
m_shaEdit.setText(m_filesList.getItemText(itemIndex, 2));
}
}
};
//////////////////////////////////////////////////////////////////////
int VACA_MAIN()
{
Application app;
MainFrame frm;
frm.setIcon(ResourceId(IDI_VACA));
frm.setVisible(true);
app.run();
return 0;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
Largest area rectangle histogram
================================
Ref - http://www.geeksforgeeks.org/largest-rectangle-under-histogram/
- http://www.geeksforgeeks.org/largest-rectangular-area-in-a-histogram-set-1/
--------------------------------------------------------------------------------
Problem
=======
Given a histogram find the area of the largest rectangle formed by it.
--------------------------------------------------------------------------------
Time Complexity
===============
O(n) - Each bar pushed to stack only once
--------------------------------------------------------------------------------
Output
======
Buy on day : 0 Sell on day: 3
Buy on day : 4 Sell on day: 6
*******************************************************************************/
#include <stdio.h>
#include <stack>
using namespace std;
int maxArea(int hist[], int n) {
stack<int> s; // holds indexes of bars in increasing order of heights
int max = 0, i = 0;
while(i < n) {
// pushing current bar to stack if it exceeds stack top
if(s.empty() || hist[i] >= hist[s.top()])
s.push(i++);
// finding area since current bar is less than the stack top
// area of rectangle with stack top as the smallest height
// right index -> i
// left index -> element before s.top()
else {
int top = s.top();
s.pop();
// if stack is empty then this is smallest member and left index is 0
int area = hist[top] * (s.empty() ? i : i - s.top() - 1);
if(area > max)
max = area;
}
}
// finding area for remaining smaller bars
while(!s.empty()) {
int top = s.top();
s.pop();
int area = hist[top] * (s.empty() ? i : i - s.top() - 1);
if(area > max)
max = area;
}
return max;
}
int main() {
int hist[] = {6, 2, 5, 4, 5, 1, 6};
printf("Max area: %d\n", maxArea(hist, 7));
return 0;
}
<commit_msg>:star2: Update Largest area of rectangle under histogram<commit_after>/*******************************************************************************
Largest area rectangle histogram
================================
Ref - http://www.geeksforgeeks.org/largest-rectangle-under-histogram/
- http://www.geeksforgeeks.org/largest-rectangular-area-in-a-histogram-set-1/
--------------------------------------------------------------------------------
Problem
=======
Given a histogram find the area of the largest rectangle formed by it.
--------------------------------------------------------------------------------
Time Complexity
===============
O(n) - Each bar pushed to stack only once
--------------------------------------------------------------------------------
Output
======
Max area: 12
*******************************************************************************/
#include <stdio.h>
#include <stack>
using namespace std;
int maxArea(int hist[], int n) {
stack<int> s; // holds indexes of bars in increasing order of heights
int max = 0, i = 0;
while(i < n) {
// pushing current bar to stack if it exceeds stack top
if(s.empty() || hist[i] >= hist[s.top()])
s.push(i++);
// finding area since current bar is less than the stack top
// area of rectangle with stack top as the smallest height
// right index -> i
// left index -> element before s.top()
else {
int top = s.top();
s.pop();
// if stack is empty then this is smallest member and left index is 0
int area = hist[top] * (s.empty() ? i : i - s.top() - 1);
if(area > max)
max = area;
}
}
// finding area for remaining smaller bars
while(!s.empty()) {
int top = s.top();
s.pop();
int area = hist[top] * (s.empty() ? i : i - s.top() - 1);
if(area > max)
max = area;
}
return max;
}
int main() {
int hist[] = {6, 2, 5, 4, 5, 1, 6};
printf("Max area: %d\n", maxArea(hist, 7));
return 0;
}
<|endoftext|> |
<commit_before>//
// Copyright RIME Developers
// Distributed under the BSD License
//
// 2011-04-24 GONG Chen <[email protected]>
//
#include <cctype>
#include <rime/common.h>
#include <rime/composition.h>
#include <rime/context.h>
#include <rime/engine.h>
#include <rime/filter.h>
#include <rime/formatter.h>
#include <rime/key_event.h>
#include <rime/menu.h>
#include <rime/processor.h>
#include <rime/schema.h>
#include <rime/segmentation.h>
#include <rime/segmentor.h>
#include <rime/switcher.h>
#include <rime/ticket.h>
#include <rime/translation.h>
#include <rime/translator.h>
namespace rime {
class ConcreteEngine : public Engine {
public:
ConcreteEngine();
virtual ~ConcreteEngine();
virtual bool ProcessKey(const KeyEvent& key_event);
virtual void ApplySchema(Schema* schema);
virtual void CommitText(string text);
virtual void Compose(Context* ctx);
protected:
void InitializeComponents();
void InitializeOptions();
void CalculateSegmentation(Segmentation* segments);
void TranslateSegments(Segmentation* segments);
void FormatText(string* text);
void OnCommit(Context* ctx);
void OnSelect(Context* ctx);
void OnContextUpdate(Context* ctx);
void OnOptionUpdate(Context* ctx, const string& option);
void OnPropertyUpdate(Context* ctx, const string& property);
vector<of<Processor>> processors_;
vector<of<Segmentor>> segmentors_;
vector<of<Translator>> translators_;
vector<of<Filter>> filters_;
vector<of<Formatter>> formatters_;
vector<of<Processor>> post_processors_;
};
// implementations
Engine* Engine::Create() {
return new ConcreteEngine;
}
Engine::Engine() : schema_(new Schema), context_(new Context) {
}
Engine::~Engine() {
context_.reset();
schema_.reset();
}
ConcreteEngine::ConcreteEngine() {
LOG(INFO) << "starting engine.";
// receive context notifications
context_->commit_notifier().connect(
[this](Context* ctx) { OnCommit(ctx); });
context_->select_notifier().connect(
[this](Context* ctx) { OnSelect(ctx); });
context_->update_notifier().connect(
[this](Context* ctx) { OnContextUpdate(ctx); });
context_->option_update_notifier().connect(
[this](Context* ctx, const string& option) {
OnOptionUpdate(ctx, option);
});
context_->property_update_notifier().connect(
[this](Context* ctx, const string& property) {
OnPropertyUpdate(ctx, property);
});
InitializeComponents();
InitializeOptions();
}
ConcreteEngine::~ConcreteEngine() {
LOG(INFO) << "engine disposed.";
processors_.clear();
segmentors_.clear();
translators_.clear();
}
bool ConcreteEngine::ProcessKey(const KeyEvent& key_event) {
DLOG(INFO) << "process key: " << key_event;
ProcessResult ret = kNoop;
for (auto& processor : processors_) {
ret = processor->ProcessKeyEvent(key_event);
if (ret == kRejected) break;
if (ret == kAccepted) return true;
}
// record unhandled keys, eg. spaces, numbers, bksp's.
context_->commit_history().Push(key_event);
// post-processing
for (auto& processor : post_processors_) {
ret = processor->ProcessKeyEvent(key_event);
if (ret == kRejected) break;
if (ret == kAccepted) return true;
}
// notify interested parties
context_->unhandled_key_notifier()(context_.get(), key_event);
return false;
}
void ConcreteEngine::OnContextUpdate(Context* ctx) {
if (!ctx) return;
Compose(ctx);
}
void ConcreteEngine::OnOptionUpdate(Context* ctx, const string& option) {
if (!ctx) return;
LOG(INFO) << "updated option: " << option;
// apply new option to active segment
if (ctx->IsComposing()) {
ctx->RefreshNonConfirmedComposition();
}
// notification
bool option_is_on = ctx->get_option(option);
string msg(option_is_on ? option : "!" + option);
message_sink_("option", msg);
}
void ConcreteEngine::OnPropertyUpdate(Context* ctx, const string& property) {
if (!ctx) return;
LOG(INFO) << "updated property: " << property;
// notification
string value = ctx->get_property(property);
string msg(property + "=" + value);
message_sink_("property", msg);
}
void ConcreteEngine::Compose(Context* ctx) {
if (!ctx) return;
Composition& comp = ctx->composition();
const string active_input = ctx->input().substr(0, ctx->caret_pos());
DLOG(INFO) << "active input: " << active_input;
comp.Reset(active_input);
if (ctx->caret_pos() < ctx->input().length() &&
ctx->caret_pos() == comp.GetConfirmedPosition()) {
// translate one segment past caret pos.
comp.Reset(ctx->input());
}
CalculateSegmentation(&comp);
TranslateSegments(&comp);
DLOG(INFO) << "composition: " << comp.GetDebugText();
}
void ConcreteEngine::CalculateSegmentation(Segmentation* segments) {
while (!segments->HasFinishedSegmentation()) {
size_t start_pos = segments->GetCurrentStartPosition();
size_t end_pos = segments->GetCurrentEndPosition();
DLOG(INFO) << "start pos: " << start_pos;
DLOG(INFO) << "end pos: " << end_pos;
// recognize a segment by calling the segmentors in turn
for (auto& segmentor : segmentors_) {
if (!segmentor->Proceed(segments))
break;
}
DLOG(INFO) << "segmentation: " << *segments;
// no advancement
if (start_pos == segments->GetCurrentEndPosition())
break;
// only one segment is allowed past caret pos, which is the segment
// immediately after the caret.
if (start_pos >= context_->caret_pos())
break;
// move onto the next segment...
if (!segments->HasFinishedSegmentation())
segments->Forward();
}
// start an empty segment only at the end of a confirmed composition.
segments->Trim();
if (!segments->empty() && segments->back().status >= Segment::kSelected)
segments->Forward();
}
void ConcreteEngine::TranslateSegments(Segmentation* segments) {
for (Segment& segment : *segments) {
if (segment.status >= Segment::kGuess)
continue;
size_t len = segment.end - segment.start;
if (len == 0)
continue;
string input = segments->input().substr(segment.start, len);
DLOG(INFO) << "translating segment: " << input;
auto menu = New<Menu>();
for (auto& translator : translators_) {
auto translation = translator->Query(input, segment);
if (!translation)
continue;
if (translation->exhausted()) {
LOG(INFO) << "Oops, got a futile translation.";
continue;
}
menu->AddTranslation(translation);
}
for (auto& filter : filters_) {
if (filter->AppliesToSegment(&segment)) {
menu->AddFilter(filter.get());
}
}
segment.status = Segment::kGuess;
segment.menu = menu;
segment.selected_index = 0;
}
}
void ConcreteEngine::FormatText(string* text) {
if (formatters_.empty())
return;
DLOG(INFO) << "applying formatters.";
for (auto& formatter : formatters_) {
formatter->Format(text);
}
}
void ConcreteEngine::CommitText(string text) {
context_->commit_history().Push(CommitRecord{"raw", text});
FormatText(&text);
DLOG(INFO) << "committing text: " << text;
sink_(text);
}
void ConcreteEngine::OnCommit(Context* ctx) {
context_->commit_history().Push(ctx->composition(), ctx->input());
string text = ctx->GetCommitText();
FormatText(&text);
DLOG(INFO) << "committing composition: " << text;
sink_(text);
}
void ConcreteEngine::OnSelect(Context* ctx) {
Segment& seg(ctx->composition().back());
seg.Close();
if (seg.end == ctx->input().length()) {
// composition has finished
seg.status = Segment::kConfirmed;
// strategy one: commit directly;
// strategy two: continue composing with another empty segment.
if (ctx->get_option("_auto_commit"))
ctx->Commit();
else
ctx->composition().Forward();
}
else {
bool updateCaret = (seg.end >= ctx->caret_pos());
ctx->composition().Forward();
if (updateCaret) {
// finished converting current segment
// move caret to the end of input
ctx->set_caret_pos(ctx->input().length());
}
else {
Compose(ctx);
}
}
}
void ConcreteEngine::ApplySchema(Schema* schema) {
if (!schema)
return;
schema_.reset(schema);
context_->Clear();
context_->ClearTransientOptions();
InitializeComponents();
InitializeOptions();
message_sink_("schema", schema->schema_id() + "/" + schema->schema_name());
}
void ConcreteEngine::InitializeComponents() {
processors_.clear();
segmentors_.clear();
translators_.clear();
filters_.clear();
if (auto switcher = New<Switcher>(this)) {
processors_.push_back(switcher);
if (schema_->schema_id() == ".default") {
if (Schema* schema = switcher->CreateSchema()) {
schema_.reset(schema);
}
}
}
Config* config = schema_->config();
if (!config)
return;
// create processors
if (auto processor_list = config->GetList("engine/processors")) {
size_t n = processor_list->size();
for (size_t i = 0; i < n; ++i) {
auto prescription = As<ConfigValue>(processor_list->GetAt(i));
if (!prescription)
continue;
Ticket ticket{this, "processor", prescription->str()};
if (auto c = Processor::Require(ticket.klass)) {
an<Processor> p(c->Create(ticket));
processors_.push_back(p);
}
else {
LOG(ERROR) << "error creating processor: '" << ticket.klass << "'";
}
}
}
// create segmentors
if (auto segmentor_list = config->GetList("engine/segmentors")) {
size_t n = segmentor_list->size();
for (size_t i = 0; i < n; ++i) {
auto prescription = As<ConfigValue>(segmentor_list->GetAt(i));
if (!prescription)
continue;
Ticket ticket{this, "segmentor", prescription->str()};
if (auto c = Segmentor::Require(ticket.klass)) {
an<Segmentor> s(c->Create(ticket));
segmentors_.push_back(s);
}
else {
LOG(ERROR) << "error creating segmentor: '" << ticket.klass << "'";
}
}
}
// create translators
if (auto translator_list = config->GetList("engine/translators")) {
size_t n = translator_list->size();
for (size_t i = 0; i < n; ++i) {
auto prescription = As<ConfigValue>(translator_list->GetAt(i));
if (!prescription)
continue;
Ticket ticket{this, "translator", prescription->str()};
if (auto c = Translator::Require(ticket.klass)) {
an<Translator> t(c->Create(ticket));
translators_.push_back(t);
}
else {
LOG(ERROR) << "error creating translator: '" << ticket.klass << "'";
}
}
}
// create filters
if (auto filter_list = config->GetList("engine/filters")) {
size_t n = filter_list->size();
for (size_t i = 0; i < n; ++i) {
auto prescription = As<ConfigValue>(filter_list->GetAt(i));
if (!prescription)
continue;
Ticket ticket{this, "filter", prescription->str()};
if (auto c = Filter::Require(ticket.klass)) {
an<Filter> f(c->Create(ticket));
filters_.push_back(f);
}
else {
LOG(ERROR) << "error creating filter: '" << ticket.klass << "'";
}
}
}
// create formatters
if (auto c = Formatter::Require("shape_formatter")) {
an<Formatter> f(c->Create(Ticket(this)));
formatters_.push_back(f);
}
else {
LOG(WARNING) << "shape_formatter not available.";
}
// create post-processors
if (auto c = Processor::Require("shape_processor")) {
an<Processor> p(c->Create(Ticket(this)));
post_processors_.push_back(p);
}
else {
LOG(WARNING) << "shape_processor not available.";
}
}
void ConcreteEngine::InitializeOptions() {
// reset custom switches
Config* config = schema_->config();
if (auto switches = config->GetList("switches")) {
for (size_t i = 0; i < switches->size(); ++i) {
auto item = As<ConfigMap>(switches->GetAt(i));
if (!item)
continue;
auto reset_value = item->GetValue("reset");
if (!reset_value)
continue;
int value = 0;
reset_value->GetInt(&value);
if (auto option_name = item->GetValue("name")) {
// toggle
context_->set_option(option_name->str(), (value != 0));
}
else if (auto options = As<ConfigList>(item->Get("options"))) {
// radio
for (size_t i = 0; i < options->size(); ++i) {
if (auto option_name = options->GetValueAt(i)) {
context_->set_option(option_name->str(),
static_cast<int>(i) == value);
}
}
}
}
}
}
} // namespace rime
<commit_msg>chore(engine.cc): Google code style; more informative name<commit_after>//
// Copyright RIME Developers
// Distributed under the BSD License
//
// 2011-04-24 GONG Chen <[email protected]>
//
#include <cctype>
#include <rime/common.h>
#include <rime/composition.h>
#include <rime/context.h>
#include <rime/engine.h>
#include <rime/filter.h>
#include <rime/formatter.h>
#include <rime/key_event.h>
#include <rime/menu.h>
#include <rime/processor.h>
#include <rime/schema.h>
#include <rime/segmentation.h>
#include <rime/segmentor.h>
#include <rime/switcher.h>
#include <rime/ticket.h>
#include <rime/translation.h>
#include <rime/translator.h>
namespace rime {
class ConcreteEngine : public Engine {
public:
ConcreteEngine();
virtual ~ConcreteEngine();
virtual bool ProcessKey(const KeyEvent& key_event);
virtual void ApplySchema(Schema* schema);
virtual void CommitText(string text);
virtual void Compose(Context* ctx);
protected:
void InitializeComponents();
void InitializeOptions();
void CalculateSegmentation(Segmentation* segments);
void TranslateSegments(Segmentation* segments);
void FormatText(string* text);
void OnCommit(Context* ctx);
void OnSelect(Context* ctx);
void OnContextUpdate(Context* ctx);
void OnOptionUpdate(Context* ctx, const string& option);
void OnPropertyUpdate(Context* ctx, const string& property);
vector<of<Processor>> processors_;
vector<of<Segmentor>> segmentors_;
vector<of<Translator>> translators_;
vector<of<Filter>> filters_;
vector<of<Formatter>> formatters_;
vector<of<Processor>> post_processors_;
};
// implementations
Engine* Engine::Create() {
return new ConcreteEngine;
}
Engine::Engine() : schema_(new Schema), context_(new Context) {
}
Engine::~Engine() {
context_.reset();
schema_.reset();
}
ConcreteEngine::ConcreteEngine() {
LOG(INFO) << "starting engine.";
// receive context notifications
context_->commit_notifier().connect(
[this](Context* ctx) { OnCommit(ctx); });
context_->select_notifier().connect(
[this](Context* ctx) { OnSelect(ctx); });
context_->update_notifier().connect(
[this](Context* ctx) { OnContextUpdate(ctx); });
context_->option_update_notifier().connect(
[this](Context* ctx, const string& option) {
OnOptionUpdate(ctx, option);
});
context_->property_update_notifier().connect(
[this](Context* ctx, const string& property) {
OnPropertyUpdate(ctx, property);
});
InitializeComponents();
InitializeOptions();
}
ConcreteEngine::~ConcreteEngine() {
LOG(INFO) << "engine disposed.";
processors_.clear();
segmentors_.clear();
translators_.clear();
}
bool ConcreteEngine::ProcessKey(const KeyEvent& key_event) {
DLOG(INFO) << "process key: " << key_event;
ProcessResult ret = kNoop;
for (auto& processor : processors_) {
ret = processor->ProcessKeyEvent(key_event);
if (ret == kRejected) break;
if (ret == kAccepted) return true;
}
// record unhandled keys, eg. spaces, numbers, bksp's.
context_->commit_history().Push(key_event);
// post-processing
for (auto& processor : post_processors_) {
ret = processor->ProcessKeyEvent(key_event);
if (ret == kRejected) break;
if (ret == kAccepted) return true;
}
// notify interested parties
context_->unhandled_key_notifier()(context_.get(), key_event);
return false;
}
void ConcreteEngine::OnContextUpdate(Context* ctx) {
if (!ctx) return;
Compose(ctx);
}
void ConcreteEngine::OnOptionUpdate(Context* ctx, const string& option) {
if (!ctx) return;
LOG(INFO) << "updated option: " << option;
// apply new option to active segment
if (ctx->IsComposing()) {
ctx->RefreshNonConfirmedComposition();
}
// notification
bool option_is_on = ctx->get_option(option);
string msg(option_is_on ? option : "!" + option);
message_sink_("option", msg);
}
void ConcreteEngine::OnPropertyUpdate(Context* ctx, const string& property) {
if (!ctx) return;
LOG(INFO) << "updated property: " << property;
// notification
string value = ctx->get_property(property);
string msg(property + "=" + value);
message_sink_("property", msg);
}
void ConcreteEngine::Compose(Context* ctx) {
if (!ctx) return;
Composition& comp = ctx->composition();
const string active_input = ctx->input().substr(0, ctx->caret_pos());
DLOG(INFO) << "active input: " << active_input;
comp.Reset(active_input);
if (ctx->caret_pos() < ctx->input().length() &&
ctx->caret_pos() == comp.GetConfirmedPosition()) {
// translate one segment past caret pos.
comp.Reset(ctx->input());
}
CalculateSegmentation(&comp);
TranslateSegments(&comp);
DLOG(INFO) << "composition: " << comp.GetDebugText();
}
void ConcreteEngine::CalculateSegmentation(Segmentation* segments) {
while (!segments->HasFinishedSegmentation()) {
size_t start_pos = segments->GetCurrentStartPosition();
size_t end_pos = segments->GetCurrentEndPosition();
DLOG(INFO) << "start pos: " << start_pos;
DLOG(INFO) << "end pos: " << end_pos;
// recognize a segment by calling the segmentors in turn
for (auto& segmentor : segmentors_) {
if (!segmentor->Proceed(segments))
break;
}
DLOG(INFO) << "segmentation: " << *segments;
// no advancement
if (start_pos == segments->GetCurrentEndPosition())
break;
// only one segment is allowed past caret pos, which is the segment
// immediately after the caret.
if (start_pos >= context_->caret_pos())
break;
// move onto the next segment...
if (!segments->HasFinishedSegmentation())
segments->Forward();
}
// start an empty segment only at the end of a confirmed composition.
segments->Trim();
if (!segments->empty() && segments->back().status >= Segment::kSelected)
segments->Forward();
}
void ConcreteEngine::TranslateSegments(Segmentation* segments) {
for (Segment& segment : *segments) {
if (segment.status >= Segment::kGuess)
continue;
size_t len = segment.end - segment.start;
if (len == 0)
continue;
string input = segments->input().substr(segment.start, len);
DLOG(INFO) << "translating segment: " << input;
auto menu = New<Menu>();
for (auto& translator : translators_) {
auto translation = translator->Query(input, segment);
if (!translation)
continue;
if (translation->exhausted()) {
LOG(INFO) << "Oops, got a futile translation.";
continue;
}
menu->AddTranslation(translation);
}
for (auto& filter : filters_) {
if (filter->AppliesToSegment(&segment)) {
menu->AddFilter(filter.get());
}
}
segment.status = Segment::kGuess;
segment.menu = menu;
segment.selected_index = 0;
}
}
void ConcreteEngine::FormatText(string* text) {
if (formatters_.empty())
return;
DLOG(INFO) << "applying formatters.";
for (auto& formatter : formatters_) {
formatter->Format(text);
}
}
void ConcreteEngine::CommitText(string text) {
context_->commit_history().Push(CommitRecord{"raw", text});
FormatText(&text);
DLOG(INFO) << "committing text: " << text;
sink_(text);
}
void ConcreteEngine::OnCommit(Context* ctx) {
context_->commit_history().Push(ctx->composition(), ctx->input());
string text = ctx->GetCommitText();
FormatText(&text);
DLOG(INFO) << "committing composition: " << text;
sink_(text);
}
void ConcreteEngine::OnSelect(Context* ctx) {
Segment& seg(ctx->composition().back());
seg.Close();
if (seg.end == ctx->input().length()) {
// composition has finished
seg.status = Segment::kConfirmed;
// strategy one: commit directly;
// strategy two: continue composing with another empty segment.
if (ctx->get_option("_auto_commit"))
ctx->Commit();
else
ctx->composition().Forward();
}
else {
bool reached_caret_pos = (seg.end >= ctx->caret_pos());
ctx->composition().Forward();
if (reached_caret_pos) {
// finished converting current segment
// move caret to the end of input
ctx->set_caret_pos(ctx->input().length());
}
else {
Compose(ctx);
}
}
}
void ConcreteEngine::ApplySchema(Schema* schema) {
if (!schema)
return;
schema_.reset(schema);
context_->Clear();
context_->ClearTransientOptions();
InitializeComponents();
InitializeOptions();
message_sink_("schema", schema->schema_id() + "/" + schema->schema_name());
}
void ConcreteEngine::InitializeComponents() {
processors_.clear();
segmentors_.clear();
translators_.clear();
filters_.clear();
if (auto switcher = New<Switcher>(this)) {
processors_.push_back(switcher);
if (schema_->schema_id() == ".default") {
if (Schema* schema = switcher->CreateSchema()) {
schema_.reset(schema);
}
}
}
Config* config = schema_->config();
if (!config)
return;
// create processors
if (auto processor_list = config->GetList("engine/processors")) {
size_t n = processor_list->size();
for (size_t i = 0; i < n; ++i) {
auto prescription = As<ConfigValue>(processor_list->GetAt(i));
if (!prescription)
continue;
Ticket ticket{this, "processor", prescription->str()};
if (auto c = Processor::Require(ticket.klass)) {
an<Processor> p(c->Create(ticket));
processors_.push_back(p);
}
else {
LOG(ERROR) << "error creating processor: '" << ticket.klass << "'";
}
}
}
// create segmentors
if (auto segmentor_list = config->GetList("engine/segmentors")) {
size_t n = segmentor_list->size();
for (size_t i = 0; i < n; ++i) {
auto prescription = As<ConfigValue>(segmentor_list->GetAt(i));
if (!prescription)
continue;
Ticket ticket{this, "segmentor", prescription->str()};
if (auto c = Segmentor::Require(ticket.klass)) {
an<Segmentor> s(c->Create(ticket));
segmentors_.push_back(s);
}
else {
LOG(ERROR) << "error creating segmentor: '" << ticket.klass << "'";
}
}
}
// create translators
if (auto translator_list = config->GetList("engine/translators")) {
size_t n = translator_list->size();
for (size_t i = 0; i < n; ++i) {
auto prescription = As<ConfigValue>(translator_list->GetAt(i));
if (!prescription)
continue;
Ticket ticket{this, "translator", prescription->str()};
if (auto c = Translator::Require(ticket.klass)) {
an<Translator> t(c->Create(ticket));
translators_.push_back(t);
}
else {
LOG(ERROR) << "error creating translator: '" << ticket.klass << "'";
}
}
}
// create filters
if (auto filter_list = config->GetList("engine/filters")) {
size_t n = filter_list->size();
for (size_t i = 0; i < n; ++i) {
auto prescription = As<ConfigValue>(filter_list->GetAt(i));
if (!prescription)
continue;
Ticket ticket{this, "filter", prescription->str()};
if (auto c = Filter::Require(ticket.klass)) {
an<Filter> f(c->Create(ticket));
filters_.push_back(f);
}
else {
LOG(ERROR) << "error creating filter: '" << ticket.klass << "'";
}
}
}
// create formatters
if (auto c = Formatter::Require("shape_formatter")) {
an<Formatter> f(c->Create(Ticket(this)));
formatters_.push_back(f);
}
else {
LOG(WARNING) << "shape_formatter not available.";
}
// create post-processors
if (auto c = Processor::Require("shape_processor")) {
an<Processor> p(c->Create(Ticket(this)));
post_processors_.push_back(p);
}
else {
LOG(WARNING) << "shape_processor not available.";
}
}
void ConcreteEngine::InitializeOptions() {
// reset custom switches
Config* config = schema_->config();
if (auto switches = config->GetList("switches")) {
for (size_t i = 0; i < switches->size(); ++i) {
auto item = As<ConfigMap>(switches->GetAt(i));
if (!item)
continue;
auto reset_value = item->GetValue("reset");
if (!reset_value)
continue;
int value = 0;
reset_value->GetInt(&value);
if (auto option_name = item->GetValue("name")) {
// toggle
context_->set_option(option_name->str(), (value != 0));
}
else if (auto options = As<ConfigList>(item->Get("options"))) {
// radio
for (size_t i = 0; i < options->size(); ++i) {
if (auto option_name = options->GetValueAt(i)) {
context_->set_option(option_name->str(),
static_cast<int>(i) == value);
}
}
}
}
}
}
} // namespace rime
<|endoftext|> |
<commit_before>/// HEADER
#include <csapex_ml/features_message.h>
/// PROJECT
#include <csapex/utility/assert.h>
#include <csapex/utility/register_msg.h>
CSAPEX_REGISTER_MESSAGE(csapex::connection_types::FeaturesMessage)
using namespace csapex;
using namespace connection_types;
FeaturesMessage::FeaturesMessage(Message::Stamp stamp)
: Message("FeaturesMessage", "/", stamp), classification(0)
{}
ConnectionType::Ptr FeaturesMessage::clone() const
{
Ptr new_msg(new FeaturesMessage);
new_msg->value = value;
new_msg->classification = classification;
return new_msg;
}
ConnectionType::Ptr FeaturesMessage::toType() const
{
Ptr new_msg(new FeaturesMessage);
return new_msg;
}
/// YAML
namespace YAML {
Node convert<csapex::connection_types::FeaturesMessage>::encode(const csapex::connection_types::FeaturesMessage& rhs)
{
Node node = convert<csapex::connection_types::Message>::encode(rhs);
node["features"] = rhs.value;
node["classification"] = rhs.classification;
node["confidence"] = rhs.confidence;
return node;
}
bool convert<csapex::connection_types::FeaturesMessage>::decode(const Node& node, csapex::connection_types::FeaturesMessage& rhs)
{
if(!node.IsMap()) {
return false;
}
convert<csapex::connection_types::Message>::decode(node, rhs);
rhs.value = node["features"].as<std::vector<float> >();
rhs.classification = node["classification"].as<int>();
if(node["confidence"].IsDefined())
rhs.confidence = node["confidence"].as<float>();
else
rhs.confidence = 1.f;
return true;
}
}
<commit_msg>feature msg: copy confidence<commit_after>/// HEADER
#include <csapex_ml/features_message.h>
/// PROJECT
#include <csapex/utility/assert.h>
#include <csapex/utility/register_msg.h>
CSAPEX_REGISTER_MESSAGE(csapex::connection_types::FeaturesMessage)
using namespace csapex;
using namespace connection_types;
FeaturesMessage::FeaturesMessage(Message::Stamp stamp)
: Message("FeaturesMessage", "/", stamp), classification(0)
{}
ConnectionType::Ptr FeaturesMessage::clone() const
{
Ptr new_msg(new FeaturesMessage);
new_msg->value = value;
new_msg->classification = classification;
new_msg->confidence = confidence;
return new_msg;
}
ConnectionType::Ptr FeaturesMessage::toType() const
{
Ptr new_msg(new FeaturesMessage);
return new_msg;
}
/// YAML
namespace YAML {
Node convert<csapex::connection_types::FeaturesMessage>::encode(const csapex::connection_types::FeaturesMessage& rhs)
{
Node node = convert<csapex::connection_types::Message>::encode(rhs);
node["features"] = rhs.value;
node["classification"] = rhs.classification;
node["confidence"] = rhs.confidence;
return node;
}
bool convert<csapex::connection_types::FeaturesMessage>::decode(const Node& node, csapex::connection_types::FeaturesMessage& rhs)
{
if(!node.IsMap()) {
return false;
}
convert<csapex::connection_types::Message>::decode(node, rhs);
rhs.value = node["features"].as<std::vector<float> >();
rhs.classification = node["classification"].as<int>();
if(node["confidence"].IsDefined())
rhs.confidence = node["confidence"].as<float>();
else
rhs.confidence = 1.f;
return true;
}
}
<|endoftext|> |
<commit_before>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2008-2011 Ames Laboratory
Iowa State University and The Regents of the University of Michigan All rights
reserved.
HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.
You may redistribute, use, and create derivate works of HOOMD-blue, in source
and binary forms, provided you abide by the following conditions:
* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer both in the code and
prominently in any materials provided with the distribution.
* 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.
* All publications and presentations based on HOOMD-blue, including any reports
or published results obtained, in whole or in part, with HOOMD-blue, will
acknowledge its use according to the terms posted at the time of submission on:
http://codeblue.umich.edu/hoomd-blue/citations.html
* Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website:
http://codeblue.umich.edu/hoomd-blue/
* Apart from the above required attributions, neither the name of the copyright
holder nor the names of HOOMD-blue's contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY
WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT 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.
*/
// Maintainer: joaander
/*! \file MSDAnalyzer.cc
\brief Defines the MSDAnalyzer class
*/
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4244 )
#endif
#include "MSDAnalyzer.h"
#include "HOOMDInitializer.h"
#ifdef ENABLE_MPI
#include "Communicator.h"
#endif
#include <boost/python.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/convenience.hpp>
using namespace boost::python;
using namespace boost::filesystem;
#include <iomanip>
using namespace std;
/*! \param sysdef SystemDefinition containing the Particle data to analyze
\param fname File name to write output to
\param header_prefix String to print before the file header
\param overwrite Will overwite an exiting file if true (default is to append)
On construction, the initial coordinates of all parrticles in the system are recoreded. The file is opened
(and overwritten if told to). Nothing is initially written to the file, that will occur on the first call to
analyze()
*/
MSDAnalyzer::MSDAnalyzer(boost::shared_ptr<SystemDefinition> sysdef,
std::string fname,
const std::string& header_prefix,
bool overwrite)
: Analyzer(sysdef), m_delimiter("\t"), m_header_prefix(header_prefix), m_appending(false),
m_columns_changed(false)
{
m_exec_conf->msg->notice(5) << "Constructing MSDAnalyzer: " << fname << " " << header_prefix << " " << overwrite << endl;
SnapshotParticleData snapshot(m_pdata->getNGlobal());
m_pdata->takeSnapshot(snapshot);
#ifdef ENABLE_MPI
// if we are not the root processor, do not perform file I/O
if (m_comm && !m_exec_conf->isRoot())
{
return;
}
#endif
// open the file
if (exists(fname) && !overwrite)
{
m_exec_conf->msg->notice(3) << "analyze.msd: Appending msd to existing file \"" << fname << "\"" << endl;
m_file.open(fname.c_str(), ios_base::in | ios_base::out | ios_base::ate);
m_appending = true;
}
else
{
m_exec_conf->msg->notice(3) << "analyze.msd: Creating new msd in file \"" << fname << "\"" << endl;
m_file.open(fname.c_str(), ios_base::out);
}
if (!m_file.good())
{
m_exec_conf->msg->error() << "analyze.msd: Unable to open file " << fname << endl;
throw runtime_error("Error initializing analyze.msd");
}
// record the initial particle positions by tag
m_initial_x.resize(m_pdata->getNGlobal());
m_initial_y.resize(m_pdata->getNGlobal());
m_initial_z.resize(m_pdata->getNGlobal());
BoxDim box = m_pdata->getGlobalBox();
// for each particle in the data
for (unsigned int tag = 0; tag < snapshot.size; tag++)
{
// save its initial position
Scalar3 pos = snapshot.pos[tag];
Scalar3 unwrapped = box.shift(pos, snapshot.image[tag]);
m_initial_x[tag] = unwrapped.x;
m_initial_y[tag] = unwrapped.y;
m_initial_z[tag] = unwrapped.z;
}
}
MSDAnalyzer::~MSDAnalyzer()
{
m_exec_conf->msg->notice(5) << "Destroying MSDAnalyzer" << endl;
}
/*!\param timestep Current time step of the simulation
analyze() will first write out the file header if the columns have changed.
On every call, analyze() will write calculate the MSD for each group and write out a row in the file.
*/
void MSDAnalyzer::analyze(unsigned int timestep)
{
if (m_prof)
m_prof->push("Analyze MSD");
// take particle data snapshot
SnapshotParticleData snapshot(m_pdata->getNGlobal());
m_pdata->takeSnapshot(snapshot);
#ifdef ENABLE_MPI
// if we are not the root processor, do not perform file I/O
if (m_comm && !m_exec_conf->isRoot())
{
if (m_prof) m_prof->pop();
return;
}
#endif
// error check
if (m_columns.size() == 0)
{
m_exec_conf->msg->warning() << "analyze.msd: No columns specified in the MSD analysis" << endl;
return;
}
// ignore writing the header on the first call when appending the file
if (m_columns_changed && m_appending)
{
m_appending = false;
m_columns_changed = false;
}
// write out the header only once if the columns change
if (m_columns_changed)
{
writeHeader();
m_columns_changed = false;
}
// write out the row every time
writeRow(timestep, snapshot);
if (m_prof)
m_prof->pop();
}
/*! \param delimiter New delimiter to set
The delimiter is printed between every element in the row of the output
*/
void MSDAnalyzer::setDelimiter(const std::string& delimiter)
{
m_delimiter = delimiter;
}
/*! \param group Particle group to calculate the MSD of
\param name Name to print in the header of the file
After a column is added with addColumn(), future calls to analyze() will calculate the MSD of the particles defined
in \a group and print out an entry under the \a name header in the file.
*/
void MSDAnalyzer::addColumn(boost::shared_ptr<ParticleGroup> group, const std::string& name)
{
m_columns.push_back(column(group, name));
m_columns_changed = true;
}
/*! \param xml_fname Name of the XML file to read in to the r0 positions
\post \a xml_fname is read and all initial r0 positions are assigned from that file.
*/
void MSDAnalyzer::setR0(const std::string& xml_fname)
{
// read in the xml file
HOOMDInitializer xml(m_exec_conf,xml_fname);
// take particle data snapshot
SnapshotParticleData snapshot(m_pdata->getNGlobal());
m_pdata->takeSnapshot(snapshot);
#ifdef ENABLE_MPI
// if we are not the root processor, do not perform file I/O
if (m_comm && !m_exec_conf->isRoot())
{
return;
}
#endif
// verify that the input matches the current system size
unsigned int nparticles = m_pdata->getNGlobal();
if (nparticles != xml.getPos().size())
{
m_exec_conf->msg->error() << "analyze.msd: Found " << xml.getPos().size() << " particles in "
<< xml_fname << ", but there are " << nparticles << " in the current simulation." << endl;
throw runtime_error("Error setting r0 in analyze.msd");
}
// determine if we have image data
bool have_image = (xml.getImage().size() == nparticles);
if (!have_image)
{
m_exec_conf->msg->warning() << "analyze.msd: Image data missing or corrupt in " << xml_fname
<< ". Computed msd values will not be correct." << endl;
}
// reset the initial positions
BoxDim box = m_pdata->getGlobalBox();
// for each particle in the data
for (unsigned int tag = 0; tag < nparticles; tag++)
{
// save its initial position
HOOMDInitializer::vec pos = xml.getPos()[tag];
m_initial_x[tag] = pos.x;
m_initial_y[tag] = pos.y;
m_initial_z[tag] = pos.z;
// adjust the positions by the image flags if we have them
if (have_image)
{
HOOMDInitializer::vec_int image = xml.getImage()[tag];
Scalar3 pos = make_scalar3(m_initial_x[tag], m_initial_y[tag], m_initial_z[tag]);
int3 image_i = make_int3(image.x, image.y, image.z);
Scalar3 unwrapped = box.shift(pos, image_i);
m_initial_x[tag] += unwrapped.x;
m_initial_y[tag] += unwrapped.y;
m_initial_z[tag] += unwrapped.z;
}
}
}
/*! The entire header row is written to the file. First, timestep is written as every file includes it and then the
columns are looped through and their names printed, separated by the delimiter.
*/
void MSDAnalyzer::writeHeader()
{
// write out the header prefix
m_file << m_header_prefix;
// timestep is always output
m_file << "timestep";
if (m_columns.size() == 0)
{
m_exec_conf->msg->warning() << "analyze.msd: No columns specified in the MSD analysis" << endl;
return;
}
// only print the delimiter after the timestep if there are more columns
m_file << m_delimiter;
// write all but the last of the quantities separated by the delimiter
for (unsigned int i = 0; i < m_columns.size()-1; i++)
m_file << m_columns[i].m_name << m_delimiter;
// write the last one with no delimiter after it
m_file << m_columns[m_columns.size()-1].m_name << endl;
m_file.flush();
}
/*! \param group Particle group to calculate the MSD of
Loop through all particles in the given group and calculate the MSD over them.
\returns The calculated MSD
*/
Scalar MSDAnalyzer::calcMSD(boost::shared_ptr<ParticleGroup const> group, const SnapshotParticleData& snapshot)
{
BoxDim box = m_pdata->getGlobalBox();
Scalar3 l_origin = m_pdata->getOrigin();
int3 image = m_pdata->getOriginImage();
Scalar3 origin = box.shift(l_origin, image);
// initial sum for the average
Scalar msd = Scalar(0.0);
// handle the case where there are 0 members gracefully
if (group->getNumMembers() == 0)
{
m_exec_conf->msg->warning() << "analyze.msd: Group has 0 members, reporting a calculated msd of 0.0" << endl;
return Scalar(0.0);
}
// for each particle in the group
for (unsigned int group_idx = 0; group_idx < group->getNumMembers(); group_idx++)
{
// get the tag for the current group member from the group
unsigned int tag = group->getMemberTag(group_idx);
Scalar3 pos = snapshot.pos[tag] + l_origin;
int3 image = snapshot.image[tag];
Scalar3 unwrapped = box.shift(pos, image);
pos -= origin;
Scalar dx = unwrapped.x - m_initial_x[tag];
Scalar dy = unwrapped.y - m_initial_y[tag];
Scalar dz = unwrapped.z - m_initial_z[tag];
msd += dx*dx + dy*dy + dz*dz;
}
// divide to complete the average
msd /= Scalar(group->getNumMembers());
return msd;
}
/*! \param timestep current time step of the simulation
Performs all the steps needed in order to calculate the MSDs for all the groups in the columns and writes out an
entire row to the file.
*/
void MSDAnalyzer::writeRow(unsigned int timestep, const SnapshotParticleData& snapshot)
{
if (m_prof) m_prof->push("MSD");
// // take particle data snapshot
// SnapshotParticleData snapshot(m_pdata->getNGlobal());
// m_pdata->takeSnapshot(snapshot);
// // This will need to be changed based on calling function
// #ifdef ENABLE_MPI
// // if we are not the root processor, do not perform file I/O
// if (m_comm && !m_exec_conf->isRoot())
// {
// if (m_prof) m_prof->pop();
// return;
// }
// #endif
// The timestep is always output
m_file << setprecision(10) << timestep;
// quit now if there is nothing to log
if (m_columns.size() == 0)
{
return;
}
// only print the delimiter after the timestep if there are more columns
m_file << m_delimiter;
// write all but the last of the columns separated by the delimiter
for (unsigned int i = 0; i < m_columns.size()-1; i++)
m_file << setprecision(10) << calcMSD(m_columns[i].m_group, snapshot) << m_delimiter;
// write the last one with no delimiter after it
m_file << setprecision(10) << calcMSD(m_columns[m_columns.size()-1].m_group, snapshot) << endl;
m_file.flush();
if (!m_file.good())
{
m_exec_conf->msg->error() << "analyze.msd: I/O error while writing file" << endl;
throw runtime_error("Error writting msd file");
}
if (m_prof) m_prof->pop();
}
void export_MSDAnalyzer()
{
class_<MSDAnalyzer, boost::shared_ptr<MSDAnalyzer>, bases<Analyzer>, boost::noncopyable>
("MSDAnalyzer", init< boost::shared_ptr<SystemDefinition>, const std::string&, const std::string&, bool >())
.def("setDelimiter", &MSDAnalyzer::setDelimiter)
.def("addColumn", &MSDAnalyzer::addColumn)
.def("setR0", &MSDAnalyzer::setR0)
;
}
#ifdef WIN32
#pragma warning( pop )
#endif
<commit_msg>-= is not allowed.<commit_after>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2008-2011 Ames Laboratory
Iowa State University and The Regents of the University of Michigan All rights
reserved.
HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.
You may redistribute, use, and create derivate works of HOOMD-blue, in source
and binary forms, provided you abide by the following conditions:
* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer both in the code and
prominently in any materials provided with the distribution.
* 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.
* All publications and presentations based on HOOMD-blue, including any reports
or published results obtained, in whole or in part, with HOOMD-blue, will
acknowledge its use according to the terms posted at the time of submission on:
http://codeblue.umich.edu/hoomd-blue/citations.html
* Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website:
http://codeblue.umich.edu/hoomd-blue/
* Apart from the above required attributions, neither the name of the copyright
holder nor the names of HOOMD-blue's contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY
WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT 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.
*/
// Maintainer: joaander
/*! \file MSDAnalyzer.cc
\brief Defines the MSDAnalyzer class
*/
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4244 )
#endif
#include "MSDAnalyzer.h"
#include "HOOMDInitializer.h"
#ifdef ENABLE_MPI
#include "Communicator.h"
#endif
#include <boost/python.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/convenience.hpp>
using namespace boost::python;
using namespace boost::filesystem;
#include <iomanip>
using namespace std;
/*! \param sysdef SystemDefinition containing the Particle data to analyze
\param fname File name to write output to
\param header_prefix String to print before the file header
\param overwrite Will overwite an exiting file if true (default is to append)
On construction, the initial coordinates of all parrticles in the system are recoreded. The file is opened
(and overwritten if told to). Nothing is initially written to the file, that will occur on the first call to
analyze()
*/
MSDAnalyzer::MSDAnalyzer(boost::shared_ptr<SystemDefinition> sysdef,
std::string fname,
const std::string& header_prefix,
bool overwrite)
: Analyzer(sysdef), m_delimiter("\t"), m_header_prefix(header_prefix), m_appending(false),
m_columns_changed(false)
{
m_exec_conf->msg->notice(5) << "Constructing MSDAnalyzer: " << fname << " " << header_prefix << " " << overwrite << endl;
SnapshotParticleData snapshot(m_pdata->getNGlobal());
m_pdata->takeSnapshot(snapshot);
#ifdef ENABLE_MPI
// if we are not the root processor, do not perform file I/O
if (m_comm && !m_exec_conf->isRoot())
{
return;
}
#endif
// open the file
if (exists(fname) && !overwrite)
{
m_exec_conf->msg->notice(3) << "analyze.msd: Appending msd to existing file \"" << fname << "\"" << endl;
m_file.open(fname.c_str(), ios_base::in | ios_base::out | ios_base::ate);
m_appending = true;
}
else
{
m_exec_conf->msg->notice(3) << "analyze.msd: Creating new msd in file \"" << fname << "\"" << endl;
m_file.open(fname.c_str(), ios_base::out);
}
if (!m_file.good())
{
m_exec_conf->msg->error() << "analyze.msd: Unable to open file " << fname << endl;
throw runtime_error("Error initializing analyze.msd");
}
// record the initial particle positions by tag
m_initial_x.resize(m_pdata->getNGlobal());
m_initial_y.resize(m_pdata->getNGlobal());
m_initial_z.resize(m_pdata->getNGlobal());
BoxDim box = m_pdata->getGlobalBox();
// for each particle in the data
for (unsigned int tag = 0; tag < snapshot.size; tag++)
{
// save its initial position
Scalar3 pos = snapshot.pos[tag];
Scalar3 unwrapped = box.shift(pos, snapshot.image[tag]);
m_initial_x[tag] = unwrapped.x;
m_initial_y[tag] = unwrapped.y;
m_initial_z[tag] = unwrapped.z;
}
}
MSDAnalyzer::~MSDAnalyzer()
{
m_exec_conf->msg->notice(5) << "Destroying MSDAnalyzer" << endl;
}
/*!\param timestep Current time step of the simulation
analyze() will first write out the file header if the columns have changed.
On every call, analyze() will write calculate the MSD for each group and write out a row in the file.
*/
void MSDAnalyzer::analyze(unsigned int timestep)
{
if (m_prof)
m_prof->push("Analyze MSD");
// take particle data snapshot
SnapshotParticleData snapshot(m_pdata->getNGlobal());
m_pdata->takeSnapshot(snapshot);
#ifdef ENABLE_MPI
// if we are not the root processor, do not perform file I/O
if (m_comm && !m_exec_conf->isRoot())
{
if (m_prof) m_prof->pop();
return;
}
#endif
// error check
if (m_columns.size() == 0)
{
m_exec_conf->msg->warning() << "analyze.msd: No columns specified in the MSD analysis" << endl;
return;
}
// ignore writing the header on the first call when appending the file
if (m_columns_changed && m_appending)
{
m_appending = false;
m_columns_changed = false;
}
// write out the header only once if the columns change
if (m_columns_changed)
{
writeHeader();
m_columns_changed = false;
}
// write out the row every time
writeRow(timestep, snapshot);
if (m_prof)
m_prof->pop();
}
/*! \param delimiter New delimiter to set
The delimiter is printed between every element in the row of the output
*/
void MSDAnalyzer::setDelimiter(const std::string& delimiter)
{
m_delimiter = delimiter;
}
/*! \param group Particle group to calculate the MSD of
\param name Name to print in the header of the file
After a column is added with addColumn(), future calls to analyze() will calculate the MSD of the particles defined
in \a group and print out an entry under the \a name header in the file.
*/
void MSDAnalyzer::addColumn(boost::shared_ptr<ParticleGroup> group, const std::string& name)
{
m_columns.push_back(column(group, name));
m_columns_changed = true;
}
/*! \param xml_fname Name of the XML file to read in to the r0 positions
\post \a xml_fname is read and all initial r0 positions are assigned from that file.
*/
void MSDAnalyzer::setR0(const std::string& xml_fname)
{
// read in the xml file
HOOMDInitializer xml(m_exec_conf,xml_fname);
// take particle data snapshot
SnapshotParticleData snapshot(m_pdata->getNGlobal());
m_pdata->takeSnapshot(snapshot);
#ifdef ENABLE_MPI
// if we are not the root processor, do not perform file I/O
if (m_comm && !m_exec_conf->isRoot())
{
return;
}
#endif
// verify that the input matches the current system size
unsigned int nparticles = m_pdata->getNGlobal();
if (nparticles != xml.getPos().size())
{
m_exec_conf->msg->error() << "analyze.msd: Found " << xml.getPos().size() << " particles in "
<< xml_fname << ", but there are " << nparticles << " in the current simulation." << endl;
throw runtime_error("Error setting r0 in analyze.msd");
}
// determine if we have image data
bool have_image = (xml.getImage().size() == nparticles);
if (!have_image)
{
m_exec_conf->msg->warning() << "analyze.msd: Image data missing or corrupt in " << xml_fname
<< ". Computed msd values will not be correct." << endl;
}
// reset the initial positions
BoxDim box = m_pdata->getGlobalBox();
// for each particle in the data
for (unsigned int tag = 0; tag < nparticles; tag++)
{
// save its initial position
HOOMDInitializer::vec pos = xml.getPos()[tag];
m_initial_x[tag] = pos.x;
m_initial_y[tag] = pos.y;
m_initial_z[tag] = pos.z;
// adjust the positions by the image flags if we have them
if (have_image)
{
HOOMDInitializer::vec_int image = xml.getImage()[tag];
Scalar3 pos = make_scalar3(m_initial_x[tag], m_initial_y[tag], m_initial_z[tag]);
int3 image_i = make_int3(image.x, image.y, image.z);
Scalar3 unwrapped = box.shift(pos, image_i);
m_initial_x[tag] += unwrapped.x;
m_initial_y[tag] += unwrapped.y;
m_initial_z[tag] += unwrapped.z;
}
}
}
/*! The entire header row is written to the file. First, timestep is written as every file includes it and then the
columns are looped through and their names printed, separated by the delimiter.
*/
void MSDAnalyzer::writeHeader()
{
// write out the header prefix
m_file << m_header_prefix;
// timestep is always output
m_file << "timestep";
if (m_columns.size() == 0)
{
m_exec_conf->msg->warning() << "analyze.msd: No columns specified in the MSD analysis" << endl;
return;
}
// only print the delimiter after the timestep if there are more columns
m_file << m_delimiter;
// write all but the last of the quantities separated by the delimiter
for (unsigned int i = 0; i < m_columns.size()-1; i++)
m_file << m_columns[i].m_name << m_delimiter;
// write the last one with no delimiter after it
m_file << m_columns[m_columns.size()-1].m_name << endl;
m_file.flush();
}
/*! \param group Particle group to calculate the MSD of
Loop through all particles in the given group and calculate the MSD over them.
\returns The calculated MSD
*/
Scalar MSDAnalyzer::calcMSD(boost::shared_ptr<ParticleGroup const> group, const SnapshotParticleData& snapshot)
{
BoxDim box = m_pdata->getGlobalBox();
Scalar3 l_origin = m_pdata->getOrigin();
int3 image = m_pdata->getOriginImage();
Scalar3 origin = box.shift(l_origin, image);
// initial sum for the average
Scalar msd = Scalar(0.0);
// handle the case where there are 0 members gracefully
if (group->getNumMembers() == 0)
{
m_exec_conf->msg->warning() << "analyze.msd: Group has 0 members, reporting a calculated msd of 0.0" << endl;
return Scalar(0.0);
}
// for each particle in the group
for (unsigned int group_idx = 0; group_idx < group->getNumMembers(); group_idx++)
{
// get the tag for the current group member from the group
unsigned int tag = group->getMemberTag(group_idx);
Scalar3 pos = snapshot.pos[tag] + l_origin;
int3 image = snapshot.image[tag];
Scalar3 unwrapped = box.shift(pos, image);
pos = pos - origin;
Scalar dx = unwrapped.x - m_initial_x[tag];
Scalar dy = unwrapped.y - m_initial_y[tag];
Scalar dz = unwrapped.z - m_initial_z[tag];
msd += dx*dx + dy*dy + dz*dz;
}
// divide to complete the average
msd /= Scalar(group->getNumMembers());
return msd;
}
/*! \param timestep current time step of the simulation
Performs all the steps needed in order to calculate the MSDs for all the groups in the columns and writes out an
entire row to the file.
*/
void MSDAnalyzer::writeRow(unsigned int timestep, const SnapshotParticleData& snapshot)
{
if (m_prof) m_prof->push("MSD");
// // take particle data snapshot
// SnapshotParticleData snapshot(m_pdata->getNGlobal());
// m_pdata->takeSnapshot(snapshot);
// // This will need to be changed based on calling function
// #ifdef ENABLE_MPI
// // if we are not the root processor, do not perform file I/O
// if (m_comm && !m_exec_conf->isRoot())
// {
// if (m_prof) m_prof->pop();
// return;
// }
// #endif
// The timestep is always output
m_file << setprecision(10) << timestep;
// quit now if there is nothing to log
if (m_columns.size() == 0)
{
return;
}
// only print the delimiter after the timestep if there are more columns
m_file << m_delimiter;
// write all but the last of the columns separated by the delimiter
for (unsigned int i = 0; i < m_columns.size()-1; i++)
m_file << setprecision(10) << calcMSD(m_columns[i].m_group, snapshot) << m_delimiter;
// write the last one with no delimiter after it
m_file << setprecision(10) << calcMSD(m_columns[m_columns.size()-1].m_group, snapshot) << endl;
m_file.flush();
if (!m_file.good())
{
m_exec_conf->msg->error() << "analyze.msd: I/O error while writing file" << endl;
throw runtime_error("Error writting msd file");
}
if (m_prof) m_prof->pop();
}
void export_MSDAnalyzer()
{
class_<MSDAnalyzer, boost::shared_ptr<MSDAnalyzer>, bases<Analyzer>, boost::noncopyable>
("MSDAnalyzer", init< boost::shared_ptr<SystemDefinition>, const std::string&, const std::string&, bool >())
.def("setDelimiter", &MSDAnalyzer::setDelimiter)
.def("addColumn", &MSDAnalyzer::addColumn)
.def("setR0", &MSDAnalyzer::setR0)
;
}
#ifdef WIN32
#pragma warning( pop )
#endif
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <sal/config.h>
#include <boost/noncopyable.hpp>
#include <sdr/contact/viewcontactofunocontrol.hxx>
#include <sdr/contact/viewobjectcontactofunocontrol.hxx>
#include <sdr/contact/objectcontactofpageview.hxx>
#include <svx/sdr/contact/displayinfo.hxx>
#include <svx/svdouno.hxx>
#include <svx/svdpagv.hxx>
#include <svx/svdview.hxx>
#include <svx/sdrpagewindow.hxx>
#include <com/sun/star/awt/XWindow2.hpp>
#include "svx/sdrpaintwindow.hxx"
#include <tools/diagnose_ex.h>
#include <vcl/pdfextoutdevdata.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <drawinglayer/primitive2d/controlprimitive2d.hxx>
#include <drawinglayer/primitive2d/sdrdecompositiontools2d.hxx>
namespace sdr { namespace contact {
using ::com::sun::star::awt::XControl;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::awt::XControlContainer;
using ::com::sun::star::awt::XControlModel;
using ::com::sun::star::awt::XWindow2;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::Exception;
//= ViewContactOfUnoControl
class ViewContactOfUnoControl_Impl: private boost::noncopyable
{
public:
ViewContactOfUnoControl_Impl();
~ViewContactOfUnoControl_Impl();
};
ViewContactOfUnoControl_Impl::ViewContactOfUnoControl_Impl()
{
}
ViewContactOfUnoControl_Impl::~ViewContactOfUnoControl_Impl()
{
}
//= ViewContactOfUnoControl
ViewContactOfUnoControl::ViewContactOfUnoControl( SdrUnoObj& _rUnoObject )
:ViewContactOfSdrObj( _rUnoObject )
,m_pImpl( new ViewContactOfUnoControl_Impl )
{
}
ViewContactOfUnoControl::~ViewContactOfUnoControl()
{
}
Reference< XControl > ViewContactOfUnoControl::getTemporaryControlForWindow(
const Window& _rWindow, Reference< XControlContainer >& _inout_ControlContainer ) const
{
SdrUnoObj* pUnoObject = dynamic_cast< SdrUnoObj* >( TryToGetSdrObject() );
OSL_ENSURE( pUnoObject, "ViewContactOfUnoControl::getTemporaryControlForDevice: no SdrUnoObj!" );
if ( !pUnoObject )
return NULL;
return ViewObjectContactOfUnoControl::getTemporaryControlForWindow( _rWindow, _inout_ControlContainer, *pUnoObject );
}
ViewObjectContact& ViewContactOfUnoControl::CreateObjectSpecificViewObjectContact( ObjectContact& _rObjectContact )
{
// print or print preview requires special handling
const OutputDevice* pDevice = _rObjectContact.TryToGetOutputDevice();
bool bPrintOrPreview = ( pDevice != NULL ) && ( pDevice->GetOutDevType() == OUTDEV_PRINTER );
ObjectContactOfPageView* pPageViewContact = dynamic_cast< ObjectContactOfPageView* >( &_rObjectContact );
bPrintOrPreview |= ( pPageViewContact != NULL ) && pPageViewContact->GetPageWindow().GetPageView().GetView().IsPrintPreview();
if ( bPrintOrPreview )
return *new UnoControlPrintOrPreviewContact( *pPageViewContact, *this );
// all others are nowadays served by the same implementation
return *new ViewObjectContactOfUnoControl( _rObjectContact, *this );
}
drawinglayer::primitive2d::Primitive2DSequence ViewContactOfUnoControl::createViewIndependentPrimitive2DSequence() const
{
// create range. Use model data directly, not getBoundRect()/getSnapRect; these will use
// the primitive data themselves in the long run. Use SdrUnoObj's (which is a SdrRectObj)
// call to GetGeoRect() to access SdrTextObj::aRect directly and without executing anything
Rectangle aRectangle(GetSdrUnoObj().GetGeoRect());
// Hack for calc, transform position of object according
// to current zoom so as objects relative position to grid
// appears stable
Point aGridOffset = GetSdrUnoObj().GetGridOffset();
aRectangle += aGridOffset;
const basegfx::B2DRange aRange(
aRectangle.Left(), aRectangle.Top(),
aRectangle.Right(), aRectangle.Bottom());
// create object transform
basegfx::B2DHomMatrix aTransform;
aTransform.set(0, 0, aRange.getWidth());
aTransform.set(1, 1, aRange.getHeight());
aTransform.set(0, 2, aRange.getMinX());
aTransform.set(1, 2, aRange.getMinY());
Reference< XControlModel > xControlModel = GetSdrUnoObj().GetUnoControlModel();
if(xControlModel.is())
{
// create control primitive WITHOUT possibly existing XControl; this would be done in
// the VOC in createPrimitive2DSequence()
const drawinglayer::primitive2d::Primitive2DReference xRetval(
new drawinglayer::primitive2d::ControlPrimitive2D(
aTransform,
xControlModel));
return drawinglayer::primitive2d::Primitive2DSequence(&xRetval, 1);
}
else
{
// always append an invisible outline for the cases where no visible content exists
const drawinglayer::primitive2d::Primitive2DReference xRetval(
drawinglayer::primitive2d::createHiddenGeometryPrimitives2D(
false, aTransform));
return drawinglayer::primitive2d::Primitive2DSequence(&xRetval, 1);
}
}
} } // namespace sdr::contact
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fdo#79883 the page view object contact must exist<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <sal/config.h>
#include <boost/noncopyable.hpp>
#include <sdr/contact/viewcontactofunocontrol.hxx>
#include <sdr/contact/viewobjectcontactofunocontrol.hxx>
#include <sdr/contact/objectcontactofpageview.hxx>
#include <svx/sdr/contact/displayinfo.hxx>
#include <svx/svdouno.hxx>
#include <svx/svdpagv.hxx>
#include <svx/svdview.hxx>
#include <svx/sdrpagewindow.hxx>
#include <com/sun/star/awt/XWindow2.hpp>
#include "svx/sdrpaintwindow.hxx"
#include <tools/diagnose_ex.h>
#include <vcl/pdfextoutdevdata.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <drawinglayer/primitive2d/controlprimitive2d.hxx>
#include <drawinglayer/primitive2d/sdrdecompositiontools2d.hxx>
namespace sdr { namespace contact {
using ::com::sun::star::awt::XControl;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::awt::XControlContainer;
using ::com::sun::star::awt::XControlModel;
using ::com::sun::star::awt::XWindow2;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::Exception;
//= ViewContactOfUnoControl
class ViewContactOfUnoControl_Impl: private boost::noncopyable
{
public:
ViewContactOfUnoControl_Impl();
~ViewContactOfUnoControl_Impl();
};
ViewContactOfUnoControl_Impl::ViewContactOfUnoControl_Impl()
{
}
ViewContactOfUnoControl_Impl::~ViewContactOfUnoControl_Impl()
{
}
//= ViewContactOfUnoControl
ViewContactOfUnoControl::ViewContactOfUnoControl( SdrUnoObj& _rUnoObject )
:ViewContactOfSdrObj( _rUnoObject )
,m_pImpl( new ViewContactOfUnoControl_Impl )
{
}
ViewContactOfUnoControl::~ViewContactOfUnoControl()
{
}
Reference< XControl > ViewContactOfUnoControl::getTemporaryControlForWindow(
const Window& _rWindow, Reference< XControlContainer >& _inout_ControlContainer ) const
{
SdrUnoObj* pUnoObject = dynamic_cast< SdrUnoObj* >( TryToGetSdrObject() );
OSL_ENSURE( pUnoObject, "ViewContactOfUnoControl::getTemporaryControlForDevice: no SdrUnoObj!" );
if ( !pUnoObject )
return NULL;
return ViewObjectContactOfUnoControl::getTemporaryControlForWindow( _rWindow, _inout_ControlContainer, *pUnoObject );
}
ViewObjectContact& ViewContactOfUnoControl::CreateObjectSpecificViewObjectContact( ObjectContact& _rObjectContact )
{
// print or print preview requires special handling
const OutputDevice* pDevice = _rObjectContact.TryToGetOutputDevice();
ObjectContactOfPageView* const pPageViewContact = dynamic_cast< ObjectContactOfPageView* >( &_rObjectContact );
const bool bPrintOrPreview = pPageViewContact
&& ( ( ( pDevice != NULL ) && ( pDevice->GetOutDevType() == OUTDEV_PRINTER ) )
|| pPageViewContact->GetPageWindow().GetPageView().GetView().IsPrintPreview()
)
;
if ( bPrintOrPreview )
return *new UnoControlPrintOrPreviewContact( *pPageViewContact, *this );
// all others are nowadays served by the same implementation
return *new ViewObjectContactOfUnoControl( _rObjectContact, *this );
}
drawinglayer::primitive2d::Primitive2DSequence ViewContactOfUnoControl::createViewIndependentPrimitive2DSequence() const
{
// create range. Use model data directly, not getBoundRect()/getSnapRect; these will use
// the primitive data themselves in the long run. Use SdrUnoObj's (which is a SdrRectObj)
// call to GetGeoRect() to access SdrTextObj::aRect directly and without executing anything
Rectangle aRectangle(GetSdrUnoObj().GetGeoRect());
// Hack for calc, transform position of object according
// to current zoom so as objects relative position to grid
// appears stable
Point aGridOffset = GetSdrUnoObj().GetGridOffset();
aRectangle += aGridOffset;
const basegfx::B2DRange aRange(
aRectangle.Left(), aRectangle.Top(),
aRectangle.Right(), aRectangle.Bottom());
// create object transform
basegfx::B2DHomMatrix aTransform;
aTransform.set(0, 0, aRange.getWidth());
aTransform.set(1, 1, aRange.getHeight());
aTransform.set(0, 2, aRange.getMinX());
aTransform.set(1, 2, aRange.getMinY());
Reference< XControlModel > xControlModel = GetSdrUnoObj().GetUnoControlModel();
if(xControlModel.is())
{
// create control primitive WITHOUT possibly existing XControl; this would be done in
// the VOC in createPrimitive2DSequence()
const drawinglayer::primitive2d::Primitive2DReference xRetval(
new drawinglayer::primitive2d::ControlPrimitive2D(
aTransform,
xControlModel));
return drawinglayer::primitive2d::Primitive2DSequence(&xRetval, 1);
}
else
{
// always append an invisible outline for the cases where no visible content exists
const drawinglayer::primitive2d::Primitive2DReference xRetval(
drawinglayer::primitive2d::createHiddenGeometryPrimitives2D(
false, aTransform));
return drawinglayer::primitive2d::Primitive2DSequence(&xRetval, 1);
}
}
} } // namespace sdr::contact
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include "kincidenceformatter.h"
#include <kstaticdeleter.h>
#include <kglobal.h>
#include <klocale.h>
#include <kiconloader.h>
#ifndef KORG_NOKABC
#include <kabc/stdaddressbook.h>
#define size count
#endif
KIncidenceFormatter* KIncidenceFormatter::mInstance = 0;
static KStaticDeleter<KIncidenceFormatter> insd;
QString KIncidenceFormatter::getFormattedText( Incidence * inc )
{
mText = "";
if ( inc->type() == "Event" )
setEvent((Event *) inc );
else if ( inc->type() == "Todo" )
setTodo((Todo *) inc );
else if ( inc->type() == "Journal" )
mText = inc->description();
return mText;
}
KIncidenceFormatter* KIncidenceFormatter::instance()
{
if (!mInstance) {
insd.setObject( mInstance, new KIncidenceFormatter());
}
return mInstance;
}
KIncidenceFormatter::~KIncidenceFormatter()
{
}
KIncidenceFormatter::KIncidenceFormatter()
{
mColorMode = 0;
}
void KIncidenceFormatter::setEvent(Event *event)
{
int mode = 0;
mCurrentIncidence = event;
bool shortDate = true;
if ( mode == 0 ) {
addTag("h3",event->summary());
}
else {
if ( mColorMode == 1 ) {
mText +="<font color=\"#00A000\">";
}
if ( mColorMode == 2 ) {
mText +="<font color=\"#C00000\">";
}
// mText +="<font color=\"#F00000\">" + i18n("O-due!") + "</font>";
if ( mode == 1 ) {
addTag("h2",i18n( "Local: " ) +event->summary());
} else {
addTag("h2",i18n( "Remote: " ) +event->summary());
}
addTag("h3",i18n( "Last modified: " ) + KGlobal::locale()->formatDateTime(event->lastModified(),shortDate, true ) );
if ( mColorMode )
mText += "</font>";
}
#if 0
if (event->cancelled ()) {
mText +="<font color=\"#B00000\">";
addTag("i",i18n("This event has been cancelled!"));
mText.append("<br>");
mText += "</font>";
}
#endif
if (!event->location().isEmpty()) {
addTag("b",i18n("Location: "));
mText.append(event->location()+"<br>");
}
if (event->doesFloat()) {
if (event->isMultiDay()) {
mText.append(i18n("<p><b>From:</b> %1 </p><p><b>To:</b> %2</p>")
.arg(event->dtStartDateStr(shortDate))
.arg(event->dtEndDateStr(shortDate)));
} else {
mText.append(i18n("<p><b>On:</b> %1</p>").arg(event->dtStartDateStr( shortDate )));
}
} else {
if (event->isMultiDay()) {
mText.append(i18n("<p><b>From:</b> %1</p> ")
.arg(event->dtStartStr()));
mText.append(i18n("<p><b>To:</b> %1</p>")
.arg(event->dtEndStr()));
} else {
mText.append(i18n("<p><b>On:</b> %1</p> ")
.arg(event->dtStartDateStr( shortDate )));
mText.append(i18n("<p><b>From:</b> %1 <b>To:</b> %2</p>")
.arg(event->dtStartTimeStr())
.arg(event->dtEndTimeStr()));
}
}
if (event->recurrence()->doesRecur()) {
QString recurText = i18n("No");
short recurs = event->recurrence()->doesRecur();
if ( recurs == Recurrence::rMinutely )
recurText = i18n("minutely");
else if ( recurs == Recurrence::rHourly )
recurText = i18n("hourly");
else if ( recurs == Recurrence::rDaily )
recurText = i18n("daily");
else if ( recurs == Recurrence::rWeekly )
recurText = i18n("weekly");
else if ( recurs == Recurrence::rMonthlyPos )
recurText = i18n("monthly");
else if ( recurs == Recurrence::rMonthlyDay )
recurText = i18n("day-monthly");
else if ( recurs == Recurrence::rYearlyMonth )
recurText = i18n("month-yearly");
else if ( recurs == Recurrence::rYearlyDay )
recurText = i18n("day-yearly");
else if ( recurs == Recurrence::rYearlyPos )
recurText = i18n("position-yearly");
addTag("p","<em>" + i18n("This is a %1 recurring event.").arg(recurText ) + "</em>");
bool last;
QDate start = QDate::currentDate();
QDate next;
next = event->recurrence()->getPreviousDate( start , &last );
if ( !last ) {
next = event->recurrence()->getNextDate( start.addDays( - 1 ) );
addTag("p",i18n("Next recurrence is on: ")+ KGlobal::locale()->formatDate( next, shortDate ) );
//addTag("p", KGlobal::locale()->formatDate( next, shortDate ));
} else {
addTag("p",i18n("<b>Last recurrence was on:</b>") );
addTag("p", KGlobal::locale()->formatDate( next, shortDate ));
}
}
if (event->isAlarmEnabled()) {
Alarm *alarm =event->alarms().first() ;
QDateTime t = alarm->time();
int min = t.secsTo( event->dtStart() )/60;
QString s =i18n("(%1 min before)").arg( min );
addTag("p",i18n("<b>Alarm on: </b>") + s + ": "+KGlobal::locale()->formatDateTime( t, shortDate ));
//addTag("p", KGlobal::locale()->formatDateTime( t, shortDate ));
//addTag("p",s);
}
addTag("p",i18n("<b>Access: </b>") +event->secrecyStr() );
// mText.append(event->secrecyStr()+"<br>");
formatCategories(event);
if (!event->description().isEmpty()) {
addTag("p",i18n("<b>Details: </b>"));
addTag("p",event->description());
}
formatReadOnly(event);
formatAttendees(event);
}
void KIncidenceFormatter::setTodo(Todo *event )
{
int mode = 0;
mCurrentIncidence = event;
bool shortDate = true;
if (mode == 0 )
addTag("h3",event->summary());
else {
if ( mColorMode == 1 ) {
mText +="<font color=\"#00A000\">";
}
if ( mColorMode == 2 ) {
mText +="<font color=\"#B00000\">";
}
if ( mode == 1 ) {
addTag("h2",i18n( "Local: " ) +event->summary());
} else {
addTag("h2",i18n( "Remote: " ) +event->summary());
}
addTag("h3",i18n( "Last modified: " ) + KGlobal::locale()->formatDateTime(event->lastModified(),shortDate, true ) );
if ( mColorMode )
mText += "</font>";
}
#if 0
if (event->cancelled ()) {
mText +="<font color=\"#B00000\">";
addTag("i",i18n("This todo has been cancelled!"));
mText.append("<br>");
mText += "</font>";
}
#endif
if (!event->location().isEmpty()) {
addTag("b",i18n("Location: "));
mText.append(event->location()+"<br>");
}
if (event->hasDueDate()) {
mText.append(i18n("<p><b>Due on:</b> %1</p>").arg(event->dtDueStr()));
}
mText.append(i18n("<p><b>Priority:</b> %2</p>")
.arg(QString::number(event->priority())));
mText.append(i18n("<p><i>%1 % completed</i></p>")
.arg(event->percentComplete()));
addTag("p",i18n("<b>Access: </b>") +event->secrecyStr() );
formatCategories(event);
if (!event->description().isEmpty()) {
addTag("p",i18n("<b>Details: </b>"));
addTag("p",event->description());
}
formatReadOnly(event);
formatAttendees(event);
}
void KIncidenceFormatter::setJournal(Journal* )
{
}
void KIncidenceFormatter::formatCategories(Incidence *event)
{
if (!event->categoriesStr().isEmpty()) {
addTag("p",i18n("<b>Categories: </b>")+event->categoriesStr() );
//mText.append(event->categoriesStr());
}
}
void KIncidenceFormatter::addTag(const QString & tag,const QString & text)
{
int number=text.contains("\n");
QString str = "<" + tag + ">";
QString tmpText=text;
QString tmpStr=str;
if(number !=-1)
{
if (number > 0) {
int pos=0;
QString tmp;
for(int i=0;i<=number;i++) {
pos=tmpText.find("\n");
tmp=tmpText.left(pos);
tmpText=tmpText.right(tmpText.length()-pos-1);
tmpStr+=tmp+"<br>";
}
}
else tmpStr += tmpText;
tmpStr+="</" + tag + ">";
mText.append(tmpStr);
}
else
{
str += text + "</" + tag + ">";
mText.append(str);
}
}
void KIncidenceFormatter::formatAttendees(Incidence *event)
{
Attendee::List attendees = event->attendees();
if ( attendees.count() ) {
KIconLoader* iconLoader = new KIconLoader();
QString iconPath = iconLoader->iconPath( "mail_generic", KIcon::Small );
addTag( "h3", i18n("Organizer") );
mText.append( "<ul><li>" );
#ifndef KORG_NOKABC
KABC::AddressBook *add_book = KABC::StdAddressBook::self();
KABC::Addressee::List addressList;
addressList = add_book->findByEmail( event->organizer() );
KABC::Addressee o = addressList.first();
if ( !o.isEmpty() && addressList.size() < 2 ) {
addLink( "uid" + o.uid(), o.formattedName() );
} else {
mText.append( event->organizer() );
}
#else
mText.append( event->organizer() );
#endif
if ( !iconPath.isNull() ) {
addLink( "mailto:" + event->organizer(),
"<img src=\"" + iconPath + "\">" );
}
mText.append( "</li></ul>" );
addTag( "h3", i18n("Attendees") );
mText.append( "<ul>" );
Attendee::List::ConstIterator it;
for( it = attendees.begin(); it != attendees.end(); ++it ) {
Attendee *a = *it;
#ifndef KORG_NOKABC
if ( a->name().isEmpty() ) {
addressList = add_book->findByEmail( a->email() );
KABC::Addressee o = addressList.first();
if ( !o.isEmpty() && addressList.size() < 2 ) {
addLink( "uid" + o.uid(), o.formattedName() );
} else {
mText += "<li>";
mText.append( a->email() );
mText += "\n";
}
} else {
mText += "<li><a href=\"uid:" + a->uid() + "\">";
if ( !a->name().isEmpty() ) mText += a->name();
else mText += a->email();
mText += "</a>\n";
}
#else
mText += "<li><a href=\"uid:" + a->uid() + "\">";
if ( !a->name().isEmpty() ) mText += a->name();
else mText += a->email();
mText += "</a>\n";
#endif
kdDebug(5850) << "formatAttendees: uid = " << a->uid() << endl;
if ( !a->email().isEmpty() ) {
if ( !iconPath.isNull() ) {
mText += "<a href=\"mailto:" + a->name() +" "+ "<" + a->email() + ">" + "\">";
mText += "<img src=\"" + iconPath + "\">";
mText += "</a>\n";
}
}
}
mText.append( "</li></ul>" );
}
}
void KIncidenceFormatter::formatReadOnly(Incidence *event)
{
if (event->isReadOnly()) {
addTag("p","<em>(" + i18n("read-only") + ")</em>");
}
}
void KIncidenceFormatter::addLink( const QString &ref, const QString &text,
bool newline )
{
mText += "<a href=\"" + ref + "\">" + text + "</a>";
if ( newline ) mText += "\n";
}
<commit_msg>Fixed compilation<commit_after>#include "kincidenceformatter.h"
#include <kstaticdeleter.h>
#include <kglobal.h>
#include <klocale.h>
#include <kiconloader.h>
#ifndef KORG_NOKABC
#include <kabc/stdaddressbook.h>
#define size count
#endif
KIncidenceFormatter* KIncidenceFormatter::mInstance = 0;
static KStaticDeleter<KIncidenceFormatter> insd;
QString KIncidenceFormatter::getFormattedText( Incidence * inc )
{
mText = "";
if ( inc->type() == "Event" )
setEvent((Event *) inc );
else if ( inc->type() == "Todo" )
setTodo((Todo *) inc );
else if ( inc->type() == "Journal" )
mText = inc->description();
return mText;
}
KIncidenceFormatter* KIncidenceFormatter::instance()
{
if (!mInstance) {
insd.setObject( mInstance, new KIncidenceFormatter());
}
return mInstance;
}
KIncidenceFormatter::~KIncidenceFormatter()
{
}
KIncidenceFormatter::KIncidenceFormatter()
{
mColorMode = 0;
}
void KIncidenceFormatter::setEvent(Event *event)
{
int mode = 0;
mCurrentIncidence = event;
bool shortDate = true;
if ( mode == 0 ) {
addTag("h3",event->summary());
}
else {
if ( mColorMode == 1 ) {
mText +="<font color=\"#00A000\">";
}
if ( mColorMode == 2 ) {
mText +="<font color=\"#C00000\">";
}
// mText +="<font color=\"#F00000\">" + i18n("O-due!") + "</font>";
if ( mode == 1 ) {
addTag("h2",i18n( "Local: " ) +event->summary());
} else {
addTag("h2",i18n( "Remote: " ) +event->summary());
}
addTag("h3",i18n( "Last modified: " ) + KGlobal::locale()->formatDateTime(event->lastModified(),shortDate, true ) );
if ( mColorMode )
mText += "</font>";
}
#if 0
if (event->cancelled ()) {
mText +="<font color=\"#B00000\">";
addTag("i",i18n("This event has been cancelled!"));
mText.append("<br>");
mText += "</font>";
}
#endif
if (!event->location().isEmpty()) {
addTag("b",i18n("Location: "));
mText.append(event->location()+"<br>");
}
if (event->doesFloat()) {
if (event->isMultiDay()) {
mText.append(i18n("<p><b>From:</b> %1 </p><p><b>To:</b> %2</p>")
.arg(event->dtStartDateStr(shortDate))
.arg(event->dtEndDateStr(shortDate)));
} else {
mText.append(i18n("<p><b>On:</b> %1</p>").arg(event->dtStartDateStr( shortDate )));
}
} else {
if (event->isMultiDay()) {
mText.append(i18n("<p><b>From:</b> %1</p> ")
.arg(event->dtStartStr()));
mText.append(i18n("<p><b>To:</b> %1</p>")
.arg(event->dtEndStr()));
} else {
mText.append(i18n("<p><b>On:</b> %1</p> ")
.arg(event->dtStartDateStr( shortDate )));
mText.append(i18n("<p><b>From:</b> %1 <b>To:</b> %2</p>")
.arg(event->dtStartTimeStr())
.arg(event->dtEndTimeStr()));
}
}
if (event->recurrence()->doesRecur()) {
QString recurText = i18n("No");
short recurs = event->recurrence()->doesRecur();
if ( recurs == Recurrence::rMinutely )
recurText = i18n("minutely");
else if ( recurs == Recurrence::rHourly )
recurText = i18n("hourly");
else if ( recurs == Recurrence::rDaily )
recurText = i18n("daily");
else if ( recurs == Recurrence::rWeekly )
recurText = i18n("weekly");
else if ( recurs == Recurrence::rMonthlyPos )
recurText = i18n("monthly");
else if ( recurs == Recurrence::rMonthlyDay )
recurText = i18n("day-monthly");
else if ( recurs == Recurrence::rYearlyMonth )
recurText = i18n("month-yearly");
else if ( recurs == Recurrence::rYearlyDay )
recurText = i18n("day-yearly");
else if ( recurs == Recurrence::rYearlyPos )
recurText = i18n("position-yearly");
addTag("p","<em>" + i18n("This is a %1 recurring event.").arg(recurText ) + "</em>");
bool last;
QDate start = QDate::currentDate();
QDate next;
next = event->recurrence()->getPreviousDate( start , &last );
if ( !last ) {
next = event->recurrence()->getNextDate( start.addDays( - 1 ) );
addTag("p",i18n("Next recurrence is on: ")+ KGlobal::locale()->formatDate( next, shortDate ) );
//addTag("p", KGlobal::locale()->formatDate( next, shortDate ));
} else {
addTag("p",i18n("<b>Last recurrence was on:</b>") );
addTag("p", KGlobal::locale()->formatDate( next, shortDate ));
}
}
if (event->isAlarmEnabled()) {
Alarm *alarm =event->alarms().first() ;
QDateTime t = alarm->time();
int min = t.secsTo( event->dtStart() )/60;
QString s =i18n("(%1 min before)").arg( min );
addTag("p",i18n("<b>Alarm on: </b>") + s + ": "+KGlobal::locale()->formatDateTime( t, shortDate ));
//addTag("p", KGlobal::locale()->formatDateTime( t, shortDate ));
//addTag("p",s);
}
addTag("p",i18n("<b>Access: </b>") +event->secrecyStr() );
// mText.append(event->secrecyStr()+"<br>");
formatCategories(event);
if (!event->description().isEmpty()) {
addTag("p",i18n("<b>Details: </b>"));
addTag("p",event->description());
}
formatReadOnly(event);
formatAttendees(event);
}
void KIncidenceFormatter::setTodo(Todo *event )
{
int mode = 0;
mCurrentIncidence = event;
bool shortDate = true;
if (mode == 0 )
addTag("h3",event->summary());
else {
if ( mColorMode == 1 ) {
mText +="<font color=\"#00A000\">";
}
if ( mColorMode == 2 ) {
mText +="<font color=\"#B00000\">";
}
if ( mode == 1 ) {
addTag("h2",i18n( "Local: " ) +event->summary());
} else {
addTag("h2",i18n( "Remote: " ) +event->summary());
}
addTag("h3",i18n( "Last modified: " ) + KGlobal::locale()->formatDateTime(event->lastModified(),shortDate, true ) );
if ( mColorMode )
mText += "</font>";
}
#if 0
if (event->cancelled ()) {
mText +="<font color=\"#B00000\">";
addTag("i",i18n("This todo has been cancelled!"));
mText.append("<br>");
mText += "</font>";
}
#endif
if (!event->location().isEmpty()) {
addTag("b",i18n("Location: "));
mText.append(event->location()+"<br>");
}
if (event->hasDueDate()) {
mText.append(i18n("<p><b>Due on:</b> %1</p>").arg(event->dtDueStr()));
}
mText.append(i18n("<p><b>Priority:</b> %2</p>")
.arg(QString::number(event->priority())));
mText.append(i18n("<p><i>%1 % completed</i></p>")
.arg(event->percentComplete()));
addTag("p",i18n("<b>Access: </b>") +event->secrecyStr() );
formatCategories(event);
if (!event->description().isEmpty()) {
addTag("p",i18n("<b>Details: </b>"));
addTag("p",event->description());
}
formatReadOnly(event);
formatAttendees(event);
}
void KIncidenceFormatter::setJournal(Journal* )
{
}
void KIncidenceFormatter::formatCategories(Incidence *event)
{
if (!event->categoriesStr().isEmpty()) {
addTag("p",i18n("<b>Categories: </b>")+event->categoriesStr() );
//mText.append(event->categoriesStr());
}
}
void KIncidenceFormatter::addTag(const QString & tag,const QString & text)
{
int number=text.contains("\n");
QString str = "<" + tag + ">";
QString tmpText=text;
QString tmpStr=str;
if(number !=-1)
{
if (number > 0) {
int pos=0;
QString tmp;
for(int i=0;i<=number;i++) {
pos=tmpText.find("\n");
tmp=tmpText.left(pos);
tmpText=tmpText.right(tmpText.length()-pos-1);
tmpStr+=tmp+"<br>";
}
}
else tmpStr += tmpText;
tmpStr+="</" + tag + ">";
mText.append(tmpStr);
}
else
{
str += text + "</" + tag + ">";
mText.append(str);
}
}
void KIncidenceFormatter::formatAttendees(Incidence *event)
{
Attendee::List attendees = event->attendees();
if ( attendees.count() ) {
KIconLoader* iconLoader = new KIconLoader();
QString iconPath = iconLoader->iconPath( "mail_generic", KIcon::Small );
addTag( "h3", i18n("Organizer") );
mText.append( "<ul><li>" );
#ifndef KORG_NOKABC
KABC::AddressBook *add_book = KABC::StdAddressBook::self();
KABC::Addressee::List addressList;
addressList = add_book->findByEmail( event->organizer().email() );
KABC::Addressee o = addressList.first();
if ( !o.isEmpty() && addressList.size() < 2 ) {
addLink( "uid" + o.uid(), o.formattedName() );
} else {
mText.append( event->organizer().fullName() );
}
#else
mText.append( event->organizer().fullName() );
#endif
if ( !iconPath.isNull() ) {
addLink( "mailto:" + event->organizer().email(), // fullName would look nicer, but needs escaping
"<img src=\"" + iconPath + "\">" );
}
mText.append( "</li></ul>" );
addTag( "h3", i18n("Attendees") );
mText.append( "<ul>" );
Attendee::List::ConstIterator it;
for( it = attendees.begin(); it != attendees.end(); ++it ) {
Attendee *a = *it;
#ifndef KORG_NOKABC
if ( a->name().isEmpty() ) {
addressList = add_book->findByEmail( a->email() );
KABC::Addressee o = addressList.first();
if ( !o.isEmpty() && addressList.size() < 2 ) {
addLink( "uid" + o.uid(), o.formattedName() );
} else {
mText += "<li>";
mText.append( a->email() );
mText += "\n";
}
} else {
mText += "<li><a href=\"uid:" + a->uid() + "\">";
if ( !a->name().isEmpty() ) mText += a->name();
else mText += a->email();
mText += "</a>\n";
}
#else
mText += "<li><a href=\"uid:" + a->uid() + "\">";
if ( !a->name().isEmpty() ) mText += a->name();
else mText += a->email();
mText += "</a>\n";
#endif
kdDebug(5850) << "formatAttendees: uid = " << a->uid() << endl;
if ( !a->email().isEmpty() ) {
if ( !iconPath.isNull() ) {
mText += "<a href=\"mailto:" + a->name() +" "+ "<" + a->email() + ">" + "\">";
mText += "<img src=\"" + iconPath + "\">";
mText += "</a>\n";
}
}
}
mText.append( "</li></ul>" );
}
}
void KIncidenceFormatter::formatReadOnly(Incidence *event)
{
if (event->isReadOnly()) {
addTag("p","<em>(" + i18n("read-only") + ")</em>");
}
}
void KIncidenceFormatter::addLink( const QString &ref, const QString &text,
bool newline )
{
mText += "<a href=\"" + ref + "\">" + text + "</a>";
if ( newline ) mText += "\n";
}
<|endoftext|> |
<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: [email protected] <Nadav Samet>
#include "rpcz/server.h"
#include <signal.h>
#include <string.h>
#include <sys/errno.h>
#include <sys/signal.h>
#include <iostream>
#include <utility>
#include "boost/bind.hpp"
#include "google/protobuf/descriptor.h"
#include "google/protobuf/message.h"
#include "google/protobuf/stubs/common.h"
#include "zmq.hpp"
#include "rpcz/callback.h"
#include "rpcz/connection_manager.h"
#include "rpcz/function_server.h"
#include "rpcz/logging.h"
#include "rpcz/macros.h"
#include "rpcz/rpc.h"
#include "rpcz/reactor.h"
#include "rpcz/service.h"
#include "rpcz/zmq_utils.h"
#include "rpcz/rpcz.pb.h"
namespace rpcz {
class ServerChannelImpl;
class ServerImpl {
public:
ServerImpl(zmq::socket_t* socket, FunctionServer* function_server);
~ServerImpl();
void Start();
void RegisterService(RpcService *service, const std::string& name);
private:
void HandleFunctionResponse(zmq::socket_t* fs_socket);
void HandleRequestWorker(MessageVector* routes_,
MessageVector* data_,
FunctionServer::ReplyFunction reply);
void HandleRequest(zmq::socket_t* fs_socket);
zmq::socket_t* socket_;
FunctionServer* function_server_;
typedef std::map<std::string, rpcz::RpcService*> RpcServiceMap;
RpcServiceMap service_map_;
DISALLOW_COPY_AND_ASSIGN(ServerImpl);
};
class ServerChannelImpl : public ServerChannel {
public:
ServerChannelImpl(MessageVector* routes,
zmq::message_t* request_id,
FunctionServer::ReplyFunction reply)
: routes_(routes), request_id_(request_id),
reply_(reply) { }
virtual void Send(const google::protobuf::Message& response) {
RpcResponseHeader generic_rpc_response;
int msg_size = response.ByteSize();
scoped_ptr<zmq::message_t> payload(new zmq::message_t(msg_size));
if (!response.SerializeToArray(payload->data(), msg_size)) {
throw InvalidMessageError("Invalid response message");
}
SendGenericResponse(generic_rpc_response,
payload.release());
}
virtual void Send0(const std::string& response) {
RpcResponseHeader generic_rpc_response;
SendGenericResponse(generic_rpc_response,
StringToMessage(response));
}
virtual void SendError(int application_error,
const std::string& error_message="") {
RpcResponseHeader generic_rpc_response;
zmq::message_t* payload = new zmq::message_t();
generic_rpc_response.set_status(status::APPLICATION_ERROR);
generic_rpc_response.set_application_error(application_error);
if (!error_message.empty()) {
generic_rpc_response.set_error(error_message);
}
SendGenericResponse(generic_rpc_response,
payload);
}
private:
scoped_ptr<MessageVector> routes_;
scoped_ptr<zmq::message_t> request_id_;
scoped_ptr<google::protobuf::Message> request_;
FunctionServer::ReplyFunction reply_;
// Sends the response back to a function server through the reply function.
// Takes ownership of the provided payload message.
void SendGenericResponse(const RpcResponseHeader& generic_rpc_response,
zmq::message_t* payload) {
size_t msg_size = generic_rpc_response.ByteSize();
zmq::message_t* zmq_response_message = new zmq::message_t(msg_size);
CHECK(generic_rpc_response.SerializeToArray(
zmq_response_message->data(),
msg_size));
routes_->push_back(request_id_.release());
routes_->push_back(zmq_response_message);
routes_->push_back(payload);
reply_(routes_.get());
}
friend class ProtoRpcService;
};
class ProtoRpcService : public RpcService {
public:
explicit ProtoRpcService(Service* service) : service_(service) {
}
virtual void DispatchRequest(const std::string& method,
const void* payload, size_t payload_len,
ServerChannel* channel_) {
scoped_ptr<ServerChannelImpl> channel(
static_cast<ServerChannelImpl*>(channel_));
const ::google::protobuf::MethodDescriptor* descriptor =
service_->GetDescriptor()->FindMethodByName(
method);
if (descriptor == NULL) {
// Invalid method name
DLOG(INFO) << "Invalid method name: " << method,
channel->SendError(application_error::NO_SUCH_METHOD);
return;
}
channel->request_.reset(CHECK_NOTNULL(
service_->GetRequestPrototype(descriptor).New()));
if (!channel->request_->ParseFromArray(payload, payload_len)) {
DLOG(INFO) << "Failed to parse request.";
// Invalid proto;
channel->SendError(application_error::INVALID_MESSAGE);
return;
}
service_->CallMethod(descriptor,
*channel->request_,
channel.release());
}
private:
Service* service_;
};
ServerImpl::ServerImpl(zmq::socket_t* socket, FunctionServer* function_server)
: socket_(socket), function_server_(function_server) {}
void ServerImpl::Start() {
// The reactor owns all sockets.
Reactor reactor;
zmq::socket_t* fs_socket = function_server_->GetConnectedSocket();
reactor.AddSocket(socket_, NewPermanentCallback(
this, &ServerImpl::HandleRequest, fs_socket));
reactor.AddSocket(fs_socket,
NewPermanentCallback(
this, &ServerImpl::HandleFunctionResponse,
fs_socket));
reactor.Loop();
}
void ServerImpl::RegisterService(RpcService *rpc_service,
const std::string& name) {
service_map_[name] = rpc_service;
}
void ServerImpl::HandleFunctionResponse(zmq::socket_t* fs_socket) {
MessageVector data;
CHECK(ReadMessageToVector(fs_socket, &data));
data.erase_first();
WriteVectorToSocket(socket_, data);
}
void ServerImpl::HandleRequestWorker(MessageVector* routes_,
MessageVector* data_,
FunctionServer::ReplyFunction reply) {
// We are responsible to delete routes and data (and the pointers they
// contain, so first wrap them in scoped_ptr's.
scoped_ptr<ServerChannel> channel(new ServerChannelImpl(
routes_,
data_->release(0),
reply));
scoped_ptr<MessageVector> data(data_);
CHECK_EQ(3u, data->size());
zmq::message_t& request = (*data)[1];
zmq::message_t& payload = (*data)[2];
RpcRequestHeader rpc_request_header;
if (!rpc_request_header.ParseFromArray(request.data(), request.size())) {
// Handle bad RPC.
DLOG(INFO) << "Received bad header.";
channel->SendError(application_error::INVALID_HEADER);
return;
};
RpcServiceMap::const_iterator service_it = service_map_.find(
rpc_request_header.service());
if (service_it == service_map_.end()) {
// Handle invalid service.
DLOG(INFO) << "Invalid service: " << rpc_request_header.service();
channel->SendError(application_error::NO_SUCH_SERVICE);
return;
}
rpcz::RpcService* service = service_it->second;
service->DispatchRequest(rpc_request_header.method(), payload.data(),
payload.size(),
channel.release());
}
void ServerImpl::HandleRequest(zmq::socket_t* fs_socket) {
scoped_ptr<MessageVector> routes(new MessageVector());
scoped_ptr<MessageVector> data(new MessageVector());
ReadMessageToVector(socket_, routes.get(), data.get());
if (data->size() != 3) {
DLOG(INFO) << "Dropping invalid requests.";
return;
}
FunctionServer::AddFunction(
fs_socket,
boost::bind(&ServerImpl::HandleRequestWorker,
this, routes.release(), data.release(), _1));
}
ServerImpl::~ServerImpl() {
DeleteContainerSecondPointer(service_map_.begin(),
service_map_.end());
}
Server::Server(zmq::socket_t* socket, EventManager* event_manager)
: server_impl_(new ServerImpl(socket, event_manager->GetFunctionServer())) {
}
Server::~Server() {
}
void Server::Start() {
server_impl_->Start();
}
void Server::RegisterService(rpcz::Service *service) {
RegisterService(service,
service->GetDescriptor()->name());
}
void Server::RegisterService(rpcz::Service *service, const std::string& name) {
RegisterService(new ProtoRpcService(service),
name);
}
void Server::RegisterService(rpcz::RpcService *rpc_service,
const std::string& name) {
server_impl_->RegisterService(rpc_service,
name);
}
} // namespace
<commit_msg>fix a bug that caused segfaults on linux (order of argument evaluation in c++ is unspecified)<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: [email protected] <Nadav Samet>
#include "rpcz/server.h"
#include <signal.h>
#include <string.h>
#include <sys/errno.h>
#include <sys/signal.h>
#include <iostream>
#include <utility>
#include "boost/bind.hpp"
#include "google/protobuf/descriptor.h"
#include "google/protobuf/message.h"
#include "google/protobuf/stubs/common.h"
#include "zmq.hpp"
#include "rpcz/callback.h"
#include "rpcz/connection_manager.h"
#include "rpcz/function_server.h"
#include "rpcz/logging.h"
#include "rpcz/macros.h"
#include "rpcz/rpc.h"
#include "rpcz/reactor.h"
#include "rpcz/service.h"
#include "rpcz/zmq_utils.h"
#include "rpcz/rpcz.pb.h"
namespace rpcz {
class ServerChannelImpl;
class ServerImpl {
public:
ServerImpl(zmq::socket_t* socket, FunctionServer* function_server);
~ServerImpl();
void Start();
void RegisterService(RpcService *service, const std::string& name);
private:
void HandleFunctionResponse(zmq::socket_t* fs_socket);
void HandleRequestWorker(MessageVector* routes_,
MessageVector* data_,
FunctionServer::ReplyFunction reply);
void HandleRequest(zmq::socket_t* fs_socket);
zmq::socket_t* socket_;
FunctionServer* function_server_;
typedef std::map<std::string, rpcz::RpcService*> RpcServiceMap;
RpcServiceMap service_map_;
DISALLOW_COPY_AND_ASSIGN(ServerImpl);
};
class ServerChannelImpl : public ServerChannel {
public:
ServerChannelImpl(MessageVector* routes,
zmq::message_t* request_id,
FunctionServer::ReplyFunction reply)
: routes_(routes), request_id_(request_id),
reply_(reply) { }
virtual void Send(const google::protobuf::Message& response) {
RpcResponseHeader generic_rpc_response;
int msg_size = response.ByteSize();
scoped_ptr<zmq::message_t> payload(new zmq::message_t(msg_size));
if (!response.SerializeToArray(payload->data(), msg_size)) {
throw InvalidMessageError("Invalid response message");
}
SendGenericResponse(generic_rpc_response,
payload.release());
}
virtual void Send0(const std::string& response) {
RpcResponseHeader generic_rpc_response;
SendGenericResponse(generic_rpc_response,
StringToMessage(response));
}
virtual void SendError(int application_error,
const std::string& error_message="") {
RpcResponseHeader generic_rpc_response;
zmq::message_t* payload = new zmq::message_t();
generic_rpc_response.set_status(status::APPLICATION_ERROR);
generic_rpc_response.set_application_error(application_error);
if (!error_message.empty()) {
generic_rpc_response.set_error(error_message);
}
SendGenericResponse(generic_rpc_response,
payload);
}
private:
scoped_ptr<MessageVector> routes_;
scoped_ptr<zmq::message_t> request_id_;
scoped_ptr<google::protobuf::Message> request_;
FunctionServer::ReplyFunction reply_;
// Sends the response back to a function server through the reply function.
// Takes ownership of the provided payload message.
void SendGenericResponse(const RpcResponseHeader& generic_rpc_response,
zmq::message_t* payload) {
size_t msg_size = generic_rpc_response.ByteSize();
zmq::message_t* zmq_response_message = new zmq::message_t(msg_size);
CHECK(generic_rpc_response.SerializeToArray(
zmq_response_message->data(),
msg_size));
routes_->push_back(request_id_.release());
routes_->push_back(zmq_response_message);
routes_->push_back(payload);
reply_(routes_.get());
}
friend class ProtoRpcService;
};
class ProtoRpcService : public RpcService {
public:
explicit ProtoRpcService(Service* service) : service_(service) {
}
virtual void DispatchRequest(const std::string& method,
const void* payload, size_t payload_len,
ServerChannel* channel_) {
scoped_ptr<ServerChannelImpl> channel(
static_cast<ServerChannelImpl*>(channel_));
const ::google::protobuf::MethodDescriptor* descriptor =
service_->GetDescriptor()->FindMethodByName(
method);
if (descriptor == NULL) {
// Invalid method name
DLOG(INFO) << "Invalid method name: " << method,
channel->SendError(application_error::NO_SUCH_METHOD);
return;
}
channel->request_.reset(CHECK_NOTNULL(
service_->GetRequestPrototype(descriptor).New()));
if (!channel->request_->ParseFromArray(payload, payload_len)) {
DLOG(INFO) << "Failed to parse request.";
// Invalid proto;
channel->SendError(application_error::INVALID_MESSAGE);
return;
}
ServerChannelImpl* channel_ptr = channel.release();
service_->CallMethod(descriptor,
*channel_ptr->request_,
channel_ptr);
}
private:
Service* service_;
};
ServerImpl::ServerImpl(zmq::socket_t* socket, FunctionServer* function_server)
: socket_(socket), function_server_(function_server) {}
void ServerImpl::Start() {
// The reactor owns all sockets.
Reactor reactor;
zmq::socket_t* fs_socket = function_server_->GetConnectedSocket();
reactor.AddSocket(socket_, NewPermanentCallback(
this, &ServerImpl::HandleRequest, fs_socket));
reactor.AddSocket(fs_socket,
NewPermanentCallback(
this, &ServerImpl::HandleFunctionResponse,
fs_socket));
reactor.Loop();
}
void ServerImpl::RegisterService(RpcService *rpc_service,
const std::string& name) {
service_map_[name] = rpc_service;
}
void ServerImpl::HandleFunctionResponse(zmq::socket_t* fs_socket) {
MessageVector data;
CHECK(ReadMessageToVector(fs_socket, &data));
data.erase_first();
WriteVectorToSocket(socket_, data);
}
void ServerImpl::HandleRequestWorker(MessageVector* routes_,
MessageVector* data_,
FunctionServer::ReplyFunction reply) {
// We are responsible to delete routes and data (and the pointers they
// contain, so first wrap them in scoped_ptr's.
scoped_ptr<ServerChannel> channel(new ServerChannelImpl(
routes_,
data_->release(0),
reply));
scoped_ptr<MessageVector> data(data_);
CHECK_EQ(3u, data->size());
zmq::message_t& request = (*data)[1];
zmq::message_t& payload = (*data)[2];
RpcRequestHeader rpc_request_header;
if (!rpc_request_header.ParseFromArray(request.data(), request.size())) {
// Handle bad RPC.
DLOG(INFO) << "Received bad header.";
channel->SendError(application_error::INVALID_HEADER);
return;
};
RpcServiceMap::const_iterator service_it = service_map_.find(
rpc_request_header.service());
if (service_it == service_map_.end()) {
// Handle invalid service.
DLOG(INFO) << "Invalid service: " << rpc_request_header.service();
channel->SendError(application_error::NO_SUCH_SERVICE);
return;
}
rpcz::RpcService* service = service_it->second;
service->DispatchRequest(rpc_request_header.method(), payload.data(),
payload.size(),
channel.release());
}
void ServerImpl::HandleRequest(zmq::socket_t* fs_socket) {
scoped_ptr<MessageVector> routes(new MessageVector());
scoped_ptr<MessageVector> data(new MessageVector());
ReadMessageToVector(socket_, routes.get(), data.get());
if (data->size() != 3) {
DLOG(INFO) << "Dropping invalid requests.";
return;
}
FunctionServer::AddFunction(
fs_socket,
boost::bind(&ServerImpl::HandleRequestWorker,
this, routes.release(), data.release(), _1));
}
ServerImpl::~ServerImpl() {
DeleteContainerSecondPointer(service_map_.begin(),
service_map_.end());
}
Server::Server(zmq::socket_t* socket, EventManager* event_manager)
: server_impl_(new ServerImpl(socket, event_manager->GetFunctionServer())) {
}
Server::~Server() {
}
void Server::Start() {
server_impl_->Start();
}
void Server::RegisterService(rpcz::Service *service) {
RegisterService(service,
service->GetDescriptor()->name());
}
void Server::RegisterService(rpcz::Service *service, const std::string& name) {
RegisterService(new ProtoRpcService(service),
name);
}
void Server::RegisterService(rpcz::RpcService *rpc_service,
const std::string& name) {
server_impl_->RegisterService(rpc_service,
name);
}
} // namespace
<|endoftext|> |
<commit_before>/*******************************************************************************
* libproxy - A library for proxy configuration
* Copyright (C) 2006 Nathaniel McCallum <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
******************************************************************************/
#include <cstdio> // For fileno(), fread(), pclose(), popen(), sscanf()
#include <sys/select.h> // For select()
#include <fcntl.h> // For fcntl()
#include <errno.h> // For errno stuff
#include <unistd.h> // For pipe(), close(), vfork(), dup(), execl(), _exit()
#include <signal.h> // For kill()
#include "../extension_config.hpp"
using namespace libproxy;
#define BUFFERSIZE 10240
#define PROXY_MODE "/system/proxy/mode"
#define PROXY_USE_AUTHENTICATION "/system/http_proxy/use_authentication"
#define PROXY_AUTH_PASSWORD "/system/http_proxy/authentication_password"
#define PROXY_AUTH_USER "/system/http_proxy/authentication_user"
#define PROXY_AUTOCONFIG_URL "/system/proxy/autoconfig_url"
#define PROXY_IGNORE_HOSTS "/system/http_proxy/ignore_hosts"
#define PROXY_HTTP_HOST "/system/http_proxy/host"
#define PROXY_HTTP_PORT "/system/http_proxy/port"
#define PROXY_FTP_HOST "/system/proxy/ftp_host"
#define PROXY_FTP_PORT "/system/proxy/ftp_port"
#define PROXY_SECURE_HOST "/system/proxy/secure_host"
#define PROXY_SECURE_PORT "/system/proxy/secure_port"
#define PROXY_SOCKS_HOST "/system/proxy/socks_host"
#define PROXY_SOCKS_PORT "/system/proxy/socks_port"
#define PROXY_SAME_FOR_ALL "/system/http_proxy/use_same_proxy"
static const char *all_keys[] = {
PROXY_MODE,
PROXY_USE_AUTHENTICATION,
PROXY_AUTH_PASSWORD,
PROXY_AUTH_USER,
PROXY_AUTOCONFIG_URL,
PROXY_IGNORE_HOSTS,
PROXY_HTTP_HOST,
PROXY_HTTP_PORT,
PROXY_FTP_HOST,
PROXY_FTP_PORT,
PROXY_SECURE_HOST,
PROXY_SECURE_PORT,
PROXY_SOCKS_HOST,
PROXY_SOCKS_PORT,
PROXY_SAME_FOR_ALL,
NULL
};
static int popen2(const char *program, FILE** read, FILE** write, pid_t* pid) {
if (!read || !write || !pid || !program || !*program)
return EINVAL;
*read = NULL;
*write = NULL;
*pid = 0;
// Open the pipes
int rpipe[2];
int wpipe[2];
if (pipe(rpipe) < 0)
return errno;
if (pipe(wpipe) < 0) {
close(rpipe[0]);
close(rpipe[1]);
return errno;
}
switch (*pid = vfork()) {
case -1: // Error
close(rpipe[0]);
close(rpipe[1]);
close(wpipe[0]);
close(wpipe[1]);
return errno;
case 0: // Child
close(STDIN_FILENO); // Close stdin
close(STDOUT_FILENO); // Close stdout
// Dup the read end of the write pipe to stdin
// Dup the write end of the read pipe to stdout
if (dup2(wpipe[0], STDIN_FILENO) != STDIN_FILENO) _exit(1);
if (dup2(rpipe[1], STDOUT_FILENO) != STDOUT_FILENO) _exit(2);
// Close unneeded fds
close(rpipe[0]);
close(rpipe[1]);
close(wpipe[0]);
close(wpipe[1]);
// Exec
execl("/bin/sh", "sh", "-c", program, (char*) NULL);
_exit(127); // Whatever we do, don't return
default: // Parent
close(rpipe[1]);
close(wpipe[0]);
*read = fdopen(rpipe[0], "r");
*write = fdopen(wpipe[1], "w");
if (*read == NULL || *write == NULL) {
if (*read != NULL) fclose(*read);
if (*write != NULL) fclose(*write);
return errno;
}
return 0;
}
}
static inline uint16_t get_port(string &port)
{
uint16_t retval;
if (sscanf(port.c_str(), "%hu", &retval) != 1)
retval = 0;
return retval;
}
class gnome_config_extension : public config_extension {
public:
gnome_config_extension() {
// Build the command
int count;
struct stat st;
string cmd = LIBEXECDIR "/pxgconf";
const char *pxgconf = getenv("PX_GCONF");
if (pxgconf)
cmd = string (pxgconf);
if (stat(cmd.c_str(), &st))
throw runtime_error ("Unable to open gconf helper!");
for (count=0 ; all_keys[count] ; count++)
cmd += string(" ", 1) + all_keys[count];
// Get our pipes
if (popen2(cmd.c_str(), &this->read, &this->write, &this->pid) != 0)
throw runtime_error("Unable to run gconf helper!");
// Read in our initial data
this->read_data(count);
// Set the read pipe to non-blocking
if (fcntl(fileno(this->read), F_SETFL, O_NONBLOCK) == -1) {
fclose(this->read);
fclose(this->write);
kill(this->pid, SIGTERM);
throw runtime_error("Unable to set pipe to non-blocking!");
}
}
~gnome_config_extension() {
fclose(this->read);
fclose(this->write);
kill(this->pid, SIGTERM);
}
url get_config(url dest) throw (runtime_error) {
// Check for changes in the config
fd_set rfds;
struct timeval timeout = { 0, 0 };
FD_ZERO(&rfds);
FD_SET(fileno(this->read), &rfds);
if (select(fileno(this->read)+1, &rfds, NULL, NULL, &timeout) > 0)
this->read_data();
// Mode is wpad:// or pac+http://...
if (this->data[PROXY_MODE] == "auto") {
string pac = this->data[PROXY_AUTOCONFIG_URL];
return url::is_valid(pac) ? url(string("pac+") + pac) : url("wpad://");
}
// Mode is http://... or socks://...
else if (this->data[PROXY_MODE] == "manual") {
string type, host, port;
bool auth = this->data[PROXY_USE_AUTHENTICATION] == "true";
string username = this->data[PROXY_AUTH_USER];
string password = this->data[PROXY_AUTH_PASSWORD];
bool same_proxy = this->data[PROXY_SAME_FOR_ALL] == "true";
// If socks is set use it (except when same_proxy is set)
if (!same_proxy) {
type = "socks";
host = this->data[PROXY_SOCKS_HOST];
port = this->data[PROXY_SOCKS_PORT];
}
if (host == "" || get_port(port) == 0) {
// Get the per-scheme proxy settings
if (dest.get_scheme() == "http") {
type = "http";
host = this->data[PROXY_HTTP_HOST];
port = this->data[PROXY_HTTP_PORT];
}
else if (dest.get_scheme() == "https") {
type = "http"; /* We merge HTTP and HTTPS */
host = this->data[PROXY_SECURE_HOST];
port = this->data[PROXY_SECURE_PORT];
}
else if (dest.get_scheme() == "ftp") {
type = "ftp";
host = this->data[PROXY_FTP_HOST];
port = this->data[PROXY_FTP_PORT];
}
// If no proxy is set and we have the same_proxy option
// enabled try socks at the end only.
if (same_proxy && (host == "" || get_port(port) == 0)) {
type = "socks";
host = this->data[PROXY_SOCKS_HOST];
port = this->data[PROXY_SOCKS_PORT];
}
}
// If host and port were found, build config url
if (host != "" && get_port(port) != 0) {
string tmp = type + "://";
if (auth)
tmp += username + ":" + password + "@";
tmp += host + ":" + port;
return url(tmp);
}
}
// Mode is direct://
return url("direct://");
}
string get_ignore(url) {
return this->data[PROXY_IGNORE_HOSTS];
}
bool set_creds(url /*proxy*/, string username, string password) {
string auth = PROXY_USE_AUTHENTICATION "\ttrue\n";
string user = string(PROXY_AUTH_USER "\t") + username + "\n";
string pass = string(PROXY_AUTH_PASSWORD "\t") + password + "\n";
return (fwrite(auth.c_str(), 1, auth.size(), this->write) == auth.size() &&
fwrite(user.c_str(), 1, user.size(), this->write) == user.size() &&
fwrite(pass.c_str(), 1, pass.size(), this->write) == pass.size());
}
private:
FILE* read;
FILE* write;
pid_t pid;
map<string, string> data;
bool read_data(int num=-1) {
if (num == 0) return true;
if (!this->read) return false; // We need the pipe to be open
for (char l[BUFFERSIZE] ; num != 0 && fgets(l, BUFFERSIZE, this->read) != NULL ; ) {
string line = l;
line = line.substr(0, line.rfind('\n'));
string key = line.substr(0, line.find("\t"));
string val = line.substr(line.find("\t")+1);
this->data[key] = val;
if (num > 0) num--;
}
return (num <= 0);
}
};
static base_extension** gnome_config_extension_init() {
base_extension** retval = new base_extension*[2];
retval[1] = NULL;
try {
retval[0] = new gnome_config_extension();
return retval;
}
catch (runtime_error) {
delete retval;
return NULL;
}
}
MM_MODULE_INIT(gnome_config_extension, gnome_config_extension_init);
MM_MODULE_TEST_EZ(gnome_config_extension,
(
getenv("GNOME_DESKTOP_SESSION_ID") ||
(getenv("DESKTOP_SESSION") && string(getenv("DESKTOP_SESSION")) == "gnome")
)
);
<commit_msg>Fix FTP to return HTTP for proxy type, and explain what is expected from HTTP server. Also improved doc to explain what is expected for HTTPS proxy server,<commit_after>/*******************************************************************************
* libproxy - A library for proxy configuration
* Copyright (C) 2006 Nathaniel McCallum <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
******************************************************************************/
#include <cstdio> // For fileno(), fread(), pclose(), popen(), sscanf()
#include <sys/select.h> // For select()
#include <fcntl.h> // For fcntl()
#include <errno.h> // For errno stuff
#include <unistd.h> // For pipe(), close(), vfork(), dup(), execl(), _exit()
#include <signal.h> // For kill()
#include "../extension_config.hpp"
using namespace libproxy;
#define BUFFERSIZE 10240
#define PROXY_MODE "/system/proxy/mode"
#define PROXY_USE_AUTHENTICATION "/system/http_proxy/use_authentication"
#define PROXY_AUTH_PASSWORD "/system/http_proxy/authentication_password"
#define PROXY_AUTH_USER "/system/http_proxy/authentication_user"
#define PROXY_AUTOCONFIG_URL "/system/proxy/autoconfig_url"
#define PROXY_IGNORE_HOSTS "/system/http_proxy/ignore_hosts"
#define PROXY_HTTP_HOST "/system/http_proxy/host"
#define PROXY_HTTP_PORT "/system/http_proxy/port"
#define PROXY_FTP_HOST "/system/proxy/ftp_host"
#define PROXY_FTP_PORT "/system/proxy/ftp_port"
#define PROXY_SECURE_HOST "/system/proxy/secure_host"
#define PROXY_SECURE_PORT "/system/proxy/secure_port"
#define PROXY_SOCKS_HOST "/system/proxy/socks_host"
#define PROXY_SOCKS_PORT "/system/proxy/socks_port"
#define PROXY_SAME_FOR_ALL "/system/http_proxy/use_same_proxy"
static const char *all_keys[] = {
PROXY_MODE,
PROXY_USE_AUTHENTICATION,
PROXY_AUTH_PASSWORD,
PROXY_AUTH_USER,
PROXY_AUTOCONFIG_URL,
PROXY_IGNORE_HOSTS,
PROXY_HTTP_HOST,
PROXY_HTTP_PORT,
PROXY_FTP_HOST,
PROXY_FTP_PORT,
PROXY_SECURE_HOST,
PROXY_SECURE_PORT,
PROXY_SOCKS_HOST,
PROXY_SOCKS_PORT,
PROXY_SAME_FOR_ALL,
NULL
};
static int popen2(const char *program, FILE** read, FILE** write, pid_t* pid) {
if (!read || !write || !pid || !program || !*program)
return EINVAL;
*read = NULL;
*write = NULL;
*pid = 0;
// Open the pipes
int rpipe[2];
int wpipe[2];
if (pipe(rpipe) < 0)
return errno;
if (pipe(wpipe) < 0) {
close(rpipe[0]);
close(rpipe[1]);
return errno;
}
switch (*pid = vfork()) {
case -1: // Error
close(rpipe[0]);
close(rpipe[1]);
close(wpipe[0]);
close(wpipe[1]);
return errno;
case 0: // Child
close(STDIN_FILENO); // Close stdin
close(STDOUT_FILENO); // Close stdout
// Dup the read end of the write pipe to stdin
// Dup the write end of the read pipe to stdout
if (dup2(wpipe[0], STDIN_FILENO) != STDIN_FILENO) _exit(1);
if (dup2(rpipe[1], STDOUT_FILENO) != STDOUT_FILENO) _exit(2);
// Close unneeded fds
close(rpipe[0]);
close(rpipe[1]);
close(wpipe[0]);
close(wpipe[1]);
// Exec
execl("/bin/sh", "sh", "-c", program, (char*) NULL);
_exit(127); // Whatever we do, don't return
default: // Parent
close(rpipe[1]);
close(wpipe[0]);
*read = fdopen(rpipe[0], "r");
*write = fdopen(wpipe[1], "w");
if (*read == NULL || *write == NULL) {
if (*read != NULL) fclose(*read);
if (*write != NULL) fclose(*write);
return errno;
}
return 0;
}
}
static inline uint16_t get_port(string &port)
{
uint16_t retval;
if (sscanf(port.c_str(), "%hu", &retval) != 1)
retval = 0;
return retval;
}
class gnome_config_extension : public config_extension {
public:
gnome_config_extension() {
// Build the command
int count;
struct stat st;
string cmd = LIBEXECDIR "/pxgconf";
const char *pxgconf = getenv("PX_GCONF");
if (pxgconf)
cmd = string (pxgconf);
if (stat(cmd.c_str(), &st))
throw runtime_error ("Unable to open gconf helper!");
for (count=0 ; all_keys[count] ; count++)
cmd += string(" ", 1) + all_keys[count];
// Get our pipes
if (popen2(cmd.c_str(), &this->read, &this->write, &this->pid) != 0)
throw runtime_error("Unable to run gconf helper!");
// Read in our initial data
this->read_data(count);
// Set the read pipe to non-blocking
if (fcntl(fileno(this->read), F_SETFL, O_NONBLOCK) == -1) {
fclose(this->read);
fclose(this->write);
kill(this->pid, SIGTERM);
throw runtime_error("Unable to set pipe to non-blocking!");
}
}
~gnome_config_extension() {
fclose(this->read);
fclose(this->write);
kill(this->pid, SIGTERM);
}
url get_config(url dest) throw (runtime_error) {
// Check for changes in the config
fd_set rfds;
struct timeval timeout = { 0, 0 };
FD_ZERO(&rfds);
FD_SET(fileno(this->read), &rfds);
if (select(fileno(this->read)+1, &rfds, NULL, NULL, &timeout) > 0)
this->read_data();
// Mode is wpad:// or pac+http://...
if (this->data[PROXY_MODE] == "auto") {
string pac = this->data[PROXY_AUTOCONFIG_URL];
return url::is_valid(pac) ? url(string("pac+") + pac) : url("wpad://");
}
// Mode is http://... or socks://...
else if (this->data[PROXY_MODE] == "manual") {
string type, host, port;
bool auth = this->data[PROXY_USE_AUTHENTICATION] == "true";
string username = this->data[PROXY_AUTH_USER];
string password = this->data[PROXY_AUTH_PASSWORD];
bool same_proxy = this->data[PROXY_SAME_FOR_ALL] == "true";
// If socks is set use it (except when same_proxy is set)
if (!same_proxy) {
type = "socks";
host = this->data[PROXY_SOCKS_HOST];
port = this->data[PROXY_SOCKS_PORT];
}
if (host == "" || get_port(port) == 0) {
// Get the per-scheme proxy settings
if (dest.get_scheme() == "http") {
type = "http";
host = this->data[PROXY_HTTP_HOST];
port = this->data[PROXY_HTTP_PORT];
}
else if (dest.get_scheme() == "https") {
// It is expected that the configured server is an
// HTTP server that support CONNECT method.
type = "http";
host = this->data[PROXY_SECURE_HOST];
port = this->data[PROXY_SECURE_PORT];
}
else if (dest.get_scheme() == "ftp") {
// It is expected that the configured server is an
// HTTP server that handles proxying FTP URLs
// (e.g. request with header "Host: ftp://ftp.host.org")
type = "http";
host = this->data[PROXY_FTP_HOST];
port = this->data[PROXY_FTP_PORT];
}
// If no proxy is set and we have the same_proxy option
// enabled try socks at the end only.
if (same_proxy && (host == "" || get_port(port) == 0)) {
type = "socks";
host = this->data[PROXY_SOCKS_HOST];
port = this->data[PROXY_SOCKS_PORT];
}
}
// If host and port were found, build config url
if (host != "" && get_port(port) != 0) {
string tmp = type + "://";
if (auth)
tmp += username + ":" + password + "@";
tmp += host + ":" + port;
return url(tmp);
}
}
// Mode is direct://
return url("direct://");
}
string get_ignore(url) {
return this->data[PROXY_IGNORE_HOSTS];
}
bool set_creds(url /*proxy*/, string username, string password) {
string auth = PROXY_USE_AUTHENTICATION "\ttrue\n";
string user = string(PROXY_AUTH_USER "\t") + username + "\n";
string pass = string(PROXY_AUTH_PASSWORD "\t") + password + "\n";
return (fwrite(auth.c_str(), 1, auth.size(), this->write) == auth.size() &&
fwrite(user.c_str(), 1, user.size(), this->write) == user.size() &&
fwrite(pass.c_str(), 1, pass.size(), this->write) == pass.size());
}
private:
FILE* read;
FILE* write;
pid_t pid;
map<string, string> data;
bool read_data(int num=-1) {
if (num == 0) return true;
if (!this->read) return false; // We need the pipe to be open
for (char l[BUFFERSIZE] ; num != 0 && fgets(l, BUFFERSIZE, this->read) != NULL ; ) {
string line = l;
line = line.substr(0, line.rfind('\n'));
string key = line.substr(0, line.find("\t"));
string val = line.substr(line.find("\t")+1);
this->data[key] = val;
if (num > 0) num--;
}
return (num <= 0);
}
};
static base_extension** gnome_config_extension_init() {
base_extension** retval = new base_extension*[2];
retval[1] = NULL;
try {
retval[0] = new gnome_config_extension();
return retval;
}
catch (runtime_error) {
delete retval;
return NULL;
}
}
MM_MODULE_INIT(gnome_config_extension, gnome_config_extension_init);
MM_MODULE_TEST_EZ(gnome_config_extension,
(
getenv("GNOME_DESKTOP_SESSION_ID") ||
(getenv("DESKTOP_SESSION") && string(getenv("DESKTOP_SESSION")) == "gnome")
)
);
<|endoftext|> |
<commit_before>/*
Stepper.cpp - - Stepper library for Wiring/Arduino - Version 0.4
Original library (0.1) by Tom Igoe.
Two-wire modifications (0.2) by Sebastian Gassner
Combination version (0.3) by Tom Igoe and David Mellis
Bug fix for four-wire (0.4) by Tom Igoe, bug fix from Noah Shibley
Drives a unipolar or bipolar stepper motor using 2 wires or 4 wires
When wiring multiple stepper motors to a microcontroller,
you quickly run out of output pins, with each motor requiring 4 connections.
By making use of the fact that at any time two of the four motor
coils are the inverse of the other two, the number of
control connections can be reduced from 4 to 2.
A slightly modified circuit around a Darlington transistor array or an L293 H-bridge
connects to only 2 microcontroler pins, inverts the signals received,
and delivers the 4 (2 plus 2 inverted ones) output signals required
for driving a stepper motor.
The sequence of control signals for 4 control wires is as follows:
Step C0 C1 C2 C3
1 1 0 1 0
2 0 1 1 0
3 0 1 0 1
4 1 0 0 1
The sequence of controls signals for 2 control wires is as follows
(columns C1 and C2 from above):
Step C0 C1
1 0 1
2 1 1
3 1 0
4 0 0
The circuits can be found at
http://www.arduino.cc/en/Tutorial/Stepper
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "Arduino.h"
#include "Stepper.h"
/*
* two-wire constructor.
* Sets which wires should control the motor.
*/
Stepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2)
{
this->step_number = 0; // which step the motor is on
this->speed = 0; // the motor speed, in revolutions per minute
this->direction = 0; // motor direction
this->last_step_time = 0; // time stamp in ms of the last step taken
this->number_of_steps = number_of_steps; // total number of steps for this motor
// Arduino pins for the motor control connection:
this->motor_pin_1 = motor_pin_1;
this->motor_pin_2 = motor_pin_2;
// setup the pins on the microcontroller:
pinMode(this->motor_pin_1, OUTPUT);
pinMode(this->motor_pin_2, OUTPUT);
// When there are only 2 pins, set the other two to 0:
this->motor_pin_3 = 0;
this->motor_pin_4 = 0;
// pin_count is used by the stepMotor() method:
this->pin_count = 2;
}
/*
* constructor for four-pin version
* Sets which wires should control the motor.
*/
Stepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2, int motor_pin_3, int motor_pin_4)
{
this->step_number = 0; // which step the motor is on
this->speed = 0; // the motor speed, in revolutions per minute
this->direction = 0; // motor direction
this->last_step_time = 0; // time stamp in ms of the last step taken
this->number_of_steps = number_of_steps; // total number of steps for this motor
// Arduino pins for the motor control connection:
this->motor_pin_1 = motor_pin_1;
this->motor_pin_2 = motor_pin_2;
this->motor_pin_3 = motor_pin_3;
this->motor_pin_4 = motor_pin_4;
// setup the pins on the microcontroller:
pinMode(this->motor_pin_1, OUTPUT);
pinMode(this->motor_pin_2, OUTPUT);
pinMode(this->motor_pin_3, OUTPUT);
pinMode(this->motor_pin_4, OUTPUT);
// pin_count is used by the stepMotor() method:
this->pin_count = 4;
}
/*
Sets the speed in revs per minute
*/
void Stepper::setSpeed(long whatSpeed)
{
this->step_delay = 60L * 1000L / this->number_of_steps / whatSpeed;
}
/*
Moves the motor steps_to_move steps. If the number is negative,
the motor moves in the reverse direction.
*/
void Stepper::step(int steps_to_move)
{
int steps_left = abs(steps_to_move); // how many steps to take
// determine direction based on whether steps_to_mode is + or -:
if (steps_to_move > 0) {this->direction = 1;}
if (steps_to_move < 0) {this->direction = 0;}
// decrement the number of steps, moving one step each time:
while(steps_left > 0) {
// move only if the appropriate delay has passed:
if (millis() - this->last_step_time >= this->step_delay) {
// get the timeStamp of when you stepped:
this->last_step_time = millis();
// increment or decrement the step number,
// depending on direction:
if (this->direction == 1) {
this->step_number++;
if (this->step_number == this->number_of_steps) {
this->step_number = 0;
}
}
else {
if (this->step_number == 0) {
this->step_number = this->number_of_steps;
}
this->step_number--;
}
// decrement the steps left:
steps_left--;
// step the motor to step number 0, 1, 2, or 3:
stepMotor(this->step_number % 4);
}
}
}
/*
* Moves the motor forward or backwards.
*/
void Stepper::stepMotor(int thisStep)
{
if (this->pin_count == 2) {
switch (thisStep) {
case 0: /* 01 */
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, HIGH);
break;
case 1: /* 11 */
digitalWrite(motor_pin_1, HIGH);
digitalWrite(motor_pin_2, HIGH);
break;
case 2: /* 10 */
digitalWrite(motor_pin_1, HIGH);
digitalWrite(motor_pin_2, LOW);
break;
case 3: /* 00 */
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, LOW);
break;
}
}
if (this->pin_count == 4) {
switch (thisStep) {
case 0: // 1010
digitalWrite(motor_pin_1, HIGH);
digitalWrite(motor_pin_2, LOW);
digitalWrite(motor_pin_3, HIGH);
digitalWrite(motor_pin_4, LOW);
break;
case 1: // 0110
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, HIGH);
digitalWrite(motor_pin_3, HIGH);
digitalWrite(motor_pin_4, LOW);
break;
case 2: //0101
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, HIGH);
digitalWrite(motor_pin_3, LOW);
digitalWrite(motor_pin_4, HIGH);
break;
case 3: //1001
digitalWrite(motor_pin_1, HIGH);
digitalWrite(motor_pin_2, LOW);
digitalWrite(motor_pin_3, LOW);
digitalWrite(motor_pin_4, HIGH);
break;
}
}
}
/*
version() returns the version of the library:
*/
int Stepper::version(void)
{
return 4;
}
<commit_msg>Update stepper library: High-speed stepping mod and timer rollover fix<commit_after>/*
Stepper.cpp - - Stepper library for Wiring/Arduino - Version 0.4
Original library (0.1) by Tom Igoe.
Two-wire modifications (0.2) by Sebastian Gassner
Combination version (0.3) by Tom Igoe and David Mellis
Bug fix for four-wire (0.4) by Tom Igoe, bug fix from Noah Shibley
High-speed stepping mod and timer rollover fix (0.5) by Eugene Kozlenko
Drives a unipolar or bipolar stepper motor using 2 wires or 4 wires
When wiring multiple stepper motors to a microcontroller,
you quickly run out of output pins, with each motor requiring 4 connections.
By making use of the fact that at any time two of the four motor
coils are the inverse of the other two, the number of
control connections can be reduced from 4 to 2.
A slightly modified circuit around a Darlington transistor array or an L293 H-bridge
connects to only 2 microcontroler pins, inverts the signals received,
and delivers the 4 (2 plus 2 inverted ones) output signals required
for driving a stepper motor. Similarly the Arduino motor shields 2 direction pins
may be used.
The sequence of control signals for 4 control wires is as follows:
Step C0 C1 C2 C3
1 1 0 1 0
2 0 1 1 0
3 0 1 0 1
4 1 0 0 1
The sequence of controls signals for 2 control wires is as follows
(columns C1 and C2 from above):
Step C0 C1
1 0 1
2 1 1
3 1 0
4 0 0
The circuits can be found at
http://www.arduino.cc/en/Tutorial/Stepper
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "Arduino.h"
#include "Stepper.h"
/*
* two-wire constructor.
* Sets which wires should control the motor.
*/
Stepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2)
{
this->step_number = 0; // which step the motor is on
this->speed = 0; // the motor speed, in revolutions per minute
this->direction = 0; // motor direction
this->last_step_time = 0; // time stamp in us of the last step taken
this->number_of_steps = number_of_steps; // total number of steps for this motor
// Arduino pins for the motor control connection:
this->motor_pin_1 = motor_pin_1;
this->motor_pin_2 = motor_pin_2;
// setup the pins on the microcontroller:
pinMode(this->motor_pin_1, OUTPUT);
pinMode(this->motor_pin_2, OUTPUT);
// When there are only 2 pins, set the other two to 0:
this->motor_pin_3 = 0;
this->motor_pin_4 = 0;
// pin_count is used by the stepMotor() method:
this->pin_count = 2;
}
/*
* constructor for four-pin version
* Sets which wires should control the motor.
*/
Stepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2, int motor_pin_3, int motor_pin_4)
{
this->step_number = 0; // which step the motor is on
this->speed = 0; // the motor speed, in revolutions per minute
this->direction = 0; // motor direction
this->last_step_time = 0; // time stamp in us of the last step taken
this->number_of_steps = number_of_steps; // total number of steps for this motor
// Arduino pins for the motor control connection:
this->motor_pin_1 = motor_pin_1;
this->motor_pin_2 = motor_pin_2;
this->motor_pin_3 = motor_pin_3;
this->motor_pin_4 = motor_pin_4;
// setup the pins on the microcontroller:
pinMode(this->motor_pin_1, OUTPUT);
pinMode(this->motor_pin_2, OUTPUT);
pinMode(this->motor_pin_3, OUTPUT);
pinMode(this->motor_pin_4, OUTPUT);
// pin_count is used by the stepMotor() method:
this->pin_count = 4;
}
/*
Sets the speed in revs per minute
*/
void Stepper::setSpeed(long whatSpeed)
{
this->step_delay = 60L * 1000L * 1000L / this->number_of_steps / whatSpeed;
}
/*
Moves the motor steps_to_move steps. If the number is negative,
the motor moves in the reverse direction.
*/
void Stepper::step(int steps_to_move)
{
int steps_left = abs(steps_to_move); // how many steps to take
// determine direction based on whether steps_to_mode is + or -:
if (steps_to_move > 0) {this->direction = 1;}
if (steps_to_move < 0) {this->direction = 0;}
// decrement the number of steps, moving one step each time:
while(steps_left > 0) {
// move only if the appropriate delay has passed:
if (micros() - this->last_step_time >= this->step_delay || micros() - this->last_step_time < 0) {
// get the timeStamp of when you stepped:
this->last_step_time = micros();
// increment or decrement the step number,
// depending on direction:
if (this->direction == 1) {
this->step_number++;
if (this->step_number == this->number_of_steps) {
this->step_number = 0;
}
}
else {
if (this->step_number == 0) {
this->step_number = this->number_of_steps;
}
this->step_number--;
}
// decrement the steps left:
steps_left--;
// step the motor to step number 0, 1, 2, or 3:
stepMotor(this->step_number % 4);
}
}
}
/*
* Moves the motor forward or backwards.
*/
void Stepper::stepMotor(int thisStep)
{
if (this->pin_count == 2) {
switch (thisStep) {
case 0: /* 01 */
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, HIGH);
break;
case 1: /* 11 */
digitalWrite(motor_pin_1, HIGH);
digitalWrite(motor_pin_2, HIGH);
break;
case 2: /* 10 */
digitalWrite(motor_pin_1, HIGH);
digitalWrite(motor_pin_2, LOW);
break;
case 3: /* 00 */
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, LOW);
break;
}
}
if (this->pin_count == 4) {
switch (thisStep) {
case 0: // 1010
digitalWrite(motor_pin_1, HIGH);
digitalWrite(motor_pin_2, LOW);
digitalWrite(motor_pin_3, HIGH);
digitalWrite(motor_pin_4, LOW);
break;
case 1: // 0110
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, HIGH);
digitalWrite(motor_pin_3, HIGH);
digitalWrite(motor_pin_4, LOW);
break;
case 2: //0101
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, HIGH);
digitalWrite(motor_pin_3, LOW);
digitalWrite(motor_pin_4, HIGH);
break;
case 3: //1001
digitalWrite(motor_pin_1, HIGH);
digitalWrite(motor_pin_2, LOW);
digitalWrite(motor_pin_3, LOW);
digitalWrite(motor_pin_4, HIGH);
break;
}
}
}
/*
version() returns the version of the library:
*/
int Stepper::version(void)
{
return 5;
}
<|endoftext|> |
<commit_before>/* mbed Microcontroller Library
* Copyright (c) 2017-2019 ARM Limited
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include "FlashIAP.h"
#include "platform/mbed_assert.h"
#include "platform/ScopedRamExecutionLock.h"
#include "platform/ScopedRomWriteLock.h"
#if DEVICE_FLASH
namespace mbed {
const unsigned int num_write_retries = 16;
SingletonPtr<PlatformMutex> FlashIAP::_mutex;
static inline bool is_aligned(uint32_t number, uint32_t alignment)
{
if ((number % alignment) != 0) {
return false;
} else {
return true;
}
}
int FlashIAP::init()
{
int ret = 0;
_mutex->lock();
{
ScopedRamExecutionLock make_ram_executable;
ScopedRomWriteLock make_rom_writable;
if (flash_init(&_flash)) {
ret = -1;
}
}
uint32_t page_size = get_page_size();
_page_buf = new uint8_t[page_size];
_mutex->unlock();
return ret;
}
int FlashIAP::deinit()
{
int ret = 0;
_mutex->lock();
{
ScopedRamExecutionLock make_ram_executable;
ScopedRomWriteLock make_rom_writable;
if (flash_free(&_flash)) {
ret = -1;
}
}
delete[] _page_buf;
_mutex->unlock();
return ret;
}
int FlashIAP::read(void *buffer, uint32_t addr, uint32_t size)
{
int32_t ret = -1;
_mutex->lock();
{
ScopedRamExecutionLock make_ram_executable;
ScopedRomWriteLock make_rom_writable;
ret = flash_read(&_flash, addr, (uint8_t *) buffer, size);
}
_mutex->unlock();
return ret;
}
int FlashIAP::program(const void *buffer, uint32_t addr, uint32_t size)
{
uint32_t page_size = get_page_size();
uint32_t flash_size = flash_get_size(&_flash);
uint32_t flash_start_addr = flash_get_start_address(&_flash);
uint8_t flash_erase_value = flash_get_erase_value(&_flash);
uint32_t chunk, prog_size;
const uint8_t *buf = (uint8_t *) buffer;
const uint8_t *prog_buf;
// addr should be aligned to page size
if (!is_aligned(addr, page_size) || (!buffer) ||
((addr + size) > (flash_start_addr + flash_size))) {
return -1;
}
int ret = 0;
_mutex->lock();
while (size && !ret) {
uint32_t current_sector_size = flash_get_sector_size(&_flash, addr);
bool unaligned_src = (((size_t) buf / sizeof(uint32_t) * sizeof(uint32_t)) != (size_t) buf);
chunk = std::min(current_sector_size - (addr % current_sector_size), size);
// Need to use the internal page buffer in any of these two cases:
// 1. Size is not page aligned
// 2. Source buffer is not aligned to uint32_t. This is not supported by many targets (although
// the pointer they accept is of uint8_t).
if (unaligned_src || (chunk < page_size)) {
chunk = std::min(chunk, page_size);
memcpy(_page_buf, buf, chunk);
if (chunk < page_size) {
memset(_page_buf + chunk, flash_erase_value, page_size - chunk);
}
prog_buf = _page_buf;
prog_size = page_size;
} else {
chunk = chunk / page_size * page_size;
prog_buf = buf;
prog_size = chunk;
}
{
// Few boards may fail the write actions due to HW limitations (like critical drivers that
// disable flash operations). Just retry a few times until success.
for (unsigned int retry = 0; retry < num_write_retries; retry++) {
ScopedRamExecutionLock make_ram_executable;
ScopedRomWriteLock make_rom_writable;
ret = flash_program_page(&_flash, addr, prog_buf, prog_size);
if (ret) {
ret = -1;
} else {
break;
}
}
}
size -= chunk;
addr += chunk;
buf += chunk;
}
_mutex->unlock();
return ret;
}
bool FlashIAP::is_aligned_to_sector(uint32_t addr, uint32_t size)
{
uint32_t current_sector_size = flash_get_sector_size(&_flash, addr);
if (!is_aligned(size, current_sector_size) ||
!is_aligned(addr, current_sector_size)) {
return false;
} else {
return true;
}
}
int FlashIAP::erase(uint32_t addr, uint32_t size)
{
uint32_t current_sector_size;
uint32_t flash_size = flash_get_size(&_flash);
uint32_t flash_start_addr = flash_get_start_address(&_flash);
uint32_t flash_end_addr = flash_start_addr + flash_size;
uint32_t erase_end_addr = addr + size;
if (erase_end_addr > flash_end_addr) {
return -1;
} else if (erase_end_addr < flash_end_addr) {
uint32_t following_sector_size = flash_get_sector_size(&_flash, erase_end_addr);
if (!is_aligned(erase_end_addr, following_sector_size)) {
return -1;
}
}
int32_t ret = 0;
_mutex->lock();
while (size && !ret) {
// Few boards may fail the erase actions due to HW limitations (like critical drivers that
// disable flash operations). Just retry a few times until success.
for (unsigned int retry = 0; retry < num_write_retries; retry++) {
ScopedRamExecutionLock make_ram_executable;
ScopedRomWriteLock make_rom_writable;
ret = flash_erase_sector(&_flash, addr);
if (ret) {
ret = -1;
} else {
break;
}
}
current_sector_size = flash_get_sector_size(&_flash, addr);
size -= current_sector_size;
addr += current_sector_size;
}
_mutex->unlock();
return ret;
}
uint32_t FlashIAP::get_page_size() const
{
return flash_get_page_size(&_flash);
}
uint32_t FlashIAP::get_sector_size(uint32_t addr) const
{
return flash_get_sector_size(&_flash, addr);
}
uint32_t FlashIAP::get_flash_start() const
{
return flash_get_start_address(&_flash);
}
uint32_t FlashIAP::get_flash_size() const
{
return flash_get_size(&_flash);
}
uint8_t FlashIAP::get_erase_value() const
{
return flash_get_erase_value(&_flash);
}
}
#endif
<commit_msg>Add check so that FlashIAP does not allocate memory on flash_init failure.<commit_after>/* mbed Microcontroller Library
* Copyright (c) 2017-2019 ARM Limited
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include "FlashIAP.h"
#include "platform/mbed_assert.h"
#include "platform/ScopedRamExecutionLock.h"
#include "platform/ScopedRomWriteLock.h"
#if DEVICE_FLASH
namespace mbed {
const unsigned int num_write_retries = 16;
SingletonPtr<PlatformMutex> FlashIAP::_mutex;
static inline bool is_aligned(uint32_t number, uint32_t alignment)
{
if ((number % alignment) != 0) {
return false;
} else {
return true;
}
}
int FlashIAP::init()
{
int ret = 0;
_mutex->lock();
{
ScopedRamExecutionLock make_ram_executable;
ScopedRomWriteLock make_rom_writable;
if (flash_init(&_flash)) {
ret = -1;
}
}
// Do not allocate if flash_init failed
if (ret == 0) {
uint32_t page_size = get_page_size();
_page_buf = new uint8_t[page_size];
}
_mutex->unlock();
return ret;
}
int FlashIAP::deinit()
{
int ret = 0;
_mutex->lock();
{
ScopedRamExecutionLock make_ram_executable;
ScopedRomWriteLock make_rom_writable;
if (flash_free(&_flash)) {
ret = -1;
}
}
delete[] _page_buf;
_mutex->unlock();
return ret;
}
int FlashIAP::read(void *buffer, uint32_t addr, uint32_t size)
{
int32_t ret = -1;
_mutex->lock();
{
ScopedRamExecutionLock make_ram_executable;
ScopedRomWriteLock make_rom_writable;
ret = flash_read(&_flash, addr, (uint8_t *) buffer, size);
}
_mutex->unlock();
return ret;
}
int FlashIAP::program(const void *buffer, uint32_t addr, uint32_t size)
{
uint32_t page_size = get_page_size();
uint32_t flash_size = flash_get_size(&_flash);
uint32_t flash_start_addr = flash_get_start_address(&_flash);
uint8_t flash_erase_value = flash_get_erase_value(&_flash);
uint32_t chunk, prog_size;
const uint8_t *buf = (uint8_t *) buffer;
const uint8_t *prog_buf;
// addr should be aligned to page size
if (!is_aligned(addr, page_size) || (!buffer) ||
((addr + size) > (flash_start_addr + flash_size))) {
return -1;
}
int ret = 0;
_mutex->lock();
while (size && !ret) {
uint32_t current_sector_size = flash_get_sector_size(&_flash, addr);
bool unaligned_src = (((size_t) buf / sizeof(uint32_t) * sizeof(uint32_t)) != (size_t) buf);
chunk = std::min(current_sector_size - (addr % current_sector_size), size);
// Need to use the internal page buffer in any of these two cases:
// 1. Size is not page aligned
// 2. Source buffer is not aligned to uint32_t. This is not supported by many targets (although
// the pointer they accept is of uint8_t).
if (unaligned_src || (chunk < page_size)) {
chunk = std::min(chunk, page_size);
memcpy(_page_buf, buf, chunk);
if (chunk < page_size) {
memset(_page_buf + chunk, flash_erase_value, page_size - chunk);
}
prog_buf = _page_buf;
prog_size = page_size;
} else {
chunk = chunk / page_size * page_size;
prog_buf = buf;
prog_size = chunk;
}
{
// Few boards may fail the write actions due to HW limitations (like critical drivers that
// disable flash operations). Just retry a few times until success.
for (unsigned int retry = 0; retry < num_write_retries; retry++) {
ScopedRamExecutionLock make_ram_executable;
ScopedRomWriteLock make_rom_writable;
ret = flash_program_page(&_flash, addr, prog_buf, prog_size);
if (ret) {
ret = -1;
} else {
break;
}
}
}
size -= chunk;
addr += chunk;
buf += chunk;
}
_mutex->unlock();
return ret;
}
bool FlashIAP::is_aligned_to_sector(uint32_t addr, uint32_t size)
{
uint32_t current_sector_size = flash_get_sector_size(&_flash, addr);
if (!is_aligned(size, current_sector_size) ||
!is_aligned(addr, current_sector_size)) {
return false;
} else {
return true;
}
}
int FlashIAP::erase(uint32_t addr, uint32_t size)
{
uint32_t current_sector_size;
uint32_t flash_size = flash_get_size(&_flash);
uint32_t flash_start_addr = flash_get_start_address(&_flash);
uint32_t flash_end_addr = flash_start_addr + flash_size;
uint32_t erase_end_addr = addr + size;
if (erase_end_addr > flash_end_addr) {
return -1;
} else if (erase_end_addr < flash_end_addr) {
uint32_t following_sector_size = flash_get_sector_size(&_flash, erase_end_addr);
if (!is_aligned(erase_end_addr, following_sector_size)) {
return -1;
}
}
int32_t ret = 0;
_mutex->lock();
while (size && !ret) {
// Few boards may fail the erase actions due to HW limitations (like critical drivers that
// disable flash operations). Just retry a few times until success.
for (unsigned int retry = 0; retry < num_write_retries; retry++) {
ScopedRamExecutionLock make_ram_executable;
ScopedRomWriteLock make_rom_writable;
ret = flash_erase_sector(&_flash, addr);
if (ret) {
ret = -1;
} else {
break;
}
}
current_sector_size = flash_get_sector_size(&_flash, addr);
size -= current_sector_size;
addr += current_sector_size;
}
_mutex->unlock();
return ret;
}
uint32_t FlashIAP::get_page_size() const
{
return flash_get_page_size(&_flash);
}
uint32_t FlashIAP::get_sector_size(uint32_t addr) const
{
return flash_get_sector_size(&_flash, addr);
}
uint32_t FlashIAP::get_flash_start() const
{
return flash_get_start_address(&_flash);
}
uint32_t FlashIAP::get_flash_size() const
{
return flash_get_size(&_flash);
}
uint8_t FlashIAP::get_erase_value() const
{
return flash_get_erase_value(&_flash);
}
}
#endif
<|endoftext|> |
<commit_before>#include "videoframe_i420.h"
#include <cstring>
namespace gg
{
VideoFrame_I420::VideoFrame_I420(bool manage_data)
: VideoFrame(manage_data)
{
}
VideoFrame_I420::VideoFrame_I420(const size_t cols, const size_t rows)
: gg::VideoFrame(true)
{
cv::Mat buffer = cv::Mat::zeros(rows, cols, CV_8UC4);
cv::cvtColor(buffer, buffer, CV_BGRA2YUV_I420);
init_from_pointer(buffer.data, buffer.total(), cols, rows);
}
VideoFrame_I420::VideoFrame_I420(unsigned char * data, const size_t length,
const size_t cols, const size_t rows,
bool manage_data)
: VideoFrame(manage_data)
{
init_from_pointer(data, length, cols, rows);
}
void VideoFrame_I420::operator =(const VideoFrame_I420 & rhs)
{
_manage_data = true;
init_from_pointer(rhs._data, rhs._data_length,
rhs._cols, rhs._rows);
}
void VideoFrame_I420::init_from_pointer(
unsigned char * data, size_t length,
size_t cols, size_t rows)
{
// TODO - check length vs rows and cols?
_data_length = length;
_cols = cols;
_rows = rows;
if (_manage_data)
{
_data = new unsigned char[_data_length];
memcpy(_data, data, _data_length);
}
else
_data = data;
}
}
<commit_msg>Issue #48: selectively allocating, reallocating data buffer in VideoFrame_I420 to avoid excess memory usage and/or memory leak<commit_after>#include "videoframe_i420.h"
#include <cstring>
namespace gg
{
VideoFrame_I420::VideoFrame_I420(bool manage_data)
: VideoFrame(manage_data)
{
}
VideoFrame_I420::VideoFrame_I420(const size_t cols, const size_t rows)
: gg::VideoFrame(true)
{
cv::Mat buffer = cv::Mat::zeros(rows, cols, CV_8UC4);
cv::cvtColor(buffer, buffer, CV_BGRA2YUV_I420);
init_from_pointer(buffer.data, buffer.total(), cols, rows);
}
VideoFrame_I420::VideoFrame_I420(unsigned char * data, const size_t length,
const size_t cols, const size_t rows,
bool manage_data)
: VideoFrame(manage_data)
{
init_from_pointer(data, length, cols, rows);
}
void VideoFrame_I420::operator =(const VideoFrame_I420 & rhs)
{
_manage_data = true;
init_from_pointer(rhs._data, rhs._data_length,
rhs._cols, rhs._rows);
}
void VideoFrame_I420::init_from_pointer(
unsigned char * data, size_t length,
size_t cols, size_t rows)
{
if (_manage_data and not _data)
_data = new unsigned char[length];
else if (_manage_data and _data_length < length)
realloc(_data, length);
// TODO - check length vs rows and cols?
_data_length = length;
_cols = cols;
_rows = rows;
if (_manage_data)
memcpy(_data, data, _data_length);
else
_data = data;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2008-2016 the MRtrix3 contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*
* MRtrix 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.
*
* For more details, see www.mrtrix.org
*
*/
#include <unsupported/Eigen/MatrixFunctions>
#include <algorithm>
#include "command.h"
#include "math/math.h"
#include "math/average_space.h"
#include "image.h"
#include "file/nifti_utils.h"
#include "transform.h"
#include "file/key_value.h"
using namespace MR;
using namespace App;
const char* operations[] = {
"invert",
"half",
"rigid",
"header",
"average",
"interpolate",
"decompose",
NULL
};
void usage ()
{
AUTHOR = "Max Pietsch ([email protected])";
DESCRIPTION
+ "This command's function is to process linear transformation matrices."
+ "It allows to perform affine matrix operations or to convert the transformation matrix provided by FSL's flirt command to a format usable in MRtrix"
;
ARGUMENTS
+ Argument ("input", "the input for the specified operation").allow_multiple()
+ Argument ("operation", "the operation to perform, one of: " + join(operations, ", ") + "."
+ "\n\ninvert: invert the input transformation:\nmatrix_in invert output"
+ "\n\nhalf: calculate the matrix square root of the input transformation:\nmatrix_in half output"
+ "\n\nrigid: calculate the rigid transformation of the affine input transformation:\nmatrix_in rigid output"
+ "\n\nheader: calculate the transformation matrix from an original image and an image with modified header:\nmov mapmovhdr header output"
+ "\n\naverage: calculate the average affine matrix of all input matrices:\ninput ... average output"
+ "\n\ninterpolate: create interpolated transformation matrix between input (t=0) and input2 (t=1). "
"Based on matrix decomposition with linear interpolation of "
" translation, rotation and stretch described in "
" Shoemake, K., Hill, M., & Duff, T. (1992). Matrix Animation and Polar Decomposition. "
" Matrix, 92, 258-264. doi:10.1.1.56.1336"
"\ninput input2 interpolate output"
+ "\n\ndecompose: decompose transformation matrix M into translation, rotation and stretch and shear (M = T * R * S). "
"The output is a key-value text file "
"scaling: vector of 3 scaling factors in x, y, z direction, "
"shear: list of shear factors for xy, xz, yz axes, "
"angles: list of Euler angles about static x, y, z axes in radians in the range [0:pi]x[-pi:pi]x[-pi:pi], "
"angle_axis: angle in radians and rotation axis, "
"translation : translation vector along x, y, z axes in mm, "
"R: composed roation matrix (R = rot_x * rot_y * rot_z), "
"S: composed scaling and shear matrix."
"\nmatrix_in decompose output"
).type_choice (operations)
+ Argument ("output", "the output transformation matrix.").type_file_out ();
}
template <typename T> int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
void run ()
{
const size_t num_inputs = argument.size() - 2;
const int op = argument[num_inputs];
const std::string& output_path = argument.back();
switch (op) {
case 0: { // invert
if (num_inputs != 1)
throw Exception ("invert requires 1 input");
transform_type input = load_transform<default_type> (argument[0]);
save_transform (input.inverse(), output_path);
break;
}
case 1: { // half
if (num_inputs != 1)
throw Exception ("half requires 1 input");
Eigen::Transform<default_type, 3, Eigen::Projective> input = load_transform<default_type> (argument[0]);
transform_type output;
Eigen::Matrix<default_type, 4, 4> half = input.matrix().sqrt();
output.matrix() = half.topLeftCorner(3,4);
save_transform (output, output_path);
break;
}
case 2: { // rigid
if (num_inputs != 1)
throw Exception ("rigid requires 1 input");
transform_type input = load_transform<default_type> (argument[0]);
transform_type output (input);
output.linear() = input.rotation();
save_transform (output, output_path);
break;
}
case 3: { // header
if (num_inputs != 2)
throw Exception ("header requires 2 inputs");
auto orig_header = Header::open (argument[0]);
auto modified_header = Header::open (argument[1]);
transform_type forward_transform = Transform(modified_header).voxel2scanner * Transform(orig_header).voxel2scanner.inverse();
save_transform (forward_transform.inverse(), output_path);
break;
}
case 4: { // average
if (num_inputs < 2)
throw Exception ("average requires at least 2 inputs");
transform_type transform_out;
Eigen::Transform<default_type, 3, Eigen::Projective> Tin;
Eigen::MatrixXd Min;
std::vector<Eigen::MatrixXd> matrices;
for (size_t i = 0; i < num_inputs; i++) {
DEBUG(str(argument[i]));
Tin = load_transform<default_type> (argument[i]);
matrices.push_back(Tin.matrix());
}
Eigen::MatrixXd average_matrix;
Math::matrix_average ( matrices, average_matrix);
transform_out.matrix() = average_matrix.topLeftCorner(3,4);
save_transform (transform_out, output_path);
break;
}
case 5: { // interpolate
if (num_inputs != 3)
throw Exception ("interpolation requires 3 inputs");
transform_type transform1 = load_transform<default_type> (argument[0]);
transform_type transform2 = load_transform<default_type> (argument[1]);
default_type t = parse_floats(argument[2])[0];
transform_type transform_out;
if (t < 0.0 || t > 1.0)
throw Exception ("t has to be in the interval [0,1]");
Eigen::MatrixXd M1 = transform1.linear();
Eigen::MatrixXd M2 = transform2.linear();
if (sgn(M1.determinant()) != sgn(M2.determinant()))
WARN("transformation determinants have different signs");
Eigen::Matrix3d R1 = transform1.rotation();
Eigen::Matrix3d R2 = transform2.rotation();
Eigen::Quaterniond Q1(R1);
Eigen::Quaterniond Q2(R2);
Eigen::Quaterniond Qout;
// stretch (shear becomes roation and stretch)
Eigen::MatrixXd S1 = R1.transpose() * M1;
Eigen::MatrixXd S2 = R2.transpose() * M2;
if (!M1.isApprox(R1*S1))
WARN ("M1 matrix decomposition might have failed");
if (!M2.isApprox(R2*S2))
WARN ("M2 matrix decomposition might have failed");
transform_out.translation() = ((1.0 - t) * transform1.translation() + t * transform2.translation());
Qout = Q1.slerp(t, Q2);
transform_out.linear() = Qout * ((1 - t) * S1 + t * S2);
INFO("\n"+str(transform_out.matrix().format(
Eigen::IOFormat(Eigen::FullPrecision, 0, ", ", ",\n", "[", "]", "[", "]"))));
save_transform (transform_out, output_path);
break;
}
case 6: { // decompose
if (num_inputs != 1)
throw Exception ("decomposition requires 1 input");
transform_type transform = load_transform<default_type> (argument[0]);
Eigen::MatrixXd M = transform.linear();
Eigen::Matrix3d R = transform.rotation();
Eigen::MatrixXd S = R.transpose() * M;
if (!M.isApprox(R*S))
WARN ("matrix decomposition might have failed");
Eigen::Vector3d euler_angles = R.eulerAngles(0, 1, 2);
assert (R.isApprox((Eigen::AngleAxisd(euler_angles[0], Eigen::Vector3d::UnitX())
* Eigen::AngleAxisd(euler_angles[1], Eigen::Vector3d::UnitY())
* Eigen::AngleAxisd(euler_angles[2], Eigen::Vector3d::UnitZ())).matrix()));
Eigen::RowVector4d angle_axis;
{
auto AA = Eigen::AngleAxis<default_type> (R);
angle_axis(0) = AA.angle();
angle_axis.block<1,3>(0,1) = AA.axis();
}
File::OFStream out (output_path);
Eigen::IOFormat fmt(Eigen::FullPrecision, Eigen::DontAlignCols, " ", "\n", "", "", "", "\n");
out << "scaling: " << Eigen::RowVector3d(S(0,0), S(1,1), S(2,2)).format(fmt);
out << "shear: " << Eigen::RowVector3d(S(0,1), S(0,2), S(1,2)).format(fmt);
out << "angles: " << euler_angles.transpose().format(fmt);
out << "angle_axis: " << angle_axis.format(fmt);
out << "translation: " << transform.translation().transpose().format(fmt);
out << "R: " << R.row(0).format(fmt);
out << "R: " << R.row(1).format(fmt);
out << "R: " << R.row(2).format(fmt);
out << "S: " << S.row(0).format(fmt);
out << "S: " << S.row(1).format(fmt);
out << "S: " << S.row(2).format(fmt);
break;
}
default: assert (0);
}
}
<commit_msg>transformcalc: Fix command description<commit_after>/*
* Copyright (c) 2008-2016 the MRtrix3 contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*
* MRtrix 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.
*
* For more details, see www.mrtrix.org
*
*/
#include <unsupported/Eigen/MatrixFunctions>
#include <algorithm>
#include "command.h"
#include "math/math.h"
#include "math/average_space.h"
#include "image.h"
#include "file/nifti_utils.h"
#include "transform.h"
#include "file/key_value.h"
using namespace MR;
using namespace App;
const char* operations[] = {
"invert",
"half",
"rigid",
"header",
"average",
"interpolate",
"decompose",
NULL
};
void usage ()
{
AUTHOR = "Max Pietsch ([email protected])";
DESCRIPTION
+ "This command's function is to perform calculations on linear transformation matrices.";
ARGUMENTS
+ Argument ("input", "the input for the specified operation").allow_multiple()
+ Argument ("operation", "the operation to perform, one of: " + join(operations, ", ") + "."
+ "\n\ninvert: invert the input transformation:\nmatrix_in invert output"
+ "\n\nhalf: calculate the matrix square root of the input transformation:\nmatrix_in half output"
+ "\n\nrigid: calculate the rigid transformation of the affine input transformation:\nmatrix_in rigid output"
+ "\n\nheader: calculate the transformation matrix from an original image and an image with modified header:\nmov mapmovhdr header output"
+ "\n\naverage: calculate the average affine matrix of all input matrices:\ninput ... average output"
+ "\n\ninterpolate: create interpolated transformation matrix between input (t=0) and input2 (t=1). "
"Based on matrix decomposition with linear interpolation of "
" translation, rotation and stretch described in "
" Shoemake, K., Hill, M., & Duff, T. (1992). Matrix Animation and Polar Decomposition. "
" Matrix, 92, 258-264. doi:10.1.1.56.1336"
"\ninput input2 interpolate output"
+ "\n\ndecompose: decompose transformation matrix M into translation, rotation and stretch and shear (M = T * R * S). "
"The output is a key-value text file "
"scaling: vector of 3 scaling factors in x, y, z direction, "
"shear: list of shear factors for xy, xz, yz axes, "
"angles: list of Euler angles about static x, y, z axes in radians in the range [0:pi]x[-pi:pi]x[-pi:pi], "
"angle_axis: angle in radians and rotation axis, "
"translation : translation vector along x, y, z axes in mm, "
"R: composed roation matrix (R = rot_x * rot_y * rot_z), "
"S: composed scaling and shear matrix."
"\nmatrix_in decompose output"
).type_choice (operations)
+ Argument ("output", "the output transformation matrix.").type_file_out ();
}
template <typename T> int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
void run ()
{
const size_t num_inputs = argument.size() - 2;
const int op = argument[num_inputs];
const std::string& output_path = argument.back();
switch (op) {
case 0: { // invert
if (num_inputs != 1)
throw Exception ("invert requires 1 input");
transform_type input = load_transform<default_type> (argument[0]);
save_transform (input.inverse(), output_path);
break;
}
case 1: { // half
if (num_inputs != 1)
throw Exception ("half requires 1 input");
Eigen::Transform<default_type, 3, Eigen::Projective> input = load_transform<default_type> (argument[0]);
transform_type output;
Eigen::Matrix<default_type, 4, 4> half = input.matrix().sqrt();
output.matrix() = half.topLeftCorner(3,4);
save_transform (output, output_path);
break;
}
case 2: { // rigid
if (num_inputs != 1)
throw Exception ("rigid requires 1 input");
transform_type input = load_transform<default_type> (argument[0]);
transform_type output (input);
output.linear() = input.rotation();
save_transform (output, output_path);
break;
}
case 3: { // header
if (num_inputs != 2)
throw Exception ("header requires 2 inputs");
auto orig_header = Header::open (argument[0]);
auto modified_header = Header::open (argument[1]);
transform_type forward_transform = Transform(modified_header).voxel2scanner * Transform(orig_header).voxel2scanner.inverse();
save_transform (forward_transform.inverse(), output_path);
break;
}
case 4: { // average
if (num_inputs < 2)
throw Exception ("average requires at least 2 inputs");
transform_type transform_out;
Eigen::Transform<default_type, 3, Eigen::Projective> Tin;
Eigen::MatrixXd Min;
std::vector<Eigen::MatrixXd> matrices;
for (size_t i = 0; i < num_inputs; i++) {
DEBUG(str(argument[i]));
Tin = load_transform<default_type> (argument[i]);
matrices.push_back(Tin.matrix());
}
Eigen::MatrixXd average_matrix;
Math::matrix_average ( matrices, average_matrix);
transform_out.matrix() = average_matrix.topLeftCorner(3,4);
save_transform (transform_out, output_path);
break;
}
case 5: { // interpolate
if (num_inputs != 3)
throw Exception ("interpolation requires 3 inputs");
transform_type transform1 = load_transform<default_type> (argument[0]);
transform_type transform2 = load_transform<default_type> (argument[1]);
default_type t = parse_floats(argument[2])[0];
transform_type transform_out;
if (t < 0.0 || t > 1.0)
throw Exception ("t has to be in the interval [0,1]");
Eigen::MatrixXd M1 = transform1.linear();
Eigen::MatrixXd M2 = transform2.linear();
if (sgn(M1.determinant()) != sgn(M2.determinant()))
WARN("transformation determinants have different signs");
Eigen::Matrix3d R1 = transform1.rotation();
Eigen::Matrix3d R2 = transform2.rotation();
Eigen::Quaterniond Q1(R1);
Eigen::Quaterniond Q2(R2);
Eigen::Quaterniond Qout;
// stretch (shear becomes roation and stretch)
Eigen::MatrixXd S1 = R1.transpose() * M1;
Eigen::MatrixXd S2 = R2.transpose() * M2;
if (!M1.isApprox(R1*S1))
WARN ("M1 matrix decomposition might have failed");
if (!M2.isApprox(R2*S2))
WARN ("M2 matrix decomposition might have failed");
transform_out.translation() = ((1.0 - t) * transform1.translation() + t * transform2.translation());
Qout = Q1.slerp(t, Q2);
transform_out.linear() = Qout * ((1 - t) * S1 + t * S2);
INFO("\n"+str(transform_out.matrix().format(
Eigen::IOFormat(Eigen::FullPrecision, 0, ", ", ",\n", "[", "]", "[", "]"))));
save_transform (transform_out, output_path);
break;
}
case 6: { // decompose
if (num_inputs != 1)
throw Exception ("decomposition requires 1 input");
transform_type transform = load_transform<default_type> (argument[0]);
Eigen::MatrixXd M = transform.linear();
Eigen::Matrix3d R = transform.rotation();
Eigen::MatrixXd S = R.transpose() * M;
if (!M.isApprox(R*S))
WARN ("matrix decomposition might have failed");
Eigen::Vector3d euler_angles = R.eulerAngles(0, 1, 2);
assert (R.isApprox((Eigen::AngleAxisd(euler_angles[0], Eigen::Vector3d::UnitX())
* Eigen::AngleAxisd(euler_angles[1], Eigen::Vector3d::UnitY())
* Eigen::AngleAxisd(euler_angles[2], Eigen::Vector3d::UnitZ())).matrix()));
Eigen::RowVector4d angle_axis;
{
auto AA = Eigen::AngleAxis<default_type> (R);
angle_axis(0) = AA.angle();
angle_axis.block<1,3>(0,1) = AA.axis();
}
File::OFStream out (output_path);
Eigen::IOFormat fmt(Eigen::FullPrecision, Eigen::DontAlignCols, " ", "\n", "", "", "", "\n");
out << "scaling: " << Eigen::RowVector3d(S(0,0), S(1,1), S(2,2)).format(fmt);
out << "shear: " << Eigen::RowVector3d(S(0,1), S(0,2), S(1,2)).format(fmt);
out << "angles: " << euler_angles.transpose().format(fmt);
out << "angle_axis: " << angle_axis.format(fmt);
out << "translation: " << transform.translation().transpose().format(fmt);
out << "R: " << R.row(0).format(fmt);
out << "R: " << R.row(1).format(fmt);
out << "R: " << R.row(2).format(fmt);
out << "S: " << S.row(0).format(fmt);
out << "S: " << S.row(1).format(fmt);
out << "S: " << S.row(2).format(fmt);
break;
}
default: assert (0);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2016 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "DatabaseCursor.h"
#include "Query.h"
#ifdef USE_SYSTEM_SQLITE
#include <sqlite3.h>
#else
#include "sqlite/sqlite3.h"
#endif
#include "Server.h"
DatabaseCursor::DatabaseCursor(CQuery *query, int *timeoutms)
: query(query), transaction_lock(false), tries(60), timeoutms(timeoutms),
lastErr(SQLITE_OK), _has_error(false), is_shutdown(false)
#ifdef LOG_READ_QUERIES
, db(db)
#endif
{
query->setupStepping(timeoutms, true);
#ifdef LOG_READ_QUERIES
active_query=new ScopedAddActiveQuery(query);
#endif
}
DatabaseCursor::~DatabaseCursor(void)
{
shutdown();
}
bool DatabaseCursor::reset()
{
tries = 60;
lastErr = SQLITE_OK;
_has_error = false;
is_shutdown = false;
transaction_lock = false;
query->setupStepping(timeoutms, false);
#ifdef LOG_READ_QUERIES
active_query = new ScopedAddActiveQuery(query, db, false);
#endif
return true;
}
bool DatabaseCursor::next(db_single_result &res)
{
res.clear();
do
{
bool reset=false;
lastErr=query->step(res, timeoutms, tries, transaction_lock, reset);
//TODO handle reset (should not happen in WAL mode)
if(lastErr==SQLITE_ROW)
{
return true;
}
}
while(query->resultOkay(lastErr));
if(lastErr!=SQLITE_DONE)
{
Server->Log("SQL Error: "+query->getErrMsg()+ " Stmt: ["+query->getStatement()+"]", LL_ERROR);
_has_error=true;
}
return false;
}
bool DatabaseCursor::has_error(void)
{
return _has_error;
}
void DatabaseCursor::shutdown()
{
if (!is_shutdown)
{
is_shutdown = true;
query->shutdownStepping(lastErr, timeoutms, transaction_lock);
#ifdef LOG_READ_QUERIES
delete active_query;
#endif
}
}
<commit_msg>Fix build<commit_after>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2016 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "DatabaseCursor.h"
#include "Query.h"
#ifdef USE_SYSTEM_SQLITE
#include <sqlite3.h>
#else
#include "sqlite/sqlite3.h"
#endif
#include "Server.h"
DatabaseCursor::DatabaseCursor(CQuery *query, int *timeoutms)
: query(query), transaction_lock(false), tries(60), timeoutms(timeoutms),
lastErr(SQLITE_OK), _has_error(false), is_shutdown(false)
#ifdef LOG_READ_QUERIES
, db(db)
#endif
{
query->setupStepping(timeoutms, true);
#ifdef LOG_READ_QUERIES
active_query=new ScopedAddActiveQuery(query);
#endif
}
DatabaseCursor::~DatabaseCursor(void)
{
shutdown();
}
bool DatabaseCursor::reset()
{
tries = 60;
lastErr = SQLITE_OK;
_has_error = false;
is_shutdown = false;
transaction_lock = false;
query->setupStepping(timeoutms, false);
#ifdef LOG_READ_QUERIES
active_query = new ScopedAddActiveQuery(query);
#endif
return true;
}
bool DatabaseCursor::next(db_single_result &res)
{
res.clear();
do
{
bool reset=false;
lastErr=query->step(res, timeoutms, tries, transaction_lock, reset);
//TODO handle reset (should not happen in WAL mode)
if(lastErr==SQLITE_ROW)
{
return true;
}
}
while(query->resultOkay(lastErr));
if(lastErr!=SQLITE_DONE)
{
Server->Log("SQL Error: "+query->getErrMsg()+ " Stmt: ["+query->getStatement()+"]", LL_ERROR);
_has_error=true;
}
return false;
}
bool DatabaseCursor::has_error(void)
{
return _has_error;
}
void DatabaseCursor::shutdown()
{
if (!is_shutdown)
{
is_shutdown = true;
query->shutdownStepping(lastErr, timeoutms, transaction_lock);
#ifdef LOG_READ_QUERIES
delete active_query;
#endif
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file qp_spline_path_generator.cc
**/
#include <algorithm>
#include <utility>
#include <vector>
#include "modules/planning/optimizer/qp_spline_path/qp_spline_path_generator.h"
#include "modules/common/proto/pnc_point.pb.h"
#include "modules/common/log.h"
#include "modules/common/macro.h"
#include "modules/common/util/string_util.h"
#include "modules/common/util/util.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/math/double.h"
#include "modules/planning/math/sl_analytic_transformation.h"
namespace apollo {
namespace planning {
using ConstPathObstacleList = std::vector<const PathObstacle*>;
QpSplinePathGenerator::QpSplinePathGenerator(
const ReferenceLine& reference_line,
const QpSplinePathConfig& qp_spline_path_config)
: reference_line_(reference_line),
qp_spline_path_config_(qp_spline_path_config) {}
bool QpSplinePathGenerator::Generate(
const ConstPathObstacleList& path_obstacles, const SpeedData& speed_data,
const common::TrajectoryPoint& init_point, PathData* const path_data) {
if (!CalculateInitFrenetPoint(init_point, &init_frenet_point_)) {
AERROR << "Fail to map init point: " << init_point.ShortDebugString();
return false;
}
double start_s = init_frenet_point_.s();
double end_s = std::min(reference_line_.length(),
init_frenet_point_.s() + FLAGS_look_forward_distance);
QpFrenetFrame qp_frenet_frame(reference_line_, path_obstacles, speed_data,
init_frenet_point_, start_s, end_s,
qp_spline_path_config_.time_resolution());
if (!qp_frenet_frame.Init(qp_spline_path_config_.num_output())) {
AERROR << "Fail to initialize qp frenet frame";
return false;
}
if (!InitCoordRange(qp_frenet_frame, &start_s, &end_s)) {
AERROR << "Measure natural coord system with s range failed!";
return false;
}
AINFO << "pss path start with " << start_s << ", end with " << end_s;
if (!InitSpline(init_frenet_point_, start_s, end_s - 0.1)) {
AERROR << "Init smoothing spline failed with (" << start_s << ", end_s "
<< end_s;
return false;
}
if (!AddConstraint(qp_frenet_frame)) {
AERROR << "Fail to setup pss path constraint.";
return false;
}
if (!AddKernel()) {
AERROR << "Fail to setup pss path kernel.";
return false;
}
if (!Solve()) {
AERROR << "Fail to solve the qp problem.";
return false;
}
AINFO << common::util::StrCat("Spline dl:", init_frenet_point_.dl(), ", ddl:",
init_frenet_point_.ddl());
// extract data
const Spline1d& spline = spline_generator_->spline();
std::vector<common::PathPoint> path_points;
double start_l = spline(init_frenet_point_.s());
ReferencePoint ref_point =
reference_line_.get_reference_point(init_frenet_point_.s());
common::math::Vec2d xy_point = SLAnalyticTransformation::CalculateXYPoint(
ref_point.heading(), common::math::Vec2d(ref_point.x(), ref_point.y()),
start_l);
double x_diff = xy_point.x() - init_point.path_point().x();
double y_diff = xy_point.y() - init_point.path_point().y();
double s = init_frenet_point_.s();
double s_resolution =
(end_s - init_frenet_point_.s()) / qp_spline_path_config_.num_output();
while (Double::Compare(s, end_s) < 0) {
double l = spline(s);
double dl = spline.Derivative(s);
double ddl = spline.SecondOrderDerivative(s);
ReferencePoint ref_point = reference_line_.get_reference_point(s);
common::math::Vec2d xy_point = SLAnalyticTransformation::CalculateXYPoint(
ref_point.heading(), common::math::Vec2d(ref_point.x(), ref_point.y()),
l);
xy_point.set_x(xy_point.x() - x_diff);
xy_point.set_y(xy_point.y() - y_diff);
double theta = SLAnalyticTransformation::CalculateTheta(
ref_point.heading(), ref_point.kappa(), l, dl);
double kappa = SLAnalyticTransformation::CalculateKappa(
ref_point.kappa(), ref_point.dkappa(), l, dl, ddl);
common::PathPoint path_point = common::util::MakePathPoint(
xy_point.x(), xy_point.y(), 0.0, theta, kappa, 0.0, 0.0);
if (path_points.size() != 0) {
double distance =
common::util::Distance2D(path_points.back(), path_point);
path_point.set_s(path_points.back().s() + distance);
}
if (Double::Compare(path_point.s(), end_s) >= 0) {
break;
}
path_points.push_back(path_point);
s += s_resolution;
}
path_data->SetReferenceLine(&reference_line_);
path_data->SetDiscretizedPath(DiscretizedPath(path_points));
return true;
}
bool QpSplinePathGenerator::CalculateInitFrenetPoint(
const common::TrajectoryPoint& traj_point,
common::FrenetFramePoint* const frenet_frame_point) {
common::SLPoint sl_point;
if (!reference_line_.get_point_in_frenet_frame(
{traj_point.path_point().x(), traj_point.path_point().y()},
&sl_point)) {
return false;
}
frenet_frame_point->set_s(sl_point.s());
frenet_frame_point->set_l(sl_point.l());
const double theta = traj_point.path_point().theta();
const double kappa = traj_point.path_point().kappa();
const double l = frenet_frame_point->l();
ReferencePoint ref_point =
reference_line_.get_reference_point(frenet_frame_point->s());
const double theta_ref = ref_point.heading();
const double kappa_ref = ref_point.kappa();
const double dkappa_ref = ref_point.dkappa();
const double dl = SLAnalyticTransformation::CalculateLateralDerivative(
theta_ref, theta, l, kappa_ref);
const double ddl =
SLAnalyticTransformation::CalculateSecondOrderLateralDerivative(
theta_ref, theta, kappa_ref, kappa, dkappa_ref, l);
frenet_frame_point->set_dl(dl);
frenet_frame_point->set_ddl(ddl);
return true;
}
bool QpSplinePathGenerator::InitCoordRange(const QpFrenetFrame& qp_frenet_frame,
double* const start_s,
double* const end_s) {
// TODO(all): step 1 get current sl coordinate - with init coordinate point
double start_point = std::max(init_frenet_point_.s() - 5.0, 0.0);
const ReferenceLine& reference_line_ = qp_frenet_frame.GetReferenceLine();
double end_point = std::min(reference_line_.length(),
*start_s + FLAGS_look_forward_distance);
end_point =
std::min(qp_frenet_frame.feasible_longitudinal_upper_bound(), end_point);
*start_s = start_point;
*end_s = end_point;
return true;
}
bool QpSplinePathGenerator::InitSpline(
const common::FrenetFramePoint& init_frenet_point, const double start_s,
const double end_s) {
// set knots
if (qp_spline_path_config_.number_of_knots() <= 1) {
AERROR << "Two few number of knots: "
<< qp_spline_path_config_.number_of_knots();
return false;
}
double distance = std::fmin(reference_line_.map_path().length(), end_s) -
init_frenet_point.s();
distance = std::fmin(distance, FLAGS_look_forward_distance);
const double delta_s = distance / qp_spline_path_config_.number_of_knots();
double curr_knot_s = init_frenet_point.s();
for (uint32_t i = 0; i <= qp_spline_path_config_.number_of_knots(); ++i) {
knots_.push_back(curr_knot_s);
curr_knot_s += delta_s;
}
// spawn a new spline generator
spline_generator_.reset(
new Spline1dGenerator(knots_, qp_spline_path_config_.spline_order()));
// set evaluated_s_
std::uint32_t num_evaluated_s =
qp_spline_path_config_.number_of_fx_constraint_knots();
if (num_evaluated_s <= 2) {
AERROR << "Too few evaluated positions. Suggest: > 2, current number: "
<< num_evaluated_s;
return false;
}
const double ds = (spline_generator_->spline().x_knots().back() -
spline_generator_->spline().x_knots().front()) /
num_evaluated_s;
double curr_evaluated_s = spline_generator_->spline().x_knots().front();
for (uint32_t i = 0; i < num_evaluated_s; ++i) {
evaluated_s_.push_back(curr_evaluated_s);
curr_evaluated_s += ds;
}
return true;
}
bool QpSplinePathGenerator::AddConstraint(
const QpFrenetFrame& qp_frenet_frame) {
Spline1dConstraint* spline_constraint =
spline_generator_->mutable_spline_constraint();
// add init status constraint
spline_constraint->AddPointConstraint(init_frenet_point_.s(),
init_frenet_point_.l());
spline_constraint->AddPointDerivativeConstraint(init_frenet_point_.s(),
init_frenet_point_.dl());
spline_constraint->AddPointSecondDerivativeConstraint(
init_frenet_point_.s(), init_frenet_point_.ddl());
ADEBUG << "init frenet point: " << init_frenet_point_.ShortDebugString();
// add end point constraint
spline_constraint->AddPointConstraint(knots_.back(), 0.0);
spline_constraint->AddPointDerivativeConstraint(knots_.back(), 0.0);
spline_constraint->AddPointSecondDerivativeConstraint(knots_.back(), 0.0);
// add map bound constraint
std::vector<double> boundary_low;
std::vector<double> boundary_high;
for (const double s : evaluated_s_) {
std::pair<double, double> boundary = std::make_pair(0.0, 0.0);
qp_frenet_frame.GetMapBound(s, &boundary);
boundary_low.push_back(boundary.first);
boundary_high.push_back(boundary.second);
}
if (!spline_constraint->AddBoundary(evaluated_s_, boundary_low,
boundary_high)) {
AERROR << "Add boundary constraint failed";
return false;
}
// add spline joint third derivative constraint
if (!spline_constraint->AddThirdDerivativeSmoothConstraint()) {
AERROR << "Add spline joint third derivative constraint failed!";
return false;
}
return true;
}
bool QpSplinePathGenerator::AddKernel() {
Spline1dKernel* spline_kernel = spline_generator_->mutable_spline_kernel();
if (qp_spline_path_config_.regularization_weight() > 0) {
spline_kernel->AddRegularization(
qp_spline_path_config_.regularization_weight());
}
if (qp_spline_path_config_.derivative_weight() > 0) {
spline_kernel->add_derivative_kernel_matrix(
qp_spline_path_config_.derivative_weight());
}
if (qp_spline_path_config_.second_derivative_weight() > 0) {
spline_kernel->add_second_order_derivative_matrix(
qp_spline_path_config_.second_derivative_weight());
}
if (qp_spline_path_config_.third_derivative_weight() > 0) {
spline_kernel->add_third_order_derivative_matrix(
qp_spline_path_config_.third_derivative_weight());
}
// reference line kernel
if (qp_spline_path_config_.number_of_knots() > 1) {
std::vector<double> l_vec(knots_.size(), 0.0);
spline_kernel->add_reference_line_kernel_matrix(
knots_, l_vec, qp_spline_path_config_.reference_line_weight());
}
return true;
}
bool QpSplinePathGenerator::Solve() {
if (!spline_generator_->Solve()) {
AERROR << "Could not solve the qp problem in spline path generator.";
return false;
}
return true;
}
} // namespace planning
} // namespace apollo
<commit_msg>planning: add qp path boundary debug log.<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file qp_spline_path_generator.cc
**/
#include <algorithm>
#include <utility>
#include <vector>
#include "modules/planning/optimizer/qp_spline_path/qp_spline_path_generator.h"
#include "modules/common/proto/pnc_point.pb.h"
#include "modules/common/log.h"
#include "modules/common/macro.h"
#include "modules/common/util/string_util.h"
#include "modules/common/util/util.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/math/double.h"
#include "modules/planning/math/sl_analytic_transformation.h"
namespace apollo {
namespace planning {
using ConstPathObstacleList = std::vector<const PathObstacle*>;
QpSplinePathGenerator::QpSplinePathGenerator(
const ReferenceLine& reference_line,
const QpSplinePathConfig& qp_spline_path_config)
: reference_line_(reference_line),
qp_spline_path_config_(qp_spline_path_config) {}
bool QpSplinePathGenerator::Generate(
const ConstPathObstacleList& path_obstacles, const SpeedData& speed_data,
const common::TrajectoryPoint& init_point, PathData* const path_data) {
if (!CalculateInitFrenetPoint(init_point, &init_frenet_point_)) {
AERROR << "Fail to map init point: " << init_point.ShortDebugString();
return false;
}
double start_s = init_frenet_point_.s();
double end_s = std::min(reference_line_.length(),
init_frenet_point_.s() + FLAGS_look_forward_distance);
QpFrenetFrame qp_frenet_frame(reference_line_, path_obstacles, speed_data,
init_frenet_point_, start_s, end_s,
qp_spline_path_config_.time_resolution());
if (!qp_frenet_frame.Init(qp_spline_path_config_.num_output())) {
AERROR << "Fail to initialize qp frenet frame";
return false;
}
if (!InitCoordRange(qp_frenet_frame, &start_s, &end_s)) {
AERROR << "Measure natural coord system with s range failed!";
return false;
}
AINFO << "pss path start with " << start_s << ", end with " << end_s;
if (!InitSpline(init_frenet_point_, start_s, end_s - 0.1)) {
AERROR << "Init smoothing spline failed with (" << start_s << ", end_s "
<< end_s;
return false;
}
if (!AddConstraint(qp_frenet_frame)) {
AERROR << "Fail to setup pss path constraint.";
return false;
}
if (!AddKernel()) {
AERROR << "Fail to setup pss path kernel.";
return false;
}
if (!Solve()) {
AERROR << "Fail to solve the qp problem.";
return false;
}
AINFO << common::util::StrCat("Spline dl:", init_frenet_point_.dl(), ", ddl:",
init_frenet_point_.ddl());
// extract data
const Spline1d& spline = spline_generator_->spline();
std::vector<common::PathPoint> path_points;
double start_l = spline(init_frenet_point_.s());
ReferencePoint ref_point =
reference_line_.get_reference_point(init_frenet_point_.s());
common::math::Vec2d xy_point = SLAnalyticTransformation::CalculateXYPoint(
ref_point.heading(), common::math::Vec2d(ref_point.x(), ref_point.y()),
start_l);
double x_diff = xy_point.x() - init_point.path_point().x();
double y_diff = xy_point.y() - init_point.path_point().y();
double s = init_frenet_point_.s();
double s_resolution =
(end_s - init_frenet_point_.s()) / qp_spline_path_config_.num_output();
while (Double::Compare(s, end_s) < 0) {
double l = spline(s);
double dl = spline.Derivative(s);
double ddl = spline.SecondOrderDerivative(s);
ReferencePoint ref_point = reference_line_.get_reference_point(s);
common::math::Vec2d xy_point = SLAnalyticTransformation::CalculateXYPoint(
ref_point.heading(), common::math::Vec2d(ref_point.x(), ref_point.y()),
l);
xy_point.set_x(xy_point.x() - x_diff);
xy_point.set_y(xy_point.y() - y_diff);
double theta = SLAnalyticTransformation::CalculateTheta(
ref_point.heading(), ref_point.kappa(), l, dl);
double kappa = SLAnalyticTransformation::CalculateKappa(
ref_point.kappa(), ref_point.dkappa(), l, dl, ddl);
common::PathPoint path_point = common::util::MakePathPoint(
xy_point.x(), xy_point.y(), 0.0, theta, kappa, 0.0, 0.0);
if (path_points.size() != 0) {
double distance =
common::util::Distance2D(path_points.back(), path_point);
path_point.set_s(path_points.back().s() + distance);
}
if (Double::Compare(path_point.s(), end_s) >= 0) {
break;
}
path_points.push_back(path_point);
s += s_resolution;
}
path_data->SetReferenceLine(&reference_line_);
path_data->SetDiscretizedPath(DiscretizedPath(path_points));
return true;
}
bool QpSplinePathGenerator::CalculateInitFrenetPoint(
const common::TrajectoryPoint& traj_point,
common::FrenetFramePoint* const frenet_frame_point) {
common::SLPoint sl_point;
if (!reference_line_.get_point_in_frenet_frame(
{traj_point.path_point().x(), traj_point.path_point().y()},
&sl_point)) {
return false;
}
frenet_frame_point->set_s(sl_point.s());
frenet_frame_point->set_l(sl_point.l());
const double theta = traj_point.path_point().theta();
const double kappa = traj_point.path_point().kappa();
const double l = frenet_frame_point->l();
ReferencePoint ref_point =
reference_line_.get_reference_point(frenet_frame_point->s());
const double theta_ref = ref_point.heading();
const double kappa_ref = ref_point.kappa();
const double dkappa_ref = ref_point.dkappa();
const double dl = SLAnalyticTransformation::CalculateLateralDerivative(
theta_ref, theta, l, kappa_ref);
const double ddl =
SLAnalyticTransformation::CalculateSecondOrderLateralDerivative(
theta_ref, theta, kappa_ref, kappa, dkappa_ref, l);
frenet_frame_point->set_dl(dl);
frenet_frame_point->set_ddl(ddl);
return true;
}
bool QpSplinePathGenerator::InitCoordRange(const QpFrenetFrame& qp_frenet_frame,
double* const start_s,
double* const end_s) {
// TODO(all): step 1 get current sl coordinate - with init coordinate point
double start_point = std::max(init_frenet_point_.s() - 5.0, 0.0);
const ReferenceLine& reference_line_ = qp_frenet_frame.GetReferenceLine();
double end_point = std::min(reference_line_.length(),
*start_s + FLAGS_look_forward_distance);
end_point =
std::min(qp_frenet_frame.feasible_longitudinal_upper_bound(), end_point);
*start_s = start_point;
*end_s = end_point;
return true;
}
bool QpSplinePathGenerator::InitSpline(
const common::FrenetFramePoint& init_frenet_point, const double start_s,
const double end_s) {
// set knots
if (qp_spline_path_config_.number_of_knots() <= 1) {
AERROR << "Two few number of knots: "
<< qp_spline_path_config_.number_of_knots();
return false;
}
double distance = std::fmin(reference_line_.map_path().length(), end_s) -
init_frenet_point.s();
distance = std::fmin(distance, FLAGS_look_forward_distance);
const double delta_s = distance / qp_spline_path_config_.number_of_knots();
double curr_knot_s = init_frenet_point.s();
for (uint32_t i = 0; i <= qp_spline_path_config_.number_of_knots(); ++i) {
knots_.push_back(curr_knot_s);
curr_knot_s += delta_s;
}
// spawn a new spline generator
spline_generator_.reset(
new Spline1dGenerator(knots_, qp_spline_path_config_.spline_order()));
// set evaluated_s_
std::uint32_t num_evaluated_s =
qp_spline_path_config_.number_of_fx_constraint_knots();
if (num_evaluated_s <= 2) {
AERROR << "Too few evaluated positions. Suggest: > 2, current number: "
<< num_evaluated_s;
return false;
}
const double ds = (spline_generator_->spline().x_knots().back() -
spline_generator_->spline().x_knots().front()) /
num_evaluated_s;
double curr_evaluated_s = spline_generator_->spline().x_knots().front();
for (uint32_t i = 0; i < num_evaluated_s; ++i) {
evaluated_s_.push_back(curr_evaluated_s);
curr_evaluated_s += ds;
}
return true;
}
bool QpSplinePathGenerator::AddConstraint(
const QpFrenetFrame& qp_frenet_frame) {
Spline1dConstraint* spline_constraint =
spline_generator_->mutable_spline_constraint();
// add init status constraint
spline_constraint->AddPointConstraint(init_frenet_point_.s(),
init_frenet_point_.l());
spline_constraint->AddPointDerivativeConstraint(init_frenet_point_.s(),
init_frenet_point_.dl());
spline_constraint->AddPointSecondDerivativeConstraint(
init_frenet_point_.s(), init_frenet_point_.ddl());
ADEBUG << "init frenet point: " << init_frenet_point_.ShortDebugString();
// add end point constraint
spline_constraint->AddPointConstraint(knots_.back(), 0.0);
spline_constraint->AddPointDerivativeConstraint(knots_.back(), 0.0);
spline_constraint->AddPointSecondDerivativeConstraint(knots_.back(), 0.0);
// add map bound constraint
std::vector<double> boundary_low;
std::vector<double> boundary_high;
for (const double s : evaluated_s_) {
std::pair<double, double> boundary = std::make_pair(0.0, 0.0);
qp_frenet_frame.GetMapBound(s, &boundary);
boundary_low.push_back(boundary.first);
boundary_high.push_back(boundary.second);
ADEBUG << "s:" << s << " boundary_low:" << boundary.first
<< " boundary_high:" << boundary.second;
}
if (!spline_constraint->AddBoundary(evaluated_s_, boundary_low,
boundary_high)) {
AERROR << "Add boundary constraint failed";
return false;
}
// add spline joint third derivative constraint
if (!spline_constraint->AddThirdDerivativeSmoothConstraint()) {
AERROR << "Add spline joint third derivative constraint failed!";
return false;
}
return true;
}
bool QpSplinePathGenerator::AddKernel() {
Spline1dKernel* spline_kernel = spline_generator_->mutable_spline_kernel();
if (qp_spline_path_config_.regularization_weight() > 0) {
spline_kernel->AddRegularization(
qp_spline_path_config_.regularization_weight());
}
if (qp_spline_path_config_.derivative_weight() > 0) {
spline_kernel->add_derivative_kernel_matrix(
qp_spline_path_config_.derivative_weight());
}
if (qp_spline_path_config_.second_derivative_weight() > 0) {
spline_kernel->add_second_order_derivative_matrix(
qp_spline_path_config_.second_derivative_weight());
}
if (qp_spline_path_config_.third_derivative_weight() > 0) {
spline_kernel->add_third_order_derivative_matrix(
qp_spline_path_config_.third_derivative_weight());
}
// reference line kernel
if (qp_spline_path_config_.number_of_knots() > 1) {
std::vector<double> l_vec(knots_.size(), 0.0);
spline_kernel->add_reference_line_kernel_matrix(
knots_, l_vec, qp_spline_path_config_.reference_line_weight());
}
return true;
}
bool QpSplinePathGenerator::Solve() {
if (!spline_generator_->Solve()) {
AERROR << "Could not solve the qp problem in spline path generator.";
return false;
}
return true;
}
} // namespace planning
} // namespace apollo
<|endoftext|> |
<commit_before>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include "ClientRegister.h"
#include "SyncThread.h"
#include "ILoginListener.h"
#include "common/RhoConf.h"
#include "common/RhodesApp.h"
#include "System.h"
rho::String rho_sysimpl_get_phone_id();
namespace rho{
namespace sync{
using namespace rho::common;
using namespace rho::db;
static const int THREAD_WAIT_TIMEOUT = 10;
static const char * const PUSH_PIN_NAME = "push_pin";
IMPLEMENT_LOGCLASS(CClientRegister,"ClientRegister");
CClientRegister* CClientRegister::m_pInstance = 0;
bool CClientRegister::s_sslVerifyPeer = true;
VectorPtr<ILoginListener*> CClientRegister::s_loginListeners;
/*static*/ CClientRegister* CClientRegister::Get()
{
if (!m_pInstance)
{
m_pInstance = new CClientRegister();
}
return m_pInstance;
}
/*static*/ CClientRegister* CClientRegister::Create()
{
String session = CSyncThread::getSyncEngine().loadSession();
if (session.length() > 0)
{
Get()->setRhoconnectCredentials("", "", session);
}
Get()->startUp();
return m_pInstance;
}
/*static*/ CClientRegister* CClientRegister::Create(const String& devicePin)
{
Get()->setDevicehPin(devicePin);
return m_pInstance;
}
/*static*/ void CClientRegister::Stop()
{
if(m_pInstance)
{
m_pInstance->doStop();
}
}
/*static*/ void CClientRegister::Destroy()
{
if ( m_pInstance )
delete m_pInstance;
m_pInstance = 0;
}
/*static*/ void CClientRegister::SetSslVerifyPeer(boolean b)
{
s_sslVerifyPeer = b;
if (m_pInstance)
m_pInstance->m_NetRequest.setSslVerifyPeer(b);
}
bool CClientRegister::GetSslVerifyPeer()
{
return s_sslVerifyPeer;
}
/*static*/void CClientRegister::AddLoginListener(ILoginListener* listener)
{
s_loginListeners.addElement(listener);
}
CClientRegister::CClientRegister() : m_nPollInterval(POLL_INTERVAL_SECONDS)
{
m_NetRequest.setSslVerifyPeer(s_sslVerifyPeer);
}
CClientRegister::~CClientRegister()
{
doStop();
m_pInstance = null;
}
void CClientRegister::setRhoconnectCredentials(const String& user, const String& pass, const String& session)
{
LOG(INFO) + "New Sync credentials - user: " + user + ", sess: " + session;
for(VectorPtr<ILoginListener*>::iterator I = s_loginListeners.begin(); I != s_loginListeners.end(); ++I)
{
(*I)->onLogin(user, pass, session);
}
startUp();
}
void CClientRegister::dropRhoconnectCredentials(const String& session)
{
for(VectorPtr<ILoginListener*>::iterator I = s_loginListeners.begin(); I != s_loginListeners.end(); ++I)
{
(*I)->onLogout(session);
}
}
void CClientRegister::setDevicehPin(const String& pin)
{
m_strDevicePin = pin;
RHOCONF().setString(PUSH_PIN_NAME, pin, true);
if (pin.length() > 0)
{
startUp();
} else
{
doStop();
}
}
void CClientRegister::startUp()
{
if ( RHOCONF().getString("syncserver").length() > 0 )
{
LOG(INFO) + "Starting ClientRegister...";
start(epLow);
stopWait();
}
}
void CClientRegister::run()
{
unsigned i = 0;
LOG(INFO)+"ClientRegister is started";
while(!isStopping())
{
i++;
LOG(INFO)+"Try to register: " + i;
if ( CSyncThread::getInstance() != null )
{
if ( doRegister(CSyncThread::getSyncEngine()) )
{
LOG(INFO)+"Registered: " + i;
break;
}
} else
LOG(INFO)+"SyncThread is not ready";
LOG(INFO)+"Waiting for "+ m_nPollInterval+ " sec to try again to register client";
wait(m_nPollInterval*1000);
}
LOG(INFO)+"ClientRegister thread shutdown";
}
String CClientRegister::getRegisterBody(const String& strClientID)
{
IRhoPushClient* pushClient = RHODESAPP().getDefaultPushClient();
int port = RHOCONF().getInt("push_port");
String body = CSyncThread::getSyncEngine().getProtocol().getClientRegisterBody( strClientID, m_strDevicePin,
port > 0 ? port : DEFAULT_PUSH_PORT, rho_rhodesapp_getplatform(), rho::System::getPhoneId(),
/*device_push_type*/ (0 != pushClient) ? pushClient->getType() : "" /*it means native push type*/);
LOG(INFO)+"getRegisterBody() BODY is: " + body;
return body;
/*
if(m_isAns)
body = CSyncThread::getSyncEngine().getProtocol().getClientAnsRegisterBody( strClientID, m_strDevicePin,
port > 0 ? port : DEFAULT_PUSH_PORT, rho_rhodesapp_getplatform(), rho_sysimpl_get_phone_id() );
else
body = CSyncThread::getSyncEngine().getProtocol().getClientRegisterBody( strClientID, m_strDevicePin,
port > 0 ? port : DEFAULT_PUSH_PORT, rho_rhodesapp_getplatform(), rho_sysimpl_get_phone_id() );
*/
}
boolean CClientRegister::doRegister(CSyncEngine& oSync)
{
String session = oSync.loadSession();
if ( session.length() == 0 )
{
m_nPollInterval = POLL_INTERVAL_INFINITE;
LOG(INFO)+"Session is empty, do register later";
return false;
}
if ( m_strDevicePin.length() == 0 )
{
m_strDevicePin = RHOCONF().getString(PUSH_PIN_NAME);
}
if ( m_strDevicePin.length() == 0 )
{
m_nPollInterval = POLL_INTERVAL_INFINITE;
LOG(INFO)+"Device PUSH pin is empty, do register later";
return false;
}
m_nPollInterval = POLL_INTERVAL_SECONDS;
String client_id = oSync.loadClientID();
if ( client_id.length() == 0 )
{
LOG(WARNING)+"Sync client_id is empty, do register later";
return false;
}
IDBResult res = CDBAdapter::getUserDB().executeSQL("SELECT token,token_sent from client_info");
if ( !res.isEnd() ) {
String token = res.getStringByIdx(0);
int token_sent = res.getIntByIdx(1) && !RHOCONF().getBool("register_push_at_startup");
if ( m_strDevicePin.compare(token) == 0 && token_sent > 0 )
{
//token in db same as new one and it was already send to the server
//so we do nothing
return true;
}
}
String strBody = getRegisterBody(client_id);
NetResponse resp = getNet().pushData( oSync.getProtocol().getClientRegisterUrl(client_id), strBody, &oSync );
if( resp.isOK() )
{
// try {
CDBAdapter::getUserDB().executeSQL("UPDATE client_info SET token_sent=?, token=?", 1, m_strDevicePin );
// } catch(Exception ex) {
// LOG.ERROR("Error saving token_sent to the DB...");
// }
LOG(INFO)+"Registered client sucessfully...";
return true;
}
LOG(WARNING)+"Network error: "+ resp.getRespCode();
return false;
}
void CClientRegister::doStop()
{
LOG(INFO) + "Stopping ClientRegister...";
m_NetRequest.cancel();
stop(WAIT_BEFOREKILL_SECONDS);
}
}
}
<commit_msg>Remove storing device pin in rhoconfig<commit_after>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include "ClientRegister.h"
#include "SyncThread.h"
#include "ILoginListener.h"
#include "common/RhoConf.h"
#include "common/RhodesApp.h"
#include "System.h"
rho::String rho_sysimpl_get_phone_id();
namespace rho{
namespace sync{
using namespace rho::common;
using namespace rho::db;
static const int THREAD_WAIT_TIMEOUT = 10;
IMPLEMENT_LOGCLASS(CClientRegister,"ClientRegister");
CClientRegister* CClientRegister::m_pInstance = 0;
bool CClientRegister::s_sslVerifyPeer = true;
VectorPtr<ILoginListener*> CClientRegister::s_loginListeners;
/*static*/ CClientRegister* CClientRegister::Get()
{
if (!m_pInstance)
{
m_pInstance = new CClientRegister();
}
return m_pInstance;
}
/*static*/ CClientRegister* CClientRegister::Create()
{
LOG(TRACE) + "Loading rhoconnect session...";
String session = CSyncThread::getSyncEngine().loadSession();
if (session.length() > 0)
{
LOG(TRACE) + "Loaded";
Get()->setRhoconnectCredentials("", "", session);
}
LOG(TRACE) + "Starting ClientRegister";
Get()->startUp();
return m_pInstance;
}
/*static*/ CClientRegister* CClientRegister::Create(const String& devicePin)
{
Get()->setDevicehPin(devicePin);
return m_pInstance;
}
/*static*/ void CClientRegister::Stop()
{
if(m_pInstance)
{
m_pInstance->doStop();
}
}
/*static*/ void CClientRegister::Destroy()
{
if ( m_pInstance )
delete m_pInstance;
m_pInstance = 0;
}
/*static*/ void CClientRegister::SetSslVerifyPeer(boolean b)
{
s_sslVerifyPeer = b;
if (m_pInstance)
m_pInstance->m_NetRequest.setSslVerifyPeer(b);
}
bool CClientRegister::GetSslVerifyPeer()
{
return s_sslVerifyPeer;
}
/*static*/void CClientRegister::AddLoginListener(ILoginListener* listener)
{
s_loginListeners.addElement(listener);
}
CClientRegister::CClientRegister() : m_nPollInterval(POLL_INTERVAL_SECONDS)
{
m_NetRequest.setSslVerifyPeer(s_sslVerifyPeer);
}
CClientRegister::~CClientRegister()
{
doStop();
m_pInstance = null;
}
void CClientRegister::setRhoconnectCredentials(const String& user, const String& pass, const String& session)
{
LOG(INFO) + "New Sync credentials - user: " + user + ", sess: " + session;
for(VectorPtr<ILoginListener*>::iterator I = s_loginListeners.begin(); I != s_loginListeners.end(); ++I)
{
(*I)->onLogin(user, pass, session);
}
startUp();
}
void CClientRegister::dropRhoconnectCredentials(const String& session)
{
for(VectorPtr<ILoginListener*>::iterator I = s_loginListeners.begin(); I != s_loginListeners.end(); ++I)
{
(*I)->onLogout(session);
}
}
void CClientRegister::setDevicehPin(const String& pin)
{
m_strDevicePin = pin;
if (pin.length() > 0)
{
startUp();
} else
{
doStop();
}
}
void CClientRegister::startUp()
{
if ( RHOCONF().getString("syncserver").length() > 0 )
{
LOG(INFO) + "Starting ClientRegister...";
start(epLow);
stopWait();
}
}
void CClientRegister::run()
{
unsigned i = 0;
LOG(INFO)+"ClientRegister is started";
while(!isStopping())
{
i++;
LOG(INFO)+"Try to register: " + i;
if ( CSyncThread::getInstance() != null )
{
if ( doRegister(CSyncThread::getSyncEngine()) )
{
LOG(INFO)+"Registered: " + i;
break;
}
} else
LOG(INFO)+"SyncThread is not ready";
LOG(INFO)+"Waiting for "+ m_nPollInterval+ " sec to try again to register client";
wait(m_nPollInterval*1000);
}
LOG(INFO)+"ClientRegister thread shutdown";
}
String CClientRegister::getRegisterBody(const String& strClientID)
{
IRhoPushClient* pushClient = RHODESAPP().getDefaultPushClient();
int port = RHOCONF().getInt("push_port");
String body = CSyncThread::getSyncEngine().getProtocol().getClientRegisterBody( strClientID, m_strDevicePin,
port > 0 ? port : DEFAULT_PUSH_PORT, rho_rhodesapp_getplatform(), rho::System::getPhoneId(),
/*device_push_type*/ (0 != pushClient) ? pushClient->getType() : "" /*it means native push type*/);
LOG(INFO)+"getRegisterBody() BODY is: " + body;
return body;
/*
if(m_isAns)
body = CSyncThread::getSyncEngine().getProtocol().getClientAnsRegisterBody( strClientID, m_strDevicePin,
port > 0 ? port : DEFAULT_PUSH_PORT, rho_rhodesapp_getplatform(), rho_sysimpl_get_phone_id() );
else
body = CSyncThread::getSyncEngine().getProtocol().getClientRegisterBody( strClientID, m_strDevicePin,
port > 0 ? port : DEFAULT_PUSH_PORT, rho_rhodesapp_getplatform(), rho_sysimpl_get_phone_id() );
*/
}
boolean CClientRegister::doRegister(CSyncEngine& oSync)
{
String session = oSync.loadSession();
if ( session.length() == 0 )
{
m_nPollInterval = POLL_INTERVAL_INFINITE;
LOG(INFO)+"Session is empty, do register later";
return false;
}
if ( m_strDevicePin.length() == 0 )
{
m_nPollInterval = POLL_INTERVAL_INFINITE;
LOG(INFO)+"Device PUSH pin is empty, do register later";
return false;
}
m_nPollInterval = POLL_INTERVAL_SECONDS;
String client_id = oSync.loadClientID();
if ( client_id.length() == 0 )
{
LOG(WARNING)+"Sync client_id is empty, do register later";
return false;
}
IDBResult res = CDBAdapter::getUserDB().executeSQL("SELECT token,token_sent from client_info");
if ( !res.isEnd() ) {
String token = res.getStringByIdx(0);
int token_sent = res.getIntByIdx(1) && !RHOCONF().getBool("register_push_at_startup");
if ( m_strDevicePin.compare(token) == 0 && token_sent > 0 )
{
//token in db same as new one and it was already send to the server
//so we do nothing
return true;
}
}
String strBody = getRegisterBody(client_id);
NetResponse resp = getNet().pushData( oSync.getProtocol().getClientRegisterUrl(client_id), strBody, &oSync );
if( resp.isOK() )
{
// try {
CDBAdapter::getUserDB().executeSQL("UPDATE client_info SET token_sent=?, token=?", 1, m_strDevicePin );
// } catch(Exception ex) {
// LOG.ERROR("Error saving token_sent to the DB...");
// }
LOG(INFO)+"Registered client sucessfully...";
return true;
}
LOG(WARNING)+"Network error: "+ resp.getRespCode();
return false;
}
void CClientRegister::doStop()
{
LOG(INFO) + "Stopping ClientRegister...";
m_NetRequest.cancel();
stop(WAIT_BEFOREKILL_SECONDS);
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2010, 2012-2013, 2015,2017-2019 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2002-2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "arch/arm/fs_workload.hh"
#include "arch/arm/faults.hh"
#include "base/loader/object_file.hh"
#include "base/loader/symtab.hh"
#include "cpu/thread_context.hh"
#include "dev/arm/gic_v2.hh"
#include "kern/system_events.hh"
#include "params/ArmFsWorkload.hh"
namespace ArmISA
{
void
SkipFunc::returnFromFuncIn(ThreadContext *tc)
{
PCState newPC = tc->pcState();
if (inAArch64(tc)) {
newPC.set(tc->readIntReg(INTREG_X30));
} else {
newPC.set(tc->readIntReg(ReturnAddressReg) & ~ULL(1));
}
CheckerCPU *checker = tc->getCheckerCpuPtr();
if (checker) {
tc->pcStateNoRecord(newPC);
} else {
tc->pcState(newPC);
}
}
FsWorkload::FsWorkload(Params *p)
: OsKernel(*p),
kernelEntry((entry & loadAddrMask) + loadAddrOffset)
{
bootLoaders.reserve(p->boot_loader.size());
for (const auto &bl : p->boot_loader) {
std::unique_ptr<ObjectFile> bl_obj;
bl_obj.reset(createObjectFile(bl));
fatal_if(!bl_obj, "Could not read bootloader: %s", bl);
bootLoaders.emplace_back(std::move(bl_obj));
}
if (obj) {
bootldr = getBootLoader(obj);
} else if (!bootLoaders.empty()) {
// No kernel specified, default to the first boot loader
bootldr = bootLoaders[0].get();
}
fatal_if(!bootLoaders.empty() && !bootldr,
"Can't find a matching boot loader / kernel combination!");
if (bootldr) {
bootldr->loadGlobalSymbols(debugSymbolTable);
_highestELIs64 = (bootldr->getArch() == ObjectFile::Arm64);
} else {
_highestELIs64 = (obj->getArch() == ObjectFile::Arm64);
}
}
void
FsWorkload::initState()
{
OsKernel::initState();
// Reset CP15?? What does that mean -- ali
// FPEXC.EN = 0
for (auto *tc: system->threadContexts) {
Reset().invoke(tc);
tc->activate();
}
auto *arm_sys = dynamic_cast<ArmSystem *>(system);
if (bootldr) {
bool is_gic_v2 =
arm_sys->getGIC()->supportsVersion(BaseGic::GicVersion::GIC_V2);
bootldr->buildImage().write(system->physProxy);
inform("Using bootloader at address %#x", bootldr->entryPoint());
// Put the address of the boot loader into r7 so we know
// where to branch to after the reset fault
// All other values needed by the boot loader to know what to do
fatal_if(!arm_sys->params()->flags_addr,
"flags_addr must be set with bootloader");
fatal_if(!arm_sys->params()->gic_cpu_addr && is_gic_v2,
"gic_cpu_addr must be set with bootloader");
for (auto tc: arm_sys->threadContexts) {
if (!arm_sys->highestELIs64())
tc->setIntReg(3, kernelEntry);
if (is_gic_v2)
tc->setIntReg(4, arm_sys->params()->gic_cpu_addr);
tc->setIntReg(5, arm_sys->params()->flags_addr);
}
inform("Using kernel entry physical address at %#x\n", kernelEntry);
} else {
// Set the initial PC to be at start of the kernel code
if (!arm_sys->highestELIs64())
arm_sys->threadContexts[0]->pcState(entry);
}
}
ObjectFile *
FsWorkload::getBootLoader(ObjectFile *const obj)
{
for (auto &bl : bootLoaders) {
if (bl->getArch() == obj->getArch())
return bl.get();
}
return nullptr;
}
Addr
FsWorkload::resetAddr() const
{
if (bootldr) {
return bootldr->entryPoint();
} else {
return kernelEntry;
}
}
} // namespace ArmISA
ArmISA::FsWorkload *
ArmFsWorkloadParams::create()
{
return new ArmISA::FsWorkload(this);
}
<commit_msg>arch-arm: Handle empty object_file scenario in ArmFsWorkload<commit_after>/*
* Copyright (c) 2010, 2012-2013, 2015,2017-2019 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2002-2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "arch/arm/fs_workload.hh"
#include "arch/arm/faults.hh"
#include "base/loader/object_file.hh"
#include "base/loader/symtab.hh"
#include "cpu/thread_context.hh"
#include "dev/arm/gic_v2.hh"
#include "kern/system_events.hh"
#include "params/ArmFsWorkload.hh"
namespace ArmISA
{
void
SkipFunc::returnFromFuncIn(ThreadContext *tc)
{
PCState newPC = tc->pcState();
if (inAArch64(tc)) {
newPC.set(tc->readIntReg(INTREG_X30));
} else {
newPC.set(tc->readIntReg(ReturnAddressReg) & ~ULL(1));
}
CheckerCPU *checker = tc->getCheckerCpuPtr();
if (checker) {
tc->pcStateNoRecord(newPC);
} else {
tc->pcState(newPC);
}
}
FsWorkload::FsWorkload(Params *p)
: OsKernel(*p),
kernelEntry((entry & loadAddrMask) + loadAddrOffset)
{
bootLoaders.reserve(p->boot_loader.size());
for (const auto &bl : p->boot_loader) {
std::unique_ptr<ObjectFile> bl_obj;
bl_obj.reset(createObjectFile(bl));
fatal_if(!bl_obj, "Could not read bootloader: %s", bl);
bootLoaders.emplace_back(std::move(bl_obj));
}
if (obj) {
bootldr = getBootLoader(obj);
} else if (!bootLoaders.empty()) {
// No kernel specified, default to the first boot loader
bootldr = bootLoaders[0].get();
}
fatal_if(!bootLoaders.empty() && !bootldr,
"Can't find a matching boot loader / kernel combination!");
if (bootldr) {
bootldr->loadGlobalSymbols(debugSymbolTable);
_highestELIs64 = (bootldr->getArch() == ObjectFile::Arm64);
} else if (obj) {
_highestELIs64 = (obj->getArch() == ObjectFile::Arm64);
}
}
void
FsWorkload::initState()
{
OsKernel::initState();
// Reset CP15?? What does that mean -- ali
// FPEXC.EN = 0
for (auto *tc: system->threadContexts) {
Reset().invoke(tc);
tc->activate();
}
auto *arm_sys = dynamic_cast<ArmSystem *>(system);
if (bootldr) {
bool is_gic_v2 =
arm_sys->getGIC()->supportsVersion(BaseGic::GicVersion::GIC_V2);
bootldr->buildImage().write(system->physProxy);
inform("Using bootloader at address %#x", bootldr->entryPoint());
// Put the address of the boot loader into r7 so we know
// where to branch to after the reset fault
// All other values needed by the boot loader to know what to do
fatal_if(!arm_sys->params()->flags_addr,
"flags_addr must be set with bootloader");
fatal_if(!arm_sys->params()->gic_cpu_addr && is_gic_v2,
"gic_cpu_addr must be set with bootloader");
for (auto tc: arm_sys->threadContexts) {
if (!arm_sys->highestELIs64())
tc->setIntReg(3, kernelEntry);
if (is_gic_v2)
tc->setIntReg(4, arm_sys->params()->gic_cpu_addr);
tc->setIntReg(5, arm_sys->params()->flags_addr);
}
inform("Using kernel entry physical address at %#x\n", kernelEntry);
} else {
// Set the initial PC to be at start of the kernel code
if (!arm_sys->highestELIs64())
arm_sys->threadContexts[0]->pcState(entry);
}
}
ObjectFile *
FsWorkload::getBootLoader(ObjectFile *const obj)
{
for (auto &bl : bootLoaders) {
if (bl->getArch() == obj->getArch())
return bl.get();
}
return nullptr;
}
Addr
FsWorkload::resetAddr() const
{
if (bootldr) {
return bootldr->entryPoint();
} else {
return kernelEntry;
}
}
} // namespace ArmISA
ArmISA::FsWorkload *
ArmFsWorkloadParams::create()
{
return new ArmISA::FsWorkload(this);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <list>
#include <string>
#include <algebra/block_matrix.h>
#include <algebra/matrix.h>
#include <algebra/vector.h>
using std::cout;
using std::endl;
using namespace MathTL;
int main()
{
cout << "Testing the class BlockMatrix ..." << endl;
BlockMatrix<double> defaultM;
cout << "- a default block matrix:" << endl << defaultM;
BlockMatrix<double> N(1);
cout << "- a BlockMatrix(1):" << endl << N;
BlockMatrix<double> M(1,2);
cout << "- a BlockMatrix(1,2) M:" << endl << M;
Matrix<double>* Mblock = new Matrix<double>(2, 3, "1 2 3 4 5 6");
M.set_block(0, 0, Mblock);
M.resize_block_row(0, Mblock->row_dimension());
M.resize_block_column(0, Mblock->column_dimension());
Mblock = new Matrix<double>(2, 2, "7 8 9 10");
M.set_block(0, 1, Mblock);
M.resize_block_column(1, Mblock->column_dimension());
cout << "- the same block matrix M after 2 * set_block(0,*,*):" << endl << M;
BlockMatrix<double>* Mcopy = new BlockMatrix<double>(M);
BlockMatrix<double>* Mcopy2 = new BlockMatrix<double>(*Mcopy);
delete Mcopy;
cout << "- testing copy constructor:" << endl << (*Mcopy2);
delete Mcopy2;
Vector<double> x(5, "1 2 3 4 5"), y(2);
M.apply(x, y);
cout << "- a vector x=" << x << ", Mx=" << y << endl;
MatrixBlock<double>* MT = M.clone_transposed();
cout << "- M^T:" << endl;
MT->print(cout);
delete MT;
x.resize(2);
x[0] = 1;
x[1] = 2;
y.resize(5);
M.apply_transposed(x, y);
cout << "- a vector x=" << x << ", (M^T)x=" << y << endl;
BlockMatrix<double> B(2,3), C(3,3);
Matrix<double>* B00 = new Matrix<double>(1, 1, "1");
B.set_block(0, 0, B00);
Matrix<double>* B01 = new Matrix<double>(1, 1, "2");
B.set_block(0, 1, B01);
// Matrix<double>* B02 = new Matrix<double>(1, 1, "3");
// B.set_block(0, 2, B02);
Matrix<double>* B10 = new Matrix<double>(1, 1, "4");
B.set_block(1, 0, B10);
Matrix<double>* B11 = new Matrix<double>(1, 1, "5");
B.set_block(1, 1, B11);
Matrix<double>* B12 = new Matrix<double>(1, 1, "6");
B.set_block(1, 2, B12);
cout << " - a BlockMatrix B:" << endl << B;
// Matrix<double>* C00 = new Matrix<double>(1, 1, "1");
// C.set_block(0, 0, C00);
Matrix<double>* C01 = new Matrix<double>(1, 1, "2");
C.set_block(0, 1, C01);
Matrix<double>* C02 = new Matrix<double>(1, 1, "3");
C.set_block(0, 2, C02);
Matrix<double>* C10 = new Matrix<double>(1, 1, "4");
C.set_block(1, 0, C10);
Matrix<double>* C11 = new Matrix<double>(1, 1, "5");
C.set_block(1, 1, C11);
Matrix<double>* C12 = new Matrix<double>(1, 1, "6");
C.set_block(1, 2, C12);
Matrix<double>* C20 = new Matrix<double>(1, 1, "7");
C.set_block(2, 0, C20);
Matrix<double>* C21 = new Matrix<double>(1, 1, "8");
C.set_block(2, 1, C21);
Matrix<double>* C22 = new Matrix<double>(1, 1, "9");
C.set_block(2, 2, C22);
cout << " - a BlockMatrix C:" << endl << C;
cout << "- B*C=" << endl << B*C;
return 0;
}
<commit_msg>test also the alternative transpose() routine<commit_after>#include <iostream>
#include <list>
#include <string>
#include <algebra/block_matrix.h>
#include <algebra/matrix.h>
#include <algebra/vector.h>
using std::cout;
using std::endl;
using namespace MathTL;
int main()
{
cout << "Testing the class BlockMatrix ..." << endl;
BlockMatrix<double> defaultM;
cout << "- a default block matrix:" << endl << defaultM;
BlockMatrix<double> N(1);
cout << "- a BlockMatrix(1):" << endl << N;
BlockMatrix<double> M(1,2);
cout << "- a BlockMatrix(1,2) M:" << endl << M;
Matrix<double>* Mblock = new Matrix<double>(2, 3, "1 2 3 4 5 6");
M.set_block(0, 0, Mblock);
M.resize_block_row(0, Mblock->row_dimension());
M.resize_block_column(0, Mblock->column_dimension());
Mblock = new Matrix<double>(2, 2, "7 8 9 10");
M.set_block(0, 1, Mblock);
M.resize_block_column(1, Mblock->column_dimension());
cout << "- the same block matrix M after 2 * set_block(0,*,*):" << endl << M;
BlockMatrix<double>* Mcopy = new BlockMatrix<double>(M);
BlockMatrix<double>* Mcopy2 = new BlockMatrix<double>(*Mcopy);
delete Mcopy;
cout << "- testing copy constructor:" << endl << (*Mcopy2);
delete Mcopy2;
Vector<double> x(5, "1 2 3 4 5"), y(2);
M.apply(x, y);
cout << "- a vector x=" << x << ", Mx=" << y << endl;
cout << "- M^T:" << endl << transpose(M);
x.resize(2);
x[0] = 1;
x[1] = 2;
y.resize(5);
M.apply_transposed(x, y);
cout << "- a vector x=" << x << ", (M^T)x=" << y << endl;
BlockMatrix<double> B(2,3), C(3,3);
Matrix<double>* B00 = new Matrix<double>(1, 1, "1");
B.set_block(0, 0, B00);
Matrix<double>* B01 = new Matrix<double>(1, 1, "2");
B.set_block(0, 1, B01);
// Matrix<double>* B02 = new Matrix<double>(1, 1, "3");
// B.set_block(0, 2, B02);
Matrix<double>* B10 = new Matrix<double>(1, 1, "4");
B.set_block(1, 0, B10);
Matrix<double>* B11 = new Matrix<double>(1, 1, "5");
B.set_block(1, 1, B11);
Matrix<double>* B12 = new Matrix<double>(1, 1, "6");
B.set_block(1, 2, B12);
cout << " - a BlockMatrix B:" << endl << B;
// Matrix<double>* C00 = new Matrix<double>(1, 1, "1");
// C.set_block(0, 0, C00);
Matrix<double>* C01 = new Matrix<double>(1, 1, "2");
C.set_block(0, 1, C01);
Matrix<double>* C02 = new Matrix<double>(1, 1, "3");
C.set_block(0, 2, C02);
Matrix<double>* C10 = new Matrix<double>(1, 1, "4");
C.set_block(1, 0, C10);
Matrix<double>* C11 = new Matrix<double>(1, 1, "5");
C.set_block(1, 1, C11);
Matrix<double>* C12 = new Matrix<double>(1, 1, "6");
C.set_block(1, 2, C12);
Matrix<double>* C20 = new Matrix<double>(1, 1, "7");
C.set_block(2, 0, C20);
Matrix<double>* C21 = new Matrix<double>(1, 1, "8");
C.set_block(2, 1, C21);
Matrix<double>* C22 = new Matrix<double>(1, 1, "9");
C.set_block(2, 2, C22);
cout << " - a BlockMatrix C:" << endl << C;
cout << "- B*C=" << endl << B*C;
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2008, Google Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
// Walk a KML NetworkLink hierarchy.
// Fetches and parses the NetworkLinks in a given file recursively.
// Prints a count of the number of KML files fetched and the total number
// of each kind of Feature in the hierachy.
#include <iostream>
#include <map>
#include <string>
#include "boost/scoped_ptr.hpp"
#include "kml/dom.h"
#include "kml/dom/xsd.h" // TODO: expose Xsd::ElementName() properly
#include "kml/engine.h"
#include "curlfetch.h"
using kmldom::ElementPtr;
using kmldom::FeaturePtr;
using kmldom::NetworkLinkPtr;
using kmldom::OverlayPtr;
using kmlengine::KmlFile;
using kmlengine::KmzCache;
using std::cout;
using std::endl;
static void CountFeature(int type_id);
static void PrintFeatureCounts();
static void PrintFileCount();
static void WalkFile(const std::string& url, KmzCache* kmz_cache);
static int file_count;
static void PrintFileCount() {
cout << "files " << file_count << endl;
}
typedef std::map<int,int> feature_counter_t;
feature_counter_t feature_counter;
static void CountFeature(int type_id) {
feature_counter_t::const_iterator entry = feature_counter.find(type_id);
if (entry == feature_counter.end()) {
feature_counter[type_id] = 1;
} else {
++feature_counter[type_id];
}
}
static void PrintFeatureCounts() {
for (feature_counter_t::const_iterator iter = feature_counter.begin();
iter != feature_counter.end(); ++iter) {
std::string element_name;
cout << kmldom::Xsd::GetSchema()->ElementName(iter->first) << " "
<< iter->second << endl;
}
}
class FeatureCounter : public kmlengine::FeatureVisitor {
public:
FeatureCounter(const KmlFile& kml_file, KmzCache* kmz_cache)
: kml_file_(kml_file), kmz_cache_(kmz_cache) {}
virtual void VisitFeature(const kmldom::FeaturePtr& feature) {
CountFeature(feature->Type());
if (OverlayPtr overlay = AsOverlay(feature)) {
std::string href;
if (kmlengine::GetIconParentHref(overlay, &href)) {
std::string url;
if (kmlengine::ResolveUri(kml_file_.get_url(), href, &url)) {
std::string data;
if (!kmz_cache_->FetchUrl(url.c_str(), &data)) {
cout << "fetch failed " << url << endl;
return;
}
cout << href << " bytes " << data.size() << endl;
}
}
}
}
private:
const KmlFile& kml_file_;
KmzCache* kmz_cache_;
};
static void HandleFile(const KmlFile& kml_file, KmzCache* kmz_cache) {
FeatureCounter feature_counter(kml_file, kmz_cache);
kmlengine::VisitFeatureHierarchy(kmlengine::GetRootFeature(kml_file.root()),
feature_counter);
}
static void WalkNetworkLinks(const KmlFile& kml_file, KmzCache* kmz_cache) {
const kmlengine::ElementVector& link_vector =
kml_file.get_link_parent_vector();
for (size_t i = 0; i < link_vector.size(); ++i) {
if (NetworkLinkPtr networklink = AsNetworkLink(link_vector[i])) {
std::string href;
if (kmlengine::GetLinkParentHref(networklink, &href)) {
std::string url;
if (kmlengine::ResolveUri(kml_file.get_url(), href, &url)) {
WalkFile(url, kmz_cache);
}
}
}
}
}
static void WalkFile(const std::string& url, KmzCache* kmz_cache) {
cout << url << endl;
std::string kml;
if (!kmz_cache->FetchUrl(url.c_str(), &kml)) {
cout << "fetch failed " << url << endl;
return;
}
// Parse it.
std::string errors;
boost::scoped_ptr<KmlFile> kml_file(KmlFile::CreateFromParse(kml, &errors));
if (!kml_file.get()) {
cout << "parse failed " << url << endl;
cout << errors;
return;
}
kml_file->set_url(url);
++file_count;
HandleFile(*kml_file.get(), kmz_cache);
WalkNetworkLinks(*kml_file.get(), kmz_cache);
}
int main(int argc, char** argv) {
if (argc != 2) {
cout << "usage: " << argv[0] << " url" << endl;
return 1;
}
const char* url = argv[1];
KmzCache kmz_cache(CurlToString, 30);
WalkFile(url, &kmz_cache);
PrintFileCount();
PrintFeatureCounts();
}
<commit_msg>Use KmlFilePtr<commit_after>// Copyright 2008, Google Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
// Walk a KML NetworkLink hierarchy.
// Fetches and parses the NetworkLinks in a given file recursively.
// Prints a count of the number of KML files fetched and the total number
// of each kind of Feature in the hierachy.
#include <iostream>
#include <map>
#include <string>
#include "kml/dom.h"
#include "kml/dom/xsd.h" // TODO: expose Xsd::ElementName() properly
#include "kml/engine.h"
#include "curlfetch.h"
using kmldom::ElementPtr;
using kmldom::FeaturePtr;
using kmldom::NetworkLinkPtr;
using kmldom::OverlayPtr;
using kmlengine::KmlFile;
using kmlengine::KmlFilePtr;
using kmlengine::KmzCache;
using std::cout;
using std::endl;
static void CountFeature(int type_id);
static void PrintFeatureCounts();
static void PrintFileCount();
static void WalkFile(const std::string& url, KmzCache* kmz_cache);
static int file_count;
static void PrintFileCount() {
cout << "files " << file_count << endl;
}
typedef std::map<int,int> feature_counter_t;
feature_counter_t feature_counter;
static void CountFeature(int type_id) {
feature_counter_t::const_iterator entry = feature_counter.find(type_id);
if (entry == feature_counter.end()) {
feature_counter[type_id] = 1;
} else {
++feature_counter[type_id];
}
}
static void PrintFeatureCounts() {
for (feature_counter_t::const_iterator iter = feature_counter.begin();
iter != feature_counter.end(); ++iter) {
std::string element_name;
cout << kmldom::Xsd::GetSchema()->ElementName(iter->first) << " "
<< iter->second << endl;
}
}
class FeatureCounter : public kmlengine::FeatureVisitor {
public:
FeatureCounter(const KmlFilePtr& kml_file, KmzCache* kmz_cache)
: kml_file_(kml_file), kmz_cache_(kmz_cache) {}
virtual void VisitFeature(const kmldom::FeaturePtr& feature) {
CountFeature(feature->Type());
if (OverlayPtr overlay = AsOverlay(feature)) {
std::string href;
if (kmlengine::GetIconParentHref(overlay, &href)) {
std::string url;
if (kmlengine::ResolveUri(kml_file_->get_url(), href, &url)) {
std::string data;
if (!kmz_cache_->FetchUrl(url.c_str(), &data)) {
cout << "fetch failed " << url << endl;
return;
}
cout << href << " bytes " << data.size() << endl;
}
}
}
}
private:
const KmlFilePtr kml_file_;
KmzCache* kmz_cache_;
};
static void HandleFile(const KmlFilePtr& kml_file, KmzCache* kmz_cache) {
FeatureCounter feature_counter(kml_file, kmz_cache);
kmlengine::VisitFeatureHierarchy(kmlengine::GetRootFeature(kml_file->root()),
feature_counter);
}
static void WalkNetworkLinks(const KmlFilePtr& kml_file, KmzCache* kmz_cache) {
const kmlengine::ElementVector& link_vector =
kml_file->get_link_parent_vector();
for (size_t i = 0; i < link_vector.size(); ++i) {
if (NetworkLinkPtr networklink = AsNetworkLink(link_vector[i])) {
std::string href;
if (kmlengine::GetLinkParentHref(networklink, &href)) {
std::string url;
if (kmlengine::ResolveUri(kml_file->get_url(), href, &url)) {
WalkFile(url, kmz_cache);
}
}
}
}
}
static void WalkFile(const std::string& url, KmzCache* kmz_cache) {
cout << url << endl;
std::string kml;
if (!kmz_cache->FetchUrl(url.c_str(), &kml)) {
cout << "fetch failed " << url << endl;
return;
}
// Parse it.
std::string errors;
KmlFilePtr kml_file = KmlFile::CreateFromParse(kml, &errors);
if (!kml_file) {
cout << "parse failed " << url << endl;
cout << errors;
return;
}
kml_file->set_url(url);
++file_count;
HandleFile(kml_file, kmz_cache);
WalkNetworkLinks(kml_file, kmz_cache);
}
int main(int argc, char** argv) {
if (argc != 2) {
cout << "usage: " << argv[0] << " url" << endl;
return 1;
}
const char* url = argv[1];
KmzCache kmz_cache(CurlToString, 30);
WalkFile(url, &kmz_cache);
PrintFileCount();
PrintFeatureCounts();
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//////////////////////////////////////////////////////////////////////////
// commodity.cc
#include "stdsneezy.h"
#include "shop.h"
#include "obj_commodity.h"
#include "shopowned.h"
TCommodity::TCommodity() :
TObj()
{
}
TCommodity::TCommodity(const TCommodity &a) :
TObj(a)
{
}
TCommodity & TCommodity::operator=(const TCommodity &a)
{
if (this == &a) return *this;
TObj::operator=(a);
return *this;
}
TCommodity::~TCommodity()
{
}
void TCommodity::assignFourValues(int, int, int, int)
{
}
void TCommodity::getFourValues(int *x1, int *x2, int *x3, int *x4) const
{
*x1 = 0;
*x2 = 0;
*x3 = 0;
*x4 = 0;
}
sstring TCommodity::statObjInfo() const
{
sstring a("");
return a;
}
void TCommodity::lowCheck()
{
if (!isname("commodity", name)) {
vlogf(LOG_LOW, fmt("raw material without COMMODITY in name (%s : %d)") %
getName() % objVnum());
}
if (!numUnits()) {
vlogf(LOG_LOW, fmt("raw material needs weight above 0.0 (%s : %d)") %
getName() % objVnum());
}
if (!pricePerUnit()) {
vlogf(LOG_LOW, fmt("raw material needs price above 0 (%s : %d)") %
getName() % objVnum());
}
TObj::lowCheck();
}
int TCommodity::sellPrice(int num, int shop_nr, float, const TBeing *ch)
{
float cost_per;
int price;
cost_per = pricePerUnit();
price = (int) (numUnits() * cost_per * shop_index[shop_nr].getProfitSell(this,ch));
if (obj_flags.cost <= 1) {
price = max(0, price);
} else {
price = max(1, price);
}
return price;
}
int TCommodity::shopPrice(int num, int shop_nr, float, const TBeing *ch) const
{
float cost_per;
int price;
cost_per = pricePerUnit();
price = (int) (num * cost_per * shop_index[shop_nr].getProfitBuy(this, ch));
price = max(1, price);
return price;
}
int TCommodity::buyMe(TBeing *ch, TMonster *keeper, int num, int shop_nr)
{
char buf[256];
char buf2[80];
int price, vnum;
float cost_per;
TObj *obj2;
if (parent != keeper) {
vlogf(LOG_BUG, "Error: buy_treasure():shop.cc obj not on keeper");
return -1;
}
if (!shop_index[shop_nr].willBuy(this)) {
keeper->doTell(ch->getName(), shop_index[shop_nr].do_not_buy);
return -1;
}
if (num > (int) (numUnits())) {
num = (int) (numUnits());
keeper->doTell(ch->getName(), fmt("I don't have that much %s. Here's the %d that I do have.") % fname(name) % num);
}
cost_per = pricePerUnit();
price = shopPrice(num, shop_nr, -1, ch);
vnum = objVnum();
if (ch->getMoney() < price) {
keeper->doTell(ch->name, shop_index[shop_nr].missing_cash2);
switch (shop_index[shop_nr].temper1) {
case 0:
keeper->doAction(ch->name, CMD_SMILE);
return -1;
case 1:
act("$n grins happily.", 0, keeper, 0, 0, TO_ROOM);
return -1;
default:
return -1;
}
}
strcpy(buf2, fname(name).c_str());
--(*this);
int num2 = (int) (numUnits()) - num;
if (num2) {
setWeight(num2/10.0);
*keeper += *this;
} else {
delete this;
}
if (num) {
obj2 = read_object(vnum, VIRTUAL);
obj2->setWeight(num/10.0);
*ch += *obj2;
keeper->doTell(ch->getName(), fmt("Here ya go. That's %d units of %s.") %
num % buf2);
act("$n buys $p.", TRUE, ch, obj2, keeper, TO_NOTVICT);
TShopOwned tso(shop_nr, keeper, ch);
tso.doBuyTransaction(price, getName(), TX_BUYING, obj2);
} else {
// this happens with sub zero weight components
vlogf(LOG_BUG, fmt("Bogus num %d in buyMe component at %d. wgt=%.2f") % num % ch->in_room % getWeight());
}
sprintf(buf, "%s/%d", SHOPFILE_PATH, shop_nr);
keeper->saveItems(buf);
ch->doSave(SILENT_YES);
return price;
}
void TCommodity::sellMe(TBeing *ch, TMonster *keeper, int shop_nr, int)
{
TThing *t;
TCommodity *obj2 = NULL;
int num, price;
char buf[256], buf2[80];
strcpy(buf2, fname(name).c_str());
price = sellPrice(1, shop_nr, -1, ch);
if (isObjStat(ITEM_NODROP)) {
ch->sendTo("You can't let go of it, it must be CURSED!\n\r");
return;
}
if (isObjStat(ITEM_PROTOTYPE)) {
ch->sendTo("That's a prototype, no selling that!\n\r");
return;
}
if (will_not_buy(ch, keeper, this, shop_nr))
return;
if (!shop_index[shop_nr].willBuy(this)) {
keeper->doTell(ch->getName(), shop_index[shop_nr].do_not_buy);
return;
}
if (keeper->getMoney() < price) {
keeper->doTell(ch->getName(), shop_index[shop_nr].missing_cash1);
return;
}
for (t = keeper->getStuff(); t; t = t->nextThing) {
obj2 = dynamic_cast<TCommodity *>(t);
if (!obj2)
continue;
if (obj2->objVnum() == objVnum())
break;
}
if (!t) {
TObj *to = read_object(objVnum(), VIRTUAL);
obj2 = dynamic_cast<TCommodity *>(to);
obj2->setWeight(0.0);
} else
--(*obj2);
num = obj2->numUnits() + numUnits();
num = max(min(num, 10000), 0);
if (num) {
obj2->setWeight(num/10.0);
*keeper += *obj2;
--(*this);
TShopOwned tso(shop_nr, keeper, ch);
tso.doSellTransaction(price, obj2->getName(), TX_SELLING, obj2);
keeper->doTell(ch->getName(), fmt("Thanks, here's your %d talens.") % price);
act("$n sells $p.", TRUE, ch, this, 0, TO_ROOM);
if (ch->isAffected(AFF_GROUP) && ch->desc &&
IS_SET(ch->desc->autobits, AUTO_SPLIT) &&
(ch->master || ch->followers)){
sprintf(buf, "%d", price);
ch->doSplit(buf, false);
}
delete this;
}
if (!ch->delaySave)
ch->doSave(SILENT_YES);
sprintf(buf, "%s/%d", SHOPFILE_PATH, shop_nr);
keeper->saveItems(buf);
return;
}
int TCommodity::sellCommod(TBeing *ch, TMonster *keeper, int shop_nr, TThing *bag)
{
int rc;
if (equippedBy)
*ch += *ch->unequip(eq_pos);
if (bag && bag != ch) {
rc = get(ch, this, bag, GETOBJOBJ, true);
if (IS_SET_DELETE(rc, DELETE_ITEM)) {
return DELETE_THIS;
}
if (IS_SET_DELETE(rc, DELETE_VICT)) {
return DELETE_ITEM;
}
if (IS_SET_DELETE(rc, DELETE_THIS)) {
return DELETE_VICT;
}
if (!dynamic_cast<TBeing *>(parent)) {
// could fail on volume or sumthing
return FALSE;
}
}
sellMe(ch, keeper, shop_nr, 1);
return FALSE;
}
void TCommodity::valueMe(TBeing *ch, TMonster *keeper, int shop_nr, int)
{
int price;
char buf2[80];
strcpy(buf2, fname(name).c_str());
price = sellPrice(1, shop_nr, -1, ch);
if (!shop_index[shop_nr].willBuy(this)) {
keeper->doTell(ch->getName(), shop_index[shop_nr].do_not_buy);
return;
}
keeper->doTell(ch->getName(), fmt("Hmm, I'd give you %d talens for that.") % price);
return;
}
const sstring TCommodity::shopList(const TBeing *ch, const sstring &arg, int min_amt, int max_amt, int, int, int k, unsigned long int) const
{
char buf[256];
float cost = pricePerUnit();
sprintf(buf, "[%2d] COMMODITY: %-20.20s : %5d units %.2f talens (per unit)\n\r",
k + 1, material_nums[getMaterial()].mat_name,
(int) (numUnits()), cost);
if (arg.empty() && min_amt == 999999) /* everything */
/* specific item */
return buf;
else if (isname(arg, name) && min_amt == 999999)
return buf;
/* specific item and specific cost */
else if (isname(arg, name) && cost >= min_amt && cost <= max_amt)
return buf;
else if (arg.empty() && cost >= min_amt && cost <= max_amt) /* specific cost */
return buf;
else
return "";
}
int TCommodity::numUnits() const
{
return (int) (10.0 * getWeight());
}
float TCommodity::pricePerUnit() const
{
/*
if(!material_nums[getMaterial()].price)
vlogf(LOG_BUG, fmt("commodity '%s' has no price for material %i") %
getName() % getMaterial());
*/
return material_nums[getMaterial()].price;
}
int TCommodity::getSizeIndex() const
{
int weight=numUnits();
if(weight<=2){
return 0;
} else if(weight<=4){
return 1;
} else if(weight<=6){
return 2;
} else if(weight<=8){
return 3;
} else if(weight<=10){
return 4;
} else if(weight<=15){
return 5;
} else {
return 6;
}
}
void TCommodity::updateDesc()
{
int sizeindex=getSizeIndex();
char buf[256];
const char *metalname [] =
{
"bit",
"nugget",
"ingot",
"sovereign",
"rod",
"bar",
"pile"
};
const char *mineralname [] =
{
"tiny piece",
"small piece",
"piece",
"large piece",
"huge piece",
"gigantic piece",
"massive piece"
};
if (isObjStat(ITEM_STRUNG)) {
delete [] name;
delete [] shortDescr;
delete [] descr;
extraDescription *exd;
while ((exd = ex_description)) {
ex_description = exd->next;
delete exd;
}
ex_description = NULL;
delete [] action_description;
action_description = NULL;
} else {
addObjStat(ITEM_STRUNG);
ex_description = NULL;
action_description = NULL;
}
if(isMineral()){
sprintf(buf, (fmt("commodity %s %s") % mineralname[sizeindex] %
material_nums[getMaterial()].mat_name).c_str());
name = mud_str_dup(buf);
sprintf(buf, (fmt("a %s of rough %s") % mineralname[sizeindex] %
material_nums[getMaterial()].mat_name).c_str());
shortDescr = mud_str_dup(buf);
sprintf(buf, (fmt("A %s of rough %s has been left here. What luck!") %
mineralname[sizeindex] %
material_nums[getMaterial()].mat_name).c_str());
setDescr(mud_str_dup(buf));
} else {
sprintf(buf, (fmt("commodity %s %s") % metalname[sizeindex] %
material_nums[getMaterial()].mat_name).c_str());
name = mud_str_dup(buf);
sprintf(buf, (fmt("a %s of %s") % metalname[sizeindex] %
material_nums[getMaterial()].mat_name).c_str());
shortDescr = mud_str_dup(buf);
sprintf(buf, (fmt("A %s of %s has been left here. What luck!") %
metalname[sizeindex] %
material_nums[getMaterial()].mat_name).c_str());
setDescr(mud_str_dup(buf));
}
obj_flags.cost = suggestedPrice();
}
int TCommodity::suggestedPrice() const
{
return (int)(numUnits() * pricePerUnit());
};
void TCommodity::setWeight(const float w)
{
TObj::setWeight(w);
// if(!bootTime)
updateDesc();
}
void TCommodity::setMaterial(ubyte num)
{
TObj::setMaterial(num);
// if(!bootTime)
updateDesc();
}
<commit_msg>fixed commodity shop code distinguishing commods based on vnum instead of mat<commit_after>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//////////////////////////////////////////////////////////////////////////
// commodity.cc
#include "stdsneezy.h"
#include "shop.h"
#include "obj_commodity.h"
#include "shopowned.h"
TCommodity::TCommodity() :
TObj()
{
}
TCommodity::TCommodity(const TCommodity &a) :
TObj(a)
{
}
TCommodity & TCommodity::operator=(const TCommodity &a)
{
if (this == &a) return *this;
TObj::operator=(a);
return *this;
}
TCommodity::~TCommodity()
{
}
void TCommodity::assignFourValues(int, int, int, int)
{
}
void TCommodity::getFourValues(int *x1, int *x2, int *x3, int *x4) const
{
*x1 = 0;
*x2 = 0;
*x3 = 0;
*x4 = 0;
}
sstring TCommodity::statObjInfo() const
{
sstring a("");
return a;
}
void TCommodity::lowCheck()
{
if (!isname("commodity", name)) {
vlogf(LOG_LOW, fmt("raw material without COMMODITY in name (%s : %d)") %
getName() % objVnum());
}
if (!numUnits()) {
vlogf(LOG_LOW, fmt("raw material needs weight above 0.0 (%s : %d)") %
getName() % objVnum());
}
if (!pricePerUnit()) {
vlogf(LOG_LOW, fmt("raw material needs price above 0 (%s : %d)") %
getName() % objVnum());
}
TObj::lowCheck();
}
int TCommodity::sellPrice(int num, int shop_nr, float, const TBeing *ch)
{
float cost_per;
int price;
cost_per = pricePerUnit();
price = (int) (numUnits() * cost_per * shop_index[shop_nr].getProfitSell(this,ch));
if (obj_flags.cost <= 1) {
price = max(0, price);
} else {
price = max(1, price);
}
return price;
}
int TCommodity::shopPrice(int num, int shop_nr, float, const TBeing *ch) const
{
float cost_per;
int price;
cost_per = pricePerUnit();
price = (int) (num * cost_per * shop_index[shop_nr].getProfitBuy(this, ch));
price = max(1, price);
return price;
}
int TCommodity::buyMe(TBeing *ch, TMonster *keeper, int num, int shop_nr)
{
char buf[256];
char buf2[80];
int price, vnum;
float cost_per;
TObj *obj2;
if (parent != keeper) {
vlogf(LOG_BUG, "Error: buy_treasure():shop.cc obj not on keeper");
return -1;
}
if (!shop_index[shop_nr].willBuy(this)) {
keeper->doTell(ch->getName(), shop_index[shop_nr].do_not_buy);
return -1;
}
if (num > (int) (numUnits())) {
num = (int) (numUnits());
keeper->doTell(ch->getName(), fmt("I don't have that much %s. Here's the %d that I do have.") % fname(name) % num);
}
cost_per = pricePerUnit();
price = shopPrice(num, shop_nr, -1, ch);
vnum = objVnum();
if (ch->getMoney() < price) {
keeper->doTell(ch->name, shop_index[shop_nr].missing_cash2);
switch (shop_index[shop_nr].temper1) {
case 0:
keeper->doAction(ch->name, CMD_SMILE);
return -1;
case 1:
act("$n grins happily.", 0, keeper, 0, 0, TO_ROOM);
return -1;
default:
return -1;
}
}
strcpy(buf2, fname(name).c_str());
--(*this);
int num2 = (int) (numUnits()) - num;
if (num2) {
setWeight(num2/10.0);
*keeper += *this;
} else {
delete this;
}
if (num) {
obj2 = read_object(vnum, VIRTUAL);
obj2->setWeight(num/10.0);
*ch += *obj2;
keeper->doTell(ch->getName(), fmt("Here ya go. That's %d units of %s.") %
num % buf2);
act("$n buys $p.", TRUE, ch, obj2, keeper, TO_NOTVICT);
TShopOwned tso(shop_nr, keeper, ch);
tso.doBuyTransaction(price, getName(), TX_BUYING, obj2);
} else {
// this happens with sub zero weight components
vlogf(LOG_BUG, fmt("Bogus num %d in buyMe component at %d. wgt=%.2f") % num % ch->in_room % getWeight());
}
sprintf(buf, "%s/%d", SHOPFILE_PATH, shop_nr);
keeper->saveItems(buf);
ch->doSave(SILENT_YES);
return price;
}
void TCommodity::sellMe(TBeing *ch, TMonster *keeper, int shop_nr, int)
{
TThing *t;
TCommodity *obj2 = NULL;
int num, price;
char buf[256], buf2[80];
strcpy(buf2, fname(name).c_str());
price = sellPrice(1, shop_nr, -1, ch);
if (isObjStat(ITEM_NODROP)) {
ch->sendTo("You can't let go of it, it must be CURSED!\n\r");
return;
}
if (isObjStat(ITEM_PROTOTYPE)) {
ch->sendTo("That's a prototype, no selling that!\n\r");
return;
}
if (will_not_buy(ch, keeper, this, shop_nr))
return;
if (!shop_index[shop_nr].willBuy(this)) {
keeper->doTell(ch->getName(), shop_index[shop_nr].do_not_buy);
return;
}
if (keeper->getMoney() < price) {
keeper->doTell(ch->getName(), shop_index[shop_nr].missing_cash1);
return;
}
for (t = keeper->getStuff(); t; t = t->nextThing) {
obj2 = dynamic_cast<TCommodity *>(t);
if (!obj2)
continue;
if (obj2->getMaterial() == getMaterial())
break;
}
if (!t) {
TObj *to = read_object(objVnum(), VIRTUAL);
obj2 = dynamic_cast<TCommodity *>(to);
obj2->setWeight(0.0);
} else
--(*obj2);
num = obj2->numUnits() + numUnits();
num = max(min(num, 10000), 0);
if (num) {
obj2->setWeight(num/10.0);
*keeper += *obj2;
--(*this);
TShopOwned tso(shop_nr, keeper, ch);
tso.doSellTransaction(price, obj2->getName(), TX_SELLING, obj2);
keeper->doTell(ch->getName(), fmt("Thanks, here's your %d talens.") % price);
act("$n sells $p.", TRUE, ch, this, 0, TO_ROOM);
if (ch->isAffected(AFF_GROUP) && ch->desc &&
IS_SET(ch->desc->autobits, AUTO_SPLIT) &&
(ch->master || ch->followers)){
sprintf(buf, "%d", price);
ch->doSplit(buf, false);
}
delete this;
}
if (!ch->delaySave)
ch->doSave(SILENT_YES);
sprintf(buf, "%s/%d", SHOPFILE_PATH, shop_nr);
keeper->saveItems(buf);
return;
}
int TCommodity::sellCommod(TBeing *ch, TMonster *keeper, int shop_nr, TThing *bag)
{
int rc;
if (equippedBy)
*ch += *ch->unequip(eq_pos);
if (bag && bag != ch) {
rc = get(ch, this, bag, GETOBJOBJ, true);
if (IS_SET_DELETE(rc, DELETE_ITEM)) {
return DELETE_THIS;
}
if (IS_SET_DELETE(rc, DELETE_VICT)) {
return DELETE_ITEM;
}
if (IS_SET_DELETE(rc, DELETE_THIS)) {
return DELETE_VICT;
}
if (!dynamic_cast<TBeing *>(parent)) {
// could fail on volume or sumthing
return FALSE;
}
}
sellMe(ch, keeper, shop_nr, 1);
return FALSE;
}
void TCommodity::valueMe(TBeing *ch, TMonster *keeper, int shop_nr, int)
{
int price;
char buf2[80];
strcpy(buf2, fname(name).c_str());
price = sellPrice(1, shop_nr, -1, ch);
if (!shop_index[shop_nr].willBuy(this)) {
keeper->doTell(ch->getName(), shop_index[shop_nr].do_not_buy);
return;
}
keeper->doTell(ch->getName(), fmt("Hmm, I'd give you %d talens for that.") % price);
return;
}
const sstring TCommodity::shopList(const TBeing *ch, const sstring &arg, int min_amt, int max_amt, int, int, int k, unsigned long int) const
{
char buf[256];
float cost = pricePerUnit();
sprintf(buf, "[%2d] COMMODITY: %-20.20s : %5d units %.2f talens (per unit)\n\r",
k + 1, material_nums[getMaterial()].mat_name,
(int) (numUnits()), cost);
if (arg.empty() && min_amt == 999999) /* everything */
/* specific item */
return buf;
else if (isname(arg, name) && min_amt == 999999)
return buf;
/* specific item and specific cost */
else if (isname(arg, name) && cost >= min_amt && cost <= max_amt)
return buf;
else if (arg.empty() && cost >= min_amt && cost <= max_amt) /* specific cost */
return buf;
else
return "";
}
int TCommodity::numUnits() const
{
return (int) (10.0 * getWeight());
}
float TCommodity::pricePerUnit() const
{
/*
if(!material_nums[getMaterial()].price)
vlogf(LOG_BUG, fmt("commodity '%s' has no price for material %i") %
getName() % getMaterial());
*/
return material_nums[getMaterial()].price;
}
int TCommodity::getSizeIndex() const
{
int weight=numUnits();
if(weight<=2){
return 0;
} else if(weight<=4){
return 1;
} else if(weight<=6){
return 2;
} else if(weight<=8){
return 3;
} else if(weight<=10){
return 4;
} else if(weight<=15){
return 5;
} else {
return 6;
}
}
void TCommodity::updateDesc()
{
int sizeindex=getSizeIndex();
char buf[256];
const char *metalname [] =
{
"bit",
"nugget",
"ingot",
"sovereign",
"rod",
"bar",
"pile"
};
const char *mineralname [] =
{
"tiny piece",
"small piece",
"piece",
"large piece",
"huge piece",
"gigantic piece",
"massive piece"
};
if (isObjStat(ITEM_STRUNG)) {
delete [] name;
delete [] shortDescr;
delete [] descr;
extraDescription *exd;
while ((exd = ex_description)) {
ex_description = exd->next;
delete exd;
}
ex_description = NULL;
delete [] action_description;
action_description = NULL;
} else {
addObjStat(ITEM_STRUNG);
ex_description = NULL;
action_description = NULL;
}
if(isMineral()){
sprintf(buf, (fmt("commodity %s %s") % mineralname[sizeindex] %
material_nums[getMaterial()].mat_name).c_str());
name = mud_str_dup(buf);
sprintf(buf, (fmt("a %s of rough %s") % mineralname[sizeindex] %
material_nums[getMaterial()].mat_name).c_str());
shortDescr = mud_str_dup(buf);
sprintf(buf, (fmt("A %s of rough %s has been left here. What luck!") %
mineralname[sizeindex] %
material_nums[getMaterial()].mat_name).c_str());
setDescr(mud_str_dup(buf));
} else {
sprintf(buf, (fmt("commodity %s %s") % metalname[sizeindex] %
material_nums[getMaterial()].mat_name).c_str());
name = mud_str_dup(buf);
sprintf(buf, (fmt("a %s of %s") % metalname[sizeindex] %
material_nums[getMaterial()].mat_name).c_str());
shortDescr = mud_str_dup(buf);
sprintf(buf, (fmt("A %s of %s has been left here. What luck!") %
metalname[sizeindex] %
material_nums[getMaterial()].mat_name).c_str());
setDescr(mud_str_dup(buf));
}
obj_flags.cost = suggestedPrice();
}
int TCommodity::suggestedPrice() const
{
return (int)(numUnits() * pricePerUnit());
};
void TCommodity::setWeight(const float w)
{
TObj::setWeight(w);
// if(!bootTime)
updateDesc();
}
void TCommodity::setMaterial(ubyte num)
{
TObj::setMaterial(num);
// if(!bootTime)
updateDesc();
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2012-, Open Perception, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) 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.
*
*/
#ifndef PCL_FILTERS_IMPL_NORMAL_SPACE_SAMPLE_H_
#define PCL_FILTERS_IMPL_NORMAL_SPACE_SAMPLE_H_
#include <pcl/filters/normal_space.h>
#include <pcl/common/io.h>
#include <vector>
#include <list>
///////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename NormalT> bool
pcl::NormalSpaceSampling<PointT, NormalT>::initCompute ()
{
if (!FilterIndices<PointT>::initCompute ())
return false;
// If sample size is 0 or if the sample size is greater then input cloud size then return entire copy of cloud
if (sample_ >= input_->size ())
{
PCL_ERROR ("[NormalSpaceSampling::initCompute] Requested more samples than the input cloud size: %d vs %zu\n",
sample_, input_->size ());
return false;
}
boost::mt19937 *rng = new boost::mt19937 (static_cast<unsigned int> (seed_));
boost::uniform_int<unsigned int> *uniform_distrib = new boost::uniform_int<unsigned int> (0, unsigned (input_->size ()));
rng_uniform_distribution_ = new boost::variate_generator<boost::mt19937, boost::uniform_int<unsigned int> > (*rng, *uniform_distrib);
return (true);
}
///////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename NormalT> void
pcl::NormalSpaceSampling<PointT, NormalT>::applyFilter (PointCloud &output)
{
std::vector<int> indices;
if (keep_organized_)
{
bool temp = extract_removed_indices_;
extract_removed_indices_ = true;
applyFilter (indices);
extract_removed_indices_ = temp;
output = *input_;
for (int rii = 0; rii < static_cast<int> (removed_indices_->size ()); ++rii) // rii = removed indices iterator
output.points[(*removed_indices_)[rii]].x = output.points[(*removed_indices_)[rii]].y = output.points[(*removed_indices_)[rii]].z = user_filter_value_;
if (!pcl_isfinite (user_filter_value_))
output.is_dense = false;
}
else
{
output.is_dense = true;
applyFilter (indices);
pcl::copyPointCloud (*input_, indices, output);
}
}
///////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename NormalT> bool
pcl::NormalSpaceSampling<PointT, NormalT>::isEntireBinSampled (boost::dynamic_bitset<> &array,
unsigned int start_index,
unsigned int length)
{
bool status = true;
for (unsigned int i = start_index; i < start_index + length; i++)
{
status = status & array.test (i);
}
return status;
}
///////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename NormalT> unsigned int
pcl::NormalSpaceSampling<PointT, NormalT>::findBin (const float *normal, unsigned int)
{
unsigned int bin_number = 0;
// Holds the bin numbers for direction cosines in x,y,z directions
unsigned int t[3] = {0,0,0};
// dcos is the direction cosine.
float dcos = 0.0;
float bin_size = 0.0;
// max_cos and min_cos are the maximum and minimum values of cos(theta) respectively
float max_cos = 1.0;
float min_cos = -1.0;
// dcos = cosf (normal[0]);
dcos = normal[0];
bin_size = (max_cos - min_cos) / static_cast<float> (binsx_);
// Finding bin number for direction cosine in x direction
unsigned int k = 0;
for (float i = min_cos; (i + bin_size) < (max_cos - bin_size); i += bin_size , k++)
{
if (dcos >= i && dcos <= (i+bin_size))
{
break;
}
}
t[0] = k;
// dcos = cosf (normal[1]);
dcos = normal[1];
bin_size = (max_cos - min_cos) / static_cast<float> (binsy_);
// Finding bin number for direction cosine in y direction
k = 0;
for (float i = min_cos; (i + bin_size) < (max_cos - bin_size); i += bin_size , k++)
{
if (dcos >= i && dcos <= (i+bin_size))
{
break;
}
}
t[1] = k;
// dcos = cosf (normal[2]);
dcos = normal[2];
bin_size = (max_cos - min_cos) / static_cast<float> (binsz_);
// Finding bin number for direction cosine in z direction
k = 0;
for (float i = min_cos; (i + bin_size) < (max_cos - bin_size); i += bin_size , k++)
{
if (dcos >= i && dcos <= (i+bin_size))
{
break;
}
}
t[2] = k;
bin_number = t[0] * (binsy_*binsz_) + t[1] * binsz_ + t[2];
return bin_number;
}
///////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename NormalT> void
pcl::NormalSpaceSampling<PointT, NormalT>::applyFilter (std::vector<int> &indices)
{
if (!initCompute ())
{
indices = *indices_;
return;
}
unsigned int max_values = (std::min) (sample_, static_cast<unsigned int> (input_normals_->size ()));
// Resize output indices to sample size
indices.resize (max_values);
removed_indices_->resize (max_values);
// Allocate memory for the histogram of normals. Normals will then be sampled from each bin.
unsigned int n_bins = binsx_ * binsy_ * binsz_;
// list<int> holds the indices of points in that bin. Using list to avoid repeated resizing of vectors.
// Helps when the point cloud is large.
std::vector<std::list <int> > normals_hg;
normals_hg.reserve (n_bins);
for (unsigned int i = 0; i < n_bins; i++)
normals_hg.push_back (std::list<int> ());
for (std::vector<int>::const_iterator it = indices_->begin (); it != indices_->end (); ++it)
{
unsigned int bin_number = findBin (input_normals_->points[*it].normal, n_bins);
normals_hg[bin_number].push_back (*it);
}
// Setting up random access for the list created above. Maintaining the iterators to individual elements of the list
// in a vector. Using vector now as the size of the list is known.
std::vector<std::vector<std::list<int>::iterator> > random_access (normals_hg.size ());
for (unsigned int i = 0; i < normals_hg.size (); i++)
{
random_access.push_back (std::vector<std::list<int>::iterator> ());
random_access[i].resize (normals_hg[i].size ());
unsigned int j = 0;
for (std::list<int>::iterator itr = normals_hg[i].begin (); itr != normals_hg[i].end (); itr++, j++)
random_access[i][j] = itr;
}
std::vector<unsigned int> start_index (normals_hg.size ());
start_index[0] = 0;
unsigned int prev_index = start_index[0];
for (unsigned int i = 1; i < normals_hg.size (); i++)
{
start_index[i] = prev_index + static_cast<unsigned int> (normals_hg[i-1].size ());
prev_index = start_index[i];
}
// Maintaining flags to check if a point is sampled
boost::dynamic_bitset<> is_sampled_flag (input_normals_->points.size ());
// Maintaining flags to check if all points in the bin are sampled
boost::dynamic_bitset<> bin_empty_flag (normals_hg.size ());
unsigned int i = 0;
while (i < sample_)
{
// Iterating through every bin and picking one point at random, until the required number of points are sampled.
for (unsigned int j = 0; j < normals_hg.size (); j++)
{
unsigned int M = static_cast<unsigned int> (normals_hg[j].size ());
if (M == 0 || bin_empty_flag.test (j)) // bin_empty_flag(i) is set if all points in that bin are sampled..
continue;
unsigned int pos = 0;
unsigned int random_index = 0;
// Picking up a sample at random from jth bin
do
{
random_index = static_cast<unsigned int> ((*rng_uniform_distribution_) () % M);
pos = start_index[j] + random_index;
} while (is_sampled_flag.test (pos));
is_sampled_flag.flip (start_index[j] + random_index);
// Checking if all points in bin j are sampled.
if (isEntireBinSampled (is_sampled_flag, start_index[j], static_cast<unsigned int> (normals_hg[j].size ())))
bin_empty_flag.flip (j);
unsigned int index = *(random_access[j][random_index]);
indices[i] = index;
i++;
if (i == sample_)
break;
}
}
// If we need to return the indices that we haven't sampled
if (extract_removed_indices_)
{
std::vector<int> indices_temp = indices;
std::sort (indices_temp.begin (), indices_temp.end ());
std::vector<int> all_indices_temp = *indices_;
std::sort (all_indices_temp.begin (), all_indices_temp.end ());
set_difference (all_indices_temp.begin (), all_indices_temp.end (),
indices_temp.begin (), indices_temp.end (),
inserter (*removed_indices_, removed_indices_->begin ()));
}
}
#define PCL_INSTANTIATE_NormalSpaceSampling(T,NT) template class PCL_EXPORTS pcl::NormalSpaceSampling<T,NT>;
#endif // PCL_FILTERS_IMPL_NORMAL_SPACE_SAMPLE_H_
<commit_msg>* Fixed memory leak in @NormalSpaceSampling@ -- why were we using pointers?<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2012-, Open Perception, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) 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.
*
*/
#ifndef PCL_FILTERS_IMPL_NORMAL_SPACE_SAMPLE_H_
#define PCL_FILTERS_IMPL_NORMAL_SPACE_SAMPLE_H_
#include <pcl/filters/normal_space.h>
#include <pcl/common/io.h>
#include <vector>
#include <list>
///////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename NormalT> bool
pcl::NormalSpaceSampling<PointT, NormalT>::initCompute ()
{
if (!FilterIndices<PointT>::initCompute ())
return false;
// If sample size is 0 or if the sample size is greater then input cloud size then return entire copy of cloud
if (sample_ >= input_->size ())
{
PCL_ERROR ("[NormalSpaceSampling::initCompute] Requested more samples than the input cloud size: %d vs %zu\n",
sample_, input_->size ());
return false;
}
boost::mt19937 rng (static_cast<unsigned int> (seed_));
boost::uniform_int<unsigned int> uniform_distrib (0, unsigned (input_->size ()));
if (rng_uniform_distribution_ != NULL)
delete rng_uniform_distribution_;
rng_uniform_distribution_ = new boost::variate_generator<boost::mt19937, boost::uniform_int<unsigned int> > (rng, uniform_distrib);
return (true);
}
///////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename NormalT> void
pcl::NormalSpaceSampling<PointT, NormalT>::applyFilter (PointCloud &output)
{
std::vector<int> indices;
if (keep_organized_)
{
bool temp = extract_removed_indices_;
extract_removed_indices_ = true;
applyFilter (indices);
extract_removed_indices_ = temp;
output = *input_;
for (int rii = 0; rii < static_cast<int> (removed_indices_->size ()); ++rii) // rii = removed indices iterator
output.points[(*removed_indices_)[rii]].x = output.points[(*removed_indices_)[rii]].y = output.points[(*removed_indices_)[rii]].z = user_filter_value_;
if (!pcl_isfinite (user_filter_value_))
output.is_dense = false;
}
else
{
output.is_dense = true;
applyFilter (indices);
pcl::copyPointCloud (*input_, indices, output);
}
}
///////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename NormalT> bool
pcl::NormalSpaceSampling<PointT, NormalT>::isEntireBinSampled (boost::dynamic_bitset<> &array,
unsigned int start_index,
unsigned int length)
{
bool status = true;
for (unsigned int i = start_index; i < start_index + length; i++)
{
status = status & array.test (i);
}
return status;
}
///////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename NormalT> unsigned int
pcl::NormalSpaceSampling<PointT, NormalT>::findBin (const float *normal, unsigned int)
{
unsigned int bin_number = 0;
// Holds the bin numbers for direction cosines in x,y,z directions
unsigned int t[3] = {0,0,0};
// dcos is the direction cosine.
float dcos = 0.0;
float bin_size = 0.0;
// max_cos and min_cos are the maximum and minimum values of cos(theta) respectively
float max_cos = 1.0;
float min_cos = -1.0;
// dcos = cosf (normal[0]);
dcos = normal[0];
bin_size = (max_cos - min_cos) / static_cast<float> (binsx_);
// Finding bin number for direction cosine in x direction
unsigned int k = 0;
for (float i = min_cos; (i + bin_size) < (max_cos - bin_size); i += bin_size , k++)
{
if (dcos >= i && dcos <= (i+bin_size))
{
break;
}
}
t[0] = k;
// dcos = cosf (normal[1]);
dcos = normal[1];
bin_size = (max_cos - min_cos) / static_cast<float> (binsy_);
// Finding bin number for direction cosine in y direction
k = 0;
for (float i = min_cos; (i + bin_size) < (max_cos - bin_size); i += bin_size , k++)
{
if (dcos >= i && dcos <= (i+bin_size))
{
break;
}
}
t[1] = k;
// dcos = cosf (normal[2]);
dcos = normal[2];
bin_size = (max_cos - min_cos) / static_cast<float> (binsz_);
// Finding bin number for direction cosine in z direction
k = 0;
for (float i = min_cos; (i + bin_size) < (max_cos - bin_size); i += bin_size , k++)
{
if (dcos >= i && dcos <= (i+bin_size))
{
break;
}
}
t[2] = k;
bin_number = t[0] * (binsy_*binsz_) + t[1] * binsz_ + t[2];
return bin_number;
}
///////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename NormalT> void
pcl::NormalSpaceSampling<PointT, NormalT>::applyFilter (std::vector<int> &indices)
{
if (!initCompute ())
{
indices = *indices_;
return;
}
unsigned int max_values = (std::min) (sample_, static_cast<unsigned int> (input_normals_->size ()));
// Resize output indices to sample size
indices.resize (max_values);
removed_indices_->resize (max_values);
// Allocate memory for the histogram of normals. Normals will then be sampled from each bin.
unsigned int n_bins = binsx_ * binsy_ * binsz_;
// list<int> holds the indices of points in that bin. Using list to avoid repeated resizing of vectors.
// Helps when the point cloud is large.
std::vector<std::list <int> > normals_hg;
normals_hg.reserve (n_bins);
for (unsigned int i = 0; i < n_bins; i++)
normals_hg.push_back (std::list<int> ());
for (std::vector<int>::const_iterator it = indices_->begin (); it != indices_->end (); ++it)
{
unsigned int bin_number = findBin (input_normals_->points[*it].normal, n_bins);
normals_hg[bin_number].push_back (*it);
}
// Setting up random access for the list created above. Maintaining the iterators to individual elements of the list
// in a vector. Using vector now as the size of the list is known.
std::vector<std::vector<std::list<int>::iterator> > random_access (normals_hg.size ());
for (unsigned int i = 0; i < normals_hg.size (); i++)
{
random_access.push_back (std::vector<std::list<int>::iterator> ());
random_access[i].resize (normals_hg[i].size ());
unsigned int j = 0;
for (std::list<int>::iterator itr = normals_hg[i].begin (); itr != normals_hg[i].end (); itr++, j++)
random_access[i][j] = itr;
}
std::vector<unsigned int> start_index (normals_hg.size ());
start_index[0] = 0;
unsigned int prev_index = start_index[0];
for (unsigned int i = 1; i < normals_hg.size (); i++)
{
start_index[i] = prev_index + static_cast<unsigned int> (normals_hg[i-1].size ());
prev_index = start_index[i];
}
// Maintaining flags to check if a point is sampled
boost::dynamic_bitset<> is_sampled_flag (input_normals_->points.size ());
// Maintaining flags to check if all points in the bin are sampled
boost::dynamic_bitset<> bin_empty_flag (normals_hg.size ());
unsigned int i = 0;
while (i < sample_)
{
// Iterating through every bin and picking one point at random, until the required number of points are sampled.
for (unsigned int j = 0; j < normals_hg.size (); j++)
{
unsigned int M = static_cast<unsigned int> (normals_hg[j].size ());
if (M == 0 || bin_empty_flag.test (j)) // bin_empty_flag(i) is set if all points in that bin are sampled..
continue;
unsigned int pos = 0;
unsigned int random_index = 0;
// Picking up a sample at random from jth bin
do
{
random_index = static_cast<unsigned int> ((*rng_uniform_distribution_) () % M);
pos = start_index[j] + random_index;
} while (is_sampled_flag.test (pos));
is_sampled_flag.flip (start_index[j] + random_index);
// Checking if all points in bin j are sampled.
if (isEntireBinSampled (is_sampled_flag, start_index[j], static_cast<unsigned int> (normals_hg[j].size ())))
bin_empty_flag.flip (j);
unsigned int index = *(random_access[j][random_index]);
indices[i] = index;
i++;
if (i == sample_)
break;
}
}
// If we need to return the indices that we haven't sampled
if (extract_removed_indices_)
{
std::vector<int> indices_temp = indices;
std::sort (indices_temp.begin (), indices_temp.end ());
std::vector<int> all_indices_temp = *indices_;
std::sort (all_indices_temp.begin (), all_indices_temp.end ());
set_difference (all_indices_temp.begin (), all_indices_temp.end (),
indices_temp.begin (), indices_temp.end (),
inserter (*removed_indices_, removed_indices_->begin ()));
}
}
#define PCL_INSTANTIATE_NormalSpaceSampling(T,NT) template class PCL_EXPORTS pcl::NormalSpaceSampling<T,NT>;
#endif // PCL_FILTERS_IMPL_NORMAL_SPACE_SAMPLE_H_
<|endoftext|> |
<commit_before><commit_msg>Always play ChromeVox enabled/disabled sounds regardless of system sound enabled flag.<commit_after><|endoftext|> |
<commit_before>#include "src/triangle.h"
#define VERTEX_SWAP(v1, v2) { gfx_Vertex s = v2; v2 = v1; v1 = s; }
// simplest case: will plot either a flat bottom or flat top triangles
enum TriangleType
{
FLAT_BOTTOM,
FLAT_TOP
};
// internal: perform triangle rendering based on its type
static void drawTriangleType(const gfx_Triangle *t, const gfx_Vertex *v0, const gfx_Vertex *v1, const gfx_Vertex *v2, unsigned char *buffer, enum TriangleType type, short colorKey);
/* ***** */
void gfx_drawTriangle(const gfx_Triangle *t, unsigned char *buffer)
{
// draw triangle to screen buffer without any color keying
gfx_drawTriangleColorKey(t, buffer, -1);
}
/* ***** */
void gfx_drawTriangleColorKey(const gfx_Triangle *t, unsigned char *buffer, short colorKey)
{
gfx_Vertex v0, v1, v2;
v0 = t->vertices[0];
v1 = t->vertices[1];
v2 = t->vertices[2];
// sort vertices so that v0 is topmost, then v2, then v1
if(v2.position.y > v1.position.y)
{
v2 = t->vertices[1];
v1 = t->vertices[2];
}
if(v0.position.y > v1.position.y)
{
v0 = v1;
v1 = t->vertices[0];
}
if(v0.position.y > v2.position.y)
VERTEX_SWAP(v0, v2)
// handle 2 basic cases of flat bottom and flat top triangles
if(v1.position.y == v2.position.y)
drawTriangleType(t, &v0, &v1, &v2, buffer, FLAT_BOTTOM, colorKey);
else if(v0.position.y == v1.position.y)
drawTriangleType(t, &v2, &v1, &v0, buffer, FLAT_TOP, colorKey);
else
{
// "Non-trivial" triangles will be broken down into a composition of flat bottom and flat top triangles.
// For this, we need to calculate a new vertex, v3 and interpolate its UV coordinates.
gfx_Vertex v3;
mth_Vector4 diff, diff2;
double ratioU = 1, ratioV = 1;
v3.position.x = v0.position.x + ((float)(v2.position.y - v0.position.y) / (float)(v1.position.y - v0.position.y)) * (v1.position.x - v0.position.x);
v3.position.y = v2.position.y;
// todo: interpolate z for proper perspective texture mapping!
v3.position.z = v2.position.z;
v3.position.w = v2.position.w;
diff = mth_vecSub(&v1.position, &v0.position);
diff2 = mth_vecSub(&v3.position, &v0.position);
if(diff.x != 0)
ratioU = diff2.x / diff.x;
if(diff.y != 0)
ratioV = diff2.y / diff.y;
// lerp the UV mapping for the triangle
v3.uv.u = v1.uv.u * ratioU + v0.uv.u * (1.0 - ratioU);
v3.uv.v = v1.uv.v * ratioV + v0.uv.v * (1.0 - ratioV);
// this swap is done to maintain consistent renderer behavior
if(v3.position.x < v2.position.x)
VERTEX_SWAP(v3, v2)
// draw the composition of both triangles to form the desired shape
drawTriangleType(t, &v0, &v3, &v2, buffer, FLAT_BOTTOM, colorKey);
drawTriangleType(t, &v1, &v3, &v2, buffer, FLAT_TOP, colorKey);
}
}
/*
* Depending on the triangle type, the order of processed vertices is as follows:
*
* v0 v0----v1
* |\ | /
* | \ | /
* | \ | /
* | \ | /
* | \ | /
* | \ |/
* v2-----v1 v2
*/
static void drawTriangleType(const gfx_Triangle *t, const gfx_Vertex *v0, const gfx_Vertex *v1, const gfx_Vertex *v2, unsigned char *buffer, enum TriangleType type, const short colorKey)
{
double invDy, dxLeft, dxRight, xLeft, xRight;
double x, y, yDir = 1;
int useColorKey = colorKey != -1 ? 1 : 0;
if(type == FLAT_BOTTOM)
{
invDy = 1.f / (v2->position.y - v0->position.y);
}
else
{
invDy = 1.f / (v0->position.y - v2->position.y);
yDir = -1;
}
dxLeft = (v2->position.x - v0->position.x) * invDy;
dxRight = (v1->position.x - v0->position.x) * invDy;
xLeft = v0->position.x;
xRight = xLeft;
if(!t->texture)
{
for(y = v0->position.y; ; y += yDir)
{
if(type == FLAT_TOP && y < v2->position.y)
{
break;
}
else if(type == FLAT_BOTTOM && y > v2->position.y)
{
// to avoid pixel wide gaps, render extra line at the junction between two final points
gfx_drawLine(xLeft-dxLeft, y, xRight-dxRight, y, t->color, buffer);
break;
}
gfx_drawLine(xLeft, y, xRight, y, t->color, buffer);
xLeft += dxLeft;
xRight += dxRight;
}
}
else
{
float texW = t->texture->width - 1;
float texH = t->texture->height - 1;
int texArea = texW * texH;
float duLeft = texW * (v2->uv.u - v0->uv.u) * invDy;
float dvLeft = texH * (v2->uv.v - v0->uv.v) * invDy;
float duRight = texW * (v1->uv.u - v0->uv.u) * invDy;
float dvRight = texH * (v1->uv.v - v0->uv.v) * invDy;
float startU = texW * v0->uv.u;
float startV = texH * v0->uv.v;
// With triangles the texture gradients (u,v slopes over the triangle surface)
// are guaranteed to be constant, so we need to calculate du and dv only once.
float invDx = 1.f / (dxRight - dxLeft);
float du = (duRight - duLeft) * invDx;
float dv = (dvRight - dvLeft) * invDx;
float startX = xLeft;
float endX = xRight;
gfx_setPalette(t->texture->palette);
for(y = v0->position.y; ; y += yDir)
{
float u = startU;
float v = startV;
if(type == FLAT_BOTTOM && y > v2->position.y)
{
u -= du;
v -= dv;
for(x = startX-dxLeft; x <= endX-dxRight; ++x)
{
unsigned char pixel = t->texture->data[(int)u + ((int)v * t->texture->height)];
if(!useColorKey || (useColorKey && pixel != (unsigned char)colorKey))
gfx_drawPixel(x, y, pixel, buffer);
u += du;
v += dv;
}
break;
}
else if ( type == FLAT_TOP && y < v2->position.y)
break;
for(x = startX; x <= endX; ++x)
{
// fetch texture data with a texArea modulus for proper effect in case u or v are > 1
unsigned char pixel = t->texture->data[((int)u + ((int)v * t->texture->height)) % texArea];
if(!useColorKey || (useColorKey && pixel != (unsigned char)colorKey))
gfx_drawPixel(x, y, pixel, buffer);
u += du;
v += dv;
}
startX += dxLeft;
endX += dxRight;
startU += duLeft;
startV += dvLeft;
}
}
}
<commit_msg>interpolate z coordinate for v3<commit_after>#include "src/triangle.h"
#define VERTEX_SWAP(v1, v2) { gfx_Vertex s = v2; v2 = v1; v1 = s; }
// simplest case: will plot either a flat bottom or flat top triangles
enum TriangleType
{
FLAT_BOTTOM,
FLAT_TOP
};
// internal: perform triangle rendering based on its type
static void drawTriangleType(const gfx_Triangle *t, const gfx_Vertex *v0, const gfx_Vertex *v1, const gfx_Vertex *v2, unsigned char *buffer, enum TriangleType type, short colorKey);
/* ***** */
void gfx_drawTriangle(const gfx_Triangle *t, unsigned char *buffer)
{
// draw triangle to screen buffer without any color keying
gfx_drawTriangleColorKey(t, buffer, -1);
}
/* ***** */
void gfx_drawTriangleColorKey(const gfx_Triangle *t, unsigned char *buffer, short colorKey)
{
gfx_Vertex v0, v1, v2;
v0 = t->vertices[0];
v1 = t->vertices[1];
v2 = t->vertices[2];
// sort vertices so that v0 is topmost, then v2, then v1
if(v2.position.y > v1.position.y)
{
v2 = t->vertices[1];
v1 = t->vertices[2];
}
if(v0.position.y > v1.position.y)
{
v0 = v1;
v1 = t->vertices[0];
}
if(v0.position.y > v2.position.y)
VERTEX_SWAP(v0, v2)
// handle 2 basic cases of flat bottom and flat top triangles
if(v1.position.y == v2.position.y)
drawTriangleType(t, &v0, &v1, &v2, buffer, FLAT_BOTTOM, colorKey);
else if(v0.position.y == v1.position.y)
drawTriangleType(t, &v2, &v1, &v0, buffer, FLAT_TOP, colorKey);
else
{
// "Non-trivial" triangles will be broken down into a composition of flat bottom and flat top triangles.
// For this, we need to calculate a new vertex, v3 and interpolate its UV coordinates.
gfx_Vertex v3;
mth_Vector4 diff, diff2;
double ratioU = 1, ratioV = 1;
v3.position.x = v0.position.x + ((float)(v2.position.y - v0.position.y) / (float)(v1.position.y - v0.position.y)) * (v1.position.x - v0.position.x);
v3.position.y = v2.position.y;
v3.position.z = v0.position.z + ((float)(v2.position.y - v0.position.y) / (float)(v1.position.y - v0.position.y)) * (v1.position.z - v0.position.z);
v3.position.w = v2.position.w;
diff = mth_vecSub(&v1.position, &v0.position);
diff2 = mth_vecSub(&v3.position, &v0.position);
if(diff.x != 0)
ratioU = diff2.x / diff.x;
if(diff.y != 0)
ratioV = diff2.y / diff.y;
// lerp the UV mapping for the triangle
v3.uv.u = v1.uv.u * ratioU + v0.uv.u * (1.0 - ratioU);
v3.uv.v = v1.uv.v * ratioV + v0.uv.v * (1.0 - ratioV);
// this swap is done to maintain consistent renderer behavior
if(v3.position.x < v2.position.x)
VERTEX_SWAP(v3, v2)
// draw the composition of both triangles to form the desired shape
drawTriangleType(t, &v0, &v3, &v2, buffer, FLAT_BOTTOM, colorKey);
drawTriangleType(t, &v1, &v3, &v2, buffer, FLAT_TOP, colorKey);
}
}
/*
* Depending on the triangle type, the order of processed vertices is as follows:
*
* v0 v0----v1
* |\ | /
* | \ | /
* | \ | /
* | \ | /
* | \ | /
* | \ |/
* v2-----v1 v2
*/
static void drawTriangleType(const gfx_Triangle *t, const gfx_Vertex *v0, const gfx_Vertex *v1, const gfx_Vertex *v2, unsigned char *buffer, enum TriangleType type, const short colorKey)
{
double invDy, dxLeft, dxRight, xLeft, xRight;
double x, y, yDir = 1;
int useColorKey = colorKey != -1 ? 1 : 0;
if(type == FLAT_BOTTOM)
{
invDy = 1.f / (v2->position.y - v0->position.y);
}
else
{
invDy = 1.f / (v0->position.y - v2->position.y);
yDir = -1;
}
dxLeft = (v2->position.x - v0->position.x) * invDy;
dxRight = (v1->position.x - v0->position.x) * invDy;
xLeft = v0->position.x;
xRight = xLeft;
if(!t->texture)
{
for(y = v0->position.y; ; y += yDir)
{
if(type == FLAT_TOP && y < v2->position.y)
{
break;
}
else if(type == FLAT_BOTTOM && y > v2->position.y)
{
// to avoid pixel wide gaps, render extra line at the junction between two final points
gfx_drawLine(xLeft-dxLeft, y, xRight-dxRight, y, t->color, buffer);
break;
}
gfx_drawLine(xLeft, y, xRight, y, t->color, buffer);
xLeft += dxLeft;
xRight += dxRight;
}
}
else
{
float texW = t->texture->width - 1;
float texH = t->texture->height - 1;
int texArea = texW * texH;
float duLeft = texW * (v2->uv.u - v0->uv.u) * invDy;
float dvLeft = texH * (v2->uv.v - v0->uv.v) * invDy;
float duRight = texW * (v1->uv.u - v0->uv.u) * invDy;
float dvRight = texH * (v1->uv.v - v0->uv.v) * invDy;
float startU = texW * v0->uv.u;
float startV = texH * v0->uv.v;
// With triangles the texture gradients (u,v slopes over the triangle surface)
// are guaranteed to be constant, so we need to calculate du and dv only once.
float invDx = 1.f / (dxRight - dxLeft);
float du = (duRight - duLeft) * invDx;
float dv = (dvRight - dvLeft) * invDx;
float startX = xLeft;
float endX = xRight;
gfx_setPalette(t->texture->palette);
for(y = v0->position.y; ; y += yDir)
{
float u = startU;
float v = startV;
if(type == FLAT_BOTTOM && y > v2->position.y)
{
u -= du;
v -= dv;
for(x = startX-dxLeft; x <= endX-dxRight; ++x)
{
unsigned char pixel = t->texture->data[(int)u + ((int)v * t->texture->height)];
if(!useColorKey || (useColorKey && pixel != (unsigned char)colorKey))
gfx_drawPixel(x, y, pixel, buffer);
u += du;
v += dv;
}
break;
}
else if ( type == FLAT_TOP && y < v2->position.y)
break;
for(x = startX; x <= endX; ++x)
{
// fetch texture data with a texArea modulus for proper effect in case u or v are > 1
unsigned char pixel = t->texture->data[((int)u + ((int)v * t->texture->height)) % texArea];
if(!useColorKey || (useColorKey && pixel != (unsigned char)colorKey))
gfx_drawPixel(x, y, pixel, buffer);
u += du;
v += dv;
}
startX += dxLeft;
endX += dxRight;
startU += duLeft;
startV += dvLeft;
}
}
}
<|endoftext|> |
<commit_before>// RUN: %clang_cc1 -triple x86_64-apple-darwin9 -verify -fsyntax-only -std=c++11 -fms-extensions %s
#if !__has_feature(attribute_deprecated_with_replacement)
#error "Missing __has_feature"
#endif
int a1 [[deprecated("warning", "fixit")]]; // expected-error{{'deprecated' attribute takes no more than 1 argument}}
int a2 [[deprecated("warning", 1)]]; // expected-error{{'deprecated' attribute takes no more than 1 argument}}
int b1 [[gnu::deprecated("warning", "fixit")]]; // expected-error{{'deprecated' attribute takes no more than 1 argument}}
int b2 [[gnu::deprecated("warning", 1)]]; // expected-error{{'deprecated' attribute takes no more than 1 argument}}
__declspec(deprecated("warning", "fixit")) int c1; // expected-error{{'deprecated' attribute takes no more than 1 argument}}
__declspec(deprecated("warning", 1)) int c2; // expected-error{{'deprecated' attribute takes no more than 1 argument}}
int d1 __attribute__((deprecated("warning", "fixit")));
int d2 __attribute__((deprecated("warning", 1))); // expected-error{{'deprecated' attribute requires a string}}
<commit_msg>Update testing case on swift-3.0 branch.<commit_after>// RUN: %clang_cc1 -triple x86_64-apple-darwin9 -verify -fsyntax-only -std=c++11 -fms-extensions %s
#if !__has_feature(attribute_deprecated_with_replacement)
#error "Missing __has_feature"
#endif
int a1 [[deprecated("warning", "fixit")]]; // expected-warning{{use of the 'deprecated' attribute is a C++14 extension}} expected-error{{'deprecated' attribute takes no more than 1 argument}}
int a2 [[deprecated("warning", 1)]]; // expected-warning{{use of the 'deprecated' attribute is a C++14 extension}} expected-error{{'deprecated' attribute takes no more than 1 argument}}
int b1 [[gnu::deprecated("warning", "fixit")]]; // expected-error{{'deprecated' attribute takes no more than 1 argument}}
int b2 [[gnu::deprecated("warning", 1)]]; // expected-error{{'deprecated' attribute takes no more than 1 argument}}
__declspec(deprecated("warning", "fixit")) int c1; // expected-error{{'deprecated' attribute takes no more than 1 argument}}
__declspec(deprecated("warning", 1)) int c2; // expected-error{{'deprecated' attribute takes no more than 1 argument}}
int d1 __attribute__((deprecated("warning", "fixit")));
int d2 __attribute__((deprecated("warning", 1))); // expected-error{{'deprecated' attribute requires a string}}
<|endoftext|> |
<commit_before>#include "PNGRead.hpp"
#include <memory>
#include <cstdio>
#include <png.h>
namespace Slic3r { namespace png {
struct PNGDescr {
png_struct *png = nullptr; png_info *info = nullptr;
PNGDescr() = default;
PNGDescr(const PNGDescr&) = delete;
PNGDescr(PNGDescr&&) = delete;
PNGDescr& operator=(const PNGDescr&) = delete;
PNGDescr& operator=(PNGDescr&&) = delete;
~PNGDescr()
{
if (png && info) png_destroy_info_struct(png, &info);
if (png) png_destroy_read_struct( &png, nullptr, nullptr);
}
};
bool is_png(const ReadBuf &rb)
{
static const constexpr int PNG_SIG_BYTES = 8;
return rb.sz >= PNG_SIG_BYTES &&
!png_sig_cmp(static_cast<png_const_bytep>(rb.buf), 0, PNG_SIG_BYTES);
}
bool decode_png(const ReadBuf &rb, ImageGreyscale &img)
{
if (!is_png(rb)) return false;
PNGDescr dsc;
dsc.png = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
if(!dsc.png) return false;
dsc.info = png_create_info_struct(dsc.png);
if(!dsc.info) return {};
FILE *io = ::fmemopen(const_cast<void *>(rb.buf), rb.sz, "rb");
png_init_io(dsc.png, io);
png_read_info(dsc.png, dsc.info);
img.cols = png_get_image_width(dsc.png, dsc.info);
img.rows = png_get_image_height(dsc.png, dsc.info);
size_t color_type = png_get_color_type(dsc.png, dsc.info);
size_t bit_depth = png_get_bit_depth(dsc.png, dsc.info);
if (color_type != PNG_COLOR_TYPE_GRAY || bit_depth != 8)
return false;
img.buf.resize(img.rows * img.cols);
auto readbuf = static_cast<png_bytep>(img.buf.data());
for (size_t r = 0; r < img.rows; ++r)
png_read_row(dsc.png, readbuf + r * img.cols, nullptr);
fclose(io);
return true;
}
}}
<commit_msg>Don't use fmemopen, its not standard.<commit_after>#include "PNGRead.hpp"
#include <memory>
#include <cstdio>
#include <png.h>
namespace Slic3r { namespace png {
struct PNGDescr {
png_struct *png = nullptr; png_info *info = nullptr;
PNGDescr() = default;
PNGDescr(const PNGDescr&) = delete;
PNGDescr(PNGDescr&&) = delete;
PNGDescr& operator=(const PNGDescr&) = delete;
PNGDescr& operator=(PNGDescr&&) = delete;
~PNGDescr()
{
if (png && info) png_destroy_info_struct(png, &info);
if (png) png_destroy_read_struct( &png, nullptr, nullptr);
}
};
bool is_png(const ReadBuf &rb)
{
static const constexpr int PNG_SIG_BYTES = 8;
return rb.sz >= PNG_SIG_BYTES &&
!png_sig_cmp(static_cast<png_const_bytep>(rb.buf), 0, PNG_SIG_BYTES);
}
// A wrapper around ReadBuf to be read repeatedly like a stream. libpng needs
// this form for its buffer read callback.
struct ReadBufReader {
const ReadBuf &rdbuf; size_t pos;
ReadBufReader(const ReadBuf &rd): rdbuf{rd}, pos{0} {}
};
// Buffer read callback for libpng. It provides an allocated output buffer and
// the amount of data it desires to read from the input.
void png_read_callback(png_struct *png_ptr,
png_bytep outBytes,
png_size_t byteCountToRead)
{
// Retrieve our input buffer through the png_ptr
auto reader = static_cast<ReadBufReader *>(png_get_io_ptr(png_ptr));
if (!reader || byteCountToRead > reader->rdbuf.sz - reader->pos) return;
auto buf = static_cast<const png_byte *>(reader->rdbuf.buf);
size_t pos = reader->pos;
std::copy(buf + pos, buf + (pos + byteCountToRead), outBytes);
reader->pos += byteCountToRead;
}
bool decode_png(const ReadBuf &rb, ImageGreyscale &img)
{
if (!is_png(rb)) return false;
PNGDescr dsc;
dsc.png = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr,
nullptr);
if(!dsc.png) return false;
dsc.info = png_create_info_struct(dsc.png);
if(!dsc.info) return {};
ReadBufReader reader {rb};
png_set_read_fn(dsc.png, static_cast<void *>(&reader), png_read_callback);
png_read_info(dsc.png, dsc.info);
img.cols = png_get_image_width(dsc.png, dsc.info);
img.rows = png_get_image_height(dsc.png, dsc.info);
size_t color_type = png_get_color_type(dsc.png, dsc.info);
size_t bit_depth = png_get_bit_depth(dsc.png, dsc.info);
if (color_type != PNG_COLOR_TYPE_GRAY || bit_depth != 8)
return false;
img.buf.resize(img.rows * img.cols);
auto readbuf = static_cast<png_bytep>(img.buf.data());
for (size_t r = 0; r < img.rows; ++r)
png_read_row(dsc.png, readbuf + r * img.cols, nullptr);
return true;
}
}} // namespace Slic3r::png
<|endoftext|> |
<commit_before>#include <osg/MatrixTransform>
#include <osg/ClipNode>
#include <osg/Billboard>
#include <osg/Geode>
#include <osg/Group>
#include <osg/Notify>
#include <osg/Material>
#include <osg/PolygonOffset>
#include <osg/PolygonMode>
#include <osg/LineStipple>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>
#include <osgUtil/TransformCallback>
#include <osgProducer/Viewer>
#include <osgUtil/Optimizer>
void write_usage(std::ostream& out,const std::string& name)
{
out << std::endl;
out <<"usage:"<< std::endl;
out <<" "<<name<<" [options] infile1 [infile2 ...]"<< std::endl;
out << std::endl;
out <<"options:"<< std::endl;
out <<" -l libraryName - load plugin of name libraryName"<< std::endl;
out <<" i.e. -l osgdb_pfb"<< std::endl;
out <<" Useful for loading reader/writers which can load"<< std::endl;
out <<" other file formats in addition to its extension."<< std::endl;
out <<" -e extensionName - load reader/wrter plugin for file extension"<< std::endl;
out <<" i.e. -e pfb"<< std::endl;
out <<" Useful short hand for specifying full library name as"<< std::endl;
out <<" done with -l above, as it automatically expands to"<< std::endl;
out <<" the full library name appropriate for each platform."<< std::endl;
out <<std::endl;
out <<" -stereo - switch on stereo rendering, using the default of,"<< std::endl;
out <<" ANAGLYPHIC or the value set in the OSG_STEREO_MODE "<< std::endl;
out <<" environmental variable. See doc/stereo.html for "<< std::endl;
out <<" further details on setting up accurate stereo "<< std::endl;
out <<" for your system. "<< std::endl;
out <<" -stereo ANAGLYPHIC - switch on anaglyphic(red/cyan) stereo rendering."<< std::endl;
out <<" -stereo QUAD_BUFFER - switch on quad buffered stereo rendering."<< std::endl;
out <<std::endl;
out <<" -stencil - use a visual with stencil buffer enabled, this "<< std::endl;
out <<" also allows the depth complexity statistics mode"<< std::endl;
out <<" to be used (press 'p' three times to cycle to it)."<< std::endl;
out << std::endl;
}
osg::Node* decorate_with_clip_node(osg::Node* subgraph)
{
osg::Group* rootnode = new osg::Group;
// create wireframe view of the model so the user can see
// what parts are being culled away.
osg::StateSet* stateset = new osg::StateSet;
//osg::Material* material = new osg::Material;
osg::PolygonMode* polymode = new osg::PolygonMode;
polymode->setMode(osg::PolygonMode::FRONT_AND_BACK,osg::PolygonMode::LINE);
stateset->setAttributeAndModes(polymode,osg::StateAttribute::OVERRIDE|osg::StateAttribute::ON);
osg::Group* wireframe_subgraph = new osg::Group;
wireframe_subgraph->setStateSet(stateset);
wireframe_subgraph->addChild(subgraph);
rootnode->addChild(wireframe_subgraph);
/*
// simple approach to adding a clipnode above a subrgaph.
// create clipped part.
osg::ClipNode* clipped_subgraph = new osg::ClipNode;
osg::BoundingSphere bs = subgraph->getBound();
bs.radius()*= 0.4f;
osg::BoundingBox bb;
bb.expandBy(bs);
clipped_subgraph->createClipBox(bb);
clipped_subgraph->addChild(subgraph);
rootnode->addChild(clipped_subgraph);
*/
// more complex approach to managing ClipNode, allowing
// ClipNode node to be transformed independantly from the subgraph
// that it is clipping.
osg::MatrixTransform* transform= new osg::MatrixTransform;
osg::NodeCallback* nc = new osgUtil::TransformCallback(subgraph->getBound().center(),osg::Vec3(0.0f,0.0f,1.0f),osg::inDegrees(45.0f));
transform->setUpdateCallback(nc);
osg::ClipNode* clipnode = new osg::ClipNode;
osg::BoundingSphere bs = subgraph->getBound();
bs.radius()*= 0.4f;
osg::BoundingBox bb;
bb.expandBy(bs);
clipnode->createClipBox(bb);
clipnode->setCullingActive(false);
transform->addChild(clipnode);
rootnode->addChild(transform);
// create clipped part.
osg::Group* clipped_subgraph = new osg::Group;
clipped_subgraph->setStateSet(clipnode->getStateSet());
clipped_subgraph->addChild(subgraph);
rootnode->addChild(clipped_subgraph);
return rootnode;
}
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use multi-pass and osg::ClipNode to clip parts of the scene away..");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// initialize the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// load the nodes from the commandline arguments.
osg::Node* loadedModel = osgDB::readNodeFiles(arguments);
if (!loadedModel)
{
write_usage(osg::notify(osg::NOTICE),argv[0]);
return 1;
}
// decorate the scenegraph with a clip node.
osg::Node* rootnode = decorate_with_clip_node(loadedModel);
// run optimization over the scene graph
osgUtil::Optimizer optimzer;
optimzer.optimize(rootnode);
// set the scene to render
viewer.setSceneData(rootnode);
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<commit_msg>Removed redundent write_usage function.<commit_after>#include <osg/MatrixTransform>
#include <osg/ClipNode>
#include <osg/Billboard>
#include <osg/Geode>
#include <osg/Group>
#include <osg/Notify>
#include <osg/Material>
#include <osg/PolygonOffset>
#include <osg/PolygonMode>
#include <osg/LineStipple>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>
#include <osgUtil/TransformCallback>
#include <osgProducer/Viewer>
#include <osgUtil/Optimizer>
osg::Node* decorate_with_clip_node(osg::Node* subgraph)
{
osg::Group* rootnode = new osg::Group;
// create wireframe view of the model so the user can see
// what parts are being culled away.
osg::StateSet* stateset = new osg::StateSet;
//osg::Material* material = new osg::Material;
osg::PolygonMode* polymode = new osg::PolygonMode;
polymode->setMode(osg::PolygonMode::FRONT_AND_BACK,osg::PolygonMode::LINE);
stateset->setAttributeAndModes(polymode,osg::StateAttribute::OVERRIDE|osg::StateAttribute::ON);
osg::Group* wireframe_subgraph = new osg::Group;
wireframe_subgraph->setStateSet(stateset);
wireframe_subgraph->addChild(subgraph);
rootnode->addChild(wireframe_subgraph);
/*
// simple approach to adding a clipnode above a subrgaph.
// create clipped part.
osg::ClipNode* clipped_subgraph = new osg::ClipNode;
osg::BoundingSphere bs = subgraph->getBound();
bs.radius()*= 0.4f;
osg::BoundingBox bb;
bb.expandBy(bs);
clipped_subgraph->createClipBox(bb);
clipped_subgraph->addChild(subgraph);
rootnode->addChild(clipped_subgraph);
*/
// more complex approach to managing ClipNode, allowing
// ClipNode node to be transformed independantly from the subgraph
// that it is clipping.
osg::MatrixTransform* transform= new osg::MatrixTransform;
osg::NodeCallback* nc = new osgUtil::TransformCallback(subgraph->getBound().center(),osg::Vec3(0.0f,0.0f,1.0f),osg::inDegrees(45.0f));
transform->setUpdateCallback(nc);
osg::ClipNode* clipnode = new osg::ClipNode;
osg::BoundingSphere bs = subgraph->getBound();
bs.radius()*= 0.4f;
osg::BoundingBox bb;
bb.expandBy(bs);
clipnode->createClipBox(bb);
clipnode->setCullingActive(false);
transform->addChild(clipnode);
rootnode->addChild(transform);
// create clipped part.
osg::Group* clipped_subgraph = new osg::Group;
clipped_subgraph->setStateSet(clipnode->getStateSet());
clipped_subgraph->addChild(subgraph);
rootnode->addChild(clipped_subgraph);
return rootnode;
}
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use multi-pass and osg::ClipNode to clip parts of the scene away..");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// initialize the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// load the nodes from the commandline arguments.
osg::Node* loadedModel = osgDB::readNodeFiles(arguments);
if (!loadedModel)
{
return 1;
}
// decorate the scenegraph with a clip node.
osg::Node* rootnode = decorate_with_clip_node(loadedModel);
// run optimization over the scene graph
osgUtil::Optimizer optimzer;
optimzer.optimize(rootnode);
// set the scene to render
viewer.setSceneData(rootnode);
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<|endoftext|> |
<commit_before>/*
Library to control the 74HC595
More info at http://bildr.org/?s=74hc595
*/
#include "Arduino.h"
#include "Shiftduino.h"
int _dataPin; //pin 14 on the 75HC595
int _latchPin; //pin 12 on the 75HC595
int _clockPin; //pin 11 on the 75HC595
int _numOfRegisterPins; //number of c.i. in cascade
#define maxRegisterPins 64
boolean _registers[maxRegisterPins];
Shiftduino::Shiftduino(uint8_t dataPin, uint8_t clockPin, uint8_t latchPin, uint8_t numOfRegisters){
_dataPin = dataPin;
pinMode(_dataPin, OUTPUT);
_clockPin = clockPin;
pinMode(_clockPin, OUTPUT);
_latchPin = latchPin;
pinMode(_latchPin, OUTPUT);
_numOfRegisterPins = numOfRegisters * 8;
//reset all register pins
clear();
writeValues();
}
//set all register pins to LOW
void Shiftduino::clear(){
for(int i = _numOfRegisterPins - 1; i >= 0; i--){
_registers[i] = LOW;
}
//set pins
writeValues();
}
//set an individual pin HIGH or LOW
void Shiftduino::setPin(int index, int value){
_registers[index] = value;
//set pins
writeValues();
}
//set an individual pin HIGH or LOW, specifiying the register number
void Shiftduino::setPin(int registerNum, int index, int value){
finalIndex = (registerNum * _numOfRegisterPins) + index;
_registers[finalIndex] = value;
//set pins
writeValues();
}
//set all pins HIGH or LOW
void Shiftduino::setPins(boolean values[]){
for(int i = _numOfRegisterPins - 1; i >= 0; i--){
_registers[i] = values[i];
}
//set pins
writeValues();
}
//set all pins HIGH or LOW
void Shiftduino::setPins(uint64_t values){
for(int i = 0; i < _numOfRegisterPins; i++){
_registers[i] = values & 0x00000001;
values >>= 1;
}
//set pins
writeValues();
}
//Set and display registers
//Only call AFTER all values are set how you would like (slow otherwise)
void Shiftduino::writeValues(){
digitalWrite(_latchPin, LOW);
for(int i = _numOfRegisterPins - 1; i >= 0; i--){
digitalWrite(_clockPin, LOW);
int value = _registers[i];
digitalWrite(_dataPin, value);
digitalWrite(_clockPin, HIGH);
}
digitalWrite(_latchPin, HIGH);
}
<commit_msg>corrected minor bug<commit_after>/*
Library to control the 74HC595
More info at http://bildr.org/?s=74hc595
*/
#include "Arduino.h"
#include "Shiftduino.h"
int _dataPin; //pin 14 on the 75HC595
int _latchPin; //pin 12 on the 75HC595
int _clockPin; //pin 11 on the 75HC595
int _numOfRegisterPins; //number of c.i. in cascade
#define maxRegisterPins 64
boolean _registers[maxRegisterPins];
Shiftduino::Shiftduino(uint8_t dataPin, uint8_t clockPin, uint8_t latchPin, uint8_t numOfRegisters){
_dataPin = dataPin;
pinMode(_dataPin, OUTPUT);
_clockPin = clockPin;
pinMode(_clockPin, OUTPUT);
_latchPin = latchPin;
pinMode(_latchPin, OUTPUT);
_numOfRegisterPins = numOfRegisters * 8;
//reset all register pins
clear();
writeValues();
}
//set all register pins to LOW
void Shiftduino::clear(){
for(int i = _numOfRegisterPins - 1; i >= 0; i--){
_registers[i] = LOW;
}
//set pins
writeValues();
}
//set an individual pin HIGH or LOW
void Shiftduino::setPin(int index, int value){
_registers[index] = value;
//set pins
writeValues();
}
//set an individual pin HIGH or LOW, specifiying the register number
void Shiftduino::setPin(int registerNum, int index, int value){
finalIndex = (registerNum * 8) + index;
_registers[finalIndex] = value;
//set pins
writeValues();
}
//set all pins HIGH or LOW
void Shiftduino::setPins(boolean values[]){
for(int i = _numOfRegisterPins - 1; i >= 0; i--){
_registers[i] = values[i];
}
//set pins
writeValues();
}
//set all pins HIGH or LOW
void Shiftduino::setPins(uint64_t values){
for(int i = 0; i < _numOfRegisterPins; i++){
_registers[i] = values & 0x00000001;
values >>= 1;
}
//set pins
writeValues();
}
//Set and display registers
//Only call AFTER all values are set how you would like (slow otherwise)
void Shiftduino::writeValues(){
digitalWrite(_latchPin, LOW);
for(int i = _numOfRegisterPins - 1; i >= 0; i--){
digitalWrite(_clockPin, LOW);
int value = _registers[i];
digitalWrite(_dataPin, value);
digitalWrite(_clockPin, HIGH);
}
digitalWrite(_latchPin, HIGH);
}
<|endoftext|> |
<commit_before>// Copyright (C) 2012-2014 Leap Motion, Inc. All rights reserved.
#pragma once
#include TYPE_INDEX_HEADER
#include <string>
#if __GNUG__ // Mac and linux
#include <cxxabi.h>
#include <cstdlib>
#include MEMORY_HEADER
#endif
//
// Demangle type names on mac and linux.
// Just returns type_info.name() on windows
//
namespace autowiring {
#if __GNUG__ // Mac and linux
std::string demangle(const std::type_info& ti) {
int status;
std::unique_ptr<char, void(*)(void*)> res{
abi::__cxa_demangle(ti.name(), nullptr, nullptr, &status),
std::free
};
return std::string(status == 0 ? res.get() : ti.name());
}
#else // Windows
std::string demangle(const std::type_info& ti) {
return std::string(ti.name());
}
#endif
template<typename T>
std::string demangle(T) {
return demangle(typeid(T));
}
}//namespace autowiring
<commit_msg>Make demangle static inline<commit_after>// Copyright (C) 2012-2014 Leap Motion, Inc. All rights reserved.
#pragma once
#include TYPE_INDEX_HEADER
#include <string>
#if __GNUG__ // Mac and linux
#include <cxxabi.h>
#include <cstdlib>
#include MEMORY_HEADER
#endif
//
// Demangle type names on mac and linux.
// Just returns type_info.name() on windows
//
namespace autowiring {
#if __GNUG__ // Mac and linux
static inline std::string demangle(const std::type_info& ti) {
int status;
std::unique_ptr<char, void(*)(void*)> res{
abi::__cxa_demangle(ti.name(), nullptr, nullptr, &status),
std::free
};
return std::string(status == 0 ? res.get() : ti.name());
}
#else // Windows
static inline std::string demangle(const std::type_info& ti) {
return std::string(ti.name());
}
#endif
template<typename T>
static inline std::string demangle(T) {
return demangle(typeid(T));
}
}//namespace autowiring
<|endoftext|> |
<commit_before>/*
* Copyright 2009-2019 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 <numeric>
#include <votca/xtp/checkpoint.h>
#include <votca/xtp/jobtopology.h>
#include <votca/xtp/polarregion.h>
#include <votca/xtp/qmregion.h>
#include <votca/xtp/segmentmapper.h>
#include <votca/xtp/staticregion.h>
namespace votca {
namespace xtp {
void JobTopology::SortRegionsDefbyId(
std::vector<tools::Property*>& regions_def) const {
std::sort(regions_def.begin(), regions_def.end(),
[](const tools::Property* A, const tools::Property* B) {
return (A->get("id").as<int>()) < (B->get("id").as<int>());
});
}
void JobTopology::ModifyOptionsByJobFile(
std::vector<tools::Property*>& regions_def) const {
const tools::Property& jobinput = _job.getInput();
std::vector<const tools::Property*> regions_def_job =
jobinput.Select("regions.region");
std::string tag = "jobfile";
for (tools::Property* prop : regions_def) {
int id = prop->get("id").as<int>();
std::vector<std::string> paths = FindReplacePathsInOptions(*prop, tag);
if (!paths.empty()) {
XTP_LOG_SAVE(logINFO, _log) << " Region " << std::to_string(id)
<< " is modified by jobfile" << std::flush;
XTP_LOG_SAVE(logINFO, _log)
<< " Replacing the following paths with jobfile entries"
<< std::flush;
for (const std::string& path : paths) {
XTP_LOG_SAVE(logINFO, _log) << " - " << path << std::flush;
}
bool found_region_in_jobfile = false;
const tools::Property* job_prop = nullptr;
for (const tools::Property* prop_job : regions_def_job) {
int id2 = prop_job->get("id").as<int>();
if (id2 == id) {
job_prop = prop_job;
found_region_in_jobfile = true;
}
}
if (!found_region_in_jobfile) {
throw std::runtime_error("Region " + std::to_string(id) +
" was not found in jobfile.");
}
UpdateFromJobfile(*prop, *job_prop, paths);
}
}
}
void JobTopology::BuildRegions(const Topology& top, tools::Property options) {
std::vector<tools::Property*> regions_def = options.Select("region");
CheckEnumerationOfRegions(regions_def);
SortRegionsDefbyId(regions_def);
ModifyOptionsByJobFile(regions_def);
std::vector<std::vector<SegId> > region_seg_ids =
PartitionRegions(regions_def, top);
// around this point the whole jobtopology will be centered
CreateRegions(options, top, region_seg_ids);
XTP_LOG_SAVE(logINFO, _log) << " Regions created" << std::flush;
for (const auto& region : _regions) {
XTP_LOG_SAVE(logINFO, _log) << *region << std::flush;
}
return;
}
std::vector<std::string> JobTopology::FindReplacePathsInOptions(
const tools::Property& options, std::string tag) const {
std::vector<std::string> result;
std::string options_path = "options.qmmm.regions.region";
for (const tools::Property& sub : options) {
if (sub.HasChildren()) {
std::vector<std::string> subresult = FindReplacePathsInOptions(sub, tag);
result.insert(result.end(), subresult.begin(), subresult.end());
} else if (sub.value() == tag) {
std::string path = sub.path() + "." + sub.name();
std::size_t pos = path.find(options_path);
if (pos != std::string::npos) {
path.replace(pos, options_path.size(), "");
}
result.push_back(path);
}
}
return result;
}
void JobTopology::UpdateFromJobfile(
tools::Property& options, const tools::Property& job_opt,
const std::vector<std::string>& paths) const {
for (const std::string& path : paths) {
if (job_opt.exists(path)) {
options.set(path, job_opt.get(path).value());
} else {
throw std::runtime_error("Jobfile does not contain options for " + path);
}
}
}
template <class T>
void JobTopology::ShiftPBC(const Topology& top, const Eigen::Vector3d& center,
T& mol) const {
Eigen::Vector3d r_pbc = top.PbShortestConnect(center, mol.getPos());
Eigen::Vector3d r = mol.getPos() - center;
Eigen::Vector3d shift = r_pbc - r;
std::cout << "mol.getPos().transpose()<<"
"<<center"
<< std::endl;
std::cout << mol.getPos().transpose() << " " << center.transpose()
<< std::endl;
std::cout << r_pbc.transpose() << " " << r.transpose() << std::endl;
if (shift.norm() > 1e-9) {
mol.Translate(shift);
}
}
void JobTopology::CreateRegions(
const tools::Property& options, const Topology& top,
const std::vector<std::vector<SegId> >& region_seg_ids) {
std::string mapfile =
options.ifExistsReturnElseThrowRuntimeError<std::string>("mapfile");
std::vector<const tools::Property*> regions_def = options.Select("region");
// around this point the whole jobtopology will be centered for removing pbc
Eigen::Vector3d center = top.getSegment(region_seg_ids[0][0].Id()).getPos();
for (const tools::Property* region_def : regions_def) {
int id = region_def->ifExistsReturnElseThrowRuntimeError<int>("id");
const std::vector<SegId>& seg_ids = region_seg_ids[id];
std::string type =
region_def->ifExistsReturnElseThrowRuntimeError<std::string>("type");
std::unique_ptr<Region> region;
QMRegion QMdummy(0, _log, "");
StaticRegion Staticdummy(0, _log);
PolarRegion Polardummy(0, _log);
if (type == QMdummy.identify()) {
std::unique_ptr<QMRegion> qmregion =
std::unique_ptr<QMRegion>(new QMRegion(id, _log, _workdir));
QMMapper qmmapper(_log);
qmmapper.LoadMappingFile(mapfile);
for (const SegId& seg_index : seg_ids) {
const Segment& segment = top.getSegment(seg_index.Id());
QMMolecule mol = qmmapper.map(segment, seg_index);
mol.setName("qm" + std::to_string(id));
ShiftPBC(top, center, mol);
qmregion->push_back(mol);
}
region = std::move(qmregion);
} else if (type == Polardummy.identify()) {
std::unique_ptr<PolarRegion> polarregion =
std::unique_ptr<PolarRegion>(new PolarRegion(id, _log));
PolarMapper polmap(_log);
polmap.LoadMappingFile(mapfile);
for (const SegId& seg_index : seg_ids) {
const Segment& segment = top.getSegment(seg_index.Id());
PolarSegment mol = polmap.map(segment, seg_index);
std::cout << "id" << seg_index.Id() << " " << segment.getId() << " "
<< segment.getPos().transpose() << " "
<< mol.getPos().transpose() << std::endl;
ShiftPBC(top, center, mol);
mol.setName("mm" + std::to_string(id));
polarregion->push_back(mol);
}
region = std::move(polarregion);
} else if (type == Staticdummy.identify()) {
std::unique_ptr<StaticRegion> staticregion =
std::unique_ptr<StaticRegion>(new StaticRegion(id, _log));
StaticMapper staticmap(_log);
staticmap.LoadMappingFile(mapfile);
for (const SegId& seg_index : seg_ids) {
const Segment& segment = top.getSegment(seg_index.Id());
StaticSegment mol = staticmap.map(segment, seg_index);
mol.setName("mm" + std::to_string(id));
ShiftPBC(top, center, mol);
staticregion->push_back(mol);
}
region = std::move(staticregion);
} else {
throw std::runtime_error("Region type not known!");
}
region->Initialize(*region_def);
_regions.push_back(std::move(region));
}
}
void JobTopology::WriteToPdb(std::string filename) const {
csg::PDBWriter writer;
writer.Open(filename, false);
writer.WriteHeader("Job:" + std::to_string(this->_job.getId()));
for (const std::unique_ptr<Region>& reg : _regions) {
reg->WritePDB(writer);
}
writer.Close();
}
std::vector<std::vector<SegId> > JobTopology::PartitionRegions(
const std::vector<tools::Property*>& regions_def,
const Topology& top) const {
std::vector<int> explicitly_named_segs_per_region;
std::vector<std::vector<SegId> > segids_per_region;
std::vector<bool> processed_segments =
std::vector<bool>(top.Segments().size(), false);
for (const tools::Property* region_def : regions_def) {
if (!region_def->exists("segments") && !region_def->exists("cutoff")) {
throw std::runtime_error(
"Region definition needs either segments or a cutoff to find "
"segments");
}
std::vector<SegId> seg_ids;
if (region_def->exists("segments")) {
std::string seg_ids_string =
region_def->get("segments").as<std::string>();
tools::Tokenizer tok(seg_ids_string, " \n\t");
for (const std::string& seg_id_string : tok.ToVector()) {
seg_ids.push_back(SegId(seg_id_string));
}
for (const SegId& seg_id : seg_ids) {
if (seg_id.Id() > int(top.Segments().size() - 1)) {
throw std::runtime_error("Segment id is not in topology");
}
processed_segments[seg_id.Id()] = true;
}
}
explicitly_named_segs_per_region.push_back(seg_ids.size());
if (region_def->exists("cutoff")) {
double cutoff = tools::conv::nm2bohr *
region_def->ifExistsReturnElseThrowRuntimeError<double>(
"cutoff.radius");
std::string seg_geometry =
region_def->ifExistsReturnElseReturnDefault<std::string>(
"cutoff.geometry", "n");
double min = top.getBox().diagonal().minCoeff();
if (cutoff > 0.5 * min) {
throw std::runtime_error(
(boost::format("Cutoff is larger than half the box size. Maximum "
"allowed cutoff is %1$1.1f") %
(tools::conv::bohr2nm * 0.5 * min))
.str());
}
std::vector<SegId> center = seg_ids;
if (region_def->exists("cutoff.region")) {
int id = region_def->get("cutoff.region").as<int>();
bool only_explicit = region_def->ifExistsReturnElseReturnDefault<bool>(
"cutoff.relative_to_explicit_segs", false);
if (id < int(segids_per_region.size())) {
center = segids_per_region[id];
if (only_explicit) {
int no_of_segs = explicitly_named_segs_per_region[id];
if (no_of_segs == 0) {
throw std::runtime_error("Region with id '" + std::to_string(id) +
"' does not have");
}
center.resize(no_of_segs, SegId(0, "n"));
// need the second argument because resize can also increase
// capacity of vector and then needs a constructor,
// here we shrink, so should not happen
}
} else {
throw std::runtime_error("Region with id '" + std::to_string(id) +
"' used for cutoff does not exist");
}
}
if (center.empty()) {
throw std::runtime_error(
"Region needs either a segment or another region to which to apply "
"the cutoff");
}
for (const SegId& segid : center) {
const Segment& center_seg = top.getSegment(segid.Id());
for (const Segment& otherseg : top.Segments()) {
if (center_seg.getId() == otherseg.getId() ||
processed_segments[otherseg.getId()]) {
continue;
}
if (top.PbShortestConnect(center_seg.getPos(), otherseg.getPos())
.norm() < cutoff) {
seg_ids.push_back(SegId(otherseg.getId(), seg_geometry));
processed_segments[otherseg.getId()] = true;
}
}
}
}
segids_per_region.push_back(seg_ids);
}
return segids_per_region;
}
void JobTopology::CheckEnumerationOfRegions(
const std::vector<tools::Property*>& regions_def) const {
std::vector<int> reg_ids;
for (const tools::Property* region_def : regions_def) {
reg_ids.push_back(
region_def->ifExistsReturnElseThrowRuntimeError<int>("id"));
}
std::vector<int> v(reg_ids.size());
std::iota(v.begin(), v.end(), 0);
if (!std::is_permutation(reg_ids.begin(), reg_ids.end(), v.begin())) {
throw std::runtime_error(
"Region id definitions are not clear. You must start at id 0 and then "
"ascending order. i.e. 0 1 2 3.");
}
}
void JobTopology::WriteToHdf5(std::string filename) const {
CheckpointFile cpf(filename, CheckpointAccessLevel::CREATE);
CheckpointWriter a = cpf.getWriter();
a(_job.getId(), "jobid");
for (const auto& region : _regions) {
CheckpointWriter w =
cpf.getWriter("region_" + std::to_string(region->getId()));
region->WriteToCpt(w);
}
}
} // namespace xtp
} // namespace votca
<commit_msg>removed couts<commit_after>/*
* Copyright 2009-2019 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 <numeric>
#include <votca/xtp/checkpoint.h>
#include <votca/xtp/jobtopology.h>
#include <votca/xtp/polarregion.h>
#include <votca/xtp/qmregion.h>
#include <votca/xtp/segmentmapper.h>
#include <votca/xtp/staticregion.h>
namespace votca {
namespace xtp {
void JobTopology::SortRegionsDefbyId(
std::vector<tools::Property*>& regions_def) const {
std::sort(regions_def.begin(), regions_def.end(),
[](const tools::Property* A, const tools::Property* B) {
return (A->get("id").as<int>()) < (B->get("id").as<int>());
});
}
void JobTopology::ModifyOptionsByJobFile(
std::vector<tools::Property*>& regions_def) const {
const tools::Property& jobinput = _job.getInput();
std::vector<const tools::Property*> regions_def_job =
jobinput.Select("regions.region");
std::string tag = "jobfile";
for (tools::Property* prop : regions_def) {
int id = prop->get("id").as<int>();
std::vector<std::string> paths = FindReplacePathsInOptions(*prop, tag);
if (!paths.empty()) {
XTP_LOG_SAVE(logINFO, _log) << " Region " << std::to_string(id)
<< " is modified by jobfile" << std::flush;
XTP_LOG_SAVE(logINFO, _log)
<< " Replacing the following paths with jobfile entries"
<< std::flush;
for (const std::string& path : paths) {
XTP_LOG_SAVE(logINFO, _log) << " - " << path << std::flush;
}
bool found_region_in_jobfile = false;
const tools::Property* job_prop = nullptr;
for (const tools::Property* prop_job : regions_def_job) {
int id2 = prop_job->get("id").as<int>();
if (id2 == id) {
job_prop = prop_job;
found_region_in_jobfile = true;
}
}
if (!found_region_in_jobfile) {
throw std::runtime_error("Region " + std::to_string(id) +
" was not found in jobfile.");
}
UpdateFromJobfile(*prop, *job_prop, paths);
}
}
}
void JobTopology::BuildRegions(const Topology& top, tools::Property options) {
std::vector<tools::Property*> regions_def = options.Select("region");
CheckEnumerationOfRegions(regions_def);
SortRegionsDefbyId(regions_def);
ModifyOptionsByJobFile(regions_def);
std::vector<std::vector<SegId> > region_seg_ids =
PartitionRegions(regions_def, top);
// around this point the whole jobtopology will be centered
CreateRegions(options, top, region_seg_ids);
XTP_LOG_SAVE(logINFO, _log) << " Regions created" << std::flush;
for (const auto& region : _regions) {
XTP_LOG_SAVE(logINFO, _log) << *region << std::flush;
}
return;
}
std::vector<std::string> JobTopology::FindReplacePathsInOptions(
const tools::Property& options, std::string tag) const {
std::vector<std::string> result;
std::string options_path = "options.qmmm.regions.region";
for (const tools::Property& sub : options) {
if (sub.HasChildren()) {
std::vector<std::string> subresult = FindReplacePathsInOptions(sub, tag);
result.insert(result.end(), subresult.begin(), subresult.end());
} else if (sub.value() == tag) {
std::string path = sub.path() + "." + sub.name();
std::size_t pos = path.find(options_path);
if (pos != std::string::npos) {
path.replace(pos, options_path.size(), "");
}
result.push_back(path);
}
}
return result;
}
void JobTopology::UpdateFromJobfile(
tools::Property& options, const tools::Property& job_opt,
const std::vector<std::string>& paths) const {
for (const std::string& path : paths) {
if (job_opt.exists(path)) {
options.set(path, job_opt.get(path).value());
} else {
throw std::runtime_error("Jobfile does not contain options for " + path);
}
}
}
template <class T>
void JobTopology::ShiftPBC(const Topology& top, const Eigen::Vector3d& center,
T& mol) const {
Eigen::Vector3d r_pbc = top.PbShortestConnect(center, mol.getPos());
Eigen::Vector3d r = mol.getPos() - center;
Eigen::Vector3d shift = r_pbc - r;
if (shift.norm() > 1e-9) {
mol.Translate(shift);
}
}
void JobTopology::CreateRegions(
const tools::Property& options, const Topology& top,
const std::vector<std::vector<SegId> >& region_seg_ids) {
std::string mapfile =
options.ifExistsReturnElseThrowRuntimeError<std::string>("mapfile");
std::vector<const tools::Property*> regions_def = options.Select("region");
// around this point the whole jobtopology will be centered for removing pbc
Eigen::Vector3d center = top.getSegment(region_seg_ids[0][0].Id()).getPos();
for (const tools::Property* region_def : regions_def) {
int id = region_def->ifExistsReturnElseThrowRuntimeError<int>("id");
const std::vector<SegId>& seg_ids = region_seg_ids[id];
std::string type =
region_def->ifExistsReturnElseThrowRuntimeError<std::string>("type");
std::unique_ptr<Region> region;
QMRegion QMdummy(0, _log, "");
StaticRegion Staticdummy(0, _log);
PolarRegion Polardummy(0, _log);
if (type == QMdummy.identify()) {
std::unique_ptr<QMRegion> qmregion =
std::unique_ptr<QMRegion>(new QMRegion(id, _log, _workdir));
QMMapper qmmapper(_log);
qmmapper.LoadMappingFile(mapfile);
for (const SegId& seg_index : seg_ids) {
const Segment& segment = top.getSegment(seg_index.Id());
QMMolecule mol = qmmapper.map(segment, seg_index);
mol.setName("qm" + std::to_string(id));
ShiftPBC(top, center, mol);
qmregion->push_back(mol);
}
region = std::move(qmregion);
} else if (type == Polardummy.identify()) {
std::unique_ptr<PolarRegion> polarregion =
std::unique_ptr<PolarRegion>(new PolarRegion(id, _log));
PolarMapper polmap(_log);
polmap.LoadMappingFile(mapfile);
for (const SegId& seg_index : seg_ids) {
const Segment& segment = top.getSegment(seg_index.Id());
PolarSegment mol = polmap.map(segment, seg_index);
ShiftPBC(top, center, mol);
mol.setName("mm" + std::to_string(id));
polarregion->push_back(mol);
}
region = std::move(polarregion);
} else if (type == Staticdummy.identify()) {
std::unique_ptr<StaticRegion> staticregion =
std::unique_ptr<StaticRegion>(new StaticRegion(id, _log));
StaticMapper staticmap(_log);
staticmap.LoadMappingFile(mapfile);
for (const SegId& seg_index : seg_ids) {
const Segment& segment = top.getSegment(seg_index.Id());
StaticSegment mol = staticmap.map(segment, seg_index);
mol.setName("mm" + std::to_string(id));
ShiftPBC(top, center, mol);
staticregion->push_back(mol);
}
region = std::move(staticregion);
} else {
throw std::runtime_error("Region type not known!");
}
region->Initialize(*region_def);
_regions.push_back(std::move(region));
}
}
void JobTopology::WriteToPdb(std::string filename) const {
csg::PDBWriter writer;
writer.Open(filename, false);
writer.WriteHeader("Job:" + std::to_string(this->_job.getId()));
for (const std::unique_ptr<Region>& reg : _regions) {
reg->WritePDB(writer);
}
writer.Close();
}
std::vector<std::vector<SegId> > JobTopology::PartitionRegions(
const std::vector<tools::Property*>& regions_def,
const Topology& top) const {
std::vector<int> explicitly_named_segs_per_region;
std::vector<std::vector<SegId> > segids_per_region;
std::vector<bool> processed_segments =
std::vector<bool>(top.Segments().size(), false);
for (const tools::Property* region_def : regions_def) {
if (!region_def->exists("segments") && !region_def->exists("cutoff")) {
throw std::runtime_error(
"Region definition needs either segments or a cutoff to find "
"segments");
}
std::vector<SegId> seg_ids;
if (region_def->exists("segments")) {
std::string seg_ids_string =
region_def->get("segments").as<std::string>();
tools::Tokenizer tok(seg_ids_string, " \n\t");
for (const std::string& seg_id_string : tok.ToVector()) {
seg_ids.push_back(SegId(seg_id_string));
}
for (const SegId& seg_id : seg_ids) {
if (seg_id.Id() > int(top.Segments().size() - 1)) {
throw std::runtime_error("Segment id is not in topology");
}
processed_segments[seg_id.Id()] = true;
}
}
explicitly_named_segs_per_region.push_back(seg_ids.size());
if (region_def->exists("cutoff")) {
double cutoff = tools::conv::nm2bohr *
region_def->ifExistsReturnElseThrowRuntimeError<double>(
"cutoff.radius");
std::string seg_geometry =
region_def->ifExistsReturnElseReturnDefault<std::string>(
"cutoff.geometry", "n");
double min = top.getBox().diagonal().minCoeff();
if (cutoff > 0.5 * min) {
throw std::runtime_error(
(boost::format("Cutoff is larger than half the box size. Maximum "
"allowed cutoff is %1$1.1f") %
(tools::conv::bohr2nm * 0.5 * min))
.str());
}
std::vector<SegId> center = seg_ids;
if (region_def->exists("cutoff.region")) {
int id = region_def->get("cutoff.region").as<int>();
bool only_explicit = region_def->ifExistsReturnElseReturnDefault<bool>(
"cutoff.relative_to_explicit_segs", false);
if (id < int(segids_per_region.size())) {
center = segids_per_region[id];
if (only_explicit) {
int no_of_segs = explicitly_named_segs_per_region[id];
if (no_of_segs == 0) {
throw std::runtime_error("Region with id '" + std::to_string(id) +
"' does not have");
}
center.resize(no_of_segs, SegId(0, "n"));
// need the second argument because resize can also increase
// capacity of vector and then needs a constructor,
// here we shrink, so should not happen
}
} else {
throw std::runtime_error("Region with id '" + std::to_string(id) +
"' used for cutoff does not exist");
}
}
if (center.empty()) {
throw std::runtime_error(
"Region needs either a segment or another region to which to apply "
"the cutoff");
}
for (const SegId& segid : center) {
const Segment& center_seg = top.getSegment(segid.Id());
for (const Segment& otherseg : top.Segments()) {
if (center_seg.getId() == otherseg.getId() ||
processed_segments[otherseg.getId()]) {
continue;
}
if (top.PbShortestConnect(center_seg.getPos(), otherseg.getPos())
.norm() < cutoff) {
seg_ids.push_back(SegId(otherseg.getId(), seg_geometry));
processed_segments[otherseg.getId()] = true;
}
}
}
}
segids_per_region.push_back(seg_ids);
}
return segids_per_region;
}
void JobTopology::CheckEnumerationOfRegions(
const std::vector<tools::Property*>& regions_def) const {
std::vector<int> reg_ids;
for (const tools::Property* region_def : regions_def) {
reg_ids.push_back(
region_def->ifExistsReturnElseThrowRuntimeError<int>("id"));
}
std::vector<int> v(reg_ids.size());
std::iota(v.begin(), v.end(), 0);
if (!std::is_permutation(reg_ids.begin(), reg_ids.end(), v.begin())) {
throw std::runtime_error(
"Region id definitions are not clear. You must start at id 0 and then "
"ascending order. i.e. 0 1 2 3.");
}
}
void JobTopology::WriteToHdf5(std::string filename) const {
CheckpointFile cpf(filename, CheckpointAccessLevel::CREATE);
CheckpointWriter a = cpf.getWriter();
a(_job.getId(), "jobid");
for (const auto& region : _regions) {
CheckpointWriter w =
cpf.getWriter("region_" + std::to_string(region->getId()));
region->WriteToCpt(w);
}
}
} // namespace xtp
} // namespace votca
<|endoftext|> |
<commit_before>#ifndef DUNE_STUFF_RANGES_RANGES_HH
#define DUNE_STUFF_RANGES_RANGES_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
#if HAVE_DUNE_GRID
#include <dune/stuff/common/disable_warnings.hh>
#include <dune/grid/common/gridview.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#include <boost/serialization/static_warning.hpp>
#endif
#if HAVE_DUNE_FEM
#include <dune/fem/version.hh>
#include <dune/stuff/common/disable_warnings.hh>
#include <dune/fem/function/common/discretefunction.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#include <dune/fem/gridpart/common/gridpart.hh>
#endif
#include <dune/stuff/common/math.hh>
#include <dune/stuff/fem/namespace.hh>
namespace Dune {
#if HAVE_DUNE_FEM
namespace Fem {
template < class DiscreteFunctionTraits >
auto begin( const Dune::Fem::DiscreteFunctionInterface< DiscreteFunctionTraits >& func )
-> decltype(func.dbegin())
{
return func.dbegin();
}
template < class DiscreteFunctionTraits >
auto end( const Dune::Fem::DiscreteFunctionInterface< DiscreteFunctionTraits >& func )
-> decltype(func.dend())
{
return func.dend();
}
template < class DiscreteFunctionTraits >
auto begin( Dune::Fem::DiscreteFunctionInterface< DiscreteFunctionTraits >& func )
-> decltype(func.dbegin())
{
return func.dbegin();
}
template < class DiscreteFunctionTraits >
auto end( Dune::Fem::DiscreteFunctionInterface< DiscreteFunctionTraits >& func )
-> decltype(func.dend())
{
return func.dend();
}
} // namespace Fem
#endif
} //namespace Dune
namespace Dune {
namespace Stuff {
namespace Common {
#if HAVE_DUNE_GRID
//! adapter enabling view usage in range-based for
template < class GridViewType, int codim = 0>
class ViewRange {
const GridViewType& view_;
public:
ViewRange(const GridViewType& view)
:view_(view)
{
BOOST_STATIC_WARNING(codim == 0 && "unnecessary ViewRange usage with codim 0");
}
typename GridViewType::template Codim< codim >::Iterator
begin() const {
return view_.template begin< codim >();
}
typename GridViewType::template Codim< codim >::Iterator
end() const {
return view_.template end< codim >();
}
};
template < class GridViewTraits, int codim = 0>
ViewRange<Dune::GridView<GridViewTraits>, codim> viewRange(const Dune::GridView<GridViewTraits>& view)
{
return ViewRange<Dune::GridView<GridViewTraits>, codim>(view);
}
/** adapter enabling intersectionniterator usage in range-based for
* works for GridParts and GridViews
*/
template < class GridAbstractionType, class EntityType >
class IntersectionRange {
const GridAbstractionType& view_;
const EntityType& entity_;
public:
IntersectionRange(const GridAbstractionType& view, const EntityType& entity)
: view_(view)
, entity_(entity)
{}
auto begin() const -> decltype(view_.ibegin(entity_)) {
return view_.ibegin(entity_);
}
auto end() const -> decltype(view_.iend(entity_)) {
return view_.iend(entity_);
}
};
template < class GridViewTraits>
IntersectionRange<Dune::GridView<GridViewTraits>,
typename Dune::GridView<GridViewTraits>::template Codim< 0 >::Entity>
intersectionRange(const Dune::GridView<GridViewTraits>& gridview,
const typename Dune::GridView<GridViewTraits>::template Codim< 0 >::Entity& entity)
{
return IntersectionRange<Dune::GridView<GridViewTraits>,
typename Dune::GridView<GridViewTraits>::template Codim< 0 >::Entity>(gridview, entity);
}
#endif //#if HAVE_DUNE_GRID
#if HAVE_DUNE_FEM
//! Range adapter for lagrange points from lagrange spaces
template < class DiscreteFunctionspaceType, int faceCodim >
class LagrangePointSetRange {
typedef typename DiscreteFunctionspaceType::LagrangePointSetType
LagrangePointSetType;
typedef typename LagrangePointSetType::template Codim< faceCodim >::SubEntityIteratorType
SubEntityIteratorType;
const LagrangePointSetType& lp_set_;
const unsigned int subEntity_;
public:
/** the template isn't lazyness here, the underlying set is templated on it too
*/
template < class EntityType >
LagrangePointSetRange(const DiscreteFunctionspaceType& space, const EntityType& entity, const unsigned int subEntity)
: lp_set_(space.lagrangePointSet(entity))
, subEntity_(subEntity)
{}
SubEntityIteratorType begin() const {
return lp_set_.template beginSubEntity< faceCodim >(subEntity_);
}
SubEntityIteratorType end() const {
return lp_set_.template endSubEntity< faceCodim >(subEntity_);
}
};
template < int codim, class DiscreteFunctionspaceType, class EntityType >
LagrangePointSetRange<DiscreteFunctionspaceType,codim>
lagrangePointSetRange(const DiscreteFunctionspaceType& space, const EntityType& entity, const int subEntity) {
return LagrangePointSetRange<DiscreteFunctionspaceType,codim>(space, entity, subEntity);
}
template < class GridPartTraits >
IntersectionRange<Dune::Fem::GridPartInterface<GridPartTraits>,
typename Dune::Fem::GridPartInterface<GridPartTraits>::template Codim< 0 >::EntityType>
intersectionRange(const Dune::Fem::GridPartInterface<GridPartTraits>& gridpart,
const typename Dune::Fem::GridPartInterface<GridPartTraits>::template Codim< 0 >::EntityType& entity)
{
return IntersectionRange<Dune::Fem::GridPartInterface<GridPartTraits>,
typename Dune::Fem::GridPartInterface<GridPartTraits>::template Codim< 0 >::EntityType>(gridpart, entity);
}
#endif //HAVE_DUNE_FEM
//! get a vector with values in [start : increment : end)
template < class T, class sequence = std::vector<T> >
sequence valueRange(const T start, const T end, const T increment = Epsilon<T>::value) {
sequence ret(typename sequence::size_type(((end>start) ? end-start : start-end)/increment), start);
typename sequence::size_type i = 0;
std::generate(std::begin(ret), std::end(ret), [&](){ return T(start + (increment * i++)); });
return ret;
}
//! get a vector with values in [0 : Epsilon<T> : end)
template < class T, class sequence = std::vector<T> >
sequence valueRange(const T end) {
return valueRange(T(0),end);
}
} // namespace Common
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_RANGES_RANGES_HH
/** Copyright (c) 2012, Felix Albrecht, Rene Milk
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the FreeBSD Project.
**/
<commit_msg>[common] fix value ranges with neg. stepsize<commit_after>#ifndef DUNE_STUFF_RANGES_RANGES_HH
#define DUNE_STUFF_RANGES_RANGES_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
#if HAVE_DUNE_GRID
#include <dune/stuff/common/disable_warnings.hh>
#include <dune/grid/common/gridview.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#include <boost/serialization/static_warning.hpp>
#endif
#if HAVE_DUNE_FEM
#include <dune/fem/version.hh>
#include <dune/stuff/common/disable_warnings.hh>
#include <dune/fem/function/common/discretefunction.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#include <dune/fem/gridpart/common/gridpart.hh>
#endif
#include <dune/stuff/common/math.hh>
#include <dune/stuff/fem/namespace.hh>
namespace Dune {
#if HAVE_DUNE_FEM
namespace Fem {
template < class DiscreteFunctionTraits >
auto begin( const Dune::Fem::DiscreteFunctionInterface< DiscreteFunctionTraits >& func )
-> decltype(func.dbegin())
{
return func.dbegin();
}
template < class DiscreteFunctionTraits >
auto end( const Dune::Fem::DiscreteFunctionInterface< DiscreteFunctionTraits >& func )
-> decltype(func.dend())
{
return func.dend();
}
template < class DiscreteFunctionTraits >
auto begin( Dune::Fem::DiscreteFunctionInterface< DiscreteFunctionTraits >& func )
-> decltype(func.dbegin())
{
return func.dbegin();
}
template < class DiscreteFunctionTraits >
auto end( Dune::Fem::DiscreteFunctionInterface< DiscreteFunctionTraits >& func )
-> decltype(func.dend())
{
return func.dend();
}
} // namespace Fem
#endif
} //namespace Dune
namespace Dune {
namespace Stuff {
namespace Common {
#if HAVE_DUNE_GRID
//! adapter enabling view usage in range-based for
template < class GridViewType, int codim = 0>
class ViewRange {
const GridViewType& view_;
public:
ViewRange(const GridViewType& view)
:view_(view)
{
BOOST_STATIC_WARNING(codim == 0 && "unnecessary ViewRange usage with codim 0");
}
typename GridViewType::template Codim< codim >::Iterator
begin() const {
return view_.template begin< codim >();
}
typename GridViewType::template Codim< codim >::Iterator
end() const {
return view_.template end< codim >();
}
};
template < class GridViewTraits, int codim = 0>
ViewRange<Dune::GridView<GridViewTraits>, codim> viewRange(const Dune::GridView<GridViewTraits>& view)
{
return ViewRange<Dune::GridView<GridViewTraits>, codim>(view);
}
/** adapter enabling intersectionniterator usage in range-based for
* works for GridParts and GridViews
*/
template < class GridAbstractionType, class EntityType >
class IntersectionRange {
const GridAbstractionType& view_;
const EntityType& entity_;
public:
IntersectionRange(const GridAbstractionType& view, const EntityType& entity)
: view_(view)
, entity_(entity)
{}
auto begin() const -> decltype(view_.ibegin(entity_)) {
return view_.ibegin(entity_);
}
auto end() const -> decltype(view_.iend(entity_)) {
return view_.iend(entity_);
}
};
template < class GridViewTraits>
IntersectionRange<Dune::GridView<GridViewTraits>,
typename Dune::GridView<GridViewTraits>::template Codim< 0 >::Entity>
intersectionRange(const Dune::GridView<GridViewTraits>& gridview,
const typename Dune::GridView<GridViewTraits>::template Codim< 0 >::Entity& entity)
{
return IntersectionRange<Dune::GridView<GridViewTraits>,
typename Dune::GridView<GridViewTraits>::template Codim< 0 >::Entity>(gridview, entity);
}
#endif //#if HAVE_DUNE_GRID
#if HAVE_DUNE_FEM
//! Range adapter for lagrange points from lagrange spaces
template < class DiscreteFunctionspaceType, int faceCodim >
class LagrangePointSetRange {
typedef typename DiscreteFunctionspaceType::LagrangePointSetType
LagrangePointSetType;
typedef typename LagrangePointSetType::template Codim< faceCodim >::SubEntityIteratorType
SubEntityIteratorType;
const LagrangePointSetType& lp_set_;
const unsigned int subEntity_;
public:
/** the template isn't lazyness here, the underlying set is templated on it too
*/
template < class EntityType >
LagrangePointSetRange(const DiscreteFunctionspaceType& space, const EntityType& entity, const unsigned int subEntity)
: lp_set_(space.lagrangePointSet(entity))
, subEntity_(subEntity)
{}
SubEntityIteratorType begin() const {
return lp_set_.template beginSubEntity< faceCodim >(subEntity_);
}
SubEntityIteratorType end() const {
return lp_set_.template endSubEntity< faceCodim >(subEntity_);
}
};
template < int codim, class DiscreteFunctionspaceType, class EntityType >
LagrangePointSetRange<DiscreteFunctionspaceType,codim>
lagrangePointSetRange(const DiscreteFunctionspaceType& space, const EntityType& entity, const int subEntity) {
return LagrangePointSetRange<DiscreteFunctionspaceType,codim>(space, entity, subEntity);
}
template < class GridPartTraits >
IntersectionRange<Dune::Fem::GridPartInterface<GridPartTraits>,
typename Dune::Fem::GridPartInterface<GridPartTraits>::template Codim< 0 >::EntityType>
intersectionRange(const Dune::Fem::GridPartInterface<GridPartTraits>& gridpart,
const typename Dune::Fem::GridPartInterface<GridPartTraits>::template Codim< 0 >::EntityType& entity)
{
return IntersectionRange<Dune::Fem::GridPartInterface<GridPartTraits>,
typename Dune::Fem::GridPartInterface<GridPartTraits>::template Codim< 0 >::EntityType>(gridpart, entity);
}
#endif //HAVE_DUNE_FEM
//! get a vector with values in [start : increment : end)
template < class T, class sequence = std::vector<T> >
sequence valueRange(const T start, const T end, const T increment = Epsilon<T>::value) {
sequence ret(typename sequence::size_type(((end>start) ? end-start : start-end)/std::abs(increment)), start);
typename sequence::size_type i = 0;
std::generate(std::begin(ret), std::end(ret), [&](){ return T(start + (increment * i++)); });
return ret;
}
//! get a vector with values in [0 : Epsilon<T> : end)
template < class T, class sequence = std::vector<T> >
sequence valueRange(const T end) {
return valueRange(T(0),end);
}
} // namespace Common
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_RANGES_RANGES_HH
/** Copyright (c) 2012, Felix Albrecht, Rene Milk
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the FreeBSD Project.
**/
<|endoftext|> |
<commit_before>/*
Copyright (c) 2012, William Magato
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) 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(S) OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the copyright holder(s) or contributors.
*/
#include <cstdint>
#include <cstring>
#include <ios>
#include <stdexcept>
#include <xen/xen.h>
#include <xen/features.h>
#include <xen/version.h>
#include <llamaos/memory/memory.h>
#include <llamaos/xen/Hypercall.h>
#include <llamaos/xen/Hypervisor.h>
#include <llamaos/config.h>
#include <llamaos/trace.h>
using namespace std;
using namespace llamaos;
using namespace llamaos::xen;
namespace llamaos {
namespace memory {
// needs initialized by startup logic
extern uint64_t *machine_table;
extern uint64_t machine_table_size;
extern uint64_t *pseudo_table;
extern uint64_t pseudo_table_size;
} }
// runtime stack memory
char RUNTIME_STACK [2 * llamaos::STACK_SIZE];
uint8_t xen_features [XENFEAT_NR_SUBMAPS * 32];
static bool verify_magic (const start_info_t *start_info)
{
if ( (nullptr != start_info)
&& (0 == strncmp (start_info->magic, "xen-", 4)))
{
return true;
}
return false;
}
static void trace_startup (const start_info_t *start_info)
{
trace ("\n\n\n*********************************\n");
trace ( "**** starting llamaOS (Xen) ***\n");
trace ( "*********************************\n\n\n");
trace ("%s\n\n", VERSION_TEXT);
trace ("=== start_info ===\n");
trace (" magic: %s\n", start_info->magic);
trace (" nr_pages: %x\n", start_info->nr_pages);
trace (" shared_info: %x\n", start_info->shared_info);
trace (" flags: %x\n", start_info->flags);
trace (" store_mfn: %x\n", start_info->store_mfn);
trace (" store_evtchn: %x\n", start_info->store_evtchn);
trace (" console.domU.mfn: %x\n", start_info->console.domU.mfn);
trace (" console.domU.evtchn: %x\n", start_info->console.domU.evtchn);
trace (" pt_base: %x\n", start_info->pt_base);
trace (" nr_pt_frames: %x\n", start_info->nr_pt_frames);
trace (" mfn_list: %x\n", start_info->mfn_list);
trace (" mod_start: %x\n", start_info->mod_start);
trace (" mod_len: %x\n", start_info->mod_len);
trace (" cmd_line: %s\n", start_info->cmd_line);
trace (" first_p2m_pfn: %x\n", start_info->first_p2m_pfn);
trace (" nr_p2m_frames: %x\n", start_info->nr_p2m_frames);
trace ("\n");
}
extern int main (int, char*[]);
void register_glibc_exports ();
typedef void (*func_ptr) (void);
extern func_ptr __CTOR_LIST__[];
extern func_ptr __DTOR_LIST__[];
static const char *program_name = "llamaOS";
extern "C"
void start (start_info_t *start_info)
{
if (verify_magic (start_info))
{
trace_startup (start_info);
// initialize memory management
memory::machine_table = memory::address_to_pointer<uint64_t>(MACH2PHYS_VIRT_START);
memory::machine_table_size = MACH2PHYS_NR_ENTRIES;
memory::pseudo_table = memory::address_to_pointer<uint64_t> (start_info->mfn_list);
memory::pseudo_table_size = start_info->nr_pages;
memory::initialize (start_info->pt_base, start_info->nr_pages);
// register callbacks to the glibc library
register_glibc_exports ();
uint64_t ctor_size = reinterpret_cast<uint64_t>(__CTOR_LIST__[0]);
trace ("__CTOR_LIST__[0]: %lx\n", ctor_size);
for (uint64_t i = ctor_size; i >= 1; i--)
{
__CTOR_LIST__[i] ();
}
// initialize libstdc++
ios_base::Init ios_base_init;
try
{
// create the one and only hypervisor object
trace ("Creating Hypervisor...\n");
Hypervisor hypervisor (start_info);
// start the application
char *argv [2];
argv [0] = const_cast<char *>(program_name);
argv [1] = 0;
main (1, argv);
trace ("ending llamaOS...\n");
for (;;);
}
catch (const std::runtime_error &e)
{
trace ("*** runtime_error: %s ***\n", e.what ());
}
catch (...)
{
trace ("*** unknown exception ***\n");
}
Hypercall::sched_op_shutdown ();
uint64_t dtor_size = reinterpret_cast<uint64_t>(__DTOR_LIST__[0]);
trace ("__DTOR_LIST__[0]: %lx\n", dtor_size);
for (uint64_t i = dtor_size; i >= 1; i--)
{
__DTOR_LIST__[i] ();
}
}
// else
// something terrible is wrong and nothing can be done about it!
}
<commit_msg>yield at close of start to stop 100 pct cpu<commit_after>/*
Copyright (c) 2012, William Magato
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) 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(S) OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the copyright holder(s) or contributors.
*/
#include <cstdint>
#include <cstring>
#include <ios>
#include <stdexcept>
#include <xen/xen.h>
#include <xen/features.h>
#include <xen/version.h>
#include <llamaos/memory/memory.h>
#include <llamaos/xen/Hypercall.h>
#include <llamaos/xen/Hypervisor.h>
#include <llamaos/config.h>
#include <llamaos/trace.h>
using namespace std;
using namespace llamaos;
using namespace llamaos::xen;
namespace llamaos {
namespace memory {
// needs initialized by startup logic
extern uint64_t *machine_table;
extern uint64_t machine_table_size;
extern uint64_t *pseudo_table;
extern uint64_t pseudo_table_size;
} }
// runtime stack memory
char RUNTIME_STACK [2 * llamaos::STACK_SIZE];
uint8_t xen_features [XENFEAT_NR_SUBMAPS * 32];
static bool verify_magic (const start_info_t *start_info)
{
if ( (nullptr != start_info)
&& (0 == strncmp (start_info->magic, "xen-", 4)))
{
return true;
}
return false;
}
static void trace_startup (const start_info_t *start_info)
{
trace ("\n\n\n*********************************\n");
trace ( "**** starting llamaOS (Xen) ***\n");
trace ( "*********************************\n\n\n");
trace ("%s\n\n", VERSION_TEXT);
trace ("=== start_info ===\n");
trace (" magic: %s\n", start_info->magic);
trace (" nr_pages: %x\n", start_info->nr_pages);
trace (" shared_info: %x\n", start_info->shared_info);
trace (" flags: %x\n", start_info->flags);
trace (" store_mfn: %x\n", start_info->store_mfn);
trace (" store_evtchn: %x\n", start_info->store_evtchn);
trace (" console.domU.mfn: %x\n", start_info->console.domU.mfn);
trace (" console.domU.evtchn: %x\n", start_info->console.domU.evtchn);
trace (" pt_base: %x\n", start_info->pt_base);
trace (" nr_pt_frames: %x\n", start_info->nr_pt_frames);
trace (" mfn_list: %x\n", start_info->mfn_list);
trace (" mod_start: %x\n", start_info->mod_start);
trace (" mod_len: %x\n", start_info->mod_len);
trace (" cmd_line: %s\n", start_info->cmd_line);
trace (" first_p2m_pfn: %x\n", start_info->first_p2m_pfn);
trace (" nr_p2m_frames: %x\n", start_info->nr_p2m_frames);
trace ("\n");
}
extern int main (int, char*[]);
void register_glibc_exports ();
typedef void (*func_ptr) (void);
extern func_ptr __CTOR_LIST__[];
extern func_ptr __DTOR_LIST__[];
static const char *program_name = "llamaOS";
extern "C"
void start (start_info_t *start_info)
{
if (verify_magic (start_info))
{
trace_startup (start_info);
// initialize memory management
memory::machine_table = memory::address_to_pointer<uint64_t>(MACH2PHYS_VIRT_START);
memory::machine_table_size = MACH2PHYS_NR_ENTRIES;
memory::pseudo_table = memory::address_to_pointer<uint64_t> (start_info->mfn_list);
memory::pseudo_table_size = start_info->nr_pages;
memory::initialize (start_info->pt_base, start_info->nr_pages);
// register callbacks to the glibc library
register_glibc_exports ();
uint64_t ctor_size = reinterpret_cast<uint64_t>(__CTOR_LIST__[0]);
trace ("__CTOR_LIST__[0]: %lx\n", ctor_size);
for (uint64_t i = ctor_size; i >= 1; i--)
{
__CTOR_LIST__[i] ();
}
// initialize libstdc++
ios_base::Init ios_base_init;
try
{
// create the one and only hypervisor object
trace ("Creating Hypervisor...\n");
Hypervisor hypervisor (start_info);
// start the application
char *argv [2];
argv [0] = const_cast<char *>(program_name);
argv [1] = 0;
main (1, argv);
trace ("ending llamaOS...\n");
}
catch (const std::runtime_error &e)
{
trace ("*** runtime_error: %s ***\n", e.what ());
}
catch (...)
{
trace ("*** unknown exception ***\n");
}
Hypercall::sched_op_shutdown ();
uint64_t dtor_size = reinterpret_cast<uint64_t>(__DTOR_LIST__[0]);
trace ("__DTOR_LIST__[0]: %lx\n", dtor_size);
for (uint64_t i = dtor_size; i >= 1; i--)
{
__DTOR_LIST__[i] ();
}
for (;;)
{
Hypercall::sched_op_yield ();
}
}
// else
// something terrible is wrong and nothing can be done about it!
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.