text stringlengths 54 60.6k |
|---|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "qmlprofilertool.h"
#include "qmlprofilerengine.h"
#include "qmlprofilerplugin.h"
#include "qmlprofilerconstants.h"
#include "qmlprofilerattachdialog.h"
#include "qmlprofilersummaryview.h"
#include "tracewindow.h"
#include "timelineview.h"
#include <qmljsdebugclient/qdeclarativedebugclient_p.h>
#include <analyzerbase/analyzermanager.h>
#include <analyzerbase/analyzerconstants.h>
#include "canvas/qdeclarativecanvas_p.h"
#include "canvas/qdeclarativecontext2d_p.h"
#include "canvas/qdeclarativetiledcanvas_p.h"
#include <qmlprojectmanager/qmlprojectrunconfiguration.h>
#include <utils/fancymainwindow.h>
#include <utils/fileinprojectfinder.h>
#include <utils/qtcassert.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
#include <texteditor/itexteditor.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/icore.h>
#include <QtCore/QFile>
#include <QtGui/QHBoxLayout>
#include <QtGui/QLabel>
#include <QtGui/QTabWidget>
#include <QtGui/QToolButton>
using namespace Analyzer;
using namespace QmlProfiler::Internal;
class QmlProfilerTool::QmlProfilerToolPrivate
{
public:
QmlProfilerToolPrivate(QmlProfilerTool *qq) : q(qq) {}
~QmlProfilerToolPrivate() {}
QmlProfilerTool *q;
QDeclarativeDebugConnection *m_client;
QTimer m_connectionTimer;
int m_connectionAttempts;
TraceWindow *m_traceWindow;
QmlProfilerSummaryView *m_summary;
ProjectExplorer::Project *m_project;
Utils::FileInProjectFinder m_projectFinder;
ProjectExplorer::RunConfiguration *m_runConfiguration;
bool m_isAttached;
QAction *m_attachAction;
QToolButton *m_recordButton;
bool m_recordingEnabled;
QString m_host;
quint64 m_port;
};
QmlProfilerTool::QmlProfilerTool(QObject *parent)
: IAnalyzerTool(parent), d(new QmlProfilerToolPrivate(this))
{
d->m_client = 0;
d->m_connectionAttempts = 0;
d->m_traceWindow = 0;
d->m_project = 0;
d->m_runConfiguration = 0;
d->m_isAttached = false;
d->m_attachAction = 0;
d->m_recordingEnabled = true;
d->m_connectionTimer.setInterval(200);
connect(&d->m_connectionTimer, SIGNAL(timeout()), SLOT(tryToConnect()));
}
QmlProfilerTool::~QmlProfilerTool()
{
delete d->m_client;
delete d;
}
QString QmlProfilerTool::id() const
{
return "QmlProfiler";
}
QString QmlProfilerTool::displayName() const
{
return tr("QML Performance Monitor");
}
IAnalyzerTool::ToolMode QmlProfilerTool::mode() const
{
return AnyMode;
}
IAnalyzerEngine *QmlProfilerTool::createEngine(const AnalyzerStartParameters &sp,
ProjectExplorer::RunConfiguration *runConfiguration)
{
QmlProfilerEngine *engine = new QmlProfilerEngine(sp, runConfiguration);
d->m_host = sp.connParams.host;
d->m_port = sp.connParams.port;
d->m_runConfiguration = runConfiguration;
d->m_project = runConfiguration->target()->project();
if (d->m_project) {
d->m_projectFinder.setProjectDirectory(d->m_project->projectDirectory());
updateProjectFileList();
connect(d->m_project, SIGNAL(fileListChanged()), this, SLOT(updateProjectFileList()));
}
connect(engine, SIGNAL(processRunning()), this, SLOT(connectClient()));
connect(engine, SIGNAL(finished()), this, SLOT(disconnectClient()));
connect(engine, SIGNAL(stopRecording()), this, SLOT(stopRecording()));
connect(d->m_traceWindow, SIGNAL(viewUpdated()), engine, SLOT(dataReceived()));
connect(this, SIGNAL(connectionFailed()), engine, SLOT(finishProcess()));
connect(this, SIGNAL(fetchingData(bool)), engine, SLOT(setFetchingData(bool)));
emit fetchingData(d->m_recordButton->isChecked());
return engine;
}
void QmlProfilerTool::initialize()
{
qmlRegisterType<Canvas>("Monitor", 1, 0, "Canvas");
qmlRegisterType<TiledCanvas>("Monitor", 1, 0, "TiledCanvas");
qmlRegisterType<Context2D>();
qmlRegisterType<CanvasImage>();
qmlRegisterType<CanvasGradient>();
qmlRegisterType<TimelineView>("Monitor", 1, 0,"TimelineView");
}
void QmlProfilerTool::extensionsInitialized()
{
}
void QmlProfilerTool::initializeDockWidgets()
{
Analyzer::AnalyzerManager *analyzerMgr = Analyzer::AnalyzerManager::instance();
Utils::FancyMainWindow *mw = analyzerMgr->mainWindow();
d->m_traceWindow = new TraceWindow(mw);
d->m_traceWindow->reset(d->m_client);
connect(d->m_traceWindow, SIGNAL(gotoSourceLocation(QString,int)),this, SLOT(gotoSourceLocation(QString,int)));
connect(d->m_traceWindow, SIGNAL(timeChanged(qreal)), this, SLOT(updateTimer(qreal)));
d->m_summary = new QmlProfilerSummaryView(mw);
connect(d->m_traceWindow, SIGNAL(range(int,qint64,qint64,QStringList,QString,int)),
d->m_summary, SLOT(addRangedEvent(int,qint64,qint64,QStringList,QString,int)));
connect(d->m_traceWindow, SIGNAL(viewUpdated()),
d->m_summary, SLOT(complete()));
connect(d->m_summary, SIGNAL(gotoSourceLocation(QString,int)),
this, SLOT(gotoSourceLocation(QString,int)));
Core::ICore *core = Core::ICore::instance();
Core::ActionManager *am = core->actionManager();
Core::ActionContainer *manalyzer = am->actionContainer(Analyzer::Constants::M_DEBUG_ANALYZER);
const Core::Context globalcontext(Core::Constants::C_GLOBAL);
d->m_attachAction = new QAction(tr("Attach..."), manalyzer);
Core::Command *command = am->registerAction(d->m_attachAction,
Constants::ATTACH, globalcontext);
command->setAttribute(Core::Command::CA_UpdateText);
manalyzer->addAction(command, Analyzer::Constants::G_ANALYZER_STARTSTOP);
connect(d->m_attachAction, SIGNAL(triggered()), this, SLOT(attach()));
connect(analyzerMgr, SIGNAL(currentToolChanged(Analyzer::IAnalyzerTool*)),
this, SLOT(updateAttachAction()));
updateAttachAction();
QDockWidget *summaryDock =
analyzerMgr->createDockWidget(this, tr("Summary"),
d->m_summary, Qt::BottomDockWidgetArea);
QDockWidget *timelineDock =
analyzerMgr->createDockWidget(this, tr("Timeline"),
d->m_traceWindow, Qt::BottomDockWidgetArea);
mw->splitDockWidget(mw->toolBarDockWidget(), summaryDock, Qt::Vertical);
mw->tabifyDockWidget(summaryDock, timelineDock);
}
QWidget *QmlProfilerTool::createControlWidget()
{
// custom toolbar (TODO)
QWidget *toolbarWidget = new QWidget;
toolbarWidget->setObjectName(QLatin1String("QmlProfilerToolBarWidget"));
QHBoxLayout *layout = new QHBoxLayout;
layout->setMargin(0);
layout->setSpacing(0);
d->m_recordButton = new QToolButton(toolbarWidget);
d->m_recordButton->setIcon(QIcon(QLatin1String(":/qmlprofiler/analyzer_category_small.png")));
d->m_recordButton->setCheckable(true);
connect(d->m_recordButton,SIGNAL(toggled(bool)), this, SLOT(setRecording(bool)));
d->m_recordButton->setChecked(true);
layout->addWidget(d->m_recordButton);
QLabel *timeLabel = new QLabel(QLatin1Char(' ') + tr("Elapsed: 0 s"));
QPalette palette = timeLabel->palette();
palette.setColor(QPalette::WindowText, Qt::white);
timeLabel->setPalette(palette);
connect(this, SIGNAL(setTimeLabel(QString)), timeLabel, SLOT(setText(QString)));
layout->addWidget(timeLabel);
toolbarWidget->setLayout(layout);
return toolbarWidget;
}
void QmlProfilerTool::connectClient()
{
QTC_ASSERT(!d->m_client, return;)
d->m_client = new QDeclarativeDebugConnection;
d->m_traceWindow->reset(d->m_client);
connect(d->m_client, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
this, SLOT(connectionStateChanged()));
d->m_connectionTimer.start();
}
void QmlProfilerTool::connectToClient()
{
if (!d->m_client || d->m_client->state() != QAbstractSocket::UnconnectedState)
return;
if (QmlProfilerPlugin::debugOutput)
qWarning("QmlProfiler: Connecting to %s:%lld ...", qPrintable(d->m_host), d->m_port);
d->m_client->connectToHost(d->m_host, d->m_port);
}
void QmlProfilerTool::disconnectClient()
{
// this might be actually be called indirectly by QDDConnectionPrivate::readyRead(), therefore allow
// method to complete before deleting object
if (d->m_client) {
d->m_client->deleteLater();
d->m_client = 0;
}
}
void QmlProfilerTool::startRecording()
{
if (d->m_client && d->m_client->isConnected()) {
clearDisplay();
d->m_traceWindow->setRecording(true);
}
emit fetchingData(true);
}
void QmlProfilerTool::stopRecording()
{
d->m_traceWindow->setRecording(false);
emit fetchingData(false);
}
void QmlProfilerTool::setRecording(bool recording)
{
d->m_recordingEnabled = recording;
if (recording)
startRecording();
else
stopRecording();
}
void QmlProfilerTool::gotoSourceLocation(const QString &fileUrl, int lineNumber)
{
if (lineNumber < 0 || fileUrl.isEmpty())
return;
const QString fileName = QUrl(fileUrl).toLocalFile();
const QString projectFileName = d->m_projectFinder.findFile(fileName);
Core::EditorManager *editorManager = Core::EditorManager::instance();
Core::IEditor *editor = editorManager->openEditor(projectFileName);
TextEditor::ITextEditor *textEditor = qobject_cast<TextEditor::ITextEditor*>(editor);
if (textEditor) {
editorManager->addCurrentPositionToNavigationHistory();
textEditor->gotoLine(lineNumber);
textEditor->widget()->setFocus();
}
}
void QmlProfilerTool::updateTimer(qreal elapsedSeconds)
{
QString timeString = QString::number(elapsedSeconds,'f',1);
timeString = QString(" ").left(6-timeString.length()) + timeString;
emit setTimeLabel(tr("elapsed: ")+timeString+QLatin1String(" s"));
}
void QmlProfilerTool::updateProjectFileList()
{
d->m_projectFinder.setProjectFiles(
d->m_project->files(ProjectExplorer::Project::ExcludeGeneratedFiles));
}
bool QmlProfilerTool::canRunRemotely() const
{
// TODO: Is this correct?
return true;
}
void QmlProfilerTool::clearDisplay()
{
d->m_traceWindow->clearDisplay();
d->m_summary->clean();
}
void QmlProfilerTool::attach()
{
if (!d->m_isAttached) {
QmlProfilerAttachDialog dialog;
int result = dialog.exec();
if (result == QDialog::Rejected)
return;
d->m_port = dialog.port();
d->m_host = dialog.address();
connectClient();
AnalyzerManager::instance()->showMode();
AnalyzerManager::instance()->popupOutputPane();
} else {
stopRecording();
}
d->m_isAttached = !d->m_isAttached;
updateAttachAction();
}
void QmlProfilerTool::updateAttachAction()
{
if (d->m_attachAction) {
if (d->m_isAttached) {
d->m_attachAction->setText(tr("Detach"));
} else {
d->m_attachAction->setText(tr("Attach..."));
}
}
d->m_attachAction->setEnabled(Analyzer::AnalyzerManager::instance()->currentTool() == this);
}
void QmlProfilerTool::tryToConnect()
{
++d->m_connectionAttempts;
if (d->m_client && d->m_client->isConnected()) {
d->m_connectionTimer.stop();
d->m_connectionAttempts = 0;
} else if (d->m_connectionAttempts == 50) {
d->m_connectionTimer.stop();
d->m_connectionAttempts = 0;
if (QmlProfilerPlugin::debugOutput) {
if (d->m_client) {
qWarning("QmlProfiler: Failed to connect: %s", qPrintable(d->m_client->errorString()));
} else {
qWarning("QmlProfiler: Failed to connect.");
}
}
emit connectionFailed();
} else {
connectToClient();
}
}
void QmlProfilerTool::connectionStateChanged()
{
if (!d->m_client)
return;
switch (d->m_client->state()) {
case QAbstractSocket::UnconnectedState:
{
if (QmlProfilerPlugin::debugOutput)
qWarning("QmlProfiler: disconnected");
break;
}
case QAbstractSocket::HostLookupState:
break;
case QAbstractSocket::ConnectingState: {
if (QmlProfilerPlugin::debugOutput)
qWarning("QmlProfiler: Connecting to debug server ...");
break;
}
case QAbstractSocket::ConnectedState:
{
if (QmlProfilerPlugin::debugOutput)
qWarning("QmlProfiler: connected and running");
updateRecordingState();
break;
}
case QAbstractSocket::ClosingState:
if (QmlProfilerPlugin::debugOutput)
qWarning("QmlProfiler: closing ...");
break;
case QAbstractSocket::BoundState:
case QAbstractSocket::ListeningState:
break;
}
}
void QmlProfilerTool::updateRecordingState()
{
if (d->m_client->isConnected()) {
d->m_traceWindow->setRecording(d->m_recordingEnabled);
} else {
d->m_traceWindow->setRecording(false);
}
if (d->m_traceWindow->isRecording())
clearDisplay();
}
<commit_msg>QmlProfiler: capitalization of elapsed time display<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "qmlprofilertool.h"
#include "qmlprofilerengine.h"
#include "qmlprofilerplugin.h"
#include "qmlprofilerconstants.h"
#include "qmlprofilerattachdialog.h"
#include "qmlprofilersummaryview.h"
#include "tracewindow.h"
#include "timelineview.h"
#include <qmljsdebugclient/qdeclarativedebugclient_p.h>
#include <analyzerbase/analyzermanager.h>
#include <analyzerbase/analyzerconstants.h>
#include "canvas/qdeclarativecanvas_p.h"
#include "canvas/qdeclarativecontext2d_p.h"
#include "canvas/qdeclarativetiledcanvas_p.h"
#include <qmlprojectmanager/qmlprojectrunconfiguration.h>
#include <utils/fancymainwindow.h>
#include <utils/fileinprojectfinder.h>
#include <utils/qtcassert.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
#include <texteditor/itexteditor.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/icore.h>
#include <QtCore/QFile>
#include <QtGui/QHBoxLayout>
#include <QtGui/QLabel>
#include <QtGui/QTabWidget>
#include <QtGui/QToolButton>
using namespace Analyzer;
using namespace QmlProfiler::Internal;
class QmlProfilerTool::QmlProfilerToolPrivate
{
public:
QmlProfilerToolPrivate(QmlProfilerTool *qq) : q(qq) {}
~QmlProfilerToolPrivate() {}
QmlProfilerTool *q;
QDeclarativeDebugConnection *m_client;
QTimer m_connectionTimer;
int m_connectionAttempts;
TraceWindow *m_traceWindow;
QmlProfilerSummaryView *m_summary;
ProjectExplorer::Project *m_project;
Utils::FileInProjectFinder m_projectFinder;
ProjectExplorer::RunConfiguration *m_runConfiguration;
bool m_isAttached;
QAction *m_attachAction;
QToolButton *m_recordButton;
bool m_recordingEnabled;
QString m_host;
quint64 m_port;
};
QmlProfilerTool::QmlProfilerTool(QObject *parent)
: IAnalyzerTool(parent), d(new QmlProfilerToolPrivate(this))
{
d->m_client = 0;
d->m_connectionAttempts = 0;
d->m_traceWindow = 0;
d->m_project = 0;
d->m_runConfiguration = 0;
d->m_isAttached = false;
d->m_attachAction = 0;
d->m_recordingEnabled = true;
d->m_connectionTimer.setInterval(200);
connect(&d->m_connectionTimer, SIGNAL(timeout()), SLOT(tryToConnect()));
}
QmlProfilerTool::~QmlProfilerTool()
{
delete d->m_client;
delete d;
}
QString QmlProfilerTool::id() const
{
return "QmlProfiler";
}
QString QmlProfilerTool::displayName() const
{
return tr("QML Performance Monitor");
}
IAnalyzerTool::ToolMode QmlProfilerTool::mode() const
{
return AnyMode;
}
IAnalyzerEngine *QmlProfilerTool::createEngine(const AnalyzerStartParameters &sp,
ProjectExplorer::RunConfiguration *runConfiguration)
{
QmlProfilerEngine *engine = new QmlProfilerEngine(sp, runConfiguration);
d->m_host = sp.connParams.host;
d->m_port = sp.connParams.port;
d->m_runConfiguration = runConfiguration;
d->m_project = runConfiguration->target()->project();
if (d->m_project) {
d->m_projectFinder.setProjectDirectory(d->m_project->projectDirectory());
updateProjectFileList();
connect(d->m_project, SIGNAL(fileListChanged()), this, SLOT(updateProjectFileList()));
}
connect(engine, SIGNAL(processRunning()), this, SLOT(connectClient()));
connect(engine, SIGNAL(finished()), this, SLOT(disconnectClient()));
connect(engine, SIGNAL(stopRecording()), this, SLOT(stopRecording()));
connect(d->m_traceWindow, SIGNAL(viewUpdated()), engine, SLOT(dataReceived()));
connect(this, SIGNAL(connectionFailed()), engine, SLOT(finishProcess()));
connect(this, SIGNAL(fetchingData(bool)), engine, SLOT(setFetchingData(bool)));
emit fetchingData(d->m_recordButton->isChecked());
return engine;
}
void QmlProfilerTool::initialize()
{
qmlRegisterType<Canvas>("Monitor", 1, 0, "Canvas");
qmlRegisterType<TiledCanvas>("Monitor", 1, 0, "TiledCanvas");
qmlRegisterType<Context2D>();
qmlRegisterType<CanvasImage>();
qmlRegisterType<CanvasGradient>();
qmlRegisterType<TimelineView>("Monitor", 1, 0,"TimelineView");
}
void QmlProfilerTool::extensionsInitialized()
{
}
void QmlProfilerTool::initializeDockWidgets()
{
Analyzer::AnalyzerManager *analyzerMgr = Analyzer::AnalyzerManager::instance();
Utils::FancyMainWindow *mw = analyzerMgr->mainWindow();
d->m_traceWindow = new TraceWindow(mw);
d->m_traceWindow->reset(d->m_client);
connect(d->m_traceWindow, SIGNAL(gotoSourceLocation(QString,int)),this, SLOT(gotoSourceLocation(QString,int)));
connect(d->m_traceWindow, SIGNAL(timeChanged(qreal)), this, SLOT(updateTimer(qreal)));
d->m_summary = new QmlProfilerSummaryView(mw);
connect(d->m_traceWindow, SIGNAL(range(int,qint64,qint64,QStringList,QString,int)),
d->m_summary, SLOT(addRangedEvent(int,qint64,qint64,QStringList,QString,int)));
connect(d->m_traceWindow, SIGNAL(viewUpdated()),
d->m_summary, SLOT(complete()));
connect(d->m_summary, SIGNAL(gotoSourceLocation(QString,int)),
this, SLOT(gotoSourceLocation(QString,int)));
Core::ICore *core = Core::ICore::instance();
Core::ActionManager *am = core->actionManager();
Core::ActionContainer *manalyzer = am->actionContainer(Analyzer::Constants::M_DEBUG_ANALYZER);
const Core::Context globalcontext(Core::Constants::C_GLOBAL);
d->m_attachAction = new QAction(tr("Attach..."), manalyzer);
Core::Command *command = am->registerAction(d->m_attachAction,
Constants::ATTACH, globalcontext);
command->setAttribute(Core::Command::CA_UpdateText);
manalyzer->addAction(command, Analyzer::Constants::G_ANALYZER_STARTSTOP);
connect(d->m_attachAction, SIGNAL(triggered()), this, SLOT(attach()));
connect(analyzerMgr, SIGNAL(currentToolChanged(Analyzer::IAnalyzerTool*)),
this, SLOT(updateAttachAction()));
updateAttachAction();
QDockWidget *summaryDock =
analyzerMgr->createDockWidget(this, tr("Summary"),
d->m_summary, Qt::BottomDockWidgetArea);
QDockWidget *timelineDock =
analyzerMgr->createDockWidget(this, tr("Timeline"),
d->m_traceWindow, Qt::BottomDockWidgetArea);
mw->splitDockWidget(mw->toolBarDockWidget(), summaryDock, Qt::Vertical);
mw->tabifyDockWidget(summaryDock, timelineDock);
}
QWidget *QmlProfilerTool::createControlWidget()
{
// custom toolbar (TODO)
QWidget *toolbarWidget = new QWidget;
toolbarWidget->setObjectName(QLatin1String("QmlProfilerToolBarWidget"));
QHBoxLayout *layout = new QHBoxLayout;
layout->setMargin(0);
layout->setSpacing(0);
d->m_recordButton = new QToolButton(toolbarWidget);
d->m_recordButton->setIcon(QIcon(QLatin1String(":/qmlprofiler/analyzer_category_small.png")));
d->m_recordButton->setCheckable(true);
connect(d->m_recordButton,SIGNAL(toggled(bool)), this, SLOT(setRecording(bool)));
d->m_recordButton->setChecked(true);
layout->addWidget(d->m_recordButton);
QLabel *timeLabel = new QLabel(tr("Elapsed: 0 s"));
QPalette palette = timeLabel->palette();
palette.setColor(QPalette::WindowText, Qt::white);
timeLabel->setPalette(palette);
timeLabel->setIndent(10);
connect(this, SIGNAL(setTimeLabel(QString)), timeLabel, SLOT(setText(QString)));
layout->addWidget(timeLabel);
toolbarWidget->setLayout(layout);
return toolbarWidget;
}
void QmlProfilerTool::connectClient()
{
QTC_ASSERT(!d->m_client, return;)
d->m_client = new QDeclarativeDebugConnection;
d->m_traceWindow->reset(d->m_client);
connect(d->m_client, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
this, SLOT(connectionStateChanged()));
d->m_connectionTimer.start();
}
void QmlProfilerTool::connectToClient()
{
if (!d->m_client || d->m_client->state() != QAbstractSocket::UnconnectedState)
return;
if (QmlProfilerPlugin::debugOutput)
qWarning("QmlProfiler: Connecting to %s:%lld ...", qPrintable(d->m_host), d->m_port);
d->m_client->connectToHost(d->m_host, d->m_port);
}
void QmlProfilerTool::disconnectClient()
{
// this might be actually be called indirectly by QDDConnectionPrivate::readyRead(), therefore allow
// method to complete before deleting object
if (d->m_client) {
d->m_client->deleteLater();
d->m_client = 0;
}
}
void QmlProfilerTool::startRecording()
{
if (d->m_client && d->m_client->isConnected()) {
clearDisplay();
d->m_traceWindow->setRecording(true);
}
emit fetchingData(true);
}
void QmlProfilerTool::stopRecording()
{
d->m_traceWindow->setRecording(false);
emit fetchingData(false);
}
void QmlProfilerTool::setRecording(bool recording)
{
d->m_recordingEnabled = recording;
if (recording)
startRecording();
else
stopRecording();
}
void QmlProfilerTool::gotoSourceLocation(const QString &fileUrl, int lineNumber)
{
if (lineNumber < 0 || fileUrl.isEmpty())
return;
const QString fileName = QUrl(fileUrl).toLocalFile();
const QString projectFileName = d->m_projectFinder.findFile(fileName);
Core::EditorManager *editorManager = Core::EditorManager::instance();
Core::IEditor *editor = editorManager->openEditor(projectFileName);
TextEditor::ITextEditor *textEditor = qobject_cast<TextEditor::ITextEditor*>(editor);
if (textEditor) {
editorManager->addCurrentPositionToNavigationHistory();
textEditor->gotoLine(lineNumber);
textEditor->widget()->setFocus();
}
}
void QmlProfilerTool::updateTimer(qreal elapsedSeconds)
{
QString timeString = QString::number(elapsedSeconds,'f',1);
timeString = QString(" ").left(6-timeString.length()) + timeString;
emit setTimeLabel(tr("Elapsed: %1 s").arg(timeString));
}
void QmlProfilerTool::updateProjectFileList()
{
d->m_projectFinder.setProjectFiles(
d->m_project->files(ProjectExplorer::Project::ExcludeGeneratedFiles));
}
bool QmlProfilerTool::canRunRemotely() const
{
// TODO: Is this correct?
return true;
}
void QmlProfilerTool::clearDisplay()
{
d->m_traceWindow->clearDisplay();
d->m_summary->clean();
}
void QmlProfilerTool::attach()
{
if (!d->m_isAttached) {
QmlProfilerAttachDialog dialog;
int result = dialog.exec();
if (result == QDialog::Rejected)
return;
d->m_port = dialog.port();
d->m_host = dialog.address();
connectClient();
AnalyzerManager::instance()->showMode();
AnalyzerManager::instance()->popupOutputPane();
} else {
stopRecording();
}
d->m_isAttached = !d->m_isAttached;
updateAttachAction();
}
void QmlProfilerTool::updateAttachAction()
{
if (d->m_attachAction) {
if (d->m_isAttached) {
d->m_attachAction->setText(tr("Detach"));
} else {
d->m_attachAction->setText(tr("Attach..."));
}
}
d->m_attachAction->setEnabled(Analyzer::AnalyzerManager::instance()->currentTool() == this);
}
void QmlProfilerTool::tryToConnect()
{
++d->m_connectionAttempts;
if (d->m_client && d->m_client->isConnected()) {
d->m_connectionTimer.stop();
d->m_connectionAttempts = 0;
} else if (d->m_connectionAttempts == 50) {
d->m_connectionTimer.stop();
d->m_connectionAttempts = 0;
if (QmlProfilerPlugin::debugOutput) {
if (d->m_client) {
qWarning("QmlProfiler: Failed to connect: %s", qPrintable(d->m_client->errorString()));
} else {
qWarning("QmlProfiler: Failed to connect.");
}
}
emit connectionFailed();
} else {
connectToClient();
}
}
void QmlProfilerTool::connectionStateChanged()
{
if (!d->m_client)
return;
switch (d->m_client->state()) {
case QAbstractSocket::UnconnectedState:
{
if (QmlProfilerPlugin::debugOutput)
qWarning("QmlProfiler: disconnected");
break;
}
case QAbstractSocket::HostLookupState:
break;
case QAbstractSocket::ConnectingState: {
if (QmlProfilerPlugin::debugOutput)
qWarning("QmlProfiler: Connecting to debug server ...");
break;
}
case QAbstractSocket::ConnectedState:
{
if (QmlProfilerPlugin::debugOutput)
qWarning("QmlProfiler: connected and running");
updateRecordingState();
break;
}
case QAbstractSocket::ClosingState:
if (QmlProfilerPlugin::debugOutput)
qWarning("QmlProfiler: closing ...");
break;
case QAbstractSocket::BoundState:
case QAbstractSocket::ListeningState:
break;
}
}
void QmlProfilerTool::updateRecordingState()
{
if (d->m_client->isConnected()) {
d->m_traceWindow->setRecording(d->m_recordingEnabled);
} else {
d->m_traceWindow->setRecording(false);
}
if (d->m_traceWindow->isRecording())
clearDisplay();
}
<|endoftext|> |
<commit_before>/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2009, 2010
* sileht, theli48@gmail.com
* Emmanuel Benazera, juban@free.fr
*
* 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 "errlog.h"
#include "se_parser_exalead.h"
#include "miscutil.h"
#include <strings.h>
#include <iostream>
using sp::miscutil;
using sp::errlog;
namespace seeks_plugins
{
se_parser_exalead::se_parser_exalead()
:se_parser(),_result_flag(false),_title_flag(false),_p_flag(false),
_summary_flag(false),_cite_flag(false),_cached_flag(false),_b_title_flag(false),
_b_summary_flag(false),_ignore_flag(false)
{
}
se_parser_exalead::~se_parser_exalead()
{
}
void se_parser_exalead::start_element(parser_context *pc,
const xmlChar *name,
const xmlChar **attributes)
{
const char *tag = (const char*)name;
if (strcasecmp(tag,"div") == 0)
{
const char *a_class = se_parser::get_attribute((const char**)attributes,"class");
if (a_class && strcasecmp(a_class,"resultContent") == 0)
{
// assert previous snippet, if any.
if (pc->_current_snippet)
{
if (pc->_current_snippet->_title.empty()
|| pc->_current_snippet->_url.empty())
{
delete pc->_current_snippet;
pc->_current_snippet = NULL;
_count--;
}
else pc->_snippets->push_back(pc->_current_snippet);
}
_result_flag = true;
search_snippet *sp = new search_snippet(_count+1);
_count++;
sp->_engine |= std::bitset<NSEs>(SE_EXALEAD);
pc->_current_snippet = sp;
}
}
else if (_result_flag)
{
if (strcasecmp(tag,"p") == 0)
{
_p_flag = true;
}
else if (_p_flag && strcasecmp(tag,"span") == 0)
{
const char *a_class = se_parser::get_attribute((const char**)attributes,"class");
if (!_summary_flag && !a_class)
_summary_flag = true;
if (_summary_flag && a_class && strcmp(a_class,"bookmarkLinks") == 0)
{
_ignore_flag = true;
}
}
else if (strcasecmp(tag,"a") == 0)
{
const char *a_class = se_parser::get_attribute((const char**)attributes,"class");
if (a_class && strcasecmp(a_class,"url") == 0)
{
_cite_flag = true;
}
else if (a_class && strcasecmp(a_class,"title") == 0)
{
_title_flag = true;
const char *a_link = se_parser::get_attribute((const char**)attributes,"href");
if (a_link)
pc->_current_snippet->set_url(a_link);
}
else if (a_class && strcasecmp(a_class,"cache") == 0)
{
_cached_flag = true;
const char *a_cached = se_parser::get_attribute((const char**)attributes,"href");
if (a_cached)
{
_cached = std::string(a_cached);
pc->_current_snippet->_cached = "http://www.exalead.com" + _cached; // beware: check on the host.
_cached = "";
}
}
}
else if (_title_flag && strcasecmp(tag,"b") == 0)
{
_b_title_flag = true;
}
else if (_summary_flag && strcasecmp(tag,"b") == 0)
{
_b_summary_flag = true;
}
}
}
void se_parser_exalead::characters(parser_context *pc,
const xmlChar *chars,
int length)
{
handle_characters(pc, chars, length);
}
void se_parser_exalead::cdata(parser_context *pc,
const xmlChar *chars,
int length)
{
handle_characters(pc, chars, length);
}
void se_parser_exalead::handle_characters(parser_context *pc,
const xmlChar *chars,
int length)
{
if (!chars)
return;
if (!_ignore_flag && _summary_flag)
{
std::string a_chars = std::string((char*)chars);
size_t i=0;
while(i<a_chars.length() && isspace(a_chars[i++]))
{
}
a_chars = a_chars.substr(i);
miscutil::replace_in_string(a_chars,"\n"," ");
miscutil::replace_in_string(a_chars,"\r"," ");
if (_b_summary_flag)
_summary += " ";
_summary += a_chars;
if (_b_summary_flag)
_summary += " ";
}
else if (_cite_flag)
{
std::string a_chars = std::string((char*)chars);
miscutil::replace_in_string(a_chars,"\n"," ");
miscutil::replace_in_string(a_chars,"\r"," ");
_cite += a_chars;
}
else if (_title_flag)
{
std::string a_chars = std::string((char*)chars);
size_t i=0;
while(i<a_chars.length() && isspace(a_chars[i++]))
{
}
a_chars = a_chars.substr(i);
miscutil::replace_in_string(a_chars,"\n"," ");
miscutil::replace_in_string(a_chars,"\r"," ");
if (_b_title_flag)
_title += " ";
_title += a_chars;
if (_b_title_flag)
_title += " ";
}
}
void se_parser_exalead::end_element(parser_context *pc,
const xmlChar *name)
{
const char *tag = (const char*) name;
if (_result_flag)
{
if (strcasecmp(tag,"div") == 0)
{
_result_flag = false;
_title_flag = false;
_p_flag = false;
_summary_flag = false;
_cite_flag = false;
_cached_flag = false;
}
else if (strcasecmp(tag,"span") == 0)
{
if (!_ignore_flag && _summary_flag)
{
pc->_current_snippet->set_summary(_summary);
_summary = "";
_summary_flag = false;
}
else if (_ignore_flag)
_ignore_flag = false;
}
else if ( _cite_flag && strcasecmp(tag,"a") == 0)
{
pc->_current_snippet->_cite = _cite;
_cite = "";
_cite_flag = false;
}
else if (_title_flag && strcasecmp(tag,"a") == 0)
{
pc->_current_snippet->_title = _title;
_title = "";
_title_flag = false;
}
else if (_title_flag && strcasecmp(tag,"b") == 0)
_b_title_flag = false;
else if (_summary_flag && strcasecmp(tag,"b") == 0)
_b_summary_flag = false;
}
}
} /* end of namespace. */
<commit_msg>fix to exalead parser<commit_after>/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2009, 2010
* sileht, theli48@gmail.com
* Emmanuel Benazera, juban@free.fr
*
* 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 "errlog.h"
#include "se_parser_exalead.h"
#include "miscutil.h"
#include <strings.h>
#include <iostream>
using sp::miscutil;
using sp::errlog;
namespace seeks_plugins
{
se_parser_exalead::se_parser_exalead()
:se_parser(),_result_flag(false),_title_flag(false),_p_flag(false),
_summary_flag(false),_cite_flag(false),_cached_flag(false),_b_title_flag(false),
_b_summary_flag(false),_ignore_flag(false)
{
}
se_parser_exalead::~se_parser_exalead()
{
}
void se_parser_exalead::start_element(parser_context *pc,
const xmlChar *name,
const xmlChar **attributes)
{
const char *tag = (const char*)name;
if (strcasecmp(tag,"div") == 0)
{
const char *a_class = se_parser::get_attribute((const char**)attributes,"class");
if (a_class && strcasecmp(a_class,"resultContent") == 0)
{
// assert previous snippet, if any.
if (pc->_current_snippet)
{
if (pc->_current_snippet->_title.empty()
|| pc->_current_snippet->_url.empty())
{
delete pc->_current_snippet;
pc->_current_snippet = NULL;
_count--;
}
else pc->_snippets->push_back(pc->_current_snippet);
}
_result_flag = true;
search_snippet *sp = new search_snippet(_count+1);
_count++;
sp->_engine |= std::bitset<NSEs>(SE_EXALEAD);
pc->_current_snippet = sp;
}
}
else if (_result_flag)
{
if (strcasecmp(tag,"p") == 0)
{
_p_flag = true;
}
else if (_p_flag && strcasecmp(tag,"span") == 0)
{
const char *a_class = se_parser::get_attribute((const char**)attributes,"class");
if (!_summary_flag && !a_class)
_summary_flag = true;
if (_summary_flag && a_class && strcmp(a_class,"bookmarkLinks") == 0)
{
_ignore_flag = true;
}
}
else if (strcasecmp(tag,"a") == 0)
{
const char *a_class = se_parser::get_attribute((const char**)attributes,"class");
if (a_class && strcasecmp(a_class,"url") == 0)
{
_cite_flag = true;
}
else if (a_class && strcasecmp(a_class,"title") == 0)
{
_title_flag = true;
const char *a_link = se_parser::get_attribute((const char**)attributes,"href");
if (a_link)
pc->_current_snippet->set_url(a_link);
}
else if (a_class && strcasecmp(a_class,"cache") == 0)
{
_cached_flag = true;
const char *a_cached = se_parser::get_attribute((const char**)attributes,"href");
if (a_cached)
{
_cached = std::string(a_cached);
pc->_current_snippet->_cached = "http://www.exalead.com" + _cached; // beware: check on the host.
_cached = "";
}
}
}
else if (_title_flag && strcasecmp(tag,"b") == 0)
{
_b_title_flag = true;
}
else if (_summary_flag && strcasecmp(tag,"b") == 0)
{
_b_summary_flag = true;
}
}
}
void se_parser_exalead::characters(parser_context *pc,
const xmlChar *chars,
int length)
{
handle_characters(pc, chars, length);
}
void se_parser_exalead::cdata(parser_context *pc,
const xmlChar *chars,
int length)
{
handle_characters(pc, chars, length);
}
void se_parser_exalead::handle_characters(parser_context *pc,
const xmlChar *chars,
int length)
{
if (!chars)
return;
if (!_ignore_flag && _summary_flag)
{
std::string a_chars = std::string((char*)chars);
size_t i=0;
while(i<a_chars.length() && isspace(a_chars[i]))
{
i++;
}
a_chars = a_chars.substr(i);
miscutil::replace_in_string(a_chars,"\n"," ");
miscutil::replace_in_string(a_chars,"\r"," ");
if (_b_summary_flag)
_summary += " ";
_summary += a_chars;
if (_b_summary_flag)
_summary += " ";
}
else if (_cite_flag)
{
std::string a_chars = std::string((char*)chars);
miscutil::replace_in_string(a_chars,"\n"," ");
miscutil::replace_in_string(a_chars,"\r"," ");
_cite += a_chars;
}
else if (_title_flag)
{
std::string a_chars = std::string((char*)chars);
size_t i=0;
while(i<a_chars.length() && isspace(a_chars[i]))
{
i++;
}
a_chars = a_chars.substr(i);
miscutil::replace_in_string(a_chars,"\n"," ");
miscutil::replace_in_string(a_chars,"\r"," ");
if (_b_title_flag)
_title += " ";
_title += a_chars;
if (_b_title_flag)
_title += " ";
}
}
void se_parser_exalead::end_element(parser_context *pc,
const xmlChar *name)
{
const char *tag = (const char*) name;
if (_result_flag)
{
if (strcasecmp(tag,"div") == 0)
{
_result_flag = false;
_title_flag = false;
_p_flag = false;
_summary_flag = false;
_cite_flag = false;
_cached_flag = false;
}
else if (strcasecmp(tag,"span") == 0)
{
if (!_ignore_flag && _summary_flag)
{
pc->_current_snippet->set_summary(_summary);
_summary = "";
_summary_flag = false;
}
else if (_ignore_flag)
_ignore_flag = false;
}
else if ( _cite_flag && strcasecmp(tag,"a") == 0)
{
pc->_current_snippet->_cite = _cite;
_cite = "";
_cite_flag = false;
}
else if (_title_flag && strcasecmp(tag,"a") == 0)
{
pc->_current_snippet->_title = _title;
_title = "";
_title_flag = false;
}
else if (_title_flag && strcasecmp(tag,"b") == 0)
_b_title_flag = false;
else if (_summary_flag && strcasecmp(tag,"b") == 0)
_b_summary_flag = false;
}
}
} /* end of namespace. */
<|endoftext|> |
<commit_before><commit_msg>Revert of Switch V8HiddenValue from hidden values to privates (patchset #7 id:120001 of https://codereview.chromium.org/1416053012/ )<commit_after><|endoftext|> |
<commit_before>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "SurveyMissionItemTest.h"
#include "QGCApplication.h"
SurveyMissionItemTest::SurveyMissionItemTest(void)
: _offlineVehicle(NULL)
{
_polyPoints << QGeoCoordinate(47.633550640000003, -122.08982199) << QGeoCoordinate(47.634129020000003, -122.08887249) <<
QGeoCoordinate(47.633619320000001, -122.08811074) << QGeoCoordinate(47.633189139999999, -122.08900124);
}
void SurveyMissionItemTest::init(void)
{
UnitTest::init();
_rgSurveySignals[gridPointsChangedIndex] = SIGNAL(gridPointsChanged());
_rgSurveySignals[cameraShotsChangedIndex] = SIGNAL(cameraShotsChanged(int));
_rgSurveySignals[coveredAreaChangedIndex] = SIGNAL(coveredAreaChanged(double));
_rgSurveySignals[cameraValueChangedIndex] = SIGNAL(cameraValueChanged());
_rgSurveySignals[gridTypeChangedIndex] = SIGNAL(gridTypeChanged(QString));
_rgSurveySignals[timeBetweenShotsChangedIndex] = SIGNAL(timeBetweenShotsChanged());
_rgSurveySignals[cameraOrientationFixedChangedIndex] = SIGNAL(cameraOrientationFixedChanged(bool));
_rgSurveySignals[refly90DegreesChangedIndex] = SIGNAL(refly90DegreesChanged(bool));
_rgSurveySignals[dirtyChangedIndex] = SIGNAL(dirtyChanged(bool));
_offlineVehicle = new Vehicle(MAV_AUTOPILOT_PX4, MAV_TYPE_QUADROTOR, qgcApp()->toolbox()->firmwarePluginManager(), this);
_surveyItem = new SurveyMissionItem(_offlineVehicle, this);
_surveyItem->setTurnaroundDist(0); // Unit test written for no turnaround distance
_mapPolygon = _surveyItem->mapPolygon();
// It's important to check that the right signals are emitted at the right time since that drives ui change.
// It's also important to check that things are not being over-signalled when they should not be, since that can lead
// to incorrect ui or perf impact of uneeded signals propogating ui change.
_multiSpy = new MultiSignalSpy();
Q_CHECK_PTR(_multiSpy);
QCOMPARE(_multiSpy->init(_surveyItem, _rgSurveySignals, _cSurveySignals), true);
}
void SurveyMissionItemTest::cleanup(void)
{
delete _surveyItem;
delete _offlineVehicle;
delete _multiSpy;
}
void SurveyMissionItemTest::_testDirty(void)
{
QVERIFY(!_surveyItem->dirty());
_surveyItem->setDirty(false);
QVERIFY(!_surveyItem->dirty());
QVERIFY(_multiSpy->checkNoSignals());
_surveyItem->setDirty(true);
QVERIFY(_surveyItem->dirty());
QVERIFY(_multiSpy->checkOnlySignalByMask(dirtyChangedMask));
QVERIFY(_multiSpy->pullBoolFromSignalIndex(dirtyChangedIndex));
_multiSpy->clearAllSignals();
_surveyItem->setDirty(false);
QVERIFY(!_surveyItem->dirty());
QVERIFY(_multiSpy->checkOnlySignalByMask(dirtyChangedMask));
QVERIFY(!_multiSpy->pullBoolFromSignalIndex(dirtyChangedIndex));
_multiSpy->clearAllSignals();
// These facts should set dirty when changed
QList<Fact*> rgFacts;
rgFacts << _surveyItem->gridAltitude() << _surveyItem->gridAngle() << _surveyItem->gridSpacing() << _surveyItem->turnaroundDist() << _surveyItem->cameraTriggerDistance() <<
_surveyItem->gridAltitudeRelative() << _surveyItem->cameraTriggerInTurnaround() << _surveyItem->hoverAndCapture();
foreach(Fact* fact, rgFacts) {
qDebug() << fact->name();
QVERIFY(!_surveyItem->dirty());
if (fact->typeIsBool()) {
fact->setRawValue(!fact->rawValue().toBool());
} else {
fact->setRawValue(fact->rawValue().toDouble() + 1);
}
QVERIFY(_multiSpy->checkSignalByMask(dirtyChangedMask));
QVERIFY(_multiSpy->pullBoolFromSignalIndex(dirtyChangedIndex));
_surveyItem->setDirty(false);
_multiSpy->clearAllSignals();
}
rgFacts.clear();
// These facts should not change dirty bit
rgFacts << _surveyItem->groundResolution() << _surveyItem->frontalOverlap() << _surveyItem->sideOverlap() << _surveyItem->cameraSensorWidth() << _surveyItem->cameraSensorHeight() <<
_surveyItem->cameraResolutionWidth() << _surveyItem->cameraResolutionHeight() << _surveyItem->cameraFocalLength() << _surveyItem->cameraOrientationLandscape() <<
_surveyItem->fixedValueIsAltitude() << _surveyItem->camera() << _surveyItem->manualGrid();
foreach(Fact* fact, rgFacts) {
qDebug() << fact->name();
QVERIFY(!_surveyItem->dirty());
if (fact->typeIsBool()) {
fact->setRawValue(!fact->rawValue().toBool());
} else {
fact->setRawValue(fact->rawValue().toDouble() + 1);
}
QVERIFY(_multiSpy->checkNoSignalByMask(dirtyChangedMask));
QVERIFY(!_surveyItem->dirty());
_multiSpy->clearAllSignals();
}
rgFacts.clear();
}
void SurveyMissionItemTest::_testCameraValueChanged(void)
{
// These facts should trigger cameraValueChanged when changed
QList<Fact*> rgFacts;
rgFacts << _surveyItem->groundResolution() << _surveyItem->frontalOverlap() << _surveyItem->sideOverlap() << _surveyItem->cameraSensorWidth() << _surveyItem->cameraSensorHeight() <<
_surveyItem->cameraResolutionWidth() << _surveyItem->cameraResolutionHeight() << _surveyItem->cameraFocalLength() << _surveyItem->cameraOrientationLandscape();
foreach(Fact* fact, rgFacts) {
qDebug() << fact->name();
if (fact->typeIsBool()) {
fact->setRawValue(!fact->rawValue().toBool());
} else {
fact->setRawValue(fact->rawValue().toDouble() + 1);
}
QVERIFY(_multiSpy->checkSignalByMask(cameraValueChangedMask));
_multiSpy->clearAllSignals();
}
rgFacts.clear();
// These facts should not trigger cameraValueChanged
rgFacts << _surveyItem->gridAltitude() << _surveyItem->gridAngle() << _surveyItem->gridSpacing() << _surveyItem->turnaroundDist() << _surveyItem->cameraTriggerDistance() <<
_surveyItem->gridAltitudeRelative() << _surveyItem->cameraTriggerInTurnaround() << _surveyItem->hoverAndCapture() <<
_surveyItem->fixedValueIsAltitude() << _surveyItem->camera() << _surveyItem->manualGrid();
foreach(Fact* fact, rgFacts) {
qDebug() << fact->name();
if (fact->typeIsBool()) {
fact->setRawValue(!fact->rawValue().toBool());
} else {
fact->setRawValue(fact->rawValue().toDouble() + 1);
}
QVERIFY(_multiSpy->checkNoSignalByMask(cameraValueChangedMask));
_multiSpy->clearAllSignals();
}
rgFacts.clear();
}
void SurveyMissionItemTest::_testCameraTrigger(void)
{
#if 0
QCOMPARE(_surveyItem->property("cameraTrigger").toBool(), true);
// Set up a grid
for (int i=0; i<3; i++) {
_mapPolygon->appendVertex(_polyPoints[i]);
}
_surveyItem->setDirty(false);
_multiSpy->clearAllSignals();
int lastSeq = _surveyItem->lastSequenceNumber();
QVERIFY(lastSeq > 0);
// Turning off camera triggering should remove two camera trigger mission items, this should trigger:
// lastSequenceNumberChanged
// dirtyChanged
_surveyItem->setProperty("cameraTrigger", false);
QVERIFY(_multiSpy->checkOnlySignalByMask(lastSequenceNumberChangedMask | dirtyChangedMask | cameraTriggerChangedMask));
QCOMPARE(_multiSpy->pullIntFromSignalIndex(lastSequenceNumberChangedIndex), lastSeq - 2);
_surveyItem->setDirty(false);
_multiSpy->clearAllSignals();
// Turn on camera triggering and make sure things go back to previous count
_surveyItem->setProperty("cameraTrigger", true);
QVERIFY(_multiSpy->checkOnlySignalByMask(lastSequenceNumberChangedMask | dirtyChangedMask | cameraTriggerChangedMask));
QCOMPARE(_multiSpy->pullIntFromSignalIndex(lastSequenceNumberChangedIndex), lastSeq);
#endif
}
// Clamp expected grid angle from 0<->180. We don't care about opposite angles like 90/270
double SurveyMissionItemTest::_clampGridAngle180(double gridAngle)
{
if (gridAngle >= 0.0) {
if (gridAngle == 360.0) {
gridAngle = 0.0;
} else if (gridAngle >= 180.0) {
gridAngle -= 180.0;
}
} else {
if (gridAngle < -180.0) {
gridAngle += 360.0;
} else {
gridAngle += 180.0;
}
}
return gridAngle;
}
void SurveyMissionItemTest::_testGridAngle(void)
{
QGCMapPolygon* mapPolygon = _surveyItem->mapPolygon();
for (int i=0; i<_polyPoints.count(); i++) {
QGeoCoordinate& vertex = _polyPoints[i];
mapPolygon->appendVertex(vertex);
}
for (double gridAngle=-360.0; gridAngle<=360.0; gridAngle++) {
_surveyItem->gridAngle()->setRawValue(gridAngle);
QVariantList gridPoints = _surveyItem->gridPoints();
QGeoCoordinate firstTransectEntry = gridPoints[0].value<QGeoCoordinate>();
QGeoCoordinate firstTransectExit = gridPoints[1].value<QGeoCoordinate>();
double azimuth = firstTransectEntry.azimuthTo(firstTransectExit);
//qDebug() << gridAngle << azimuth << _clampGridAngle180(gridAngle) << _clampGridAngle180(azimuth);
QCOMPARE((int)_clampGridAngle180(gridAngle), (int)_clampGridAngle180(azimuth));
}
}
void SurveyMissionItemTest::_testEntryLocation(void)
{
QGCMapPolygon* mapPolygon = _surveyItem->mapPolygon();
for (int i=0; i<_polyPoints.count(); i++) {
QGeoCoordinate& vertex = _polyPoints[i];
mapPolygon->appendVertex(vertex);
}
for (double gridAngle=-360.0; gridAngle<=360.0; gridAngle++) {
_surveyItem->gridAngle()->setRawValue(gridAngle);
QList<QGeoCoordinate> rgSeenEntryCoords;
QList<int> rgEntryLocation;
rgEntryLocation << SurveyMissionItem::EntryLocationTopLeft
<< SurveyMissionItem::EntryLocationTopRight
<< SurveyMissionItem::EntryLocationBottomLeft
<< SurveyMissionItem::EntryLocationBottomRight;
// Validate that each entry location is unique
for (int i=0; i<rgEntryLocation.count(); i++) {
int entryLocation = rgEntryLocation[i];
_surveyItem->gridEntryLocation()->setRawValue(entryLocation);
QVERIFY(!rgSeenEntryCoords.contains(_surveyItem->coordinate()));
rgSeenEntryCoords << _surveyItem->coordinate();
}
rgSeenEntryCoords.clear();
}
}
<commit_msg>Fix unit test dirty bit<commit_after>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "SurveyMissionItemTest.h"
#include "QGCApplication.h"
SurveyMissionItemTest::SurveyMissionItemTest(void)
: _offlineVehicle(NULL)
{
_polyPoints << QGeoCoordinate(47.633550640000003, -122.08982199) << QGeoCoordinate(47.634129020000003, -122.08887249) <<
QGeoCoordinate(47.633619320000001, -122.08811074) << QGeoCoordinate(47.633189139999999, -122.08900124);
}
void SurveyMissionItemTest::init(void)
{
UnitTest::init();
_rgSurveySignals[gridPointsChangedIndex] = SIGNAL(gridPointsChanged());
_rgSurveySignals[cameraShotsChangedIndex] = SIGNAL(cameraShotsChanged(int));
_rgSurveySignals[coveredAreaChangedIndex] = SIGNAL(coveredAreaChanged(double));
_rgSurveySignals[cameraValueChangedIndex] = SIGNAL(cameraValueChanged());
_rgSurveySignals[gridTypeChangedIndex] = SIGNAL(gridTypeChanged(QString));
_rgSurveySignals[timeBetweenShotsChangedIndex] = SIGNAL(timeBetweenShotsChanged());
_rgSurveySignals[cameraOrientationFixedChangedIndex] = SIGNAL(cameraOrientationFixedChanged(bool));
_rgSurveySignals[refly90DegreesChangedIndex] = SIGNAL(refly90DegreesChanged(bool));
_rgSurveySignals[dirtyChangedIndex] = SIGNAL(dirtyChanged(bool));
_offlineVehicle = new Vehicle(MAV_AUTOPILOT_PX4, MAV_TYPE_QUADROTOR, qgcApp()->toolbox()->firmwarePluginManager(), this);
_surveyItem = new SurveyMissionItem(_offlineVehicle, this);
_surveyItem->setTurnaroundDist(0); // Unit test written for no turnaround distance
_surveyItem->setDirty(false);
_mapPolygon = _surveyItem->mapPolygon();
// It's important to check that the right signals are emitted at the right time since that drives ui change.
// It's also important to check that things are not being over-signalled when they should not be, since that can lead
// to incorrect ui or perf impact of uneeded signals propogating ui change.
_multiSpy = new MultiSignalSpy();
Q_CHECK_PTR(_multiSpy);
QCOMPARE(_multiSpy->init(_surveyItem, _rgSurveySignals, _cSurveySignals), true);
}
void SurveyMissionItemTest::cleanup(void)
{
delete _surveyItem;
delete _offlineVehicle;
delete _multiSpy;
}
void SurveyMissionItemTest::_testDirty(void)
{
QVERIFY(!_surveyItem->dirty());
_surveyItem->setDirty(false);
QVERIFY(!_surveyItem->dirty());
QVERIFY(_multiSpy->checkNoSignals());
_surveyItem->setDirty(true);
QVERIFY(_surveyItem->dirty());
QVERIFY(_multiSpy->checkOnlySignalByMask(dirtyChangedMask));
QVERIFY(_multiSpy->pullBoolFromSignalIndex(dirtyChangedIndex));
_multiSpy->clearAllSignals();
_surveyItem->setDirty(false);
QVERIFY(!_surveyItem->dirty());
QVERIFY(_multiSpy->checkOnlySignalByMask(dirtyChangedMask));
QVERIFY(!_multiSpy->pullBoolFromSignalIndex(dirtyChangedIndex));
_multiSpy->clearAllSignals();
// These facts should set dirty when changed
QList<Fact*> rgFacts;
rgFacts << _surveyItem->gridAltitude() << _surveyItem->gridAngle() << _surveyItem->gridSpacing() << _surveyItem->turnaroundDist() << _surveyItem->cameraTriggerDistance() <<
_surveyItem->gridAltitudeRelative() << _surveyItem->cameraTriggerInTurnaround() << _surveyItem->hoverAndCapture();
foreach(Fact* fact, rgFacts) {
qDebug() << fact->name();
QVERIFY(!_surveyItem->dirty());
if (fact->typeIsBool()) {
fact->setRawValue(!fact->rawValue().toBool());
} else {
fact->setRawValue(fact->rawValue().toDouble() + 1);
}
QVERIFY(_multiSpy->checkSignalByMask(dirtyChangedMask));
QVERIFY(_multiSpy->pullBoolFromSignalIndex(dirtyChangedIndex));
_surveyItem->setDirty(false);
_multiSpy->clearAllSignals();
}
rgFacts.clear();
// These facts should not change dirty bit
rgFacts << _surveyItem->groundResolution() << _surveyItem->frontalOverlap() << _surveyItem->sideOverlap() << _surveyItem->cameraSensorWidth() << _surveyItem->cameraSensorHeight() <<
_surveyItem->cameraResolutionWidth() << _surveyItem->cameraResolutionHeight() << _surveyItem->cameraFocalLength() << _surveyItem->cameraOrientationLandscape() <<
_surveyItem->fixedValueIsAltitude() << _surveyItem->camera() << _surveyItem->manualGrid();
foreach(Fact* fact, rgFacts) {
qDebug() << fact->name();
QVERIFY(!_surveyItem->dirty());
if (fact->typeIsBool()) {
fact->setRawValue(!fact->rawValue().toBool());
} else {
fact->setRawValue(fact->rawValue().toDouble() + 1);
}
QVERIFY(_multiSpy->checkNoSignalByMask(dirtyChangedMask));
QVERIFY(!_surveyItem->dirty());
_multiSpy->clearAllSignals();
}
rgFacts.clear();
}
void SurveyMissionItemTest::_testCameraValueChanged(void)
{
// These facts should trigger cameraValueChanged when changed
QList<Fact*> rgFacts;
rgFacts << _surveyItem->groundResolution() << _surveyItem->frontalOverlap() << _surveyItem->sideOverlap() << _surveyItem->cameraSensorWidth() << _surveyItem->cameraSensorHeight() <<
_surveyItem->cameraResolutionWidth() << _surveyItem->cameraResolutionHeight() << _surveyItem->cameraFocalLength() << _surveyItem->cameraOrientationLandscape();
foreach(Fact* fact, rgFacts) {
qDebug() << fact->name();
if (fact->typeIsBool()) {
fact->setRawValue(!fact->rawValue().toBool());
} else {
fact->setRawValue(fact->rawValue().toDouble() + 1);
}
QVERIFY(_multiSpy->checkSignalByMask(cameraValueChangedMask));
_multiSpy->clearAllSignals();
}
rgFacts.clear();
// These facts should not trigger cameraValueChanged
rgFacts << _surveyItem->gridAltitude() << _surveyItem->gridAngle() << _surveyItem->gridSpacing() << _surveyItem->turnaroundDist() << _surveyItem->cameraTriggerDistance() <<
_surveyItem->gridAltitudeRelative() << _surveyItem->cameraTriggerInTurnaround() << _surveyItem->hoverAndCapture() <<
_surveyItem->fixedValueIsAltitude() << _surveyItem->camera() << _surveyItem->manualGrid();
foreach(Fact* fact, rgFacts) {
qDebug() << fact->name();
if (fact->typeIsBool()) {
fact->setRawValue(!fact->rawValue().toBool());
} else {
fact->setRawValue(fact->rawValue().toDouble() + 1);
}
QVERIFY(_multiSpy->checkNoSignalByMask(cameraValueChangedMask));
_multiSpy->clearAllSignals();
}
rgFacts.clear();
}
void SurveyMissionItemTest::_testCameraTrigger(void)
{
#if 0
QCOMPARE(_surveyItem->property("cameraTrigger").toBool(), true);
// Set up a grid
for (int i=0; i<3; i++) {
_mapPolygon->appendVertex(_polyPoints[i]);
}
_surveyItem->setDirty(false);
_multiSpy->clearAllSignals();
int lastSeq = _surveyItem->lastSequenceNumber();
QVERIFY(lastSeq > 0);
// Turning off camera triggering should remove two camera trigger mission items, this should trigger:
// lastSequenceNumberChanged
// dirtyChanged
_surveyItem->setProperty("cameraTrigger", false);
QVERIFY(_multiSpy->checkOnlySignalByMask(lastSequenceNumberChangedMask | dirtyChangedMask | cameraTriggerChangedMask));
QCOMPARE(_multiSpy->pullIntFromSignalIndex(lastSequenceNumberChangedIndex), lastSeq - 2);
_surveyItem->setDirty(false);
_multiSpy->clearAllSignals();
// Turn on camera triggering and make sure things go back to previous count
_surveyItem->setProperty("cameraTrigger", true);
QVERIFY(_multiSpy->checkOnlySignalByMask(lastSequenceNumberChangedMask | dirtyChangedMask | cameraTriggerChangedMask));
QCOMPARE(_multiSpy->pullIntFromSignalIndex(lastSequenceNumberChangedIndex), lastSeq);
#endif
}
// Clamp expected grid angle from 0<->180. We don't care about opposite angles like 90/270
double SurveyMissionItemTest::_clampGridAngle180(double gridAngle)
{
if (gridAngle >= 0.0) {
if (gridAngle == 360.0) {
gridAngle = 0.0;
} else if (gridAngle >= 180.0) {
gridAngle -= 180.0;
}
} else {
if (gridAngle < -180.0) {
gridAngle += 360.0;
} else {
gridAngle += 180.0;
}
}
return gridAngle;
}
void SurveyMissionItemTest::_testGridAngle(void)
{
QGCMapPolygon* mapPolygon = _surveyItem->mapPolygon();
for (int i=0; i<_polyPoints.count(); i++) {
QGeoCoordinate& vertex = _polyPoints[i];
mapPolygon->appendVertex(vertex);
}
for (double gridAngle=-360.0; gridAngle<=360.0; gridAngle++) {
_surveyItem->gridAngle()->setRawValue(gridAngle);
QVariantList gridPoints = _surveyItem->gridPoints();
QGeoCoordinate firstTransectEntry = gridPoints[0].value<QGeoCoordinate>();
QGeoCoordinate firstTransectExit = gridPoints[1].value<QGeoCoordinate>();
double azimuth = firstTransectEntry.azimuthTo(firstTransectExit);
//qDebug() << gridAngle << azimuth << _clampGridAngle180(gridAngle) << _clampGridAngle180(azimuth);
QCOMPARE((int)_clampGridAngle180(gridAngle), (int)_clampGridAngle180(azimuth));
}
}
void SurveyMissionItemTest::_testEntryLocation(void)
{
QGCMapPolygon* mapPolygon = _surveyItem->mapPolygon();
for (int i=0; i<_polyPoints.count(); i++) {
QGeoCoordinate& vertex = _polyPoints[i];
mapPolygon->appendVertex(vertex);
}
for (double gridAngle=-360.0; gridAngle<=360.0; gridAngle++) {
_surveyItem->gridAngle()->setRawValue(gridAngle);
QList<QGeoCoordinate> rgSeenEntryCoords;
QList<int> rgEntryLocation;
rgEntryLocation << SurveyMissionItem::EntryLocationTopLeft
<< SurveyMissionItem::EntryLocationTopRight
<< SurveyMissionItem::EntryLocationBottomLeft
<< SurveyMissionItem::EntryLocationBottomRight;
// Validate that each entry location is unique
for (int i=0; i<rgEntryLocation.count(); i++) {
int entryLocation = rgEntryLocation[i];
_surveyItem->gridEntryLocation()->setRawValue(entryLocation);
QVERIFY(!rgSeenEntryCoords.contains(_surveyItem->coordinate()));
rgSeenEntryCoords << _surveyItem->coordinate();
}
rgSeenEntryCoords.clear();
}
}
<|endoftext|> |
<commit_before>#ifndef MANIFOLDS_FUNCTIONS_DERIVATIVES_HH
#define MANIFOLDS_FUNCTIONS_DERIVATIVES_HH
#include "addition.hh"
#include "multiplication.hh"
#include "variables.hh"
#include "division.hh"
#include "polynomial.hh"
#include "trig.hh"
#include "operators.hh"
#include "matrix.hh"
namespace manifolds {
template <int iter>
struct DerivativeWrapper
{
template <class ... Funcs, int i,
std::size_t ... indices>
static auto Derivative(const Addition<Funcs...> & a,
Variable<i> v,
std::integer_sequence<std::size_t, indices...>)
{
return
Add(DerivativeWrapper<iter+1>::
Derivative(std::get<indices>(a.GetFunctions())..., v));
}
template <class ... Funcs, int i>
static auto Derivative(const Addition<Funcs...> & a,
Variable<i> v)
{
return DerivativeWrapper<iter+1>::
Derivative(a, v, std::index_sequence_for<Funcs...>());
}
template <class F, int i>
static auto Derivative(UnaryMinus<F> f, Variable<i> v)
{
return -DerivativeWrapper<iter+1>::
Derivative(f.GetFunction(), v);
}
template <class Func, int i>
static auto Derivative(const Composition<Func> & c,
Variable<i> v)
{
return DerivativeWrapper<iter+1>::
Derivative(std::get<0>(c.GetFunctions()), v);
}
template <class Func, class ... Funcs, int i,
class = typename std::enable_if<
(sizeof...(Funcs)>0)>::type>
static auto Derivative(const Composition<Func,Funcs...> & c,
Variable<i> v)
{
auto funcs = remove_element<0>(c.GetFunctions());
auto d = Derivative(std::get<0>(c.GetFunctions()),
Variable<0>());
auto next =
std::tuple_cat(std::make_tuple(d), funcs);
return Composition<decltype(d), Funcs...>(next) *
DerivativeWrapper<iter+1>::
Derivative(Composition<Funcs...>(funcs), v);
}
template <class F1, class F2, int i>
static auto Derivative(const Division<F1,F2>& d,
Variable<i> v)
{
auto n = d.GetNumerator();
auto de = d.GetDenominator();
return (DerivativeWrapper<iter+1>::Derivative(n, v) * de -
n * DerivativeWrapper<iter+1>::Derivative(de, v)) /
(de * de);
}
template <int i, class ... Funcs, int d_i,
std::size_t ... lefts, std::size_t ... rights>
static auto TimesDerivHelper(const Multiplication<Funcs...> & a,
Variable<d_i> v,
std::integer_sequence<
std::size_t, lefts...>,
std::integer_sequence<
std::size_t, rights...>)
{
auto t = a.GetFunctions();
return Multiply(std::get<lefts>(t)...,
DerivativeWrapper<iter+1>::
Derivative(std::get<i>(t),v),
std::get<rights+i+1>(t)...);
}
template <int i, class ... Funcs, int d_i>
static auto TimesDerivHelper(const Multiplication<Funcs...> & a,
Variable<d_i> v)
{
return TimesDerivHelper<i>
(a, v, std::make_index_sequence<i>(),
std::make_index_sequence<
sizeof...(Funcs)-i-1>());
}
template <class ... Funcs, int i,
std::size_t ... indices>
static auto Derivative(const Multiplication<Funcs...> & a,
Variable<i> v,
std::integer_sequence<std::size_t, indices...>)
{
return
Add(TimesDerivHelper<indices>(a, v)...);
}
template <class ... Funcs, int i>
static auto Derivative(const Multiplication<Funcs...> & a,
Variable<i> v)
{
return DerivativeWrapper<iter+1>::
Derivative(a, v, std::index_sequence_for<Funcs...>());
}
template <class CoeffType, class Order, int i>
static auto Derivative(const Polynomial<CoeffType, Order> & p,
Variable<i>)
{
return zero;
}
template <class CoeffType, int i>
static auto Derivative(Polynomial<CoeffType, int_<1>> p,
Variable<i>)
{
return zero;
}
template <class CoeffType, class Order,
class = typename std::enable_if<
Order::value != 1
>::type>
static auto Derivative(const Polynomial<CoeffType, Order> & p,
Variable<0>)
{
std::array<CoeffType, Order::value-1> d;
for(unsigned i = 0; i < Order::value-1; i++)
d[i] = (i+1)*p.GetCoeffs()[i+1];
return Polynomial<CoeffType,int_<Order::value-1>>{d};
}
#define TRIG_DERIV(func, deriv) \
static auto Derivative(func,Variable<0>){return deriv;} \
template <int i> \
static auto Derivative(func,Variable<i>){return zero;}
TRIG_DERIV(Sin, Cos())
TRIG_DERIV(Cos, -Sin())
TRIG_DERIV(Tan, 1_c / (Cos()*Cos()))
TRIG_DERIV(Log, 1_c / x)
TRIG_DERIV(Sinh, Cosh())
TRIG_DERIV(Cosh, Sinh())
TRIG_DERIV(Tanh, 1_c / (Cosh()*Cosh()))
TRIG_DERIV(ASin, 1_c / Sqrt()(1_c-x*x))
TRIG_DERIV(ACos, -1_c / Sqrt()(1_c-x*x))
TRIG_DERIV(ATan, 1_c / (1_c+x*x))
TRIG_DERIV(ASinh, 1_c / Sqrt()(1_c+x*x))
TRIG_DERIV(ACosh, 1_c / Sqrt()(-1_c+x*x))
TRIG_DERIV(ATanh, 1_c / (1_c-x*x))
TRIG_DERIV(Exp, Exp())
TRIG_DERIV(Sqrt, 0.5_c / Sqrt())
TRIG_DERIV(Zero, zero)
#undef TRIG_DERIV
template <int i>
static auto Derivative(Pow, Variable<i>)
{
return zero;
}
static auto Derivative(Pow, Variable<0>)
{
return y * Pow()(x, y-1_c);
}
static auto Derivative(Pow, Variable<1>)
{
return (Log()(x)) * Pow()(x, y);
}
template <int i>
static auto Derivative(Variable<i>, Variable<i>)
{
return 1_c;
}
template <int i, int j>
static auto Derivative(Variable<i>, Variable<j>)
{
return zero;
}
template <class T, std::size_t ... ins>
static auto FullDeriv(T t, int_<T::output_dim>,
std::integer_sequence<std::size_t, ins...>)
{
return std::tuple<>();
}
template <class T>
static auto GetOutputs(T t, int_<1>)
{
return std::make_tuple(t);
}
template <class T, int i>
static auto GetOutputs(T t, int_<i>)
{
return t.GetOutputs();
}
template <class T>
static auto GetOutputs(T t)
{
return GetOutputs(t, int_<T::output_dim>());
}
template <int col, class T, std::size_t ... ins,
class = typename std::enable_if<
col != T::output_dim>::type>
static auto FullDeriv(T t, int_<col>,
std::integer_sequence<std::size_t, ins...> b)
{
auto r =
std::make_tuple(Derivative(std::get<col>(GetOutputs(t)),
Variable<ins>())...);
return tuple_cat(r, DerivativeWrapper<iter+1>::
FullDeriv(t, int_<col+1>(), b));
}
template <class T>
static auto FullDerivOutput(std::tuple<T> t,
int_<1>, int_<1>)
{
return std::get<0>(t);
}
template <class ... Ts, int rows, int cols>
static auto FullDerivOutput(std::tuple<Ts...> t,
int_<rows>, int_<cols>)
{
return GetFunctionMatrix<rows,cols>(t);
}
template <class T>
static auto FullDeriv(T t)
{
return DerivativeWrapper<iter+1>::
FullDeriv(t, int_<0>(), std::make_index_sequence<
T::input_dim>());
}
};
template <class T, int i>
auto Derivative(T t, Variable<i> v)
{
return DerivativeWrapper<0>::Derivative(t, v);
}
template <class T>
auto Derivative(T t)
{
return DerivativeWrapper<0>::Derivative(t, x);
}
template <class T>
auto FullDerivative(T t)
{
return DerivativeWrapper<0>::
FullDerivOutput(DerivativeWrapper<0>::FullDeriv(t),
int_<T::output_dim>(),
int_<T::input_dim>());
}
template <int order, int i = 0>
struct D
{
template <class F>
auto operator()(F f) const
{
return D<order-1,i>()(Derivative(f, Variable<i>()));
}
};
template <int i>
struct D<0,i>
{
template <class F>
auto operator()(F f) const
{
return f;
}
};
}
#endif
<commit_msg>Added derivative of FunctionMatrix and fixed derivative of function composition (especially in regards to multi-dimensional functions)<commit_after>#ifndef MANIFOLDS_FUNCTIONS_DERIVATIVES_HH
#define MANIFOLDS_FUNCTIONS_DERIVATIVES_HH
#include "addition.hh"
#include "multiplication.hh"
#include "variables.hh"
#include "division.hh"
#include "polynomial.hh"
#include "trig.hh"
#include "operators.hh"
#include "matrix.hh"
#ifdef PRINT_SIMPLIFIES
# define PRINT_DERIV(object, variable, name) \
std::cout << "Taking derivative of " << name \
<< " (" << object << ") with respect to " << variable <<'\n'
#else
# define PRINT_DERIV(o, v, n)
#endif
namespace manifolds {
template <int iter>
struct DerivativeWrapper
{
template <class ... Funcs, int i,
std::size_t ... indices>
static auto Derivative(const Addition<Funcs...> & a,
Variable<i> v,
std::integer_sequence<std::size_t, indices...>)
{
return
Add(DerivativeWrapper<iter+1>::
Derivative(std::get<indices>(a.GetFunctions())..., v));
}
template <class ... Funcs, int i>
static auto Derivative(const Addition<Funcs...> & a,
Variable<i> v)
{
PRINT_DERIV(a, v, "addition");
return DerivativeWrapper<iter+1>::
Derivative(a, v, std::index_sequence_for<Funcs...>());
}
template <class F, int i>
static auto Derivative(UnaryMinus<F> f, Variable<i> v)
{
PRINT_DERIV(f, v, "negative of function");
return -DerivativeWrapper<iter+1>::
Derivative(f.GetFunction(), v);
}
template <class Func, int i>
static auto Derivative(const Composition<Func> & c,
Variable<i> v)
{
PRINT_DERIV(c, v, "last composition");
return DerivativeWrapper<iter+1>::
Derivative(std::get<0>(c.GetFunctions()),v);
}
template <class Func, class ... Funcs, int i,
class = typename std::enable_if<
(sizeof...(Funcs)>0)>::type>
static auto Derivative(const Composition<Func,Funcs...> & c,
Variable<i> v)
{
PRINT_DERIV(c, v, "composition");
auto funcs = remove_element<0>(c.GetFunctions());
auto d = FullDeriv(std::get<0>(c.GetFunctions()));
auto next =
std::tuple_cat(std::make_tuple(d), funcs);
return Composition<decltype(d), Funcs...>(next) *
DerivativeWrapper<iter+1>::
Derivative(Composition<Funcs...>(funcs), v);
}
template <class F1, class F2, int i>
static auto Derivative(const Division<F1,F2>& d,
Variable<i> v)
{
PRINT_DERIV(d, v, "division");
auto n = d.GetNumerator();
auto de = d.GetDenominator();
return (DerivativeWrapper<iter+1>::Derivative(n, v) * de -
n * DerivativeWrapper<iter+1>::Derivative(de, v)) /
(de * de);
}
template <int i, class ... Funcs, int d_i,
std::size_t ... lefts, std::size_t ... rights>
static auto TimesDerivHelper(const Multiplication<Funcs...> & a,
Variable<d_i> v,
std::integer_sequence<
std::size_t, lefts...>,
std::integer_sequence<
std::size_t, rights...>)
{
auto t = a.GetFunctions();
return Multiply(std::get<lefts>(t)...,
DerivativeWrapper<iter+1>::
Derivative(std::get<i>(t),v),
std::get<rights+i+1>(t)...);
}
template <int i, class ... Funcs, int d_i>
static auto TimesDerivHelper(const Multiplication<Funcs...> & a,
Variable<d_i> v)
{
return TimesDerivHelper<i>
(a, v, std::make_index_sequence<i>(),
std::make_index_sequence<
sizeof...(Funcs)-i-1>());
}
template <class ... Funcs, int i,
std::size_t ... indices>
static auto Derivative(const Multiplication<Funcs...> & a,
Variable<i> v,
std::integer_sequence<std::size_t, indices...>)
{
return
Add(TimesDerivHelper<indices>(a, v)...);
}
template <class ... Funcs, int i>
static auto Derivative(const Multiplication<Funcs...> & a,
Variable<i> v)
{
PRINT_DERIV(a, v, "multiplication");
return DerivativeWrapper<iter+1>::
Derivative(a, v, std::index_sequence_for<Funcs...>());
}
template <class CoeffType, class Order, int i>
static auto Derivative(const Polynomial<CoeffType, Order> & p,
Variable<i> v)
{
PRINT_DERIV(p, v, "non-constant polynomial");
return zero;
}
template <class CoeffType, int i>
static auto Derivative(Polynomial<CoeffType, int_<1>> p,
Variable<i> v)
{
PRINT_DERIV(p, v, "constant polynomial");
return zero;
}
template <class CoeffType, class Order,
class = typename std::enable_if<
Order::value != 1
>::type>
static auto Derivative(const Polynomial<CoeffType, Order> & p,
Variable<0> v)
{
PRINT_SIMPLIFIES(p, v, "non-constant polynomial");
std::array<CoeffType, Order::value-1> d;
for(unsigned i = 0; i < Order::value-1; i++)
d[i] = (i+1)*p.GetCoeffs()[i+1];
return Polynomial<CoeffType,int_<Order::value-1>>{d};
}
#define TRIG_DERIV(func, deriv) \
static auto Derivative(func f,Variable<0> v){ \
PRINT_DERIV(f,v,#func); return deriv;} \
template <int i> \
static auto Derivative(func f,Variable<i> v){ \
PRINT_DERIV(f,v,#func); return zero;}
TRIG_DERIV(Sin, Cos())
TRIG_DERIV(Cos, -Sin())
TRIG_DERIV(Tan, 1_c / (Cos()*Cos()))
TRIG_DERIV(Log, 1_c / x)
TRIG_DERIV(Sinh, Cosh())
TRIG_DERIV(Cosh, Sinh())
TRIG_DERIV(Tanh, 1_c / (Cosh()*Cosh()))
TRIG_DERIV(ASin, 1_c / Sqrt()(1_c-x*x))
TRIG_DERIV(ACos, -1_c / Sqrt()(1_c-x*x))
TRIG_DERIV(ATan, 1_c / (1_c+x*x))
TRIG_DERIV(ASinh, 1_c / Sqrt()(1_c+x*x))
TRIG_DERIV(ACosh, 1_c / Sqrt()(-1_c+x*x))
TRIG_DERIV(ATanh, 1_c / (1_c-x*x))
TRIG_DERIV(Exp, Exp())
TRIG_DERIV(Sqrt, 0.5_c / Sqrt())
TRIG_DERIV(Zero, zero)
#undef TRIG_DERIV
template <int i>
static auto Derivative(Pow p, Variable<i> v)
{
PRINT_DERIV(p, v, "Pow");
return zero;
}
static auto Derivative(Pow p, Variable<0> v)
{
PRINT_DERIV(p, v, "Pow");
return y * Pow()(x, y-1_c);
}
static auto Derivative(Pow p, Variable<1> v)
{
PRINT_DERIV(p, v, "Pow");
return (Log()(x)) * Pow()(x, y);
}
template <int i>
static auto Derivative(Variable<i> v1, Variable<i> v2)
{
PRINT_DERIV(v1, v2, "variable");
return 1_c;
}
template <int i, int j>
static auto Derivative(Variable<i> v1, Variable<j> v2)
{
PRINT_DERIV(v1, v2, "variable");
return zero;
}
template <class ... Functions, int i,
std::size_t ... indices>
static auto Derivative(FunctionMatrix<Functions...> m,
Variable<i> v,
std::integer_sequence<
std::size_t,indices...>)
{
typedef FunctionMatrix<Functions...> M;
return GetFunctionMatrix<
M::num_rows,M::num_cols>
(std::make_tuple(Derivative
(std::get<indices>(m.GetFunctions()),
v)...));
}
template <class ... Functions, int i>
static auto Derivative(FunctionMatrix<Functions...> m,
Variable<i> v)
{
PRINT_DERIV(m, v, "function matrix");
static const int size =
std::tuple_size<decltype(m.GetFunctions())>::type::value;
return Derivative
(m, v, std::make_index_sequence<size>());
}
template <class T, std::size_t ... ins>
static auto FullDerivHelper(T t, int_<T::output_dim>,
std::integer_sequence<std::size_t, ins...>)
{
return std::tuple<>();
}
template <class T>
static auto GetOutputs(T t, int_<1>)
{
return std::make_tuple(t);
}
template <class T, int i>
static auto GetOutputs(T t, int_<i>)
{
return t.GetOutputs();
}
template <class T>
static auto GetOutputs(T t)
{
return GetOutputs(t, int_<T::output_dim>());
}
template <int col, class T, std::size_t ... ins,
class = typename std::enable_if<
col != T::output_dim>::type>
static auto FullDerivHelper(T t, int_<col>,
std::integer_sequence<std::size_t, ins...> b)
{
auto r =
std::make_tuple(Derivative(std::get<col>(GetOutputs(t)),
Variable<ins>())...);
return tuple_cat(r, DerivativeWrapper<iter+1>::
FullDerivHelper(t, int_<col+1>(), b));
}
template <class T>
static auto FullDerivOutput(std::tuple<T> t,
int_<1>, int_<1>)
{
return std::get<0>(t);
}
template <class ... Ts, int rows, int cols>
static auto FullDerivOutput(std::tuple<Ts...> t,
int_<rows>, int_<cols>)
{
return GetFunctionMatrix<rows,cols>(t);
}
template <class T>
static auto FullDeriv(T t)
{
#ifdef PRINT_SIMPLIFIES
std::cout << "Taking full derivative of " << t << '\n';
#endif
return FullDerivOutput
(DerivativeWrapper<iter+1>::
FullDerivHelper(t, int_<0>(),
std::make_index_sequence<
T::input_dim>()),
int_<T::output_dim>(), int_<T::input_dim>());
}
};
template <class T, int i>
auto Derivative(T t, Variable<i> v)
{
return DerivativeWrapper<0>::Derivative(t, v);
}
template <class T>
auto Derivative(T t)
{
return DerivativeWrapper<0>::Derivative(t, x);
}
template <class T>
auto FullDerivative(T t)
{
return DerivativeWrapper<0>::FullDeriv(t);
}
template <int order, int i = 0>
struct D
{
template <class F>
auto operator()(F f) const
{
return D<order-1,i>()(Derivative(f, Variable<i>()));
}
};
template <int i>
struct D<0,i>
{
template <class F>
auto operator()(F f) const
{
return f;
}
};
}
#endif
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright 2019 ScyllaDB
*/
#include <boost/intrusive/parent_from_member.hpp>
#include <seastar/core/fair_queue.hh>
#include <seastar/core/future.hh>
#include <seastar/core/shared_ptr.hh>
#include <seastar/core/circular_buffer.hh>
#include <seastar/util/noncopyable_function.hh>
#include <seastar/core/reactor.hh>
#include <queue>
#include <chrono>
#include <unordered_set>
#include <cmath>
#include "fmt/format.h"
#include "fmt/ostream.h"
namespace seastar {
static_assert(sizeof(fair_queue_ticket) == sizeof(uint64_t), "unexpected fair_queue_ticket size");
static_assert(sizeof(fair_queue_entry) <= 3 * sizeof(void*), "unexpected fair_queue_entry::_hook size");
static_assert(sizeof(fair_queue_entry::container_list_t) == 2 * sizeof(void*), "unexpected priority_class::_queue size");
fair_queue_ticket::fair_queue_ticket(uint32_t weight, uint32_t size) noexcept
: _weight(weight)
, _size(size)
{}
float fair_queue_ticket::normalize(fair_queue_ticket denominator) const noexcept {
return float(_weight) / denominator._weight + float(_size) / denominator._size;
}
fair_queue_ticket fair_queue_ticket::operator+(fair_queue_ticket desc) const noexcept {
return fair_queue_ticket(_weight + desc._weight, _size + desc._size);
}
fair_queue_ticket& fair_queue_ticket::operator+=(fair_queue_ticket desc) noexcept {
_weight += desc._weight;
_size += desc._size;
return *this;
}
fair_queue_ticket fair_queue_ticket::operator-(fair_queue_ticket desc) const noexcept {
return fair_queue_ticket(_weight - desc._weight, _size - desc._size);
}
fair_queue_ticket& fair_queue_ticket::operator-=(fair_queue_ticket desc) noexcept {
_weight -= desc._weight;
_size -= desc._size;
return *this;
}
bool fair_queue_ticket::strictly_less(fair_queue_ticket rhs) const noexcept {
return (_weight < rhs._weight) && (_size < rhs._size);
}
fair_queue_ticket::operator bool() const noexcept {
return (_weight > 0) || (_size > 0);
}
bool fair_queue_ticket::operator==(const fair_queue_ticket& o) const noexcept {
return _weight == o._weight && _size == o._size;
}
std::ostream& operator<<(std::ostream& os, fair_queue_ticket t) {
return os << t._weight << ":" << t._size;
}
fair_group_rover::fair_group_rover(uint32_t weight, uint32_t size) noexcept
: _weight(weight)
, _size(size)
{}
fair_queue_ticket fair_group_rover::maybe_ahead_of(const fair_group_rover& other) const noexcept {
return fair_queue_ticket(std::max<int32_t>(_weight - other._weight, 0),
std::max<int32_t>(_size - other._size, 0));
}
fair_group_rover fair_group_rover::operator+(fair_queue_ticket t) const noexcept {
return fair_group_rover(_weight + t._weight, _size + t._size);
}
std::ostream& operator<<(std::ostream& os, fair_group_rover r) {
return os << r._weight << ":" << r._size;
}
fair_group::fair_group(config cfg) noexcept
: _capacity_tail(fair_group_rover(0, 0))
, _capacity_head(fair_group_rover(cfg.max_req_count, cfg.max_bytes_count))
, _maximum_capacity(cfg.max_req_count, cfg.max_bytes_count)
{
assert(!_capacity_tail.load(std::memory_order_relaxed)
.maybe_ahead_of(_capacity_head.load(std::memory_order_relaxed)));
seastar_logger.debug("Created fair group, capacity {}:{}", cfg.max_req_count, cfg.max_bytes_count);
}
fair_group_rover fair_group::grab_capacity(fair_queue_ticket cap) noexcept {
fair_group_rover cur = _capacity_tail.load(std::memory_order_relaxed);
while (!_capacity_tail.compare_exchange_weak(cur, cur + cap)) ;
return cur;
}
void fair_group::release_capacity(fair_queue_ticket cap) noexcept {
fair_group_rover cur = _capacity_head.load(std::memory_order_relaxed);
while (!_capacity_head.compare_exchange_weak(cur, cur + cap)) ;
}
fair_queue::fair_queue(fair_group& group, config cfg)
: _config(std::move(cfg))
, _group(group)
, _base(std::chrono::steady_clock::now())
{
seastar_logger.debug("Created fair queue, ticket pace {}:{}", cfg.ticket_weight_pace, cfg.ticket_size_pace);
}
void fair_queue::push_priority_class(priority_class_ptr pc) {
if (!pc->_queued) {
_handles.push(pc);
pc->_queued = true;
}
}
priority_class_ptr fair_queue::peek_priority_class() {
assert(!_handles.empty());
return _handles.top();
}
void fair_queue::pop_priority_class(priority_class_ptr pc) {
assert(pc->_queued);
pc->_queued = false;
_handles.pop();
}
float fair_queue::normalize_factor() const {
return std::numeric_limits<float>::min();
}
void fair_queue::normalize_stats() {
auto time_delta = std::log(normalize_factor()) * _config.tau;
// time_delta is negative; and this may advance _base into the future
_base -= std::chrono::duration_cast<clock_type::duration>(time_delta);
for (auto& pc: _all_classes) {
pc->_accumulated *= normalize_factor();
}
}
std::chrono::microseconds fair_queue_ticket::duration_at_pace(float weight_pace, float size_pace) const noexcept {
unsigned long dur = ((_weight * weight_pace) + (_size * size_pace));
return std::chrono::microseconds(dur);
}
bool fair_queue::grab_pending_capacity(fair_queue_ticket cap) noexcept {
fair_group_rover pending_head = _pending->orig_tail + cap;
if (pending_head.maybe_ahead_of(_group.head())) {
return false;
}
if (cap == _pending->cap) {
_pending.reset();
} else {
/*
* This branch is called when the fair queue decides to
* submit not the same request that entered it into the
* pending state and this new request crawls through the
* expected head value.
*/
_pending->orig_tail = _group.grab_capacity(cap);
}
return true;
}
bool fair_queue::grab_capacity(fair_queue_ticket cap) noexcept {
if (_pending) {
return grab_pending_capacity(cap);
}
fair_group_rover orig_tail = _group.grab_capacity(cap);
if ((orig_tail + cap).maybe_ahead_of(_group.head())) {
_pending.emplace(orig_tail, cap);
return false;
}
return true;
}
priority_class_ptr fair_queue::register_priority_class(uint32_t shares) {
priority_class_ptr pclass = make_lw_shared<priority_class>(shares);
_all_classes.insert(pclass);
return pclass;
}
void fair_queue::unregister_priority_class(priority_class_ptr pclass) {
assert(pclass->_queue.empty());
_all_classes.erase(pclass);
}
size_t fair_queue::waiters() const {
return _requests_queued;
}
size_t fair_queue::requests_currently_executing() const {
return _requests_executing;
}
fair_queue_ticket fair_queue::resources_currently_waiting() const {
return _resources_queued;
}
fair_queue_ticket fair_queue::resources_currently_executing() const {
return _resources_executing;
}
void fair_queue::queue(priority_class_ptr pc, fair_queue_entry& ent) {
// We need to return a future in this function on which the caller can wait.
// Since we don't know which queue we will use to execute the next request - if ours or
// someone else's, we need a separate promise at this point.
push_priority_class(pc);
pc->_queue.push_back(ent);
_resources_queued += ent._ticket;
_requests_queued++;
}
void fair_queue::notify_requests_finished(fair_queue_ticket desc, unsigned nr) noexcept {
_resources_executing -= desc;
_requests_executing -= nr;
_group.release_capacity(desc);
}
void fair_queue::dispatch_requests(std::function<void(fair_queue_entry&)> cb) {
while (_resources_queued) {
priority_class_ptr h;
while (true) {
h = peek_priority_class();
if (!h->_queue.empty()) {
break;
}
pop_priority_class(h);
}
auto& req = h->_queue.front();
if (!grab_capacity(req._ticket)) {
break;
}
pop_priority_class(h);
h->_queue.pop_front();
_resources_executing += req._ticket;
_resources_queued -= req._ticket;
_requests_executing++;
_requests_queued--;
auto delta = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - _base);
auto req_cost = req._ticket.normalize(_group.maximum_capacity()) / h->_shares;
auto cost = expf(1.0f/_config.tau.count() * delta.count()) * req_cost;
float next_accumulated = h->_accumulated + cost;
while (std::isinf(next_accumulated)) {
normalize_stats();
// If we have renormalized, our time base will have changed. This should happen very infrequently
delta = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - _base);
cost = expf(1.0f/_config.tau.count() * delta.count()) * req_cost;
next_accumulated = h->_accumulated + cost;
}
h->_accumulated = next_accumulated;
if (!h->_queue.empty()) {
push_priority_class(h);
}
cb(req);
}
}
}
<commit_msg>fair_queue: Change the dispatch condition<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright 2019 ScyllaDB
*/
#include <boost/intrusive/parent_from_member.hpp>
#include <seastar/core/fair_queue.hh>
#include <seastar/core/future.hh>
#include <seastar/core/shared_ptr.hh>
#include <seastar/core/circular_buffer.hh>
#include <seastar/util/noncopyable_function.hh>
#include <seastar/core/reactor.hh>
#include <queue>
#include <chrono>
#include <unordered_set>
#include <cmath>
#include "fmt/format.h"
#include "fmt/ostream.h"
namespace seastar {
static_assert(sizeof(fair_queue_ticket) == sizeof(uint64_t), "unexpected fair_queue_ticket size");
static_assert(sizeof(fair_queue_entry) <= 3 * sizeof(void*), "unexpected fair_queue_entry::_hook size");
static_assert(sizeof(fair_queue_entry::container_list_t) == 2 * sizeof(void*), "unexpected priority_class::_queue size");
fair_queue_ticket::fair_queue_ticket(uint32_t weight, uint32_t size) noexcept
: _weight(weight)
, _size(size)
{}
float fair_queue_ticket::normalize(fair_queue_ticket denominator) const noexcept {
return float(_weight) / denominator._weight + float(_size) / denominator._size;
}
fair_queue_ticket fair_queue_ticket::operator+(fair_queue_ticket desc) const noexcept {
return fair_queue_ticket(_weight + desc._weight, _size + desc._size);
}
fair_queue_ticket& fair_queue_ticket::operator+=(fair_queue_ticket desc) noexcept {
_weight += desc._weight;
_size += desc._size;
return *this;
}
fair_queue_ticket fair_queue_ticket::operator-(fair_queue_ticket desc) const noexcept {
return fair_queue_ticket(_weight - desc._weight, _size - desc._size);
}
fair_queue_ticket& fair_queue_ticket::operator-=(fair_queue_ticket desc) noexcept {
_weight -= desc._weight;
_size -= desc._size;
return *this;
}
bool fair_queue_ticket::strictly_less(fair_queue_ticket rhs) const noexcept {
return (_weight < rhs._weight) && (_size < rhs._size);
}
fair_queue_ticket::operator bool() const noexcept {
return (_weight > 0) || (_size > 0);
}
bool fair_queue_ticket::operator==(const fair_queue_ticket& o) const noexcept {
return _weight == o._weight && _size == o._size;
}
std::ostream& operator<<(std::ostream& os, fair_queue_ticket t) {
return os << t._weight << ":" << t._size;
}
fair_group_rover::fair_group_rover(uint32_t weight, uint32_t size) noexcept
: _weight(weight)
, _size(size)
{}
fair_queue_ticket fair_group_rover::maybe_ahead_of(const fair_group_rover& other) const noexcept {
return fair_queue_ticket(std::max<int32_t>(_weight - other._weight, 0),
std::max<int32_t>(_size - other._size, 0));
}
fair_group_rover fair_group_rover::operator+(fair_queue_ticket t) const noexcept {
return fair_group_rover(_weight + t._weight, _size + t._size);
}
std::ostream& operator<<(std::ostream& os, fair_group_rover r) {
return os << r._weight << ":" << r._size;
}
fair_group::fair_group(config cfg) noexcept
: _capacity_tail(fair_group_rover(0, 0))
, _capacity_head(fair_group_rover(cfg.max_req_count, cfg.max_bytes_count))
, _maximum_capacity(cfg.max_req_count, cfg.max_bytes_count)
{
assert(!_capacity_tail.load(std::memory_order_relaxed)
.maybe_ahead_of(_capacity_head.load(std::memory_order_relaxed)));
seastar_logger.debug("Created fair group, capacity {}:{}", cfg.max_req_count, cfg.max_bytes_count);
}
fair_group_rover fair_group::grab_capacity(fair_queue_ticket cap) noexcept {
fair_group_rover cur = _capacity_tail.load(std::memory_order_relaxed);
while (!_capacity_tail.compare_exchange_weak(cur, cur + cap)) ;
return cur;
}
void fair_group::release_capacity(fair_queue_ticket cap) noexcept {
fair_group_rover cur = _capacity_head.load(std::memory_order_relaxed);
while (!_capacity_head.compare_exchange_weak(cur, cur + cap)) ;
}
fair_queue::fair_queue(fair_group& group, config cfg)
: _config(std::move(cfg))
, _group(group)
, _base(std::chrono::steady_clock::now())
{
seastar_logger.debug("Created fair queue, ticket pace {}:{}", cfg.ticket_weight_pace, cfg.ticket_size_pace);
}
void fair_queue::push_priority_class(priority_class_ptr pc) {
if (!pc->_queued) {
_handles.push(pc);
pc->_queued = true;
}
}
priority_class_ptr fair_queue::peek_priority_class() {
assert(!_handles.empty());
return _handles.top();
}
void fair_queue::pop_priority_class(priority_class_ptr pc) {
assert(pc->_queued);
pc->_queued = false;
_handles.pop();
}
float fair_queue::normalize_factor() const {
return std::numeric_limits<float>::min();
}
void fair_queue::normalize_stats() {
auto time_delta = std::log(normalize_factor()) * _config.tau;
// time_delta is negative; and this may advance _base into the future
_base -= std::chrono::duration_cast<clock_type::duration>(time_delta);
for (auto& pc: _all_classes) {
pc->_accumulated *= normalize_factor();
}
}
std::chrono::microseconds fair_queue_ticket::duration_at_pace(float weight_pace, float size_pace) const noexcept {
unsigned long dur = ((_weight * weight_pace) + (_size * size_pace));
return std::chrono::microseconds(dur);
}
bool fair_queue::grab_pending_capacity(fair_queue_ticket cap) noexcept {
fair_group_rover pending_head = _pending->orig_tail + cap;
if (pending_head.maybe_ahead_of(_group.head())) {
return false;
}
if (cap == _pending->cap) {
_pending.reset();
} else {
/*
* This branch is called when the fair queue decides to
* submit not the same request that entered it into the
* pending state and this new request crawls through the
* expected head value.
*/
_pending->orig_tail = _group.grab_capacity(cap);
}
return true;
}
bool fair_queue::grab_capacity(fair_queue_ticket cap) noexcept {
if (_pending) {
return grab_pending_capacity(cap);
}
fair_group_rover orig_tail = _group.grab_capacity(cap);
if ((orig_tail + cap).maybe_ahead_of(_group.head())) {
_pending.emplace(orig_tail, cap);
return false;
}
return true;
}
priority_class_ptr fair_queue::register_priority_class(uint32_t shares) {
priority_class_ptr pclass = make_lw_shared<priority_class>(shares);
_all_classes.insert(pclass);
return pclass;
}
void fair_queue::unregister_priority_class(priority_class_ptr pclass) {
assert(pclass->_queue.empty());
_all_classes.erase(pclass);
}
size_t fair_queue::waiters() const {
return _requests_queued;
}
size_t fair_queue::requests_currently_executing() const {
return _requests_executing;
}
fair_queue_ticket fair_queue::resources_currently_waiting() const {
return _resources_queued;
}
fair_queue_ticket fair_queue::resources_currently_executing() const {
return _resources_executing;
}
void fair_queue::queue(priority_class_ptr pc, fair_queue_entry& ent) {
// We need to return a future in this function on which the caller can wait.
// Since we don't know which queue we will use to execute the next request - if ours or
// someone else's, we need a separate promise at this point.
push_priority_class(pc);
pc->_queue.push_back(ent);
_resources_queued += ent._ticket;
_requests_queued++;
}
void fair_queue::notify_requests_finished(fair_queue_ticket desc, unsigned nr) noexcept {
_resources_executing -= desc;
_requests_executing -= nr;
_group.release_capacity(desc);
}
void fair_queue::dispatch_requests(std::function<void(fair_queue_entry&)> cb) {
while (_requests_queued) {
priority_class_ptr h;
while (true) {
h = peek_priority_class();
if (!h->_queue.empty()) {
break;
}
pop_priority_class(h);
}
auto& req = h->_queue.front();
if (!grab_capacity(req._ticket)) {
break;
}
pop_priority_class(h);
h->_queue.pop_front();
_resources_executing += req._ticket;
_resources_queued -= req._ticket;
_requests_executing++;
_requests_queued--;
auto delta = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - _base);
auto req_cost = req._ticket.normalize(_group.maximum_capacity()) / h->_shares;
auto cost = expf(1.0f/_config.tau.count() * delta.count()) * req_cost;
float next_accumulated = h->_accumulated + cost;
while (std::isinf(next_accumulated)) {
normalize_stats();
// If we have renormalized, our time base will have changed. This should happen very infrequently
delta = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - _base);
cost = expf(1.0f/_config.tau.count() * delta.count()) * req_cost;
next_accumulated = h->_accumulated + cost;
}
h->_accumulated = next_accumulated;
if (!h->_queue.empty()) {
push_priority_class(h);
}
cb(req);
}
}
}
<|endoftext|> |
<commit_before>#include <babylon/states/depth_culling_state.h>
#include <babylon/babylon_stl_util.h>
#include <babylon/interfaces/igl_rendering_context.h>
namespace BABYLON {
DepthCullingState::DepthCullingState()
: isDirty{this, &DepthCullingState::get_isDirty}
, zOffset{this, &DepthCullingState::get_zOffset, &DepthCullingState::set_zOffset}
, cullFace{this, &DepthCullingState::get_cullFace, &DepthCullingState::set_cullFace}
, cull{this, &DepthCullingState::get_cull, &DepthCullingState::set_cull}
, depthFunc{this, &DepthCullingState::get_depthFunc, &DepthCullingState::set_depthFunc}
, depthMask{this, &DepthCullingState::get_depthMask, &DepthCullingState::set_depthMask}
, depthTest{this, &DepthCullingState::get_depthTest, &DepthCullingState::set_depthTest}
, frontFace{this, &DepthCullingState::get_frontFace, &DepthCullingState::set_frontFace}
, _isDepthTestDirty{false}
, _isDepthMaskDirty{false}
, _isDepthFuncDirty{false}
, _isCullFaceDirty{false}
, _isCullDirty{false}
, _isZOffsetDirty{false}
, _isFrontFaceDirty{false}
, _depthFunc{std::nullopt}
, _cull{std::nullopt}
, _cullFace{std::nullopt}
, _zOffset{0.f}
, _frontFace{std::nullopt}
{
reset();
}
DepthCullingState::~DepthCullingState() = default;
bool DepthCullingState::get_isDirty() const
{
return _isDepthFuncDirty || _isDepthTestDirty || _isDepthMaskDirty || _isCullFaceDirty
|| _isCullDirty || _isZOffsetDirty || _isFrontFaceDirty;
}
float DepthCullingState::get_zOffset() const
{
return _zOffset;
}
void DepthCullingState::set_zOffset(float value)
{
if (stl_util::almost_equal(_zOffset, value)) {
return;
}
_zOffset = value;
_isZOffsetDirty = true;
}
std::optional<int>& DepthCullingState::get_cullFace()
{
return _cullFace;
}
void DepthCullingState::set_cullFace(const std::optional<int>& value)
{
if (_cullFace == value) {
return;
}
_cullFace = value;
_isCullFaceDirty = true;
}
std::optional<bool>& DepthCullingState::get_cull()
{
return _cull;
}
void DepthCullingState::set_cull(const std::optional<bool>& value)
{
if (_cull == value) {
return;
}
_cull = value;
_isCullDirty = true;
}
std::optional<int>& DepthCullingState::get_depthFunc()
{
return _depthFunc;
}
void DepthCullingState::set_depthFunc(const std::optional<int>& value)
{
if (_depthFunc == value) {
return;
}
_depthFunc = value;
_isDepthFuncDirty = true;
}
bool DepthCullingState::get_depthMask() const
{
return _depthMask;
}
void DepthCullingState::set_depthMask(bool value)
{
if (_depthMask == value) {
return;
}
_depthMask = value;
_isDepthMaskDirty = true;
}
bool DepthCullingState::get_depthTest() const
{
return _depthTest;
}
void DepthCullingState::set_depthTest(bool value)
{
if (_depthTest == value) {
return;
}
_depthTest = value;
_isDepthTestDirty = true;
}
std::optional<unsigned int>& DepthCullingState::get_frontFace()
{
return _frontFace;
}
void DepthCullingState::set_frontFace(const std::optional<unsigned int>& value)
{
if (_frontFace == value) {
return;
}
_frontFace = value;
_isFrontFaceDirty = true;
}
void DepthCullingState::reset()
{
_depthMask = true;
_depthTest = true;
_depthFunc = std::nullopt;
_cullFace = std::nullopt;
_cull = std::nullopt;
_zOffset = 0.f;
_frontFace = std::nullopt;
_isDepthTestDirty = true;
_isDepthMaskDirty = true;
_isDepthFuncDirty = false;
_isCullFaceDirty = false;
_isCullDirty = false;
_isZOffsetDirty = false;
_isFrontFaceDirty = false;
}
void DepthCullingState::apply(GL::IGLRenderingContext& gl)
{
if (!isDirty()) {
return;
}
// Cull
if (_isCullDirty) {
const auto& iCullFace = cull();
if (iCullFace && *iCullFace) {
gl.enable(GL::CULL_FACE);
}
else {
gl.disable(GL::CULL_FACE);
}
_isCullDirty = false;
}
// Cull face
if (_isCullFaceDirty) {
gl.cullFace(static_cast<unsigned int>(*cullFace()));
_isCullFaceDirty = false;
}
// Depth mask
if (_isDepthMaskDirty) {
gl.depthMask(depthMask());
_isDepthMaskDirty = false;
}
// Depth test
if (_isDepthTestDirty) {
if (depthTest()) {
gl.enable(GL::DEPTH_TEST);
}
else {
gl.disable(GL::DEPTH_TEST);
}
_isDepthTestDirty = false;
}
// Depth func
if (_isDepthFuncDirty) {
gl.depthFunc(static_cast<unsigned int>(*depthFunc()));
_isDepthFuncDirty = false;
}
// zOffset
if (_isZOffsetDirty) {
if (!stl_util::almost_equal(zOffset(), 0.f)) {
gl.enable(GL::POLYGON_OFFSET_FILL);
gl.polygonOffset(zOffset(), 0);
}
else {
gl.disable(GL::POLYGON_OFFSET_FILL);
}
_isZOffsetDirty = false;
}
// Front face
if (_isFrontFaceDirty) {
gl.frontFace(*frontFace());
_isFrontFaceDirty = false;
}
}
} // end of namespace BABYLON
<commit_msg>Added explicit checks for optional values<commit_after>#include <babylon/states/depth_culling_state.h>
#include <babylon/babylon_stl_util.h>
#include <babylon/interfaces/igl_rendering_context.h>
namespace BABYLON {
DepthCullingState::DepthCullingState()
: isDirty{this, &DepthCullingState::get_isDirty}
, zOffset{this, &DepthCullingState::get_zOffset, &DepthCullingState::set_zOffset}
, cullFace{this, &DepthCullingState::get_cullFace, &DepthCullingState::set_cullFace}
, cull{this, &DepthCullingState::get_cull, &DepthCullingState::set_cull}
, depthFunc{this, &DepthCullingState::get_depthFunc, &DepthCullingState::set_depthFunc}
, depthMask{this, &DepthCullingState::get_depthMask, &DepthCullingState::set_depthMask}
, depthTest{this, &DepthCullingState::get_depthTest, &DepthCullingState::set_depthTest}
, frontFace{this, &DepthCullingState::get_frontFace, &DepthCullingState::set_frontFace}
, _isDepthTestDirty{false}
, _isDepthMaskDirty{false}
, _isDepthFuncDirty{false}
, _isCullFaceDirty{false}
, _isCullDirty{false}
, _isZOffsetDirty{false}
, _isFrontFaceDirty{false}
, _depthFunc{std::nullopt}
, _cull{std::nullopt}
, _cullFace{std::nullopt}
, _zOffset{0.f}
, _frontFace{std::nullopt}
{
reset();
}
DepthCullingState::~DepthCullingState() = default;
bool DepthCullingState::get_isDirty() const
{
return _isDepthFuncDirty || _isDepthTestDirty || _isDepthMaskDirty || _isCullFaceDirty
|| _isCullDirty || _isZOffsetDirty || _isFrontFaceDirty;
}
float DepthCullingState::get_zOffset() const
{
return _zOffset;
}
void DepthCullingState::set_zOffset(float value)
{
if (stl_util::almost_equal(_zOffset, value)) {
return;
}
_zOffset = value;
_isZOffsetDirty = true;
}
std::optional<int>& DepthCullingState::get_cullFace()
{
return _cullFace;
}
void DepthCullingState::set_cullFace(const std::optional<int>& value)
{
if (_cullFace == value) {
return;
}
if (_cullFace.has_value() && value.has_value() && *_cullFace == *value) {
return;
}
_cullFace = value;
_isCullFaceDirty = true;
}
std::optional<bool>& DepthCullingState::get_cull()
{
return _cull;
}
void DepthCullingState::set_cull(const std::optional<bool>& value)
{
if (_cull == value) {
return;
}
if (_cull.has_value() && value.has_value() && *_cull == *value) {
return;
}
_cull = value;
_isCullDirty = true;
}
std::optional<int>& DepthCullingState::get_depthFunc()
{
return _depthFunc;
}
void DepthCullingState::set_depthFunc(const std::optional<int>& value)
{
if (_depthFunc == value) {
return;
}
if (_depthFunc.has_value() && value.has_value() && *_depthFunc == *value) {
return;
}
_depthFunc = value;
_isDepthFuncDirty = true;
}
bool DepthCullingState::get_depthMask() const
{
return _depthMask;
}
void DepthCullingState::set_depthMask(bool value)
{
if (_depthMask == value) {
return;
}
_depthMask = value;
_isDepthMaskDirty = true;
}
bool DepthCullingState::get_depthTest() const
{
return _depthTest;
}
void DepthCullingState::set_depthTest(bool value)
{
if (_depthTest == value) {
return;
}
_depthTest = value;
_isDepthTestDirty = true;
}
std::optional<unsigned int>& DepthCullingState::get_frontFace()
{
return _frontFace;
}
void DepthCullingState::set_frontFace(const std::optional<unsigned int>& value)
{
if (_frontFace == value) {
return;
}
if (_frontFace.has_value() && value.has_value() && *_frontFace == *value) {
return;
}
_frontFace = value;
_isFrontFaceDirty = true;
}
void DepthCullingState::reset()
{
_depthMask = true;
_depthTest = true;
_depthFunc = std::nullopt;
_cullFace = std::nullopt;
_cull = std::nullopt;
_zOffset = 0.f;
_frontFace = std::nullopt;
_isDepthTestDirty = true;
_isDepthMaskDirty = true;
_isDepthFuncDirty = false;
_isCullFaceDirty = false;
_isCullDirty = false;
_isZOffsetDirty = false;
_isFrontFaceDirty = false;
}
void DepthCullingState::apply(GL::IGLRenderingContext& gl)
{
if (!isDirty()) {
return;
}
// Cull
if (_isCullDirty) {
const auto& iCullFace = cull();
if (iCullFace && *iCullFace) {
gl.enable(GL::CULL_FACE);
}
else {
gl.disable(GL::CULL_FACE);
}
_isCullDirty = false;
}
// Cull face
if (_isCullFaceDirty) {
gl.cullFace(static_cast<unsigned int>(*cullFace()));
_isCullFaceDirty = false;
}
// Depth mask
if (_isDepthMaskDirty) {
gl.depthMask(depthMask());
_isDepthMaskDirty = false;
}
// Depth test
if (_isDepthTestDirty) {
if (depthTest()) {
gl.enable(GL::DEPTH_TEST);
}
else {
gl.disable(GL::DEPTH_TEST);
}
_isDepthTestDirty = false;
}
// Depth func
if (_isDepthFuncDirty) {
gl.depthFunc(static_cast<unsigned int>(*depthFunc()));
_isDepthFuncDirty = false;
}
// zOffset
if (_isZOffsetDirty) {
if (!stl_util::almost_equal(zOffset(), 0.f)) {
gl.enable(GL::POLYGON_OFFSET_FILL);
gl.polygonOffset(zOffset(), 0);
}
else {
gl.disable(GL::POLYGON_OFFSET_FILL);
}
_isZOffsetDirty = false;
}
// Front face
if (_isFrontFaceDirty) {
gl.frontFace(*frontFace());
_isFrontFaceDirty = false;
}
}
} // end of namespace BABYLON
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/public/common/renderer_preferences.h"
namespace content {
RendererPreferences::RendererPreferences()
: can_accept_load_drops(true),
should_antialias_text(true),
hinting(RENDERER_PREFERENCES_HINTING_SYSTEM_DEFAULT),
subpixel_rendering(
RENDERER_PREFERENCES_SUBPIXEL_RENDERING_SYSTEM_DEFAULT),
use_subpixel_positioning(false),
focus_ring_color(0),
thumb_active_color(0),
thumb_inactive_color(0),
track_color(0),
active_selection_bg_color(0),
active_selection_fg_color(0),
inactive_selection_bg_color(0),
inactive_selection_fg_color(0),
browser_handles_non_local_top_level_requests(false),
browser_handles_all_top_level_requests(false),
caret_blink_interval(0),
enable_referrers(true),
default_zoom_level(0) {
}
} // namespace content
<commit_msg>Coverity: Fix uninit member variables.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/public/common/renderer_preferences.h"
namespace content {
RendererPreferences::RendererPreferences()
: can_accept_load_drops(true),
should_antialias_text(true),
hinting(RENDERER_PREFERENCES_HINTING_SYSTEM_DEFAULT),
use_autohinter(false),
use_bitmaps(false),
subpixel_rendering(
RENDERER_PREFERENCES_SUBPIXEL_RENDERING_SYSTEM_DEFAULT),
use_subpixel_positioning(false),
focus_ring_color(0),
thumb_active_color(0),
thumb_inactive_color(0),
track_color(0),
active_selection_bg_color(0),
active_selection_fg_color(0),
inactive_selection_bg_color(0),
inactive_selection_fg_color(0),
browser_handles_non_local_top_level_requests(false),
browser_handles_all_top_level_requests(false),
caret_blink_interval(0),
enable_referrers(true),
default_zoom_level(0) {
}
} // namespace content
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) 2011 Werner Mayer <wmayer@users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#define INITGUID
#include "Common.h"
HINSTANCE g_hinstDll = NULL;
LONG g_cRef = 0;
typedef struct _REGKEY_DELETEKEY
{
HKEY hKey;
LPCWSTR lpszSubKey;
} REGKEY_DELETEKEY;
typedef struct _REGKEY_SUBKEY_AND_VALUE
{
HKEY hKey;
LPCWSTR lpszSubKey;
LPCWSTR lpszValue;
DWORD dwType;
DWORD_PTR dwData;
;
} REGKEY_SUBKEY_AND_VALUE;
STDAPI CreateRegistryKeys(REGKEY_SUBKEY_AND_VALUE* aKeys, ULONG cKeys);
STDAPI DeleteRegistryKeys(REGKEY_DELETEKEY* aKeys, ULONG cKeys);
BOOL APIENTRY DllMain(HINSTANCE hinstDll,
DWORD dwReason,
LPVOID pvReserved)
{
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
g_hinstDll = hinstDll;
break;
}
return TRUE;
}
STDAPI_(HINSTANCE) DllInstance()
{
return g_hinstDll;
}
STDAPI DllCanUnloadNow()
{
return g_cRef ? S_FALSE : S_OK;
}
STDAPI_(ULONG) DllAddRef()
{
LONG cRef = InterlockedIncrement(&g_cRef);
return cRef;
}
STDAPI_(ULONG) DllRelease()
{
LONG cRef = InterlockedDecrement(&g_cRef);
if (0 > cRef)
cRef = 0;
return cRef;
}
STDAPI DllRegisterServer()
{
// This tells the shell to invalidate the thumbnail cache. This is important because any .recipe files
// viewed before registering this handler would otherwise show cached blank thumbnails.
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
WCHAR szModule[MAX_PATH];
ZeroMemory(szModule, sizeof(szModule));
GetModuleFileName(g_hinstDll, szModule, ARRAYSIZE(szModule));
//uncomment the following
REGKEY_SUBKEY_AND_VALUE keys[] = {
{HKEY_CLASSES_ROOT, L"CLSID\\" szCLSID_SampleThumbnailProvider, NULL, REG_SZ, (DWORD_PTR)L"FCStd Thumbnail Provider"},
#if 1
//{HKEY_CLASSES_ROOT, L"CLSID\\DisableProcessIsolation", NULL, REG_DWORD, (DWORD) 1},
{HKEY_CLASSES_ROOT, L"CLSID\\" szCLSID_SampleThumbnailProvider, L"DisableProcessIsolation", REG_DWORD, (DWORD) 1},
#endif
{HKEY_CLASSES_ROOT, L"CLSID\\" szCLSID_SampleThumbnailProvider L"\\InprocServer32", NULL, REG_SZ, (DWORD_PTR)szModule},
{HKEY_CLASSES_ROOT, L"CLSID\\" szCLSID_SampleThumbnailProvider L"\\InprocServer32", L"ThreadingModel", REG_SZ, (DWORD_PTR)L"Apartment"},
//{HKEY_CLASSES_ROOT, L".FCStd\\shellex", L"Trick only here to create shellex when not existing",REG_DWORD, 1},
{HKEY_CLASSES_ROOT, L".FCStd\\shellex\\{E357FCCD-A995-4576-B01F-234630154E96}", NULL, REG_SZ, (DWORD_PTR)szCLSID_SampleThumbnailProvider}
};
return CreateRegistryKeys(keys, ARRAYSIZE(keys));
}
STDAPI DllUnregisterServer()
{
REGKEY_DELETEKEY keys[] = {{HKEY_CLASSES_ROOT, L"CLSID\\" szCLSID_SampleThumbnailProvider}};
return DeleteRegistryKeys(keys, ARRAYSIZE(keys));
}
STDAPI CreateRegistryKey(REGKEY_SUBKEY_AND_VALUE* pKey)
{
size_t cbData;
LPVOID pvData = NULL;
HRESULT hr = S_OK;
switch(pKey->dwType)
{
case REG_DWORD:
pvData = (LPVOID)(LPDWORD)&pKey->dwData;
cbData = sizeof(DWORD);
break;
case REG_SZ:
case REG_EXPAND_SZ:
hr = StringCbLength((LPCWSTR)pKey->dwData, STRSAFE_MAX_CCH, &cbData);
if (SUCCEEDED(hr))
{
pvData = (LPVOID)(LPCWSTR)pKey->dwData;
cbData += sizeof(WCHAR);
}
break;
default:
hr = E_INVALIDARG;
}
if (SUCCEEDED(hr))
{
LSTATUS status = SHSetValue(pKey->hKey, pKey->lpszSubKey, pKey->lpszValue, pKey->dwType, pvData, (DWORD)cbData);
if (NOERROR != status)
{
hr = HRESULT_FROM_WIN32(status);
}
}
return hr;
}
STDAPI CreateRegistryKeys(REGKEY_SUBKEY_AND_VALUE* aKeys, ULONG cKeys)
{
HRESULT hr = S_OK;
for (ULONG iKey = 0; iKey < cKeys; iKey++)
{
HRESULT hrTemp = CreateRegistryKey(&aKeys[iKey]);
if (FAILED(hrTemp))
{
hr = hrTemp;
}
}
return hr;
}
STDAPI DeleteRegistryKeys(REGKEY_DELETEKEY* aKeys, ULONG cKeys)
{
HRESULT hr = S_OK;
LSTATUS status;
for (ULONG iKey = 0; iKey < cKeys; iKey++)
{
status = RegDeleteTree(aKeys[iKey].hKey, aKeys[iKey].lpszSubKey);
if (NOERROR != status)
{
hr = HRESULT_FROM_WIN32(status);
}
}
return hr;
}<commit_msg>[Tools] extend ThumbNail Provider for .FCBak<commit_after>/***************************************************************************
* Copyright (c) 2011 Werner Mayer <wmayer@users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#define INITGUID
#include "Common.h"
HINSTANCE g_hinstDll = NULL;
LONG g_cRef = 0;
typedef struct _REGKEY_DELETEKEY
{
HKEY hKey;
LPCWSTR lpszSubKey;
} REGKEY_DELETEKEY;
typedef struct _REGKEY_SUBKEY_AND_VALUE
{
HKEY hKey;
LPCWSTR lpszSubKey;
LPCWSTR lpszValue;
DWORD dwType;
DWORD_PTR dwData;
;
} REGKEY_SUBKEY_AND_VALUE;
STDAPI CreateRegistryKeys(REGKEY_SUBKEY_AND_VALUE* aKeys, ULONG cKeys);
STDAPI DeleteRegistryKeys(REGKEY_DELETEKEY* aKeys, ULONG cKeys);
BOOL APIENTRY DllMain(HINSTANCE hinstDll,
DWORD dwReason,
LPVOID pvReserved)
{
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
g_hinstDll = hinstDll;
break;
}
return TRUE;
}
STDAPI_(HINSTANCE) DllInstance()
{
return g_hinstDll;
}
STDAPI DllCanUnloadNow()
{
return g_cRef ? S_FALSE : S_OK;
}
STDAPI_(ULONG) DllAddRef()
{
LONG cRef = InterlockedIncrement(&g_cRef);
return cRef;
}
STDAPI_(ULONG) DllRelease()
{
LONG cRef = InterlockedDecrement(&g_cRef);
if (0 > cRef)
cRef = 0;
return cRef;
}
STDAPI DllRegisterServer()
{
// This tells the shell to invalidate the thumbnail cache. This is important because any .recipe files
// viewed before registering this handler would otherwise show cached blank thumbnails.
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
WCHAR szModule[MAX_PATH];
ZeroMemory(szModule, sizeof(szModule));
GetModuleFileName(g_hinstDll, szModule, ARRAYSIZE(szModule));
//uncomment the following
REGKEY_SUBKEY_AND_VALUE keys[] = {
{HKEY_CLASSES_ROOT, L"CLSID\\" szCLSID_SampleThumbnailProvider, NULL, REG_SZ, (DWORD_PTR)L"FCStd Thumbnail Provider"},
#if 1
//{HKEY_CLASSES_ROOT, L"CLSID\\DisableProcessIsolation", NULL, REG_DWORD, (DWORD) 1},
{HKEY_CLASSES_ROOT, L"CLSID\\" szCLSID_SampleThumbnailProvider, L"DisableProcessIsolation", REG_DWORD, (DWORD) 1},
#endif
{HKEY_CLASSES_ROOT, L"CLSID\\" szCLSID_SampleThumbnailProvider L"\\InprocServer32", NULL, REG_SZ, (DWORD_PTR)szModule},
{HKEY_CLASSES_ROOT, L"CLSID\\" szCLSID_SampleThumbnailProvider L"\\InprocServer32", L"ThreadingModel", REG_SZ, (DWORD_PTR)L"Apartment"},
//{HKEY_CLASSES_ROOT, L".FCStd\\shellex", L"Trick only here to create shellex when not existing",REG_DWORD, 1},
{HKEY_CLASSES_ROOT, L".FCStd\\shellex\\{E357FCCD-A995-4576-B01F-234630154E96}", NULL, REG_SZ, (DWORD_PTR)szCLSID_SampleThumbnailProvider},
{HKEY_CLASSES_ROOT, L".FCBak\\shellex\\{E357FCCD-A995-4576-B01F-234630154E96}", NULL, REG_SZ, (DWORD_PTR)szCLSID_SampleThumbnailProvider}
};
return CreateRegistryKeys(keys, ARRAYSIZE(keys));
}
STDAPI DllUnregisterServer()
{
REGKEY_DELETEKEY keys[] = {{HKEY_CLASSES_ROOT, L"CLSID\\" szCLSID_SampleThumbnailProvider}};
return DeleteRegistryKeys(keys, ARRAYSIZE(keys));
}
STDAPI CreateRegistryKey(REGKEY_SUBKEY_AND_VALUE* pKey)
{
size_t cbData;
LPVOID pvData = NULL;
HRESULT hr = S_OK;
switch(pKey->dwType)
{
case REG_DWORD:
pvData = (LPVOID)(LPDWORD)&pKey->dwData;
cbData = sizeof(DWORD);
break;
case REG_SZ:
case REG_EXPAND_SZ:
hr = StringCbLength((LPCWSTR)pKey->dwData, STRSAFE_MAX_CCH, &cbData);
if (SUCCEEDED(hr))
{
pvData = (LPVOID)(LPCWSTR)pKey->dwData;
cbData += sizeof(WCHAR);
}
break;
default:
hr = E_INVALIDARG;
}
if (SUCCEEDED(hr))
{
LSTATUS status = SHSetValue(pKey->hKey, pKey->lpszSubKey, pKey->lpszValue, pKey->dwType, pvData, (DWORD)cbData);
if (NOERROR != status)
{
hr = HRESULT_FROM_WIN32(status);
}
}
return hr;
}
STDAPI CreateRegistryKeys(REGKEY_SUBKEY_AND_VALUE* aKeys, ULONG cKeys)
{
HRESULT hr = S_OK;
for (ULONG iKey = 0; iKey < cKeys; iKey++)
{
HRESULT hrTemp = CreateRegistryKey(&aKeys[iKey]);
if (FAILED(hrTemp))
{
hr = hrTemp;
}
}
return hr;
}
STDAPI DeleteRegistryKeys(REGKEY_DELETEKEY* aKeys, ULONG cKeys)
{
HRESULT hr = S_OK;
LSTATUS status;
for (ULONG iKey = 0; iKey < cKeys; iKey++)
{
status = RegDeleteTree(aKeys[iKey].hKey, aKeys[iKey].lpszSubKey);
if (NOERROR != status)
{
hr = HRESULT_FROM_WIN32(status);
}
}
return hr;
}<|endoftext|> |
<commit_before><commit_msg>Sketcher: Fix lock constraint reference mode<commit_after><|endoftext|> |
<commit_before>#include "reFuncDefs.hpp"
#include "microservice.hpp"
#include "objInfo.hpp"
#include <glob.h>
#include <boost/unordered_map.hpp>
#include <boost/filesystem.hpp>
#include <boost/system/error_code.hpp>
namespace bfs = boost::filesystem;
namespace bs = boost::system;
namespace err = boost::system::errc;
typedef boost::unordered_map<std::string, uintmax_t> size_map_t;
bool is_it_done(
const bfs::path& filepath,
size_map_t& sizes ) {
bs::error_code ec;
if ( bfs::is_regular_file( filepath, ec ) &&
ec == err::success &&
( sizes.count( filepath.generic_string() ) == 0 ||
sizes[filepath.generic_string()] != bfs::file_size( filepath ) ) ) {
return false;
}
else if ( bfs::is_directory( filepath, ec ) && ec == err::success ) {
for ( bfs::directory_iterator iter( filepath ), end_iter; iter != end_iter; iter++ ) {
if ( !is_it_done( iter->path(), sizes ) ) {
return false;
}
}
}
return true;
}
void add_file_sizes(
const bfs::path& filepath,
size_map_t& sizes ) {
bs::error_code ec;
if ( bfs::is_regular_file( filepath, ec ) &&
ec == err::success ) {
sizes[filepath.generic_string()] = bfs::file_size( filepath );
}
else if ( bfs::is_directory( filepath, ec ) && ec == err::success ) {
for ( bfs::directory_iterator iter( filepath ), end_iter; iter != end_iter; iter++ ) {
add_file_sizes( iter->path(), sizes );
}
}
}
MICROSERVICE_BEGIN(
msiget_filepaths_from_glob,
STR, glob_string, INPUT,
INT, seconds_delay, INPUT,
INT, second_proc_wait, INPUT,
KeyValPair, filepaths, OUTPUT ALLOC )
RE_TEST_MACRO( " Calling msiget_filepaths_from_glob" );
glob_t glob_struct;
glob( glob_string, GLOB_MARK | GLOB_TILDE_CHECK, NULL, &glob_struct );
memset( &filepaths, 0, sizeof( filepaths ) );
size_map_t sizes;
for ( size_t i = 0; i < glob_struct.gl_pathc; i++ ) {
bfs::path filepath( glob_struct.gl_pathv[i] );
add_file_sizes( filepath, sizes );
}
if ( sizes.empty() ) {
RETURN( 0 );
}
sleep( seconds_delay );
for ( size_t i = 0; i < glob_struct.gl_pathc; i++ ) {
rodsLog(
LOG_DEBUG,
"msiget_filepaths_from_glob - processing [%s]",
glob_struct.gl_pathv[i] );
bfs::path filepath( glob_struct.gl_pathv[i] );
if ( is_it_done( filepath, sizes ) ) {
bs::error_code ec;
if ( bfs::is_regular_file( filepath, ec ) && ec == err::success ) {
time_t file_time = bfs::last_write_time( filepath );
time_t curr_time = time(0);
time_t off_time = file_time + second_proc_wait;
time_t diff_time = off_time - curr_time;
if( curr_time > off_time ) {
addKeyVal( &filepaths, glob_struct.gl_pathv[i], "-d" );
} else {
rodsLog(
LOG_DEBUG,
"msiget_filepaths_from_glob - filepath [%s] is too young by [%d] seconds",
glob_struct.gl_pathv[i],
off_time - curr_time );
}
}
else if ( bfs::is_directory( filepath, ec ) && ec == err::success ) {
addKeyVal( &filepaths, glob_struct.gl_pathv[i], "-C" );
}
}
}
globfree( &glob_struct );
RETURN( 0 );
// cppcheck-suppress syntaxError
MICROSERVICE_END
<commit_msg>header files had moved<commit_after>#include "reFuncDefs.hpp"
#include "microservice.hpp"
#include "objInfo.hpp"
#include "rcMisc.h"
#include <glob.h>
#include <boost/unordered_map.hpp>
#include <boost/filesystem.hpp>
#include <boost/system/error_code.hpp>
namespace bfs = boost::filesystem;
namespace bs = boost::system;
namespace err = boost::system::errc;
typedef boost::unordered_map<std::string, uintmax_t> size_map_t;
bool is_it_done(
const bfs::path& filepath,
size_map_t& sizes ) {
bs::error_code ec;
if ( bfs::is_regular_file( filepath, ec ) &&
ec == err::success &&
( sizes.count( filepath.generic_string() ) == 0 ||
sizes[filepath.generic_string()] != bfs::file_size( filepath ) ) ) {
return false;
}
else if ( bfs::is_directory( filepath, ec ) && ec == err::success ) {
for ( bfs::directory_iterator iter( filepath ), end_iter; iter != end_iter; iter++ ) {
if ( !is_it_done( iter->path(), sizes ) ) {
return false;
}
}
}
return true;
}
void add_file_sizes(
const bfs::path& filepath,
size_map_t& sizes ) {
bs::error_code ec;
if ( bfs::is_regular_file( filepath, ec ) &&
ec == err::success ) {
sizes[filepath.generic_string()] = bfs::file_size( filepath );
}
else if ( bfs::is_directory( filepath, ec ) && ec == err::success ) {
for ( bfs::directory_iterator iter( filepath ), end_iter; iter != end_iter; iter++ ) {
add_file_sizes( iter->path(), sizes );
}
}
}
MICROSERVICE_BEGIN(
msiget_filepaths_from_glob,
STR, glob_string, INPUT,
INT, seconds_delay, INPUT,
INT, second_proc_wait, INPUT,
KeyValPair, filepaths, OUTPUT ALLOC )
RE_TEST_MACRO( " Calling msiget_filepaths_from_glob" );
glob_t glob_struct;
glob( glob_string, GLOB_MARK | GLOB_TILDE_CHECK, NULL, &glob_struct );
memset( &filepaths, 0, sizeof( filepaths ) );
size_map_t sizes;
for ( size_t i = 0; i < glob_struct.gl_pathc; i++ ) {
bfs::path filepath( glob_struct.gl_pathv[i] );
add_file_sizes( filepath, sizes );
}
if ( sizes.empty() ) {
RETURN( 0 );
}
sleep( seconds_delay );
for ( size_t i = 0; i < glob_struct.gl_pathc; i++ ) {
rodsLog(
LOG_DEBUG,
"msiget_filepaths_from_glob - processing [%s]",
glob_struct.gl_pathv[i] );
bfs::path filepath( glob_struct.gl_pathv[i] );
if ( is_it_done( filepath, sizes ) ) {
bs::error_code ec;
if ( bfs::is_regular_file( filepath, ec ) && ec == err::success ) {
time_t file_time = bfs::last_write_time( filepath );
time_t curr_time = time(0);
time_t off_time = file_time + second_proc_wait;
time_t diff_time = off_time - curr_time;
if( curr_time > off_time ) {
addKeyVal( &filepaths, glob_struct.gl_pathv[i], "-d" );
} else {
rodsLog(
LOG_DEBUG,
"msiget_filepaths_from_glob - filepath [%s] is too young by [%d] seconds",
glob_struct.gl_pathv[i],
off_time - curr_time );
}
}
else if ( bfs::is_directory( filepath, ec ) && ec == err::success ) {
addKeyVal( &filepaths, glob_struct.gl_pathv[i], "-C" );
}
}
}
globfree( &glob_struct );
RETURN( 0 );
// cppcheck-suppress syntaxError
MICROSERVICE_END
<|endoftext|> |
<commit_before>#include <vtkMultiBlockDataSet.h>
#include <vtkSphereSource.h>
#include <vtkNew.h>
#include <vtkCompositePolyDataMapper2.h>
#include <vtkCompositeDataDisplayAttributes.h>
#include <vtkActor.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
int main( int argc, char *argv[] )
{
vtkNew<vtkSphereSource> sphere1;
sphere1->SetRadius(3);
sphere1->SetCenter(0,0,0);
sphere1->Update();
vtkNew<vtkSphereSource> sphere2;
sphere2->SetRadius(2);
sphere2->SetCenter(2,0,0);
sphere2->Update();
vtkNew<vtkMultiBlockDataSet> mbds;
mbds->SetNumberOfBlocks(3);
mbds->SetBlock(0, sphere1->GetOutput());
// Leave block 1 NULL. NULL blocks are valid and should be handled by
// algorithms that process multiblock datasets. Especially when
// running in parallel where the blocks owned by other processes are
// NULL in this process.
mbds->SetBlock(2, sphere2->GetOutput());
vtkNew<vtkCompositePolyDataMapper2> mapper;
mapper->SetInputData((vtkPolyData*)mbds.Get());
vtkNew<vtkCompositeDataDisplayAttributes> cdsa;
// You can use the vtkCompositeDataDisplayAttributes to set the color
// opacity and visibiliy of individual blocks of the multiblock dataset.
// This sets the block at flat index 3 red
// Note that the index is the flat index in the tree, so the whole multiblock
// is index 0 and the blocks are flat indexes 1, 2 and 3. This affects
// the block returned by mbds->GetBlock(2).
double color[] = {1, 0, 0};
cdsa->SetBlockColor(3, color);
mapper->SetCompositeDataDisplayAttributes(cdsa.Get());
vtkNew<vtkActor> actor;
actor->SetMapper(mapper.Get());
vtkNew<vtkRenderer> renderer;
vtkNew<vtkRenderWindow> renderWindow;
renderWindow->AddRenderer(renderer.Get());
vtkNew<vtkRenderWindowInteractor> renderWindowInteractor;
renderWindowInteractor->SetRenderWindow(renderWindow.Get());
renderer->AddActor(actor.Get());
renderWindow->Render();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
<commit_msg>Using the new API of vtkCompositeDataDisplayAttributes.<commit_after>#include <vtkMultiBlockDataSet.h>
#include <vtkSphereSource.h>
#include <vtkNew.h>
#include <vtkCompositePolyDataMapper2.h>
#include <vtkCompositeDataDisplayAttributes.h>
#include <vtkActor.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
int main( int argc, char *argv[] )
{
vtkNew<vtkSphereSource> sphere1;
sphere1->SetRadius(3);
sphere1->SetCenter(0,0,0);
sphere1->Update();
vtkNew<vtkSphereSource> sphere2;
sphere2->SetRadius(2);
sphere2->SetCenter(2,0,0);
sphere2->Update();
vtkNew<vtkMultiBlockDataSet> mbds;
mbds->SetNumberOfBlocks(3);
mbds->SetBlock(0, sphere1->GetOutput());
// Leave block 1 NULL. NULL blocks are valid and should be handled by
// algorithms that process multiblock datasets. Especially when
// running in parallel where the blocks owned by other processes are
// NULL in this process.
mbds->SetBlock(2, sphere2->GetOutput());
vtkNew<vtkCompositePolyDataMapper2> mapper;
mapper->SetInputDataObject(mbds.GetPointer());
vtkNew<vtkCompositeDataDisplayAttributes> cdsa;
// You can use the vtkCompositeDataDisplayAttributes to set the color,
// opacity and visibiliy of individual blocks of the multiblock dataset.
// Attributes are mapped by block pointers (vtkDataObject*), so these can
// be queried by their flat index through a convenience function in the
// attribute class (vtkCompositeDataDisplayAttributes::DataObjectFromIndex).
// This sets the block at flat index 3 red
// Note that the index is the flat index in the tree, so the whole multiblock
// is index 0 and the blocks are flat indexes 1, 2 and 3. This affects
// the block returned by mbds->GetBlock(2).
double color[] = {1, 0, 0};
unsigned int top_index = 0;
auto dobj = cdsa->DataObjectFromIndex(3, mbds.GetPointer(), top_index);
cdsa->SetBlockColor(dobj, color);
mapper->SetCompositeDataDisplayAttributes(cdsa.Get());
vtkNew<vtkActor> actor;
actor->SetMapper(mapper.Get());
vtkNew<vtkRenderer> renderer;
vtkNew<vtkRenderWindow> renderWindow;
renderWindow->AddRenderer(renderer.Get());
vtkNew<vtkRenderWindowInteractor> renderWindowInteractor;
renderWindowInteractor->SetRenderWindow(renderWindow.Get());
renderer->AddActor(actor.Get());
renderWindow->Render();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>
#include "common_headers.h"
#include "circa.h"
#include "common.h"
namespace circa {
void test_simple()
{
Branch* branch = new Branch();
Term* print_term = quick_exec_function(branch,
"subroutine-create('print-term,list(string),void)");
Term* input_names = constant_list(branch, TermList(constant_string(branch, "t")));
print_term = exec_function(branch, get_global("subroutine-name-inputs"),
TermList(print_term, input_names));
branch->bindName(print_term, "print-term");
quick_eval_function(as_subroutine(print_term)->branch, "print(to-string(t))");
quick_exec_function(branch, "print-term('test)");
}
void test_using_subroutine_append()
{
Branch* branch = new Branch();
quick_exec_function(branch, "test-sub = subroutine-create('test-sub, list(int,int), int)");
quick_exec_function(branch, "print(subroutine-print(test-sub))");
quick_exec_function(branch, "test-sub = subroutine-name-inputs(test-sub,list('a,'b))");
quick_exec_function(branch, "a = subroutine-get-local(test-sub,'a)");
quick_exec_function(branch, "b = subroutine-get-local(test-sub,'b)");
quick_exec_function(branch, "append-result = subroutine-append(test-sub, mult, list(a,4))");
quick_exec_function(branch, "test-sub = get-field(append-result, 'sub)");
quick_exec_function(branch, "print(subroutine-print(test-sub))");
quick_exec_function(branch, "a-times-4 = get-field(append-result, 'term)");
quick_exec_function(branch, "append-result = subroutine-append(test-sub, mult, list(b,3))");
quick_exec_function(branch, "test-sub = get-field(append-result, 'sub)");
quick_exec_function(branch, "b-times-3 = get-field(append-result, 'term)");
quick_exec_function(branch,
"append-result = subroutine-append(test-sub, add, list(a-times-4,b-times-3))");
quick_exec_function(branch, "test-sub = get-field(append-result, 'sub)");
quick_exec_function(branch, "sum = get-field(append-result, 'term)");
quick_exec_function(branch, "test-sub = subroutine-bind(test-sub, sum, 'output)");
quick_exec_function(branch, "write-text-file('sub-append-test, export-graphviz(test-sub))");
quick_exec_function(branch, "print(subroutine-print(test-sub))");
// Finally, run it
//std::cout << quick_exec_function(branch, "test-sub(2,3)")->toString();
}
void test_using_subroutine_eval()
{
Branch* branch = new Branch();
quick_exec_function(branch, "sub = subroutine-create('test-sub, list(int,int), int)");
quick_exec_function(branch, "sub = subroutine-name-inputs(sub, list('a,'b))");
quick_exec_function(branch, "sub = subroutine-eval(sub, \"a-times-four = mult(a,4)\")");
quick_exec_function(branch, "sub = subroutine-eval(sub, \"b-times-three = mult(b,3)\")");
quick_exec_function(branch, "sub = subroutine-eval(sub, \"return add(a-times-four,b-times-three)\")");
quick_exec_function(branch, "sub = subroutine-eval(sub, \"print(to-string(b-times-three))\")");
quick_exec_function(branch, "print(to-string(sub(1,2)))");
}
void subroutine_test()
{
// test_simple();
test_using_subroutine_append();
test_using_subroutine_eval();
}
}
<commit_msg>Cleaned up tests, no more console spam. Removing subroutine-append<commit_after>
#include "common_headers.h"
#include "circa.h"
#include "common.h"
namespace circa {
void test_simple()
{
Branch* branch = new Branch();
Term* print_term = quick_exec_function(branch,
"subroutine-create('print-term,list(string),void)");
Term* input_names = constant_list(branch, TermList(constant_string(branch, "t")));
print_term = exec_function(branch, get_global("subroutine-name-inputs"),
TermList(print_term, input_names));
branch->bindName(print_term, "print-term");
quick_eval_function(as_subroutine(print_term)->branch, "print(to-string(t))");
quick_exec_function(branch, "print-term('test)");
}
void test_using_subroutine_eval()
{
Branch* branch = new Branch();
quick_exec_function(branch, "sub = subroutine-create('test-sub, list(int,int), int)");
quick_exec_function(branch, "sub = subroutine-name-inputs(sub, list('a,'b))");
quick_exec_function(branch, "sub = subroutine-eval(sub, \"a-times-four = mult(a,4)\")");
quick_exec_function(branch, "sub = subroutine-eval(sub, \"b-times-three = mult(b,3)\")");
quick_exec_function(branch, "sub = subroutine-eval(sub, \"return add(a-times-four,b-times-three)\")");
test_assert(as_int(quick_exec_function(branch, "sub(1,2))")) == 10);
}
void subroutine_test()
{
test_using_subroutine_eval();
}
}
<|endoftext|> |
<commit_before>/*
* examples/omp_smithvalence.C
* Copyright (c) Linbox
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*/
/**\file examples/omp_smithvalence.C
* @example examples/omp_smithvalence.C
\brief Valence of sparse matrix over Z or Zp.
\ingroup examples
*/
#ifndef DISABLE_COMMENTATOR
#define DISABLE_COMMENTATOR
#endif
#include <iostream>
#include <omp.h>
#include "smithvalence.h"
using namespace LinBox;
int main (int argc, char **argv)
{
// commentator().setMaxDetailLevel (-1);
// commentator().setMaxDepth (-1);
// commentator().setReportStream (std::cerr);
if (argc < 2 || argc > 4) {
std::cerr << "Usage: omp_smithvalence <matrix-file-in-supported-format> [-ata|-aat|valence] [coprime]" << std::endl;
std::cerr << " Optional parameters valence and coprime are integers." << std::endl;
std::cerr << " Prime factors of valence will be used for local computation." << std::endl;
std::cerr << " coprime will be used for overall rank computation." << std::endl;
return -1;
}
std::ifstream input (argv[1]);
if (!input) { std::cerr << "Error opening matrix file " << argv[1] << std::endl; return -1; }
Givaro::ZRing<Integer> ZZ;
MatrixStream< Givaro::ZRing<Integer> > ms( ZZ, input );
typedef SparseMatrix<Givaro::ZRing<Integer>> Blackbox;
Blackbox A (ms);
input.close();
std::cout << "A is " << A.rowdim() << " by " << A.coldim() << std::endl;
Givaro::ZRing<Integer>::Element val_A;
LinBox::Timer chrono; chrono.start();
if (argc >= 3) {
Transpose<Blackbox> T(&A);
if (strcmp(argv[2],"-ata") == 0) {
Compose< Transpose<Blackbox>, Blackbox > C (&T, &A);
std::cout << "A^T A is " << C.rowdim() << " by " << C.coldim() << std::endl;
valence(val_A, C);
}
else if (strcmp(argv[2],"-aat") == 0) {
Compose< Blackbox, Transpose<Blackbox> > C (&A, &T);
std::cout << "A A^T is " << C.rowdim() << " by " << C.coldim() << std::endl;
valence(val_A, C);
}
else {
std::cout << "Suppose primes are contained in " << argv[2] << std::endl;
val_A = LinBox::Integer(argv[2]);
}
}
else {
if (A.rowdim() != A.coldim()) {
std::cerr << "Valence works only on square matrices, try either to change the dimension in the matrix file, or to compute the valence of A A^T or A^T A, via the -aat or -ata options." << std::endl;
exit(0);
}
else
valence (val_A, A);
}
std::cout << "Valence is " << val_A << std::endl;
std::vector<Givaro::Integer> Moduli;
std::vector<size_t> exponents;
Givaro::IntFactorDom<> FTD;
typedef std::pair<Givaro::Integer,unsigned long> PairIntRk;
std::vector< PairIntRk > smith;
Givaro::Integer coprimeV=2;
if (argc >= 4) {
coprimeV =Givaro::Integer(argv[3]);
}
while ( gcd(val_A,coprimeV) > 1 ) {
FTD.nextprimein(coprimeV);
}
if (argc >= 4) {
std::cout << "Suppose " << argv[3] << " is coprime with Smith form" << std::endl;
}
std::cout << "Some factors (50000 factoring loop bound): ";
FTD.set(Moduli, exponents, val_A, 50000);
std::vector<size_t>::const_iterator eit=exponents.begin();
for(std::vector<Givaro::Integer>::const_iterator mit=Moduli.begin();
mit != Moduli.end(); ++mit,++eit)
std::cout << *mit << '^' << *eit << ' ';
std::cout << std::endl;
smith.resize(Moduli.size());
unsigned long coprimeR;
std::cout << "num procs: " << omp_get_num_procs() << std::endl;
std::cout << "max threads: " << omp_get_max_threads() << std::endl;
// #pragma omp parallel for shared(smith, Moduli)
// for(size_t j=0; j<(Moduli.size()+1); ++j) {
// if (j >= Moduli.size()) {
// LRank(coprimeR, argv[1], coprimeV);
// std::cerr << "Integer Rank (mod " << coprimeV << ") is " << coprimeR << " on thread: " << omp_get_thread_num() << std::endl;
// } else {
// unsigned long r; LRank(r, argv[1], Moduli[j]);
// std::cerr << "Rank mod " << Moduli[j] << " is " << r << " on thread: " << omp_get_thread_num() << std::endl;
// smith[j] = PairIntRk( Moduli[j], r);
// }
// }
#pragma omp parallel
{
#pragma omp single
{
for(size_t j=0; j<Moduli.size(); ++j) {
smith[j].first = Moduli[j];
#pragma omp task shared(smith,argv) firstprivate(j)
LRank(smith[j].second, argv[1], smith[j].first);
}
LRank(coprimeR, argv[1], coprimeV);
}
}
std::vector<Givaro::Integer> SmithDiagonal(coprimeR,Givaro::Integer(1));
/*
for(std::vector<Givaro::Integer>::const_iterator mit=Moduli.begin();
mit != Moduli.end(); ++mit) {
unsigned long r; LRank(r, argv[1], *mit);
std::cerr << "Rank mod " << *mit << " is " << r << std::endl;
smith.push_back(PairIntRk(*mit, r));
for(size_t i=r; i < coprimeR; ++i)
SmithDiagonal[i] *= *mit;
}
*/
#pragma omp parallel for shared(SmithDiagonal, smith, exponents)
for(size_t j=0; j<Moduli.size(); ++j) {
if (smith[j].second != coprimeR) {
std::vector<size_t> ranks;
ranks.push_back(smith[j].second);
size_t effexp;
if (exponents[j] > 1) {
if (smith[j].first == 2)
PRankPowerOfTwo(ranks, effexp, argv[1], exponents[j], coprimeR);
else
PRank(ranks, effexp, argv[1], smith[j].first, exponents[j], coprimeR);
}
else {
if (smith[j].first == 2)
PRankPowerOfTwo(ranks, effexp, argv[1], 2, coprimeR);
else
PRank(ranks, effexp, argv[1], smith[j].first, 2, coprimeR);
}
if (ranks.size() == 1) ranks.push_back(coprimeR);
if (effexp < exponents[j]) {
for(size_t expo = effexp<<1; ranks.back() < coprimeR; expo<<=1) {
if (smith[j].first == 2)
PRankIntegerPowerOfTwo(ranks, argv[1], expo, coprimeR);
else
PRankInteger(ranks, argv[1], smith[j].first, expo, coprimeR);
}
} else {
for(size_t expo = (exponents[j])<<1; ranks.back() < coprimeR; expo<<=1) {
if (smith[j].first == 2)
PRankPowerOfTwo(ranks, effexp, argv[1], expo, coprimeR);
else
PRank(ranks, effexp, argv[1], smith[j].first, expo, coprimeR);
if (ranks.size() < expo) {
std::cerr << "It seems we need a larger prime power, it will take longer ..." << std::endl;
// break;
if (smith[j].first == 2)
PRankIntegerPowerOfTwo(ranks, argv[1], expo, coprimeR);
else
PRankInteger(ranks, argv[1], smith[j].first, expo, coprimeR);
}
}
}
#pragma omp critical
{
for(size_t i=smith[j].second; i < coprimeR; ++i) {
SmithDiagonal[i] *= smith[j].first;
}
std::vector<size_t>::const_iterator rit=ranks.begin();
// unsigned long modrank = *rit;
for(++rit; rit!= ranks.end(); ++rit) {
if ((*rit)>= coprimeR) break;
for(size_t i=(*rit); i < coprimeR; ++i)
SmithDiagonal[i] *= smith[j].first;
// modrank = *rit;
}
}
}
}
chrono.stop();
Givaro::Integer si=1;
size_t num=0;
std::cerr << "Integer Smith Form :" << std::endl;
std::cout << '(';
for( std::vector<Givaro::Integer>::const_iterator dit=SmithDiagonal.begin();
dit != SmithDiagonal.end(); ++dit) {
if (*dit == si) ++num;
else {
std::cerr << '[' << si << ',' << num << "] ";
num=1;
si = *dit;
}
}
std::cerr << '[' << si << ',' << num << "] " << std::endl;
num = std::min(A.rowdim(),A.coldim()) - SmithDiagonal.size();
si = ZZ.zero;
if (num > 0) std::cout << '[' << si << ',' << num << ']';
std::cout << ')' << std::endl;
std::cerr << chrono << std::endl;
return 0;
}
// Local Variables:
// mode: C++
// tab-width: 4
// indent-tabs-mode: nil
// c-basic-offset: 4
// End:
// vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
<commit_msg>no return<commit_after>/*
* examples/omp_smithvalence.C
* Copyright (c) Linbox
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*/
/**\file examples/omp_smithvalence.C
* @example examples/omp_smithvalence.C
\brief Valence of sparse matrix over Z or Zp.
\ingroup examples
*/
#ifndef DISABLE_COMMENTATOR
#define DISABLE_COMMENTATOR
#endif
#include <iostream>
#include <omp.h>
#include "smithvalence.h"
using namespace LinBox;
int main (int argc, char **argv)
{
// commentator().setMaxDetailLevel (-1);
// commentator().setMaxDepth (-1);
// commentator().setReportStream (std::cerr);
if (argc < 2 || argc > 4) {
std::cerr << "Usage: omp_smithvalence <matrix-file-in-supported-format> [-ata|-aat|valence] [coprime]" << std::endl;
std::cerr << " Optional parameters valence and coprime are integers." << std::endl;
std::cerr << " Prime factors of valence will be used for local computation." << std::endl;
std::cerr << " coprime will be used for overall rank computation." << std::endl;
return -1;
}
std::ifstream input (argv[1]);
if (!input) { std::cerr << "Error opening matrix file " << argv[1] << std::endl; return -1; }
Givaro::ZRing<Integer> ZZ;
MatrixStream< Givaro::ZRing<Integer> > ms( ZZ, input );
typedef SparseMatrix<Givaro::ZRing<Integer>> Blackbox;
Blackbox A (ms);
input.close();
std::cout << "A is " << A.rowdim() << " by " << A.coldim() << std::endl;
Givaro::ZRing<Integer>::Element val_A;
LinBox::Timer chrono; chrono.start();
if (argc >= 3) {
Transpose<Blackbox> T(&A);
if (strcmp(argv[2],"-ata") == 0) {
Compose< Transpose<Blackbox>, Blackbox > C (&T, &A);
std::cout << "A^T A is " << C.rowdim() << " by " << C.coldim() << std::endl;
valence(val_A, C);
}
else if (strcmp(argv[2],"-aat") == 0) {
Compose< Blackbox, Transpose<Blackbox> > C (&A, &T);
std::cout << "A A^T is " << C.rowdim() << " by " << C.coldim() << std::endl;
valence(val_A, C);
}
else {
std::cout << "Suppose primes are contained in " << argv[2] << std::endl;
val_A = LinBox::Integer(argv[2]);
}
}
else {
if (A.rowdim() != A.coldim()) {
std::cerr << "Valence works only on square matrices, try either to change the dimension in the matrix file, or to compute the valence of A A^T or A^T A, via the -aat or -ata options." << std::endl;
exit(0);
}
else
valence (val_A, A);
}
std::cout << "Valence is " << val_A << std::endl;
std::vector<Givaro::Integer> Moduli;
std::vector<size_t> exponents;
Givaro::IntFactorDom<> FTD;
typedef std::pair<Givaro::Integer,unsigned long> PairIntRk;
std::vector< PairIntRk > smith;
Givaro::Integer coprimeV=2;
if (argc >= 4) {
coprimeV =Givaro::Integer(argv[3]);
}
while ( gcd(val_A,coprimeV) > 1 ) {
FTD.nextprimein(coprimeV);
}
if (argc >= 4) {
std::cout << "Suppose " << argv[3] << " is coprime with Smith form" << std::endl;
}
std::cout << "Some factors (50000 factoring loop bound): ";
FTD.set(Moduli, exponents, val_A, 50000);
std::vector<size_t>::const_iterator eit=exponents.begin();
for(std::vector<Givaro::Integer>::const_iterator mit=Moduli.begin();
mit != Moduli.end(); ++mit,++eit)
std::cout << *mit << '^' << *eit << ' ';
std::cout << std::endl;
smith.resize(Moduli.size());
unsigned long coprimeR;
std::cout << "num procs: " << omp_get_num_procs() << std::endl;
std::cout << "max threads: " << omp_get_max_threads() << std::endl;
// #pragma omp parallel for shared(smith, Moduli)
// for(size_t j=0; j<(Moduli.size()+1); ++j) {
// if (j >= Moduli.size()) {
// LRank(coprimeR, argv[1], coprimeV);
// std::cerr << "Integer Rank (mod " << coprimeV << ") is " << coprimeR << " on thread: " << omp_get_thread_num() << std::endl;
// } else {
// unsigned long r; LRank(r, argv[1], Moduli[j]);
// std::cerr << "Rank mod " << Moduli[j] << " is " << r << " on thread: " << omp_get_thread_num() << std::endl;
// smith[j] = PairIntRk( Moduli[j], r);
// }
// }
#pragma omp parallel
{
#pragma omp single
{
for(size_t j=0; j<Moduli.size(); ++j) {
smith[j].first = Moduli[j];
#pragma omp task shared(smith,argv) firstprivate(j)
LRank(smith[j].second, argv[1], smith[j].first);
}
LRank(coprimeR, argv[1], coprimeV);
}
}
std::vector<Givaro::Integer> SmithDiagonal(coprimeR,Givaro::Integer(1));
/*
for(std::vector<Givaro::Integer>::const_iterator mit=Moduli.begin();
mit != Moduli.end(); ++mit) {
unsigned long r; LRank(r, argv[1], *mit);
std::cerr << "Rank mod " << *mit << " is " << r << std::endl;
smith.push_back(PairIntRk(*mit, r));
for(size_t i=r; i < coprimeR; ++i)
SmithDiagonal[i] *= *mit;
}
*/
#pragma omp parallel for shared(SmithDiagonal, smith, exponents)
for(size_t j=0; j<Moduli.size(); ++j) {
if (smith[j].second != coprimeR) {
std::vector<size_t> ranks;
ranks.push_back(smith[j].second);
size_t effexp;
if (exponents[j] > 1) {
if (smith[j].first == 2)
PRankPowerOfTwo(ranks, effexp, argv[1], exponents[j], coprimeR);
else
PRank(ranks, effexp, argv[1], smith[j].first, exponents[j], coprimeR);
}
else {
if (smith[j].first == 2)
PRankPowerOfTwo(ranks, effexp, argv[1], 2, coprimeR);
else
PRank(ranks, effexp, argv[1], smith[j].first, 2, coprimeR);
}
if (ranks.size() == 1) ranks.push_back(coprimeR);
if (effexp < exponents[j]) {
for(size_t expo = effexp<<1; ranks.back() < coprimeR; expo<<=1) {
if (smith[j].first == 2)
PRankIntegerPowerOfTwo(ranks, argv[1], expo, coprimeR);
else
PRankInteger(ranks, argv[1], smith[j].first, expo, coprimeR);
}
} else {
for(size_t expo = (exponents[j])<<1; ranks.back() < coprimeR; expo<<=1) {
if (smith[j].first == 2)
PRankPowerOfTwo(ranks, effexp, argv[1], expo, coprimeR);
else
PRank(ranks, effexp, argv[1], smith[j].first, expo, coprimeR);
if (ranks.size() < expo) {
std::cerr << "It seems we need a larger prime power, it will take longer ..." << std::endl;
// break;
if (smith[j].first == 2)
PRankIntegerPowerOfTwo(ranks, argv[1], expo, coprimeR);
else
PRankInteger(ranks, argv[1], smith[j].first, expo, coprimeR);
}
}
}
#pragma omp critical
{
for(size_t i=smith[j].second; i < coprimeR; ++i) {
SmithDiagonal[i] *= smith[j].first;
}
std::vector<size_t>::const_iterator rit=ranks.begin();
// unsigned long modrank = *rit;
for(++rit; rit!= ranks.end(); ++rit) {
if ((*rit)>= coprimeR) break;
for(size_t i=(*rit); i < coprimeR; ++i)
SmithDiagonal[i] *= smith[j].first;
// modrank = *rit;
}
}
}
}
chrono.stop();
Givaro::Integer si=1;
size_t num=0;
std::cerr << "Integer Smith Form :" << std::endl;
std::cout << '(';
for( std::vector<Givaro::Integer>::const_iterator dit=SmithDiagonal.begin();
dit != SmithDiagonal.end(); ++dit) {
if (*dit == si) ++num;
else {
std::cerr << '[' << si << ',' << num << "] ";
num=1;
si = *dit;
}
}
std::cerr << '[' << si << ',' << num << "] ";
num = std::min(A.rowdim(),A.coldim()) - SmithDiagonal.size();
si = ZZ.zero;
if (num > 0) std::cout << '[' << si << ',' << num << ']';
std::cout << ')' << std::endl;
std::cerr << chrono << std::endl;
return 0;
}
// Local Variables:
// mode: C++
// tab-width: 4
// indent-tabs-mode: nil
// c-basic-offset: 4
// End:
// vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
<|endoftext|> |
<commit_before>/** \file add_subsystem_tags.cc
* \brief Add additional tags for interfaces to identitify subset views of
IxTheo like RelBib and Bibstudies
* \author Johannes Riedl
*/
/*
Copyright (C) 2018, Library of the University of Tübingen
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 <fstream>
#include <iostream>
#include <map>
#include <vector>
#include <cstdlib>
#include "Compiler.h"
#include "File.h"
#include "FileUtil.h"
#include "MARC.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "util.h"
namespace {
const std::string RELBIB_TAG("REL");
const std::string BIBSTUDIES_TAG("BIB");
enum SUBSYSTEM { RELBIB, BIBSTUDIES };
const unsigned NUM_OF_SUBSYSTEMS(2);
[[noreturn]] void Usage() {
std::cerr << "Usage: " << ::progname << " marc_input marc_output\n";
std::exit(EXIT_FAILURE);
}
bool HasRelBibSSGN(const MARC::Record &record) {
for (const auto& field : record.getTagRange("084")) {
const MARC::Subfields subfields(field.getSubfields());
if (subfields.hasSubfieldWithValue('2', "ssgn") and subfields.hasSubfieldWithValue('a', "0"))
return true;
}
return false;
}
bool HasRelBibIxTheoNotation(const MARC::Record &record) {
// Integrate IxTheo Notations A*.B*,T*,V*,X*,Z*
static const std::string RELBIB_IXTHEO_NOTATION_PATTERN("^[ABTVXZ][A-Z].*|.*:[ABTVXZ][A-Z].*");
static RegexMatcher * const relbib_ixtheo_notations_matcher(RegexMatcher::RegexMatcherFactory(RELBIB_IXTHEO_NOTATION_PATTERN));
for (const auto& field : record.getTagRange("652")) {
for (const auto& subfield_a : field.getSubfields().extractSubfields("a")) {
if (relbib_ixtheo_notations_matcher->matched(subfield_a))
return true;
}
}
return false;
}
bool HasPlausibleDDCPrefix(const std::string &ddc_string) {
// Exclude records that where the entry in the DCC field is not plausible
static const std::string PLAUSIBLE_DDC_PREFIX_PATTERN("^\\d\\d");
static RegexMatcher * const plausible_ddc_prefix_matcher(RegexMatcher::RegexMatcherFactoryOrDie(PLAUSIBLE_DDC_PREFIX_PATTERN));
return plausible_ddc_prefix_matcher->matched(ddc_string);
}
// Additional criteria that prevent the exclusion of a record that has a 220-289 field
bool HasAdditionalRelbibAdmissionDDC(const MARC::Record &record) {
static const std::string RELBIB_ADMIT_DDC_PATTERN("^([12][01][0-9]|2[9][0-9]|[3-9][0-9][0-9]).*$");
static RegexMatcher * const relbib_admit_ddc_range_matcher(RegexMatcher::RegexMatcherFactoryOrDie(RELBIB_ADMIT_DDC_PATTERN));
for (const auto &field : record.getTagRange("082")) {
for (const auto &subfield_a : field.getSubfields().extractSubfields("a")) {
if (HasPlausibleDDCPrefix(subfield_a) and relbib_admit_ddc_range_matcher->matched(subfield_a))
return true;
}
}
return false;
}
bool HasRelBibExcludeDDC(const MARC::Record &record) {
if (not record.hasTag("082"))
return true;
// Exclude DDC 220-289
static const std::string RELBIB_EXCLUDE_DDC_RANGE_PATTERN("^2[2-8][0-9](/|\\.){0,2}[^.]*$");
static RegexMatcher * const relbib_exclude_ddc_range_matcher(RegexMatcher::RegexMatcherFactoryOrDie(RELBIB_EXCLUDE_DDC_RANGE_PATTERN));
// Make sure we have 082-fields to examine
if (not record.hasTag("082"))
return false;
// In general we exclude if the exclude range is matched
// But we include it anyway if we find another reasonable DDC-code
for (const auto &field : record.getTagRange("082")) {
for (const auto &subfield_a : field.getSubfields().extractSubfields("a")) {
if (relbib_exclude_ddc_range_matcher->matched(subfield_a)) {
if (not HasAdditionalRelbibAdmissionDDC(record))
return true;
}
}
}
// Exclude item if it has only a 400 or 800 DDC notation
static const std::string RELBIB_EXCLUDE_DDC_CATEGORIES_PATTERN("^[48][0-9][0-9]$");
static RegexMatcher * const relbib_exclude_ddc_categories_matcher(RegexMatcher::RegexMatcherFactoryOrDie(RELBIB_EXCLUDE_DDC_CATEGORIES_PATTERN));
for (const auto &field : record.getTagRange("082")) {
for (const auto &subfield_a : field.getSubfields().extractSubfields('a')) {
if (HasPlausibleDDCPrefix(subfield_a) and not relbib_exclude_ddc_categories_matcher->matched(subfield_a))
return false;
}
}
return true;
}
bool MatchesRelBibDDC(const MARC::Record &record) {
return not HasRelBibExcludeDDC(record);
}
bool IsDefinitelyRelBib(const MARC::Record &record) {
return HasRelBibSSGN(record) or HasRelBibIxTheoNotation(record) or MatchesRelBibDDC(record);
}
bool IsProbablyRelBib(const MARC::Record &record) {
for (const auto& field : record.getTagRange("191")) {
for (const auto& subfield : field.getSubfields().extractSubfields("a")) {
if (subfield == "1")
return true;
}
}
return false;
}
std::set<std::string> GetTemporarySuperiorRelBibList() {
const std::string relbib_superior_temporary_file("/usr/local/ub_tools/cpp/data/relbib_superior_temporary.txt");
std::set<std::string> superior_temporary_list;
File superior_temporary(relbib_superior_temporary_file, "r");
std::string line;
while (superior_temporary.getline(&line) and not superior_temporary.eof())
superior_temporary_list.emplace(line);
return superior_temporary_list;
}
bool IsTemporaryRelBibSuperior(const MARC::Record &record) {
static std::set<std::string> superior_temporary_list(GetTemporarySuperiorRelBibList());
if (superior_temporary_list.find(record.getControlNumber()) != superior_temporary_list.end())
return true;
return false;
}
bool ExcludeBecauseOfRWEX(const MARC::Record &record) {
for (const auto &field : record.getTagRange("LOK")) {
const auto &subfields(field.getSubfields());
for (const auto &subfield0: subfields.extractSubfields('0')) {
if (not StringUtil::StartsWith(subfield0, "935"))
continue;
for (const auto &subfield_a : subfields.extractSubfields('a')) {
if (subfield_a == "rwex")
return true;
}
}
}
return false;
}
bool IsRelBibRecord(const MARC::Record &record) {
return ((IsDefinitelyRelBib(record) or
IsProbablyRelBib(record) or
IsTemporaryRelBibSuperior(record))
and not ExcludeBecauseOfRWEX(record));
}
bool HasBibStudiesIxTheoNotation(const MARC::Record &record) {
static const std::string BIBSTUDIES_IXTHEO_PATTERN("^[H][A-Z].*|.*:[H][A-Z].*");
static RegexMatcher * const relbib_ixtheo_notations_matcher(RegexMatcher::RegexMatcherFactory(BIBSTUDIES_IXTHEO_PATTERN));
for (const auto &field : record.getTagRange("652")) {
for (const auto &subfield_a : field.getSubfields().extractSubfields("a")) {
if (relbib_ixtheo_notations_matcher->matched(subfield_a))
return true;
}
}
return false;
}
bool IsBibStudiesRecord(const MARC::Record &record) {
return HasBibStudiesIxTheoNotation(record);
}
void AddSubsystemTag(MARC::Record * const record, const std::string &tag) {
// Don't insert twice
if (record->getFirstField(tag) != record->end())
return;
MARC::Subfields subfields;
subfields.addSubfield('a', "1");
record->insertField(tag, subfields);
}
void CollectSuperiorOrParallelWorks(const MARC::Record &record, std::unordered_set<std::string> * const superior_or_parallel_works) {
const std::set<std::string> parallel(MARC::ExtractCrossReferencePPNs(record));
superior_or_parallel_works->insert(parallel.begin(), parallel.end());
superior_or_parallel_works->insert(record.getSuperiorControlNumber());
}
// Get set of immediately belonging or superior or parallel records
void GetSubsystemPPNSet(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer,
std::vector<std::unordered_set<std::string>> * const subsystem_sets) {
while (const MARC::Record record = marc_reader->read()) {
if (IsRelBibRecord(record)) {
((*subsystem_sets)[RELBIB]).emplace(record.getControlNumber());
CollectSuperiorOrParallelWorks(record, &((*subsystem_sets)[RELBIB]));
}
if (IsBibStudiesRecord(record)) {
((*subsystem_sets)[BIBSTUDIES]).emplace(record.getControlNumber());
CollectSuperiorOrParallelWorks(record, &((*subsystem_sets)[BIBSTUDIES]));
}
marc_writer->write(record);
}
}
void AddSubsystemTags(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer,
const std::vector<std::unordered_set<std::string>> &subsystem_sets) {
unsigned record_count(0), modified_count(0);
while (MARC::Record record = marc_reader->read()) {
++record_count;
bool modified_record(false);
if ((subsystem_sets[RELBIB]).find(record.getControlNumber()) != subsystem_sets[RELBIB].end()) {
AddSubsystemTag(&record, RELBIB_TAG);
modified_record = true;
}
if ((subsystem_sets[BIBSTUDIES]).find(record.getControlNumber()) != subsystem_sets[RELBIB].end()) {
AddSubsystemTag(&record, BIBSTUDIES_TAG);
modified_record = true;
}
if (modified_record)
++modified_count;
marc_writer->write(record);
}
LOG_INFO("Modified " + std::to_string(modified_count) + " of " + std::to_string(record_count) + " records.");
}
void InitializeSubsystemPPNSets(std::vector<std::unordered_set<std::string>> * const subsystem_ppn_sets) {
for (unsigned i = 0; i < NUM_OF_SUBSYSTEMS; ++i)
subsystem_ppn_sets->push_back(std::unordered_set<std::string>());
}
} //unnamed namespace
int Main(int argc, char **argv) {
if (argc != 3)
Usage();
const std::string marc_input_filename(argv[1]);
const std::string marc_output_filename(argv[2]);
if (unlikely(marc_input_filename == marc_output_filename))
LOG_ERROR("Title data input file name equals output file name!");
std::vector<std::unordered_set<std::string>> subsystem_sets;
InitializeSubsystemPPNSets(&subsystem_sets);
std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(marc_input_filename));
FileUtil::AutoTempFile tmp_marc_file("/dev/shm/", ".mrc");
std::unique_ptr<MARC::Writer> marc_tmp_writer(MARC::Writer::Factory(tmp_marc_file.getFilePath()));
GetSubsystemPPNSet(marc_reader.get(), marc_tmp_writer.get(), &subsystem_sets);
if (not marc_tmp_writer->flush())
LOG_ERROR("Could not flush to " + tmp_marc_file.getFilePath());
std::unique_ptr<MARC::Reader> marc_tmp_reader(MARC::Reader::Factory(tmp_marc_file.getFilePath()));
std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(marc_output_filename));
AddSubsystemTags(marc_tmp_reader.get(), marc_writer.get(), subsystem_sets);
return EXIT_SUCCESS;
}
<commit_msg>Requested changes<commit_after>/** \file add_subsystem_tags.cc
* \brief Add additional tags for interfaces to identitify subset views of
IxTheo like RelBib and Bibstudies
* \author Johannes Riedl
*/
/*
Copyright (C) 2018, Library of the University of Tübingen
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 <fstream>
#include <iostream>
#include <map>
#include <vector>
#include <cstdlib>
#include "Compiler.h"
#include "File.h"
#include "FileUtil.h"
#include "MARC.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "util.h"
namespace {
const std::string RELBIB_TAG("REL");
const std::string BIBSTUDIES_TAG("BIB");
enum SubSystem { RELBIB, BIBSTUDIES };
const unsigned NUM_OF_SUBSYSTEMS(2);
[[noreturn]] void Usage() {
std::cerr << "Usage: " << ::progname << " marc_input marc_output\n";
std::exit(EXIT_FAILURE);
}
bool HasRelBibSSGN(const MARC::Record &record) {
for (const auto& field : record.getTagRange("084")) {
const MARC::Subfields subfields(field.getSubfields());
if (subfields.hasSubfieldWithValue('2', "ssgn") and subfields.hasSubfieldWithValue('a', "0"))
return true;
}
return false;
}
bool HasRelBibIxTheoNotation(const MARC::Record &record) {
// Integrate IxTheo Notations A*.B*,T*,V*,X*,Z*
static const std::string RELBIB_IXTHEO_NOTATION_PATTERN("^[ABTVXZ][A-Z].*|.*:[ABTVXZ][A-Z].*");
static RegexMatcher * const relbib_ixtheo_notations_matcher(RegexMatcher::RegexMatcherFactory(RELBIB_IXTHEO_NOTATION_PATTERN));
for (const auto& field : record.getTagRange("652")) {
for (const auto& subfield_a : field.getSubfields().extractSubfields("a")) {
if (relbib_ixtheo_notations_matcher->matched(subfield_a))
return true;
}
}
return false;
}
bool HasPlausibleDDCPrefix(const std::string &ddc_string) {
// Exclude records that where the entry in the DCC field is not plausible
static const std::string PLAUSIBLE_DDC_PREFIX_PATTERN("^\\d\\d");
static RegexMatcher * const plausible_ddc_prefix_matcher(RegexMatcher::RegexMatcherFactoryOrDie(PLAUSIBLE_DDC_PREFIX_PATTERN));
return plausible_ddc_prefix_matcher->matched(ddc_string);
}
// Additional criteria that prevent the exclusion of a record that has a 220-289 field
bool HasAdditionalRelbibAdmissionDDC(const MARC::Record &record) {
static const std::string RELBIB_ADMIT_DDC_PATTERN("^([12][01][0-9]|2[9][0-9]|[3-9][0-9][0-9]).*$");
static RegexMatcher * const relbib_admit_ddc_range_matcher(RegexMatcher::RegexMatcherFactoryOrDie(RELBIB_ADMIT_DDC_PATTERN));
for (const auto &field : record.getTagRange("082")) {
for (const auto &subfield_a : field.getSubfields().extractSubfields("a")) {
if (HasPlausibleDDCPrefix(subfield_a) and relbib_admit_ddc_range_matcher->matched(subfield_a))
return true;
}
}
return false;
}
bool HasRelBibExcludeDDC(const MARC::Record &record) {
if (not record.hasTag("082"))
return true;
// Exclude DDC 220-289
static const std::string RELBIB_EXCLUDE_DDC_RANGE_PATTERN("^2[2-8][0-9](/|\\.){0,2}[^.]*$");
static RegexMatcher * const relbib_exclude_ddc_range_matcher(RegexMatcher::RegexMatcherFactoryOrDie(RELBIB_EXCLUDE_DDC_RANGE_PATTERN));
// Make sure we have 082-fields to examine
if (not record.hasTag("082"))
return false;
// In general we exclude if the exclude range is matched
// But we include it anyway if we find another reasonable DDC-code
for (const auto &field : record.getTagRange("082")) {
for (const auto &subfield_a : field.getSubfields().extractSubfields("a")) {
if (relbib_exclude_ddc_range_matcher->matched(subfield_a)) {
if (not HasAdditionalRelbibAdmissionDDC(record))
return true;
}
}
}
// Exclude item if it has only a 400 or 800 DDC notation
static const std::string RELBIB_EXCLUDE_DDC_CATEGORIES_PATTERN("^[48][0-9][0-9]$");
static RegexMatcher * const relbib_exclude_ddc_categories_matcher(RegexMatcher::RegexMatcherFactoryOrDie(RELBIB_EXCLUDE_DDC_CATEGORIES_PATTERN));
for (const auto &field : record.getTagRange("082")) {
for (const auto &subfield_a : field.getSubfields().extractSubfields('a')) {
if (HasPlausibleDDCPrefix(subfield_a) and not relbib_exclude_ddc_categories_matcher->matched(subfield_a))
return false;
}
}
return true;
}
bool MatchesRelBibDDC(const MARC::Record &record) {
return not HasRelBibExcludeDDC(record);
}
bool IsDefinitelyRelBib(const MARC::Record &record) {
return HasRelBibSSGN(record) or HasRelBibIxTheoNotation(record) or MatchesRelBibDDC(record);
}
bool IsProbablyRelBib(const MARC::Record &record) {
for (const auto& field : record.getTagRange("191")) {
for (const auto& subfield : field.getSubfields().extractSubfields("a")) {
if (subfield == "1")
return true;
}
}
return false;
}
std::set<std::string> GetTemporarySuperiorRelBibList() {
const std::string relbib_superior_temporary_file("/usr/local/ub_tools/cpp/data/relbib_superior_temporary.txt");
std::set<std::string> superior_temporary_list;
File superior_temporary(relbib_superior_temporary_file, "r");
std::string line;
while (superior_temporary.getline(&line) and not superior_temporary.eof())
superior_temporary_list.emplace(line);
return superior_temporary_list;
}
bool IsTemporaryRelBibSuperior(const MARC::Record &record) {
static std::set<std::string> superior_temporary_list(GetTemporarySuperiorRelBibList());
if (superior_temporary_list.find(record.getControlNumber()) != superior_temporary_list.end())
return true;
return false;
}
bool ExcludeBecauseOfRWEX(const MARC::Record &record) {
for (const auto &field : record.getTagRange("LOK")) {
const auto &subfields(field.getSubfields());
for (const auto &subfield0: subfields.extractSubfields('0')) {
if (not StringUtil::StartsWith(subfield0, "935"))
continue;
for (const auto &subfield_a : subfields.extractSubfields('a')) {
if (subfield_a == "rwex")
return true;
}
}
}
return false;
}
bool IsRelBibRecord(const MARC::Record &record) {
return ((IsDefinitelyRelBib(record) or
IsProbablyRelBib(record) or
IsTemporaryRelBibSuperior(record))
and not ExcludeBecauseOfRWEX(record));
}
bool HasBibStudiesIxTheoNotation(const MARC::Record &record) {
static const std::string BIBSTUDIES_IXTHEO_PATTERN("^[H][A-Z].*|.*:[H][A-Z].*");
static RegexMatcher * const relbib_ixtheo_notations_matcher(RegexMatcher::RegexMatcherFactory(BIBSTUDIES_IXTHEO_PATTERN));
for (const auto &field : record.getTagRange("652")) {
for (const auto &subfield_a : field.getSubfields().extractSubfields("a")) {
if (relbib_ixtheo_notations_matcher->matched(subfield_a))
return true;
}
}
return false;
}
bool IsBibStudiesRecord(const MARC::Record &record) {
return HasBibStudiesIxTheoNotation(record);
}
void AddSubsystemTag(MARC::Record * const record, const std::string &tag) {
// Don't insert twice
if (record->getFirstField(tag) != record->end())
return;
MARC::Subfields subfields;
subfields.addSubfield('a', "1");
record->insertField(tag, subfields);
}
void CollectSuperiorOrParallelWorks(const MARC::Record &record, std::unordered_set<std::string> * const superior_or_parallel_works) {
const std::set<std::string> parallel(MARC::ExtractCrossReferencePPNs(record));
superior_or_parallel_works->insert(parallel.begin(), parallel.end());
superior_or_parallel_works->insert(record.getSuperiorControlNumber());
}
// Get set of immediately belonging or superior or parallel records
void GetSubsystemPPNSet(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer,
std::vector<std::unordered_set<std::string>> * const subsystem_sets) {
while (const MARC::Record record = marc_reader->read()) {
if (IsRelBibRecord(record)) {
((*subsystem_sets)[RELBIB]).emplace(record.getControlNumber());
CollectSuperiorOrParallelWorks(record, &((*subsystem_sets)[RELBIB]));
}
if (IsBibStudiesRecord(record)) {
((*subsystem_sets)[BIBSTUDIES]).emplace(record.getControlNumber());
CollectSuperiorOrParallelWorks(record, &((*subsystem_sets)[BIBSTUDIES]));
}
marc_writer->write(record);
}
}
void AddSubsystemTags(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer,
const std::vector<std::unordered_set<std::string>> &subsystem_sets) {
unsigned record_count(0), modified_count(0);
while (MARC::Record record = marc_reader->read()) {
++record_count;
bool modified_record(false);
if ((subsystem_sets[RELBIB]).find(record.getControlNumber()) != subsystem_sets[RELBIB].end()) {
AddSubsystemTag(&record, RELBIB_TAG);
modified_record = true;
}
if ((subsystem_sets[BIBSTUDIES]).find(record.getControlNumber()) != subsystem_sets[RELBIB].end()) {
AddSubsystemTag(&record, BIBSTUDIES_TAG);
modified_record = true;
}
if (modified_record)
++modified_count;
marc_writer->write(record);
}
LOG_INFO("Modified " + std::to_string(modified_count) + " of " + std::to_string(record_count) + " records.");
}
void InitializeSubsystemPPNSets(std::vector<std::unordered_set<std::string>> * const subsystem_ppn_sets) {
for (unsigned i = 0; i < NUM_OF_SUBSYSTEMS; ++i)
subsystem_ppn_sets->push_back(std::unordered_set<std::string>());
}
} //unnamed namespace
int Main(int argc, char **argv) {
if (argc != 3)
Usage();
const std::string marc_input_filename(argv[1]);
const std::string marc_output_filename(argv[2]);
if (unlikely(marc_input_filename == marc_output_filename))
LOG_ERROR("Title data input file name equals output file name!");
std::vector<std::unordered_set<std::string>> subsystem_sets;
InitializeSubsystemPPNSets(&subsystem_sets);
std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(marc_input_filename));
FileUtil::AutoTempFile tmp_marc_file("/dev/shm/", ".mrc");
std::unique_ptr<MARC::Writer> marc_tmp_writer(MARC::Writer::Factory(tmp_marc_file.getFilePath()));
GetSubsystemPPNSet(marc_reader.get(), marc_tmp_writer.get(), &subsystem_sets);
if (not marc_tmp_writer->flush())
LOG_ERROR("Could not flush to " + tmp_marc_file.getFilePath());
std::unique_ptr<MARC::Reader> marc_tmp_reader(MARC::Reader::Factory(tmp_marc_file.getFilePath()));
std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(marc_output_filename));
AddSubsystemTags(marc_tmp_reader.get(), marc_writer.get(), subsystem_sets);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <cpuid.h>
#include "cpuid.h"
namespace z
{
namespace system
{
void cpuid::det_vendor()
{
uint32_t eax, ebx, ecx, edx;
good = __get_cpuid(0, &eax, &ebx, &ecx, &edx);
/*asm volatile
(
"cpuid" :
"=a" (regs[0]), "=b" (regs[1]), "=c" (regs[2]), "=d" (regs[3]) :
"a" (cmd), "c" (0)
);*/
// ECX is set to zero for CPUID function 4
if (good)
{
char vendor[13];
vendor[12] = 0;
*((uint32_t*)&vendor[0]) = ebx;
*((uint32_t*)&vendor[4]) = edx;
*((uint32_t*)&vendor[8]) = ecx;
_vendor = vendor;
}
}
void cpuid::det_cpu()
{
uint32_t eax, ebx, ecx, edx;
__get_cpuid(1, &eax, &ebx, &ecx, &edx);
_cpus = (ebx >> 16) & 0xff;
_cpuFeatures = edx;
if (_vendor == "GenuineIntel")
{
__get_cpuid(4, &eax, &ebx, &ecx, &edx);
_cores = ((eax >> 26) & 0x3f) + 1;
}
else if (_vendor == "AuthenticAMD")
{
__get_cpuid(0x80000008, &eax, &ebx, &ecx, &edx);
_cores = (ecx & 0xff) + 1;
}
else
{
_cores = _cpus;
}
_allow_smt = _cpuFeatures & (1 << 28) && _cores < _cpus;
}
cpuid::cpuid()
{
det_vendor(); //'good' will be determined after vendorID
if (good)
{
det_cpu();
}
}
const core::string<ascii>& cpuid::vendor()
{
return _vendor;
}
int cpuid::cpus()
{
return _cpus;
}
int cpuid::cores()
{
return _cores;
}
}
}
<commit_msg>Getting rid of warnings<commit_after>#include <cpuid.h>
#include "cpuid.h"
namespace z
{
namespace system
{
void cpuid::det_vendor()
{
uint32_t eax(0), ebx(0), ecx(0), edx(0);
good = __get_cpuid(0, &eax, &ebx, &ecx, &edx);
/*asm volatile
(
"cpuid" :
"=a" (regs[0]), "=b" (regs[1]), "=c" (regs[2]), "=d" (regs[3]) :
"a" (cmd), "c" (0)
);*/
// ECX is set to zero for CPUID function 4
if (good)
{
char vendor[13];
vendor[12] = 0;
uint32_t* ptr = (uint32_t*)vendor;
ptr[0] = ebx;
ptr[1] = edx;
ptr[2] = ecx;
_vendor = vendor;
}
}
void cpuid::det_cpu()
{
uint32_t eax(0), ebx(0), ecx(0), edx(0);
__get_cpuid(1, &eax, &ebx, &ecx, &edx);
_cpus = (ebx >> 16) & 0xff;
_cpuFeatures = edx;
if (_vendor == "GenuineIntel")
{
__get_cpuid(4, &eax, &ebx, &ecx, &edx);
_cores = ((eax >> 26) & 0x3f) + 1;
}
else if (_vendor == "AuthenticAMD")
{
__get_cpuid(0x80000008, &eax, &ebx, &ecx, &edx);
_cores = (ecx & 0xff) + 1;
}
else
{
_cores = _cpus;
}
_allow_smt = _cpuFeatures & (1 << 28) && _cores < _cpus;
}
cpuid::cpuid()
{
det_vendor(); //'good' will be determined after vendorID
if (good)
{
det_cpu();
}
}
const core::string<ascii>& cpuid::vendor()
{
return _vendor;
}
int cpuid::cpus()
{
return _cpus;
}
int cpuid::cores()
{
return _cores;
}
}
}
<|endoftext|> |
<commit_before>/*-------------------------------------------------------------------------
*
* database.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /n-store/src/storage/table.cpp
*
*-------------------------------------------------------------------------
*/
#include "backend/storage/database.h"
#include "backend/storage/table_factory.h"
#include "backend/common/logger.h"
#include <sstream>
namespace peloton {
namespace storage {
Database::~Database() {
// Clean up all the tables
for (auto table : tables) delete table;
}
//===--------------------------------------------------------------------===//
// TABLE
//===--------------------------------------------------------------------===//
void Database::AddTable(storage::DataTable* table) {
{
std::lock_guard<std::mutex> lock(database_mutex);
tables.push_back(table);
}
}
storage::DataTable* Database::GetTableWithOid(const oid_t table_oid) const {
for (auto table : tables)
if (table->GetOid() == table_oid) return table;
return nullptr;
}
storage::DataTable* Database::GetTableWithName(
const std::string table_name) const {
for (auto table : tables)
if (table->GetName() == table_name) return table;
return nullptr;
}
void Database::DropTableWithOid(const oid_t table_oid) {
{
std::lock_guard<std::mutex> lock(database_mutex);
oid_t table_offset = 0;
for (auto table : tables) {
if (table->GetOid() == table_oid) break;
table_offset++;
}
assert(table_offset < tables.size());
// Drop the database
tables.erase(tables.begin() + table_offset);
}
}
storage::DataTable* Database::GetTable(const oid_t table_offset) const {
assert(table_offset < tables.size());
auto table = tables.at(table_offset);
return table;
}
oid_t Database::GetTableCount() const { return tables.size(); }
//===--------------------------------------------------------------------===//
// STATS
//===--------------------------------------------------------------------===//
void Database::UpdateStats(Peloton_Status* status){
LOG_INFO("Update All Stats in Database(%u)", database_oid);
// TODO :: need to check whether ... table... is changed or not
std::vector<dirty_table_info*> dirty_tables;
for( int table_offset=0; table_offset<GetTableCount(); table_offset++){
auto table = GetTable(table_offset);
std::vector<dirty_index_info*> dirty_indexes;
for (int index_offset = 0; index_offset < table->GetIndexCount(); index_offset++) {
auto index = table->GetIndex(index_offset);
auto dirty_index = CreateDirtyIndex(index->GetOid(), index->GetNumberOfTuples());
dirty_indexes.push_back(dirty_index);
}
auto dirty_table = CreateDirtyTable(table->GetOid(),
table->GetNumberOfTuples(),
CreateDirtyIndexes(dirty_indexes),
dirty_indexes.size());
dirty_tables.push_back(dirty_table);
}
status->m_dirty_tables = CreateDirtyTables(dirty_tables);
status->m_dirty_count = dirty_tables.size();
}
void Database::UpdateStatsWithOid(const oid_t table_oid){
LOG_INFO("Update table(%u)'s stats in Database(%u)", table_oid, database_oid);
auto table = GetTableWithOid(table_oid);
bridge::Bridge::SetNumberOfTuples(table_oid, table->GetNumberOfTuples());
for (int index_offset = 0; index_offset < table->GetIndexCount();
index_offset++) {
auto index = table->GetIndex(index_offset);
bridge::Bridge::SetNumberOfTuples(index->GetOid(),
index->GetNumberOfTuples());
}
}
//===--------------------------------------------------------------------===//
// UTILITIES
//===--------------------------------------------------------------------===//
dirty_table_info** Database::CreateDirtyTables(std::vector< dirty_table_info*> dirty_tables_vec){
//XXX:: TopSharedMem???
dirty_table_info** dirty_tables = (dirty_table_info**)palloc(sizeof(dirty_table_info*)*dirty_tables_vec.size());
oid_t table_itr=0;
for(auto dirty_table : dirty_tables_vec)
dirty_tables[table_itr] = dirty_table;
return dirty_tables;
}
dirty_index_info** Database::CreateDirtyIndexes(std::vector< dirty_index_info*> dirty_indexes_vec){
dirty_index_info** dirty_indexes = (dirty_index_info**)palloc(sizeof(dirty_index_info*)*dirty_indexes_vec.size());
oid_t index_itr=0;
for(auto dirty_index : dirty_indexes_vec)
dirty_indexes[index_itr] = dirty_index;
return dirty_indexes;
}
dirty_table_info* Database::CreateDirtyTable(oid_t table_oid, float number_of_tuples, dirty_index_info** dirty_indexes, oid_t index_count){
dirty_table_info* dirty_table = (dirty_table_info*)palloc(sizeof(dirty_table_info));
dirty_table->table_oid = table_oid;
dirty_table->number_of_tuples = number_of_tuples;
dirty_table->dirty_indexes = dirty_indexes;
dirty_table->index_count = index_count;
return dirty_table;
}
dirty_index_info* Database::CreateDirtyIndex(oid_t index_oid, float number_of_tuples){
dirty_index_info* dirty_index = (dirty_index_info*)palloc(sizeof(dirty_index_info));
dirty_index->index_oid = index_oid;
dirty_index->number_of_tuples = number_of_tuples;
return dirty_index;
}
std::ostream& operator<<(std::ostream& os, const Database& database) {
os << "=====================================================\n";
os << "DATABASE(" << database.GetOid() << ") : \n";
oid_t table_count = database.GetTableCount();
std::cout << "Table Count : " << table_count << "\n";
oid_t table_itr = 0;
for (auto table : database.tables) {
if (table != nullptr) {
std::cout << "(" << ++table_itr << "/" << table_count << ") "
<< "Table Name(" << table->GetOid() << ") : " << table->GetName() << "\n"
<< *(table->GetSchema()) << std::endl;
oid_t index_count = table->GetIndexCount();
if (index_count > 0) {
std::cout << "Index Count : " << index_count << std::endl;
for (int index_itr = 0; index_itr < index_count; index_itr++) {
index::Index* index = table->GetIndex(index_itr);
switch (index->GetIndexType()) {
case INDEX_CONSTRAINT_TYPE_PRIMARY_KEY:
std::cout << "primary key index \n";
break;
case INDEX_CONSTRAINT_TYPE_UNIQUE:
std::cout << "unique index \n";
break;
default:
std::cout << "default index \n";
break;
}
std::cout << *index << std::endl;
}
}
if (table->HasForeignKeys()) {
std::cout << "foreign tables \n";
oid_t foreign_key_count = table->GetForeignKeyCount();
for (int foreign_key_itr = 0; foreign_key_itr < foreign_key_count;
foreign_key_itr++) {
auto foreign_key = table->GetForeignKey(foreign_key_itr);
auto sink_table_oid = foreign_key->GetSinkTableOid();
auto sink_table = database.GetTableWithOid(sink_table_oid);
auto sink_table_schema = sink_table->GetSchema();
std::cout << "table name : " << sink_table->GetName() << " "
<< *sink_table_schema << std::endl;
}
}
}
}
os << "=====================================================\n";
return os;
}
} // End storage namespace
} // End peloton namespace
<commit_msg>Used shared memory for dirty tables<commit_after>/*-------------------------------------------------------------------------
*
* database.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /n-store/src/storage/table.cpp
*
*-------------------------------------------------------------------------
*/
#include "backend/storage/database.h"
#include "backend/storage/table_factory.h"
#include "backend/common/logger.h"
#include <sstream>
namespace peloton {
namespace storage {
Database::~Database() {
// Clean up all the tables
for (auto table : tables) delete table;
}
//===--------------------------------------------------------------------===//
// TABLE
//===--------------------------------------------------------------------===//
void Database::AddTable(storage::DataTable* table) {
{
std::lock_guard<std::mutex> lock(database_mutex);
tables.push_back(table);
}
}
storage::DataTable* Database::GetTableWithOid(const oid_t table_oid) const {
for (auto table : tables)
if (table->GetOid() == table_oid) return table;
return nullptr;
}
storage::DataTable* Database::GetTableWithName(
const std::string table_name) const {
for (auto table : tables)
if (table->GetName() == table_name) return table;
return nullptr;
}
void Database::DropTableWithOid(const oid_t table_oid) {
{
std::lock_guard<std::mutex> lock(database_mutex);
oid_t table_offset = 0;
for (auto table : tables) {
if (table->GetOid() == table_oid) break;
table_offset++;
}
assert(table_offset < tables.size());
// Drop the database
tables.erase(tables.begin() + table_offset);
}
}
storage::DataTable* Database::GetTable(const oid_t table_offset) const {
assert(table_offset < tables.size());
auto table = tables.at(table_offset);
return table;
}
oid_t Database::GetTableCount() const { return tables.size(); }
//===--------------------------------------------------------------------===//
// STATS
//===--------------------------------------------------------------------===//
void Database::UpdateStats(Peloton_Status* status){
LOG_INFO("Update All Stats in Database(%u)", database_oid);
// TODO :: need to check whether ... table... is changed or not
std::vector<dirty_table_info*> dirty_tables;
for( int table_offset=0; table_offset<GetTableCount(); table_offset++){
auto table = GetTable(table_offset);
std::vector<dirty_index_info*> dirty_indexes;
for (int index_offset = 0; index_offset < table->GetIndexCount(); index_offset++) {
auto index = table->GetIndex(index_offset);
auto dirty_index = CreateDirtyIndex(index->GetOid(), index->GetNumberOfTuples());
dirty_indexes.push_back(dirty_index);
}
auto dirty_table = CreateDirtyTable(table->GetOid(),
table->GetNumberOfTuples(),
CreateDirtyIndexes(dirty_indexes),
dirty_indexes.size());
dirty_tables.push_back(dirty_table);
}
status->m_dirty_tables = CreateDirtyTables(dirty_tables);
status->m_dirty_count = dirty_tables.size();
}
void Database::UpdateStatsWithOid(const oid_t table_oid){
LOG_INFO("Update table(%u)'s stats in Database(%u)", table_oid, database_oid);
auto table = GetTableWithOid(table_oid);
bridge::Bridge::SetNumberOfTuples(table_oid, table->GetNumberOfTuples());
for (int index_offset = 0; index_offset < table->GetIndexCount();
index_offset++) {
auto index = table->GetIndex(index_offset);
bridge::Bridge::SetNumberOfTuples(index->GetOid(),
index->GetNumberOfTuples());
}
}
//===--------------------------------------------------------------------===//
// UTILITIES
//===--------------------------------------------------------------------===//
dirty_table_info** Database::CreateDirtyTables(std::vector< dirty_table_info*> dirty_tables_vec){
//XXX:: TopSharedMem???
MemoryContext oldcxt = MemoryContextSwitchTo(TopSharedMemoryContext);
dirty_table_info** dirty_tables = (dirty_table_info**)palloc(sizeof(dirty_table_info*)*dirty_tables_vec.size());
MemoryContextSwitchTo(oldcxt);
oid_t table_itr=0;
for(auto dirty_table : dirty_tables_vec)
dirty_tables[table_itr] = dirty_table;
return dirty_tables;
}
dirty_index_info** Database::CreateDirtyIndexes(std::vector< dirty_index_info*> dirty_indexes_vec){
MemoryContext oldcxt = MemoryContextSwitchTo(TopSharedMemoryContext);
dirty_index_info** dirty_indexes = (dirty_index_info**)palloc(sizeof(dirty_index_info*)*dirty_indexes_vec.size());
MemoryContextSwitchTo(oldcxt);
oid_t index_itr=0;
for(auto dirty_index : dirty_indexes_vec)
dirty_indexes[index_itr] = dirty_index;
return dirty_indexes;
}
dirty_table_info* Database::CreateDirtyTable(oid_t table_oid, float number_of_tuples, dirty_index_info** dirty_indexes, oid_t index_count){
MemoryContext oldcxt = MemoryContextSwitchTo(TopSharedMemoryContext);
dirty_table_info* dirty_table = (dirty_table_info*)palloc(sizeof(dirty_table_info));
MemoryContextSwitchTo(oldcxt);
dirty_table->table_oid = table_oid;
dirty_table->number_of_tuples = number_of_tuples;
dirty_table->dirty_indexes = dirty_indexes;
dirty_table->index_count = index_count;
return dirty_table;
}
dirty_index_info* Database::CreateDirtyIndex(oid_t index_oid, float number_of_tuples){
MemoryContext oldcxt = MemoryContextSwitchTo(TopSharedMemoryContext);
dirty_index_info* dirty_index = (dirty_index_info*)palloc(sizeof(dirty_index_info));
MemoryContextSwitchTo(oldcxt);
dirty_index->index_oid = index_oid;
dirty_index->number_of_tuples = number_of_tuples;
return dirty_index;
}
std::ostream& operator<<(std::ostream& os, const Database& database) {
os << "=====================================================\n";
os << "DATABASE(" << database.GetOid() << ") : \n";
oid_t table_count = database.GetTableCount();
std::cout << "Table Count : " << table_count << "\n";
oid_t table_itr = 0;
for (auto table : database.tables) {
if (table != nullptr) {
std::cout << "(" << ++table_itr << "/" << table_count << ") "
<< "Table Name(" << table->GetOid() << ") : " << table->GetName() << "\n"
<< *(table->GetSchema()) << std::endl;
oid_t index_count = table->GetIndexCount();
if (index_count > 0) {
std::cout << "Index Count : " << index_count << std::endl;
for (int index_itr = 0; index_itr < index_count; index_itr++) {
index::Index* index = table->GetIndex(index_itr);
switch (index->GetIndexType()) {
case INDEX_CONSTRAINT_TYPE_PRIMARY_KEY:
std::cout << "primary key index \n";
break;
case INDEX_CONSTRAINT_TYPE_UNIQUE:
std::cout << "unique index \n";
break;
default:
std::cout << "default index \n";
break;
}
std::cout << *index << std::endl;
}
}
if (table->HasForeignKeys()) {
std::cout << "foreign tables \n";
oid_t foreign_key_count = table->GetForeignKeyCount();
for (int foreign_key_itr = 0; foreign_key_itr < foreign_key_count;
foreign_key_itr++) {
auto foreign_key = table->GetForeignKey(foreign_key_itr);
auto sink_table_oid = foreign_key->GetSinkTableOid();
auto sink_table = database.GetTableWithOid(sink_table_oid);
auto sink_table_schema = sink_table->GetSchema();
std::cout << "table name : " << sink_table->GetName() << " "
<< *sink_table_schema << std::endl;
}
}
}
}
os << "=====================================================\n";
return os;
}
} // End storage namespace
} // End peloton namespace
<|endoftext|> |
<commit_before>#include "caffe2/core/common_cudnn.h"
#include "caffe2/core/context_gpu.h"
#include "caffe2/core/operator.h"
#include "caffe2/core/types.h"
namespace caffe2 {
namespace {
// Round up N to nearest multiple of A.
size_t roundUp(size_t n, size_t a) {
return n + ((-n % a) + a) % a;
}
constexpr size_t alignmentBytes = 128;
// Returns the index into mask_and_states where states_data begins.
// Ensures that states_data is properly aligned.
template <typename T>
size_t firstElementForStates(size_t mask_bytes) {
return roundUp(mask_bytes, alignmentBytes) / sizeof(T);
}
// Calculate the required size of the tensor which holds the data for both
// "reserveSpace" (mask) and "states" (RNG states).
template <typename T>
vector<size_t> sizeForMaskAndStates(
size_t mask_bytes, size_t states_bytes) {
return vector<size_t>{firstElementForStates<T>(mask_bytes) +
(roundUp(states_bytes, sizeof(T)) / sizeof(T))};
}
}
class CuDNNDropoutOp final : public Operator<CUDAContext> {
public:
USE_OPERATOR_FUNCTIONS(CUDAContext);
CuDNNDropoutOp(const OperatorDef& operator_def, Workspace* ws)
: Operator<CUDAContext>(operator_def, ws),
cudnn_wrapper_(&context_),
ratio_(OperatorBase::GetSingleArgument<float>("ratio", 0.5)),
is_test_(OperatorBase::GetSingleArgument<int>("is_test", 0)) {
CAFFE_ENFORCE_GE(ratio_, 0);
CAFFE_ENFORCE_LT(ratio_, 1);
CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&data_desc_));
CUDNN_ENFORCE(cudnnCreateDropoutDescriptor(&dropout_desc_));
CUDNN_ENFORCE(cudnnDropoutGetStatesSize(
cudnn_wrapper_.inline_cudnn_handle(),
reinterpret_cast<size_t*>(&states_size_in_bytes_)));
}
~CuDNNDropoutOp() noexcept {
CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(data_desc_));
CUDNN_ENFORCE(cudnnDestroyDropoutDescriptor(dropout_desc_));
}
template <typename T, typename M>
bool DoRunWithType();
bool RunOnDevice() override;
protected:
CuDNNWrapper cudnn_wrapper_;
cudnnTensorDescriptor_t data_desc_;
cudnnDropoutDescriptor_t dropout_desc_;
vector<TIndex> cudnn_input_dims_;
float ratio_;
bool is_test_;
size_t states_size_in_bytes_, reserve_space_size_in_bytes_;
// Input: X, Output: Y, mask_and_states
};
class CuDNNDropoutGradientOp final : public Operator<CUDAContext> {
public:
USE_OPERATOR_FUNCTIONS(CUDAContext);
CuDNNDropoutGradientOp(const OperatorDef& operator_def, Workspace* ws)
: Operator<CUDAContext>(operator_def, ws),
cudnn_wrapper_(&context_),
ratio_(OperatorBase::GetSingleArgument<float>("ratio", 0.5)),
is_test_(OperatorBase::GetSingleArgument<int>("is_test", 0)) {
CAFFE_ENFORCE_GE(ratio_, 0);
CAFFE_ENFORCE_LT(ratio_, 1);
CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&data_desc_));
CUDNN_ENFORCE(cudnnCreateDropoutDescriptor(&dropout_desc_));
CUDNN_ENFORCE(cudnnDropoutGetStatesSize(
cudnn_wrapper_.inline_cudnn_handle(),
reinterpret_cast<size_t*>(&states_size_in_bytes_)));
}
~CuDNNDropoutGradientOp() noexcept {
CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(data_desc_));
CUDNN_ENFORCE(cudnnDestroyDropoutDescriptor(dropout_desc_));
}
template <typename T, typename M>
bool DoRunWithType();
bool RunOnDevice() override;
protected:
CuDNNWrapper cudnn_wrapper_;
cudnnTensorDescriptor_t data_desc_;
cudnnDropoutDescriptor_t dropout_desc_;
vector<TIndex> cudnn_input_dims_;
float ratio_;
bool is_test_;
size_t states_size_in_bytes_, reserve_space_size_in_bytes_;
// Input: dY, mask_and_states, Output: dX
};
template <typename T, typename M>
bool CuDNNDropoutOp::DoRunWithType() {
const auto& X = Input(0);
auto* Y = Output(0);
auto* mask_and_states = Output(1);
auto size_prod = 1;
for (auto dim : X.dims()) {
size_prod *= dim;
}
// Reshape tensor descriptors if necessary
if (X.dims() != cudnn_input_dims_) {
VLOG(1) << "Setting descriptors";
cudnn_input_dims_ = X.dims();
CUDNN_ENFORCE(cudnnSetTensor4dDescriptor(
data_desc_,
GetCudnnTensorFormat(StorageOrder::NCHW),
cudnnTypeWrapper<T>::type,
size_prod,
1,
1,
1));
// get the reserve space we need
CUDNN_ENFORCE(cudnnDropoutGetReserveSpaceSize(
data_desc_, &reserve_space_size_in_bytes_));
// resize the output to hold both mask and states
mask_and_states->Resize(sizeForMaskAndStates<T>(
reserve_space_size_in_bytes_, states_size_in_bytes_));
// get location of states data in mask_and_states
T* states_data = mask_and_states->template mutable_data<T>() +
firstElementForStates<T>(reserve_space_size_in_bytes_);
// set the dropout descriptor
CUDNN_ENFORCE(cudnnSetDropoutDescriptor(
dropout_desc_,
cudnn_wrapper_.inline_cudnn_handle(),
ratio_,
states_data,
states_size_in_bytes_,
0 // seed
));
}
// now actually run the computation
if (is_test_) {
if (Y != &X) {
context_.Copy<T, CUDAContext, CUDAContext>(
X.size(), X.template data<T>(), Y->template mutable_data<T>());
}
return true;
} else {
CUDNN_ENFORCE(cudnnDropoutForward(
cudnn_wrapper_.inline_cudnn_handle(),
dropout_desc_,
data_desc_,
X.template data<T>(),
data_desc_,
Y->template mutable_data<T>(),
mask_and_states->raw_mutable_data(),
reserve_space_size_in_bytes_));
}
return true;
}
bool CuDNNDropoutOp::RunOnDevice() {
// dispatch based on contents of tensor(s)
const auto& X = Input(0);
auto* Y = Output(0);
Y->ResizeLike(X);
if (X.IsType<float>()) {
return DoRunWithType<float, float>();
} else if (X.IsType<float16>()) {
return DoRunWithType<float16, float>();
}
return false;
}
template <typename T, typename M>
bool CuDNNDropoutGradientOp::DoRunWithType() {
const auto& dY = Input(0);
const auto& mask_and_states = Input(1);
auto* dX = Output(0);
auto size_prod = 1;
for (auto dim : dY.dims()) {
size_prod *= dim;
}
if (dY.dims() != cudnn_input_dims_) {
cudnn_input_dims_ = dY.dims();
CUDNN_ENFORCE(cudnnSetTensor4dDescriptor(
data_desc_,
GetCudnnTensorFormat(StorageOrder::NCHW),
cudnnTypeWrapper<T>::type,
size_prod,
1,
1,
1));
// get the reserve space we need
CUDNN_ENFORCE(cudnnDropoutGetReserveSpaceSize(
data_desc_, &reserve_space_size_in_bytes_));
// get location of states data in mask_and_states
T* states_data = const_cast<T*>(
mask_and_states.template data<T>() +
firstElementForStates<T>(reserve_space_size_in_bytes_));
// set the dropout descriptor
CUDNN_ENFORCE(cudnnSetDropoutDescriptor(
dropout_desc_,
cudnn_wrapper_.inline_cudnn_handle(),
ratio_,
states_data,
states_size_in_bytes_,
0 // seed
));
}
// run the computation
void* mask_data = const_cast<void*>(mask_and_states.raw_data());
CUDNN_ENFORCE(cudnnDropoutBackward(
cudnn_wrapper_.inline_cudnn_handle(),
dropout_desc_,
data_desc_,
dY.data<T>(),
data_desc_,
dX->template mutable_data<T>(),
mask_data,
reserve_space_size_in_bytes_));
return true;
}
bool CuDNNDropoutGradientOp::RunOnDevice() {
// dispatch based on contents of tensor(s)
const auto& dY = Input(0);
const auto& states = Input(1);
auto* dX = Output(0);
dX->ResizeLike(dY);
if (dY.IsType<float>()) {
return DoRunWithType<float, float>();
} else if (dY.IsType<float16>()) {
return DoRunWithType<float16, float>();
}
return false;
}
namespace {
REGISTER_CUDNN_OPERATOR(Dropout, CuDNNDropoutOp);
REGISTER_CUDNN_OPERATOR(DropoutGrad, CuDNNDropoutGradientOp);
}
}; // namespace caffe2
<commit_msg>protect cudnnSetDropoutDescriptor with mutex<commit_after>#include "caffe2/core/common_cudnn.h"
#include "caffe2/core/context_gpu.h"
#include "caffe2/core/operator.h"
#include "caffe2/core/types.h"
namespace caffe2 {
namespace {
// Round up N to nearest multiple of A.
size_t roundUp(size_t n, size_t a) {
return n + ((-n % a) + a) % a;
}
constexpr size_t alignmentBytes = 128;
// Returns the index into mask_and_states where states_data begins.
// Ensures that states_data is properly aligned.
template <typename T>
size_t firstElementForStates(size_t mask_bytes) {
return roundUp(mask_bytes, alignmentBytes) / sizeof(T);
}
// Calculate the required size of the tensor which holds the data for both
// "reserveSpace" (mask) and "states" (RNG states).
template <typename T>
vector<size_t> sizeForMaskAndStates(
size_t mask_bytes, size_t states_bytes) {
return vector<size_t>{firstElementForStates<T>(mask_bytes) +
(roundUp(states_bytes, sizeof(T)) / sizeof(T))};
}
}
class CuDNNDropoutOp final : public Operator<CUDAContext> {
public:
USE_OPERATOR_FUNCTIONS(CUDAContext);
CuDNNDropoutOp(const OperatorDef& operator_def, Workspace* ws)
: Operator<CUDAContext>(operator_def, ws),
cudnn_wrapper_(&context_),
ratio_(OperatorBase::GetSingleArgument<float>("ratio", 0.5)),
is_test_(OperatorBase::GetSingleArgument<int>("is_test", 0)) {
CAFFE_ENFORCE_GE(ratio_, 0);
CAFFE_ENFORCE_LT(ratio_, 1);
CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&data_desc_));
CUDNN_ENFORCE(cudnnCreateDropoutDescriptor(&dropout_desc_));
CUDNN_ENFORCE(cudnnDropoutGetStatesSize(
cudnn_wrapper_.inline_cudnn_handle(),
reinterpret_cast<size_t*>(&states_size_in_bytes_)));
}
~CuDNNDropoutOp() noexcept {
CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(data_desc_));
CUDNN_ENFORCE(cudnnDestroyDropoutDescriptor(dropout_desc_));
}
template <typename T, typename M>
bool DoRunWithType();
bool RunOnDevice() override;
protected:
CuDNNWrapper cudnn_wrapper_;
cudnnTensorDescriptor_t data_desc_;
cudnnDropoutDescriptor_t dropout_desc_;
vector<TIndex> cudnn_input_dims_;
float ratio_;
bool is_test_;
size_t states_size_in_bytes_, reserve_space_size_in_bytes_;
// Input: X, Output: Y, mask_and_states
};
class CuDNNDropoutGradientOp final : public Operator<CUDAContext> {
public:
USE_OPERATOR_FUNCTIONS(CUDAContext);
CuDNNDropoutGradientOp(const OperatorDef& operator_def, Workspace* ws)
: Operator<CUDAContext>(operator_def, ws),
cudnn_wrapper_(&context_),
ratio_(OperatorBase::GetSingleArgument<float>("ratio", 0.5)),
is_test_(OperatorBase::GetSingleArgument<int>("is_test", 0)) {
CAFFE_ENFORCE_GE(ratio_, 0);
CAFFE_ENFORCE_LT(ratio_, 1);
CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&data_desc_));
CUDNN_ENFORCE(cudnnCreateDropoutDescriptor(&dropout_desc_));
CUDNN_ENFORCE(cudnnDropoutGetStatesSize(
cudnn_wrapper_.inline_cudnn_handle(),
reinterpret_cast<size_t*>(&states_size_in_bytes_)));
}
~CuDNNDropoutGradientOp() noexcept {
CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(data_desc_));
CUDNN_ENFORCE(cudnnDestroyDropoutDescriptor(dropout_desc_));
}
template <typename T, typename M>
bool DoRunWithType();
bool RunOnDevice() override;
protected:
CuDNNWrapper cudnn_wrapper_;
cudnnTensorDescriptor_t data_desc_;
cudnnDropoutDescriptor_t dropout_desc_;
vector<TIndex> cudnn_input_dims_;
float ratio_;
bool is_test_;
size_t states_size_in_bytes_, reserve_space_size_in_bytes_;
// Input: dY, mask_and_states, Output: dX
};
template <typename T, typename M>
bool CuDNNDropoutOp::DoRunWithType() {
const auto& X = Input(0);
auto* Y = Output(0);
auto* mask_and_states = Output(1);
auto size_prod = 1;
for (auto dim : X.dims()) {
size_prod *= dim;
}
// Reshape tensor descriptors if necessary
if (X.dims() != cudnn_input_dims_) {
VLOG(1) << "Setting descriptors";
cudnn_input_dims_ = X.dims();
CUDNN_ENFORCE(cudnnSetTensor4dDescriptor(
data_desc_,
GetCudnnTensorFormat(StorageOrder::NCHW),
cudnnTypeWrapper<T>::type,
size_prod,
1,
1,
1));
// get the reserve space we need
CUDNN_ENFORCE(cudnnDropoutGetReserveSpaceSize(
data_desc_, &reserve_space_size_in_bytes_));
// resize the output to hold both mask and states
mask_and_states->Resize(sizeForMaskAndStates<T>(
reserve_space_size_in_bytes_, states_size_in_bytes_));
// get location of states data in mask_and_states
T* states_data = mask_and_states->template mutable_data<T>() +
firstElementForStates<T>(reserve_space_size_in_bytes_);
// set the dropout descriptor
{
// Need to protect as clashes with NCCL
std::lock_guard<std::mutex> lk(CUDAContext::mutex());
CUDNN_ENFORCE(cudnnSetDropoutDescriptor(
dropout_desc_,
cudnn_wrapper_.inline_cudnn_handle(),
ratio_,
states_data,
states_size_in_bytes_,
0 // seed
));
}
}
// now actually run the computation
if (is_test_) {
if (Y != &X) {
context_.Copy<T, CUDAContext, CUDAContext>(
X.size(), X.template data<T>(), Y->template mutable_data<T>());
}
return true;
} else {
CUDNN_ENFORCE(cudnnDropoutForward(
cudnn_wrapper_.inline_cudnn_handle(),
dropout_desc_,
data_desc_,
X.template data<T>(),
data_desc_,
Y->template mutable_data<T>(),
mask_and_states->raw_mutable_data(),
reserve_space_size_in_bytes_));
}
return true;
}
bool CuDNNDropoutOp::RunOnDevice() {
// dispatch based on contents of tensor(s)
const auto& X = Input(0);
auto* Y = Output(0);
Y->ResizeLike(X);
if (X.IsType<float>()) {
return DoRunWithType<float, float>();
} else if (X.IsType<float16>()) {
return DoRunWithType<float16, float>();
}
return false;
}
template <typename T, typename M>
bool CuDNNDropoutGradientOp::DoRunWithType() {
const auto& dY = Input(0);
const auto& mask_and_states = Input(1);
auto* dX = Output(0);
auto size_prod = 1;
for (auto dim : dY.dims()) {
size_prod *= dim;
}
if (dY.dims() != cudnn_input_dims_) {
cudnn_input_dims_ = dY.dims();
CUDNN_ENFORCE(cudnnSetTensor4dDescriptor(
data_desc_,
GetCudnnTensorFormat(StorageOrder::NCHW),
cudnnTypeWrapper<T>::type,
size_prod,
1,
1,
1));
// get the reserve space we need
CUDNN_ENFORCE(cudnnDropoutGetReserveSpaceSize(
data_desc_, &reserve_space_size_in_bytes_));
// get location of states data in mask_and_states
T* states_data = const_cast<T*>(
mask_and_states.template data<T>() +
firstElementForStates<T>(reserve_space_size_in_bytes_));
// set the dropout descriptor
{
// Need to protect as clashes with NCCL
std::lock_guard<std::mutex> lk(CUDAContext::mutex());
CUDNN_ENFORCE(cudnnSetDropoutDescriptor(
dropout_desc_,
cudnn_wrapper_.inline_cudnn_handle(),
ratio_,
states_data,
states_size_in_bytes_,
0 // seed
));
}
}
// run the computation
void* mask_data = const_cast<void*>(mask_and_states.raw_data());
CUDNN_ENFORCE(cudnnDropoutBackward(
cudnn_wrapper_.inline_cudnn_handle(),
dropout_desc_,
data_desc_,
dY.data<T>(),
data_desc_,
dX->template mutable_data<T>(),
mask_data,
reserve_space_size_in_bytes_));
return true;
}
bool CuDNNDropoutGradientOp::RunOnDevice() {
// dispatch based on contents of tensor(s)
const auto& dY = Input(0);
const auto& states = Input(1);
auto* dX = Output(0);
dX->ResizeLike(dY);
if (dY.IsType<float>()) {
return DoRunWithType<float, float>();
} else if (dY.IsType<float16>()) {
return DoRunWithType<float16, float>();
}
return false;
}
namespace {
REGISTER_CUDNN_OPERATOR(Dropout, CuDNNDropoutOp);
REGISTER_CUDNN_OPERATOR(DropoutGrad, CuDNNDropoutGradientOp);
}
}; // namespace caffe2
<|endoftext|> |
<commit_before>#include <cgreen/internal/cpp_assertions.h>
#include <cgreen/constraint.h>
#include <stdint.h>
#include <string.h>
#include <string>
namespace cgreen {
void assert_that_(const char *file, int line, const char *actual_string,
const std::string& actual, Constraint* constraint) {
// if they are using a string constraint, they are almost certainly meaning to do a deep comparison
if (is_string_comparing(constraint)) {
assert_that_(file, line, actual_string, (intptr_t) (actual.c_str()),
constraint);
return;
}
assert_that_(file, line, actual_string, (const std::string *) (&actual),
constraint);
}
void assert_that_(const char *file, int line, const char *actual_string,
const std::string *actual, Constraint* constraint) {
// if they are using a string constraint, they are almost certainly meaning to do a deep comparison
if (is_string_comparing(constraint)) {
assert_that_(file, line, actual_string, (intptr_t) (actual->c_str()),
constraint);
return;
}
assert_that_(file, line, actual_string, (intptr_t) actual, constraint);
}
}
<commit_msg>Minor edit<commit_after>#include <cgreen/internal/cpp_assertions.h>
#include <cgreen/constraint.h>
#include <stdint.h>
#include <string.h>
#include <string>
namespace cgreen {
void assert_that_(const char *file, int line, const char *actual_string,
const std::string& actual, Constraint* constraint) {
// if they are using a string constraint, they are almost certainly meaning to do a deep comparison
if (is_string_comparing(constraint)) {
assert_that_(file, line, actual_string, (intptr_t) (actual.c_str()),
constraint);
return;
}
assert_that_(file, line, actual_string, (const std::string *) (&actual), constraint);
}
void assert_that_(const char *file, int line, const char *actual_string,
const std::string *actual, Constraint* constraint) {
// if they are using a string constraint, they are almost certainly meaning to do a deep comparison
if (is_string_comparing(constraint)) {
assert_that_(file, line, actual_string, (intptr_t) (actual->c_str()),
constraint);
return;
}
assert_that_(file, line, actual_string, (intptr_t) actual, constraint);
}
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(DIRECTORY_ENUMERATOR_HEADER_GUARD_1357924680)
#define DIRECTORY_ENUMERATOR_HEADER_GUARD_1357924680
// Base header file. Must be first.
#include <PlatformSupport/PlatformSupportDefinitions.hpp>
#if defined(_MSC_VER)
#include <io.h>
#elif defined(__GNUC__)
#include <dirent.h>
#else
#error Unsupported platform!!!
#endif
#include <functional>
#include <iterator>
#include <vector>
#include <XalanDOM/XalanDOMString.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#if defined(_MSC_VER)
class FindFileStruct : public _wfinddata_t
{
enum eAttributes
{
eAttributeArchive = _A_ARCH,
eAttributeDirectory = _A_SUBDIR,
eAttributeHidden = _A_HIDDEN,
eAttributeNormal = _A_NORMAL,
eReadOnly = _A_RDONLY,
eSystem = _A_SYSTEM
};
public:
/**
* Retrieve name of file
*
* @return file name
*/
const XalanDOMChar*
getName() const
{
return name;
}
/**
* Determine whether file is a directory
*
* @return true if file is a directory
*/
bool
isDirectory() const
{
return attrib & eAttributeDirectory ? true : false;
}
};
#elif defined(__GNUC__)
class FindFileStruct : public dirent
{
public:
/**
* Retrieve name of file
*
* @return file name
*/
const char* getName() const
{
return d_name;
}
/**
* Determine whether file is a directory
*
* @return true if file is a directory
*/
bool isDirectory() const
{
return d_type == DT_DIR;
}
};
#else
#error Unsupported platform!!!
#endif
#if defined(XALAN_NO_NAMESPACES)
struct DirectoryFilterPredicate : public unary_function<FindFileStruct, bool>
#else
struct DirectoryFilterPredicate : public std::unary_function<FindFileStruct, bool>
#endif
{
result_type
operator()(const argument_type& theFindData) const
{
return theFindData.isDirectory();
}
};
#if defined(XALAN_NO_NAMESPACES)
struct FilesOnlyFilterPredicate : public unary_function<FindFileStruct, bool>
#else
struct FilesOnlyFilterPredicate : public std::unary_function<FindFileStruct, bool>
#endif
{
result_type
operator()(const argument_type& theFindData) const
{
DirectoryFilterPredicate theDirectoryPredicate;
return !theDirectoryPredicate(theFindData);
}
};
template<class OutputIteratorType,
class FilterPredicateType,
class StringType,
class StringConversionFunction>
void
EnumerateDirectory(
const StringType& theDirectory,
OutputIteratorType theOutputIterator,
FilterPredicateType theFilterPredicate,
StringConversionFunction theConversionFunction)
{
#if defined(_MSC_VER)
StringType theSearchSpec(clone(theDirectory));
theSearchSpec += "\\*";
FindFileStruct theFindData;
long theSearchHandle = _wfindfirst(const_cast<wchar_t*>(theConversionFunction(theSearchSpec)),
&theFindData);
if (theSearchHandle != -1)
{
try
{
do
{
if (theFilterPredicate(theFindData) == true)
{
*theOutputIterator = theFindData.getName();
}
}
while(_wfindnext(theSearchHandle,
&theFindData) == 0);
}
catch(...)
{
_findclose(theSearchHandle);
throw;
}
_findclose(theSearchHandle);
}
#elif defined(__GNUC__)
assert(false);
#else
#error Unsupported platform!!!
#endif
}
template<class CollectionType,
class FilterPredicateType = FilesOnlyFilterPredicate,
class StringType = XalanDOMString,
class StringConversionFunction = c_wstr_functor>
#if defined(XALAN_NO_NAMESPACES)
struct DirectoryEnumeratorFunctor : public unary_function<StringType, CollectionType>
#else
struct DirectoryEnumeratorFunctor : public std::unary_function<StringType, CollectionType>
#endif
{
result_type
operator()(const argument_type& theDirectory) const
{
result_type theCollection;
operator()(theDirectory,
theCollection);
return theCollection;
}
void
operator()(const argument_type& theDirectory,
CollectionType& theCollection) const
{
#if !defined(XALAN_NO_NAMESPACES)
using std::back_inserter;
#endif
EnumerateDirectory(theDirectory,
back_inserter(theCollection),
m_filterPredicate,
m_conversionFunction);
}
private:
FilterPredicateType m_filterPredicate;
StringConversionFunction m_conversionFunction;
};
#endif // DIRECTORY_ENUMERATOR_HEADER_GUARD_1357924680
<commit_msg>Rearranged some ifdefs.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(DIRECTORY_ENUMERATOR_HEADER_GUARD_1357924680)
#define DIRECTORY_ENUMERATOR_HEADER_GUARD_1357924680
// Base header file. Must be first.
#include <PlatformSupport/PlatformSupportDefinitions.hpp>
#if defined(_MSC_VER)
#include <io.h>
#else
#include <dirent.h>
#endif
#include <functional>
#include <iterator>
#include <vector>
#include <XalanDOM/XalanDOMString.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#if defined(_MSC_VER)
class FindFileStruct : public _wfinddata_t
{
enum eAttributes
{
eAttributeArchive = _A_ARCH,
eAttributeDirectory = _A_SUBDIR,
eAttributeHidden = _A_HIDDEN,
eAttributeNormal = _A_NORMAL,
eReadOnly = _A_RDONLY,
eSystem = _A_SYSTEM
};
public:
/**
* Retrieve name of file
*
* @return file name
*/
const XalanDOMChar*
getName() const
{
return name;
}
/**
* Determine whether file is a directory
*
* @return true if file is a directory
*/
bool
isDirectory() const
{
return attrib & eAttributeDirectory ? true : false;
}
};
#else
class FindFileStruct : public dirent
{
public:
/**
* Retrieve name of file
*
* @return file name
*/
const char* getName() const
{
return d_name;
}
/**
* Determine whether file is a directory
*
* @return true if file is a directory
*/
bool isDirectory() const
{
return d_type == DT_DIR;
}
};
#endif
#if defined(XALAN_NO_NAMESPACES)
struct DirectoryFilterPredicate : public unary_function<FindFileStruct, bool>
#else
struct DirectoryFilterPredicate : public std::unary_function<FindFileStruct, bool>
#endif
{
result_type
operator()(const argument_type& theFindData) const
{
return theFindData.isDirectory();
}
};
#if defined(XALAN_NO_NAMESPACES)
struct FilesOnlyFilterPredicate : public unary_function<FindFileStruct, bool>
#else
struct FilesOnlyFilterPredicate : public std::unary_function<FindFileStruct, bool>
#endif
{
result_type
operator()(const argument_type& theFindData) const
{
DirectoryFilterPredicate theDirectoryPredicate;
return !theDirectoryPredicate(theFindData);
}
};
template<class OutputIteratorType,
class FilterPredicateType,
class StringType,
class StringConversionFunction>
void
EnumerateDirectory(
const StringType& theDirectory,
OutputIteratorType theOutputIterator,
FilterPredicateType theFilterPredicate,
StringConversionFunction theConversionFunction)
{
#if defined(_MSC_VER)
StringType theSearchSpec(clone(theDirectory));
theSearchSpec += "\\*";
FindFileStruct theFindData;
long theSearchHandle = _wfindfirst(const_cast<wchar_t*>(theConversionFunction(theSearchSpec)),
&theFindData);
if (theSearchHandle != -1)
{
try
{
do
{
if (theFilterPredicate(theFindData) == true)
{
*theOutputIterator = theFindData.getName();
}
}
while(_wfindnext(theSearchHandle,
&theFindData) == 0);
}
catch(...)
{
_findclose(theSearchHandle);
throw;
}
_findclose(theSearchHandle);
}
#elif defined(__GNUC__)
assert(false);
#else
#error Unsupported platform!!!
#endif
}
template<class CollectionType,
class FilterPredicateType = FilesOnlyFilterPredicate,
class StringType = XalanDOMString,
class StringConversionFunction = c_wstr_functor>
#if defined(XALAN_NO_NAMESPACES)
struct DirectoryEnumeratorFunctor : public unary_function<StringType, CollectionType>
#else
struct DirectoryEnumeratorFunctor : public std::unary_function<StringType, CollectionType>
#endif
{
result_type
operator()(const argument_type& theDirectory) const
{
result_type theCollection;
operator()(theDirectory,
theCollection);
return theCollection;
}
void
operator()(const argument_type& theDirectory,
CollectionType& theCollection) const
{
#if !defined(XALAN_NO_NAMESPACES)
using std::back_inserter;
#endif
EnumerateDirectory(theDirectory,
back_inserter(theCollection),
m_filterPredicate,
m_conversionFunction);
}
private:
FilterPredicateType m_filterPredicate;
StringConversionFunction m_conversionFunction;
};
#endif // DIRECTORY_ENUMERATOR_HEADER_GUARD_1357924680
<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2019 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#pragma once
#include <type_traits>
#include "caf/fwd.hpp"
namespace caf {
namespace mixin {
// TODO: legacy API. Deprecate with 0.18, remove with 0.19.
template <class T>
struct is_blocking_requester : std::false_type {};
} // namespace mixin
} // namespace caf
namespace caf {
// Note: having marker types for blocking and non-blocking may seem redundant,
// because an actor is either the one or the other. However, we cannot conclude
// that an actor is non-blocking if it does not have the blocking marker. Actor
// types such as `local_actor` have neither markers, because they are
// "incomplete", i.e., they serve as base type for both blocking and
// non-blocking actors. Hence, we need both markers even though they are
// mutually exclusive. The same reasoning applies to the dynamically vs.
// statically typed markers.
/// Marker type for dynamically typed actors.
struct dynamically_typed_actor_base {};
/// Marker type for statically typed actors.
struct statically_typed_actor_base {};
/// Marker type for blocking actors.
struct blocking_actor_base {};
/// Marker type for non-blocking actors.
struct non_blocking_actor_base {};
/// Default implementation of `actor_traits` for non-actors (SFINAE-friendly).
/// @relates actor_traits
template <class T, bool ExtendsAbstractActor>
struct default_actor_traits {
static constexpr bool is_dynamically_typed = false;
static constexpr bool is_statically_typed = false;
static constexpr bool is_blocking = false;
static constexpr bool is_non_blocking = false;
static constexpr bool is_incomplete = true;
};
/// Default implementation of `actor_traits` for regular actors.
/// @relates actor_traits
template <class T>
struct default_actor_traits<T, true> {
/// Denotes whether `T` is dynamically typed.
static constexpr bool is_dynamically_typed
= std::is_base_of<dynamically_typed_actor_base, T>::value;
/// Denotes whether `T` is statically typed.
static constexpr bool is_statically_typed
= std::is_base_of<statically_typed_actor_base, T>::value;
/// Denotes whether `T` is a blocking actor type.
static constexpr bool is_blocking
= std::is_base_of<blocking_actor_base, T>::value
|| mixin::is_blocking_requester<T>::value;
/// Denotes whether `T` is a non-blocking actor type.
static constexpr bool is_non_blocking
= std::is_base_of<non_blocking_actor_base, T>::value;
/// Denotes whether `T` is an incomplete actor type that misses one or more
/// markers.
static constexpr bool is_incomplete
= (!is_dynamically_typed && !is_statically_typed)
|| (!is_blocking && !is_non_blocking);
static_assert(!is_dynamically_typed || !is_statically_typed,
"an actor cannot be both statically and dynamically typed");
static_assert(!is_blocking || !is_non_blocking,
"an actor cannot be both blocking and non-blocking");
};
/// Provides uniform access to properties of actor types.
template <class T>
struct actor_traits
: default_actor_traits<T, std::is_base_of<abstract_actor, T>::value> {};
} // namespace caf
<commit_msg>Switch to nested namespace syntax<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2019 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#pragma once
#include <type_traits>
#include "caf/fwd.hpp"
namespace caf::mixin {
// TODO: legacy API. Deprecate with 0.18, remove with 0.19.
template <class T>
struct is_blocking_requester : std::false_type {};
} // namespace caf::mixin
namespace caf {
// Note: having marker types for blocking and non-blocking may seem redundant,
// because an actor is either the one or the other. However, we cannot conclude
// that an actor is non-blocking if it does not have the blocking marker. Actor
// types such as `local_actor` have neither markers, because they are
// "incomplete", i.e., they serve as base type for both blocking and
// non-blocking actors. Hence, we need both markers even though they are
// mutually exclusive. The same reasoning applies to the dynamically vs.
// statically typed markers.
/// Marker type for dynamically typed actors.
struct dynamically_typed_actor_base {};
/// Marker type for statically typed actors.
struct statically_typed_actor_base {};
/// Marker type for blocking actors.
struct blocking_actor_base {};
/// Marker type for non-blocking actors.
struct non_blocking_actor_base {};
/// Default implementation of `actor_traits` for non-actors (SFINAE-friendly).
/// @relates actor_traits
template <class T, bool ExtendsAbstractActor>
struct default_actor_traits {
static constexpr bool is_dynamically_typed = false;
static constexpr bool is_statically_typed = false;
static constexpr bool is_blocking = false;
static constexpr bool is_non_blocking = false;
static constexpr bool is_incomplete = true;
};
/// Default implementation of `actor_traits` for regular actors.
/// @relates actor_traits
template <class T>
struct default_actor_traits<T, true> {
/// Denotes whether `T` is dynamically typed.
static constexpr bool is_dynamically_typed
= std::is_base_of<dynamically_typed_actor_base, T>::value;
/// Denotes whether `T` is statically typed.
static constexpr bool is_statically_typed
= std::is_base_of<statically_typed_actor_base, T>::value;
/// Denotes whether `T` is a blocking actor type.
static constexpr bool is_blocking
= std::is_base_of<blocking_actor_base, T>::value
|| mixin::is_blocking_requester<T>::value;
/// Denotes whether `T` is a non-blocking actor type.
static constexpr bool is_non_blocking
= std::is_base_of<non_blocking_actor_base, T>::value;
/// Denotes whether `T` is an incomplete actor type that misses one or more
/// markers.
static constexpr bool is_incomplete
= (!is_dynamically_typed && !is_statically_typed)
|| (!is_blocking && !is_non_blocking);
static_assert(!is_dynamically_typed || !is_statically_typed,
"an actor cannot be both statically and dynamically typed");
static_assert(!is_blocking || !is_non_blocking,
"an actor cannot be both blocking and non-blocking");
};
/// Provides uniform access to properties of actor types.
template <class T>
struct actor_traits
: default_actor_traits<T, std::is_base_of<abstract_actor, T>::value> {};
} // namespace caf
<|endoftext|> |
<commit_before>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
* Copyright (c) 2010 Ruslan Kabatsayev <b7.10110111@gmail.com>
*
* 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.
*
* 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 "oxygenscrolledwindowdata.h"
#include "../oxygengtkutils.h"
#include "../config.h"
#include <cassert>
#include <iostream>
namespace Oxygen
{
//_____________________________________________
void ScrolledWindowData::connect( GtkWidget* widget )
{
assert( GTK_IS_SCROLLED_WINDOW( widget ) );
assert( !_target );
// store target
_target = widget;
// check child
GtkWidget* child( gtk_bin_get_child( GTK_BIN( widget ) ) );
#if OXYGEN_DEBUG
std::cout
<< "Oxygen::ScrolledWindowData::connect -"
<< " child: " << child << " (" << G_OBJECT_TYPE_NAME( child ) << ")"
<< std::endl;
#endif
if( GTK_IS_TREE_VIEW( child ) )
{
registerChild( child );
} else {
// list widget types for which scrolled window needs register
static const char* widgetTypes[] = { "ExoIconView", "GeditView", "FMIconContainer", 0L };
for( unsigned int i = 0; widgetTypes[i]; i++ )
{
if( Gtk::gtk_object_is_a( G_OBJECT( child ), widgetTypes[i] ) )
{
registerChild( child );
break;
}
}
}
}
//_____________________________________________
void ScrolledWindowData::disconnect( GtkWidget* widget )
{
_target = 0;
for( ChildDataMap::iterator iter = _childrenData.begin(); iter != _childrenData.end(); iter++ )
{ iter->second.disconnect( iter->first ); }
_childrenData.clear();
}
//________________________________________________________________________________
void ScrolledWindowData::setHovered( GtkWidget* widget, bool value )
{
bool oldHover( hovered() );
ChildDataMap::iterator iter( _childrenData.find( widget ) );
if( iter != _childrenData.end() ) iter->second._hovered = value;
else return;
// need to schedule repaint of the whole widget
if( oldHover != hovered() && _target ) gtk_widget_queue_draw( _target );
}
//________________________________________________________________________________
void ScrolledWindowData::setFocused( GtkWidget* widget, bool value )
{
bool oldFocus( focused() );
ChildDataMap::iterator iter( _childrenData.find( widget ) );
if( iter != _childrenData.end() ) iter->second._focused = value;
else return;
// need to schedule repaint of the whole widget
if( oldFocus != focused() && _target ) gtk_widget_queue_draw( _target );
}
//_____________________________________________
void ScrolledWindowData::registerChild( GtkWidget* widget )
{
// make sure widget is not already in map
if( _childrenData.find( widget ) == _childrenData.end() )
{
#if OXYGEN_DEBUG
std::cout
<< "Oxygen::ScrolledWindowData::registerChild -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
// adjust event mask
gtk_widget_add_events( widget, GDK_ENTER_NOTIFY_MASK|GDK_LEAVE_NOTIFY_MASK );
// allocate new Hover data
ChildData data;
data._destroyId.connect( G_OBJECT(widget), "destroy", G_CALLBACK( childDestroyNotifyEvent ), this );
data._styleChangeId.connect( G_OBJECT(widget), "style-set", G_CALLBACK( childStyleChangeNotifyEvent ), this );
data._enterId.connect( G_OBJECT(widget), "enter-notify-event", G_CALLBACK( enterNotifyEvent ), this );
data._leaveId.connect( G_OBJECT(widget), "leave-notify-event", G_CALLBACK( leaveNotifyEvent ), this );
data._focusInId.connect( G_OBJECT(widget), "focus-in-event", G_CALLBACK( focusInNotifyEvent ), this );
data._focusOutId.connect( G_OBJECT(widget), "focus-out-event", G_CALLBACK( focusOutNotifyEvent ), this );
// and insert in map
_childrenData.insert( std::make_pair( widget, data ) );
// set initial focus
setFocused( widget, gtk_widget_has_focus( widget ) );
// set initial hover
const bool enabled( gtk_widget_get_state( widget ) != GTK_STATE_INSENSITIVE );
// on connection, needs to check whether mouse pointer is in widget or not
// to have the proper initial value of the hover flag
if( enabled )
{
gint xPointer,yPointer;
gdk_window_get_pointer(widget->window,&xPointer,&yPointer, 0L);
GdkRectangle rect = { 0, 0, widget->allocation.width, widget->allocation.height };
setHovered( widget, Gtk::gdk_rectangle_contains( &rect, xPointer, yPointer ) );
}
}
}
//________________________________________________________________________________
void ScrolledWindowData::unregisterChild( GtkWidget* widget )
{
// loopup in hover map
ChildDataMap::iterator iter( _childrenData.find( widget ) );
if( iter == _childrenData.end() ) return;
#if OXYGEN_DEBUG
std::cout
<< "Oxygen::ScrolledWindowData::unregisterChild -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
iter->second.disconnect( widget );
_childrenData.erase( iter );
}
//________________________________________________________________________________
#if OXYGEN_DEBUG
void ScrolledWindowData::ChildData::disconnect( GtkWidget* widget )
#else
void ScrolledWindowData::ChildData::disconnect( GtkWidget* )
#endif
{
#if OXYGEN_DEBUG
std::cout
<< "Oxygen::ScrolledWindowData::ChildData::disconnect -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
_destroyId.disconnect();
_styleChangeId.disconnect();
_enterId.disconnect();
_leaveId.disconnect();
_focusInId.disconnect();
_focusOutId.disconnect();
_hovered = false;
_focused = false;
}
//____________________________________________________________________________________________
gboolean ScrolledWindowData::childDestroyNotifyEvent( GtkWidget* widget, gpointer data )
{
#if OXYGEN_DEBUG
std::cout
<< "Oxygen::ScrolledWindowData::childDestroyNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
static_cast<ScrolledWindowData*>(data)->unregisterChild( widget );
return FALSE;
}
//____________________________________________________________________________________________
void ScrolledWindowData::childStyleChangeNotifyEvent( GtkWidget* widget, GtkStyle*, gpointer data )
{ static_cast<ScrolledWindowData*>(data)->unregisterChild( widget ); }
//________________________________________________________________________________
gboolean ScrolledWindowData::enterNotifyEvent( GtkWidget* widget, GdkEventCrossing*, gpointer data )
{
#if OXYGEN_DEBUG
std::cout << "Oxygen::ScrolledWindowData::enterNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
static_cast<ScrolledWindowData*>( data )->setHovered( widget, true );
return FALSE;
}
//________________________________________________________________________________
gboolean ScrolledWindowData::leaveNotifyEvent( GtkWidget* widget, GdkEventCrossing*, gpointer data )
{
#if OXYGEN_DEBUG
std::cout << "Oxygen::ScrolledWindowData::leaveNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
static_cast<ScrolledWindowData*>( data )->setHovered( widget, false );
return FALSE;
}
//________________________________________________________________________________
gboolean ScrolledWindowData::focusInNotifyEvent( GtkWidget* widget, GdkEvent*, gpointer data )
{
#if OXYGEN_DEBUG
std::cout << "Oxygen::ScrolledWindowData::focusInNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
static_cast<ScrolledWindowData*>( data )->setFocused( widget, true );
return FALSE;
}
//________________________________________________________________________________
gboolean ScrolledWindowData::focusOutNotifyEvent( GtkWidget* widget, GdkEvent*, gpointer data )
{
#if OXYGEN_DEBUG
std::cout << "Oxygen::ScrolledWindowData::focusOutNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
static_cast<ScrolledWindowData*>( data )->setFocused( widget, false );
return FALSE;
}
}
<commit_msg>Do not add ENTER/LEAVE event mask to scrolledwindowdata children if is treeview, because it is not necessary.<commit_after>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
* Copyright (c) 2010 Ruslan Kabatsayev <b7.10110111@gmail.com>
*
* 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.
*
* 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 "oxygenscrolledwindowdata.h"
#include "../oxygengtkutils.h"
#include "../config.h"
#include <cassert>
#include <iostream>
namespace Oxygen
{
//_____________________________________________
void ScrolledWindowData::connect( GtkWidget* widget )
{
assert( GTK_IS_SCROLLED_WINDOW( widget ) );
assert( !_target );
// store target
_target = widget;
// check child
GtkWidget* child( gtk_bin_get_child( GTK_BIN( widget ) ) );
#if OXYGEN_DEBUG
std::cout
<< "Oxygen::ScrolledWindowData::connect -"
<< " child: " << child << " (" << G_OBJECT_TYPE_NAME( child ) << ")"
<< std::endl;
#endif
if( GTK_IS_TREE_VIEW( child ) )
{
registerChild( child );
} else {
// list widget types for which scrolled window needs register
static const char* widgetTypes[] = { "ExoIconView", "GeditView", "FMIconContainer", 0L };
for( unsigned int i = 0; widgetTypes[i]; i++ )
{
if( Gtk::gtk_object_is_a( G_OBJECT( child ), widgetTypes[i] ) )
{
registerChild( child );
break;
}
}
}
}
//_____________________________________________
void ScrolledWindowData::disconnect( GtkWidget* widget )
{
_target = 0;
for( ChildDataMap::iterator iter = _childrenData.begin(); iter != _childrenData.end(); iter++ )
{ iter->second.disconnect( iter->first ); }
_childrenData.clear();
}
//________________________________________________________________________________
void ScrolledWindowData::setHovered( GtkWidget* widget, bool value )
{
bool oldHover( hovered() );
ChildDataMap::iterator iter( _childrenData.find( widget ) );
if( iter != _childrenData.end() ) iter->second._hovered = value;
else return;
// need to schedule repaint of the whole widget
if( oldHover != hovered() && _target ) gtk_widget_queue_draw( _target );
}
//________________________________________________________________________________
void ScrolledWindowData::setFocused( GtkWidget* widget, bool value )
{
bool oldFocus( focused() );
ChildDataMap::iterator iter( _childrenData.find( widget ) );
if( iter != _childrenData.end() ) iter->second._focused = value;
else return;
// need to schedule repaint of the whole widget
if( oldFocus != focused() && _target ) gtk_widget_queue_draw( _target );
}
//_____________________________________________
void ScrolledWindowData::registerChild( GtkWidget* widget )
{
// make sure widget is not already in map
if( _childrenData.find( widget ) == _childrenData.end() )
{
#if OXYGEN_DEBUG
std::cout
<< "Oxygen::ScrolledWindowData::registerChild -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
// adjust event mask
if( !GTK_IS_TREE_VIEW( widget ) )
{ gtk_widget_add_events( widget, GDK_ENTER_NOTIFY_MASK|GDK_LEAVE_NOTIFY_MASK ); }
// allocate new Hover data
ChildData data;
data._destroyId.connect( G_OBJECT(widget), "destroy", G_CALLBACK( childDestroyNotifyEvent ), this );
data._styleChangeId.connect( G_OBJECT(widget), "style-set", G_CALLBACK( childStyleChangeNotifyEvent ), this );
data._enterId.connect( G_OBJECT(widget), "enter-notify-event", G_CALLBACK( enterNotifyEvent ), this );
data._leaveId.connect( G_OBJECT(widget), "leave-notify-event", G_CALLBACK( leaveNotifyEvent ), this );
data._focusInId.connect( G_OBJECT(widget), "focus-in-event", G_CALLBACK( focusInNotifyEvent ), this );
data._focusOutId.connect( G_OBJECT(widget), "focus-out-event", G_CALLBACK( focusOutNotifyEvent ), this );
// and insert in map
_childrenData.insert( std::make_pair( widget, data ) );
// set initial focus
setFocused( widget, gtk_widget_has_focus( widget ) );
// set initial hover
const bool enabled( gtk_widget_get_state( widget ) != GTK_STATE_INSENSITIVE );
// on connection, needs to check whether mouse pointer is in widget or not
// to have the proper initial value of the hover flag
if( enabled )
{
gint xPointer,yPointer;
gdk_window_get_pointer(widget->window,&xPointer,&yPointer, 0L);
GdkRectangle rect = { 0, 0, widget->allocation.width, widget->allocation.height };
setHovered( widget, Gtk::gdk_rectangle_contains( &rect, xPointer, yPointer ) );
}
}
}
//________________________________________________________________________________
void ScrolledWindowData::unregisterChild( GtkWidget* widget )
{
// loopup in hover map
ChildDataMap::iterator iter( _childrenData.find( widget ) );
if( iter == _childrenData.end() ) return;
#if OXYGEN_DEBUG
std::cout
<< "Oxygen::ScrolledWindowData::unregisterChild -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
iter->second.disconnect( widget );
_childrenData.erase( iter );
}
//________________________________________________________________________________
#if OXYGEN_DEBUG
void ScrolledWindowData::ChildData::disconnect( GtkWidget* widget )
#else
void ScrolledWindowData::ChildData::disconnect( GtkWidget* )
#endif
{
#if OXYGEN_DEBUG
std::cout
<< "Oxygen::ScrolledWindowData::ChildData::disconnect -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
_destroyId.disconnect();
_styleChangeId.disconnect();
_enterId.disconnect();
_leaveId.disconnect();
_focusInId.disconnect();
_focusOutId.disconnect();
_hovered = false;
_focused = false;
}
//____________________________________________________________________________________________
gboolean ScrolledWindowData::childDestroyNotifyEvent( GtkWidget* widget, gpointer data )
{
#if OXYGEN_DEBUG
std::cout
<< "Oxygen::ScrolledWindowData::childDestroyNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
static_cast<ScrolledWindowData*>(data)->unregisterChild( widget );
return FALSE;
}
//____________________________________________________________________________________________
void ScrolledWindowData::childStyleChangeNotifyEvent( GtkWidget* widget, GtkStyle*, gpointer data )
{ static_cast<ScrolledWindowData*>(data)->unregisterChild( widget ); }
//________________________________________________________________________________
gboolean ScrolledWindowData::enterNotifyEvent( GtkWidget* widget, GdkEventCrossing*, gpointer data )
{
#if OXYGEN_DEBUG
std::cout << "Oxygen::ScrolledWindowData::enterNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
static_cast<ScrolledWindowData*>( data )->setHovered( widget, true );
return FALSE;
}
//________________________________________________________________________________
gboolean ScrolledWindowData::leaveNotifyEvent( GtkWidget* widget, GdkEventCrossing*, gpointer data )
{
#if OXYGEN_DEBUG
std::cout << "Oxygen::ScrolledWindowData::leaveNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
static_cast<ScrolledWindowData*>( data )->setHovered( widget, false );
return FALSE;
}
//________________________________________________________________________________
gboolean ScrolledWindowData::focusInNotifyEvent( GtkWidget* widget, GdkEvent*, gpointer data )
{
#if OXYGEN_DEBUG
std::cout << "Oxygen::ScrolledWindowData::focusInNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
static_cast<ScrolledWindowData*>( data )->setFocused( widget, true );
return FALSE;
}
//________________________________________________________________________________
gboolean ScrolledWindowData::focusOutNotifyEvent( GtkWidget* widget, GdkEvent*, gpointer data )
{
#if OXYGEN_DEBUG
std::cout << "Oxygen::ScrolledWindowData::focusOutNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
static_cast<ScrolledWindowData*>( data )->setFocused( widget, false );
return FALSE;
}
}
<|endoftext|> |
<commit_before>#pragma once
#include "type.hpp"
#include "error.hpp"
#define BOOST_PP_VARIADICS 1
#include <boost/preprocessor.hpp>
namespace spn {
template <class... Ts>
struct ValueHolder {
template <class T2>
void ref(T2*) {}
template <class T2>
void cref(T2*) const {}
};
template <class T, class... Ts>
struct ValueHolder<T, Ts...> : ValueHolder<Ts...> {
using base = ValueHolder<Ts...>;
using value_type = typename T::value_type;
value_type value;
value_type& ref(T*) { return value; }
const value_type& cref(T*) const { return value; }
template <class T2>
auto ref(T2* p) -> decltype(base::ref(p)) {
return base::ref(p); }
template <class T2>
auto cref(T2* p) const -> decltype(base::cref(p)) {
return base::cref(p); }
};
//! キャッシュ変数の自動管理クラス
template <class Class, class... Ts>
class RFlag : public ValueHolder<Ts...> {
public:
using FlagValue = uint32_t;
private:
using base = ValueHolder<Ts...>;
using ct_base = spn::CType<Ts...>;
template <class T>
static T* _GetNull() { return reinterpret_cast<T*>(0); }
mutable FlagValue _rflag = All();
//! integral_constantの値がtrueなら引数テンプレートのOr()を返す
template <class T0>
static constexpr FlagValue _Add_If(std::integral_constant<bool,false>) { return 0; }
template <class T0>
static constexpr FlagValue _Add_If(std::integral_constant<bool,true>) { return OrLH<T0>(); }
template <class T, int N>
static constexpr FlagValue _IterateLH(std::integral_constant<int,N>) {
using T0 = typename ct_base::template At<N>::type;
using T0Has = typename T0::template Has<T>;
return _Add_If<T0>(T0Has()) |
_IterateLH<T>(std::integral_constant<int,N+1>());
}
template <class T>
static constexpr FlagValue _IterateLH(std::integral_constant<int,ct_base::size>) { return 0; }
template <class T, int N>
static constexpr FlagValue _IterateHL(std::integral_constant<int,N>) {
using T0 = typename T::template At<N>::type;
return OrHL<T0>() | _IterateHL<T>(std::integral_constant<int,N-1>());
}
template <class T>
static constexpr FlagValue _IterateHL(std::integral_constant<int,-1>) { return 0; }
template <class T>
auto _refresh(const Class* self) const -> decltype(base::cref(_GetNull<T>())) {
const base* ptrC = this;
base* ptr = const_cast<base*>(ptrC);
_rflag &= ~(self->_refresh(ptr->ref(_GetNull<T>()), _GetNull<T>()));
_rflag &= ~Get<T>();
AssertP(Trap, !(_rflag & OrHL<T>()), "refresh flag was not cleared correctly")
return ptrC->cref(_GetNull<T>());
}
template <class TA>
static constexpr FlagValue _GetSingle() {
return 1 << ct_base::template Find<TA>::result;
}
template <class... TsA>
static constexpr FlagValue _Sum(std::integral_constant<int,0>) { return 0; }
template <class TA, class... TsA, int N>
static constexpr FlagValue _Sum(std::integral_constant<int,N>) {
return _GetSingle<TA>() | _Sum<TsA...>(std::integral_constant<int,N-1>());
}
template <class... TsA>
void _setFlag(std::integral_constant<int,0>) {}
template <class T, class... TsA, int N>
void _setFlag(std::integral_constant<int,N>) {
// 自分以下の階層はフラグを下ろす
_rflag &= ~OrHL<T>();
// 自分の階層より上の変数は全てフラグを立てる
_rflag |= OrLH<T>() & ~Get<T>();
_setFlag<TsA...>(std::integral_constant<int,N-1>());
}
public:
template <class... TsA>
static constexpr FlagValue Get() {
return _Sum<TsA...>(std::integral_constant<int,sizeof...(TsA)>());
}
static constexpr FlagValue All() {
return (1 << (sizeof...(Ts)+1)) -1;
}
FlagValue GetFlag() const {
return _rflag;
}
template <class... TsA>
FlagValue Test() const {
return GetFlag() & Get<TsA...>();
}
template <class T>
static constexpr FlagValue OrLH() {
// TypeListを巡回、A::Has<T>ならOr<A>()をたす
return Get<T>() | _IterateLH<T>(std::integral_constant<int,0>());
}
template <class T>
static constexpr FlagValue OrHL() {
return Get<T>() | _IterateHL<T>(std::integral_constant<int,T::size-1>());
}
//! 更新フラグだけを立てる
template <class... TsA>
void setFlag() {
_setFlag<TsA...>(std::integral_constant<int,sizeof...(TsA)>());
}
template <class T>
auto get(const Class* self) const -> decltype(base::cref(_GetNull<T>())) {
if(!(_rflag & Get<T>()))
return base::cref(_GetNull<T>());
return _refresh<T>(self);
}
template <class T>
auto ref() const -> typename std::decay<decltype(base::cref(_GetNull<T>()))>::type& {
// 更新チェックなしで参照を返す
const auto& ret = base::cref(_GetNull<T>());
return const_cast<typename std::decay<decltype(ret)>::type&>(ret);
}
template <class T>
auto refF() -> decltype(ref<T>()) {
// 更新フラグありで参照を返す
setFlag<T>();
return ref<T>();
}
//! キャッシュ機能付きの値を変更する際に使用
template <class T, class TA>
void set(TA&& t) {
refF<T>() = std::forward<TA>(t);
}
};
#define RFLAG(clazz, seq) \
using RFlag_t = spn::RFlag<clazz, BOOST_PP_SEQ_ENUM(seq)>; \
RFlag_t _rflag; \
template <class T, class... Ts> \
friend class spn::RFlag;
#define RFLAG_RVALUE_BASE(name, valueT, ...) \
struct name : spn::CType<__VA_ARGS__> { \
using value_type = valueT; \
value_type value; };
#define RFLAG_RVALUE(name, ...) \
RFLAG_RVALUE_BASE(name, __VA_ARGS__) \
BOOST_PP_IF( \
BOOST_PP_LESS_EQUAL( \
BOOST_PP_VARIADIC_SIZE(__VA_ARGS__), \
1 \
), \
RFLAG_RVALUE_, \
RFLAG_RVALUE_D_ \
)(name, __VA_ARGS__)
#define RFLAG_RVALUE_D_(name, valueT, ...) \
uint32_t _refresh(valueT&, name*) const;
#define RFLAG_RVALUE_(name, valueT) \
uint32_t _refresh(valueT&, name*) const { return 0; }
#define RFLAG_GETMETHOD(name) auto get##name() const -> decltype(_rflag.get<name>(this)) { return _rflag.get<name>(this); }
#define PASS_THROUGH(func, ...) func(__VA_ARGS__)
#define RFLAG_FUNC(z, data, elem) PASS_THROUGH(RFLAG_RVALUE, BOOST_PP_SEQ_ENUM(elem))
#define SEQ_GETFIRST(z, data, elem) (BOOST_PP_SEQ_ELEM(0,elem))
#define RFLAG_S(clazz, seq) \
BOOST_PP_SEQ_FOR_EACH( \
RFLAG_FUNC, \
BOOST_PP_NIL, \
seq \
) \
RFLAG( \
clazz, \
BOOST_PP_SEQ_FOR_EACH( \
SEQ_GETFIRST, \
BOOST_PP_NIL, \
seq \
) \
)
#define RFLAG_FUNC2(z, data, elem) RFLAG_GETMETHOD(elem)
#define RFLAG_GETMETHOD_S(seq) \
BOOST_PP_SEQ_FOR_EACH( \
RFLAG_FUNC2, \
BOOST_PP_NIL, \
BOOST_PP_SEQ_FOR_EACH( \
SEQ_GETFIRST, \
BOOST_PP_NIL, \
seq \
) \
)
#define RFLAG_SETMETHOD(name) \
template <class TArg> \
void BOOST_PP_CAT(set, name(TArg&& t)) { _rflag.set<name>(std::forward<TArg>(t)); }
#define RFLAG_FUNC3(z, dummy, seq) \
BOOST_PP_IF( \
BOOST_PP_LESS_EQUAL( \
BOOST_PP_SEQ_SIZE(seq), \
2 \
), \
RFLAG_SETMETHOD, \
NOTHING_ARG \
)(BOOST_PP_SEQ_ELEM(0, seq))
#define RFLAG_SETMETHOD_S(seq) \
BOOST_PP_SEQ_FOR_EACH( \
RFLAG_FUNC3, \
BOOST_PP_NIL, \
seq \
)
/* class MyClass {
RFLAG_RVALUE(Value0, Type0)
RFLAG_RVALUE(Value0, Type0, Depends....) をクラス内に変数分だけ書く
更新関数を uint32_t _refresh(Type0&, Value0*) const; の形で記述
RFLAG(MyClass, Value0, Value0...)
public:
// 参照用の関数
RFLAG_GETMETHOD(Value0)
RFLAG_GETMETHOD(Value1)
参照する時は _rflag.get<Value0>(this) とやるか、
getValue0()とすると依存変数の自動更新
_rfvalue.ref<Value0>(this)とすれば依存関係を無視して取り出せる
--- 上記の簡略系 ---
#define SEQ ((Value0)(Type0))((Value1)(Type1)(Depend))
private:
RFLAG_S(MyClass, SEQ)
public:
RFLAG_GETMETHOD_S(SEQ) */
#define VARIADIC_FOR_EACH_FUNC(z, n, data) BOOST_PP_TUPLE_ELEM(0, data)(1, BOOST_PP_TUPLE_ELEM(1,data), BOOST_PP_TUPLE_ELEM(BOOST_PP_ADD(n,2),data))
#define VARIADIC_FOR_EACH(macro, data, ...) BOOST_PP_REPEAT(BOOST_PP_VARIADIC_SIZE(__VA_ARGS__), VARIADIC_FOR_EACH_FUNC, BOOST_PP_VARIADIC_TO_TUPLE(macro, data, __VA_ARGS__))
}
<commit_msg>RFlag: refメソッド定義マクロを追加<commit_after>#pragma once
#include "type.hpp"
#include "error.hpp"
#define BOOST_PP_VARIADICS 1
#include <boost/preprocessor.hpp>
namespace spn {
template <class... Ts>
struct ValueHolder {
template <class T2>
void ref(T2*) {}
template <class T2>
void cref(T2*) const {}
};
template <class T, class... Ts>
struct ValueHolder<T, Ts...> : ValueHolder<Ts...> {
using base = ValueHolder<Ts...>;
using value_type = typename T::value_type;
value_type value;
value_type& ref(T*) { return value; }
const value_type& cref(T*) const { return value; }
template <class T2>
auto ref(T2* p) -> decltype(base::ref(p)) {
return base::ref(p); }
template <class T2>
auto cref(T2* p) const -> decltype(base::cref(p)) {
return base::cref(p); }
};
//! キャッシュ変数の自動管理クラス
template <class Class, class... Ts>
class RFlag : public ValueHolder<Ts...> {
public:
using FlagValue = uint32_t;
private:
using base = ValueHolder<Ts...>;
using ct_base = spn::CType<Ts...>;
template <class T>
static T* _GetNull() { return reinterpret_cast<T*>(0); }
mutable FlagValue _rflag = All();
//! integral_constantの値がtrueなら引数テンプレートのOr()を返す
template <class T0>
static constexpr FlagValue _Add_If(std::integral_constant<bool,false>) { return 0; }
template <class T0>
static constexpr FlagValue _Add_If(std::integral_constant<bool,true>) { return OrLH<T0>(); }
template <class T, int N>
static constexpr FlagValue _IterateLH(std::integral_constant<int,N>) {
using T0 = typename ct_base::template At<N>::type;
using T0Has = typename T0::template Has<T>;
return _Add_If<T0>(T0Has()) |
_IterateLH<T>(std::integral_constant<int,N+1>());
}
template <class T>
static constexpr FlagValue _IterateLH(std::integral_constant<int,ct_base::size>) { return 0; }
template <class T, int N>
static constexpr FlagValue _IterateHL(std::integral_constant<int,N>) {
using T0 = typename T::template At<N>::type;
return OrHL<T0>() | _IterateHL<T>(std::integral_constant<int,N-1>());
}
template <class T>
static constexpr FlagValue _IterateHL(std::integral_constant<int,-1>) { return 0; }
template <class T>
auto _refresh(const Class* self) const -> decltype(base::cref(_GetNull<T>())) {
const base* ptrC = this;
base* ptr = const_cast<base*>(ptrC);
_rflag &= ~(self->_refresh(ptr->ref(_GetNull<T>()), _GetNull<T>()));
_rflag &= ~Get<T>();
AssertP(Trap, !(_rflag & OrHL<T>()), "refresh flag was not cleared correctly")
return ptrC->cref(_GetNull<T>());
}
template <class TA>
static constexpr FlagValue _GetSingle() {
return 1 << ct_base::template Find<TA>::result;
}
template <class... TsA>
static constexpr FlagValue _Sum(std::integral_constant<int,0>) { return 0; }
template <class TA, class... TsA, int N>
static constexpr FlagValue _Sum(std::integral_constant<int,N>) {
return _GetSingle<TA>() | _Sum<TsA...>(std::integral_constant<int,N-1>());
}
template <class... TsA>
void _setFlag(std::integral_constant<int,0>) {}
template <class T, class... TsA, int N>
void _setFlag(std::integral_constant<int,N>) {
// 自分以下の階層はフラグを下ろす
_rflag &= ~OrHL<T>();
// 自分の階層より上の変数は全てフラグを立てる
_rflag |= OrLH<T>() & ~Get<T>();
_setFlag<TsA...>(std::integral_constant<int,N-1>());
}
public:
template <class... TsA>
static constexpr FlagValue Get() {
return _Sum<TsA...>(std::integral_constant<int,sizeof...(TsA)>());
}
static constexpr FlagValue All() {
return (1 << (sizeof...(Ts)+1)) -1;
}
FlagValue GetFlag() const {
return _rflag;
}
template <class... TsA>
FlagValue Test() const {
return GetFlag() & Get<TsA...>();
}
template <class T>
static constexpr FlagValue OrLH() {
// TypeListを巡回、A::Has<T>ならOr<A>()をたす
return Get<T>() | _IterateLH<T>(std::integral_constant<int,0>());
}
template <class T>
static constexpr FlagValue OrHL() {
return Get<T>() | _IterateHL<T>(std::integral_constant<int,T::size-1>());
}
//! 更新フラグだけを立てる
template <class... TsA>
void setFlag() {
_setFlag<TsA...>(std::integral_constant<int,sizeof...(TsA)>());
}
template <class T>
auto get(const Class* self) const -> decltype(base::cref(_GetNull<T>())) {
if(!(_rflag & Get<T>()))
return base::cref(_GetNull<T>());
return _refresh<T>(self);
}
template <class T>
auto ref() const -> typename std::decay<decltype(base::cref(_GetNull<T>()))>::type& {
// 更新チェックなしで参照を返す
const auto& ret = base::cref(_GetNull<T>());
return const_cast<typename std::decay<decltype(ret)>::type&>(ret);
}
template <class T>
auto refF() -> decltype(ref<T>()) {
// 更新フラグありで参照を返す
setFlag<T>();
return ref<T>();
}
//! キャッシュ機能付きの値を変更する際に使用
template <class T, class TA>
void set(TA&& t) {
refF<T>() = std::forward<TA>(t);
}
};
#define RFLAG(clazz, seq) \
using RFlag_t = spn::RFlag<clazz, BOOST_PP_SEQ_ENUM(seq)>; \
RFlag_t _rflag; \
template <class T, class... Ts> \
friend class spn::RFlag;
#define RFLAG_RVALUE_BASE(name, valueT, ...) \
struct name : spn::CType<__VA_ARGS__> { \
using value_type = valueT; \
value_type value; };
#define RFLAG_RVALUE(name, ...) \
RFLAG_RVALUE_BASE(name, __VA_ARGS__) \
BOOST_PP_IF( \
BOOST_PP_LESS_EQUAL( \
BOOST_PP_VARIADIC_SIZE(__VA_ARGS__), \
1 \
), \
RFLAG_RVALUE_, \
RFLAG_RVALUE_D_ \
)(name, __VA_ARGS__)
#define RFLAG_RVALUE_D_(name, valueT, ...) \
uint32_t _refresh(valueT&, name*) const;
#define RFLAG_RVALUE_(name, valueT) \
uint32_t _refresh(valueT&, name*) const { return 0; }
#define RFLAG_GETMETHOD(name) auto get##name() const -> decltype(_rflag.get<name>(this)) { return _rflag.get<name>(this); }
#define PASS_THROUGH(func, ...) func(__VA_ARGS__)
#define RFLAG_FUNC(z, data, elem) PASS_THROUGH(RFLAG_RVALUE, BOOST_PP_SEQ_ENUM(elem))
#define SEQ_GETFIRST(z, data, elem) (BOOST_PP_SEQ_ELEM(0,elem))
#define RFLAG_S(clazz, seq) \
BOOST_PP_SEQ_FOR_EACH( \
RFLAG_FUNC, \
BOOST_PP_NIL, \
seq \
) \
RFLAG( \
clazz, \
BOOST_PP_SEQ_FOR_EACH( \
SEQ_GETFIRST, \
BOOST_PP_NIL, \
seq \
) \
)
#define RFLAG_FUNC2(z, data, elem) RFLAG_GETMETHOD(elem)
#define RFLAG_GETMETHOD_S(seq) \
BOOST_PP_SEQ_FOR_EACH( \
RFLAG_FUNC2, \
BOOST_PP_NIL, \
BOOST_PP_SEQ_FOR_EACH( \
SEQ_GETFIRST, \
BOOST_PP_NIL, \
seq \
) \
)
#define RFLAG_FUNC3(z, func, seq) \
BOOST_PP_IF( \
BOOST_PP_LESS_EQUAL( \
BOOST_PP_SEQ_SIZE(seq), \
2 \
), \
func, \
NOTHING_ARG \
)(BOOST_PP_SEQ_ELEM(0, seq))
//! キャッシュ変数にset()メソッドを定義
#define RFLAG_SETMETHOD(name) \
template <class TArg> \
void BOOST_PP_CAT(set, name(TArg&& t)) { _rflag.set<name>(std::forward<TArg>(t)); }
//! 最下層のキャッシュ変数に一括でset()メソッドを定義
#define RFLAG_SETMETHOD_S(seq) \
BOOST_PP_SEQ_FOR_EACH( \
RFLAG_FUNC3, \
RFLAG_SETMETHOD, \
seq \
)
//! キャッシュ変数にref()メソッドを定義
#define RFLAG_REFMETHOD(name) \
auto& BOOST_PP_CAT(ref, name()) { return _rflag.refF<name>(); }
//! 最下層のキャッシュ変数に一括でref()メソッドを定義
#define RFLAG_REFMETHOD_S(seq) \
BOOST_PP_SEQ_FOR_EACH( \
RFLAG_FUNC3, \
RFLAG_REFMETHOD, \
seq \
)
/* class MyClass {
RFLAG_RVALUE(Value0, Type0)
RFLAG_RVALUE(Value0, Type0, Depends....) をクラス内に変数分だけ書く
更新関数を uint32_t _refresh(Type0&, Value0*) const; の形で記述
RFLAG(MyClass, Value0, Value0...)
public:
// 参照用の関数
RFLAG_GETMETHOD(Value0)
RFLAG_GETMETHOD(Value1)
参照する時は _rflag.get<Value0>(this) とやるか、
getValue0()とすると依存変数の自動更新
_rfvalue.ref<Value0>(this)とすれば依存関係を無視して取り出せる
--- 上記の簡略系 ---
#define SEQ ((Value0)(Type0))((Value1)(Type1)(Depend))
private:
RFLAG_S(MyClass, SEQ)
public:
RFLAG_GETMETHOD_S(SEQ) */
#define VARIADIC_FOR_EACH_FUNC(z, n, data) BOOST_PP_TUPLE_ELEM(0, data)(1, BOOST_PP_TUPLE_ELEM(1,data), BOOST_PP_TUPLE_ELEM(BOOST_PP_ADD(n,2),data))
#define VARIADIC_FOR_EACH(macro, data, ...) BOOST_PP_REPEAT(BOOST_PP_VARIADIC_SIZE(__VA_ARGS__), VARIADIC_FOR_EACH_FUNC, BOOST_PP_VARIADIC_TO_TUPLE(macro, data, __VA_ARGS__))
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (C) 2021 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* Test code for the Magnetometer calibration routine
* Run this test only using make tests TESTFILTER=mag_calibration
*
* @author Mathieu Bresciani <mathieu@auterion.com>
*/
#include <gtest/gtest.h>
#include <matrix/matrix/math.hpp>
#include <px4_platform_common/defines.h>
#include "lm_fit.hpp"
#include "mag_calibration_test_data.h"
using matrix::Vector3f;
class MagCalTest : public ::testing::Test
{
public:
void generate2SidesMagData(float *x, float *y, float *z, unsigned int n_samples, float mag_str);
/* Generate regularly spaced data on a sphere
* Ref.: How to generate equidistributed points on the surface of a sphere, Markus Deserno, 2004
*/
void generateRegularData(float *x, float *y, float *z, unsigned int n_samples, float mag_str);
void modifyOffsetScale(float *x, float *y, float *z, unsigned int n_samples, Vector3f offsets, Vector3f scale_factors);
};
void MagCalTest::generate2SidesMagData(float *x, float *y, float *z, unsigned int n_samples, float mag_str)
{
float psi = 0.f;
float theta = 0.f;
const float d_angle = 2.f * M_PI_F / float(n_samples / 2);
for (int i = 0; i < int(n_samples / 2); i++) {
x[i] = mag_str * sinf(psi);
y[i] = mag_str * cosf(psi);
z[i] = 0.f;
psi += d_angle;
}
for (int i = int(n_samples / 2); i < int(n_samples); i++) {
x[i] = mag_str * sinf(theta);
y[i] = 0.f;
z[i] = mag_str * cosf(theta);
theta += d_angle;
}
}
void MagCalTest::generateRegularData(float *x, float *y, float *z, unsigned int n_samples, float mag_str)
{
const float a = 4.f * M_PI_F * mag_str * mag_str / n_samples;
const float d = sqrtf(a);
const int m_theta = static_cast<int>(M_PI_F / d);
const float d_theta = M_PI_F / static_cast<float>(m_theta);
const float d_phi = a / d_theta;
unsigned int n_count = 0;
for (int m = 0; m < m_theta; m++) {
const float theta = M_PI_F * (m + 0.5f) / static_cast<float>(m_theta);
const int m_phi = static_cast<int>(2.f * M_PI_F * sinf(theta / d_phi));
for (int n = 0; n < m_phi; n++) {
const float phi = 2.f * M_PI_F * n / static_cast<float>(m_phi);
x[n_count] = mag_str * sinf(theta) * cosf(phi);
y[n_count] = mag_str * sinf(theta) * sinf(phi);
z[n_count] = mag_str * cosf(theta);
n_count++;
}
}
if (n_count > n_samples) {
printf("Error placing samples, n = %d\n", n_count);
return;
}
// Padd with constant data
while (n_count < n_samples) {
x[n_count] = x[n_count - 1];
y[n_count] = y[n_count - 1];
z[n_count] = z[n_count - 1];
n_count++;
}
}
void MagCalTest::modifyOffsetScale(float *x, float *y, float *z, unsigned int n_samples, Vector3f offsets,
Vector3f scale_factors)
{
for (unsigned int k = 0; k < n_samples; k++) {
x[k] = x[k] * scale_factors(0) + offsets(0);
y[k] = y[k] * scale_factors(1) + offsets(1);
z[k] = z[k] * scale_factors(2) + offsets(2);
}
}
TEST_F(MagCalTest, sphere2Sides)
{
// GIVEN: a dataset of points located on two orthogonal circles
// perfectly centered on the origin
static constexpr unsigned int N_SAMPLES = 240;
const float mag_str_true = 0.4f;
const Vector3f offset_true;
const Vector3f scale_true = {1.f, 1.f, 1.f};
float x[N_SAMPLES];
float y[N_SAMPLES];
float z[N_SAMPLES];
generate2SidesMagData(x, y, z, N_SAMPLES, mag_str_true);
float fitness = 1.0e30f;
float sphere_lambda = 1.f;
float sphere_radius = 0.2f;
Vector3f offset;
Vector3f diag = {1.f, 1.f, 1.f};
Vector3f offdiag;
// WHEN: fitting a sphere with the data and given a wrong initial radius
int ret = run_lm_sphere_fit(x, y, z,
fitness, sphere_lambda, N_SAMPLES,
&offset(0), &offset(1), &offset(2),
&sphere_radius,
&diag(0), &diag(1), &diag(2),
&offdiag(0), &offdiag(1), &offdiag(2));
// THEN: the algorithm should converge in a single step
EXPECT_EQ(ret, 0);
EXPECT_LT(fitness, 1e-5f);
EXPECT_NEAR(sphere_radius, mag_str_true, 0.001f) << "radius: " << sphere_radius;
EXPECT_NEAR(offset(0), offset_true(0), 0.001f) << "offset X: " << offset(0);
EXPECT_NEAR(offset(1), offset_true(1), 0.001f) << "offset Y: " << offset(1);
EXPECT_NEAR(offset(2), offset_true(2), 0.001f) << "offset Z: " << offset(2);
EXPECT_NEAR(diag(0), scale_true(0), 0.001f) << "scale X: " << scale_true(0);
EXPECT_NEAR(diag(1), scale_true(1), 0.001f) << "scale Y: " << scale_true(1);
EXPECT_NEAR(diag(2), scale_true(2), 0.001f) << "scale Z: " << scale_true(2);
}
TEST_F(MagCalTest, sphereRegularlySpaced)
{
// GIVEN: a dataset of regularly spaced points
// on a perfect sphere but not centered on the origin
static constexpr unsigned int N_SAMPLES = 240;
const float mag_str_true = 0.4f;
const Vector3f offset_true = {-1.07f, 0.35f, -0.78f};
const Vector3f scale_true = {1.f, 1.f, 1.f};
float x[N_SAMPLES];
float y[N_SAMPLES];
float z[N_SAMPLES];
generateRegularData(x, y, z, N_SAMPLES, mag_str_true);
modifyOffsetScale(x, y, z, N_SAMPLES, offset_true, scale_true);
float fitness = 1.0e30f;
float sphere_lambda = 1.f;
float sphere_radius = 0.2f;
Vector3f offset;
Vector3f diag = {1.f, 1.f, 1.f};
Vector3f offdiag;
bool sphere_fit_success = false;
// WHEN: fitting a sphere to the data
for (int i = 0; i < 8; i++) {
const bool ret = run_lm_sphere_fit(x, y, z,
fitness, sphere_lambda, N_SAMPLES,
&offset(0), &offset(1), &offset(2),
&sphere_radius,
&diag(0), &diag(1), &diag(2),
&offdiag(0), &offdiag(1), &offdiag(2));
if (ret == 0) {
sphere_fit_success = true;
} else if (sphere_fit_success) {
break;
}
}
// THEN: the algorithm should converge in a few iterations and
// find the correct parameters
EXPECT_TRUE(sphere_fit_success);
EXPECT_LT(fitness, 1e-6f);
EXPECT_NEAR(sphere_radius, mag_str_true, 0.001f) << "radius: " << sphere_radius;
EXPECT_NEAR(offset(0), offset_true(0), 0.001f) << "offset X: " << offset(0);
EXPECT_NEAR(offset(1), offset_true(1), 0.001f) << "offset Y: " << offset(1);
EXPECT_NEAR(offset(2), offset_true(2), 0.001f) << "offset Z: " << offset(2);
EXPECT_NEAR(diag(0), scale_true(0), 0.001f) << "scale X: " << scale_true(0);
EXPECT_NEAR(diag(1), scale_true(1), 0.001f) << "scale Y: " << scale_true(1);
EXPECT_NEAR(diag(2), scale_true(2), 0.001f) << "scale Z: " << scale_true(2);
}
TEST_F(MagCalTest, replayTestData)
{
// GIVEN: a real test dataset with large offsets
// and where the two first iterations of the LM algorithm
// produces a negative radius and a constant fitness value
constexpr unsigned int N_SAMPLES = 231;
const float mag_str_true = 0.4f;
const Vector3f offset_true = {-0.18f, 0.05f, -0.58f};
const Vector3f scale_true = {1.f, 1.f, 1.f};
float fitness = 1.0e30f;
float sphere_lambda = 1.f;
float sphere_radius = 0.2f;
Vector3f offset;
Vector3f diag = {1.f, 1.f, 1.f};
Vector3f offdiag;
bool sphere_fit_success = false;
// WHEN: fitting a sphere to the data
for (int i = 0; i < 100; i++) {
const bool ret = run_lm_sphere_fit(mag_data1_x, mag_data1_y, mag_data1_z,
fitness, sphere_lambda, N_SAMPLES,
&offset(0), &offset(1), &offset(2),
&sphere_radius,
&diag(0), &diag(1), &diag(2),
&offdiag(0), &offdiag(1), &offdiag(2));
printf("fitness: %.6f\t sphere_lambda: %.3f\t radius: %.3f\n",
(double)fitness, (double)sphere_lambda, (double)sphere_radius);
// This is fragile because it is a copy of the code and not a
// test of the code itself. TODO: move the check in a function that
// can be tested here
if (ret == 0) {
sphere_fit_success = true;
} else if (sphere_fit_success
&& (i > 10)
&& (fitness < 0.01f)
&& (sphere_radius >= 0.2f)
&& (sphere_radius <= 0.7f)) {
break;
}
}
// THEN: the algorithm should converge and find the correct parameters
EXPECT_TRUE(sphere_fit_success);
EXPECT_LT(fitness, 1e-3f);
EXPECT_NEAR(sphere_radius, mag_str_true, 0.1f) << "radius: " << sphere_radius;
EXPECT_NEAR(offset(0), offset_true(0), 0.01f) << "offset X: " << offset(0);
EXPECT_NEAR(offset(1), offset_true(1), 0.01f) << "offset Y: " << offset(1);
EXPECT_NEAR(offset(2), offset_true(2), 0.01f) << "offset Z: " << offset(2);
EXPECT_NEAR(diag(0), scale_true(0), 0.01f) << "scale X: " << scale_true(0);
EXPECT_NEAR(diag(1), scale_true(1), 0.01f) << "scale Y: " << scale_true(1);
EXPECT_NEAR(diag(2), scale_true(2), 0.01f) << "scale Z: " << scale_true(2);
}
<commit_msg>mag test: add ellipsoid test<commit_after>/****************************************************************************
*
* Copyright (C) 2021 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* Test code for the Magnetometer calibration routine
* Run this test only using make tests TESTFILTER=mag_calibration
*
* @author Mathieu Bresciani <mathieu@auterion.com>
*/
#include <gtest/gtest.h>
#include <matrix/matrix/math.hpp>
#include <px4_platform_common/defines.h>
#include "lm_fit.hpp"
#include "mag_calibration_test_data.h"
using matrix::Vector3f;
class MagCalTest : public ::testing::Test
{
public:
void generate2SidesMagData(float *x, float *y, float *z, unsigned int n_samples, float mag_str);
/* Generate regularly spaced data on a sphere
* Ref.: How to generate equidistributed points on the surface of a sphere, Markus Deserno, 2004
*/
void generateRegularData(float *x, float *y, float *z, unsigned int n_samples, float mag_str);
void modifyOffsetScale(float *x, float *y, float *z, unsigned int n_samples, Vector3f offsets, Vector3f scale_factors);
};
void MagCalTest::generate2SidesMagData(float *x, float *y, float *z, unsigned int n_samples, float mag_str)
{
float psi = 0.f;
float theta = 0.f;
const float d_angle = 2.f * M_PI_F / float(n_samples / 2);
for (int i = 0; i < int(n_samples / 2); i++) {
x[i] = mag_str * sinf(psi);
y[i] = mag_str * cosf(psi);
z[i] = 0.f;
psi += d_angle;
}
for (int i = int(n_samples / 2); i < int(n_samples); i++) {
x[i] = mag_str * sinf(theta);
y[i] = 0.f;
z[i] = mag_str * cosf(theta);
theta += d_angle;
}
}
void MagCalTest::generateRegularData(float *x, float *y, float *z, unsigned int n_samples, float mag_str)
{
const float a = 4.f * M_PI_F * mag_str * mag_str / n_samples;
const float d = sqrtf(a);
const int m_theta = static_cast<int>(M_PI_F / d);
const float d_theta = M_PI_F / static_cast<float>(m_theta);
const float d_phi = a / d_theta;
unsigned int n_count = 0;
for (int m = 0; m < m_theta; m++) {
const float theta = M_PI_F * (m + 0.5f) / static_cast<float>(m_theta);
const int m_phi = static_cast<int>(2.f * M_PI_F * sinf(theta / d_phi));
for (int n = 0; n < m_phi; n++) {
const float phi = 2.f * M_PI_F * n / static_cast<float>(m_phi);
x[n_count] = mag_str * sinf(theta) * cosf(phi);
y[n_count] = mag_str * sinf(theta) * sinf(phi);
z[n_count] = mag_str * cosf(theta);
n_count++;
}
}
if (n_count > n_samples) {
printf("Error placing samples, n = %d\n", n_count);
return;
}
// Padd with constant data
while (n_count < n_samples) {
x[n_count] = x[n_count - 1];
y[n_count] = y[n_count - 1];
z[n_count] = z[n_count - 1];
n_count++;
}
}
void MagCalTest::modifyOffsetScale(float *x, float *y, float *z, unsigned int n_samples, Vector3f offsets,
Vector3f scale_factors)
{
for (unsigned int k = 0; k < n_samples; k++) {
x[k] = x[k] * scale_factors(0) + offsets(0);
y[k] = y[k] * scale_factors(1) + offsets(1);
z[k] = z[k] * scale_factors(2) + offsets(2);
}
}
TEST_F(MagCalTest, sphere2Sides)
{
// GIVEN: a dataset of points located on two orthogonal circles
// perfectly centered on the origin
static constexpr unsigned int N_SAMPLES = 240;
const float mag_str_true = 0.4f;
const Vector3f offset_true;
const Vector3f scale_true = {1.f, 1.f, 1.f};
float x[N_SAMPLES];
float y[N_SAMPLES];
float z[N_SAMPLES];
generate2SidesMagData(x, y, z, N_SAMPLES, mag_str_true);
float fitness = 1.0e30f;
float sphere_lambda = 1.f;
float sphere_radius = 0.2f;
Vector3f offset;
Vector3f diag = {1.f, 1.f, 1.f};
Vector3f offdiag;
// WHEN: fitting a sphere with the data and given a wrong initial radius
int ret = run_lm_sphere_fit(x, y, z,
fitness, sphere_lambda, N_SAMPLES,
&offset(0), &offset(1), &offset(2),
&sphere_radius,
&diag(0), &diag(1), &diag(2),
&offdiag(0), &offdiag(1), &offdiag(2));
// THEN: the algorithm should converge in a single step
EXPECT_EQ(ret, 0);
EXPECT_LT(fitness, 1e-5f);
EXPECT_NEAR(sphere_radius, mag_str_true, 0.001f) << "radius: " << sphere_radius;
EXPECT_NEAR(offset(0), offset_true(0), 0.001f) << "offset X: " << offset(0);
EXPECT_NEAR(offset(1), offset_true(1), 0.001f) << "offset Y: " << offset(1);
EXPECT_NEAR(offset(2), offset_true(2), 0.001f) << "offset Z: " << offset(2);
EXPECT_NEAR(diag(0), scale_true(0), 0.001f) << "scale X: " << scale_true(0);
EXPECT_NEAR(diag(1), scale_true(1), 0.001f) << "scale Y: " << scale_true(1);
EXPECT_NEAR(diag(2), scale_true(2), 0.001f) << "scale Z: " << scale_true(2);
}
TEST_F(MagCalTest, sphereRegularlySpaced)
{
// GIVEN: a dataset of regularly spaced points
// on a perfect sphere but not centered on the origin
static constexpr unsigned int N_SAMPLES = 240;
const float mag_str_true = 0.4f;
const Vector3f offset_true = {-1.07f, 0.35f, -0.78f};
const Vector3f scale_true = {1.f, 1.f, 1.f};
float x[N_SAMPLES];
float y[N_SAMPLES];
float z[N_SAMPLES];
generateRegularData(x, y, z, N_SAMPLES, mag_str_true);
modifyOffsetScale(x, y, z, N_SAMPLES, offset_true, scale_true);
float fitness = 1.0e30f;
float sphere_lambda = 1.f;
float sphere_radius = 0.2f;
Vector3f offset;
Vector3f diag = {1.f, 1.f, 1.f};
Vector3f offdiag;
bool sphere_fit_success = false;
// WHEN: fitting a sphere to the data
for (int i = 0; i < 8; i++) {
const bool ret = run_lm_sphere_fit(x, y, z,
fitness, sphere_lambda, N_SAMPLES,
&offset(0), &offset(1), &offset(2),
&sphere_radius,
&diag(0), &diag(1), &diag(2),
&offdiag(0), &offdiag(1), &offdiag(2));
if (ret == 0) {
sphere_fit_success = true;
} else if (sphere_fit_success) {
break;
}
}
// THEN: the algorithm should converge in a few iterations and
// find the correct parameters
EXPECT_TRUE(sphere_fit_success);
EXPECT_LT(fitness, 1e-6f);
EXPECT_NEAR(sphere_radius, mag_str_true, 0.001f) << "radius: " << sphere_radius;
EXPECT_NEAR(offset(0), offset_true(0), 0.001f) << "offset X: " << offset(0);
EXPECT_NEAR(offset(1), offset_true(1), 0.001f) << "offset Y: " << offset(1);
EXPECT_NEAR(offset(2), offset_true(2), 0.001f) << "offset Z: " << offset(2);
EXPECT_NEAR(diag(0), scale_true(0), 0.001f) << "scale X: " << scale_true(0);
EXPECT_NEAR(diag(1), scale_true(1), 0.001f) << "scale Y: " << scale_true(1);
EXPECT_NEAR(diag(2), scale_true(2), 0.001f) << "scale Z: " << scale_true(2);
}
TEST_F(MagCalTest, replayTestData)
{
// GIVEN: a real test dataset with large offsets
// and where the two first iterations of the LM algorithm
// produces a negative radius and a constant fitness value
constexpr unsigned int N_SAMPLES = 231;
const float mag_str_true = 0.4f;
const Vector3f offset_true = {-0.18f, 0.05f, -0.58f};
const Vector3f scale_true = {1.f, 1.06f, 0.94f};
float fitness = 1.0e30f;
float sphere_lambda = 1.f;
float sphere_radius = 0.2f;
Vector3f offset;
Vector3f diag = {1.f, 1.f, 1.f};
Vector3f offdiag;
bool sphere_fit_success = false;
// WHEN: fitting a sphere to the data
for (int i = 0; i < 100; i++) {
const bool ret = run_lm_sphere_fit(mag_data1_x, mag_data1_y, mag_data1_z,
fitness, sphere_lambda, N_SAMPLES,
&offset(0), &offset(1), &offset(2),
&sphere_radius,
&diag(0), &diag(1), &diag(2),
&offdiag(0), &offdiag(1), &offdiag(2));
printf("fitness: %.6f\t sphere_lambda: %.3f\t radius: %.3f\n",
(double)fitness, (double)sphere_lambda, (double)sphere_radius);
// This is fragile because it is a copy of the code and not a
// test of the code itself. TODO: move the check in a function that
// can be tested here
if (ret == 0) {
sphere_fit_success = true;
} else if (sphere_fit_success
&& (i > 10)
&& (fitness < 0.01f)
&& (sphere_radius >= 0.2f)
&& (sphere_radius <= 0.7f)) {
break;
}
}
printf("Ellipsoid fit\n");
bool ellipsoid_fit_success = false;
for (int i = 0; i < 100; i++) {
const bool ret = run_lm_ellipsoid_fit(mag_data1_x, mag_data1_y, mag_data1_z,
fitness, sphere_lambda, N_SAMPLES,
&offset(0), &offset(1), &offset(2),
&sphere_radius,
&diag(0), &diag(1), &diag(2),
&offdiag(0), &offdiag(1), &offdiag(2));
printf("fitness: %.6f\t sphere_lambda: %.3f\t radius: %.3f\n",
(double)fitness, (double)sphere_lambda, (double)sphere_radius);
if (ret == 0) {
ellipsoid_fit_success = true;
} else if (ellipsoid_fit_success) {
break;
}
}
// THEN: the algorithm should converge and find the correct parameters
EXPECT_TRUE(sphere_fit_success);
EXPECT_TRUE(ellipsoid_fit_success);
EXPECT_LT(fitness, 1e-3f);
EXPECT_NEAR(sphere_radius, mag_str_true, 0.1f) << "radius: " << sphere_radius;
EXPECT_NEAR(offset(0), offset_true(0), 0.01f) << "offset X: " << offset(0);
EXPECT_NEAR(offset(1), offset_true(1), 0.01f) << "offset Y: " << offset(1);
EXPECT_NEAR(offset(2), offset_true(2), 0.01f) << "offset Z: " << offset(2);
EXPECT_NEAR(diag(0), scale_true(0), 0.01f) << "scale X: " << diag(0);
EXPECT_NEAR(diag(1), scale_true(1), 0.01f) << "scale Y: " << diag(1);
EXPECT_NEAR(diag(2), scale_true(2), 0.01f) << "scale Z: " << diag(2);
}
<|endoftext|> |
<commit_before>// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#include "caf/config.hpp"
// exclude this suite; seems to be too much to swallow for MSVC
#ifndef CAF_WINDOWS
# define CAF_SUITE typed_spawn
# include "core-test.hpp"
# include "caf/string_algorithms.hpp"
# include "caf/all.hpp"
# define ERROR_HANDLER [&](error& err) { CAF_FAIL(err); }
using std::string;
using namespace caf;
using namespace std::string_literals;
namespace {
static_assert(std::is_same<reacts_to<int, int>, result<void>(int, int)>::value);
static_assert(std::is_same<replies_to<double>::with<double>,
result<double>(double)>::value);
// check invariants of type system
using dummy1 = typed_actor<result<void>(int, int), result<double>(double)>;
using dummy2 = dummy1::extend<reacts_to<ok_atom>>;
static_assert(std::is_convertible<dummy2, dummy1>::value,
"handle not assignable to narrower definition");
using dummy3 = typed_actor<reacts_to<float, int>>;
using dummy4 = typed_actor<replies_to<int>::with<double>>;
using dummy5 = dummy4::extend_with<dummy3>;
static_assert(std::is_convertible<dummy5, dummy3>::value,
"handle not assignable to narrower definition");
static_assert(std::is_convertible<dummy5, dummy4>::value,
"handle not assignable to narrower definition");
/******************************************************************************
* simple request/response test *
******************************************************************************/
using server_type = typed_actor<replies_to<my_request>::with<bool>>;
server_type::behavior_type typed_server1() {
return {
[](const my_request& req) { return req.a == req.b; },
};
}
server_type::behavior_type typed_server2(server_type::pointer) {
return typed_server1();
}
class typed_server3 : public server_type::base {
public:
typed_server3(actor_config& cfg, const string& line, actor buddy)
: server_type::base(cfg) {
anon_send(buddy, line);
}
behavior_type make_behavior() override {
return typed_server2(this);
}
};
void client(event_based_actor* self, const actor& parent,
const server_type& serv) {
self->request(serv, infinite, my_request{0, 0}).then([=](bool val1) {
CAF_CHECK_EQUAL(val1, true);
self->request(serv, infinite, my_request{10, 20}).then([=](bool val2) {
CAF_CHECK_EQUAL(val2, false);
self->send(parent, ok_atom_v);
});
});
}
/******************************************************************************
* test skipping of messages intentionally + using become() *
******************************************************************************/
using event_testee_type
= typed_actor<replies_to<get_state_atom>::with<string>,
replies_to<string>::with<void>, replies_to<float>::with<void>,
replies_to<int>::with<int>>;
class event_testee : public event_testee_type::base {
public:
event_testee(actor_config& cfg) : event_testee_type::base(cfg) {
set_default_handler(skip);
}
behavior_type wait4string() {
return {
partial_behavior_init,
[=](get_state_atom) { return "wait4string"; },
[=](const string&) { become(wait4int()); },
};
}
behavior_type wait4int() {
return {
partial_behavior_init,
[=](get_state_atom) { return "wait4int"; },
[=](int) -> int {
become(wait4float());
return 42;
},
};
}
behavior_type wait4float() {
return {
partial_behavior_init,
[=](get_state_atom) { return "wait4float"; },
[=](float) { become(wait4string()); },
};
}
behavior_type make_behavior() override {
return wait4int();
}
};
/******************************************************************************
* simple 'forwarding' chain *
******************************************************************************/
using string_actor = typed_actor<replies_to<string>::with<string>>;
string_actor::behavior_type string_reverter() {
return {
[](string& str) -> string {
std::reverse(str.begin(), str.end());
return std::move(str);
},
};
}
// uses `return delegate(...)`
string_actor::behavior_type string_delegator(string_actor::pointer self,
string_actor master, bool leaf) {
auto next = leaf ? self->spawn(string_delegator, master, false) : master;
self->link_to(next);
return {
[=](string& str) -> delegated<string> {
return self->delegate(next, std::move(str));
},
};
}
using maybe_string_actor
= typed_actor<replies_to<string>::with<ok_atom, string>>;
maybe_string_actor::behavior_type maybe_string_reverter() {
return {
[](string& str) -> result<ok_atom, string> {
if (str.empty())
return sec::invalid_argument;
std::reverse(str.begin(), str.end());
return {ok_atom_v, std::move(str)};
},
};
}
maybe_string_actor::behavior_type
maybe_string_delegator(maybe_string_actor::pointer self,
const maybe_string_actor& x) {
self->link_to(x);
return {
[=](string& s) -> delegated<ok_atom, string> {
return self->delegate(x, std::move(s));
},
};
}
/******************************************************************************
* sending typed actor handles *
******************************************************************************/
int_actor::behavior_type int_fun() {
return {
[](int i) { return i * i; },
};
}
behavior foo(event_based_actor* self) {
return {
[=](int i, int_actor server) {
self->delegate(server, i);
self->quit();
},
};
}
int_actor::behavior_type int_fun2(int_actor::pointer self) {
self->set_down_handler([=](down_msg& dm) {
CAF_CHECK_EQUAL(dm.reason, exit_reason::normal);
self->quit();
});
return {
[=](int i) {
self->monitor(self->current_sender());
return i * i;
},
};
}
behavior foo2(event_based_actor* self) {
return {
[=](int i, int_actor server) {
self->delegate(server, i);
self->quit();
},
};
}
float_actor::behavior_type float_fun(float_actor::pointer self) {
return {
[=](float a) {
CAF_CHECK_EQUAL(a, 1.0f);
self->quit(exit_reason::user_shutdown);
},
};
}
int_actor::behavior_type foo3(int_actor::pointer self) {
auto b = self->spawn<linked>(float_fun);
self->send(b, 1.0f);
return {
[=](int) { return 0; },
};
}
struct fixture : test_coordinator_fixture<> {
void test_typed_spawn(server_type ts) {
CAF_MESSAGE("the server returns false for inequal numbers");
inject((my_request), from(self).to(ts).with(my_request{1, 2}));
expect((bool), from(ts).to(self).with(false));
CAF_MESSAGE("the server returns true for equal numbers");
inject((my_request), from(self).to(ts).with(my_request{42, 42}));
expect((bool), from(ts).to(self).with(true));
CAF_CHECK_EQUAL(sys.registry().running(), 2u);
auto c1 = self->spawn(client, self, ts);
run();
expect((ok_atom), from(c1).to(self).with(ok_atom_v));
CAF_CHECK_EQUAL(sys.registry().running(), 2u);
}
};
} // namespace
CAF_TEST_FIXTURE_SCOPE(typed_spawn_tests, fixture)
/******************************************************************************
* put it all together *
******************************************************************************/
CAF_TEST(typed_spawns) {
CAF_MESSAGE("run test series with typed_server1");
test_typed_spawn(sys.spawn(typed_server1));
self->await_all_other_actors_done();
CAF_MESSAGE("finished test series with `typed_server1`");
CAF_MESSAGE("run test series with typed_server2");
test_typed_spawn(sys.spawn(typed_server2));
self->await_all_other_actors_done();
CAF_MESSAGE("finished test series with `typed_server2`");
auto serv3 = self->spawn<typed_server3>("hi there", self);
run();
expect((string), from(serv3).to(self).with("hi there"s));
test_typed_spawn(serv3);
}
CAF_TEST(event_testee_series) {
auto et = self->spawn<event_testee>();
CAF_MESSAGE("et->message_types() returns an interface description");
typed_actor<replies_to<get_state_atom>::with<string>> sub_et = et;
std::set<string> iface{"(get_state_atom) -> (std::string)",
"(std::string) -> (void)", "(float) -> (void)",
"(int32_t) -> (int32_t)"};
CAF_CHECK_EQUAL(join(sub_et->message_types(), ","), join(iface, ","));
CAF_MESSAGE("the testee skips messages to drive its internal state machine");
self->send(et, 1);
self->send(et, 2);
self->send(et, 3);
self->send(et, .1f);
self->send(et, "hello event testee!"s);
self->send(et, .2f);
self->send(et, .3f);
self->send(et, "hello again event testee!"s);
self->send(et, "goodbye event testee!"s);
run();
expect((int), from(et).to(self).with(42));
expect((int), from(et).to(self).with(42));
expect((int), from(et).to(self).with(42));
inject((get_state_atom), from(self).to(sub_et).with(get_state_atom_v));
expect((string), from(et).to(self).with("wait4int"s));
}
CAF_TEST(string_delegator_chain) {
// run test series with string reverter
auto aut = self->spawn<monitored>(string_delegator,
sys.spawn(string_reverter), true);
std::set<string> iface{"(std::string) -> (std::string)"};
CAF_CHECK_EQUAL(aut->message_types(), iface);
inject((string), from(self).to(aut).with("Hello World!"s));
run();
expect((string), to(self).with("!dlroW olleH"s));
}
CAF_TEST(maybe_string_delegator_chain) {
CAF_LOG_TRACE(CAF_ARG(self));
auto aut = sys.spawn(maybe_string_delegator,
sys.spawn(maybe_string_reverter));
CAF_MESSAGE("send empty string, expect error");
inject((string), from(self).to(aut).with(""s));
run();
expect((error), to(self).with(sec::invalid_argument));
CAF_MESSAGE("send abcd string, expect dcba");
inject((string), from(self).to(aut).with("abcd"s));
run();
expect((ok_atom, string), to(self).with(ok_atom_v, "dcba"s));
}
CAF_TEST(sending_typed_actors) {
auto aut = sys.spawn(int_fun);
self->send(self->spawn(foo), 10, aut);
run();
expect((int), to(self).with(100));
self->spawn(foo3);
run();
}
CAF_TEST(sending_typed_actors_and_down_msg) {
auto aut = sys.spawn(int_fun2);
self->send(self->spawn(foo2), 10, aut);
run();
expect((int), to(self).with(100));
}
CAF_TEST(check_signature) {
using foo_type = typed_actor<replies_to<put_atom>::with<ok_atom>>;
using foo_result_type = result<ok_atom>;
using bar_type = typed_actor<reacts_to<ok_atom>>;
auto foo_action = [](foo_type::pointer ptr) -> foo_type::behavior_type {
return {
[=](put_atom) -> foo_result_type {
ptr->quit();
return {ok_atom_v};
},
};
};
auto bar_action = [=](bar_type::pointer ptr) -> bar_type::behavior_type {
auto foo = ptr->spawn<linked>(foo_action);
ptr->send(foo, put_atom_v);
return {
[=](ok_atom) { ptr->quit(); },
};
};
auto x = self->spawn(bar_action);
run();
}
SCENARIO("state-classes may use typed pointers") {
GIVEN("a state class for a statically typed actor type") {
using foo_type = typed_actor<result<int32_t>(get_atom)>;
struct foo_state {
foo_state(foo_type::pointer_view selfptr) : self(selfptr) {
foo_type hdl{self};
CHECK_EQ(selfptr, actor_cast<abstract_actor*>(hdl));
foo_type hdl2{selfptr};
CHECK_EQ(hdl, hdl2);
}
foo_type::behavior_type make_behavior() {
return {
[](get_atom) { return int32_t{42}; },
};
}
foo_type::pointer_view self;
};
using foo_impl = stateful_actor<foo_state, foo_type::impl>;
WHEN("spawning a stateful actor using the state class") {
auto foo = sys.spawn<foo_impl>();
THEN("the actor calls make_behavior of the state class") {
inject((get_atom), from(self).to(foo).with(get_atom_v));
expect((int32_t), from(foo).to(self).with(42));
}
}
}
}
CAF_TEST_FIXTURE_SCOPE_END()
#endif // CAF_WINDOWS
<commit_msg>Fix typo<commit_after>// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#include "caf/config.hpp"
// exclude this suite; seems to be too much to swallow for MSVC
#ifndef CAF_WINDOWS
# define CAF_SUITE typed_spawn
# include "core-test.hpp"
# include "caf/string_algorithms.hpp"
# include "caf/all.hpp"
# define ERROR_HANDLER [&](error& err) { CAF_FAIL(err); }
using std::string;
using namespace caf;
using namespace std::string_literals;
namespace {
static_assert(std::is_same<reacts_to<int, int>, result<void>(int, int)>::value);
static_assert(std::is_same<replies_to<double>::with<double>,
result<double>(double)>::value);
// check invariants of type system
using dummy1 = typed_actor<result<void>(int, int), result<double>(double)>;
using dummy2 = dummy1::extend<reacts_to<ok_atom>>;
static_assert(std::is_convertible<dummy2, dummy1>::value,
"handle not assignable to narrower definition");
using dummy3 = typed_actor<reacts_to<float, int>>;
using dummy4 = typed_actor<replies_to<int>::with<double>>;
using dummy5 = dummy4::extend_with<dummy3>;
static_assert(std::is_convertible<dummy5, dummy3>::value,
"handle not assignable to narrower definition");
static_assert(std::is_convertible<dummy5, dummy4>::value,
"handle not assignable to narrower definition");
/******************************************************************************
* simple request/response test *
******************************************************************************/
using server_type = typed_actor<replies_to<my_request>::with<bool>>;
server_type::behavior_type typed_server1() {
return {
[](const my_request& req) { return req.a == req.b; },
};
}
server_type::behavior_type typed_server2(server_type::pointer) {
return typed_server1();
}
class typed_server3 : public server_type::base {
public:
typed_server3(actor_config& cfg, const string& line, actor buddy)
: server_type::base(cfg) {
anon_send(buddy, line);
}
behavior_type make_behavior() override {
return typed_server2(this);
}
};
void client(event_based_actor* self, const actor& parent,
const server_type& serv) {
self->request(serv, infinite, my_request{0, 0}).then([=](bool val1) {
CAF_CHECK_EQUAL(val1, true);
self->request(serv, infinite, my_request{10, 20}).then([=](bool val2) {
CAF_CHECK_EQUAL(val2, false);
self->send(parent, ok_atom_v);
});
});
}
/******************************************************************************
* test skipping of messages intentionally + using become() *
******************************************************************************/
using event_testee_type
= typed_actor<replies_to<get_state_atom>::with<string>,
replies_to<string>::with<void>, replies_to<float>::with<void>,
replies_to<int>::with<int>>;
class event_testee : public event_testee_type::base {
public:
event_testee(actor_config& cfg) : event_testee_type::base(cfg) {
set_default_handler(skip);
}
behavior_type wait4string() {
return {
partial_behavior_init,
[=](get_state_atom) { return "wait4string"; },
[=](const string&) { become(wait4int()); },
};
}
behavior_type wait4int() {
return {
partial_behavior_init,
[=](get_state_atom) { return "wait4int"; },
[=](int) -> int {
become(wait4float());
return 42;
},
};
}
behavior_type wait4float() {
return {
partial_behavior_init,
[=](get_state_atom) { return "wait4float"; },
[=](float) { become(wait4string()); },
};
}
behavior_type make_behavior() override {
return wait4int();
}
};
/******************************************************************************
* simple 'forwarding' chain *
******************************************************************************/
using string_actor = typed_actor<replies_to<string>::with<string>>;
string_actor::behavior_type string_reverter() {
return {
[](string& str) -> string {
std::reverse(str.begin(), str.end());
return std::move(str);
},
};
}
// uses `return delegate(...)`
string_actor::behavior_type string_delegator(string_actor::pointer self,
string_actor master, bool leaf) {
auto next = leaf ? self->spawn(string_delegator, master, false) : master;
self->link_to(next);
return {
[=](string& str) -> delegated<string> {
return self->delegate(next, std::move(str));
},
};
}
using maybe_string_actor
= typed_actor<replies_to<string>::with<ok_atom, string>>;
maybe_string_actor::behavior_type maybe_string_reverter() {
return {
[](string& str) -> result<ok_atom, string> {
if (str.empty())
return sec::invalid_argument;
std::reverse(str.begin(), str.end());
return {ok_atom_v, std::move(str)};
},
};
}
maybe_string_actor::behavior_type
maybe_string_delegator(maybe_string_actor::pointer self,
const maybe_string_actor& x) {
self->link_to(x);
return {
[=](string& s) -> delegated<ok_atom, string> {
return self->delegate(x, std::move(s));
},
};
}
/******************************************************************************
* sending typed actor handles *
******************************************************************************/
int_actor::behavior_type int_fun() {
return {
[](int i) { return i * i; },
};
}
behavior foo(event_based_actor* self) {
return {
[=](int i, int_actor server) {
self->delegate(server, i);
self->quit();
},
};
}
int_actor::behavior_type int_fun2(int_actor::pointer self) {
self->set_down_handler([=](down_msg& dm) {
CAF_CHECK_EQUAL(dm.reason, exit_reason::normal);
self->quit();
});
return {
[=](int i) {
self->monitor(self->current_sender());
return i * i;
},
};
}
behavior foo2(event_based_actor* self) {
return {
[=](int i, int_actor server) {
self->delegate(server, i);
self->quit();
},
};
}
float_actor::behavior_type float_fun(float_actor::pointer self) {
return {
[=](float a) {
CAF_CHECK_EQUAL(a, 1.0f);
self->quit(exit_reason::user_shutdown);
},
};
}
int_actor::behavior_type foo3(int_actor::pointer self) {
auto b = self->spawn<linked>(float_fun);
self->send(b, 1.0f);
return {
[=](int) { return 0; },
};
}
struct fixture : test_coordinator_fixture<> {
void test_typed_spawn(server_type ts) {
CAF_MESSAGE("the server returns false for inequal numbers");
inject((my_request), from(self).to(ts).with(my_request{1, 2}));
expect((bool), from(ts).to(self).with(false));
CAF_MESSAGE("the server returns true for equal numbers");
inject((my_request), from(self).to(ts).with(my_request{42, 42}));
expect((bool), from(ts).to(self).with(true));
CAF_CHECK_EQUAL(sys.registry().running(), 2u);
auto c1 = self->spawn(client, self, ts);
run();
expect((ok_atom), from(c1).to(self).with(ok_atom_v));
CAF_CHECK_EQUAL(sys.registry().running(), 2u);
}
};
} // namespace
CAF_TEST_FIXTURE_SCOPE(typed_spawn_tests, fixture)
/******************************************************************************
* put it all together *
******************************************************************************/
CAF_TEST(typed_spawns) {
CAF_MESSAGE("run test series with typed_server1");
test_typed_spawn(sys.spawn(typed_server1));
self->await_all_other_actors_done();
CAF_MESSAGE("finished test series with `typed_server1`");
CAF_MESSAGE("run test series with typed_server2");
test_typed_spawn(sys.spawn(typed_server2));
self->await_all_other_actors_done();
CAF_MESSAGE("finished test series with `typed_server2`");
auto serv3 = self->spawn<typed_server3>("hi there", self);
run();
expect((string), from(serv3).to(self).with("hi there"s));
test_typed_spawn(serv3);
}
CAF_TEST(event_testee_series) {
auto et = self->spawn<event_testee>();
CAF_MESSAGE("et->message_types() returns an interface description");
typed_actor<replies_to<get_state_atom>::with<string>> sub_et = et;
std::set<string> iface{"(get_state_atom) -> (std::string)",
"(std::string) -> (void)", "(float) -> (void)",
"(int32_t) -> (int32_t)"};
CAF_CHECK_EQUAL(join(sub_et->message_types(), ","), join(iface, ","));
CAF_MESSAGE("the testee skips messages to drive its internal state machine");
self->send(et, 1);
self->send(et, 2);
self->send(et, 3);
self->send(et, .1f);
self->send(et, "hello event testee!"s);
self->send(et, .2f);
self->send(et, .3f);
self->send(et, "hello again event testee!"s);
self->send(et, "goodbye event testee!"s);
run();
expect((int), from(et).to(self).with(42));
expect((int), from(et).to(self).with(42));
expect((int), from(et).to(self).with(42));
inject((get_state_atom), from(self).to(sub_et).with(get_state_atom_v));
expect((string), from(et).to(self).with("wait4int"s));
}
CAF_TEST(string_delegator_chain) {
// run test series with string reverter
auto aut = self->spawn<monitored>(string_delegator,
sys.spawn(string_reverter), true);
std::set<string> iface{"(std::string) -> (std::string)"};
CAF_CHECK_EQUAL(aut->message_types(), iface);
inject((string), from(self).to(aut).with("Hello World!"s));
run();
expect((string), to(self).with("!dlroW olleH"s));
}
CAF_TEST(maybe_string_delegator_chain) {
CAF_LOG_TRACE(CAF_ARG(self));
auto aut = sys.spawn(maybe_string_delegator,
sys.spawn(maybe_string_reverter));
CAF_MESSAGE("send empty string, expect error");
inject((string), from(self).to(aut).with(""s));
run();
expect((error), to(self).with(sec::invalid_argument));
CAF_MESSAGE("send abcd string, expect dcba");
inject((string), from(self).to(aut).with("abcd"s));
run();
expect((ok_atom, string), to(self).with(ok_atom_v, "dcba"s));
}
CAF_TEST(sending_typed_actors) {
auto aut = sys.spawn(int_fun);
self->send(self->spawn(foo), 10, aut);
run();
expect((int), to(self).with(100));
self->spawn(foo3);
run();
}
CAF_TEST(sending_typed_actors_and_down_msg) {
auto aut = sys.spawn(int_fun2);
self->send(self->spawn(foo2), 10, aut);
run();
expect((int), to(self).with(100));
}
CAF_TEST(check_signature) {
using foo_type = typed_actor<replies_to<put_atom>::with<ok_atom>>;
using foo_result_type = result<ok_atom>;
using bar_type = typed_actor<reacts_to<ok_atom>>;
auto foo_action = [](foo_type::pointer ptr) -> foo_type::behavior_type {
return {
[=](put_atom) -> foo_result_type {
ptr->quit();
return {ok_atom_v};
},
};
};
auto bar_action = [=](bar_type::pointer ptr) -> bar_type::behavior_type {
auto foo = ptr->spawn<linked>(foo_action);
ptr->send(foo, put_atom_v);
return {
[=](ok_atom) { ptr->quit(); },
};
};
auto x = self->spawn(bar_action);
run();
}
SCENARIO("state classes may use typed pointers") {
GIVEN("a state class for a statically typed actor type") {
using foo_type = typed_actor<result<int32_t>(get_atom)>;
struct foo_state {
foo_state(foo_type::pointer_view selfptr) : self(selfptr) {
foo_type hdl{self};
CHECK_EQ(selfptr, actor_cast<abstract_actor*>(hdl));
foo_type hdl2{selfptr};
CHECK_EQ(hdl, hdl2);
}
foo_type::behavior_type make_behavior() {
return {
[](get_atom) { return int32_t{42}; },
};
}
foo_type::pointer_view self;
};
using foo_impl = stateful_actor<foo_state, foo_type::impl>;
WHEN("spawning a stateful actor using the state class") {
auto foo = sys.spawn<foo_impl>();
THEN("the actor calls make_behavior of the state class") {
inject((get_atom), from(self).to(foo).with(get_atom_v));
expect((int32_t), from(foo).to(self).with(42));
}
}
}
}
CAF_TEST_FIXTURE_SCOPE_END()
#endif // CAF_WINDOWS
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreLog.h"
#include <iomanip>
#include <iostream>
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT
# include <windows.h>
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_NACL
# include "ppapi/cpp/var.h"
# include "ppapi/cpp/instance.h"
#endif
namespace Ogre
{
#if OGRE_PLATFORM == OGRE_PLATFORM_NACL
pp::Instance* Log::mInstance = NULL;
#endif
//-----------------------------------------------------------------------
Log::Log( const String& name, bool debuggerOuput, bool suppressFile ) :
mLogLevel(LL_NORMAL), mDebugOut(debuggerOuput),
mSuppressFile(suppressFile), mTimeStamp(true), mLogName(name)
{
if (!mSuppressFile)
{
mLog.open(name.c_str());
}
}
//-----------------------------------------------------------------------
Log::~Log()
{
OGRE_LOCK_AUTO_MUTEX;
if (!mSuppressFile)
{
mLog.close();
}
}
//-----------------------------------------------------------------------
void Log::logMessage( const String& message, LogMessageLevel lml, bool maskDebug )
{
OGRE_LOCK_AUTO_MUTEX;
if ((mLogLevel + lml) >= OGRE_LOG_THRESHOLD)
{
bool skipThisMessage = false;
for( mtLogListener::iterator i = mListeners.begin(); i != mListeners.end(); ++i )
(*i)->messageLogged( message, lml, maskDebug, mLogName, skipThisMessage);
if (!skipThisMessage)
{
#if OGRE_PLATFORM == OGRE_PLATFORM_NACL
if(mInstance != NULL)
{
mInstance->PostMessage(message.c_str());
}
#else
if (mDebugOut && !maskDebug)
{
# if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT
# if OGRE_WCHAR_T_STRINGS
OutputDebugStringW(message.c_str());
OutputDebugStringW(L"\n");
# else
OutputDebugStringA(message.c_str());
OutputDebugStringA("\n");
# endif
# endif
if (lml == LML_CRITICAL)
std::cerr << message << std::endl;
else
std::cout << message << std::endl;
}
#endif
// Write time into log
if (!mSuppressFile)
{
if (mTimeStamp)
{
struct tm *pTime;
time_t ctTime; time(&ctTime);
pTime = localtime( &ctTime );
mLog << std::setw(2) << std::setfill('0') << pTime->tm_hour
<< ":" << std::setw(2) << std::setfill('0') << pTime->tm_min
<< ":" << std::setw(2) << std::setfill('0') << pTime->tm_sec
<< ": ";
}
mLog << message << std::endl;
// Flush stcmdream to ensure it is written (incase of a crash, we need log to be up to date)
mLog.flush();
}
}
}
}
//-----------------------------------------------------------------------
void Log::setTimeStampEnabled(bool timeStamp)
{
OGRE_LOCK_AUTO_MUTEX;
mTimeStamp = timeStamp;
}
//-----------------------------------------------------------------------
void Log::setDebugOutputEnabled(bool debugOutput)
{
OGRE_LOCK_AUTO_MUTEX;
mDebugOut = debugOutput;
}
//-----------------------------------------------------------------------
void Log::setLogDetail(LoggingLevel ll)
{
OGRE_LOCK_AUTO_MUTEX;
mLogLevel = ll;
}
//-----------------------------------------------------------------------
void Log::addListener(LogListener* listener)
{
OGRE_LOCK_AUTO_MUTEX;
mListeners.push_back(listener);
}
//-----------------------------------------------------------------------
void Log::removeListener(LogListener* listener)
{
OGRE_LOCK_AUTO_MUTEX;
mListeners.erase(std::find(mListeners.begin(), mListeners.end(), listener));
}
//---------------------------------------------------------------------
Log::Stream Log::stream(LogMessageLevel lml, bool maskDebug)
{
return Stream(this, lml, maskDebug);
}
}
<commit_msg>Call OutputDebugStringA/W only if OGRE_DEBUG_MODE, to reduce noise and prevent AppStore validation error on WinRT<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreLog.h"
#include <iomanip>
#include <iostream>
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT
# include <windows.h>
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_NACL
# include "ppapi/cpp/var.h"
# include "ppapi/cpp/instance.h"
#endif
namespace Ogre
{
#if OGRE_PLATFORM == OGRE_PLATFORM_NACL
pp::Instance* Log::mInstance = NULL;
#endif
//-----------------------------------------------------------------------
Log::Log( const String& name, bool debuggerOuput, bool suppressFile ) :
mLogLevel(LL_NORMAL), mDebugOut(debuggerOuput),
mSuppressFile(suppressFile), mTimeStamp(true), mLogName(name)
{
if (!mSuppressFile)
{
mLog.open(name.c_str());
}
}
//-----------------------------------------------------------------------
Log::~Log()
{
OGRE_LOCK_AUTO_MUTEX;
if (!mSuppressFile)
{
mLog.close();
}
}
//-----------------------------------------------------------------------
void Log::logMessage( const String& message, LogMessageLevel lml, bool maskDebug )
{
OGRE_LOCK_AUTO_MUTEX;
if ((mLogLevel + lml) >= OGRE_LOG_THRESHOLD)
{
bool skipThisMessage = false;
for( mtLogListener::iterator i = mListeners.begin(); i != mListeners.end(); ++i )
(*i)->messageLogged( message, lml, maskDebug, mLogName, skipThisMessage);
if (!skipThisMessage)
{
#if OGRE_PLATFORM == OGRE_PLATFORM_NACL
if(mInstance != NULL)
{
mInstance->PostMessage(message.c_str());
}
#else
if (mDebugOut && !maskDebug)
{
# if (OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT) && OGRE_DEBUG_MODE
# if OGRE_WCHAR_T_STRINGS
OutputDebugStringW(message.c_str());
OutputDebugStringW(L"\n");
# else
OutputDebugStringA(message.c_str());
OutputDebugStringA("\n");
# endif
# endif
if (lml == LML_CRITICAL)
std::cerr << message << std::endl;
else
std::cout << message << std::endl;
}
#endif
// Write time into log
if (!mSuppressFile)
{
if (mTimeStamp)
{
struct tm *pTime;
time_t ctTime; time(&ctTime);
pTime = localtime( &ctTime );
mLog << std::setw(2) << std::setfill('0') << pTime->tm_hour
<< ":" << std::setw(2) << std::setfill('0') << pTime->tm_min
<< ":" << std::setw(2) << std::setfill('0') << pTime->tm_sec
<< ": ";
}
mLog << message << std::endl;
// Flush stcmdream to ensure it is written (incase of a crash, we need log to be up to date)
mLog.flush();
}
}
}
}
//-----------------------------------------------------------------------
void Log::setTimeStampEnabled(bool timeStamp)
{
OGRE_LOCK_AUTO_MUTEX;
mTimeStamp = timeStamp;
}
//-----------------------------------------------------------------------
void Log::setDebugOutputEnabled(bool debugOutput)
{
OGRE_LOCK_AUTO_MUTEX;
mDebugOut = debugOutput;
}
//-----------------------------------------------------------------------
void Log::setLogDetail(LoggingLevel ll)
{
OGRE_LOCK_AUTO_MUTEX;
mLogLevel = ll;
}
//-----------------------------------------------------------------------
void Log::addListener(LogListener* listener)
{
OGRE_LOCK_AUTO_MUTEX;
mListeners.push_back(listener);
}
//-----------------------------------------------------------------------
void Log::removeListener(LogListener* listener)
{
OGRE_LOCK_AUTO_MUTEX;
mListeners.erase(std::find(mListeners.begin(), mListeners.end(), listener));
}
//---------------------------------------------------------------------
Log::Stream Log::stream(LogMessageLevel lml, bool maskDebug)
{
return Stream(this, lml, maskDebug);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007-2010 Digital Bazaar, Inc. All rights reserved.
*/
#include "monarch/config/ConfigManager.h"
#include "monarch/data/json/JsonWriter.h"
#include "monarch/io/File.h"
#include "monarch/io/FileOutputStream.h"
#include "monarch/rt/Exception.h"
#include "monarch/test/Test.h"
#include "monarch/test/TestModule.h"
using namespace std;
using namespace monarch::config;
using namespace monarch::io;
using namespace monarch::rt;
using namespace monarch::test;
namespace mo_test_config
{
static void runConfigManagerTest(TestRunner& tr)
{
tr.group("ConfigManager");
tr.test("init");
{
DynamicObject expect;
expect->setType(Map);
ConfigManager cm;
Config cfg;
cfg[ConfigManager::ID] = "config";
cfg[ConfigManager::MERGE]->setType(Map);
assert(cm.addConfig(cfg));
assertDynoCmp(cm.getConfig("config", true), cfg);
assertDynoCmp(cm.getConfig("config", false), expect);
assertDynoCmp(cm.getConfig("config"), expect);
}
tr.passIfNoException();
tr.test("init & clear");
{
DynamicObject expect;
expect->setType(Map);
ConfigManager cm;
Config cfg;
cfg[ConfigManager::ID] = "config";
cfg[ConfigManager::MERGE]->setType(Map);
assert(cm.addConfig(cfg));
cm.clear();
Config cfg2 = cm.getConfig("config");
assert(cfg2.isNull());
}
tr.passIfException();
tr.test("1 config");
{
DynamicObject expect;
expect->setType(Map);
expect["a"] = 0;
ConfigManager cm;
Config cfg;
cfg[ConfigManager::ID] = "config";
cfg[ConfigManager::MERGE]["a"] = 0;
assert(cm.addConfig(cfg));
assertNoException();
assertDynoCmp(cm.getConfig("config"), expect);
}
tr.passIfNoException();
tr.test("config change");
{
ConfigManager cm;
Config cfg;
cfg[ConfigManager::ID] = "config";
cfg[ConfigManager::MERGE]["a"] = 0;
assert(cm.addConfig(cfg));
DynamicObject a;
a["a"] = 0;
assertDynoCmp(cm.getConfig("config"), a);
Config change = cm.getConfig("config", true);
change[ConfigManager::MERGE]["a"] = 1;
assert(cm.setConfig(change));
DynamicObject expect;
expect["a"] = 1;
assert(cm.getConfig("config") != a);
assertDynoCmp(cm.getConfig("config"), expect);
}
tr.passIfNoException();
tr.test("invalid set config");
{
ConfigManager cm;
Config cfg;
cfg[ConfigManager::ID] = "config";
cfg[ConfigManager::MERGE]["a"] = 0;
assert(!cm.setConfig(cfg));
}
tr.passIfException();
tr.test("double add config");
{
ConfigManager cm;
Config cfg;
cfg[ConfigManager::ID] = "config";
cfg[ConfigManager::MERGE]["a"] = 0;
assert(cm.addConfig(cfg));
cfg[ConfigManager::MERGE]["a"] = 1;
assert(cm.addConfig(cfg));
DynamicObject expect;
expect["a"] = 1;
assertDynoCmp(cm.getConfig("config"), expect);
}
tr.passIfNoException();
tr.test("add");
{
DynamicObject expect;
expect["a"] = 0;
expect["b"] = 1;
expect["c"] = 2;
ConfigManager cm;
Config a;
a[ConfigManager::ID] = "config";
a[ConfigManager::MERGE]["a"] = 0;
Config b;
b[ConfigManager::ID] = "config";
b[ConfigManager::MERGE]["b"] = 1;
Config c;
c[ConfigManager::ID] = "config";
c[ConfigManager::MERGE]["c"] = 2;
assert(cm.addConfig(a));
assertNoException();
assert(cm.addConfig(b));
assertNoException();
assert(cm.addConfig(c));
assertNoException();
assertDynoCmp(cm.getConfig("config"), expect);
}
tr.passIfNoException();
tr.test("bad remove");
{
ConfigManager cm;
assert(!cm.removeConfig("error"));
assertException();
Exception::clear();
}
tr.passIfNoException();
tr.test("remove");
{
DynamicObject expect;
expect["a"] = 0;
expect["b"] = 1;
expect["c"] = 2;
ConfigManager cm;
Config a;
a[ConfigManager::ID] = "config a";
a[ConfigManager::GROUP] = "group";
a[ConfigManager::MERGE]["a"] = 0;
Config b;
b[ConfigManager::ID] = "config b";
b[ConfigManager::GROUP] = "group";
b[ConfigManager::MERGE]["b"] = 1;
Config c;
c[ConfigManager::ID] = "config c";
c[ConfigManager::GROUP] = "group";
c[ConfigManager::MERGE]["c"] = 2;
assert(cm.addConfig(a));
assertNoException();
assert(cm.addConfig(b));
assertNoException();
assert(cm.addConfig(c));
assertNoException();
assertDynoCmp(cm.getConfig("group"), expect);
DynamicObject expect2;
expect2["a"] = 0;
expect2["c"] = 2;
assert(cm.removeConfig("config b"));
assertDynoCmp(cm.getConfig("group"), expect2);
}
tr.passIfNoException();
tr.test("default value");
{
ConfigManager cm;
Config a;
a[ConfigManager::ID] = "config a";
a[ConfigManager::MERGE] = 1;
assert(cm.addConfig(a));
assertNoException();
Config b;
b[ConfigManager::ID] = "config b";
b[ConfigManager::PARENT] = "config a";
b[ConfigManager::MERGE] = ConfigManager::DEFAULT_VALUE;
assert(cm.addConfig(b));
assertNoException();
DynamicObject expect;
expect = 1;
assertDynoCmp(cm.getConfig("config b"), expect);
}
tr.passIfNoException();
tr.test("default values");
{
ConfigManager cm;
Config cfga;
cfga[ConfigManager::ID] = "config a";
Config& a = cfga[ConfigManager::MERGE];
a[0] = 10;
a[1] = 11;
a[2]["0"] = 120;
a[2]["1"] = 121;
assert(cm.addConfig(cfga));
assertNoException();
Config cfgb;
cfgb[ConfigManager::ID] = "config b";
cfgb[ConfigManager::PARENT] = "config a";
Config& b = cfgb[ConfigManager::MERGE];
b[0] = ConfigManager::DEFAULT_VALUE;
b[1] = 21;
b[2]["0"] = ConfigManager::DEFAULT_VALUE;
b[2]["1"] = 221;
assert(cm.addConfig(cfgb));
assertNoException();
DynamicObject expect;
expect[0] = 10;
expect[1] = 21;
expect[2]["0"] = 120;
expect[2]["1"] = 221;
assertDynoCmp(cm.getConfig("config b"), expect);
}
tr.passIfNoException();
tr.test("keyword substitution {RESOURCE_DIR}");
{
DynamicObject expect;
expect["dir"] = "/the/real/dir";
expect["dir-plus"] = "/the/real/dir/plus/more";
//expect["name"] = "Digital Bazaar, Inc.";
ConfigManager cm;
Config a;
a[ConfigManager::ID] = "config";
a[ConfigManager::MERGE]["dir"] = "{RESOURCE_DIR}";
a[ConfigManager::MERGE]["dir-plus"] = "{RESOURCE_DIR}/plus/more";
// FIXME: only supports "{RESOURCE_DIR}" now
//a[ConfigManager::MERGE]["other"] = "{DB}";
cm.setKeyword("RESOURCE_DIR", "/the/real/dir");
//cm.setKeyword("DB", "Digital Bazaar, Inc.");
assert(cm.addConfig(a));
assertNoException();
assertDynoCmp(cm.getConfig("config"), expect);
}
tr.passIfNoException();
tr.test("keyword substitution {CURRENT_DIR}");
{
DynamicObject expect;
string cwd;
string cwdPlusMore;
string absoluteDir;
File configFile = File::createTempFile("test-config-file");
FileOutputStream fos(configFile);
// create and populate the config file
string configFileText =
"{\n"
"\"_id_\": \"config\",\n"
"\"_merge_\": {\n"
" \"dir\": \"{CURRENT_DIR}\",\n"
" \"dir-plus\": \"{CURRENT_DIR}/plus/more\" }\n"
"}\n";
fos.write(configFileText.c_str(), configFileText.length());
fos.close();
// modify the current working directory to the expected value
absoluteDir = File::dirname(configFile->getAbsolutePath());
cwd = absoluteDir.c_str();
cwdPlusMore = cwd.c_str();
cwdPlusMore.append("/plus/more");
// set the expected values
expect["dir"] = cwd.c_str();
expect["dir-plus"] = cwdPlusMore.c_str();
// create the configuration
ConfigManager cm;
assert(cm.addConfigFile(configFile->getAbsolutePath(),
true, absoluteDir.c_str(), true, false));
assertNoException();
assertDynoCmp(cm.getConfig("config"), expect);
}
tr.passIfNoException();
#if 0
tr.test("user preferences");
{
ConfigManager cm;
// node
// built in or loaded defaults
DynamicObject nodec;
nodec["node"]["host"] = "localhost";
nodec["node"]["port"] = 19100;
nodec["node"]["modulePath"] = "/usr/lib/bitmunk/modules";
nodec["node"]["userModulePath"] = "~/.bitmunk/modules";
assert(cm.addConfig(nodec));
assertNoException();
// user
// loaded defaults
DynamicObject userc;
userc["node"]["port"] = 19100;
userc["node"]["comment"] = "My precious...";
assert(cm.addConfig(userc, ConfigManager::Custom));
assertNoException();
// user makes changes during runtime
DynamicObject c = cm.getConfig();
c["node"]["port"] = 19200;
c["node"]["userModulePath"] = "~/.bitmunk/modules:~/.bitmunk/modules-dev";
c["node"][ConfigManager::TMP]["not in changes"] = true;
// get the changes from defaults to current config
// serialize this to disk as needed
DynamicObject changes;
cm.getChanges(changes);
// check it's correct
DynamicObject expect;
expect["node"]["port"] = 19200;
expect["node"]["comment"] = "My precious...";
expect["node"]["userModulePath"] = "~/.bitmunk/modules:~/.bitmunk/modules-dev";
// NOTE: will not have TMP var
assertDynoCmp(changes, expect);
}
tr.passIfNoException();
#endif
tr.test("versioning");
{
ConfigManager cm;
cm.getVersions()->clear();
Config c;
c[ConfigManager::ID] = "config";
assert(cm.addConfig(c));
assertNoException();
cm.addVersion("1");
assert(!cm.addConfig(c));
assertException();
Exception::clear();
c[ConfigManager::VERSION] = "2";
cm.removeConfig("config");
assert(!cm.addConfig(c));
assertException();
Exception::clear();
c[ConfigManager::VERSION] = "1";
assert(cm.addConfig(c));
assertNoException();
c[ConfigManager::VERSION] = "2";
cm.removeConfig("config");
cm.addVersion("2");
assert(cm.addConfig(c));
assertNoException();
}
tr.passIfNoException();
tr.test("empty array & map");
{
ConfigManager cm;
DynamicObject a;
a[ConfigManager::ID] = "config";
a[ConfigManager::MERGE][0]->setType(Array);
a[ConfigManager::MERGE][1]->setType(Map);
assert(cm.addConfig(a));
assertNoException();
DynamicObject expect;
expect[0]->setType(Array);
expect[1]->setType(Map);
assertDynoCmp(cm.getConfig("config"), expect);
}
tr.passIfNoException();
tr.test("empty group ids");
{
ConfigManager cm;
DynamicObject expect;
expect->setType(Array);
assertDynoCmp(cm.getIdsInGroup("Not-A-Group"), expect);
}
tr.passIfNoException();
tr.test("group ids");
{
ConfigManager cm;
DynamicObject c;
c[ConfigManager::ID] = "c0";
c[ConfigManager::GROUP] = "c";
assert(cm.addConfig(c));
assertNoException();
c[ConfigManager::ID] = "c1";
c[ConfigManager::GROUP] = "c";
assert(cm.addConfig(c));
assertNoException();
DynamicObject expect;
expect->setType(Array);
expect[0] = "c0";
expect[1] = "c1";
assertDynoCmp(cm.getIdsInGroup("c"), expect);
}
tr.passIfNoException();
tr.test("replace keywords");
{
ConfigManager cm;
DynamicObject c;
bool success;
c[ConfigManager::ID] = "c";
c[ConfigManager::MERGE]["test"] = "{A}";
DynamicObject vars;
vars["A"] = "a";
success = ConfigManager::replaceKeywords(c, vars);
assertNoException();
assert(success);
DynamicObject expect;
expect[ConfigManager::ID] = "c";
expect[ConfigManager::MERGE]["test"] = "a";
assertDynoCmp(c, expect);
}
tr.passIfNoException();
tr.test("replace keywords (invalid keyword)");
{
ConfigManager cm;
DynamicObject c;
bool success;
c[ConfigManager::ID] = "c";
c[ConfigManager::MERGE]["test"] = "{UNKNOWN}";
DynamicObject vars;
vars["A"] = "a";
success = ConfigManager::replaceKeywords(c, vars);
assertException();
assert(!success);
}
tr.passIfException();
tr.ungroup();
}
static bool run(TestRunner& tr)
{
if(tr.isDefaultEnabled())
{
runConfigManagerTest(tr);
}
return true;
}
} // end namespace
MO_TEST_MODULE_FN("monarch.tests.config.test", "1.0", mo_test_config::run)
<commit_msg>Append modulePath to an array.<commit_after>/*
* Copyright (c) 2007-2010 Digital Bazaar, Inc. All rights reserved.
*/
#include "monarch/config/ConfigManager.h"
#include "monarch/data/json/JsonWriter.h"
#include "monarch/io/File.h"
#include "monarch/io/FileOutputStream.h"
#include "monarch/rt/Exception.h"
#include "monarch/test/Test.h"
#include "monarch/test/TestModule.h"
using namespace std;
using namespace monarch::config;
using namespace monarch::io;
using namespace monarch::rt;
using namespace monarch::test;
namespace mo_test_config
{
static void runConfigManagerTest(TestRunner& tr)
{
tr.group("ConfigManager");
tr.test("init");
{
DynamicObject expect;
expect->setType(Map);
ConfigManager cm;
Config cfg;
cfg[ConfigManager::ID] = "config";
cfg[ConfigManager::MERGE]->setType(Map);
assert(cm.addConfig(cfg));
assertDynoCmp(cm.getConfig("config", true), cfg);
assertDynoCmp(cm.getConfig("config", false), expect);
assertDynoCmp(cm.getConfig("config"), expect);
}
tr.passIfNoException();
tr.test("init & clear");
{
DynamicObject expect;
expect->setType(Map);
ConfigManager cm;
Config cfg;
cfg[ConfigManager::ID] = "config";
cfg[ConfigManager::MERGE]->setType(Map);
assert(cm.addConfig(cfg));
cm.clear();
Config cfg2 = cm.getConfig("config");
assert(cfg2.isNull());
}
tr.passIfException();
tr.test("1 config");
{
DynamicObject expect;
expect->setType(Map);
expect["a"] = 0;
ConfigManager cm;
Config cfg;
cfg[ConfigManager::ID] = "config";
cfg[ConfigManager::MERGE]["a"] = 0;
assert(cm.addConfig(cfg));
assertNoException();
assertDynoCmp(cm.getConfig("config"), expect);
}
tr.passIfNoException();
tr.test("config change");
{
ConfigManager cm;
Config cfg;
cfg[ConfigManager::ID] = "config";
cfg[ConfigManager::MERGE]["a"] = 0;
assert(cm.addConfig(cfg));
DynamicObject a;
a["a"] = 0;
assertDynoCmp(cm.getConfig("config"), a);
Config change = cm.getConfig("config", true);
change[ConfigManager::MERGE]["a"] = 1;
assert(cm.setConfig(change));
DynamicObject expect;
expect["a"] = 1;
assert(cm.getConfig("config") != a);
assertDynoCmp(cm.getConfig("config"), expect);
}
tr.passIfNoException();
tr.test("invalid set config");
{
ConfigManager cm;
Config cfg;
cfg[ConfigManager::ID] = "config";
cfg[ConfigManager::MERGE]["a"] = 0;
assert(!cm.setConfig(cfg));
}
tr.passIfException();
tr.test("double add config");
{
ConfigManager cm;
Config cfg;
cfg[ConfigManager::ID] = "config";
cfg[ConfigManager::MERGE]["a"] = 0;
assert(cm.addConfig(cfg));
cfg[ConfigManager::MERGE]["a"] = 1;
assert(cm.addConfig(cfg));
DynamicObject expect;
expect["a"] = 1;
assertDynoCmp(cm.getConfig("config"), expect);
}
tr.passIfNoException();
tr.test("add");
{
DynamicObject expect;
expect["a"] = 0;
expect["b"] = 1;
expect["c"] = 2;
ConfigManager cm;
Config a;
a[ConfigManager::ID] = "config";
a[ConfigManager::MERGE]["a"] = 0;
Config b;
b[ConfigManager::ID] = "config";
b[ConfigManager::MERGE]["b"] = 1;
Config c;
c[ConfigManager::ID] = "config";
c[ConfigManager::MERGE]["c"] = 2;
assert(cm.addConfig(a));
assertNoException();
assert(cm.addConfig(b));
assertNoException();
assert(cm.addConfig(c));
assertNoException();
assertDynoCmp(cm.getConfig("config"), expect);
}
tr.passIfNoException();
tr.test("bad remove");
{
ConfigManager cm;
assert(!cm.removeConfig("error"));
assertException();
Exception::clear();
}
tr.passIfNoException();
tr.test("remove");
{
DynamicObject expect;
expect["a"] = 0;
expect["b"] = 1;
expect["c"] = 2;
ConfigManager cm;
Config a;
a[ConfigManager::ID] = "config a";
a[ConfigManager::GROUP] = "group";
a[ConfigManager::MERGE]["a"] = 0;
Config b;
b[ConfigManager::ID] = "config b";
b[ConfigManager::GROUP] = "group";
b[ConfigManager::MERGE]["b"] = 1;
Config c;
c[ConfigManager::ID] = "config c";
c[ConfigManager::GROUP] = "group";
c[ConfigManager::MERGE]["c"] = 2;
assert(cm.addConfig(a));
assertNoException();
assert(cm.addConfig(b));
assertNoException();
assert(cm.addConfig(c));
assertNoException();
assertDynoCmp(cm.getConfig("group"), expect);
DynamicObject expect2;
expect2["a"] = 0;
expect2["c"] = 2;
assert(cm.removeConfig("config b"));
assertDynoCmp(cm.getConfig("group"), expect2);
}
tr.passIfNoException();
tr.test("default value");
{
ConfigManager cm;
Config a;
a[ConfigManager::ID] = "config a";
a[ConfigManager::MERGE] = 1;
assert(cm.addConfig(a));
assertNoException();
Config b;
b[ConfigManager::ID] = "config b";
b[ConfigManager::PARENT] = "config a";
b[ConfigManager::MERGE] = ConfigManager::DEFAULT_VALUE;
assert(cm.addConfig(b));
assertNoException();
DynamicObject expect;
expect = 1;
assertDynoCmp(cm.getConfig("config b"), expect);
}
tr.passIfNoException();
tr.test("default values");
{
ConfigManager cm;
Config cfga;
cfga[ConfigManager::ID] = "config a";
Config& a = cfga[ConfigManager::MERGE];
a[0] = 10;
a[1] = 11;
a[2]["0"] = 120;
a[2]["1"] = 121;
assert(cm.addConfig(cfga));
assertNoException();
Config cfgb;
cfgb[ConfigManager::ID] = "config b";
cfgb[ConfigManager::PARENT] = "config a";
Config& b = cfgb[ConfigManager::MERGE];
b[0] = ConfigManager::DEFAULT_VALUE;
b[1] = 21;
b[2]["0"] = ConfigManager::DEFAULT_VALUE;
b[2]["1"] = 221;
assert(cm.addConfig(cfgb));
assertNoException();
DynamicObject expect;
expect[0] = 10;
expect[1] = 21;
expect[2]["0"] = 120;
expect[2]["1"] = 221;
assertDynoCmp(cm.getConfig("config b"), expect);
}
tr.passIfNoException();
tr.test("keyword substitution {RESOURCE_DIR}");
{
DynamicObject expect;
expect["dir"] = "/the/real/dir";
expect["dir-plus"] = "/the/real/dir/plus/more";
//expect["name"] = "Digital Bazaar, Inc.";
ConfigManager cm;
Config a;
a[ConfigManager::ID] = "config";
a[ConfigManager::MERGE]["dir"] = "{RESOURCE_DIR}";
a[ConfigManager::MERGE]["dir-plus"] = "{RESOURCE_DIR}/plus/more";
// FIXME: only supports "{RESOURCE_DIR}" now
//a[ConfigManager::MERGE]["other"] = "{DB}";
cm.setKeyword("RESOURCE_DIR", "/the/real/dir");
//cm.setKeyword("DB", "Digital Bazaar, Inc.");
assert(cm.addConfig(a));
assertNoException();
assertDynoCmp(cm.getConfig("config"), expect);
}
tr.passIfNoException();
tr.test("keyword substitution {CURRENT_DIR}");
{
DynamicObject expect;
string cwd;
string cwdPlusMore;
string absoluteDir;
File configFile = File::createTempFile("test-config-file");
FileOutputStream fos(configFile);
// create and populate the config file
string configFileText =
"{\n"
"\"_id_\": \"config\",\n"
"\"_merge_\": {\n"
" \"dir\": \"{CURRENT_DIR}\",\n"
" \"dir-plus\": \"{CURRENT_DIR}/plus/more\" }\n"
"}\n";
fos.write(configFileText.c_str(), configFileText.length());
fos.close();
// modify the current working directory to the expected value
absoluteDir = File::dirname(configFile->getAbsolutePath());
cwd = absoluteDir.c_str();
cwdPlusMore = cwd.c_str();
cwdPlusMore.append("/plus/more");
// set the expected values
expect["dir"] = cwd.c_str();
expect["dir-plus"] = cwdPlusMore.c_str();
// create the configuration
ConfigManager cm;
assert(cm.addConfigFile(configFile->getAbsolutePath(),
true, absoluteDir.c_str(), true, false));
assertNoException();
assertDynoCmp(cm.getConfig("config"), expect);
}
tr.passIfNoException();
#if 0
tr.test("user preferences");
{
ConfigManager cm;
// node
// built in or loaded defaults
DynamicObject nodec;
nodec["node"]["host"] = "localhost";
nodec["node"]["port"] = 19100;
nodec["node"]["modulePath"]->append() = "/usr/lib/bitmunk/modules";
nodec["node"]["userModulePath"] = "~/.bitmunk/modules";
assert(cm.addConfig(nodec));
assertNoException();
// user
// loaded defaults
DynamicObject userc;
userc["node"]["port"] = 19100;
userc["node"]["comment"] = "My precious...";
assert(cm.addConfig(userc, ConfigManager::Custom));
assertNoException();
// user makes changes during runtime
DynamicObject c = cm.getConfig();
c["node"]["port"] = 19200;
c["node"]["userModulePath"] = "~/.bitmunk/modules:~/.bitmunk/modules-dev";
c["node"][ConfigManager::TMP]["not in changes"] = true;
// get the changes from defaults to current config
// serialize this to disk as needed
DynamicObject changes;
cm.getChanges(changes);
// check it's correct
DynamicObject expect;
expect["node"]["port"] = 19200;
expect["node"]["comment"] = "My precious...";
expect["node"]["userModulePath"] = "~/.bitmunk/modules:~/.bitmunk/modules-dev";
// NOTE: will not have TMP var
assertDynoCmp(changes, expect);
}
tr.passIfNoException();
#endif
tr.test("versioning");
{
ConfigManager cm;
cm.getVersions()->clear();
Config c;
c[ConfigManager::ID] = "config";
assert(cm.addConfig(c));
assertNoException();
cm.addVersion("1");
assert(!cm.addConfig(c));
assertException();
Exception::clear();
c[ConfigManager::VERSION] = "2";
cm.removeConfig("config");
assert(!cm.addConfig(c));
assertException();
Exception::clear();
c[ConfigManager::VERSION] = "1";
assert(cm.addConfig(c));
assertNoException();
c[ConfigManager::VERSION] = "2";
cm.removeConfig("config");
cm.addVersion("2");
assert(cm.addConfig(c));
assertNoException();
}
tr.passIfNoException();
tr.test("empty array & map");
{
ConfigManager cm;
DynamicObject a;
a[ConfigManager::ID] = "config";
a[ConfigManager::MERGE][0]->setType(Array);
a[ConfigManager::MERGE][1]->setType(Map);
assert(cm.addConfig(a));
assertNoException();
DynamicObject expect;
expect[0]->setType(Array);
expect[1]->setType(Map);
assertDynoCmp(cm.getConfig("config"), expect);
}
tr.passIfNoException();
tr.test("empty group ids");
{
ConfigManager cm;
DynamicObject expect;
expect->setType(Array);
assertDynoCmp(cm.getIdsInGroup("Not-A-Group"), expect);
}
tr.passIfNoException();
tr.test("group ids");
{
ConfigManager cm;
DynamicObject c;
c[ConfigManager::ID] = "c0";
c[ConfigManager::GROUP] = "c";
assert(cm.addConfig(c));
assertNoException();
c[ConfigManager::ID] = "c1";
c[ConfigManager::GROUP] = "c";
assert(cm.addConfig(c));
assertNoException();
DynamicObject expect;
expect->setType(Array);
expect[0] = "c0";
expect[1] = "c1";
assertDynoCmp(cm.getIdsInGroup("c"), expect);
}
tr.passIfNoException();
tr.test("replace keywords");
{
ConfigManager cm;
DynamicObject c;
bool success;
c[ConfigManager::ID] = "c";
c[ConfigManager::MERGE]["test"] = "{A}";
DynamicObject vars;
vars["A"] = "a";
success = ConfigManager::replaceKeywords(c, vars);
assertNoException();
assert(success);
DynamicObject expect;
expect[ConfigManager::ID] = "c";
expect[ConfigManager::MERGE]["test"] = "a";
assertDynoCmp(c, expect);
}
tr.passIfNoException();
tr.test("replace keywords (invalid keyword)");
{
ConfigManager cm;
DynamicObject c;
bool success;
c[ConfigManager::ID] = "c";
c[ConfigManager::MERGE]["test"] = "{UNKNOWN}";
DynamicObject vars;
vars["A"] = "a";
success = ConfigManager::replaceKeywords(c, vars);
assertException();
assert(!success);
}
tr.passIfException();
tr.ungroup();
}
static bool run(TestRunner& tr)
{
if(tr.isDefaultEnabled())
{
runConfigManagerTest(tr);
}
return true;
}
} // end namespace
MO_TEST_MODULE_FN("monarch.tests.config.test", "1.0", mo_test_config::run)
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2014 The QXmpp developers
*
* Author:
* Jeremy Lainé
*
* Source:
* https://github.com/qxmpp-project/qxmpp
*
* This file is a part of QXmpp library.
*
* 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.
*
*/
#include <QDomElement>
#include "QXmppConstants.h"
#include "QXmppStreamFeatures.h"
QXmppStreamFeatures::QXmppStreamFeatures()
: m_bindMode(Disabled),
m_sessionMode(Disabled),
m_nonSaslAuthMode(Disabled),
m_tlsMode(Disabled)
{
}
QXmppStreamFeatures::Mode QXmppStreamFeatures::bindMode() const
{
return m_bindMode;
}
void QXmppStreamFeatures::setBindMode(QXmppStreamFeatures::Mode mode)
{
m_bindMode = mode;
}
QXmppStreamFeatures::Mode QXmppStreamFeatures::sessionMode() const
{
return m_sessionMode;
}
void QXmppStreamFeatures::setSessionMode(Mode mode)
{
m_sessionMode = mode;
}
QXmppStreamFeatures::Mode QXmppStreamFeatures::nonSaslAuthMode() const
{
return m_nonSaslAuthMode;
}
void QXmppStreamFeatures::setNonSaslAuthMode(QXmppStreamFeatures::Mode mode)
{
m_nonSaslAuthMode = mode;
}
QStringList QXmppStreamFeatures::authMechanisms() const
{
return m_authMechanisms;
}
void QXmppStreamFeatures::setAuthMechanisms(const QStringList &mechanisms)
{
m_authMechanisms = mechanisms;
}
QStringList QXmppStreamFeatures::compressionMethods() const
{
return m_compressionMethods;
}
void QXmppStreamFeatures::setCompressionMethods(const QStringList &methods)
{
m_compressionMethods = methods;
}
QXmppStreamFeatures::Mode QXmppStreamFeatures::tlsMode() const
{
return m_tlsMode;
}
void QXmppStreamFeatures::setTlsMode(QXmppStreamFeatures::Mode mode)
{
m_tlsMode = mode;
}
QXmppStreamFeatures::Mode QXmppStreamFeatures::streamManagementMode() const
{
return m_streamManagementMode;
}
void QXmppStreamFeatures::setStreamManagementMode(Mode mode)
{
m_streamManagementMode = mode;
}
/// \cond
bool QXmppStreamFeatures::isStreamFeatures(const QDomElement &element)
{
return element.namespaceURI() == ns_stream &&
element.tagName() == "features";
}
static QXmppStreamFeatures::Mode readFeature(const QDomElement &element, const char *tagName, const char *tagNs)
{
QDomElement subElement = element.firstChildElement(tagName);
if (subElement.namespaceURI() == tagNs)
{
if (!subElement.firstChildElement("required").isNull())
return QXmppStreamFeatures::Required;
else
return QXmppStreamFeatures::Enabled;
} else {
return QXmppStreamFeatures::Disabled;
}
}
void QXmppStreamFeatures::parse(const QDomElement &element)
{
m_bindMode = readFeature(element, "bind", ns_bind);
m_sessionMode = readFeature(element, "session", ns_session);
m_nonSaslAuthMode = readFeature(element, "auth", ns_authFeature);
m_tlsMode = readFeature(element, "starttls", ns_tls);
m_streamManagementMode = readFeature(element, "sm", ns_stream_management);
// parse advertised compression methods
QDomElement compression = element.firstChildElement("compression");
if (compression.namespaceURI() == ns_compressFeature)
{
QDomElement subElement = compression.firstChildElement("method");
while(!subElement.isNull())
{
m_compressionMethods << subElement.text();
subElement = subElement.nextSiblingElement("method");
}
}
// parse advertised SASL Authentication mechanisms
QDomElement mechs = element.firstChildElement("mechanisms");
if (mechs.namespaceURI() == ns_sasl)
{
QDomElement subElement = mechs.firstChildElement("mechanism");
while(!subElement.isNull()) {
m_authMechanisms << subElement.text();
subElement = subElement.nextSiblingElement("mechanism");
}
}
}
static void writeFeature(QXmlStreamWriter *writer, const char *tagName, const char *tagNs, QXmppStreamFeatures::Mode mode)
{
if (mode != QXmppStreamFeatures::Disabled)
{
writer->writeStartElement(tagName);
writer->writeAttribute("xmlns", tagNs);
if (mode == QXmppStreamFeatures::Required)
writer->writeEmptyElement("required");
writer->writeEndElement();
}
}
void QXmppStreamFeatures::toXml(QXmlStreamWriter *writer) const
{
writer->writeStartElement("stream:features");
writeFeature(writer, "bind", ns_bind, m_bindMode);
writeFeature(writer, "session", ns_session, m_sessionMode);
writeFeature(writer, "auth", ns_authFeature, m_nonSaslAuthMode);
writeFeature(writer, "starttls", ns_tls, m_tlsMode);
if (!m_compressionMethods.isEmpty())
{
writer->writeStartElement("compression");
writer->writeAttribute("xmlns", ns_compressFeature);
foreach (const QString &method, m_compressionMethods)
writer->writeTextElement("method", method);
writer->writeEndElement();
}
if (!m_authMechanisms.isEmpty())
{
writer->writeStartElement("mechanisms");
writer->writeAttribute("xmlns", ns_sasl);
foreach (const QString &mechanism, m_authMechanisms)
writer->writeTextElement("mechanism", mechanism);
writer->writeEndElement();
}
writeFeature(writer, "sm", ns_stream_management, m_streamManagementMode);
writer->writeEndElement();
}
/// \endcond
<commit_msg>Fixed bug, what some server features not parsed correctly<commit_after>/*
* Copyright (C) 2008-2014 The QXmpp developers
*
* Author:
* Jeremy Lainé
*
* Source:
* https://github.com/qxmpp-project/qxmpp
*
* This file is a part of QXmpp library.
*
* 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.
*
*/
#include <QDomElement>
#include "QXmppConstants.h"
#include "QXmppStreamFeatures.h"
QXmppStreamFeatures::QXmppStreamFeatures()
: m_bindMode(Disabled),
m_sessionMode(Disabled),
m_nonSaslAuthMode(Disabled),
m_tlsMode(Disabled)
{
}
QXmppStreamFeatures::Mode QXmppStreamFeatures::bindMode() const
{
return m_bindMode;
}
void QXmppStreamFeatures::setBindMode(QXmppStreamFeatures::Mode mode)
{
m_bindMode = mode;
}
QXmppStreamFeatures::Mode QXmppStreamFeatures::sessionMode() const
{
return m_sessionMode;
}
void QXmppStreamFeatures::setSessionMode(Mode mode)
{
m_sessionMode = mode;
}
QXmppStreamFeatures::Mode QXmppStreamFeatures::nonSaslAuthMode() const
{
return m_nonSaslAuthMode;
}
void QXmppStreamFeatures::setNonSaslAuthMode(QXmppStreamFeatures::Mode mode)
{
m_nonSaslAuthMode = mode;
}
QStringList QXmppStreamFeatures::authMechanisms() const
{
return m_authMechanisms;
}
void QXmppStreamFeatures::setAuthMechanisms(const QStringList &mechanisms)
{
m_authMechanisms = mechanisms;
}
QStringList QXmppStreamFeatures::compressionMethods() const
{
return m_compressionMethods;
}
void QXmppStreamFeatures::setCompressionMethods(const QStringList &methods)
{
m_compressionMethods = methods;
}
QXmppStreamFeatures::Mode QXmppStreamFeatures::tlsMode() const
{
return m_tlsMode;
}
void QXmppStreamFeatures::setTlsMode(QXmppStreamFeatures::Mode mode)
{
m_tlsMode = mode;
}
QXmppStreamFeatures::Mode QXmppStreamFeatures::streamManagementMode() const
{
return m_streamManagementMode;
}
void QXmppStreamFeatures::setStreamManagementMode(Mode mode)
{
m_streamManagementMode = mode;
}
/// \cond
bool QXmppStreamFeatures::isStreamFeatures(const QDomElement &element)
{
return element.namespaceURI() == ns_stream &&
element.tagName() == "features";
}
static QXmppStreamFeatures::Mode readFeature(const QDomElement &element, const char *tagName, const char *tagNs)
{
QDomElement subElement = element.firstChildElement(tagName);
while (!subElement.isNull()) {
if (subElement.namespaceURI() == tagNs) {
if (!subElement.firstChildElement("required").isNull())
return QXmppStreamFeatures::Required;
return QXmppStreamFeatures::Enabled;
}
subElement = subElement.nextSiblingElement();
}
return QXmppStreamFeatures::Disabled;
}
void QXmppStreamFeatures::parse(const QDomElement &element)
{
m_bindMode = readFeature(element, "bind", ns_bind);
m_sessionMode = readFeature(element, "session", ns_session);
m_nonSaslAuthMode = readFeature(element, "auth", ns_authFeature);
m_tlsMode = readFeature(element, "starttls", ns_tls);
m_streamManagementMode = readFeature(element, "sm", ns_stream_management);
// parse advertised compression methods
QDomElement compression = element.firstChildElement("compression");
if (compression.namespaceURI() == ns_compressFeature)
{
QDomElement subElement = compression.firstChildElement("method");
while(!subElement.isNull())
{
m_compressionMethods << subElement.text();
subElement = subElement.nextSiblingElement("method");
}
}
// parse advertised SASL Authentication mechanisms
QDomElement mechs = element.firstChildElement("mechanisms");
if (mechs.namespaceURI() == ns_sasl)
{
QDomElement subElement = mechs.firstChildElement("mechanism");
while(!subElement.isNull()) {
m_authMechanisms << subElement.text();
subElement = subElement.nextSiblingElement("mechanism");
}
}
}
static void writeFeature(QXmlStreamWriter *writer, const char *tagName, const char *tagNs, QXmppStreamFeatures::Mode mode)
{
if (mode != QXmppStreamFeatures::Disabled)
{
writer->writeStartElement(tagName);
writer->writeAttribute("xmlns", tagNs);
if (mode == QXmppStreamFeatures::Required)
writer->writeEmptyElement("required");
writer->writeEndElement();
}
}
void QXmppStreamFeatures::toXml(QXmlStreamWriter *writer) const
{
writer->writeStartElement("stream:features");
writeFeature(writer, "bind", ns_bind, m_bindMode);
writeFeature(writer, "session", ns_session, m_sessionMode);
writeFeature(writer, "auth", ns_authFeature, m_nonSaslAuthMode);
writeFeature(writer, "starttls", ns_tls, m_tlsMode);
if (!m_compressionMethods.isEmpty())
{
writer->writeStartElement("compression");
writer->writeAttribute("xmlns", ns_compressFeature);
foreach (const QString &method, m_compressionMethods)
writer->writeTextElement("method", method);
writer->writeEndElement();
}
if (!m_authMechanisms.isEmpty())
{
writer->writeStartElement("mechanisms");
writer->writeAttribute("xmlns", ns_sasl);
foreach (const QString &mechanism, m_authMechanisms)
writer->writeTextElement("mechanism", mechanism);
writer->writeEndElement();
}
writeFeature(writer, "sm", ns_stream_management, m_streamManagementMode);
writer->writeEndElement();
}
/// \endcond
<|endoftext|> |
<commit_before>/*
* diagonalize.cc
*/
#include "llvm/Pass.h"
#include "llvm/Function.h"
#include "llvm/Constants.h"
#include "llvm/Instructions.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/ADT/ValueMap.h"
#include "llvm/Support/PatternMatch.h"
#include "llvm/Support/raw_ostream.h"
#include <Eigen/Core>
#include <Eigen/LU>
#include <Eigen/Dense>
#include <Eigen/Eigenvalues>
using namespace llvm;
using namespace PatternMatch;
using namespace Eigen;
#define OP_IN_RANGE(_op, _start, _end) \
(_op >= Instruction::_start && _op <= Instruction::_end)
namespace
{
struct ADPass : public LoopPass
{
private:
Loop* loop;
DominatorTree* DT;
std::vector<BasicBlock*> blocks;
/* Keep track of the loop range. */
int64_t iter_base;
Value* iter_final;
PHINode* iter_var;
/* Store tags for state variables. */
ValueMap<PHINode*, int> phis;
typedef ValueMap<PHINode*, double> Coefficients;
public:
static char ID;
ADPass() : LoopPass(ID) {}
virtual void getAnalysisUsage(AnalysisUsage& AU) const {
AU.addRequired<DominatorTree>();
}
virtual bool runOnLoop(Loop* L, LPPassManager&) {
if (L->getSubLoops().size()) {
return false;
}
if (!L->getUniqueExitBlock()) {
return false;
}
loop = L;
blocks = loop->getBlocks();
DT = &getAnalysis<DominatorTree>();
phis.clear();
/* Filter away loops with unsupported instructions. */
int nr_cmps = 0;
ICmpInst* icmp = NULL;
for (auto it = blocks.begin(); it != blocks.end(); ++it) {
BasicBlock* BB = *it;
for (auto II = BB->begin(); II != BB->end(); ++II) {
Instruction* instr = static_cast<Instruction*>(II);
if (isa<ICmpInst>(instr)) {
if (++nr_cmps > 1) {
return false;
} else {
icmp = cast<ICmpInst>(instr);
}
} else if (isa<PHINode>(instr)) {
PHINode* PN = cast<PHINode>(instr);
if (PN->getNumIncomingValues() != 2
|| !DT->properlyDominates(PN->getIncomingBlock(0),
blocks.front()))
{
return false;
}
Value* inLhs = PN->getIncomingValue(0);
if (!(isa<ConstantInt>(inLhs) || isa<ConstantFP>(inLhs))) {
return false;
} else {
phis[PN] = 0;
}
} else if (isa<BinaryOperator>(instr)) {
BinaryOperator* binop = cast<BinaryOperator>(instr);
if (!(OP_IN_RANGE(binop->getOpcode(), Add, FDiv))) {
return false;
}
} else if (!(isa<BranchInst>(instr)
|| isa<IndirectBrInst>(instr)))
{
return false;
}
}
}
/* Extract the loop iterator if possible. */
if (!icmp || !extractIterator(icmp)) {
return false;
} else {
phis.erase(iter_var);
}
int phi_index = 0;
for (auto kv = phis.begin(); kv != phis.end(); ++kv) {
errs() << "PHINode: " << *kv->first
<< "\n\t Label: " << phi_index << "\n";
phis[kv->first] = phi_index++;
}
/* Find the initial state and all linear dependence relations. */
MatrixXd InitialState(phis.size(), 1);
MatrixXcd TransformationMatrix(phis.size(), phis.size());
for (auto kv = phis.begin(); kv != phis.end(); ++kv) {
PHINode* PN = kv->first;
int phi_label = phis[PN];
InitialState(phi_label, 0) = DoubleFromValue(PN->getIncomingValue(0));
Coefficients coeffs;
if (!trackUpdates(phi_label, PN->getIncomingValue(1), coeffs)) {
return false;
}
for (auto ckv = coeffs.begin(); ckv != coeffs.end(); ++ckv) {
int target_phi = phis[kv->first];
TransformationMatrix(phi_label, target_phi) = kv->second;
}
}
#if 0
/* XXX:
* How do we check if complex eigenvalues were generated? Avoid this case...
*/
EigenSolver<MatrixXd> EigGen(TransformationMatrix);
MatrixXcd P = EigGen.eigenvectors();
MatrixXcd D = EigGen.eigenvalues().asDiagonal();
MatrixXcd Pinv = P.inverse();
/* XXX:
* Perform P * (D^[iter_final]) * Pinv * InitialState, and assign the final
* values back into the state variables.
*/
#endif
return false;
}
private:
bool extractIterator(ICmpInst* icmp) {
/* In canonical form, LLVM should pass us an ICmp with the predicate
* reduced to an equality comparison. The LHS should contain the loop
* increment, and the RHS should be an out-of-loop 'constant'. */
Value *cmpLhs, *cmpRhs;
ICmpInst::Predicate IPred;
if (match(icmp, m_ICmp(IPred, m_Value(cmpLhs),
m_Value(cmpRhs)))
&& IPred == CmpInst::Predicate::ICMP_EQ)
{
if (isa<Instruction>(cmpRhs)) {
Instruction* irhs = cast<Instruction>(cmpRhs);
if (!DT->properlyDominates(irhs->getParent(), blocks.front())) {
return false;
}
}
Value *incrLhs, *incrRhs;
if (match(cmpLhs, m_Add(m_Value(incrLhs), m_Value(incrRhs)))) {
if (isa<PHINode>(incrLhs)
&& isa<ConstantInt>(incrRhs)
&& cast<ConstantInt>(incrRhs)->isOne())
{
iter_final = cmpRhs;
iter_var = cast<PHINode>(incrLhs);
Value* iter_initial = iter_var->getIncomingValue(0);
if (isa<ConstantInt>(iter_initial)) {
iter_base = IntFromValue(iter_initial);
return true;
}
}
}
}
return false;
}
bool trackUpdates(Value* parent, Coefficients& coeffs) {
if (isa<PHINode>(parent)) {
/* Isolated PHINodes contribute one copy of themselves. */
PHINode* PN = cast<PHINode>(parent);
coeffs[PN] = 1;
} else if (isa<BinaryOperator>(parent)) {
BinaryOperator* binop = cast<BinaryOperator>(parent);
int opcode = binop->getOpcode();
Value *LHS = binop->getOperand(0), *RHS = binop->getOperand(1);
Coefficients lhsCoeffs, rhsCoeffs;
double scalar;
if (!(trackUpdates(LHS, lhsCoeffs) && trackUpdates(RHS, rhsCoeffs))) {
return false;
}
if (OP_IN_RANGE(opcode, Add, Fsub)) {
/* Add instructions shouldn't operate on scalars. */
if (scalarExpr(lhsCoeffs) || scalarExpr(rhsCoeffs)) {
return false;
}
} else {
/* Multiply instructions must have (only) one scalar operand. */
if (scalarExpr(lhsCoeffs) ^ scalarExpr(rhsCoeffs)) {
return false;
}
/* Divide instructions cannot have scalar numerators. */
if (OP_IN_RANGE(opcode, Udiv, FDiv) && !scalarExpr(LHS)) {
return false;
}
scalar = DoubleFromValue(scalarExpr(lhsCoeffs) ? LHS : RHS);
}
for (auto kv = phis.begin(); kv != phis.end(); ++kv) {
PHINode* PN = kv->first;
double lcoeff = lhsCoeffs.lookup(PN), rcoeff = rhsCoeffs.lookup(PN);
if (lcoeff == 0 && rcoeff == 0) {
continue;
}
if (OP_IN_RANGE(opcode, Add, FAdd)) {
coeffs[PN] = lcoeff + rcoeff;
} else if (OP_IN_RANGE(opcode, Sub, FSub)) {
coeffs[PN] = lcoeff - rcoeff;
} else if (OP_IN_RANGE(opcode, Mul, FMul)) {
coeffs[PN] = scalar * (lcoeff + rcoeff);
} else {
coeffs[PN] = (1 / scalar) * (lcoeff + rcoeff);
}
}
} else return false;
return true;
}
int64_t IntFromValue(Value* V) {
return cast<ConstantInt>(V)->getValue().getSExtValue();
}
double DoubleFromValue(Value* V) {
if (isa<ConstantInt>(V)) {
return double(IntFromValue(V));
} else if (isa<ConstantFP>(V)) {
return cast<ConstantFP>(V)->getValueAPF().convertToDouble();
}
}
bool scalarExpr(Coefficients& coeffs) {
return coeffs.size() == 0;
}
};
char ADPass::ID = 0;
}
static RegisterPass<ADPass> X("auto-diagonalize",
"Diagonalize linear dynamical systems", false, false);
<commit_msg>Able to properly grab the transformation matrix for fib.cc<commit_after>/*
* diagonalize.cc
*/
#include "llvm/Pass.h"
#include "llvm/Function.h"
#include "llvm/Constants.h"
#include "llvm/Instructions.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/ADT/ValueMap.h"
#include "llvm/Support/PatternMatch.h"
#include "llvm/Support/raw_ostream.h"
#include <Eigen/Core>
#include <Eigen/LU>
#include <Eigen/Dense>
#include <Eigen/Eigenvalues>
#include <iostream>
using namespace llvm;
using namespace PatternMatch;
using namespace Eigen;
#define OP_IN_RANGE(_op, _start, _end) \
(_op >= Instruction:: _start && _op <= Instruction:: _end)
namespace
{
struct ADPass : public LoopPass
{
private:
Loop* loop;
DominatorTree* DT;
std::vector<BasicBlock*> blocks;
/* Keep track of the loop range. */
int64_t iter_base;
Value* iter_final;
PHINode* iter_var;
/* Store tags for state variables. */
ValueMap<PHINode*, int> phis;
typedef ValueMap<PHINode*, double> Coefficients;
public:
static char ID;
ADPass() : LoopPass(ID) {}
virtual void getAnalysisUsage(AnalysisUsage& AU) const {
AU.addRequired<DominatorTree>();
}
virtual bool runOnLoop(Loop* L, LPPassManager&) {
if (L->getSubLoops().size()) {
return false;
}
if (!L->getUniqueExitBlock()) {
return false;
}
loop = L;
blocks = loop->getBlocks();
DT = &getAnalysis<DominatorTree>();
phis.clear();
/* Filter away loops with unsupported instructions. */
int nr_cmps = 0;
ICmpInst* icmp = NULL;
for (auto it = blocks.begin(); it != blocks.end(); ++it) {
BasicBlock* BB = *it;
for (auto II = BB->begin(); II != BB->end(); ++II) {
Instruction* instr = static_cast<Instruction*>(II);
if (isa<ICmpInst>(instr)) {
if (++nr_cmps > 1) {
return false;
} else {
icmp = cast<ICmpInst>(instr);
}
} else if (isa<PHINode>(instr)) {
PHINode* PN = cast<PHINode>(instr);
if (PN->getNumIncomingValues() != 2
|| !DT->properlyDominates(PN->getIncomingBlock(0),
blocks.front()))
{
return false;
}
Value* inLhs = PN->getIncomingValue(0);
if (!(isa<ConstantInt>(inLhs) || isa<ConstantFP>(inLhs))) {
return false;
} else {
phis[PN] = 0;
}
} else if (isa<BinaryOperator>(instr)) {
BinaryOperator* binop = cast<BinaryOperator>(instr);
if (!(OP_IN_RANGE(binop->getOpcode(), Add, FDiv))) {
return false;
}
} else if (!(isa<BranchInst>(instr)
|| isa<IndirectBrInst>(instr)))
{
return false;
}
}
}
/* Extract the loop iterator if possible. */
if (!icmp || !extractIterator(icmp)) {
return false;
} else {
phis.erase(iter_var);
}
int phi_index = 0;
for (auto kv = phis.begin(); kv != phis.end(); ++kv) {
phis[kv->first] = phi_index++;
}
/* Find the initial state and all linear dependence relations. */
size_t nr_phis = phis.size();
MatrixXd InitialState(nr_phis, 1);
MatrixXd TransformationMatrix(nr_phis, nr_phis);
TransformationMatrix << MatrixXd::Zero(nr_phis, nr_phis);
for (auto kv = phis.begin(); kv != phis.end(); ++kv) {
PHINode* PN = kv->first;
int phi_label = phis[PN];
InitialState(phi_label, 0) = DoubleFromValue(PN->getIncomingValue(0));
Coefficients coeffs;
if (!trackUpdates(PN->getIncomingValue(1), coeffs)) {
return false;
}
for (auto ckv = coeffs.begin(); ckv != coeffs.end(); ++ckv) {
int target_phi = phis[ckv->first];
TransformationMatrix(phi_label, target_phi) = ckv->second;
}
}
// XXX
std::cout << TransformationMatrix << "\n";
#if 0
/* XXX:
* How do we check if complex eigenvalues were generated? Avoid this case...
*/
EigenSolver<MatrixXd> EigGen(TransformationMatrix);
MatrixXd P = EigGen.eigenvectors();
MatrixXd D = EigGen.eigenvalues().asDiagonal();
MatrixXd Pinv = P.inverse();
/* XXX:
* Perform P * (D^[iter_final]) * Pinv * InitialState, and assign the final
* values back into the state variables.
*/
#endif
return false;
}
private:
bool extractIterator(ICmpInst* icmp) {
/* In canonical form, LLVM should pass us an ICmp with the predicate
* reduced to an equality comparison. The LHS should contain the loop
* increment, and the RHS should be an out-of-loop 'constant'. */
Value *cmpLhs, *cmpRhs;
ICmpInst::Predicate IPred;
if (match(icmp, m_ICmp(IPred, m_Value(cmpLhs),
m_Value(cmpRhs)))
&& IPred == CmpInst::Predicate::ICMP_EQ)
{
if (isa<Instruction>(cmpRhs)) {
Instruction* irhs = cast<Instruction>(cmpRhs);
if (!DT->properlyDominates(irhs->getParent(), blocks.front())) {
return false;
}
}
Value *incrLhs, *incrRhs;
if (match(cmpLhs, m_Add(m_Value(incrLhs), m_Value(incrRhs)))) {
if (isa<PHINode>(incrLhs)
&& isa<ConstantInt>(incrRhs)
&& cast<ConstantInt>(incrRhs)->isOne())
{
iter_final = cmpRhs;
iter_var = cast<PHINode>(incrLhs);
Value* iter_initial = iter_var->getIncomingValue(0);
if (isa<ConstantInt>(iter_initial)) {
iter_base = IntFromValue(iter_initial);
return true;
}
}
}
}
return false;
}
bool trackUpdates(Value* parent, Coefficients& coeffs) {
if (isa<Constant>(parent)) {
return true;
} else if (isa<PHINode>(parent)) {
PHINode* PN = cast<PHINode>(parent);
if (!phis.count(PN)) {
return false;
} else {
coeffs[PN] = 1;
}
} else if (isa<BinaryOperator>(parent)) {
BinaryOperator* binop = cast<BinaryOperator>(parent);
int opcode = binop->getOpcode();
Value *LHS = binop->getOperand(0), *RHS = binop->getOperand(1);
Coefficients lhsCoeffs, rhsCoeffs;
double scalar;
if (!(trackUpdates(LHS, lhsCoeffs) && trackUpdates(RHS, rhsCoeffs))) {
return false;
}
if (OP_IN_RANGE(opcode, Add, FSub)) {
/* Add instructions shouldn't operate on scalars. */
if (scalarExpr(lhsCoeffs) || scalarExpr(rhsCoeffs)) {
return false;
}
} else {
/* Multiply instructions must have (only) one scalar operand. */
if (scalarExpr(lhsCoeffs) ^ scalarExpr(rhsCoeffs)) {
return false;
}
/* Divide instructions cannot have scalar numerators. */
if (OP_IN_RANGE(opcode, UDiv, FDiv) && !scalarExpr(lhsCoeffs)) {
return false;
}
scalar = DoubleFromValue(scalarExpr(lhsCoeffs) ? LHS : RHS);
}
for (auto kv = phis.begin(); kv != phis.end(); ++kv) {
PHINode* PN = kv->first;
double lcoeff = lhsCoeffs.lookup(PN), rcoeff = rhsCoeffs.lookup(PN);
/* Adding trivial entries to the coefficient table breaks scalarExpr(). */
if (lcoeff == 0 && rcoeff == 0) {
continue;
}
if (OP_IN_RANGE(opcode, Add, FAdd)) {
coeffs[PN] = lcoeff + rcoeff;
} else if (OP_IN_RANGE(opcode, Sub, FSub)) {
coeffs[PN] = lcoeff - rcoeff;
} else if (OP_IN_RANGE(opcode, Mul, FMul)) {
coeffs[PN] = scalar * (lcoeff + rcoeff);
} else {
coeffs[PN] = (1 / scalar) * (lcoeff + rcoeff);
}
}
} else return false;
return true;
}
int64_t IntFromValue(Value* V) {
return cast<ConstantInt>(V)->getValue().getSExtValue();
}
double DoubleFromValue(Value* V) {
if (isa<ConstantInt>(V)) {
return double(IntFromValue(V));
} else if (isa<ConstantFP>(V)) {
return cast<ConstantFP>(V)->getValueAPF().convertToDouble();
}
return 0;
}
bool scalarExpr(Coefficients& coeffs) {
return coeffs.size() == 0;
}
};
char ADPass::ID = 0;
}
static RegisterPass<ADPass> X("auto-diagonalize",
"Diagonalize linear dynamical systems", false, false);
<|endoftext|> |
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/system/chromeos/virtual_keyboard/virtual_keyboard_tray.h"
#include "ash/shelf/shelf_constants.h"
#include "ash/shell.h"
#include "ash/system/status_area_widget.h"
#include "ash/system/tray/system_tray_notifier.h"
#include "ash/system/tray/tray_constants.h"
#include "ash/system/tray/tray_utils.h"
#include "grit/ash_resources.h"
#include "grit/ash_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/events/event.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/keyboard/keyboard_controller.h"
#include "ui/views/controls/button/image_button.h"
namespace ash {
namespace {
class VirtualKeyboardButton : public views::ImageButton {
public:
VirtualKeyboardButton(views::ButtonListener* listener);
virtual ~VirtualKeyboardButton();
// Overridden from views::ImageButton:
virtual gfx::Size GetPreferredSize() const OVERRIDE;
private:
DISALLOW_COPY_AND_ASSIGN(VirtualKeyboardButton);
};
VirtualKeyboardButton::VirtualKeyboardButton(views::ButtonListener* listener)
: views::ImageButton(listener) {
}
VirtualKeyboardButton::~VirtualKeyboardButton() {
}
gfx::Size VirtualKeyboardButton::GetPreferredSize() const {
const int virtual_keyboard_button_height = kShelfSize;
gfx::Size size = ImageButton::GetPreferredSize();
int padding = virtual_keyboard_button_height - size.height();
size.set_height(virtual_keyboard_button_height);
size.set_width(size.width() + padding);
return size;
}
} // namespace
VirtualKeyboardTray::VirtualKeyboardTray(StatusAreaWidget* status_area_widget)
: TrayBackgroundView(status_area_widget),
button_(NULL) {
button_ = new VirtualKeyboardButton(this);
button_->SetImage(views::CustomButton::STATE_NORMAL,
ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
IDR_AURA_UBER_TRAY_VIRTUAL_KEYBOARD));
button_->SetImageAlignment(views::ImageButton::ALIGN_CENTER,
views::ImageButton::ALIGN_MIDDLE);
tray_container()->AddChildView(button_);
SetContentsBackground();
// The Shell may not exist in some unit tests.
if (Shell::HasInstance()) {
Shell::GetInstance()->system_tray_notifier()->
AddAccessibilityObserver(this);
}
}
VirtualKeyboardTray::~VirtualKeyboardTray() {
// The Shell may not exist in some unit tests.
if (Shell::HasInstance()) {
Shell::GetInstance()->system_tray_notifier()->
RemoveAccessibilityObserver(this);
}
}
void VirtualKeyboardTray::SetShelfAlignment(ShelfAlignment alignment) {
TrayBackgroundView::SetShelfAlignment(alignment);
tray_container()->SetBorder(views::Border::NullBorder());
}
base::string16 VirtualKeyboardTray::GetAccessibleNameForTray() {
return l10n_util::GetStringUTF16(
IDS_ASH_VIRTUAL_KEYBOARD_TRAY_ACCESSIBLE_NAME);
}
void VirtualKeyboardTray::HideBubbleWithView(
const views::TrayBubbleView* bubble_view) {
}
bool VirtualKeyboardTray::ClickedOutsideBubble() {
return false;
}
bool VirtualKeyboardTray::PerformAction(const ui::Event& event) {
keyboard::KeyboardController::GetInstance()->ShowKeyboard(true);
return true;
}
void VirtualKeyboardTray::ButtonPressed(views::Button* sender,
const ui::Event& event) {
DCHECK_EQ(button_, sender);
PerformAction(event);
}
void VirtualKeyboardTray::OnAccessibilityModeChanged(
AccessibilityNotificationVisibility notify) {
SetVisible(Shell::GetInstance()->accessibility_delegate()->
IsVirtualKeyboardEnabled());
}
} // namespace ash
<commit_msg>Fix padding of a11y keyboard indicator when shelf is vertically aligned.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/system/chromeos/virtual_keyboard/virtual_keyboard_tray.h"
#include "ash/shelf/shelf.h"
#include "ash/shelf/shelf_constants.h"
#include "ash/shell.h"
#include "ash/system/status_area_widget.h"
#include "ash/system/tray/system_tray_notifier.h"
#include "ash/system/tray/tray_constants.h"
#include "ash/system/tray/tray_utils.h"
#include "grit/ash_resources.h"
#include "grit/ash_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/events/event.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/keyboard/keyboard_controller.h"
#include "ui/views/controls/button/image_button.h"
namespace ash {
VirtualKeyboardTray::VirtualKeyboardTray(StatusAreaWidget* status_area_widget)
: TrayBackgroundView(status_area_widget),
button_(NULL) {
button_ = new views::ImageButton(this);
button_->SetImage(views::CustomButton::STATE_NORMAL,
ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
IDR_AURA_UBER_TRAY_VIRTUAL_KEYBOARD));
button_->SetImageAlignment(views::ImageButton::ALIGN_CENTER,
views::ImageButton::ALIGN_MIDDLE);
tray_container()->AddChildView(button_);
SetContentsBackground();
// The Shell may not exist in some unit tests.
if (Shell::HasInstance()) {
Shell::GetInstance()->system_tray_notifier()->
AddAccessibilityObserver(this);
}
}
VirtualKeyboardTray::~VirtualKeyboardTray() {
// The Shell may not exist in some unit tests.
if (Shell::HasInstance()) {
Shell::GetInstance()->system_tray_notifier()->
RemoveAccessibilityObserver(this);
}
}
void VirtualKeyboardTray::SetShelfAlignment(ShelfAlignment alignment) {
TrayBackgroundView::SetShelfAlignment(alignment);
tray_container()->SetBorder(views::Border::NullBorder());
// Pad button size to align with other controls in the system tray.
const gfx::ImageSkia image = button_->GetImage(
views::CustomButton::STATE_NORMAL);
int top_padding = (kTrayBarButtonWidth - image.height()) / 2;
int left_padding = (kTrayBarButtonWidth - image.width()) / 2;
int bottom_padding = kTrayBarButtonWidth - image.height() - top_padding;
int right_padding = kTrayBarButtonWidth - image.width() - left_padding;
// Square up the padding if horizontally aligned. Avoid extra padding when
// vertically aligned as the button would violate the width constraint on the
// shelf.
if (alignment == SHELF_ALIGNMENT_BOTTOM || alignment == SHELF_ALIGNMENT_TOP) {
gfx::Insets insets = button_->GetInsets();
int additional_padding = std::max(0, top_padding - left_padding);
left_padding += additional_padding;
right_padding += additional_padding;
}
button_->SetBorder(views::Border::CreateEmptyBorder(
top_padding,
left_padding,
bottom_padding,
right_padding));
}
base::string16 VirtualKeyboardTray::GetAccessibleNameForTray() {
return l10n_util::GetStringUTF16(
IDS_ASH_VIRTUAL_KEYBOARD_TRAY_ACCESSIBLE_NAME);
}
void VirtualKeyboardTray::HideBubbleWithView(
const views::TrayBubbleView* bubble_view) {
}
bool VirtualKeyboardTray::ClickedOutsideBubble() {
return false;
}
bool VirtualKeyboardTray::PerformAction(const ui::Event& event) {
keyboard::KeyboardController::GetInstance()->ShowKeyboard(true);
return true;
}
void VirtualKeyboardTray::ButtonPressed(views::Button* sender,
const ui::Event& event) {
DCHECK_EQ(button_, sender);
PerformAction(event);
}
void VirtualKeyboardTray::OnAccessibilityModeChanged(
AccessibilityNotificationVisibility notify) {
SetVisible(Shell::GetInstance()->accessibility_delegate()->
IsVirtualKeyboardEnabled());
}
} // namespace ash
<|endoftext|> |
<commit_before># ifndef CPPAD_CORE_ABS_NORMAL_HPP
# define CPPAD_CORE_ABS_NORMAL_HPP
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-17 Bradley M. Bell
CppAD is distributed under multiple licenses. This distribution is under
the terms of the
Eclipse Public License Version 1.0.
A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
/*
$begin abs_normal$$
$spell
Andreas Griewank
Jens-Uwe Bernt
Manuel Radons
Tom Streubel
const
$$
$latex
\newcommand{\B}[1]{ {\bf #1} }
\newcommand{\W}[1]{ \; #1 \; }
$$
$section Create An Abs-normal Representation of a Function$$
$head Under Construction$$
This is an in-progress design, and does not yet have an implementation.
$head Syntax$$
$icode%g%.abs_normal(%f%)%$$
$head Reference$$
Andreas Griewank, Jens-Uwe Bernt, Manuel Radons, Tom Streubel,
$italic Solving piecewise linear systems in abs-normal form$$,
Linear Algebra and its Applications,
vol. 471 (2015), pages 500-530.
$head f$$
The object $icode f$$ has prototype
$codei%
const ADFun<%Base%>& %f%
%$$
It represents a function $latex f : \B{R}^n \rightarrow \B{R}^m$$.
We assume that the only non-smooth terms in the representation are
absolute value functions and use $latex s \in \B{Z}_+$$
to represent the number of these terms.
$head g$$
The object $icode g$$ has prototype
$codei%
ADFun<%Base%> %g%
%$$
The initial function representation in $icode g$$ is lost.
Upon return it represents the smooth function
$latex g : \B{R}^{n + s} \rightarrow \B{R}^{m + s}$$ is defined by
$latex \[
g( x , u )
=
\left[ \begin{array}{c} y(x, u) \\ z(x, u) \end{array} \right]
\] $$
were $latex y(x, u)$$ and $latex z(x, u)$$ are defined below.
$subhead a(x)$$
Let $latex \zeta_0 ( x )$$
denote the argument for the first absolute value term in $latex f(x)$$,
$latex \zeta_1 ( x , |\zeta_0 (x)| )$$ for the second term, and so on.
For $latex i = 0 , \ldots , {s-1}$$ define
$latex \[
a_i (x)
=
| \zeta_i ( x , a_0 (x) , \ldots , a_{i-1} (x ) ) |
\] $$
This defines $latex a : \B{R}^n \rightarrow \B{R}^s$$.
$subhead z(x, u)$$
Define the smooth function
$latex z : \B{R}^{n + s} \rightarrow \B{R}^s$$ by
$latex \[
z_i ( x , u ) = \zeta_i ( x , u_0 , \ldots , u_{i-1} )
\] $$
$subhead y(x, u)$$
There is a smooth function
$latex y : \B{R}^{n + s} \rightarrow \B{R}^m$$
such that $latex y( x , u ) = f(x)$$ whenever $latex u = a(x)$$.
$head Affine Approximation$$
We define the affine approximations
$latex \[
\begin{array}{rcl}
\tilde{y}( \hat{x} \W{:} x , u )
& = &
y ( \hat{x}, a( \hat{x} ) )
+ \partial_x y ( \hat{x}, a( \hat{x} ) ) ( x - \hat{x} )
+ \partial_u y ( \hat{x}, a( \hat{x} ) ) ( u - a( \hat{x} ) )
\\
\tilde{z}( \hat{x} \W{:} x , u )
& = &
z ( \hat{x}, a( \hat{x} ) )
+ \partial_x z ( \hat{x}, a( \hat{x} ) ) ( x - \hat{x} )
+ \partial_u z ( \hat{x}, a( \hat{x} ) ) ( u - a( \hat{x} ) )
\end{array}
\] $$
It follows that
$latex \[
\begin{array}{rcl}
y( x , u )
& = &
\tilde{y}( \hat{x} \W{:} x , u ) + o ( x - \hat{x}, u - a( \hat{x} ) )
\\
z( x , u )
& = &
\tilde{z}( \hat{x} \W{:} x , u ) + o ( x - \hat{x}, u - a( \hat{x} ) )
\end{array}
\] $$
$head Abs-normal Approximation$$
$subhead Approximating a(x)$$
The function $latex a(x)$$ is not smooth, but it is equal to
$latex | z(x, u) |$$ when $latex u = a(x)$$.
Furthermore
$latex \[
\tilde{z}( \hat{x} \W{:} x , u )
=
z ( \hat{x}, a( \hat{x} ) )
+ \partial_x z ( \hat{x}, a( \hat{x} ) ) ( x - \hat{x} )
+ \partial_u z ( \hat{x}, a( \hat{x} ) ) ( u - a( \hat{x} ) )
\] $$
Now the partial of $latex z_i$$ with respect to $latex u_j$$ is zero
for $latex j \geq i$$. It follows that
$latex \[
\tilde{z}_i ( \hat{x} \W{:} x , u )
=
z_i ( \hat{x}, a( \hat{x} ) )
+ \partial_x z_i ( \hat{x}, a( \hat{x} ) ) ( x - \hat{x} )
+ \sum_{j < i} \partial_{u(j)}
z_i ( \hat{x}, a( \hat{x} ) ) ( u_j - a_j ( \hat{x} ) )
\] $$
Considering the case $latex i = 0$$ we define
$latex \[
\tilde{a}_0 ( \hat{x} \W{:} x )
=
| \tilde{z}_0 ( \hat{x} \W{:} x , u ) |
=
\left|
z_0 ( \hat{x}, a( \hat{x} ) )
+ \partial_x z_0 ( \hat{x}, a( \hat{x} ) ) ( x - \hat{x} )
\right|
\] $$
It follows that
$latex \[
a_0 (x) = \tilde{a}_0 ( \hat{x} \W{:} x ) + o ( x - \hat{x} )
\] $$
In general, we define $latex \tilde{a}_i$$ using
$latex \tilde{a}_j$$ for $latex j < i$$ as follows:
$latex \[
\tilde{a}_i ( \hat{x} \W{:} x )
=
\left |
z_i ( \hat{x}, a( \hat{x} ) )
+ \partial_x z_i ( \hat{x}, a( \hat{x} ) ) ( x - \hat{x} )
+ \sum_{j < i} \partial_{u(j)}
z_i ( \hat{x}, a( \hat{x} ) )
( \hat{a}_j ( \hat{x} \W{:} x ) - a_j ( \hat{x} ) )
\right|
\] $$
It follows that
$latex \[
a (x) = \tilde{a} ( \hat{x} \W{:} x ) + o ( x - \hat{x} )
\] $$
Note that in the case where $latex z(x, u)$$ and $latex y(x, u)$$ are
affine,
$latex \[
\tilde{a} ( \hat{x} \W{:} x ) = a( x )
\] $$
$subhead Approximating f(x)$$
$latex \[
f(x)
=
y ( x , a(x ) )
=
\tilde{y} ( \hat{x} \W{:} x , \tilde{a} ( \hat{x} \W{:} x ) )
+ o( \Delta x )
\] $$
$head Correspondence to Literature$$
Using the notation
$latex Z = \partial_x z(\hat{x}, \hat{u})$$,
$latex L = \partial_u z(\hat{x}, \hat{u})$$,
$latex J = \partial_x y(\hat{x}, \hat{u})$$,
$latex Y = \partial_u y(\hat{x}, \hat{u})$$,
the approximation for $latex z$$ and $latex y$$ are
$latex \[
\begin{array}{rcl}
\tilde{z} ( \hat{x} \W{:} x , u )
& = &
z ( \hat{x}, a( \hat{x} ) ) + Z ( x - \hat{x} ) + L ( u - a( \hat{x} ) )
\\
\tilde{y} ( \hat{x} \W{:} x , u )
& = &
y ( \hat{x}, a( \hat{x} ) ) + J ( x - \hat{x} ) + Y ( u - a( \hat{x} ) )
\end{array}
\] $$
Moving the terms with $latex \hat{x}$$ together, we have
$latex \[
\begin{array}{rcl}
\tilde{z} ( \hat{x} \W{:} x , u )
& = &
z ( \hat{x}, a( \hat{x} ) ) - Z \hat{x} - L a( \hat{x} ) + Z x + L u
\\
\tilde{y} ( \hat{x} \W{:} x , u )
& = &
y ( \hat{x}, a( \hat{x} ) ) - J \hat{x} - Y a( \hat{x} ) + J x + Y u
\end{array}
\] $$
Using the notation
$latex c = z ( \hat{x}, \hat{u} ) - Z \hat{x} - L \hat{u}$$,
$latex b = y ( \hat{x}, \hat{u} ) - J \hat{x} - Y \hat{u}$$,
we have
$latex \[
\begin{array}{rcl}
\tilde{z} ( \hat{x} \W{:} x , u ) & = & c + Z x + L u
\\
\tilde{y} ( \hat{x} \W{:} x , u ) & = & b + J x + Y u
\end{array}
\] $$
Considering the affine case, where the approximations are exact,
and choosing $latex u = a(x) = |z(x, u)|$$, we obtain
$latex \[
\begin{array}{rcl}
z( x , a(x ) ) & = & c + Z x + L |z( x , a(x ) )|
\\
y( x , a(x ) ) & = & b + J x + Y |z( x , a(x ) )|
\end{array}
\] $$
This is Equation (2) of the reference.
$end
*/
# endif
<commit_msg>abs_normal.hpp: Change approximations to use [] notation.<commit_after># ifndef CPPAD_CORE_ABS_NORMAL_HPP
# define CPPAD_CORE_ABS_NORMAL_HPP
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-17 Bradley M. Bell
CppAD is distributed under multiple licenses. This distribution is under
the terms of the
Eclipse Public License Version 1.0.
A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
/*
$begin abs_normal$$
$spell
Andreas Griewank
Jens-Uwe Bernt
Manuel Radons
Tom Streubel
const
$$
$latex
\newcommand{\B}[1]{ {\bf #1} }
$$
$section Create An Abs-normal Representation of a Function$$
$head Under Construction$$
This is an in-progress design, and does not yet have an implementation.
$head Syntax$$
$icode%g%.abs_normal(%f%)%$$
$head Reference$$
Andreas Griewank, Jens-Uwe Bernt, Manuel Radons, Tom Streubel,
$italic Solving piecewise linear systems in abs-normal form$$,
Linear Algebra and its Applications,
vol. 471 (2015), pages 500-530.
$head f$$
The object $icode f$$ has prototype
$codei%
const ADFun<%Base%>& %f%
%$$
It represents a function $latex f : \B{R}^n \rightarrow \B{R}^m$$.
We assume that the only non-smooth terms in the representation are
absolute value functions and use $latex s \in \B{Z}_+$$
to represent the number of these terms.
$head g$$
The object $icode g$$ has prototype
$codei%
ADFun<%Base%> %g%
%$$
The initial function representation in $icode g$$ is lost.
Upon return it represents the smooth function
$latex g : \B{R}^{n + s} \rightarrow \B{R}^{m + s}$$ is defined by
$latex \[
g( x , u )
=
\left[ \begin{array}{c} y(x, u) \\ z(x, u) \end{array} \right]
\] $$
were $latex y(x, u)$$ and $latex z(x, u)$$ are defined below.
$subhead a(x)$$
Let $latex \zeta_0 ( x )$$
denote the argument for the first absolute value term in $latex f(x)$$,
$latex \zeta_1 ( x , |\zeta_0 (x)| )$$ for the second term, and so on.
For $latex i = 0 , \ldots , {s-1}$$ define
$latex \[
a_i (x)
=
| \zeta_i ( x , a_0 (x) , \ldots , a_{i-1} (x ) ) |
\] $$
This defines $latex a : \B{R}^n \rightarrow \B{R}^s$$.
$subhead z(x, u)$$
Define the smooth function
$latex z : \B{R}^{n + s} \rightarrow \B{R}^s$$ by
$latex \[
z_i ( x , u ) = \zeta_i ( x , u_0 , \ldots , u_{i-1} )
\] $$
$subhead y(x, u)$$
There is a smooth function
$latex y : \B{R}^{n + s} \rightarrow \B{R}^m$$
such that $latex y( x , u ) = f(x)$$ whenever $latex u = a(x)$$.
$head Affine Approximation$$
We define the affine approximations
$latex \[
\begin{array}{rcl}
y[ \hat{x} ]( x , u )
& = &
y ( \hat{x}, a( \hat{x} ) )
+ \partial_x y ( \hat{x}, a( \hat{x} ) ) ( x - \hat{x} )
+ \partial_u y ( \hat{x}, a( \hat{x} ) ) ( u - a( \hat{x} ) )
\\
z[ \hat{x} ]( x , u )
& = &
z ( \hat{x}, a( \hat{x} ) )
+ \partial_x z ( \hat{x}, a( \hat{x} ) ) ( x - \hat{x} )
+ \partial_u z ( \hat{x}, a( \hat{x} ) ) ( u - a( \hat{x} ) )
\end{array}
\] $$
It follows that
$latex \[
\begin{array}{rcl}
y( x , u )
& = &
y[ \hat{x} ]( x , u ) + o ( x - \hat{x}, u - a( \hat{x} ) )
\\
z( x , u )
& = &
z[ \hat{x} ]( x , u ) + o ( x - \hat{x}, u - a( \hat{x} ) )
\end{array}
\] $$
$head Abs-normal Approximation$$
$subhead Approximating a(x)$$
The function $latex a(x)$$ is not smooth, but it is equal to
$latex | z(x, u) |$$ when $latex u = a(x)$$.
Furthermore
$latex \[
z[ \hat{x} ]( x , u )
=
z ( \hat{x}, a( \hat{x} ) )
+ \partial_x z ( \hat{x}, a( \hat{x} ) ) ( x - \hat{x} )
+ \partial_u z ( \hat{x}, a( \hat{x} ) ) ( u - a( \hat{x} ) )
\] $$
Now the partial of $latex z_i$$ with respect to $latex u_j$$ is zero
for $latex j \geq i$$. It follows that
$latex \[
z_i [ \hat{x} ]( x , u )
=
z_i ( \hat{x}, a( \hat{x} ) )
+ \partial_x z_i ( \hat{x}, a( \hat{x} ) ) ( x - \hat{x} )
+ \sum_{j < i} \partial_{u(j)}
z_i ( \hat{x}, a( \hat{x} ) ) ( u_j - a_j ( \hat{x} ) )
\] $$
Considering the case $latex i = 0$$ we define
$latex \[
a_0 [ \hat{x} ]( x )
=
| z_0 [ \hat{x} ]( x , u ) |
=
\left|
z_0 ( \hat{x}, a( \hat{x} ) )
+ \partial_x z_0 ( \hat{x}, a( \hat{x} ) ) ( x - \hat{x} )
\right|
\] $$
It follows that
$latex \[
a_0 (x) = a_0 [ \hat{x} ]( x ) + o ( x - \hat{x} )
\] $$
In general, we define $latex a_i [ \hat{x} ]$$ using
$latex a_j [ \hat{x} ]$$ for $latex j < i$$ as follows:
$latex \[
a_i [ \hat{x} ]( x )
=
\left |
z_i ( \hat{x}, a( \hat{x} ) )
+ \partial_x z_i ( \hat{x}, a( \hat{x} ) ) ( x - \hat{x} )
+ \sum_{j < i} \partial_{u(j)}
z_i ( \hat{x}, a( \hat{x} ) )
( a_j [ \hat{x} ] ( x ) - a_j ( \hat{x} ) )
\right|
\] $$
It follows that
$latex \[
a (x) = a[ \hat{x} ]( x ) + o ( x - \hat{x} )
\] $$
Note that in the case where $latex z(x, u)$$ and $latex y(x, u)$$ are
affine,
$latex \[
a[ \hat{x} ]( x ) = a( x )
\] $$
$subhead Approximating f(x)$$
$latex \[
f(x)
=
y ( x , a(x ) )
=
y [ \hat{x} ] ( x , a[ \hat{x} ] ( x ) )
+ o( \Delta x )
\] $$
$head Correspondence to Literature$$
Using the notation
$latex Z = \partial_x z(\hat{x}, \hat{u})$$,
$latex L = \partial_u z(\hat{x}, \hat{u})$$,
$latex J = \partial_x y(\hat{x}, \hat{u})$$,
$latex Y = \partial_u y(\hat{x}, \hat{u})$$,
the approximation for $latex z$$ and $latex y$$ are
$latex \[
\begin{array}{rcl}
z[ \hat{x} ]( x , u )
& = &
z ( \hat{x}, a( \hat{x} ) ) + Z ( x - \hat{x} ) + L ( u - a( \hat{x} ) )
\\
y[ \hat{x} ]( x , u )
& = &
y ( \hat{x}, a( \hat{x} ) ) + J ( x - \hat{x} ) + Y ( u - a( \hat{x} ) )
\end{array}
\] $$
Moving the terms with $latex \hat{x}$$ together, we have
$latex \[
\begin{array}{rcl}
z[ \hat{x} ]( x , u )
& = &
z ( \hat{x}, a( \hat{x} ) ) - Z \hat{x} - L a( \hat{x} ) + Z x + L u
\\
y[ \hat{x} ]( x , u )
& = &
y ( \hat{x}, a( \hat{x} ) ) - J \hat{x} - Y a( \hat{x} ) + J x + Y u
\end{array}
\] $$
Using the notation
$latex c = z ( \hat{x}, \hat{u} ) - Z \hat{x} - L \hat{u}$$,
$latex b = y ( \hat{x}, \hat{u} ) - J \hat{x} - Y \hat{u}$$,
we have
$latex \[
\begin{array}{rcl}
z[ \hat{x} ]( x , u ) & = & c + Z x + L u
\\
y[ \hat{x} ]( x , u ) & = & b + J x + Y u
\end{array}
\] $$
Considering the affine case, where the approximations are exact,
and choosing $latex u = a(x) = |z(x, u)|$$, we obtain
$latex \[
\begin{array}{rcl}
z( x , a(x ) ) & = & c + Z x + L |z( x , a(x ) )|
\\
y( x , a(x ) ) & = & b + J x + Y |z( x , a(x ) )|
\end{array}
\] $$
This is Equation (2) of the reference.
$end
*/
# endif
<|endoftext|> |
<commit_before>/**
* @file ExecuteProcess.cpp
* ExecuteProcess class implementation
*
* 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.
*/
#include "TimeUtil.h"
#include "ExecuteProcess.h"
#include "ProcessContext.h"
#include "ProcessSession.h"
#include <cstring>
const std::string ExecuteProcess::ProcessorName("ExecuteProcess");
Property ExecuteProcess::Command("Command", "Specifies the command to be executed; if just the name of an executable is provided, it must be in the user's environment PATH.", "");
Property ExecuteProcess::CommandArguments("Command Arguments",
"The arguments to supply to the executable delimited by white space. White space can be escaped by enclosing it in double-quotes.", "");
Property ExecuteProcess::WorkingDir("Working Directory",
"The directory to use as the current working directory when executing the command", "");
Property ExecuteProcess::BatchDuration("Batch Duration",
"If the process is expected to be long-running and produce textual output, a batch duration can be specified.", "0");
Property ExecuteProcess::RedirectErrorStream("Redirect Error Stream",
"If true will redirect any error stream output of the process to the output stream.", "false");
Relationship ExecuteProcess::Success("success", "All created FlowFiles are routed to this relationship.");
void ExecuteProcess::initialize()
{
//! Set the supported properties
std::set<Property> properties;
properties.insert(Command);
properties.insert(CommandArguments);
properties.insert(WorkingDir);
properties.insert(BatchDuration);
properties.insert(RedirectErrorStream);
setSupportedProperties(properties);
//! Set the supported relationships
std::set<Relationship> relationships;
relationships.insert(Success);
setSupportedRelationships(relationships);
}
void ExecuteProcess::onTrigger(ProcessContext *context, ProcessSession *session)
{
std::string value;
if (context->getProperty(Command.getName(), value))
{
this->_command = value;
}
if (context->getProperty(CommandArguments.getName(), value))
{
this->_commandArgument = value;
}
if (context->getProperty(WorkingDir.getName(), value))
{
this->_workingDir = value;
}
if (context->getProperty(BatchDuration.getName(), value))
{
TimeUnit unit;
if (Property::StringToTime(value, _batchDuration, unit) &&
Property::ConvertTimeUnitToMS(_batchDuration, unit, _batchDuration))
{
}
}
if (context->getProperty(RedirectErrorStream.getName(), value))
{
Property::StringToBool(value, _redirectErrorStream);
}
this->_fullCommand = _command + " " + _commandArgument;
if (_fullCommand.length() == 0)
{
yield();
return;
}
if (_workingDir.length() > 0 && _workingDir != ".")
{
// change to working directory
if (chdir(_workingDir.c_str()) != 0)
{
_logger->log_error("Execute Command can not chdir %s", _workingDir.c_str());
yield();
return;
}
}
_logger->log_info("Execute Command %s", _fullCommand.c_str());
// split the command into array
char cstr[_fullCommand.length()+1];
std::strcpy(cstr, _fullCommand.c_str());
char *p = std::strtok (cstr, " ");
int argc = 0;
char *argv[64];
while (p != 0 && argc < 64)
{
argv[argc] = p;
p = std::strtok(NULL, " ");
argc++;
}
argv[argc] = NULL;
int status, died;
if (!_processRunning)
{
_processRunning = true;
// if the process has not launched yet
// create the pipe
if (pipe(_pipefd) == -1)
{
_processRunning = false;
yield();
return;
}
switch (_pid = fork())
{
case -1:
_logger->log_error("Execute Process fork failed");
_processRunning = false;
close(_pipefd[0]);
close(_pipefd[1]);
yield();
break;
case 0 : // this is the code the child runs
close(1); // close stdout
dup(_pipefd[1]); // points pipefd at file descriptor
if (_redirectErrorStream)
// redirect stderr
dup2(_pipefd[1], 2);
close(_pipefd[0]);
execvp(argv[0], argv);
exit(1);
break;
default: // this is the code the parent runs
// the parent isn't going to write to the pipe
close(_pipefd[1]);
if (_batchDuration > 0)
{
while (1)
{
std::this_thread::sleep_for(std::chrono::milliseconds(_batchDuration));
char buffer[4096];
int numRead = read(_pipefd[0], buffer, sizeof(buffer));
if (numRead <= 0)
break;
_logger->log_info("Execute Command Respond %d", numRead);
ExecuteProcess::WriteCallback callback(buffer, numRead);
FlowFileRecord *flowFile = session->create();
if (!flowFile)
continue;
session->write(flowFile, &callback);
session->transfer(flowFile, Success);
session->commit();
}
}
else
{
char buffer[4096];
char *bufPtr = buffer;
int totalRead = 0;
FlowFileRecord *flowFile = NULL;
while (1)
{
int numRead = read(_pipefd[0], bufPtr, (sizeof(buffer) - totalRead));
if (numRead <= 0)
{
if (totalRead > 0)
{
_logger->log_info("Execute Command Respond %d", totalRead);
// child exits and close the pipe
ExecuteProcess::WriteCallback callback(buffer, totalRead);
if (!flowFile)
{
flowFile = session->create();
if (!flowFile)
break;
session->write(flowFile, &callback);
}
else
{
session->append(flowFile, &callback);
}
session->transfer(flowFile, Success);
}
break;
}
else
{
if (numRead == (sizeof(buffer) - totalRead))
{
// we reach the max buffer size
_logger->log_info("Execute Command Max Respond %d", sizeof(buffer));
ExecuteProcess::WriteCallback callback(buffer, sizeof(buffer));
if (!flowFile)
{
flowFile = session->create();
if (!flowFile)
continue;
session->write(flowFile, &callback);
}
else
{
session->append(flowFile, &callback);
}
// Rewind
totalRead = 0;
bufPtr = buffer;
}
else
{
totalRead += numRead;
bufPtr += numRead;
}
}
}
}
died= wait(&status);
if (WIFEXITED(status))
{
_logger->log_info("Execute Command Complete %s status %d pid %d", _fullCommand.c_str(), WEXITSTATUS(status), _pid);
}
else
{
_logger->log_info("Execute Command Complete %s status %d pid %d", _fullCommand.c_str(), WTERMSIG(status), _pid);
}
close(_pipefd[0]);
_processRunning = false;
break;
}
}
}
<commit_msg>MINIFI-161: Provide command and arguments as attributes in ExecuteProcess<commit_after>/**
* @file ExecuteProcess.cpp
* ExecuteProcess class implementation
*
* 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.
*/
#include "TimeUtil.h"
#include "ExecuteProcess.h"
#include "ProcessContext.h"
#include "ProcessSession.h"
#include <cstring>
const std::string ExecuteProcess::ProcessorName("ExecuteProcess");
Property ExecuteProcess::Command("Command", "Specifies the command to be executed; if just the name of an executable is provided, it must be in the user's environment PATH.", "");
Property ExecuteProcess::CommandArguments("Command Arguments",
"The arguments to supply to the executable delimited by white space. White space can be escaped by enclosing it in double-quotes.", "");
Property ExecuteProcess::WorkingDir("Working Directory",
"The directory to use as the current working directory when executing the command", "");
Property ExecuteProcess::BatchDuration("Batch Duration",
"If the process is expected to be long-running and produce textual output, a batch duration can be specified.", "0");
Property ExecuteProcess::RedirectErrorStream("Redirect Error Stream",
"If true will redirect any error stream output of the process to the output stream.", "false");
Relationship ExecuteProcess::Success("success", "All created FlowFiles are routed to this relationship.");
void ExecuteProcess::initialize()
{
//! Set the supported properties
std::set<Property> properties;
properties.insert(Command);
properties.insert(CommandArguments);
properties.insert(WorkingDir);
properties.insert(BatchDuration);
properties.insert(RedirectErrorStream);
setSupportedProperties(properties);
//! Set the supported relationships
std::set<Relationship> relationships;
relationships.insert(Success);
setSupportedRelationships(relationships);
}
void ExecuteProcess::onTrigger(ProcessContext *context, ProcessSession *session)
{
std::string value;
if (context->getProperty(Command.getName(), value))
{
this->_command = value;
}
if (context->getProperty(CommandArguments.getName(), value))
{
this->_commandArgument = value;
}
if (context->getProperty(WorkingDir.getName(), value))
{
this->_workingDir = value;
}
if (context->getProperty(BatchDuration.getName(), value))
{
TimeUnit unit;
if (Property::StringToTime(value, _batchDuration, unit) &&
Property::ConvertTimeUnitToMS(_batchDuration, unit, _batchDuration))
{
}
}
if (context->getProperty(RedirectErrorStream.getName(), value))
{
Property::StringToBool(value, _redirectErrorStream);
}
this->_fullCommand = _command + " " + _commandArgument;
if (_fullCommand.length() == 0)
{
yield();
return;
}
if (_workingDir.length() > 0 && _workingDir != ".")
{
// change to working directory
if (chdir(_workingDir.c_str()) != 0)
{
_logger->log_error("Execute Command can not chdir %s", _workingDir.c_str());
yield();
return;
}
}
_logger->log_info("Execute Command %s", _fullCommand.c_str());
// split the command into array
char cstr[_fullCommand.length()+1];
std::strcpy(cstr, _fullCommand.c_str());
char *p = std::strtok (cstr, " ");
int argc = 0;
char *argv[64];
while (p != 0 && argc < 64)
{
argv[argc] = p;
p = std::strtok(NULL, " ");
argc++;
}
argv[argc] = NULL;
int status, died;
if (!_processRunning)
{
_processRunning = true;
// if the process has not launched yet
// create the pipe
if (pipe(_pipefd) == -1)
{
_processRunning = false;
yield();
return;
}
switch (_pid = fork())
{
case -1:
_logger->log_error("Execute Process fork failed");
_processRunning = false;
close(_pipefd[0]);
close(_pipefd[1]);
yield();
break;
case 0 : // this is the code the child runs
close(1); // close stdout
dup(_pipefd[1]); // points pipefd at file descriptor
if (_redirectErrorStream)
// redirect stderr
dup2(_pipefd[1], 2);
close(_pipefd[0]);
execvp(argv[0], argv);
exit(1);
break;
default: // this is the code the parent runs
// the parent isn't going to write to the pipe
close(_pipefd[1]);
if (_batchDuration > 0)
{
while (1)
{
std::this_thread::sleep_for(std::chrono::milliseconds(_batchDuration));
char buffer[4096];
int numRead = read(_pipefd[0], buffer, sizeof(buffer));
if (numRead <= 0)
break;
_logger->log_info("Execute Command Respond %d", numRead);
ExecuteProcess::WriteCallback callback(buffer, numRead);
FlowFileRecord *flowFile = session->create();
if (!flowFile)
continue;
flowFile->addAttribute("command", _command.c_str());
flowFile->addAttribute("command.arguments", _commandArgument.c_str());
session->write(flowFile, &callback);
session->transfer(flowFile, Success);
session->commit();
}
}
else
{
char buffer[4096];
char *bufPtr = buffer;
int totalRead = 0;
FlowFileRecord *flowFile = NULL;
while (1)
{
int numRead = read(_pipefd[0], bufPtr, (sizeof(buffer) - totalRead));
if (numRead <= 0)
{
if (totalRead > 0)
{
_logger->log_info("Execute Command Respond %d", totalRead);
// child exits and close the pipe
ExecuteProcess::WriteCallback callback(buffer, totalRead);
if (!flowFile)
{
flowFile = session->create();
if (!flowFile)
break;
flowFile->addAttribute("command", _command.c_str());
flowFile->addAttribute("command.arguments", _commandArgument.c_str());
session->write(flowFile, &callback);
}
else
{
session->append(flowFile, &callback);
}
session->transfer(flowFile, Success);
}
break;
}
else
{
if (numRead == (sizeof(buffer) - totalRead))
{
// we reach the max buffer size
_logger->log_info("Execute Command Max Respond %d", sizeof(buffer));
ExecuteProcess::WriteCallback callback(buffer, sizeof(buffer));
if (!flowFile)
{
flowFile = session->create();
if (!flowFile)
continue;
flowFile->addAttribute("command", _command.c_str());
flowFile->addAttribute("command.arguments", _commandArgument.c_str());
session->write(flowFile, &callback);
}
else
{
session->append(flowFile, &callback);
}
// Rewind
totalRead = 0;
bufPtr = buffer;
}
else
{
totalRead += numRead;
bufPtr += numRead;
}
}
}
}
died= wait(&status);
if (WIFEXITED(status))
{
_logger->log_info("Execute Command Complete %s status %d pid %d", _fullCommand.c_str(), WEXITSTATUS(status), _pid);
}
else
{
_logger->log_info("Execute Command Complete %s status %d pid %d", _fullCommand.c_str(), WTERMSIG(status), _pid);
}
close(_pipefd[0]);
_processRunning = false;
break;
}
}
}
<|endoftext|> |
<commit_before>/**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2011 Sandro Santilli <strk@kbt.io>
* Copyright (C) 2005 Refractions Research Inc.
* Copyright (C) 2001-2002 Vivid Solutions Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: operation/buffer/OffsetCurveSetBuilder.java r378 (JTS-1.12)
*
**********************************************************************/
#include <geos/constants.h>
#include <geos/algorithm/Distance.h>
#include <geos/algorithm/Orientation.h>
#include <geos/algorithm/MinimumDiameter.h>
#include <geos/util/UnsupportedOperationException.h>
#include <geos/operation/buffer/OffsetCurveSetBuilder.h>
#include <geos/operation/buffer/OffsetCurveBuilder.h>
#include <geos/operation/valid/RepeatedPointRemover.h>
#include <geos/geom/CoordinateSequence.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/GeometryCollection.h>
#include <geos/geom/Point.h>
#include <geos/geom/LinearRing.h>
#include <geos/geom/LineString.h>
#include <geos/geom/Polygon.h>
#include <geos/geom/Location.h>
#include <geos/geom/Triangle.h>
#include <geos/geom/Position.h>
#include <geos/geomgraph/Label.h>
#include <geos/noding/NodedSegmentString.h>
#include <geos/util.h>
#include <algorithm> // for min
#include <cmath>
#include <cassert>
#include <memory>
#include <vector>
#include <typeinfo>
#ifndef GEOS_DEBUG
#define GEOS_DEBUG 0
#endif
//using namespace geos::operation::overlay;
using namespace geos::geom;
using namespace geos::noding; // SegmentString
using namespace geos::geomgraph; // Label, Position
using namespace geos::algorithm; // Orientation
namespace geos {
namespace operation { // geos.operation
namespace buffer { // geos.operation.buffer
OffsetCurveSetBuilder::OffsetCurveSetBuilder(const Geometry& newInputGeom,
double newDistance, OffsetCurveBuilder& newCurveBuilder):
inputGeom(newInputGeom),
distance(newDistance),
curveBuilder(newCurveBuilder),
curveList(),
isInvertOrientation(false)
{
}
OffsetCurveSetBuilder::~OffsetCurveSetBuilder()
{
for(std::size_t i = 0, n = curveList.size(); i < n; ++i) {
SegmentString* ss = curveList[i];
delete ss;
}
for(std::size_t i = 0, n = newLabels.size(); i < n; ++i) {
delete newLabels[i];
}
}
/* public */
std::vector<SegmentString*>&
OffsetCurveSetBuilder::getCurves()
{
add(inputGeom);
return curveList;
}
/*public*/
void
OffsetCurveSetBuilder::addCurves(const std::vector<CoordinateSequence*>& lineList,
geom::Location leftLoc, geom::Location rightLoc)
{
for(std::size_t i = 0, n = lineList.size(); i < n; ++i) {
CoordinateSequence* coords = lineList[i];
addCurve(coords, leftLoc, rightLoc);
}
}
/*private*/
void
OffsetCurveSetBuilder::addCurve(CoordinateSequence* coord,
geom::Location leftLoc, geom::Location rightLoc)
{
#if GEOS_DEBUG
std::cerr << __FUNCTION__ << ": coords=" << coord->toString() << std::endl;
#endif
// don't add null curves!
if(coord->getSize() < 2) {
#if GEOS_DEBUG
std::cerr << " skipped (size<2)" << std::endl;
#endif
delete coord;
return;
}
// add the edge for a coordinate list which is a raw offset curve
Label* newlabel = new Label(0, Location::BOUNDARY, leftLoc, rightLoc);
// coord ownership transferred to SegmentString
SegmentString* e = new NodedSegmentString(coord, newlabel);
// SegmentString doesnt own the sequence, so we need to delete in
// the destructor
newLabels.push_back(newlabel);
curveList.push_back(e);
}
/*private*/
void
OffsetCurveSetBuilder::add(const Geometry& g)
{
if(g.isEmpty()) {
#if GEOS_DEBUG
std::cerr << __FUNCTION__ << ": skip empty geometry" << std::endl;
#endif
return;
}
const Polygon* poly = dynamic_cast<const Polygon*>(&g);
if(poly) {
addPolygon(poly);
return;
}
const LineString* line = dynamic_cast<const LineString*>(&g);
if(line) {
addLineString(line);
return;
}
const Point* point = dynamic_cast<const Point*>(&g);
if(point) {
addPoint(point);
return;
}
const GeometryCollection* collection = dynamic_cast<const GeometryCollection*>(&g);
if(collection) {
addCollection(collection);
return;
}
std::string out = typeid(g).name();
throw util::UnsupportedOperationException("GeometryGraph::add(Geometry &): unknown geometry type: " + out);
}
/*private*/
void
OffsetCurveSetBuilder::addCollection(const GeometryCollection* gc)
{
for(std::size_t i = 0, n = gc->getNumGeometries(); i < n; i++) {
const Geometry* g = gc->getGeometryN(i);
add(*g);
}
}
/*private*/
void
OffsetCurveSetBuilder::addPoint(const Point* p)
{
// a zero or negative width buffer of a point is empty
if(distance <= 0.0) {
return;
}
const CoordinateSequence* coord = p->getCoordinatesRO();
if (coord->size() >= 1 && ! coord->getAt(0).isValid()) {
return;
}
std::vector<CoordinateSequence*> lineList;
curveBuilder.getLineCurve(coord, distance, lineList);
addCurves(lineList, Location::EXTERIOR, Location::INTERIOR);
}
/*private*/
void
OffsetCurveSetBuilder::addLineString(const LineString* line)
{
if (curveBuilder.isLineOffsetEmpty(distance)) {
return;
}
auto coord = operation::valid::RepeatedPointRemover::removeRepeatedAndInvalidPoints(line->getCoordinatesRO());
/**
* Rings (closed lines) are generated with a continuous curve,
* with no end arcs. This produces better quality linework,
* and avoids noding issues with arcs around almost-parallel end segments.
* See JTS #523 and #518.
*
* Singled-sided buffers currently treat rings as if they are lines.
*/
if (CoordinateSequence::isRing(coord.get()) && ! curveBuilder.getBufferParameters().isSingleSided()) {
addRingBothSides(coord.get(), distance);
}
else {
std::vector<CoordinateSequence*> lineList;
curveBuilder.getLineCurve(coord.get(), distance, lineList);
addCurves(lineList, Location::EXTERIOR, Location::INTERIOR);
}
}
/*private*/
void
OffsetCurveSetBuilder::addPolygon(const Polygon* p)
{
double offsetDistance = distance;
int offsetSide = Position::LEFT;
if(distance < 0.0) {
offsetDistance = -distance;
offsetSide = Position::RIGHT;
}
const LinearRing* shell = p->getExteriorRing();
// optimization - don't bother computing buffer
// if the polygon would be completely eroded
if(distance < 0.0 && isErodedCompletely(shell, distance)) {
#if GEOS_DEBUG
std::cerr << __FUNCTION__ << ": polygon is eroded completely " << std::endl;
#endif
return;
}
auto shellCoord =
operation::valid::RepeatedPointRemover::removeRepeatedAndInvalidPoints(shell->getCoordinatesRO());
// don't attempt to buffer a polygon
// with too few distinct vertices
if(distance <= 0.0 && shellCoord->size() < 3) {
return;
}
addRingSide(
shellCoord.get(),
offsetDistance,
offsetSide,
Location::EXTERIOR,
Location::INTERIOR);
for(std::size_t i = 0, n = p->getNumInteriorRing(); i < n; ++i) {
const LineString* hls = p->getInteriorRingN(i);
const LinearRing* hole = detail::down_cast<const LinearRing*>(hls);
// optimization - don't bother computing buffer for this hole
// if the hole would be completely covered
if(distance > 0.0 && isErodedCompletely(hole, -distance)) {
continue;
}
auto holeCoord = valid::RepeatedPointRemover::removeRepeatedAndInvalidPoints(hole->getCoordinatesRO());
// Holes are topologically labelled opposite to the shell,
// since the interior of the polygon lies on their opposite
// side (on the left, if the hole is oriented CCW)
addRingSide(
holeCoord.get(),
offsetDistance,
Position::opposite(offsetSide),
Location::INTERIOR,
Location::EXTERIOR);
}
}
/* private */
void
OffsetCurveSetBuilder::addRingBothSides(const CoordinateSequence* coord, double p_distance)
{
addRingSide(coord, p_distance,
Position::LEFT,
Location::EXTERIOR, Location::INTERIOR);
/* Add the opposite side of the ring
*/
addRingSide(coord, p_distance,
Position::RIGHT,
Location::INTERIOR, Location::EXTERIOR);
}
/* private */
void
OffsetCurveSetBuilder::addRingSide(const CoordinateSequence* coord,
double offsetDistance, int side, geom::Location cwLeftLoc, geom::Location cwRightLoc)
{
// don't bother adding ring if it is "flat" and
// will disappear in the output
if(offsetDistance == 0.0 && coord->size() < LinearRing::MINIMUM_VALID_SIZE) {
return;
}
Location leftLoc = cwLeftLoc;
Location rightLoc = cwRightLoc;
#if GEOS_DEBUG
std::cerr << "OffsetCurveSetBuilder::addPolygonRing: CCW: " << Orientation::isCCW(coord) << std::endl;
#endif
bool isCCW = isRingCCW(coord);
if (coord->size() >= LinearRing::MINIMUM_VALID_SIZE && isCCW)
{
leftLoc = cwRightLoc;
rightLoc = cwLeftLoc;
#if GEOS_DEBUG
std::cerr << " side " << side << " becomes " << Position::opposite(side) << std::endl;
#endif
side = Position::opposite(side);
}
std::vector<CoordinateSequence*> lineList;
curveBuilder.getRingCurve(coord, side, offsetDistance, lineList);
// ASSERT: lineList contains exactly 1 curve (this is teh JTS semantics)
if (lineList.size() > 0) {
const CoordinateSequence* curve = lineList[0];
/**
* If the offset curve has inverted completely it will produce
* an unwanted artifact in the result, so skip it.
*/
if (isRingCurveInverted(coord, offsetDistance, curve)) {
return;
}
}
addCurves(lineList, leftLoc, rightLoc);
}
/* private static*/
bool
OffsetCurveSetBuilder::isRingCurveInverted(
const CoordinateSequence* inputPts, double dist,
const CoordinateSequence* curvePts)
{
if (dist == 0.0) return false;
/**
* Only proper rings can invert.
*/
if (inputPts->size() <= 3) return false;
/**
* Heuristic based on low chance that a ring with many vertices will invert.
* This low limit ensures this test is fairly efficient.
*/
if (inputPts->size() >= MAX_INVERTED_RING_SIZE) return false;
/**
* An inverted curve has no more points than the input ring.
* This also eliminates concave inputs (which will produce fillet arcs)
*/
if (curvePts->size() > inputPts->size()) return false;
/**
* Check if the curve vertices are all closer to the input ring
* than the buffer distance.
* If so, the curve is NOT a valid buffer curve.
*/
double distTol = NEARNESS_FACTOR * fabs(dist);
double maxDist = maxDistance(curvePts, inputPts);
bool isCurveTooClose = maxDist < distTol;
return isCurveTooClose;
}
/**
* Computes the maximum distance out of a set of points to a linestring.
*
* @param pts the points
* @param line the linestring vertices
* @return the maximum distance
*/
/* private static */
double
OffsetCurveSetBuilder::maxDistance(const CoordinateSequence* pts, const CoordinateSequence* line) {
double maxDistance = 0;
for (std::size_t i = 0; i < pts->size(); i++) {
const Coordinate& p = pts->getAt(i);
double dist = Distance::pointToSegmentString(p, line);
if (dist > maxDistance) {
maxDistance = dist;
}
}
return maxDistance;
}
/*private*/
bool
OffsetCurveSetBuilder::isErodedCompletely(const LinearRing* ring,
double bufferDistance)
{
const CoordinateSequence* ringCoord = ring->getCoordinatesRO();
// degenerate ring has no area
if(ringCoord->getSize() < 4) {
return bufferDistance < 0;
}
// important test to eliminate inverted triangle bug
// also optimizes erosion test for triangles
if(ringCoord->getSize() == 4) {
return isTriangleErodedCompletely(ringCoord, bufferDistance);
}
const Envelope* env = ring->getEnvelopeInternal();
double envMinDimension = std::min(env->getHeight(), env->getWidth());
if(bufferDistance < 0.0 && 2 * std::abs(bufferDistance) > envMinDimension) {
return true;
}
return false;
}
/*private*/
bool
OffsetCurveSetBuilder::isTriangleErodedCompletely(
const CoordinateSequence* triangleCoord, double bufferDistance)
{
Triangle tri(triangleCoord->getAt(0), triangleCoord->getAt(1), triangleCoord->getAt(2));
Coordinate inCentre;
tri.inCentre(inCentre);
double distToCentre = Distance::pointToSegment(inCentre, tri.p0, tri.p1);
bool ret = distToCentre < std::fabs(bufferDistance);
return ret;
}
/*private*/
bool
OffsetCurveSetBuilder::isRingCCW(const CoordinateSequence* coords) const
{
bool isCCW = algorithm::Orientation::isCCWArea(coords);
//--- invert orientation if required
if (isInvertOrientation) return ! isCCW;
return isCCW;
}
} // namespace geos.operation.buffer
} // namespace geos.operation
} // namespace geos
<commit_msg>OffsetCurveSetBuilder::addRingSide(): fix memleak<commit_after>/**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2011 Sandro Santilli <strk@kbt.io>
* Copyright (C) 2005 Refractions Research Inc.
* Copyright (C) 2001-2002 Vivid Solutions Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: operation/buffer/OffsetCurveSetBuilder.java r378 (JTS-1.12)
*
**********************************************************************/
#include <geos/constants.h>
#include <geos/algorithm/Distance.h>
#include <geos/algorithm/Orientation.h>
#include <geos/algorithm/MinimumDiameter.h>
#include <geos/util/UnsupportedOperationException.h>
#include <geos/operation/buffer/OffsetCurveSetBuilder.h>
#include <geos/operation/buffer/OffsetCurveBuilder.h>
#include <geos/operation/valid/RepeatedPointRemover.h>
#include <geos/geom/CoordinateSequence.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/GeometryCollection.h>
#include <geos/geom/Point.h>
#include <geos/geom/LinearRing.h>
#include <geos/geom/LineString.h>
#include <geos/geom/Polygon.h>
#include <geos/geom/Location.h>
#include <geos/geom/Triangle.h>
#include <geos/geom/Position.h>
#include <geos/geomgraph/Label.h>
#include <geos/noding/NodedSegmentString.h>
#include <geos/util.h>
#include <algorithm> // for min
#include <cmath>
#include <cassert>
#include <memory>
#include <vector>
#include <typeinfo>
#ifndef GEOS_DEBUG
#define GEOS_DEBUG 0
#endif
//using namespace geos::operation::overlay;
using namespace geos::geom;
using namespace geos::noding; // SegmentString
using namespace geos::geomgraph; // Label, Position
using namespace geos::algorithm; // Orientation
namespace geos {
namespace operation { // geos.operation
namespace buffer { // geos.operation.buffer
OffsetCurveSetBuilder::OffsetCurveSetBuilder(const Geometry& newInputGeom,
double newDistance, OffsetCurveBuilder& newCurveBuilder):
inputGeom(newInputGeom),
distance(newDistance),
curveBuilder(newCurveBuilder),
curveList(),
isInvertOrientation(false)
{
}
OffsetCurveSetBuilder::~OffsetCurveSetBuilder()
{
for(std::size_t i = 0, n = curveList.size(); i < n; ++i) {
SegmentString* ss = curveList[i];
delete ss;
}
for(std::size_t i = 0, n = newLabels.size(); i < n; ++i) {
delete newLabels[i];
}
}
/* public */
std::vector<SegmentString*>&
OffsetCurveSetBuilder::getCurves()
{
add(inputGeom);
return curveList;
}
/*public*/
void
OffsetCurveSetBuilder::addCurves(const std::vector<CoordinateSequence*>& lineList,
geom::Location leftLoc, geom::Location rightLoc)
{
for(std::size_t i = 0, n = lineList.size(); i < n; ++i) {
CoordinateSequence* coords = lineList[i];
addCurve(coords, leftLoc, rightLoc);
}
}
/*private*/
void
OffsetCurveSetBuilder::addCurve(CoordinateSequence* coord,
geom::Location leftLoc, geom::Location rightLoc)
{
#if GEOS_DEBUG
std::cerr << __FUNCTION__ << ": coords=" << coord->toString() << std::endl;
#endif
// don't add null curves!
if(coord->getSize() < 2) {
#if GEOS_DEBUG
std::cerr << " skipped (size<2)" << std::endl;
#endif
delete coord;
return;
}
// add the edge for a coordinate list which is a raw offset curve
Label* newlabel = new Label(0, Location::BOUNDARY, leftLoc, rightLoc);
// coord ownership transferred to SegmentString
SegmentString* e = new NodedSegmentString(coord, newlabel);
// SegmentString doesnt own the sequence, so we need to delete in
// the destructor
newLabels.push_back(newlabel);
curveList.push_back(e);
}
/*private*/
void
OffsetCurveSetBuilder::add(const Geometry& g)
{
if(g.isEmpty()) {
#if GEOS_DEBUG
std::cerr << __FUNCTION__ << ": skip empty geometry" << std::endl;
#endif
return;
}
const Polygon* poly = dynamic_cast<const Polygon*>(&g);
if(poly) {
addPolygon(poly);
return;
}
const LineString* line = dynamic_cast<const LineString*>(&g);
if(line) {
addLineString(line);
return;
}
const Point* point = dynamic_cast<const Point*>(&g);
if(point) {
addPoint(point);
return;
}
const GeometryCollection* collection = dynamic_cast<const GeometryCollection*>(&g);
if(collection) {
addCollection(collection);
return;
}
std::string out = typeid(g).name();
throw util::UnsupportedOperationException("GeometryGraph::add(Geometry &): unknown geometry type: " + out);
}
/*private*/
void
OffsetCurveSetBuilder::addCollection(const GeometryCollection* gc)
{
for(std::size_t i = 0, n = gc->getNumGeometries(); i < n; i++) {
const Geometry* g = gc->getGeometryN(i);
add(*g);
}
}
/*private*/
void
OffsetCurveSetBuilder::addPoint(const Point* p)
{
// a zero or negative width buffer of a point is empty
if(distance <= 0.0) {
return;
}
const CoordinateSequence* coord = p->getCoordinatesRO();
if (coord->size() >= 1 && ! coord->getAt(0).isValid()) {
return;
}
std::vector<CoordinateSequence*> lineList;
curveBuilder.getLineCurve(coord, distance, lineList);
addCurves(lineList, Location::EXTERIOR, Location::INTERIOR);
}
/*private*/
void
OffsetCurveSetBuilder::addLineString(const LineString* line)
{
if (curveBuilder.isLineOffsetEmpty(distance)) {
return;
}
auto coord = operation::valid::RepeatedPointRemover::removeRepeatedAndInvalidPoints(line->getCoordinatesRO());
/**
* Rings (closed lines) are generated with a continuous curve,
* with no end arcs. This produces better quality linework,
* and avoids noding issues with arcs around almost-parallel end segments.
* See JTS #523 and #518.
*
* Singled-sided buffers currently treat rings as if they are lines.
*/
if (CoordinateSequence::isRing(coord.get()) && ! curveBuilder.getBufferParameters().isSingleSided()) {
addRingBothSides(coord.get(), distance);
}
else {
std::vector<CoordinateSequence*> lineList;
curveBuilder.getLineCurve(coord.get(), distance, lineList);
addCurves(lineList, Location::EXTERIOR, Location::INTERIOR);
}
}
/*private*/
void
OffsetCurveSetBuilder::addPolygon(const Polygon* p)
{
double offsetDistance = distance;
int offsetSide = Position::LEFT;
if(distance < 0.0) {
offsetDistance = -distance;
offsetSide = Position::RIGHT;
}
const LinearRing* shell = p->getExteriorRing();
// optimization - don't bother computing buffer
// if the polygon would be completely eroded
if(distance < 0.0 && isErodedCompletely(shell, distance)) {
#if GEOS_DEBUG
std::cerr << __FUNCTION__ << ": polygon is eroded completely " << std::endl;
#endif
return;
}
auto shellCoord =
operation::valid::RepeatedPointRemover::removeRepeatedAndInvalidPoints(shell->getCoordinatesRO());
// don't attempt to buffer a polygon
// with too few distinct vertices
if(distance <= 0.0 && shellCoord->size() < 3) {
return;
}
addRingSide(
shellCoord.get(),
offsetDistance,
offsetSide,
Location::EXTERIOR,
Location::INTERIOR);
for(std::size_t i = 0, n = p->getNumInteriorRing(); i < n; ++i) {
const LineString* hls = p->getInteriorRingN(i);
const LinearRing* hole = detail::down_cast<const LinearRing*>(hls);
// optimization - don't bother computing buffer for this hole
// if the hole would be completely covered
if(distance > 0.0 && isErodedCompletely(hole, -distance)) {
continue;
}
auto holeCoord = valid::RepeatedPointRemover::removeRepeatedAndInvalidPoints(hole->getCoordinatesRO());
// Holes are topologically labelled opposite to the shell,
// since the interior of the polygon lies on their opposite
// side (on the left, if the hole is oriented CCW)
addRingSide(
holeCoord.get(),
offsetDistance,
Position::opposite(offsetSide),
Location::INTERIOR,
Location::EXTERIOR);
}
}
/* private */
void
OffsetCurveSetBuilder::addRingBothSides(const CoordinateSequence* coord, double p_distance)
{
addRingSide(coord, p_distance,
Position::LEFT,
Location::EXTERIOR, Location::INTERIOR);
/* Add the opposite side of the ring
*/
addRingSide(coord, p_distance,
Position::RIGHT,
Location::INTERIOR, Location::EXTERIOR);
}
/* private */
void
OffsetCurveSetBuilder::addRingSide(const CoordinateSequence* coord,
double offsetDistance, int side, geom::Location cwLeftLoc, geom::Location cwRightLoc)
{
// don't bother adding ring if it is "flat" and
// will disappear in the output
if(offsetDistance == 0.0 && coord->size() < LinearRing::MINIMUM_VALID_SIZE) {
return;
}
Location leftLoc = cwLeftLoc;
Location rightLoc = cwRightLoc;
#if GEOS_DEBUG
std::cerr << "OffsetCurveSetBuilder::addPolygonRing: CCW: " << Orientation::isCCW(coord) << std::endl;
#endif
bool isCCW = isRingCCW(coord);
if (coord->size() >= LinearRing::MINIMUM_VALID_SIZE && isCCW)
{
leftLoc = cwRightLoc;
rightLoc = cwLeftLoc;
#if GEOS_DEBUG
std::cerr << " side " << side << " becomes " << Position::opposite(side) << std::endl;
#endif
side = Position::opposite(side);
}
std::vector<CoordinateSequence*> lineList;
curveBuilder.getRingCurve(coord, side, offsetDistance, lineList);
// ASSERT: lineList contains exactly 1 curve (this is teh JTS semantics)
if (lineList.size() > 0) {
const CoordinateSequence* curve = lineList[0];
/**
* If the offset curve has inverted completely it will produce
* an unwanted artifact in the result, so skip it.
*/
if (isRingCurveInverted(coord, offsetDistance, curve)) {
for( auto line: lineList ) {
delete line;
}
return;
}
}
addCurves(lineList, leftLoc, rightLoc);
}
/* private static*/
bool
OffsetCurveSetBuilder::isRingCurveInverted(
const CoordinateSequence* inputPts, double dist,
const CoordinateSequence* curvePts)
{
if (dist == 0.0) return false;
/**
* Only proper rings can invert.
*/
if (inputPts->size() <= 3) return false;
/**
* Heuristic based on low chance that a ring with many vertices will invert.
* This low limit ensures this test is fairly efficient.
*/
if (inputPts->size() >= MAX_INVERTED_RING_SIZE) return false;
/**
* An inverted curve has no more points than the input ring.
* This also eliminates concave inputs (which will produce fillet arcs)
*/
if (curvePts->size() > inputPts->size()) return false;
/**
* Check if the curve vertices are all closer to the input ring
* than the buffer distance.
* If so, the curve is NOT a valid buffer curve.
*/
double distTol = NEARNESS_FACTOR * fabs(dist);
double maxDist = maxDistance(curvePts, inputPts);
bool isCurveTooClose = maxDist < distTol;
return isCurveTooClose;
}
/**
* Computes the maximum distance out of a set of points to a linestring.
*
* @param pts the points
* @param line the linestring vertices
* @return the maximum distance
*/
/* private static */
double
OffsetCurveSetBuilder::maxDistance(const CoordinateSequence* pts, const CoordinateSequence* line) {
double maxDistance = 0;
for (std::size_t i = 0; i < pts->size(); i++) {
const Coordinate& p = pts->getAt(i);
double dist = Distance::pointToSegmentString(p, line);
if (dist > maxDistance) {
maxDistance = dist;
}
}
return maxDistance;
}
/*private*/
bool
OffsetCurveSetBuilder::isErodedCompletely(const LinearRing* ring,
double bufferDistance)
{
const CoordinateSequence* ringCoord = ring->getCoordinatesRO();
// degenerate ring has no area
if(ringCoord->getSize() < 4) {
return bufferDistance < 0;
}
// important test to eliminate inverted triangle bug
// also optimizes erosion test for triangles
if(ringCoord->getSize() == 4) {
return isTriangleErodedCompletely(ringCoord, bufferDistance);
}
const Envelope* env = ring->getEnvelopeInternal();
double envMinDimension = std::min(env->getHeight(), env->getWidth());
if(bufferDistance < 0.0 && 2 * std::abs(bufferDistance) > envMinDimension) {
return true;
}
return false;
}
/*private*/
bool
OffsetCurveSetBuilder::isTriangleErodedCompletely(
const CoordinateSequence* triangleCoord, double bufferDistance)
{
Triangle tri(triangleCoord->getAt(0), triangleCoord->getAt(1), triangleCoord->getAt(2));
Coordinate inCentre;
tri.inCentre(inCentre);
double distToCentre = Distance::pointToSegment(inCentre, tri.p0, tri.p1);
bool ret = distToCentre < std::fabs(bufferDistance);
return ret;
}
/*private*/
bool
OffsetCurveSetBuilder::isRingCCW(const CoordinateSequence* coords) const
{
bool isCCW = algorithm::Orientation::isCCWArea(coords);
//--- invert orientation if required
if (isInvertOrientation) return ! isCCW;
return isCCW;
}
} // namespace geos.operation.buffer
} // namespace geos.operation
} // namespace geos
<|endoftext|> |
<commit_before>#include <fstream>
#include <iostream>
#include <stdexcept>
#include <vector>
#include "napiconfig.h"
#include "binary/BinaryRetriever.hpp"
#include "string_util.h"
using std::invalid_argument;
using std::runtime_error;
using std::string;
using std::vector;
using std::cout;
using std::endl;
typedef uint32_t data_t;
/**
* \file NXtranslate/binary/BinaryRetriever.cpp
*/
/**
* All nodes returned by BinaryRetriever::getData will have this name.
*/
static const string NAME("binary");
/**
* This is the constructor for the object. No resources are allocated.
*
* \param str The source string is ignored, but necessary to implement
* the interface.
*/
BinaryRetriever::BinaryRetriever(const string &source_file): filename(source_file)
{
// there is nothing additional to allocate
}
/**
* Since no resources were allocated, the destructor does nothing
*/
BinaryRetriever::~BinaryRetriever()
{
// there is nothing to deallocate
}
static size_t calculate_position(const vector<int> &file_size,
const vector<int> &pos)
{
size_t rank=file_size.size();
size_t result=0;
for( size_t i=0 ; i<rank ; ++i )
{
result=static_cast<size_t>(file_size[i]*result+pos[i]);
}
return result;
}
static bool increment_position(const vector<int> &offset,
const vector<int> &size,
vector<int> &pos)
{
int index=size.size()-2;
while(index>=0){
if(pos[index]+1<offset[index]+size[index])
{
pos[index]++;
return true;
}
else
{
pos[index]=offset[index];
index--;
}
}
return false;
}
/**
* This is the method for retrieving data from a file. The string must
* be of the form "type:offset,delta,number".
*
* \param location is the string that is used by the retriever to
* create the data.
* \param tr is the tree to put the result into.
*/
void BinaryRetriever::getData(const string &location, tree<Node> &tr)
{
// check that the argument is not an empty string
if(location.size()<=0)
{
throw invalid_argument("cannot parse empty string");
}
// break the location string into three parts: file_size,data_start,data_size
string file_size_str;
string start_str;
string size_str;
{
vector<string> temp=string_util::split(location,"][");
if(temp.size()!=3)
{
throw invalid_argument("wrong number of groups in location string");
}
file_size_str=temp[0].substr(1);
start_str=temp[1];
size_str=temp[2].substr(0,temp[2].size()-1);
}
// convert the parts into vector<int>
vector<int> file_size=string_util::str_to_intVec(file_size_str);
vector<int> start=string_util::str_to_intVec(start_str);
vector<int> size=string_util::str_to_intVec(size_str);
// check for the same dimension
int rank=file_size.size();
if(start.size()!=rank || size.size()!=rank)
{
throw invalid_argument("All parts of the location string must be the same rank");
}
// confirm that the size doesn't have a zero component
for( size_t i ; i<rank ; ++i )
{
if( size[i]<=0 )
{
throw invalid_argument("the size arguments must all be greater than zero");
}
}
// check that the request doesn't seek past the end of the file
for( size_t i ; i<rank ; ++i )
{
if(file_size[i]<start[i]+size[i])
{
throw invalid_argument("start[i]+size[i] must be less than file_size[i]");
}
}
// determine the total file size
size_t tot_file_size=1;
for( vector<int>::iterator it=file_size.begin() ; it!=file_size.end() ; ++it)
{
tot_file_size*=(*it);
}
// set up the starting position
vector<int> pos;
for( size_t i=0 ; i<start.size() ; i++ )
{
pos.push_back(start[i]);
}
// create integer copy of size
int dims[size.size()];
for( size_t i=0 ; i<size.size() ; ++i )
{
dims[i]=size[i];
}
// allocate the space for the result
void *data;
if(NXmalloc(&data,rank,dims,NX_UINT32)!=NX_OK)
{
throw runtime_error("NXmalloc failed");
}
// prepare data buffer
size_t data_size=sizeof(data_t);
/*
size_t num_items=1;
size_t buffer_size=num_items; // read a single element at a time
data_t data_buffer[buffer_size];
*/
// open the file
std::ifstream data_file(filename.c_str(), std::ios::binary);
if(!(data_file.is_open()))
{
throw runtime_error("Failed opening file");
}
// check the file size against claims
{
data_file.seekg(0,std::ios::beg);
long begin=data_file.tellg();
data_file.seekg(0,std::ios::end);
long end=data_file.tellg();
if( (end-begin)!=(tot_file_size*data_size) )
{
throw runtime_error("Actual file size does not match claimed file size");
}
}
// number for the scalar version of the offset
size_t scalar_position;
// index into data array
size_t data_index=0;
// buffer to read data into
size_t num_items=*(size.rbegin());
size_t buffer_size=num_items*data_size;
data_t data_buffer[num_items];
// push through the file grabbing the proper bits
scalar_position=data_size*calculate_position(file_size,pos);
data_file.seekg(scalar_position,std::ios::beg);
data_file.read(reinterpret_cast<char *>(data_buffer),buffer_size);
// copy into final array
memcpy((static_cast<data_t *>(data))+data_index,data_buffer,buffer_size);
data_index+=num_items;
while(increment_position(start,size,pos))
{
// calculate where to go and read in a block of data
scalar_position=data_size*calculate_position(file_size,pos);
data_file.seekg(scalar_position,std::ios::beg);
data_file.read(reinterpret_cast<char *>(data_buffer),buffer_size);
// copy into final array
memcpy((static_cast<data_t *>(data))+data_index,data_buffer,buffer_size);
data_index+=num_items;
}
// close the file
data_file.close();
// create the node - this copies the data
Node node=Node(NAME,data,rank,dims,NX_UINT32);
// insert the data into the tree
tr.insert(tr.begin(),node);
// delete the data
if(NXfree(&data)!=NX_OK)
{
throw runtime_error("NXfree failed");
}
}
/**
* The MIME_TYPE is necessary so the retriever can be selected by the
* factory.
*/
const string BinaryRetriever::MIME_TYPE("binary");
/**
* This function returns a string representation of the retriever for
* debugging. Since no resources are allocated the string is always
* identical.
*
* \return The string returned is always "[loopy]".
*/
string BinaryRetriever::toString() const
{
return "["+MIME_TYPE+"]:"+filename;
}
<commit_msg>Added ability to deal with multiple types of binary data.<commit_after>#include <fstream>
#include <iostream>
#include <stdexcept>
#include <vector>
#include "napiconfig.h"
#include "binary/BinaryRetriever.hpp"
#include "string_util.h"
using std::invalid_argument;
using std::runtime_error;
using std::string;
using std::vector;
using std::cout;
using std::endl;
static const string INT8("INT8");
static const string INT16("INT16");
static const string INT32("INT32");
static const string UINT8("UINT8");
static const string UINT16("UINT16");
static const string UINT32("UINT32");
static const string FLOAT32("FLOAT32");
static const string FLOAT64("FLOAT64");
static const string BYTE("BYTE");
static const int DEFAULT_TYPE=NX_UINT32;
/**
* \file NXtranslate/binary/BinaryRetriever.cpp
*/
/**
* All nodes returned by BinaryRetriever::getData will have this name.
*/
static const string NAME("binary");
/**
* This is the constructor for the object. No resources are allocated.
*
* \param str The source string is ignored, but necessary to implement
* the interface.
*/
BinaryRetriever::BinaryRetriever(const string &source_file): filename(source_file)
{
// there is nothing additional to allocate
}
/**
* Since no resources were allocated, the destructor does nothing
*/
BinaryRetriever::~BinaryRetriever()
{
// there is nothing to deallocate
}
static size_t calculate_position(const vector<int> &file_size,
const vector<int> &pos)
{
size_t rank=file_size.size();
size_t result=0;
for( size_t i=0 ; i<rank ; ++i )
{
result=static_cast<size_t>(file_size[i]*result+pos[i]);
}
return result;
}
static bool increment_position(const vector<int> &offset,
const vector<int> &size,
vector<int> &pos)
{
int index=size.size()-2;
while(index>=0){
if(pos[index]+1<offset[index]+size[index])
{
pos[index]++;
return true;
}
else
{
pos[index]=offset[index];
index--;
}
}
return false;
}
/**
* This function turns the type as a string into an integer for use
* with NeXus.
*/
static int getDataType(const string &str_type){
if(str_type.empty()){
return DEFAULT_TYPE;
}else if(str_type==INT8){
return NX_INT8;
}else if(str_type==INT16){
return NX_INT16;
}else if(str_type==INT32){
return NX_INT32;
}else if(str_type==UINT8){
return NX_UINT8;
}else if(str_type==UINT16){
return NX_UINT16;
}else if(str_type==UINT32){
return NX_UINT32;
}else if(str_type==FLOAT32){
return NX_FLOAT32;
}else if(str_type==FLOAT64){
return NX_FLOAT64;
}else if(str_type==BYTE){
return NX_CHAR;
}else{
throw invalid_argument("Invalid type: "+str_type);
}
}
/**
* This function turns the type as a string into a platform dependent
* size.
*/
static size_t getDataTypeSize(const int type){
if(type==NX_INT8){
return sizeof(int8_t);
}else if(type==NX_INT16){
return sizeof(int16_t);
}else if(type==NX_INT32){
return sizeof(int32_t);
}else if(type==NX_UINT8){
return sizeof(uint8_t);
}else if(type==NX_UINT16){
return sizeof(uint16_t);
}else if(type==NX_UINT32){
return sizeof(uint32_t);
}else if(type==NX_FLOAT32){
return sizeof(float);
}else if(type==NX_FLOAT64){
return sizeof(double);
}else if(type==NX_CHAR){
return sizeof(char);
}else{
throw invalid_argument("This statement should never be reached");
}
}
/**
* This is the method for retrieving data from a file. The string must
* be of the form "type:offset,delta,number".
*
* \param location is the string that is used by the retriever to
* create the data.
* \param tr is the tree to put the result into.
*/
void BinaryRetriever::getData(const string &location, tree<Node> &tr)
{
// check that the argument is not an empty string
if(location.size()<=0)
{
throw invalid_argument("cannot parse empty string");
}
// break the location string into a type and sizing information
int type;
string sizing;
{
vector<string> temp=string_util::split(location,":");
cout << "SIZE=" << temp.size() << endl;
if(temp.size()==1){
type=getDataType("");
sizing=location;
}else if(temp.size()==2){
type=getDataType(temp[0]);
sizing=temp[1];
}else{
throw invalid_argument("can only specify one type in location string");
}
cout << "\"" << type << "\" \"" << sizing << "\"" << endl;
}
// break the location string into three parts: file_size,data_start,data_size
string file_size_str;
string start_str;
string size_str;
{
vector<string> temp=string_util::split(sizing,"][");
if(temp.size()!=3)
{
throw invalid_argument("wrong number of groups in location string");
}
file_size_str=temp[0].substr(1);
start_str=temp[1];
size_str=temp[2].substr(0,temp[2].size()-1);
}
// convert the parts into vector<int>
vector<int> file_size=string_util::str_to_intVec(file_size_str);
vector<int> start=string_util::str_to_intVec(start_str);
vector<int> size=string_util::str_to_intVec(size_str);
// check for the same dimension
int rank=file_size.size();
if(start.size()!=rank || size.size()!=rank)
{
throw invalid_argument("All parts of the location string must be the same rank");
}
// confirm that the size doesn't have a zero component
for( size_t i ; i<rank ; ++i )
{
if( size[i]<=0 )
{
throw invalid_argument("the size arguments must all be greater than zero");
}
}
// check that the request doesn't seek past the end of the file
for( size_t i ; i<rank ; ++i )
{
if(file_size[i]<start[i]+size[i])
{
throw invalid_argument("start[i]+size[i] must be less than file_size[i]");
}
}
// determine the total file size
size_t tot_file_size=1;
for( vector<int>::iterator it=file_size.begin() ; it!=file_size.end() ; ++it)
{
tot_file_size*=(*it);
}
// set up the starting position
vector<int> pos;
for( size_t i=0 ; i<start.size() ; i++ )
{
pos.push_back(start[i]);
}
// create integer copy of size
int dims[size.size()];
for( size_t i=0 ; i<size.size() ; ++i )
{
dims[i]=size[i];
}
// allocate the space for the result
void *data;
cout << "TYPE=" << type << endl;
if(NXmalloc(&data,rank,dims,type)!=NX_OK)
{
throw runtime_error("NXmalloc failed");
}
// prepare data buffer
size_t data_size=getDataTypeSize(type);
/*
size_t num_items=1;
size_t buffer_size=num_items; // read a single element at a time
data_t data_buffer[buffer_size];
*/
// open the file
std::ifstream data_file(filename.c_str(), std::ios::binary);
if(!(data_file.is_open()))
{
throw runtime_error("Failed opening file");
}
// check the file size against claims
{
data_file.seekg(0,std::ios::beg);
long begin=data_file.tellg();
data_file.seekg(0,std::ios::end);
long end=data_file.tellg();
if( (end-begin)!=(tot_file_size*data_size) )
{
throw runtime_error("Actual file size does not match claimed file size");
}
}
// number for the scalar version of the offset
size_t scalar_position;
// index into data array
size_t data_index=0;
// buffer to read data into
size_t num_items=*(size.rbegin());
size_t buffer_size=num_items*data_size;
char data_buffer[buffer_size];
// push through the file grabbing the proper bits
scalar_position=data_size*calculate_position(file_size,pos);
data_file.seekg(scalar_position,std::ios::beg);
data_file.read(data_buffer,buffer_size);
// copy into final array
memcpy((static_cast<char *>(data))+data_index*data_size,data_buffer,buffer_size);
data_index+=num_items;
while(increment_position(start,size,pos))
{
// calculate where to go and read in a block of data
scalar_position=data_size*calculate_position(file_size,pos);
data_file.seekg(scalar_position,std::ios::beg);
data_file.read(reinterpret_cast<char *>(data_buffer),buffer_size);
// copy into final array
memcpy((static_cast<char *>(data))+data_index*data_size,data_buffer,buffer_size);
data_index+=num_items;
}
// close the file
data_file.close();
// create the node - this copies the data
Node node=Node(NAME,data,rank,dims,NX_UINT32);
// insert the data into the tree
tr.insert(tr.begin(),node);
// delete the data
if(NXfree(&data)!=NX_OK)
{
throw runtime_error("NXfree failed");
}
}
/**
* The MIME_TYPE is necessary so the retriever can be selected by the
* factory.
*/
const string BinaryRetriever::MIME_TYPE("binary");
/**
* This function returns a string representation of the retriever for
* debugging. Since no resources are allocated the string is always
* identical.
*
* \return The string returned is always "[loopy]".
*/
string BinaryRetriever::toString() const
{
return "["+MIME_TYPE+"]:"+filename;
}
<|endoftext|> |
<commit_before>/* CUDA memory management functions
*
* Copyright (C) 2008 Peter Colberg
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CUDA_MEMORY_HPP
#define CUDA_MEMORY_HPP
#include <assert.h>
#include <cuda/cuda_runtime.h>
#include <cuda_wrapper/host/vector.hpp>
#include <cuda_wrapper/symbol.hpp>
#include <cuda_wrapper/vector.hpp>
#include <vector>
namespace cuda
{
/**
* copy from device memory area to device memory area
*/
template <typename T, typename U>
void copy(vector<T> const& src, vector<U>& dst)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpy(dst.data(), src.data(), src.size() * sizeof(T), cudaMemcpyDeviceToDevice));
}
/**
* copy from host memory area to device memory area
*/
template <typename T, typename AllocT, typename U>
void copy(std::vector<T, AllocT> const& src, vector<U>& dst)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpy(dst.data(), src.data(), src.size() * sizeof(T), cudaMemcpyHostToDevice));
}
/**
* copy from device memory area to host memory area
*/
template <typename T, typename U, typename AllocU>
void copy(vector<T> const& src, std::vector<U, AllocU>& dst)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpy(dst.data(), src.data(), src.size() * sizeof(T), cudaMemcpyDeviceToHost));
}
/**
* copy from host memory area to host memory area
*/
template <typename T, typename AllocT, typename U, typename AllocU>
void copy(std::vector<T, AllocT> const& src, std::vector<U, AllocU>& dst)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpy(dst.data(), src.data(), src.size() * sizeof(T), cudaMemcpyHostToHost));
}
/**
* copy from device symbol to value
*/
template <typename T, typename U>
void copy(symbol<T> const& src, U& dst)
{
assert(src.size() == 1);
CUDA_CALL(cudaMemcpyFromSymbol(&dst, reinterpret_cast<char const*>(src.data()), src.size() * sizeof(T), 0, cudaMemcpyDeviceToHost));
}
/**
* copy from device symbol to host memory area
*/
template <typename T, typename U, typename AllocU>
void copy(symbol<T> const& src, std::vector<U, AllocU>& dst)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpyFromSymbol(dst.data(), reinterpret_cast<char const*>(src.data()), src.size() * sizeof(T), 0, cudaMemcpyDeviceToHost));
}
/*
* copy from device symbol to device memory area
*/
template <typename T, typename U>
void copy(symbol<T> const& src, vector<U>& dst)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpyFromSymbol(dst.data(), reinterpret_cast<char const*>(src.data()), src.size() * sizeof(T), 0, cudaMemcpyDeviceToDevice));
}
/**
* copy from value to device symbol
*/
template <typename T, typename U>
void copy(T const& src, symbol<U>& dst)
{
assert(1 == dst.size());
CUDA_CALL(cudaMemcpyToSymbol(reinterpret_cast<char const*>(dst.data()), &src, sizeof(T), 0, cudaMemcpyHostToDevice));
}
/**
* copy from host memory area to device symbol
*/
template <typename T, typename AllocT, typename U>
void copy(std::vector<T, AllocT> const& src, symbol<U>& dst)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpyToSymbol(reinterpret_cast<char const*>(dst.data()), src.data(), src.size() * sizeof(T), 0, cudaMemcpyHostToDevice));
}
/**
* copy from device memory area to device symbol
*/
template <typename T, typename U>
void copy(vector<T> const& src, symbol<U>& dst)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpyToSymbol(reinterpret_cast<char const*>(dst.data()), src.data(), src.size() * sizeof(T), 0, cudaMemcpyDeviceToDevice));
}
#ifdef CUDA_WRAPPER_ASYNC_API
/**
* asynchronous copy from device memory area to device memory area
*/
template <typename T, typename U>
void copy(vector<T> const& src, vector<U>& dst, stream& stream)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpyAsync(dst.data(), src.data(), src.size() * sizeof(T), cudaMemcpyDeviceToDevice, stream.data()));
}
/**
* asynchronous copy from host memory area to device memory area
*/
template <typename T, typename U>
void copy(host::vector<T> const& src, vector<U>& dst, stream& stream)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpyAsync(dst.data(), src.data(), src.size() * sizeof(T), cudaMemcpyHostToDevice, stream.data()));
}
/**
* asynchronous copy from host memory area to host memory area
*/
template <typename T, typename U>
void copy(host::vector<T> const& src, host::vector<U>& dst, stream& stream)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpyAsync(dst.data(), src.data(), src.size() * sizeof(T), cudaMemcpyHostToHost, stream.data()));
}
/**
* asynchronous copy from device memory area to host memory area
*/
template <typename T, typename U>
void copy(vector<T> const& src, host::vector<U>& dst, stream& stream)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpyAsync(dst.data(), src.data(), src.size() * sizeof(T), cudaMemcpyDeviceToHost, stream.data()));
}
#endif /* CUDA_WRAPPER_ASYNC_API */
} // namespace cuda
#endif /* ! CUDA_MEMORY_HPP */
<commit_msg>Return to type-safe CUDA memcpy functions<commit_after>/* CUDA memory management functions
*
* Copyright (C) 2008 Peter Colberg
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CUDA_MEMORY_HPP
#define CUDA_MEMORY_HPP
#include <assert.h>
#include <cuda/cuda_runtime.h>
#include <cuda_wrapper/host/vector.hpp>
#include <cuda_wrapper/symbol.hpp>
#include <cuda_wrapper/vector.hpp>
#include <vector>
namespace cuda
{
/**
* copy from device memory area to device memory area
*/
template <typename T>
void copy(vector<T> const& src, vector<T>& dst)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpy(dst.data(), src.data(), src.size() * sizeof(T), cudaMemcpyDeviceToDevice));
}
/**
* copy from host memory area to device memory area
*/
template <typename T, typename Alloc>
void copy(std::vector<T, Alloc> const& src, vector<T>& dst)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpy(dst.data(), src.data(), src.size() * sizeof(T), cudaMemcpyHostToDevice));
}
/**
* copy from device memory area to host memory area
*/
template <typename T, typename Alloc>
void copy(vector<T> const& src, std::vector<T, Alloc>& dst)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpy(dst.data(), src.data(), src.size() * sizeof(T), cudaMemcpyDeviceToHost));
}
/**
* copy from host memory area to host memory area
*/
template <typename T, typename Alloc>
void copy(std::vector<T, Alloc> const& src, std::vector<T, Alloc>& dst)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpy(dst.data(), src.data(), src.size() * sizeof(T), cudaMemcpyHostToHost));
}
/**
* copy from device symbol to value
*/
template <typename T>
void copy(symbol<T> const& src, T& dst)
{
assert(src.size() == 1);
CUDA_CALL(cudaMemcpyFromSymbol(&dst, reinterpret_cast<char const*>(src.data()), src.size() * sizeof(T), 0, cudaMemcpyDeviceToHost));
}
/**
* copy from device symbol to host memory area
*/
template <typename T, typename Alloc>
void copy(symbol<T> const& src, std::vector<T, Alloc>& dst)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpyFromSymbol(dst.data(), reinterpret_cast<char const*>(src.data()), src.size() * sizeof(T), 0, cudaMemcpyDeviceToHost));
}
/*
* copy from device symbol to device memory area
*/
template <typename T>
void copy(symbol<T> const& src, vector<T>& dst)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpyFromSymbol(dst.data(), reinterpret_cast<char const*>(src.data()), src.size() * sizeof(T), 0, cudaMemcpyDeviceToDevice));
}
/**
* copy from value to device symbol
*/
template <typename T>
void copy(T const& src, symbol<T>& dst)
{
assert(1 == dst.size());
CUDA_CALL(cudaMemcpyToSymbol(reinterpret_cast<char const*>(dst.data()), &src, sizeof(T), 0, cudaMemcpyHostToDevice));
}
/**
* copy from host memory area to device symbol
*/
template <typename T, typename Alloc>
void copy(std::vector<T, Alloc> const& src, symbol<T>& dst)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpyToSymbol(reinterpret_cast<char const*>(dst.data()), src.data(), src.size() * sizeof(T), 0, cudaMemcpyHostToDevice));
}
/**
* copy from device memory area to device symbol
*/
template <typename T>
void copy(vector<T> const& src, symbol<T>& dst)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpyToSymbol(reinterpret_cast<char const*>(dst.data()), src.data(), src.size() * sizeof(T), 0, cudaMemcpyDeviceToDevice));
}
#ifdef CUDA_WRAPPER_ASYNC_API
/**
* asynchronous copy from device memory area to device memory area
*/
template <typename T>
void copy(vector<T> const& src, vector<T>& dst, stream& stream)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpyAsync(dst.data(), src.data(), src.size() * sizeof(T), cudaMemcpyDeviceToDevice, stream.data()));
}
/**
* asynchronous copy from host memory area to device memory area
*/
template <typename T>
void copy(host::vector<T> const& src, vector<T>& dst, stream& stream)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpyAsync(dst.data(), src.data(), src.size() * sizeof(T), cudaMemcpyHostToDevice, stream.data()));
}
/**
* asynchronous copy from host memory area to host memory area
*/
template <typename T>
void copy(host::vector<T> const& src, host::vector<T>& dst, stream& stream)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpyAsync(dst.data(), src.data(), src.size() * sizeof(T), cudaMemcpyHostToHost, stream.data()));
}
/**
* asynchronous copy from device memory area to host memory area
*/
template <typename T>
void copy(vector<T> const& src, host::vector<T>& dst, stream& stream)
{
assert(src.size() == dst.size());
CUDA_CALL(cudaMemcpyAsync(dst.data(), src.data(), src.size() * sizeof(T), cudaMemcpyDeviceToHost, stream.data()));
}
#endif /* CUDA_WRAPPER_ASYNC_API */
} // namespace cuda
#endif /* ! CUDA_MEMORY_HPP */
<|endoftext|> |
<commit_before>/* bzfls
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <sstream>
#include <string>
#include <stdio.h>
#include <string.h>
#include "config.h"
// opaque version number increments on protocol incompatibility
#ifndef BZ_PROTO_VERSION
#define BZ_PROTO_VERSION "0019"
#endif
#ifndef BZ_MAJOR_VERSION
#define BZ_MAJOR_VERSION 1
#endif
#ifndef BZ_MINOR_VERSION
#define BZ_MINOR_VERSION 11
#endif
#ifndef BZ_REV
#define BZ_REV 30
#endif
// DEVEL | STABLE | MAINT
#ifndef BZ_BUILD_TYPE
#define BZ_BUILD_TYPE "DEVEL"
#endif
const char *bzfcopyright = "Copyright (c) 1993 - 2004 Tim Riker";
#ifndef BZ_BUILD_DATE
/* to get the version in the right format YYYYMMDD */
/* yes this is horible but it needs to be done to get it right */
/* windows should pull from a resouce */
/* *nix gets this from the passed from my the Makefile */
char buildDate[] = {__DATE__};
int getBuildDate()
{
int year = 1900, month = 0, day = 0;
char monthStr[512];
sscanf(buildDate, "%s %d %d", monthStr, &day, &year);
// we want it not as a name but a number
if (strcmp(monthStr, "Jan") == 0)
month = 1;
else if (strcmp(monthStr, "Feb") == 0)
month = 2;
else if (strcmp(monthStr, "Mar") == 0)
month = 3;
else if (strcmp(monthStr, "Apr") == 0)
month = 4;
else if (strcmp(monthStr, "May") == 0)
month = 5;
else if (strcmp(monthStr, "Jun") == 0)
month = 6;
else if (strcmp(monthStr, "Jul") == 0)
month = 7;
else if (strcmp(monthStr, "Aug") == 0)
month = 8;
else if (strcmp(monthStr, "Sep") == 0)
month = 9;
else if (strcmp(monthStr, "Oct") == 0)
month = 10;
else if (strcmp(monthStr, "Nov") == 0)
month = 11;
else if (strcmp(monthStr, "Dec") == 0)
month = 12;
return (year*10000) + (month*100)+ day;
}
#endif
// down here so above gets created
#include "version.h"
const char* getProtocolVersion()
{
static std::string protVersion = BZ_PROTO_VERSION;
return protVersion.c_str();
}
const char* getServerVersion()
{
static std::string serverVersion = std::string("BZFS") + getProtocolVersion();
return serverVersion.c_str();
}
const char* getAppVersion()
{
static std::string appVersion = "";
if (!appVersion.size()){
std::ostringstream appVersionStream;
// TODO add current platform, release, cpu, etc
appVersionStream << BZ_MAJOR_VERSION << "." << BZ_MINOR_VERSION << "." << BZ_REV << "." << BZ_BUILD_DATE
<< "-" << BZ_BUILD_TYPE << "-" << BZ_BUILD_OS;
#ifdef HAVE_SDL
appVersionStream << "-SDL";
#endif
appVersion = appVersionStream.str();
}
return appVersion.c_str();
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>!MsgVersion, !MsgAudio, !MsgVideo, bump version<commit_after>/* bzfls
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <sstream>
#include <string>
#include <stdio.h>
#include <string.h>
#include "config.h"
// opaque version number increments on protocol incompatibility
#ifndef BZ_PROTO_VERSION
#define BZ_PROTO_VERSION "0020"
#endif
#ifndef BZ_MAJOR_VERSION
#define BZ_MAJOR_VERSION 1
#endif
#ifndef BZ_MINOR_VERSION
#define BZ_MINOR_VERSION 11
#endif
#ifndef BZ_REV
#define BZ_REV 30
#endif
// DEVEL | STABLE | MAINT
#ifndef BZ_BUILD_TYPE
#define BZ_BUILD_TYPE "DEVEL"
#endif
const char *bzfcopyright = "Copyright (c) 1993 - 2004 Tim Riker";
#ifndef BZ_BUILD_DATE
/* to get the version in the right format YYYYMMDD */
/* yes this is horible but it needs to be done to get it right */
/* windows should pull from a resouce */
/* *nix gets this from the passed from my the Makefile */
char buildDate[] = {__DATE__};
int getBuildDate()
{
int year = 1900, month = 0, day = 0;
char monthStr[512];
sscanf(buildDate, "%s %d %d", monthStr, &day, &year);
// we want it not as a name but a number
if (strcmp(monthStr, "Jan") == 0)
month = 1;
else if (strcmp(monthStr, "Feb") == 0)
month = 2;
else if (strcmp(monthStr, "Mar") == 0)
month = 3;
else if (strcmp(monthStr, "Apr") == 0)
month = 4;
else if (strcmp(monthStr, "May") == 0)
month = 5;
else if (strcmp(monthStr, "Jun") == 0)
month = 6;
else if (strcmp(monthStr, "Jul") == 0)
month = 7;
else if (strcmp(monthStr, "Aug") == 0)
month = 8;
else if (strcmp(monthStr, "Sep") == 0)
month = 9;
else if (strcmp(monthStr, "Oct") == 0)
month = 10;
else if (strcmp(monthStr, "Nov") == 0)
month = 11;
else if (strcmp(monthStr, "Dec") == 0)
month = 12;
return (year*10000) + (month*100)+ day;
}
#endif
// down here so above gets created
#include "version.h"
const char* getProtocolVersion()
{
static std::string protVersion = BZ_PROTO_VERSION;
return protVersion.c_str();
}
const char* getServerVersion()
{
static std::string serverVersion = std::string("BZFS") + getProtocolVersion();
return serverVersion.c_str();
}
const char* getAppVersion()
{
static std::string appVersion = "";
if (!appVersion.size()){
std::ostringstream appVersionStream;
// TODO add current platform, release, cpu, etc
appVersionStream << BZ_MAJOR_VERSION << "." << BZ_MINOR_VERSION << "." << BZ_REV << "." << BZ_BUILD_DATE
<< "-" << BZ_BUILD_TYPE << "-" << BZ_BUILD_OS;
#ifdef HAVE_SDL
appVersionStream << "-SDL";
#endif
appVersion = appVersionStream.str();
}
return appVersion.c_str();
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/*
Copyright (c) 2012, 2018 Intel Corporation
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 Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// written by Roman Dementiev
#define HACK_TO_REMOVE_DUPLICATE_ERROR
#include "cpucounters.h"
#ifdef _MSC_VER
#include <windows.h>
#include "../PCM_Win/windriver.h"
#else
#include <unistd.h>
#endif
#include <iostream>
#include <stdlib.h>
#include <iomanip>
#include <string.h>
#ifdef _MSC_VER
#include "freegetopt/getopt.h"
#endif
uint64 read_number(char * str)
{
std::istringstream stream(str);
if (strstr(str, "x")) stream >> std::hex;
uint64 result = 0;
stream >> result;
return result;
}
void print_usage(const char * progname)
{
std::cout << "Usage " << progname << " [-w value] [-d] group bus device function offset\n\n";
std::cout << " Reads/writes 32-bit PCICFG register \n";
std::cout << " -w value : write the value before reading \n";
std::cout << " -d : output all numbers in dec (default is hex)\n";
std::cout << "\n";
}
int main(int argc, char * argv[])
{
std::cout << "\n Processor Counter Monitor " << PCM_VERSION << std::endl;
std::cout << "\n PCICFG read/write utility\n\n";
uint32 value = 0;
bool write = false;
bool dec = false;
int my_opt = -1;
while ((my_opt = getopt(argc, argv, "w:d")) != -1)
{
switch (my_opt)
{
case 'w':
write = true;
value = read_number(optarg);
break;
case 'd':
dec = true;
break;
default:
print_usage(argv[0]);
return -1;
}
}
if (optind + 4 >= argc)
{
print_usage(argv[0]);
return -1;
}
int group = (int)read_number(argv[optind]);
int bus = (int)read_number(argv[optind + 1]);
int device = (int)read_number(argv[optind+2]);
int function = (int)read_number(argv[optind+3]);
int offset = (int)read_number(argv[optind+4]);
#ifdef _MSC_VER
// Increase the priority a bit to improve context switching delays on Windows
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
TCHAR driverPath[1032];
GetCurrentDirectory(1024, driverPath);
wcscat_s(driverPath, 1032, L"\\msr.sys");
// WARNING: This driver code (msr.sys) is only for testing purposes, not for production use
Driver drv;
// drv.stop(); // restart driver (usually not needed)
if (!drv.start(driverPath))
{
std::cerr << "Can not load MSR driver." << std::endl;
std::cerr << "You must have signed msr.sys driver in your current directory and have administrator rights to run this program" << std::endl;
return -1;
}
#endif
try {
PciHandleType h(group, bus, device, function);
if (!dec) std::cout << std::hex << std::showbase;
if (write)
{
std::cout << " Writing " << value << " to " << group << ":"<<bus<<":"<<device<<":"<< function<<"@"<<offset << std::endl;
h.write32(offset, value);
}
value = 0;
h.read32(offset, &value);
std::cout << " Read value " << value << " from " << group << ":"<<bus<<":"<<device<<":"<< function<<"@"<<offset << "\n" << std::endl;
}
catch (std::exception & e)
{
std::cerr << "Error accessing registers: " << e.what() << std::endl;
std::cerr << "Please check if the program can access MSR/PCICFG drivers." << std::endl;
}
}
<commit_msg>add a note about *extended* configuration space access<commit_after>/*
Copyright (c) 2012, 2018 Intel Corporation
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 Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// written by Roman Dementiev
#define HACK_TO_REMOVE_DUPLICATE_ERROR
#include "cpucounters.h"
#ifdef _MSC_VER
#include <windows.h>
#include "../PCM_Win/windriver.h"
#else
#include <unistd.h>
#endif
#include <iostream>
#include <stdlib.h>
#include <iomanip>
#include <string.h>
#ifdef _MSC_VER
#include "freegetopt/getopt.h"
#endif
uint64 read_number(char * str)
{
std::istringstream stream(str);
if (strstr(str, "x")) stream >> std::hex;
uint64 result = 0;
stream >> result;
return result;
}
void print_usage(const char * progname)
{
std::cout << "Usage " << progname << " [-w value] [-d] group bus device function offset\n\n";
std::cout << " Reads/writes 32-bit PCICFG register \n";
std::cout << " -w value : write the value before reading \n";
std::cout << " -d : output all numbers in dec (default is hex)\n";
std::cout << "\n";
}
int main(int argc, char * argv[])
{
std::cout << "\n Processor Counter Monitor " << PCM_VERSION << std::endl;
std::cout << "\n PCICFG read/write utility\n\n";
#ifdef __linux__
#ifndef PCM_USE_PCI_MM_LINUX
std::cout << "\n To access *extended* configuration space recompile with -DPCM_USE_PCI_MM_LINUX option.\n";
#endif
#endif
uint32 value = 0;
bool write = false;
bool dec = false;
int my_opt = -1;
while ((my_opt = getopt(argc, argv, "w:d")) != -1)
{
switch (my_opt)
{
case 'w':
write = true;
value = read_number(optarg);
break;
case 'd':
dec = true;
break;
default:
print_usage(argv[0]);
return -1;
}
}
if (optind + 4 >= argc)
{
print_usage(argv[0]);
return -1;
}
int group = (int)read_number(argv[optind]);
int bus = (int)read_number(argv[optind + 1]);
int device = (int)read_number(argv[optind+2]);
int function = (int)read_number(argv[optind+3]);
int offset = (int)read_number(argv[optind+4]);
#ifdef _MSC_VER
// Increase the priority a bit to improve context switching delays on Windows
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
TCHAR driverPath[1032];
GetCurrentDirectory(1024, driverPath);
wcscat_s(driverPath, 1032, L"\\msr.sys");
// WARNING: This driver code (msr.sys) is only for testing purposes, not for production use
Driver drv;
// drv.stop(); // restart driver (usually not needed)
if (!drv.start(driverPath))
{
std::cerr << "Can not load MSR driver." << std::endl;
std::cerr << "You must have signed msr.sys driver in your current directory and have administrator rights to run this program" << std::endl;
return -1;
}
#endif
try {
PciHandleType h(group, bus, device, function);
if (!dec) std::cout << std::hex << std::showbase;
if (write)
{
std::cout << " Writing " << value << " to " << group << ":"<<bus<<":"<<device<<":"<< function<<"@"<<offset << std::endl;
h.write32(offset, value);
}
value = 0;
h.read32(offset, &value);
std::cout << " Read value " << value << " from " << group << ":"<<bus<<":"<<device<<":"<< function<<"@"<<offset << "\n" << std::endl;
}
catch (std::exception & e)
{
std::cerr << "Error accessing registers: " << e.what() << std::endl;
std::cerr << "Please check if the program can access MSR/PCICFG drivers." << std::endl;
}
}
<|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.
*/
/*
* Copyright 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#ifndef CQL3_COLUMN_IDENTIFIER_HH
#define CQL3_COLUMN_IDENTIFIER_HH
#include "cql3/selection/selectable.hh"
#include "database.hh"
#include <algorithm>
#include <functional>
#include <iostream>
namespace cql3 {
#if 0
import java.util.List;
import java.util.Locale;
import java.nio.ByteBuffer;
import org.apache.cassandra.cache.IMeasurableMemory;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.ColumnDefinition;
import org.apache.cassandra.cql3.selection.Selectable;
import org.apache.cassandra.cql3.selection.Selector;
import org.apache.cassandra.cql3.selection.SimpleSelector;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.exceptions.InvalidRequestException;
import org.apache.cassandra.db.marshal.CompositeType;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.ObjectSizes;
import org.apache.cassandra.utils.memory.AbstractAllocator;
#endif
/**
* Represents an identifer for a CQL column definition.
* TODO : should support light-weight mode without text representation for when not interned
*/
class column_identifier final : public selection::selectable /* implements IMeasurableMemory*/ {
public:
bytes bytes_;
private:
sstring _text;
#if 0
private static final long EMPTY_SIZE = ObjectSizes.measure(new ColumnIdentifier("", true));
#endif
public:
column_identifier(sstring raw_text, bool keep_case) {
_text = std::move(raw_text);
if (!keep_case) {
std::transform(_text.begin(), _text.end(), _text.begin(), ::tolower);
}
bytes_ = to_bytes(_text);
}
column_identifier(bytes bytes_, shared_ptr<abstract_type> type)
: bytes_(std::move(bytes_))
, _text(type->get_string(this->bytes_))
{ }
column_identifier(bytes bytes_, sstring text)
: bytes_(std::move(bytes_))
, _text(std::move(text))
{ }
bool operator==(const column_identifier& other) const {
return bytes_ == other.bytes_;
}
const sstring& text() const {
return _text;
}
sstring to_string() const {
return _text;
}
friend std::ostream& operator<<(std::ostream& out, const column_identifier& i) {
return out << i._text;
}
#if 0
public long unsharedHeapSize()
{
return EMPTY_SIZE
+ ObjectSizes.sizeOnHeapOf(bytes)
+ ObjectSizes.sizeOf(text);
}
public long unsharedHeapSizeExcludingData()
{
return EMPTY_SIZE
+ ObjectSizes.sizeOnHeapExcludingData(bytes)
+ ObjectSizes.sizeOf(text);
}
public ColumnIdentifier clone(AbstractAllocator allocator)
{
return new ColumnIdentifier(allocator.clone(bytes), text);
}
public Selector.Factory newSelectorFactory(CFMetaData cfm, List<ColumnDefinition> defs) throws InvalidRequestException
{
ColumnDefinition def = cfm.getColumnDefinition(this);
if (def == null)
throw new InvalidRequestException(String.format("Undefined name %s in selection clause", this));
return SimpleSelector.newFactory(def.name.toString(), addAndGetIndex(def, defs), def.type);
}
#endif
/**
* Because Thrift-created tables may have a non-text comparator, we cannot determine the proper 'key' until
* we know the comparator. ColumnIdentifier.Raw is a placeholder that can be converted to a real ColumnIdentifier
* once the comparator is known with prepare(). This should only be used with identifiers that are actual
* column names. See CASSANDRA-8178 for more background.
*/
class raw final : public selectable::raw {
private:
const sstring _raw_text;
sstring _text;
public:
raw(sstring raw_text, bool keep_case)
: _raw_text{raw_text}
, _text{raw_text}
{
if (!keep_case) {
std::transform(_text.begin(), _text.end(), _text.begin(), ::tolower);
}
}
virtual ::shared_ptr<selectable> prepare(schema_ptr s) override {
return prepare_column_identifier(s);
}
::shared_ptr<column_identifier> prepare_column_identifier(schema_ptr s);
virtual bool processes_selection() const override {
return false;
}
bool operator==(const raw& other) const {
return _text == other._text;
}
virtual sstring to_string() const {
return _text;
}
friend std::hash<column_identifier::raw>;
friend std::ostream& operator<<(std::ostream& out, const column_identifier::raw& id);
};
};
static inline
column_definition* get_column_definition(schema_ptr schema, column_identifier& id) {
return schema->get_column_definition(id.bytes_);
}
static inline
::shared_ptr<column_identifier> to_identifier(const column_definition& def) {
return def.column_specification->name;
}
static inline
std::vector<::shared_ptr<column_identifier>> to_identifiers(const std::vector<const column_definition*>& defs) {
std::vector<::shared_ptr<column_identifier>> r;
r.reserve(defs.size());
for (auto&& def : defs) {
r.push_back(to_identifier(*def));
}
return r;
}
}
namespace std {
template<>
struct hash<cql3::column_identifier> {
size_t operator()(const cql3::column_identifier& i) const {
return std::hash<bytes>()(i.bytes_);
}
};
template<>
struct hash<cql3::column_identifier::raw> {
size_t operator()(const cql3::column_identifier::raw& r) const {
return std::hash<sstring>()(r._text);
}
};
}
#endif
<commit_msg>cql3: Introduce column_identifier::name()<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.
*/
/*
* Copyright 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#ifndef CQL3_COLUMN_IDENTIFIER_HH
#define CQL3_COLUMN_IDENTIFIER_HH
#include "cql3/selection/selectable.hh"
#include "database.hh"
#include <algorithm>
#include <functional>
#include <iostream>
namespace cql3 {
#if 0
import java.util.List;
import java.util.Locale;
import java.nio.ByteBuffer;
import org.apache.cassandra.cache.IMeasurableMemory;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.ColumnDefinition;
import org.apache.cassandra.cql3.selection.Selectable;
import org.apache.cassandra.cql3.selection.Selector;
import org.apache.cassandra.cql3.selection.SimpleSelector;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.exceptions.InvalidRequestException;
import org.apache.cassandra.db.marshal.CompositeType;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.ObjectSizes;
import org.apache.cassandra.utils.memory.AbstractAllocator;
#endif
/**
* Represents an identifer for a CQL column definition.
* TODO : should support light-weight mode without text representation for when not interned
*/
class column_identifier final : public selection::selectable /* implements IMeasurableMemory*/ {
public:
bytes bytes_;
private:
sstring _text;
#if 0
private static final long EMPTY_SIZE = ObjectSizes.measure(new ColumnIdentifier("", true));
#endif
public:
column_identifier(sstring raw_text, bool keep_case) {
_text = std::move(raw_text);
if (!keep_case) {
std::transform(_text.begin(), _text.end(), _text.begin(), ::tolower);
}
bytes_ = to_bytes(_text);
}
column_identifier(bytes bytes_, shared_ptr<abstract_type> type)
: bytes_(std::move(bytes_))
, _text(type->get_string(this->bytes_))
{ }
column_identifier(bytes bytes_, sstring text)
: bytes_(std::move(bytes_))
, _text(std::move(text))
{ }
bool operator==(const column_identifier& other) const {
return bytes_ == other.bytes_;
}
const sstring& text() const {
return _text;
}
const bytes& name() const {
return bytes_;
}
sstring to_string() const {
return _text;
}
friend std::ostream& operator<<(std::ostream& out, const column_identifier& i) {
return out << i._text;
}
#if 0
public long unsharedHeapSize()
{
return EMPTY_SIZE
+ ObjectSizes.sizeOnHeapOf(bytes)
+ ObjectSizes.sizeOf(text);
}
public long unsharedHeapSizeExcludingData()
{
return EMPTY_SIZE
+ ObjectSizes.sizeOnHeapExcludingData(bytes)
+ ObjectSizes.sizeOf(text);
}
public ColumnIdentifier clone(AbstractAllocator allocator)
{
return new ColumnIdentifier(allocator.clone(bytes), text);
}
public Selector.Factory newSelectorFactory(CFMetaData cfm, List<ColumnDefinition> defs) throws InvalidRequestException
{
ColumnDefinition def = cfm.getColumnDefinition(this);
if (def == null)
throw new InvalidRequestException(String.format("Undefined name %s in selection clause", this));
return SimpleSelector.newFactory(def.name.toString(), addAndGetIndex(def, defs), def.type);
}
#endif
/**
* Because Thrift-created tables may have a non-text comparator, we cannot determine the proper 'key' until
* we know the comparator. ColumnIdentifier.Raw is a placeholder that can be converted to a real ColumnIdentifier
* once the comparator is known with prepare(). This should only be used with identifiers that are actual
* column names. See CASSANDRA-8178 for more background.
*/
class raw final : public selectable::raw {
private:
const sstring _raw_text;
sstring _text;
public:
raw(sstring raw_text, bool keep_case)
: _raw_text{raw_text}
, _text{raw_text}
{
if (!keep_case) {
std::transform(_text.begin(), _text.end(), _text.begin(), ::tolower);
}
}
virtual ::shared_ptr<selectable> prepare(schema_ptr s) override {
return prepare_column_identifier(s);
}
::shared_ptr<column_identifier> prepare_column_identifier(schema_ptr s);
virtual bool processes_selection() const override {
return false;
}
bool operator==(const raw& other) const {
return _text == other._text;
}
virtual sstring to_string() const {
return _text;
}
friend std::hash<column_identifier::raw>;
friend std::ostream& operator<<(std::ostream& out, const column_identifier::raw& id);
};
};
static inline
column_definition* get_column_definition(schema_ptr schema, column_identifier& id) {
return schema->get_column_definition(id.bytes_);
}
static inline
::shared_ptr<column_identifier> to_identifier(const column_definition& def) {
return def.column_specification->name;
}
static inline
std::vector<::shared_ptr<column_identifier>> to_identifiers(const std::vector<const column_definition*>& defs) {
std::vector<::shared_ptr<column_identifier>> r;
r.reserve(defs.size());
for (auto&& def : defs) {
r.push_back(to_identifier(*def));
}
return r;
}
}
namespace std {
template<>
struct hash<cql3::column_identifier> {
size_t operator()(const cql3::column_identifier& i) const {
return std::hash<bytes>()(i.bytes_);
}
};
template<>
struct hash<cql3::column_identifier::raw> {
size_t operator()(const cql3::column_identifier::raw& r) const {
return std::hash<sstring>()(r._text);
}
};
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "CrashManager.h"
#include "OrbitBase/Logging.h"
#include "services.grpc.pb.h"
namespace {
class CrashManagerImpl final : public CrashManager {
public:
explicit CrashManagerImpl(std::shared_ptr<grpc::Channel> channel);
void CrashOrbitService(
CrashOrbitServiceRequest_CrashType crash_type) override;
private:
std::unique_ptr<CrashService::Stub> crash_service_;
};
CrashManagerImpl::CrashManagerImpl(std::shared_ptr<grpc::Channel> channel)
: crash_service_(CrashService::NewStub(channel)) {}
void CrashManagerImpl::CrashOrbitService(
CrashOrbitServiceRequest_CrashType crash_type) {
CrashOrbitServiceRequest request;
request.set_crash_type(crash_type);
CrashOrbitServiceResponse response;
grpc::ClientContext context;
grpc::Status status =
crash_service_->CrashOrbitService(&context, request, &response);
if (!status.ok()) {
ERROR("Grpc call failed: %s", status.error_message());
}
}
} // namespace
std::unique_ptr<CrashManager> CrashManager::Create(
std::shared_ptr<grpc::Channel> channel) {
std::unique_ptr<CrashManagerImpl> impl =
std::make_unique<CrashManagerImpl>(channel);
return impl;
}
<commit_msg>fix CrashOrbitService call<commit_after>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "CrashManager.h"
#include "OrbitBase/Logging.h"
#include "services.grpc.pb.h"
namespace {
class CrashManagerImpl final : public CrashManager {
public:
explicit CrashManagerImpl(std::shared_ptr<grpc::Channel> channel);
void CrashOrbitService(
CrashOrbitServiceRequest_CrashType crash_type) override;
private:
std::unique_ptr<CrashService::Stub> crash_service_;
};
CrashManagerImpl::CrashManagerImpl(std::shared_ptr<grpc::Channel> channel)
: crash_service_(CrashService::NewStub(channel)) {}
void CrashManagerImpl::CrashOrbitService(
CrashOrbitServiceRequest_CrashType crash_type) {
CrashOrbitServiceRequest request;
request.set_crash_type(crash_type);
CrashOrbitServiceResponse response;
grpc::ClientContext context;
std::function<void(grpc::Status)> callback = [](::grpc::Status status) {
if (!status.ok()) {
ERROR("Grpc call failed: %s", status.error_message());
}
};
crash_service_->experimental_async()->CrashOrbitService(&context, &request,
&response, callback);
}
} // namespace
std::unique_ptr<CrashManager> CrashManager::Create(
std::shared_ptr<grpc::Channel> channel) {
std::unique_ptr<CrashManagerImpl> impl =
std::make_unique<CrashManagerImpl>(channel);
return impl;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* pxgsettings - A helper binary to query gsettings
* Copyright (C) 2006 Nathaniel McCallum <nathaniel@natemccallum.com>
* Copyright (C) 2011 Dominique Leuenberger <dominique@leuenberger.net>
*
* 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>
#include <unistd.h>
#include <signal.h>
#include <stdexcept>
#include <glib.h>
#include <glib-object.h>
#include <gio/gio.h>
using namespace std;
static GMainLoop* loop = NULL;
static int print_value(GVariant *value, const char *suffix) {
if (!value) return 0;
if (g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {
return printf("%s%s", g_variant_get_string(value, NULL), suffix);
}
else if(g_variant_is_of_type(value, G_VARIANT_TYPE_INT32)) {
return printf("%d%s", g_variant_get_int32(value), suffix);
}
else if(g_variant_is_of_type(value, G_VARIANT_TYPE_BOOLEAN)) {
gboolean result;
result = g_variant_get_boolean(value);
return printf("%s%s", result ? "true" : "false", suffix);
}
else if(g_variant_is_of_type(value, G_VARIANT_TYPE_ARRAY)) {
int count;
const gchar** items;
items = g_variant_get_strv(value, NULL);
for (count=0; items[count]; count++) {
printf("%s%s", count < 1 ? "" : ",", items[count]);
}
printf("%s", suffix);
return count;
}
else {
throw exception();
}
return 0;
}
static void on_value_change(GSettings *settings, const gchar *key, gpointer user_data) {
printf("%s/%s\t", (gchar *)user_data, key);
print_value(g_settings_get_value(settings, key), "\n");
}
static void on_sig(int /*signal*/) {
g_main_loop_quit(loop);
}
static gboolean err(GIOChannel* /*source*/, GIOCondition /*condition*/, gpointer /*data*/) {
g_main_loop_quit(loop);
return false;
}
static gboolean in(GIOChannel *source, GIOCondition condition, gpointer data) {
gchar *key, *val;
GIOStatus st = g_io_channel_read_line(source, &key, NULL, NULL, NULL);
// Remove the trailing '\n'
for (int i=0 ; key && key[i] ; i++)
if (key[i] == '\n')
key[i] = '\0';
// If we were successful
if (key && st == G_IO_STATUS_NORMAL) {
if (!g_strrstr(key, "\t"))
goto exit;
val = g_strrstr(key, "\t") + 1;
*(val-1) = '\0';
g_free(key);
return true;
}
else if (key && st == G_IO_STATUS_AGAIN) {
g_free(key);
return in(source, condition, data);
}
exit:
g_free(key);
return err(source, condition, data);
}
int main(int argc, char **argv) {
if (argc < 2) return 1;
// Register sighup handler
if (signal(SIGHUP, on_sig) == SIG_ERR || signal(SIGPIPE, on_sig) == SIG_ERR || signal(SIGABRT, on_sig) == SIG_ERR) {
fprintf(stderr, "Unable to trap signals!");
return 2;
}
// Switch stdout to line buffering
if (setvbuf(stdout, NULL, _IOLBF, 0)) {
fprintf(stderr, "Unable to switch stdout to line buffering!");
return 3;
}
// Switch stdin to line buffering
if (setvbuf(stdin, NULL, _IOLBF, 0)) {
fprintf(stderr, "Unable to switch stdin to line buffering!");
return 4;
}
// Init
g_type_init();
// Get the main loop
loop = g_main_loop_new(NULL, false);
// Setup our GIO Channels
GIOChannel* inchan = g_io_channel_unix_new(fileno(stdin));
GIOChannel* outchan = g_io_channel_unix_new(fileno(stdout));
g_io_add_watch(inchan, G_IO_IN, in, NULL);
g_io_add_watch(inchan, G_IO_PRI, in, NULL);
g_io_add_watch(inchan, G_IO_ERR, err, NULL);
g_io_add_watch(inchan, G_IO_HUP, err, NULL);
g_io_add_watch(outchan, G_IO_ERR, err, NULL);
g_io_add_watch(outchan, G_IO_HUP, err, NULL);
// Get GConf client
GSettings* client;
for (int i=1; i<argc; i++) {
client = g_settings_new(argv[i]);
gchar** keys = g_settings_list_keys(client);
for (int j=0; keys[j]; on_value_change(client, keys[j++],argv[i] ));
g_signal_connect(client, "changed::", (GCallback) on_value_change, argv[i]);
}
g_main_loop_run(loop);
// Cleanup
while (G_IS_OBJECT(client)) {
g_object_unref(client);
}
g_io_channel_shutdown(inchan, FALSE, NULL);
g_io_channel_shutdown(outchan, FALSE, NULL);
g_io_channel_unref(inchan);
g_io_channel_unref(outchan);
g_main_loop_unref(loop);
}
<commit_msg>pxgsettings: rename "client" object to "settings", to follow GSettings guidelines and forget GConf<commit_after>/*******************************************************************************
* pxgsettings - A helper binary to query gsettings
* Copyright (C) 2006 Nathaniel McCallum <nathaniel@natemccallum.com>
* Copyright (C) 2011 Dominique Leuenberger <dominique@leuenberger.net>
*
* 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>
#include <unistd.h>
#include <signal.h>
#include <stdexcept>
#include <glib.h>
#include <glib-object.h>
#include <gio/gio.h>
using namespace std;
static GMainLoop* loop = NULL;
static int print_value(GVariant *value, const char *suffix) {
if (!value) return 0;
if (g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {
return printf("%s%s", g_variant_get_string(value, NULL), suffix);
}
else if(g_variant_is_of_type(value, G_VARIANT_TYPE_INT32)) {
return printf("%d%s", g_variant_get_int32(value), suffix);
}
else if(g_variant_is_of_type(value, G_VARIANT_TYPE_BOOLEAN)) {
gboolean result;
result = g_variant_get_boolean(value);
return printf("%s%s", result ? "true" : "false", suffix);
}
else if(g_variant_is_of_type(value, G_VARIANT_TYPE_ARRAY)) {
int count;
const gchar** items;
items = g_variant_get_strv(value, NULL);
for (count=0; items[count]; count++) {
printf("%s%s", count < 1 ? "" : ",", items[count]);
}
printf("%s", suffix);
return count;
}
else {
throw exception();
}
return 0;
}
static void on_value_change(GSettings *settings, const gchar *key, gpointer user_data) {
printf("%s/%s\t", (gchar *)user_data, key);
print_value(g_settings_get_value(settings, key), "\n");
}
static void on_sig(int /*signal*/) {
g_main_loop_quit(loop);
}
static gboolean err(GIOChannel* /*source*/, GIOCondition /*condition*/, gpointer /*data*/) {
g_main_loop_quit(loop);
return false;
}
static gboolean in(GIOChannel *source, GIOCondition condition, gpointer data) {
gchar *key, *val;
GIOStatus st = g_io_channel_read_line(source, &key, NULL, NULL, NULL);
// Remove the trailing '\n'
for (int i=0 ; key && key[i] ; i++)
if (key[i] == '\n')
key[i] = '\0';
// If we were successful
if (key && st == G_IO_STATUS_NORMAL) {
if (!g_strrstr(key, "\t"))
goto exit;
val = g_strrstr(key, "\t") + 1;
*(val-1) = '\0';
g_free(key);
return true;
}
else if (key && st == G_IO_STATUS_AGAIN) {
g_free(key);
return in(source, condition, data);
}
exit:
g_free(key);
return err(source, condition, data);
}
int main(int argc, char **argv) {
if (argc < 2) return 1;
// Register sighup handler
if (signal(SIGHUP, on_sig) == SIG_ERR || signal(SIGPIPE, on_sig) == SIG_ERR || signal(SIGABRT, on_sig) == SIG_ERR) {
fprintf(stderr, "Unable to trap signals!");
return 2;
}
// Switch stdout to line buffering
if (setvbuf(stdout, NULL, _IOLBF, 0)) {
fprintf(stderr, "Unable to switch stdout to line buffering!");
return 3;
}
// Switch stdin to line buffering
if (setvbuf(stdin, NULL, _IOLBF, 0)) {
fprintf(stderr, "Unable to switch stdin to line buffering!");
return 4;
}
// Init
g_type_init();
// Get the main loop
loop = g_main_loop_new(NULL, false);
// Setup our GIO Channels
GIOChannel* inchan = g_io_channel_unix_new(fileno(stdin));
GIOChannel* outchan = g_io_channel_unix_new(fileno(stdout));
g_io_add_watch(inchan, G_IO_IN, in, NULL);
g_io_add_watch(inchan, G_IO_PRI, in, NULL);
g_io_add_watch(inchan, G_IO_ERR, err, NULL);
g_io_add_watch(inchan, G_IO_HUP, err, NULL);
g_io_add_watch(outchan, G_IO_ERR, err, NULL);
g_io_add_watch(outchan, G_IO_HUP, err, NULL);
// Get GSettings obkecy
GSettings* settings;
for (int i=1; i<argc; i++) {
settings = g_settings_new(argv[i]);
gchar** keys = g_settings_list_keys(settings);
for (int j=0; keys[j]; on_value_change(settings, keys[j++],argv[i] ));
g_signal_connect(settings, "changed::", (GCallback) on_value_change, argv[i]);
}
g_main_loop_run(loop);
// Cleanup
while (G_IS_OBJECT(settings)) {
g_object_unref(settings);
}
g_io_channel_shutdown(inchan, FALSE, NULL);
g_io_channel_shutdown(outchan, FALSE, NULL);
g_io_channel_unref(inchan);
g_io_channel_unref(outchan);
g_main_loop_unref(loop);
}
<|endoftext|> |
<commit_before>/* CUDA global device memory vector
*
* Copyright (C) 2007 Peter Colberg
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CUDA_VECTOR_HPP
#define CUDA_VECTOR_HPP
#include <algorithm>
#include <cuda_wrapper/allocator.hpp>
#include <vector>
namespace cuda
{
/**
* CUDA global device memory vector
*/
template <typename T>
class vector : private std::vector<T, allocator<T> >
{
public:
typedef allocator<T> _Alloc;
typedef std::vector<T, allocator<T> > _Base;
typedef vector<T> vector_type;
typedef T value_type;
typedef size_t size_type;
public:
vector() : size_(0) {}
/**
* initialize device vector of given size
*/
vector(size_type size) : size_(size)
{
_Base::reserve(size_);
}
/**
* shallow copy constructor
*/
vector(vector_type const& v) : size_(v.size())
{
_Base::reserve(size_);
}
/**
* shallow assignment operator
*/
vector_type& operator=(vector_type const& v)
{
resize(v.size());
return *this;
}
/**
* returns element count of device vector
*/
size_type size() const
{
return size_;
}
/**
* resize element count of device vector
*/
void resize(size_type size)
{
// size of vector must always be kept at zero to prevent
// initialization of vector elements, so use vector::reserve
// in place of vector::resize
_Base::reserve(size);
size_ = size;
}
/**
* returns capacity
*/
size_type capacity() const
{
return _Base::capacity();
}
/**
* allocate enough memory for specified number of elements
*/
void reserve(size_type n)
{
_Base::reserve(std::max(size_, n));
}
/**
* returns device pointer to allocated device memory
*/
value_type* data()
{
return _Base::data();
}
/**
* returns device pointer to allocated device memory
*/
value_type const* data() const
{
return _Base::data();
}
private:
size_type size_;
};
} // namespace cuda
#endif /* CUDA_VECTOR_HPP */
<commit_msg>Add swap to CUDA vector and use deep copy constructor and assignment operator<commit_after>/* CUDA global device memory vector
*
* Copyright (C) 2007 Peter Colberg
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CUDA_VECTOR_HPP
#define CUDA_VECTOR_HPP
#include <algorithm>
#include <cuda_wrapper/allocator.hpp>
#include <cuda_wrapper/memory.hpp>
#include <vector>
namespace cuda
{
/**
* CUDA global device memory vector
*/
template <typename T>
class vector : private std::vector<T, allocator<T> >
{
public:
typedef allocator<T> _Alloc;
typedef std::vector<T, allocator<T> > _Base;
typedef vector<T> vector_type;
typedef T value_type;
typedef size_t size_type;
public:
vector() : size_(0) {}
/**
* initialize device vector of given size
*/
vector(size_type size) : size_(size)
{
_Base::reserve(size_);
}
/**
* deep copy constructor
*/
vector(vector_type const& v)
{
vector w(v.size());
copy(v, w);
swap(w);
}
/**
* deep assignment operator
*/
vector_type& operator=(vector_type const& v)
{
vector w(v.size());
copy(v, w);
swap(w);
return *this;
}
/**
* swap device memory with another vector
*/
void swap(vector_type& v)
{
std::swap(v.size_, size_);
_Base::swap(v);
}
/**
* returns element count of device vector
*/
size_type size() const
{
return size_;
}
/**
* resize element count of device vector
*/
void resize(size_type size)
{
// size of vector must always be kept at zero to prevent
// initialization of vector elements, so use vector::reserve
// in place of vector::resize
_Base::reserve(size);
size_ = size;
}
/**
* returns capacity
*/
size_type capacity() const
{
return _Base::capacity();
}
/**
* allocate enough memory for specified number of elements
*/
void reserve(size_type n)
{
_Base::reserve(std::max(size_, n));
}
/**
* returns device pointer to allocated device memory
*/
value_type* data()
{
return _Base::data();
}
/**
* returns device pointer to allocated device memory
*/
value_type const* data() const
{
return _Base::data();
}
private:
size_type size_;
};
} // namespace cuda
#endif /* CUDA_VECTOR_HPP */
<|endoftext|> |
<commit_before>//Sample provided by Thiago Massari Guedes
//August 2015
//http://www.simplycpp.com/
#include "example_main.h"
#include <iostream>
#include <map>
using namespace std;
struct Cash {
using Date = unsigned int;
Date date; //yyyymmdd
double value;
};
template<typename T>
struct CashRange {
using const_iterator = typename T::const_iterator;
CashRange(const_iterator begin, const_iterator end)
{
_begin = begin;
_end = end;
}
const const_iterator begin() const { return _begin; }
const const_iterator end() const { return _end; }
private:
const_iterator _begin;
const_iterator _end;
};
class CashFlow {
using CashMap = multimap<Cash::Date, Cash>;
using const_iterator = multimap<Cash::Date, Cash>::const_iterator;
multimap<Cash::Date, Cash> _flow;
public:
CashFlow()
{
int date = 20150000;
for(int m=1; m < 8; m+=2) {
for(int d=1; d <= 30; d += 6) {
int dt = date+(m*100)+d;
Cash c; c.date = dt; (c.value = m + d * 10.0) / (double)(d*10-m);
_flow.insert( make_pair(dt, c) );
}
}
}
auto getMonthlyFlow(int year, int month) -> CashRange<CashMap>
{
int kb = (year * 10000) + (month * 100) + 00;
int ke = (year * 10000) + (month * 100) + 31;
cout << kb << " - " << ke << endl;
const auto b = _flow.lower_bound(kb);
if( b == _flow.end() ) {
return CashRange<CashMap>(_flow.cend(), _flow.cend());
}
const auto e = _flow.upper_bound(ke);
return CashRange<CashMap>(b, e);
}
};
EXAMPLE_MAIN(range_for)
{
cout << "Getting data from 2015-03" << endl;
CashFlow flow;
for(auto &c : flow.getMonthlyFlow(2015, 03)) {
cout << c.second.date << ": " << c.second.value << endl;
}
return 0;
}
<commit_msg>Removed forgotten cout<commit_after>//Sample provided by Thiago Massari Guedes
//August 2015
//http://www.simplycpp.com/
#include "example_main.h"
#include <iostream>
#include <map>
using namespace std;
struct Cash {
using Date = unsigned int;
Date date; //yyyymmdd
double value;
};
template<typename T>
struct CashRange {
using const_iterator = typename T::const_iterator;
CashRange(const_iterator begin, const_iterator end)
{
_begin = begin;
_end = end;
}
const const_iterator begin() const { return _begin; }
const const_iterator end() const { return _end; }
private:
const_iterator _begin;
const_iterator _end;
};
class CashFlow {
using CashMap = multimap<Cash::Date, Cash>;
using const_iterator = multimap<Cash::Date, Cash>::const_iterator;
multimap<Cash::Date, Cash> _flow;
public:
CashFlow()
{
int date = 20150000;
for(int m=1; m < 8; m+=2) {
for(int d=1; d <= 30; d += 6) {
int dt = date+(m*100)+d;
Cash c; c.date = dt; (c.value = m + d * 10.0) / (double)(d*10-m);
_flow.insert( make_pair(dt, c) );
}
}
}
auto getMonthlyFlow(int year, int month) -> CashRange<CashMap>
{
int kb = (year * 10000) + (month * 100) + 00;
int ke = (year * 10000) + (month * 100) + 31;
const auto b = _flow.lower_bound(kb);
if( b == _flow.end() ) {
return CashRange<CashMap>(_flow.cend(), _flow.cend());
}
const auto e = _flow.upper_bound(ke);
return CashRange<CashMap>(b, e);
}
};
EXAMPLE_MAIN(range_for)
{
cout << "Getting data from 2015-03" << endl;
CashFlow flow;
for(auto &c : flow.getMonthlyFlow(2015, 03)) {
cout << c.second.date << ": " << c.second.value << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>//
// MCIMAPCapabilityOperation.cpp
// mailcore2
//
// Created by DINH Viêt Hoà on 3/4/13.
// Copyright (c) 2013 MailCore. All rights reserved.
//
#include "MCIMAPCapabilityOperation.h"
#include "MCIMAPSession.h"
#include "MCIMAPAsyncConnection.h"
using namespace mailcore;
IMAPCapabilityOperation::IMAPCapabilityOperation()
{
mCapabilities = NULL;
}
IMAPCapabilityOperation::~IMAPCapabilityOperation()
{
MC_SAFE_RELEASE(mCapabilities);
}
IndexSet * IMAPCapabilityOperation::capabilities()
{
return mCapabilities;
}
void IMAPCapabilityOperation::main()
{
ErrorCode error;
mCapabilities = session()->session()->capability(&error);
MC_SAFE_RETAIN(mCapabilities);
setError(error);
}
<commit_msg>Force capability operation to login()<commit_after>//
// MCIMAPCapabilityOperation.cpp
// mailcore2
//
// Created by DINH Viêt Hoà on 3/4/13.
// Copyright (c) 2013 MailCore. All rights reserved.
//
#include "MCIMAPCapabilityOperation.h"
#include "MCIMAPSession.h"
#include "MCIMAPAsyncConnection.h"
using namespace mailcore;
IMAPCapabilityOperation::IMAPCapabilityOperation()
{
mCapabilities = NULL;
}
IMAPCapabilityOperation::~IMAPCapabilityOperation()
{
MC_SAFE_RELEASE(mCapabilities);
}
IndexSet * IMAPCapabilityOperation::capabilities()
{
return mCapabilities;
}
void IMAPCapabilityOperation::main()
{
ErrorCode error;
session()->session()->loginIfNeeded(&error);
if (error != ErrorNone) {
setError(error);
return;
}
mCapabilities = session()->session()->capability(&error);
MC_SAFE_RETAIN(mCapabilities);
setError(error);
}
<|endoftext|> |
<commit_before>/**********************************************************************
* Copyright (c) 2014 Jason W. DeGraw
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#include <model/Model.hpp>
#include <osversion/VersionTranslator.hpp>
#include <utilities/core/CommandLine.hpp>
#include <utilities/core/Path.hpp>
#include <utilities/idf/IdfObject.hpp>
#include <model/ThermalZone.hpp>
#include <model/Surface.hpp>
#include <model/SubSurface.hpp>
#include <model/AirflowNetworkSimulationControl_Impl.hpp>
#include <energyplus/ForwardTranslator.hpp>
//#include <utilities/idd/AirflowNetwork_SimulationControl_FieldEnums.hxx>
#include <utilities/idd/AirflowNetwork_MultiZone_Surface_FieldEnums.hxx>
//#include <utilities/idd/IddEnums.hxx>
#include <string>
#include <iostream>
using namespace openstudio;
using namespace openstudio::model;
class AirflowNetworkBuilder : public openstudio::model::detail::SurfaceNetworkBuilder
{
public:
explicit AirflowNetworkBuilder(bool linkSubSurfaces=false);
std::vector<IdfObject> idfObjects();
protected:
virtual bool linkExteriorSurface(const ThermalZone &zone, const Space &space, const Surface &surface);
virtual bool linkExteriorSubSurface(const ThermalZone &zone, const Space &space, const Surface &surface, const SubSurface &subSurface);
virtual bool linkInteriorSurface(const ThermalZone &zone, const Space &space, const Surface &surface,
const Surface &adjacentSurface, const Space &adjacentSpace, const ThermalZone &adjacentZone);
virtual bool linkInteriorSubSurface(const ThermalZone &zone, const Space &space, const Surface &surface, const SubSurface &subSurface,
const SubSurface &adjacentSubSurface, const Surface &adjacentSurface, const Space &adjacentSpace, const ThermalZone &adjacentZone);
private:
bool linkSurface(const std::string &elementName, const Surface &surface, std::vector<IdfObject> &surfaces);
std::vector<IdfObject> m_idfObjects;
std::vector<IdfObject> m_airflowElements;
std::vector<IdfObject> m_interiorSurfaces;
std::vector<IdfObject> m_exteriorSurfaces;
bool m_includeSubSurfaces;
std::map<std::string,double> m_maxArea;
std::map<std::string,double> m_surfaceArea;
REGISTER_LOGGER("openstudio.model.detail.AirflowNetworkBuilder");
};
AirflowNetworkBuilder::AirflowNetworkBuilder(bool includeSubSurfaces) : SurfaceNetworkBuilder(nullptr),m_includeSubSurfaces(includeSubSurfaces)
{
}
std::vector<IdfObject> AirflowNetworkBuilder::idfObjects()
{
std::cout << "Maximum exterior area: " << m_maxArea["ExteriorComponent"] << std::endl;
std::cout << "Maximum interior area: " << m_maxArea["InteriorComponent"] << std::endl;
/*
double maxArea = m_maxArea["Exterior"];
if(m_maxArea["Interior"] > maxArea) {
maxArea = m_maxArea["Interior"];
}
*/
QStringList idfStrings;
idfStrings.clear();
idfStrings << "AirflowNetwork:MultiZone:ReferenceCrackConditions"
<< "ReferenceCrackConditions" // !- Name of Reference Crack Conditions
<< "20.0" // !- Reference Temperature for Crack Data {C}
<< "101325" // !- Reference Barometric Pressure for Crack Data {Pa}
<< "0.0"; // !- Reference Humidity Ratio for Crack Data {kgWater/kgDryAir}
m_airflowElements.push_back(openstudio::IdfObject::load((idfStrings.join(",")+";").toStdString()).get());
// This is the "two elements to rule them all" approach
// Generate exterior leakage element
idfStrings.clear();
idfStrings << "AirflowNetwork:MultiZone:Surface:Crack"
<< "ExteriorComponent" // !- Name of Surface Crack Component
<< QString().sprintf("%g",m_maxArea["ExteriorComponent"]*4.99082e-4) // !- Air Mass Flow Coefficient at Reference Conditions {kg/s}
<< "0.65" // !- Air Mass Flow Exponent {dimensionless}
<< "ReferenceCrackConditions"; // !- Reference Crack Conditions
m_airflowElements.push_back(openstudio::IdfObject::load((idfStrings.join(",")+";").toStdString()).get());
// Generate interior leakage element
idfStrings.clear();
idfStrings << "AirflowNetwork:MultiZone:Surface:Crack"
<< "InteriorComponent" // !- Name of Surface Crack Component
<< QString().sprintf("%g",m_maxArea["InteriorComponent"]*2.0*4.99082e-4) // !- Air Mass Flow Coefficient at Reference Conditions {kg/s}
<< "0.65" // !- Air Mass Flow Exponent {dimensionless}
<< "ReferenceCrackConditions"; // !- Reference Crack Conditions
m_airflowElements.push_back(openstudio::IdfObject::load((idfStrings.join(",")+";").toStdString()).get());
std::vector<IdfObject> objects = m_airflowElements;
/*
// Set the multipliers on all the elements appropriately
BOOST_FOREACH(IdfObject obj, m_exteriorSurfaces) {
boost::optional<std::string> optName = obj.getString(AirflowNetwork_MultiZone_SurfaceFields::SurfaceName,false);
if(optName) {
// boost::optional<double> optArea = obj.getDouble(AirflowNetwork_MultiZone_SurfaceFields::Window_DoorOpeningFactororCrackFactor,false);
if(obj.setDouble(AirflowNetwork_MultiZone_SurfaceFields::Window_DoorOpeningFactororCrackFactor,m_surfaceArea[optName.get()]/m_maxArea["ExteriorComponent"])) {
objects.push_back(obj);
}
}
}
BOOST_FOREACH(IdfObject obj, m_interiorSurfaces) {
}
*/
objects.insert(objects.end(), m_exteriorSurfaces.begin(), m_exteriorSurfaces.end());
objects.insert(objects.end(), m_interiorSurfaces.begin(), m_interiorSurfaces.end());
return objects;
}
bool AirflowNetworkBuilder::linkSurface(const std::string &elementName, const Surface &surface, std::vector<IdfObject> &surfaces)
{
QString idfFormat = QString("AirflowNetwork:MultiZone:Surface,%1,") + QString::fromStdString(elementName) + QString(",%2,%3;");
boost::optional<std::string> name = surface.name();
if(!name) {
LOG(Warn, "Surface '" << openstudio::toString(surface.handle()) << "' has no name, will not be present in airflow network.");
return false;
}
// Get the surface area, store the maximum
double surfaceArea = surface.grossArea();
if(m_includeSubSurfaces) {
surfaceArea = surface.netArea();
}
std::map<std::string,double>::iterator it = m_maxArea.find(elementName);
if(it == m_maxArea.end()) {
m_maxArea[elementName] = surfaceArea;
} else {
if(it->second < surfaceArea) {
it->second = surfaceArea;
}
}
m_surfaceArea[name.get()] = surfaceArea;
QString idfString = idfFormat.arg(openstudio::toQString(name.get())).arg("").arg(1);
boost::optional<IdfObject> obj = openstudio::IdfObject::load(idfString.toStdString());
if(!obj) {
LOG(Error, "Failed to generate AirflowNetwork surface for " << name.get());
return false;
}
surfaces.push_back(obj.get());
return true;
}
bool AirflowNetworkBuilder::linkExteriorSurface(const ThermalZone &zone, const Space &space, const Surface &surface)
{
return linkSurface("ExteriorComponent", surface, m_exteriorSurfaces);
}
bool AirflowNetworkBuilder::linkInteriorSurface(const ThermalZone &zone, const Space &space, const Surface &surface,
const Surface &adjacentSurface, const Space &adjacentSpace, const ThermalZone &adjacentZone)
{
return linkSurface("InteriorComponent", surface, m_interiorSurfaces);
}
bool AirflowNetworkBuilder::linkExteriorSubSurface(const ThermalZone &zone, const Space &space, const Surface &surface, const SubSurface &subSurface)
{
return true;
}
bool AirflowNetworkBuilder::linkInteriorSubSurface(const ThermalZone &zone, const Space &space, const Surface &surface, const SubSurface &subSurface,
const SubSurface &adjacentSubSurface, const Surface &adjacentSurface, const Space &adjacentSpace, const ThermalZone &adjacentZone)
{
return true;
}
void usage( boost::program_options::options_description desc)
{
std::cout << "Usage: addafnidf --inputPath=./path/to/input.osm" << std::endl;
std::cout << " or: addafnidf input.osm" << std::endl;
std::cout << desc << std::endl;
}
int main(int argc, char *argv[])
{
std::string inputPathString;
boost::program_options::options_description desc("Allowed options");
desc.add_options()
("help", "print help message")
("inputPath", boost::program_options::value<std::string>(&inputPathString), "path to OSM file");
boost::program_options::positional_options_description pos;
pos.add("inputPath", -1);
boost::program_options::variables_map vm;
// The following try/catch block is necessary to avoid uncaught
// exceptions when the program is executed with more than one
// "positional" argument - there's got to be a better way.
try {
boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(desc).positional(pos).run(),
vm);
boost::program_options::notify(vm);
}
catch(std::exception&) {
std::cerr << "Execution failed: check arguments and retry."<< std::endl << std::endl;
usage(desc);
return EXIT_FAILURE;
}
if (vm.count("help")) {
usage(desc);
return EXIT_SUCCESS;
}
if(!vm.count("inputPath")) {
std::cerr << "No input path given." << std::endl << std::endl;
usage(desc);
return EXIT_FAILURE;
}
openstudio::path inputPath = openstudio::toPath(inputPathString);
if(!boost::filesystem::exists(inputPath)) {
std::cerr << "Input path does not exist." << std::endl;
return EXIT_FAILURE;
}
openstudio::osversion::VersionTranslator vt;
boost::optional<openstudio::model::Model> model = vt.loadModel(inputPath);
if(!model) {
std::cerr << "Unable to load file '"<< inputPathString << "' as an OpenStudio model." << std::endl;
return EXIT_FAILURE;
}
// Get an E+ workspace
openstudio::energyplus::ForwardTranslator translator;
openstudio::Workspace workspace = translator.translateModel(model.get(),nullptr);
// Add AFN objects
AirflowNetworkBuilder builder;
builder.build(model.get());
std::vector<openstudio::IdfObject> idfObjects = builder.idfObjects();
if(!idfObjects.size()) {
std::cerr << "No AirflowNetwork objects were added to model, no IDF output written." << std::endl;
return EXIT_FAILURE;
}
std::cout << "Adding " << idfObjects.size() << " IDF objects to model." << std::endl;
std::vector<openstudio::WorkspaceObject> workObjects = workspace.addObjects(idfObjects);
if(workObjects.empty()) {
std::cerr << "Failed to add IDF objects to model, no IDF output written." << std::endl;
return EXIT_FAILURE;
}
openstudio::path outPath = inputPath.replace_extension(openstudio::toPath("idf").string());
if(!workspace.save(outPath,true)) {
std::cerr << "Failed to write IDF file." << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>Complete the AFN export<commit_after>/**********************************************************************
* Copyright (c) 2014 Jason W. DeGraw
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#include <model/Model.hpp>
#include <osversion/VersionTranslator.hpp>
#include <utilities/core/CommandLine.hpp>
#include <utilities/core/Path.hpp>
#include <utilities/idf/IdfObject.hpp>
#include <model/ThermalZone.hpp>
#include <model/ThermalZone_Impl.hpp>
#include <model/Surface.hpp>
#include <model/SubSurface.hpp>
#include <model/AirflowNetworkSimulationControl_Impl.hpp>
#include <energyplus/ForwardTranslator.hpp>
//#include <utilities/idd/AirflowNetwork_SimulationControl_FieldEnums.hxx>
#include <utilities/idd/AirflowNetwork_MultiZone_Surface_FieldEnums.hxx>
//#include <utilities/idd/IddEnums.hxx>
#include <string>
#include <iostream>
using namespace openstudio;
using namespace openstudio::model;
class AirflowNetworkBuilder : public openstudio::model::detail::SurfaceNetworkBuilder
{
public:
explicit AirflowNetworkBuilder(bool linkSubSurfaces=false);
std::vector<IdfObject> idfObjects();
virtual bool build(model::Model & model);
protected:
virtual bool linkExteriorSurface(const ThermalZone &zone, const Space &space, const Surface &surface);
virtual bool linkExteriorSubSurface(const ThermalZone &zone, const Space &space, const Surface &surface, const SubSurface &subSurface);
virtual bool linkInteriorSurface(const ThermalZone &zone, const Space &space, const Surface &surface,
const Surface &adjacentSurface, const Space &adjacentSpace, const ThermalZone &adjacentZone);
virtual bool linkInteriorSubSurface(const ThermalZone &zone, const Space &space, const Surface &surface, const SubSurface &subSurface,
const SubSurface &adjacentSubSurface, const Surface &adjacentSurface, const Space &adjacentSpace, const ThermalZone &adjacentZone);
private:
bool linkSurface(const std::string &elementName, const Surface &surface, std::vector<IdfObject> &surfaces);
//std::vector<IdfObject> m_idfObjects;
std::vector<IdfObject> m_airflowObjects;
std::vector<IdfObject> m_interiorSurfaces;
std::vector<IdfObject> m_exteriorSurfaces;
bool m_includeSubSurfaces;
std::map<std::string,double> m_maxArea;
std::map<std::string,double> m_surfaceArea;
REGISTER_LOGGER("openstudio.model.detail.AirflowNetworkBuilder");
};
AirflowNetworkBuilder::AirflowNetworkBuilder(bool includeSubSurfaces) : SurfaceNetworkBuilder(nullptr),m_includeSubSurfaces(includeSubSurfaces)
{
}
std::vector<IdfObject> AirflowNetworkBuilder::idfObjects()
{
std::cout << "Maximum exterior area: " << m_maxArea["ExteriorComponent"] << std::endl;
std::cout << "Maximum interior area: " << m_maxArea["InteriorComponent"] << std::endl;
/*
double maxArea = m_maxArea["Exterior"];
if(m_maxArea["Interior"] > maxArea) {
maxArea = m_maxArea["Interior"];
}
*/
QStringList idfStrings;
idfStrings.clear();
idfStrings << "AirflowNetwork:MultiZone:ReferenceCrackConditions"
<< "ReferenceCrackConditions" // !- Name of Reference Crack Conditions
<< "20.0" // !- Reference Temperature for Crack Data {C}
<< "101325" // !- Reference Barometric Pressure for Crack Data {Pa}
<< "0.0"; // !- Reference Humidity Ratio for Crack Data {kgWater/kgDryAir}
m_airflowObjects.push_back(openstudio::IdfObject::load((idfStrings.join(",")+";").toStdString()).get());
// This is the "two elements to rule them all" approach
// Generate exterior leakage element
idfStrings.clear();
idfStrings << "AirflowNetwork:MultiZone:Surface:Crack"
<< "ExteriorComponent" // !- Name of Surface Crack Component
<< QString().sprintf("%g",m_maxArea["ExteriorComponent"]*4.99082e-4) // !- Air Mass Flow Coefficient at Reference Conditions {kg/s}
<< "0.65" // !- Air Mass Flow Exponent {dimensionless}
<< "ReferenceCrackConditions"; // !- Reference Crack Conditions
m_airflowObjects.push_back(openstudio::IdfObject::load((idfStrings.join(",")+";").toStdString()).get());
// Generate interior leakage element
idfStrings.clear();
idfStrings << "AirflowNetwork:MultiZone:Surface:Crack"
<< "InteriorComponent" // !- Name of Surface Crack Component
<< QString().sprintf("%g",m_maxArea["InteriorComponent"]*2.0*4.99082e-4) // !- Air Mass Flow Coefficient at Reference Conditions {kg/s}
<< "0.65" // !- Air Mass Flow Exponent {dimensionless}
<< "ReferenceCrackConditions"; // !- Reference Crack Conditions
m_airflowObjects.push_back(openstudio::IdfObject::load((idfStrings.join(",")+";").toStdString()).get());
std::vector<IdfObject> objects = m_airflowObjects;
// Set the multipliers on all the elements appropriately
double maxArea = m_maxArea["ExteriorComponent"];
BOOST_FOREACH(IdfObject obj, m_exteriorSurfaces) {
boost::optional<std::string> optName = obj.getString(AirflowNetwork_MultiZone_SurfaceFields::SurfaceName,false);
if(optName && m_surfaceArea[optName.get()]) {
if(obj.setDouble(AirflowNetwork_MultiZone_SurfaceFields::Window_DoorOpeningFactororCrackFactor,m_surfaceArea[optName.get()]/maxArea)) {
objects.push_back(obj);
}
}
}
maxArea = m_maxArea["InteriorComponent"];
BOOST_FOREACH(IdfObject obj, m_interiorSurfaces) {
boost::optional<std::string> optName = obj.getString(AirflowNetwork_MultiZone_SurfaceFields::SurfaceName,false);
if(optName && m_surfaceArea[optName.get()]) {
if(obj.setDouble(AirflowNetwork_MultiZone_SurfaceFields::Window_DoorOpeningFactororCrackFactor,m_surfaceArea[optName.get()]/maxArea)) {
objects.push_back(obj);
}
}
}
objects.insert(objects.end(), m_exteriorSurfaces.begin(), m_exteriorSurfaces.end());
objects.insert(objects.end(), m_interiorSurfaces.begin(), m_interiorSurfaces.end());
return objects;
}
bool AirflowNetworkBuilder::build(model::Model & model)
{
QStringList idfStrings;
BOOST_FOREACH(openstudio::model::ThermalZone thermalZone, model.getConcreteModelObjects<openstudio::model::ThermalZone>()) {
boost::optional<std::string> name = thermalZone.name();
if(!name) {
LOG(Error, "Thermal zone '" << thermalZone.handle() << "' has no name, translation aborted");
return false;
}
idfStrings.clear();
idfStrings << "AirflowNetwork:Multizone:Zone"
<< openstudio::toQString(*name) // !- Name of Associated Thermal Zone
<< "NoVent" // !- Ventilation Control Mode
<< "" // !- Vent Temperature Schedule Name
<< "" // !- Limit Value on Multiplier for Modulating Venting Open Factor {dimensionless}
<< "" // !- Lower Value on Inside/Outside Temperature Difference for
// !- Modulating the Venting Open Factor {deltaC}
<< "" // !- Upper Value on Inside/Outside Temperature Difference for
// !- Modulating the Venting Open Factor {deltaC}
<< "" // !- Lower Value on Inside/Outside Enthalpy Difference for Modulating
// !- the Venting Open Factor {J/kg}
<< "" // !- Upper Value on Inside/Outside Enthalpy Difference for Modulating
// !- the Venting Open Factor {J/kg}
<< ""; // !- Venting Availability Schedule Name
m_airflowObjects.push_back(openstudio::IdfObject::load((idfStrings.join(",")+";").toStdString()).get());
}
return SurfaceNetworkBuilder::build(model);
}
bool AirflowNetworkBuilder::linkSurface(const std::string &elementName, const Surface &surface, std::vector<IdfObject> &surfaces)
{
QString idfFormat = QString("AirflowNetwork:MultiZone:Surface,%1,") + QString::fromStdString(elementName) + QString(",%2,%3;");
boost::optional<std::string> name = surface.name();
if(!name) {
LOG(Warn, "Surface '" << openstudio::toString(surface.handle()) << "' has no name, will not be present in airflow network.");
return false;
}
// Get the surface area, store the maximum
double surfaceArea = surface.grossArea();
if(m_includeSubSurfaces) {
surfaceArea = surface.netArea();
}
std::map<std::string,double>::iterator it = m_maxArea.find(elementName);
if(it == m_maxArea.end()) {
m_maxArea[elementName] = surfaceArea;
} else {
if(it->second < surfaceArea) {
it->second = surfaceArea;
}
}
m_surfaceArea[name.get()] = surfaceArea;
QString idfString = idfFormat.arg(openstudio::toQString(name.get())).arg("").arg(1);
boost::optional<IdfObject> obj = openstudio::IdfObject::load(idfString.toStdString());
if(!obj) {
LOG(Error, "Failed to generate AirflowNetwork surface for " << name.get());
return false;
}
surfaces.push_back(obj.get());
return true;
}
bool AirflowNetworkBuilder::linkExteriorSurface(const ThermalZone &zone, const Space &space, const Surface &surface)
{
return linkSurface("ExteriorComponent", surface, m_exteriorSurfaces);
}
bool AirflowNetworkBuilder::linkInteriorSurface(const ThermalZone &zone, const Space &space, const Surface &surface,
const Surface &adjacentSurface, const Space &adjacentSpace, const ThermalZone &adjacentZone)
{
return linkSurface("InteriorComponent", surface, m_interiorSurfaces);
}
bool AirflowNetworkBuilder::linkExteriorSubSurface(const ThermalZone &zone, const Space &space, const Surface &surface, const SubSurface &subSurface)
{
return true;
}
bool AirflowNetworkBuilder::linkInteriorSubSurface(const ThermalZone &zone, const Space &space, const Surface &surface, const SubSurface &subSurface,
const SubSurface &adjacentSubSurface, const Surface &adjacentSurface, const Space &adjacentSpace, const ThermalZone &adjacentZone)
{
return true;
}
void usage( boost::program_options::options_description desc)
{
std::cout << "Usage: addafnidf --inputPath=./path/to/input.osm" << std::endl;
std::cout << " or: addafnidf input.osm" << std::endl;
std::cout << desc << std::endl;
}
int main(int argc, char *argv[])
{
std::string inputPathString;
boost::program_options::options_description desc("Allowed options");
desc.add_options()
("help", "print help message")
("inputPath", boost::program_options::value<std::string>(&inputPathString), "path to OSM file");
boost::program_options::positional_options_description pos;
pos.add("inputPath", -1);
boost::program_options::variables_map vm;
// The following try/catch block is necessary to avoid uncaught
// exceptions when the program is executed with more than one
// "positional" argument - there's got to be a better way.
try {
boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(desc).positional(pos).run(),
vm);
boost::program_options::notify(vm);
}
catch(std::exception&) {
std::cerr << "Execution failed: check arguments and retry."<< std::endl << std::endl;
usage(desc);
return EXIT_FAILURE;
}
if (vm.count("help")) {
usage(desc);
return EXIT_SUCCESS;
}
if(!vm.count("inputPath")) {
std::cerr << "No input path given." << std::endl << std::endl;
usage(desc);
return EXIT_FAILURE;
}
openstudio::path inputPath = openstudio::toPath(inputPathString);
if(!boost::filesystem::exists(inputPath)) {
std::cerr << "Input path does not exist." << std::endl;
return EXIT_FAILURE;
}
openstudio::osversion::VersionTranslator vt;
boost::optional<openstudio::model::Model> model = vt.loadModel(inputPath);
if(!model) {
std::cerr << "Unable to load file '"<< inputPathString << "' as an OpenStudio model." << std::endl;
return EXIT_FAILURE;
}
// Get an E+ workspace
openstudio::energyplus::ForwardTranslator translator;
openstudio::Workspace workspace = translator.translateModel(model.get(),nullptr);
// Add AFN objects
AirflowNetworkBuilder builder;
builder.build(model.get());
std::vector<openstudio::IdfObject> idfObjects = builder.idfObjects();
if(!idfObjects.size()) {
std::cerr << "No AirflowNetwork objects were added to model, no IDF output written." << std::endl;
return EXIT_FAILURE;
}
std::cout << "Adding " << idfObjects.size() << " IDF objects to model." << std::endl;
std::vector<openstudio::WorkspaceObject> workObjects = workspace.addObjects(idfObjects);
if(workObjects.empty()) {
std::cerr << "Failed to add IDF objects to model, no IDF output written." << std::endl;
return EXIT_FAILURE;
}
openstudio::path outPath = inputPath.replace_extension(openstudio::toPath("idf").string());
if(!workspace.save(outPath,true)) {
std::cerr << "Failed to write IDF file." << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* Delegate helper pooling.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "Stock.hxx"
#include "stock/MapStock.hxx"
#include "stock/Class.hxx"
#include "stock/Item.hxx"
#include "async.hxx"
#include "failure.hxx"
#include "system/fd_util.h"
#include "system/sigutil.h"
#include "event/Event.hxx"
#include "event/Callback.hxx"
#include "spawn/exec.hxx"
#include "spawn/ChildOptions.hxx"
#include "gerrno.h"
#include "pool.hxx"
#include <daemon/log.h>
#include <assert.h>
#include <unistd.h>
#include <sched.h>
#include <sys/un.h>
#include <sys/socket.h>
struct DelegateArgs {
const char *helper;
const ChildOptions *options;
int fds[2];
sigset_t signals;
};
struct DelegateProcess final : PoolStockItem {
const char *const uri;
pid_t pid;
int fd = -1;
Event event;
explicit DelegateProcess(struct pool &_pool, CreateStockItem c,
const char *_uri)
:PoolStockItem(_pool, c), uri(_uri) {}
~DelegateProcess() override {
if (fd >= 0) {
event.Delete();
close(fd);
}
}
void EventCallback(int fd, short event);
/* virtual methods from class StockItem */
bool Borrow(gcc_unused void *ctx) override {
event.Delete();
return true;
}
bool Release(gcc_unused void *ctx) override {
static constexpr struct timeval tv = {
.tv_sec = 60,
.tv_usec = 0,
};
event.Add(tv);
return true;
}
};
/*
* libevent callback
*
*/
inline void
DelegateProcess::EventCallback(gcc_unused int _fd, short events)
{
assert(_fd == fd);
if ((events & EV_TIMEOUT) == 0) {
assert((events & EV_READ) != 0);
char buffer;
ssize_t nbytes = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT);
if (nbytes < 0)
daemon_log(2, "error on idle delegate process: %s\n",
strerror(errno));
else if (nbytes > 0)
daemon_log(2, "unexpected data from idle delegate process\n");
}
InvokeIdleDisconnect();
pool_commit();
}
/*
* clone() function
*
*/
static int
delegate_stock_fn(void *ctx)
{
auto *info = (DelegateArgs *)ctx;
install_default_signal_handlers();
leave_signal_section(&info->signals);
info->options->Apply(true);
dup2(info->fds[1], STDIN_FILENO);
close(info->fds[0]);
close(info->fds[1]);
Exec e;
info->options->jail.InsertWrapper(e, nullptr);
e.Append(info->helper);
e.DoExec();
}
/*
* stock class
*
*/
static void
delegate_stock_create(gcc_unused void *ctx,
struct pool &parent_pool, CreateStockItem c,
const char *uri, void *_info,
gcc_unused struct pool &caller_pool,
gcc_unused struct async_operation_ref &async_ref)
{
auto *const info = (DelegateArgs *)_info;
const auto *const options = info->options;
if (socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, info->fds) < 0) {
GError *error = new_error_errno_msg("socketpair() failed: %s");
c.InvokeCreateError(error);
return;
}
int clone_flags = SIGCHLD;
clone_flags = options->ns.GetCloneFlags(clone_flags);
/* avoid race condition due to libevent signal handler in child
process */
enter_signal_section(&info->signals);
char stack[8192];
long pid = clone(delegate_stock_fn, stack + sizeof(stack),
clone_flags, info);
if (pid < 0) {
GError *error = new_error_errno_msg("clone() failed");
leave_signal_section(&info->signals);
close(info->fds[0]);
close(info->fds[1]);
c.InvokeCreateError(error);
return;
}
leave_signal_section(&info->signals);
close(info->fds[1]);
auto &pool = *pool_new_linear(&parent_pool, "delegate_stock", 512);
auto *process = NewFromPool<DelegateProcess>(pool, pool, c, uri);
process->pid = pid;
process->fd = info->fds[0];
process->event.Set(process->fd, EV_READ|EV_TIMEOUT,
MakeEventCallback(DelegateProcess, EventCallback),
process);
process->InvokeCreateSuccess();
}
static constexpr StockClass delegate_stock_class = {
.create = delegate_stock_create,
};
/*
* interface
*
*/
StockMap *
delegate_stock_new(struct pool *pool)
{
return hstock_new(*pool, delegate_stock_class, nullptr, 0, 16);
}
void
delegate_stock_get(StockMap *delegate_stock, struct pool *pool,
const char *helper,
const ChildOptions &options,
StockGetHandler &handler,
struct async_operation_ref &async_ref)
{
const char *uri = helper;
char options_buffer[4096];
*options.MakeId(options_buffer) = 0;
if (*options_buffer != 0)
uri = p_strcat(pool, helper, "|", options_buffer, nullptr);
auto info = NewFromPool<DelegateArgs>(*pool);
info->helper = helper;
info->options = &options;
hstock_get(*delegate_stock, *pool, uri, info, handler, async_ref);
}
void
delegate_stock_put(StockMap *delegate_stock,
StockItem &item, bool destroy)
{
auto *process = (DelegateProcess *)&item;
hstock_put(*delegate_stock, process->uri, item, destroy);
}
int
delegate_stock_item_get(StockItem &item)
{
auto *process = (DelegateProcess *)&item;
return process->fd;
}
<commit_msg>delegate/Stock: use HeapStockItem<commit_after>/*
* Delegate helper pooling.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "Stock.hxx"
#include "stock/MapStock.hxx"
#include "stock/Class.hxx"
#include "stock/Item.hxx"
#include "async.hxx"
#include "failure.hxx"
#include "system/fd_util.h"
#include "system/sigutil.h"
#include "event/Event.hxx"
#include "event/Callback.hxx"
#include "spawn/exec.hxx"
#include "spawn/ChildOptions.hxx"
#include "gerrno.h"
#include "pool.hxx"
#include <daemon/log.h>
#include <assert.h>
#include <unistd.h>
#include <sched.h>
#include <sys/un.h>
#include <sys/socket.h>
struct DelegateArgs {
const char *helper;
const ChildOptions *options;
int fds[2];
sigset_t signals;
};
struct DelegateProcess final : HeapStockItem {
const char *const uri;
pid_t pid;
int fd = -1;
Event event;
explicit DelegateProcess(CreateStockItem c,
const char *_uri)
:HeapStockItem(c), uri(_uri) {}
~DelegateProcess() override {
if (fd >= 0) {
event.Delete();
close(fd);
}
}
void EventCallback(int fd, short event);
/* virtual methods from class StockItem */
bool Borrow(gcc_unused void *ctx) override {
event.Delete();
return true;
}
bool Release(gcc_unused void *ctx) override {
static constexpr struct timeval tv = {
.tv_sec = 60,
.tv_usec = 0,
};
event.Add(tv);
return true;
}
};
/*
* libevent callback
*
*/
inline void
DelegateProcess::EventCallback(gcc_unused int _fd, short events)
{
assert(_fd == fd);
if ((events & EV_TIMEOUT) == 0) {
assert((events & EV_READ) != 0);
char buffer;
ssize_t nbytes = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT);
if (nbytes < 0)
daemon_log(2, "error on idle delegate process: %s\n",
strerror(errno));
else if (nbytes > 0)
daemon_log(2, "unexpected data from idle delegate process\n");
}
InvokeIdleDisconnect();
pool_commit();
}
/*
* clone() function
*
*/
static int
delegate_stock_fn(void *ctx)
{
auto *info = (DelegateArgs *)ctx;
install_default_signal_handlers();
leave_signal_section(&info->signals);
info->options->Apply(true);
dup2(info->fds[1], STDIN_FILENO);
close(info->fds[0]);
close(info->fds[1]);
Exec e;
info->options->jail.InsertWrapper(e, nullptr);
e.Append(info->helper);
e.DoExec();
}
/*
* stock class
*
*/
static void
delegate_stock_create(gcc_unused void *ctx,
gcc_unused struct pool &parent_pool, CreateStockItem c,
const char *uri, void *_info,
gcc_unused struct pool &caller_pool,
gcc_unused struct async_operation_ref &async_ref)
{
auto *const info = (DelegateArgs *)_info;
const auto *const options = info->options;
if (socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, info->fds) < 0) {
GError *error = new_error_errno_msg("socketpair() failed: %s");
c.InvokeCreateError(error);
return;
}
int clone_flags = SIGCHLD;
clone_flags = options->ns.GetCloneFlags(clone_flags);
/* avoid race condition due to libevent signal handler in child
process */
enter_signal_section(&info->signals);
char stack[8192];
long pid = clone(delegate_stock_fn, stack + sizeof(stack),
clone_flags, info);
if (pid < 0) {
GError *error = new_error_errno_msg("clone() failed");
leave_signal_section(&info->signals);
close(info->fds[0]);
close(info->fds[1]);
c.InvokeCreateError(error);
return;
}
leave_signal_section(&info->signals);
close(info->fds[1]);
auto *process = new DelegateProcess(c, uri);
process->pid = pid;
process->fd = info->fds[0];
process->event.Set(process->fd, EV_READ|EV_TIMEOUT,
MakeEventCallback(DelegateProcess, EventCallback),
process);
process->InvokeCreateSuccess();
}
static constexpr StockClass delegate_stock_class = {
.create = delegate_stock_create,
};
/*
* interface
*
*/
StockMap *
delegate_stock_new(struct pool *pool)
{
return hstock_new(*pool, delegate_stock_class, nullptr, 0, 16);
}
void
delegate_stock_get(StockMap *delegate_stock, struct pool *pool,
const char *helper,
const ChildOptions &options,
StockGetHandler &handler,
struct async_operation_ref &async_ref)
{
const char *uri = helper;
char options_buffer[4096];
*options.MakeId(options_buffer) = 0;
if (*options_buffer != 0)
uri = p_strcat(pool, helper, "|", options_buffer, nullptr);
auto info = NewFromPool<DelegateArgs>(*pool);
info->helper = helper;
info->options = &options;
hstock_get(*delegate_stock, *pool, uri, info, handler, async_ref);
}
void
delegate_stock_put(StockMap *delegate_stock,
StockItem &item, bool destroy)
{
auto *process = (DelegateProcess *)&item;
hstock_put(*delegate_stock, process->uri, item, destroy);
}
int
delegate_stock_item_get(StockItem &item)
{
auto *process = (DelegateProcess *)&item;
return process->fd;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* 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: canvasfont.hxx,v $
* $Revision: 1.7 $
*
* 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.
*
************************************************************************/
#ifndef _VCLCANVAS_CANVASFONT_HXX
#define _VCLCANVAS_CANVASFONT_HXX
#include <comphelper/implementationreference.hxx>
#include <cppuhelper/compbase2.hxx>
#include <comphelper/broadcasthelper.hxx>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/geometry/Matrix2D.hpp>
#include <com/sun/star/rendering/FontRequest.hpp>
#include <com/sun/star/rendering/XCanvasFont.hpp>
#include <vcl/font.hxx>
#include <canvas/vclwrapper.hxx>
#include "spritecanvas.hxx"
#include "impltools.hxx"
#include <boost/utility.hpp>
/* Definition of CanvasFont class */
namespace vclcanvas
{
typedef ::cppu::WeakComponentImplHelper2< ::com::sun::star::rendering::XCanvasFont,
::com::sun::star::lang::XServiceInfo > CanvasFont_Base;
class CanvasFont : public ::comphelper::OBaseMutex,
public CanvasFont_Base,
private ::boost::noncopyable
{
public:
typedef ::comphelper::ImplementationReference<
CanvasFont,
::com::sun::star::rendering::XCanvasFont > Reference;
CanvasFont( const ::com::sun::star::rendering::FontRequest& fontRequest,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& extraFontProperties,
const ::com::sun::star::geometry::Matrix2D& rFontMatrix,
const DeviceRef& rDevice );
/// Dispose all internal references
virtual void SAL_CALL disposing();
// XCanvasFont
virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XTextLayout > SAL_CALL createTextLayout( const ::com::sun::star::rendering::StringContext& aText, sal_Int8 nDirection, sal_Int64 nRandomSeed ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::rendering::FontRequest SAL_CALL getFontRequest( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::rendering::FontMetrics SAL_CALL getFontMetrics( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< double > SAL_CALL getAvailableSizes( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > SAL_CALL getExtraFontProperties( ) throw (::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException );
::Font getVCLFont() const;
private:
::canvas::vcltools::VCLObject<Font> maFont;
::com::sun::star::rendering::FontRequest maFontRequest;
DeviceRef mpRefDevice;
};
}
#endif /* _VCLCANVAS_CANVASFONT_HXX */
<commit_msg>INTEGRATION: CWS canvas05 (1.6.112); FILE MERGED 2008/04/21 07:29:02 thb 1.6.112.2: RESYNC: (1.6-1.7); FILE MERGED 2007/12/20 22:18:59 thb 1.6.112.1: #i81092# #i78888# #i78925# #i79258# #i79437# #i84784# Large canvas rework, completing various areas such as color spaces, bitmap data access, true sprite and non-sprite implementations, and upstreaming the canvas parts of rodos emf+ rendering<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: canvasfont.hxx,v $
* $Revision: 1.8 $
*
* 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.
*
************************************************************************/
#ifndef _VCLCANVAS_CANVASFONT_HXX
#define _VCLCANVAS_CANVASFONT_HXX
#include <comphelper/implementationreference.hxx>
#include <cppuhelper/compbase2.hxx>
#include <comphelper/broadcasthelper.hxx>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/geometry/Matrix2D.hpp>
#include <com/sun/star/rendering/FontRequest.hpp>
#include <com/sun/star/rendering/XCanvasFont.hpp>
#include <com/sun/star/rendering/XGraphicDevice.hpp>
#include <vcl/font.hxx>
#include <canvas/vclwrapper.hxx>
#include "spritecanvas.hxx"
#include "impltools.hxx"
#include <boost/utility.hpp>
/* Definition of CanvasFont class */
namespace vclcanvas
{
typedef ::cppu::WeakComponentImplHelper2< ::com::sun::star::rendering::XCanvasFont,
::com::sun::star::lang::XServiceInfo > CanvasFont_Base;
class CanvasFont : public ::comphelper::OBaseMutex,
public CanvasFont_Base,
private ::boost::noncopyable
{
public:
typedef ::comphelper::ImplementationReference<
CanvasFont,
::com::sun::star::rendering::XCanvasFont > Reference;
CanvasFont( const ::com::sun::star::rendering::FontRequest& fontRequest,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& extraFontProperties,
const ::com::sun::star::geometry::Matrix2D& rFontMatrix,
::com::sun::star::rendering::XGraphicDevice& rDevice,
const OutDevProviderSharedPtr& rOutDevProvider );
/// Dispose all internal references
virtual void SAL_CALL disposing();
// XCanvasFont
virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XTextLayout > SAL_CALL createTextLayout( const ::com::sun::star::rendering::StringContext& aText, sal_Int8 nDirection, sal_Int64 nRandomSeed ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::rendering::FontRequest SAL_CALL getFontRequest( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::rendering::FontMetrics SAL_CALL getFontMetrics( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< double > SAL_CALL getAvailableSizes( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > SAL_CALL getExtraFontProperties( ) throw (::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException );
::Font getVCLFont() const;
private:
::canvas::vcltools::VCLObject<Font> maFont;
::com::sun::star::rendering::FontRequest maFontRequest;
::com::sun::star::uno::Reference< ::com::sun::star::rendering::XGraphicDevice> mpRefDevice;
OutDevProviderSharedPtr mpOutDevProvider;
};
}
#endif /* _VCLCANVAS_CANVASFONT_HXX */
<|endoftext|> |
<commit_before>/*$Id$
*
* This source file is a part of the Fresco Project.
* Copyright (C) 1999 Stefan Seefeld <stefan@berlin-consortium.org>
* Copyright (C) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
* Copyright (C) 2001 Bastian Blank <bastianb@gmx.de>
* Copyright (C) 2003 Tobias Hunger <tobias@fresco.org>
* http://www.fresco.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#include <Prague/IPC/ptybuf.hh>
#include <cerrno>
#include <sstream>
#include <iostream>
using namespace Prague;
#if defined(HAVE__GETPTY) || defined(HAVE_OPENPTY)
# undef HAVE_DEV_PTMX
#endif
#ifdef HAVE_PTY_H
# include <pty.h>
#endif
#if defined(HAVE_DEV_PTMX) && defined(HAVE_SYS_STROPTS_H)
# include <sys/stropts.h>
#endif
#if defined (HAVE_LIBUTIL_H)
# include <libutil.h>
#endif
#if defined (HAVE_OPENPTY) || defined (BSD4_4)
#elif defined (HAVE__GETPTY)
#elif defined (HAVE_DEV_PTMX)
#elif defined (HAVE_DEV_PTS_AND_PTC)
#else
# include <fcntl.h>
#endif
inline void throw_runtime_error(const std::string s) throw(std::runtime_error)
{
throw std::runtime_error(s + ": " + strerror(errno));
}
//inline char ctrl(char c) { return c & 0x1f;}
ptybuf::ptybuf() :
ipcbuf(std::ios::in | std::ios::out)
{ }
ptybuf::~ptybuf()
{
if (my_tty != -1)
close(my_tty);
}
std::streamsize ptybuf::sys_read(char *buf, std::streamsize len) throw(std::runtime_error)
{
std::streamsize rval = -1;
do
rval = ::read(fd(), buf, len);
while (rval == -1 && errno == EINTR);
if (rval == -1 && errno == EIO) return 0;
if (rval == -1 && errno != EAGAIN)
throw_runtime_error("ptybuf::read failed");
}
int ptybuf::openpty() throw (std::runtime_error)
{
if (fd() == -1)
setup();
return fd();
}
int ptybuf::opentty() throw (std::runtime_error)
{
if (my_tty == -1)
setup();
return my_tty;
}
void ptybuf::setup() throw (std::runtime_error)
{
int ttyfd;
int ptyfd;
std::cerr << "Trying to open PTY/TTY pair..." << std::endl;
#if defined(HAVE_OPENPTY) || defined(BSD4_4)
// openpty(3) exists in OSF/1 and some other os'es
std::cerr << " using openpty." << std::endl;
int i;
i = ::openpty(&ptyfd, &ttyfd, NULL, NULL, NULL);
if (i < 0) throw_runtime_error("Openpty failed");
fd(ptyfd);
my_tty = ttyfd;
my_ptydev = ttyname(ptyfd);
#elif defined(HAVE__GETPTY)
// _getpty(3) exists in SGI Irix 4.x, 5.x & 6.x -- it generates more
// pty's automagically when needed
std::cerr << " using _getpty." << std::endl;
char *name = _getpty(&ptyfd, O_RDWR, 0622, 0);
if (!name) throw_runtime_error("_getpty failed")
// Open the slave side.
ttyfd = open(name, O_RDWR | O_NOCTTY);
if (ttyfd < 0) throw_runtime_error("Failed to open");
fd(ptyfd);
my_tty = ttyfd;
ptydev = name;
#elif defined(HAVE_DEV_PTMX)
/*
* This code is used e.g. on Solaris 2.x. (Note that Solaris 2.3
* also has bsd-style ptys, but they simply do not work.)
*/
std::cerr << " using ptmx." << std::endl;
mysig_t old_signal;
char *name;
ptyfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
if (ptyfd < 0) throw_runtime_error("Failed to open /dev/ptmx");
old_signal = mysignal(SIGCHLD, SIG_DFL);
if (grantpt(ptyfd) < 0)
{
close(ptyfd);
throw_runtime_error("grantpt failed");
}
mysignal(SIGCHLD, old_signal);
if (unlockpt(ptyfd) < 0)
{
close(ptyfd);
throw_runtime_error("unlockpt failed");
}
// Open the slave side.
ttyfd = open(name, O_RDWR | O_NOCTTY);
if (ttyfd < 0) throw_runtime_error("Failed to open");
fd(ptyfd);
my_tty = ttyfd;
my_ptydev = std::string(name);
#elif defined(HAVE_DEV_PTS_AND_PTC)
/* AIX-style pty code. */
std::cerr << " using pts/ptc." << std::endl;
ptyfd = open("/dev/ptc", O_RDWR | O_NOCTTY);
if (ptyfd < 0) throw_runtime_error("Failed to open /dev/ptc");
char *name = ttyname(ptyfd);
ttyfd = open(name, O_RDWR | O_NOCTTY);
if (ttyfd < 0)
{
close(ptyfd);
throw_runtime_error("Failed to open "+name)
}
fd(ptyfd);
my_tty = ttyfd;
my_ptydev = name;
#else
/* BSD-style pty code. */
std::cerr << " using BSD-style." << std::endl;
std::stringstream buf1;
std::stringstream buf2;
const std::string ptymajors("pqrstuvwxyzabcdefghijklmnoABCDEFGHIJKLMNOPQRSTUVWXYZ");
const std::string ptyminors("0123456789abcdef");
int num_minors = ptyminors.length();
int num_ptys = ptymajors.length() * num_minors;
for (size_t i = 0; i < num_ptys; i++)
{
buf1.str("/dev/pty");
buf1 << ptymajors[i / num_minors] << ptyminors[i % num_minors];
buf2.str("/dev/tty");
buf2 << ptymajors[i / num_minors] << ptyminors[i % num_minors];
ptyfd = open(buf1.str().c_str(), O_RDWR | O_NOCTTY);
if (ptyfd < 0)
{
/* Try SCO style naming */
buf1.str("/dev/ptyp"); buf1 << i;
buf2.str("/dev/ttyp"); buf2 << i;
ptyfd = open(buf1.str().c_str(), O_RDWR | O_NOCTTY);
if (ptyfd < 0) continue;
}
break; // found a master, get out of here!
}
/* Open the slave side. */
ttyfd = open(buf2.str().c_str(), O_RDWR | O_NOCTTY);
if (ttyfd < 0)
{
close(ptyfd);
throw_runtime_error("Failed to open "+buf2.str());
}
fd(ptyfd);
my_tty = ttyfd;
my_ptydev = buf1.str();
#endif
std::cerr << "Got TTY/PTY pair." << std::endl;
}
<commit_msg>Include config.hh so that the defines we are using here are actually defined. This should close bug241.<commit_after>/*$Id$
*
* This source file is a part of the Fresco Project.
* Copyright (C) 1999 Stefan Seefeld <stefan@berlin-consortium.org>
* Copyright (C) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
* Copyright (C) 2001 Bastian Blank <bastianb@gmx.de>
* Copyright (C) 2003 Tobias Hunger <tobias@fresco.org>
* http://www.fresco.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#include <Prague/IPC/ptybuf.hh>
#include <Prague/config.hh>
#include <cerrno>
#include <sstream>
#include <iostream>
using namespace Prague;
#if defined(HAVE__GETPTY) || defined(HAVE_OPENPTY)
# undef HAVE_DEV_PTMX
#endif
#ifdef HAVE_PTY_H
# include <pty.h>
#endif
#if defined(HAVE_DEV_PTMX) && defined(HAVE_SYS_STROPTS_H)
# include <sys/stropts.h>
#endif
#if defined (HAVE_LIBUTIL_H)
# include <libutil.h>
#endif
#if defined (HAVE_OPENPTY) || defined (BSD4_4)
#elif defined (HAVE__GETPTY)
#elif defined (HAVE_DEV_PTMX)
#elif defined (HAVE_DEV_PTS_AND_PTC)
#else
# include <fcntl.h>
#endif
inline void throw_runtime_error(const std::string s) throw(std::runtime_error)
{
throw std::runtime_error(s + ": " + strerror(errno));
}
ptybuf::ptybuf() :
ipcbuf(std::ios::in | std::ios::out)
{ }
ptybuf::~ptybuf()
{
if (my_tty != -1) close(my_tty);
}
std::streamsize ptybuf::sys_read(char *buf, std::streamsize len) throw(std::runtime_error)
{
std::streamsize rval = -1;
do
rval = ::read(fd(), buf, len);
while (rval == -1 && errno == EINTR);
if (rval == -1 && errno == EIO) return 0;
if (rval == -1 && errno != EAGAIN)
throw_runtime_error("ptybuf::read failed");
}
int ptybuf::openpty() throw (std::runtime_error)
{
if (fd() == -1)
setup();
return fd();
}
int ptybuf::opentty() throw (std::runtime_error)
{
if (my_tty == -1)
setup();
return my_tty;
}
void ptybuf::setup() throw (std::runtime_error)
{
int ttyfd;
int ptyfd;
std::cerr << "Trying to open PTY/TTY pair..." << std::endl;
#if defined(HAVE_OPENPTY) || defined(BSD4_4)
// openpty(3) exists in OSF/1 and some other os'es
std::cerr << " using openpty." << std::endl;
int i;
i = ::openpty(&ptyfd, &ttyfd, NULL, NULL, NULL);
if (i < 0) throw_runtime_error("Openpty failed");
fd(ptyfd);
my_tty = ttyfd;
my_ptydev = ttyname(ptyfd);
#elif defined(HAVE__GETPTY)
// _getpty(3) exists in SGI Irix 4.x, 5.x & 6.x -- it generates more
// pty's automagically when needed
std::cerr << " using _getpty." << std::endl;
char *name = _getpty(&ptyfd, O_RDWR, 0622, 0);
if (!name) throw_runtime_error("_getpty failed")
// Open the slave side.
ttyfd = open(name, O_RDWR | O_NOCTTY);
if (ttyfd < 0) throw_runtime_error("Failed to open");
fd(ptyfd);
my_tty = ttyfd;
ptydev = name;
#elif defined(HAVE_DEV_PTMX)
/*
* This code is used e.g. on Solaris 2.x. (Note that Solaris 2.3
* also has bsd-style ptys, but they simply do not work.)
*/
std::cerr << " using ptmx." << std::endl;
mysig_t old_signal;
char *name;
ptyfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
if (ptyfd < 0) throw_runtime_error("Failed to open /dev/ptmx");
old_signal = mysignal(SIGCHLD, SIG_DFL);
if (grantpt(ptyfd) < 0)
{
close(ptyfd);
throw_runtime_error("grantpt failed");
}
mysignal(SIGCHLD, old_signal);
if (unlockpt(ptyfd) < 0)
{
close(ptyfd);
throw_runtime_error("unlockpt failed");
}
// Open the slave side.
ttyfd = open(name, O_RDWR | O_NOCTTY);
if (ttyfd < 0) throw_runtime_error("Failed to open");
fd(ptyfd);
my_tty = ttyfd;
my_ptydev = std::string(name);
#elif defined(HAVE_DEV_PTS_AND_PTC)
/* AIX-style pty code. */
std::cerr << " using pts/ptc." << std::endl;
ptyfd = open("/dev/ptc", O_RDWR | O_NOCTTY);
if (ptyfd < 0) throw_runtime_error("Failed to open /dev/ptc");
char *name = ttyname(ptyfd);
ttyfd = open(name, O_RDWR | O_NOCTTY);
if (ttyfd < 0)
{
close(ptyfd);
throw_runtime_error("Failed to open "+name)
}
fd(ptyfd);
my_tty = ttyfd;
my_ptydev = name;
#else
/* BSD-style pty code. */
std::cerr << " using BSD-style." << std::endl;
std::stringstream buf1;
std::stringstream buf2;
const std::string ptymajors("pqrstuvwxyzabcdefghijklmnoABCDEFGHIJKLMNOPQRSTUVWXYZ");
const std::string ptyminors("0123456789abcdef");
int num_minors = ptyminors.length();
int num_ptys = ptymajors.length() * num_minors;
for (size_t i = 0; i < num_ptys; i++)
{
buf1.str("/dev/pty");
buf1 << ptymajors[i / num_minors] << ptyminors[i % num_minors];
buf2.str("/dev/tty");
buf2 << ptymajors[i / num_minors] << ptyminors[i % num_minors];
ptyfd = open(buf1.str().c_str(), O_RDWR | O_NOCTTY);
if (ptyfd < 0)
{
/* Try SCO style naming */
buf1.str("/dev/ptyp"); buf1 << i;
buf2.str("/dev/ttyp"); buf2 << i;
ptyfd = open(buf1.str().c_str(), O_RDWR | O_NOCTTY);
if (ptyfd < 0) continue;
}
break; // found a master, get out of here!
}
/* Open the slave side. */
ttyfd = open(buf2.str().c_str(), O_RDWR | O_NOCTTY);
if (ttyfd < 0)
{
close(ptyfd);
throw_runtime_error("Failed to open "+buf2.str());
}
fd(ptyfd);
my_tty = ttyfd;
my_ptydev = buf1.str();
#endif
std::cerr << "Got TTY/PTY pair." << std::endl;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2009 Yahoo! Inc. All rights reserved. The copyrights
embodied in the content of this file are licensed under the BSD
(revised) open source license
*/
#include <stdio.h>
#include <float.h>
#include "cache.h"
#include "io.h"
#include "parse_regressor.h"
#include "parser.h"
#include "parse_args.h"
#include "sender.h"
#include "network.h"
#include "global_data.h"
const float default_decay = 1.;
po::variables_map parse_args(int argc, char *argv[], boost::program_options::options_description& desc,
gd_vars& vars,
regressor &r, parser* par,
string& final_regressor_name)
{
vars.init();
global.program_name = argv[0];
// Declare the supported options.
desc.add_options()
("active_simulation", "active learning simulation mode")
("active_mellowness", po::value<float>(&global.active_c0)->default_value(8.f), "active learning mellowness parameter c_0. Default 8")
("adaptive", "use adaptive, individual learning rates.")
("audit,a", "print weights of features")
("bit_precision,b", po::value<size_t>(),
"number of bits in the feature table")
("backprop", "turn on delayed backprop")
("cache,c", "Use a cache. The default is <data>.cache")
("cache_file", po::value< vector<string> >(), "The location(s) of cache_file.")
("compressed", "use gzip format whenever appropriate. If a cache file is being created, this option creates a compressed cache file. A mixture of raw-text & compressed inputs are supported if this option is on")
("corrective", "turn on corrective updates")
("data,d", po::value< string >()->default_value(""), "Example Set")
("daemon", "read data from port 39523")
("decay_learning_rate", po::value<float>(&global.eta_decay_rate)->default_value(default_decay),
"Set Decay factor for learning_rate between passes")
("final_regressor,f", po::value< string >(), "Final regressor")
("global_multiplier", po::value<float>(&global.global_multiplier)->default_value(1.0), "Global update multiplier")
("delayed_global", "Do delayed global updates")
("hash", po::value< string > (), "how to hash the features. Available options: strings, all")
("help,h","Output Arguments")
("version","Version information")
("initial_weight", po::value<float>(&global.initial_weight)->default_value(0.), "Set all weights to an initial value of 1.")
("initial_regressor,i", po::value< vector<string> >(), "Initial regressor(s)")
("initial_t", po::value<float>(&(par->t))->default_value(1.), "initial t value")
("min_prediction", po::value<double>(&global.min_label), "Smallest prediction to output")
("max_prediction", po::value<double>(&global.max_label), "Largest prediction to output")
("multisource", po::value<size_t>(), "multiple sources for daemon input")
("noop","do no learning")
("port", po::value<size_t>(),"port to listen on")
("power_t", po::value<float>(&vars.power_t)->default_value(0.5), "t power value")
("predictto", po::value< string > (), "host to send predictions to")
("learning_rate,l", po::value<float>(&global.eta)->default_value(10),
"Set Learning Rate")
("passes", po::value<size_t>(&global.numpasses)->default_value(1),
"Number of Training Passes")
("predictions,p", po::value< string >(), "File to output predictions to")
("quadratic,q", po::value< vector<string> > (),
"Create and use quadratic features")
("quiet", "Don't output diagnostics")
("raw_predictions,r", po::value< string >(),
"File to output unnormalized predictions to")
("sendto", po::value< vector<string> >(), "send example to <hosts>")
("testonly,t", "Ignore label information and just test")
("thread_bits", po::value<size_t>(&global.thread_bits)->default_value(0), "log_2 threads")
("loss_function", po::value<string>()->default_value("squared"), "Specify the loss function to be used, uses squared by default. Currently available ones are squared, hinge, logistic and quantile.")
("quantile_tau", po::value<double>()->default_value(0.5), "Parameter \\tau associated with Quantile loss. Defaults to 0.5")
("unique_id", po::value<size_t>(&global.unique_id)->default_value(0),"unique id used for cluster parallel")
("sort_features", "turn this on to disregard order in which features have been defined. This will lead to smaller cache sizes")
("ngram", po::value<size_t>(), "Generate N grams")
("skips", po::value<size_t>(), "Generate skips in N grams. This in conjunction with the ngram tag can be used to generate generalized n-skip-k-gram.");
global.queries = 0;
global.example_number = 0;
global.weighted_examples = 0.;
global.old_weighted_examples = 0.;
global.backprop = false;
global.corrective = false;
global.delayed_global = false;
global.weighted_labels = 0.;
global.total_features = 0;
global.sum_loss = 0.0;
global.sum_loss_since_last_dump = 0.0;
global.dump_interval = exp(1.);
global.num_bits = 18;
global.default_bits = true;
global.final_prediction_sink.begin = global.final_prediction_sink.end=global.final_prediction_sink.end_array = NULL;
global.raw_prediction = -1;
global.local_prediction = -1;
global.print = print_result;
global.min_label = 0.;
global.max_label = 1.;
global.adaptive = false;
global.audit = false;
global.active_simulation =false;
global.reg = &r;
po::positional_options_description p;
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).
options(desc).positional(p).run(), vm);
po::notify(vm);
global.partition_bits = global.thread_bits;
if (vm.count("help") || argc == 1) {
/* upon direct query for help -- spit it out to stdout */
cout << "\n" << desc << "\n";
exit(0);
}
if (vm.count("active_simulation"))
global.active_simulation = true;
if (vm.count("adaptive")) {
global.adaptive = true;
vars.power_t = 0.0;
}
if (vm.count("backprop")) {
global.backprop = true;
cout << "enabling backprop updates" << endl;
}
if (vm.count("corrective")) {
global.corrective = true;
cout << "enabling corrective updates" << endl;
}
if (vm.count("delayed_global")) {
global.delayed_global = true;
cout << "enabling delayed_global updates" << endl;
}
if (vm.count("version") || argc == 1) {
/* upon direct query for version -- spit it out to stdout */
cout << version << "\n";
exit(0);
}
if(vm.count("ngram")){
global.ngram = vm["ngram"].as<size_t>();
if(!vm.count("skip_gram")) cout << "You have chosen to generate " << global.ngram << "-grams" << endl;
}
if(vm.count("skips"))
{
global.skips = vm["skips"].as<size_t>();
if(!vm.count("ngram"))
{
cout << "You can not skip unless ngram is > 1" << endl;
exit(1);
}
cout << "You have chosen to generate " << global.skips << "-skip-" << global.ngram << "-grams" << endl;
if(global.skips > 4)
{
cout << "*********************************" << endl;
cout << "Generating these features might take quite some time" << endl;
cout << "*********************************" << endl;
}
}
if (vm.count("bit_precision"))
{
global.default_bits = false;
global.num_bits = vm["bit_precision"].as< size_t>();
}
if(vm.count("compressed")){
set_compressed(par);
}
if(vm.count("sort_features"))
par->sort_features = true;
if (global.num_bits > 30) {
cerr << "The system limits at 30 bits of precision!\n" << endl;
exit(1);
}
if (vm.count("quiet"))
global.quiet = true;
else
global.quiet = false;
if (vm.count("quadratic"))
{
global.pairs = vm["quadratic"].as< vector<string> >();
if (!global.quiet)
{
cerr << "creating quadratic features for pairs: ";
for (vector<string>::iterator i = global.pairs.begin(); i != global.pairs.end();i++) {
cerr << *i << " ";
if (i->length() > 2)
cerr << endl << "warning, ignoring characters after the 2nd.\n";
if (i->length() < 2) {
cerr << endl << "error, quadratic features must involve two sets.\n";
exit(0);
}
}
cerr << endl;
}
}
parse_regressor_args(vm, r, final_regressor_name, global.quiet);
if (vm.count("active_c0"))
global.active_c0 = vm["active_c0"].as<float>();
if (vm.count("min_prediction"))
global.min_label = vm["min_prediction"].as<double>();
if (vm.count("max_prediction"))
global.max_label = vm["max_prediction"].as<double>();
if (vm.count("min_prediction") || vm.count("max_prediction"))
set_minmax = noop_mm;
string loss_function;
if(vm.count("loss_function"))
loss_function = vm["loss_function"].as<string>();
else
loss_function = "squaredloss";
double loss_parameter = 0.0;
if(vm.count("quantile_tau"))
loss_parameter = vm["quantile_tau"].as<double>();
r.loss = getLossFunction(loss_function, loss_parameter);
global.loss = r.loss;
global.eta *= pow(par->t, vars.power_t);
if (global.eta_decay_rate != default_decay && global.numpasses == 1)
cerr << "Warning: decay_learning_rate has no effect when there is only one pass" << endl;
if (pow(global.eta_decay_rate, global.numpasses) < 0.0001 )
cerr << "Warning: the learning rate for the last pass is multiplied by: " << pow(global.eta_decay_rate, global.numpasses)
<< " adjust to --decay_learning_rate larger to avoid this." << endl;
parse_source_args(vm,par,global.quiet,global.numpasses);
if (!global.quiet)
{
cerr << "Num weight bits = " << global.num_bits << endl;
cerr << "learning rate = " << global.eta << endl;
cerr << "initial_t = " << par->t << endl;
cerr << "power_t = " << vars.power_t << endl;
if (global.numpasses > 1)
cerr << "decay_learning_rate = " << global.eta_decay_rate << endl;
}
if (vm.count("predictions")) {
if (!global.quiet)
cerr << "predictions = " << vm["predictions"].as< string >() << endl;
if (strcmp(vm["predictions"].as< string >().c_str(), "stdout") == 0)
{
int_pair pf = {1,0};
push(global.final_prediction_sink,pf);//stdout
}
else
{
const char* fstr = (vm["predictions"].as< string >().c_str());
int_pair pf = {fileno(fopen(fstr,"w")),0};
if (pf.fd < 0)
cerr << "Error opening the predictions file: " << fstr << endl;
push(global.final_prediction_sink,pf);
}
}
if (vm.count("raw_predictions")) {
if (!global.quiet)
cerr << "raw predictions = " << vm["raw_predictions"].as< string >() << endl;
if (strcmp(vm["raw_predictions"].as< string >().c_str(), "stdout") == 0)
global.raw_prediction = 1;//stdout
else
global.raw_prediction = fileno(fopen(vm["raw_predictions"].as< string >().c_str(), "w"));
}
if (vm.count("audit"))
global.audit = true;
parse_send_args(vm, global.pairs);
if (vm.count("testonly"))
{
if (!global.quiet)
cerr << "only testing" << endl;
global.training = false;
}
else
{
global.training = true;
if (!global.quiet)
cerr << "learning_rate set to " << global.eta << endl;
}
if (vm.count("predictto"))
{
if (!global.quiet)
cerr << "predictto = " << vm["predictto"].as< string >() << endl;
global.local_prediction = open_socket(vm["predictto"].as< string > ().c_str(), global.unique_id);
}
return vm;
}
<commit_msg>fixed nan label on testonly bug<commit_after>/*
Copyright (c) 2009 Yahoo! Inc. All rights reserved. The copyrights
embodied in the content of this file are licensed under the BSD
(revised) open source license
*/
#include <stdio.h>
#include <float.h>
#include "cache.h"
#include "io.h"
#include "parse_regressor.h"
#include "parser.h"
#include "parse_args.h"
#include "sender.h"
#include "network.h"
#include "global_data.h"
const float default_decay = 1.;
po::variables_map parse_args(int argc, char *argv[], boost::program_options::options_description& desc,
gd_vars& vars,
regressor &r, parser* par,
string& final_regressor_name)
{
vars.init();
global.program_name = argv[0];
// Declare the supported options.
desc.add_options()
("active_simulation", "active learning simulation mode")
("active_mellowness", po::value<float>(&global.active_c0)->default_value(8.f), "active learning mellowness parameter c_0. Default 8")
("adaptive", "use adaptive, individual learning rates.")
("audit,a", "print weights of features")
("bit_precision,b", po::value<size_t>(),
"number of bits in the feature table")
("backprop", "turn on delayed backprop")
("cache,c", "Use a cache. The default is <data>.cache")
("cache_file", po::value< vector<string> >(), "The location(s) of cache_file.")
("compressed", "use gzip format whenever appropriate. If a cache file is being created, this option creates a compressed cache file. A mixture of raw-text & compressed inputs are supported if this option is on")
("corrective", "turn on corrective updates")
("data,d", po::value< string >()->default_value(""), "Example Set")
("daemon", "read data from port 39523")
("decay_learning_rate", po::value<float>(&global.eta_decay_rate)->default_value(default_decay),
"Set Decay factor for learning_rate between passes")
("final_regressor,f", po::value< string >(), "Final regressor")
("global_multiplier", po::value<float>(&global.global_multiplier)->default_value(1.0), "Global update multiplier")
("delayed_global", "Do delayed global updates")
("hash", po::value< string > (), "how to hash the features. Available options: strings, all")
("help,h","Output Arguments")
("version","Version information")
("initial_weight", po::value<float>(&global.initial_weight)->default_value(0.), "Set all weights to an initial value of 1.")
("initial_regressor,i", po::value< vector<string> >(), "Initial regressor(s)")
("initial_t", po::value<float>(&(par->t))->default_value(1.), "initial t value")
("min_prediction", po::value<double>(&global.min_label), "Smallest prediction to output")
("max_prediction", po::value<double>(&global.max_label), "Largest prediction to output")
("multisource", po::value<size_t>(), "multiple sources for daemon input")
("noop","do no learning")
("port", po::value<size_t>(),"port to listen on")
("power_t", po::value<float>(&vars.power_t)->default_value(0.5), "t power value")
("predictto", po::value< string > (), "host to send predictions to")
("learning_rate,l", po::value<float>(&global.eta)->default_value(10),
"Set Learning Rate")
("passes", po::value<size_t>(&global.numpasses)->default_value(1),
"Number of Training Passes")
("predictions,p", po::value< string >(), "File to output predictions to")
("quadratic,q", po::value< vector<string> > (),
"Create and use quadratic features")
("quiet", "Don't output diagnostics")
("raw_predictions,r", po::value< string >(),
"File to output unnormalized predictions to")
("sendto", po::value< vector<string> >(), "send example to <hosts>")
("testonly,t", "Ignore label information and just test")
("thread_bits", po::value<size_t>(&global.thread_bits)->default_value(0), "log_2 threads")
("loss_function", po::value<string>()->default_value("squared"), "Specify the loss function to be used, uses squared by default. Currently available ones are squared, hinge, logistic and quantile.")
("quantile_tau", po::value<double>()->default_value(0.5), "Parameter \\tau associated with Quantile loss. Defaults to 0.5")
("unique_id", po::value<size_t>(&global.unique_id)->default_value(0),"unique id used for cluster parallel")
("sort_features", "turn this on to disregard order in which features have been defined. This will lead to smaller cache sizes")
("ngram", po::value<size_t>(), "Generate N grams")
("skips", po::value<size_t>(), "Generate skips in N grams. This in conjunction with the ngram tag can be used to generate generalized n-skip-k-gram.");
global.queries = 0;
global.example_number = 0;
global.weighted_examples = 0.;
global.old_weighted_examples = 0.;
global.backprop = false;
global.corrective = false;
global.delayed_global = false;
global.weighted_labels = 0.;
global.total_features = 0;
global.sum_loss = 0.0;
global.sum_loss_since_last_dump = 0.0;
global.dump_interval = exp(1.);
global.num_bits = 18;
global.default_bits = true;
global.final_prediction_sink.begin = global.final_prediction_sink.end=global.final_prediction_sink.end_array = NULL;
global.raw_prediction = -1;
global.local_prediction = -1;
global.print = print_result;
global.min_label = 0.;
global.max_label = 1.;
global.adaptive = false;
global.audit = false;
global.active_simulation =false;
global.reg = &r;
po::positional_options_description p;
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).
options(desc).positional(p).run(), vm);
po::notify(vm);
global.partition_bits = global.thread_bits;
if (vm.count("help") || argc == 1) {
/* upon direct query for help -- spit it out to stdout */
cout << "\n" << desc << "\n";
exit(0);
}
if (vm.count("active_simulation"))
global.active_simulation = true;
if (vm.count("adaptive")) {
global.adaptive = true;
vars.power_t = 0.0;
}
if (vm.count("backprop")) {
global.backprop = true;
cout << "enabling backprop updates" << endl;
}
if (vm.count("corrective")) {
global.corrective = true;
cout << "enabling corrective updates" << endl;
}
if (vm.count("delayed_global")) {
global.delayed_global = true;
cout << "enabling delayed_global updates" << endl;
}
if (vm.count("version") || argc == 1) {
/* upon direct query for version -- spit it out to stdout */
cout << version << "\n";
exit(0);
}
if(vm.count("ngram")){
global.ngram = vm["ngram"].as<size_t>();
if(!vm.count("skip_gram")) cout << "You have chosen to generate " << global.ngram << "-grams" << endl;
}
if(vm.count("skips"))
{
global.skips = vm["skips"].as<size_t>();
if(!vm.count("ngram"))
{
cout << "You can not skip unless ngram is > 1" << endl;
exit(1);
}
cout << "You have chosen to generate " << global.skips << "-skip-" << global.ngram << "-grams" << endl;
if(global.skips > 4)
{
cout << "*********************************" << endl;
cout << "Generating these features might take quite some time" << endl;
cout << "*********************************" << endl;
}
}
if (vm.count("bit_precision"))
{
global.default_bits = false;
global.num_bits = vm["bit_precision"].as< size_t>();
}
if(vm.count("compressed")){
set_compressed(par);
}
if(vm.count("sort_features"))
par->sort_features = true;
if (global.num_bits > 30) {
cerr << "The system limits at 30 bits of precision!\n" << endl;
exit(1);
}
if (vm.count("quiet"))
global.quiet = true;
else
global.quiet = false;
if (vm.count("quadratic"))
{
global.pairs = vm["quadratic"].as< vector<string> >();
if (!global.quiet)
{
cerr << "creating quadratic features for pairs: ";
for (vector<string>::iterator i = global.pairs.begin(); i != global.pairs.end();i++) {
cerr << *i << " ";
if (i->length() > 2)
cerr << endl << "warning, ignoring characters after the 2nd.\n";
if (i->length() < 2) {
cerr << endl << "error, quadratic features must involve two sets.\n";
exit(0);
}
}
cerr << endl;
}
}
parse_regressor_args(vm, r, final_regressor_name, global.quiet);
if (vm.count("active_c0"))
global.active_c0 = vm["active_c0"].as<float>();
if (vm.count("min_prediction"))
global.min_label = vm["min_prediction"].as<double>();
if (vm.count("max_prediction"))
global.max_label = vm["max_prediction"].as<double>();
if (vm.count("min_prediction") || vm.count("max_prediction") || vm.count("testonly"))
set_minmax = noop_mm;
string loss_function;
if(vm.count("loss_function"))
loss_function = vm["loss_function"].as<string>();
else
loss_function = "squaredloss";
double loss_parameter = 0.0;
if(vm.count("quantile_tau"))
loss_parameter = vm["quantile_tau"].as<double>();
r.loss = getLossFunction(loss_function, loss_parameter);
global.loss = r.loss;
global.eta *= pow(par->t, vars.power_t);
if (global.eta_decay_rate != default_decay && global.numpasses == 1)
cerr << "Warning: decay_learning_rate has no effect when there is only one pass" << endl;
if (pow(global.eta_decay_rate, global.numpasses) < 0.0001 )
cerr << "Warning: the learning rate for the last pass is multiplied by: " << pow(global.eta_decay_rate, global.numpasses)
<< " adjust to --decay_learning_rate larger to avoid this." << endl;
parse_source_args(vm,par,global.quiet,global.numpasses);
if (!global.quiet)
{
cerr << "Num weight bits = " << global.num_bits << endl;
cerr << "learning rate = " << global.eta << endl;
cerr << "initial_t = " << par->t << endl;
cerr << "power_t = " << vars.power_t << endl;
if (global.numpasses > 1)
cerr << "decay_learning_rate = " << global.eta_decay_rate << endl;
}
if (vm.count("predictions")) {
if (!global.quiet)
cerr << "predictions = " << vm["predictions"].as< string >() << endl;
if (strcmp(vm["predictions"].as< string >().c_str(), "stdout") == 0)
{
int_pair pf = {1,0};
push(global.final_prediction_sink,pf);//stdout
}
else
{
const char* fstr = (vm["predictions"].as< string >().c_str());
int_pair pf = {fileno(fopen(fstr,"w")),0};
if (pf.fd < 0)
cerr << "Error opening the predictions file: " << fstr << endl;
push(global.final_prediction_sink,pf);
}
}
if (vm.count("raw_predictions")) {
if (!global.quiet)
cerr << "raw predictions = " << vm["raw_predictions"].as< string >() << endl;
if (strcmp(vm["raw_predictions"].as< string >().c_str(), "stdout") == 0)
global.raw_prediction = 1;//stdout
else
global.raw_prediction = fileno(fopen(vm["raw_predictions"].as< string >().c_str(), "w"));
}
if (vm.count("audit"))
global.audit = true;
parse_send_args(vm, global.pairs);
if (vm.count("testonly"))
{
if (!global.quiet)
cerr << "only testing" << endl;
global.training = false;
}
else
{
global.training = true;
if (!global.quiet)
cerr << "learning_rate set to " << global.eta << endl;
}
if (vm.count("predictto"))
{
if (!global.quiet)
cerr << "predictto = " << vm["predictto"].as< string >() << endl;
global.local_prediction = open_socket(vm["predictto"].as< string > ().c_str(), global.unique_id);
}
return vm;
}
<|endoftext|> |
<commit_before>#include <BinaryTree.hpp>
#include <catch.hpp>
SCENARIO ("init", "[init]")
{
BinaryTree<int> obj;
REQUIRE(obj.root_() == nullptr);
}
SCENARIO ("output to cout", "<<")
{
BinaryTree<int> tree;
tree.insert_node(3);
REQUIRE( std::cout << tree );
}
SCENARIO("find_node", "[find_node]")
{
BinaryTree<int> obj;
obj.insert_node(4);
obj.insert_node(2);
REQUIRE(obj.find_node(2, obj.root_()) != nullptr);
REQUIRE(obj.find_node(2, obj.root_())->data == 2);
}
SCENARIO("insert", "[insert]")
{
BinaryTree<int> obj;
obj.insert_node(3);
REQUIRE(obj.find_node(3, obj.root_())->data == 3);
}
SCENARIO("removeElement", "[remEl]")
{
BinaryTree<int> obj;
obj.insert_node(1);
obj.insert_node(2);
obj.insert_node(3);
obj.remove_element(1);
REQUIRE(obj.find_node(1, obj.root_())== nullptr);
REQUIRE(obj.find_node(2, obj.root_())== obj.root_());
REQUIRE(obj.root_() != nullptr);
REQUIRE(obj.count() == 2);
}
SCENARIO("DEL", "[Del]")
{
BinaryTree<int> obj;
obj.insert_node(1);
obj.insert_node(2);
obj.remove_element(2);
REQUIRE(count == 1);
}
<commit_msg>Update init.cpp<commit_after>#include <BinaryTree.hpp>
#include <catch.hpp>
SCENARIO ("init", "[init]")
{
BinaryTree<int> obj;
REQUIRE(obj.root_() == nullptr);
}
SCENARIO ("output to cout", "<<")
{
BinaryTree<int> tree;
tree.insert_node(3);
REQUIRE( std::cout << tree );
}
SCENARIO("find_node", "[find_node]")
{
BinaryTree<int> obj;
obj.insert_node(4);
obj.insert_node(2);
REQUIRE(obj.find_node(2, obj.root_()) != nullptr);
REQUIRE(obj.find_node(2, obj.root_())->data == 2);
}
SCENARIO("insert", "[insert]")
{
BinaryTree<int> obj;
obj.insert_node(3);
REQUIRE(obj.find_node(3, obj.root_())->data == 3);
}
SCENARIO("removeElement", "[remEl]")
{
BinaryTree<int> obj;
obj.insert_node(1);
obj.insert_node(2);
obj.insert_node(3);
obj.remove_element(1);
REQUIRE(obj.find_node(1, obj.root_())== nullptr);
REQUIRE(obj.find_node(2, obj.root_())== obj.root_());
REQUIRE(obj.root_() != nullptr);
}
SCENARIO("DEL", "[Del]")
{
BinaryTree<int> obj;
obj.insert_node(1);
obj.insert_node(2);
obj.remove_element(2);
REQUIRE(obj.count() == 1);
}
<|endoftext|> |
<commit_before><commit_msg>Fix IBL in hellopbr.<commit_after><|endoftext|> |
<commit_before>// Copyright 2019 Google LLC
//
// 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 <fcntl.h>
#include <stddef.h>
#include <stdint.h>
#include <limits>
#include <string>
#include <tuple>
#include <vector>
#include "absl/base/optimization.h"
#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "absl/flags/usage.h"
#include "absl/status/status.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "google/protobuf/text_format.h"
#include "riegeli/base/base.h"
#include "riegeli/base/chain.h"
#include "riegeli/base/object.h"
#include "riegeli/bytes/chain_backward_writer.h"
#include "riegeli/bytes/chain_reader.h"
#include "riegeli/bytes/fd_reader.h"
#include "riegeli/bytes/limiting_reader.h"
#include "riegeli/bytes/message_parse.h"
#include "riegeli/bytes/message_serialize.h"
#include "riegeli/bytes/null_backward_writer.h"
#include "riegeli/bytes/reader_utils.h"
#include "riegeli/bytes/std_io.h"
#include "riegeli/bytes/varint_reading.h"
#include "riegeli/bytes/writer.h"
#include "riegeli/chunk_encoding/chunk.h"
#include "riegeli/chunk_encoding/constants.h"
#include "riegeli/chunk_encoding/decompressor.h"
#include "riegeli/chunk_encoding/field_projection.h"
#include "riegeli/chunk_encoding/transpose_decoder.h"
#include "riegeli/records/chunk_reader.h"
#include "riegeli/records/records_metadata.pb.h"
#include "riegeli/records/skipped_region.h"
#include "riegeli/records/tools/riegeli_summary.pb.h"
ABSL_FLAG(bool, show_records_metadata, true,
"If true, show parsed file metadata.");
ABSL_FLAG(bool, show_record_sizes, false,
"If true, show the list of record sizes in each chunk.");
namespace riegeli {
namespace tools {
namespace {
absl::Status DescribeFileMetadataChunk(const Chunk& chunk,
RecordsMetadata* records_metadata) {
// Based on `RecordReaderBase::ParseMetadata()`.
if (ABSL_PREDICT_FALSE(chunk.header.num_records() != 0)) {
return absl::DataLossError(absl::StrCat(
"Invalid file metadata chunk: number of records is not zero: ",
chunk.header.num_records()));
}
ChainReader<> data_reader(&chunk.data);
TransposeDecoder transpose_decoder;
ChainBackwardWriter<Chain> serialized_metadata_writer(
std::forward_as_tuple(), ChainBackwardWriterBase::Options().set_size_hint(
chunk.header.decoded_data_size()));
std::vector<size_t> limits;
const bool ok = transpose_decoder.Decode(
&data_reader, 1, chunk.header.decoded_data_size(), FieldProjection::All(),
&serialized_metadata_writer, &limits);
if (ABSL_PREDICT_FALSE(!serialized_metadata_writer.Close())) {
return serialized_metadata_writer.status();
}
if (ABSL_PREDICT_FALSE(!ok)) return transpose_decoder.status();
if (ABSL_PREDICT_FALSE(!data_reader.VerifyEndAndClose())) {
return data_reader.status();
}
const Chain& serialized_metadata = serialized_metadata_writer.dest();
RIEGELI_ASSERT_EQ(limits.size(), 1u)
<< "Metadata chunk has unexpected record limits";
RIEGELI_ASSERT_EQ(limits.back(), serialized_metadata.size())
<< "Metadata chunk has unexpected record limits";
return ParseFromChain(serialized_metadata, records_metadata);
}
absl::Status DescribeSimpleChunk(const Chunk& chunk,
summary::SimpleChunk* simple_chunk) {
// Based on `SimpleDecoder::Decode()`.
ChainReader<> chunk_reader(&chunk.data);
const absl::optional<uint8_t> compression_type_byte = ReadByte(&chunk_reader);
if (ABSL_PREDICT_FALSE(compression_type_byte == absl::nullopt)) {
return absl::DataLossError("Reading compression type failed");
}
const CompressionType compression_type =
static_cast<CompressionType>(*compression_type_byte);
simple_chunk->set_compression_type(
static_cast<summary::CompressionType>(compression_type));
if (absl::GetFlag(FLAGS_show_record_sizes)) {
const absl::optional<uint64_t> sizes_size = ReadVarint64(&chunk_reader);
if (ABSL_PREDICT_FALSE(sizes_size == absl::nullopt)) {
return absl::DataLossError("Reading size of sizes failed");
}
if (ABSL_PREDICT_FALSE(*sizes_size > std::numeric_limits<Position>::max() -
chunk_reader.pos())) {
return absl::ResourceExhaustedError("Size of sizes too large");
}
internal::Decompressor<LimitingReader<>> sizes_decompressor(
std::forward_as_tuple(&chunk_reader, chunk_reader.pos() + *sizes_size),
compression_type);
if (ABSL_PREDICT_FALSE(!sizes_decompressor.healthy())) {
return sizes_decompressor.status();
}
while (IntCast<size_t>(simple_chunk->record_sizes_size()) <
chunk.header.num_records()) {
const absl::optional<uint64_t> size =
ReadVarint64(sizes_decompressor.reader());
if (ABSL_PREDICT_FALSE(size == absl::nullopt)) {
return !sizes_decompressor.reader()->healthy()
? sizes_decompressor.reader()->status()
: absl::DataLossError("Reading record size failed");
}
simple_chunk->add_record_sizes(*size);
}
if (ABSL_PREDICT_FALSE(!sizes_decompressor.VerifyEndAndClose())) {
return sizes_decompressor.status();
}
}
return absl::OkStatus();
}
absl::Status DescribeTransposedChunk(
const Chunk& chunk, summary::TransposedChunk* transposed_chunk) {
ChainReader<> chunk_reader(&chunk.data);
if (absl::GetFlag(FLAGS_show_record_sizes)) {
// Based on `ChunkDecoder::Parse()`.
TransposeDecoder transpose_decoder;
NullBackwardWriter dest_writer(NullBackwardWriter::kInitiallyOpen);
std::vector<size_t> limits;
const bool ok =
transpose_decoder.Decode(&chunk_reader, chunk.header.num_records(),
chunk.header.decoded_data_size(),
FieldProjection::All(), &dest_writer, &limits);
if (ABSL_PREDICT_FALSE(!dest_writer.Close())) return dest_writer.status();
if (ABSL_PREDICT_FALSE(!ok)) return transpose_decoder.status();
if (ABSL_PREDICT_FALSE(!chunk_reader.VerifyEndAndClose())) {
return chunk_reader.status();
}
size_t prev_limit = 0;
for (const size_t next_limit : limits) {
RIEGELI_ASSERT_LE(prev_limit, next_limit)
<< "Failed postcondition of TransposeDecoder: "
"record end positions not sorted";
transposed_chunk->add_record_sizes(next_limit - prev_limit);
prev_limit = next_limit;
}
} else {
// Based on `TransposeDecoder::Decode()`.
const absl::optional<uint8_t> compression_type_byte =
ReadByte(&chunk_reader);
if (ABSL_PREDICT_FALSE(compression_type_byte == absl::nullopt)) {
return absl::DataLossError("Reading compression type failed");
}
transposed_chunk->set_compression_type(
static_cast<summary::CompressionType>(*compression_type_byte));
}
return absl::OkStatus();
}
void DescribeFile(absl::string_view filename, Writer* report) {
absl::Format(report,
"file {\n"
" filename: \"%s\"\n",
absl::Utf8SafeCEscape(filename));
DefaultChunkReader<FdReader<>> chunk_reader(
std::forward_as_tuple(filename, O_RDONLY));
const absl::optional<Position> size = chunk_reader.Size();
if (size != absl::nullopt) {
absl::Format(report, " file_size: %u\n", *size);
}
google::protobuf::TextFormat::Printer printer;
printer.SetInitialIndentLevel(2);
printer.SetUseShortRepeatedPrimitives(true);
printer.SetUseUtf8StringEscaping(true);
for (;;) {
report->Flush(FlushType::kFromProcess);
const Position chunk_begin = chunk_reader.pos();
Chunk chunk;
if (ABSL_PREDICT_FALSE(!chunk_reader.ReadChunk(&chunk))) {
SkippedRegion skipped_region;
if (chunk_reader.Recover(&skipped_region)) {
absl::Format(StdErr(), "%s\n", skipped_region.message());
continue;
}
break;
}
summary::Chunk chunk_summary;
chunk_summary.set_chunk_begin(chunk_begin);
chunk_summary.set_chunk_type(
static_cast<summary::ChunkType>(chunk.header.chunk_type()));
chunk_summary.set_data_size(chunk.header.data_size());
chunk_summary.set_num_records(chunk.header.num_records());
chunk_summary.set_decoded_data_size(chunk.header.decoded_data_size());
{
absl::Status status;
switch (chunk.header.chunk_type()) {
case ChunkType::kFileMetadata:
if (absl::GetFlag(FLAGS_show_records_metadata)) {
status = DescribeFileMetadataChunk(
chunk, chunk_summary.mutable_file_metadata_chunk());
}
break;
case ChunkType::kSimple:
status =
DescribeSimpleChunk(chunk, chunk_summary.mutable_simple_chunk());
break;
case ChunkType::kTransposed:
status = DescribeTransposedChunk(
chunk, chunk_summary.mutable_transposed_chunk());
break;
default:
break;
}
if (ABSL_PREDICT_FALSE(!status.ok())) {
absl::Format(StdErr(), "%s\n", status.message());
}
}
absl::Format(report, " chunk {\n");
WriterOutputStream proto_out(report);
printer.Print(chunk_summary, &proto_out);
absl::Format(report, " }\n");
}
absl::Format(report, "}\n");
if (!chunk_reader.Close()) {
absl::Format(StdErr(), "%s\n", chunk_reader.status().message());
}
}
const char kUsage[] =
"Usage: describe_riegeli_file (OPTION|FILE)...\n"
"\n"
"Shows summary of Riegeli/records file contents.\n";
} // namespace
} // namespace tools
} // namespace riegeli
int main(int argc, char** argv) {
absl::SetProgramUsageMessage(riegeli::tools::kUsage);
const std::vector<char*> args = absl::ParseCommandLine(argc, argv);
for (size_t i = 1; i < args.size(); ++i) {
riegeli::tools::DescribeFile(args[i], riegeli::StdOut());
}
}
<commit_msg>If reading encounters an unexpected end of data, inject a failure into the `Reader` instead of checking `healthy()`.<commit_after>// Copyright 2019 Google LLC
//
// 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 <fcntl.h>
#include <stddef.h>
#include <stdint.h>
#include <limits>
#include <string>
#include <tuple>
#include <vector>
#include "absl/base/optimization.h"
#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "absl/flags/usage.h"
#include "absl/status/status.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "google/protobuf/text_format.h"
#include "riegeli/base/base.h"
#include "riegeli/base/chain.h"
#include "riegeli/base/object.h"
#include "riegeli/bytes/chain_backward_writer.h"
#include "riegeli/bytes/chain_reader.h"
#include "riegeli/bytes/fd_reader.h"
#include "riegeli/bytes/limiting_reader.h"
#include "riegeli/bytes/message_parse.h"
#include "riegeli/bytes/message_serialize.h"
#include "riegeli/bytes/null_backward_writer.h"
#include "riegeli/bytes/reader_utils.h"
#include "riegeli/bytes/std_io.h"
#include "riegeli/bytes/varint_reading.h"
#include "riegeli/bytes/writer.h"
#include "riegeli/chunk_encoding/chunk.h"
#include "riegeli/chunk_encoding/constants.h"
#include "riegeli/chunk_encoding/decompressor.h"
#include "riegeli/chunk_encoding/field_projection.h"
#include "riegeli/chunk_encoding/transpose_decoder.h"
#include "riegeli/records/chunk_reader.h"
#include "riegeli/records/records_metadata.pb.h"
#include "riegeli/records/skipped_region.h"
#include "riegeli/records/tools/riegeli_summary.pb.h"
ABSL_FLAG(bool, show_records_metadata, true,
"If true, show parsed file metadata.");
ABSL_FLAG(bool, show_record_sizes, false,
"If true, show the list of record sizes in each chunk.");
namespace riegeli {
namespace tools {
namespace {
absl::Status DescribeFileMetadataChunk(const Chunk& chunk,
RecordsMetadata* records_metadata) {
// Based on `RecordReaderBase::ParseMetadata()`.
if (ABSL_PREDICT_FALSE(chunk.header.num_records() != 0)) {
return absl::DataLossError(absl::StrCat(
"Invalid file metadata chunk: number of records is not zero: ",
chunk.header.num_records()));
}
ChainReader<> data_reader(&chunk.data);
TransposeDecoder transpose_decoder;
ChainBackwardWriter<Chain> serialized_metadata_writer(
std::forward_as_tuple(), ChainBackwardWriterBase::Options().set_size_hint(
chunk.header.decoded_data_size()));
std::vector<size_t> limits;
const bool ok = transpose_decoder.Decode(
&data_reader, 1, chunk.header.decoded_data_size(), FieldProjection::All(),
&serialized_metadata_writer, &limits);
if (ABSL_PREDICT_FALSE(!serialized_metadata_writer.Close())) {
return serialized_metadata_writer.status();
}
if (ABSL_PREDICT_FALSE(!ok)) return transpose_decoder.status();
if (ABSL_PREDICT_FALSE(!data_reader.VerifyEndAndClose())) {
return data_reader.status();
}
const Chain& serialized_metadata = serialized_metadata_writer.dest();
RIEGELI_ASSERT_EQ(limits.size(), 1u)
<< "Metadata chunk has unexpected record limits";
RIEGELI_ASSERT_EQ(limits.back(), serialized_metadata.size())
<< "Metadata chunk has unexpected record limits";
return ParseFromChain(serialized_metadata, records_metadata);
}
absl::Status DescribeSimpleChunk(const Chunk& chunk,
summary::SimpleChunk* simple_chunk) {
// Based on `SimpleDecoder::Decode()`.
ChainReader<> chunk_reader(&chunk.data);
const absl::optional<uint8_t> compression_type_byte = ReadByte(&chunk_reader);
if (ABSL_PREDICT_FALSE(compression_type_byte == absl::nullopt)) {
return absl::DataLossError("Reading compression type failed");
}
const CompressionType compression_type =
static_cast<CompressionType>(*compression_type_byte);
simple_chunk->set_compression_type(
static_cast<summary::CompressionType>(compression_type));
if (absl::GetFlag(FLAGS_show_record_sizes)) {
const absl::optional<uint64_t> sizes_size = ReadVarint64(&chunk_reader);
if (ABSL_PREDICT_FALSE(sizes_size == absl::nullopt)) {
return absl::DataLossError("Reading size of sizes failed");
}
if (ABSL_PREDICT_FALSE(*sizes_size > std::numeric_limits<Position>::max() -
chunk_reader.pos())) {
return absl::ResourceExhaustedError("Size of sizes too large");
}
internal::Decompressor<LimitingReader<>> sizes_decompressor(
std::forward_as_tuple(&chunk_reader, chunk_reader.pos() + *sizes_size),
compression_type);
if (ABSL_PREDICT_FALSE(!sizes_decompressor.healthy())) {
return sizes_decompressor.status();
}
while (IntCast<size_t>(simple_chunk->record_sizes_size()) <
chunk.header.num_records()) {
const absl::optional<uint64_t> size =
ReadVarint64(sizes_decompressor.reader());
if (ABSL_PREDICT_FALSE(size == absl::nullopt)) {
sizes_decompressor.reader()->Fail(
absl::DataLossError("Reading record size failed"));
return sizes_decompressor.reader()->status();
}
simple_chunk->add_record_sizes(*size);
}
if (ABSL_PREDICT_FALSE(!sizes_decompressor.VerifyEndAndClose())) {
return sizes_decompressor.status();
}
}
return absl::OkStatus();
}
absl::Status DescribeTransposedChunk(
const Chunk& chunk, summary::TransposedChunk* transposed_chunk) {
ChainReader<> chunk_reader(&chunk.data);
if (absl::GetFlag(FLAGS_show_record_sizes)) {
// Based on `ChunkDecoder::Parse()`.
TransposeDecoder transpose_decoder;
NullBackwardWriter dest_writer(NullBackwardWriter::kInitiallyOpen);
std::vector<size_t> limits;
const bool ok =
transpose_decoder.Decode(&chunk_reader, chunk.header.num_records(),
chunk.header.decoded_data_size(),
FieldProjection::All(), &dest_writer, &limits);
if (ABSL_PREDICT_FALSE(!dest_writer.Close())) return dest_writer.status();
if (ABSL_PREDICT_FALSE(!ok)) return transpose_decoder.status();
if (ABSL_PREDICT_FALSE(!chunk_reader.VerifyEndAndClose())) {
return chunk_reader.status();
}
size_t prev_limit = 0;
for (const size_t next_limit : limits) {
RIEGELI_ASSERT_LE(prev_limit, next_limit)
<< "Failed postcondition of TransposeDecoder: "
"record end positions not sorted";
transposed_chunk->add_record_sizes(next_limit - prev_limit);
prev_limit = next_limit;
}
} else {
// Based on `TransposeDecoder::Decode()`.
const absl::optional<uint8_t> compression_type_byte =
ReadByte(&chunk_reader);
if (ABSL_PREDICT_FALSE(compression_type_byte == absl::nullopt)) {
return absl::DataLossError("Reading compression type failed");
}
transposed_chunk->set_compression_type(
static_cast<summary::CompressionType>(*compression_type_byte));
}
return absl::OkStatus();
}
void DescribeFile(absl::string_view filename, Writer* report) {
absl::Format(report,
"file {\n"
" filename: \"%s\"\n",
absl::Utf8SafeCEscape(filename));
DefaultChunkReader<FdReader<>> chunk_reader(
std::forward_as_tuple(filename, O_RDONLY));
const absl::optional<Position> size = chunk_reader.Size();
if (size != absl::nullopt) {
absl::Format(report, " file_size: %u\n", *size);
}
google::protobuf::TextFormat::Printer printer;
printer.SetInitialIndentLevel(2);
printer.SetUseShortRepeatedPrimitives(true);
printer.SetUseUtf8StringEscaping(true);
for (;;) {
report->Flush(FlushType::kFromProcess);
const Position chunk_begin = chunk_reader.pos();
Chunk chunk;
if (ABSL_PREDICT_FALSE(!chunk_reader.ReadChunk(&chunk))) {
SkippedRegion skipped_region;
if (chunk_reader.Recover(&skipped_region)) {
absl::Format(StdErr(), "%s\n", skipped_region.message());
continue;
}
break;
}
summary::Chunk chunk_summary;
chunk_summary.set_chunk_begin(chunk_begin);
chunk_summary.set_chunk_type(
static_cast<summary::ChunkType>(chunk.header.chunk_type()));
chunk_summary.set_data_size(chunk.header.data_size());
chunk_summary.set_num_records(chunk.header.num_records());
chunk_summary.set_decoded_data_size(chunk.header.decoded_data_size());
{
absl::Status status;
switch (chunk.header.chunk_type()) {
case ChunkType::kFileMetadata:
if (absl::GetFlag(FLAGS_show_records_metadata)) {
status = DescribeFileMetadataChunk(
chunk, chunk_summary.mutable_file_metadata_chunk());
}
break;
case ChunkType::kSimple:
status =
DescribeSimpleChunk(chunk, chunk_summary.mutable_simple_chunk());
break;
case ChunkType::kTransposed:
status = DescribeTransposedChunk(
chunk, chunk_summary.mutable_transposed_chunk());
break;
default:
break;
}
if (ABSL_PREDICT_FALSE(!status.ok())) {
absl::Format(StdErr(), "%s\n", status.message());
}
}
absl::Format(report, " chunk {\n");
WriterOutputStream proto_out(report);
printer.Print(chunk_summary, &proto_out);
absl::Format(report, " }\n");
}
absl::Format(report, "}\n");
if (!chunk_reader.Close()) {
absl::Format(StdErr(), "%s\n", chunk_reader.status().message());
}
}
const char kUsage[] =
"Usage: describe_riegeli_file (OPTION|FILE)...\n"
"\n"
"Shows summary of Riegeli/records file contents.\n";
} // namespace
} // namespace tools
} // namespace riegeli
int main(int argc, char** argv) {
absl::SetProgramUsageMessage(riegeli::tools::kUsage);
const std::vector<char*> args = absl::ParseCommandLine(argc, argv);
for (size_t i = 1; i < args.size(); ++i) {
riegeli::tools::DescribeFile(args[i], riegeli::StdOut());
}
}
<|endoftext|> |
<commit_before>#include <stack.hpp>
#include <catch.hpp>
#include <iostream>
using namespace std;
SCENARIO("count", "[count]"){
stack<int> s;
s.push(1);
REQUIRE(s.count()==1);
}
SCENARIO("push", "[push]"){
stack<int> s;
s.push(1);
REQUIRE(s.count()==1);
}
SCENARIO("pop", "[pop]"){
stack<int> s;
s.push(1);
REQUIRE(*(s.pop())==1);
REQUIRE(s.count()==0);
}
SCENARIO("prisv", "[prisv]"){
stack<int> s;
s.push(1);
stack<int> s2;
s2=s;
REQUIRE(s.count()==1);
}
SCENARIO("empty", "[empty]"){
stack<int> s1, s2;
s1.push(1);
REQUIRE(!s1.empty());
REQUIRE(s2.empty());
}
SCENARIO("threads", "[threads]"){
stack<int> s;
s.push(1);
s.push(2);
s.push(3);
std::thread t1([&s](){
for (int i = 0; i < 5; i++) {
s.push(i + 4);
}
});
std::thread t2([&s](){
for (int i = 0; i < 5; i++)
{
s.pop();
}
});
t1.join();
t2.join();
REQUIRE(s.count()==3);
}
<commit_msg>Update init.cpp<commit_after>#include <stack.hpp>
#include <catch.hpp>
#include <iostream>
using namespace std;
SCENARIO("count", "[count]"){
stack<int> s;
s.push(1);
REQUIRE(s.count()==1);
}
SCENARIO("push", "[push]"){
stack<int> s;
s.push(1);
REQUIRE(s.count()==1);
}
SCENARIO("pop", "[pop]"){
stack<int> s;
s.push(1);
REQUIRE(*(s.pop())==1);
REQUIRE(s.count()==0);
}
SCENARIO("prisv", "[prisv]"){
stack<int> s;
s.push(1);
stack<int> s2;
s2=s;
REQUIRE(s.count()==1);
}
SCENARIO("empty", "[empty]"){
stack<int> s1, s2;
s1.push(1);
REQUIRE(!s1.empty());
REQUIRE(s2.empty());
}
SCENARIO("threads", "[threads]"){
stack<int> s;
s.push(1);
s.push(2);
s.push(3);
std::thread t1([&s](){
for (int i = 0; i < 5; i++) {
s.push(i + 4);
}
});
std::thread t2([&s](){
for (int i = 0; i < 5; i++)
{
s.pop();
}
});
t1.join();
t2.join();
REQUIRE(s.count()==3);
}
<|endoftext|> |
<commit_before>#include "Fracao.h"
#include <iostream>
void operacoesAritmeticas( void );
int main( int argc, char const *argv[] ) {
operacoesAritmeticas();
return 0;
}
void operacoesAritmeticas( void ) {
Fracao a( 1, 2 );
Fracao b( 1, 3 );
Fracao c( 5, 2 );
int d = 10;
int e = 0;
std::cout << a << "+" << b << "=" << a + b << '\n';
std::cout << a << "-" << b << "=" << a - b << '\n';
std::cout << a << "/" << b << "=" << a / b << '\n';
std::cout << a << "*" << b << "=" << a * b << '\n';
std::cout << '\n';
std::cout << b << "+" << a << "=" << b + a << '\n';
std::cout << b << "-" << a << "=" << b - a << '\n';
std::cout << b << "/" << a << "=" << b / a << '\n';
std::cout << b << "*" << a << "=" << b * a << '\n';
std::cout << '\n';
std::cout << a << "+" << c << "=" << a + c << '\n';
std::cout << a << "-" << c << "=" << a - c << '\n';
std::cout << a << "/" << c << "=" << a / c << '\n';
std::cout << a << "*" << c << "=" << a * c << '\n';
std::cout << '\n';
std::cout << a << "+" << d << "=" << a + d << '\n';
std::cout << a << "-" << d << "=" << a - d << '\n';
std::cout << a << "/" << d << "=" << a / d << '\n';
std::cout << a << "*" << d << "=" << a * d << '\n';
std::cout << '\n';
std::cout << d << "+" << a << "=" << d + a << '\n';
std::cout << d << "-" << a << "=" << d - a << '\n';
std::cout << d << "/" << a << "=" << d / a << '\n';
std::cout << d << "*" << a << "=" << d * a << '\n';
std::cout << '\n';
std::cout << a << "+" << d << "=" << a + e << '\n';
std::cout << a << "-" << d << "=" << a - e << '\n';
std::cout << a << "/" << d << "=" << a / e << '\n';
std::cout << a << "*" << d << "=" << a * e << '\n';
std::cout << '\n';
std::cout << d << "+" << a << "=" << e + a << '\n';
std::cout << d << "-" << a << "=" << e - a << '\n';
std::cout << d << "/" << a << "=" << e / a << '\n';
std::cout << d << "*" << a << "=" << e * a << '\n';
std::cout << '\n';
}
<commit_msg>Teste operações de incremento e decremento<commit_after>#include "Fracao.h"
#include <iostream>
void operacoesAritmeticas( void );
void operacoesIncrementoEDecremento( void );
int main( int argc, char const *argv[] ) {
std::cout << "OPERAÇÕES ARITMETICAS" << '\n';
operacoesAritmeticas();
std::cout << "OPERAÇÕES INCREMENTO E DECREMENTO" << '\n';
operacoesIncrementoEDecremento();
return 0;
}
void operacoesAritmeticas( void ) {
Fracao a( 1, 2 );
Fracao b( 1, 3 );
const Fracao c( 5, 2 );
int d = 10;
int e = 0;
std::cout << a << "+" << b << "=" << a + b << '\n';
std::cout << a << "-" << b << "=" << a - b << '\n';
std::cout << a << "/" << b << "=" << a / b << '\n';
std::cout << a << "*" << b << "=" << a * b << '\n';
std::cout << '\n';
std::cout << b << "+" << a << "=" << b + a << '\n';
std::cout << b << "-" << a << "=" << b - a << '\n';
std::cout << b << "/" << a << "=" << b / a << '\n';
std::cout << b << "*" << a << "=" << b * a << '\n';
std::cout << '\n';
std::cout << a << "+" << c << "=" << a + c << '\n';
std::cout << a << "-" << c << "=" << a - c << '\n';
std::cout << a << "/" << c << "=" << a / c << '\n';
std::cout << a << "*" << c << "=" << a * c << '\n';
std::cout << '\n';
std::cout << a << "+" << d << "=" << a + d << '\n';
std::cout << a << "-" << d << "=" << a - d << '\n';
std::cout << a << "/" << d << "=" << a / d << '\n';
std::cout << a << "*" << d << "=" << a * d << '\n';
std::cout << '\n';
std::cout << d << "+" << a << "=" << d + a << '\n';
std::cout << d << "-" << a << "=" << d - a << '\n';
std::cout << d << "/" << a << "=" << d / a << '\n';
std::cout << d << "*" << a << "=" << d * a << '\n';
std::cout << '\n';
std::cout << a << "+" << e << "=" << a + e << '\n';
std::cout << a << "-" << e << "=" << a - e << '\n';
std::cout << a << "/" << e << "=" << a / e << '\n';
std::cout << a << "*" << e << "=" << a * e << '\n';
std::cout << '\n';
std::cout << e << "+" << a << "=" << e + a << '\n';
std::cout << e << "-" << a << "=" << e - a << '\n';
std::cout << e << "/" << a << "=" << e / a << '\n';
std::cout << e << "*" << a << "=" << e * a << '\n';
std::cout << '\n';
}
void operacoesIncrementoEDecremento( void ) {
Fracao a( 1, 2 );
Fracao b( 1, 3 );
const Fracao c( 5, 2 );
int d = 10;
int e = 0;
std::cout << a << "++"
<< "=" << a++ << '\n';
std::cout << "++" << a << "=" << ++a << '\n';
std::cout << b << "++"
<< "=" << b++ << '\n';
std::cout << "++" << b << "=" << ++b << '\n';
std::cout << "++(" << a << "+" << b << ")=" << ++( a + b ) << '\n';
std::cout << "++(" << a << "-" << b << ")=" << ++( a - b ) << '\n';
std::cout << "++(" << a << "/" << b << ")=" << ++( a / b ) << '\n';
std::cout << "++(" << a << "*" << b << ")=" << ++( a * b ) << '\n';
std::cout << '\n';
std::cout << "++(" << b << "+" << a << ")=" << ++( b + a ) << '\n';
std::cout << "++(" << b << "-" << a << ")=" << ++( b - a ) << '\n';
std::cout << "++(" << b << "/" << a << ")=" << ++( b / a ) << '\n';
std::cout << "++(" << b << "*" << a << ")=" << ++( b * a ) << '\n';
std::cout << '\n';
std::cout << "++(" << a << "+" << c << ")=" << ++( a + c ) << '\n';
std::cout << "++(" << a << "-" << c << ")=" << ++( a - c ) << '\n';
std::cout << "++(" << a << "/" << c << ")=" << ++( a / c ) << '\n';
std::cout << "++(" << a << "*" << c << ")=" << ++( a * c ) << '\n';
std::cout << '\n';
std::cout << "++(" << a << "+" << d << ")=" << ++( a + d ) << '\n';
std::cout << "++(" << a << "-" << d << ")=" << ++( a - d ) << '\n';
std::cout << "++(" << a << "/" << d << ")=" << ++( a / d ) << '\n';
std::cout << "++(" << a << "*" << d << ")=" << ++( a * d ) << '\n';
std::cout << '\n';
std::cout << "++(" << d << "+" << a << ")=" << ++( d + a ) << '\n';
std::cout << "++(" << d << "-" << a << ")=" << ++( d - a ) << '\n';
std::cout << "++(" << d << "/" << a << ")=" << ++( d / a ) << '\n';
std::cout << "++(" << d << "*" << a << ")=" << ++( d * a ) << '\n';
std::cout << '\n';
std::cout << "++(" << a << "+" << e << ")=" << ++( a + e ) << '\n';
std::cout << "++(" << a << "-" << e << ")=" << ++( a - e ) << '\n';
std::cout << "++(" << a << "/" << e << ")=" << ++( a / e ) << '\n';
std::cout << "++(" << a << "*" << e << ")=" << ++( a * e ) << '\n';
std::cout << '\n';
std::cout << "++(" << e << "+" << a << ")=" << ++( e + a ) << '\n';
std::cout << "++(" << e << "-" << a << ")=" << ++( e - a ) << '\n';
std::cout << "++(" << e << "/" << a << ")=" << ++( e / a ) << '\n';
std::cout << "++(" << e << "*" << a << ")=" << ++( e * a ) << '\n';
std::cout << '\n';
}
<|endoftext|> |
<commit_before>#include "catch.hpp"
#include <iostream>
#include "Database_Creator.hpp"
#include "Database_Sorter.hpp"
person readPerson(std::string file_name, size_t index) {
person result;
std::ifstream file(file_name);
for (size_t i = 0; i < index + 1; i++) {
file >> result;
}
file.close();
return result;
}
bool isALessThanB(char A, char B, bool is_capital) {
std::string alphabet;
if (is_capital) {
alphabet = " АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ";
}
else {
alphabet = " абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
}
size_t A_i;
size_t B_i;
for (size_t i = 0; i < alphabet.size(); i++) {
if (alphabet[i] == A) {
A_i = i;
}
if (alphabet[i] == B) {
B_i = i;
}
}
return A_i < B_i;
}
bool isANotMoreThanB(person A, person B) {
for (size_t i = 0; i < A.surname.length(); i++) {
char A_char = A.surname[i];
char B_char = (i < B.surname.length()) ? B.surname[i] : ' ';
if (isALessThanB(A.surname[i], B.surname[i], i == 0)) {
return true;
}
else {
if (A.surname[i] != B.surname[i]) {
return false;
}
}
}
return true;
}
SCENARIO("Sort", "[s]") {
//setlocale(LC_ALL, "ru_RU.utf8");
std::ifstream ru("russian_letters.txt");
for (size_t i = 0; i < 6; i++) {
std::string str;
ru >> str;
russian_letters[i] = str[0];
}
ru.close();
/*size_t n_persons = 2001;
size_t RAM_amount = 10000;
std::string names_file_name = "names.txt";
std::string surnames_file_name = "surnames.txt";
std::string database_file_name = "database.txt";
std::string output_file_name = "sorted_database.txt";
{
Database_Creator database_creator(database_file_name, names_file_name, surnames_file_name, n_persons);
Database_Sorter database_sorter(database_file_name, output_file_name, RAM_amount);
size_t start = clock();
database_sorter.sortDatabase();
size_t result = clock() - start;
std::cout << result << std::endl;
system("pause");
}
for (size_t i = 0; i < 0; i++) {
size_t person1_i = rand() % n_persons;
size_t person2_i = person1_i + rand() % (n_persons - person1_i);
person person1 = readPerson(output_file_name, person1_i);
person person2 = readPerson(output_file_name, person2_i);
REQUIRE(isANotMoreThanB(person1, person2));
}*/
}
<commit_msg>Update init.cpp<commit_after>#include "catch.hpp"
#include <iostream>
#include "Database_Creator.hpp"
#include "Database_Sorter.hpp"
person readPerson(std::string file_name, size_t index) {
person result;
std::ifstream file(file_name);
for (size_t i = 0; i < index + 1; i++) {
file >> result;
}
file.close();
return result;
}
bool isALessThanB(char A, char B, bool is_capital) {
std::string alphabet;
if (is_capital) {
alphabet = " АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ";
}
else {
alphabet = " абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
}
size_t A_i;
size_t B_i;
for (size_t i = 0; i < alphabet.size(); i++) {
if (alphabet[i] == A) {
A_i = i;
}
if (alphabet[i] == B) {
B_i = i;
}
}
return A_i < B_i;
}
bool isANotMoreThanB(person A, person B) {
for (size_t i = 0; i < A.surname.length(); i++) {
char A_char = A.surname[i];
char B_char = (i < B.surname.length()) ? B.surname[i] : ' ';
if (isALessThanB(A.surname[i], B.surname[i], i == 0)) {
return true;
}
else {
if (A.surname[i] != B.surname[i]) {
return false;
}
}
}
return true;
}
SCENARIO("Sort", "[s]") {
//setlocale(LC_ALL, "ru_RU.utf8");
std::ifstream ru("russian_letters.txt");
for (size_t i = 0; i < 6; i++) {
std::string str;
ru >> str;
russian_letters[i] = str[0];
}
ru.close();
size_t n_persons = 2001;
size_t RAM_amount = 10000;
std::string names_file_name = "names.txt";
std::string surnames_file_name = "surnames.txt";
std::string database_file_name = "database.txt";
std::string output_file_name = "sorted_database.txt";
{
Database_Creator database_creator(database_file_name, names_file_name, surnames_file_name, n_persons);
/*Database_Sorter database_sorter(database_file_name, output_file_name, RAM_amount);
size_t start = clock();
database_sorter.sortDatabase();
size_t result = clock() - start;
std::cout << result << std::endl;
system("pause");
}
for (size_t i = 0; i < 0; i++) {
size_t person1_i = rand() % n_persons;
size_t person2_i = person1_i + rand() % (n_persons - person1_i);
person person1 = readPerson(output_file_name, person1_i);
person person2 = readPerson(output_file_name, person2_i);
REQUIRE(isANotMoreThanB(person1, person2));
}*/
}
<|endoftext|> |
<commit_before>#include "catch.hpp"
#include <iostream>
#include "Database_Creator.hpp"
#include "Database_Sorter.hpp"
person readPerson(std::string file_name, size_t index) {
person result;
std::ifstream file(file_name);
for (size_t i = 0; i < index + 1; i++) {
file >> result;
}
file.close();
return result;
}
/*bool isALessThanB(char A, char B, bool is_capital) {
std::string alphabet;
if (is_capital) {
alphabet = " АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ";
}
else {
alphabet = " абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
}
size_t A_i;
size_t B_i;
for (size_t i = 0; i < alphabet.size(); i++) {
if (alphabet[i] == A) {
A_i = i;
}
if (alphabet[i] == B) {
B_i = i;
}
}
return A_i < B_i;
}*/
bool isANotMoreThanB(person A, person B) {
for (size_t i = 0; i < A.surname.length(); i++) {
char A_char = A.surname[i];
char B_char = (i < B.surname.length()) ? B.surname[i] : ' ';
if (letterI(A.surname[i], i == 0) < letterI(B.surname[i], i == 0)) {
return true;
}
else {
if (A.surname[i] != B.surname[i]) {
return false;
}
}
}
return true;
}
SCENARIO("Sort", "[s]") {
//setlocale(LC_ALL, "ru_RU.utf8");
std::ifstream ru("russian_letters.txt");
for (size_t i = 0; i < 6; i++) {
std::string str;
ru >> str;
russian_letters[i] = str[0];
}
ru.close();
size_t n_persons = 2001;
size_t RAM_amount = 10000;
std::string names_file_name = "Names";
std::string surnames_file_name = "Surnames";
std::string database_file_name = "database.txt";
std::string output_file_name = "sorted_database.txt";
{
Database_Creator database_creator(database_file_name, names_file_name, surnames_file_name, n_persons);
Database_Sorter database_sorter(database_file_name, output_file_name, RAM_amount);
size_t start = clock();
database_sorter.sortDatabase();
size_t result = clock() - start;
std::cout << result << std::endl;
system("pause");
}
for (size_t i = 0; i < 1000; i++) {
size_t person1_i = rand() % n_persons;
size_t person2_i = person1_i + rand() % (n_persons - person1_i);
person person1 = readPerson(output_file_name, person1_i);
person person2 = readPerson(output_file_name, person2_i);
REQUIRE(isANotMoreThanB(person1, person2));
}
/*std::string str = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ";
REQUIRE(letterI(str[1], true) == 2);
REQUIRE(letterI(str[2], true) == 3);
REQUIRE(letterI(str[3], true) == 4);
REQUIRE(letterI(str[4], true) == 5);*/
}
<commit_msg>Update init.cpp<commit_after>#include "catch.hpp"
#include <iostream>
#include "Database_Creator.hpp"
#include "Database_Sorter.hpp"
person readPerson(std::string file_name, size_t index) {
person result;
std::ifstream file(file_name);
for (size_t i = 0; i < index + 1; i++) {
file >> result;
}
file.close();
return result;
}
/*bool isALessThanB(char A, char B, bool is_capital) {
std::string alphabet;
if (is_capital) {
alphabet = " АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ";
}
else {
alphabet = " абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
}
size_t A_i;
size_t B_i;
for (size_t i = 0; i < alphabet.size(); i++) {
if (alphabet[i] == A) {
A_i = i;
}
if (alphabet[i] == B) {
B_i = i;
}
}
return A_i < B_i;
}*/
bool isANotMoreThanB(person A, person B) {
for (size_t i = 0; i < A.surname.length(); i++) {
char A_char = A.surname[i];
char B_char = (i < B.surname.length()) ? B.surname[i] : ' ';
if (letterI(A.surname[i], i == 0) < letterI(B.surname[i], i == 0)) {
return true;
}
else {
if (A.surname[i] != B.surname[i]) {
return false;
}
}
}
return true;
}
SCENARIO("LetterI", "[l]") {
REQUIRE(letterI('A', true) == 1);
}
SCENARIO("Sort", "[s]") {
//setlocale(LC_ALL, "ru_RU.utf8");
std::ifstream ru("russian_letters.txt");
for (size_t i = 0; i < 6; i++) {
std::string str;
ru >> str;
russian_letters[i] = str[0];
}
ru.close();
size_t n_persons = 2001;
size_t RAM_amount = 10000;
std::string names_file_name = "Names";
std::string surnames_file_name = "Surnames";
std::string database_file_name = "database.txt";
std::string output_file_name = "sorted_database.txt";
{
Database_Creator database_creator(database_file_name, names_file_name, surnames_file_name, n_persons);
Database_Sorter database_sorter(database_file_name, output_file_name, RAM_amount);
size_t start = clock();
database_sorter.sortDatabase();
size_t result = clock() - start;
std::cout << result << std::endl;
system("pause");
}
for (size_t i = 0; i < 1000; i++) {
size_t person1_i = rand() % n_persons;
size_t person2_i = person1_i + rand() % (n_persons - person1_i);
person person1 = readPerson(output_file_name, person1_i);
person person2 = readPerson(output_file_name, person2_i);
REQUIRE(isANotMoreThanB(person1, person2));
}
/*std::string str = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ";
REQUIRE(letterI(str[1], true) == 2);
REQUIRE(letterI(str[2], true) == 3);
REQUIRE(letterI(str[3], true) == 4);
REQUIRE(letterI(str[4], true) == 5);*/
}
<|endoftext|> |
<commit_before>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2015 *
* *
* 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 "gtest/gtest.h"
#include <ghoul/cmdparser/cmdparser>
#include <ghoul/filesystem/filesystem>
#include <ghoul/logging/logging>
#include <ghoul/misc/dictionary.h>
#include <ghoul/lua/ghoul_lua.h>
#include <test_common.inl>
//#include <test_spicemanager.inl>
#include <test_scenegraphloader.inl>
//#include <test_luaconversions.inl>
//#include <test_powerscalecoordinates.inl>
#include <openspace/engine/openspaceengine.h>
#include <openspace/engine/configurationmanager.h>
#include <openspace/util/constants.h>
#include <openspace/util/factorymanager.h>
#include <openspace/util/time.h>
#include <iostream>
using namespace ghoul::cmdparser;
using namespace ghoul::filesystem;
using namespace ghoul::logging;
namespace {
std::string _loggerCat = "OpenSpaceTest";
}
int main(int argc, char** argv) {
std::vector<std::string> args;
openspace::OpenSpaceEngine::create(argc, argv, args);
//LogManager::initialize(LogManager::LogLevel::Debug);
//LogMgr.addLog(new ConsoleLog);
//FileSystem::initialize();
//std::string configurationFilePath = "";
//LDEBUG("Finding configuration");
//if (!openspace::OpenSpaceEngine::findConfiguration(configurationFilePath)) {
// LFATAL("Could not find OpenSpace configuration file!");
// assert(false);
//}
////LINFO("Configuration file found: " << FileSys.absolutePath(configurationFilePath));
//openspace::ConfigurationManager manager;
//manager.loadFromFile(configurationFilePath);
//openspace::FactoryManager::initialize();
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Clean test main.cpp<commit_after>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2015 *
* *
* 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 "gtest/gtest.h"
#include <ghoul/cmdparser/cmdparser>
#include <ghoul/filesystem/filesystem>
#include <ghoul/logging/logging>
#include <ghoul/misc/dictionary.h>
#include <ghoul/lua/ghoul_lua.h>
#include <test_common.inl>
//#include <test_spicemanager.inl>
#include <test_scenegraphloader.inl>
//#include <test_luaconversions.inl>
//#include <test_powerscalecoordinates.inl>
#include <openspace/engine/openspaceengine.h>
#include <openspace/engine/configurationmanager.h>
#include <openspace/util/constants.h>
#include <openspace/util/factorymanager.h>
#include <openspace/util/time.h>
#include <iostream>
using namespace ghoul::cmdparser;
using namespace ghoul::filesystem;
using namespace ghoul::logging;
namespace {
std::string _loggerCat = "OpenSpaceTest";
}
int main(int argc, char** argv) {
std::vector<std::string> args;
openspace::OpenSpaceEngine::create(argc, argv, args);
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
// #include <glm/glm.hpp>
// #include <glm/gtx/intersect.hpp>
#include "sphere.hpp"
#include "box.hpp"
#include "material.hpp"
#include "light.hpp"
#include "camera.hpp"
#include "sdfloader.hpp"
#include "renderer.hpp"
TEST_CASE("test material", "[test material]")
{
std::cout << std::endl << "Material Tests: " << std::endl;
std::cout << "(Default-Konstructor)" <<std::endl;
Material mat1;
std::string s1 = "defaultmaterial";
Color col1{};
REQUIRE(mat1.name() == s1);
REQUIRE(mat1.ka() == col1);
REQUIRE(mat1.kd() == col1);
REQUIRE(mat1.ks() == col1);
REQUIRE(mat1.m() == 0);
std::cout << mat1;
std::cout << std::endl << "(Konstructor)" << std::endl;
std::string s2 = "mat2";
Color col2{1.0f,0.0f,1.0f};
Material mat2{s2,col2,col2,col2,1};
REQUIRE(mat2.name() == s2);
REQUIRE(mat2.ka() == col2);
REQUIRE(mat2.kd() == col2);
REQUIRE(mat2.ks() == col2);
REQUIRE(mat2.m() == 1);
std::cout << mat2;
}
TEST_CASE("test box", "[test box]")
{
std::cout << std::endl << "Box Tests: " << std::endl;
Box box1;
glm::vec3 vec3{};
REQUIRE(box1.min() == vec3);
REQUIRE(box1.max() == vec3);
Box box2{glm::vec3{1.0,1.0,1.0},glm::vec3{3.0,4.0,5.0}};
glm::vec3 p1{1.0,1.0,1.0};
glm::vec3 p2{3.0,4.0,5.0};
REQUIRE(box2.min() == p1);
REQUIRE(box2.max() == p2);
REQUIRE(box2.area() == Approx(52.0));
REQUIRE(box2.volume() == Approx(24.0));
std::cout << std::endl;
std::string b = "Box3";
Material mat{};
Box box3{glm::vec3{1.0,1.0,1.0}, glm::vec3{2.0,2.0,2.0}, b, mat};
REQUIRE(box3.name() == b);
REQUIRE(box3.material() == mat);
std::cout << box3;
}
TEST_CASE("test sphere", "[test sphere]")
{
std::cout << std::endl << "Sphere Tests: " << std::endl;
Sphere sphere0;
glm::vec3 vec0{};
std::string a = "defaultshape";
Material mat{};
REQUIRE(sphere0.radius() == Approx(0.0));
REQUIRE(sphere0.center() == vec0);
REQUIRE(sphere0.name() == a);
REQUIRE(sphere0.material() == mat);
std::cout << sphere0;
glm::vec3 vec1{1.0,1.0,1.0};
std::string b = "sphere1";
Sphere sphere1{vec1, 1.0, b, mat};
REQUIRE(sphere1.radius() == Approx(1.0));
REQUIRE(sphere1.center() == vec1);
REQUIRE(sphere1.name() == b);
REQUIRE(sphere1.material() == mat);
REQUIRE(sphere1.area() == Approx(12.5664));
REQUIRE(sphere1.volume() == Approx(4.18879f));
std::cout << sphere1;
}
/*TEST_CASE("test intersectRaySphere", "[test intersectRaySphere]")
{
std::cout << std::endl << "Intersect-Ray-Sphere Tests: " << std::endl;
glm::vec3 ray_origin1(0.0,0.0,0.0);
glm::vec3 ray_direction1(0.0,0.0,1.0);
Ray ray1{ray_origin1,ray_direction1};
glm::vec3 ray_origin2(2.0,1.0,3.0);
glm::vec3 ray_direction2(4.0,2.0,6.0);
Ray ray2{ray_origin2,ray_direction2};
float sphere_radius(1.0);
Material mat{};
glm::vec3 sphere_center0(0.0,0.0,5.0);
std::string a = "sphere0";
Sphere sphere0{sphere_center0, sphere_radius, a, mat};
glm::vec3 sphere_center1(3.0,1.5,4.5);
std::string b = "sphere1";
Sphere sphere1{sphere_center1, sphere_radius, b, mat};
glm::vec3 sphere_center2(7.0,7.0,7.0);
std::string c = "sphere2";
Sphere sphere2{sphere_center2, sphere_radius, c, mat};
float distance(0.0);
REQUIRE(sphere0.intersect(ray1, distance) == true);
REQUIRE(distance == Approx(4.0f));
REQUIRE(sphere1.intersect(ray2, distance) == true);
REQUIRE(sphere2.intersect(ray2, distance) == false);
}*/
TEST_CASE("test intersectRayBox", "[test intersectRayBox]")
{
std::cout << std::endl << "Intersect-Ray-Box Tests: " << std::endl;
glm::vec3 ray_origin0(0.0,0.0,0.0);
glm::vec3 ray_direction0(1.0,1.0,1.0);
Ray ray0{ray_origin0,ray_direction0};
glm::vec3 ray_origin1(3.0,1.5,4.5);
glm::vec3 ray_direction1(-1.0,-1.0,-1.0);
Ray ray1{ray_origin1,ray_direction1};
std::string a = "box0";
Material mat{};
glm::vec3 box_min0(2.0,2.0,2.0);
glm::vec3 box_max0(4.0,4.0,4.0);
Box box0{box_min0, box_max0, a, mat};
std::string b = "box1";
glm::vec3 box_min1(3.0,1.5,4.5);
glm::vec3 box_max1(1.0,1.0,1.0);
Box box1{box_min1, box_max1, b, mat};
std::string c = "box2";
glm::vec3 box_min2(7.0,7.0,7.0);
glm::vec3 box_max2(6.0,8.0,6.0);
Box box2{box_min2, box_max2, c, mat};
Hit hit0 = box0.intersect(ray0);
std::cout << hit0;
Hit hit1 = box0.intersect(ray1);
std::cout << hit1;
// REQUIRE(box2.intersect(ray1) == temp);
// REQUIRE(box0.intersect(ray0) == temp);
// REQUIRE(box1.intersect(ray1) == temp);
}
TEST_CASE("test light", "[test light]"){
std::cout << std::endl << "Light Tests: " << std::endl;
std::cout << "(Default-Konstructor)" <<std::endl;
Light light1;
std::string s1 = "defaultlight";
glm::vec3 pos0(0.0,0.0,0.0);
Color c0;
REQUIRE(light1.name() == s1);
REQUIRE(light1.pos() == pos0);
REQUIRE(light1.dl() == c0);
std::cout << light1;
}
TEST_CASE("test camera", "[test camera]"){
std::cout << "Camera Tests: " << std::endl;
std::cout << "(Default-Konstructor)" <<std::endl;
Camera cam1;
std::string s1 = "defaultcam";
glm::vec3 pos0(0.0,0.0,0.0);
float fovx = 60.0f;
REQUIRE(cam1.name() == s1);
REQUIRE(cam1.pos() == pos0);
REQUIRE(cam1.fovx() == fovx);
std::cout << cam1;
glm::vec3 d(1.0,1.0,1.0);
//std::cout << cam1.castray(d) << std::endl;
}
TEST_CASE("sdfloader_material", "[sdfloader]"){
Sdfloader loader{"./materials.txt"};
std::shared_ptr<Scene> s = loader.loadscene("./materials.txt");
}
TEST_CASE("sdfloader Test", "[sdfloader test]"){
Sdfloader loader{"./test.txt"};
std::shared_ptr<Scene> sptr = loader.loadscene("./test.txt");
Scene s = *sptr;
std::cout << "\n" ;
std::cout << "Ambientes Licht: \n" << s.amblight << std::endl;
std::cout << "Background-Color: \n" << s.background << std::endl;
std::cout << *s.materials["red"] << std::endl;
std::cout << *s.materials["blue"] << std::endl;
std::cout << *s.shapes_ptr[0];
std::cout << *s.shapes_ptr[1];
std::cout << s.camera;
std::cout << *s.lights[0];
}
TEST_CASE("renderer Test", "[renderer test]"){
Sdfloader loader{"./test.txt"};
std::shared_ptr<Scene> s = loader.loadscene("./test.txt");
Renderer renderer(s);
renderer.render();
}
// AUFGABENBLATT 6
/*TEST_CASE("statischer Typ/dynamischer Typ Variable", "[6.7]")
{
std::cout << std::endl << "6.7:" << std::endl;
Color rot(255,0,0);
Material red("ton" ,rot,rot,rot,7.1f);
glm::vec3 position(0,0,0);
std::shared_ptr<Sphere> s1 = std::make_shared<Sphere>(
position, 1.2, "sphere0", red
);
std::shared_ptr<Shape> s2 = std::make_shared<Sphere>(
position, 1.2, "sphere1", red
);
s1->print(std::cout);
s2->print(std::cout);
//C++ ist eine statisch typisierte Sprache.
//In C++ können Variablen einer Basisklasse Objekte einer abgeleiteten Klasse referenzieren.
//Da hier im Beispiel die Pointer von verschiedenen Typen sind, kann man sehen, dass diese trotzdem auf das gleiche Objekt zeigen können.
//Der erste erzeugte Sphere-Pointer zeigt auf eine Sphere, hier sind statische und dynamische Klasse die selbe.
//Der zweite erzeugte Shape-Pointer zeigt auf eine Sphere, hier ist Shape die statische und Sphere ist die dynamische Klasse.
}
TEST_CASE("destructor", "[6.8]")
{
std::cout << std::endl << "6.8:" << std::endl;
Material red("red",Color {255,0,0}, 0.0);
glm::vec3 position(0,0,0);
Sphere* s1 = new Sphere(position, 1.2f, "sphere0", red);
Shape* s2 = new Sphere(position, 1.2f, "sphere1", red);
s1->print(std::cout);
s2->print(std::cout);
delete s1;
delete s2;
//Ohne virtual wird beim Shape-Pointer der Destruktor der Sphere nicht aufgerufen, da hier nur der Destruktor von der Klasse aufgerufen wird auf den der Pointer zeigt.
//Bei dem Sphere-Pointer werden zwei Destruktoren aufgerufen, da wenn der Destruktor der Sphere aufgerufen wird, auf welche der Pointer zeigt, automatisch auch noch der Destruktor der Basisklasse aufgerufen wird.
//Wenn man virtual verwendet wird auch für den Shape-Pointer der Destruktor der Sphere-Klasse aufgerufen, da der Destruktor des Pointers virtual und Sphere die abgeleitete Klasse der Basisklasse Shape ist.
}*/
int main(int argc, char *argv[])
{
return Catch::Session().run(argc, argv);
}
<commit_msg>updating box intersect tests<commit_after>#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
// #include <glm/glm.hpp>
// #include <glm/gtx/intersect.hpp>
#include "sphere.hpp"
#include "box.hpp"
#include "material.hpp"
#include "light.hpp"
#include "camera.hpp"
#include "sdfloader.hpp"
#include "renderer.hpp"
TEST_CASE("test material", "[test material]")
{
std::cout << std::endl << "Material Tests: " << std::endl;
std::cout << "(Default-Konstructor)" <<std::endl;
Material mat1;
std::string s1 = "defaultmaterial";
Color col1{};
REQUIRE(mat1.name() == s1);
REQUIRE(mat1.ka() == col1);
REQUIRE(mat1.kd() == col1);
REQUIRE(mat1.ks() == col1);
REQUIRE(mat1.m() == 0);
std::cout << mat1;
std::cout << std::endl << "(Konstructor)" << std::endl;
std::string s2 = "mat2";
Color col2{1.0f,0.0f,1.0f};
Material mat2{s2,col2,col2,col2,1};
REQUIRE(mat2.name() == s2);
REQUIRE(mat2.ka() == col2);
REQUIRE(mat2.kd() == col2);
REQUIRE(mat2.ks() == col2);
REQUIRE(mat2.m() == 1);
std::cout << mat2;
}
TEST_CASE("test box", "[test box]")
{
std::cout << std::endl << "Box Tests: " << std::endl;
Box box1;
glm::vec3 vec3{};
REQUIRE(box1.min() == vec3);
REQUIRE(box1.max() == vec3);
Box box2{glm::vec3{1.0,1.0,1.0},glm::vec3{3.0,4.0,5.0}};
glm::vec3 p1{1.0,1.0,1.0};
glm::vec3 p2{3.0,4.0,5.0};
REQUIRE(box2.min() == p1);
REQUIRE(box2.max() == p2);
REQUIRE(box2.area() == Approx(52.0));
REQUIRE(box2.volume() == Approx(24.0));
std::cout << std::endl;
std::string b = "Box3";
Material mat{};
Box box3{glm::vec3{1.0,1.0,1.0}, glm::vec3{2.0,2.0,2.0}, b, mat};
REQUIRE(box3.name() == b);
REQUIRE(box3.material() == mat);
std::cout << box3;
}
TEST_CASE("test sphere", "[test sphere]")
{
std::cout << std::endl << "Sphere Tests: " << std::endl;
Sphere sphere0;
glm::vec3 vec0{};
std::string a = "defaultshape";
Material mat{};
REQUIRE(sphere0.radius() == Approx(0.0));
REQUIRE(sphere0.center() == vec0);
REQUIRE(sphere0.name() == a);
REQUIRE(sphere0.material() == mat);
std::cout << sphere0;
glm::vec3 vec1{1.0,1.0,1.0};
std::string b = "sphere1";
Sphere sphere1{vec1, 1.0, b, mat};
REQUIRE(sphere1.radius() == Approx(1.0));
REQUIRE(sphere1.center() == vec1);
REQUIRE(sphere1.name() == b);
REQUIRE(sphere1.material() == mat);
REQUIRE(sphere1.area() == Approx(12.5664));
REQUIRE(sphere1.volume() == Approx(4.18879f));
std::cout << sphere1;
}
/*TEST_CASE("test intersectRaySphere", "[test intersectRaySphere]")
{
std::cout << std::endl << "Intersect-Ray-Sphere Tests: " << std::endl;
glm::vec3 ray_origin1(0.0,0.0,0.0);
glm::vec3 ray_direction1(0.0,0.0,1.0);
Ray ray1{ray_origin1,ray_direction1};
glm::vec3 ray_origin2(2.0,1.0,3.0);
glm::vec3 ray_direction2(4.0,2.0,6.0);
Ray ray2{ray_origin2,ray_direction2};
float sphere_radius(1.0);
Material mat{};
glm::vec3 sphere_center0(0.0,0.0,5.0);
std::string a = "sphere0";
Sphere sphere0{sphere_center0, sphere_radius, a, mat};
glm::vec3 sphere_center1(3.0,1.5,4.5);
std::string b = "sphere1";
Sphere sphere1{sphere_center1, sphere_radius, b, mat};
glm::vec3 sphere_center2(7.0,7.0,7.0);
std::string c = "sphere2";
Sphere sphere2{sphere_center2, sphere_radius, c, mat};
float distance(0.0);
REQUIRE(sphere0.intersect(ray1, distance) == true);
REQUIRE(distance == Approx(4.0f));
REQUIRE(sphere1.intersect(ray2, distance) == true);
REQUIRE(sphere2.intersect(ray2, distance) == false);
}*/
TEST_CASE("test intersectRayBox", "[test intersectRayBox]")
{
std::cout << std::endl << "Intersect-Ray-Box Tests: " << std::endl;
glm::vec3 ray_origin0(0.0,0.0,0.0);
glm::vec3 ray_direction0(1.0,1.0,1.0);
Ray ray0{ray_origin0,ray_direction0};
glm::vec3 ray_origin1(3.0,1.5,4.5);
glm::vec3 ray_direction1(-1.0,-1.0,-1.0);
Ray ray1{ray_origin1,ray_direction1};
std::string a = "box0";
Material mat{};
glm::vec3 box_min0(2.0,2.0,2.0);
glm::vec3 box_max0(4.0,4.0,4.0);
Box box0{box_min0, box_max0, a, mat};
std::string b = "box1";
glm::vec3 box_min1(3.0,1.5,4.5);
glm::vec3 box_max1(1.0,1.0,1.0);
Box box1{box_min1, box_max1, b, mat};
std::string c = "box2";
glm::vec3 box_min2(7.0,7.0,7.0);
glm::vec3 box_max2(6.0,8.0,6.0);
Box box2{box_min2, box_max2, c, mat};
Hit hit0 = box0.intersect(ray0);
std::cout << hit0;
Hit hit1 = box0.intersect(ray1);
std::cout << hit1;
Hit hit2 = box1.intersect(ray1);
std::cout << hit2;
Hit hit3 = box2.intersect(ray1);
std::cout << hit3;
// REQUIRE(box2.intersect(ray1) == temp);
// REQUIRE(box0.intersect(ray0) == temp);
// REQUIRE(box1.intersect(ray1) == temp);
}
TEST_CASE("test light", "[test light]"){
std::cout << std::endl << "Light Tests: " << std::endl;
std::cout << "(Default-Konstructor)" <<std::endl;
Light light1;
std::string s1 = "defaultlight";
glm::vec3 pos0(0.0,0.0,0.0);
Color c0;
REQUIRE(light1.name() == s1);
REQUIRE(light1.pos() == pos0);
REQUIRE(light1.dl() == c0);
std::cout << light1;
}
TEST_CASE("test camera", "[test camera]"){
std::cout << "Camera Tests: " << std::endl;
std::cout << "(Default-Konstructor)" <<std::endl;
Camera cam1;
std::string s1 = "defaultcam";
glm::vec3 pos0(0.0,0.0,0.0);
float fovx = 60.0f;
REQUIRE(cam1.name() == s1);
REQUIRE(cam1.pos() == pos0);
REQUIRE(cam1.fovx() == fovx);
std::cout << cam1;
glm::vec3 d(1.0,1.0,1.0);
//std::cout << cam1.castray(d) << std::endl;
}
TEST_CASE("sdfloader_material", "[sdfloader]"){
Sdfloader loader{"./materials.txt"};
std::shared_ptr<Scene> s = loader.loadscene("./materials.txt");
}
TEST_CASE("sdfloader Test", "[sdfloader test]"){
Sdfloader loader{"./test.txt"};
std::shared_ptr<Scene> sptr = loader.loadscene("./test.txt");
Scene s = *sptr;
std::cout << "\n" ;
std::cout << "Ambientes Licht: \n" << s.amblight << std::endl;
std::cout << "Background-Color: \n" << s.background << std::endl;
std::cout << *s.materials["red"] << std::endl;
std::cout << *s.materials["blue"] << std::endl;
std::cout << *s.shapes_ptr[0];
std::cout << *s.shapes_ptr[1];
std::cout << s.camera;
std::cout << *s.lights[0];
}
TEST_CASE("renderer Test", "[renderer test]"){
Sdfloader loader{"./test.txt"};
std::shared_ptr<Scene> s = loader.loadscene("./test.txt");
Renderer renderer(s);
renderer.render();
}
// AUFGABENBLATT 6
/*TEST_CASE("statischer Typ/dynamischer Typ Variable", "[6.7]")
{
std::cout << std::endl << "6.7:" << std::endl;
Color rot(255,0,0);
Material red("ton" ,rot,rot,rot,7.1f);
glm::vec3 position(0,0,0);
std::shared_ptr<Sphere> s1 = std::make_shared<Sphere>(
position, 1.2, "sphere0", red
);
std::shared_ptr<Shape> s2 = std::make_shared<Sphere>(
position, 1.2, "sphere1", red
);
s1->print(std::cout);
s2->print(std::cout);
//C++ ist eine statisch typisierte Sprache.
//In C++ können Variablen einer Basisklasse Objekte einer abgeleiteten Klasse referenzieren.
//Da hier im Beispiel die Pointer von verschiedenen Typen sind, kann man sehen, dass diese trotzdem auf das gleiche Objekt zeigen können.
//Der erste erzeugte Sphere-Pointer zeigt auf eine Sphere, hier sind statische und dynamische Klasse die selbe.
//Der zweite erzeugte Shape-Pointer zeigt auf eine Sphere, hier ist Shape die statische und Sphere ist die dynamische Klasse.
}
TEST_CASE("destructor", "[6.8]")
{
std::cout << std::endl << "6.8:" << std::endl;
Material red("red",Color {255,0,0}, 0.0);
glm::vec3 position(0,0,0);
Sphere* s1 = new Sphere(position, 1.2f, "sphere0", red);
Shape* s2 = new Sphere(position, 1.2f, "sphere1", red);
s1->print(std::cout);
s2->print(std::cout);
delete s1;
delete s2;
//Ohne virtual wird beim Shape-Pointer der Destruktor der Sphere nicht aufgerufen, da hier nur der Destruktor von der Klasse aufgerufen wird auf den der Pointer zeigt.
//Bei dem Sphere-Pointer werden zwei Destruktoren aufgerufen, da wenn der Destruktor der Sphere aufgerufen wird, auf welche der Pointer zeigt, automatisch auch noch der Destruktor der Basisklasse aufgerufen wird.
//Wenn man virtual verwendet wird auch für den Shape-Pointer der Destruktor der Sphere-Klasse aufgerufen, da der Destruktor des Pointers virtual und Sphere die abgeleitete Klasse der Basisklasse Shape ist.
}*/
int main(int argc, char *argv[])
{
return Catch::Session().run(argc, argv);
}
<|endoftext|> |
<commit_before>#include "Fury/BufferManager.h"
namespace fury
{
void BufferManager::Remove(size_t id)
{
auto it = m_Buffers.find(id);
if (it != m_Buffers.end())
m_Buffers.erase(it);
}
void BufferManager::Release(size_t id)
{
auto it = m_Buffers.find(id);
if (it != m_Buffers.end())
{
if (!it->second.expired())
it->second.lock()->DeleteBuffer();
m_Buffers.erase(it);
}
}
void BufferManager::RemoveAll()
{
m_Buffers.clear();
}
void BufferManager::ReleaseAll()
{
for (auto pair : m_Buffers)
{
if (!pair.second.expired())
pair.second.lock()->DeleteBuffer();
}
m_Buffers.clear();
}
void BufferManager::IncreaseMemory(unsigned int byte, bool gpu)
{
if (gpu)
m_GPUMemories += byte;
else
m_GPUMemories += byte;
}
void BufferManager::DecreaseMemory(unsigned int byte, bool gpu)
{
if (gpu)
m_GPUMemories -= byte;
else
m_CPUMemories -= byte;
}
unsigned int BufferManager::GetMemoryInMegaByte(bool gpu)
{
if (gpu)
return m_GPUMemories / 1000000;
else
return m_CPUMemories / 1000000;
}
}<commit_msg>Update BufferManager.cpp<commit_after>#include "Fury/BufferManager.h"
namespace fury
{
void BufferManager::Remove(size_t id)
{
auto it = m_Buffers.find(id);
if (it != m_Buffers.end())
m_Buffers.erase(it);
}
void BufferManager::Release(size_t id)
{
auto it = m_Buffers.find(id);
if (it != m_Buffers.end())
{
if (!it->second.expired())
it->second.lock()->DeleteBuffer();
m_Buffers.erase(it);
}
}
void BufferManager::RemoveAll()
{
m_Buffers.clear();
}
void BufferManager::ReleaseAll()
{
for (auto pair : m_Buffers)
{
if (!pair.second.expired())
pair.second.lock()->DeleteBuffer();
}
m_Buffers.clear();
}
void BufferManager::IncreaseMemory(unsigned int byte, bool gpu)
{
if (gpu)
m_GPUMemories += byte;
else
m_CPUMemories += byte;
}
void BufferManager::DecreaseMemory(unsigned int byte, bool gpu)
{
if (gpu)
m_GPUMemories -= byte;
else
m_CPUMemories -= byte;
}
unsigned int BufferManager::GetMemoryInMegaByte(bool gpu)
{
if (gpu)
return m_GPUMemories / 1000000;
else
return m_CPUMemories / 1000000;
}
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2018 PaddlePaddle 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. */
#include "paddle/fluid/operators/math/concat.h"
#include <gtest/gtest.h>
#include <vector>
#include "paddle/fluid/framework/tensor_util.h"
template <typename DeviceContext, typename Place>
void testConcat() {
paddle::framework::Tensor input_a_cpu;
paddle::framework::Tensor input_b_cpu;
paddle::framework::Tensor out_cpu;
paddle::framework::Tensor input_a;
paddle::framework::Tensor input_b;
paddle::framework::Tensor out;
DeviceContext* context = new DeviceContext(Place());
// DeviceContext context(Place());
/**
* cast1:
* inputs:
* t_a.shape: [2, 3, 4]
* t_b.shape: [3, 3, 4]
* output:
* out.shape: [5, 3, 4]
*/
auto dim_a = paddle::framework::make_ddim({2, 3, 4});
auto dim_b = paddle::framework::make_ddim({3, 3, 4});
auto dim_out = paddle::framework::make_ddim({5, 3, 4});
input_a.mutable_data<int>(dim_a, Place());
input_b.mutable_data<int>(dim_b, Place());
out.mutable_data<int>(dim_out, Place());
if (paddle::platform::is_gpu_place(Place())) {
input_a_cpu.mutable_data<int>(dim_a, paddle::platform::CPUPlace());
input_b_cpu.mutable_data<int>(dim_b, paddle::platform::CPUPlace());
out_cpu.mutable_data<int>(dim_out, paddle::platform::CPUPlace());
}
int* a_ptr;
int* b_ptr;
if (paddle::platform::is_gpu_place(Place())) {
a_ptr = input_a_cpu.data<int>();
b_ptr = input_b_cpu.data<int>();
} else {
a_ptr = input_a.data<int>();
b_ptr = input_b.data<int>();
}
for (int i = 0; i < 2 * 3 * 4; ++i) {
a_ptr[i] = i;
}
for (int i = 0; i < 3 * 3 * 4; ++i) {
b_ptr[i] = i;
}
if (paddle::platform::is_gpu_place(Place())) {
paddle::framework::TensorCopy(input_a_cpu, Place(), *context, &input_a);
paddle::framework::TensorCopy(input_b_cpu, Place(), *context, &input_b);
}
std::vector<paddle::framework::Tensor> input;
input.push_back(input_a);
input.push_back(input_b);
paddle::operators::math::ConcatFunctor<DeviceContext, int> concat_functor;
concat_functor(*context, input, 0, &out);
// check the dim of input_a, input_b
PADDLE_ENFORCE_EQ(input_a.dims(), dim_a);
PADDLE_ENFORCE_EQ(input_b.dims(), dim_b);
int* out_ptr;
if (paddle::platform::is_gpu_place(Place())) {
paddle::framework::TensorCopy(out, paddle::platform::CPUPlace(), *context,
&out_cpu);
out_ptr = out_cpu.data<int>();
} else {
out_ptr = out.data<int>();
}
int cols = 2 * 3 * 4;
int idx_a = 0, idx_b = 0;
for (int j = 0; j < 5 * 3 * 4; ++j) {
if (j >= cols) {
PADDLE_ENFORCE_EQ(out_ptr[j], b_ptr[idx_b]);
++idx_b;
} else {
PADDLE_ENFORCE_EQ(out_ptr[j], a_ptr[idx_a]);
++idx_a;
}
}
//
/**
* cast2:
* inputs:
* t_a.shape: [2, 3, 4]
* t_b.shape: [2, 4, 4]
* output:
* out.shape: [2, 7, 4]
*/
dim_a = paddle::framework::make_ddim({2, 3, 4});
dim_b = paddle::framework::make_ddim({2, 4, 4});
dim_out = paddle::framework::make_ddim({2, 7, 4});
input_a.Resize(dim_a);
input_b.Resize(dim_b);
out.Resize(dim_out);
if (paddle::platform::is_gpu_place(Place())) {
input_a_cpu.Resize(dim_a);
input_b_cpu.Resize(dim_b);
out_cpu.Resize(dim_out);
}
if (paddle::platform::is_gpu_place(Place())) {
a_ptr = input_a_cpu.data<int>();
b_ptr = input_b_cpu.data<int>();
} else {
a_ptr = input_a.data<int>();
b_ptr = input_b.data<int>();
}
for (int i = 0; i < 2 * 3 * 4; ++i) {
a_ptr[i] = i;
}
for (int i = 0; i < 2 * 4 * 4; ++i) {
b_ptr[i] = i;
}
if (paddle::platform::is_gpu_place(Place())) {
paddle::framework::TensorCopy(input_a_cpu, Place(), *context, &input_a);
paddle::framework::TensorCopy(input_b_cpu, Place(), *context, &input_b);
}
input.clear();
input.push_back(input_a);
input.push_back(input_b);
concat_functor(*context, input, 1, &out);
// check the dim of input_a, input_b
PADDLE_ENFORCE_EQ(input_a.dims(), dim_a);
PADDLE_ENFORCE_EQ(input_b.dims(), dim_b);
if (paddle::platform::is_gpu_place(Place())) {
paddle::framework::TensorCopy(out, paddle::platform::CPUPlace(), *context,
&out_cpu);
out_ptr = out_cpu.data<int>();
} else {
out_ptr = out.data<int>();
}
cols = 3 * 4;
idx_a = 0, idx_b = 0;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 28; ++j) {
if (j >= cols) {
PADDLE_ENFORCE_EQ(out_ptr[i * 28 + j], b_ptr[idx_b]);
++idx_b;
} else {
PADDLE_ENFORCE_EQ(out_ptr[i * 28 + j], a_ptr[idx_a]);
++idx_a;
}
}
}
/**
* cast3:
* inputs:
* t_a.shape: [2, 3, 5]
* t_b.shape: [2, 3, 4]
* output:
* out.shape: [2, 3, 9]
*/
dim_a = paddle::framework::make_ddim({2, 3, 4});
dim_b = paddle::framework::make_ddim({2, 3, 5});
dim_out = paddle::framework::make_ddim({2, 3, 9});
input_a.Resize(dim_a);
input_b.Resize(dim_b);
out.Resize(dim_out);
if (paddle::platform::is_gpu_place(Place())) {
input_a_cpu.Resize(dim_a);
input_b_cpu.Resize(dim_b);
out_cpu.Resize(dim_out);
}
if (paddle::platform::is_gpu_place(Place())) {
a_ptr = input_a_cpu.data<int>();
b_ptr = input_b_cpu.data<int>();
} else {
a_ptr = input_a.data<int>();
b_ptr = input_b.data<int>();
}
for (int i = 0; i < 2 * 3 * 4; ++i) {
a_ptr[i] = i;
}
for (int i = 0; i < 2 * 3 * 5; ++i) {
b_ptr[i] = i;
}
if (paddle::platform::is_gpu_place(Place())) {
paddle::framework::TensorCopy(input_a_cpu, Place(), *context, &input_a);
paddle::framework::TensorCopy(input_b_cpu, Place(), *context, &input_b);
}
input.clear();
input.push_back(input_a);
input.push_back(input_b);
concat_functor(*context, input, 2, &out);
// check the dim of input_a, input_b
PADDLE_ENFORCE_EQ(input_a.dims(), dim_a);
PADDLE_ENFORCE_EQ(input_b.dims(), dim_b);
if (paddle::platform::is_gpu_place(Place())) {
paddle::framework::TensorCopy(out, paddle::platform::CPUPlace(), *context,
&out_cpu);
out_ptr = out_cpu.data<int>();
} else {
out_ptr = out.data<int>();
}
// check the data
cols = 4;
idx_a = 0, idx_b = 0;
for (int i = 0; i < 6; ++i) {
for (int j = 0; j < 9; ++j) {
if (j >= cols) {
PADDLE_ENFORCE_EQ(out_ptr[i * 9 + j], b_ptr[idx_b]);
++idx_b;
} else {
PADDLE_ENFORCE_EQ(out_ptr[i * 9 + j], a_ptr[idx_a]);
++idx_a;
}
}
}
/**
* cast4:
* inputs:
* axis = 1
* t_a.shape: [2, 3, 4]
* t_b.shape: [2, 3, 4]
* output:
* out.shape: [2, 6, 4]
*/
dim_a = paddle::framework::make_ddim({2, 3, 4});
dim_b = paddle::framework::make_ddim({2, 3, 4});
dim_out = paddle::framework::make_ddim({2, 6, 4});
input_a.Resize(dim_a);
input_b.Resize(dim_b);
out.Resize(dim_out);
if (paddle::platform::is_gpu_place(Place())) {
input_a_cpu.Resize(dim_a);
input_b_cpu.Resize(dim_b);
out_cpu.Resize(dim_out);
}
if (paddle::platform::is_gpu_place(Place())) {
a_ptr = input_a_cpu.data<int>();
b_ptr = input_b_cpu.data<int>();
} else {
a_ptr = input_a.data<int>();
b_ptr = input_b.data<int>();
}
for (int i = 0; i < 2 * 3 * 4; ++i) {
a_ptr[i] = i;
}
for (int i = 0; i < 2 * 3 * 4; ++i) {
b_ptr[i] = i;
}
if (paddle::platform::is_gpu_place(Place())) {
paddle::framework::TensorCopy(input_a_cpu, Place(), *context, &input_a);
paddle::framework::TensorCopy(input_b_cpu, Place(), *context, &input_b);
}
input.clear();
input.push_back(input_a);
input.push_back(input_b);
concat_functor(*context, input, 1, &out);
// check the dim of input_a, input_b
PADDLE_ENFORCE_EQ(input_a.dims(), dim_a);
PADDLE_ENFORCE_EQ(input_b.dims(), dim_b);
if (paddle::platform::is_gpu_place(Place())) {
paddle::framework::TensorCopy(out, paddle::platform::CPUPlace(), *context,
&out_cpu);
out_ptr = out_cpu.data<int>();
} else {
out_ptr = out.data<int>();
}
// check the data
cols = 12;
idx_a = 0, idx_b = 0;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 24; ++j) {
if (j >= cols) {
PADDLE_ENFORCE_EQ(out_ptr[i * 24 + j], b_ptr[idx_b]);
++idx_b;
} else {
PADDLE_ENFORCE_EQ(out_ptr[i * 24 + j], a_ptr[idx_a]);
++idx_a;
}
}
}
}
TEST(math, concat) {
testConcat<paddle::platform::CPUDeviceContext, paddle::platform::CPUPlace>();
#ifdef PADDLE_WITH_CUDA
testConcat<paddle::platform::CUDADeviceContext,
paddle::platform::CUDAPlace>();
#endif
}
<commit_msg>fix errors in concat_test<commit_after>/* Copyright (c) 2018 PaddlePaddle 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. */
#include "paddle/fluid/operators/math/concat.h"
#include <gtest/gtest.h>
#include <vector>
#include "paddle/fluid/framework/tensor_util.h"
template <typename DeviceContext, typename Place>
void testConcat() {
paddle::framework::Tensor input_a_cpu;
paddle::framework::Tensor input_b_cpu;
paddle::framework::Tensor out_cpu;
paddle::framework::Tensor input_a;
paddle::framework::Tensor input_b;
paddle::framework::Tensor out;
DeviceContext* context = new DeviceContext(Place());
// DeviceContext context(Place());
/**
* cast1:
* inputs:
* t_a.shape: [2, 3, 4]
* t_b.shape: [3, 3, 4]
* output:
* out.shape: [5, 3, 4]
*/
auto dim_a = paddle::framework::make_ddim({2, 3, 4});
auto dim_b = paddle::framework::make_ddim({3, 3, 4});
auto dim_out = paddle::framework::make_ddim({5, 3, 4});
input_a.mutable_data<int>(dim_a, Place());
input_b.mutable_data<int>(dim_b, Place());
out.mutable_data<int>(dim_out, Place());
if (paddle::platform::is_gpu_place(Place())) {
input_a_cpu.mutable_data<int>(dim_a, paddle::platform::CPUPlace());
input_b_cpu.mutable_data<int>(dim_b, paddle::platform::CPUPlace());
out_cpu.mutable_data<int>(dim_out, paddle::platform::CPUPlace());
}
int* a_ptr;
int* b_ptr;
if (paddle::platform::is_gpu_place(Place())) {
a_ptr = input_a_cpu.data<int>();
b_ptr = input_b_cpu.data<int>();
} else {
a_ptr = input_a.data<int>();
b_ptr = input_b.data<int>();
}
for (int i = 0; i < 2 * 3 * 4; ++i) {
a_ptr[i] = i;
}
for (int i = 0; i < 3 * 3 * 4; ++i) {
b_ptr[i] = i;
}
if (paddle::platform::is_gpu_place(Place())) {
paddle::framework::TensorCopySync(input_a_cpu, Place(), &input_a);
paddle::framework::TensorCopySync(input_b_cpu, Place(), &input_b);
}
std::vector<paddle::framework::Tensor> input;
input.push_back(input_a);
input.push_back(input_b);
paddle::operators::math::ConcatFunctor<DeviceContext, int> concat_functor;
concat_functor(*context, input, 0, &out);
// check the dim of input_a, input_b
PADDLE_ENFORCE_EQ(input_a.dims(), dim_a);
PADDLE_ENFORCE_EQ(input_b.dims(), dim_b);
int* out_ptr;
if (paddle::platform::is_gpu_place(Place())) {
paddle::framework::TensorCopySync(out, paddle::platform::CPUPlace(),
&out_cpu);
out_ptr = out_cpu.data<int>();
} else {
out_ptr = out.data<int>();
}
int cols = 2 * 3 * 4;
int idx_a = 0, idx_b = 0;
for (int j = 0; j < 5 * 3 * 4; ++j) {
if (j >= cols) {
PADDLE_ENFORCE_EQ(out_ptr[j], b_ptr[idx_b]);
++idx_b;
} else {
PADDLE_ENFORCE_EQ(out_ptr[j], a_ptr[idx_a]);
++idx_a;
}
}
//
/**
* cast2:
* inputs:
* t_a.shape: [2, 3, 4]
* t_b.shape: [2, 4, 4]
* output:
* out.shape: [2, 7, 4]
*/
dim_a = paddle::framework::make_ddim({2, 3, 4});
dim_b = paddle::framework::make_ddim({2, 4, 4});
dim_out = paddle::framework::make_ddim({2, 7, 4});
input_a.Resize(dim_a);
input_b.Resize(dim_b);
out.Resize(dim_out);
if (paddle::platform::is_gpu_place(Place())) {
input_a_cpu.Resize(dim_a);
input_b_cpu.Resize(dim_b);
out_cpu.Resize(dim_out);
}
if (paddle::platform::is_gpu_place(Place())) {
a_ptr = input_a_cpu.data<int>();
b_ptr = input_b_cpu.data<int>();
} else {
a_ptr = input_a.data<int>();
b_ptr = input_b.data<int>();
}
for (int i = 0; i < 2 * 3 * 4; ++i) {
a_ptr[i] = i;
}
for (int i = 0; i < 2 * 4 * 4; ++i) {
b_ptr[i] = i;
}
if (paddle::platform::is_gpu_place(Place())) {
paddle::framework::TensorCopySync(input_a_cpu, Place(), &input_a);
paddle::framework::TensorCopySync(input_b_cpu, Place(), &input_b);
}
input.clear();
input.push_back(input_a);
input.push_back(input_b);
concat_functor(*context, input, 1, &out);
// check the dim of input_a, input_b
PADDLE_ENFORCE_EQ(input_a.dims(), dim_a);
PADDLE_ENFORCE_EQ(input_b.dims(), dim_b);
if (paddle::platform::is_gpu_place(Place())) {
paddle::framework::TensorCopySync(out, paddle::platform::CPUPlace(),
&out_cpu);
out_ptr = out_cpu.data<int>();
} else {
out_ptr = out.data<int>();
}
cols = 3 * 4;
idx_a = 0, idx_b = 0;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 28; ++j) {
if (j >= cols) {
PADDLE_ENFORCE_EQ(out_ptr[i * 28 + j], b_ptr[idx_b]);
++idx_b;
} else {
PADDLE_ENFORCE_EQ(out_ptr[i * 28 + j], a_ptr[idx_a]);
++idx_a;
}
}
}
/**
* cast3:
* inputs:
* t_a.shape: [2, 3, 5]
* t_b.shape: [2, 3, 4]
* output:
* out.shape: [2, 3, 9]
*/
dim_a = paddle::framework::make_ddim({2, 3, 4});
dim_b = paddle::framework::make_ddim({2, 3, 5});
dim_out = paddle::framework::make_ddim({2, 3, 9});
input_a.Resize(dim_a);
input_b.Resize(dim_b);
out.Resize(dim_out);
if (paddle::platform::is_gpu_place(Place())) {
input_a_cpu.Resize(dim_a);
input_b_cpu.Resize(dim_b);
out_cpu.Resize(dim_out);
}
if (paddle::platform::is_gpu_place(Place())) {
a_ptr = input_a_cpu.data<int>();
b_ptr = input_b_cpu.data<int>();
} else {
a_ptr = input_a.data<int>();
b_ptr = input_b.data<int>();
}
for (int i = 0; i < 2 * 3 * 4; ++i) {
a_ptr[i] = i;
}
for (int i = 0; i < 2 * 3 * 5; ++i) {
b_ptr[i] = i;
}
if (paddle::platform::is_gpu_place(Place())) {
paddle::framework::TensorCopySync(input_a_cpu, Place(), &input_a);
paddle::framework::TensorCopySync(input_b_cpu, Place(), &input_b);
}
input.clear();
input.push_back(input_a);
input.push_back(input_b);
concat_functor(*context, input, 2, &out);
// check the dim of input_a, input_b
PADDLE_ENFORCE_EQ(input_a.dims(), dim_a);
PADDLE_ENFORCE_EQ(input_b.dims(), dim_b);
if (paddle::platform::is_gpu_place(Place())) {
paddle::framework::TensorCopySync(out, paddle::platform::CPUPlace(),
&out_cpu);
out_ptr = out_cpu.data<int>();
} else {
out_ptr = out.data<int>();
}
// check the data
cols = 4;
idx_a = 0, idx_b = 0;
for (int i = 0; i < 6; ++i) {
for (int j = 0; j < 9; ++j) {
if (j >= cols) {
PADDLE_ENFORCE_EQ(out_ptr[i * 9 + j], b_ptr[idx_b]);
++idx_b;
} else {
PADDLE_ENFORCE_EQ(out_ptr[i * 9 + j], a_ptr[idx_a]);
++idx_a;
}
}
}
/**
* cast4:
* inputs:
* axis = 1
* t_a.shape: [2, 3, 4]
* t_b.shape: [2, 3, 4]
* output:
* out.shape: [2, 6, 4]
*/
dim_a = paddle::framework::make_ddim({2, 3, 4});
dim_b = paddle::framework::make_ddim({2, 3, 4});
dim_out = paddle::framework::make_ddim({2, 6, 4});
input_a.Resize(dim_a);
input_b.Resize(dim_b);
out.Resize(dim_out);
if (paddle::platform::is_gpu_place(Place())) {
input_a_cpu.Resize(dim_a);
input_b_cpu.Resize(dim_b);
out_cpu.Resize(dim_out);
}
if (paddle::platform::is_gpu_place(Place())) {
a_ptr = input_a_cpu.data<int>();
b_ptr = input_b_cpu.data<int>();
} else {
a_ptr = input_a.data<int>();
b_ptr = input_b.data<int>();
}
for (int i = 0; i < 2 * 3 * 4; ++i) {
a_ptr[i] = i;
}
for (int i = 0; i < 2 * 3 * 4; ++i) {
b_ptr[i] = i;
}
if (paddle::platform::is_gpu_place(Place())) {
paddle::framework::TensorCopySync(input_a_cpu, Place(), &input_a);
paddle::framework::TensorCopySync(input_b_cpu, Place(), &input_b);
}
input.clear();
input.push_back(input_a);
input.push_back(input_b);
concat_functor(*context, input, 1, &out);
// check the dim of input_a, input_b
PADDLE_ENFORCE_EQ(input_a.dims(), dim_a);
PADDLE_ENFORCE_EQ(input_b.dims(), dim_b);
if (paddle::platform::is_gpu_place(Place())) {
paddle::framework::TensorCopySync(out, paddle::platform::CPUPlace(),
&out_cpu);
out_ptr = out_cpu.data<int>();
} else {
out_ptr = out.data<int>();
}
// check the data
cols = 12;
idx_a = 0, idx_b = 0;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 24; ++j) {
if (j >= cols) {
PADDLE_ENFORCE_EQ(out_ptr[i * 24 + j], b_ptr[idx_b]);
++idx_b;
} else {
PADDLE_ENFORCE_EQ(out_ptr[i * 24 + j], a_ptr[idx_a]);
++idx_a;
}
}
}
}
TEST(math, concat) {
testConcat<paddle::platform::CPUDeviceContext, paddle::platform::CPUPlace>();
#ifdef PADDLE_WITH_CUDA
testConcat<paddle::platform::CUDADeviceContext,
paddle::platform::CUDAPlace>();
#endif
}
<|endoftext|> |
<commit_before>// Copyright 2015-2020 Elviss Strazdins. All rights reserved.
#include "../core/Setup.h"
#include <algorithm>
#include <fstream>
#if defined(_WIN32)
# pragma push_macro("WIN32_LEAN_AND_MEAN")
# pragma push_macro("NOMINMAX")
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# ifndef NOMINMAX
# define NOMINMAX
# endif
# include <Windows.h>
# include <ShlObj.h>
# include <Shlwapi.h>
# pragma pop_macro("WIN32_LEAN_AND_MEAN")
# pragma pop_macro("NOMINMAX")
#elif defined(__APPLE__)
# include <TargetConditionals.h>
# include <objc/message.h>
# include <objc/NSObjCRuntime.h>
# include <CoreFoundation/CoreFoundation.h>
#elif defined(__ANDROID__)
# include "../core/android/EngineAndroid.hpp"
#elif defined(__linux__)
# include <pwd.h>
#endif
#include "FileSystem.hpp"
#include "Archive.hpp"
#include "../core/Engine.hpp"
#include "../utils/Log.hpp"
#if defined(__APPLE__)
# include "CfPointer.hpp"
#endif
namespace ouzel
{
namespace storage
{
FileSystem::FileSystem(Engine& initEngine):
engine(initEngine)
{
#if defined(_WIN32)
std::vector<WCHAR> buffer(MAX_PATH + 1);
for (;;)
{
HINSTANCE instance = GetModuleHandleW(nullptr);
if (!instance)
throw std::system_error(GetLastError(), std::system_category(), "Failed to get module handle");
if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size())))
throw std::system_error(GetLastError(), std::system_category(), "Failed to get module filename");
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
buffer.resize(buffer.size() * 2);
else
break;
}
const int bufferSize = WideCharToMultiByte(CP_UTF8, 0, buffer.data(), -1, nullptr, 0, nullptr, nullptr);
if (bufferSize == 0)
throw std::system_error(GetLastError(), std::system_category(), "Failed to convert wide char to UTF-8");
std::vector<char> appFilename(bufferSize);
if (WideCharToMultiByte(CP_UTF8, 0, buffer.data(), -1, appFilename.data(), bufferSize, nullptr, nullptr) == 0)
throw std::system_error(GetLastError(), std::system_category(), "Failed to convert wide char to UTF-8");
appPath = Path(appFilename.data()).getDirectory();
engine.log(Log::Level::Info) << "Application directory: " << appPath;
#elif defined(__APPLE__)
CFBundleRef bundle = CFBundleGetMainBundle();
if (!bundle)
throw std::runtime_error("Failed to get main bundle");
CfPointer<CFURLRef> relativePath = CFBundleCopyResourcesDirectoryURL(bundle);
if (!relativePath)
throw std::runtime_error("Failed to get resource directory");
CfPointer<CFURLRef> absolutePath = CFURLCopyAbsoluteURL(relativePath.get());
CfPointer<CFStringRef> path = CFURLCopyFileSystemPath(absolutePath.get(), kCFURLPOSIXPathStyle);
const CFIndex maximumSize = CFStringGetMaximumSizeOfFileSystemRepresentation(path.get());
std::vector<char> resourceDirectory(static_cast<std::size_t>(maximumSize));
const Boolean result = CFStringGetFileSystemRepresentation(path.get(), resourceDirectory.data(), maximumSize);
if (!result)
throw std::runtime_error("Failed to get resource directory");
appPath = resourceDirectory.data();
engine.log(Log::Level::Info) << "Application directory: " << appPath;
#elif defined(__ANDROID__)
// not available for Android
#elif defined(__linux__)
char executableDirectory[PATH_MAX];
ssize_t length;
if ((length = readlink("/proc/self/exe", executableDirectory, sizeof(executableDirectory) - 1)) == -1)
throw std::system_error(errno, std::system_category(), "Failed to get current directory");
executableDirectory[length] = '\0';
appPath = Path(executableDirectory).getDirectory();
engine.log(Log::Level::Info) << "Application directory: " << appPath;
#endif
}
Path FileSystem::getStorageDirectory(const bool user) const
{
#if defined(_WIN32)
WCHAR appDataPath[MAX_PATH];
HRESULT hr;
if (FAILED(hr = SHGetFolderPathW(nullptr, (user ? CSIDL_LOCAL_APPDATA : CSIDL_COMMON_APPDATA) | CSIDL_FLAG_CREATE, nullptr, SHGFP_TYPE_CURRENT, appDataPath)))
throw std::system_error(hr, std::system_category(), "Failed to get the path of the AppData directory");
const int appDataBufferSize = WideCharToMultiByte(CP_UTF8, 0, appDataPath, -1, nullptr, 0, nullptr, nullptr);
if (appDataBufferSize == 0)
throw std::system_error(GetLastError(), std::system_category(), "Failed to convert wide char to UTF-8");
std::vector<char> appDataBuffer(appDataBufferSize);
if (WideCharToMultiByte(CP_UTF8, 0, appDataPath, -1, appDataBuffer.data(), appDataBufferSize, nullptr, nullptr) == 0)
throw std::system_error(GetLastError(), std::system_category(), "Failed to convert wide char to UTF-8");
std::string path = appDataBuffer.data();
path += Path::directorySeparator + OUZEL_DEVELOPER_NAME;
if (!directoryExists(path))
{
const int bufferSize = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
if (bufferSize == 0)
throw std::system_error(GetLastError(), std::system_category(), "Failed to convert UTF-8 to wide char");
std::vector<WCHAR> buffer(bufferSize);
if (MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, buffer.data(), bufferSize) == 0)
throw std::system_error(GetLastError(), std::system_category(), "Failed to convert UTF-8 to wide char");
// relative paths longer than MAX_PATH are not supported
if (buffer.size() > MAX_PATH)
buffer.insert(buffer.begin(), {L'\\', L'\\', L'?', L'\\'});
const DWORD attributes = GetFileAttributesW(buffer.data());
if (attributes == INVALID_FILE_ATTRIBUTES)
{
if (!CreateDirectoryW(buffer.data(), nullptr))
throw std::system_error(GetLastError(), std::system_category(), "Failed to create directory " + path);
}
else if ((attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
throw std::runtime_error(path + " is not a directory");
}
path += Path::directorySeparator + OUZEL_APPLICATION_NAME;
if (!directoryExists(path))
{
const int bufferSize = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
if (bufferSize == 0)
throw std::system_error(GetLastError(), std::system_category(), "Failed to convert UTF-8 to wide char");
std::vector<WCHAR> buffer(bufferSize);
if (MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, buffer.data(), bufferSize) == 0)
throw std::system_error(GetLastError(), std::system_category(), "Failed to convert UTF-8 to wide char");
// relative paths longer than MAX_PATH are not supported
if (buffer.size() > MAX_PATH)
buffer.insert(buffer.begin(), {L'\\', L'\\', L'?', L'\\'});
const DWORD attributes = GetFileAttributesW(buffer.data());
if (attributes == INVALID_FILE_ATTRIBUTES)
{
if (!CreateDirectoryW(buffer.data(), nullptr))
throw std::system_error(GetLastError(), std::system_category(), "Failed to create directory " + path);
}
else if ((attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
throw std::runtime_error(path + " is not a directory");
}
return path;
#elif TARGET_OS_IOS || TARGET_OS_TV
id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager"));
constexpr NSUInteger NSDocumentDirectory = 9;
constexpr NSUInteger NSUserDomainMask = 1;
constexpr NSUInteger NSLocalDomainMask = 2;
id documentDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSDocumentDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil);
if (!documentDirectory)
throw std::runtime_error("Failed to get document directory");
id documentDirectoryString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(documentDirectory, sel_getUid("path"));
return reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(documentDirectoryString, sel_getUid("UTF8String"));
#elif TARGET_OS_MAC
id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager"));
constexpr NSUInteger NSApplicationSupportDirectory = 14;
constexpr NSUInteger NSUserDomainMask = 1;
constexpr NSUInteger NSLocalDomainMask = 2;
id applicationSupportDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSApplicationSupportDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil);
if (!applicationSupportDirectory)
throw std::runtime_error("Failed to get application support directory");
CFBundleRef bundle = CFBundleGetMainBundle();
CFStringRef identifier = CFBundleGetIdentifier(bundle);
if (!identifier)
identifier = CFSTR(OUZEL_DEVELOPER_NAME "." OUZEL_APPLICATION_NAME);
id path = reinterpret_cast<id (*)(id, SEL, CFStringRef)>(&objc_msgSend)(applicationSupportDirectory, sel_getUid("URLByAppendingPathComponent:"), identifier);
reinterpret_cast<void (*)(id, SEL, id, BOOL, id, id)>(&objc_msgSend)(fileManager, sel_getUid("createDirectoryAtURL:withIntermediateDirectories:attributes:error:"), path, YES, nil, nil);
id pathString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(path, sel_getUid("path"));
return reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(pathString, sel_getUid("UTF8String"));
#elif defined(__ANDROID__)
static_cast<void>(user);
EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);
return engineAndroid.getFilesDirectory();
#elif defined(__linux__)
std::string path;
const char* homeDirectory = getenv("XDG_DATA_HOME");
if (homeDirectory)
path = homeDirectory;
else
{
struct passwd pwent;
struct passwd* pwentp;
std::vector<char> buffer(1024);
int e;
while ((e = getpwuid_r(getuid(), &pwent, buffer.data(), buffer.size(), &pwentp)) == ERANGE)
buffer.resize(buffer.size() * 2);
if (e != 0)
throw std::runtime_error("Failed to get home directory");
else
path = pwent.pw_dir;
path += Path::directorySeparator + ".local";
if (!directoryExists(path))
if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1)
throw std::system_error(errno, std::system_category(), "Failed to create directory " + path);
path += Path::directorySeparator + "share";
if (!directoryExists(path))
if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1)
throw std::system_error(errno, std::system_category(), "Failed to create directory " + path);
}
path += Path::directorySeparator + OUZEL_DEVELOPER_NAME;
if (!directoryExists(path))
if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1)
throw std::system_error(errno, std::system_category(), "Failed to create directory " + path);
path += Path::directorySeparator + OUZEL_APPLICATION_NAME;
if (!directoryExists(path))
if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1)
throw std::system_error(errno, std::system_category(), "Failed to create directory " + path);
return path;
#else
return "";
#endif
}
std::vector<std::uint8_t> FileSystem::readFile(const Path& filename, const bool searchResources)
{
if (searchResources)
for (auto& archive : archives)
if (archive.second.fileExists(filename))
return archive.second.readFile(filename);
#if defined(__ANDROID__)
if (!Path(filename).isAbsolute())
{
EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);
AAsset* asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.c_str(), AASSET_MODE_STREAMING);
if (!asset)
throw std::runtime_error("Failed to open file " + filename);
std::vector<std::uint8_t> data;
std::uint8_t buffer[1024];
for (;;)
{
const int bytesRead = AAsset_read(asset, buffer, sizeof(buffer));
if (bytesRead < 0)
throw std::runtime_error("Failed to read from file");
else if (bytesRead == 0)
break;
data.insert(data.end(), buffer, buffer + bytesRead);
}
AAsset_close(asset);
return data;
}
#endif
const auto path = getPath(filename, searchResources);
// file does not exist
if (path.isEmpty())
throw std::runtime_error("Failed to find file " + std::string(filename));
std::ifstream f(path, std::ios::binary);
return {std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()};
}
bool FileSystem::resourceFileExists(const Path& filename) const
{
if (filename.isAbsolute())
return fileExists(filename);
else
{
Path result = appPath / filename;
if (fileExists(result))
return true;
else
for (const auto& path : resourcePaths)
{
if (path.isAbsolute()) // if resource path is absolute
result = path / filename;
else
result = appPath / path / filename;
if (fileExists(result))
return true;
}
return false;
}
}
bool FileSystem::directoryExists(const Path& dirname) const
{
#if defined(__ANDROID__)
EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);
AAssetDir* assetDir = AAssetManager_openDir(engineAndroid.getAssetManager(), dirname.getGeneric().c_str());
const bool exists = AAssetDir_getNextFileName(assetDir) != nullptr;
AAssetDir_close(assetDir);
if (exists) return true;
#endif
return dirname.isDirectory();
}
bool FileSystem::fileExists(const Path& filename) const
{
#if defined(__ANDROID__)
EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);
AAsset* asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.c_str(), AASSET_MODE_STREAMING);
if (asset)
{
AAsset_close(asset);
return true;
}
#endif
return filename.isRegular();
}
} // namespace storage
} // namespace ouzel
<commit_msg>Fix Android build<commit_after>// Copyright 2015-2020 Elviss Strazdins. All rights reserved.
#include "../core/Setup.h"
#include <algorithm>
#include <fstream>
#if defined(_WIN32)
# pragma push_macro("WIN32_LEAN_AND_MEAN")
# pragma push_macro("NOMINMAX")
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# ifndef NOMINMAX
# define NOMINMAX
# endif
# include <Windows.h>
# include <ShlObj.h>
# include <Shlwapi.h>
# pragma pop_macro("WIN32_LEAN_AND_MEAN")
# pragma pop_macro("NOMINMAX")
#elif defined(__APPLE__)
# include <TargetConditionals.h>
# include <objc/message.h>
# include <objc/NSObjCRuntime.h>
# include <CoreFoundation/CoreFoundation.h>
#elif defined(__ANDROID__)
# include "../core/android/EngineAndroid.hpp"
#elif defined(__linux__)
# include <pwd.h>
#endif
#include "FileSystem.hpp"
#include "Archive.hpp"
#include "../core/Engine.hpp"
#include "../utils/Log.hpp"
#if defined(__APPLE__)
# include "CfPointer.hpp"
#endif
namespace ouzel
{
namespace storage
{
FileSystem::FileSystem(Engine& initEngine):
engine(initEngine)
{
#if defined(_WIN32)
std::vector<WCHAR> buffer(MAX_PATH + 1);
for (;;)
{
HINSTANCE instance = GetModuleHandleW(nullptr);
if (!instance)
throw std::system_error(GetLastError(), std::system_category(), "Failed to get module handle");
if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size())))
throw std::system_error(GetLastError(), std::system_category(), "Failed to get module filename");
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
buffer.resize(buffer.size() * 2);
else
break;
}
const int bufferSize = WideCharToMultiByte(CP_UTF8, 0, buffer.data(), -1, nullptr, 0, nullptr, nullptr);
if (bufferSize == 0)
throw std::system_error(GetLastError(), std::system_category(), "Failed to convert wide char to UTF-8");
std::vector<char> appFilename(bufferSize);
if (WideCharToMultiByte(CP_UTF8, 0, buffer.data(), -1, appFilename.data(), bufferSize, nullptr, nullptr) == 0)
throw std::system_error(GetLastError(), std::system_category(), "Failed to convert wide char to UTF-8");
appPath = Path(appFilename.data()).getDirectory();
engine.log(Log::Level::Info) << "Application directory: " << appPath;
#elif defined(__APPLE__)
CFBundleRef bundle = CFBundleGetMainBundle();
if (!bundle)
throw std::runtime_error("Failed to get main bundle");
CfPointer<CFURLRef> relativePath = CFBundleCopyResourcesDirectoryURL(bundle);
if (!relativePath)
throw std::runtime_error("Failed to get resource directory");
CfPointer<CFURLRef> absolutePath = CFURLCopyAbsoluteURL(relativePath.get());
CfPointer<CFStringRef> path = CFURLCopyFileSystemPath(absolutePath.get(), kCFURLPOSIXPathStyle);
const CFIndex maximumSize = CFStringGetMaximumSizeOfFileSystemRepresentation(path.get());
std::vector<char> resourceDirectory(static_cast<std::size_t>(maximumSize));
const Boolean result = CFStringGetFileSystemRepresentation(path.get(), resourceDirectory.data(), maximumSize);
if (!result)
throw std::runtime_error("Failed to get resource directory");
appPath = resourceDirectory.data();
engine.log(Log::Level::Info) << "Application directory: " << appPath;
#elif defined(__ANDROID__)
// not available for Android
#elif defined(__linux__)
char executableDirectory[PATH_MAX];
ssize_t length;
if ((length = readlink("/proc/self/exe", executableDirectory, sizeof(executableDirectory) - 1)) == -1)
throw std::system_error(errno, std::system_category(), "Failed to get current directory");
executableDirectory[length] = '\0';
appPath = Path(executableDirectory).getDirectory();
engine.log(Log::Level::Info) << "Application directory: " << appPath;
#endif
}
Path FileSystem::getStorageDirectory(const bool user) const
{
#if defined(_WIN32)
WCHAR appDataPath[MAX_PATH];
HRESULT hr;
if (FAILED(hr = SHGetFolderPathW(nullptr, (user ? CSIDL_LOCAL_APPDATA : CSIDL_COMMON_APPDATA) | CSIDL_FLAG_CREATE, nullptr, SHGFP_TYPE_CURRENT, appDataPath)))
throw std::system_error(hr, std::system_category(), "Failed to get the path of the AppData directory");
const int appDataBufferSize = WideCharToMultiByte(CP_UTF8, 0, appDataPath, -1, nullptr, 0, nullptr, nullptr);
if (appDataBufferSize == 0)
throw std::system_error(GetLastError(), std::system_category(), "Failed to convert wide char to UTF-8");
std::vector<char> appDataBuffer(appDataBufferSize);
if (WideCharToMultiByte(CP_UTF8, 0, appDataPath, -1, appDataBuffer.data(), appDataBufferSize, nullptr, nullptr) == 0)
throw std::system_error(GetLastError(), std::system_category(), "Failed to convert wide char to UTF-8");
std::string path = appDataBuffer.data();
path += Path::directorySeparator + OUZEL_DEVELOPER_NAME;
if (!directoryExists(path))
{
const int bufferSize = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
if (bufferSize == 0)
throw std::system_error(GetLastError(), std::system_category(), "Failed to convert UTF-8 to wide char");
std::vector<WCHAR> buffer(bufferSize);
if (MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, buffer.data(), bufferSize) == 0)
throw std::system_error(GetLastError(), std::system_category(), "Failed to convert UTF-8 to wide char");
// relative paths longer than MAX_PATH are not supported
if (buffer.size() > MAX_PATH)
buffer.insert(buffer.begin(), {L'\\', L'\\', L'?', L'\\'});
const DWORD attributes = GetFileAttributesW(buffer.data());
if (attributes == INVALID_FILE_ATTRIBUTES)
{
if (!CreateDirectoryW(buffer.data(), nullptr))
throw std::system_error(GetLastError(), std::system_category(), "Failed to create directory " + path);
}
else if ((attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
throw std::runtime_error(path + " is not a directory");
}
path += Path::directorySeparator + OUZEL_APPLICATION_NAME;
if (!directoryExists(path))
{
const int bufferSize = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
if (bufferSize == 0)
throw std::system_error(GetLastError(), std::system_category(), "Failed to convert UTF-8 to wide char");
std::vector<WCHAR> buffer(bufferSize);
if (MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, buffer.data(), bufferSize) == 0)
throw std::system_error(GetLastError(), std::system_category(), "Failed to convert UTF-8 to wide char");
// relative paths longer than MAX_PATH are not supported
if (buffer.size() > MAX_PATH)
buffer.insert(buffer.begin(), {L'\\', L'\\', L'?', L'\\'});
const DWORD attributes = GetFileAttributesW(buffer.data());
if (attributes == INVALID_FILE_ATTRIBUTES)
{
if (!CreateDirectoryW(buffer.data(), nullptr))
throw std::system_error(GetLastError(), std::system_category(), "Failed to create directory " + path);
}
else if ((attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
throw std::runtime_error(path + " is not a directory");
}
return path;
#elif TARGET_OS_IOS || TARGET_OS_TV
id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager"));
constexpr NSUInteger NSDocumentDirectory = 9;
constexpr NSUInteger NSUserDomainMask = 1;
constexpr NSUInteger NSLocalDomainMask = 2;
id documentDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSDocumentDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil);
if (!documentDirectory)
throw std::runtime_error("Failed to get document directory");
id documentDirectoryString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(documentDirectory, sel_getUid("path"));
return reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(documentDirectoryString, sel_getUid("UTF8String"));
#elif TARGET_OS_MAC
id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager"));
constexpr NSUInteger NSApplicationSupportDirectory = 14;
constexpr NSUInteger NSUserDomainMask = 1;
constexpr NSUInteger NSLocalDomainMask = 2;
id applicationSupportDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSApplicationSupportDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil);
if (!applicationSupportDirectory)
throw std::runtime_error("Failed to get application support directory");
CFBundleRef bundle = CFBundleGetMainBundle();
CFStringRef identifier = CFBundleGetIdentifier(bundle);
if (!identifier)
identifier = CFSTR(OUZEL_DEVELOPER_NAME "." OUZEL_APPLICATION_NAME);
id path = reinterpret_cast<id (*)(id, SEL, CFStringRef)>(&objc_msgSend)(applicationSupportDirectory, sel_getUid("URLByAppendingPathComponent:"), identifier);
reinterpret_cast<void (*)(id, SEL, id, BOOL, id, id)>(&objc_msgSend)(fileManager, sel_getUid("createDirectoryAtURL:withIntermediateDirectories:attributes:error:"), path, YES, nil, nil);
id pathString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(path, sel_getUid("path"));
return reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(pathString, sel_getUid("UTF8String"));
#elif defined(__ANDROID__)
static_cast<void>(user);
EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);
return engineAndroid.getFilesDirectory();
#elif defined(__linux__)
std::string path;
const char* homeDirectory = getenv("XDG_DATA_HOME");
if (homeDirectory)
path = homeDirectory;
else
{
struct passwd pwent;
struct passwd* pwentp;
std::vector<char> buffer(1024);
int e;
while ((e = getpwuid_r(getuid(), &pwent, buffer.data(), buffer.size(), &pwentp)) == ERANGE)
buffer.resize(buffer.size() * 2);
if (e != 0)
throw std::runtime_error("Failed to get home directory");
else
path = pwent.pw_dir;
path += Path::directorySeparator + ".local";
if (!directoryExists(path))
if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1)
throw std::system_error(errno, std::system_category(), "Failed to create directory " + path);
path += Path::directorySeparator + "share";
if (!directoryExists(path))
if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1)
throw std::system_error(errno, std::system_category(), "Failed to create directory " + path);
}
path += Path::directorySeparator + OUZEL_DEVELOPER_NAME;
if (!directoryExists(path))
if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1)
throw std::system_error(errno, std::system_category(), "Failed to create directory " + path);
path += Path::directorySeparator + OUZEL_APPLICATION_NAME;
if (!directoryExists(path))
if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1)
throw std::system_error(errno, std::system_category(), "Failed to create directory " + path);
return path;
#else
return "";
#endif
}
std::vector<std::uint8_t> FileSystem::readFile(const Path& filename, const bool searchResources)
{
if (searchResources)
for (auto& archive : archives)
if (archive.second.fileExists(filename))
return archive.second.readFile(filename);
#if defined(__ANDROID__)
if (!Path(filename).isAbsolute())
{
EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);
AAsset* asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.getGeneric().c_str(), AASSET_MODE_STREAMING);
if (!asset)
throw std::runtime_error("Failed to open file " + filename);
std::vector<std::uint8_t> data;
std::uint8_t buffer[1024];
for (;;)
{
const int bytesRead = AAsset_read(asset, buffer, sizeof(buffer));
if (bytesRead < 0)
throw std::runtime_error("Failed to read from file");
else if (bytesRead == 0)
break;
data.insert(data.end(), buffer, buffer + bytesRead);
}
AAsset_close(asset);
return data;
}
#endif
const auto path = getPath(filename, searchResources);
// file does not exist
if (path.isEmpty())
throw std::runtime_error("Failed to find file " + std::string(filename));
std::ifstream f(path, std::ios::binary);
return {std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()};
}
bool FileSystem::resourceFileExists(const Path& filename) const
{
if (filename.isAbsolute())
return fileExists(filename);
else
{
Path result = appPath / filename;
if (fileExists(result))
return true;
else
for (const auto& path : resourcePaths)
{
if (path.isAbsolute()) // if resource path is absolute
result = path / filename;
else
result = appPath / path / filename;
if (fileExists(result))
return true;
}
return false;
}
}
bool FileSystem::directoryExists(const Path& dirname) const
{
#if defined(__ANDROID__)
EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);
AAssetDir* assetDir = AAssetManager_openDir(engineAndroid.getAssetManager(), dirname.getGeneric().c_str());
const bool exists = AAssetDir_getNextFileName(assetDir) != nullptr;
AAssetDir_close(assetDir);
if (exists) return true;
#endif
return dirname.isDirectory();
}
bool FileSystem::fileExists(const Path& filename) const
{
#if defined(__ANDROID__)
EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);
AAsset* asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.c_str(), AASSET_MODE_STREAMING);
if (asset)
{
AAsset_close(asset);
return true;
}
#endif
return filename.isRegular();
}
} // namespace storage
} // namespace ouzel
<|endoftext|> |
<commit_before>#include "chainerx/float16.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <vector>
#include <gtest/gtest.h>
namespace chainerx {
namespace {
bool IsNan(Float16 x) {
uint16_t exp = x.data() & 0x7c00;
uint16_t frac = x.data() & 0x03ff;
return exp == 0x7c00 && frac != 0x0000;
}
// Checks if `d` is equal to FromFloat16(ToFloat16(d)) with tolerance `tol`.
// This function cannot take NaN as a parameter. The cast of NaN is tested in `Float16Nan`.
void CheckToFloat16FromFloat16Near(double d, double tol) {
Float16 h{d};
Float16 f{static_cast<float>(d)};
EXPECT_EQ(h.data(), f.data());
float f_result = static_cast<float>(h);
double d_result = static_cast<double>(h);
ASSERT_FALSE(std::isnan(d));
EXPECT_FALSE(std::isnan(f_result));
EXPECT_FALSE(std::isnan(d_result));
EXPECT_FALSE(IsNan(h));
if (std::isinf(d)) {
// Signed inf
EXPECT_EQ(d, f_result);
EXPECT_EQ(d, d_result);
} else {
// Absolute error or relative error should be less or equal to tol.
tol = std::max(tol, tol * std::abs(d));
EXPECT_NEAR(d, f_result, tol);
EXPECT_NEAR(d, d_result, tol);
}
}
// Checks if `h` is equal to ToFloat16(FromFloat16(h)) exactly.
// This function cannot take NaN as a parameter. The cast of NaN is tested in `Float16Nan`.
void CheckFromFloat16ToFloat16Eq(Float16 h) {
float f = static_cast<float>(h);
double d = static_cast<double>(h);
EXPECT_EQ(d, static_cast<double>(f));
ASSERT_FALSE(IsNan(h));
EXPECT_FALSE(std::isnan(f));
EXPECT_FALSE(std::isnan(d));
EXPECT_EQ(h.data(), Float16{f}.data());
EXPECT_EQ(h.data(), Float16{d}.data());
}
TEST(NativeFloat16Test, Float16Zero) {
EXPECT_EQ(Float16{float{0.0}}.data(), 0x0000);
EXPECT_EQ(Float16{float{-0.0}}.data(), 0x8000);
EXPECT_EQ(Float16{double{0.0}}.data(), 0x0000);
EXPECT_EQ(Float16{double{-0.0}}.data(), 0x8000);
EXPECT_EQ(static_cast<float>(Float16::FromData(0x0000)), 0.0);
EXPECT_EQ(static_cast<float>(Float16::FromData(0x8000)), -0.0);
EXPECT_EQ(static_cast<double>(Float16::FromData(0x0000)), 0.0);
EXPECT_EQ(static_cast<double>(Float16::FromData(0x8000)), -0.0);
// Checks if the value is casted to 0.0 or -0.0
EXPECT_EQ(1 / static_cast<float>(Float16::FromData(0x0000)), std::numeric_limits<float>::infinity());
EXPECT_EQ(1 / static_cast<float>(Float16::FromData(0x8000)), -std::numeric_limits<float>::infinity());
EXPECT_EQ(1 / static_cast<double>(Float16::FromData(0x0000)), std::numeric_limits<float>::infinity());
EXPECT_EQ(1 / static_cast<double>(Float16::FromData(0x8000)), -std::numeric_limits<float>::infinity());
}
TEST(NativeFloat16Test, Float16Normalized) {
for (double x = 1e-3; x < 1e3; x *= 1.01) { // NOLINT(clang-analyzer-security.FloatLoopCounter,cert-flp30-c)
EXPECT_NE(Float16{x}.data() & 0x7c00, 0);
CheckToFloat16FromFloat16Near(x, 1e-3);
CheckToFloat16FromFloat16Near(-x, 1e-3);
}
for (uint16_t bit = 0x0400; bit < 0x7c00; ++bit) {
CheckFromFloat16ToFloat16Eq(Float16::FromData(bit | 0x0000));
CheckFromFloat16ToFloat16Eq(Float16::FromData(bit | 0x8000));
}
}
TEST(NativeFloat16Test, Float16Denormalized) {
for (double x = 1e-7; x < 1e-5; x += 1e-7) { // NOLINT(clang-analyzer-security.FloatLoopCounter,cert-flp30-c)
// Check if the underflow gap around zero is filled with denormal number.
EXPECT_EQ(Float16{x}.data() & 0x7c00, 0x0000);
EXPECT_NE(Float16{x}.data() & 0x03ff, 0x0000);
CheckToFloat16FromFloat16Near(x, 1e-7);
CheckToFloat16FromFloat16Near(-x, 1e-7);
}
for (uint16_t bit = 0x0000; bit < 0x0400; ++bit) {
CheckFromFloat16ToFloat16Eq(Float16::FromData(bit | 0x0000));
CheckFromFloat16ToFloat16Eq(Float16::FromData(bit | 0x8000));
}
}
TEST(NativeFloat16Test, Float16Inf) {
EXPECT_EQ(Float16{std::numeric_limits<float>::infinity()}.data(), 0x7c00);
EXPECT_EQ(Float16{-std::numeric_limits<float>::infinity()}.data(), 0xfc00);
EXPECT_EQ(Float16{std::numeric_limits<double>::infinity()}.data(), 0x7c00);
EXPECT_EQ(Float16{-std::numeric_limits<double>::infinity()}.data(), 0xfc00);
EXPECT_EQ(std::numeric_limits<float>::infinity(), static_cast<float>(Float16::FromData(0x7c00)));
EXPECT_EQ(-std::numeric_limits<float>::infinity(), static_cast<float>(Float16::FromData(0xfc00)));
EXPECT_EQ(std::numeric_limits<double>::infinity(), static_cast<double>(Float16::FromData(0x7c00)));
EXPECT_EQ(-std::numeric_limits<double>::infinity(), static_cast<double>(Float16::FromData(0xfc00)));
}
TEST(NativeFloat16Test, Float16Nan) {
for (uint16_t bit = 0x7c01; bit < 0x8000; ++bit) {
EXPECT_TRUE(std::isnan(static_cast<float>(Float16::FromData(bit | 0x0000))));
EXPECT_TRUE(std::isnan(static_cast<float>(Float16::FromData(bit | 0x8000))));
EXPECT_TRUE(std::isnan(static_cast<double>(Float16::FromData(bit | 0x0000))));
EXPECT_TRUE(std::isnan(static_cast<double>(Float16::FromData(bit | 0x8000))));
}
EXPECT_TRUE(IsNan(Float16{float{NAN}}));
EXPECT_TRUE(IsNan(Float16{double{NAN}}));
}
// Get the partial set of all Float16 values for reduction of test execution time.
// The returned list includes the all values whose trailing 8 digits are `0b00000000` or `0b01010101`.
// This list includes all special values (e.g. signed zero, infinity) and some of normalized/denormalize numbers and NaN.
std::vector<Float16> GetFloat16Values() {
std::vector<Float16> values;
values.reserve(1 << 9);
// Use uint32_t instead of uint16_t to avoid overflow
for (uint32_t bit = 0x0000; bit <= 0xffff; bit += 0x0100) {
values.emplace_back(Float16::FromData(bit | 0x0000));
values.emplace_back(Float16::FromData(bit | 0x0055));
}
return values;
}
// Checks if `l` is equal to `r` or both of them are NaN.
void ExpectEqFloat16(Float16 l, Float16 r) {
if (IsNan(l) && IsNan(r)) {
return;
}
EXPECT_EQ(l.data(), r.data());
}
TEST(NativeFloat16Test, Float16Neg) {
// Use uint32_t instead of uint16_t to avoid overflow
for (uint32_t bit = 0x0000; bit <= 0xffff; ++bit) {
Float16 x = Float16::FromData(bit);
Float16 expected{-static_cast<double>(x)};
ExpectEqFloat16(expected, -x);
}
}
TEST(NativeFloat16Test, Float16Add) {
for (Float16 x : GetFloat16Values()) {
for (Float16 y : GetFloat16Values()) {
Float16 expected{static_cast<double>(x) + static_cast<double>(y)};
ExpectEqFloat16(expected, x + y);
ExpectEqFloat16(expected, y + x);
}
}
}
TEST(NativeFloat16Test, Float16Subtract) {
for (Float16 x : GetFloat16Values()) {
for (Float16 y : GetFloat16Values()) {
Float16 expected{static_cast<double>(x) - static_cast<double>(y)};
ExpectEqFloat16(expected, x - y);
}
}
}
TEST(NativeFloat16Test, Float16Multiply) {
for (Float16 x : GetFloat16Values()) {
for (Float16 y : GetFloat16Values()) {
Float16 expected{static_cast<double>(x) * static_cast<double>(y)};
ExpectEqFloat16(expected, x * y);
ExpectEqFloat16(expected, y * x);
EXPECT_EQ(expected.data(), (x * y).data());
}
}
}
TEST(NativeFloat16Test, Float16Divide) {
for (Float16 x : GetFloat16Values()) {
for (Float16 y : GetFloat16Values()) {
Float16 expected{static_cast<double>(x) / static_cast<double>(y)};
ExpectEqFloat16(expected, x / y);
}
}
}
TEST(NativeFloat16Test, Float16AddI) {
for (Float16 x : GetFloat16Values()) {
for (Float16 y : GetFloat16Values()) {
Float16 expected{static_cast<double>(y) + static_cast<double>(x)};
Float16 z = (y += x);
ExpectEqFloat16(expected, y);
ExpectEqFloat16(expected, z);
}
}
}
TEST(NativeFloat16Test, Float16SubtractI) {
for (Float16 x : GetFloat16Values()) {
for (Float16 y : GetFloat16Values()) {
Float16 expected{static_cast<double>(y) - static_cast<double>(x)};
Float16 z = y -= x;
ExpectEqFloat16(expected, y);
ExpectEqFloat16(expected, z);
}
}
}
TEST(NativeFloat16Test, Float16MultiplyI) {
for (Float16 x : GetFloat16Values()) {
for (Float16 y : GetFloat16Values()) {
Float16 expected{static_cast<double>(y) * static_cast<double>(x)};
Float16 z = y *= x;
ExpectEqFloat16(expected, y);
ExpectEqFloat16(expected, z);
}
}
}
TEST(NativeFloat16Test, Float16DivideI) {
for (Float16 x : GetFloat16Values()) {
for (Float16 y : GetFloat16Values()) {
Float16 expected{static_cast<double>(y) / static_cast<double>(x)};
Float16 z = y /= x;
ExpectEqFloat16(expected, y);
ExpectEqFloat16(expected, z);
}
}
}
TEST(NativeFloat16Test, FloatComparison) {
for (Float16 x : GetFloat16Values()) {
for (Float16 y : GetFloat16Values()) {
#define run_compare_check(op) \
do { \
EXPECT_EQ(static_cast<double>(x) op static_cast<double>(y), x op y); \
EXPECT_EQ(static_cast<double>(y) op static_cast<double>(x), y op x); \
} while (false)
run_compare_check(==);
run_compare_check(!=);
run_compare_check(<);
run_compare_check(>);
run_compare_check(<=);
run_compare_check(>=);
#undef run_compare_check
}
}
}
} // namespace
} // namespace chainerx
<commit_msg>Change macro name according to naming convension<commit_after>#include "chainerx/float16.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <vector>
#include <gtest/gtest.h>
namespace chainerx {
namespace {
bool IsNan(Float16 x) {
uint16_t exp = x.data() & 0x7c00;
uint16_t frac = x.data() & 0x03ff;
return exp == 0x7c00 && frac != 0x0000;
}
// Checks if `d` is equal to FromFloat16(ToFloat16(d)) with tolerance `tol`.
// This function cannot take NaN as a parameter. The cast of NaN is tested in `Float16Nan`.
void CheckToFloat16FromFloat16Near(double d, double tol) {
Float16 h{d};
Float16 f{static_cast<float>(d)};
EXPECT_EQ(h.data(), f.data());
float f_result = static_cast<float>(h);
double d_result = static_cast<double>(h);
ASSERT_FALSE(std::isnan(d));
EXPECT_FALSE(std::isnan(f_result));
EXPECT_FALSE(std::isnan(d_result));
EXPECT_FALSE(IsNan(h));
if (std::isinf(d)) {
// Signed inf
EXPECT_EQ(d, f_result);
EXPECT_EQ(d, d_result);
} else {
// Absolute error or relative error should be less or equal to tol.
tol = std::max(tol, tol * std::abs(d));
EXPECT_NEAR(d, f_result, tol);
EXPECT_NEAR(d, d_result, tol);
}
}
// Checks if `h` is equal to ToFloat16(FromFloat16(h)) exactly.
// This function cannot take NaN as a parameter. The cast of NaN is tested in `Float16Nan`.
void CheckFromFloat16ToFloat16Eq(Float16 h) {
float f = static_cast<float>(h);
double d = static_cast<double>(h);
EXPECT_EQ(d, static_cast<double>(f));
ASSERT_FALSE(IsNan(h));
EXPECT_FALSE(std::isnan(f));
EXPECT_FALSE(std::isnan(d));
EXPECT_EQ(h.data(), Float16{f}.data());
EXPECT_EQ(h.data(), Float16{d}.data());
}
TEST(NativeFloat16Test, Float16Zero) {
EXPECT_EQ(Float16{float{0.0}}.data(), 0x0000);
EXPECT_EQ(Float16{float{-0.0}}.data(), 0x8000);
EXPECT_EQ(Float16{double{0.0}}.data(), 0x0000);
EXPECT_EQ(Float16{double{-0.0}}.data(), 0x8000);
EXPECT_EQ(static_cast<float>(Float16::FromData(0x0000)), 0.0);
EXPECT_EQ(static_cast<float>(Float16::FromData(0x8000)), -0.0);
EXPECT_EQ(static_cast<double>(Float16::FromData(0x0000)), 0.0);
EXPECT_EQ(static_cast<double>(Float16::FromData(0x8000)), -0.0);
// Checks if the value is casted to 0.0 or -0.0
EXPECT_EQ(1 / static_cast<float>(Float16::FromData(0x0000)), std::numeric_limits<float>::infinity());
EXPECT_EQ(1 / static_cast<float>(Float16::FromData(0x8000)), -std::numeric_limits<float>::infinity());
EXPECT_EQ(1 / static_cast<double>(Float16::FromData(0x0000)), std::numeric_limits<float>::infinity());
EXPECT_EQ(1 / static_cast<double>(Float16::FromData(0x8000)), -std::numeric_limits<float>::infinity());
}
TEST(NativeFloat16Test, Float16Normalized) {
for (double x = 1e-3; x < 1e3; x *= 1.01) { // NOLINT(clang-analyzer-security.FloatLoopCounter,cert-flp30-c)
EXPECT_NE(Float16{x}.data() & 0x7c00, 0);
CheckToFloat16FromFloat16Near(x, 1e-3);
CheckToFloat16FromFloat16Near(-x, 1e-3);
}
for (uint16_t bit = 0x0400; bit < 0x7c00; ++bit) {
CheckFromFloat16ToFloat16Eq(Float16::FromData(bit | 0x0000));
CheckFromFloat16ToFloat16Eq(Float16::FromData(bit | 0x8000));
}
}
TEST(NativeFloat16Test, Float16Denormalized) {
for (double x = 1e-7; x < 1e-5; x += 1e-7) { // NOLINT(clang-analyzer-security.FloatLoopCounter,cert-flp30-c)
// Check if the underflow gap around zero is filled with denormal number.
EXPECT_EQ(Float16{x}.data() & 0x7c00, 0x0000);
EXPECT_NE(Float16{x}.data() & 0x03ff, 0x0000);
CheckToFloat16FromFloat16Near(x, 1e-7);
CheckToFloat16FromFloat16Near(-x, 1e-7);
}
for (uint16_t bit = 0x0000; bit < 0x0400; ++bit) {
CheckFromFloat16ToFloat16Eq(Float16::FromData(bit | 0x0000));
CheckFromFloat16ToFloat16Eq(Float16::FromData(bit | 0x8000));
}
}
TEST(NativeFloat16Test, Float16Inf) {
EXPECT_EQ(Float16{std::numeric_limits<float>::infinity()}.data(), 0x7c00);
EXPECT_EQ(Float16{-std::numeric_limits<float>::infinity()}.data(), 0xfc00);
EXPECT_EQ(Float16{std::numeric_limits<double>::infinity()}.data(), 0x7c00);
EXPECT_EQ(Float16{-std::numeric_limits<double>::infinity()}.data(), 0xfc00);
EXPECT_EQ(std::numeric_limits<float>::infinity(), static_cast<float>(Float16::FromData(0x7c00)));
EXPECT_EQ(-std::numeric_limits<float>::infinity(), static_cast<float>(Float16::FromData(0xfc00)));
EXPECT_EQ(std::numeric_limits<double>::infinity(), static_cast<double>(Float16::FromData(0x7c00)));
EXPECT_EQ(-std::numeric_limits<double>::infinity(), static_cast<double>(Float16::FromData(0xfc00)));
}
TEST(NativeFloat16Test, Float16Nan) {
for (uint16_t bit = 0x7c01; bit < 0x8000; ++bit) {
EXPECT_TRUE(std::isnan(static_cast<float>(Float16::FromData(bit | 0x0000))));
EXPECT_TRUE(std::isnan(static_cast<float>(Float16::FromData(bit | 0x8000))));
EXPECT_TRUE(std::isnan(static_cast<double>(Float16::FromData(bit | 0x0000))));
EXPECT_TRUE(std::isnan(static_cast<double>(Float16::FromData(bit | 0x8000))));
}
EXPECT_TRUE(IsNan(Float16{float{NAN}}));
EXPECT_TRUE(IsNan(Float16{double{NAN}}));
}
// Get the partial set of all Float16 values for reduction of test execution time.
// The returned list includes the all values whose trailing 8 digits are `0b00000000` or `0b01010101`.
// This list includes all special values (e.g. signed zero, infinity) and some of normalized/denormalize numbers and NaN.
std::vector<Float16> GetFloat16Values() {
std::vector<Float16> values;
values.reserve(1 << 9);
// Use uint32_t instead of uint16_t to avoid overflow
for (uint32_t bit = 0x0000; bit <= 0xffff; bit += 0x0100) {
values.emplace_back(Float16::FromData(bit | 0x0000));
values.emplace_back(Float16::FromData(bit | 0x0055));
}
return values;
}
// Checks if `l` is equal to `r` or both of them are NaN.
void ExpectEqFloat16(Float16 l, Float16 r) {
if (IsNan(l) && IsNan(r)) {
return;
}
EXPECT_EQ(l.data(), r.data());
}
TEST(NativeFloat16Test, Float16Neg) {
// Use uint32_t instead of uint16_t to avoid overflow
for (uint32_t bit = 0x0000; bit <= 0xffff; ++bit) {
Float16 x = Float16::FromData(bit);
Float16 expected{-static_cast<double>(x)};
ExpectEqFloat16(expected, -x);
}
}
TEST(NativeFloat16Test, Float16Add) {
for (Float16 x : GetFloat16Values()) {
for (Float16 y : GetFloat16Values()) {
Float16 expected{static_cast<double>(x) + static_cast<double>(y)};
ExpectEqFloat16(expected, x + y);
ExpectEqFloat16(expected, y + x);
}
}
}
TEST(NativeFloat16Test, Float16Subtract) {
for (Float16 x : GetFloat16Values()) {
for (Float16 y : GetFloat16Values()) {
Float16 expected{static_cast<double>(x) - static_cast<double>(y)};
ExpectEqFloat16(expected, x - y);
}
}
}
TEST(NativeFloat16Test, Float16Multiply) {
for (Float16 x : GetFloat16Values()) {
for (Float16 y : GetFloat16Values()) {
Float16 expected{static_cast<double>(x) * static_cast<double>(y)};
ExpectEqFloat16(expected, x * y);
ExpectEqFloat16(expected, y * x);
EXPECT_EQ(expected.data(), (x * y).data());
}
}
}
TEST(NativeFloat16Test, Float16Divide) {
for (Float16 x : GetFloat16Values()) {
for (Float16 y : GetFloat16Values()) {
Float16 expected{static_cast<double>(x) / static_cast<double>(y)};
ExpectEqFloat16(expected, x / y);
}
}
}
TEST(NativeFloat16Test, Float16AddI) {
for (Float16 x : GetFloat16Values()) {
for (Float16 y : GetFloat16Values()) {
Float16 expected{static_cast<double>(y) + static_cast<double>(x)};
Float16 z = (y += x);
ExpectEqFloat16(expected, y);
ExpectEqFloat16(expected, z);
}
}
}
TEST(NativeFloat16Test, Float16SubtractI) {
for (Float16 x : GetFloat16Values()) {
for (Float16 y : GetFloat16Values()) {
Float16 expected{static_cast<double>(y) - static_cast<double>(x)};
Float16 z = y -= x;
ExpectEqFloat16(expected, y);
ExpectEqFloat16(expected, z);
}
}
}
TEST(NativeFloat16Test, Float16MultiplyI) {
for (Float16 x : GetFloat16Values()) {
for (Float16 y : GetFloat16Values()) {
Float16 expected{static_cast<double>(y) * static_cast<double>(x)};
Float16 z = y *= x;
ExpectEqFloat16(expected, y);
ExpectEqFloat16(expected, z);
}
}
}
TEST(NativeFloat16Test, Float16DivideI) {
for (Float16 x : GetFloat16Values()) {
for (Float16 y : GetFloat16Values()) {
Float16 expected{static_cast<double>(y) / static_cast<double>(x)};
Float16 z = y /= x;
ExpectEqFloat16(expected, y);
ExpectEqFloat16(expected, z);
}
}
}
TEST(NativeFloat16Test, FloatComparison) {
for (Float16 x : GetFloat16Values()) {
for (Float16 y : GetFloat16Values()) {
#define CHECK_COMPARISION_OPERATOR(op) \
{ \
EXPECT_EQ(static_cast<double>(x) op static_cast<double>(y), x op y); \
EXPECT_EQ(static_cast<double>(y) op static_cast<double>(x), y op x); \
};
CHECK_COMPARISION_OPERATOR(==);
CHECK_COMPARISION_OPERATOR(!=);
CHECK_COMPARISION_OPERATOR(<);
CHECK_COMPARISION_OPERATOR(>);
CHECK_COMPARISION_OPERATOR(<=);
CHECK_COMPARISION_OPERATOR(>=);
#undef CHECK_COMPARISION_OPERATOR
}
}
}
} // namespace
} // namespace chainerx
<|endoftext|> |
<commit_before><commit_msg>Add trace events for mouse capture logic in WebViewImpl<commit_after><|endoftext|> |
<commit_before>//
// Created by Vitali Kurlovich on 4/4/16.
//
#ifndef RMVECTORMATH_TQUATERNION_DEF_HPP
#define RMVECTORMATH_TQUATERNION_DEF_HPP
#include "../../common/common.hpp"
#include "vector/TVector3.hpp"
#include "vector/TVector4.hpp"
namespace rmmath {
namespace complex {
template<typename T>
struct TQuaternion {
union {
struct {
T w, i, j, k;
};
struct {
T re;
vector::TVector3<T> im;
};
vector::TVector4<T> wijk;
};
constexpr
TQuaternion( const T w = 0, const T i = 0, const T j = 0, const T k = 0 ) noexcept
: w(w), i(i), j(j), k(k)
{}
constexpr
TQuaternion( const T w, const vector::TVector3<T>& vec ) noexcept
: re(w), im(vec)
{}
constexpr
TQuaternion( const vector::TVector3<T>& vec, const T w = 0 ) noexcept
: re(w), im(vec)
{}
static const TQuaternion<T>& zero() {
static TQuaternion<T> zero;
return zero;
}
static const TQuaternion<T>& identity() {
static TQuaternion<T> identity(1, 0, 0, 0);
return identity;
}
};
}
template <typename T>
constexpr bool equal(const complex::TQuaternion<T> &a, const complex::TQuaternion<T> &b) noexcept {
return &a == &b ||
(equal<T>(a.w, b.w) && equal<T>(a.i, b.i) && equal<T>(a.j, b.j) && equal<T>(a.k, b.k));
}
}
#endif //RMVECTORMATH_TQUATERNION_DEF_HPP
<commit_msg>fix paths<commit_after>//
// Created by Vitali Kurlovich on 4/4/16.
//
#ifndef RMVECTORMATH_TQUATERNION_DEF_HPP
#define RMVECTORMATH_TQUATERNION_DEF_HPP
#include "../../common/common.hpp"
#include "../../vector/vector3x/TVector3_def.hpp"
#include "../../vector/vector2x/TVector2_def.hpp"
namespace rmmath {
namespace complex {
template<typename T>
struct TQuaternion {
union {
struct {
T w, i, j, k;
};
struct {
T re;
vector::TVector3<T> im;
};
vector::TVector4<T> wijk;
};
constexpr
TQuaternion( const T w = 0, const T i = 0, const T j = 0, const T k = 0 ) noexcept
: w(w), i(i), j(j), k(k)
{}
constexpr
TQuaternion( const T w, const vector::TVector3<T>& vec ) noexcept
: re(w), im(vec)
{}
constexpr
TQuaternion( const vector::TVector3<T>& vec, const T w = 0 ) noexcept
: re(w), im(vec)
{}
static const TQuaternion<T>& zero() {
static TQuaternion<T> zero;
return zero;
}
static const TQuaternion<T>& identity() {
static TQuaternion<T> identity(1, 0, 0, 0);
return identity;
}
};
}
template <typename T>
constexpr bool equal(const complex::TQuaternion<T> &a, const complex::TQuaternion<T> &b) noexcept {
return &a == &b ||
(equal<T>(a.w, b.w) && equal<T>(a.i, b.i) && equal<T>(a.j, b.j) && equal<T>(a.k, b.k));
}
}
#endif //RMVECTORMATH_TQUATERNION_DEF_HPP
<|endoftext|> |
<commit_before>#ifndef RADIUM_TOPOLOGICALMESH_TESTS_HPP_
#define RADIUM_TOPOLOGICALMESH_TESTS_HPP_
#include <Core/Mesh/MeshPrimitives.hpp>
#include <Core/Mesh/TopologicalTriMesh/TopologicalMesh.hpp>
#include <Core/Mesh/TriangleMesh.hpp>
#include <Tests/Tests.hpp>
#include <OpenMesh/Tools/Subdivider/Uniform/CatmullClarkT.hh>
#include <OpenMesh/Tools/Subdivider/Uniform/LoopT.hh>
#include <OpenMesh/Tools/Decimater/DecimaterT.hh>
#include <OpenMesh/Tools/Decimater/ModQuadricT.hh>
using Ra::Core::TopologicalMesh;
using Ra::Core::TriangleMesh;
using Ra::Core::Vector3;
namespace RaTests {
class TopologicalMeshTests : public Test {
using Catmull = OpenMesh::Subdivider::Uniform::CatmullClarkT<Ra::Core::TopologicalMesh>;
using Loop = OpenMesh::Subdivider::Uniform::LoopT<Ra::Core::TopologicalMesh>;
using Decimater = OpenMesh::Decimater::DecimaterT<Ra::Core::TopologicalMesh>;
using HModQuadric = OpenMesh::Decimater::ModQuadricT<Ra::Core::TopologicalMesh>::Handle;
void testCopyConsistency() {
TriangleMesh newMesh;
TriangleMesh mesh;
TopologicalMesh topologicalMesh;
// Test for close mesh
mesh = Ra::Core::MeshUtils::makeBox();
topologicalMesh = TopologicalMesh( mesh );
newMesh = topologicalMesh.toTriangleMesh();
RA_UNIT_TEST( isSameMesh( mesh, newMesh ), "Conversion to topological box mesh" );
mesh = Ra::Core::MeshUtils::makeSharpBox();
topologicalMesh = TopologicalMesh( mesh );
newMesh = topologicalMesh.toTriangleMesh();
RA_UNIT_TEST( isSameMesh( mesh, newMesh ), "Conversion to topological sharp box mesh" );
// Test for mesh with boundaries
mesh = Ra::Core::MeshUtils::makePlaneGrid( 2, 2 );
topologicalMesh = TopologicalMesh( mesh );
newMesh = topologicalMesh.toTriangleMesh();
RA_UNIT_TEST( isSameMesh( mesh, newMesh ), "Conversion to topological grid mesh" );
mesh = Ra::Core::MeshUtils::makeCylinder( Vector3( 0, 0, 0 ), Vector3( 0, 0, 1 ), 1 );
topologicalMesh = TopologicalMesh( mesh );
newMesh = topologicalMesh.toTriangleMesh();
RA_UNIT_TEST( isSameMesh( mesh, newMesh ), "Conversion to topological cylinder mesh" );
}
bool isSameMesh( TriangleMesh& meshOne, TriangleMesh& meshTwo ) {
bool result = true;
int i = 0;
// Check length
if ( meshOne.vertices().size() != meshTwo.vertices().size() )
return false;
if ( meshOne.normals().size() != meshTwo.normals().size() )
return false;
if ( meshOne.m_triangles.size() != meshTwo.m_triangles.size() )
return false;
// Check triangles
std::vector<Ra::Core::Vector3> stackVertices;
std::vector<Ra::Core::Vector3> stackNormals;
i = 0;
while ( result && i < meshOne.m_triangles.size() )
{
std::vector<Ra::Core::Vector3>::iterator it;
stackVertices.clear();
stackVertices.push_back( meshOne.vertices()[meshOne.m_triangles[i][0]] );
stackVertices.push_back( meshOne.vertices()[meshOne.m_triangles[i][1]] );
stackVertices.push_back( meshOne.vertices()[meshOne.m_triangles[i][2]] );
stackNormals.clear();
stackNormals.push_back( meshOne.normals()[meshOne.m_triangles[i][0]] );
stackNormals.push_back( meshOne.normals()[meshOne.m_triangles[i][1]] );
stackNormals.push_back( meshOne.normals()[meshOne.m_triangles[i][2]] );
for ( int j = 0; j < 3; ++j )
{
it = find( stackVertices.begin(), stackVertices.end(),
meshTwo.vertices()[meshTwo.m_triangles[i][j]] );
if ( it != stackVertices.end() )
{
stackVertices.erase( it );
} else
{ result = false; }
}
for ( int j = 0; j < 3; ++j )
{
it = find( stackNormals.begin(), stackNormals.end(),
meshTwo.normals()[meshTwo.m_triangles[i][j]] );
if ( it != stackNormals.end() )
{
stackNormals.erase( it );
} else
{ result = false; }
}
++i;
}
return result;
}
void run() override { testCopyConsistency(); }
};
RA_TEST_CLASS( TopologicalMeshTests );
} // namespace RaTests
#endif
<commit_msg>Add test for topologicalMesh normal functions.<commit_after>#ifndef RADIUM_TOPOLOGICALMESH_TESTS_HPP_
#define RADIUM_TOPOLOGICALMESH_TESTS_HPP_
#include <Core/Mesh/MeshPrimitives.hpp>
#include <Core/Mesh/TopologicalTriMesh/TopologicalMesh.hpp>
#include <Core/Mesh/TriangleMesh.hpp>
#include <Tests/Tests.hpp>
#include <OpenMesh/Tools/Subdivider/Uniform/CatmullClarkT.hh>
#include <OpenMesh/Tools/Subdivider/Uniform/LoopT.hh>
#include <OpenMesh/Tools/Decimater/DecimaterT.hh>
#include <OpenMesh/Tools/Decimater/ModQuadricT.hh>
using Ra::Core::TopologicalMesh;
using Ra::Core::TriangleMesh;
using Ra::Core::Vector3;
namespace RaTests {
class TopologicalMeshTests : public Test {
using Catmull = OpenMesh::Subdivider::Uniform::CatmullClarkT<Ra::Core::TopologicalMesh>;
using Loop = OpenMesh::Subdivider::Uniform::LoopT<Ra::Core::TopologicalMesh>;
using Decimater = OpenMesh::Decimater::DecimaterT<Ra::Core::TopologicalMesh>;
using HModQuadric = OpenMesh::Decimater::ModQuadricT<Ra::Core::TopologicalMesh>::Handle;
void testCopyConsistency() {
TriangleMesh newMesh;
TriangleMesh mesh;
TopologicalMesh topologicalMesh;
// Test for close mesh
mesh = Ra::Core::MeshUtils::makeBox();
topologicalMesh = TopologicalMesh( mesh );
newMesh = topologicalMesh.toTriangleMesh();
RA_UNIT_TEST( isSameMesh( mesh, newMesh ), "Conversion to topological box mesh" );
mesh = Ra::Core::MeshUtils::makeSharpBox();
topologicalMesh = TopologicalMesh( mesh );
newMesh = topologicalMesh.toTriangleMesh();
RA_UNIT_TEST( isSameMesh( mesh, newMesh ), "Conversion to topological sharp box mesh" );
// Test for mesh with boundaries
mesh = Ra::Core::MeshUtils::makePlaneGrid( 2, 2 );
topologicalMesh = TopologicalMesh( mesh );
newMesh = topologicalMesh.toTriangleMesh();
RA_UNIT_TEST( isSameMesh( mesh, newMesh ), "Conversion to topological grid mesh" );
mesh = Ra::Core::MeshUtils::makeCylinder( Vector3( 0, 0, 0 ), Vector3( 0, 0, 1 ), 1 );
topologicalMesh = TopologicalMesh( mesh );
newMesh = topologicalMesh.toTriangleMesh();
RA_UNIT_TEST( isSameMesh( mesh, newMesh ), "Conversion to topological cylinder mesh" );
mesh = Ra::Core::MeshUtils::makeBox();
topologicalMesh = TopologicalMesh( mesh );
for ( TopologicalMesh::VertexIter v_it = topologicalMesh.vertices_begin();
v_it != topologicalMesh.vertices_end(); ++v_it )
{
topologicalMesh.set_normal(
*v_it, TopologicalMesh::Normal( Scalar( 1. ), Scalar( 0. ), Scalar( 0. ) ) );
}
for ( TopologicalMesh::VertexIter v_it = topologicalMesh.vertices_begin();
v_it != topologicalMesh.vertices_end(); ++v_it )
{
topologicalMesh.propagate_normal_to_surronding_he( *v_it );
}
{
newMesh = topologicalMesh.toTriangleMesh();
bool check1 = true;
bool check2 = true;
for ( auto n : newMesh.normals() )
{
if ( !areApproxEqual( n.dot( Vector3( Scalar( 1. ), Scalar( 0. ), Scalar( 0. ) ) ),
Scalar( 1. ) ) )
{
check1 = false;
}
if ( n.dot( Vector3( Scalar( 0.5 ), Scalar( 0. ), Scalar( 0. ) ) ) > Scalar( 0.8 ) )
{
check2 = false;
}
}
RA_UNIT_TEST( check1 && check2,
"Set normal to topo vertex and apply them to halfedge" );
}
}
bool isSameMesh( TriangleMesh& meshOne, TriangleMesh& meshTwo ) {
bool result = true;
int i = 0;
// Check length
if ( meshOne.vertices().size() != meshTwo.vertices().size() )
return false;
if ( meshOne.normals().size() != meshTwo.normals().size() )
return false;
if ( meshOne.m_triangles.size() != meshTwo.m_triangles.size() )
return false;
// Check triangles
std::vector<Ra::Core::Vector3> stackVertices;
std::vector<Ra::Core::Vector3> stackNormals;
i = 0;
while ( result && i < meshOne.m_triangles.size() )
{
std::vector<Ra::Core::Vector3>::iterator it;
stackVertices.clear();
stackVertices.push_back( meshOne.vertices()[meshOne.m_triangles[i][0]] );
stackVertices.push_back( meshOne.vertices()[meshOne.m_triangles[i][1]] );
stackVertices.push_back( meshOne.vertices()[meshOne.m_triangles[i][2]] );
stackNormals.clear();
stackNormals.push_back( meshOne.normals()[meshOne.m_triangles[i][0]] );
stackNormals.push_back( meshOne.normals()[meshOne.m_triangles[i][1]] );
stackNormals.push_back( meshOne.normals()[meshOne.m_triangles[i][2]] );
for ( int j = 0; j < 3; ++j )
{
it = find( stackVertices.begin(), stackVertices.end(),
meshTwo.vertices()[meshTwo.m_triangles[i][j]] );
if ( it != stackVertices.end() )
{
stackVertices.erase( it );
} else
{ result = false; }
}
for ( int j = 0; j < 3; ++j )
{
it = find( stackNormals.begin(), stackNormals.end(),
meshTwo.normals()[meshTwo.m_triangles[i][j]] );
if ( it != stackNormals.end() )
{
stackNormals.erase( it );
} else
{ result = false; }
}
++i;
}
return result;
}
void run() override { testCopyConsistency(); }
};
RA_TEST_CLASS( TopologicalMeshTests );
} // namespace RaTests
#endif
<|endoftext|> |
<commit_before>/* GG is a GUI for SDL and OpenGL.
Copyright (C) 2003-2011 T. Zachary Laine
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
If you do not wish to comply with the terms of the LGPL please
contact the author as other terms are available for a fee.
Zach Laine
whatwasthataddress@gmail.com */
#include <GG/EveGlue.h>
#include <GG/GUI.h>
#include <GG/StyleFactory.h>
#include <GG/adobe/dictionary.hpp>
#include <GG/adobe/localization.hpp>
#include <GG/adobe/name.hpp>
#include <GG/adobe/future/widgets/headers/platform_widget_utils.hpp>
#include <GG/adobe/future/widgets/headers/widget_tokens.hpp>
#include <GG/adobe/future/widgets/headers/virtual_machine_extension.hpp>
#include <GG/dialogs/ColorDlg.h>
#include <GG/dialogs/FileDlg.h>
#include <GG/dialogs/ThreeButtonDlg.h>
namespace {
#define CASE(x) (name == adobe::static_name_t(#x)) retval = x
GLenum name_to_min_filter(adobe::name_t name)
{
GLenum retval = GL_NEAREST_MIPMAP_LINEAR;
if CASE(GL_NEAREST);
else if CASE(GL_LINEAR);
else if CASE(GL_NEAREST_MIPMAP_NEAREST);
else if CASE(GL_LINEAR_MIPMAP_NEAREST);
else if CASE(GL_NEAREST_MIPMAP_LINEAR);
else if CASE(GL_LINEAR_MIPMAP_LINEAR);
else if (name)
throw std::runtime_error(adobe::make_string("Invalid OpenGL minification filter ", name.c_str()));
return retval;
}
GLenum name_to_mag_filter(adobe::name_t name)
{
GLenum retval = GL_LINEAR;
if CASE(GL_NEAREST);
else if CASE(GL_LINEAR);
else if (name)
throw std::runtime_error(adobe::make_string("Invalid OpenGL magnification filter ", name.c_str()));
return retval;
}
GLenum name_to_wrap(adobe::name_t name)
{
GLenum retval = GL_REPEAT;
if CASE(GL_CLAMP);
else if CASE(GL_CLAMP_TO_BORDER);
else if CASE(GL_CLAMP_TO_EDGE);
else if CASE(GL_MIRRORED_REPEAT);
else if CASE(GL_REPEAT);
else if (name)
throw std::runtime_error(adobe::make_string("Invalid OpenGL wrap mode ", name.c_str()));
return retval;
}
#undef CASE
adobe::any_regular_t texture(const adobe::dictionary_t& named_argument_set)
{
if (named_argument_set.empty())
return adobe::any_regular_t(adobe::empty_t());
std::string filename;
adobe::dictionary_t wrap;
adobe::dictionary_t filter;
bool mipmap(false);
get_value(named_argument_set, adobe::key_name, filename);
get_value(named_argument_set, adobe::static_name_t("filter"), filter);
get_value(named_argument_set, adobe::key_wrap, wrap);
get_value(named_argument_set, adobe::static_name_t("mipmap"), mipmap);
adobe::name_t wrap_s;
adobe::name_t wrap_t;
adobe::name_t min_filter;
adobe::name_t mag_filter;
get_value(wrap, adobe::static_name_t("s"), wrap_s);
get_value(wrap, adobe::static_name_t("t"), wrap_t);
get_value(filter, adobe::static_name_t("min"), min_filter);
get_value(filter, adobe::static_name_t("mag"), mag_filter);
boost::shared_ptr<GG::Texture> texture;
if (!filename.empty()) {
try {
texture = GG::GUI::GetGUI()->GetTexture(filename, mipmap);
if (wrap_s || wrap_t)
texture->SetWrap(name_to_wrap(wrap_s), name_to_wrap(wrap_t));
if (min_filter || mag_filter)
texture->SetFilters(name_to_min_filter(min_filter), name_to_mag_filter(mag_filter));
} catch (...) {
return adobe::any_regular_t(adobe::empty_t());
}
}
return adobe::any_regular_t(texture);
}
adobe::any_regular_t subtexture(const adobe::dictionary_t& named_argument_set)
{
if (named_argument_set.empty())
return adobe::any_regular_t(adobe::empty_t());
std::string texture_name;
boost::shared_ptr<GG::Texture> texture;
int x1;
int x2;
int y1;
int y2;
bool all_needed_args = true;
if (get_value(named_argument_set, adobe::static_name_t("texture"), texture_name)) {
try {
texture = GG::GUI::GetGUI()->GetTexture(texture_name);
} catch (...) {}
} else {
get_value(named_argument_set, adobe::static_name_t("texture"), texture);
}
all_needed_args &= get_value(named_argument_set, adobe::static_name_t("x1"), x1);
all_needed_args &= get_value(named_argument_set, adobe::static_name_t("y1"), y1);
all_needed_args &= get_value(named_argument_set, adobe::static_name_t("x2"), x2);
all_needed_args &= get_value(named_argument_set, adobe::static_name_t("y2"), y2);
if (texture && all_needed_args)
return adobe::any_regular_t(GG::SubTexture(texture, GG::X(x1), GG::Y(y1), GG::X(x2), GG::Y(y2)));
else
return adobe::any_regular_t(adobe::empty_t());
}
}
namespace adobe { namespace implementation {
any_regular_t color_dialog(const dictionary_t& parameters)
{
any_regular_t retval;
GG::Clr original_color;
GG::Clr dialog_color(GG::CLR_GRAY);
GG::Clr border_color(GG::CLR_GRAY);
GG::Clr text_color(GG::CLR_BLACK);
get_value(parameters, static_name_t("original_color"), original_color);
get_value(parameters, static_name_t("dialog_color"), dialog_color);
get_value(parameters, static_name_t("border_color"), border_color);
get_value(parameters, static_name_t("text_color"), text_color);
std::auto_ptr<GG::ColorDlg> color_dialog;
if (parameters.count(static_name_t("original_color"))) {
color_dialog.reset(
implementation::Factory().NewColorDlg(
GG::X0, GG::Y0,
original_color,
implementation::DefaultFont(),
dialog_color,
border_color,
text_color
)
);
} else {
color_dialog.reset(
implementation::Factory().NewColorDlg(
GG::X0, GG::Y0,
implementation::DefaultFont(),
dialog_color,
border_color,
text_color
)
);
}
#define LOCALIZE(name) color_dialog->Set##name(localization_invoke(color_dialog->name()))
LOCALIZE(NewString);
LOCALIZE(OldString);
LOCALIZE(RedString);
LOCALIZE(GreenString);
LOCALIZE(BlueString);
LOCALIZE(HueString);
LOCALIZE(SaturationString);
LOCALIZE(ValueString);
LOCALIZE(AlphaString);
LOCALIZE(OkString);
LOCALIZE(CancelString);
#undef LOCALIZE
GG::X app_width = GG::GUI::GetGUI()->AppWidth();
GG::Y app_height = GG::GUI::GetGUI()->AppHeight();
color_dialog->MoveTo(
GG::Pt((app_width - color_dialog->Width()) / 2,
(app_height - color_dialog->Height()) / 2)
);
color_dialog->Run();
if (color_dialog->ColorWasSelected())
retval = any_regular_t(color_dialog->Result());
return retval;
}
any_regular_t file_dialog(const dictionary_t& parameters)
{
any_regular_t retval;
std::string directory;
std::string filename;
bool save = false;
bool multi = false;
GG::Clr color(GG::CLR_GRAY);
GG::Clr border_color(GG::CLR_GRAY);
GG::Clr text_color(GG::CLR_BLACK);
get_value(parameters, adobe::static_name_t("directory"), directory);
get_value(parameters, adobe::static_name_t("filename"), filename);
get_value(parameters, adobe::static_name_t("save"), save);
get_value(parameters, adobe::static_name_t("multi"), multi);
get_value(parameters, adobe::static_name_t("color"), color);
get_value(parameters, adobe::static_name_t("border_color"), border_color);
get_value(parameters, adobe::static_name_t("text_color"), text_color);
std::auto_ptr<GG::FileDlg> file_dialog(
adobe::implementation::Factory().NewFileDlg(
directory,
filename,
save,
multi,
adobe::implementation::DefaultFont(),
color,
border_color,
text_color
)
);
#define LOCALIZE(name) file_dialog->Set##name(localization_invoke(file_dialog->name()))
LOCALIZE(FilesString);
LOCALIZE(FileTypesString);
LOCALIZE(SaveString);
LOCALIZE(OpenString);
LOCALIZE(CancelString);
LOCALIZE(MalformedFilenameString);
LOCALIZE(OverwritePromptString);
LOCALIZE(InvalidFilenameString);
LOCALIZE(FilenameIsADirectoryString);
LOCALIZE(FileDoesNotExistString);
LOCALIZE(DeviceIsNotReadyString);
LOCALIZE(ThreeButtonDlgOKString);
LOCALIZE(ThreeButtonDlgCancelString);
#undef LOCALIZE
file_dialog->Run();
array_t* array = 0;
if (!file_dialog->Result().empty()) {
retval.assign(array_t());
array = &retval.cast<array_t>();
}
for (std::set<std::string>::const_iterator it = file_dialog->Result().begin();
it != file_dialog->Result().end();
++it) {
array->push_back(any_regular_t(*it));
}
return retval;
}
any_regular_t three_button_dialog(const dictionary_t& parameters)
{
any_regular_t retval;
std::string message;
unsigned int width = 0;
unsigned int height = 0;
GG::Clr color(GG::CLR_GRAY);
GG::Clr border_color(GG::CLR_GRAY);
GG::Clr button_color(GG::CLR_GRAY);
GG::Clr text_color(GG::CLR_BLACK);
unsigned int buttons;
std::string zero;
std::string one;
std::string two;
implementation::get_localized_string(parameters, adobe::static_name_t("message"), message);
get_value(parameters, adobe::static_name_t("width"), width);
get_value(parameters, adobe::static_name_t("height"), height);
get_value(parameters, adobe::static_name_t("color"), color);
get_value(parameters, adobe::static_name_t("border_color"), border_color);
get_value(parameters, adobe::static_name_t("button_color"), button_color);
get_value(parameters, adobe::static_name_t("text_color"), text_color);
get_value(parameters, adobe::static_name_t("buttons"), buttons);
implementation::get_localized_string(parameters, adobe::static_name_t("zero"), zero);
implementation::get_localized_string(parameters, adobe::static_name_t("one"), one);
implementation::get_localized_string(parameters, adobe::static_name_t("two"), two);
std::auto_ptr<GG::ThreeButtonDlg> three_button_dialog;
if (width && height) {
three_button_dialog.reset(
adobe::implementation::Factory().NewThreeButtonDlg(
GG::X0, GG::Y0,
GG::X(width), GG::Y(height),
message,
adobe::implementation::DefaultFont(),
color,
border_color,
button_color,
text_color,
buttons,
zero,
one,
two
)
);
} else {
three_button_dialog.reset(
adobe::implementation::Factory().NewThreeButtonDlg(
GG::X0, GG::Y0,
message,
adobe::implementation::DefaultFont(),
color,
border_color,
button_color,
text_color,
buttons,
zero,
one,
two
)
);
}
GG::X app_width = GG::GUI::GetGUI()->AppWidth();
GG::Y app_height = GG::GUI::GetGUI()->AppHeight();
three_button_dialog->MoveTo(
GG::Pt((app_width - three_button_dialog->Width()) / 2,
(app_height - three_button_dialog->Height()) / 2)
);
three_button_dialog->Run();
retval = any_regular_t(three_button_dialog->Result());
return retval;
}
} }
namespace {
bool register_()
{
GG::RegisterDictionaryFunction(adobe::static_name_t("texture"), &texture);
GG::RegisterDictionaryFunction(adobe::static_name_t("subtexture"), &subtexture);
GG::RegisterDictionaryFunction(adobe::static_name_t("color_dialog"), &adobe::implementation::color_dialog);
GG::RegisterDictionaryFunction(adobe::static_name_t("file_dialog"), &adobe::implementation::file_dialog);
GG::RegisterDictionaryFunction(adobe::static_name_t("three_button_dialog"), &adobe::implementation::three_button_dialog);
return true;
}
bool dummy = register_();
}
<commit_msg>Added missing initialization for buttons in three_button_dialog().<commit_after>/* GG is a GUI for SDL and OpenGL.
Copyright (C) 2003-2011 T. Zachary Laine
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
If you do not wish to comply with the terms of the LGPL please
contact the author as other terms are available for a fee.
Zach Laine
whatwasthataddress@gmail.com */
#include <GG/EveGlue.h>
#include <GG/GUI.h>
#include <GG/StyleFactory.h>
#include <GG/adobe/dictionary.hpp>
#include <GG/adobe/localization.hpp>
#include <GG/adobe/name.hpp>
#include <GG/adobe/future/widgets/headers/platform_widget_utils.hpp>
#include <GG/adobe/future/widgets/headers/widget_tokens.hpp>
#include <GG/adobe/future/widgets/headers/virtual_machine_extension.hpp>
#include <GG/dialogs/ColorDlg.h>
#include <GG/dialogs/FileDlg.h>
#include <GG/dialogs/ThreeButtonDlg.h>
namespace {
#define CASE(x) (name == adobe::static_name_t(#x)) retval = x
GLenum name_to_min_filter(adobe::name_t name)
{
GLenum retval = GL_NEAREST_MIPMAP_LINEAR;
if CASE(GL_NEAREST);
else if CASE(GL_LINEAR);
else if CASE(GL_NEAREST_MIPMAP_NEAREST);
else if CASE(GL_LINEAR_MIPMAP_NEAREST);
else if CASE(GL_NEAREST_MIPMAP_LINEAR);
else if CASE(GL_LINEAR_MIPMAP_LINEAR);
else if (name)
throw std::runtime_error(adobe::make_string("Invalid OpenGL minification filter ", name.c_str()));
return retval;
}
GLenum name_to_mag_filter(adobe::name_t name)
{
GLenum retval = GL_LINEAR;
if CASE(GL_NEAREST);
else if CASE(GL_LINEAR);
else if (name)
throw std::runtime_error(adobe::make_string("Invalid OpenGL magnification filter ", name.c_str()));
return retval;
}
GLenum name_to_wrap(adobe::name_t name)
{
GLenum retval = GL_REPEAT;
if CASE(GL_CLAMP);
else if CASE(GL_CLAMP_TO_BORDER);
else if CASE(GL_CLAMP_TO_EDGE);
else if CASE(GL_MIRRORED_REPEAT);
else if CASE(GL_REPEAT);
else if (name)
throw std::runtime_error(adobe::make_string("Invalid OpenGL wrap mode ", name.c_str()));
return retval;
}
#undef CASE
adobe::any_regular_t texture(const adobe::dictionary_t& named_argument_set)
{
if (named_argument_set.empty())
return adobe::any_regular_t(adobe::empty_t());
std::string filename;
adobe::dictionary_t wrap;
adobe::dictionary_t filter;
bool mipmap(false);
get_value(named_argument_set, adobe::key_name, filename);
get_value(named_argument_set, adobe::static_name_t("filter"), filter);
get_value(named_argument_set, adobe::key_wrap, wrap);
get_value(named_argument_set, adobe::static_name_t("mipmap"), mipmap);
adobe::name_t wrap_s;
adobe::name_t wrap_t;
adobe::name_t min_filter;
adobe::name_t mag_filter;
get_value(wrap, adobe::static_name_t("s"), wrap_s);
get_value(wrap, adobe::static_name_t("t"), wrap_t);
get_value(filter, adobe::static_name_t("min"), min_filter);
get_value(filter, adobe::static_name_t("mag"), mag_filter);
boost::shared_ptr<GG::Texture> texture;
if (!filename.empty()) {
try {
texture = GG::GUI::GetGUI()->GetTexture(filename, mipmap);
if (wrap_s || wrap_t)
texture->SetWrap(name_to_wrap(wrap_s), name_to_wrap(wrap_t));
if (min_filter || mag_filter)
texture->SetFilters(name_to_min_filter(min_filter), name_to_mag_filter(mag_filter));
} catch (...) {
return adobe::any_regular_t(adobe::empty_t());
}
}
return adobe::any_regular_t(texture);
}
adobe::any_regular_t subtexture(const adobe::dictionary_t& named_argument_set)
{
if (named_argument_set.empty())
return adobe::any_regular_t(adobe::empty_t());
std::string texture_name;
boost::shared_ptr<GG::Texture> texture;
int x1;
int x2;
int y1;
int y2;
bool all_needed_args = true;
if (get_value(named_argument_set, adobe::static_name_t("texture"), texture_name)) {
try {
texture = GG::GUI::GetGUI()->GetTexture(texture_name);
} catch (...) {}
} else {
get_value(named_argument_set, adobe::static_name_t("texture"), texture);
}
all_needed_args &= get_value(named_argument_set, adobe::static_name_t("x1"), x1);
all_needed_args &= get_value(named_argument_set, adobe::static_name_t("y1"), y1);
all_needed_args &= get_value(named_argument_set, adobe::static_name_t("x2"), x2);
all_needed_args &= get_value(named_argument_set, adobe::static_name_t("y2"), y2);
if (texture && all_needed_args)
return adobe::any_regular_t(GG::SubTexture(texture, GG::X(x1), GG::Y(y1), GG::X(x2), GG::Y(y2)));
else
return adobe::any_regular_t(adobe::empty_t());
}
}
namespace adobe { namespace implementation {
any_regular_t color_dialog(const dictionary_t& parameters)
{
any_regular_t retval;
GG::Clr original_color;
GG::Clr dialog_color(GG::CLR_GRAY);
GG::Clr border_color(GG::CLR_GRAY);
GG::Clr text_color(GG::CLR_BLACK);
get_value(parameters, static_name_t("original_color"), original_color);
get_value(parameters, static_name_t("dialog_color"), dialog_color);
get_value(parameters, static_name_t("border_color"), border_color);
get_value(parameters, static_name_t("text_color"), text_color);
std::auto_ptr<GG::ColorDlg> color_dialog;
if (parameters.count(static_name_t("original_color"))) {
color_dialog.reset(
implementation::Factory().NewColorDlg(
GG::X0, GG::Y0,
original_color,
implementation::DefaultFont(),
dialog_color,
border_color,
text_color
)
);
} else {
color_dialog.reset(
implementation::Factory().NewColorDlg(
GG::X0, GG::Y0,
implementation::DefaultFont(),
dialog_color,
border_color,
text_color
)
);
}
#define LOCALIZE(name) color_dialog->Set##name(localization_invoke(color_dialog->name()))
LOCALIZE(NewString);
LOCALIZE(OldString);
LOCALIZE(RedString);
LOCALIZE(GreenString);
LOCALIZE(BlueString);
LOCALIZE(HueString);
LOCALIZE(SaturationString);
LOCALIZE(ValueString);
LOCALIZE(AlphaString);
LOCALIZE(OkString);
LOCALIZE(CancelString);
#undef LOCALIZE
GG::X app_width = GG::GUI::GetGUI()->AppWidth();
GG::Y app_height = GG::GUI::GetGUI()->AppHeight();
color_dialog->MoveTo(
GG::Pt((app_width - color_dialog->Width()) / 2,
(app_height - color_dialog->Height()) / 2)
);
color_dialog->Run();
if (color_dialog->ColorWasSelected())
retval = any_regular_t(color_dialog->Result());
return retval;
}
any_regular_t file_dialog(const dictionary_t& parameters)
{
any_regular_t retval;
std::string directory;
std::string filename;
bool save = false;
bool multi = false;
GG::Clr color(GG::CLR_GRAY);
GG::Clr border_color(GG::CLR_GRAY);
GG::Clr text_color(GG::CLR_BLACK);
get_value(parameters, adobe::static_name_t("directory"), directory);
get_value(parameters, adobe::static_name_t("filename"), filename);
get_value(parameters, adobe::static_name_t("save"), save);
get_value(parameters, adobe::static_name_t("multi"), multi);
get_value(parameters, adobe::static_name_t("color"), color);
get_value(parameters, adobe::static_name_t("border_color"), border_color);
get_value(parameters, adobe::static_name_t("text_color"), text_color);
std::auto_ptr<GG::FileDlg> file_dialog(
adobe::implementation::Factory().NewFileDlg(
directory,
filename,
save,
multi,
adobe::implementation::DefaultFont(),
color,
border_color,
text_color
)
);
#define LOCALIZE(name) file_dialog->Set##name(localization_invoke(file_dialog->name()))
LOCALIZE(FilesString);
LOCALIZE(FileTypesString);
LOCALIZE(SaveString);
LOCALIZE(OpenString);
LOCALIZE(CancelString);
LOCALIZE(MalformedFilenameString);
LOCALIZE(OverwritePromptString);
LOCALIZE(InvalidFilenameString);
LOCALIZE(FilenameIsADirectoryString);
LOCALIZE(FileDoesNotExistString);
LOCALIZE(DeviceIsNotReadyString);
LOCALIZE(ThreeButtonDlgOKString);
LOCALIZE(ThreeButtonDlgCancelString);
#undef LOCALIZE
file_dialog->Run();
array_t* array = 0;
if (!file_dialog->Result().empty()) {
retval.assign(array_t());
array = &retval.cast<array_t>();
}
for (std::set<std::string>::const_iterator it = file_dialog->Result().begin();
it != file_dialog->Result().end();
++it) {
array->push_back(any_regular_t(*it));
}
return retval;
}
any_regular_t three_button_dialog(const dictionary_t& parameters)
{
any_regular_t retval;
std::string message;
unsigned int width = 0;
unsigned int height = 0;
GG::Clr color(GG::CLR_GRAY);
GG::Clr border_color(GG::CLR_GRAY);
GG::Clr button_color(GG::CLR_GRAY);
GG::Clr text_color(GG::CLR_BLACK);
unsigned int buttons = 2;
std::string zero;
std::string one;
std::string two;
implementation::get_localized_string(parameters, adobe::static_name_t("message"), message);
get_value(parameters, adobe::static_name_t("width"), width);
get_value(parameters, adobe::static_name_t("height"), height);
get_value(parameters, adobe::static_name_t("color"), color);
get_value(parameters, adobe::static_name_t("border_color"), border_color);
get_value(parameters, adobe::static_name_t("button_color"), button_color);
get_value(parameters, adobe::static_name_t("text_color"), text_color);
get_value(parameters, adobe::static_name_t("buttons"), buttons);
implementation::get_localized_string(parameters, adobe::static_name_t("zero"), zero);
implementation::get_localized_string(parameters, adobe::static_name_t("one"), one);
implementation::get_localized_string(parameters, adobe::static_name_t("two"), two);
std::auto_ptr<GG::ThreeButtonDlg> three_button_dialog;
if (width && height) {
three_button_dialog.reset(
adobe::implementation::Factory().NewThreeButtonDlg(
GG::X0, GG::Y0,
GG::X(width), GG::Y(height),
message,
adobe::implementation::DefaultFont(),
color,
border_color,
button_color,
text_color,
buttons,
zero,
one,
two
)
);
} else {
three_button_dialog.reset(
adobe::implementation::Factory().NewThreeButtonDlg(
GG::X1, GG::Y1,
message,
adobe::implementation::DefaultFont(),
color,
border_color,
button_color,
text_color,
buttons,
zero,
one,
two
)
);
}
GG::X app_width = GG::GUI::GetGUI()->AppWidth();
GG::Y app_height = GG::GUI::GetGUI()->AppHeight();
three_button_dialog->MoveTo(
GG::Pt((app_width - three_button_dialog->Width()) / 2,
(app_height - three_button_dialog->Height()) / 2)
);
three_button_dialog->Run();
retval = any_regular_t(three_button_dialog->Result());
return retval;
}
} }
namespace {
bool register_()
{
GG::RegisterDictionaryFunction(adobe::static_name_t("texture"), &texture);
GG::RegisterDictionaryFunction(adobe::static_name_t("subtexture"), &subtexture);
GG::RegisterDictionaryFunction(adobe::static_name_t("color_dialog"), &adobe::implementation::color_dialog);
GG::RegisterDictionaryFunction(adobe::static_name_t("file_dialog"), &adobe::implementation::file_dialog);
GG::RegisterDictionaryFunction(adobe::static_name_t("three_button_dialog"), &adobe::implementation::three_button_dialog);
return true;
}
bool dummy = register_();
}
<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/io/middleman_actor.hpp"
#ifdef CAF_WINDOWS
# include <winsock2.h>
# include <ws2tcpip.h> // socket_size_type, etc. (MSVC20xx)
#else
# include <sys/socket.h>
# include <sys/types.h>
#endif
#include <stdexcept>
#include <tuple>
#include <utility>
#include "caf/actor.hpp"
#include "caf/actor_proxy.hpp"
#include "caf/actor_system_config.hpp"
#include "caf/detail/socket_guard.hpp"
#include "caf/logger.hpp"
#include "caf/node_id.hpp"
#include "caf/sec.hpp"
#include "caf/send.hpp"
#include "caf/typed_event_based_actor.hpp"
#include "caf/io/basp_broker.hpp"
#include "caf/io/middleman_actor_impl.hpp"
#include "caf/io/system_messages.hpp"
#include "caf/io/network/default_multiplexer.hpp"
#include "caf/io/network/doorman_impl.hpp"
#include "caf/io/network/interfaces.hpp"
#include "caf/io/network/stream_impl.hpp"
#ifdef CAF_WINDOWS
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif // CAF_WINDOWS
# ifndef NOMINMAX
# define NOMINMAX
# endif // NOMINMAX
# ifdef CAF_MINGW
# undef _WIN32_WINNT
# undef WINVER
# define _WIN32_WINNT WindowsVista
# define WINVER WindowsVista
# include <w32api.h>
# endif // CAF_MINGW
# include <windows.h>
# include <winsock2.h>
# include <ws2ipdef.h>
# include <ws2tcpip.h>
#else
# include <sys/socket.h>
# include <sys/types.h>
#endif
#include "caf/openssl/session.hpp"
namespace caf::openssl {
namespace {
using native_socket = io::network::native_socket;
using default_mpx = io::network::default_multiplexer;
struct ssl_policy {
ssl_policy(session_ptr session) : session_(std::move(session)) {
// nop
}
rw_state read_some(size_t& result, native_socket fd, void* buf, size_t len) {
CAF_LOG_TRACE(CAF_ARG(fd) << CAF_ARG(len));
return session_->read_some(result, fd, buf, len);
}
rw_state
write_some(size_t& result, native_socket fd, const void* buf, size_t len) {
CAF_LOG_TRACE(CAF_ARG(fd) << CAF_ARG(len));
return session_->write_some(result, fd, buf, len);
}
bool try_accept(native_socket& result, native_socket fd) {
CAF_LOG_TRACE(CAF_ARG(fd));
sockaddr_storage addr;
memset(&addr, 0, sizeof(addr));
caf::io::network::socket_size_type addrlen = sizeof(addr);
result = accept(fd, reinterpret_cast<sockaddr*>(&addr), &addrlen);
// note accept4 is better to avoid races in setting CLOEXEC (but not posix)
if (result == io::network::invalid_native_socket) {
auto err = io::network::last_socket_error();
if (!io::network::would_block_or_temporarily_unavailable(err))
CAF_LOG_ERROR(
"accept failed:" << io::network::socket_error_as_string(err));
return false;
}
io::network::child_process_inherit(result, false);
CAF_LOG_DEBUG(CAF_ARG(fd) << CAF_ARG(result));
return session_->try_accept(result);
}
bool must_read_more(native_socket fd, size_t threshold) {
return session_->must_read_more(fd, threshold);
}
private:
session_ptr session_;
};
class scribe_impl : public io::scribe {
public:
scribe_impl(default_mpx& mpx, native_socket sockfd, session_ptr sptr)
: scribe(io::network::conn_hdl_from_socket(sockfd)),
launched_(false),
stream_(mpx, sockfd, std::move(sptr)) {
// nop
}
~scribe_impl() override {
CAF_LOG_TRACE("");
}
void configure_read(io::receive_policy::config config) override {
CAF_LOG_TRACE(CAF_ARG(config));
stream_.configure_read(config);
if (!launched_)
launch();
}
void ack_writes(bool enable) override {
CAF_LOG_TRACE(CAF_ARG(enable));
stream_.ack_writes(enable);
}
byte_buffer& wr_buf() override {
return stream_.wr_buf();
}
byte_buffer& rd_buf() override {
return stream_.rd_buf();
}
void graceful_shutdown() override {
CAF_LOG_TRACE("");
stream_.graceful_shutdown();
detach(&stream_.backend(), false);
}
void flush() override {
CAF_LOG_TRACE("");
stream_.flush(this);
}
std::string addr() const override {
auto x = io::network::remote_addr_of_fd(stream_.fd());
if (!x)
return "";
return *x;
}
uint16_t port() const override {
auto x = io::network::remote_port_of_fd(stream_.fd());
if (!x)
return 0;
return *x;
}
void launch() {
CAF_LOG_TRACE("");
CAF_ASSERT(!launched_);
launched_ = true;
stream_.start(this);
// This schedules the scribe in case SSL still needs to call SSL_connect
// or SSL_accept. Otherwise, the backend simply removes the socket for
// write operations after the first "nop write".
stream_.force_empty_write(this);
}
void add_to_loop() override {
CAF_LOG_TRACE("");
stream_.activate(this);
}
void remove_from_loop() override {
CAF_LOG_TRACE("");
stream_.passivate();
}
private:
bool launched_;
io::network::stream_impl<ssl_policy> stream_;
};
class doorman_impl : public io::network::doorman_impl {
public:
doorman_impl(default_mpx& mx, native_socket sockfd)
: io::network::doorman_impl(mx, sockfd) {
// nop
}
bool new_connection() override {
CAF_LOG_TRACE("");
if (detached())
// we are already disconnected from the broker while the multiplexer
// did not yet remove the socket, this can happen if an I/O event causes
// the broker to call close_all() while the pollset contained
// further activities for the broker
return false;
auto& dm = acceptor_.backend();
auto fd = acceptor_.accepted_socket();
detail::socket_guard sguard{fd};
io::network::nonblocking(fd, true);
auto sssn = make_session(parent()->system(), fd, true);
if (sssn == nullptr) {
CAF_LOG_ERROR("Unable to create SSL session for accepted socket");
return false;
}
auto scrb = make_counted<scribe_impl>(dm, fd, std::move(sssn));
auto hdl = scrb->hdl();
parent()->add_scribe(std::move(scrb));
auto result = doorman::new_connection(&dm, hdl);
if (result)
sguard.release();
return result;
}
};
class middleman_actor_impl : public io::middleman_actor_impl {
public:
middleman_actor_impl(actor_config& cfg, actor default_broker)
: io::middleman_actor_impl(cfg, std::move(default_broker)) {
// nop
}
const char* name() const override {
return "openssl::middleman_actor";
}
protected:
expected<io::scribe_ptr>
connect(const std::string& host, uint16_t port) override {
CAF_LOG_TRACE(CAF_ARG(host) << CAF_ARG(port));
auto fd = io::network::new_tcp_connection(host, port);
if (!fd)
return std::move(fd.error());
io::network::nonblocking(*fd, true);
auto sssn = make_session(system(), *fd, false);
if (!sssn) {
CAF_LOG_ERROR("Unable to create SSL session for connection");
return sec::cannot_connect_to_node;
}
CAF_LOG_DEBUG("successfully created an SSL session for:" << CAF_ARG(host)
<< CAF_ARG(port));
return make_counted<scribe_impl>(mpx(), *fd, std::move(sssn));
}
expected<io::doorman_ptr>
open(uint16_t port, const char* addr, bool reuse) override {
CAF_LOG_TRACE(CAF_ARG(port) << CAF_ARG(reuse));
auto fd = io::network::new_tcp_acceptor_impl(port, addr, reuse);
if (!fd)
return std::move(fd.error());
return make_counted<doorman_impl>(mpx(), *fd);
}
private:
default_mpx& mpx() {
return static_cast<default_mpx&>(system().middleman().backend());
}
};
} // namespace
io::middleman_actor make_middleman_actor(actor_system& sys, actor db) {
return !get_or(sys.config(), "caf.middleman.attach-utility-actors", false)
? sys.spawn<middleman_actor_impl, detached + hidden>(std::move(db))
: sys.spawn<middleman_actor_impl, hidden>(std::move(db));
}
} // namespace caf::openssl
<commit_msg>Fix potential double-close on socket<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/io/middleman_actor.hpp"
#ifdef CAF_WINDOWS
# include <winsock2.h>
# include <ws2tcpip.h> // socket_size_type, etc. (MSVC20xx)
#else
# include <sys/socket.h>
# include <sys/types.h>
#endif
#include <stdexcept>
#include <tuple>
#include <utility>
#include "caf/actor.hpp"
#include "caf/actor_proxy.hpp"
#include "caf/actor_system_config.hpp"
#include "caf/detail/socket_guard.hpp"
#include "caf/logger.hpp"
#include "caf/node_id.hpp"
#include "caf/sec.hpp"
#include "caf/send.hpp"
#include "caf/typed_event_based_actor.hpp"
#include "caf/io/basp_broker.hpp"
#include "caf/io/middleman_actor_impl.hpp"
#include "caf/io/system_messages.hpp"
#include "caf/io/network/default_multiplexer.hpp"
#include "caf/io/network/doorman_impl.hpp"
#include "caf/io/network/interfaces.hpp"
#include "caf/io/network/stream_impl.hpp"
#ifdef CAF_WINDOWS
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif // CAF_WINDOWS
# ifndef NOMINMAX
# define NOMINMAX
# endif // NOMINMAX
# ifdef CAF_MINGW
# undef _WIN32_WINNT
# undef WINVER
# define _WIN32_WINNT WindowsVista
# define WINVER WindowsVista
# include <w32api.h>
# endif // CAF_MINGW
# include <windows.h>
# include <winsock2.h>
# include <ws2ipdef.h>
# include <ws2tcpip.h>
#else
# include <sys/socket.h>
# include <sys/types.h>
#endif
#include "caf/openssl/session.hpp"
namespace caf::openssl {
namespace {
using native_socket = io::network::native_socket;
using default_mpx = io::network::default_multiplexer;
struct ssl_policy {
ssl_policy(session_ptr session) : session_(std::move(session)) {
// nop
}
rw_state read_some(size_t& result, native_socket fd, void* buf, size_t len) {
CAF_LOG_TRACE(CAF_ARG(fd) << CAF_ARG(len));
return session_->read_some(result, fd, buf, len);
}
rw_state
write_some(size_t& result, native_socket fd, const void* buf, size_t len) {
CAF_LOG_TRACE(CAF_ARG(fd) << CAF_ARG(len));
return session_->write_some(result, fd, buf, len);
}
bool try_accept(native_socket& result, native_socket fd) {
CAF_LOG_TRACE(CAF_ARG(fd));
sockaddr_storage addr;
memset(&addr, 0, sizeof(addr));
caf::io::network::socket_size_type addrlen = sizeof(addr);
result = accept(fd, reinterpret_cast<sockaddr*>(&addr), &addrlen);
// note accept4 is better to avoid races in setting CLOEXEC (but not posix)
if (result == io::network::invalid_native_socket) {
auto err = io::network::last_socket_error();
if (!io::network::would_block_or_temporarily_unavailable(err))
CAF_LOG_ERROR(
"accept failed:" << io::network::socket_error_as_string(err));
return false;
}
io::network::child_process_inherit(result, false);
CAF_LOG_DEBUG(CAF_ARG(fd) << CAF_ARG(result));
return session_->try_accept(result);
}
bool must_read_more(native_socket fd, size_t threshold) {
return session_->must_read_more(fd, threshold);
}
private:
session_ptr session_;
};
class scribe_impl : public io::scribe {
public:
scribe_impl(default_mpx& mpx, native_socket sockfd, session_ptr sptr)
: scribe(io::network::conn_hdl_from_socket(sockfd)),
launched_(false),
stream_(mpx, sockfd, std::move(sptr)) {
// nop
}
~scribe_impl() override {
CAF_LOG_TRACE("");
}
void configure_read(io::receive_policy::config config) override {
CAF_LOG_TRACE(CAF_ARG(config));
stream_.configure_read(config);
if (!launched_)
launch();
}
void ack_writes(bool enable) override {
CAF_LOG_TRACE(CAF_ARG(enable));
stream_.ack_writes(enable);
}
byte_buffer& wr_buf() override {
return stream_.wr_buf();
}
byte_buffer& rd_buf() override {
return stream_.rd_buf();
}
void graceful_shutdown() override {
CAF_LOG_TRACE("");
stream_.graceful_shutdown();
detach(&stream_.backend(), false);
}
void flush() override {
CAF_LOG_TRACE("");
stream_.flush(this);
}
std::string addr() const override {
auto x = io::network::remote_addr_of_fd(stream_.fd());
if (!x)
return "";
return *x;
}
uint16_t port() const override {
auto x = io::network::remote_port_of_fd(stream_.fd());
if (!x)
return 0;
return *x;
}
void launch() {
CAF_LOG_TRACE("");
CAF_ASSERT(!launched_);
launched_ = true;
stream_.start(this);
// This schedules the scribe in case SSL still needs to call SSL_connect
// or SSL_accept. Otherwise, the backend simply removes the socket for
// write operations after the first "nop write".
stream_.force_empty_write(this);
}
void add_to_loop() override {
CAF_LOG_TRACE("");
stream_.activate(this);
}
void remove_from_loop() override {
CAF_LOG_TRACE("");
stream_.passivate();
}
private:
bool launched_;
io::network::stream_impl<ssl_policy> stream_;
};
class doorman_impl : public io::network::doorman_impl {
public:
doorman_impl(default_mpx& mx, native_socket sockfd)
: io::network::doorman_impl(mx, sockfd) {
// nop
}
bool new_connection() override {
CAF_LOG_TRACE("");
if (detached())
// we are already disconnected from the broker while the multiplexer
// did not yet remove the socket, this can happen if an I/O event causes
// the broker to call close_all() while the pollset contained
// further activities for the broker
return false;
auto& dm = acceptor_.backend();
auto fd = acceptor_.accepted_socket();
detail::socket_guard sguard{fd};
io::network::nonblocking(fd, true);
auto sssn = make_session(parent()->system(), fd, true);
if (sssn == nullptr) {
CAF_LOG_ERROR("Unable to create SSL session for accepted socket");
return false;
}
auto scrb = make_counted<scribe_impl>(dm, fd, std::move(sssn));
sguard.release(); // The scribe claims ownership of the socket.
auto hdl = scrb->hdl();
parent()->add_scribe(std::move(scrb));
return doorman::new_connection(&dm, hdl);
}
};
class middleman_actor_impl : public io::middleman_actor_impl {
public:
middleman_actor_impl(actor_config& cfg, actor default_broker)
: io::middleman_actor_impl(cfg, std::move(default_broker)) {
// nop
}
const char* name() const override {
return "openssl::middleman_actor";
}
protected:
expected<io::scribe_ptr>
connect(const std::string& host, uint16_t port) override {
CAF_LOG_TRACE(CAF_ARG(host) << CAF_ARG(port));
auto fd = io::network::new_tcp_connection(host, port);
if (!fd)
return std::move(fd.error());
io::network::nonblocking(*fd, true);
auto sssn = make_session(system(), *fd, false);
if (!sssn) {
CAF_LOG_ERROR("Unable to create SSL session for connection");
return sec::cannot_connect_to_node;
}
CAF_LOG_DEBUG("successfully created an SSL session for:" << CAF_ARG(host)
<< CAF_ARG(port));
return make_counted<scribe_impl>(mpx(), *fd, std::move(sssn));
}
expected<io::doorman_ptr>
open(uint16_t port, const char* addr, bool reuse) override {
CAF_LOG_TRACE(CAF_ARG(port) << CAF_ARG(reuse));
auto fd = io::network::new_tcp_acceptor_impl(port, addr, reuse);
if (!fd)
return std::move(fd.error());
return make_counted<doorman_impl>(mpx(), *fd);
}
private:
default_mpx& mpx() {
return static_cast<default_mpx&>(system().middleman().backend());
}
};
} // namespace
io::middleman_actor make_middleman_actor(actor_system& sys, actor db) {
return !get_or(sys.config(), "caf.middleman.attach-utility-actors", false)
? sys.spawn<middleman_actor_impl, detached + hidden>(std::move(db))
: sys.spawn<middleman_actor_impl, hidden>(std::move(db));
}
} // namespace caf::openssl
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008 Nokia Corporation.
*
* Contact: Marius Vollmer <marius.vollmer@nokia.com>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "infoxmlkeysfinder.h"
#include "logging.h"
#include "loggingfeatures.h"
/*!
\class InfoXmlKeysFinder
\brief Implements a SAX parser to parse xml files with provider/key data.
This class is not exported in the public API. Traditional old-school context-based
parsing logic here.
*/
/// Called when parsing starts.
bool InfoXmlKeysFinder::startDocument()
{
keyDataHash.clear();
inProvider = false;
inKey = false;
inKeyType = false;
inKeyDoc = false;
return true;
}
/// Called for each <element> when we start parsing it.
bool InfoXmlKeysFinder::startElement(const QString&, const QString&, const QString &name, const QXmlAttributes &attrs)
{
// <provider> ...
if (inProvider == false && name == "provider") {
inProvider = true;
currentProvider = getAttrValue(attrs, "service");
currentBus = getAttrValue(attrs, "bus");
return true;
}
// <properties> ...
if (inProvider == false && name == "properties") {
inProvider = true;
currentProvider = "";
currentBus = "";
return true;
}
// <key> ...
if (inKey == false && inProvider == true && name == "key") {
// Reset all potential key data
currentKeyName = "";
currentKeyType = canonicalizeType (getAttrValue(attrs, "type"));
currentKeyDoc = "";
currentKeyName = getAttrValue(attrs, "name");
inKey = true;
return true;
}
// <type> ...
if (inKeyType == false && inKey == true && name == "type") {
inKeyType = true;
currentKeyType = ""; // Reset type data
return true;
}
// <doc> ...
if (inKeyDoc == false && inKey == true && name == "doc") {
inKeyDoc = true;
currentKeyDoc = ""; // Reset doc data
return true;
}
// complex types
if (inKeyType == true && complexKeyType == false) {
contextWarning() << F_XML << "Key" << currentKeyName << "has a complex type, which is unsupported for now.";
complexKeyType = true;
currentKeyType = "";
}
return true;
}
/// Called for each </element> when we stop parsing it.
bool InfoXmlKeysFinder::endElement(const QString&, const QString&, const QString &name)
{
// ... </provider>
if (inProvider == true && name == "provider") {
inProvider = false;
inKey = false;
inKeyDoc = false;
inKeyType = false;
return true;
}
// ... </key>
if (inKey == true && name == "key") {
// If at least name is ok, add to list
if (currentKeyName != "") {
contextDebug() << F_XML << "Got key:" << currentKeyName;
InfoKeyData data;
data.name = currentKeyName;
data.type = currentKeyType;
data.doc = currentKeyDoc;
data.provider = currentProvider;
data.bus = currentBus;
if (keyDataHash.contains(currentKeyName))
contextWarning() << F_XML << "Key" << currentKeyName << "already defined in this xml file. Overwriting.";
keyDataHash.insert(currentKeyName, data);
}
inKey = false;
inKeyDoc = false;
inKeyType = false;
complexKeyType = false;
return true;
}
// ... </doc>
if (inKeyDoc == true && name == "doc") {
inKeyDoc = false;
return true;
}
// ... </type>
if (inKeyType == true && name == "type") {
inKeyType = false;
return true;
}
return true;
}
/// Called for each bit of textual data. We trim spaces here.
bool InfoXmlKeysFinder::characters(const QString &chars)
{
// <type> CHARS ...
if (inKeyType == true && complexKeyType == false) {
if (currentKeyType != "")
contextWarning() << F_XML << "Key" << currentKeyName << "already has a type. Overwriting.";
currentKeyType = canonicalizeType (chars.trimmed());
return true;
}
// <doc> CHARS ...
if (inKeyDoc == true) {
currentKeyDoc += chars.trimmed();
return true;
}
return true;
}
/* Private */
/// In the given \a attrs atribute list, find the one with \a attrName and return it's value.
/// Returns empty string if attribute not found.
QString InfoXmlKeysFinder::getAttrValue(const QXmlAttributes &attrs, const QString &attrName)
{
for (int i = 0; i< attrs.count(); i++) {
if (attrs.localName(i) == attrName)
return attrs.value(i);
}
return "";
}
// Convert a subset of new-style type names to the currently used
// old-style type names. This way we can slowly fade in new-style
// types.
QString InfoXmlKeysFinder::canonicalizeType (const QString &type)
{
if (type == "bool")
return "TRUTH";
else if (type == "int32")
return "INT";
else if (type == "string")
return "STRING";
else if (type == "double")
return "DOUBLE";
else
return type;
}
<commit_msg>libcontextsubscriber: Fix for a bug introduced in install-core-props branch: Now the non-complex types of all properties (incl. the first one) are parsed correctly from the xml files.<commit_after>/*
* Copyright (C) 2008 Nokia Corporation.
*
* Contact: Marius Vollmer <marius.vollmer@nokia.com>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "infoxmlkeysfinder.h"
#include "logging.h"
#include "loggingfeatures.h"
/*!
\class InfoXmlKeysFinder
\brief Implements a SAX parser to parse xml files with provider/key data.
This class is not exported in the public API. Traditional old-school context-based
parsing logic here.
*/
/// Called when parsing starts.
bool InfoXmlKeysFinder::startDocument()
{
keyDataHash.clear();
inProvider = false;
inKey = false;
inKeyType = false;
inKeyDoc = false;
complexKeyType = false;
return true;
}
/// Called for each <element> when we start parsing it.
bool InfoXmlKeysFinder::startElement(const QString&, const QString&, const QString &name, const QXmlAttributes &attrs)
{
// <provider> ...
if (inProvider == false && name == "provider") {
inProvider = true;
currentProvider = getAttrValue(attrs, "service");
currentBus = getAttrValue(attrs, "bus");
return true;
}
// <properties> ...
if (inProvider == false && name == "properties") {
inProvider = true;
currentProvider = "";
currentBus = "";
return true;
}
// <key> ...
if (inKey == false && inProvider == true && name == "key") {
// Reset all potential key data
currentKeyName = "";
currentKeyType = canonicalizeType (getAttrValue(attrs, "type"));
currentKeyDoc = "";
currentKeyName = getAttrValue(attrs, "name");
inKey = true;
return true;
}
// <type> ...
if (inKeyType == false && inKey == true && name == "type") {
inKeyType = true;
currentKeyType = ""; // Reset type data
return true;
}
// <doc> ...
if (inKeyDoc == false && inKey == true && name == "doc") {
inKeyDoc = true;
currentKeyDoc = ""; // Reset doc data
return true;
}
// complex types
if (inKeyType == true && complexKeyType == false) {
contextWarning() << F_XML << "Key" << currentKeyName << "has a complex type, which is unsupported for now.";
complexKeyType = true;
currentKeyType = "";
}
return true;
}
/// Called for each </element> when we stop parsing it.
bool InfoXmlKeysFinder::endElement(const QString&, const QString&, const QString &name)
{
// ... </provider>
if (inProvider == true && name == "provider") {
inProvider = false;
inKey = false;
inKeyDoc = false;
inKeyType = false;
return true;
}
// ... </key>
if (inKey == true && name == "key") {
// If at least name is ok, add to list
if (currentKeyName != "") {
contextDebug() << F_XML << "Got key:" << currentKeyName;
InfoKeyData data;
data.name = currentKeyName;
data.type = currentKeyType;
data.doc = currentKeyDoc;
data.provider = currentProvider;
data.bus = currentBus;
if (keyDataHash.contains(currentKeyName))
contextWarning() << F_XML << "Key" << currentKeyName << "already defined in this xml file. Overwriting.";
keyDataHash.insert(currentKeyName, data);
}
inKey = false;
inKeyDoc = false;
inKeyType = false;
complexKeyType = false;
return true;
}
// ... </doc>
if (inKeyDoc == true && name == "doc") {
inKeyDoc = false;
return true;
}
// ... </type>
if (inKeyType == true && name == "type") {
inKeyType = false;
return true;
}
return true;
}
/// Called for each bit of textual data. We trim spaces here.
bool InfoXmlKeysFinder::characters(const QString &chars)
{
// <type> CHARS ...
if (inKeyType == true && complexKeyType == false) {
if (currentKeyType != "")
contextWarning() << F_XML << "Key" << currentKeyName << "already has a type. Overwriting.";
currentKeyType = canonicalizeType (chars.trimmed());
return true;
}
// <doc> CHARS ...
if (inKeyDoc == true) {
currentKeyDoc += chars.trimmed();
return true;
}
return true;
}
/* Private */
/// In the given \a attrs atribute list, find the one with \a attrName and return it's value.
/// Returns empty string if attribute not found.
QString InfoXmlKeysFinder::getAttrValue(const QXmlAttributes &attrs, const QString &attrName)
{
for (int i = 0; i< attrs.count(); i++) {
if (attrs.localName(i) == attrName)
return attrs.value(i);
}
return "";
}
// Convert a subset of new-style type names to the currently used
// old-style type names. This way we can slowly fade in new-style
// types.
QString InfoXmlKeysFinder::canonicalizeType (const QString &type)
{
if (type == "bool")
return "TRUTH";
else if (type == "int32")
return "INT";
else if (type == "string")
return "STRING";
else if (type == "double")
return "DOUBLE";
else
return type;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/child_process_host.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/file_path.h"
#include "base/histogram.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/singleton.h"
#include "base/string_util.h"
#include "base/waitable_event.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/env_vars.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/plugin_messages.h"
#include "chrome/common/process_watcher.h"
#include "chrome/common/result_codes.h"
#include "chrome/installer/util/google_update_settings.h"
#if defined(OS_LINUX)
#include "base/linux_util.h"
#endif // OS_LINUX
#if defined(OS_POSIX)
// This is defined in chrome/browser/google_update_settings_posix.cc. It's the
// static string containing the user's unique GUID. We send this in the crash
// report.
namespace google_update {
extern std::string posix_guid;
} // namespace google_update
#endif // OS_POSIX
namespace {
typedef std::list<ChildProcessHost*> ChildProcessList;
// The NotificationTask is used to notify about plugin process connection/
// disconnection. It is needed because the notifications in the
// NotificationService must happen in the main thread.
class ChildNotificationTask : public Task {
public:
ChildNotificationTask(
NotificationType notification_type, ChildProcessInfo* info)
: notification_type_(notification_type), info_(*info) { }
virtual void Run() {
NotificationService::current()->
Notify(notification_type_, NotificationService::AllSources(),
Details<ChildProcessInfo>(&info_));
}
private:
NotificationType notification_type_;
ChildProcessInfo info_;
};
} // namespace
ChildProcessHost::ChildProcessHost(
ProcessType type, ResourceDispatcherHost* resource_dispatcher_host)
: Receiver(type, -1),
ALLOW_THIS_IN_INITIALIZER_LIST(listener_(this)),
resource_dispatcher_host_(resource_dispatcher_host),
opening_channel_(false) {
Singleton<ChildProcessList>::get()->push_back(this);
}
ChildProcessHost::~ChildProcessHost() {
Singleton<ChildProcessList>::get()->remove(this);
if (resource_dispatcher_host_)
resource_dispatcher_host_->CancelRequestsForProcess(id());
}
// static
FilePath ChildProcessHost::GetChildPath(bool allow_self) {
FilePath child_path;
child_path = CommandLine::ForCurrentProcess()->GetSwitchValuePath(
switches::kBrowserSubprocessPath);
if (!child_path.empty())
return child_path;
#if defined(OS_MACOSX)
// On the Mac, the child executable lives at a predefined location within
// the app bundle's versioned directory.
return chrome::GetVersionedDirectory().
Append(chrome::kHelperProcessExecutablePath);
#endif
#if defined(OS_LINUX)
// Use /proc/self/exe rather than our known binary path so updates
// can't swap out the binary from underneath us.
if (allow_self)
return FilePath("/proc/self/exe");
#endif
// On most platforms, the child executable is the same as the current
// executable.
PathService::Get(base::FILE_EXE, &child_path);
return child_path;
}
// static
void ChildProcessHost::SetCrashReporterCommandLine(CommandLine* command_line) {
#if defined(USE_LINUX_BREAKPAD)
const bool unattended = (getenv(env_vars::kHeadless) != NULL);
if (unattended || GoogleUpdateSettings::GetCollectStatsConsent()) {
command_line->AppendSwitchWithValue(switches::kEnableCrashReporter,
ASCIIToWide(google_update::posix_guid +
"," +
base::GetLinuxDistro()));
}
#elif defined(OS_MACOSX)
if (GoogleUpdateSettings::GetCollectStatsConsent())
command_line->AppendSwitchWithValue(switches::kEnableCrashReporter,
ASCIIToWide(google_update::posix_guid));
#endif // OS_MACOSX
}
void ChildProcessHost::Launch(
#if defined(OS_WIN)
const FilePath& exposed_dir,
#elif defined(OS_POSIX)
bool use_zygote,
const base::environment_vector& environ,
#endif
CommandLine* cmd_line) {
child_process_.reset(new ChildProcessLauncher(
#if defined(OS_WIN)
exposed_dir,
#elif defined(OS_POSIX)
use_zygote,
environ,
channel_->GetClientFileDescriptor(),
#endif
cmd_line,
&listener_));
}
bool ChildProcessHost::CreateChannel() {
channel_id_ = GenerateRandomChannelID(this);
channel_.reset(new IPC::Channel(
channel_id_, IPC::Channel::MODE_SERVER, &listener_));
if (!channel_->Connect())
return false;
opening_channel_ = true;
return true;
}
void ChildProcessHost::InstanceCreated() {
Notify(NotificationType::CHILD_INSTANCE_CREATED);
}
bool ChildProcessHost::Send(IPC::Message* msg) {
if (!channel_.get()) {
delete msg;
return false;
}
return channel_->Send(msg);
}
void ChildProcessHost::Notify(NotificationType type) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE, new ChildNotificationTask(type, this));
}
bool ChildProcessHost::DidChildCrash() {
return child_process_->DidProcessCrash();
}
void ChildProcessHost::OnChildDied() {
if (handle() != base::kNullProcessHandle) {
bool did_crash = DidChildCrash();
if (did_crash) {
OnProcessCrashed();
// Report that this child process crashed.
Notify(NotificationType::CHILD_PROCESS_CRASHED);
UMA_HISTOGRAM_COUNTS("ChildProcess.Crashes", this->type());
}
// Notify in the main loop of the disconnection.
Notify(NotificationType::CHILD_PROCESS_HOST_DISCONNECTED);
}
delete this;
}
ChildProcessHost::ListenerHook::ListenerHook(ChildProcessHost* host)
: host_(host) {
}
void ChildProcessHost::ListenerHook::OnMessageReceived(
const IPC::Message& msg) {
#ifdef IPC_MESSAGE_LOG_ENABLED
IPC::Logging* logger = IPC::Logging::current();
if (msg.type() == IPC_LOGGING_ID) {
logger->OnReceivedLoggingMessage(msg);
return;
}
if (logger->Enabled())
logger->OnPreDispatchMessage(msg);
#endif
bool msg_is_ok = true;
bool handled = false;
if (host_->resource_dispatcher_host_)
host_->resource_dispatcher_host_->OnMessageReceived(
msg, host_, &msg_is_ok);
if (!handled) {
if (msg.type() == PluginProcessHostMsg_ShutdownRequest::ID) {
// Must remove the process from the list now, in case it gets used for a
// new instance before our watcher tells us that the process terminated.
Singleton<ChildProcessList>::get()->remove(host_);
if (host_->CanShutdown())
host_->Send(new PluginProcessMsg_Shutdown());
} else {
host_->OnMessageReceived(msg);
}
}
if (!msg_is_ok)
base::KillProcess(host_->handle(), ResultCodes::KILLED_BAD_MESSAGE, false);
#ifdef IPC_MESSAGE_LOG_ENABLED
if (logger->Enabled())
logger->OnPostDispatchMessage(msg, host_->channel_id_);
#endif
}
void ChildProcessHost::ListenerHook::OnChannelConnected(int32 peer_pid) {
host_->opening_channel_ = false;
host_->OnChannelConnected(peer_pid);
#if defined(IPC_MESSAGE_LOG_ENABLED)
bool enabled = IPC::Logging::current()->Enabled();
host_->Send(new PluginProcessMsg_SetIPCLoggingEnabled(enabled));
#endif
host_->Send(new PluginProcessMsg_AskBeforeShutdown());
// Notify in the main loop of the connection.
host_->Notify(NotificationType::CHILD_PROCESS_HOST_CONNECTED);
}
void ChildProcessHost::ListenerHook::OnChannelError() {
host_->opening_channel_ = false;
host_->OnChannelError();
// This will delete host_, which will also destroy this!
host_->OnChildDied();
}
void ChildProcessHost::ListenerHook::OnProcessLaunched() {
if (!host_->child_process_->GetHandle()) {
delete this;
return;
}
host_->set_handle(host_->child_process_->GetHandle());
host_->OnProcessLaunched();
}
ChildProcessHost::Iterator::Iterator()
: all_(true), type_(UNKNOWN_PROCESS) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)) <<
"ChildProcessInfo::Iterator must be used on the IO thread.";
iterator_ = Singleton<ChildProcessList>::get()->begin();
}
ChildProcessHost::Iterator::Iterator(ProcessType type)
: all_(false), type_(type) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)) <<
"ChildProcessInfo::Iterator must be used on the IO thread.";
iterator_ = Singleton<ChildProcessList>::get()->begin();
if (!Done() && (*iterator_)->type() != type_)
++(*this);
}
ChildProcessHost* ChildProcessHost::Iterator::operator++() {
do {
++iterator_;
if (Done())
break;
if (!all_ && (*iterator_)->type() != type_)
continue;
return *iterator_;
} while (true);
return NULL;
}
bool ChildProcessHost::Iterator::Done() {
return iterator_ == Singleton<ChildProcessList>::get()->end();
}
void ChildProcessHost::ForceShutdown() {
Singleton<ChildProcessList>::get()->remove(this);
Send(new PluginProcessMsg_Shutdown());
}
<commit_msg>Make handled set to true if ResourceDispatcherHost uses a message.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/child_process_host.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/file_path.h"
#include "base/histogram.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/singleton.h"
#include "base/string_util.h"
#include "base/waitable_event.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/env_vars.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/plugin_messages.h"
#include "chrome/common/process_watcher.h"
#include "chrome/common/result_codes.h"
#include "chrome/installer/util/google_update_settings.h"
#if defined(OS_LINUX)
#include "base/linux_util.h"
#endif // OS_LINUX
#if defined(OS_POSIX)
// This is defined in chrome/browser/google_update_settings_posix.cc. It's the
// static string containing the user's unique GUID. We send this in the crash
// report.
namespace google_update {
extern std::string posix_guid;
} // namespace google_update
#endif // OS_POSIX
namespace {
typedef std::list<ChildProcessHost*> ChildProcessList;
// The NotificationTask is used to notify about plugin process connection/
// disconnection. It is needed because the notifications in the
// NotificationService must happen in the main thread.
class ChildNotificationTask : public Task {
public:
ChildNotificationTask(
NotificationType notification_type, ChildProcessInfo* info)
: notification_type_(notification_type), info_(*info) { }
virtual void Run() {
NotificationService::current()->
Notify(notification_type_, NotificationService::AllSources(),
Details<ChildProcessInfo>(&info_));
}
private:
NotificationType notification_type_;
ChildProcessInfo info_;
};
} // namespace
ChildProcessHost::ChildProcessHost(
ProcessType type, ResourceDispatcherHost* resource_dispatcher_host)
: Receiver(type, -1),
ALLOW_THIS_IN_INITIALIZER_LIST(listener_(this)),
resource_dispatcher_host_(resource_dispatcher_host),
opening_channel_(false) {
Singleton<ChildProcessList>::get()->push_back(this);
}
ChildProcessHost::~ChildProcessHost() {
Singleton<ChildProcessList>::get()->remove(this);
if (resource_dispatcher_host_)
resource_dispatcher_host_->CancelRequestsForProcess(id());
}
// static
FilePath ChildProcessHost::GetChildPath(bool allow_self) {
FilePath child_path;
child_path = CommandLine::ForCurrentProcess()->GetSwitchValuePath(
switches::kBrowserSubprocessPath);
if (!child_path.empty())
return child_path;
#if defined(OS_MACOSX)
// On the Mac, the child executable lives at a predefined location within
// the app bundle's versioned directory.
return chrome::GetVersionedDirectory().
Append(chrome::kHelperProcessExecutablePath);
#endif
#if defined(OS_LINUX)
// Use /proc/self/exe rather than our known binary path so updates
// can't swap out the binary from underneath us.
if (allow_self)
return FilePath("/proc/self/exe");
#endif
// On most platforms, the child executable is the same as the current
// executable.
PathService::Get(base::FILE_EXE, &child_path);
return child_path;
}
// static
void ChildProcessHost::SetCrashReporterCommandLine(CommandLine* command_line) {
#if defined(USE_LINUX_BREAKPAD)
const bool unattended = (getenv(env_vars::kHeadless) != NULL);
if (unattended || GoogleUpdateSettings::GetCollectStatsConsent()) {
command_line->AppendSwitchWithValue(switches::kEnableCrashReporter,
ASCIIToWide(google_update::posix_guid +
"," +
base::GetLinuxDistro()));
}
#elif defined(OS_MACOSX)
if (GoogleUpdateSettings::GetCollectStatsConsent())
command_line->AppendSwitchWithValue(switches::kEnableCrashReporter,
ASCIIToWide(google_update::posix_guid));
#endif // OS_MACOSX
}
void ChildProcessHost::Launch(
#if defined(OS_WIN)
const FilePath& exposed_dir,
#elif defined(OS_POSIX)
bool use_zygote,
const base::environment_vector& environ,
#endif
CommandLine* cmd_line) {
child_process_.reset(new ChildProcessLauncher(
#if defined(OS_WIN)
exposed_dir,
#elif defined(OS_POSIX)
use_zygote,
environ,
channel_->GetClientFileDescriptor(),
#endif
cmd_line,
&listener_));
}
bool ChildProcessHost::CreateChannel() {
channel_id_ = GenerateRandomChannelID(this);
channel_.reset(new IPC::Channel(
channel_id_, IPC::Channel::MODE_SERVER, &listener_));
if (!channel_->Connect())
return false;
opening_channel_ = true;
return true;
}
void ChildProcessHost::InstanceCreated() {
Notify(NotificationType::CHILD_INSTANCE_CREATED);
}
bool ChildProcessHost::Send(IPC::Message* msg) {
if (!channel_.get()) {
delete msg;
return false;
}
return channel_->Send(msg);
}
void ChildProcessHost::Notify(NotificationType type) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE, new ChildNotificationTask(type, this));
}
bool ChildProcessHost::DidChildCrash() {
return child_process_->DidProcessCrash();
}
void ChildProcessHost::OnChildDied() {
if (handle() != base::kNullProcessHandle) {
bool did_crash = DidChildCrash();
if (did_crash) {
OnProcessCrashed();
// Report that this child process crashed.
Notify(NotificationType::CHILD_PROCESS_CRASHED);
UMA_HISTOGRAM_COUNTS("ChildProcess.Crashes", this->type());
}
// Notify in the main loop of the disconnection.
Notify(NotificationType::CHILD_PROCESS_HOST_DISCONNECTED);
}
delete this;
}
ChildProcessHost::ListenerHook::ListenerHook(ChildProcessHost* host)
: host_(host) {
}
void ChildProcessHost::ListenerHook::OnMessageReceived(
const IPC::Message& msg) {
#ifdef IPC_MESSAGE_LOG_ENABLED
IPC::Logging* logger = IPC::Logging::current();
if (msg.type() == IPC_LOGGING_ID) {
logger->OnReceivedLoggingMessage(msg);
return;
}
if (logger->Enabled())
logger->OnPreDispatchMessage(msg);
#endif
bool msg_is_ok = true;
bool handled = false;
if (host_->resource_dispatcher_host_) {
handled = host_->resource_dispatcher_host_->OnMessageReceived(
msg, host_, &msg_is_ok);
}
if (!handled) {
if (msg.type() == PluginProcessHostMsg_ShutdownRequest::ID) {
// Must remove the process from the list now, in case it gets used for a
// new instance before our watcher tells us that the process terminated.
Singleton<ChildProcessList>::get()->remove(host_);
if (host_->CanShutdown())
host_->Send(new PluginProcessMsg_Shutdown());
} else {
host_->OnMessageReceived(msg);
}
}
if (!msg_is_ok)
base::KillProcess(host_->handle(), ResultCodes::KILLED_BAD_MESSAGE, false);
#ifdef IPC_MESSAGE_LOG_ENABLED
if (logger->Enabled())
logger->OnPostDispatchMessage(msg, host_->channel_id_);
#endif
}
void ChildProcessHost::ListenerHook::OnChannelConnected(int32 peer_pid) {
host_->opening_channel_ = false;
host_->OnChannelConnected(peer_pid);
#if defined(IPC_MESSAGE_LOG_ENABLED)
bool enabled = IPC::Logging::current()->Enabled();
host_->Send(new PluginProcessMsg_SetIPCLoggingEnabled(enabled));
#endif
host_->Send(new PluginProcessMsg_AskBeforeShutdown());
// Notify in the main loop of the connection.
host_->Notify(NotificationType::CHILD_PROCESS_HOST_CONNECTED);
}
void ChildProcessHost::ListenerHook::OnChannelError() {
host_->opening_channel_ = false;
host_->OnChannelError();
// This will delete host_, which will also destroy this!
host_->OnChildDied();
}
void ChildProcessHost::ListenerHook::OnProcessLaunched() {
if (!host_->child_process_->GetHandle()) {
delete this;
return;
}
host_->set_handle(host_->child_process_->GetHandle());
host_->OnProcessLaunched();
}
ChildProcessHost::Iterator::Iterator()
: all_(true), type_(UNKNOWN_PROCESS) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)) <<
"ChildProcessInfo::Iterator must be used on the IO thread.";
iterator_ = Singleton<ChildProcessList>::get()->begin();
}
ChildProcessHost::Iterator::Iterator(ProcessType type)
: all_(false), type_(type) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)) <<
"ChildProcessInfo::Iterator must be used on the IO thread.";
iterator_ = Singleton<ChildProcessList>::get()->begin();
if (!Done() && (*iterator_)->type() != type_)
++(*this);
}
ChildProcessHost* ChildProcessHost::Iterator::operator++() {
do {
++iterator_;
if (Done())
break;
if (!all_ && (*iterator_)->type() != type_)
continue;
return *iterator_;
} while (true);
return NULL;
}
bool ChildProcessHost::Iterator::Done() {
return iterator_ == Singleton<ChildProcessList>::get()->end();
}
void ChildProcessHost::ForceShutdown() {
Singleton<ChildProcessList>::get()->remove(this);
Send(new PluginProcessMsg_Shutdown());
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/main_menu.h"
#include <string>
#include <vector>
#include "app/gfx/insets.h"
#include "app/resource_bundle.h"
#include "base/command_line.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_view_host_factory.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/renderer_host/render_widget_host_view_gtk.h"
#include "chrome/browser/renderer_host/site_instance.h"
#include "chrome/browser/renderer_preferences_util.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/render_view_host_delegate_helper.h"
#include "grit/app_resources.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "views/background.h"
#include "views/painter.h"
#include "views/screen.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_gtk.h"
namespace chromeos {
// Initial size of the renderer. This is contained within a window whose size
// is set to the size of the image IDR_MAIN_MENU_BUTTON_DROP_DOWN.
static const int kRendererX = 0;
static const int kRendererY = 25;
static const int kRendererWidth = 250;
static const int kRendererHeight = 400;
// Insets defining the regions that are stretched and titled to create the
// background of the popup. These constants are fed into
// Painter::CreateImagePainter as the insets, see it for details.
static const int kBackgroundImageTop = 27;
static const int kBackgroundImageLeft = 85;
static const int kBackgroundImageBottom = 10;
static const int kBackgroundImageRight = 8;
// Command line switch for specifying url of the page.
static const wchar_t kURLSwitch[] = L"main-menu-url";
// Command line switch for specifying the size of the main menu. The default is
// full screen.
static const wchar_t kMenuSizeSwitch[] = L"main-menu-size";
// URL of the page to load. This is ignored if kURLSwitch is specified.
static const char kMenuURL[] = "http://goto.ext.google.com/crux-home";
// Returns the size of the popup. By default the popup is sized slightly
// larger than full screen, but can be overriden by the command line switch
// kMenuSizeSwitch.
static gfx::Size GetPopupSize() {
std::wstring cl_size =
CommandLine::ForCurrentProcess()->GetSwitchValue(kMenuSizeSwitch);
if (!cl_size.empty()) {
std::vector<std::string> chunks;
SplitString(WideToUTF8(cl_size), 'x', &chunks);
if (chunks.size() == 2)
return gfx::Size(StringToInt(chunks[0]), StringToInt(chunks[1]));
}
gfx::Size size =
views::Screen::GetMonitorAreaNearestPoint(gfx::Point(0, 0)).size();
// When full screen we don't want to see the drop shadow. Adjust the width
// so the drop shadow ends up off screen.
size.Enlarge(kBackgroundImageRight, kBackgroundImageBottom);
return size;
}
// Returns the size for the renderer widget host view given the specified
// size of the popup.
static gfx::Size CalculateRWHVSize(const gfx::Size& popup_size) {
return gfx::Size(popup_size.width() - kRendererX - kBackgroundImageRight,
popup_size.height() - kRendererY - kBackgroundImageBottom);
}
// Returns the URL of the menu.
static GURL GetMenuURL() {
std::wstring url_string =
CommandLine::ForCurrentProcess()->GetSwitchValue(kURLSwitch);
if (!url_string.empty())
return GURL(WideToUTF8(url_string));
return GURL(kMenuURL);
}
// static
void MainMenu::Show(Browser* browser) {
MainMenu::Get()->ShowImpl(browser);
}
// static
void MainMenu::ScheduleCreation() {
MessageLoop::current()->PostDelayedTask(FROM_HERE, new LoadTask(), 5000);
}
MainMenu::~MainMenu() {
// NOTE: we leak the menu_rvh_ and popup_ as by the time we get here the
// message loop and notification services have been shutdown.
// TODO(sky): fix this.
// menu_rvh_->Shutdown();
// popup_->CloseNow();
}
MainMenu::MainMenu()
: browser_(NULL),
popup_(NULL),
site_instance_(NULL),
menu_rvh_(NULL),
rwhv_(NULL),
ALLOW_THIS_IN_INITIALIZER_LIST(tab_contents_delegate_(this)),
ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)),
has_shown_(false) {
SkBitmap* drop_down_image = ResourceBundle::GetSharedInstance().
GetBitmapNamed(IDR_MAIN_MENU_BUTTON_DROP_DOWN);
views::WidgetGtk* menu_popup =
new views::WidgetGtk(views::WidgetGtk::TYPE_POPUP);
popup_ = menu_popup;
// The background image has transparency, so we make the window transparent.
menu_popup->MakeTransparent();
gfx::Size popup_size = GetPopupSize();
menu_popup->Init(NULL, gfx::Rect(0, 0, popup_size.width(),
popup_size.height()));
views::Painter* painter = views::Painter::CreateImagePainter(
*drop_down_image,
gfx::Insets(kBackgroundImageTop, kBackgroundImageLeft,
kBackgroundImageBottom, kBackgroundImageRight),
false);
menu_popup->GetRootView()->set_background(
views::Background::CreateBackgroundPainter(true, painter));
GURL menu_url(GetMenuURL());
DCHECK(BrowserList::begin() != BrowserList::end());
// TODO(sky): this shouldn't pick a random profile to use.
Profile* profile = (*BrowserList::begin())->profile();
site_instance_ = SiteInstance::CreateSiteInstanceForURL(profile, menu_url);
menu_rvh_ = new RenderViewHost(site_instance_, this, MSG_ROUTING_NONE);
rwhv_ = new RenderWidgetHostViewGtk(menu_rvh_);
rwhv_->InitAsChild();
menu_rvh_->CreateRenderView(profile->GetRequestContext());
menu_popup->AddChild(rwhv_->GetNativeView());
gfx::Size rwhv_size = CalculateRWHVSize(popup_size);
menu_popup->PositionChild(rwhv_->GetNativeView(), kRendererX, kRendererY,
rwhv_size.width(), rwhv_size.height());
rwhv_->SetSize(rwhv_size);
menu_rvh_->NavigateToURL(menu_url);
}
// static
MainMenu* MainMenu::Get() {
return Singleton<MainMenu>::get();
}
void MainMenu::ShowImpl(Browser* browser) {
Cleanup();
browser_ = browser;
popup_->Show();
GtkWidget* rwhv_widget = rwhv_->GetNativeView();
if (!has_shown_) {
has_shown_ = true;
gtk_widget_realize(rwhv_widget);
g_signal_connect(rwhv_widget, "button-press-event",
G_CALLBACK(CallButtonPressEvent), this);
}
// Do a mouse grab on the renderer widget host view's widget so that we can
// close the popup if the user clicks anywhere else. And do a keyboard
// grab so that we get all key events.
gdk_pointer_grab(rwhv_widget->window, FALSE,
static_cast<GdkEventMask>(
GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK |
GDK_POINTER_MOTION_MASK),
NULL, NULL, GDK_CURRENT_TIME);
gdk_keyboard_grab(rwhv_widget->window, FALSE, GDK_CURRENT_TIME);
}
void MainMenu::Hide() {
gdk_keyboard_ungrab(GDK_CURRENT_TIME);
gdk_pointer_ungrab(GDK_CURRENT_TIME);
popup_->Hide();
// The stack may have pending_contents_ on it. Delay deleting the
// pending_contents_ as TabContents doesn't deal well with being deleted
// while on the stack.
MessageLoop::current()->PostTask(FROM_HERE,
method_factory_.NewRunnableMethod(&MainMenu::Cleanup));
}
void MainMenu::Cleanup() {
pending_contents_.reset(NULL);
method_factory_.RevokeAll();
}
// static
gboolean MainMenu::CallButtonPressEvent(GtkWidget* widget,
GdkEventButton* event,
MainMenu* menu) {
return menu->OnButtonPressEvent(widget, event);
}
gboolean MainMenu::OnButtonPressEvent(GtkWidget* widget,
GdkEventButton* event) {
if (event->x < 0 || event->y < 0 ||
event->x >= widget->allocation.width ||
event->y >= widget->allocation.height) {
// The user clicked outside the bounds of the menu, delete the main which
// results in closing it.
Hide();
}
return FALSE;
}
void MainMenu::RequestMove(const gfx::Rect& new_bounds) {
// Invoking PositionChild results in a gtk signal that triggers attempting to
// to resize the window. We need to set the size request so that it resizes
// correctly when this happens.
gtk_widget_set_size_request(popup_->GetNativeView(),
new_bounds.width(), new_bounds.height());
gfx::Size rwhv_size = CalculateRWHVSize(new_bounds.size());
popup_->PositionChild(rwhv_->GetNativeView(), kRendererX, kRendererY,
rwhv_size.width(), rwhv_size.height());
popup_->SetBounds(new_bounds);
rwhv_->SetSize(rwhv_size);
}
RendererPreferences MainMenu::GetRendererPrefs(Profile* profile) const {
return renderer_preferences_util::GetInitedRendererPreferences(profile);
}
void MainMenu::CreateNewWindow(int route_id) {
if (pending_contents_.get()) {
NOTREACHED();
return;
}
helper_.CreateNewWindow(route_id, browser_->profile(), site_instance_,
DOMUIFactory::GetDOMUIType(GURL(GetMenuURL())),
NULL);
pending_contents_.reset(helper_.GetCreatedWindow(route_id));
pending_contents_->set_delegate(&tab_contents_delegate_);
}
void MainMenu::ShowCreatedWindow(int route_id,
WindowOpenDisposition disposition,
const gfx::Rect& initial_pos,
bool user_gesture,
const GURL& creator_url) {
if (disposition == NEW_POPUP) {
pending_contents_->set_delegate(NULL);
browser_->GetSelectedTabContents()->AddNewContents(
pending_contents_.release(), disposition, initial_pos, user_gesture,
creator_url);
Hide();
}
}
void MainMenu::TabContentsDelegateImpl::OpenURLFromTab(
TabContents* source,
const GURL& url,
const GURL& referrer,
WindowOpenDisposition disposition,
PageTransition::Type transition) {
menu_->browser_->OpenURL(url, referrer, NEW_FOREGROUND_TAB,
PageTransition::LINK);
menu_->Hide();
}
// LoadTask -------------------------------------------------------------------
void MainMenu::LoadTask::Run() {
MainMenu::Get();
}
} // namespace chromeos
<commit_msg>Fixes bug in MainMenu that if there are no browsers around when timer fires we get a crash.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/main_menu.h"
#include <string>
#include <vector>
#include "app/gfx/insets.h"
#include "app/resource_bundle.h"
#include "base/command_line.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_view_host_factory.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/renderer_host/render_widget_host_view_gtk.h"
#include "chrome/browser/renderer_host/site_instance.h"
#include "chrome/browser/renderer_preferences_util.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/render_view_host_delegate_helper.h"
#include "grit/app_resources.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "views/background.h"
#include "views/painter.h"
#include "views/screen.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_gtk.h"
namespace chromeos {
// Initial size of the renderer. This is contained within a window whose size
// is set to the size of the image IDR_MAIN_MENU_BUTTON_DROP_DOWN.
static const int kRendererX = 0;
static const int kRendererY = 25;
static const int kRendererWidth = 250;
static const int kRendererHeight = 400;
// Insets defining the regions that are stretched and titled to create the
// background of the popup. These constants are fed into
// Painter::CreateImagePainter as the insets, see it for details.
static const int kBackgroundImageTop = 27;
static const int kBackgroundImageLeft = 85;
static const int kBackgroundImageBottom = 10;
static const int kBackgroundImageRight = 8;
// Command line switch for specifying url of the page.
static const wchar_t kURLSwitch[] = L"main-menu-url";
// Command line switch for specifying the size of the main menu. The default is
// full screen.
static const wchar_t kMenuSizeSwitch[] = L"main-menu-size";
// URL of the page to load. This is ignored if kURLSwitch is specified.
static const char kMenuURL[] = "http://goto.ext.google.com/crux-home";
// Returns the size of the popup. By default the popup is sized slightly
// larger than full screen, but can be overriden by the command line switch
// kMenuSizeSwitch.
static gfx::Size GetPopupSize() {
std::wstring cl_size =
CommandLine::ForCurrentProcess()->GetSwitchValue(kMenuSizeSwitch);
if (!cl_size.empty()) {
std::vector<std::string> chunks;
SplitString(WideToUTF8(cl_size), 'x', &chunks);
if (chunks.size() == 2)
return gfx::Size(StringToInt(chunks[0]), StringToInt(chunks[1]));
}
gfx::Size size =
views::Screen::GetMonitorAreaNearestPoint(gfx::Point(0, 0)).size();
// When full screen we don't want to see the drop shadow. Adjust the width
// so the drop shadow ends up off screen.
size.Enlarge(kBackgroundImageRight, kBackgroundImageBottom);
return size;
}
// Returns the size for the renderer widget host view given the specified
// size of the popup.
static gfx::Size CalculateRWHVSize(const gfx::Size& popup_size) {
return gfx::Size(popup_size.width() - kRendererX - kBackgroundImageRight,
popup_size.height() - kRendererY - kBackgroundImageBottom);
}
// Returns the URL of the menu.
static GURL GetMenuURL() {
std::wstring url_string =
CommandLine::ForCurrentProcess()->GetSwitchValue(kURLSwitch);
if (!url_string.empty())
return GURL(WideToUTF8(url_string));
return GURL(kMenuURL);
}
// static
void MainMenu::Show(Browser* browser) {
MainMenu::Get()->ShowImpl(browser);
}
// static
void MainMenu::ScheduleCreation() {
MessageLoop::current()->PostDelayedTask(FROM_HERE, new LoadTask(), 5000);
}
MainMenu::~MainMenu() {
// NOTE: we leak the menu_rvh_ and popup_ as by the time we get here the
// message loop and notification services have been shutdown.
// TODO(sky): fix this.
// menu_rvh_->Shutdown();
// popup_->CloseNow();
}
MainMenu::MainMenu()
: browser_(NULL),
popup_(NULL),
site_instance_(NULL),
menu_rvh_(NULL),
rwhv_(NULL),
ALLOW_THIS_IN_INITIALIZER_LIST(tab_contents_delegate_(this)),
ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)),
has_shown_(false) {
SkBitmap* drop_down_image = ResourceBundle::GetSharedInstance().
GetBitmapNamed(IDR_MAIN_MENU_BUTTON_DROP_DOWN);
views::WidgetGtk* menu_popup =
new views::WidgetGtk(views::WidgetGtk::TYPE_POPUP);
popup_ = menu_popup;
// The background image has transparency, so we make the window transparent.
menu_popup->MakeTransparent();
gfx::Size popup_size = GetPopupSize();
menu_popup->Init(NULL, gfx::Rect(0, 0, popup_size.width(),
popup_size.height()));
views::Painter* painter = views::Painter::CreateImagePainter(
*drop_down_image,
gfx::Insets(kBackgroundImageTop, kBackgroundImageLeft,
kBackgroundImageBottom, kBackgroundImageRight),
false);
menu_popup->GetRootView()->set_background(
views::Background::CreateBackgroundPainter(true, painter));
GURL menu_url(GetMenuURL());
DCHECK(BrowserList::begin() != BrowserList::end());
// TODO(sky): this shouldn't pick a random profile to use.
Profile* profile = (*BrowserList::begin())->profile();
site_instance_ = SiteInstance::CreateSiteInstanceForURL(profile, menu_url);
menu_rvh_ = new RenderViewHost(site_instance_, this, MSG_ROUTING_NONE);
rwhv_ = new RenderWidgetHostViewGtk(menu_rvh_);
rwhv_->InitAsChild();
menu_rvh_->CreateRenderView(profile->GetRequestContext());
menu_popup->AddChild(rwhv_->GetNativeView());
gfx::Size rwhv_size = CalculateRWHVSize(popup_size);
menu_popup->PositionChild(rwhv_->GetNativeView(), kRendererX, kRendererY,
rwhv_size.width(), rwhv_size.height());
rwhv_->SetSize(rwhv_size);
menu_rvh_->NavigateToURL(menu_url);
}
// static
MainMenu* MainMenu::Get() {
return Singleton<MainMenu>::get();
}
void MainMenu::ShowImpl(Browser* browser) {
Cleanup();
browser_ = browser;
popup_->Show();
GtkWidget* rwhv_widget = rwhv_->GetNativeView();
if (!has_shown_) {
has_shown_ = true;
gtk_widget_realize(rwhv_widget);
g_signal_connect(rwhv_widget, "button-press-event",
G_CALLBACK(CallButtonPressEvent), this);
}
// Do a mouse grab on the renderer widget host view's widget so that we can
// close the popup if the user clicks anywhere else. And do a keyboard
// grab so that we get all key events.
gdk_pointer_grab(rwhv_widget->window, FALSE,
static_cast<GdkEventMask>(
GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK |
GDK_POINTER_MOTION_MASK),
NULL, NULL, GDK_CURRENT_TIME);
gdk_keyboard_grab(rwhv_widget->window, FALSE, GDK_CURRENT_TIME);
}
void MainMenu::Hide() {
gdk_keyboard_ungrab(GDK_CURRENT_TIME);
gdk_pointer_ungrab(GDK_CURRENT_TIME);
popup_->Hide();
// The stack may have pending_contents_ on it. Delay deleting the
// pending_contents_ as TabContents doesn't deal well with being deleted
// while on the stack.
MessageLoop::current()->PostTask(FROM_HERE,
method_factory_.NewRunnableMethod(&MainMenu::Cleanup));
}
void MainMenu::Cleanup() {
pending_contents_.reset(NULL);
method_factory_.RevokeAll();
}
// static
gboolean MainMenu::CallButtonPressEvent(GtkWidget* widget,
GdkEventButton* event,
MainMenu* menu) {
return menu->OnButtonPressEvent(widget, event);
}
gboolean MainMenu::OnButtonPressEvent(GtkWidget* widget,
GdkEventButton* event) {
if (event->x < 0 || event->y < 0 ||
event->x >= widget->allocation.width ||
event->y >= widget->allocation.height) {
// The user clicked outside the bounds of the menu, delete the main which
// results in closing it.
Hide();
}
return FALSE;
}
void MainMenu::RequestMove(const gfx::Rect& new_bounds) {
// Invoking PositionChild results in a gtk signal that triggers attempting to
// to resize the window. We need to set the size request so that it resizes
// correctly when this happens.
gtk_widget_set_size_request(popup_->GetNativeView(),
new_bounds.width(), new_bounds.height());
gfx::Size rwhv_size = CalculateRWHVSize(new_bounds.size());
popup_->PositionChild(rwhv_->GetNativeView(), kRendererX, kRendererY,
rwhv_size.width(), rwhv_size.height());
popup_->SetBounds(new_bounds);
rwhv_->SetSize(rwhv_size);
}
RendererPreferences MainMenu::GetRendererPrefs(Profile* profile) const {
return renderer_preferences_util::GetInitedRendererPreferences(profile);
}
void MainMenu::CreateNewWindow(int route_id) {
if (pending_contents_.get()) {
NOTREACHED();
return;
}
helper_.CreateNewWindow(route_id, browser_->profile(), site_instance_,
DOMUIFactory::GetDOMUIType(GURL(GetMenuURL())),
NULL);
pending_contents_.reset(helper_.GetCreatedWindow(route_id));
pending_contents_->set_delegate(&tab_contents_delegate_);
}
void MainMenu::ShowCreatedWindow(int route_id,
WindowOpenDisposition disposition,
const gfx::Rect& initial_pos,
bool user_gesture,
const GURL& creator_url) {
if (disposition == NEW_POPUP) {
pending_contents_->set_delegate(NULL);
browser_->GetSelectedTabContents()->AddNewContents(
pending_contents_.release(), disposition, initial_pos, user_gesture,
creator_url);
Hide();
}
}
void MainMenu::TabContentsDelegateImpl::OpenURLFromTab(
TabContents* source,
const GURL& url,
const GURL& referrer,
WindowOpenDisposition disposition,
PageTransition::Type transition) {
menu_->browser_->OpenURL(url, referrer, NEW_FOREGROUND_TAB,
PageTransition::LINK);
menu_->Hide();
}
// LoadTask -------------------------------------------------------------------
void MainMenu::LoadTask::Run() {
if (BrowserList::begin() == BrowserList::end())
return; // No browser are around. Generally only happens during testing.
MainMenu::Get();
}
} // namespace chromeos
<|endoftext|> |
<commit_before>#pragma once
#include <bts/blockchain/chain_database.hpp>
#include <bts/wallet/wallet.hpp>
#include <bts/net/node.hpp>
#include <bts/rpc/rpc_client_api.hpp>
#include <bts/api/common_api.hpp>
#include <bts/rpc_stubs/common_api_client.hpp>
#include <fc/thread/thread.hpp>
#include <fc/log/logger_config.hpp>
#include <memory>
#include <boost/program_options.hpp>
namespace bts { namespace rpc {
class rpc_server;
typedef std::shared_ptr<rpc_server> rpc_server_ptr;
} }
namespace bts { namespace cli {
class cli;
}};
namespace bts { namespace client {
using namespace bts::blockchain;
using namespace bts::wallet;
using namespace bts::mail;
boost::program_options::variables_map parse_option_variables(int argc, char** argv);
fc::path get_data_dir(const boost::program_options::variables_map& option_variables);
fc::variant_object version_info();
namespace detail { class client_impl; }
using namespace bts::rpc;
struct rpc_server_config
{
rpc_server_config()
: enable(false),
rpc_endpoint(fc::ip::endpoint::from_string("127.0.0.1:0")),
httpd_endpoint(fc::ip::endpoint::from_string("127.0.0.1:0")),
htdocs("./htdocs")
{}
bool enable;
std::string rpc_user;
std::string rpc_password;
fc::ip::endpoint rpc_endpoint;
fc::ip::endpoint httpd_endpoint;
fc::path htdocs;
bool is_valid() const; /* Currently just checks if rpc port is set */
};
struct chain_server_config
{
chain_server_config()
: enabled(false),
listen_port(0)
{}
bool enabled;
uint16_t listen_port;
};
struct config
{
config( ) :
default_peers(vector<string>{"104.131.204.143:", "54.77.61.238:", "54.77.248.208:"}),
mail_server_enabled(false),
wallet_enabled(true),
ignore_console(false),
use_upnp(true),
maximum_number_of_connections(BTS_NET_DEFAULT_MAX_CONNECTIONS) ,
delegate_server( fc::ip::endpoint::from_string("0.0.0.0:0") ),
default_delegate_peers( vector<string>({"107.170.30.182:9988"}) )
{
#ifdef BTS_TEST_NETWORK
uint32_t port = BTS_NET_TEST_P2P_PORT + BTS_TEST_NETWORK_VERSION;
#else
uint32_t port = BTS_NET_DEFAULT_P2P_PORT;
#endif
default_peers[0] += fc::to_string( port );
default_peers[1] += fc::to_string( port + 100 );
default_peers[2] += fc::to_string( port + 200 );
logging = fc::logging_config::default_config();
}
rpc_server_config rpc;
vector<string> default_peers;
vector<string> chain_servers;
chain_server_config chain_server;
bool mail_server_enabled;
bool wallet_enabled;
bool ignore_console;
bool use_upnp;
optional<fc::path> genesis_config;
uint16_t maximum_number_of_connections;
fc::logging_config logging;
fc::ip::endpoint delegate_server;
vector<string> default_delegate_peers;
fc::optional<std::string> growl_notify_endpoint;
fc::optional<std::string> growl_password;
fc::optional<std::string> growl_bitshares_client_identifier;
};
/**
* @class client
* @brief integrates the network, wallet, and blockchain
*
*/
class client : public bts::rpc_stubs::common_api_client,
public std::enable_shared_from_this<client>
{
public:
client();
client(bts::net::simulated_network_ptr network_to_connect_to);
void simulate_disconnect( bool state );
virtual ~client();
void start_networking(std::function<void()> network_started_callback = std::function<void()>());
void configure_from_command_line(int argc, char** argv);
fc::future<void> start();
void open(const path& data_dir,
optional<fc::path> genesis_file_path = optional<fc::path>(),
std::function<void(float)> reindex_status_callback = std::function<void(float)>());
void init_cli();
void set_daemon_mode(bool daemon_mode);
chain_database_ptr get_chain()const;
wallet_ptr get_wallet()const;
mail_server_ptr get_mail_server()const;
bts::rpc::rpc_server_ptr get_rpc_server()const;
bts::net::node_ptr get_node()const;
fc::path get_data_dir()const;
// returns true if the client is connected to the network
bool is_connected() const;
bts::net::node_id_t get_node_id() const;
const config& configure(const fc::path& configuration_directory);
// functions for taking command-line parameters and passing them on to the p2p node
void listen_on_port( uint16_t port_to_listen, bool wait_if_not_available);
void accept_incoming_p2p_connections(bool accept);
void listen_to_p2p_network();
static fc::ip::endpoint string_to_endpoint(const std::string& remote_endpoint);
void add_node( const string& remote_endpoint );
void connect_to_peer( const string& remote_endpoint );
void connect_to_p2p_network();
fc::ip::endpoint get_p2p_listening_endpoint() const;
bool handle_message(const bts::net::message&, bool sync_mode);
void sync_status(uint32_t item_type, uint32_t item_count);
protected:
virtual bts::api::common_api* get_impl() const override;
private:
unique_ptr<detail::client_impl> my;
};
typedef shared_ptr<client> client_ptr;
/* Message broadcast on the network to notify all clients of some important information
(security vulnerability, new version, that sort of thing) */
class client_notification
{
public:
fc::time_point_sec timestamp;
string message;
fc::ecc::compact_signature signature;
//client_notification();
fc::sha256 digest() const;
void sign(const fc::ecc::private_key& key);
fc::ecc::public_key signee() const;
};
typedef shared_ptr<client_notification> client_notification_ptr;
} } // bts::client
extern const std::string BTS_MESSAGE_MAGIC;
FC_REFLECT(bts::client::client_notification, (timestamp)(message)(signature) )
FC_REFLECT( bts::client::rpc_server_config, (enable)(rpc_user)(rpc_password)(rpc_endpoint)(httpd_endpoint)(htdocs) )
FC_REFLECT( bts::client::chain_server_config, (enabled)(listen_port) )
FC_REFLECT( bts::client::config,
(rpc)(default_peers)(chain_servers)(chain_server)(mail_server_enabled)
(wallet_enabled)(ignore_console)(logging)
(delegate_server)
(default_delegate_peers)
(growl_notify_endpoint)
(growl_password)
(growl_bitshares_client_identifier) )
<commit_msg>Update seed nodes<commit_after>#pragma once
#include <bts/blockchain/chain_database.hpp>
#include <bts/wallet/wallet.hpp>
#include <bts/net/node.hpp>
#include <bts/rpc/rpc_client_api.hpp>
#include <bts/api/common_api.hpp>
#include <bts/rpc_stubs/common_api_client.hpp>
#include <fc/thread/thread.hpp>
#include <fc/log/logger_config.hpp>
#include <memory>
#include <boost/program_options.hpp>
namespace bts { namespace rpc {
class rpc_server;
typedef std::shared_ptr<rpc_server> rpc_server_ptr;
} }
namespace bts { namespace cli {
class cli;
}};
namespace bts { namespace client {
using namespace bts::blockchain;
using namespace bts::wallet;
using namespace bts::mail;
boost::program_options::variables_map parse_option_variables(int argc, char** argv);
fc::path get_data_dir(const boost::program_options::variables_map& option_variables);
fc::variant_object version_info();
namespace detail { class client_impl; }
using namespace bts::rpc;
struct rpc_server_config
{
rpc_server_config()
: enable(false),
rpc_endpoint(fc::ip::endpoint::from_string("127.0.0.1:0")),
httpd_endpoint(fc::ip::endpoint::from_string("127.0.0.1:0")),
htdocs("./htdocs")
{}
bool enable;
std::string rpc_user;
std::string rpc_password;
fc::ip::endpoint rpc_endpoint;
fc::ip::endpoint httpd_endpoint;
fc::path htdocs;
bool is_valid() const; /* Currently just checks if rpc port is set */
};
struct chain_server_config
{
chain_server_config()
: enabled(false),
listen_port(0)
{}
bool enabled;
uint16_t listen_port;
};
struct config
{
config( ) :
default_peers(vector<string>{"104.131.204.143:", "54.77.61.238:", "54.207.13.136:", "54.169.39.185"}),
mail_server_enabled(false),
wallet_enabled(true),
ignore_console(false),
use_upnp(true),
maximum_number_of_connections(BTS_NET_DEFAULT_MAX_CONNECTIONS) ,
delegate_server( fc::ip::endpoint::from_string("0.0.0.0:0") ),
default_delegate_peers( vector<string>({"107.170.30.182:9988"}) )
{
#ifdef BTS_TEST_NETWORK
uint32_t port = BTS_NET_TEST_P2P_PORT + BTS_TEST_NETWORK_VERSION;
#else
uint32_t port = BTS_NET_DEFAULT_P2P_PORT;
#endif
default_peers[0] += fc::to_string( port );
default_peers[1] += fc::to_string( port + 100 );
default_peers[2] += fc::to_string( port + 200 );
logging = fc::logging_config::default_config();
}
rpc_server_config rpc;
vector<string> default_peers;
vector<string> chain_servers;
chain_server_config chain_server;
bool mail_server_enabled;
bool wallet_enabled;
bool ignore_console;
bool use_upnp;
optional<fc::path> genesis_config;
uint16_t maximum_number_of_connections;
fc::logging_config logging;
fc::ip::endpoint delegate_server;
vector<string> default_delegate_peers;
fc::optional<std::string> growl_notify_endpoint;
fc::optional<std::string> growl_password;
fc::optional<std::string> growl_bitshares_client_identifier;
};
/**
* @class client
* @brief integrates the network, wallet, and blockchain
*
*/
class client : public bts::rpc_stubs::common_api_client,
public std::enable_shared_from_this<client>
{
public:
client();
client(bts::net::simulated_network_ptr network_to_connect_to);
void simulate_disconnect( bool state );
virtual ~client();
void start_networking(std::function<void()> network_started_callback = std::function<void()>());
void configure_from_command_line(int argc, char** argv);
fc::future<void> start();
void open(const path& data_dir,
optional<fc::path> genesis_file_path = optional<fc::path>(),
std::function<void(float)> reindex_status_callback = std::function<void(float)>());
void init_cli();
void set_daemon_mode(bool daemon_mode);
chain_database_ptr get_chain()const;
wallet_ptr get_wallet()const;
mail_server_ptr get_mail_server()const;
bts::rpc::rpc_server_ptr get_rpc_server()const;
bts::net::node_ptr get_node()const;
fc::path get_data_dir()const;
// returns true if the client is connected to the network
bool is_connected() const;
bts::net::node_id_t get_node_id() const;
const config& configure(const fc::path& configuration_directory);
// functions for taking command-line parameters and passing them on to the p2p node
void listen_on_port( uint16_t port_to_listen, bool wait_if_not_available);
void accept_incoming_p2p_connections(bool accept);
void listen_to_p2p_network();
static fc::ip::endpoint string_to_endpoint(const std::string& remote_endpoint);
void add_node( const string& remote_endpoint );
void connect_to_peer( const string& remote_endpoint );
void connect_to_p2p_network();
fc::ip::endpoint get_p2p_listening_endpoint() const;
bool handle_message(const bts::net::message&, bool sync_mode);
void sync_status(uint32_t item_type, uint32_t item_count);
protected:
virtual bts::api::common_api* get_impl() const override;
private:
unique_ptr<detail::client_impl> my;
};
typedef shared_ptr<client> client_ptr;
/* Message broadcast on the network to notify all clients of some important information
(security vulnerability, new version, that sort of thing) */
class client_notification
{
public:
fc::time_point_sec timestamp;
string message;
fc::ecc::compact_signature signature;
//client_notification();
fc::sha256 digest() const;
void sign(const fc::ecc::private_key& key);
fc::ecc::public_key signee() const;
};
typedef shared_ptr<client_notification> client_notification_ptr;
} } // bts::client
extern const std::string BTS_MESSAGE_MAGIC;
FC_REFLECT(bts::client::client_notification, (timestamp)(message)(signature) )
FC_REFLECT( bts::client::rpc_server_config, (enable)(rpc_user)(rpc_password)(rpc_endpoint)(httpd_endpoint)(htdocs) )
FC_REFLECT( bts::client::chain_server_config, (enabled)(listen_port) )
FC_REFLECT( bts::client::config,
(rpc)(default_peers)(chain_servers)(chain_server)(mail_server_enabled)
(wallet_enabled)(ignore_console)(logging)
(delegate_server)
(default_delegate_peers)
(growl_notify_endpoint)
(growl_password)
(growl_bitshares_client_identifier) )
<|endoftext|> |
<commit_before>#include "BasicPartitioner.h"
#include "Node.h"
#include "Camera.h"
#include <memory>
#include <algorithm>
using namespace std;
#define MIN_NODES 128
#define MIN_LIGHTS 32
BasicPartitioner :: BasicPartitioner()
{
m_Nodes.reserve(MIN_NODES);
m_Lights.reserve(MIN_LIGHTS);
}
void BasicPartitioner :: partition(const Node* root)
{
assert(m_pCamera);
//size_t sz = m_Nodes.size();
//size_t lsz = m_Lights.size();
//unsigned node_idx=0;
//unsigned light_idx=0;
m_Lights.clear();
m_Nodes.clear();
Node::LoopCtrl lc = Node::LC_STEP;
root->each([&](const Node* node) {
//if(node->is_light())
// LOG("light");
if(node->visible() && node->is_partitioner(m_pCamera))
{
auto subnodes = node->visible_nodes(m_pCamera);
for(unsigned i=0;i<subnodes.size();++i)
{
//if(node_idx >= sz) {
//sz = max<unsigned>(MIN_NODES, sz*2);
//m_Nodes.resize(sz);
//}
//m_Nodes[node_idx] = subnodes[i];
if(node->is_light())
m_Lights.push_back((const Light*)node);
else
m_Nodes.push_back(subnodes[i]);
//++node_idx;
}
//lc = Node::LC_SKIP; // skip tree
return;
}
if(not m_pCamera->is_visible(node, &lc)){
if(not node->visible())
lc = Node::LC_SKIP;
return;
}
//if(node->is_light())
// LOG("(2) light");
// LC_SKIP when visible=true is not impl
// so we'll reset to LC_STEP here
lc = Node::LC_STEP;
if(node->is_light()) {
//if(light_idx >= lsz) {
// lsz = max<unsigned>(MIN_LIGHTS, lsz*2);
// m_Lights.resize(lsz);
//}
//m_Lights[light_idx] = (const Light*)node;
//++light_idx;
m_Lights.push_back((const Light*)node);
} else {
//if(node_idx >= sz) {
// sz = max<unsigned>(MIN_NODES, sz*2);
// m_Nodes.resize(sz);
//}
//m_Nodes[node_idx] = node;
//++node_idx;
m_Nodes.push_back(node);
}
}, Node::Each::RECURSIVE | Node::Each::INCLUDE_SELF, &lc);
//if(node_idx >= sz)
// m_Nodes.resize(max<unsigned>(MIN_NODES, sz*2));
//if(light_idx >= lsz)
// m_Lights.resize(max<unsigned>(MIN_LIGHTS, lsz*2));
stable_sort(ENTIRE(m_Nodes),//.begin(), m_Nodes.begin() + node_idx,
[](const Node* a, const Node* b){
if(not a && b)
return false;
if(not b && a)
return true;
if(not a && not b)
return true;
if(not floatcmp(a->layer(), b->layer()))
return a->layer() < b->layer();
return false;
}
);
// mark endpoints
//m_Nodes[node_idx] = nullptr;
//m_Lights[light_idx] = nullptr;
}
void BasicPartitioner :: lazy_logic(Freq:: Time t)
{
}
void BasicPartitioner :: logic(Freq::Time t)
{
++m_Recur;
vector<shared_ptr<bool>> unset;
// check 1-to-1 collisions
for(
auto itr = m_Collisions.begin();
itr != m_Collisions.end();
){
if(not *itr->recheck){
++itr;
continue;
}
auto a = itr->a.lock();
if(not a) {
itr = m_Collisions.erase(itr);
continue;
}
auto b = itr->b.lock();
if(not b) {
itr = m_Collisions.erase(itr);
continue;
}
if(a->world_box().collision(b->world_box())) {
itr->on_collision(a.get(), b.get());
if(not itr->collision) {
itr->collision = true;
itr->on_touch(a.get(), b.get());
}
} else {
itr->on_no_collision(a.get(), b.get());
if(itr->collision) {
itr->collision = false;
itr->on_untouch(a.get(), b.get());
}
}
if(a.unique() || b.unique()) {
itr = m_Collisions.erase(itr);
continue;
}
*itr->recheck = false;
++itr;
}
// check type collisions
for(
auto itr = m_TypedCollisions.begin();
itr != m_TypedCollisions.end();
){
unsigned type = itr->b;
if(m_Objects.size() <= type){
++itr;
continue;
}
if(not *itr->recheck && not *m_Objects[type].recheck){
++itr;
continue;
}
unset.push_back(m_Objects[type].recheck);
auto a = itr->a.lock();
if(not a) {
itr = m_TypedCollisions.erase(itr);
continue;
}
auto pcs = get_potentials(a.get(), type);
unsigned collisions = 0;
//for(auto jtr = m_Objects[type].objects.begin();
// jtr != m_Objects[type].objects.end();
//){
for(auto jtr = pcs.begin(); jtr != pcs.end();)
{
auto b = jtr->lock();
if(not b) {
jtr = m_Objects[type].objects.erase(jtr);
continue;
}
if(a->world_box().collision(b->world_box())) {
itr->on_collision(a.get(), b.get());
++collisions;
} else {
itr->on_no_collision(a.get(), b.get());
}
++jtr;
}
if(itr->collision != (bool)collisions)
{
itr->collision = (bool)collisions;
if(collisions)
itr->on_touch(a.get(), nullptr);
else
itr->on_untouch(a.get(), nullptr);
}
if(a.unique()) {
itr = m_TypedCollisions.erase(itr);
continue;
}
*itr->recheck = false;
++itr;
}
// check intertype collisions
for(
auto itr = m_IntertypeCollisions.begin();
itr != m_IntertypeCollisions.end();
){
auto type_a = itr->a;
auto type_b = itr->b;
if(not *m_Objects[type_a].recheck && not *m_Objects[type_b].recheck){
++itr;
continue;
}
unset.push_back(m_Objects[type_a].recheck);
unset.push_back(m_Objects[type_b].recheck);
for(auto jtr = m_Objects[type_a].objects.begin();
jtr != m_Objects[type_a].objects.end();
){
unsigned collisions = 0;
auto a = jtr->lock();
if(not a) {
jtr = m_Objects[type_a].objects.erase(jtr);
continue;
}
auto pcs = get_potentials(a.get(), type_b);
for(auto htr = pcs.begin();
htr != pcs.end()
;){
//auto pcs = get_potentials(a.get(), type_b)
//for(auto htr = m_Objects[type_b].objects.begin();
// htr != m_Objects[type_b].objects.end();
//){
auto b = htr->lock();
if(not b) {
htr = m_Objects[type_b].objects.erase(htr);
continue;
}
if(a == b) // same object
goto iter;
if(a->world_box().collision(b->world_box())) {
itr->on_collision(a.get(), b.get());
++collisions;
} else {
itr->on_no_collision(a.get(), b.get());
}
iter:
++htr;
}
if(itr->collision != (bool)collisions)
{
itr->collision = (bool)collisions;
if(collisions)
itr->on_touch(a.get(), nullptr);
else
itr->on_untouch(a.get(), nullptr);
}
++jtr;
}
++itr;
}
for(auto& unset_me: unset)
*unset_me = false;
--m_Recur;
if(m_Recur == 0){
for(auto&& func: m_Pending)
func();
m_Pending.clear();
}
}
std::vector<std::weak_ptr<Node>> BasicPartitioner :: get_potentials(
Node* n, unsigned typ
){
auto potentials = m_Objects[typ].objects;
auto pcs_itr = m_Providers.find(typ);
if(pcs_itr != m_Providers.end()){
auto more = pcs_itr->second(n->world_box());
std::copy(ENTIRE(more), back_inserter(potentials));
}
return potentials;
}
void BasicPartitioner :: register_provider(unsigned type,
std::function<
std::vector<std::weak_ptr<Node>> (Box)
> func)
{
m_Providers[type] = func;
}
vector<Node*> BasicPartitioner :: get_collisions_for(Node* n)
{
vector<Node*> r;
for(
auto itr = m_Collisions.begin();
itr != m_Collisions.end();
++itr
){
auto a = itr->a.lock();
if(not a) {
// erasing may invalidate iterators of outer loops
itr = m_Collisions.erase(itr);
continue;
}
if(a.get() == n)
{
auto b = itr->b.lock();
if(not b) {
itr = m_Collisions.erase(itr);
continue;
}
if(a->world_box().collision(b->world_box()))
r.push_back(b.get());
}
}
return r;
}
std::vector<Node*> BasicPartitioner :: get_collisions_for(Node* n, unsigned type)
{
std::vector<Node*> r;
if(m_Objects.size() <= type)
return r;
auto pcs = get_potentials(n, type);
for(auto itr = pcs.begin();
itr != pcs.end();
++itr
){
auto b = itr->lock();
if(not b) {
//itr = m_Objects[type].erase(itr);
continue;
}
if(n->world_box().collision(b->world_box()))
r.push_back(b.get());
}
return r;
}
std::vector<Node*> BasicPartitioner :: get_collisions_for(unsigned type_a, unsigned type_b)
{
return std::vector<Node*>();
}
void BasicPartitioner :: on_collision(
const std::shared_ptr<Node>& a,
const std::shared_ptr<Node>& b,
std::function<void(Node*, Node*)> col,
std::function<void(Node*, Node*)> no_col,
std::function<void(Node*, Node*)> touch,
std::function<void(Node*, Node*)> untouch
){
auto pair = Pair<weak_ptr<Node>, weak_ptr<Node>>(a,b);
if(col) pair.on_collision.connect(col);
if(no_col) pair.on_no_collision.connect(no_col);
if(touch) pair.on_touch.connect(touch);
if(untouch) pair.on_untouch.connect(untouch);
m_Collisions.push_back(std::move(pair));
auto rc = std::weak_ptr<bool>(m_Collisions.back().recheck);
auto cb = [rc]{ TRY(*std::shared_ptr<bool>(rc) = true;); };
a->on_pend.connect(cb);
a->on_free.connect(cb);
b->on_pend.connect(cb);
a->on_free.connect(cb);
}
void BasicPartitioner :: on_touch(
const std::shared_ptr<Node>& a,
const std::shared_ptr<Node>& b,
std::function<void(Node*, Node*)> touch
){
return on_collision(
a,b,
std::function<void(Node*, Node*)>(),
std::function<void(Node*, Node*)>(),
touch
);
}
void BasicPartitioner :: on_collision(
const std::shared_ptr<Node>& a,
unsigned type,
std::function<void(Node*, Node*)> col,
std::function<void(Node*, Node*)> no_col,
std::function<void(Node*, Node*)> touch,
std::function<void(Node*, Node*)> untouch
){
if(type>=m_Objects.size()) m_Objects.resize(type+1);
auto pair = Pair<weak_ptr<Node>, unsigned>(a,type);
if(col) pair.on_collision.connect(col);
if(no_col) pair.on_no_collision.connect(no_col);
if(touch) pair.on_touch.connect(touch);
if(untouch) pair.on_untouch.connect(untouch);
m_TypedCollisions.push_back(std::move(pair));
auto rc = std::weak_ptr<bool>(m_TypedCollisions.back().recheck);
auto cb = [rc]{ TRY(*std::shared_ptr<bool>(rc) = true;); };
a->on_pend.connect(cb);
a->on_free.connect(cb);
}
void BasicPartitioner :: on_collision(
unsigned type_a,
unsigned type_b,
std::function<void(Node*, Node*)> col,
std::function<void(Node*, Node*)> no_col,
std::function<void(Node*, Node*)> touch,
std::function<void(Node*, Node*)> untouch
){
if(type_a>=m_Objects.size() || type_b>=m_Objects.size())
m_Objects.resize(std::max(type_a, type_b)+1);
auto pair = Pair<unsigned, unsigned>(type_a,type_b);
if(col) pair.on_collision.connect(col);
if(no_col) pair.on_no_collision.connect(no_col);
if(touch) pair.on_touch.connect(touch);
if(untouch) pair.on_untouch.connect(untouch);
m_IntertypeCollisions.push_back(std::move(pair));
}
void BasicPartitioner :: register_object(
const std::shared_ptr<Node>& a,
unsigned type
){
auto func = [&]{
if(type>=m_Objects.size()) m_Objects.resize(type+1);
m_Objects[type].objects.emplace_back(a);
auto rc = std::weak_ptr<bool>(m_Objects[type].recheck);
auto cb = [rc]{ TRY(*std::shared_ptr<bool>(rc) = true;); };
a->on_pend.connect(cb);
a->on_free.connect(cb);
};
if(m_Recur)
m_Pending.push_back(func);
else
func();
}
void BasicPartitioner :: deregister_object(
const std::shared_ptr<Node>& a,
unsigned type
){
}
void BasicPartitioner :: deregister_object(
const std::shared_ptr<Node>& a
){
// remove all object->object collision pairs involving object
kit::remove_if(m_Collisions, [a](const Pair<std::weak_ptr<Node>, std::weak_ptr<Node>>& p){
auto ap = p.a.lock();
auto bp = p.b.lock();
return
not ap ||
not bp ||
a == ap ||
a == bp;
});
}
void BasicPartitioner :: after(std::function<void()> func)
{
m_Pending.push_back(func);
}
<commit_msg>can't erase itr<commit_after>#include "BasicPartitioner.h"
#include "Node.h"
#include "Camera.h"
#include <memory>
#include <algorithm>
using namespace std;
#define MIN_NODES 128
#define MIN_LIGHTS 32
BasicPartitioner :: BasicPartitioner()
{
m_Nodes.reserve(MIN_NODES);
m_Lights.reserve(MIN_LIGHTS);
}
void BasicPartitioner :: partition(const Node* root)
{
assert(m_pCamera);
//size_t sz = m_Nodes.size();
//size_t lsz = m_Lights.size();
//unsigned node_idx=0;
//unsigned light_idx=0;
m_Lights.clear();
m_Nodes.clear();
Node::LoopCtrl lc = Node::LC_STEP;
root->each([&](const Node* node) {
//if(node->is_light())
// LOG("light");
if(node->visible() && node->is_partitioner(m_pCamera))
{
auto subnodes = node->visible_nodes(m_pCamera);
for(unsigned i=0;i<subnodes.size();++i)
{
//if(node_idx >= sz) {
//sz = max<unsigned>(MIN_NODES, sz*2);
//m_Nodes.resize(sz);
//}
//m_Nodes[node_idx] = subnodes[i];
if(node->is_light())
m_Lights.push_back((const Light*)node);
else
m_Nodes.push_back(subnodes[i]);
//++node_idx;
}
//lc = Node::LC_SKIP; // skip tree
return;
}
if(not m_pCamera->is_visible(node, &lc)){
if(not node->visible())
lc = Node::LC_SKIP;
return;
}
//if(node->is_light())
// LOG("(2) light");
// LC_SKIP when visible=true is not impl
// so we'll reset to LC_STEP here
lc = Node::LC_STEP;
if(node->is_light()) {
//if(light_idx >= lsz) {
// lsz = max<unsigned>(MIN_LIGHTS, lsz*2);
// m_Lights.resize(lsz);
//}
//m_Lights[light_idx] = (const Light*)node;
//++light_idx;
m_Lights.push_back((const Light*)node);
} else {
//if(node_idx >= sz) {
// sz = max<unsigned>(MIN_NODES, sz*2);
// m_Nodes.resize(sz);
//}
//m_Nodes[node_idx] = node;
//++node_idx;
m_Nodes.push_back(node);
}
}, Node::Each::RECURSIVE | Node::Each::INCLUDE_SELF, &lc);
//if(node_idx >= sz)
// m_Nodes.resize(max<unsigned>(MIN_NODES, sz*2));
//if(light_idx >= lsz)
// m_Lights.resize(max<unsigned>(MIN_LIGHTS, lsz*2));
stable_sort(ENTIRE(m_Nodes),//.begin(), m_Nodes.begin() + node_idx,
[](const Node* a, const Node* b){
if(not a && b)
return false;
if(not b && a)
return true;
if(not a && not b)
return true;
if(not floatcmp(a->layer(), b->layer()))
return a->layer() < b->layer();
return false;
}
);
// mark endpoints
//m_Nodes[node_idx] = nullptr;
//m_Lights[light_idx] = nullptr;
}
void BasicPartitioner :: lazy_logic(Freq:: Time t)
{
}
void BasicPartitioner :: logic(Freq::Time t)
{
++m_Recur;
vector<shared_ptr<bool>> unset;
// check 1-to-1 collisions
for(
auto itr = m_Collisions.begin();
itr != m_Collisions.end();
){
if(not *itr->recheck){
++itr;
continue;
}
auto a = itr->a.lock();
if(not a) {
itr = m_Collisions.erase(itr);
continue;
}
auto b = itr->b.lock();
if(not b) {
itr = m_Collisions.erase(itr);
continue;
}
if(a->world_box().collision(b->world_box())) {
itr->on_collision(a.get(), b.get());
if(not itr->collision) {
itr->collision = true;
itr->on_touch(a.get(), b.get());
}
} else {
itr->on_no_collision(a.get(), b.get());
if(itr->collision) {
itr->collision = false;
itr->on_untouch(a.get(), b.get());
}
}
if(a.unique() || b.unique()) {
itr = m_Collisions.erase(itr);
continue;
}
*itr->recheck = false;
++itr;
}
// check type collisions
for(
auto itr = m_TypedCollisions.begin();
itr != m_TypedCollisions.end();
){
unsigned type = itr->b;
if(m_Objects.size() <= type){
++itr;
continue;
}
if(not *itr->recheck && not *m_Objects[type].recheck){
++itr;
continue;
}
unset.push_back(m_Objects[type].recheck);
auto a = itr->a.lock();
if(not a) {
itr = m_TypedCollisions.erase(itr);
continue;
}
auto pcs = get_potentials(a.get(), type);
unsigned collisions = 0;
//for(auto jtr = m_Objects[type].objects.begin();
// jtr != m_Objects[type].objects.end();
//){
for(auto jtr = pcs.begin(); jtr != pcs.end();)
{
auto b = jtr->lock();
//if(not b) {
// jtr = m_Objects[type].objects.erase(jtr);
// continue;
//}
if(a->world_box().collision(b->world_box())) {
itr->on_collision(a.get(), b.get());
++collisions;
} else {
itr->on_no_collision(a.get(), b.get());
}
++jtr;
}
if(itr->collision != (bool)collisions)
{
itr->collision = (bool)collisions;
if(collisions)
itr->on_touch(a.get(), nullptr);
else
itr->on_untouch(a.get(), nullptr);
}
if(a.unique()) {
itr = m_TypedCollisions.erase(itr);
continue;
}
*itr->recheck = false;
++itr;
}
// check intertype collisions
for(
auto itr = m_IntertypeCollisions.begin();
itr != m_IntertypeCollisions.end();
){
auto type_a = itr->a;
auto type_b = itr->b;
if(not *m_Objects[type_a].recheck && not *m_Objects[type_b].recheck){
++itr;
continue;
}
unset.push_back(m_Objects[type_a].recheck);
unset.push_back(m_Objects[type_b].recheck);
for(auto jtr = m_Objects[type_a].objects.begin();
jtr != m_Objects[type_a].objects.end();
){
unsigned collisions = 0;
auto a = jtr->lock();
if(not a) {
jtr = m_Objects[type_a].objects.erase(jtr);
continue;
}
auto pcs = get_potentials(a.get(), type_b);
for(auto htr = pcs.begin();
htr != pcs.end()
;){
//auto pcs = get_potentials(a.get(), type_b)
//for(auto htr = m_Objects[type_b].objects.begin();
// htr != m_Objects[type_b].objects.end();
//){
auto b = htr->lock();
//if(not b) {
// htr = m_Objects[type_b].objects.erase(htr);
// continue;
//}
if(a == b) // same object
goto iter;
if(a->world_box().collision(b->world_box())) {
itr->on_collision(a.get(), b.get());
++collisions;
} else {
itr->on_no_collision(a.get(), b.get());
}
iter:
++htr;
}
if(itr->collision != (bool)collisions)
{
itr->collision = (bool)collisions;
if(collisions)
itr->on_touch(a.get(), nullptr);
else
itr->on_untouch(a.get(), nullptr);
}
++jtr;
}
++itr;
}
for(auto& unset_me: unset)
*unset_me = false;
--m_Recur;
if(m_Recur == 0){
for(auto&& func: m_Pending)
func();
m_Pending.clear();
}
}
std::vector<std::weak_ptr<Node>> BasicPartitioner :: get_potentials(
Node* n, unsigned typ
){
auto potentials = m_Objects[typ].objects;
auto pcs_itr = m_Providers.find(typ);
if(pcs_itr != m_Providers.end()){
auto more = pcs_itr->second(n->world_box());
std::copy(ENTIRE(more), back_inserter(potentials));
}
return potentials;
}
void BasicPartitioner :: register_provider(unsigned type,
std::function<
std::vector<std::weak_ptr<Node>> (Box)
> func)
{
m_Providers[type] = func;
}
vector<Node*> BasicPartitioner :: get_collisions_for(Node* n)
{
vector<Node*> r;
for(
auto itr = m_Collisions.begin();
itr != m_Collisions.end();
++itr
){
auto a = itr->a.lock();
if(not a) {
// erasing may invalidate iterators of outer loops
itr = m_Collisions.erase(itr);
continue;
}
if(a.get() == n)
{
auto b = itr->b.lock();
if(not b) {
itr = m_Collisions.erase(itr);
continue;
}
if(a->world_box().collision(b->world_box()))
r.push_back(b.get());
}
}
return r;
}
std::vector<Node*> BasicPartitioner :: get_collisions_for(Node* n, unsigned type)
{
std::vector<Node*> r;
if(m_Objects.size() <= type)
return r;
auto pcs = get_potentials(n, type);
for(auto itr = pcs.begin();
itr != pcs.end();
++itr
){
auto b = itr->lock();
if(not b) {
//itr = m_Objects[type].erase(itr);
continue;
}
if(n->world_box().collision(b->world_box()))
r.push_back(b.get());
}
return r;
}
std::vector<Node*> BasicPartitioner :: get_collisions_for(unsigned type_a, unsigned type_b)
{
return std::vector<Node*>();
}
void BasicPartitioner :: on_collision(
const std::shared_ptr<Node>& a,
const std::shared_ptr<Node>& b,
std::function<void(Node*, Node*)> col,
std::function<void(Node*, Node*)> no_col,
std::function<void(Node*, Node*)> touch,
std::function<void(Node*, Node*)> untouch
){
auto pair = Pair<weak_ptr<Node>, weak_ptr<Node>>(a,b);
if(col) pair.on_collision.connect(col);
if(no_col) pair.on_no_collision.connect(no_col);
if(touch) pair.on_touch.connect(touch);
if(untouch) pair.on_untouch.connect(untouch);
m_Collisions.push_back(std::move(pair));
auto rc = std::weak_ptr<bool>(m_Collisions.back().recheck);
auto cb = [rc]{ TRY(*std::shared_ptr<bool>(rc) = true;); };
a->on_pend.connect(cb);
a->on_free.connect(cb);
b->on_pend.connect(cb);
a->on_free.connect(cb);
}
void BasicPartitioner :: on_touch(
const std::shared_ptr<Node>& a,
const std::shared_ptr<Node>& b,
std::function<void(Node*, Node*)> touch
){
return on_collision(
a,b,
std::function<void(Node*, Node*)>(),
std::function<void(Node*, Node*)>(),
touch
);
}
void BasicPartitioner :: on_collision(
const std::shared_ptr<Node>& a,
unsigned type,
std::function<void(Node*, Node*)> col,
std::function<void(Node*, Node*)> no_col,
std::function<void(Node*, Node*)> touch,
std::function<void(Node*, Node*)> untouch
){
if(type>=m_Objects.size()) m_Objects.resize(type+1);
auto pair = Pair<weak_ptr<Node>, unsigned>(a,type);
if(col) pair.on_collision.connect(col);
if(no_col) pair.on_no_collision.connect(no_col);
if(touch) pair.on_touch.connect(touch);
if(untouch) pair.on_untouch.connect(untouch);
m_TypedCollisions.push_back(std::move(pair));
auto rc = std::weak_ptr<bool>(m_TypedCollisions.back().recheck);
auto cb = [rc]{ TRY(*std::shared_ptr<bool>(rc) = true;); };
a->on_pend.connect(cb);
a->on_free.connect(cb);
}
void BasicPartitioner :: on_collision(
unsigned type_a,
unsigned type_b,
std::function<void(Node*, Node*)> col,
std::function<void(Node*, Node*)> no_col,
std::function<void(Node*, Node*)> touch,
std::function<void(Node*, Node*)> untouch
){
if(type_a>=m_Objects.size() || type_b>=m_Objects.size())
m_Objects.resize(std::max(type_a, type_b)+1);
auto pair = Pair<unsigned, unsigned>(type_a,type_b);
if(col) pair.on_collision.connect(col);
if(no_col) pair.on_no_collision.connect(no_col);
if(touch) pair.on_touch.connect(touch);
if(untouch) pair.on_untouch.connect(untouch);
m_IntertypeCollisions.push_back(std::move(pair));
}
void BasicPartitioner :: register_object(
const std::shared_ptr<Node>& a,
unsigned type
){
auto func = [&]{
if(type>=m_Objects.size()) m_Objects.resize(type+1);
m_Objects[type].objects.emplace_back(a);
auto rc = std::weak_ptr<bool>(m_Objects[type].recheck);
auto cb = [rc]{ TRY(*std::shared_ptr<bool>(rc) = true;); };
a->on_pend.connect(cb);
a->on_free.connect(cb);
};
if(m_Recur)
m_Pending.push_back(func);
else
func();
}
void BasicPartitioner :: deregister_object(
const std::shared_ptr<Node>& a,
unsigned type
){
}
void BasicPartitioner :: deregister_object(
const std::shared_ptr<Node>& a
){
// remove all object->object collision pairs involving object
kit::remove_if(m_Collisions, [a](const Pair<std::weak_ptr<Node>, std::weak_ptr<Node>>& p){
auto ap = p.a.lock();
auto bp = p.b.lock();
return
not ap ||
not bp ||
a == ap ||
a == bp;
});
}
void BasicPartitioner :: after(std::function<void()> func)
{
m_Pending.push_back(func);
}
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File: NekManager.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description:
//
///////////////////////////////////////////////////////////////////////////////
#ifndef NEKTAR_LIB_UTILITIES_BASIC_UTILS_NEK_MANAGER_HPP
#define NEKTAR_LIB_UTILITIES_BASIC_UTILS_NEK_MANAGER_HPP
#include <algorithm>
#include <map>
#include <boost/function.hpp>
#include <boost/call_traits.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/concept_check.hpp>
#include <LibUtilities/Foundations/Points.hpp>
#include <LibUtilities/BasicUtils/ErrorUtil.hpp>
using namespace std;
namespace Nektar
{
namespace LibUtilities
{
template <typename KeyType, typename ValueT>
class NekManager
{
public:
BOOST_CLASS_REQUIRE(KeyType, boost, LessThanComparableConcept);
typedef boost::shared_ptr<ValueT> ValueType;
typedef boost::function<ValueType (const KeyType& key)> CreateFuncType;
typedef std::map<KeyType, ValueType> ValueContainer;
typedef std::map<KeyType, CreateFuncType, opLess> CreateFuncContainer;
NekManager() :
m_values(),
m_globalCreateFunc(),
m_keySpecificCreateFuncs()
{
};
explicit NekManager(CreateFuncType f) :
m_values(),
m_globalCreateFunc(f),
m_keySpecificCreateFuncs()
{
}
~NekManager() {}
void RegisterCreator(typename boost::call_traits<KeyType>::const_reference key,
const CreateFuncType& createFunc)
{
m_keySpecificCreateFuncs[key] = createFunc;
}
ValueType operator[](typename boost::call_traits<KeyType>::const_reference key)
{
typename ValueContainer::iterator found = m_values.find(key);
if( found != m_values.end() )
{
return (*found).second;
}
else
{
static ValueType result;
// No object, create a new one.
CreateFuncType f = m_globalCreateFunc;
typename CreateFuncContainer::iterator keyFound = m_keySpecificCreateFuncs.find(key);
if( keyFound != m_keySpecificCreateFuncs.end() )
{
f = (*keyFound).second;
}
if( f )
{
result = f(key);
m_values[key] = result;
return m_values[key];
}
else
{
std::string keyAsString = boost::lexical_cast<std::string>(key);
std::string message = std::string("No create func found for key ") + keyAsString;
NEKERROR(ErrorUtil::efatal, message.c_str());
}
return result;
}
}
private:
NekManager(const NekManager<KeyType, ValueType>& rhs);
NekManager<KeyType, ValueType>& operator=(const NekManager<KeyType, ValueType>& rhs);
ValueContainer m_values;
CreateFuncType m_globalCreateFunc;
CreateFuncContainer m_keySpecificCreateFuncs;
};
}
}
#endif //NEKTAR_LIB_UTILITIES_BASIC_UTILS_NEK_MANAGER_HPP
<commit_msg>Added template parameter to specify the less-than operator for the NekManager to use for finding the registered create method. A default has been specified that uses the global operator defined for the key.<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File: NekManager.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description:
//
///////////////////////////////////////////////////////////////////////////////
#ifndef NEKTAR_LIB_UTILITIES_BASIC_UTILS_NEK_MANAGER_HPP
#define NEKTAR_LIB_UTILITIES_BASIC_UTILS_NEK_MANAGER_HPP
#include <algorithm>
#include <map>
#include <boost/function.hpp>
#include <boost/call_traits.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/concept_check.hpp>
#include <LibUtilities/Foundations/Points.hpp>
#include <LibUtilities/BasicUtils/ErrorUtil.hpp>
using namespace std;
namespace Nektar
{
namespace LibUtilities
{
template <typename KeyType>
struct defOpLessCreator
{
bool operator()(const KeyType &lhs, const KeyType &rhs)
{
return ::operator<(lhs, rhs);
}
};
template <typename KeyType, typename ValueT, typename opLessCreator = defOpLessCreator<KeyType> >
class NekManager
{
public:
BOOST_CLASS_REQUIRE(KeyType, boost, LessThanComparableConcept);
typedef boost::shared_ptr<ValueT> ValueType;
typedef boost::function<ValueType (const KeyType& key)> CreateFuncType;
typedef std::map<KeyType, ValueType> ValueContainer;
typedef std::map<KeyType, CreateFuncType, opLessCreator> CreateFuncContainer;
NekManager() :
m_values(),
m_globalCreateFunc(),
m_keySpecificCreateFuncs()
{
};
explicit NekManager(CreateFuncType f) :
m_values(),
m_globalCreateFunc(f),
m_keySpecificCreateFuncs()
{
}
~NekManager() {}
void RegisterCreator(typename boost::call_traits<KeyType>::const_reference key,
const CreateFuncType& createFunc)
{
m_keySpecificCreateFuncs[key] = createFunc;
}
ValueType operator[](typename boost::call_traits<KeyType>::const_reference key)
{
typename ValueContainer::iterator found = m_values.find(key);
if( found != m_values.end() )
{
return (*found).second;
}
else
{
static ValueType result;
// No object, create a new one.
CreateFuncType f = m_globalCreateFunc;
typename CreateFuncContainer::iterator keyFound = m_keySpecificCreateFuncs.find(key);
if( keyFound != m_keySpecificCreateFuncs.end() )
{
f = (*keyFound).second;
}
if( f )
{
result = f(key);
m_values[key] = result;
return m_values[key];
}
else
{
std::string keyAsString = boost::lexical_cast<std::string>(key);
std::string message = std::string("No create func found for key ") + keyAsString;
NEKERROR(ErrorUtil::efatal, message.c_str());
}
return result;
}
}
private:
NekManager(const NekManager<KeyType, ValueType, opLessCreator>& rhs);
NekManager<KeyType, ValueType, opLessCreator>& operator=(const NekManager<KeyType, ValueType, opLessCreator>& rhs);
ValueContainer m_values;
CreateFuncType m_globalCreateFunc;
CreateFuncContainer m_keySpecificCreateFuncs;
};
}
}
#endif //NEKTAR_LIB_UTILITIES_BASIC_UTILS_NEK_MANAGER_HPP
<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010 Francois Beaune
//
// 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.
//
// Interface header.
#include "appleseed.h"
namespace foundation
{
//
// Library information.
//
// Return the name of the library.
const char* Appleseed::get_lib_name()
{
// Windows.
#if defined _WIN32
return "appleseed.dll";
// Mac OS X.
#elif defined __APPLE__
return "appleseed.dylib";
// Other operating system.
#else
return "appleseed.so";
#endif
}
// Return the version string of the library.
const char* Appleseed::get_lib_version()
{
return "1.1.0-UNOFFICIAL";
}
// Return the maturity level of the library.
const char* Appleseed::get_lib_maturity_level()
{
return "alpha";
}
// Return the build number of the library.
size_t Appleseed::get_lib_build_number()
{
// This works as follow: the build number is stored in a static variable
// whose name is unique (the text after build_number_ is a GUID).
// Before compilation begins, a tool searches for this variable declaration
// (in this file) and increases the build number by 1.
static const size_t build_number_335A07D9_68C1_4E21_86FA_60C64BD6FE6C = 7605;
return build_number_335A07D9_68C1_4E21_86FA_60C64BD6FE6C;
}
// Return the configuration of the library.
const char* Appleseed::get_lib_configuration()
{
#ifdef DEBUG
return "Debug";
#else
return "Release";
#endif
}
// Return the compilation date of the library.
const char* Appleseed::get_lib_compilation_date()
{
return __DATE__;
}
// Return the compilation time of the library.
const char* Appleseed::get_lib_compilation_time()
{
return __TIME__;
}
} // namespace foundation
<commit_msg>updated library maturity level from "alpha" to "alpha-1".<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010 Francois Beaune
//
// 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.
//
// Interface header.
#include "appleseed.h"
namespace foundation
{
//
// Library information.
//
// Return the name of the library.
const char* Appleseed::get_lib_name()
{
// Windows.
#if defined _WIN32
return "appleseed.dll";
// Mac OS X.
#elif defined __APPLE__
return "appleseed.dylib";
// Other operating system.
#else
return "appleseed.so";
#endif
}
// Return the version string of the library.
const char* Appleseed::get_lib_version()
{
return "1.1.0-UNOFFICIAL";
}
// Return the maturity level of the library.
const char* Appleseed::get_lib_maturity_level()
{
return "alpha-1";
}
// Return the build number of the library.
size_t Appleseed::get_lib_build_number()
{
// This works as follow: the build number is stored in a static variable
// whose name is unique (the text after build_number_ is a GUID).
// Before compilation begins, a tool searches for this variable declaration
// (in this file) and increases the build number by 1.
static const size_t build_number_335A07D9_68C1_4E21_86FA_60C64BD6FE6C = 7606;
return build_number_335A07D9_68C1_4E21_86FA_60C64BD6FE6C;
}
// Return the configuration of the library.
const char* Appleseed::get_lib_configuration()
{
#ifdef DEBUG
return "Debug";
#else
return "Release";
#endif
}
// Return the compilation date of the library.
const char* Appleseed::get_lib_compilation_date()
{
return __DATE__;
}
// Return the compilation time of the library.
const char* Appleseed::get_lib_compilation_time()
{
return __TIME__;
}
} // namespace foundation
<|endoftext|> |
<commit_before>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
*
* 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 "../base64inputstream.h"
#include "../fileinputstream.h"
#include "inputstreamtests.h"
using namespace Strigi;
int
Base64InputStreamTest(int argc, char* argv[]) {
founderrors = 0;
FileInputStream file("base64enc.txt");
Base64InputStream b64(&file);
const char* start;
int32_t nread = b64.read(start, 1, 0);
while (nread > 0) {
//printf("%i\n", nread);
for (int i=0; i<nread; ++i) {
fprintf(stderr, "%c", start[i]);
}
nread = b64.read(start, 1, 0);
}
printf("\n");
VERIFY(chdir(argv[1]) == 0);
for (int i=0; i<ninputstreamtests; ++i) {
FileInputStream file("a.zip");
charinputstreamtests[i](&file);
}
return founderrors;
}
<commit_msg>Resolve merge conflict.<commit_after>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
*
* 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 "../base64inputstream.h"
#include "inputstreamtests.h"
using namespace Strigi;
int
Base64InputStreamTest(int argc, char* argv[]) {
if (argc < 2) return 1;
VERIFY(chdir(argv[1]) == 0);
founderrors = 0;
TESTONFILE(Base64InputStream, "base64enc.txt");
return founderrors;
}
<|endoftext|> |
<commit_before>#include <yuni/yuni.h>
#include "type-check.h"
using namespace Yuni;
namespace Nany
{
namespace TypeCheck
{
namespace // anonymous
{
static Match isAtomSimilarTo(const ClassdefTable& table, const CTarget* target, const Atom& atom, const Atom& to)
{
if (&atom == &to) // identity
return Match::strictEqual;
if (atom.type != to.type) // can not be similar to a different type
return Match::none;
switch (atom.type)
{
case Atom::Type::funcdef:
{
uint32_t apsize = atom.parameters.size();
if (apsize != to.parameters.size())
return Match::none;
for (uint32_t p = 0; p != apsize; ++p)
{
auto& atomParam = atom.parameters[p];
auto& toParam = to.parameters[p];
if (atomParam.first != toParam.first)
return Match::none;
auto& cdefAtom = table.classdef(atomParam.second.clid);
auto& cdefTo = table.classdef(toParam.second.clid);
if (cdefAtom.atom != cdefTo.atom)
return Match::none;
if (cdefAtom.qualifiers != cdefTo.qualifiers)
return Match::none;
}
// checking the return type
bool hasReturnType = atom.hasReturnType();
if (hasReturnType != to.hasReturnType())
return Match::none;
if (hasReturnType)
{
auto& cdefAtom = table.classdef(atom.returnType.clid);
auto& cdefTo = table.classdef(to.returnType.clid);
if (Match::none == isSimilarTo(table, target, cdefAtom, cdefTo, false))
return Match::none;
}
return Match::equal;
}
case Atom::Type::classdef:
{
bool found = true;
atom.eachChild([&](const Atom& child) -> bool
{
found = false;
// try to find a similar atom
to.eachChild(child.name, [&](const Atom& toChild) -> bool
{
if (Match::none != isAtomSimilarTo(table, target, child, toChild))
{
found = true;
return false;
}
return true;
});
return found;
});
return found ? Match::equal : Match::none;
}
case Atom::Type::typealias:
{
assert(false and "type comparison - with typedef - implementation missing");
break;
}
case Atom::Type::namespacedef:
case Atom::Type::vardef:
case Atom::Type::unit:
{
assert(false and "invalid type comparison");
break;
}
}
return Match::none;
}
} // anonymous namespace
Match isSimilarTo(const ClassdefTable& table, const CTarget* target, const Classdef& from, const Classdef& to,
bool allowImplicit)
{
// identity
// (note: comparing only the address of 'from' and 'to' is not good enough
// since symlink may exist in the table.classdef table)
if (from.clid == to.clid)
return Match::strictEqual;
// constness
if (from.qualifiers.constant and (not to.qualifiers.constant))
return Match::none;
// the target accepts anything
if (to.isAny())
return Match::strictEqual;
// same builtin, identity as weel
if (to.isBuiltinOrVoid() or from.isBuiltinOrVoid())
return (from.kind == to.kind) ? Match::strictEqual : Match::none;
const Atom* toAtom = table.findClassdefAtom(to);
if (unlikely(toAtom == nullptr)) // type not resolved
return Match::none;
auto similarity = Match::none;
if (from.hasAtom())
{
similarity = isAtomSimilarTo(table, target, *from.atom, *toAtom);
if (similarity == Match::none)
return Match::none;
}
// follow-ups
for (auto& clid: from.followup.extends)
{
auto extendSimilarity = isSimilarTo(table, target, table.classdef(clid), to, allowImplicit);
if (Match::none == extendSimilarity)
return Match::none;
if (similarity == Match::none)
similarity = extendSimilarity;
}
return similarity;
}
} // namespace TypeCheck
} // namespace Nany
<commit_msg>typing: 'any' is not a perfect match (less precise than a real type)<commit_after>#include <yuni/yuni.h>
#include "type-check.h"
using namespace Yuni;
namespace Nany
{
namespace TypeCheck
{
namespace // anonymous
{
static Match isAtomSimilarTo(const ClassdefTable& table, const CTarget* target, const Atom& atom, const Atom& to)
{
if (&atom == &to) // identity
return Match::strictEqual;
if (atom.type != to.type) // can not be similar to a different type
return Match::none;
switch (atom.type)
{
case Atom::Type::funcdef:
{
uint32_t apsize = atom.parameters.size();
if (apsize != to.parameters.size())
return Match::none;
for (uint32_t p = 0; p != apsize; ++p)
{
auto& atomParam = atom.parameters[p];
auto& toParam = to.parameters[p];
if (atomParam.first != toParam.first)
return Match::none;
auto& cdefAtom = table.classdef(atomParam.second.clid);
auto& cdefTo = table.classdef(toParam.second.clid);
if (cdefAtom.atom != cdefTo.atom)
return Match::none;
if (cdefAtom.qualifiers != cdefTo.qualifiers)
return Match::none;
}
// checking the return type
bool hasReturnType = atom.hasReturnType();
if (hasReturnType != to.hasReturnType())
return Match::none;
if (hasReturnType)
{
auto& cdefAtom = table.classdef(atom.returnType.clid);
auto& cdefTo = table.classdef(to.returnType.clid);
if (Match::none == isSimilarTo(table, target, cdefAtom, cdefTo, false))
return Match::none;
}
return Match::equal;
}
case Atom::Type::classdef:
{
bool found = true;
atom.eachChild([&](const Atom& child) -> bool
{
found = false;
// try to find a similar atom
to.eachChild(child.name, [&](const Atom& toChild) -> bool
{
if (Match::none != isAtomSimilarTo(table, target, child, toChild))
{
found = true;
return false;
}
return true;
});
return found;
});
return found ? Match::equal : Match::none;
}
case Atom::Type::typealias:
{
assert(false and "type comparison - with typedef - implementation missing");
break;
}
case Atom::Type::namespacedef:
case Atom::Type::vardef:
case Atom::Type::unit:
{
assert(false and "invalid type comparison");
break;
}
}
return Match::none;
}
} // anonymous namespace
Match isSimilarTo(const ClassdefTable& table, const CTarget* target, const Classdef& from, const Classdef& to,
bool allowImplicit)
{
// identity
// (note: comparing only the address of 'from' and 'to' is not good enough
// since symlink may exist in the table.classdef table)
if (from.clid == to.clid)
return Match::strictEqual;
// constness
if (from.qualifiers.constant and (not to.qualifiers.constant))
return Match::none;
// the target accepts anything
if (to.isAny())
return Match::equal;
// same builtin, identity as weel
if (to.isBuiltinOrVoid() or from.isBuiltinOrVoid())
return (from.kind == to.kind) ? Match::strictEqual : Match::none;
const Atom* toAtom = table.findClassdefAtom(to);
if (unlikely(toAtom == nullptr)) // type not resolved
return Match::none;
auto similarity = Match::none;
if (from.hasAtom())
{
similarity = isAtomSimilarTo(table, target, *from.atom, *toAtom);
if (similarity == Match::none)
return Match::none;
}
// follow-ups
for (auto& clid: from.followup.extends)
{
auto extendSimilarity = isSimilarTo(table, target, table.classdef(clid), to, allowImplicit);
if (Match::none == extendSimilarity)
return Match::none;
if (similarity == Match::none)
similarity = extendSimilarity;
}
return similarity;
}
} // namespace TypeCheck
} // namespace Nany
<|endoftext|> |
<commit_before>
#include "backend/bridge/dml/expr/pg_func_map.h"
namespace peloton {
namespace bridge {
/**
* @brief Mapping PG Function Id to Peloton Function Meta Info.
*/
std::unordered_map<Oid, const PltFuncMetaInfo> kPgFuncMap({
//====--------------------------------
// Relational comparison
//====--------------------------------
{63, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{65, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{67, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{158, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{159, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{287, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{293, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{1718, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{84, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{144, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{145, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{157, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{164, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{165, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{288, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{294, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{1719, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{56, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{64, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{66, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{160, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{161, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{1246, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{289, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{295, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{1722, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{57, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{73, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{146, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{147, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{162, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{163, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{291, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{297, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{1720, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{74, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{150, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{151, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{168, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{169, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{1692, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{292, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{298, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{1721, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{72, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{148, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{149, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{166, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{167, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{1691, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{290, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{296, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{1723, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
//====--------------------------------
// Basic arithmetics
//====--------------------------------
{176, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{177, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{178, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{179, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{204, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{218, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{180, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{181, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{182, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{183, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{205, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{219, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{141, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{152, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{170, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{171, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{202, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{216, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{153, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
{154, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
{172, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
{173, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
{203, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
{217, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
//====--------------------------------
// Cast
//====--------------------------------
{480, { EXPRESSION_TYPE_CAST, 1 } }, // int8 -> int4
{481, { EXPRESSION_TYPE_CAST, 1 } }, // int4 -> int8
{668, { EXPRESSION_TYPE_CAST, 3 } }, // bpchar -> bpchar
{669, { EXPRESSION_TYPE_CAST, 3 } }, // varchar -> varchar
{1703, { EXPRESSION_TYPE_CAST, 2 } }, // numeric -> numeric
{1740, { EXPRESSION_TYPE_CAST, 3 } }, // int8 -> numeric
{1742, { EXPRESSION_TYPE_CAST, 3 } }, // float4 -> numeric
{1743, { EXPRESSION_TYPE_CAST, 3 } }, // float8 -> numeric
{1744, { EXPRESSION_TYPE_CAST, 1 } }, // numeric -> int4
{1745, { EXPRESSION_TYPE_CAST, 1 } }, // numeric -> float4
{1746, { EXPRESSION_TYPE_CAST, 1 } }, // numeric -> float8
{1781, { EXPRESSION_TYPE_CAST, 1 } }, // int8 -> numeric
{1782, { EXPRESSION_TYPE_CAST, 1 } }, // int2 -> numeric
});
/**
* @brief Mapping PG transit function to Aggregate types.
* We have to separate it from kPgFuncMap,
* because the two maps may have overlapping functions that have
* different meaning in Peloton.
* For example, PG Function Id 218 (float8pl) means an PLUS in
* 'ordinary' expressions,
* but means a SUM(float) in an aggregation.
*/
std::unordered_map<Oid, const PltFuncMetaInfo> kPgTransitFuncMap({
//====--------------------------------
// "Transit function" of Aggregates
//====--------------------------------
{ 768, { EXPRESSION_TYPE_AGGREGATE_MAX, 1} },
{ 770, { EXPRESSION_TYPE_AGGREGATE_MAX, 1} },
{ 223, { EXPRESSION_TYPE_AGGREGATE_MAX, 1} },
{ 769, { EXPRESSION_TYPE_AGGREGATE_MIN, 1} },
{ 771, { EXPRESSION_TYPE_AGGREGATE_MIN, 1} },
{ 224, { EXPRESSION_TYPE_AGGREGATE_MIN, 1} },
{ 1840, { EXPRESSION_TYPE_AGGREGATE_SUM, 1} },
{ 1841, { EXPRESSION_TYPE_AGGREGATE_SUM, 1} },
{ 1842, { EXPRESSION_TYPE_AGGREGATE_SUM, 1} },
{ 218, { EXPRESSION_TYPE_AGGREGATE_SUM, 1} },
{ 222, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1834, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1835, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1836, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1833, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1962, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1963, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{1219, {EXPRESSION_TYPE_AGGREGATE_COUNT, 1} },
{2804, {EXPRESSION_TYPE_AGGREGATE_COUNT, 1} }
});
}
}
<commit_msg>add support from numeric ops<commit_after>
#include "backend/bridge/dml/expr/pg_func_map.h"
namespace peloton {
namespace bridge {
/**
* @brief Mapping PG Function Id to Peloton Function Meta Info.
*/
std::unordered_map<Oid, const PltFuncMetaInfo> kPgFuncMap({
//====--------------------------------
// Relational comparison
//====--------------------------------
{63, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{65, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{67, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{158, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{159, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{287, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{293, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{1718, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{84, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{144, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{145, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{157, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{164, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{165, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{288, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{294, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{1719, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{56, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{64, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{66, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{160, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{161, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{1246, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{289, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{295, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{1722, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{57, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{73, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{146, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{147, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{162, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{163, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{291, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{297, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{1720, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{74, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{150, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{151, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{168, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{169, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{1692, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{292, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{298, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{1721, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{72, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{148, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{149, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{166, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{167, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{1691, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{290, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{296, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{1723, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
//====--------------------------------
// Basic arithmetics
//====--------------------------------
{176, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{177, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{178, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{179, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{204, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{218, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{1724, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{180, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{181, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{182, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{183, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{205, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{219, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{1725, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{141, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{152, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{170, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{171, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{202, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{216, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{1726, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{153, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
{154, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
{172, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
{173, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
{203, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
{217, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
{1727, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
//====--------------------------------
// Cast
//====--------------------------------
{480, { EXPRESSION_TYPE_CAST, 1 } }, // int8 -> int4
{481, { EXPRESSION_TYPE_CAST, 1 } }, // int4 -> int8
{668, { EXPRESSION_TYPE_CAST, 3 } }, // bpchar -> bpchar
{669, { EXPRESSION_TYPE_CAST, 3 } }, // varchar -> varchar
{1703, { EXPRESSION_TYPE_CAST, 2 } }, // numeric -> numeric
{1740, { EXPRESSION_TYPE_CAST, 3 } }, // int8 -> numeric
{1742, { EXPRESSION_TYPE_CAST, 3 } }, // float4 -> numeric
{1743, { EXPRESSION_TYPE_CAST, 3 } }, // float8 -> numeric
{1744, { EXPRESSION_TYPE_CAST, 1 } }, // numeric -> int4
{1745, { EXPRESSION_TYPE_CAST, 1 } }, // numeric -> float4
{1746, { EXPRESSION_TYPE_CAST, 1 } }, // numeric -> float8
{1781, { EXPRESSION_TYPE_CAST, 1 } }, // int8 -> numeric
{1782, { EXPRESSION_TYPE_CAST, 1 } }, // int2 -> numeric
});
/**
* @brief Mapping PG transit function to Aggregate types.
* We have to separate it from kPgFuncMap,
* because the two maps may have overlapping functions that have
* different meaning in Peloton.
* For example, PG Function Id 218 (float8pl) means an PLUS in
* 'ordinary' expressions,
* but means a SUM(float) in an aggregation.
*/
std::unordered_map<Oid, const PltFuncMetaInfo> kPgTransitFuncMap({
//====--------------------------------
// "Transit function" of Aggregates
//====--------------------------------
{ 768, { EXPRESSION_TYPE_AGGREGATE_MAX, 1} },
{ 770, { EXPRESSION_TYPE_AGGREGATE_MAX, 1} },
{ 223, { EXPRESSION_TYPE_AGGREGATE_MAX, 1} },
{ 769, { EXPRESSION_TYPE_AGGREGATE_MIN, 1} },
{ 771, { EXPRESSION_TYPE_AGGREGATE_MIN, 1} },
{ 224, { EXPRESSION_TYPE_AGGREGATE_MIN, 1} },
{ 1840, { EXPRESSION_TYPE_AGGREGATE_SUM, 1} },
{ 1841, { EXPRESSION_TYPE_AGGREGATE_SUM, 1} },
{ 1842, { EXPRESSION_TYPE_AGGREGATE_SUM, 1} },
{ 218, { EXPRESSION_TYPE_AGGREGATE_SUM, 1} },
{ 222, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1834, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1835, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1836, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1833, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1962, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1963, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{1219, {EXPRESSION_TYPE_AGGREGATE_COUNT, 1} },
{2804, {EXPRESSION_TYPE_AGGREGATE_COUNT, 1} }
});
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2020 *
* *
* 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 <openspace/engine/globals.h>
#include <openspace/engine/downloadmanager.h>
#include <openspace/engine/configuration.h>
#include <openspace/engine/globalscallbacks.h>
#include <openspace/engine/moduleengine.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/engine/syncengine.h>
#include <openspace/engine/virtualpropertymanager.h>
#include <openspace/engine/windowdelegate.h>
#include <openspace/interaction/interactionmonitor.h>
#include <openspace/interaction/keybindingmanager.h>
#include <openspace/interaction/joystickinputstate.h>
#include <openspace/interaction/websocketinputstate.h>
#include <openspace/interaction/navigationhandler.h>
#include <openspace/interaction/sessionrecording.h>
#include <openspace/interaction/shortcutmanager.h>
#include <openspace/mission/missionmanager.h>
#include <openspace/network/parallelpeer.h>
#include <openspace/properties/propertyowner.h>
#include <openspace/rendering/dashboard.h>
#include <openspace/rendering/deferredcastermanager.h>
#include <openspace/rendering/luaconsole.h>
#include <openspace/rendering/raycastermanager.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/rendering/screenspacerenderable.h>
#include <openspace/scene/profile.h>
#include <openspace/scripting/scriptengine.h>
#include <openspace/scripting/scriptscheduler.h>
#include <openspace/util/memorymanager.h>
#include <openspace/util/timemanager.h>
#include <openspace/util/versionchecker.h>
#include <ghoul/misc/assert.h>
#include <ghoul/glm.h>
#include <ghoul/font/fontmanager.h>
#include <ghoul/misc/profiling.h>
#include <ghoul/misc/sharedmemory.h>
#include <ghoul/opengl/texture.h>
#include <array>
namespace openspace {
namespace {
constexpr const int TotalSize =
sizeof(ghoul::fontrendering::FontManager) +
sizeof(Dashboard) +
sizeof(DeferredcasterManager) +
sizeof(DownloadManager) +
sizeof(LuaConsole) +
sizeof(MemoryManager) +
sizeof(MissionManager) +
sizeof(ModuleEngine) +
sizeof(OpenSpaceEngine) +
sizeof(ParallelPeer) +
sizeof(RaycasterManager) +
sizeof(RenderEngine) +
sizeof(std::vector<std::unique_ptr<ScreenSpaceRenderable>>) +
sizeof(SyncEngine) +
sizeof(TimeManager) +
sizeof(VersionChecker) +
sizeof(VirtualPropertyManager) +
sizeof(WindowDelegate) +
sizeof(configuration::Configuration) +
sizeof(interaction::InteractionMonitor) +
sizeof(interaction::WebsocketInputStates) +
sizeof(interaction::KeybindingManager) +
sizeof(interaction::NavigationHandler) +
sizeof(interaction::SessionRecording) +
sizeof(interaction::ShortcutManager) +
sizeof(properties::PropertyOwner) +
sizeof(properties::PropertyOwner) +
sizeof(scripting::ScriptEngine) +
sizeof(scripting::ScriptScheduler) +
sizeof(Profile);
std::array<std::byte, TotalSize> DataStorage;
} // namespace
} // namespace openspace
namespace openspace::global {
void create() {
ZoneScoped
callback::create();
std::byte* currentPos = DataStorage.data();
fontManager = new (currentPos) ghoul::fontrendering::FontManager({ 1536, 1536, 1 });
ghoul_assert(fontManager, "No fontManager");
currentPos += sizeof(ghoul::fontrendering::FontManager);
dashboard = new (currentPos) Dashboard;
ghoul_assert(dashboard, "No dashboard");
currentPos += sizeof(Dashboard);
deferredcasterManager = new (currentPos) DeferredcasterManager;
ghoul_assert(deferredcasterManager, "No deferredcasterManager");
currentPos += sizeof(DeferredcasterManager);
downloadManager = new (currentPos) DownloadManager;
ghoul_assert(downloadManager, "No downloadManager");
currentPos += sizeof(DownloadManager);
luaConsole = new (currentPos) LuaConsole;
ghoul_assert(luaConsole, "No luaConsole");
currentPos += sizeof(LuaConsole);
memoryManager = new (currentPos) MemoryManager;
ghoul_assert(memoryManager, "No memoryManager");
currentPos += sizeof(MemoryManager);
missionManager = new (currentPos) MissionManager;
ghoul_assert(missionManager, "No missionManager");
currentPos += sizeof(MissionManager);
moduleEngine = new (currentPos) ModuleEngine;
ghoul_assert(moduleEngine, "No moduleEngine");
currentPos += sizeof(ModuleEngine);
openSpaceEngine = new (currentPos) OpenSpaceEngine;
ghoul_assert(openSpaceEngine, "No openSpaceEngine");
currentPos += sizeof(OpenSpaceEngine);
parallelPeer = new (currentPos) ParallelPeer;
ghoul_assert(parallelPeer, "No parallelPeer");
currentPos += sizeof(ParallelPeer);
raycasterManager = new (currentPos) RaycasterManager;
ghoul_assert(raycasterManager, "No raycasterManager");
currentPos += sizeof(RaycasterManager);
renderEngine = new (currentPos) RenderEngine;
ghoul_assert(renderEngine, "No renderEngine");
currentPos += sizeof(RenderEngine);
screenSpaceRenderables =
new (currentPos) std::vector<std::unique_ptr<ScreenSpaceRenderable>>;
ghoul_assert(screenSpaceRenderables, "No screenSpaceRenderables");
currentPos += sizeof(std::vector<std::unique_ptr<ScreenSpaceRenderable>>);
syncEngine = new (currentPos) SyncEngine(4096);
ghoul_assert(syncEngine, "No syncEngine");
currentPos += sizeof(SyncEngine);
timeManager = new (currentPos) TimeManager;
ghoul_assert(timeManager, "No timeManager");
currentPos += sizeof(TimeManager);
versionChecker = new (currentPos) VersionChecker;
ghoul_assert(versionChecker, "No versionChecker");
currentPos += sizeof(VersionChecker);
virtualPropertyManager = new (currentPos) VirtualPropertyManager;
ghoul_assert(virtualPropertyManager, "No virtualPropertyManager");
currentPos += sizeof(VirtualPropertyManager);
windowDelegate = new (currentPos) WindowDelegate;
ghoul_assert(windowDelegate, "No windowDelegate");
currentPos += sizeof(WindowDelegate);
configuration = new (currentPos) configuration::Configuration;
ghoul_assert(configuration, "No configuration");
currentPos += sizeof(configuration::Configuration);
interactionMonitor = new (currentPos) interaction::InteractionMonitor;
ghoul_assert(interactionMonitor, "No interactionMonitor");
currentPos += sizeof(interaction::InteractionMonitor);
joystickInputStates = new (currentPos) interaction::JoystickInputStates;
ghoul_assert(joystickInputStates, "No joystickInputStates");
currentPos += sizeof(interaction::JoystickInputStates);
websocketInputStates = new (currentPos) interaction::WebsocketInputStates;
ghoul_assert(websocketInputStates, "No websocketInputStates");
currentPos += sizeof(interaction::WebsocketInputStates);
keybindingManager = new (currentPos) interaction::KeybindingManager;
ghoul_assert(keybindingManager, "No keybindingManager");
currentPos += sizeof(interaction::KeybindingManager);
navigationHandler = new (currentPos) interaction::NavigationHandler;
ghoul_assert(navigationHandler, "No navigationHandler");
currentPos += sizeof(interaction::NavigationHandler);
sessionRecording = new (currentPos) interaction::SessionRecording(true);
ghoul_assert(sessionRecording, "No sessionRecording");
currentPos += sizeof(interaction::SessionRecording);
shortcutManager = new (currentPos) interaction::ShortcutManager;
ghoul_assert(shortcutManager, "No shortcutManager");
currentPos += sizeof(interaction::ShortcutManager);
rootPropertyOwner = new (currentPos) properties::PropertyOwner({ "" });
ghoul_assert(rootPropertyOwner, "No rootPropertyOwner");
currentPos += sizeof(properties::PropertyOwner);
screenSpaceRootPropertyOwner =
new (currentPos) properties::PropertyOwner({ "ScreenSpace" });
ghoul_assert(screenSpaceRootPropertyOwner, "No screenSpaceRootPropertyOwner");
currentPos += sizeof(properties::PropertyOwner);
scriptEngine = new (currentPos) scripting::ScriptEngine;
ghoul_assert(scriptEngine, "No scriptEngine");
currentPos += sizeof(scripting::ScriptEngine);
scriptScheduler = new (currentPos) scripting::ScriptScheduler;
ghoul_assert(scriptScheduler, "No scriptScheduler");
currentPos += sizeof(scripting::ScriptScheduler);
profile = new (currentPos) Profile;
ghoul_assert(profile, "No profile");
currentPos += sizeof(Profile);
}
void initialize() {
ZoneScoped
rootPropertyOwner->addPropertySubOwner(global::moduleEngine);
navigationHandler->setPropertyOwner(global::rootPropertyOwner);
// New property subowners also have to be added to the ImGuiModule callback!
rootPropertyOwner->addPropertySubOwner(global::navigationHandler);
rootPropertyOwner->addPropertySubOwner(global::interactionMonitor);
rootPropertyOwner->addPropertySubOwner(global::sessionRecording);
rootPropertyOwner->addPropertySubOwner(global::timeManager);
rootPropertyOwner->addPropertySubOwner(global::renderEngine);
rootPropertyOwner->addPropertySubOwner(global::screenSpaceRootPropertyOwner);
rootPropertyOwner->addPropertySubOwner(global::parallelPeer);
rootPropertyOwner->addPropertySubOwner(global::luaConsole);
rootPropertyOwner->addPropertySubOwner(global::dashboard);
syncEngine->addSyncable(global::scriptEngine);
}
void initializeGL() {
ZoneScoped
}
void destroy() {
LDEBUGC("Globals", "Destroying 'Profile'");
profile->~Profile();
LDEBUGC("Globals", "Destroying 'ScriptScheduler'");
scriptScheduler->~ScriptScheduler();
LDEBUGC("Globals", "Destroying 'ScriptEngine'");
scriptEngine->~ScriptEngine();
LDEBUGC("Globals", "Destroying 'ScreenSpace Root Owner'");
screenSpaceRootPropertyOwner->~PropertyOwner();
LDEBUGC("Globals", "Destroying 'Root Owner'");
rootPropertyOwner->~PropertyOwner();
LDEBUGC("Globals", "Destroying 'ShortcutManager'");
shortcutManager->~ShortcutManager();
LDEBUGC("Globals", "Destroying 'SessionRecording'");
sessionRecording->~SessionRecording();
LDEBUGC("Globals", "Destroying 'NavigationHandler'");
navigationHandler->~NavigationHandler();
LDEBUGC("Globals", "Destroying 'KeybindingManager'");
keybindingManager->~KeybindingManager();
LDEBUGC("Globals", "Destroying 'WebsocketInputStates'");
websocketInputStates->~WebsocketInputStates();
LDEBUGC("Globals", "Destroying 'JoystickInputStates'");
joystickInputStates->~JoystickInputStates();
LDEBUGC("Globals", "Destroying 'InteractionMonitor'");
interactionMonitor->~InteractionMonitor();
LDEBUGC("Globals", "Destroying 'Configuration'");
configuration->~Configuration();
LDEBUGC("Globals", "Destroying 'WindowDelegate'");
windowDelegate->~WindowDelegate();
LDEBUGC("Globals", "Destroying 'VirtualPropertyManager'");
virtualPropertyManager->~VirtualPropertyManager();
LDEBUGC("Globals", "Destroying 'VersionChecker'");
versionChecker->~VersionChecker();
LDEBUGC("Globals", "Destroying 'TimeManager'");
timeManager->~TimeManager();
LDEBUGC("Globals", "Destroying 'SyncEngine'");
syncEngine->~SyncEngine();
LDEBUGC("Globals", "Destroying 'ScreenSpaceRenderables'");
screenSpaceRenderables->~vector<std::unique_ptr<ScreenSpaceRenderable>>();
LDEBUGC("Globals", "Destroying 'RenderEngine'");
renderEngine->~RenderEngine();
LDEBUGC("Globals", "Destroying 'RaycasterManager'");
raycasterManager->~RaycasterManager();
LDEBUGC("Globals", "Destroying 'ParallelPeer'");
parallelPeer->~ParallelPeer();
LDEBUGC("Globals", "Destroying 'OpenSpaceEngine'");
openSpaceEngine->~OpenSpaceEngine();
LDEBUGC("Globals", "Destroying 'ModuleEngine'");
moduleEngine->~ModuleEngine();
LDEBUGC("Globals", "Destroying 'MissionManager'");
missionManager->~MissionManager();
LDEBUGC("Globals", "Destroying 'MemoryManager'");
memoryManager->~MemoryManager();
LDEBUGC("Globals", "Destroying 'LuaConsole'");
luaConsole->~LuaConsole();
LDEBUGC("Globals", "Destroying 'DownloadManager'");
downloadManager->~DownloadManager();
LDEBUGC("Globals", "Destroying 'DeferredcasterManager'");
deferredcasterManager->~DeferredcasterManager();
LDEBUGC("Globals", "Destroying 'Dashboard'");
dashboard->~Dashboard();
LDEBUGC("Globals", "Destroying 'FontManager'");
fontManager->~FontManager();
std::fill(DataStorage.begin(), DataStorage.end(), std::byte(0));
callback::destroy();
}
void deinitialize() {
ZoneScoped
for (std::unique_ptr<ScreenSpaceRenderable>& ssr : *screenSpaceRenderables) {
ssr->deinitialize();
}
syncEngine->removeSyncables(timeManager->getSyncables());
moduleEngine->deinitialize();
luaConsole->deinitialize();
scriptEngine->deinitialize();
fontManager->deinitialize();
}
void deinitializeGL() {
ZoneScoped
for (std::unique_ptr<ScreenSpaceRenderable>& ssr : *screenSpaceRenderables) {
ssr->deinitializeGL();
}
renderEngine->deinitializeGL();
moduleEngine->deinitializeGL();
}
} // namespace openspace::global
<commit_msg>Modified globals DataStorage method to make gcc happy on linux<commit_after>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2020 *
* *
* 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 <openspace/engine/globals.h>
#include <openspace/engine/downloadmanager.h>
#include <openspace/engine/configuration.h>
#include <openspace/engine/globalscallbacks.h>
#include <openspace/engine/moduleengine.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/engine/syncengine.h>
#include <openspace/engine/virtualpropertymanager.h>
#include <openspace/engine/windowdelegate.h>
#include <openspace/interaction/interactionmonitor.h>
#include <openspace/interaction/keybindingmanager.h>
#include <openspace/interaction/joystickinputstate.h>
#include <openspace/interaction/websocketinputstate.h>
#include <openspace/interaction/navigationhandler.h>
#include <openspace/interaction/sessionrecording.h>
#include <openspace/interaction/shortcutmanager.h>
#include <openspace/mission/missionmanager.h>
#include <openspace/network/parallelpeer.h>
#include <openspace/properties/propertyowner.h>
#include <openspace/rendering/dashboard.h>
#include <openspace/rendering/deferredcastermanager.h>
#include <openspace/rendering/luaconsole.h>
#include <openspace/rendering/raycastermanager.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/rendering/screenspacerenderable.h>
#include <openspace/scene/profile.h>
#include <openspace/scripting/scriptengine.h>
#include <openspace/scripting/scriptscheduler.h>
#include <openspace/util/memorymanager.h>
#include <openspace/util/timemanager.h>
#include <openspace/util/versionchecker.h>
#include <ghoul/misc/assert.h>
#include <ghoul/glm.h>
#include <ghoul/font/fontmanager.h>
#include <ghoul/misc/profiling.h>
#include <ghoul/misc/sharedmemory.h>
#include <ghoul/opengl/texture.h>
#include <array>
namespace openspace {
namespace {
constexpr const int TotalSize =
sizeof(ghoul::fontrendering::FontManager) +
sizeof(Dashboard) +
sizeof(DeferredcasterManager) +
sizeof(DownloadManager) +
sizeof(LuaConsole) +
sizeof(MemoryManager) +
sizeof(MissionManager) +
sizeof(ModuleEngine) +
sizeof(OpenSpaceEngine) +
sizeof(ParallelPeer) +
sizeof(RaycasterManager) +
sizeof(RenderEngine) +
sizeof(std::vector<std::unique_ptr<ScreenSpaceRenderable>>) +
sizeof(SyncEngine) +
sizeof(TimeManager) +
sizeof(VersionChecker) +
sizeof(VirtualPropertyManager) +
sizeof(WindowDelegate) +
sizeof(configuration::Configuration) +
sizeof(interaction::InteractionMonitor) +
sizeof(interaction::WebsocketInputStates) +
sizeof(interaction::KeybindingManager) +
sizeof(interaction::NavigationHandler) +
sizeof(interaction::SessionRecording) +
sizeof(interaction::ShortcutManager) +
sizeof(properties::PropertyOwner) +
sizeof(properties::PropertyOwner) +
sizeof(scripting::ScriptEngine) +
sizeof(scripting::ScriptScheduler) +
sizeof(Profile);
std::vector<std::byte> DataStorage;
} // namespace
} // namespace openspace
namespace openspace::global {
void create() {
ZoneScoped
callback::create();
DataStorage.resize(TotalSize);
std::byte* currentPos = DataStorage.data();
fontManager = new (currentPos) ghoul::fontrendering::FontManager({ 1536, 1536, 1 });
ghoul_assert(fontManager, "No fontManager");
currentPos += sizeof(ghoul::fontrendering::FontManager);
dashboard = new (currentPos) Dashboard;
ghoul_assert(dashboard, "No dashboard");
currentPos += sizeof(Dashboard);
deferredcasterManager = new (currentPos) DeferredcasterManager;
ghoul_assert(deferredcasterManager, "No deferredcasterManager");
currentPos += sizeof(DeferredcasterManager);
downloadManager = new (currentPos) DownloadManager;
ghoul_assert(downloadManager, "No downloadManager");
currentPos += sizeof(DownloadManager);
luaConsole = new (currentPos) LuaConsole;
ghoul_assert(luaConsole, "No luaConsole");
currentPos += sizeof(LuaConsole);
memoryManager = new (currentPos) MemoryManager;
ghoul_assert(memoryManager, "No memoryManager");
currentPos += sizeof(MemoryManager);
missionManager = new (currentPos) MissionManager;
ghoul_assert(missionManager, "No missionManager");
currentPos += sizeof(MissionManager);
moduleEngine = new (currentPos) ModuleEngine;
ghoul_assert(moduleEngine, "No moduleEngine");
currentPos += sizeof(ModuleEngine);
openSpaceEngine = new (currentPos) OpenSpaceEngine;
ghoul_assert(openSpaceEngine, "No openSpaceEngine");
currentPos += sizeof(OpenSpaceEngine);
parallelPeer = new (currentPos) ParallelPeer;
ghoul_assert(parallelPeer, "No parallelPeer");
currentPos += sizeof(ParallelPeer);
raycasterManager = new (currentPos) RaycasterManager;
ghoul_assert(raycasterManager, "No raycasterManager");
currentPos += sizeof(RaycasterManager);
renderEngine = new (currentPos) RenderEngine;
ghoul_assert(renderEngine, "No renderEngine");
currentPos += sizeof(RenderEngine);
screenSpaceRenderables =
new (currentPos) std::vector<std::unique_ptr<ScreenSpaceRenderable>>;
ghoul_assert(screenSpaceRenderables, "No screenSpaceRenderables");
currentPos += sizeof(std::vector<std::unique_ptr<ScreenSpaceRenderable>>);
syncEngine = new (currentPos) SyncEngine(4096);
ghoul_assert(syncEngine, "No syncEngine");
currentPos += sizeof(SyncEngine);
timeManager = new (currentPos) TimeManager;
ghoul_assert(timeManager, "No timeManager");
currentPos += sizeof(TimeManager);
versionChecker = new (currentPos) VersionChecker;
ghoul_assert(versionChecker, "No versionChecker");
currentPos += sizeof(VersionChecker);
virtualPropertyManager = new (currentPos) VirtualPropertyManager;
ghoul_assert(virtualPropertyManager, "No virtualPropertyManager");
currentPos += sizeof(VirtualPropertyManager);
windowDelegate = new (currentPos) WindowDelegate;
ghoul_assert(windowDelegate, "No windowDelegate");
currentPos += sizeof(WindowDelegate);
configuration = new (currentPos) configuration::Configuration;
ghoul_assert(configuration, "No configuration");
currentPos += sizeof(configuration::Configuration);
interactionMonitor = new (currentPos) interaction::InteractionMonitor;
ghoul_assert(interactionMonitor, "No interactionMonitor");
currentPos += sizeof(interaction::InteractionMonitor);
joystickInputStates = new (currentPos) interaction::JoystickInputStates;
ghoul_assert(joystickInputStates, "No joystickInputStates");
currentPos += sizeof(interaction::JoystickInputStates);
websocketInputStates = new (currentPos) interaction::WebsocketInputStates;
ghoul_assert(websocketInputStates, "No websocketInputStates");
currentPos += sizeof(interaction::WebsocketInputStates);
keybindingManager = new (currentPos) interaction::KeybindingManager;
ghoul_assert(keybindingManager, "No keybindingManager");
currentPos += sizeof(interaction::KeybindingManager);
navigationHandler = new (currentPos) interaction::NavigationHandler;
ghoul_assert(navigationHandler, "No navigationHandler");
currentPos += sizeof(interaction::NavigationHandler);
sessionRecording = new (currentPos) interaction::SessionRecording(true);
ghoul_assert(sessionRecording, "No sessionRecording");
currentPos += sizeof(interaction::SessionRecording);
shortcutManager = new (currentPos) interaction::ShortcutManager;
ghoul_assert(shortcutManager, "No shortcutManager");
currentPos += sizeof(interaction::ShortcutManager);
rootPropertyOwner = new (currentPos) properties::PropertyOwner({ "" });
ghoul_assert(rootPropertyOwner, "No rootPropertyOwner");
currentPos += sizeof(properties::PropertyOwner);
screenSpaceRootPropertyOwner =
new (currentPos) properties::PropertyOwner({ "ScreenSpace" });
ghoul_assert(screenSpaceRootPropertyOwner, "No screenSpaceRootPropertyOwner");
currentPos += sizeof(properties::PropertyOwner);
scriptEngine = new (currentPos) scripting::ScriptEngine;
ghoul_assert(scriptEngine, "No scriptEngine");
currentPos += sizeof(scripting::ScriptEngine);
scriptScheduler = new (currentPos) scripting::ScriptScheduler;
ghoul_assert(scriptScheduler, "No scriptScheduler");
currentPos += sizeof(scripting::ScriptScheduler);
profile = new (currentPos) Profile;
ghoul_assert(profile, "No profile");
currentPos += sizeof(Profile);
}
void initialize() {
ZoneScoped
rootPropertyOwner->addPropertySubOwner(global::moduleEngine);
navigationHandler->setPropertyOwner(global::rootPropertyOwner);
// New property subowners also have to be added to the ImGuiModule callback!
rootPropertyOwner->addPropertySubOwner(global::navigationHandler);
rootPropertyOwner->addPropertySubOwner(global::interactionMonitor);
rootPropertyOwner->addPropertySubOwner(global::sessionRecording);
rootPropertyOwner->addPropertySubOwner(global::timeManager);
rootPropertyOwner->addPropertySubOwner(global::renderEngine);
rootPropertyOwner->addPropertySubOwner(global::screenSpaceRootPropertyOwner);
rootPropertyOwner->addPropertySubOwner(global::parallelPeer);
rootPropertyOwner->addPropertySubOwner(global::luaConsole);
rootPropertyOwner->addPropertySubOwner(global::dashboard);
syncEngine->addSyncable(global::scriptEngine);
}
void initializeGL() {
ZoneScoped
}
void destroy() {
LDEBUGC("Globals", "Destroying 'Profile'");
profile->~Profile();
LDEBUGC("Globals", "Destroying 'ScriptScheduler'");
scriptScheduler->~ScriptScheduler();
LDEBUGC("Globals", "Destroying 'ScriptEngine'");
scriptEngine->~ScriptEngine();
LDEBUGC("Globals", "Destroying 'ScreenSpace Root Owner'");
screenSpaceRootPropertyOwner->~PropertyOwner();
LDEBUGC("Globals", "Destroying 'Root Owner'");
rootPropertyOwner->~PropertyOwner();
LDEBUGC("Globals", "Destroying 'ShortcutManager'");
shortcutManager->~ShortcutManager();
LDEBUGC("Globals", "Destroying 'SessionRecording'");
sessionRecording->~SessionRecording();
LDEBUGC("Globals", "Destroying 'NavigationHandler'");
navigationHandler->~NavigationHandler();
LDEBUGC("Globals", "Destroying 'KeybindingManager'");
keybindingManager->~KeybindingManager();
LDEBUGC("Globals", "Destroying 'WebsocketInputStates'");
websocketInputStates->~WebsocketInputStates();
LDEBUGC("Globals", "Destroying 'JoystickInputStates'");
joystickInputStates->~JoystickInputStates();
LDEBUGC("Globals", "Destroying 'InteractionMonitor'");
interactionMonitor->~InteractionMonitor();
LDEBUGC("Globals", "Destroying 'Configuration'");
configuration->~Configuration();
LDEBUGC("Globals", "Destroying 'WindowDelegate'");
windowDelegate->~WindowDelegate();
LDEBUGC("Globals", "Destroying 'VirtualPropertyManager'");
virtualPropertyManager->~VirtualPropertyManager();
LDEBUGC("Globals", "Destroying 'VersionChecker'");
versionChecker->~VersionChecker();
LDEBUGC("Globals", "Destroying 'TimeManager'");
timeManager->~TimeManager();
LDEBUGC("Globals", "Destroying 'SyncEngine'");
syncEngine->~SyncEngine();
LDEBUGC("Globals", "Destroying 'ScreenSpaceRenderables'");
screenSpaceRenderables->~vector<std::unique_ptr<ScreenSpaceRenderable>>();
LDEBUGC("Globals", "Destroying 'RenderEngine'");
renderEngine->~RenderEngine();
LDEBUGC("Globals", "Destroying 'RaycasterManager'");
raycasterManager->~RaycasterManager();
LDEBUGC("Globals", "Destroying 'ParallelPeer'");
parallelPeer->~ParallelPeer();
LDEBUGC("Globals", "Destroying 'OpenSpaceEngine'");
openSpaceEngine->~OpenSpaceEngine();
LDEBUGC("Globals", "Destroying 'ModuleEngine'");
moduleEngine->~ModuleEngine();
LDEBUGC("Globals", "Destroying 'MissionManager'");
missionManager->~MissionManager();
LDEBUGC("Globals", "Destroying 'MemoryManager'");
memoryManager->~MemoryManager();
LDEBUGC("Globals", "Destroying 'LuaConsole'");
luaConsole->~LuaConsole();
LDEBUGC("Globals", "Destroying 'DownloadManager'");
downloadManager->~DownloadManager();
LDEBUGC("Globals", "Destroying 'DeferredcasterManager'");
deferredcasterManager->~DeferredcasterManager();
LDEBUGC("Globals", "Destroying 'Dashboard'");
dashboard->~Dashboard();
LDEBUGC("Globals", "Destroying 'FontManager'");
fontManager->~FontManager();
DataStorage.clear();
callback::destroy();
}
void deinitialize() {
ZoneScoped
for (std::unique_ptr<ScreenSpaceRenderable>& ssr : *screenSpaceRenderables) {
ssr->deinitialize();
}
syncEngine->removeSyncables(timeManager->getSyncables());
moduleEngine->deinitialize();
luaConsole->deinitialize();
scriptEngine->deinitialize();
fontManager->deinitialize();
}
void deinitializeGL() {
ZoneScoped
for (std::unique_ptr<ScreenSpaceRenderable>& ssr : *screenSpaceRenderables) {
ssr->deinitializeGL();
}
renderEngine->deinitializeGL();
moduleEngine->deinitializeGL();
}
} // namespace openspace::global
<|endoftext|> |
<commit_before>/*
main.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB
Kleopatra is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Kleopatra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "aboutdata.h"
#include "kwatchgnupgmainwin.h"
#include <kuniqueapplication.h>
#include <kcmdlineargs.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <kdebug.h>
class KWatchGnuPGApplication : public KUniqueApplication {
public:
KWatchGnuPGApplication();
~KWatchGnuPGApplication();
virtual int newInstance();
private:
KWatchGnuPGMainWindow* mMainWin;
};
KWatchGnuPGApplication::KWatchGnuPGApplication()
: KUniqueApplication(), mMainWin(0)
{
}
KWatchGnuPGApplication::~KWatchGnuPGApplication()
{
delete mMainWin;
}
int KWatchGnuPGApplication::newInstance()
{
if( !mMainWin ) {
mMainWin = new KWatchGnuPGMainWindow( 0, "kwatchgnupg mainwin" );
setMainWidget( mMainWin );
}
mMainWin->show();
return KUniqueApplication::newInstance();
}
int main( int argc, char** argv )
{
AboutData aboutData;
KCmdLineArgs::init(argc, argv, &aboutData);
static const KCmdLineOptions options[] = {
KCmdLineLastOption// End of options.
};
KCmdLineArgs::addCmdLineOptions( options );
KWatchGnuPGApplication::addCmdLineOptions();
#if 0
if (!KWatchGnuPGApplication::start()) {
kdError() << "KWatchGnuPG is already running!" << endl;
return 0;
}
#endif
KWatchGnuPGApplication app;
return app.exec();
}
<commit_msg>Exit the process when closing the window<commit_after>/*
main.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB
Kleopatra is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Kleopatra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "aboutdata.h"
#include "kwatchgnupgmainwin.h"
#include <kuniqueapplication.h>
#include <kcmdlineargs.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <kdebug.h>
class KWatchGnuPGApplication : public KUniqueApplication {
public:
KWatchGnuPGApplication();
~KWatchGnuPGApplication();
virtual int newInstance();
private:
KWatchGnuPGMainWindow* mMainWin;
};
KWatchGnuPGApplication::KWatchGnuPGApplication()
: KUniqueApplication(), mMainWin(0)
{
}
KWatchGnuPGApplication::~KWatchGnuPGApplication()
{
delete mMainWin;
}
int KWatchGnuPGApplication::newInstance()
{
if( !mMainWin ) {
mMainWin = new KWatchGnuPGMainWindow( 0, "kwatchgnupg mainwin" );
setMainWidget( mMainWin );
}
mMainWin->show();
return KUniqueApplication::newInstance();
}
int main( int argc, char** argv )
{
AboutData aboutData;
KCmdLineArgs::init(argc, argv, &aboutData);
static const KCmdLineOptions options[] = {
KCmdLineLastOption// End of options.
};
KCmdLineArgs::addCmdLineOptions( options );
KWatchGnuPGApplication::addCmdLineOptions();
#if 0
if (!KWatchGnuPGApplication::start()) {
kdError() << "KWatchGnuPG is already running!" << endl;
return 0;
}
#endif
KWatchGnuPGApplication app;
QObject::connect( &app, SIGNAL( lastWindowClosed() ), &app, SLOT( quit() ) );
return app.exec();
}
<|endoftext|> |
<commit_before>#include "spectrum_display.hh"
#include <essentia/algorithmfactory.h>
#include <essentia/algorithm.h>
#include <QPainter>
#include <QDebug>
#include <algorithm>
namespace Decomposer {
static QColor BACKGROUND_COLOR("#33ffd6");
struct SpectrumDisplay::Private
{
std::vector<essentia::Real> input;
std::vector<essentia::Real> output;
std::unique_ptr<essentia::standard::Algorithm> spectrum;
};
SpectrumDisplay::SpectrumDisplay(QWidget* p)
: QWidget(p)
, buffer_(sampleRate_, windowSize_)
{
p_ = std::make_unique<Private>();
p_->input.resize(windowSize_);
essentia::standard::AlgorithmFactory& factory = essentia::standard::AlgorithmFactory::instance();
p_->spectrum.reset(factory.create("Spectrum", "size", 4096));
p_->spectrum->input("frame").set(p_->input);
p_->spectrum->output("spectrum").set(p_->output);
}
SpectrumDisplay::~SpectrumDisplay()
{
}
void SpectrumDisplay::addData(const AudioBuffer& data)
{
buffer_.append(data);
unpaintedSamples += data.getSamples();
if (double(unpaintedSamples) / buffer_.getRate() > 0.05 && buffer_.size() == windowSize_)
{
calculate();
repaint();
unpaintedSamples = 0;
}
}
void SpectrumDisplay::setWindowSize(int size)
{
if (size != windowSize_)
{
windowSize_ = size;
buffer_.setLength(sampleRate_, windowSize_);
unpaintedSamples = 0;
}
}
void SpectrumDisplay::setSampleRate(int rate)
{
if (rate != sampleRate_)
{
sampleRate_ = rate;
buffer_.setLength(sampleRate_, windowSize_);
unpaintedSamples = 0;
}
}
void SpectrumDisplay::paintEvent(QPaintEvent*)
{
QPainter painter(this);
painter.fillRect(rect(), BACKGROUND_COLOR);
double h = height();
int yZoom = 4;
int xZoom = 16;
for(size_t i = 0 ; i < p_->output.size()/xZoom; i++)
{
float v = p_->output[i];
double x = double(width()) * i / p_->output.size();
double y = 2 * h * v / windowSize_;
// zoom
y *= yZoom;
x *= xZoom;
painter.drawLine(QPointF(x, h), QPointF(x, h-y));
}
}
void SpectrumDisplay::calculate()
{
assert(buffer_.size() == windowSize_);
p_->input.resize(windowSize_);
std::copy(buffer_.begin(), buffer_.end(), p_->input.begin());
p_->spectrum->compute();
qDebug() << "Spectrum size=" << p_->output.size();
auto max = *std::max_element(p_->output.begin(), p_->output.end());
auto min = *std::min_element(p_->output.begin(), p_->output.end());
qDebug() << "range=" << min << ", " << max;
}
}
<commit_msg>spectrum with windowing<commit_after>#include "spectrum_display.hh"
#include <essentia/algorithmfactory.h>
#include <essentia/algorithm.h>
#include <QPainter>
#include <QDebug>
#include <algorithm>
namespace Decomposer {
static QColor BACKGROUND_COLOR("#33ffd6");
struct SpectrumDisplay::Private
{
std::vector<essentia::Real> input;
std::vector<essentia::Real> windowed;
std::vector<essentia::Real> output;
std::unique_ptr<essentia::standard::Algorithm> spectrum;
std::unique_ptr<essentia::standard::Algorithm> window;
};
SpectrumDisplay::SpectrumDisplay(QWidget* p)
: QWidget(p)
, buffer_(sampleRate_, windowSize_)
{
p_ = std::make_unique<Private>();
p_->input.resize(windowSize_);
essentia::standard::AlgorithmFactory& factory = essentia::standard::AlgorithmFactory::instance();
p_->spectrum.reset(factory.create(
"Spectrum",
"size", 4096));
p_->window.reset(factory.create(
"Windowing",
"type", "blackmanharris62"));
p_->window->input("frame").set(p_->input);
p_->window->output("frame").set(p_->windowed);
p_->spectrum->input("frame").set(p_->windowed);
p_->spectrum->output("spectrum").set(p_->output);
}
SpectrumDisplay::~SpectrumDisplay()
{
}
void SpectrumDisplay::addData(const AudioBuffer& data)
{
buffer_.append(data);
unpaintedSamples += data.getSamples();
if (double(unpaintedSamples) / buffer_.getRate() > 0.05 && buffer_.size() == windowSize_)
{
calculate();
repaint();
unpaintedSamples = 0;
}
}
void SpectrumDisplay::setWindowSize(int size)
{
if (size != windowSize_)
{
windowSize_ = size;
buffer_.setLength(sampleRate_, windowSize_);
unpaintedSamples = 0;
}
}
void SpectrumDisplay::setSampleRate(int rate)
{
if (rate != sampleRate_)
{
sampleRate_ = rate;
buffer_.setLength(sampleRate_, windowSize_);
unpaintedSamples = 0;
}
}
void SpectrumDisplay::paintEvent(QPaintEvent*)
{
QPainter painter(this);
painter.fillRect(rect(), BACKGROUND_COLOR);
double h = height();
int yZoom = 4;
int xZoom = 16;
for(size_t i = 0 ; i < p_->output.size()/xZoom; i++)
{
float v = p_->output[i];
double x = double(width()) * i / p_->output.size();
double y = v * h;
// zoom
y *= yZoom;
x *= xZoom;
painter.drawLine(QPointF(x, h), QPointF(x, h-y));
}
}
void SpectrumDisplay::calculate()
{
assert(buffer_.size() == windowSize_);
p_->input.resize(windowSize_);
std::copy(buffer_.begin(), buffer_.end(), p_->input.begin());
p_->window->compute();
p_->spectrum->compute();
qDebug() << "Spectrum size=" << p_->output.size();
auto max = *std::max_element(p_->output.begin(), p_->output.end());
auto min = *std::min_element(p_->output.begin(), p_->output.end());
qDebug() << "range=" << min << ", " << max;
}
}
<|endoftext|> |
<commit_before>// MIT License
//
// Copyright (c) 2017 Artur Wyszyński, aljen at hitomi dot pl
//
// 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 <fstream>
#include <iostream>
#include <string_view>
#include "core/registry.h"
#include "elements/logic/clock.h"
#include "elements/package.h"
#define TRACE_LOGIC 0
namespace elements {
Package::Package()
: Element{}
{
m_data.push_back(this);
addInput(ValueType::eBool, "#1");
addInput(ValueType::eBool, "#2");
addInput(ValueType::eBool, "#3");
addOutput(ValueType::eBool, "#1");
}
Package::~Package()
{
size_t const SIZE{ m_data.size() };
for (size_t i = 1; i < SIZE; ++i) {
auto *const element = m_data[i];
if (element) delete element;
}
}
void Package::serialize(Element::Json &a_json)
{
Element::serialize(a_json);
auto &jsonNode = a_json["node"];
jsonNode["inputs_position"]["x"] = m_inputsPosition.x;
jsonNode["inputs_position"]["y"] = m_inputsPosition.y;
jsonNode["outputs_position"]["x"] = m_outputsPosition.x;
jsonNode["outputs_position"]["y"] = m_outputsPosition.y;
auto &jsonPackage = a_json["package"];
jsonPackage["description"] = m_packageDescription;
jsonPackage["path"] = m_packagePath;
jsonPackage["icon"] = m_packageIcon;
auto jsonElements = Json::array();
// TODO(aljen): fix holes
size_t const DATA_SIZE{ m_data.size() };
for (size_t i = 1; i < DATA_SIZE; ++i) {
auto const element = m_data[i];
if (element == nullptr) continue;
Json jsonElement{};
element->serialize(jsonElement);
jsonElements.push_back(jsonElement);
}
jsonPackage["elements"] = jsonElements;
auto jsonConnections = Json::array();
for (auto const &connection : m_connections) {
Json jsonConnection{}, jsonConnect{}, jsonTo{};
jsonConnect["id"] = connection.from_id;
jsonConnect["socket"] = connection.from_socket;
jsonTo["id"] = connection.to_id;
jsonTo["socket"] = connection.to_socket;
jsonConnection["connect"] = jsonConnect;
jsonConnection["to"] = jsonTo;
jsonConnections.push_back(jsonConnection);
}
jsonPackage["connections"] = jsonConnections;
}
void Package::deserialize(Json const &a_json)
{
std::cout << __PRETTY_FUNCTION__ << '>' << std::endl;
Element::deserialize(a_json);
auto const &jsonNode = a_json["node"];
auto const jsonInputsPosition = jsonNode["inputs_position"];
auto const jsonInputsPositionX = jsonInputsPosition["x"].get<double>();
auto const jsonInputsPositionY = jsonInputsPosition["y"].get<double>();
auto const jsonOutputsPosition = jsonNode["outputs_position"];
auto const jsonOutputsPositionX = jsonOutputsPosition["x"].get<double>();
auto const jsonOutputsPositionY = jsonOutputsPosition["y"].get<double>();
auto const &jsonPackage = a_json["package"];
auto const &jsonElements = jsonPackage["elements"];
auto const &jsonConnections = jsonPackage["connections"];
auto const &jsonDescription = jsonPackage["description"].get<std::string>();
auto const &jsonIcon = jsonPackage["icon"].get<std::string>();
auto const &jsonPath = jsonPackage["path"].get<std::string>();
setPackageDescription(jsonDescription);
setPackageIcon(jsonIcon);
setPackagePath(jsonPath);
setInputsPosition(jsonInputsPositionX, jsonInputsPositionY);
setOutputsPosition(jsonOutputsPositionX, jsonOutputsPositionY);
for (auto const &temp : jsonElements) {
auto const &elementGroup = temp["element"];
auto const elementType = elementGroup["type"].get<std::string>();
auto const element = add(elementType.c_str());
element->deserialize(temp);
}
for (auto const &connection : jsonConnections) {
auto const &from = connection["connect"];
auto const &to = connection["to"];
auto const &fromId = from["id"].get<size_t>();
auto const &fromSocket = from["socket"].get<uint8_t>();
auto const &toId = to["id"].get<size_t>();
auto const &toSocket = to["socket"].get<uint8_t>();
std::cerr << "from " << fromId << "@" << static_cast<int>(fromSocket) << " to " << toId << "@"
<< static_cast<int>(toSocket) << std::endl;
connect(fromId, fromSocket, toId, toSocket);
}
std::cout << __PRETTY_FUNCTION__ << '<' << std::endl;
}
Element *Package::add(string::hash_t a_hash)
{
core::Registry ®istry{ core::Registry::get() };
Element *const element{ registry.createElement(a_hash) };
assert(element);
size_t index{};
if (m_free.empty()) {
index = m_data.size();
m_data.emplace_back(element);
} else {
index = m_free.back();
assert(m_data[index] == nullptr);
m_data[index] = element;
m_free.pop_back();
}
element->m_package = this;
element->m_id = index;
if (element->hash() == logic::Clock::HASH) {
using logic::Clock;
Clock *const clock{ reinterpret_cast<Clock *const>(element) };
clock->reset(Clock::clock_t::now());
m_clocks.push_back(clock);
}
return element;
}
void Package::remove(size_t a_id)
{
assert(a_id > 0);
assert(a_id < m_data.size());
assert(std::find(std::begin(m_free), std::end(m_free), a_id) == std::end(m_free));
if (m_data[a_id]->hash() == logic::Clock::HASH) std::remove(std::begin(m_clocks), std::end(m_clocks), m_data[a_id]);
delete m_data[a_id];
m_data[a_id] = nullptr;
m_free.emplace_back(a_id);
}
Element *Package::get(size_t a_id) const
{
assert(a_id < m_data.size());
assert(std::find(std::begin(m_free), std::end(m_free), a_id) == std::end(m_free));
return m_data[a_id];
}
bool Package::connect(size_t a_sourceId, uint8_t a_outputId, size_t a_targetId, uint8_t a_inputId)
{
Element *const source{ get(a_sourceId) };
Element *const target{ get(a_targetId) };
std::cerr << "source_id: " << a_sourceId << "@" << static_cast<int>(a_outputId) << " "
<< "target_id: " << a_targetId << "@" << static_cast<int>(a_inputId) << std::endl;
if (a_sourceId != 0 && a_targetId != 0) {
std::cerr << "normal connect, element to element" << std::endl;
assert(target->m_inputs[a_inputId].type == source->m_outputs[a_outputId].type);
target->m_inputs[a_inputId].id = a_sourceId;
target->m_inputs[a_inputId].slot = a_outputId;
target->m_inputs[a_inputId].value = &source->m_outputs[a_outputId].value;
} else if (a_sourceId == 0) {
std::cerr << "package connect, package input to element input" << std::endl;
target->m_inputs[a_inputId].id = a_sourceId;
target->m_inputs[a_inputId].slot = a_outputId;
target->m_inputs[a_inputId].value = source->m_inputs[a_outputId].value;
} else if (a_targetId == 0) {
std::cerr << "package connect, element output to package output" << std::endl;
}
#if TRACE_LOGIC
std::cerr << "Notifying " << a_targetId << " (" << target->name() << ")";
std::cerr << "@" << static_cast<int32_t>(a_inputId) << " when " << a_sourceId << " (" << source->name() << ")";
std::cerr << "@" << static_cast<int32_t>(a_outputId) << " changes.." << std::endl;
#endif
m_connections.emplace_back(Connection{ a_sourceId, a_outputId, a_targetId, a_inputId });
m_callbacks[a_sourceId].insert(a_targetId);
if (target->calculate()) elementChanged(a_targetId);
return true;
}
void Package::threadFunction()
{
while (!m_quit) {
auto const now = logic::Clock::clock_t::now();
for (auto &&clock : m_clocks) {
clock->update(now);
}
if (!tryDispatch()) std::this_thread::yield();
}
}
void Package::startDispatchThread()
{
m_thread = std::thread(&Package::threadFunction, this);
}
void Package::quitDispatchThread()
{
m_quit = true;
if (m_thread.joinable()) m_thread.join();
}
bool Package::tryDispatch()
{
size_t id{};
bool const dequeued{ m_queue.try_dequeue(id) };
if (dequeued) {
#if TRACE_LOGIC
std::cerr << "Dequeued id: " << id << std::endl;
#endif
dispatch(id);
}
return dequeued;
}
void Package::dispatch(size_t a_id)
{
Element *const source{ get(a_id) };
if (source->m_callback) source->m_callback(source);
if (m_callbacks.find(a_id) == std::end(m_callbacks)) {
#if TRACE_LOGIC
std::cerr << "Callbacks list for id: " << a_id << " (" << source->name() << ")"
<< " don't exist." << std::endl;
#endif
return;
}
if (m_callbacks[a_id].empty()) {
#if TRACE_LOGIC
std::cerr << "Callbacks list for id: " << a_id << " (" << source->name() << ")"
<< " is empty." << std::endl;
#endif
return;
}
#if TRACE_LOGIC
std::cerr << "Dispatching dependencies for id: " << a_id << " (" << source->name() << ")" << std::endl;
#endif
for (auto id : m_callbacks[a_id]) {
Element *const element{ get(id) };
#if TRACE_LOGIC
std::cerr << "Recalculating id: " << id << " (" << element->name() << ")"
<< " because id: " << a_id << " (" << source->name() << ")"
<< " changed." << std::endl;
#endif
if (element->calculate()) elementChanged(id);
}
}
void Package::elementChanged(size_t a_id)
{
m_queue.enqueue(a_id);
}
void Package::open(std::string const &a_filename)
{
std::ifstream file{ a_filename };
if (!file.is_open()) return;
Json json{};
file >> json;
deserialize(json);
}
void Package::save(std::string const &a_filename)
{
Json json{};
serialize(json);
std::ofstream file{ a_filename };
file << json.dump(2);
}
} // namespace elements
<commit_msg>Simplify Package dtor<commit_after>// MIT License
//
// Copyright (c) 2017 Artur Wyszyński, aljen at hitomi dot pl
//
// 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 <fstream>
#include <iostream>
#include <string_view>
#include "core/registry.h"
#include "elements/logic/clock.h"
#include "elements/package.h"
#define TRACE_LOGIC 0
namespace elements {
Package::Package()
: Element{}
{
m_data.push_back(this);
addInput(ValueType::eBool, "#1");
addInput(ValueType::eBool, "#2");
addInput(ValueType::eBool, "#3");
addOutput(ValueType::eBool, "#1");
}
Package::~Package()
{
size_t const SIZE{ m_data.size() };
for (size_t i = 1; i < SIZE; ++i) delete m_data[i];
}
void Package::serialize(Element::Json &a_json)
{
Element::serialize(a_json);
auto &jsonNode = a_json["node"];
jsonNode["inputs_position"]["x"] = m_inputsPosition.x;
jsonNode["inputs_position"]["y"] = m_inputsPosition.y;
jsonNode["outputs_position"]["x"] = m_outputsPosition.x;
jsonNode["outputs_position"]["y"] = m_outputsPosition.y;
auto &jsonPackage = a_json["package"];
jsonPackage["description"] = m_packageDescription;
jsonPackage["path"] = m_packagePath;
jsonPackage["icon"] = m_packageIcon;
auto jsonElements = Json::array();
// TODO(aljen): fix holes
size_t const DATA_SIZE{ m_data.size() };
for (size_t i = 1; i < DATA_SIZE; ++i) {
auto const element = m_data[i];
if (element == nullptr) continue;
Json jsonElement{};
element->serialize(jsonElement);
jsonElements.push_back(jsonElement);
}
jsonPackage["elements"] = jsonElements;
auto jsonConnections = Json::array();
for (auto const &connection : m_connections) {
Json jsonConnection{}, jsonConnect{}, jsonTo{};
jsonConnect["id"] = connection.from_id;
jsonConnect["socket"] = connection.from_socket;
jsonTo["id"] = connection.to_id;
jsonTo["socket"] = connection.to_socket;
jsonConnection["connect"] = jsonConnect;
jsonConnection["to"] = jsonTo;
jsonConnections.push_back(jsonConnection);
}
jsonPackage["connections"] = jsonConnections;
}
void Package::deserialize(Json const &a_json)
{
std::cout << __PRETTY_FUNCTION__ << '>' << std::endl;
Element::deserialize(a_json);
auto const &jsonNode = a_json["node"];
auto const jsonInputsPosition = jsonNode["inputs_position"];
auto const jsonInputsPositionX = jsonInputsPosition["x"].get<double>();
auto const jsonInputsPositionY = jsonInputsPosition["y"].get<double>();
auto const jsonOutputsPosition = jsonNode["outputs_position"];
auto const jsonOutputsPositionX = jsonOutputsPosition["x"].get<double>();
auto const jsonOutputsPositionY = jsonOutputsPosition["y"].get<double>();
auto const &jsonPackage = a_json["package"];
auto const &jsonElements = jsonPackage["elements"];
auto const &jsonConnections = jsonPackage["connections"];
auto const &jsonDescription = jsonPackage["description"].get<std::string>();
auto const &jsonIcon = jsonPackage["icon"].get<std::string>();
auto const &jsonPath = jsonPackage["path"].get<std::string>();
setPackageDescription(jsonDescription);
setPackageIcon(jsonIcon);
setPackagePath(jsonPath);
setInputsPosition(jsonInputsPositionX, jsonInputsPositionY);
setOutputsPosition(jsonOutputsPositionX, jsonOutputsPositionY);
for (auto const &temp : jsonElements) {
auto const &elementGroup = temp["element"];
auto const elementType = elementGroup["type"].get<std::string>();
auto const element = add(elementType.c_str());
element->deserialize(temp);
}
for (auto const &connection : jsonConnections) {
auto const &from = connection["connect"];
auto const &to = connection["to"];
auto const &fromId = from["id"].get<size_t>();
auto const &fromSocket = from["socket"].get<uint8_t>();
auto const &toId = to["id"].get<size_t>();
auto const &toSocket = to["socket"].get<uint8_t>();
std::cerr << "from " << fromId << "@" << static_cast<int>(fromSocket) << " to " << toId << "@"
<< static_cast<int>(toSocket) << std::endl;
connect(fromId, fromSocket, toId, toSocket);
}
std::cout << __PRETTY_FUNCTION__ << '<' << std::endl;
}
Element *Package::add(string::hash_t a_hash)
{
core::Registry ®istry{ core::Registry::get() };
Element *const element{ registry.createElement(a_hash) };
assert(element);
size_t index{};
if (m_free.empty()) {
index = m_data.size();
m_data.emplace_back(element);
} else {
index = m_free.back();
assert(m_data[index] == nullptr);
m_data[index] = element;
m_free.pop_back();
}
element->m_package = this;
element->m_id = index;
if (element->hash() == logic::Clock::HASH) {
using logic::Clock;
Clock *const clock{ reinterpret_cast<Clock *const>(element) };
clock->reset(Clock::clock_t::now());
m_clocks.push_back(clock);
}
return element;
}
void Package::remove(size_t a_id)
{
assert(a_id > 0);
assert(a_id < m_data.size());
assert(std::find(std::begin(m_free), std::end(m_free), a_id) == std::end(m_free));
if (m_data[a_id]->hash() == logic::Clock::HASH) std::remove(std::begin(m_clocks), std::end(m_clocks), m_data[a_id]);
delete m_data[a_id];
m_data[a_id] = nullptr;
m_free.emplace_back(a_id);
}
Element *Package::get(size_t a_id) const
{
assert(a_id < m_data.size());
assert(std::find(std::begin(m_free), std::end(m_free), a_id) == std::end(m_free));
return m_data[a_id];
}
bool Package::connect(size_t a_sourceId, uint8_t a_outputId, size_t a_targetId, uint8_t a_inputId)
{
Element *const source{ get(a_sourceId) };
Element *const target{ get(a_targetId) };
std::cerr << "source_id: " << a_sourceId << "@" << static_cast<int>(a_outputId) << " "
<< "target_id: " << a_targetId << "@" << static_cast<int>(a_inputId) << std::endl;
if (a_sourceId != 0 && a_targetId != 0) {
std::cerr << "normal connect, element to element" << std::endl;
assert(target->m_inputs[a_inputId].type == source->m_outputs[a_outputId].type);
target->m_inputs[a_inputId].id = a_sourceId;
target->m_inputs[a_inputId].slot = a_outputId;
target->m_inputs[a_inputId].value = &source->m_outputs[a_outputId].value;
} else if (a_sourceId == 0) {
std::cerr << "package connect, package input to element input" << std::endl;
target->m_inputs[a_inputId].id = a_sourceId;
target->m_inputs[a_inputId].slot = a_outputId;
target->m_inputs[a_inputId].value = source->m_inputs[a_outputId].value;
} else if (a_targetId == 0) {
std::cerr << "package connect, element output to package output" << std::endl;
}
#if TRACE_LOGIC
std::cerr << "Notifying " << a_targetId << " (" << target->name() << ")";
std::cerr << "@" << static_cast<int32_t>(a_inputId) << " when " << a_sourceId << " (" << source->name() << ")";
std::cerr << "@" << static_cast<int32_t>(a_outputId) << " changes.." << std::endl;
#endif
m_connections.emplace_back(Connection{ a_sourceId, a_outputId, a_targetId, a_inputId });
m_callbacks[a_sourceId].insert(a_targetId);
if (target->calculate()) elementChanged(a_targetId);
return true;
}
void Package::threadFunction()
{
while (!m_quit) {
auto const now = logic::Clock::clock_t::now();
for (auto &&clock : m_clocks) {
clock->update(now);
}
if (!tryDispatch()) std::this_thread::yield();
}
}
void Package::startDispatchThread()
{
m_thread = std::thread(&Package::threadFunction, this);
}
void Package::quitDispatchThread()
{
m_quit = true;
if (m_thread.joinable()) m_thread.join();
}
bool Package::tryDispatch()
{
size_t id{};
bool const dequeued{ m_queue.try_dequeue(id) };
if (dequeued) {
#if TRACE_LOGIC
std::cerr << "Dequeued id: " << id << std::endl;
#endif
dispatch(id);
}
return dequeued;
}
void Package::dispatch(size_t a_id)
{
Element *const source{ get(a_id) };
if (source->m_callback) source->m_callback(source);
if (m_callbacks.find(a_id) == std::end(m_callbacks)) {
#if TRACE_LOGIC
std::cerr << "Callbacks list for id: " << a_id << " (" << source->name() << ")"
<< " don't exist." << std::endl;
#endif
return;
}
if (m_callbacks[a_id].empty()) {
#if TRACE_LOGIC
std::cerr << "Callbacks list for id: " << a_id << " (" << source->name() << ")"
<< " is empty." << std::endl;
#endif
return;
}
#if TRACE_LOGIC
std::cerr << "Dispatching dependencies for id: " << a_id << " (" << source->name() << ")" << std::endl;
#endif
for (auto id : m_callbacks[a_id]) {
Element *const element{ get(id) };
#if TRACE_LOGIC
std::cerr << "Recalculating id: " << id << " (" << element->name() << ")"
<< " because id: " << a_id << " (" << source->name() << ")"
<< " changed." << std::endl;
#endif
if (element->calculate()) elementChanged(id);
}
}
void Package::elementChanged(size_t a_id)
{
m_queue.enqueue(a_id);
}
void Package::open(std::string const &a_filename)
{
std::ifstream file{ a_filename };
if (!file.is_open()) return;
Json json{};
file >> json;
deserialize(json);
}
void Package::save(std::string const &a_filename)
{
Json json{};
serialize(json);
std::ofstream file{ a_filename };
file << json.dump(2);
}
} // namespace elements
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: charsetlistbox.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: kz $ $Date: 2008-03-07 11:20:11 $
*
* 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_dbaccess.hxx"
#include "charsetlistbox.hxx"
/** === begin UNO includes === **/
/** === end UNO includes === **/
#include <svtools/itemset.hxx>
#include <svtools/stritem.hxx>
//........................................................................
namespace dbaui
{
//........................................................................
/** === begin UNO using === **/
/** === end UNO using === **/
//====================================================================
//= CharSetListBox
//====================================================================
//--------------------------------------------------------------------
CharSetListBox::CharSetListBox( Window* _pParent, const ResId& _rResId )
:ListBox( _pParent, _rResId )
{
SetDropDownLineCount( 20 );
OCharsetDisplay::const_iterator charSet = m_aCharSets.begin();
while ( charSet != m_aCharSets.end() )
{
InsertEntry( (*charSet).getDisplayName() );
++charSet;
}
}
//--------------------------------------------------------------------
CharSetListBox::~CharSetListBox()
{
}
//--------------------------------------------------------------------
void CharSetListBox::SelectEntryByIanaName( const String& _rIanaName )
{
OCharsetDisplay::const_iterator aFind = m_aCharSets.findIanaName( _rIanaName );
if (aFind == m_aCharSets.end())
{
DBG_ERROR( "CharSetListBox::SelectEntryByIanaName: unknown charset falling back to system language!" );
aFind = m_aCharSets.findEncoding( RTL_TEXTENCODING_DONTKNOW );
}
if ( aFind == m_aCharSets.end() )
{
SelectEntry( String() );
}
else
{
String sDisplayName = (*aFind).getDisplayName();
if ( LISTBOX_ENTRY_NOTFOUND == GetEntryPos( sDisplayName ) )
{
// in our settings, there was an encoding selected which is not valid for the current
// data source type
// This is worth at least an assertion.
DBG_ERROR( "CharSetListBox::SelectEntryByIanaName: invalid character set!" );
sDisplayName = String();
}
SelectEntry( sDisplayName );
}
}
//--------------------------------------------------------------------
bool CharSetListBox::StoreSelectedCharSet( SfxItemSet& _rSet, const USHORT _nItemId )
{
bool bChangedSomething = false;
if ( GetSelectEntryPos() != GetSavedValue() )
{
OCharsetDisplay::const_iterator aFind = m_aCharSets.findDisplayName( GetSelectEntry() );
DBG_ASSERT( aFind != m_aCharSets.end(), "CharSetListBox::StoreSelectedCharSet: could not translate the selected character set!" );
if ( aFind != m_aCharSets.end() )
{
_rSet.Put( SfxStringItem( _nItemId, (*aFind).getIanaName() ) );
bChangedSomething = true;
}
}
return bChangedSomething;
}
//........................................................................
} // namespace dbaui
//........................................................................
<commit_msg>INTEGRATION: CWS changefileheader (1.2.14); FILE MERGED 2008/03/31 13:27:10 rt 1.2.14.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: charsetlistbox.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_dbaccess.hxx"
#include "charsetlistbox.hxx"
/** === begin UNO includes === **/
/** === end UNO includes === **/
#include <svtools/itemset.hxx>
#include <svtools/stritem.hxx>
//........................................................................
namespace dbaui
{
//........................................................................
/** === begin UNO using === **/
/** === end UNO using === **/
//====================================================================
//= CharSetListBox
//====================================================================
//--------------------------------------------------------------------
CharSetListBox::CharSetListBox( Window* _pParent, const ResId& _rResId )
:ListBox( _pParent, _rResId )
{
SetDropDownLineCount( 20 );
OCharsetDisplay::const_iterator charSet = m_aCharSets.begin();
while ( charSet != m_aCharSets.end() )
{
InsertEntry( (*charSet).getDisplayName() );
++charSet;
}
}
//--------------------------------------------------------------------
CharSetListBox::~CharSetListBox()
{
}
//--------------------------------------------------------------------
void CharSetListBox::SelectEntryByIanaName( const String& _rIanaName )
{
OCharsetDisplay::const_iterator aFind = m_aCharSets.findIanaName( _rIanaName );
if (aFind == m_aCharSets.end())
{
DBG_ERROR( "CharSetListBox::SelectEntryByIanaName: unknown charset falling back to system language!" );
aFind = m_aCharSets.findEncoding( RTL_TEXTENCODING_DONTKNOW );
}
if ( aFind == m_aCharSets.end() )
{
SelectEntry( String() );
}
else
{
String sDisplayName = (*aFind).getDisplayName();
if ( LISTBOX_ENTRY_NOTFOUND == GetEntryPos( sDisplayName ) )
{
// in our settings, there was an encoding selected which is not valid for the current
// data source type
// This is worth at least an assertion.
DBG_ERROR( "CharSetListBox::SelectEntryByIanaName: invalid character set!" );
sDisplayName = String();
}
SelectEntry( sDisplayName );
}
}
//--------------------------------------------------------------------
bool CharSetListBox::StoreSelectedCharSet( SfxItemSet& _rSet, const USHORT _nItemId )
{
bool bChangedSomething = false;
if ( GetSelectEntryPos() != GetSavedValue() )
{
OCharsetDisplay::const_iterator aFind = m_aCharSets.findDisplayName( GetSelectEntry() );
DBG_ASSERT( aFind != m_aCharSets.end(), "CharSetListBox::StoreSelectedCharSet: could not translate the selected character set!" );
if ( aFind != m_aCharSets.end() )
{
_rSet.Put( SfxStringItem( _nItemId, (*aFind).getIanaName() ) );
bChangedSomething = true;
}
}
return bChangedSomething;
}
//........................................................................
} // namespace dbaui
//........................................................................
<|endoftext|> |
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 "compiler/rewriter/rules/ruleset.h"
#include "compiler/expression/expr.h"
#include "compiler/rewriter/tools/expr_tools.h"
#include "indexing/value_index.h"
namespace zorba {
static store::Item* getIndexName(expr *e)
{
// The following two checks are required if we run after
// normalization. It does not hurt, otherwise -- so leave it
// here.
if (e->get_expr_kind() == promote_expr_kind)
{
e = static_cast<promote_expr *>(e)->get_input();
}
if (is_data(e))
{
e = get_fo_arg(e, 0);
}
if (e->get_expr_kind() == const_expr_kind)
{
return static_cast<const_expr*>(e)->get_val().getp();
}
return NULL;
}
RULE_REWRITE_PRE(ExpandBuildIndex)
{
if (node->get_expr_kind() != fo_expr_kind)
return NULL;
fo_expr* fo = static_cast<fo_expr *>(&*node);
if (fo->get_func() != LOOKUP_RESOLVED_FN(ZORBA_OPEXTENSIONS_NS, "build-index", 1))
return NULL;
short sctxid = fo->get_cur_sctx();
static_context* sctx = rCtx.getStaticContext(fo);
//
// Get index qname
//
store::Item* qnameStringItem = getIndexName((*fo)[0].getp());
ZORBA_ASSERT(qnameStringItem != NULL);
store::Item_t qnameItem =
sctx->lookup_var_qname(qnameStringItem->getStringValue()->c_str(), fo->get_loc());
//
// Get ValueIndex obj from static ctx.
//
ValueIndex* vi = sctx->lookup_index(qnameItem);
ZORBA_ASSERT(vi != NULL);
std::vector<expr_t> se_args;
//
// create index-session-opener(uri) expr
//
expr_t openQnameExpr(new const_expr(sctxid, fo->get_loc(), qnameItem));
expr_t open_index(new fo_expr(sctxid,
fo->get_loc(),
LOOKUP_OP1("index-session-opener"),
openQnameExpr));
se_args.push_back(open_index);
//
// Create FOR clause:
// for $$dot at $$pos in domain_expr
//
expr::substitution_t subst;
flwor_expr::clause_list_t clauses;
var_expr_t dot = vi->getDomainVariable();
var_expr_t pos = vi->getDomainPositionVariable();
expr_t newdom = vi->getDomainExpression()->clone(subst);
var_expr_t newdot = new var_expr(dot->get_cur_sctx(),
dot->get_loc(),
dot->get_kind(),
dot->get_varname());
var_expr_t newpos = new var_expr(pos->get_cur_sctx(),
pos->get_loc(),
pos->get_kind(),
pos->get_varname());
subst[dot] = newdot;
subst[pos] = newpos;
for_clause* fc = new for_clause(dot->get_cur_sctx(),
dot->get_loc(),
newdot,
newdom,
newpos);
newdot->set_flwor_clause(fc);
newpos->set_flwor_clause(fc);
clauses.push_back(fc);
//
// Create RETURN clause:
// return index-builder(qname, $$dot, field1_expr, ..., fieldN_expr)
//
std::vector<expr_t> index_builder_args;
expr_t buildQnameExpr(new const_expr(sctxid, fo->get_loc(), qnameItem));
index_builder_args.push_back(buildQnameExpr);
expr_t domainVarExpr(new wrapper_expr(sctxid, fo->get_loc(), newdot.getp()));
index_builder_args.push_back(domainVarExpr);
const std::vector<expr_t>& idx_fields(vi->getKeyExpressions());
int n = idx_fields.size();
for(int i = 0; i < n; ++i)
{
index_builder_args.push_back(idx_fields[i]->clone(subst));
}
expr_t ret_expr(new fo_expr(sctxid,
fo->get_loc(),
LOOKUP_OPN("index-builder"),
index_builder_args));
//
// Create flwor_expr with the above FOR and RETURN clauses.
//
rchandle<flwor_expr> flwor = new flwor_expr(sctxid, fo->get_loc(), false);
flwor->set_return_expr(ret_expr);
for (unsigned i = 0; i < clauses.size(); ++i)
{
flwor->add_clause(clauses[i]);
}
se_args.push_back(flwor.getp());
//
// Create index-session-closer(uri) expr.
//
expr_t closeQnameExpr(new const_expr(sctxid, fo->get_loc(), qnameItem));
expr_t close_index(new fo_expr(sctxid, fo->get_loc(),
LOOKUP_OP1("index-session-closer"),
closeQnameExpr));
se_args.push_back(close_index);
//
// Create sequential_expr:
//
// index-session-opener(uri);
//
// for $$dot at $$pos in domain_expr
// return index-builder(uri, $$dot, field1_expr, ..., fieldN_expr);
//
// index-session-closer(uri);
//
expr_t se = new sequential_expr(sctxid, fo->get_loc(), se_args);
return se;
}
RULE_REWRITE_POST(ExpandBuildIndex)
{
return NULL;
}
}
/* vim:set ts=2 sw=2: */
<commit_msg>builtin function lookup done based on function enum id<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2016-2017 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "test/test_syscoin_services.h"
#include "utiltime.h"
#include "util.h"
#include "rpc/server.h"
#include "alias.h"
#include "cert.h"
#include "asset.h"
#include "base58.h"
#include "chainparams.h"
#include <boost/test/unit_test.hpp>
#include <boost/lexical_cast.hpp>
#include <iterator>
#include <chrono>
#include "ranges.h"
using namespace boost::chrono;
using namespace std;
BOOST_GLOBAL_FIXTURE( SyscoinTestingSetup );
BOOST_FIXTURE_TEST_SUITE(syscoin_asset_allocation_tests, BasicSyscoinTestingSetup)
BOOST_AUTO_TEST_CASE(generate_asset_allocation_send)
{
UniValue r;
printf("Running generate_asset_allocation_send...\n");
GenerateBlocks(5);
AliasNew("node1", "jagassetallocationsend1", "data");
AliasNew("node2", "jagassetallocationsend2", "data");
string guid = AssetNew("node1", "usd", "jagassetallocationsend1", "data", "8", "false", "1", "-1");
AssetSend("node1", guid, "\"[{\\\"aliasto\\\":\\\"jagassetallocationsend1\\\",\\\"amount\\\":1}]\"", "assetallocationsend");
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " jagassetallocationsend1 false"));
UniValue balance = find_value(r.get_obj(), "balance");
BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8, false), 1 * COIN);
string txid0 = AssetAllocationTransfer(false, "node1", guid, "jagassetallocationsend1", "\"[{\\\"aliasto\\\":\\\"jagassetallocationsend2\\\",\\\"amount\\\":0.11}]\"", "allocationsendmemo");
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " jagassetallocationsend2 false"));
balance = find_value(r.get_obj(), "balance");
BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8, false),0.11 * COIN);
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid0));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND);
// send using zdag
string txid1 = AssetAllocationTransfer(true, "node1", guid, "jagassetallocationsend1", "\"[{\\\"aliasto\\\":\\\"jagassetallocationsend2\\\",\\\"amount\\\":0.12}]\"", "allocationsendmemo");
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " jagassetallocationsend2 false"));
balance = find_value(r.get_obj(), "balance");
BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8, false), 0.23 * COIN);
// non zdag cannot be found since it was already mined, but ends up briefly in conflict state because sender is conflicted
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid0));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK);
// first tx should have to wait 1 sec for good status
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid1));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK);
// check just sender
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 ''"));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK);
// wait for 1 second as required by unit test
MilliSleep(1000);
// second send
string txid2 = AssetAllocationTransfer(true, "node1", guid, "jagassetallocationsend1", "\"[{\\\"aliasto\\\":\\\"jagassetallocationsend2\\\",\\\"amount\\\":0.13}]\"", "allocationsendmemo");
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " jagassetallocationsend2 false"));
balance = find_value(r.get_obj(), "balance");
BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8, false), 0.36 * COIN);
// sender is conflicted so txid0 is conflicted by extension even if its not found
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid0));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK);
// first ones now OK because it was found explicitely
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid1));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK);
// second one hasn't waited enough time yet
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid2));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK);
// check just sender
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 ''"));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK);
// wait for 1.5 second to clear minor warning status
MilliSleep(1500);
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid0));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND);
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid1));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK);
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid2));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK);
// check just sender as well
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 ''"));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK);
// after pow, should get not found on all of them
GenerateBlocks(1);
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid0));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND);
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid1));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND);
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid2));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND);
// check just sender as well
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 ''"));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND);
}
BOOST_AUTO_TEST_CASE(generate_asset_allocation_througput)
{
UniValue r;
printf("Running generate_asset_allocation_througputlkoi...\n");
GenerateBlocks(5);
vector<string> assetVec;
// create 1000 aliases and assets for each asset
for (int i = 0; i < 1000; i++) {
string aliasname = "jagthroughput-" + boost::lexical_cast<string>(i);
string aliasnameto = "jagthroughput3-" + boost::lexical_cast<string>(i);
AliasNew("node1",aliasname, "data");
AliasNew("node3", aliasnameto, "data");
string guid = AssetNew("node1", "usd", aliasname, "data", "8", "false", "1", "-1");
assetVec.push_back(guid);
}
vector<string> assetSendTxVec;
for (auto& guid : assetVec) {
string hex_str = AssetSend("node1", guid, "\"[{\\\"aliasto\\\":\\\"" + aliasnameto "\\\",\\\"amount\\\":1}]\"", "assetallocationsend", "''", false);
assetSendTxVec.push_back(hex_str);
}
map<string, int64_t> sendTimes;
for (auto& hex_str : assetSendTxVec) {
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "syscoinsendrawtransaction " + hex_str));
string txid = find_value(r.get_obj(), "txid").get_str();
sendTimes[txid] = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
}
float totalTime = 0;
// wait 10 seconds
MilliSleep(10000);
BOOST_CHECK_NO_THROW(r = CallRPC("node3", "tpstestinfo"));
UniValue tpsresponse = r.get_array();
for (int i = 0; i < tpsresponse.size();i++) {
UniValue responesObj = tpsresponse[i].get_obj();
string txid = find_value(responesObj, "txid").get_str();
int64_t timeRecv = find_value(responesObj, "time").get_int64();
if (sendTimes.find(txid) == sendTimes.end())
continue;
totalTime += timeRecv - sendTimes[txid];
}
totalTime /= tpsresponse.size();
printf("totalTime %.2f, num responses %d\n", totalTime, tpsresponse.size());
}
BOOST_AUTO_TEST_SUITE_END ()
<commit_msg>compile<commit_after>// Copyright (c) 2016-2017 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "test/test_syscoin_services.h"
#include "utiltime.h"
#include "util.h"
#include "rpc/server.h"
#include "alias.h"
#include "cert.h"
#include "asset.h"
#include "base58.h"
#include "chainparams.h"
#include <boost/test/unit_test.hpp>
#include <boost/lexical_cast.hpp>
#include <iterator>
#include <chrono>
#include "ranges.h"
using namespace boost::chrono;
using namespace std;
BOOST_GLOBAL_FIXTURE( SyscoinTestingSetup );
BOOST_FIXTURE_TEST_SUITE(syscoin_asset_allocation_tests, BasicSyscoinTestingSetup)
BOOST_AUTO_TEST_CASE(generate_asset_allocation_send)
{
UniValue r;
printf("Running generate_asset_allocation_send...\n");
GenerateBlocks(5);
AliasNew("node1", "jagassetallocationsend1", "data");
AliasNew("node2", "jagassetallocationsend2", "data");
string guid = AssetNew("node1", "usd", "jagassetallocationsend1", "data", "8", "false", "1", "-1");
AssetSend("node1", guid, "\"[{\\\"aliasto\\\":\\\"jagassetallocationsend1\\\",\\\"amount\\\":1}]\"", "assetallocationsend");
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " jagassetallocationsend1 false"));
UniValue balance = find_value(r.get_obj(), "balance");
BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8, false), 1 * COIN);
string txid0 = AssetAllocationTransfer(false, "node1", guid, "jagassetallocationsend1", "\"[{\\\"aliasto\\\":\\\"jagassetallocationsend2\\\",\\\"amount\\\":0.11}]\"", "allocationsendmemo");
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " jagassetallocationsend2 false"));
balance = find_value(r.get_obj(), "balance");
BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8, false),0.11 * COIN);
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid0));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND);
// send using zdag
string txid1 = AssetAllocationTransfer(true, "node1", guid, "jagassetallocationsend1", "\"[{\\\"aliasto\\\":\\\"jagassetallocationsend2\\\",\\\"amount\\\":0.12}]\"", "allocationsendmemo");
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " jagassetallocationsend2 false"));
balance = find_value(r.get_obj(), "balance");
BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8, false), 0.23 * COIN);
// non zdag cannot be found since it was already mined, but ends up briefly in conflict state because sender is conflicted
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid0));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK);
// first tx should have to wait 1 sec for good status
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid1));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK);
// check just sender
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 ''"));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK);
// wait for 1 second as required by unit test
MilliSleep(1000);
// second send
string txid2 = AssetAllocationTransfer(true, "node1", guid, "jagassetallocationsend1", "\"[{\\\"aliasto\\\":\\\"jagassetallocationsend2\\\",\\\"amount\\\":0.13}]\"", "allocationsendmemo");
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " jagassetallocationsend2 false"));
balance = find_value(r.get_obj(), "balance");
BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8, false), 0.36 * COIN);
// sender is conflicted so txid0 is conflicted by extension even if its not found
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid0));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK);
// first ones now OK because it was found explicitely
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid1));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK);
// second one hasn't waited enough time yet
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid2));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK);
// check just sender
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 ''"));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK);
// wait for 1.5 second to clear minor warning status
MilliSleep(1500);
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid0));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND);
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid1));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK);
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid2));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK);
// check just sender as well
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 ''"));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK);
// after pow, should get not found on all of them
GenerateBlocks(1);
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid0));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND);
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid1));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND);
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid2));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND);
// check just sender as well
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 ''"));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND);
}
BOOST_AUTO_TEST_CASE(generate_asset_allocation_througput)
{
UniValue r;
printf("Running generate_asset_allocation_througputlkoi...\n");
GenerateBlocks(5);
map<string, string> assetMap;
// create 1000 aliases and assets for each asset
for (int i = 0; i < 1000; i++) {
string aliasname = "jagthroughput-" + boost::lexical_cast<string>(i);
string aliasnameto = "jagthroughput3-" + boost::lexical_cast<string>(i);
AliasNew("node1",aliasname, "data");
AliasNew("node3", aliasnameto, "data");
string guid = AssetNew("node1", "usd", aliasname, "data", "8", "false", "1", "-1");
assetMap[guid] = aliasnameto;
}
vector<string> assetSendTxVec;
for (auto& assetTuple : assetMap) {
string hex_str = AssetSend("node1", assetTuple.first, "\"[{\\\"aliasto\\\":\\\"" + assetTuple.second "\\\",\\\"amount\\\":1}]\"", "assetallocationsend", "''", false);
assetSendTxVec.push_back(hex_str);
}
map<string, int64_t> sendTimes;
for (auto& hex_str : assetSendTxVec) {
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "syscoinsendrawtransaction " + hex_str));
string txid = find_value(r.get_obj(), "txid").get_str();
sendTimes[txid] = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
}
float totalTime = 0;
// wait 10 seconds
MilliSleep(10000);
BOOST_CHECK_NO_THROW(r = CallRPC("node3", "tpstestinfo"));
UniValue tpsresponse = r.get_array();
for (int i = 0; i < tpsresponse.size();i++) {
UniValue responesObj = tpsresponse[i].get_obj();
string txid = find_value(responesObj, "txid").get_str();
int64_t timeRecv = find_value(responesObj, "time").get_int64();
if (sendTimes.find(txid) == sendTimes.end())
continue;
totalTime += timeRecv - sendTimes[txid];
}
totalTime /= tpsresponse.size();
printf("totalTime %.2f, num responses %d\n", totalTime, tpsresponse.size());
}
BOOST_AUTO_TEST_SUITE_END ()
<|endoftext|> |
<commit_before><commit_msg>WaE: unused variable 'aReferenceString' [loplugin]<commit_after><|endoftext|> |
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved.
#include "concurrency/fifo_enforcer.hpp"
#include "arch/runtime/coroutines.hpp"
#include "concurrency/cond_var.hpp"
#include "concurrency/wait_any.hpp"
void fifo_enforcer_state_t::advance_by_read(DEBUG_VAR fifo_enforcer_read_token_t token) THROWS_NOTHING {
rassert(timestamp == token.timestamp);
num_reads++;
}
void fifo_enforcer_state_t::advance_by_write(fifo_enforcer_write_token_t token) THROWS_NOTHING {
rassert(timestamp == token.timestamp.timestamp_before());
rassert(num_reads == token.num_preceding_reads);
timestamp = token.timestamp.timestamp_after();
num_reads = 0;
}
fifo_enforcer_read_token_t fifo_enforcer_source_t::enter_read() THROWS_NOTHING {
assert_thread();
mutex_assertion_t::acq_t freeze(&lock);
state.num_reads++;
return fifo_enforcer_read_token_t(state.timestamp);
}
fifo_enforcer_write_token_t fifo_enforcer_source_t::enter_write() THROWS_NOTHING {
assert_thread();
mutex_assertion_t::acq_t freeze(&lock);
fifo_enforcer_write_token_t token(transition_timestamp_t::starting_from(state.timestamp), state.num_reads);
state.timestamp = token.timestamp.timestamp_after();
state.num_reads = 0;
return token;
}
fifo_enforcer_sink_t::exit_read_t::exit_read_t() THROWS_NOTHING :
parent(NULL), ended(false) { }
fifo_enforcer_sink_t::exit_read_t::exit_read_t(fifo_enforcer_sink_t *p, fifo_enforcer_read_token_t t) THROWS_NOTHING :
parent(NULL), ended(false)
{
begin(p, t);
}
void fifo_enforcer_sink_t::exit_read_t::begin(fifo_enforcer_sink_t *p, fifo_enforcer_read_token_t t) THROWS_NOTHING {
rassert(parent == NULL);
rassert(p != NULL);
parent = p;
token = t;
parent->assert_thread();
mutex_assertion_t::acq_t acq(&parent->internal_lock);
parent->internal_read_queue.push(this);
parent->internal_pump();
}
void fifo_enforcer_sink_t::exit_read_t::end() THROWS_NOTHING {
rassert(parent && !ended);
parent->assert_thread();
mutex_assertion_t::acq_t acq(&parent->internal_lock);
if (is_pulsed()) {
parent->internal_finish_a_reader(token);
} else {
/* Swap us out for a dummy. The dummy is heap-allocated and it will
delete itself when it's done. */
class dummy_exit_read_t : public internal_exit_read_t {
public:
dummy_exit_read_t(fifo_enforcer_read_token_t t, fifo_enforcer_sink_t *s) :
token(t), sink(s) { }
fifo_enforcer_read_token_t get_token() const {
return token;
}
void on_reached_head_of_queue() {
sink->internal_read_queue.remove(this);
sink->internal_finish_a_reader(token);
delete this;
}
void on_early_shutdown() {
delete this;
}
fifo_enforcer_read_token_t token;
fifo_enforcer_sink_t *sink;
};
parent->internal_read_queue.swap_in_place(this,
new dummy_exit_read_t(token, parent));
}
ended = true;
}
fifo_enforcer_sink_t::exit_read_t::~exit_read_t() THROWS_NOTHING {
if (parent && !ended) {
end();
}
}
fifo_enforcer_sink_t::exit_write_t::exit_write_t() THROWS_NOTHING :
parent(NULL), ended(false) { }
fifo_enforcer_sink_t::exit_write_t::exit_write_t(fifo_enforcer_sink_t *p, fifo_enforcer_write_token_t t) THROWS_NOTHING :
parent(NULL), ended(false)
{
begin(p, t);
}
void fifo_enforcer_sink_t::exit_write_t::begin(fifo_enforcer_sink_t *p, fifo_enforcer_write_token_t t) THROWS_NOTHING {
ASSERT_FINITE_CORO_WAITING;
rassert(parent == NULL);
rassert(p != NULL);
parent = p;
token = t;
parent->assert_thread();
mutex_assertion_t::acq_t acq(&parent->internal_lock);
parent->internal_write_queue.push(this);
parent->internal_pump();
}
void fifo_enforcer_sink_t::exit_write_t::end() THROWS_NOTHING {
rassert(parent && !ended);
mutex_assertion_t::acq_t acq(&parent->internal_lock);
if (is_pulsed()) {
parent->internal_finish_a_writer(token);
} else {
// KSI: Why would we need a dummy?
/* Swap us out for a dummy. */
class dummy_exit_write_t : public internal_exit_write_t {
public:
dummy_exit_write_t(fifo_enforcer_write_token_t t, fifo_enforcer_sink_t *s) :
token(t), sink(s) { }
fifo_enforcer_write_token_t get_token() const {
return token;
}
void on_reached_head_of_queue() {
// KSI: This probably calls 'delete this' later than it should.
sink->internal_write_queue.remove(this);
sink->internal_finish_a_writer(token);
delete this;
}
void on_early_shutdown() {
delete this;
}
fifo_enforcer_write_token_t token;
fifo_enforcer_sink_t *sink;
};
parent->internal_write_queue.swap_in_place(this,
new dummy_exit_write_t(token, parent));
}
ended = true;
}
fifo_enforcer_sink_t::exit_write_t::~exit_write_t() THROWS_NOTHING {
if (parent && !ended) {
end();
}
}
fifo_enforcer_sink_t::~fifo_enforcer_sink_t() THROWS_NOTHING {
while (!internal_read_queue.empty()) {
internal_exit_read_t *read = internal_read_queue.pop();
read->on_early_shutdown();
}
while (!internal_write_queue.empty()) {
internal_exit_write_t *write = internal_write_queue.pop();
write->on_early_shutdown();
}
}
void fifo_enforcer_sink_t::internal_pump() THROWS_NOTHING {
ASSERT_FINITE_CORO_WAITING;
if (in_pump) {
pump_should_keep_going = true;
} else {
in_pump = true;
do {
pump_should_keep_going = false;
while (!internal_read_queue.empty() &&
internal_read_queue.peek()->get_token().timestamp == finished_state.timestamp) {
internal_exit_read_t *read = internal_read_queue.peek();
popped_state.advance_by_read(read->get_token());
read->on_reached_head_of_queue();
}
if (!internal_write_queue.empty() &&
internal_write_queue.peek()->get_token().timestamp.timestamp_before() == finished_state.timestamp &&
internal_write_queue.peek()->get_token().num_preceding_reads == finished_state.num_reads) {
internal_exit_write_t *write = internal_write_queue.peek();
popped_state.advance_by_write(write->get_token());
write->on_reached_head_of_queue();
}
} while (pump_should_keep_going);
in_pump = false;
}
}
void fifo_enforcer_sink_t::internal_finish_a_reader(fifo_enforcer_read_token_t token) THROWS_NOTHING {
rassert(popped_state.timestamp == token.timestamp);
rassert(finished_state.num_reads <= popped_state.num_reads);
finished_state.advance_by_read(token);
internal_pump();
}
void fifo_enforcer_sink_t::internal_finish_a_writer(fifo_enforcer_write_token_t token) THROWS_NOTHING {
rassert(popped_state.timestamp == token.timestamp.timestamp_after());
rassert(popped_state.num_reads == 0);
finished_state.advance_by_write(token);
internal_pump();
}
<commit_msg>Removed fifo enforcer peanut gallery KSIs.<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved.
#include "concurrency/fifo_enforcer.hpp"
#include "arch/runtime/coroutines.hpp"
#include "concurrency/cond_var.hpp"
#include "concurrency/wait_any.hpp"
void fifo_enforcer_state_t::advance_by_read(DEBUG_VAR fifo_enforcer_read_token_t token) THROWS_NOTHING {
rassert(timestamp == token.timestamp);
num_reads++;
}
void fifo_enforcer_state_t::advance_by_write(fifo_enforcer_write_token_t token) THROWS_NOTHING {
rassert(timestamp == token.timestamp.timestamp_before());
rassert(num_reads == token.num_preceding_reads);
timestamp = token.timestamp.timestamp_after();
num_reads = 0;
}
fifo_enforcer_read_token_t fifo_enforcer_source_t::enter_read() THROWS_NOTHING {
assert_thread();
mutex_assertion_t::acq_t freeze(&lock);
state.num_reads++;
return fifo_enforcer_read_token_t(state.timestamp);
}
fifo_enforcer_write_token_t fifo_enforcer_source_t::enter_write() THROWS_NOTHING {
assert_thread();
mutex_assertion_t::acq_t freeze(&lock);
fifo_enforcer_write_token_t token(transition_timestamp_t::starting_from(state.timestamp), state.num_reads);
state.timestamp = token.timestamp.timestamp_after();
state.num_reads = 0;
return token;
}
fifo_enforcer_sink_t::exit_read_t::exit_read_t() THROWS_NOTHING :
parent(NULL), ended(false) { }
fifo_enforcer_sink_t::exit_read_t::exit_read_t(fifo_enforcer_sink_t *p, fifo_enforcer_read_token_t t) THROWS_NOTHING :
parent(NULL), ended(false)
{
begin(p, t);
}
void fifo_enforcer_sink_t::exit_read_t::begin(fifo_enforcer_sink_t *p, fifo_enforcer_read_token_t t) THROWS_NOTHING {
rassert(parent == NULL);
rassert(p != NULL);
parent = p;
token = t;
parent->assert_thread();
mutex_assertion_t::acq_t acq(&parent->internal_lock);
parent->internal_read_queue.push(this);
parent->internal_pump();
}
void fifo_enforcer_sink_t::exit_read_t::end() THROWS_NOTHING {
rassert(parent && !ended);
parent->assert_thread();
mutex_assertion_t::acq_t acq(&parent->internal_lock);
if (is_pulsed()) {
parent->internal_finish_a_reader(token);
} else {
/* Swap us out for a dummy. The dummy is heap-allocated and it will
delete itself when it's done. */
class dummy_exit_read_t : public internal_exit_read_t {
public:
dummy_exit_read_t(fifo_enforcer_read_token_t t, fifo_enforcer_sink_t *s) :
token(t), sink(s) { }
fifo_enforcer_read_token_t get_token() const {
return token;
}
void on_reached_head_of_queue() {
sink->internal_read_queue.remove(this);
sink->internal_finish_a_reader(token);
delete this;
}
void on_early_shutdown() {
delete this;
}
fifo_enforcer_read_token_t token;
fifo_enforcer_sink_t *sink;
};
parent->internal_read_queue.swap_in_place(this,
new dummy_exit_read_t(token, parent));
}
ended = true;
}
fifo_enforcer_sink_t::exit_read_t::~exit_read_t() THROWS_NOTHING {
if (parent && !ended) {
end();
}
}
fifo_enforcer_sink_t::exit_write_t::exit_write_t() THROWS_NOTHING :
parent(NULL), ended(false) { }
fifo_enforcer_sink_t::exit_write_t::exit_write_t(fifo_enforcer_sink_t *p, fifo_enforcer_write_token_t t) THROWS_NOTHING :
parent(NULL), ended(false)
{
begin(p, t);
}
void fifo_enforcer_sink_t::exit_write_t::begin(fifo_enforcer_sink_t *p, fifo_enforcer_write_token_t t) THROWS_NOTHING {
ASSERT_FINITE_CORO_WAITING;
rassert(parent == NULL);
rassert(p != NULL);
parent = p;
token = t;
parent->assert_thread();
mutex_assertion_t::acq_t acq(&parent->internal_lock);
parent->internal_write_queue.push(this);
parent->internal_pump();
}
void fifo_enforcer_sink_t::exit_write_t::end() THROWS_NOTHING {
rassert(parent && !ended);
mutex_assertion_t::acq_t acq(&parent->internal_lock);
if (is_pulsed()) {
parent->internal_finish_a_writer(token);
} else {
/* Swap us out for a dummy. */
class dummy_exit_write_t : public internal_exit_write_t {
public:
dummy_exit_write_t(fifo_enforcer_write_token_t t, fifo_enforcer_sink_t *s) :
token(t), sink(s) { }
fifo_enforcer_write_token_t get_token() const {
return token;
}
void on_reached_head_of_queue() {
sink->internal_write_queue.remove(this);
sink->internal_finish_a_writer(token);
delete this;
}
void on_early_shutdown() {
delete this;
}
fifo_enforcer_write_token_t token;
fifo_enforcer_sink_t *sink;
};
parent->internal_write_queue.swap_in_place(this,
new dummy_exit_write_t(token, parent));
}
ended = true;
}
fifo_enforcer_sink_t::exit_write_t::~exit_write_t() THROWS_NOTHING {
if (parent && !ended) {
end();
}
}
fifo_enforcer_sink_t::~fifo_enforcer_sink_t() THROWS_NOTHING {
while (!internal_read_queue.empty()) {
internal_exit_read_t *read = internal_read_queue.pop();
read->on_early_shutdown();
}
while (!internal_write_queue.empty()) {
internal_exit_write_t *write = internal_write_queue.pop();
write->on_early_shutdown();
}
}
void fifo_enforcer_sink_t::internal_pump() THROWS_NOTHING {
ASSERT_FINITE_CORO_WAITING;
if (in_pump) {
pump_should_keep_going = true;
} else {
in_pump = true;
do {
pump_should_keep_going = false;
while (!internal_read_queue.empty() &&
internal_read_queue.peek()->get_token().timestamp == finished_state.timestamp) {
internal_exit_read_t *read = internal_read_queue.peek();
popped_state.advance_by_read(read->get_token());
read->on_reached_head_of_queue();
}
if (!internal_write_queue.empty() &&
internal_write_queue.peek()->get_token().timestamp.timestamp_before() == finished_state.timestamp &&
internal_write_queue.peek()->get_token().num_preceding_reads == finished_state.num_reads) {
internal_exit_write_t *write = internal_write_queue.peek();
popped_state.advance_by_write(write->get_token());
write->on_reached_head_of_queue();
}
} while (pump_should_keep_going);
in_pump = false;
}
}
void fifo_enforcer_sink_t::internal_finish_a_reader(fifo_enforcer_read_token_t token) THROWS_NOTHING {
rassert(popped_state.timestamp == token.timestamp);
rassert(finished_state.num_reads <= popped_state.num_reads);
finished_state.advance_by_read(token);
internal_pump();
}
void fifo_enforcer_sink_t::internal_finish_a_writer(fifo_enforcer_write_token_t token) THROWS_NOTHING {
rassert(popped_state.timestamp == token.timestamp.timestamp_after());
rassert(popped_state.num_reads == 0);
finished_state.advance_by_write(token);
internal_pump();
}
<|endoftext|> |
<commit_before>
/*******************************************************************************
* Copyright (C) 2016 Advanced Micro Devices, Inc. All rights reserved.
******************************************************************************/
#include <unistd.h>
#include <gtest/gtest.h>
#include <math.h>
#include <stdexcept>
#include <vector>
#include "rocfft.h"
#include "test_constants.h"
#include "rocfft_against_fftw.h"
#include "fftw_transform.h"
using ::testing::TestWithParam;
using ::testing::Values;
using ::testing::ValuesIn;
using ::testing::Combine;
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
class accuracy_test_pow2_single : public ::testing::Test {
protected:
accuracy_test_pow2_single(){}
virtual ~accuracy_test_pow2_single(){}
virtual void SetUp(){}
virtual void TearDown(){
}
};
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
class accuracy_test_pow2_double : public ::testing::Test {
protected:
accuracy_test_pow2_double(){}
virtual ~accuracy_test_pow2_double(){}
virtual void SetUp(){}
virtual void TearDown(){
}
};
//65536=pow(2,16) //8388608 = pow(2,23)
#define POW2_RANGE 2, 4, 8, 16, 32, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432
#define POW3_RANGE 3, 9, 27, 81, 243, 729, 2187
#define POW5_RANGE 5, 25, 125, 625, 3125
#define MIX_RANGE 6, 10, 12, 15, 20, 30, 120, 150, 225, 240, 300, 486, 600, 900, 1250, 1500, 1875, 2160, 2187, 2250, 2500, 3000, 4000
size_t pow2_range[] = { POW2_RANGE };
size_t pow3_range[] = { POW3_RANGE };
size_t pow5_range[] = { POW5_RANGE };
size_t mix_range[] = { MIX_RANGE };
static size_t batch_range[] = {1};
static size_t stride_range[] = {1};
rocfft_result_placement placeness_range[] = {rocfft_placement_notinplace, rocfft_placement_inplace};
rocfft_transform_type transform_range[] = {rocfft_transform_type_complex_forward, rocfft_transform_type_complex_inverse};
namespace powerX
{
class accuracy_test: public :: TestWithParam < std::tuple<size_t, size_t, rocfft_result_placement, rocfft_transform_type, size_t > >
{
protected:
accuracy_test(){}
virtual ~accuracy_test(){}
virtual void SetUp(){}
virtual void TearDown(){}
};
template< class T, class fftw_T >
void normal_1D_complex_interleaved_to_complex_interleaved(size_t N, size_t batch, rocfft_result_placement placeness, rocfft_transform_type transform_type, size_t stride)
{
std::vector<size_t> lengths;
lengths.push_back( N );
std::vector<size_t> input_strides;
std::vector<size_t> output_strides;
input_strides.push_back(stride);
output_strides.push_back(stride);
size_t input_distance = 0;
size_t output_distance = 0;
rocfft_array_type in_array_type = rocfft_array_type_complex_interleaved;
rocfft_array_type out_array_type = rocfft_array_type_complex_interleaved;
data_pattern pattern = sawtooth;
complex_to_complex<T, fftw_T>( pattern, transform_type, lengths, batch, input_strides, output_strides, input_distance, output_distance, in_array_type, out_array_type, placeness );
usleep(1e4);
}
// *****************************************************
// Complex to Complex
// *****************************************************
TEST_P(accuracy_test, normal_1D_complex_interleaved_to_complex_interleaved_single_precision)
{
size_t N = std::get<0>(GetParam());
size_t batch = std::get<1>(GetParam());
rocfft_result_placement placeness = std::get<2>(GetParam());
rocfft_transform_type transform_type = std::get<3>(GetParam());
size_t stride = std::get<4>(GetParam());
try { normal_1D_complex_interleaved_to_complex_interleaved< float, fftwf_complex >(N, batch, placeness, transform_type, stride); }
catch( const std::exception& err ) { handle_exception(err); }
}
TEST_P(accuracy_test, normal_1D_complex_interleaved_to_complex_interleaved_double_precision)
{
size_t N = std::get<0>(GetParam());
size_t batch = std::get<1>(GetParam());
rocfft_result_placement placeness = std::get<2>(GetParam());
rocfft_transform_type transform_type = std::get<3>(GetParam());
size_t stride = std::get<4>(GetParam());
try { normal_1D_complex_interleaved_to_complex_interleaved< double, fftw_complex >(N, batch, placeness, transform_type, stride); }
catch( const std::exception& err ) { handle_exception(err); }
}
// *****************************************************
// Real to Complex
// *****************************************************
template< class T, class fftw_T >
void normal_1D_real_interleaved_to_hermitian_interleaved(size_t N, size_t batch, rocfft_result_placement placeness, rocfft_transform_type transform_type, size_t stride)
{
std::vector<size_t> lengths;
lengths.push_back( N );
std::vector<size_t> input_strides;
std::vector<size_t> output_strides;
input_strides.push_back(stride);
output_strides.push_back(stride);
size_t input_distance = 0;
size_t output_distance = 0;
rocfft_array_type in_array_type = rocfft_array_type_real;
rocfft_array_type out_array_type = rocfft_array_type_hermitian_interleaved;
data_pattern pattern = sawtooth;
real_to_complex<T, fftw_T>( pattern, transform_type, lengths, batch, input_strides, output_strides, input_distance, output_distance, in_array_type, out_array_type, rocfft_placement_notinplace );//must be non-inplace tranform
}
TEST_P(accuracy_test, normal_1D_real_interleaved_to_hermitian_interleaved_single_precision)
{
size_t N = std::get<0>(GetParam());
size_t batch = std::get<1>(GetParam());
rocfft_result_placement placeness = rocfft_placement_notinplace;//must be non-inplace
rocfft_transform_type transform_type = rocfft_transform_type_real_forward;// must be real forward
size_t stride = std::get<4>(GetParam());
try { normal_1D_real_interleaved_to_hermitian_interleaved< float, fftwf_complex >(N, batch, placeness, transform_type, stride); }
catch( const std::exception& err ) { handle_exception(err); }
}
// *****************************************************
// *****************************************************
//Values is for a single item; ValuesIn is for an array
//ValuesIn take each element (a vector) and combine them and feed them to test_p
INSTANTIATE_TEST_CASE_P(rocfft_pow2,
accuracy_test,
Combine(
ValuesIn(pow2_range), ValuesIn(batch_range), ValuesIn(placeness_range), ValuesIn(transform_range), ValuesIn(stride_range)
)
);
INSTANTIATE_TEST_CASE_P(rocfft_pow3,
accuracy_test,
Combine(
ValuesIn(pow3_range), ValuesIn(batch_range), ValuesIn(placeness_range), ValuesIn(transform_range), ValuesIn(stride_range)
)
);
INSTANTIATE_TEST_CASE_P(rocfft_pow5,
accuracy_test,
Combine(
ValuesIn(pow5_range), ValuesIn(batch_range), ValuesIn(placeness_range), ValuesIn(transform_range), ValuesIn(stride_range)
)
);
INSTANTIATE_TEST_CASE_P(rocfft_pow_mix,
accuracy_test,
Combine(
ValuesIn(mix_range), ValuesIn(batch_range), ValuesIn(placeness_range), ValuesIn(transform_range), ValuesIn(stride_range)
)
);
// *****************************************************
// *****************************************************
//TESTS disabled by default since they take a long time to execute
//TO enable this tests
//1. make sure ENV CLFFT_REQUEST_LIB_NOMEMALLOC=1
//2. pass --gtest_also_run_disabled_tests to TEST.exe
#define CLFFT_TEST_HUGE
#ifdef CLFFT_TEST_HUGE
#define HUGE_TEST_MAKE(test_name, len, bat) \
template< class T, class fftw_T > \
void test_name() \
{ \
std::vector<size_t> lengths; \
lengths.push_back( len ); \
size_t batch = bat; \
\
std::vector<size_t> input_strides; \
std::vector<size_t> output_strides; \
size_t input_distance = 0; \
size_t output_distance = 0; \
rocfft_array_type in_array_type = rocfft_array_type_complex_planar; \
rocfft_array_type out_array_type = rocfft_array_type_complex_planar; \
rocfft_result_placement placeness = rocfft_placement_inplace; \
rocfft_transform_type transform_type = rocfft_transform_type_complex_forward; \
\
data_pattern pattern = sawtooth; \
complex_to_complex<T, fftw_T>( pattern, transform_type, lengths, batch, input_strides, output_strides, input_distance, output_distance, in_array_type, out_array_type, placeness ); \
}
#define SP_HUGE_TEST(test_name, len, bat) \
\
HUGE_TEST_MAKE(test_name, len, bat) \
\
TEST_F(accuracy_test_pow2_single, test_name) \
{ \
try { test_name< float, fftwf_complex >(); } \
catch( const std::exception& err ) { handle_exception(err); } \
}
#define DP_HUGE_TEST(test_name, len, bat) \
\
HUGE_TEST_MAKE(test_name, len, bat) \
\
TEST_F(accuracy_test_pow2_double, test_name) \
{ \
try { test_name< double, fftw_complex >(); } \
catch( const std::exception& err ) { handle_exception(err); } \
}
SP_HUGE_TEST( DISABLED_huge_sp_test_1, 1048576, 11 )
SP_HUGE_TEST( DISABLED_huge_sp_test_2, 1048576*2, 7 )
SP_HUGE_TEST( DISABLED_huge_sp_test_3, 1048576*4, 3 )
SP_HUGE_TEST( DISABLED_huge_sp_test_4, 1048576*8, 5 )
SP_HUGE_TEST( DISABLED_huge_sp_test_5, 1048576*16, 3 )
SP_HUGE_TEST( DISABLED_huge_sp_test_6, 1048576*32, 2 )
SP_HUGE_TEST( DISABLED_huge_sp_test_7, 1048576*64, 1 )
DP_HUGE_TEST( DISABLED_huge_dp_test_1, 524288, 11 )
DP_HUGE_TEST( DISABLED_huge_dp_test_2, 524288*2, 7 )
DP_HUGE_TEST( DISABLED_huge_dp_test_3, 524288*4, 3 )
DP_HUGE_TEST( DISABLED_huge_dp_test_4, 524288*8, 5 )
DP_HUGE_TEST( DISABLED_huge_dp_test_5, 524288*16, 3 )
DP_HUGE_TEST( DISABLED_huge_dp_test_6, 524288*32, 2 )
DP_HUGE_TEST( DISABLED_huge_dp_test_7, 524288*64, 1 )
SP_HUGE_TEST( DISABLED_large_sp_test_1, 8192, 11 )
SP_HUGE_TEST( DISABLED_large_sp_test_2, 8192*2, 7 )
SP_HUGE_TEST( DISABLED_large_sp_test_3, 8192*4, 3 )
SP_HUGE_TEST( DISABLED_large_sp_test_4, 8192*8, 5 )
SP_HUGE_TEST( DISABLED_large_sp_test_5, 8192*16, 3 )
SP_HUGE_TEST( DISABLED_large_sp_test_6, 8192*32, 21 )
SP_HUGE_TEST( DISABLED_large_sp_test_7, 8192*64, 17 )
DP_HUGE_TEST( DISABLED_large_dp_test_1, 4096, 11 )
DP_HUGE_TEST( DISABLED_large_dp_test_2, 4096*2, 7 )
DP_HUGE_TEST( DISABLED_large_dp_test_3, 4096*4, 3 )
DP_HUGE_TEST( DISABLED_large_dp_test_4, 4096*8, 5 )
DP_HUGE_TEST( DISABLED_large_dp_test_5, 4096*16, 3 )
DP_HUGE_TEST( DISABLED_large_dp_test_6, 4096*32, 21 )
DP_HUGE_TEST( DISABLED_large_dp_test_7, 4096*64, 17 )
#endif
} //namespace
<commit_msg>comment out hermitian test which does not have implementation now<commit_after>
/*******************************************************************************
* Copyright (C) 2016 Advanced Micro Devices, Inc. All rights reserved.
******************************************************************************/
#include <unistd.h>
#include <gtest/gtest.h>
#include <math.h>
#include <stdexcept>
#include <vector>
#include "rocfft.h"
#include "test_constants.h"
#include "rocfft_against_fftw.h"
#include "fftw_transform.h"
using ::testing::TestWithParam;
using ::testing::Values;
using ::testing::ValuesIn;
using ::testing::Combine;
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
class accuracy_test_pow2_single : public ::testing::Test {
protected:
accuracy_test_pow2_single(){}
virtual ~accuracy_test_pow2_single(){}
virtual void SetUp(){}
virtual void TearDown(){
}
};
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
class accuracy_test_pow2_double : public ::testing::Test {
protected:
accuracy_test_pow2_double(){}
virtual ~accuracy_test_pow2_double(){}
virtual void SetUp(){}
virtual void TearDown(){
}
};
//65536=pow(2,16) //8388608 = pow(2,23)
#define POW2_RANGE 2, 4, 8, 16, 32, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432
#define POW3_RANGE 3, 9, 27, 81, 243, 729, 2187
#define POW5_RANGE 5, 25, 125, 625, 3125
#define MIX_RANGE 6, 10, 12, 15, 20, 30, 120, 150, 225, 240, 300, 486, 600, 900, 1250, 1500, 1875, 2160, 2187, 2250, 2500, 3000, 4000
size_t pow2_range[] = { POW2_RANGE };
size_t pow3_range[] = { POW3_RANGE };
size_t pow5_range[] = { POW5_RANGE };
size_t mix_range[] = { MIX_RANGE };
static size_t batch_range[] = {1};
static size_t stride_range[] = {1};
rocfft_result_placement placeness_range[] = {rocfft_placement_notinplace, rocfft_placement_inplace};
rocfft_transform_type transform_range[] = {rocfft_transform_type_complex_forward, rocfft_transform_type_complex_inverse};
namespace powerX
{
class accuracy_test: public :: TestWithParam < std::tuple<size_t, size_t, rocfft_result_placement, rocfft_transform_type, size_t > >
{
protected:
accuracy_test(){}
virtual ~accuracy_test(){}
virtual void SetUp(){}
virtual void TearDown(){}
};
template< class T, class fftw_T >
void normal_1D_complex_interleaved_to_complex_interleaved(size_t N, size_t batch, rocfft_result_placement placeness, rocfft_transform_type transform_type, size_t stride)
{
std::vector<size_t> lengths;
lengths.push_back( N );
std::vector<size_t> input_strides;
std::vector<size_t> output_strides;
input_strides.push_back(stride);
output_strides.push_back(stride);
size_t input_distance = 0;
size_t output_distance = 0;
rocfft_array_type in_array_type = rocfft_array_type_complex_interleaved;
rocfft_array_type out_array_type = rocfft_array_type_complex_interleaved;
data_pattern pattern = sawtooth;
complex_to_complex<T, fftw_T>( pattern, transform_type, lengths, batch, input_strides, output_strides, input_distance, output_distance, in_array_type, out_array_type, placeness );
usleep(1e4);
}
// *****************************************************
// Complex to Complex
// *****************************************************
TEST_P(accuracy_test, normal_1D_complex_interleaved_to_complex_interleaved_single_precision)
{
size_t N = std::get<0>(GetParam());
size_t batch = std::get<1>(GetParam());
rocfft_result_placement placeness = std::get<2>(GetParam());
rocfft_transform_type transform_type = std::get<3>(GetParam());
size_t stride = std::get<4>(GetParam());
try { normal_1D_complex_interleaved_to_complex_interleaved< float, fftwf_complex >(N, batch, placeness, transform_type, stride); }
catch( const std::exception& err ) { handle_exception(err); }
}
TEST_P(accuracy_test, normal_1D_complex_interleaved_to_complex_interleaved_double_precision)
{
size_t N = std::get<0>(GetParam());
size_t batch = std::get<1>(GetParam());
rocfft_result_placement placeness = std::get<2>(GetParam());
rocfft_transform_type transform_type = std::get<3>(GetParam());
size_t stride = std::get<4>(GetParam());
try { normal_1D_complex_interleaved_to_complex_interleaved< double, fftw_complex >(N, batch, placeness, transform_type, stride); }
catch( const std::exception& err ) { handle_exception(err); }
}
// *****************************************************
// Real to Complex
// *****************************************************
/*
template< class T, class fftw_T >
void normal_1D_real_interleaved_to_hermitian_interleaved(size_t N, size_t batch, rocfft_result_placement placeness, rocfft_transform_type transform_type, size_t stride)
{
std::vector<size_t> lengths;
lengths.push_back( N );
std::vector<size_t> input_strides;
std::vector<size_t> output_strides;
input_strides.push_back(stride);
output_strides.push_back(stride);
size_t input_distance = 0;
size_t output_distance = 0;
rocfft_array_type in_array_type = rocfft_array_type_real;
rocfft_array_type out_array_type = rocfft_array_type_hermitian_interleaved;
data_pattern pattern = sawtooth;
real_to_complex<T, fftw_T>( pattern, transform_type, lengths, batch, input_strides, output_strides, input_distance, output_distance, in_array_type, out_array_type, rocfft_placement_notinplace );//must be non-inplace tranform
}
TEST_P(accuracy_test, normal_1D_real_interleaved_to_hermitian_interleaved_single_precision)
{
size_t N = std::get<0>(GetParam());
size_t batch = std::get<1>(GetParam());
rocfft_result_placement placeness = rocfft_placement_notinplace;//must be non-inplace
rocfft_transform_type transform_type = rocfft_transform_type_real_forward;// must be real forward
size_t stride = std::get<4>(GetParam());
try { normal_1D_real_interleaved_to_hermitian_interleaved< float, fftwf_complex >(N, batch, placeness, transform_type, stride); }
catch( const std::exception& err ) { handle_exception(err); }
}
*/
// *****************************************************
// *****************************************************
//Values is for a single item; ValuesIn is for an array
//ValuesIn take each element (a vector) and combine them and feed them to test_p
INSTANTIATE_TEST_CASE_P(rocfft_pow2,
accuracy_test,
Combine(
ValuesIn(pow2_range), ValuesIn(batch_range), ValuesIn(placeness_range), ValuesIn(transform_range), ValuesIn(stride_range)
)
);
INSTANTIATE_TEST_CASE_P(rocfft_pow3,
accuracy_test,
Combine(
ValuesIn(pow3_range), ValuesIn(batch_range), ValuesIn(placeness_range), ValuesIn(transform_range), ValuesIn(stride_range)
)
);
INSTANTIATE_TEST_CASE_P(rocfft_pow5,
accuracy_test,
Combine(
ValuesIn(pow5_range), ValuesIn(batch_range), ValuesIn(placeness_range), ValuesIn(transform_range), ValuesIn(stride_range)
)
);
INSTANTIATE_TEST_CASE_P(rocfft_pow_mix,
accuracy_test,
Combine(
ValuesIn(mix_range), ValuesIn(batch_range), ValuesIn(placeness_range), ValuesIn(transform_range), ValuesIn(stride_range)
)
);
// *****************************************************
// *****************************************************
//TESTS disabled by default since they take a long time to execute
//TO enable this tests
//1. make sure ENV CLFFT_REQUEST_LIB_NOMEMALLOC=1
//2. pass --gtest_also_run_disabled_tests to TEST.exe
#define CLFFT_TEST_HUGE
#ifdef CLFFT_TEST_HUGE
#define HUGE_TEST_MAKE(test_name, len, bat) \
template< class T, class fftw_T > \
void test_name() \
{ \
std::vector<size_t> lengths; \
lengths.push_back( len ); \
size_t batch = bat; \
\
std::vector<size_t> input_strides; \
std::vector<size_t> output_strides; \
size_t input_distance = 0; \
size_t output_distance = 0; \
rocfft_array_type in_array_type = rocfft_array_type_complex_planar; \
rocfft_array_type out_array_type = rocfft_array_type_complex_planar; \
rocfft_result_placement placeness = rocfft_placement_inplace; \
rocfft_transform_type transform_type = rocfft_transform_type_complex_forward; \
\
data_pattern pattern = sawtooth; \
complex_to_complex<T, fftw_T>( pattern, transform_type, lengths, batch, input_strides, output_strides, input_distance, output_distance, in_array_type, out_array_type, placeness ); \
}
#define SP_HUGE_TEST(test_name, len, bat) \
\
HUGE_TEST_MAKE(test_name, len, bat) \
\
TEST_F(accuracy_test_pow2_single, test_name) \
{ \
try { test_name< float, fftwf_complex >(); } \
catch( const std::exception& err ) { handle_exception(err); } \
}
#define DP_HUGE_TEST(test_name, len, bat) \
\
HUGE_TEST_MAKE(test_name, len, bat) \
\
TEST_F(accuracy_test_pow2_double, test_name) \
{ \
try { test_name< double, fftw_complex >(); } \
catch( const std::exception& err ) { handle_exception(err); } \
}
SP_HUGE_TEST( DISABLED_huge_sp_test_1, 1048576, 11 )
SP_HUGE_TEST( DISABLED_huge_sp_test_2, 1048576*2, 7 )
SP_HUGE_TEST( DISABLED_huge_sp_test_3, 1048576*4, 3 )
SP_HUGE_TEST( DISABLED_huge_sp_test_4, 1048576*8, 5 )
SP_HUGE_TEST( DISABLED_huge_sp_test_5, 1048576*16, 3 )
SP_HUGE_TEST( DISABLED_huge_sp_test_6, 1048576*32, 2 )
SP_HUGE_TEST( DISABLED_huge_sp_test_7, 1048576*64, 1 )
DP_HUGE_TEST( DISABLED_huge_dp_test_1, 524288, 11 )
DP_HUGE_TEST( DISABLED_huge_dp_test_2, 524288*2, 7 )
DP_HUGE_TEST( DISABLED_huge_dp_test_3, 524288*4, 3 )
DP_HUGE_TEST( DISABLED_huge_dp_test_4, 524288*8, 5 )
DP_HUGE_TEST( DISABLED_huge_dp_test_5, 524288*16, 3 )
DP_HUGE_TEST( DISABLED_huge_dp_test_6, 524288*32, 2 )
DP_HUGE_TEST( DISABLED_huge_dp_test_7, 524288*64, 1 )
SP_HUGE_TEST( DISABLED_large_sp_test_1, 8192, 11 )
SP_HUGE_TEST( DISABLED_large_sp_test_2, 8192*2, 7 )
SP_HUGE_TEST( DISABLED_large_sp_test_3, 8192*4, 3 )
SP_HUGE_TEST( DISABLED_large_sp_test_4, 8192*8, 5 )
SP_HUGE_TEST( DISABLED_large_sp_test_5, 8192*16, 3 )
SP_HUGE_TEST( DISABLED_large_sp_test_6, 8192*32, 21 )
SP_HUGE_TEST( DISABLED_large_sp_test_7, 8192*64, 17 )
DP_HUGE_TEST( DISABLED_large_dp_test_1, 4096, 11 )
DP_HUGE_TEST( DISABLED_large_dp_test_2, 4096*2, 7 )
DP_HUGE_TEST( DISABLED_large_dp_test_3, 4096*4, 3 )
DP_HUGE_TEST( DISABLED_large_dp_test_4, 4096*8, 5 )
DP_HUGE_TEST( DISABLED_large_dp_test_5, 4096*16, 3 )
DP_HUGE_TEST( DISABLED_large_dp_test_6, 4096*32, 21 )
DP_HUGE_TEST( DISABLED_large_dp_test_7, 4096*64, 17 )
#endif
} //namespace
<|endoftext|> |
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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.
*/
# if defined(__APPLE__) || defined(__FreeBSD__)
# include "hpc_aio_provider.h"
# include <fcntl.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <aio.h>
# include <stdio.h>
# include "mix_all_io_looper.h"
# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "aio.provider.hpc"
namespace dsn { namespace tools {
struct posix_disk_aio_context : public disk_aio
{
struct aiocb cb;
aio_task* tsk;
hpc_aio_provider* this_;
utils::notify_event* evt;
error_code err;
uint32_t bytes;
};
hpc_aio_provider::hpc_aio_provider(disk_engine* disk, aio_provider* inner_provider)
: aio_provider(disk, inner_provider)
{
_callback = [this](
int native_error,
uint32_t io_size,
uintptr_t lolp_or_events
)
{
auto e = (struct kevent*)lolp_or_events;
auto io = (struct aiocb*)e->ident;
complete_aio(io, 0, 0);
};
_looper = nullptr;
}
void hpc_aio_provider::start(io_modifer& ctx)
{
_looper = get_io_looper(node(), ctx.queue, ctx.mode);
}
hpc_aio_provider::~hpc_aio_provider()
{
}
dsn_handle_t hpc_aio_provider::open(const char* file_name, int oflag, int pmode)
{
dsn_handle_t handle;
dsn_handle_t invalid_handle = (dsn_handle_t)(uintptr_t)(-1);
handle = (dsn_handle_t)(uintptr_t)::open(file_name, oflag, pmode);
if (handle == invalid_handle)
{
return invalid_handle;
}
if (_looper->bind_io_handle(handle, &_callback, EVFILT_AIO) != ERR_OK)
{
dassert(false, "Unable to bind aio handle.");
}
return (dsn_handle_t)(uintptr_t)ret;
}
error_code hpc_aio_provider::close(dsn_handle_t hFile)
{
// TODO: handle failure
auto error = _looper->unbind_io_handle(hFile, &_callback);
if (error != ERR_OK)
{
return error;
}
error = ::close((int)(uintptr_t)(hFile)) == 0 ? ERR_OK : ERR_FILE_OPERATION_FAILED;
return error;
}
disk_aio* hpc_aio_provider::prepare_aio_context(aio_task* tsk)
{
auto r = new posix_disk_aio_context;
bzero((char*)&r->cb, sizeof(r->cb));
r->tsk = tsk;
r->evt = nullptr;
return r;
}
void hpc_aio_provider::aio(aio_task* aio_tsk)
{
auto err = aio_internal(aio_tsk, true);
err.end_tracking();
}
error_code hpc_aio_provider::aio_internal(aio_task* aio_tsk, bool async, __out_param uint32_t* pbytes /*= nullptr*/)
{
auto aio = (posix_disk_aio_context *)aio_tsk->aio();
int r;
aio->this_ = this;
aio->cb.aio_fildes = static_cast<int>((ssize_t)aio->file);
aio->cb.aio_buf = aio->buffer;
aio->cb.aio_nbytes = aio->buffer_size;
aio->cb.aio_offset = aio->file_offset;
// set up callback
aio->cb.aio_sigevent.sigev_notify = SIGEV_KEVENT;
aio->cb.aio_sigevent.sigev_notify_kqueue = (int)_looper->native_handle();
aio->cb.aio_sigevent.sigev_notify_kevent_flags = EV_CLEAR;
//aio->cb.aio_sigevent.sigev_notify_function = aio_completed;
//aio->cb.aio_sigevent.sigev_notify_attributes = nullptr;
aio->cb.aio_sigevent.sigev_value.sival_ptr = aio;
if (!async)
{
aio->evt = new utils::notify_event();
aio->err = ERR_OK;
aio->bytes = 0;
}
switch (aio->type)
{
case AIO_Read:
r = aio_read(&aio->cb);
break;
case AIO_Write:
r = aio_write(&aio->cb);
break;
default:
dassert(false, "unknown aio type %u", static_cast<int>(aio->type));
break;
}
if (r != 0)
{
derror("file op failed, err = %d (%s). On FreeBSD, you may need to load"
" aio kernel module by running 'sudo kldload aio'.", errno, strerror(errno));
if (async)
{
complete_io(aio_tsk, ERR_FILE_OPERATION_FAILED, 0);
}
else
{
delete aio->evt;
aio->evt = nullptr;
}
return ERR_FILE_OPERATION_FAILED;
}
else
{
if (async)
{
return ERR_IO_PENDING;
}
else
{
aio->evt->wait();
delete aio->evt;
aio->evt = nullptr;
if (pbytes != nullptr)
{
*pbytes = aio->bytes;
}
return aio->err;
}
}
}
void hpc_aio_provider::complete_aio(struct aiocb* io, int bytes, int err)
{
auto ctx = (posix_disk_aio_context *)io->aio_sigevent.sigev_value.sival_ptr;
int err = aio_error(&ctx->cb);
if (err != EINPROGRESS)
{
if (err != 0)
{
derror("file operation failed, errno = %d", errno);
}
size_t bytes = aio_return(&ctx->cb); // from e.g., read or write
if (!ctx->evt)
{
aio_task* aio(ctx->tsk);
ctx->this_->complete_io(aio, err == 0 ? ERR_OK : ERR_FILE_OPERATION_FAILED, bytes);
}
else
{
ctx->err = err == 0 ? ERR_OK : ERR_FILE_OPERATION_FAILED;
ctx->bytes = bytes;
ctx->evt->notify();
}
}
}
}} // end namespace dsn::tools
#endif
<commit_msg>Nits.<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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.
*/
# if defined(__APPLE__) || defined(__FreeBSD__)
# include "hpc_aio_provider.h"
# include <fcntl.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <aio.h>
# include <stdio.h>
# include "mix_all_io_looper.h"
# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "aio.provider.hpc"
namespace dsn { namespace tools {
struct posix_disk_aio_context : public disk_aio
{
struct aiocb cb;
aio_task* tsk;
hpc_aio_provider* this_;
utils::notify_event* evt;
error_code err;
uint32_t bytes;
};
hpc_aio_provider::hpc_aio_provider(disk_engine* disk, aio_provider* inner_provider)
: aio_provider(disk, inner_provider)
{
_callback = [this](
int native_error,
uint32_t io_size,
uintptr_t lolp_or_events
)
{
auto e = (struct kevent*)lolp_or_events;
auto io = (struct aiocb*)e->ident;
complete_aio(io, 0, 0);
};
_looper = nullptr;
}
void hpc_aio_provider::start(io_modifer& ctx)
{
_looper = get_io_looper(node(), ctx.queue, ctx.mode);
}
hpc_aio_provider::~hpc_aio_provider()
{
}
dsn_handle_t hpc_aio_provider::open(const char* file_name, int oflag, int pmode)
{
dsn_handle_t handle;
dsn_handle_t invalid_handle = (dsn_handle_t)(uintptr_t)(-1);
handle = (dsn_handle_t)(uintptr_t)::open(file_name, oflag, pmode);
if (handle == invalid_handle)
{
return invalid_handle;
}
if (_looper->bind_io_handle(handle, &_callback, EVFILT_AIO) != ERR_OK)
{
dassert(false, "Unable to bind aio handle.");
}
return (dsn_handle_t)(uintptr_t)ret;
}
error_code hpc_aio_provider::close(dsn_handle_t hFile)
{
// TODO: handle failure
auto error = _looper->unbind_io_handle(hFile, &_callback);
if (error != ERR_OK)
{
return error;
}
error = ::close((int)(uintptr_t)(hFile)) == 0 ? ERR_OK : ERR_FILE_OPERATION_FAILED;
return error;
}
disk_aio* hpc_aio_provider::prepare_aio_context(aio_task* tsk)
{
auto r = new posix_disk_aio_context;
bzero((char*)&r->cb, sizeof(r->cb));
r->tsk = tsk;
r->evt = nullptr;
return r;
}
void hpc_aio_provider::aio(aio_task* aio_tsk)
{
auto err = aio_internal(aio_tsk, true);
err.end_tracking();
}
error_code hpc_aio_provider::aio_internal(aio_task* aio_tsk, bool async, __out_param uint32_t* pbytes /*= nullptr*/)
{
auto aio = (posix_disk_aio_context *)aio_tsk->aio();
int r;
aio->this_ = this;
aio->cb.aio_fildes = static_cast<int>((ssize_t)aio->file);
aio->cb.aio_buf = aio->buffer;
aio->cb.aio_nbytes = aio->buffer_size;
aio->cb.aio_offset = aio->file_offset;
// set up callback
aio->cb.aio_sigevent.sigev_notify = SIGEV_KEVENT;
aio->cb.aio_sigevent.sigev_notify_kqueue = (int)_looper->native_handle();
aio->cb.aio_sigevent.sigev_notify_kevent_flags = EV_CLEAR;
//aio->cb.aio_sigevent.sigev_notify_function = aio_completed;
//aio->cb.aio_sigevent.sigev_notify_attributes = nullptr;
aio->cb.aio_sigevent.sigev_value.sival_ptr = aio;
if (!async)
{
aio->evt = new utils::notify_event();
aio->err = ERR_OK;
aio->bytes = 0;
}
switch (aio->type)
{
case AIO_Read:
r = aio_read(&aio->cb);
break;
case AIO_Write:
r = aio_write(&aio->cb);
break;
default:
dassert(false, "unknown aio type %u", static_cast<int>(aio->type));
break;
}
if (r != 0)
{
derror("file op failed, err = %d (%s). On FreeBSD, you may need to load"
" aio kernel module by running 'sudo kldload aio'.", errno, strerror(errno));
if (async)
{
complete_io(aio_tsk, ERR_FILE_OPERATION_FAILED, 0);
}
else
{
delete aio->evt;
aio->evt = nullptr;
}
return ERR_FILE_OPERATION_FAILED;
}
else
{
if (async)
{
return ERR_IO_PENDING;
}
else
{
aio->evt->wait();
delete aio->evt;
aio->evt = nullptr;
if (pbytes != nullptr)
{
*pbytes = aio->bytes;
}
return aio->err;
}
}
}
void hpc_aio_provider::complete_aio(struct aiocb* io, int bytes, int err)
{
auto ctx = (posix_disk_aio_context *)(io->aio_sigevent.sigev_value.sival_ptr);
int err = aio_error(&ctx->cb);
if (err != EINPROGRESS)
{
if (err != 0)
{
derror("file operation failed, errno = %d", errno);
}
size_t bytes = aio_return(&ctx->cb); // from e.g., read or write
if (!ctx->evt)
{
aio_task* aio(ctx->tsk);
ctx->this_->complete_io(aio, err == 0 ? ERR_OK : ERR_FILE_OPERATION_FAILED, bytes);
}
else
{
ctx->err = err == 0 ? ERR_OK : ERR_FILE_OPERATION_FAILED;
ctx->bytes = bytes;
ctx->evt->notify();
}
}
}
}} // end namespace dsn::tools
#endif
<|endoftext|> |
<commit_before>#ifdef WIN32
# ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista.
# define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows.
# endif/*_WIN32_WINNT*/
# define WIN32_LEAN_AND_MEAN
# include <winsock2.h>
# include <windows.h>
#else
# include <signal.h>
#endif/*WIN32*/
#include "udt.h"
#include "twainet.h"
#include "application.h"
#include "utils/utils.h"
#include "common/logger.h"
#pragma warning(disable: 4273)
extern "C" void Twainet::InitLibrary(const Twainet::TwainetCallback& twainet)
{
UDT::startup();
Application::GetInstance().Init(twainet);
#ifndef WIN32
signal(SIGPIPE, SIG_IGN);
#endif/*WIN32*/
}
extern "C" void Twainet::FreeLibrary()
{
ManagersContainer::GetInstance().Join();
UDT::cleanup();
}
extern "C" Twainet::Module Twainet::CreateModule(const Twainet::ModuleName& moduleName, bool isCoordinator)
{
TwainetModule* module = Application::GetInstance().CreateModule(moduleName);
isCoordinator ? module->StartAsCoordinator() : module->Start();
return (Twainet::Module*)module;
}
extern "C" void Twainet::DeleteModule(const Twainet::Module module)
{
if(!module)
return;
Application::GetInstance().DeleteModule((TwainetModule*)module);
}
extern "C" void Twainet::CreateServer(const Twainet::Module module, int port, bool local)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->StartServer(port, local);
}
extern "C" void Twainet::ConnectToServer(const Twainet::Module module, const char* host, int port, const UserPassword& userPassword)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->SetUserName(userPassword.m_user);
twainetModule->SetPassword(userPassword.m_pass);
twainetModule->Connect(host, port);
}
extern "C" void Twainet::DisconnectFromServer(const Twainet::Module module)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->Disconnect();
}
extern "C" void Twainet::DisconnectFromClient(const Twainet::Module module, const char* sessionId)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->DisconnectModule(IPCObjectName(ClientServerModule::m_clientIPCName, sessionId));
}
extern "C" void Twainet::ConnectToModule(const Twainet::Module module, const Twainet::ModuleName& moduleName)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->ConnectTo(IPCObjectName(moduleName.m_name, moduleName.m_host, moduleName.m_suffix));
}
extern "C" void DisconnectFromModule(const Twainet::Module module, const Twainet::ModuleName& moduleName)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->DisconnectModule(IPCObjectName(moduleName.m_name, moduleName.m_host, moduleName.m_suffix));
}
extern "C" void Twainet::CreateTunnel(const Twainet::Module module, const char* sessionId, Twainet::TypeConnection type)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->InitNewTunnel(sessionId, (TunnelConnector::TypeConnection)type);
}
extern "C" void Twainet::DisconnectTunnel(const Twainet::Module module, const char* sessionId)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->DestroyTunnel(sessionId);
}
extern "C" void Twainet::SendMessage(const Twainet::Module module, const Twainet::Message& msg)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
IPCMessage message;
message.set_message_name(msg.m_typeMessage);
message.set_message(msg.m_data, msg.m_dataLen);
for(int i = 0; i < msg.m_pathLen; i++)
{
*message.add_ipc_path() = IPCObjectName(msg.m_path[i].m_name, msg.m_path[i].m_host, msg.m_path[i].m_suffix);
}
IPCMessageSignal msgSignal(message);
twainetModule->SendMsg(msgSignal);
}
extern "C" Twainet::ModuleName Twainet::GetModuleName(const Twainet::Module module)
{
if(!module)
{
ModuleName moduleName = {0};
return moduleName;
}
TwainetModule* twainetModule = (TwainetModule*)module;
const IPCObjectName& name = twainetModule->GetModuleName();
Twainet::ModuleName retName = {0};
#ifdef WIN32
strcpy_s(retName.m_name, MAX_NAME_LENGTH, name.module_name().c_str());
strcpy_s(retName.m_host, MAX_NAME_LENGTH, name.host_name().c_str());
strcpy_s(retName.m_suffix, MAX_NAME_LENGTH, name.suffix().c_str());
#else
strcpy(retName.m_name, name.module_name().c_str());
strcpy(retName.m_host, name.host_name().c_str());
strcpy(retName.m_suffix, name.suffix().c_str());
#endif/*WIN32*/
return retName;
}
extern "C" void ChangeModuleName(const Twainet::Module module, const Twainet::ModuleName& moduleName)
{
if(!module)
{
return;
}
TwainetModule* twainetModule = (TwainetModule*)module;
IPCObjectName ipcModuleName(moduleName.m_name, moduleName.m_host, moduleName.m_suffix);
twainetModule->UpdateModuleName(ipcModuleName);
}
extern "C" const char* Twainet::GetSessionId(const Twainet::Module module)
{
TwainetModule* twainetModule = (TwainetModule*)module;
return twainetModule->GetSessionId().c_str();
}
extern "C" int Twainet::GetExistingModules(const Twainet::Module module, Twainet::ModuleName* modules, int& sizeModules)
{
if(!module)
return 0;
TwainetModule* twainetModule = (TwainetModule*)module;
std::vector<IPCObjectName> objects = twainetModule->GetIPCObjects();
if(sizeModules < (int)objects.size())
{
sizeModules = objects.size();
return 0;
}
int i = 0;
for(std::vector<IPCObjectName>::iterator it = objects.begin();
it != objects.end(); it++, i++)
{
#ifdef WIN32
strcpy_s(modules[i].m_name, MAX_NAME_LENGTH, it->module_name().c_str());
strcpy_s(modules[i].m_host, MAX_NAME_LENGTH, it->host_name().c_str());
strcpy_s(modules[i].m_suffix, MAX_NAME_LENGTH, it->suffix().c_str());
#else
strcpy(modules[i].m_name, it->module_name().c_str());
strcpy(modules[i].m_host, it->host_name().c_str());
strcpy(modules[i].m_suffix, it->suffix().c_str());
#endif/*WIN32*/
}
return objects.size();
}
extern "C" void Twainet::SetTunnelType(const Twainet::Module module, const char* oneSessionId, const char* twoSessionId, Twainet::TypeConnection type)
{
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->SetTypeTunnel(oneSessionId, twoSessionId, (TunnelConnector::TypeConnection)type);
}
extern "C" void Twainet::SetUsersList(const Twainet::Module module, const Twainet::UserPassword* users, int sizeUsers)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->ClearUsers();
for(int i = 0; i < sizeUsers; i++)
{
twainetModule->AddUser(users[i].m_user, users[i].m_pass);
}
}
extern "C" void Twainet::UseProxy(const Twainet::Module module, const char* host, int port, const Twainet::UserPassword& userPassword)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->UseProxy(host, port);
twainetModule->SetProxyUserName(userPassword.m_user);
twainetModule->SetProxyPassword(userPassword.m_pass);
}
extern "C" void Twainet::UseStandartConnections(const Twainet::Module module)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->UseStandartConnections();
}
extern "C" void Twainet::UseLog(char* logFileName)
{
Logger::GetInstance().SetLogFile(logFileName);
}
extern "C" void Twainet::CreateInternalConnection(const Twainet::Module module, const Twainet::ModuleName& moduleName, const char* ip, int port, const char* id)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
IPCObjectName ipcModuleName(moduleName.m_name, moduleName.m_host, moduleName.m_suffix);
twainetModule->CreateInternalConnection(ipcModuleName, ip, port, id);
}
extern "C" int Twainet::GetInternalConnections(const Twainet::Module module, Twainet::InternalConnection* connections, int& sizeConnections)
{
if(!module)
return 0;
TwainetModule* twainetModule = (TwainetModule*)module;
std::vector<IPCObjectName> objects = twainetModule->GetInternalConnections();
if(sizeConnections < (int)objects.size())
{
sizeConnections = objects.size();
return 0;
}
int i = 0;
for(std::vector<IPCObjectName>::iterator it = objects.begin();
it != objects.end(); it++, i++)
{
#ifdef WIN32
strcpy_s(connections[i].m_moduleName.m_name, MAX_NAME_LENGTH, it->module_name().c_str());
strcpy_s(connections[i].m_moduleName.m_host, MAX_NAME_LENGTH, it->host_name().c_str());
strcpy_s(connections[i].m_moduleName.m_suffix, MAX_NAME_LENGTH, it->suffix().c_str());
strcpy_s(connections[i].m_id, MAX_NAME_LENGTH, it->internal().c_str());
#else
strcpy(connections[i].m_moduleName.m_name, it->module_name().c_str());
strcpy(connections[i].m_moduleName.m_host, it->host_name().c_str());
strcpy(connections[i].m_moduleName.m_suffix, it->suffix().c_str());
strcpy(connections[i].m_id, it->internal().c_str());
#endif/*WIN32*/
}
return objects.size();
}
extern "C" int Twainet::GetModuleNameString(const ModuleName& moduleName, char* str, int& strlen)
{
IPCObjectName name(moduleName.m_name, moduleName.m_host, moduleName.m_suffix);
std::string strModuleName = name.GetModuleNameString();
if(strlen < (int)strModuleName.size())
{
strlen = strModuleName.size();
return 0;
}
#ifdef WIN32
strcpy_s(str, strlen, strModuleName.c_str());
#else
strcpy(str, strModuleName.c_str());
#endif/*WIN32*/
}
<commit_msg>little fix<commit_after>#ifdef WIN32
# ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista.
# define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows.
# endif/*_WIN32_WINNT*/
# define WIN32_LEAN_AND_MEAN
# include <winsock2.h>
# include <windows.h>
#else
# include <signal.h>
#endif/*WIN32*/
#include "udt.h"
#include "twainet.h"
#include "application.h"
#include "utils/utils.h"
#include "common/logger.h"
#pragma warning(disable: 4273)
extern "C" void Twainet::InitLibrary(const Twainet::TwainetCallback& twainet)
{
UDT::startup();
Application::GetInstance().Init(twainet);
#ifndef WIN32
signal(SIGPIPE, SIG_IGN);
#endif/*WIN32*/
}
extern "C" void Twainet::FreeLibrary()
{
ManagersContainer::GetInstance().Join();
UDT::cleanup();
}
extern "C" Twainet::Module Twainet::CreateModule(const Twainet::ModuleName& moduleName, bool isCoordinator)
{
TwainetModule* module = Application::GetInstance().CreateModule(moduleName);
isCoordinator ? module->StartAsCoordinator() : module->Start();
return (Twainet::Module*)module;
}
extern "C" void Twainet::DeleteModule(const Twainet::Module module)
{
if(!module)
return;
Application::GetInstance().DeleteModule((TwainetModule*)module);
}
extern "C" void Twainet::CreateServer(const Twainet::Module module, int port, bool local)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->StartServer(port, local);
}
extern "C" void Twainet::ConnectToServer(const Twainet::Module module, const char* host, int port, const UserPassword& userPassword)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->SetUserName(userPassword.m_user);
twainetModule->SetPassword(userPassword.m_pass);
twainetModule->Connect(host, port);
}
extern "C" void Twainet::DisconnectFromServer(const Twainet::Module module)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->Disconnect();
}
extern "C" void Twainet::DisconnectFromClient(const Twainet::Module module, const char* sessionId)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->DisconnectModule(IPCObjectName(ClientServerModule::m_clientIPCName, sessionId));
}
extern "C" void Twainet::ConnectToModule(const Twainet::Module module, const Twainet::ModuleName& moduleName)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->ConnectTo(IPCObjectName(moduleName.m_name, moduleName.m_host, moduleName.m_suffix));
}
extern "C" void DisconnectFromModule(const Twainet::Module module, const Twainet::ModuleName& moduleName)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->DisconnectModule(IPCObjectName(moduleName.m_name, moduleName.m_host, moduleName.m_suffix));
}
extern "C" void Twainet::CreateTunnel(const Twainet::Module module, const char* sessionId, Twainet::TypeConnection type)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->InitNewTunnel(sessionId, (TunnelConnector::TypeConnection)type);
}
extern "C" void Twainet::DisconnectTunnel(const Twainet::Module module, const char* sessionId)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->DestroyTunnel(sessionId);
}
extern "C" void Twainet::SendMessage(const Twainet::Module module, const Twainet::Message& msg)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
IPCMessage message;
message.set_message_name(msg.m_typeMessage);
message.set_message(msg.m_data, msg.m_dataLen);
for(int i = 0; i < msg.m_pathLen; i++)
{
*message.add_ipc_path() = IPCObjectName(msg.m_path[i].m_name, msg.m_path[i].m_host, msg.m_path[i].m_suffix);
}
IPCMessageSignal msgSignal(message);
twainetModule->SendMsg(msgSignal);
}
extern "C" Twainet::ModuleName Twainet::GetModuleName(const Twainet::Module module)
{
if(!module)
{
ModuleName moduleName = {0};
return moduleName;
}
TwainetModule* twainetModule = (TwainetModule*)module;
const IPCObjectName& name = twainetModule->GetModuleName();
Twainet::ModuleName retName = {0};
#ifdef WIN32
strcpy_s(retName.m_name, MAX_NAME_LENGTH, name.module_name().c_str());
strcpy_s(retName.m_host, MAX_NAME_LENGTH, name.host_name().c_str());
strcpy_s(retName.m_suffix, MAX_NAME_LENGTH, name.suffix().c_str());
#else
strcpy(retName.m_name, name.module_name().c_str());
strcpy(retName.m_host, name.host_name().c_str());
strcpy(retName.m_suffix, name.suffix().c_str());
#endif/*WIN32*/
return retName;
}
extern "C" void ChangeModuleName(const Twainet::Module module, const Twainet::ModuleName& moduleName)
{
if(!module)
{
return;
}
TwainetModule* twainetModule = (TwainetModule*)module;
IPCObjectName ipcModuleName(moduleName.m_name, moduleName.m_host, moduleName.m_suffix);
twainetModule->UpdateModuleName(ipcModuleName);
}
extern "C" const char* Twainet::GetSessionId(const Twainet::Module module)
{
TwainetModule* twainetModule = (TwainetModule*)module;
return twainetModule->GetSessionId().c_str();
}
extern "C" int Twainet::GetExistingModules(const Twainet::Module module, Twainet::ModuleName* modules, int& sizeModules)
{
if(!module)
return 0;
TwainetModule* twainetModule = (TwainetModule*)module;
std::vector<IPCObjectName> objects = twainetModule->GetIPCObjects();
if(sizeModules < (int)objects.size())
{
sizeModules = objects.size();
return 0;
}
int i = 0;
for(std::vector<IPCObjectName>::iterator it = objects.begin();
it != objects.end(); it++, i++)
{
#ifdef WIN32
strcpy_s(modules[i].m_name, MAX_NAME_LENGTH, it->module_name().c_str());
strcpy_s(modules[i].m_host, MAX_NAME_LENGTH, it->host_name().c_str());
strcpy_s(modules[i].m_suffix, MAX_NAME_LENGTH, it->suffix().c_str());
#else
strcpy(modules[i].m_name, it->module_name().c_str());
strcpy(modules[i].m_host, it->host_name().c_str());
strcpy(modules[i].m_suffix, it->suffix().c_str());
#endif/*WIN32*/
}
return objects.size();
}
extern "C" void Twainet::SetTunnelType(const Twainet::Module module, const char* oneSessionId, const char* twoSessionId, Twainet::TypeConnection type)
{
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->SetTypeTunnel(oneSessionId, twoSessionId, (TunnelConnector::TypeConnection)type);
}
extern "C" void Twainet::SetUsersList(const Twainet::Module module, const Twainet::UserPassword* users, int sizeUsers)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->ClearUsers();
for(int i = 0; i < sizeUsers; i++)
{
twainetModule->AddUser(users[i].m_user, users[i].m_pass);
}
}
extern "C" void Twainet::UseProxy(const Twainet::Module module, const char* host, int port, const Twainet::UserPassword& userPassword)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->UseProxy(host, port);
twainetModule->SetProxyUserName(userPassword.m_user);
twainetModule->SetProxyPassword(userPassword.m_pass);
}
extern "C" void Twainet::UseStandartConnections(const Twainet::Module module)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
twainetModule->UseStandartConnections();
}
extern "C" void Twainet::UseLog(char* logFileName)
{
Logger::GetInstance().SetLogFile(logFileName);
}
extern "C" void Twainet::CreateInternalConnection(const Twainet::Module module, const Twainet::ModuleName& moduleName, const char* ip, int port, const char* id)
{
if(!module)
return;
TwainetModule* twainetModule = (TwainetModule*)module;
IPCObjectName ipcModuleName(moduleName.m_name, moduleName.m_host, moduleName.m_suffix);
twainetModule->CreateInternalConnection(ipcModuleName, ip, port, id);
}
extern "C" int Twainet::GetInternalConnections(const Twainet::Module module, Twainet::InternalConnection* connections, int& sizeConnections)
{
if(!module)
return 0;
TwainetModule* twainetModule = (TwainetModule*)module;
std::vector<IPCObjectName> objects = twainetModule->GetInternalConnections();
if(sizeConnections < (int)objects.size())
{
sizeConnections = objects.size();
return 0;
}
int i = 0;
for(std::vector<IPCObjectName>::iterator it = objects.begin();
it != objects.end(); it++, i++)
{
#ifdef WIN32
strcpy_s(connections[i].m_moduleName.m_name, MAX_NAME_LENGTH, it->module_name().c_str());
strcpy_s(connections[i].m_moduleName.m_host, MAX_NAME_LENGTH, it->host_name().c_str());
strcpy_s(connections[i].m_moduleName.m_suffix, MAX_NAME_LENGTH, it->suffix().c_str());
strcpy_s(connections[i].m_id, MAX_NAME_LENGTH, it->internal().c_str());
#else
strcpy(connections[i].m_moduleName.m_name, it->module_name().c_str());
strcpy(connections[i].m_moduleName.m_host, it->host_name().c_str());
strcpy(connections[i].m_moduleName.m_suffix, it->suffix().c_str());
strcpy(connections[i].m_id, it->internal().c_str());
#endif/*WIN32*/
}
return objects.size();
}
extern "C" int Twainet::GetModuleNameString(const ModuleName& moduleName, char* str, int& strlen)
{
IPCObjectName name(moduleName.m_name, moduleName.m_host, moduleName.m_suffix);
std::string strModuleName = name.GetModuleNameString();
if(strlen < (int)strModuleName.size())
{
strlen = strModuleName.size();
return 0;
}
#ifdef WIN32
strcpy_s(str, strlen, strModuleName.c_str());
#else
strcpy(str, strModuleName.c_str());
#endif/*WIN32*/
return strlen;
}
<|endoftext|> |
<commit_before>/*************************************************************************
* Copyright (c) 2014 eProsima. All rights reserved.
*
* This copy of eProsima RTPS is licensed to you under the terms described in the
* fastrtps_LIBRARY_LICENSE file included in this distribution.
*
*************************************************************************/
/*
* ResourceSendImpl.cpp
*
*/
#include "fastrtps/rtps/resources/ResourceSendImpl.h"
#include "fastrtps/rtps/common/CDRMessage_t.h"
#include "fastrtps/utils/RTPSLog.h"
#include "fastrtps/utils/IPFinder.h"
using boost::asio::ip::udp;
namespace eprosima {
namespace fastrtps{
namespace rtps {
static const char* const CLASS_NAME = "SendResource";
static const int MAX_BIND_TRIES = 100;
ResourceSendImpl::ResourceSendImpl() :
m_useIP4(true),
m_useIP6(true),
//m_send_socket_v4(m_send_service),
//m_send_socket_v6(m_send_service),
m_bytes_sent(0),
m_send_next(true),
mp_RTPSParticipant(nullptr),
mp_mutex(new boost::recursive_mutex())
{
}
bool ResourceSendImpl::initSend(RTPSParticipantImpl* pimpl,const Locator_t& loc,uint32_t sendsockBuffer,bool useIP4,bool useIP6)
{
const char* const METHOD_NAME = "initSend";
m_useIP4 = useIP4;
m_useIP6 = useIP6;
LocatorList_t list;
IPFinder::getAllIPAddress(&list);
boost::asio::socket_base::send_buffer_size option;
bool not_bind = true;
int bind_tries = 0;
for (auto lit = list.begin(); lit != list.end(); ++lit)
{
if (lit->kind == LOCATOR_KIND_UDPv4 && m_useIP4)
{
mv_sendLocator_v4.push_back(loc);
auto sendLocv4 = mv_sendLocator_v4.back();
sendLocv4.port = loc.port;
//OPEN SOCKETS:
mv_send_socket_v4.push_back(new boost::asio::ip::udp::socket(m_send_service));
auto sendSocketv4 = mv_send_socket_v4.back();
sendSocketv4->open(boost::asio::ip::udp::v4());
sendSocketv4->set_option(boost::asio::socket_base::send_buffer_size(sendsockBuffer));
bind_tries = 0;
udp::endpoint send_endpoint;
while (not_bind && bind_tries < MAX_BIND_TRIES)
{
send_endpoint = udp::endpoint(boost::asio::ip::address_v4(lit->to_IP4_long()), sendLocv4.port);
try{
sendSocketv4->bind(send_endpoint);
not_bind = false;
}
catch (boost::system::system_error const& e)
{
logInfo(RTPS_MSG_OUT, "UDPv4 Error binding endpoint: (" << send_endpoint << ") with socket: " << sendSocketv4->local_endpoint()
<< " with boost msg: "<<e.what() , C_YELLOW);
sendLocv4.port++;
}
++bind_tries;
}
if(!not_bind)
{
sendSocketv4->get_option(option);
logInfo(RTPS_MSG_OUT, "UDPv4: " << sendSocketv4->local_endpoint() << "|| State: " << sendSocketv4->is_open() <<
" || buffer size: " << option.value(), C_YELLOW);
}
else
{
logWarning(RTPS_MSG_OUT,"UDPv4: Maxmimum Number of tries while binding in this interface: "<<send_endpoint,C_YELLOW)
mv_sendLocator_v4.erase(mv_sendLocator_v4.end()-1);
delete(*(mv_send_socket_v4.end()-1));
mv_send_socket_v4.erase(mv_send_socket_v4.end()-1);
}
not_bind = true;
}
else if (lit->kind == LOCATOR_KIND_UDPv6 && m_useIP6)
{
mv_sendLocator_v6.push_back(loc);
auto sendLocv6 = mv_sendLocator_v6.back();
sendLocv6.port = loc.port;
//OPEN SOCKETS:
mv_send_socket_v6.push_back(new boost::asio::ip::udp::socket(m_send_service));
auto sendSocketv6 = mv_send_socket_v6.back();
sendSocketv6->open(boost::asio::ip::udp::v6());
sendSocketv6->set_option(boost::asio::socket_base::send_buffer_size(sendsockBuffer));
bind_tries = 0;
udp::endpoint send_endpoint;
while (not_bind && bind_tries < MAX_BIND_TRIES)
{
boost::asio::ip::address_v6::bytes_type bt;
for (uint8_t i = 0; i < 16;++i)
bt[i] = lit->address[i];
#if defined(_WIN32)
send_endpoint = udp::endpoint(boost::asio::ip::address_v6(bt), sendLocv6.port);
#else
send_endpoint = udp::endpoint(boost::asio::ip::address_v6(), sendLocv6.port);
#endif
try{
sendSocketv6->bind(send_endpoint);
not_bind = false;
}
catch (boost::system::system_error const& e)
{
logInfo(RTPS_MSG_OUT, "UDPv6 Error binding endpoint: (" << send_endpoint << ") with socket: " << sendSocketv6->local_endpoint()
<< " with boost msg: "<<e.what() , C_YELLOW);
sendLocv6.port++;
}
++bind_tries;
}
if(!not_bind)
{
sendSocketv6->get_option(option);
logInfo(RTPS_MSG_OUT, "UDPv6: " << sendSocketv6->local_endpoint() << "|| State: " << sendSocketv6->is_open() <<
" || buffer size: " << option.value(), C_YELLOW);
}
else
{
logWarning(RTPS_MSG_OUT,"UDPv6: Maxmimum Number of tries while binding in this endpoint: "<<send_endpoint,C_YELLOW);
mv_sendLocator_v6.erase(mv_sendLocator_v6.end()-1);
delete(*(mv_send_socket_v6.end()-1));
mv_send_socket_v6.erase(mv_send_socket_v6.end()-1);
}
not_bind = true;
}
}
return true;
}
ResourceSendImpl::~ResourceSendImpl()
{
const char* const METHOD_NAME = "~SendResource";
logInfo(RTPS_MSG_OUT,"",C_YELLOW);
for (auto it = mv_send_socket_v4.begin(); it != mv_send_socket_v4.end(); ++it)
(*it)->close();
for (auto it = mv_send_socket_v6.begin(); it != mv_send_socket_v6.end(); ++it)
(*it)->close();
m_send_service.stop();
for (auto it = mv_send_socket_v4.begin(); it != mv_send_socket_v4.end(); ++it)
delete(*it);
for (auto it = mv_send_socket_v6.begin(); it != mv_send_socket_v6.end(); ++it)
delete(*it);
delete(mp_mutex);
}
void ResourceSendImpl::sendSync(CDRMessage_t* msg, const Locator_t& loc)
{
const char* const METHOD_NAME = "sendSync";
boost::lock_guard<boost::recursive_mutex> guard(*this->mp_mutex);
if(loc.port == 0)
return;
if(loc.kind == LOCATOR_KIND_UDPv4 && m_useIP4)
{
boost::asio::ip::address_v4::bytes_type addr;
for(uint8_t i=0;i<4;i++)
addr[i] = loc.address[12+i];
m_send_endpoint_v4 = udp::endpoint(boost::asio::ip::address_v4(addr),loc.port);
for (auto sockit = mv_send_socket_v4.begin(); sockit != mv_send_socket_v4.end(); ++sockit)
{
logInfo(RTPS_MSG_OUT,"UDPv4: " << msg->length << " bytes TO endpoint: " << m_send_endpoint_v4
<< " FROM " << (*sockit)->local_endpoint(), C_YELLOW);
if(m_send_endpoint_v4.port()>0)
{
m_bytes_sent = 0;
if(m_send_next)
{
try {
m_bytes_sent = (*sockit)->send_to(boost::asio::buffer((void*)msg->buffer, msg->length), m_send_endpoint_v4);
}
catch (const std::exception& error) {
// Should print the actual error message
logWarning(RTPS_MSG_OUT, "Error: " << error.what(), C_YELLOW);
}
}
else
{
m_send_next = true;
}
logInfo (RTPS_MSG_OUT,"SENT " << m_bytes_sent,C_YELLOW);
}
else if(m_send_endpoint_v4.port()<=0)
{
logWarning(RTPS_MSG_OUT,"Port invalid",C_YELLOW);
}
else
logError(RTPS_MSG_OUT,"Port error",C_YELLOW);
}
}
else if(loc.kind == LOCATOR_KIND_UDPv6 && m_useIP6)
{
boost::asio::ip::address_v6::bytes_type addr;
for(uint8_t i=0;i<16;i++)
addr[i] = loc.address[i];
m_send_endpoint_v6 = udp::endpoint(boost::asio::ip::address_v6(addr),loc.port);
for (auto sockit = mv_send_socket_v4.begin(); sockit != mv_send_socket_v4.end(); ++sockit)
{
logInfo(RTPS_MSG_OUT, "UDPv6: " << msg->length << " bytes TO endpoint: "
<< m_send_endpoint_v6 << " FROM " << (*sockit)->local_endpoint(), C_YELLOW);
if (m_send_endpoint_v6.port()>0)
{
m_bytes_sent = 0;
if (m_send_next)
{
try {
m_bytes_sent = (*sockit)->send_to(boost::asio::buffer((void*)msg->buffer, msg->length), m_send_endpoint_v6);
}
catch (const std::exception& error) {
// Should print the actual error message
logWarning(RTPS_MSG_OUT, "Error: " << error.what(), C_YELLOW);
}
}
else
{
m_send_next = true;
}
logInfo(RTPS_MSG_OUT, "SENT " << m_bytes_sent, C_YELLOW);
}
else if (m_send_endpoint_v6.port() <= 0)
{
logWarning(RTPS_MSG_OUT, "Port invalid", C_YELLOW);
}
else
logError(RTPS_MSG_OUT, "Port error", C_YELLOW);
}
}
else
{
logInfo(RTPS_MSG_OUT,"Destination "<< loc << " not valid for this ListenResource",C_YELLOW);
}
}
boost::recursive_mutex* ResourceSendImpl::getMutex() {return mp_mutex;}
}
} /* namespace rtps */
} /* namespace eprosima */
<commit_msg>Still not working in linux for IP6 multiple interfaces<commit_after>/*************************************************************************
* Copyright (c) 2014 eProsima. All rights reserved.
*
* This copy of eProsima RTPS is licensed to you under the terms described in the
* fastrtps_LIBRARY_LICENSE file included in this distribution.
*
*************************************************************************/
/*
* ResourceSendImpl.cpp
*
*/
#include "fastrtps/rtps/resources/ResourceSendImpl.h"
#include "fastrtps/rtps/common/CDRMessage_t.h"
#include "fastrtps/utils/RTPSLog.h"
#include "fastrtps/utils/IPFinder.h"
using boost::asio::ip::udp;
namespace eprosima {
namespace fastrtps{
namespace rtps {
static const char* const CLASS_NAME = "SendResource";
static const int MAX_BIND_TRIES = 100;
ResourceSendImpl::ResourceSendImpl() :
m_useIP4(true),
m_useIP6(true),
//m_send_socket_v4(m_send_service),
//m_send_socket_v6(m_send_service),
m_bytes_sent(0),
m_send_next(true),
mp_RTPSParticipant(nullptr),
mp_mutex(new boost::recursive_mutex())
{
}
bool ResourceSendImpl::initSend(RTPSParticipantImpl* pimpl,const Locator_t& loc,uint32_t sendsockBuffer,bool useIP4,bool useIP6)
{
const char* const METHOD_NAME = "initSend";
m_useIP4 = useIP4;
m_useIP6 = useIP6;
LocatorList_t list;
IPFinder::getAllIPAddress(&list);
boost::asio::socket_base::send_buffer_size option;
bool not_bind = true;
int bind_tries = 0;
for (auto lit = list.begin(); lit != list.end(); ++lit)
{
if (lit->kind == LOCATOR_KIND_UDPv4 && m_useIP4)
{
mv_sendLocator_v4.push_back(loc);
auto sendLocv4 = mv_sendLocator_v4.back();
sendLocv4.port = loc.port;
//OPEN SOCKETS:
mv_send_socket_v4.push_back(new boost::asio::ip::udp::socket(m_send_service));
auto sendSocketv4 = mv_send_socket_v4.back();
sendSocketv4->open(boost::asio::ip::udp::v4());
sendSocketv4->set_option(boost::asio::socket_base::send_buffer_size(sendsockBuffer));
bind_tries = 0;
udp::endpoint send_endpoint;
while (not_bind && bind_tries < MAX_BIND_TRIES)
{
send_endpoint = udp::endpoint(boost::asio::ip::address_v4(lit->to_IP4_long()), sendLocv4.port);
try{
sendSocketv4->bind(send_endpoint);
not_bind = false;
}
catch (boost::system::system_error const& e)
{
logInfo(RTPS_MSG_OUT, "UDPv4 Error binding endpoint: (" << send_endpoint << ") with socket: " << sendSocketv4->local_endpoint()
<< " with boost msg: "<<e.what() , C_YELLOW);
sendLocv4.port++;
}
++bind_tries;
}
if(!not_bind)
{
sendSocketv4->get_option(option);
logInfo(RTPS_MSG_OUT, "UDPv4: " << sendSocketv4->local_endpoint() << "|| State: " << sendSocketv4->is_open() <<
" || buffer size: " << option.value(), C_YELLOW);
}
else
{
logWarning(RTPS_MSG_OUT,"UDPv4: Maxmimum Number of tries while binding in this interface: "<<send_endpoint,C_YELLOW)
mv_sendLocator_v4.erase(mv_sendLocator_v4.end()-1);
delete(*(mv_send_socket_v4.end()-1));
mv_send_socket_v4.erase(mv_send_socket_v4.end()-1);
}
not_bind = true;
}
else if (lit->kind == LOCATOR_KIND_UDPv6 && m_useIP6)
{
mv_sendLocator_v6.push_back(loc);
auto sendLocv6 = mv_sendLocator_v6.back();
sendLocv6.port = loc.port;
//OPEN SOCKETS:
mv_send_socket_v6.push_back(new boost::asio::ip::udp::socket(m_send_service));
auto sendSocketv6 = mv_send_socket_v6.back();
sendSocketv6->open(boost::asio::ip::udp::v6());
sendSocketv6->set_option(boost::asio::socket_base::send_buffer_size(sendsockBuffer));
bind_tries = 0;
udp::endpoint send_endpoint;
while (not_bind && bind_tries < MAX_BIND_TRIES)
{
boost::asio::ip::address_v6::bytes_type bt;
for (uint8_t i = 0; i < 16;++i)
bt[i] = lit->address[i];
#if defined(_WIN32)
send_endpoint = udp::endpoint(boost::asio::ip::address_v6(bt), sendLocv6.port);
#else
send_endpoint = udp::endpoint(boost::asio::ip::address_v6(bt), sendLocv6.port);
#endif
try{
sendSocketv6->bind(send_endpoint);
not_bind = false;
}
catch (boost::system::system_error const& e)
{
logInfo(RTPS_MSG_OUT, "UDPv6 Error binding endpoint: (" << send_endpoint << ") with socket: " << sendSocketv6->local_endpoint()
<< " with boost msg: "<<e.what() , C_YELLOW);
sendLocv6.port++;
}
++bind_tries;
}
if(!not_bind)
{
sendSocketv6->get_option(option);
logInfo(RTPS_MSG_OUT, "UDPv6: " << sendSocketv6->local_endpoint() << "|| State: " << sendSocketv6->is_open() <<
" || buffer size: " << option.value(), C_YELLOW);
}
else
{
logWarning(RTPS_MSG_OUT,"UDPv6: Maxmimum Number of tries while binding in this endpoint: "<<send_endpoint,C_YELLOW);
mv_sendLocator_v6.erase(mv_sendLocator_v6.end()-1);
delete(*(mv_send_socket_v6.end()-1));
mv_send_socket_v6.erase(mv_send_socket_v6.end()-1);
}
not_bind = true;
}
}
return true;
}
ResourceSendImpl::~ResourceSendImpl()
{
const char* const METHOD_NAME = "~SendResource";
logInfo(RTPS_MSG_OUT,"",C_YELLOW);
for (auto it = mv_send_socket_v4.begin(); it != mv_send_socket_v4.end(); ++it)
(*it)->close();
for (auto it = mv_send_socket_v6.begin(); it != mv_send_socket_v6.end(); ++it)
(*it)->close();
m_send_service.stop();
for (auto it = mv_send_socket_v4.begin(); it != mv_send_socket_v4.end(); ++it)
delete(*it);
for (auto it = mv_send_socket_v6.begin(); it != mv_send_socket_v6.end(); ++it)
delete(*it);
delete(mp_mutex);
}
void ResourceSendImpl::sendSync(CDRMessage_t* msg, const Locator_t& loc)
{
const char* const METHOD_NAME = "sendSync";
boost::lock_guard<boost::recursive_mutex> guard(*this->mp_mutex);
if(loc.port == 0)
return;
if(loc.kind == LOCATOR_KIND_UDPv4 && m_useIP4)
{
boost::asio::ip::address_v4::bytes_type addr;
for(uint8_t i=0;i<4;i++)
addr[i] = loc.address[12+i];
m_send_endpoint_v4 = udp::endpoint(boost::asio::ip::address_v4(addr),loc.port);
for (auto sockit = mv_send_socket_v4.begin(); sockit != mv_send_socket_v4.end(); ++sockit)
{
logInfo(RTPS_MSG_OUT,"UDPv4: " << msg->length << " bytes TO endpoint: " << m_send_endpoint_v4
<< " FROM " << (*sockit)->local_endpoint(), C_YELLOW);
if(m_send_endpoint_v4.port()>0)
{
m_bytes_sent = 0;
if(m_send_next)
{
try {
m_bytes_sent = (*sockit)->send_to(boost::asio::buffer((void*)msg->buffer, msg->length), m_send_endpoint_v4);
}
catch (const std::exception& error) {
// Should print the actual error message
logWarning(RTPS_MSG_OUT, "Error: " << error.what(), C_YELLOW);
}
}
else
{
m_send_next = true;
}
logInfo (RTPS_MSG_OUT,"SENT " << m_bytes_sent,C_YELLOW);
}
else if(m_send_endpoint_v4.port()<=0)
{
logWarning(RTPS_MSG_OUT,"Port invalid",C_YELLOW);
}
else
logError(RTPS_MSG_OUT,"Port error",C_YELLOW);
}
}
else if(loc.kind == LOCATOR_KIND_UDPv6 && m_useIP6)
{
boost::asio::ip::address_v6::bytes_type addr;
for(uint8_t i=0;i<16;i++)
addr[i] = loc.address[i];
m_send_endpoint_v6 = udp::endpoint(boost::asio::ip::address_v6(addr),loc.port);
for (auto sockit = mv_send_socket_v4.begin(); sockit != mv_send_socket_v4.end(); ++sockit)
{
logInfo(RTPS_MSG_OUT, "UDPv6: " << msg->length << " bytes TO endpoint: "
<< m_send_endpoint_v6 << " FROM " << (*sockit)->local_endpoint(), C_YELLOW);
if (m_send_endpoint_v6.port()>0)
{
m_bytes_sent = 0;
if (m_send_next)
{
try {
m_bytes_sent = (*sockit)->send_to(boost::asio::buffer((void*)msg->buffer, msg->length), m_send_endpoint_v6);
}
catch (const std::exception& error) {
// Should print the actual error message
logWarning(RTPS_MSG_OUT, "Error: " << error.what(), C_YELLOW);
}
}
else
{
m_send_next = true;
}
logInfo(RTPS_MSG_OUT, "SENT " << m_bytes_sent, C_YELLOW);
}
else if (m_send_endpoint_v6.port() <= 0)
{
logWarning(RTPS_MSG_OUT, "Port invalid", C_YELLOW);
}
else
logError(RTPS_MSG_OUT, "Port error", C_YELLOW);
}
}
else
{
logInfo(RTPS_MSG_OUT,"Destination "<< loc << " not valid for this ListenResource",C_YELLOW);
}
}
boost::recursive_mutex* ResourceSendImpl::getMutex() {return mp_mutex;}
}
} /* namespace rtps */
} /* namespace eprosima */
<|endoftext|> |
<commit_before>/*
* SessionProfiler.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionProfiler.hpp"
#include <core/Exec.hpp>
#include <session/SessionModuleContext.hpp>
#include <core/Error.hpp>
#include <core/Exec.hpp>
#include <r/RSexp.hpp>
#include <r/RRoutines.hpp>
#include <r/RUtil.hpp>
#include <r/ROptions.hpp>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace profiler {
namespace {
#define kProfilesCacheDir "profiles-cache"
#define kProfilesUrlPath "profiles"
std::string profilesCacheDir()
{
return module_context::scopedScratchPath().childPath(kProfilesCacheDir)
.absolutePath();
}
SEXP rs_profilesPath()
{
r::sexp::Protect rProtect;
return r::sexp::create(profilesCacheDir(), &rProtect);
}
} // anonymous namespace
void handleProfilerResReq(const http::Request& request,
http::Response* pResponse)
{
std::string resourceName = http::util::pathAfterPrefix(request, "/" kProfilesUrlPath "/");
core::FilePath profilesPath = core::FilePath(profilesCacheDir());
core::FilePath profileResource = profilesPath.childPath(resourceName);
pResponse->setCacheableFile(profileResource, request);
}
void onDocPendingRemove(
boost::shared_ptr<source_database::SourceDocument> pDoc)
{
// check to see if there is cached data
std::string path = pDoc->getProperty("path");
std::string htmlLocalPath = pDoc->getProperty("htmlLocalPath");
if (htmlLocalPath.empty() && path.empty())
return;
r::exec::RFunction rFunction(".rs.rpc.clear_profile");
rFunction.addParam(path);
rFunction.addParam(htmlLocalPath);
Error error = rFunction.call();
if (error)
{
LOG_ERROR(error);
return;
}
}
Error initialize()
{
ExecBlock initBlock ;
source_database::events().onDocPendingRemove.connect(onDocPendingRemove);
initBlock.addFunctions()
(boost::bind(module_context::sourceModuleRFile, "SessionProfiler.R"))
(boost::bind(module_context::registerUriHandler, "/" kProfilesUrlPath "/", handleProfilerResReq));
RS_REGISTER_CALL_METHOD(rs_profilesPath, 0);
return initBlock.execute();
}
} // namespace profiler
} // namespace modules
} // namesapce session
} // namespace rstudio
<commit_msg>ensure system encoding for profiles cache dir<commit_after>/*
* SessionProfiler.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionProfiler.hpp"
#include <core/Exec.hpp>
#include <session/SessionModuleContext.hpp>
#include <core/Error.hpp>
#include <core/Exec.hpp>
#include <r/RSexp.hpp>
#include <r/RRoutines.hpp>
#include <r/RUtil.hpp>
#include <r/ROptions.hpp>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace profiler {
namespace {
#define kProfilesCacheDir "profiles-cache"
#define kProfilesUrlPath "profiles"
std::string profilesCacheDir()
{
return module_context::scopedScratchPath().childPath(kProfilesCacheDir)
.absolutePath();
}
SEXP rs_profilesPath()
{
r::sexp::Protect rProtect;
std::string cacheDir = core::string_utils::utf8ToSystem(profilesCacheDir());
return r::sexp::create(cacheDir, &rProtect);
}
} // anonymous namespace
void handleProfilerResReq(const http::Request& request,
http::Response* pResponse)
{
std::string resourceName = http::util::pathAfterPrefix(request, "/" kProfilesUrlPath "/");
core::FilePath profilesPath = core::FilePath(profilesCacheDir());
core::FilePath profileResource = profilesPath.childPath(resourceName);
pResponse->setCacheableFile(profileResource, request);
}
void onDocPendingRemove(
boost::shared_ptr<source_database::SourceDocument> pDoc)
{
// check to see if there is cached data
std::string path = pDoc->getProperty("path");
std::string htmlLocalPath = pDoc->getProperty("htmlLocalPath");
if (htmlLocalPath.empty() && path.empty())
return;
r::exec::RFunction rFunction(".rs.rpc.clear_profile");
rFunction.addParam(path);
rFunction.addParam(htmlLocalPath);
Error error = rFunction.call();
if (error)
{
LOG_ERROR(error);
return;
}
}
Error initialize()
{
ExecBlock initBlock ;
source_database::events().onDocPendingRemove.connect(onDocPendingRemove);
initBlock.addFunctions()
(boost::bind(module_context::sourceModuleRFile, "SessionProfiler.R"))
(boost::bind(module_context::registerUriHandler, "/" kProfilesUrlPath "/", handleProfilerResReq));
RS_REGISTER_CALL_METHOD(rs_profilesPath, 0);
return initBlock.execute();
}
} // namespace profiler
} // namespace modules
} // namesapce session
} // namespace rstudio
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007 MIPS Technologies, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Korey Sewell
*
*/
#include "config/the_isa.hh"
#include "cpu/inorder/resources/fetch_seq_unit.hh"
#include "cpu/inorder/resource_pool.hh"
#include "debug/InOrderFetchSeq.hh"
#include "debug/InOrderStall.hh"
using namespace std;
using namespace TheISA;
using namespace ThePipeline;
FetchSeqUnit::FetchSeqUnit(std::string res_name, int res_id, int res_width,
Cycles res_latency, InOrderCPU *_cpu,
ThePipeline::Params *params)
: Resource(res_name, res_id, res_width, res_latency, _cpu),
instSize(sizeof(MachInst))
{
for (ThreadID tid = 0; tid < ThePipeline::MaxThreads; tid++) {
pcValid[tid] = false;
pcBlockStage[tid] = 0;
//@todo: Use CPU's squashSeqNum here instead of maintaining our own
// state
squashSeqNum[tid] = (InstSeqNum)-1;
lastSquashCycle[tid] = 0;
}
}
FetchSeqUnit::~FetchSeqUnit()
{
delete [] resourceEvent;
}
void
FetchSeqUnit::init()
{
resourceEvent = new FetchSeqEvent[width];
for (int i = 0; i < width; i++) {
reqs[i] = new ResourceRequest(this);
}
initSlots();
}
void
FetchSeqUnit::execute(int slot_num)
{
ResourceRequest* fs_req = reqs[slot_num];
DynInstPtr inst = fs_req->inst;
ThreadID tid = inst->readTid();
int stage_num = fs_req->getStageNum();
if (inst->fault != NoFault) {
DPRINTF(InOrderFetchSeq,
"[tid:%i]: [sn:%i]: Detected %s fault @ %x. Forwarding to "
"next stage.\n", tid, inst->seqNum, inst->fault->name(),
inst->pcState());
fs_req->done();
return;
}
switch (fs_req->cmd)
{
case AssignNextPC:
{
DPRINTF(InOrderFetchSeq, "[tid:%i]: Current PC is %s\n", tid,
pc[tid]);
if (pcValid[tid]) {
inst->pcState(pc[tid]);
inst->setMemAddr(pc[tid].instAddr());
// Advance to next PC (typically PC + 4)
pc[tid].advance();
inst->setSeqNum(cpu->getAndIncrementInstSeq(tid));
DPRINTF(InOrderFetchSeq, "[tid:%i]: Assigning [sn:%i] to "
"PC %s\n", tid, inst->seqNum, inst->pcState());
fs_req->done();
} else {
DPRINTF(InOrderStall, "STALL: [tid:%i]: NPC not valid\n", tid);
fs_req->done(false);
}
}
break;
case UpdateTargetPC:
{
assert(!inst->isCondDelaySlot() &&
"Not Handling Conditional Delay Slot");
if (inst->isControl()) {
if (inst->isReturn() && !inst->predTaken()) {
// If it's a return, then we must wait for resolved address.
// The Predictor will mark a return a false as "not taken"
// if there is no RAS entry
DPRINTF(InOrderFetchSeq, "[tid:%d]: Setting block signal "
"for stage %i.\n",
tid, stage_num);
cpu->pipelineStage[stage_num]->
toPrevStages->stageBlock[stage_num][tid] = true;
pcValid[tid] = false;
pcBlockStage[tid] = stage_num;
} else if (inst->predTaken()) {
// Taken Control
inst->setSquashInfo(stage_num);
setupSquash(inst, stage_num, tid);
DPRINTF(InOrderFetchSeq, "[tid:%i] Setting up squash to "
"start from stage %i, after [sn:%i].\n",
tid, stage_num, inst->squashSeqNum);
}
} else {
DPRINTF(InOrderFetchSeq, "[tid:%i]: [sn:%i]: Ignoring branch "
"target update since then is not a control "
"instruction.\n", tid, inst->seqNum);
}
fs_req->done();
}
break;
default:
fatal("Unrecognized command to %s", resName);
}
}
void
FetchSeqUnit::squash(DynInstPtr inst, int squash_stage,
InstSeqNum squash_seq_num, ThreadID tid)
{
DPRINTF(InOrderFetchSeq, "[tid:%i]: Updating due to squash from %s (%s) "
"stage %i.\n", tid, inst->instName(), inst->pcState(),
squash_stage);
if (lastSquashCycle[tid] == curTick() &&
squashSeqNum[tid] <= squash_seq_num) {
DPRINTF(InOrderFetchSeq, "[tid:%i]: Ignoring squash from stage %i, "
"since there is an outstanding squash that is older.\n",
tid, squash_stage);
} else {
squashSeqNum[tid] = squash_seq_num;
lastSquashCycle[tid] = curTick();
if (inst->staticInst) {
if (inst->fault != NoFault) {
// A Trap Caused This Fault and will update the pc state
// when done trapping
DPRINTF(InOrderFetchSeq, "[tid:%i] Blocking due to fault @ "
"[sn:%i].%s %s \n", inst->seqNum,
inst->instName(), inst->pcState());
pcValid[tid] = false;
} else {
TheISA::PCState nextPC;
assert(inst->staticInst);
if (inst->isControl()) {
nextPC = inst->readPredTarg();
// If we are already fetching this PC then advance to next PC
// =======
// This should handle ISAs w/delay slots and annulled delay
// slots to figure out which is the next PC to fetch after
// a mispredict
DynInstPtr bdelay_inst = NULL;
ListIt bdelay_it;
if (inst->onInstList) {
bdelay_it = inst->getInstListIt();
bdelay_it++;
} else {
InstSeqNum branch_delay_num = inst->seqNum + 1;
bdelay_it = cpu->findInst(branch_delay_num, tid);
}
if (bdelay_it != cpu->instList[tid].end()) {
bdelay_inst = (*bdelay_it);
}
if (bdelay_inst) {
if (bdelay_inst->pc.instAddr() == nextPC.instAddr()) {
bdelay_inst->pc = nextPC;
advancePC(nextPC, inst->staticInst);
DPRINTF(InOrderFetchSeq, "Advanced PC to %s\n", nextPC);
}
}
} else {
nextPC = inst->pcState();
advancePC(nextPC, inst->staticInst);
}
DPRINTF(InOrderFetchSeq, "[tid:%i]: Setting PC to %s.\n",
tid, nextPC);
pc[tid] = nextPC;
// Unblock Any Stages Waiting for this information to be updated ...
if (!pcValid[tid]) {
DPRINTF(InOrderFetchSeq, "[tid:%d]: Setting unblock signal "
"for stage %i.\n",
tid, pcBlockStage[tid]);
// Need to use "fromNextStages" instead of "toPrevStages"
// because the timebuffer will have already have advanced
// in the tick function and this squash function will happen after
// the tick
cpu->pipelineStage[pcBlockStage[tid]]->
fromNextStages->stageUnblock[pcBlockStage[tid]][tid] = true;
}
pcValid[tid] = true;
}
}
}
Resource::squash(inst, squash_stage, squash_seq_num, tid);
}
FetchSeqUnit::FetchSeqEvent::FetchSeqEvent()
: ResourceEvent()
{ }
void
FetchSeqUnit::FetchSeqEvent::process()
{
FetchSeqUnit* fs_res = dynamic_cast<FetchSeqUnit*>(resource);
assert(fs_res);
for (int i = 0; i < MaxThreads; i++) {
fs_res->pc[i] = fs_res->cpu->pcState(i);
DPRINTF(InOrderFetchSeq, "[tid:%i]: Setting PC: %s.\n",
fs_res->pc[i]);
fs_res->pcValid[i] = true;
}
}
void
FetchSeqUnit::activateThread(ThreadID tid)
{
pcValid[tid] = true;
pc[tid] = cpu->pcState(tid);
cpu->fetchPriorityList.push_back(tid);
DPRINTF(InOrderFetchSeq, "[tid:%i]: Reading PC: %s.\n",
tid, pc[tid]);
}
void
FetchSeqUnit::deactivateThread(ThreadID tid)
{
pcValid[tid] = false;
pcBlockStage[tid] = 0;
squashSeqNum[tid] = (InstSeqNum)-1;
lastSquashCycle[tid] = 0;
list<ThreadID>::iterator thread_it = find(cpu->fetchPriorityList.begin(),
cpu->fetchPriorityList.end(),
tid);
if (thread_it != cpu->fetchPriorityList.end())
cpu->fetchPriorityList.erase(thread_it);
}
void
FetchSeqUnit::suspendThread(ThreadID tid)
{
deactivateThread(tid);
}
void
FetchSeqUnit::trap(Fault fault, ThreadID tid, DynInstPtr inst)
{
pcValid[tid] = true;
pc[tid] = cpu->pcState(tid);
DPRINTF(InOrderFetchSeq, "[tid:%i]: Trap updating to PC: "
"%s.\n", tid, pc[tid]);
}
void
FetchSeqUnit::updateAfterContextSwitch(DynInstPtr inst, ThreadID tid)
{
pcValid[tid] = true;
if (cpu->thread[tid]->lastGradIsBranch) {
/** This function assumes that the instruction causing the context
* switch was right after the branch. Thus, if it's not, then
* we are updating incorrectly here
*/
assert(cpu->nextInstAddr(tid) == inst->instAddr());
pc[tid] = cpu->thread[tid]->lastBranchPC;
} else {
pc[tid] = inst->pcState();
}
assert(inst->staticInst);
advancePC(pc[tid], inst->staticInst);
DPRINTF(InOrderFetchSeq, "[tid:%i]: Updating PCs due to Context Switch."
"Assigning PC: %s.\n", tid, pc[tid]);
}
<commit_msg>inorder cpu: add missing DPRINTF argument<commit_after>/*
* Copyright (c) 2007 MIPS Technologies, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Korey Sewell
*
*/
#include "config/the_isa.hh"
#include "cpu/inorder/resources/fetch_seq_unit.hh"
#include "cpu/inorder/resource_pool.hh"
#include "debug/InOrderFetchSeq.hh"
#include "debug/InOrderStall.hh"
using namespace std;
using namespace TheISA;
using namespace ThePipeline;
FetchSeqUnit::FetchSeqUnit(std::string res_name, int res_id, int res_width,
Cycles res_latency, InOrderCPU *_cpu,
ThePipeline::Params *params)
: Resource(res_name, res_id, res_width, res_latency, _cpu),
instSize(sizeof(MachInst))
{
for (ThreadID tid = 0; tid < ThePipeline::MaxThreads; tid++) {
pcValid[tid] = false;
pcBlockStage[tid] = 0;
//@todo: Use CPU's squashSeqNum here instead of maintaining our own
// state
squashSeqNum[tid] = (InstSeqNum)-1;
lastSquashCycle[tid] = 0;
}
}
FetchSeqUnit::~FetchSeqUnit()
{
delete [] resourceEvent;
}
void
FetchSeqUnit::init()
{
resourceEvent = new FetchSeqEvent[width];
for (int i = 0; i < width; i++) {
reqs[i] = new ResourceRequest(this);
}
initSlots();
}
void
FetchSeqUnit::execute(int slot_num)
{
ResourceRequest* fs_req = reqs[slot_num];
DynInstPtr inst = fs_req->inst;
ThreadID tid = inst->readTid();
int stage_num = fs_req->getStageNum();
if (inst->fault != NoFault) {
DPRINTF(InOrderFetchSeq,
"[tid:%i]: [sn:%i]: Detected %s fault @ %x. Forwarding to "
"next stage.\n", tid, inst->seqNum, inst->fault->name(),
inst->pcState());
fs_req->done();
return;
}
switch (fs_req->cmd)
{
case AssignNextPC:
{
DPRINTF(InOrderFetchSeq, "[tid:%i]: Current PC is %s\n", tid,
pc[tid]);
if (pcValid[tid]) {
inst->pcState(pc[tid]);
inst->setMemAddr(pc[tid].instAddr());
// Advance to next PC (typically PC + 4)
pc[tid].advance();
inst->setSeqNum(cpu->getAndIncrementInstSeq(tid));
DPRINTF(InOrderFetchSeq, "[tid:%i]: Assigning [sn:%i] to "
"PC %s\n", tid, inst->seqNum, inst->pcState());
fs_req->done();
} else {
DPRINTF(InOrderStall, "STALL: [tid:%i]: NPC not valid\n", tid);
fs_req->done(false);
}
}
break;
case UpdateTargetPC:
{
assert(!inst->isCondDelaySlot() &&
"Not Handling Conditional Delay Slot");
if (inst->isControl()) {
if (inst->isReturn() && !inst->predTaken()) {
// If it's a return, then we must wait for resolved address.
// The Predictor will mark a return a false as "not taken"
// if there is no RAS entry
DPRINTF(InOrderFetchSeq, "[tid:%d]: Setting block signal "
"for stage %i.\n",
tid, stage_num);
cpu->pipelineStage[stage_num]->
toPrevStages->stageBlock[stage_num][tid] = true;
pcValid[tid] = false;
pcBlockStage[tid] = stage_num;
} else if (inst->predTaken()) {
// Taken Control
inst->setSquashInfo(stage_num);
setupSquash(inst, stage_num, tid);
DPRINTF(InOrderFetchSeq, "[tid:%i] Setting up squash to "
"start from stage %i, after [sn:%i].\n",
tid, stage_num, inst->squashSeqNum);
}
} else {
DPRINTF(InOrderFetchSeq, "[tid:%i]: [sn:%i]: Ignoring branch "
"target update since then is not a control "
"instruction.\n", tid, inst->seqNum);
}
fs_req->done();
}
break;
default:
fatal("Unrecognized command to %s", resName);
}
}
void
FetchSeqUnit::squash(DynInstPtr inst, int squash_stage,
InstSeqNum squash_seq_num, ThreadID tid)
{
DPRINTF(InOrderFetchSeq, "[tid:%i]: Updating due to squash from %s (%s) "
"stage %i.\n", tid, inst->instName(), inst->pcState(),
squash_stage);
if (lastSquashCycle[tid] == curTick() &&
squashSeqNum[tid] <= squash_seq_num) {
DPRINTF(InOrderFetchSeq, "[tid:%i]: Ignoring squash from stage %i, "
"since there is an outstanding squash that is older.\n",
tid, squash_stage);
} else {
squashSeqNum[tid] = squash_seq_num;
lastSquashCycle[tid] = curTick();
if (inst->staticInst) {
if (inst->fault != NoFault) {
// A Trap Caused This Fault and will update the pc state
// when done trapping
DPRINTF(InOrderFetchSeq, "[tid:%i] Blocking due to fault @ "
"[sn:%i].%s %s \n", tid, inst->seqNum,
inst->instName(), inst->pcState());
pcValid[tid] = false;
} else {
TheISA::PCState nextPC;
assert(inst->staticInst);
if (inst->isControl()) {
nextPC = inst->readPredTarg();
// If we are already fetching this PC then advance to next PC
// =======
// This should handle ISAs w/delay slots and annulled delay
// slots to figure out which is the next PC to fetch after
// a mispredict
DynInstPtr bdelay_inst = NULL;
ListIt bdelay_it;
if (inst->onInstList) {
bdelay_it = inst->getInstListIt();
bdelay_it++;
} else {
InstSeqNum branch_delay_num = inst->seqNum + 1;
bdelay_it = cpu->findInst(branch_delay_num, tid);
}
if (bdelay_it != cpu->instList[tid].end()) {
bdelay_inst = (*bdelay_it);
}
if (bdelay_inst) {
if (bdelay_inst->pc.instAddr() == nextPC.instAddr()) {
bdelay_inst->pc = nextPC;
advancePC(nextPC, inst->staticInst);
DPRINTF(InOrderFetchSeq, "Advanced PC to %s\n", nextPC);
}
}
} else {
nextPC = inst->pcState();
advancePC(nextPC, inst->staticInst);
}
DPRINTF(InOrderFetchSeq, "[tid:%i]: Setting PC to %s.\n",
tid, nextPC);
pc[tid] = nextPC;
// Unblock Any Stages Waiting for this information to be updated ...
if (!pcValid[tid]) {
DPRINTF(InOrderFetchSeq, "[tid:%d]: Setting unblock signal "
"for stage %i.\n",
tid, pcBlockStage[tid]);
// Need to use "fromNextStages" instead of "toPrevStages"
// because the timebuffer will have already have advanced
// in the tick function and this squash function will happen after
// the tick
cpu->pipelineStage[pcBlockStage[tid]]->
fromNextStages->stageUnblock[pcBlockStage[tid]][tid] = true;
}
pcValid[tid] = true;
}
}
}
Resource::squash(inst, squash_stage, squash_seq_num, tid);
}
FetchSeqUnit::FetchSeqEvent::FetchSeqEvent()
: ResourceEvent()
{ }
void
FetchSeqUnit::FetchSeqEvent::process()
{
FetchSeqUnit* fs_res = dynamic_cast<FetchSeqUnit*>(resource);
assert(fs_res);
for (int i = 0; i < MaxThreads; i++) {
fs_res->pc[i] = fs_res->cpu->pcState(i);
DPRINTF(InOrderFetchSeq, "[tid:%i]: Setting PC: %s.\n",
fs_res->pc[i]);
fs_res->pcValid[i] = true;
}
}
void
FetchSeqUnit::activateThread(ThreadID tid)
{
pcValid[tid] = true;
pc[tid] = cpu->pcState(tid);
cpu->fetchPriorityList.push_back(tid);
DPRINTF(InOrderFetchSeq, "[tid:%i]: Reading PC: %s.\n",
tid, pc[tid]);
}
void
FetchSeqUnit::deactivateThread(ThreadID tid)
{
pcValid[tid] = false;
pcBlockStage[tid] = 0;
squashSeqNum[tid] = (InstSeqNum)-1;
lastSquashCycle[tid] = 0;
list<ThreadID>::iterator thread_it = find(cpu->fetchPriorityList.begin(),
cpu->fetchPriorityList.end(),
tid);
if (thread_it != cpu->fetchPriorityList.end())
cpu->fetchPriorityList.erase(thread_it);
}
void
FetchSeqUnit::suspendThread(ThreadID tid)
{
deactivateThread(tid);
}
void
FetchSeqUnit::trap(Fault fault, ThreadID tid, DynInstPtr inst)
{
pcValid[tid] = true;
pc[tid] = cpu->pcState(tid);
DPRINTF(InOrderFetchSeq, "[tid:%i]: Trap updating to PC: "
"%s.\n", tid, pc[tid]);
}
void
FetchSeqUnit::updateAfterContextSwitch(DynInstPtr inst, ThreadID tid)
{
pcValid[tid] = true;
if (cpu->thread[tid]->lastGradIsBranch) {
/** This function assumes that the instruction causing the context
* switch was right after the branch. Thus, if it's not, then
* we are updating incorrectly here
*/
assert(cpu->nextInstAddr(tid) == inst->instAddr());
pc[tid] = cpu->thread[tid]->lastBranchPC;
} else {
pc[tid] = inst->pcState();
}
assert(inst->staticInst);
advancePC(pc[tid], inst->staticInst);
DPRINTF(InOrderFetchSeq, "[tid:%i]: Updating PCs due to Context Switch."
"Assigning PC: %s.\n", tid, pc[tid]);
}
<|endoftext|> |
<commit_before>/*=========================================================================
Copyright (c) Kitware Inc.
All rights reserved.
=========================================================================*/
// .SECTION Description
// This program illustrates the use of various filters acting upon hyper
// tree grid data sets. It generates output files in VTK format.
//
// .SECTION Usage
// --branch-factor opt Branching factor of hyper tree grid
// --dimension opt Dimension of hyper tree grid
// --grid-size-X opt Size of hyper tree grid in X direction
// --grid-size-Y opt Size of hyper tree grid in Y direction
// --grid-size-Z opt Size of hyper tree grid in Z direction
// --max-level opt Maximum depth of hyper tree grid
// --skip-Axis-Cut Skip axis cut filter
// --skip-Contour Skip contour filter
// --skip-Cut Skip cut filter
// --skip-Geometry Skip geometry filter
// --skip-Shrink Skip shrink filter
//
// .SECTION Thanks
// This example was written by Philippe Pebay and Charles Law, Kitware 2012
// This work was supported in part by Commissariat a l'Energie Atomique (CEA/DIF)
#include "vtkHyperTreeGrid.h"
#include "vtkHyperTreeGridAxisCut.h"
#include "vtkHyperTreeGridSource.h"
#include "vtkHyperTreeGridGeometry.h"
#include "vtkContourFilter.h"
#include "vtkCutter.h"
#include "vtkDataSetWriter.h"
#include "vtkNew.h"
#include "vtkPlane.h"
#include "vtkPointData.h"
#include "vtkPolyDataWriter.h"
#include "vtkShrinkFilter.h"
#include "vtkUnstructuredGrid.h"
#include "vtkUnstructuredGridWriter.h"
#include "vtksys/CommandLineArguments.hxx"
int main( int argc, char* argv[] )
{
// Default parameters and options
int dim = 3;
int branch = 3;
int max = 3;
int nX = 3;
int nY = 4;
int nZ = 2;
bool skipAxisCut = false;
bool skipContour = false;
bool skipCut = false;
bool skipGeometry = false;
bool skipShrink = false;
// Initialize command line argument parser
vtksys::CommandLineArguments clArgs;
clArgs.Initialize( argc, argv );
clArgs.StoreUnusedArguments( false );
// Parse command line parameters and options
clArgs.AddArgument( "--dimension",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&dim, "Dimension of hyper tree grid" );
clArgs.AddArgument( "--branch-factor",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&branch, "Branching factor of hyper tree grid" );
clArgs.AddArgument( "--max-level",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&max, "Maximum depth of hyper tree grid" );
clArgs.AddArgument( "--grid-size-X",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&nX, "Size of hyper tree grid in X direction" );
clArgs.AddArgument( "--grid-size-Y",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&nY, "Size of hyper tree grid in Y direction" );
clArgs.AddArgument( "--grid-size-Z",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&nZ, "Size of hyper tree grid in Z direction" );
clArgs.AddArgument( "--skip-Axis-Cut",
vtksys::CommandLineArguments::NO_ARGUMENT,
&skipAxisCut, "Skip axis cut filter" );
clArgs.AddArgument( "--skip-Contour",
vtksys::CommandLineArguments::NO_ARGUMENT,
&skipAxisCut, "Skip contour filter" );
clArgs.AddArgument( "--skip-Cut",
vtksys::CommandLineArguments::NO_ARGUMENT,
&skipCut, "Skip cut filter" );
clArgs.AddArgument( "--skip-Geometry",
vtksys::CommandLineArguments::NO_ARGUMENT,
&skipGeometry, "Skip geometry filter" );
clArgs.AddArgument( "--skip-Shrink",
vtksys::CommandLineArguments::NO_ARGUMENT,
&skipShrink, "Skip shrink filter" );
// If incorrect arguments were provided, provide some help and terminate in error.
if ( ! clArgs.Parse() )
{
cerr << "Usage: "
<< clArgs.GetHelp()
<< "\n";
}
// Ensure that parsed dimensionality makes sense
if ( dim > 3 )
{
dim = 3;
}
else if ( dim < 1 )
{
dim = 1;
}
// Ensure that parsed branch factor makes sense
if ( branch > 3 )
{
branch = 3;
}
else if ( branch < 2 )
{
branch = 2;
}
// Ensure that parsed maximum level makes sense
if ( max < 1 )
{
max = 1;
}
// Ensure that parsed grid sizes make sense
if ( nX < 1 )
{
nX = 1;
}
if ( nY < 1 )
{
nY = 1;
}
if ( nZ < 1 )
{
nZ = 1;
}
// Ensure that parsed grid sizes are consistent with dimensionality
if ( dim < 3 )
{
nZ = 1;
if ( dim < 2 )
{
nY = 1;
}
}
// Create hyper tree grid source
vtkNew<vtkHyperTreeGridSource> fractal;
fractal->SetMaximumLevel( max );
fractal->DualOn();
if ( dim == 3 )
{
fractal->SetGridSize( nX, nY, nZ );
}
fractal->SetGridSize( nX, nY, nZ );
fractal->SetDimension( dim );
fractal->SetAxisBranchFactor( branch );
fractal->Update();
vtkHyperTreeGrid* htGrid = fractal->GetOutput();
cerr << " Number of hyper tree dual grid cells: "
<< htGrid->GetNumberOfCells()
<< endl;
if ( ! skipGeometry )
{
cerr << "# Geometry" << endl;
vtkNew<vtkHyperTreeGridGeometry> geometry;
geometry->SetInputConnection( fractal->GetOutputPort() );
vtkNew<vtkPolyDataWriter> writer4;
writer4->SetFileName( "./hyperTreeGridGeometry.vtk" );
writer4->SetInputConnection( geometry->GetOutputPort() );
writer4->Write();
cerr << " Number of surface cells: "
<< geometry->GetOutput()->GetNumberOfCells()
<< endl;
}
if ( ! skipContour )
{
cerr << "# Contour" << endl;
vtkNew<vtkContourFilter> contour;
contour->SetInputData( htGrid );
int nContours = 2;
double* range = htGrid->GetPointData()->GetScalars()->GetRange();
cerr << " Calculating "
<< nContours
<< " iso-contours across ["
<< range[0]
<< ", "
<< range[1]
<< "] range:"
<< endl;
contour->SetNumberOfContours( nContours );
double resolution = ( range[1] - range[0] ) / ( nContours + 1. );
double isovalue = resolution;
for ( int i = 0; i < nContours; ++ i, isovalue += resolution )
{
cerr << " Contour "
<< i
<< " at iso-value: "
<< isovalue
<< endl;
contour->SetValue( i, isovalue );
}
vtkNew<vtkPolyDataWriter> writer0;
writer0->SetFileName( "./hyperTreeGridContour.vtk" );
writer0->SetInputConnection( contour->GetOutputPort() );
writer0->Write();
cerr << " Number of cells in iso-contours: "
<< contour->GetOutput()->GetNumberOfCells()
<< endl;
}
if ( ! skipShrink )
{
cerr << "# Shrink" << endl;
vtkNew<vtkShrinkFilter> shrink;
shrink->SetInputData( htGrid );
shrink->SetShrinkFactor( 1. );
vtkNew<vtkUnstructuredGridWriter> writer1;
writer1->SetFileName( "./hyperTreeGridShrink.vtk" );
writer1->SetInputConnection( shrink->GetOutputPort() );
writer1->Write();
cerr << " Number of shrunk cells: "
<< shrink->GetOutput()->GetNumberOfCells()
<< endl;
}
if ( ! skipAxisCut )
{
// Axis-aligned cut works only in 3D for now
if ( dim == 3 )
{
cerr << "# HyperTreeGridAxisCut" << endl;
vtkNew<vtkHyperTreeGridAxisCut> axisCut;
axisCut->SetInputConnection( fractal->GetOutputPort() );
axisCut->SetPlaneNormalAxis( 2 );
axisCut->SetPlanePosition( .1 );
vtkNew<vtkPolyDataWriter> writer2;
writer2->SetFileName( "./hyperTreeGridAxisCut.vtk" );
writer2->SetInputConnection( axisCut->GetOutputPort() );
writer2->Write();
cerr << " Number of cells in axis cut: "
<< axisCut->GetOutput()->GetNumberOfCells()
<< endl;
}
}
if ( ! skipCut )
{
cerr << "# Cut" << endl;
vtkNew<vtkCutter> cut;
vtkNew<vtkPlane> plane;
plane->SetOrigin( .5, .5, .15 );
plane->SetNormal( 0, 0, 1 );
cut->SetInputData( htGrid );
cut->SetCutFunction( plane.GetPointer() );
vtkNew<vtkPolyDataWriter> writer3;
writer3->SetFileName( "./hyperTreeGridCut.vtk" );
writer3->SetInputConnection( cut->GetOutputPort() );
writer3->Write();
cerr << " Number of cells in generic cut: "
<< cut->GetOutput()->GetNumberOfCells()
<< endl;
}
return 0;
}
<commit_msg>Added option to specify number of contours. Fixed a bug.<commit_after>/*=========================================================================
Copyright (c) Kitware Inc.
All rights reserved.
=========================================================================*/
// .SECTION Description
// This program illustrates the use of various filters acting upon hyper
// tree grid data sets. It generates output files in VTK format.
//
// .SECTION Usage
// --branch-factor opt Branching factor of hyper tree grid
// --dimension opt Dimension of hyper tree grid
// --grid-size-X opt Size of hyper tree grid in X direction
// --grid-size-Y opt Size of hyper tree grid in Y direction
// --grid-size-Z opt Size of hyper tree grid in Z direction
// --max-level opt Maximum depth of hyper tree grid
// --contours Number of iso-contours to be calculated
// --skip-Axis-Cut Skip axis cut filter
// --skip-Contour Skip contour filter
// --skip-Cut Skip cut filter
// --skip-Geometry Skip geometry filter
// --skip-Shrink Skip shrink filter
//
// .SECTION Thanks
// This example was written by Philippe Pebay and Charles Law, Kitware 2012
// This work was supported in part by Commissariat a l'Energie Atomique (CEA/DIF)
#include "vtkHyperTreeGrid.h"
#include "vtkHyperTreeGridAxisCut.h"
#include "vtkHyperTreeGridSource.h"
#include "vtkHyperTreeGridGeometry.h"
#include "vtkContourFilter.h"
#include "vtkCutter.h"
#include "vtkDataSetWriter.h"
#include "vtkNew.h"
#include "vtkPlane.h"
#include "vtkPointData.h"
#include "vtkPolyDataWriter.h"
#include "vtkShrinkFilter.h"
#include "vtkUnstructuredGrid.h"
#include "vtkUnstructuredGridWriter.h"
#include "vtksys/CommandLineArguments.hxx"
int main( int argc, char* argv[] )
{
// Default parameters and options
int dim = 3;
int branch = 3;
int max = 3;
int nX = 3;
int nY = 4;
int nZ = 2;
int nContours = 2;
bool skipAxisCut = false;
bool skipContour = false;
bool skipCut = false;
bool skipGeometry = false;
bool skipShrink = false;
// Initialize command line argument parser
vtksys::CommandLineArguments clArgs;
clArgs.Initialize( argc, argv );
clArgs.StoreUnusedArguments( false );
// Parse command line parameters and options
clArgs.AddArgument( "--dimension",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&dim, "Dimension of hyper tree grid" );
clArgs.AddArgument( "--branch-factor",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&branch, "Branching factor of hyper tree grid" );
clArgs.AddArgument( "--max-level",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&max, "Maximum depth of hyper tree grid" );
clArgs.AddArgument( "--grid-size-X",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&nX, "Size of hyper tree grid in X direction" );
clArgs.AddArgument( "--grid-size-Y",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&nY, "Size of hyper tree grid in Y direction" );
clArgs.AddArgument( "--grid-size-Z",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&nZ, "Size of hyper tree grid in Z direction" );
clArgs.AddArgument( "--contours",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&nContours, "Number of iso-contours to be calculated" );
clArgs.AddArgument( "--skip-Axis-Cut",
vtksys::CommandLineArguments::NO_ARGUMENT,
&skipAxisCut, "Skip axis cut filter" );
clArgs.AddArgument( "--skip-Contour",
vtksys::CommandLineArguments::NO_ARGUMENT,
&skipContour, "Skip contour filter" );
clArgs.AddArgument( "--skip-Cut",
vtksys::CommandLineArguments::NO_ARGUMENT,
&skipCut, "Skip cut filter" );
clArgs.AddArgument( "--skip-Geometry",
vtksys::CommandLineArguments::NO_ARGUMENT,
&skipGeometry, "Skip geometry filter" );
clArgs.AddArgument( "--skip-Shrink",
vtksys::CommandLineArguments::NO_ARGUMENT,
&skipShrink, "Skip shrink filter" );
// If incorrect arguments were provided, provide some help and terminate in error.
if ( ! clArgs.Parse() )
{
cerr << "Usage: "
<< clArgs.GetHelp()
<< "\n";
}
// Ensure that parsed dimensionality makes sense
if ( dim > 3 )
{
dim = 3;
}
else if ( dim < 1 )
{
dim = 1;
}
// Ensure that parsed branch factor makes sense
if ( branch > 3 )
{
branch = 3;
}
else if ( branch < 2 )
{
branch = 2;
}
// Ensure that parsed maximum level makes sense
if ( max < 1 )
{
max = 1;
}
// Ensure that parsed grid sizes make sense
if ( nX < 1 )
{
nX = 1;
}
if ( nY < 1 )
{
nY = 1;
}
if ( nZ < 1 )
{
nZ = 1;
}
// Ensure that parsed grid sizes are consistent with dimensionality
if ( dim < 3 )
{
nZ = 1;
if ( dim < 2 )
{
nY = 1;
}
}
// Create hyper tree grid source
vtkNew<vtkHyperTreeGridSource> fractal;
fractal->SetMaximumLevel( max );
fractal->DualOn();
if ( dim == 3 )
{
fractal->SetGridSize( nX, nY, nZ );
}
fractal->SetGridSize( nX, nY, nZ );
fractal->SetDimension( dim );
fractal->SetAxisBranchFactor( branch );
fractal->Update();
vtkHyperTreeGrid* htGrid = fractal->GetOutput();
cerr << " Number of hyper tree dual grid cells: "
<< htGrid->GetNumberOfCells()
<< endl;
if ( ! skipGeometry )
{
cerr << "# Geometry" << endl;
vtkNew<vtkHyperTreeGridGeometry> geometry;
geometry->SetInputConnection( fractal->GetOutputPort() );
vtkNew<vtkPolyDataWriter> writer4;
writer4->SetFileName( "./hyperTreeGridGeometry.vtk" );
writer4->SetInputConnection( geometry->GetOutputPort() );
writer4->Write();
cerr << " Number of surface cells: "
<< geometry->GetOutput()->GetNumberOfCells()
<< endl;
}
if ( ! skipContour )
{
cerr << "# Contour" << endl;
vtkNew<vtkContourFilter> contour;
contour->SetInputData( htGrid );
double* range = htGrid->GetPointData()->GetScalars()->GetRange();
cerr << " Calculating "
<< nContours
<< " iso-contours across ["
<< range[0]
<< ", "
<< range[1]
<< "] range:"
<< endl;
contour->SetNumberOfContours( nContours );
double resolution = ( range[1] - range[0] ) / ( nContours + 1. );
double isovalue = resolution;
for ( int i = 0; i < nContours; ++ i, isovalue += resolution )
{
cerr << " Contour "
<< i
<< " at iso-value: "
<< isovalue
<< endl;
contour->SetValue( i, isovalue );
}
vtkNew<vtkPolyDataWriter> writer0;
writer0->SetFileName( "./hyperTreeGridContour.vtk" );
writer0->SetInputConnection( contour->GetOutputPort() );
writer0->Write();
cerr << " Number of cells in iso-contours: "
<< contour->GetOutput()->GetNumberOfCells()
<< endl;
}
if ( ! skipShrink )
{
cerr << "# Shrink" << endl;
vtkNew<vtkShrinkFilter> shrink;
shrink->SetInputData( htGrid );
shrink->SetShrinkFactor( 1. );
vtkNew<vtkUnstructuredGridWriter> writer1;
writer1->SetFileName( "./hyperTreeGridShrink.vtk" );
writer1->SetInputConnection( shrink->GetOutputPort() );
writer1->Write();
cerr << " Number of shrunk cells: "
<< shrink->GetOutput()->GetNumberOfCells()
<< endl;
}
if ( ! skipAxisCut )
{
// Axis-aligned cut works only in 3D for now
if ( dim == 3 )
{
cerr << "# HyperTreeGridAxisCut" << endl;
vtkNew<vtkHyperTreeGridAxisCut> axisCut;
axisCut->SetInputConnection( fractal->GetOutputPort() );
axisCut->SetPlaneNormalAxis( 2 );
axisCut->SetPlanePosition( .1 );
vtkNew<vtkPolyDataWriter> writer2;
writer2->SetFileName( "./hyperTreeGridAxisCut.vtk" );
writer2->SetInputConnection( axisCut->GetOutputPort() );
writer2->Write();
cerr << " Number of cells in axis cut: "
<< axisCut->GetOutput()->GetNumberOfCells()
<< endl;
}
}
if ( ! skipCut )
{
cerr << "# Cut" << endl;
vtkNew<vtkCutter> cut;
vtkNew<vtkPlane> plane;
plane->SetOrigin( .5, .5, .15 );
plane->SetNormal( 0, 0, 1 );
cut->SetInputData( htGrid );
cut->SetCutFunction( plane.GetPointer() );
vtkNew<vtkPolyDataWriter> writer3;
writer3->SetFileName( "./hyperTreeGridCut.vtk" );
writer3->SetInputConnection( cut->GetOutputPort() );
writer3->Write();
cerr << " Number of cells in generic cut: "
<< cut->GetOutput()->GetNumberOfCells()
<< endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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.
*/
# if defined(__APPLE__) || defined(__FreeBSD__)
# include "hpc_aio_provider.h"
# include <fcntl.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <aio.h>
# include <stdio.h>
# include "mix_all_io_looper.h"
# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "aio.provider.hpc"
namespace dsn { namespace tools {
struct posix_disk_aio_context : public disk_aio
{
struct aiocb cb;
aio_task* tsk;
hpc_aio_provider* this_;
utils::notify_event* evt;
error_code err;
uint32_t bytes;
};
#ifndef io_prep_pread
static inline void io_prep_pread(struct aiocb *iocb, int fd, void *buf, size_t count, long long offset)
{
memset(iocb, 0, sizeof(*iocb));
iocb->aio_fildes = fd;
iocb->aio_lio_opcode = LIO_READ;
iocb->aio_reqprio = 0;
iocb->aio_buf = buf;
iocb->aio_nbytes = count;
iocb->aio_offset = offset;
}
#endif
#ifndef io_prep_pwrite
static inline void io_prep_pwrite(struct aiocb *iocb, int fd, void *buf, size_t count, long long offset)
{
memset(iocb, 0, sizeof(*iocb));
iocb->aio_fildes = fd;
iocb->aio_lio_opcode = LIO_WRITE;
iocb->aio_reqprio = 0;
iocb->aio_buf = buf;
iocb->aio_nbytes = count;
iocb->aio_offset = offset;
}
#endif
hpc_aio_provider::hpc_aio_provider(disk_engine* disk, aio_provider* inner_provider)
: aio_provider(disk, inner_provider)
{
_callback = [this](
int native_error,
uint32_t io_size,
uintptr_t lolp_or_events
)
{
auto e = (struct kevent*)lolp_or_events;
auto io = (struct aiocb*)(e->ident);
complete_aio(io);
};
_looper = nullptr;
}
void hpc_aio_provider::start(io_modifer& ctx)
{
_looper = get_io_looper(node(), ctx.queue, ctx.mode);
}
hpc_aio_provider::~hpc_aio_provider()
{
}
dsn_handle_t hpc_aio_provider::open(const char* file_name, int oflag, int pmode)
{
// No need to bind handle since EVFILT_AIO is registered when aio_* is called.
return (dsn_handle_t)(uintptr_t)::open(file_name, (oflag | O_NONBLOCK), pmode);
}
error_code hpc_aio_provider::close(dsn_handle_t fh)
{
if (::close((int)(uintptr_t)(fh)) == 0)
{
return ERR_OK;
}
else
{
derror("close file failed, err = %s\n", strerror(errno));
return ERR_FILE_OPERATION_FAILED;
}
}
disk_aio* hpc_aio_provider::prepare_aio_context(aio_task* tsk)
{
auto r = new posix_disk_aio_context;
bzero((char*)&r->cb, sizeof(r->cb));
r->tsk = tsk;
r->evt = nullptr;
return r;
}
void hpc_aio_provider::aio(aio_task* aio_tsk)
{
auto err = aio_internal(aio_tsk, true);
err.end_tracking();
}
error_code hpc_aio_provider::aio_internal(aio_task* aio_tsk, bool async, /*out*/ uint32_t* pbytes /*= nullptr*/)
{
auto aio = (posix_disk_aio_context *)aio_tsk->aio();
int r;
aio->this_ = this;
// set up callback
aio->cb.aio_sigevent.sigev_notify = SIGEV_KEVENT;
aio->cb.aio_sigevent.sigev_notify_kqueue = (int)(uintptr_t)_looper->native_handle();
aio->cb.aio_sigevent.sigev_notify_kevent_flags = EV_CLEAR;
aio->cb.aio_sigevent.sigev_value.sival_ptr = &_callback;
if (!async)
{
aio->evt = new utils::notify_event();
aio->err = ERR_OK;
aio->bytes = 0;
}
switch (aio->type)
{
case AIO_Read:
io_prep_pread(&aio->cb, static_cast<int>((ssize_t)aio->file), aio->buffer, aio->buffer_size, aio->file_offset);
r = aio_read(&aio->cb);
break;
case AIO_Write:
io_prep_pwrite(&aio->cb, static_cast<int>((ssize_t)aio->file), aio->buffer, aio->buffer_size, aio->file_offset);
r = aio_write(&aio->cb);
break;
default:
dassert(false, "unknown aio type %u", static_cast<int>(aio->type));
break;
}
if (r != 0)
{
derror("file op failed, err = %d (%s). On FreeBSD, you may need to load"
" aio kernel module by running 'sudo kldload aio'.", errno, strerror(errno));
if (async)
{
complete_io(aio_tsk, ERR_FILE_OPERATION_FAILED, 0);
}
else
{
delete aio->evt;
aio->evt = nullptr;
}
return ERR_FILE_OPERATION_FAILED;
}
else
{
if (async)
{
return ERR_IO_PENDING;
}
else
{
aio->evt->wait();
delete aio->evt;
aio->evt = nullptr;
if (pbytes != nullptr)
{
*pbytes = aio->bytes;
}
return aio->err;
}
}
}
void hpc_aio_provider::complete_aio(struct aiocb* io)
{
posix_disk_aio_context* ctx = CONTAINING_RECORD(io, posix_disk_aio_context, cb);
error_code ec;
int bytes = 0;
int err = aio_error(&ctx->cb);
if (err != 0)
{
derror("aio error, err = %s", strerror(err));
ec = ERR_FILE_OPERATION_FAILED;
}
else
{
bytes = aio_return(&ctx->cb); // from e.g., read or write
dassert(bytes >= 0, "bytes = %d.", bytes);
ec = bytes > 0 ? ERR_OK : ERR_HANDLE_EOF;
}
if (!ctx->evt)
{
aio_task* aio(ctx->tsk);
ctx->this_->complete_io(aio, ec, bytes);
}
else
{
ctx->err = ec;
ctx->bytes = bytes;
ctx->evt->notify();
}
}
}} // end namespace dsn::tools
#endif
<commit_msg>Remove O_NONBLOCK when openning a file.<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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.
*/
# if defined(__APPLE__) || defined(__FreeBSD__)
# include "hpc_aio_provider.h"
# include <fcntl.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <aio.h>
# include <stdio.h>
# include "mix_all_io_looper.h"
# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "aio.provider.hpc"
namespace dsn { namespace tools {
struct posix_disk_aio_context : public disk_aio
{
struct aiocb cb;
aio_task* tsk;
hpc_aio_provider* this_;
utils::notify_event* evt;
error_code err;
uint32_t bytes;
};
#ifndef io_prep_pread
static inline void io_prep_pread(struct aiocb *iocb, int fd, void *buf, size_t count, long long offset)
{
memset(iocb, 0, sizeof(*iocb));
iocb->aio_fildes = fd;
iocb->aio_lio_opcode = LIO_READ;
iocb->aio_reqprio = 0;
iocb->aio_buf = buf;
iocb->aio_nbytes = count;
iocb->aio_offset = offset;
}
#endif
#ifndef io_prep_pwrite
static inline void io_prep_pwrite(struct aiocb *iocb, int fd, void *buf, size_t count, long long offset)
{
memset(iocb, 0, sizeof(*iocb));
iocb->aio_fildes = fd;
iocb->aio_lio_opcode = LIO_WRITE;
iocb->aio_reqprio = 0;
iocb->aio_buf = buf;
iocb->aio_nbytes = count;
iocb->aio_offset = offset;
}
#endif
hpc_aio_provider::hpc_aio_provider(disk_engine* disk, aio_provider* inner_provider)
: aio_provider(disk, inner_provider)
{
_callback = [this](
int native_error,
uint32_t io_size,
uintptr_t lolp_or_events
)
{
auto e = (struct kevent*)lolp_or_events;
auto io = (struct aiocb*)(e->ident);
complete_aio(io);
};
_looper = nullptr;
}
void hpc_aio_provider::start(io_modifer& ctx)
{
_looper = get_io_looper(node(), ctx.queue, ctx.mode);
}
hpc_aio_provider::~hpc_aio_provider()
{
}
dsn_handle_t hpc_aio_provider::open(const char* file_name, int oflag, int pmode)
{
// No need to bind handle since EVFILT_AIO is registered when aio_* is called.
return (dsn_handle_t)(uintptr_t)::open(file_name, oflag, pmode);
}
error_code hpc_aio_provider::close(dsn_handle_t fh)
{
if (::close((int)(uintptr_t)(fh)) == 0)
{
return ERR_OK;
}
else
{
derror("close file failed, err = %s\n", strerror(errno));
return ERR_FILE_OPERATION_FAILED;
}
}
disk_aio* hpc_aio_provider::prepare_aio_context(aio_task* tsk)
{
auto r = new posix_disk_aio_context;
bzero((char*)&r->cb, sizeof(r->cb));
r->tsk = tsk;
r->evt = nullptr;
return r;
}
void hpc_aio_provider::aio(aio_task* aio_tsk)
{
auto err = aio_internal(aio_tsk, true);
err.end_tracking();
}
error_code hpc_aio_provider::aio_internal(aio_task* aio_tsk, bool async, /*out*/ uint32_t* pbytes /*= nullptr*/)
{
auto aio = (posix_disk_aio_context *)aio_tsk->aio();
int r;
aio->this_ = this;
// set up callback
aio->cb.aio_sigevent.sigev_notify = SIGEV_KEVENT;
aio->cb.aio_sigevent.sigev_notify_kqueue = (int)(uintptr_t)_looper->native_handle();
aio->cb.aio_sigevent.sigev_notify_kevent_flags = EV_CLEAR;
aio->cb.aio_sigevent.sigev_value.sival_ptr = &_callback;
if (!async)
{
aio->evt = new utils::notify_event();
aio->err = ERR_OK;
aio->bytes = 0;
}
switch (aio->type)
{
case AIO_Read:
io_prep_pread(&aio->cb, static_cast<int>((ssize_t)aio->file), aio->buffer, aio->buffer_size, aio->file_offset);
r = aio_read(&aio->cb);
break;
case AIO_Write:
io_prep_pwrite(&aio->cb, static_cast<int>((ssize_t)aio->file), aio->buffer, aio->buffer_size, aio->file_offset);
r = aio_write(&aio->cb);
break;
default:
dassert(false, "unknown aio type %u", static_cast<int>(aio->type));
break;
}
if (r != 0)
{
derror("file op failed, err = %d (%s). On FreeBSD, you may need to load"
" aio kernel module by running 'sudo kldload aio'.", errno, strerror(errno));
if (async)
{
complete_io(aio_tsk, ERR_FILE_OPERATION_FAILED, 0);
}
else
{
delete aio->evt;
aio->evt = nullptr;
}
return ERR_FILE_OPERATION_FAILED;
}
else
{
if (async)
{
return ERR_IO_PENDING;
}
else
{
aio->evt->wait();
delete aio->evt;
aio->evt = nullptr;
if (pbytes != nullptr)
{
*pbytes = aio->bytes;
}
return aio->err;
}
}
}
void hpc_aio_provider::complete_aio(struct aiocb* io)
{
posix_disk_aio_context* ctx = CONTAINING_RECORD(io, posix_disk_aio_context, cb);
error_code ec;
int bytes = 0;
int err = aio_error(&ctx->cb);
if (err != 0)
{
derror("aio error, err = %s", strerror(err));
ec = ERR_FILE_OPERATION_FAILED;
}
else
{
bytes = aio_return(&ctx->cb); // from e.g., read or write
dassert(bytes >= 0, "bytes = %d.", bytes);
ec = bytes > 0 ? ERR_OK : ERR_HANDLE_EOF;
}
if (!ctx->evt)
{
aio_task* aio(ctx->tsk);
ctx->this_->complete_io(aio, ec, bytes);
}
else
{
ctx->err = ec;
ctx->bytes = bytes;
ctx->evt->notify();
}
}
}} // end namespace dsn::tools
#endif
<|endoftext|> |
<commit_before><commit_msg>Fix for Qt event freeze problem on Windows <commit_after><|endoftext|> |
<commit_before>// Part of Arac Neural Network Composition Library.
// (c) 2008 by Justin S Bayer, <bayer.justin@googlemail.com>
#ifndef ARAC_MDRNN_C
#define ARAC_MDRNN_C
#include <iostream>
#include <cstring>
#include "mdrnn.h"
using arac::structure::Component;
using arac::structure::connections::FullConnection;
using arac::structure::networks::mdrnns::Mdrnn;
template <class module_type>
Mdrnn<module_type>::Mdrnn(int timedim, int hiddensize) :
BaseMdrnn(timedim),
_hiddensize(hiddensize),
_module_p(0)
{
_sequence_shape_p = new int[_timedim];
_block_shape_p = new int[_timedim];
_multiplied_sizes_p = new int[_timedim];
for(int i = 0; i < _timedim; i++)
{
// We cannot use the setters here, because they invoke the recalculation
// which results in undefined behaviour.
_sequence_shape_p[i] = 1;
_block_shape_p[i] = 1;
}
update_sizes();
}
template <class module_type>
Mdrnn<module_type>::~Mdrnn()
{
delete[] _sequence_shape_p;
delete[] _block_shape_p;
delete _module_p;
std::vector<FullConnection*>::iterator con_iter;
for(con_iter = _connections.begin();
con_iter != _connections.end();
con_iter++)
{
delete *con_iter;
}
}
template <class module_type>
void
Mdrnn<module_type>::init_multiplied_sizes()
{
int size = 1;
for(int i = 0; i < _timedim; i++)
{
_multiplied_sizes_p[i] = size;
size *= _sequence_shape_p[i];
}
}
template <class module_type>
void
Mdrnn<module_type>::update_sizes()
{
_blocksize = 1;
for (int i = 0; i < _timedim; i++)
{
_blocksize *= _block_shape_p[i];
}
assert(_blocksize > 0);
_sequencelength = 1;
for (int i = 0; i < _timedim; i++)
{
_sequencelength *= _sequence_shape_p[i];
}
_sequencelength /= _blocksize;
_insize = _sequencelength * _blocksize;
_outsize = _sequencelength * _hiddensize;
}
template <class module_type>
void
Mdrnn<module_type>::sort()
{
// Initialize multilied sizes.
init_multiplied_sizes();
update_sizes();
// Initialize module.
if (_module_p != 0)
{
delete _module_p;
}
_module_p = new module_type(_hiddensize);
_module_p->set_mode(Component::Sequential);
// Delete connections from previous sortings.
std::vector<FullConnection*>::iterator con_iter;
for (con_iter = _connections.begin();
con_iter != _connections.end();
con_iter++)
{
delete (*con_iter);
}
_connections.clear();
// Also clear the parametrized vector.
_parametrizeds.clear();
// Initialize recurrent self connections.
int recurrency = 1;
for(int i = 0; i < _timedim; i++)
{
FullConnection* con_p = new FullConnection(_module_p, _module_p);
con_p->set_mode(Component::Sequential);
con_p->set_recurrent(recurrency);
recurrency *= _sequence_shape_p[i] / _block_shape_p[i];
_connections.push_back(con_p);
_parametrizeds.push_back(con_p);
}
// Add a connection from the bias.
FullConnection* con_p = new FullConnection(&_bias, _module_p);
_parametrizeds.push_back(con_p);
_connections.push_back(con_p);
// Ininitialize buffers.
init_buffers();
// Indicate that the net is ready for use.
_dirty = false;
}
template <class module_type>
void
Mdrnn<module_type>::clear()
{
BaseMdrnn::clear();
_module_p->clear();
}
template <class module_type>
void
Mdrnn<module_type>::clear_derivatives()
{
std::vector<FullConnection*>::iterator coniter;
for (coniter = _connections.begin();
coniter != _connections.end();
coniter++)
{
(*coniter)->clear_derivatives();
}
}
template <class module_type>
void
Mdrnn<module_type>::_forward()
{
// We keep the coordinates of the current block in here.
double* coords_p = new double[_timedim];
// TODO: save memory by not copying but referencing.
for(int i = 0; i < sequencelength(); i++)
{
std::vector<FullConnection*>::iterator con_iter;
int j = 0;
for(con_iter = _connections.begin();
con_iter != _connections.end();
con_iter++)
{
// If the current coordinate is zero, we are at a border of the
// input in that dimension. In that case, the connections may not be
// forwarded, since we don't want to look around corners.
if (coords_p[j] == 0)
{
(*con_iter)->dry_forward();
}
else
{
(*con_iter)->forward();
}
j++;
}
_module_p->add_to_input(input()[timestep()] + blocksize() * i);
_module_p->forward();
next_coords(coords_p);
}
// Copy the output to the mdrnns outputbuffer.
// TODO: save memory by not copying but referencing.
std::vector<double*>::iterator dblp_iter;
for(int i = 0; i < sequencelength(); i++)
{
memcpy(output()[timestep()] + i * _hiddensize,
_module_p->output()[i],
_hiddensize * sizeof(double));
}
}
template <class module_type>
void
Mdrnn<module_type>::_backward()
{
// We keep the coordinates of the current block in here.
double* coords_p = new double[_timedim];
memset(coords_p, 0, sizeof(double) * _timedim);
// TODO: save memory by not copying but referencing.
for(int i = sequencelength() - 1; i >= 0; i--)
{
std::vector<FullConnection*>::iterator con_iter;
int j = 0;
for(con_iter = _connections.begin();
// All but the bias connection.
con_iter < _connections.end();
con_iter++, j++)
{
// std::cout << coords_p[j] << " ";
// If the current coordinate is zero, we are at a border of the
// input in that dimension. In that case, the connections may not be
// forwarded, since we don't want to look around corners.
if (coords_p[j] == 0)
{
(*con_iter)->dry_backward();
}
else
{
(*con_iter)->backward();
}
}
// Bias connection is always backwarded.
_connections.back()->backward();
_module_p->add_to_outerror(outerror()[timestep() - 1] + i);
_module_p->backward();
next_coords(coords_p);
}
// Copy the output to the mdrnns outputbuffer.
// TODO: save memory by not copying but referencing.
for(int i = 0; i < sequencelength(); i++)
{
memcpy(inerror()[timestep() - 1] + i * blocksize(),
_module_p->outerror()[i],
blocksize() * sizeof(double));
}
}
#endif<commit_msg>Fixed a bug: Mdrnns did not clear their connections and its bias, which made them crash if .activate() was called multiple times withouth .back_activate() in between.<commit_after>// Part of Arac Neural Network Composition Library.
// (c) 2008 by Justin S Bayer, <bayer.justin@googlemail.com>
#ifndef ARAC_MDRNN_C
#define ARAC_MDRNN_C
#include <iostream>
#include <cstring>
#include "mdrnn.h"
using arac::structure::Component;
using arac::structure::connections::FullConnection;
using arac::structure::networks::mdrnns::Mdrnn;
template <class module_type>
Mdrnn<module_type>::Mdrnn(int timedim, int hiddensize) :
BaseMdrnn(timedim),
_hiddensize(hiddensize),
_module_p(0)
{
_sequence_shape_p = new int[_timedim];
_block_shape_p = new int[_timedim];
_multiplied_sizes_p = new int[_timedim];
for(int i = 0; i < _timedim; i++)
{
// We cannot use the setters here, because they invoke the recalculation
// which results in undefined behaviour.
_sequence_shape_p[i] = 1;
_block_shape_p[i] = 1;
}
update_sizes();
}
template <class module_type>
Mdrnn<module_type>::~Mdrnn()
{
delete[] _sequence_shape_p;
delete[] _block_shape_p;
delete _module_p;
std::vector<FullConnection*>::iterator con_iter;
for(con_iter = _connections.begin();
con_iter != _connections.end();
con_iter++)
{
delete *con_iter;
}
}
template <class module_type>
void
Mdrnn<module_type>::init_multiplied_sizes()
{
int size = 1;
for(int i = 0; i < _timedim; i++)
{
_multiplied_sizes_p[i] = size;
size *= _sequence_shape_p[i];
}
}
template <class module_type>
void
Mdrnn<module_type>::update_sizes()
{
_blocksize = 1;
for (int i = 0; i < _timedim; i++)
{
_blocksize *= _block_shape_p[i];
}
assert(_blocksize > 0);
_sequencelength = 1;
for (int i = 0; i < _timedim; i++)
{
_sequencelength *= _sequence_shape_p[i];
}
_sequencelength /= _blocksize;
_insize = _sequencelength * _blocksize;
_outsize = _sequencelength * _hiddensize;
}
template <class module_type>
void
Mdrnn<module_type>::sort()
{
// Initialize multilied sizes.
init_multiplied_sizes();
update_sizes();
// Initialize module.
if (_module_p != 0)
{
delete _module_p;
}
_module_p = new module_type(_hiddensize);
_module_p->set_mode(Component::Sequential);
// Delete connections from previous sortings.
std::vector<FullConnection*>::iterator con_iter;
for (con_iter = _connections.begin();
con_iter != _connections.end();
con_iter++)
{
delete (*con_iter);
}
_connections.clear();
// Also clear the parametrized vector.
_parametrizeds.clear();
// Initialize recurrent self connections.
int recurrency = 1;
for(int i = 0; i < _timedim; i++)
{
FullConnection* con_p = new FullConnection(_module_p, _module_p);
con_p->set_mode(Component::Sequential);
con_p->set_recurrent(recurrency);
recurrency *= _sequence_shape_p[i] / _block_shape_p[i];
_connections.push_back(con_p);
_parametrizeds.push_back(con_p);
}
// Add a connection from the bias.
FullConnection* con_p = new FullConnection(&_bias, _module_p);
_parametrizeds.push_back(con_p);
_connections.push_back(con_p);
// Ininitialize buffers.
init_buffers();
// Indicate that the net is ready for use.
_dirty = false;
}
template <class module_type>
void
Mdrnn<module_type>::clear()
{
BaseMdrnn::clear();
_module_p->clear();
_bias.clear();
std::vector<FullConnection*>::iterator coniter;
for (coniter = _connections.begin();
coniter != _connections.end();
coniter++)
{
(*coniter)->clear();
}
}
template <class module_type>
void
Mdrnn<module_type>::clear_derivatives()
{
std::vector<FullConnection*>::iterator coniter;
for (coniter = _connections.begin();
coniter != _connections.end();
coniter++)
{
(*coniter)->clear_derivatives();
}
}
template <class module_type>
void
Mdrnn<module_type>::_forward()
{
// We keep the coordinates of the current block in here.
double* coords_p = new double[_timedim];
// TODO: save memory by not copying but referencing.
for(int i = 0; i < sequencelength(); i++)
{
std::vector<FullConnection*>::iterator con_iter;
int j = 0;
for(con_iter = _connections.begin();
con_iter != _connections.end();
con_iter++)
{
// If the current coordinate is zero, we are at a border of the
// input in that dimension. In that case, the connections may not be
// forwarded, since we don't want to look around corners.
if (coords_p[j] == 0)
{
(*con_iter)->dry_forward();
}
else
{
(*con_iter)->forward();
}
j++;
}
_module_p->add_to_input(input()[timestep()] + blocksize() * i);
_module_p->forward();
next_coords(coords_p);
}
// Copy the output to the mdrnns outputbuffer.
// TODO: save memory by not copying but referencing.
std::vector<double*>::iterator dblp_iter;
for(int i = 0; i < sequencelength(); i++)
{
memcpy(output()[timestep()] + i * _hiddensize,
_module_p->output()[i],
_hiddensize * sizeof(double));
}
}
template <class module_type>
void
Mdrnn<module_type>::_backward()
{
// We keep the coordinates of the current block in here.
double* coords_p = new double[_timedim];
memset(coords_p, 0, sizeof(double) * _timedim);
// TODO: save memory by not copying but referencing.
for(int i = sequencelength() - 1; i >= 0; i--)
{
std::vector<FullConnection*>::iterator con_iter;
int j = 0;
for(con_iter = _connections.begin();
// All but the bias connection.
con_iter < _connections.end();
con_iter++, j++)
{
// std::cout << coords_p[j] << " ";
// If the current coordinate is zero, we are at a border of the
// input in that dimension. In that case, the connections may not be
// forwarded, since we don't want to look around corners.
if (coords_p[j] == 0)
{
(*con_iter)->dry_backward();
}
else
{
(*con_iter)->backward();
}
}
// Bias connection is always backwarded.
_connections.back()->backward();
_module_p->add_to_outerror(outerror()[timestep() - 1] + i);
_module_p->backward();
next_coords(coords_p);
}
// Copy the output to the mdrnns outputbuffer.
// TODO: save memory by not copying but referencing.
for(int i = 0; i < sequencelength(); i++)
{
memcpy(inerror()[timestep() - 1] + i * blocksize(),
_module_p->outerror()[i],
blocksize() * sizeof(double));
}
}
#endif<|endoftext|> |
<commit_before>#ifndef __ZOMBYE_SCRIPTING_SYSTEM_HPP__
#define __ZOMBYE_SCRIPTING_SYSTEM_HPP__
#include <memory>
#include <angelscript.h>
#include <scriptbuilder/scriptbuilder.h>
namespace zombye {
class game;
}
namespace zombye {
class scripting_system {
private:
game& game_;
std::unique_ptr<asIScriptEngine, void(*)(asIScriptEngine*)> script_engine_;
std::unique_ptr<asIScriptContext, void(*)(asIScriptContext*)> script_context_;
std::unique_ptr<CScriptBuilder> script_builder_;
public:
scripting_system(game& game);
~scripting_system() = default;
scripting_system(const scripting_system& rhs) = delete;
scripting_system& operator=(const scripting_system& rhs) = delete;
scripting_system(scripting_system&& rhs) = delete;
scripting_system& operator=(scripting_system&& rhs) = delete;
void begin_module(const std::string& module_name);
void load_script(const std::string& file_name);
void end_module();
void exec(const std::string& function_decl, const std::string& module_name);
};
}
#endif
<commit_msg>add function for registering free functions<commit_after>#ifndef __ZOMBYE_SCRIPTING_SYSTEM_HPP__
#define __ZOMBYE_SCRIPTING_SYSTEM_HPP__
#include <memory>
#include <angelscript.h>
#include <scriptbuilder/scriptbuilder.h>
namespace zombye {
class game;
}
namespace zombye {
class scripting_system {
private:
game& game_;
std::unique_ptr<asIScriptEngine, void(*)(asIScriptEngine*)> script_engine_;
std::unique_ptr<asIScriptContext, void(*)(asIScriptContext*)> script_context_;
std::unique_ptr<CScriptBuilder> script_builder_;
public:
scripting_system(game& game);
~scripting_system() = default;
scripting_system(const scripting_system& rhs) = delete;
scripting_system& operator=(const scripting_system& rhs) = delete;
scripting_system(scripting_system&& rhs) = delete;
scripting_system& operator=(scripting_system&& rhs) = delete;
void begin_module(const std::string& module_name);
void load_script(const std::string& file_name);
void end_module();
void exec(const std::string& function_decl, const std::string& module_name);
template<typename t>
void register_function(const std::string function_decl, const t& function) {
auto result = script_engine_->RegisterGlobalFunction(function_decl.c_str(), asFUNCTION(function), asCALL_CDECL);
if (result < 0) {
throw std::runtime_error("Could not register function " + function_decl);
}
}
};
}
#endif
<|endoftext|> |
<commit_before>#include "package_manager/ostreemanager.h"
#include <stdio.h>
#include <unistd.h>
#include <fstream>
#include <gio/gio.h>
#include <json/json.h>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/filesystem.hpp>
#include <ostree-1/ostree-async-progress.h>
#include <utility>
#include "logging/logging.h"
#include "utilities/utils.h"
using OstreeProgressPtr = std::unique_ptr<OstreeAsyncProgress, GObjectFinalizer<OstreeAsyncProgress>>;
static void aktualizr_progress_cb(OstreeAsyncProgress *progress, gpointer data)
{
auto *percent_complete = static_cast<guint*>(data);
g_autofree char *status = ostree_async_progress_get_status(progress);
guint scanning = ostree_async_progress_get_uint(progress, "scanning");
guint outstanding_fetches = ostree_async_progress_get_uint(progress, "outstanding-fetches");
guint outstanding_metadata_fetches = ostree_async_progress_get_uint(progress, "outstanding-metadata-fetches");
guint outstanding_writes = ostree_async_progress_get_uint(progress, "outstanding-writes");
guint n_scanned_metadata = ostree_async_progress_get_uint(progress, "scanned-metadata");
if (status != nullptr && *status != '\0') {
LOG_INFO << "ostree-pull: " << status;
}
else if (outstanding_fetches != 0) {
float fetched = ostree_async_progress_get_uint(progress, "fetched");
guint metadata_fetched = ostree_async_progress_get_uint(progress, "metadata-fetched");
guint requested = ostree_async_progress_get_uint(progress, "requested");
if (scanning != 0 || outstanding_metadata_fetches != 0) {
LOG_INFO << "ostree-pull: Receiving metadata objects: " << metadata_fetched << " outstanding: " << outstanding_metadata_fetches;
} else {
guint calculated = round(((fetched) / requested) * 100);
if (calculated != *percent_complete) {
LOG_INFO << "ostree-pull: Receiving objects: " << calculated << "% ";
*percent_complete = calculated;
}
}
}
else if (outstanding_writes != 0) {
LOG_INFO << "ostree-pull: Writing objects: " << outstanding_writes;
}
else {
LOG_INFO << "ostree-pull: Scanning metadata: " << n_scanned_metadata;
}
}
data::InstallOutcome OstreeManager::pull(const boost::filesystem::path &sysroot_path, const std::string &ostree_server,
const KeyManager &keys, const std::string &refhash) {
const char *const commit_ids[] = {refhash.c_str()};
GCancellable *cancellable = nullptr;
GError *error = nullptr;
GVariantBuilder builder;
GVariant *options;
OstreeProgressPtr progress = nullptr;
guint percent_complete = 0;
OstreeSysrootPtr sysroot = OstreeManager::LoadSysroot(sysroot_path);
OstreeRepoPtr repo = LoadRepo(sysroot.get(), &error);
if (error != nullptr) {
LOG_ERROR << "Could not get OSTree repo";
g_error_free(error);
return data::InstallOutcome(data::INSTALL_FAILED, "Could not get OSTree repo");
}
GHashTable *ref_list = nullptr;
if (ostree_repo_list_commit_objects_starting_with(repo.get(), refhash.c_str(), &ref_list, nullptr, &error) != 0) {
guint length = g_hash_table_size(ref_list);
g_hash_table_destroy(ref_list); // OSTree creates the table with destroy notifiers, so no memory leaks expected
// should never be greater than 1, but use >= for robustness
if (length >= 1) {
LOG_DEBUG << "refhash already pulled";
return data::InstallOutcome(data::ALREADY_PROCESSED, "Refhash was already pulled");
}
}
if (error != nullptr) {
g_error_free(error);
error = nullptr;
}
if (!OstreeManager::addRemote(repo.get(), ostree_server, keys)) {
return data::InstallOutcome(data::INSTALL_FAILED, "Error adding OSTree remote");
}
g_variant_builder_init(&builder, G_VARIANT_TYPE("a{sv}"));
g_variant_builder_add(&builder, "{s@v}", "flags", g_variant_new_variant(g_variant_new_int32(0)));
g_variant_builder_add(&builder, "{s@v}", "refs", g_variant_new_variant(g_variant_new_strv(commit_ids, 1)));
options = g_variant_builder_end(&builder);
progress.reset(ostree_async_progress_new_and_connect(aktualizr_progress_cb, &percent_complete));
if (ostree_repo_pull_with_options(repo.get(), remote, options, progress.get(), cancellable, &error) == 0) {
LOG_ERROR << "Error of pulling image: " << error->message;
data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message);
g_error_free(error);
g_variant_unref(options);
return install_outcome;
}
ostree_async_progress_finish(progress.get());
g_variant_unref(options);
return data::InstallOutcome(data::OK, "Pulling ostree image was successful");
}
data::InstallOutcome OstreeManager::install(const Uptane::Target &target) const {
const char *opt_osname = nullptr;
GCancellable *cancellable = nullptr;
GError *error = nullptr;
char *revision;
if (config.os.size() != 0u) {
opt_osname = config.os.c_str();
}
OstreeSysrootPtr sysroot = OstreeManager::LoadSysroot(config.sysroot);
OstreeRepoPtr repo = LoadRepo(sysroot.get(), &error);
if (error != nullptr) {
LOG_ERROR << "could not get repo";
g_error_free(error);
return data::InstallOutcome(data::INSTALL_FAILED, "could not get repo");
}
auto origin = StructGuard<GKeyFile>(
ostree_sysroot_origin_new_from_refspec(sysroot.get(), target.sha256Hash().c_str()), g_key_file_free);
if (ostree_repo_resolve_rev(repo.get(), target.sha256Hash().c_str(), FALSE, &revision, &error) == 0) {
LOG_ERROR << error->message;
data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message);
g_error_free(error);
return install_outcome;
}
OstreeDeployment *merge_deployment = ostree_sysroot_get_merge_deployment(sysroot.get(), opt_osname);
if (merge_deployment == nullptr) {
LOG_ERROR << "No merge deployment";
return data::InstallOutcome(data::INSTALL_FAILED, "No merge deployment");
}
if (ostree_sysroot_prepare_cleanup(sysroot.get(), cancellable, &error) == 0) {
LOG_ERROR << error->message;
data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message);
g_error_free(error);
return install_outcome;
}
std::string args_content =
std::string(ostree_bootconfig_parser_get(ostree_deployment_get_bootconfig(merge_deployment), "options"));
std::vector<std::string> args_vector;
boost::split(args_vector, args_content, boost::is_any_of(" "));
std::vector<const char *> kargs_strv_vector;
kargs_strv_vector.reserve(args_vector.size() + 1);
for (auto it = args_vector.begin(); it != args_vector.end(); ++it) {
kargs_strv_vector.push_back((*it).c_str());
}
kargs_strv_vector[args_vector.size()] = nullptr;
auto kargs_strv = const_cast<char **>(&kargs_strv_vector[0]);
OstreeDeployment *new_deployment = nullptr;
if (ostree_sysroot_deploy_tree(sysroot.get(), opt_osname, revision, origin.get(), merge_deployment, kargs_strv,
&new_deployment, cancellable, &error) == 0) {
LOG_ERROR << "ostree_sysroot_deploy_tree: " << error->message;
data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message);
g_error_free(error);
return install_outcome;
}
if (ostree_sysroot_simple_write_deployment(sysroot.get(), nullptr, new_deployment, merge_deployment,
OSTREE_SYSROOT_SIMPLE_WRITE_DEPLOYMENT_FLAGS_NONE, cancellable,
&error) == 0) {
LOG_ERROR << "ostree_sysroot_simple_write_deployment:" << error->message;
data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message);
g_error_free(error);
return install_outcome;
}
LOG_INFO << "Performing sync()";
sync();
return data::InstallOutcome(data::OK, "Installation successful");
}
OstreeManager::OstreeManager(PackageConfig pconfig, std::shared_ptr<INvStorage> storage)
: config(std::move(pconfig)), storage_(std::move(storage)) {
try {
OstreeManager::getCurrent();
} catch (...) {
throw std::runtime_error("Could not find OSTree sysroot at: " + config.sysroot.string());
}
}
Json::Value OstreeManager::getInstalledPackages() {
std::string packages_str = Utils::readFile(config.packages_file);
std::vector<std::string> package_lines;
boost::split(package_lines, packages_str, boost::is_any_of("\n"));
Json::Value packages(Json::arrayValue);
for (auto it = package_lines.begin(); it != package_lines.end(); ++it) {
if (it->empty()) {
continue;
}
size_t pos = it->find(" ");
if (pos == std::string::npos) {
throw std::runtime_error("Wrong packages file format");
}
Json::Value package;
package["name"] = it->substr(0, pos);
package["version"] = it->substr(pos + 1);
packages.append(package);
}
return packages;
}
Uptane::Target OstreeManager::getCurrent() {
OstreeDeploymentPtr staged_deployment = getStagedDeployment();
if (!staged_deployment) {
throw std::runtime_error("No deployments found in OSTree sysroot at: " + config.sysroot.string());
}
std::string current_hash = ostree_deployment_get_csum(staged_deployment.get());
std::vector<Uptane::Target> installed_versions;
storage_->loadInstalledVersions(&installed_versions);
std::vector<Uptane::Target>::iterator it;
for (it = installed_versions.begin(); it != installed_versions.end(); it++) {
if (it->sha256Hash() == current_hash) {
return *it;
}
}
return getUnknown();
}
OstreeDeploymentPtr OstreeManager::getStagedDeployment() {
OstreeSysrootPtr sysroot_smart = OstreeManager::LoadSysroot(config.sysroot);
GPtrArray *deployments = nullptr;
OstreeDeployment *res = nullptr;
deployments = ostree_sysroot_get_deployments(sysroot_smart.get());
if (deployments->len > 0) {
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
auto *d = static_cast<OstreeDeployment *>(deployments->pdata[0]);
auto *d2 = static_cast<OstreeDeployment *>(g_object_ref(d));
res = d2;
}
g_ptr_array_unref(deployments);
return OstreeDeploymentPtr(res);
}
OstreeSysrootPtr OstreeManager::LoadSysroot(const boost::filesystem::path &path) {
OstreeSysroot *sysroot = nullptr;
if (!path.empty()) {
GFile *fl = g_file_new_for_path(path.c_str());
sysroot = ostree_sysroot_new(fl);
g_object_unref(fl);
} else {
sysroot = ostree_sysroot_new_default();
}
GError *error = nullptr;
if (ostree_sysroot_load(sysroot, nullptr, &error) == 0) {
if (error != nullptr) {
g_error_free(error);
}
g_object_unref(sysroot);
throw std::runtime_error("could not load sysroot");
}
return OstreeSysrootPtr(sysroot);
}
OstreeRepoPtr OstreeManager::LoadRepo(OstreeSysroot *sysroot, GError **error) {
OstreeRepo *repo = nullptr;
if (ostree_sysroot_get_repo(sysroot, &repo, nullptr, error) == 0) {
return OstreeRepoPtr();
}
return OstreeRepoPtr(repo);
}
bool OstreeManager::addRemote(OstreeRepo *repo, const std::string &url, const KeyManager &keys) {
GCancellable *cancellable = nullptr;
GError *error = nullptr;
GVariantBuilder b;
GVariant *options;
g_variant_builder_init(&b, G_VARIANT_TYPE("a{sv}"));
g_variant_builder_add(&b, "{s@v}", "gpg-verify", g_variant_new_variant(g_variant_new_boolean(FALSE)));
std::string cert_file = keys.getCertFile();
std::string pkey_file = keys.getPkeyFile();
std::string ca_file = keys.getCaFile();
if (!cert_file.empty() && !pkey_file.empty() && !ca_file.empty()) {
g_variant_builder_add(&b, "{s@v}", "tls-client-cert-path",
g_variant_new_variant(g_variant_new_string(cert_file.c_str())));
g_variant_builder_add(&b, "{s@v}", "tls-client-key-path",
g_variant_new_variant(g_variant_new_string(pkey_file.c_str())));
g_variant_builder_add(&b, "{s@v}", "tls-ca-path", g_variant_new_variant(g_variant_new_string(ca_file.c_str())));
}
options = g_variant_builder_end(&b);
if (ostree_repo_remote_change(repo, nullptr, OSTREE_REPO_REMOTE_CHANGE_DELETE_IF_EXISTS, remote, url.c_str(), options,
cancellable, &error) == 0) {
LOG_ERROR << "Error of adding remote: " << error->message;
g_error_free(error);
g_variant_unref(options);
return false;
}
if (ostree_repo_remote_change(repo, nullptr, OSTREE_REPO_REMOTE_CHANGE_ADD_IF_NOT_EXISTS, remote, url.c_str(),
options, cancellable, &error) == 0) {
LOG_ERROR << "Error of adding remote: " << error->message;
g_error_free(error);
g_variant_unref(options);
return false;
}
g_variant_unref(options);
return true;
}
<commit_msg>ostree: Fix clang-format warnings<commit_after>#include "package_manager/ostreemanager.h"
#include <stdio.h>
#include <unistd.h>
#include <fstream>
#include <gio/gio.h>
#include <json/json.h>
#include <ostree-1/ostree-async-progress.h>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/filesystem.hpp>
#include <utility>
#include "logging/logging.h"
#include "utilities/utils.h"
using OstreeProgressPtr = std::unique_ptr<OstreeAsyncProgress, GObjectFinalizer<OstreeAsyncProgress>>;
static void aktualizr_progress_cb(OstreeAsyncProgress *progress, gpointer data) {
auto *percent_complete = static_cast<guint *>(data);
g_autofree char *status = ostree_async_progress_get_status(progress);
guint scanning = ostree_async_progress_get_uint(progress, "scanning");
guint outstanding_fetches = ostree_async_progress_get_uint(progress, "outstanding-fetches");
guint outstanding_metadata_fetches = ostree_async_progress_get_uint(progress, "outstanding-metadata-fetches");
guint outstanding_writes = ostree_async_progress_get_uint(progress, "outstanding-writes");
guint n_scanned_metadata = ostree_async_progress_get_uint(progress, "scanned-metadata");
if (status != nullptr && *status != '\0') {
LOG_INFO << "ostree-pull: " << status;
} else if (outstanding_fetches != 0) {
float fetched = ostree_async_progress_get_uint(progress, "fetched");
guint metadata_fetched = ostree_async_progress_get_uint(progress, "metadata-fetched");
guint requested = ostree_async_progress_get_uint(progress, "requested");
if (scanning != 0 || outstanding_metadata_fetches != 0) {
LOG_INFO << "ostree-pull: Receiving metadata objects: " << metadata_fetched
<< " outstanding: " << outstanding_metadata_fetches;
} else {
guint calculated = round(((fetched) / requested) * 100);
if (calculated != *percent_complete) {
LOG_INFO << "ostree-pull: Receiving objects: " << calculated << "% ";
*percent_complete = calculated;
}
}
} else if (outstanding_writes != 0) {
LOG_INFO << "ostree-pull: Writing objects: " << outstanding_writes;
} else {
LOG_INFO << "ostree-pull: Scanning metadata: " << n_scanned_metadata;
}
}
data::InstallOutcome OstreeManager::pull(const boost::filesystem::path &sysroot_path, const std::string &ostree_server,
const KeyManager &keys, const std::string &refhash) {
const char *const commit_ids[] = {refhash.c_str()};
GCancellable *cancellable = nullptr;
GError *error = nullptr;
GVariantBuilder builder;
GVariant *options;
OstreeProgressPtr progress = nullptr;
guint percent_complete = 0;
OstreeSysrootPtr sysroot = OstreeManager::LoadSysroot(sysroot_path);
OstreeRepoPtr repo = LoadRepo(sysroot.get(), &error);
if (error != nullptr) {
LOG_ERROR << "Could not get OSTree repo";
g_error_free(error);
return data::InstallOutcome(data::INSTALL_FAILED, "Could not get OSTree repo");
}
GHashTable *ref_list = nullptr;
if (ostree_repo_list_commit_objects_starting_with(repo.get(), refhash.c_str(), &ref_list, nullptr, &error) != 0) {
guint length = g_hash_table_size(ref_list);
g_hash_table_destroy(ref_list); // OSTree creates the table with destroy notifiers, so no memory leaks expected
// should never be greater than 1, but use >= for robustness
if (length >= 1) {
LOG_DEBUG << "refhash already pulled";
return data::InstallOutcome(data::ALREADY_PROCESSED, "Refhash was already pulled");
}
}
if (error != nullptr) {
g_error_free(error);
error = nullptr;
}
if (!OstreeManager::addRemote(repo.get(), ostree_server, keys)) {
return data::InstallOutcome(data::INSTALL_FAILED, "Error adding OSTree remote");
}
g_variant_builder_init(&builder, G_VARIANT_TYPE("a{sv}"));
g_variant_builder_add(&builder, "{s@v}", "flags", g_variant_new_variant(g_variant_new_int32(0)));
g_variant_builder_add(&builder, "{s@v}", "refs", g_variant_new_variant(g_variant_new_strv(commit_ids, 1)));
options = g_variant_builder_end(&builder);
progress.reset(ostree_async_progress_new_and_connect(aktualizr_progress_cb, &percent_complete));
if (ostree_repo_pull_with_options(repo.get(), remote, options, progress.get(), cancellable, &error) == 0) {
LOG_ERROR << "Error of pulling image: " << error->message;
data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message);
g_error_free(error);
g_variant_unref(options);
return install_outcome;
}
ostree_async_progress_finish(progress.get());
g_variant_unref(options);
return data::InstallOutcome(data::OK, "Pulling ostree image was successful");
}
data::InstallOutcome OstreeManager::install(const Uptane::Target &target) const {
const char *opt_osname = nullptr;
GCancellable *cancellable = nullptr;
GError *error = nullptr;
char *revision;
if (config.os.size() != 0u) {
opt_osname = config.os.c_str();
}
OstreeSysrootPtr sysroot = OstreeManager::LoadSysroot(config.sysroot);
OstreeRepoPtr repo = LoadRepo(sysroot.get(), &error);
if (error != nullptr) {
LOG_ERROR << "could not get repo";
g_error_free(error);
return data::InstallOutcome(data::INSTALL_FAILED, "could not get repo");
}
auto origin = StructGuard<GKeyFile>(
ostree_sysroot_origin_new_from_refspec(sysroot.get(), target.sha256Hash().c_str()), g_key_file_free);
if (ostree_repo_resolve_rev(repo.get(), target.sha256Hash().c_str(), FALSE, &revision, &error) == 0) {
LOG_ERROR << error->message;
data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message);
g_error_free(error);
return install_outcome;
}
OstreeDeployment *merge_deployment = ostree_sysroot_get_merge_deployment(sysroot.get(), opt_osname);
if (merge_deployment == nullptr) {
LOG_ERROR << "No merge deployment";
return data::InstallOutcome(data::INSTALL_FAILED, "No merge deployment");
}
if (ostree_sysroot_prepare_cleanup(sysroot.get(), cancellable, &error) == 0) {
LOG_ERROR << error->message;
data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message);
g_error_free(error);
return install_outcome;
}
std::string args_content =
std::string(ostree_bootconfig_parser_get(ostree_deployment_get_bootconfig(merge_deployment), "options"));
std::vector<std::string> args_vector;
boost::split(args_vector, args_content, boost::is_any_of(" "));
std::vector<const char *> kargs_strv_vector;
kargs_strv_vector.reserve(args_vector.size() + 1);
for (auto it = args_vector.begin(); it != args_vector.end(); ++it) {
kargs_strv_vector.push_back((*it).c_str());
}
kargs_strv_vector[args_vector.size()] = nullptr;
auto kargs_strv = const_cast<char **>(&kargs_strv_vector[0]);
OstreeDeployment *new_deployment = nullptr;
if (ostree_sysroot_deploy_tree(sysroot.get(), opt_osname, revision, origin.get(), merge_deployment, kargs_strv,
&new_deployment, cancellable, &error) == 0) {
LOG_ERROR << "ostree_sysroot_deploy_tree: " << error->message;
data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message);
g_error_free(error);
return install_outcome;
}
if (ostree_sysroot_simple_write_deployment(sysroot.get(), nullptr, new_deployment, merge_deployment,
OSTREE_SYSROOT_SIMPLE_WRITE_DEPLOYMENT_FLAGS_NONE, cancellable,
&error) == 0) {
LOG_ERROR << "ostree_sysroot_simple_write_deployment:" << error->message;
data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message);
g_error_free(error);
return install_outcome;
}
LOG_INFO << "Performing sync()";
sync();
return data::InstallOutcome(data::OK, "Installation successful");
}
OstreeManager::OstreeManager(PackageConfig pconfig, std::shared_ptr<INvStorage> storage)
: config(std::move(pconfig)), storage_(std::move(storage)) {
try {
OstreeManager::getCurrent();
} catch (...) {
throw std::runtime_error("Could not find OSTree sysroot at: " + config.sysroot.string());
}
}
Json::Value OstreeManager::getInstalledPackages() {
std::string packages_str = Utils::readFile(config.packages_file);
std::vector<std::string> package_lines;
boost::split(package_lines, packages_str, boost::is_any_of("\n"));
Json::Value packages(Json::arrayValue);
for (auto it = package_lines.begin(); it != package_lines.end(); ++it) {
if (it->empty()) {
continue;
}
size_t pos = it->find(" ");
if (pos == std::string::npos) {
throw std::runtime_error("Wrong packages file format");
}
Json::Value package;
package["name"] = it->substr(0, pos);
package["version"] = it->substr(pos + 1);
packages.append(package);
}
return packages;
}
Uptane::Target OstreeManager::getCurrent() {
OstreeDeploymentPtr staged_deployment = getStagedDeployment();
if (!staged_deployment) {
throw std::runtime_error("No deployments found in OSTree sysroot at: " + config.sysroot.string());
}
std::string current_hash = ostree_deployment_get_csum(staged_deployment.get());
std::vector<Uptane::Target> installed_versions;
storage_->loadInstalledVersions(&installed_versions);
std::vector<Uptane::Target>::iterator it;
for (it = installed_versions.begin(); it != installed_versions.end(); it++) {
if (it->sha256Hash() == current_hash) {
return *it;
}
}
return getUnknown();
}
OstreeDeploymentPtr OstreeManager::getStagedDeployment() {
OstreeSysrootPtr sysroot_smart = OstreeManager::LoadSysroot(config.sysroot);
GPtrArray *deployments = nullptr;
OstreeDeployment *res = nullptr;
deployments = ostree_sysroot_get_deployments(sysroot_smart.get());
if (deployments->len > 0) {
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
auto *d = static_cast<OstreeDeployment *>(deployments->pdata[0]);
auto *d2 = static_cast<OstreeDeployment *>(g_object_ref(d));
res = d2;
}
g_ptr_array_unref(deployments);
return OstreeDeploymentPtr(res);
}
OstreeSysrootPtr OstreeManager::LoadSysroot(const boost::filesystem::path &path) {
OstreeSysroot *sysroot = nullptr;
if (!path.empty()) {
GFile *fl = g_file_new_for_path(path.c_str());
sysroot = ostree_sysroot_new(fl);
g_object_unref(fl);
} else {
sysroot = ostree_sysroot_new_default();
}
GError *error = nullptr;
if (ostree_sysroot_load(sysroot, nullptr, &error) == 0) {
if (error != nullptr) {
g_error_free(error);
}
g_object_unref(sysroot);
throw std::runtime_error("could not load sysroot");
}
return OstreeSysrootPtr(sysroot);
}
OstreeRepoPtr OstreeManager::LoadRepo(OstreeSysroot *sysroot, GError **error) {
OstreeRepo *repo = nullptr;
if (ostree_sysroot_get_repo(sysroot, &repo, nullptr, error) == 0) {
return OstreeRepoPtr();
}
return OstreeRepoPtr(repo);
}
bool OstreeManager::addRemote(OstreeRepo *repo, const std::string &url, const KeyManager &keys) {
GCancellable *cancellable = nullptr;
GError *error = nullptr;
GVariantBuilder b;
GVariant *options;
g_variant_builder_init(&b, G_VARIANT_TYPE("a{sv}"));
g_variant_builder_add(&b, "{s@v}", "gpg-verify", g_variant_new_variant(g_variant_new_boolean(FALSE)));
std::string cert_file = keys.getCertFile();
std::string pkey_file = keys.getPkeyFile();
std::string ca_file = keys.getCaFile();
if (!cert_file.empty() && !pkey_file.empty() && !ca_file.empty()) {
g_variant_builder_add(&b, "{s@v}", "tls-client-cert-path",
g_variant_new_variant(g_variant_new_string(cert_file.c_str())));
g_variant_builder_add(&b, "{s@v}", "tls-client-key-path",
g_variant_new_variant(g_variant_new_string(pkey_file.c_str())));
g_variant_builder_add(&b, "{s@v}", "tls-ca-path", g_variant_new_variant(g_variant_new_string(ca_file.c_str())));
}
options = g_variant_builder_end(&b);
if (ostree_repo_remote_change(repo, nullptr, OSTREE_REPO_REMOTE_CHANGE_DELETE_IF_EXISTS, remote, url.c_str(), options,
cancellable, &error) == 0) {
LOG_ERROR << "Error of adding remote: " << error->message;
g_error_free(error);
g_variant_unref(options);
return false;
}
if (ostree_repo_remote_change(repo, nullptr, OSTREE_REPO_REMOTE_CHANGE_ADD_IF_NOT_EXISTS, remote, url.c_str(),
options, cancellable, &error) == 0) {
LOG_ERROR << "Error of adding remote: " << error->message;
g_error_free(error);
g_variant_unref(options);
return false;
}
g_variant_unref(options);
return true;
}
<|endoftext|> |
<commit_before>//
// MCIndexSet.cpp
// mailcore2
//
// Created by DINH Viêt Hoà on 3/4/13.
// Copyright (c) 2013 MailCore. All rights reserved.
//
#include "MCIndexSet.h"
#include "MCString.h"
#include "MCAssert.h"
#include "MCRange.h"
#include "MCLog.h"
#include "MCArray.h"
#include "MCHashMap.h"
#include "MCUtils.h"
using namespace mailcore;
void IndexSet::init()
{
mRanges = NULL;
mAllocated = 0;
mCount = 0;
}
IndexSet::IndexSet()
{
init();
}
IndexSet::IndexSet(IndexSet * o)
{
init();
mRanges = new Range[o->mAllocated];
for(unsigned int i = 0 ; i < o->mCount ; i ++) {
mRanges[i] = o->mRanges[i];
}
mAllocated = o->mAllocated;
mCount = o->mCount;
}
IndexSet::~IndexSet()
{
removeAllIndexes();
}
IndexSet * IndexSet::indexSet()
{
IndexSet * result = new IndexSet();
result->autorelease();
return result;
}
IndexSet * IndexSet::indexSetWithRange(Range range)
{
IndexSet * result = new IndexSet();
result->autorelease();
result->addRange(range);
return result;
}
IndexSet * IndexSet::indexSetWithIndex(uint64_t idx)
{
IndexSet * result = new IndexSet();
result->autorelease();
result->addIndex(idx);
return result;
}
unsigned int IndexSet::count()
{
unsigned int total = 0;
for(unsigned int i = 0 ; i < mCount ; i ++) {
total += mRanges[i].length + 1;
}
return total;
}
int IndexSet::rangeIndexForIndexWithBounds(uint64_t idx, unsigned int left, unsigned int right)
{
unsigned int middle = (left + right) / 2;
Range middleRange = mRanges[middle];
if (left == right) {
if ((idx >= RangeLeftBound(middleRange)) && (idx <= RangeRightBound(middleRange))) {
return left;
}
return -1;
}
if ((idx >= RangeLeftBound(middleRange)) && (idx <= RangeRightBound(middleRange))) {
return middle;
}
if (idx < middleRange.location) {
return rangeIndexForIndexWithBounds(idx, left, middle);
}
else {
return rangeIndexForIndexWithBounds(idx, middle + 1, right);
}
}
int IndexSet::rangeIndexForIndex(uint64_t idx)
{
if (mCount == 0)
return -1;
return rangeIndexForIndexWithBounds(idx, 0, mCount - 1);
}
int IndexSet::rightRangeIndexForIndexWithBounds(uint64_t idx, unsigned int left, unsigned int right)
{
unsigned int middle = (left + right) / 2;
Range middleRange = mRanges[middle];
if (left == right) {
if (idx > middleRange.location + middleRange.length) {
return left + 1;
}
else {
return left;
}
}
if (idx < middleRange.location + middleRange.length) {
return rightRangeIndexForIndexWithBounds(idx, left, middle);
}
else {
return rightRangeIndexForIndexWithBounds(idx, middle + 1, right);
}
}
int IndexSet::rightRangeIndexForIndex(uint64_t idx)
{
if (mCount == 0)
return 0;
return rightRangeIndexForIndexWithBounds(idx, 0, mCount - 1);
}
int IndexSet::leftRangeIndexForIndexWithBounds(uint64_t idx, unsigned int left, unsigned int right)
{
unsigned int middle = (left + right) / 2;
Range middleRange = mRanges[middle];
if (left == right) {
if (idx <= RangeRightBound(middleRange)) {
return left;
}
else {
return left + 1;
}
}
if (idx <= RangeRightBound(middleRange)) {
return leftRangeIndexForIndexWithBounds(idx, left, middle);
}
else {
return leftRangeIndexForIndexWithBounds(idx, middle + 1, right);
}
}
int IndexSet::leftRangeIndexForIndex(uint64_t idx)
{
if (mCount == 0)
return 0;
return leftRangeIndexForIndexWithBounds(idx, 0, mCount - 1);
}
void IndexSet::addRangeIndex(unsigned int rangeIndex)
{
if (mAllocated < mCount + 1) {
while (mAllocated < mCount + 1) {
if (mAllocated == 0) {
mAllocated = 4;
}
mAllocated *= 2;
}
Range * rangesReplacement = new Range[mAllocated];
for(unsigned int i = 0 ; i < rangeIndex ; i ++) {
rangesReplacement[i] = mRanges[i];
}
for(unsigned int i = rangeIndex ; i < mCount ; i ++) {
rangesReplacement[i + 1] = mRanges[i];
}
mCount ++;
rangesReplacement[rangeIndex].location = 0;
rangesReplacement[rangeIndex].length = 0;
delete [] mRanges;
mRanges = rangesReplacement;
}
else {
if (mCount > 0) {
for(int i = mCount - 1 ; i >= (int) rangeIndex ; i --) {
mRanges[i + 1] = mRanges[i];
}
}
mCount ++;
mRanges[rangeIndex].location = 0;
mRanges[rangeIndex].length = 0;
}
}
void IndexSet::addRange(Range range)
{
int rangeIndex = leftRangeIndexForIndex(range.location);
addRangeIndex(rangeIndex);
mRanges[rangeIndex] = range;
mergeRanges(rangeIndex);
if (rangeIndex > 0) {
tryToMergeAdjacentRanges(rangeIndex - 1);
}
if (rangeIndex < mCount - 1) {
tryToMergeAdjacentRanges(rangeIndex);
}
}
void IndexSet::tryToMergeAdjacentRanges(unsigned int rangeIndex)
{
if (RangeRightBound(mRanges[rangeIndex]) == UINT64_MAX)
return;
if (RangeRightBound(mRanges[rangeIndex]) + 1 != mRanges[rangeIndex + 1].location) {
return;
}
uint64_t right = RangeRightBound(mRanges[rangeIndex + 1]);
removeRangeIndex(rangeIndex + 1, 1);
mRanges[rangeIndex].length = right - mRanges[rangeIndex].location;
}
void IndexSet::mergeRanges(unsigned int rangeIndex)
{
int right = rangeIndex;
for(int i = rangeIndex ; i < mCount ; i ++) {
if (RangeHasIntersection(mRanges[rangeIndex], mRanges[i])) {
right = i;
}
else {
break;
}
}
if (right == rangeIndex)
return;
IndexSet * indexSet = RangeUnion(mRanges[rangeIndex], mRanges[right]);
MCAssert(indexSet->rangesCount() > 0);
Range range = indexSet->allRanges()[0];
removeRangeIndex(rangeIndex + 1, right - rangeIndex);
mRanges[rangeIndex] = range;
}
void IndexSet::addIndex(uint64_t idx)
{
addRange(RangeMake(idx, 0));
}
void IndexSet::removeRangeIndex(unsigned int rangeIndex, unsigned int count)
{
for(unsigned int i = rangeIndex + count ; i < mCount ; i ++) {
mRanges[i - count] = mRanges[i];
}
mCount -= count;
}
void IndexSet::removeRange(Range range)
{
int left = -1;
int right = -1;
int leftRangeIndex = leftRangeIndexForIndex(range.location);
if (leftRangeIndex >= mCount) {
leftRangeIndex = mCount - 1;
}
for(int i = leftRangeIndex ; i < mCount ; i ++) {
if (RangeHasIntersection(mRanges[i], range)) {
IndexSet * indexSet = RangeRemoveRange(mRanges[i], range);
if (indexSet->rangesCount() == 0) {
if (left == -1) {
left = i;
}
right = i;
mRanges[i] = RangeEmpty;
}
else if (indexSet->rangesCount() == 1) {
mRanges[i] = indexSet->allRanges()[0];
}
else {
MCAssert(indexSet->rangesCount() == 2);
addRangeIndex(i);
mRanges[i] = indexSet->allRanges()[0];
mRanges[i + 1] = indexSet->allRanges()[1];
}
}
else {
break;
}
}
if (left != -1) {
removeRangeIndex(left, right - left + 1);
}
}
void IndexSet::removeIndex(uint64_t idx)
{
removeRange(RangeMake(idx, 0));
}
bool IndexSet::containsIndex(uint64_t idx)
{
int rangeIndex = rangeIndexForIndex(idx);
return rangeIndex != -1;
}
unsigned int IndexSet::rangesCount()
{
return mCount;
}
Range * IndexSet::allRanges()
{
return mRanges;
}
void IndexSet::removeAllIndexes()
{
delete[] mRanges;
mRanges = NULL;
mAllocated = 0;
mCount = 0;
}
String * IndexSet::description()
{
String * result = String::string();
for(unsigned int i = 0 ; i < mCount ; i ++) {
if (i != 0) {
result->appendUTF8Format(",");
}
if (mRanges[i].length == 0) {
result->appendUTF8Format("%llu",
(unsigned long long) mRanges[i].location);
}
else {
result->appendUTF8Format("%llu-%llu",
(unsigned long long) mRanges[i].location,
(unsigned long long) (mRanges[i].location + mRanges[i].length));
}
}
return result;
}
Object * IndexSet::copy()
{
return new IndexSet(this);
}
void IndexSet::intersectsRange(Range range)
{
uint64_t right = RangeRightBound(range);
if (right == UINT64_MAX) {
removeRange(RangeMake(0, range.location - 1));
}
else {
removeRange(RangeMake(0, range.location - 1));
removeRange(RangeMake(right, UINT64_MAX));
}
}
HashMap * IndexSet::serializable()
{
HashMap * result = Object::serializable();
Array * ranges = Array::array();
for(unsigned int i = 0 ; i < mCount ; i ++) {
ranges->addObject(RangeToString(mRanges[i]));
}
result->setObjectForKey(MCSTR("ranges"), ranges);
return result;
}
void IndexSet::importSerializable(HashMap * serializable)
{
Array * ranges = (Array *) serializable->objectForKey(MCSTR("ranges"));
for(unsigned int i = 0 ; i < ranges->count() ; i ++) {
String * rangeStr = (String *) ranges->objectAtIndex(i);
addRange(RangeFromString(rangeStr));
}
}
void IndexSet::addIndexSet(IndexSet * indexSet)
{
for(unsigned int i = 0 ; i < indexSet->rangesCount() ; i ++) {
addRange(indexSet->allRanges()[i]);
}
}
void IndexSet::removeIndexSet(IndexSet * indexSet)
{
for(unsigned int i = 0 ; i < indexSet->rangesCount() ; i ++) {
removeRange(indexSet->allRanges()[i]);
}
}
void IndexSet::intersectsIndexSet(IndexSet * indexSet)
{
IndexSet * result = new IndexSet();
for(unsigned int i = 0 ; i < indexSet->rangesCount() ; i ++) {
IndexSet * rangeIntersect = (IndexSet *) copy();
rangeIntersect->intersectsRange(indexSet->allRanges()[i]);
result->addIndexSet(rangeIntersect);
rangeIntersect->release();
}
removeAllIndexes();
addIndexSet(result);
result->release();
}
static void * createObject()
{
return new IndexSet();
}
__attribute__((constructor))
static void initialize()
{
Object::registerObjectConstructor("mailcore::IndexSet", &createObject);
}
<commit_msg>Fixed intersction methods<commit_after>//
// MCIndexSet.cpp
// mailcore2
//
// Created by DINH Viêt Hoà on 3/4/13.
// Copyright (c) 2013 MailCore. All rights reserved.
//
#include "MCIndexSet.h"
#include "MCString.h"
#include "MCAssert.h"
#include "MCRange.h"
#include "MCLog.h"
#include "MCArray.h"
#include "MCHashMap.h"
#include "MCUtils.h"
using namespace mailcore;
void IndexSet::init()
{
mRanges = NULL;
mAllocated = 0;
mCount = 0;
}
IndexSet::IndexSet()
{
init();
}
IndexSet::IndexSet(IndexSet * o)
{
init();
mRanges = new Range[o->mAllocated];
for(unsigned int i = 0 ; i < o->mCount ; i ++) {
mRanges[i] = o->mRanges[i];
}
mAllocated = o->mAllocated;
mCount = o->mCount;
}
IndexSet::~IndexSet()
{
removeAllIndexes();
}
IndexSet * IndexSet::indexSet()
{
IndexSet * result = new IndexSet();
result->autorelease();
return result;
}
IndexSet * IndexSet::indexSetWithRange(Range range)
{
IndexSet * result = new IndexSet();
result->autorelease();
result->addRange(range);
return result;
}
IndexSet * IndexSet::indexSetWithIndex(uint64_t idx)
{
IndexSet * result = new IndexSet();
result->autorelease();
result->addIndex(idx);
return result;
}
unsigned int IndexSet::count()
{
unsigned int total = 0;
for(unsigned int i = 0 ; i < mCount ; i ++) {
total += mRanges[i].length + 1;
}
return total;
}
int IndexSet::rangeIndexForIndexWithBounds(uint64_t idx, unsigned int left, unsigned int right)
{
unsigned int middle = (left + right) / 2;
Range middleRange = mRanges[middle];
if (left == right) {
if ((idx >= RangeLeftBound(middleRange)) && (idx <= RangeRightBound(middleRange))) {
return left;
}
return -1;
}
if ((idx >= RangeLeftBound(middleRange)) && (idx <= RangeRightBound(middleRange))) {
return middle;
}
if (idx < middleRange.location) {
return rangeIndexForIndexWithBounds(idx, left, middle);
}
else {
return rangeIndexForIndexWithBounds(idx, middle + 1, right);
}
}
int IndexSet::rangeIndexForIndex(uint64_t idx)
{
if (mCount == 0)
return -1;
return rangeIndexForIndexWithBounds(idx, 0, mCount - 1);
}
int IndexSet::rightRangeIndexForIndexWithBounds(uint64_t idx, unsigned int left, unsigned int right)
{
unsigned int middle = (left + right) / 2;
Range middleRange = mRanges[middle];
if (left == right) {
if (idx > middleRange.location + middleRange.length) {
return left + 1;
}
else {
return left;
}
}
if (idx < middleRange.location + middleRange.length) {
return rightRangeIndexForIndexWithBounds(idx, left, middle);
}
else {
return rightRangeIndexForIndexWithBounds(idx, middle + 1, right);
}
}
int IndexSet::rightRangeIndexForIndex(uint64_t idx)
{
if (mCount == 0)
return 0;
return rightRangeIndexForIndexWithBounds(idx, 0, mCount - 1);
}
int IndexSet::leftRangeIndexForIndexWithBounds(uint64_t idx, unsigned int left, unsigned int right)
{
unsigned int middle = (left + right) / 2;
Range middleRange = mRanges[middle];
if (left == right) {
if (idx <= RangeRightBound(middleRange)) {
return left;
}
else {
return left + 1;
}
}
if (idx <= RangeRightBound(middleRange)) {
return leftRangeIndexForIndexWithBounds(idx, left, middle);
}
else {
return leftRangeIndexForIndexWithBounds(idx, middle + 1, right);
}
}
int IndexSet::leftRangeIndexForIndex(uint64_t idx)
{
if (mCount == 0)
return 0;
return leftRangeIndexForIndexWithBounds(idx, 0, mCount - 1);
}
void IndexSet::addRangeIndex(unsigned int rangeIndex)
{
if (mAllocated < mCount + 1) {
while (mAllocated < mCount + 1) {
if (mAllocated == 0) {
mAllocated = 4;
}
mAllocated *= 2;
}
Range * rangesReplacement = new Range[mAllocated];
for(unsigned int i = 0 ; i < rangeIndex ; i ++) {
rangesReplacement[i] = mRanges[i];
}
for(unsigned int i = rangeIndex ; i < mCount ; i ++) {
rangesReplacement[i + 1] = mRanges[i];
}
mCount ++;
rangesReplacement[rangeIndex].location = 0;
rangesReplacement[rangeIndex].length = 0;
delete [] mRanges;
mRanges = rangesReplacement;
}
else {
if (mCount > 0) {
for(int i = mCount - 1 ; i >= (int) rangeIndex ; i --) {
mRanges[i + 1] = mRanges[i];
}
}
mCount ++;
mRanges[rangeIndex].location = 0;
mRanges[rangeIndex].length = 0;
}
}
void IndexSet::addRange(Range range)
{
int rangeIndex = leftRangeIndexForIndex(range.location);
addRangeIndex(rangeIndex);
mRanges[rangeIndex] = range;
mergeRanges(rangeIndex);
if (rangeIndex > 0) {
tryToMergeAdjacentRanges(rangeIndex - 1);
}
if (rangeIndex < mCount - 1) {
tryToMergeAdjacentRanges(rangeIndex);
}
}
void IndexSet::tryToMergeAdjacentRanges(unsigned int rangeIndex)
{
if (RangeRightBound(mRanges[rangeIndex]) == UINT64_MAX)
return;
if (RangeRightBound(mRanges[rangeIndex]) + 1 != mRanges[rangeIndex + 1].location) {
return;
}
uint64_t right = RangeRightBound(mRanges[rangeIndex + 1]);
removeRangeIndex(rangeIndex + 1, 1);
mRanges[rangeIndex].length = right - mRanges[rangeIndex].location;
}
void IndexSet::mergeRanges(unsigned int rangeIndex)
{
int right = rangeIndex;
for(int i = rangeIndex ; i < mCount ; i ++) {
if (RangeHasIntersection(mRanges[rangeIndex], mRanges[i])) {
right = i;
}
else {
break;
}
}
if (right == rangeIndex)
return;
IndexSet * indexSet = RangeUnion(mRanges[rangeIndex], mRanges[right]);
MCAssert(indexSet->rangesCount() > 0);
Range range = indexSet->allRanges()[0];
removeRangeIndex(rangeIndex + 1, right - rangeIndex);
mRanges[rangeIndex] = range;
}
void IndexSet::addIndex(uint64_t idx)
{
addRange(RangeMake(idx, 0));
}
void IndexSet::removeRangeIndex(unsigned int rangeIndex, unsigned int count)
{
for(unsigned int i = rangeIndex + count ; i < mCount ; i ++) {
mRanges[i - count] = mRanges[i];
}
mCount -= count;
}
void IndexSet::removeRange(Range range)
{
int left = -1;
int right = -1;
int leftRangeIndex = leftRangeIndexForIndex(range.location);
if (leftRangeIndex >= mCount) {
leftRangeIndex = mCount - 1;
}
for(int i = leftRangeIndex ; i < mCount ; i ++) {
if (RangeHasIntersection(mRanges[i], range)) {
IndexSet * indexSet = RangeRemoveRange(mRanges[i], range);
if (indexSet->rangesCount() == 0) {
if (left == -1) {
left = i;
}
right = i;
mRanges[i] = RangeEmpty;
}
else if (indexSet->rangesCount() == 1) {
mRanges[i] = indexSet->allRanges()[0];
}
else {
MCAssert(indexSet->rangesCount() == 2);
addRangeIndex(i);
mRanges[i] = indexSet->allRanges()[0];
mRanges[i + 1] = indexSet->allRanges()[1];
}
}
else {
break;
}
}
if (left != -1) {
removeRangeIndex(left, right - left + 1);
}
}
void IndexSet::removeIndex(uint64_t idx)
{
removeRange(RangeMake(idx, 0));
}
bool IndexSet::containsIndex(uint64_t idx)
{
int rangeIndex = rangeIndexForIndex(idx);
return rangeIndex != -1;
}
unsigned int IndexSet::rangesCount()
{
return mCount;
}
Range * IndexSet::allRanges()
{
return mRanges;
}
void IndexSet::removeAllIndexes()
{
delete[] mRanges;
mRanges = NULL;
mAllocated = 0;
mCount = 0;
}
String * IndexSet::description()
{
String * result = String::string();
for(unsigned int i = 0 ; i < mCount ; i ++) {
if (i != 0) {
result->appendUTF8Format(",");
}
if (mRanges[i].length == 0) {
result->appendUTF8Format("%llu",
(unsigned long long) mRanges[i].location);
}
else {
result->appendUTF8Format("%llu-%llu",
(unsigned long long) mRanges[i].location,
(unsigned long long) (mRanges[i].location + mRanges[i].length));
}
}
return result;
}
Object * IndexSet::copy()
{
return new IndexSet(this);
}
void IndexSet::intersectsRange(Range range)
{
uint64_t right = RangeRightBound(range);
if (right == UINT64_MAX) {
removeRange(RangeMake(0, range.location - 1));
}
else {
removeRange(RangeMake(0, range.location - 1));
removeRange(RangeMake(right + 1, UINT64_MAX));
}
}
HashMap * IndexSet::serializable()
{
HashMap * result = Object::serializable();
Array * ranges = Array::array();
for(unsigned int i = 0 ; i < mCount ; i ++) {
ranges->addObject(RangeToString(mRanges[i]));
}
result->setObjectForKey(MCSTR("ranges"), ranges);
return result;
}
void IndexSet::importSerializable(HashMap * serializable)
{
Array * ranges = (Array *) serializable->objectForKey(MCSTR("ranges"));
for(unsigned int i = 0 ; i < ranges->count() ; i ++) {
String * rangeStr = (String *) ranges->objectAtIndex(i);
addRange(RangeFromString(rangeStr));
}
}
void IndexSet::addIndexSet(IndexSet * indexSet)
{
for(unsigned int i = 0 ; i < indexSet->rangesCount() ; i ++) {
addRange(indexSet->allRanges()[i]);
}
}
void IndexSet::removeIndexSet(IndexSet * indexSet)
{
for(unsigned int i = 0 ; i < indexSet->rangesCount() ; i ++) {
removeRange(indexSet->allRanges()[i]);
}
}
void IndexSet::intersectsIndexSet(IndexSet * indexSet)
{
IndexSet * result = new IndexSet();
for(unsigned int i = 0 ; i < indexSet->rangesCount() ; i ++) {
IndexSet * rangeIntersect = (IndexSet *) copy();
rangeIntersect->intersectsRange(indexSet->allRanges()[i]);
result->addIndexSet(rangeIntersect);
rangeIntersect->release();
}
removeAllIndexes();
addIndexSet(result);
result->release();
}
static void * createObject()
{
return new IndexSet();
}
__attribute__((constructor))
static void initialize()
{
Object::registerObjectConstructor("mailcore::IndexSet", &createObject);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <linbox/blackbox/toeplitz.h>
#ifdef __LINBOX_HAVE_NTL
#include <linbox/field/ntl-lzz_pX.h>
#include <linbox/field/ntl-lzz_p.h>
#endif
#include <linbox/solutions/det.h>
#include <linbox/blackbox/dense.h>
#include <linbox/randiter/random-prime.h>
#include <linbox/util/commentator.h>
#include "test-common.h"
#include <cstdlib>
#include <ctime>
#include <linbox/integer.h>
using namespace std;
using namespace LinBox;
int main(int argc, char* argv[]) {
static size_t N_BOUND = 100;
static Argument args[] = {
{ 'n', "-n N", "Set dimension limit of test matrices to NxN.", TYPE_INT, &N_BOUND },
{ '\0' }
};
parseArguments (argc, argv, args);
commentator.start("Toeplitz determinant test suite", "Toeplitz det");
commentator.getMessageClass (INTERNAL_DESCRIPTION).setMaxDepth (3);
commentator.getMessageClass (INTERNAL_DESCRIPTION).setMaxDetailLevel (Commentator::LEVEL_UNIMPORTANT);
ostream& report = commentator.report();
bool pass = true;
#ifdef __LINBOX_HAVE_NTL
srand(time(0));
RandomPrimeIterator rp;
NTL_zz_p::RandIter rand;
report << "\tUsing random primes and square matrices of size 2 to " << N_BOUND << endl;
//for( int i = 0; pass && i < 2; ++i ) {
size_t n;
do { n = rand() % N_BOUND; } while( n < 2 );
NTL_zz_p CF( *rp );
NTL_zz_pX PF(CF);
DenseMatrix<NTL_zz_p> A(CF,n,n);
NTL_zz_p::Element temp;
NTL_zz_pX::Element poly;
PF.init(poly,0);
size_t r,c;
for( int diff = 1 - ((int)n); diff <= ((int)n) - 1; ++diff ) {
rand.random(temp);
PF.setCoeff(poly,(size_t)(diff + n - 1), temp );
r = c = 0;
if( diff < 0 ) c = (size_t)(diff*-1);
else r = (size_t)diff;
for( ; r < n && c < n; ++r, ++c )
A.setEntry(r,c,temp);
}
Toeplitz<NTL_zz_p,NTL_zz_pX> T( PF, poly, n );
NTL_zz_p::Element res1, res2;
//det(res1,A);
det(res1,T);
det(res2,T);
if( res1 != res2 ) pass = false;
//}
#else
report << "No test, because no NTL." << endl;
#endif
report << endl;
if( pass ) report << "<====== Passed!" << endl;
else report << "<====== Failed!" << endl;
commentator.stop("toeplitz determinant test suite");
return (pass ? 0 : 1);
#if 0
NTL_ZZ_pX F( 65521 );
NTL_ZZ_pX::Element a,b;
F.init(a,1);
F.init(b,4);
F.mulin(a,b);
F.write(cout,a) << endl;
F.write(cout) << endl;
NTL_ZZ_pX::Element T;
Toeplitz<NTL_ZZ_p> Q(F.getCoeffField());
vector<int> v;
v.push_back( -3 );
v.push_back( 50 );
v.push_back( 71 );
v.push_back( -43 );
v.push_back( 91 );
v.push_back( 16 );
v.push_back( 78 );
F.init(T,v);
Toeplitz<NTL_ZZ_p,NTL_ZZ_pX> mat( F, T, 4 );
Toeplitz<NTL_ZZ_p,NTL_ZZ_pX>::Element res;
//mat.det( res );
det(res,mat);
/*
F.init( T, v );
NTL_ZZ_pX::Coeff res;
toeplitz_determinant( F, res, T, 4 );
*/
//cout << res << endl;
commentator.stop("toeplitz determinant test suite");
#endif
}
<commit_msg>changed randiter name form rand to randit<commit_after>#include <iostream>
#include <vector>
#include <linbox/blackbox/toeplitz.h>
#ifdef __LINBOX_HAVE_NTL
#include <linbox/field/ntl-lzz_pX.h>
#include <linbox/field/ntl-lzz_p.h>
#endif
#include <linbox/solutions/det.h>
#include <linbox/blackbox/dense.h>
#include <linbox/randiter/random-prime.h>
#include <linbox/util/commentator.h>
#include "test-common.h"
#include <cstdlib>
#include <ctime>
#include <linbox/integer.h>
using namespace std;
using namespace LinBox;
int main(int argc, char* argv[]) {
static size_t N_BOUND = 100;
static Argument args[] = {
{ 'n', "-n N", "Set dimension limit of test matrices to NxN.", TYPE_INT, &N_BOUND },
{ '\0' }
};
parseArguments (argc, argv, args);
commentator.start("Toeplitz determinant test suite", "Toeplitz det");
commentator.getMessageClass (INTERNAL_DESCRIPTION).setMaxDepth (3);
commentator.getMessageClass (INTERNAL_DESCRIPTION).setMaxDetailLevel (Commentator::LEVEL_UNIMPORTANT);
ostream& report = commentator.report();
bool pass = true;
#ifdef __LINBOX_HAVE_NTL
srand(time(0));
RandomPrimeIterator rp;
NTL_zz_p::RandIter randit;
report << "\tUsing random primes and square matrices of size 2 to " << N_BOUND << endl;
//for( int i = 0; pass && i < 2; ++i ) {
size_t n;
do { n = rand() % N_BOUND; } while( n < 2 );
NTL_zz_p CF( *rp );
NTL_zz_pX PF(CF);
DenseMatrix<NTL_zz_p> A(CF,n,n);
NTL_zz_p::Element temp;
NTL_zz_pX::Element poly;
PF.init(poly,0);
size_t r,c;
for( int diff = 1 - ((int)n); diff <= ((int)n) - 1; ++diff ) {
randit.random(temp);
PF.setCoeff(poly,(size_t)(diff + n - 1), temp );
r = c = 0;
if( diff < 0 ) c = (size_t)(diff*-1);
else r = (size_t)diff;
for( ; r < n && c < n; ++r, ++c )
A.setEntry(r,c,temp);
}
Toeplitz<NTL_zz_p,NTL_zz_pX> T( PF, poly, n );
NTL_zz_p::Element res1, res2;
//det(res1,A);
det(res1,T);
det(res2,T);
if( res1 != res2 ) pass = false;
//}
#else
report << "No test, because no NTL." << endl;
#endif
report << endl;
if( pass ) report << "<====== Passed!" << endl;
else report << "<====== Failed!" << endl;
commentator.stop("toeplitz determinant test suite");
return (pass ? 0 : 1);
#if 0
NTL_ZZ_pX F( 65521 );
NTL_ZZ_pX::Element a,b;
F.init(a,1);
F.init(b,4);
F.mulin(a,b);
F.write(cout,a) << endl;
F.write(cout) << endl;
NTL_ZZ_pX::Element T;
Toeplitz<NTL_ZZ_p> Q(F.getCoeffField());
vector<int> v;
v.push_back( -3 );
v.push_back( 50 );
v.push_back( 71 );
v.push_back( -43 );
v.push_back( 91 );
v.push_back( 16 );
v.push_back( 78 );
F.init(T,v);
Toeplitz<NTL_ZZ_p,NTL_ZZ_pX> mat( F, T, 4 );
Toeplitz<NTL_ZZ_p,NTL_ZZ_pX>::Element res;
//mat.det( res );
det(res,mat);
/*
F.init( T, v );
NTL_ZZ_pX::Coeff res;
toeplitz_determinant( F, res, T, 4 );
*/
//cout << res << endl;
commentator.stop("toeplitz determinant test suite");
#endif
}
<|endoftext|> |
<commit_before>//|||||||||||||||||||||||||||||||||||||||||||||||
#include "ValleyApp.hpp"
#include <OgreLight.h>
#include <OgreWindowEventUtilities.h>
#include <OgreStringConverter.h>
//|||||||||||||||||||||||||||||||||||||||||||||||
ValleyApp::ValleyApp()
{
m_pOgreHeadNode = 0;
m_pOgreHeadEntity = 0;
mTerrainsImported = false;
}
ValleyApp::~ValleyApp()
{
destroyScene();
delete OgreFramework::getSingletonPtr();
}
void ValleyApp::destroyScene(void)
{
OgreFramework::getSingletonPtr()->m_pLog->logMessage("Scene cleaned up!");
OGRE_DELETE mTerrainGroup;
OGRE_DELETE mTerrainGlobals;
}
void getTerrainImage(bool flipX, bool flipY, Ogre::Image& img)
{
img.load("2peaks.png", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
if (flipX)
img.flipAroundY();
if (flipY)
img.flipAroundX();
}
void ValleyApp::defineTerrain(long x, long y)
{
Ogre::String filename = mTerrainGroup->generateFilename(x, y);
if (Ogre::ResourceGroupManager::getSingleton().resourceExists(mTerrainGroup->getResourceGroup(), filename))
{
mTerrainGroup->defineTerrain(x, y);
}
else
{
Ogre::Image img;
getTerrainImage(x % 2 != 0, y % 2 != 0, img);
mTerrainGroup->defineTerrain(x, y, &img);
mTerrainsImported = true;
}
}
void ValleyApp::configureTerrainDefaults(Ogre::Light* light)
{
// Configure global
mTerrainGlobals->setMaxPixelError(8);
// testing composite map
mTerrainGlobals->setCompositeMapDistance(30000);
// Important to set these so that the terrain knows what to use for derived (non-realtime) data
mTerrainGlobals->setLightMapDirection(light->getDerivedDirection());
mTerrainGlobals->setCompositeMapAmbient(OgreFramework::getSingletonPtr()->m_pSceneMgr->getAmbientLight());
mTerrainGlobals->setCompositeMapDiffuse(light->getDiffuseColour());
// Configure default import settings for if we use imported image
Ogre::Terrain::ImportData& defaultimp = mTerrainGroup->getDefaultImportSettings();
defaultimp.terrainSize = 513;
defaultimp.worldSize = 12000.0f;
defaultimp.inputScale = 600*6;
defaultimp.minBatchSize = 33;
defaultimp.maxBatchSize = 65;
// textures
defaultimp.layerList.resize(3);
defaultimp.layerList[0].worldSize = 100;
defaultimp.layerList[0].textureNames.push_back("dirt_grayrocky_diffusespecular.dds");
defaultimp.layerList[0].textureNames.push_back("dirt_grayrocky_normalheight.dds");
defaultimp.layerList[1].worldSize = 30;
defaultimp.layerList[1].textureNames.push_back("grass_green-01_diffusespecular.dds");
defaultimp.layerList[1].textureNames.push_back("grass_green-01_normalheight.dds");
defaultimp.layerList[2].worldSize = 200;
defaultimp.layerList[2].textureNames.push_back("growth_weirdfungus-03_diffusespecular.dds");
defaultimp.layerList[2].textureNames.push_back("growth_weirdfungus-03_normalheight.dds");
}
void ValleyApp::initBlendMaps(Ogre::Terrain* terrain)
{
Ogre::TerrainLayerBlendMap* blendMap0 = terrain->getLayerBlendMap(1);
Ogre::TerrainLayerBlendMap* blendMap1 = terrain->getLayerBlendMap(2);
Ogre::Real minHeight0 = 70;
Ogre::Real fadeDist0 = 40;
Ogre::Real minHeight1 = 70;
Ogre::Real fadeDist1 = 15;
float* pBlend1 = blendMap1->getBlendPointer();
for (Ogre::uint16 y = 0; y < terrain->getLayerBlendMapSize(); ++y)
{
for (Ogre::uint16 x = 0; x < terrain->getLayerBlendMapSize(); ++x)
{
Ogre::Real tx, ty;
blendMap0->convertImageToTerrainSpace(x, y, &tx, &ty);
Ogre::Real height = terrain->getHeightAtTerrainPosition(tx, ty);
Ogre::Real val = (height - minHeight0) / fadeDist0;
val = Ogre::Math::Clamp(val, (Ogre::Real)0, (Ogre::Real)1);
*plend0++ = val;
val = (height - minHeight1) / fadeDist1;
val = Ogre::Math::Clamp(val, (Ogre::Real)0, (Ogre::Real)1);
*pBlend1++ = val;
}
}
blendMap0->dirty();
blendMap1->dirty();
blendMap0->update();
blendMap1->update();
}
void ValleyApp::startGame()
{
new OgreFramework();
if(!OgreFramework::getSingletonPtr()->initOgre("ValleyApp v1.0", this, 0))
return;
m_bShutdown = false;
OgreFramework::getSingletonPtr()->m_pLog->logMessage("Game initialized!");
setupGameScene();
runGame();
}
//|||||||||||||||||||||||||||||||||||||||||||||||
void ValleyApp::setupGameScene()
{
OgreFramework::getSingletonPtr()->m_pCamera->setPosition(Ogre::Vector3(1683, 1000, 2116));
OgreFramework::getSingletonPtr()->m_pCamera->lookAt(Ogre::Vector3(0, 0, 0));
OgreFramework::getSingletonPtr()->m_pCamera->setNearClipDistance(0.1);
OgreFramework::getSingletonPtr()->m_pCamera->setFarClipDistance(50000);
if (OgreFramework::getSingletonPtr()->m_pRoot->getRenderSystem()->getCapabilities()->hasCapability(Ogre::RSC_INFINITE_FAR_PLANE))
{
OgreFramework::getSingletonPtr()->m_pCamera->setFarClipDistance(0); // enable infinite far clip distance if we can
}
// Play with startup Texture Filtering options
// Note: Pressing T on runtime will discarde those settings
// Ogre::MaterialManager::getSingleton().setDefaultTextureFiltering(Ogre::TFO_ANISOTROPIC);
// Ogre::MaterialManager::getSingleton().setDefaultAnisotropy(7);
//Ogre::Vector3 lightdir(0.55, -0.3, 0.75);
Ogre::Vector3 lightdir(0.2, -1.0, 0.2);
lightdir.normalise();
Ogre::Light* light = OgreFramework::getSingletonPtr()->m_pSceneMgr->createLight("tstLight");
light->setType(Ogre::Light::LT_DIRECTIONAL);
light->setDirection(lightdir);
light->setDiffuseColour(Ogre::ColourValue::White);
light->setSpecularColour(Ogre::ColourValue(0.4, 0.4, 0.4));
OgreFramework::getSingletonPtr()->m_pSceneMgr->setAmbientLight(Ogre::ColourValue(0.2, 0.2, 0.2));
mTerrainGlobals = OGRE_NEW Ogre::TerrainGlobalOptions();
mTerrainGroup = OGRE_NEW Ogre::TerrainGroup(OgreFramework::getSingletonPtr()->m_pSceneMgr, Ogre::Terrain::ALIGN_X_Z, 513, 12000.0f);
mTerrainGroup->setFilenameConvention(Ogre::String("ValleyTerrain"), Ogre::String("dat"));
mTerrainGroup->setOrigin(Ogre::Vector3::ZERO);
configureTerrainDefaults(light);
for (long x = 0; x <= 0; ++x)
for (long y = 0; y <= 0; ++y)
defineTerrain(x, y);
// sync load since we want everything in place when we start
mTerrainGroup->loadAllTerrains(true);
if (mTerrainsImported)
{
Ogre::TerrainGroup::TerrainIterator ti = mTerrainGroup->getTerrainIterator();
while(ti.hasMoreElements())
{
Ogre::Terrain* t = ti.getNext()->instance;
initBlendMaps(t);
}
}
mTerrainGroup->freeTemporaryResources();
// Ogre::ColourValue fadeColour(0.9, 0.9, 0.9);
// //OgreFramework::getSingletonPtr()->m_pSceneMgr->setFog(Ogre::FOG_LINEAR, fadeColour, 0.0, 10, 1200);
// OgreFramework::getSingletonPtr()->m_pViewport->setBackgroundColour(fadeColour);
//
// Ogre::Plane plane;
// plane.d = 100;
// plane.normal = Ogre::Vector3::NEGATIVE_UNIT_Y;
//mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8, 500);
//OgreFramework::getSingletonPtr()->m_pSceneMgr->setSkyPlane(true, plane, "Examples/CloudySky", 500, 20, true, 0.5, 150, 150);
// OgreFramework::getSingletonPtr()->m_pSceneMgr->setSkyBox(true, "Examples/SpaceSkyBox");
//
//
// m_pOgreHeadEntity = OgreFramework::getSingletonPtr()->m_pSceneMgr->createEntity("OgreHeadEntity", "ogrehead.mesh");
// m_pOgreHeadNode = OgreFramework::getSingletonPtr()->m_pSceneMgr->getRootSceneNode()->createChildSceneNode("OgreHeadNode");
// m_pOgreHeadNode->attachObject(m_pOgreHeadEntity);
}
void ValleyApp::runGame()
{
OgreFramework::getSingletonPtr()->m_pLog->logMessage("Start main loop...");
int timeSinceLastFrame = 0;
int startTime = 0;
OgreFramework::getSingletonPtr()->m_pRenderWnd->resetStatistics();
while(!m_bShutdown && !OgreFramework::getSingletonPtr()->isOgreToBeShutDown())
{
if(OgreFramework::getSingletonPtr()->m_pRenderWnd->isClosed())m_bShutdown = true;
Ogre::WindowEventUtilities::messagePump();
if(OgreFramework::getSingletonPtr()->m_pRenderWnd->isActive())
{
startTime = OgreFramework::getSingletonPtr()->m_pTimer->getMilliseconds();
OgreFramework::getSingletonPtr()->m_pKeyboard->capture();
OgreFramework::getSingletonPtr()->m_pMouse->capture();
OgreFramework::getSingletonPtr()->updateOgre(timeSinceLastFrame);
OgreFramework::getSingletonPtr()->m_pRoot->renderOneFrame();
timeSinceLastFrame = OgreFramework::getSingletonPtr()->m_pTimer->getMilliseconds() - startTime;
}
else
{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
Sleep(1000);
#else
sleep(1);
#endif
}
}
OgreFramework::getSingletonPtr()->m_pLog->logMessage("Main loop quit");
OgreFramework::getSingletonPtr()->m_pLog->logMessage("Shutdown OGRE...");
}
//|||||||||||||||||||||||||||||||||||||||||||||||
bool ValleyApp::keyPressed(const OIS::KeyEvent &keyEventRef)
{
OgreFramework::getSingletonPtr()->keyPressed(keyEventRef);
if(OgreFramework::getSingletonPtr()->m_pKeyboard->isKeyDown(OIS::KC_F))
{
//do something
}
return true;
}
//|||||||||||||||||||||||||||||||||||||||||||||||
bool ValleyApp::keyReleased(const OIS::KeyEvent &keyEventRef)
{
OgreFramework::getSingletonPtr()->keyReleased(keyEventRef);
return true;
}
//|||||||||||||||||||||||||||||||||||||||||||||||
<commit_msg>Fixed bug with textures, added a manual object usage<commit_after>//|||||||||||||||||||||||||||||||||||||||||||||||
#include "ValleyApp.hpp"
#include <OgreLight.h>
#include <OgreWindowEventUtilities.h>
#include <OgreStringConverter.h>
#include <OgreManualObject.h>
//|||||||||||||||||||||||||||||||||||||||||||||||
ValleyApp::ValleyApp()
{
m_pOgreHeadNode = 0;
m_pOgreHeadEntity = 0;
mTerrainsImported = false;
}
ValleyApp::~ValleyApp()
{
destroyScene();
delete OgreFramework::getSingletonPtr();
}
void ValleyApp::destroyScene(void)
{
OgreFramework::getSingletonPtr()->m_pLog->logMessage("Scene cleaned up!");
OGRE_DELETE mTerrainGroup;
OGRE_DELETE mTerrainGlobals;
}
void getTerrainImage(bool flipX, bool flipY, Ogre::Image& img)
{
img.load("heightmap.bmp", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
if (flipX)
img.flipAroundY();
if (flipY)
img.flipAroundX();
}
void ValleyApp::defineTerrain(long x, long y)
{
Ogre::String filename = mTerrainGroup->generateFilename(x, y);
if (Ogre::ResourceGroupManager::getSingleton().resourceExists(mTerrainGroup->getResourceGroup(), filename))
{
mTerrainGroup->defineTerrain(x, y);
}
else
{
Ogre::Image img;
getTerrainImage(x % 2 != 0, y % 2 != 0, img);
mTerrainGroup->defineTerrain(x, y, &img);
mTerrainsImported = true;
}
}
void ValleyApp::configureTerrainDefaults(Ogre::Light* light)
{
// Configure global
mTerrainGlobals->setMaxPixelError(8);
// testing composite map
mTerrainGlobals->setCompositeMapDistance(30000);
// Important to set these so that the terrain knows what to use for derived (non-realtime) data
mTerrainGlobals->setLightMapDirection(light->getDerivedDirection());
mTerrainGlobals->setCompositeMapAmbient(OgreFramework::getSingletonPtr()->m_pSceneMgr->getAmbientLight());
mTerrainGlobals->setCompositeMapDiffuse(light->getDiffuseColour());
// Configure default import settings for if we use imported image
Ogre::Terrain::ImportData& defaultimp = mTerrainGroup->getDefaultImportSettings();
defaultimp.terrainSize = 513;
defaultimp.worldSize = 12000.0f;
defaultimp.inputScale = 600*6;
defaultimp.minBatchSize = 33;
defaultimp.maxBatchSize = 65;
// textures
defaultimp.layerList.resize(3);
defaultimp.layerList[0].worldSize = 100;
defaultimp.layerList[0].textureNames.push_back("dirt_grayrocky_diffusespecular.dds");
defaultimp.layerList[0].textureNames.push_back("dirt_grayrocky_normalheight.dds");
defaultimp.layerList[1].worldSize = 30;
defaultimp.layerList[1].textureNames.push_back("grass_green-01_diffusespecular.dds");
defaultimp.layerList[1].textureNames.push_back("grass_green-01_normalheight.dds");
defaultimp.layerList[2].worldSize = 200;
defaultimp.layerList[2].textureNames.push_back("growth_weirdfungus-03_diffusespecular.dds");
defaultimp.layerList[2].textureNames.push_back("growth_weirdfungus-03_normalheight.dds");
}
void ValleyApp::initBlendMaps(Ogre::Terrain* terrain)
{
Ogre::TerrainLayerBlendMap* blendMap0 = terrain->getLayerBlendMap(1);
Ogre::TerrainLayerBlendMap* blendMap1 = terrain->getLayerBlendMap(2);
Ogre::Real minHeight0 = 70;
Ogre::Real fadeDist0 = 40;
Ogre::Real minHeight1 = 70;
Ogre::Real fadeDist1 = 15;
float* pBlend0 = blendMap0->getBlendPointer();
float* pBlend1 = blendMap1->getBlendPointer();
for (Ogre::uint16 y = 0; y < terrain->getLayerBlendMapSize(); ++y)
{
for (Ogre::uint16 x = 0; x < terrain->getLayerBlendMapSize(); ++x)
{
Ogre::Real tx, ty;
blendMap0->convertImageToTerrainSpace(x, y, &tx, &ty);
Ogre::Real height = terrain->getHeightAtTerrainPosition(tx, ty);
Ogre::Real val = (height - minHeight0) / fadeDist0;
val = Ogre::Math::Clamp(val, (Ogre::Real)0, (Ogre::Real)1);
*pBlend0++ = val;
val = (height - minHeight1) / fadeDist1;
val = Ogre::Math::Clamp(val, (Ogre::Real)0, (Ogre::Real)1);
*pBlend1++ = val;
}
}
blendMap0->dirty();
blendMap1->dirty();
blendMap0->update();
blendMap1->update();
}
void ValleyApp::startGame()
{
new OgreFramework();
if(!OgreFramework::getSingletonPtr()->initOgre("ValleyApp v1.0", this, 0))
return;
m_bShutdown = false;
OgreFramework::getSingletonPtr()->m_pLog->logMessage("Game initialized!");
setupGameScene();
runGame();
}
//|||||||||||||||||||||||||||||||||||||||||||||||
void ValleyApp::setupGameScene()
{
OgreFramework::getSingletonPtr()->m_pCamera->setPosition(Ogre::Vector3(1683, 1000, 2116));
OgreFramework::getSingletonPtr()->m_pCamera->lookAt(Ogre::Vector3(0, 0, 0));
OgreFramework::getSingletonPtr()->m_pCamera->setNearClipDistance(0.1);
OgreFramework::getSingletonPtr()->m_pCamera->setFarClipDistance(50000);
if (OgreFramework::getSingletonPtr()->m_pRoot->getRenderSystem()->getCapabilities()->hasCapability(Ogre::RSC_INFINITE_FAR_PLANE))
{
OgreFramework::getSingletonPtr()->m_pCamera->setFarClipDistance(0); // enable infinite far clip distance if we can
}
// Play with startup Texture Filtering options
// Note: Pressing T on runtime will discarde those settings
// Ogre::MaterialManager::getSingleton().setDefaultTextureFiltering(Ogre::TFO_ANISOTROPIC);
// Ogre::MaterialManager::getSingleton().setDefaultAnisotropy(7);
//Ogre::Vector3 lightdir(0.55, -0.3, 0.75);
Ogre::Vector3 lightdir(0.2, -1.0, 0.2);
lightdir.normalise();
Ogre::Light* light = OgreFramework::getSingletonPtr()->m_pSceneMgr->createLight("tstLight");
light->setType(Ogre::Light::LT_DIRECTIONAL);
light->setDirection(lightdir);
light->setDiffuseColour(Ogre::ColourValue::White);
light->setSpecularColour(Ogre::ColourValue(0.4, 0.4, 0.4));
OgreFramework::getSingletonPtr()->m_pSceneMgr->setAmbientLight(Ogre::ColourValue(0.2, 0.2, 0.2));
mTerrainGlobals = OGRE_NEW Ogre::TerrainGlobalOptions();
mTerrainGroup = OGRE_NEW Ogre::TerrainGroup(OgreFramework::getSingletonPtr()->m_pSceneMgr, Ogre::Terrain::ALIGN_X_Z, 513, 12000.0f);
mTerrainGroup->setFilenameConvention(Ogre::String("ValleyTerrain"), Ogre::String("dat"));
mTerrainGroup->setOrigin(Ogre::Vector3::ZERO);
configureTerrainDefaults(light);
for (long x = 0; x <= 0; ++x)
for (long y = 0; y <= 0; ++y)
defineTerrain(x, y);
// sync load since we want everything in place when we start
mTerrainGroup->loadAllTerrains(true);
if (mTerrainsImported)
{
Ogre::TerrainGroup::TerrainIterator ti = mTerrainGroup->getTerrainIterator();
while(ti.hasMoreElements())
{
Ogre::Terrain* t = ti.getNext()->instance;
initBlendMaps(t);
}
}
mTerrainGroup->freeTemporaryResources();
Ogre::ManualObject* manual = OgreFramework::getSingletonPtr()->m_pSceneMgr->createManualObject("manual");
manual->begin("BaseWhiteNoLighting", Ogre::RenderOperation::OT_TRIANGLE_FAN);
manual->position(-200, -200, 0);
manual->position( 200, -200, 0);
manual->position( 200, 200, 0);
manual->position(-200, 200, 0);
manual->end();
OgreFramework::getSingletonPtr()->m_pSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(manual);
// Ogre::ColourValue fadeColour(0.9, 0.9, 0.9);
// //OgreFramework::getSingletonPtr()->m_pSceneMgr->setFog(Ogre::FOG_LINEAR, fadeColour, 0.0, 10, 1200);
// OgreFramework::getSingletonPtr()->m_pViewport->setBackgroundColour(fadeColour);
//
// Ogre::Plane plane;
// plane.d = 100;
// plane.normal = Ogre::Vector3::NEGATIVE_UNIT_Y;
//mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8, 500);
//OgreFramework::getSingletonPtr()->m_pSceneMgr->setSkyPlane(true, plane, "Examples/CloudySky", 500, 20, true, 0.5, 150, 150);
// OgreFramework::getSingletonPtr()->m_pSceneMgr->setSkyBox(true, "Examples/SpaceSkyBox");
//
//
// m_pOgreHeadEntity = OgreFramework::getSingletonPtr()->m_pSceneMgr->createEntity("OgreHeadEntity", "ogrehead.mesh");
// m_pOgreHeadNode = OgreFramework::getSingletonPtr()->m_pSceneMgr->getRootSceneNode()->createChildSceneNode("OgreHeadNode");
// m_pOgreHeadNode->attachObject(m_pOgreHeadEntity);
}
void ValleyApp::runGame()
{
OgreFramework::getSingletonPtr()->m_pLog->logMessage("Start main loop...");
int timeSinceLastFrame = 0;
int startTime = 0;
OgreFramework::getSingletonPtr()->m_pRenderWnd->resetStatistics();
while(!m_bShutdown && !OgreFramework::getSingletonPtr()->isOgreToBeShutDown())
{
if(OgreFramework::getSingletonPtr()->m_pRenderWnd->isClosed())m_bShutdown = true;
Ogre::WindowEventUtilities::messagePump();
if(OgreFramework::getSingletonPtr()->m_pRenderWnd->isActive())
{
startTime = OgreFramework::getSingletonPtr()->m_pTimer->getMilliseconds();
OgreFramework::getSingletonPtr()->m_pKeyboard->capture();
OgreFramework::getSingletonPtr()->m_pMouse->capture();
OgreFramework::getSingletonPtr()->updateOgre(timeSinceLastFrame);
OgreFramework::getSingletonPtr()->m_pRoot->renderOneFrame();
timeSinceLastFrame = OgreFramework::getSingletonPtr()->m_pTimer->getMilliseconds() - startTime;
}
else
{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
Sleep(1000);
#else
sleep(1);
#endif
}
}
OgreFramework::getSingletonPtr()->m_pLog->logMessage("Main loop quit");
OgreFramework::getSingletonPtr()->m_pLog->logMessage("Shutdown OGRE...");
}
//|||||||||||||||||||||||||||||||||||||||||||||||
bool ValleyApp::keyPressed(const OIS::KeyEvent &keyEventRef)
{
OgreFramework::getSingletonPtr()->keyPressed(keyEventRef);
if(OgreFramework::getSingletonPtr()->m_pKeyboard->isKeyDown(OIS::KC_F))
{
//do something
}
return true;
}
//|||||||||||||||||||||||||||||||||||||||||||||||
bool ValleyApp::keyReleased(const OIS::KeyEvent &keyEventRef)
{
OgreFramework::getSingletonPtr()->keyReleased(keyEventRef);
return true;
}
//|||||||||||||||||||||||||||||||||||||||||||||||
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.