text
stringlengths 54
60.6k
|
---|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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 [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdeclarativerepeater_p.h"
#include "qdeclarativerepeater_p_p.h"
#include "qdeclarativevisualitemmodel_p.h"
#include <qdeclarativelistaccessor_p.h>
#include <qlistmodelinterface_p.h>
QT_BEGIN_NAMESPACE
QDeclarativeRepeaterPrivate::QDeclarativeRepeaterPrivate()
: model(0), ownModel(false)
{
}
QDeclarativeRepeaterPrivate::~QDeclarativeRepeaterPrivate()
{
if (ownModel)
delete model;
}
/*!
\qmlclass Repeater QDeclarativeRepeater
\since 4.7
\inherits Item
\brief The Repeater item allows you to repeat a component based on a model.
The Repeater item is used when you want to create a large number of
similar items. For each entry in the model, an item is instantiated
in a context seeded with data from the model. If the repeater will
be instantiating a large number of instances, it may be more efficient to
use one of Qt Declarative's \l {xmlViews}{view items}.
The model may be either an object list, a string list, a number or a Qt model.
In each case, the data element and the index is exposed to each instantiated
component.
The index is always exposed as an accessible \c index property.
In the case of an object or string list, the data element (of type string
or object) is available as the \c modelData property. In the case of a Qt model,
all roles are available as named properties just like in the view classes. The
following example shows how to use the index property inside the instantiated
items.
\snippet doc/src/snippets/declarative/repeater-index.qml 0
\image repeater-index.png
Items instantiated by the Repeater are inserted, in order, as
children of the Repeater's parent. The insertion starts immediately after
the repeater's position in its parent stacking list. This is to allow
you to use a Repeater inside a layout. The following QML example shows how
the instantiated items would visually appear stacked between the red and
blue rectangles.
\snippet doc/src/snippets/declarative/repeater.qml 0
\image repeater.png
The repeater instance continues to own all items it instantiates, even
if they are otherwise manipulated. It is illegal to manually remove an item
created by the Repeater.
*/
/*!
\internal
\class QDeclarativeRepeater
\qmlclass Repeater
XXX Repeater is very conservative in how it instatiates/deletes items. Also
new model entries will not be created and old ones will not be removed.
*/
/*!
Create a new QDeclarativeRepeater instance.
*/
QDeclarativeRepeater::QDeclarativeRepeater(QDeclarativeItem *parent)
: QDeclarativeItem(*(new QDeclarativeRepeaterPrivate), parent)
{
}
/*!
Destroy the repeater instance. All items it instantiated are also
destroyed.
*/
QDeclarativeRepeater::~QDeclarativeRepeater()
{
}
/*!
\qmlproperty any Repeater::model
The model providing data for the repeater.
The model may be either an object list, a string list, a number or a Qt model.
In each case, the data element and the index is exposed to each instantiated
component. The index is always exposed as an accessible \c index property.
In the case of an object or string list, the data element (of type string
or object) is available as the \c modelData property. In the case of a Qt model,
all roles are available as named properties just like in the view classes.
As a special case the model can also be merely a number. In this case it will
create that many instances of the component. They will also be assigned an index
based on the order they are created.
Models can also be created directly in QML, using a \l{ListModel} or \l{XmlListModel}.
\sa {qmlmodels}{Data Models}
*/
QVariant QDeclarativeRepeater::model() const
{
Q_D(const QDeclarativeRepeater);
return d->dataSource;
}
void QDeclarativeRepeater::setModel(const QVariant &model)
{
Q_D(QDeclarativeRepeater);
if (d->dataSource == model)
return;
clear();
if (d->model) {
disconnect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int)));
disconnect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int)));
disconnect(d->model, SIGNAL(itemsMoved(int,int,int)), this, SLOT(itemsMoved(int,int,int)));
disconnect(d->model, SIGNAL(modelReset()), this, SLOT(modelReset()));
/*
disconnect(d->model, SIGNAL(createdItem(int, QDeclarativeItem*)), this, SLOT(createdItem(int,QDeclarativeItem*)));
disconnect(d->model, SIGNAL(destroyingItem(QDeclarativeItem*)), this, SLOT(destroyingItem(QDeclarativeItem*)));
*/
}
d->dataSource = model;
emit modelChanged();
QObject *object = qvariant_cast<QObject*>(model);
QDeclarativeVisualModel *vim = 0;
if (object && (vim = qobject_cast<QDeclarativeVisualModel *>(object))) {
if (d->ownModel) {
delete d->model;
d->ownModel = false;
}
d->model = vim;
} else {
if (!d->ownModel) {
d->model = new QDeclarativeVisualDataModel(qmlContext(this));
d->ownModel = true;
}
if (QDeclarativeVisualDataModel *dataModel = qobject_cast<QDeclarativeVisualDataModel*>(d->model))
dataModel->setModel(model);
}
if (d->model) {
connect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int)));
connect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int)));
connect(d->model, SIGNAL(itemsMoved(int,int,int)), this, SLOT(itemsMoved(int,int,int)));
connect(d->model, SIGNAL(modelReset()), this, SLOT(modelReset()));
/*
connect(d->model, SIGNAL(createdItem(int, QDeclarativeItem*)), this, SLOT(createdItem(int,QDeclarativeItem*)));
connect(d->model, SIGNAL(destroyingItem(QDeclarativeItem*)), this, SLOT(destroyingItem(QDeclarativeItem*)));
*/
regenerate();
emit countChanged();
}
}
/*!
\qmlproperty Component Repeater::delegate
\default
The delegate provides a template defining each item instantiated by the repeater.
The index is exposed as an accessible \c index property. Properties of the
model are also available depending upon the type of \l {qmlmodels}{Data Model}.
*/
QDeclarativeComponent *QDeclarativeRepeater::delegate() const
{
Q_D(const QDeclarativeRepeater);
if (d->model) {
if (QDeclarativeVisualDataModel *dataModel = qobject_cast<QDeclarativeVisualDataModel*>(d->model))
return dataModel->delegate();
}
return 0;
}
void QDeclarativeRepeater::setDelegate(QDeclarativeComponent *delegate)
{
Q_D(QDeclarativeRepeater);
if (QDeclarativeVisualDataModel *dataModel = qobject_cast<QDeclarativeVisualDataModel*>(d->model))
if (delegate == dataModel->delegate())
return;
if (!d->ownModel) {
d->model = new QDeclarativeVisualDataModel(qmlContext(this));
d->ownModel = true;
}
if (QDeclarativeVisualDataModel *dataModel = qobject_cast<QDeclarativeVisualDataModel*>(d->model)) {
dataModel->setDelegate(delegate);
regenerate();
emit delegateChanged();
}
}
/*!
\qmlproperty int Repeater::count
This property holds the number of items in the repeater.
*/
int QDeclarativeRepeater::count() const
{
Q_D(const QDeclarativeRepeater);
if (d->model)
return d->model->count();
return 0;
}
/*!
\internal
*/
void QDeclarativeRepeater::componentComplete()
{
QDeclarativeItem::componentComplete();
regenerate();
}
/*!
\internal
*/
QVariant QDeclarativeRepeater::itemChange(GraphicsItemChange change,
const QVariant &value)
{
QVariant rv = QDeclarativeItem::itemChange(change, value);
if (change == ItemParentHasChanged) {
regenerate();
}
return rv;
}
void QDeclarativeRepeater::clear()
{
Q_D(QDeclarativeRepeater);
if (d->model) {
foreach (QDeclarativeItem *item, d->deletables) {
item->setParentItem(this);
d->model->release(item);
}
}
d->deletables.clear();
}
/*!
\internal
*/
void QDeclarativeRepeater::regenerate()
{
Q_D(QDeclarativeRepeater);
if (!isComponentComplete())
return;
clear();
if (!d->model || !d->model->count() || !d->model->isValid() || !parentItem() || !isComponentComplete())
return;
for (int ii = 0; ii < count(); ++ii) {
QDeclarativeItem *item = d->model->item(ii);
if (item) {
item->setParent(parentItem());
item->stackBefore(this);
d->deletables << item;
}
}
}
void QDeclarativeRepeater::itemsInserted(int index, int count)
{
Q_D(QDeclarativeRepeater);
if (!isComponentComplete())
return;
for (int i = 0; i < count; ++i) {
int modelIndex = index + i;
QDeclarativeItem *item = d->model->item(modelIndex);
if (item) {
item->setParent(parentItem());
if (modelIndex < d->deletables.count())
item->stackBefore(d->deletables.at(modelIndex));
else
item->stackBefore(this);
d->deletables.insert(modelIndex, item);
}
}
}
void QDeclarativeRepeater::itemsRemoved(int index, int count)
{
Q_D(QDeclarativeRepeater);
if (!isComponentComplete())
return;
while (count--) {
QDeclarativeItem *item = d->deletables.takeAt(index);
if (item) {
item->setParentItem(this);
d->model->release(item);
}
}
}
void QDeclarativeRepeater::itemsMoved(int from, int to, int count)
{
Q_D(QDeclarativeRepeater);
if (!isComponentComplete())
return;
QList<QDeclarativeItem*> removed;
int removedCount = count;
while (removedCount--)
removed << d->deletables.takeAt(from);
for (int i = 0; i < count; ++i)
d->deletables.insert(to + i, removed.at(i));
for (int i = 0; i < d->model->count(); ++i) {
if (i < from && i < to)
continue;
QDeclarativeItem *item = d->deletables.at(i);
if (i < d->deletables.count()-1)
item->stackBefore(d->deletables.at(i+1));
else
item->stackBefore(this);
}
}
void QDeclarativeRepeater::modelReset()
{
if (!isComponentComplete())
return;
regenerate();
}
QT_END_NAMESPACE
<commit_msg>Setting stacking order from top to bottom seems to work better.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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 [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdeclarativerepeater_p.h"
#include "qdeclarativerepeater_p_p.h"
#include "qdeclarativevisualitemmodel_p.h"
#include <qdeclarativelistaccessor_p.h>
#include <qlistmodelinterface_p.h>
QT_BEGIN_NAMESPACE
QDeclarativeRepeaterPrivate::QDeclarativeRepeaterPrivate()
: model(0), ownModel(false)
{
}
QDeclarativeRepeaterPrivate::~QDeclarativeRepeaterPrivate()
{
if (ownModel)
delete model;
}
/*!
\qmlclass Repeater QDeclarativeRepeater
\since 4.7
\inherits Item
\brief The Repeater item allows you to repeat a component based on a model.
The Repeater item is used when you want to create a large number of
similar items. For each entry in the model, an item is instantiated
in a context seeded with data from the model. If the repeater will
be instantiating a large number of instances, it may be more efficient to
use one of Qt Declarative's \l {xmlViews}{view items}.
The model may be either an object list, a string list, a number or a Qt model.
In each case, the data element and the index is exposed to each instantiated
component.
The index is always exposed as an accessible \c index property.
In the case of an object or string list, the data element (of type string
or object) is available as the \c modelData property. In the case of a Qt model,
all roles are available as named properties just like in the view classes. The
following example shows how to use the index property inside the instantiated
items.
\snippet doc/src/snippets/declarative/repeater-index.qml 0
\image repeater-index.png
Items instantiated by the Repeater are inserted, in order, as
children of the Repeater's parent. The insertion starts immediately after
the repeater's position in its parent stacking list. This is to allow
you to use a Repeater inside a layout. The following QML example shows how
the instantiated items would visually appear stacked between the red and
blue rectangles.
\snippet doc/src/snippets/declarative/repeater.qml 0
\image repeater.png
The repeater instance continues to own all items it instantiates, even
if they are otherwise manipulated. It is illegal to manually remove an item
created by the Repeater.
*/
/*!
\internal
\class QDeclarativeRepeater
\qmlclass Repeater
XXX Repeater is very conservative in how it instatiates/deletes items. Also
new model entries will not be created and old ones will not be removed.
*/
/*!
Create a new QDeclarativeRepeater instance.
*/
QDeclarativeRepeater::QDeclarativeRepeater(QDeclarativeItem *parent)
: QDeclarativeItem(*(new QDeclarativeRepeaterPrivate), parent)
{
}
/*!
Destroy the repeater instance. All items it instantiated are also
destroyed.
*/
QDeclarativeRepeater::~QDeclarativeRepeater()
{
}
/*!
\qmlproperty any Repeater::model
The model providing data for the repeater.
The model may be either an object list, a string list, a number or a Qt model.
In each case, the data element and the index is exposed to each instantiated
component. The index is always exposed as an accessible \c index property.
In the case of an object or string list, the data element (of type string
or object) is available as the \c modelData property. In the case of a Qt model,
all roles are available as named properties just like in the view classes.
As a special case the model can also be merely a number. In this case it will
create that many instances of the component. They will also be assigned an index
based on the order they are created.
Models can also be created directly in QML, using a \l{ListModel} or \l{XmlListModel}.
\sa {qmlmodels}{Data Models}
*/
QVariant QDeclarativeRepeater::model() const
{
Q_D(const QDeclarativeRepeater);
return d->dataSource;
}
void QDeclarativeRepeater::setModel(const QVariant &model)
{
Q_D(QDeclarativeRepeater);
if (d->dataSource == model)
return;
clear();
if (d->model) {
disconnect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int)));
disconnect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int)));
disconnect(d->model, SIGNAL(itemsMoved(int,int,int)), this, SLOT(itemsMoved(int,int,int)));
disconnect(d->model, SIGNAL(modelReset()), this, SLOT(modelReset()));
/*
disconnect(d->model, SIGNAL(createdItem(int, QDeclarativeItem*)), this, SLOT(createdItem(int,QDeclarativeItem*)));
disconnect(d->model, SIGNAL(destroyingItem(QDeclarativeItem*)), this, SLOT(destroyingItem(QDeclarativeItem*)));
*/
}
d->dataSource = model;
emit modelChanged();
QObject *object = qvariant_cast<QObject*>(model);
QDeclarativeVisualModel *vim = 0;
if (object && (vim = qobject_cast<QDeclarativeVisualModel *>(object))) {
if (d->ownModel) {
delete d->model;
d->ownModel = false;
}
d->model = vim;
} else {
if (!d->ownModel) {
d->model = new QDeclarativeVisualDataModel(qmlContext(this));
d->ownModel = true;
}
if (QDeclarativeVisualDataModel *dataModel = qobject_cast<QDeclarativeVisualDataModel*>(d->model))
dataModel->setModel(model);
}
if (d->model) {
connect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int)));
connect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int)));
connect(d->model, SIGNAL(itemsMoved(int,int,int)), this, SLOT(itemsMoved(int,int,int)));
connect(d->model, SIGNAL(modelReset()), this, SLOT(modelReset()));
/*
connect(d->model, SIGNAL(createdItem(int, QDeclarativeItem*)), this, SLOT(createdItem(int,QDeclarativeItem*)));
connect(d->model, SIGNAL(destroyingItem(QDeclarativeItem*)), this, SLOT(destroyingItem(QDeclarativeItem*)));
*/
regenerate();
emit countChanged();
}
}
/*!
\qmlproperty Component Repeater::delegate
\default
The delegate provides a template defining each item instantiated by the repeater.
The index is exposed as an accessible \c index property. Properties of the
model are also available depending upon the type of \l {qmlmodels}{Data Model}.
*/
QDeclarativeComponent *QDeclarativeRepeater::delegate() const
{
Q_D(const QDeclarativeRepeater);
if (d->model) {
if (QDeclarativeVisualDataModel *dataModel = qobject_cast<QDeclarativeVisualDataModel*>(d->model))
return dataModel->delegate();
}
return 0;
}
void QDeclarativeRepeater::setDelegate(QDeclarativeComponent *delegate)
{
Q_D(QDeclarativeRepeater);
if (QDeclarativeVisualDataModel *dataModel = qobject_cast<QDeclarativeVisualDataModel*>(d->model))
if (delegate == dataModel->delegate())
return;
if (!d->ownModel) {
d->model = new QDeclarativeVisualDataModel(qmlContext(this));
d->ownModel = true;
}
if (QDeclarativeVisualDataModel *dataModel = qobject_cast<QDeclarativeVisualDataModel*>(d->model)) {
dataModel->setDelegate(delegate);
regenerate();
emit delegateChanged();
}
}
/*!
\qmlproperty int Repeater::count
This property holds the number of items in the repeater.
*/
int QDeclarativeRepeater::count() const
{
Q_D(const QDeclarativeRepeater);
if (d->model)
return d->model->count();
return 0;
}
/*!
\internal
*/
void QDeclarativeRepeater::componentComplete()
{
QDeclarativeItem::componentComplete();
regenerate();
}
/*!
\internal
*/
QVariant QDeclarativeRepeater::itemChange(GraphicsItemChange change,
const QVariant &value)
{
QVariant rv = QDeclarativeItem::itemChange(change, value);
if (change == ItemParentHasChanged) {
regenerate();
}
return rv;
}
void QDeclarativeRepeater::clear()
{
Q_D(QDeclarativeRepeater);
if (d->model) {
foreach (QDeclarativeItem *item, d->deletables) {
item->setParentItem(this);
d->model->release(item);
}
}
d->deletables.clear();
}
/*!
\internal
*/
void QDeclarativeRepeater::regenerate()
{
Q_D(QDeclarativeRepeater);
if (!isComponentComplete())
return;
clear();
if (!d->model || !d->model->count() || !d->model->isValid() || !parentItem() || !isComponentComplete())
return;
for (int ii = 0; ii < count(); ++ii) {
QDeclarativeItem *item = d->model->item(ii);
if (item) {
item->setParent(parentItem());
item->stackBefore(this);
d->deletables << item;
}
}
}
void QDeclarativeRepeater::itemsInserted(int index, int count)
{
Q_D(QDeclarativeRepeater);
if (!isComponentComplete())
return;
for (int i = 0; i < count; ++i) {
int modelIndex = index + i;
QDeclarativeItem *item = d->model->item(modelIndex);
if (item) {
item->setParent(parentItem());
if (modelIndex < d->deletables.count())
item->stackBefore(d->deletables.at(modelIndex));
else
item->stackBefore(this);
d->deletables.insert(modelIndex, item);
}
}
}
void QDeclarativeRepeater::itemsRemoved(int index, int count)
{
Q_D(QDeclarativeRepeater);
if (!isComponentComplete())
return;
while (count--) {
QDeclarativeItem *item = d->deletables.takeAt(index);
if (item) {
item->setParentItem(this);
d->model->release(item);
}
}
}
void QDeclarativeRepeater::itemsMoved(int from, int to, int count)
{
Q_D(QDeclarativeRepeater);
if (!isComponentComplete())
return;
QList<QDeclarativeItem*> removed;
int removedCount = count;
while (removedCount--)
removed << d->deletables.takeAt(from);
for (int i = 0; i < count; ++i)
d->deletables.insert(to + i, removed.at(i));
d->deletables.last()->stackBefore(this);
for (int i = d->model->count()-1; i > 0; --i) {
QDeclarativeItem *item = d->deletables.at(i-1);
item->stackBefore(d->deletables.at(i));
}
}
void QDeclarativeRepeater::modelReset()
{
if (!isComponentComplete())
return;
regenerate();
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>#include <iostream>
const int GLOB = 0;
class T {
public:
T(int t) : _t{t} { std::cout << "T()\n"; }
T(T &t) : _t{t._t} { std::cout << "T(&)\n"; }
T(T &&t) : _t{t._t} { std::cout << "T(&&)\n"; }
~T(void) { std::cout << "~T()\n"; }
private:
int _t;
};
T getT(void)
{
T t{1};
return t;
}
// Note! RValue references must not be named! point of move( x ) is to remove
// name from scope to force a rvalue reference.
int main(void)
{
// lvalue
int a; // cell (s1) + capability to access it ('a').
// rvalue
(void) 1; // literal value 1, no capability to access it / identify it beyond
// the semicolumn.
// lvalue + rvalue
a = 1; // store rvalue (1) into cell (s1) using capability 'a'.
// Notes: values (rvalues) can be stored into a cell through a capability
// (lvalue).
// lvalue (pointers)
int *b; // cell (s2 [for pointer val] + capability to access it ('b')
// + 'derefernce' operation on capability
// best to think of pointers as a type that stores a capability.
// I.e., it reifies as a value a capability. So while 'a' is a
// capabilty to access the cell s1, 'b' is a capability to access the
// cell s2, which itself can store a capability.
//
// 'dereference' operation, invokes the capability stored in s2,
// access the cell it identifies.
// *b = 0 // error as we have yet to store a capability in cell s2.
(void) &a; // reify capability 'a' into a rvalue.
b = &a; // store capability 'a' into cell s2 using capability 'b'.
// &9; // error as can't derive a new capability (lvalue) from an rvalue....
// what cell would it be for?
// lvalue references
int &c = a; // creates a new capability 'a' to access the cell s1
// identified by capability 'a'.
// int &c; // error as need to refer to an existing capability when creating
// new one.
int &c1 = c; // create another capability 'c1' to access cell s1
c = 0; // update cell (s1) to store the rvalue 0 using capability 'c'.
a = 0; // equivalent to above, but using capability 'a'.
// Note: the cell that a capability identifies can't be changed after
// declaration. Pointers provide an ability to achieve operations that
// utilize this feature, but they do so through a layer of indirection where
// a capability has been reified into a rvalue stored in the cell that the
// pointer type capability identifies.
int d = a; // creates cell (s3) with capability 'd' to access it + stores a
// copy of the rvalue in cell s1 referenced by capability 'a'.
// lvalue references (more)
// int &e = 0; // error as 0 is an rvalue, and we need an lvalue to create a
// new capability, since what cell would 'e' be a capability
// for in this situation?
const int &e = 0; // OK as since 'e' is a capability to only access (but not
// modify) a cell, we can create it from an rvalue.
// Why want? If the type was expensive to copy, this gives
// us a constant reference to a literal.
// (int&) e = 1; // may work or fail depending on how the compiler allocated '0'.
// const int &e = GLOB;
// (int&) e = 1; // extremely likely to segfault as GLOB allocated in
// read-only text section.
// rvalue references
int &&f = 0; // create cell (s4) and capability to access it 'f' + store 0;
f = 1;
// rvalue references (move)
int &&g = 1;
int &h = g;
int &&i = std::move(g);
int &&j = 2;
std::cout << "&g: " << &g << std::endl;
std::cout << "&h: " << &h << std::endl;
std::cout << "&i: " << &i << std::endl;
std::cout << "j: " << j << std::endl;
std::cout << "&j: " << &j << std::endl;
j = std::move(g);
std::cout << "j: " << j << std::endl;
std::cout << "&j: " << &j << std::endl;
// why rvalue references?
T&& t = getT();
return 0;
}
<commit_msg>More play with rvalue references<commit_after>#include <iostream>
const int GLOB = 0;
class T {
public:
T(int t) : _t{t} { std::cout << "T()\n"; }
~T(void) { std::cout << "~T()\n"; }
T(const T &t) : _t{t._t} { std::cout << "T(&)\n"; }
T & operator=(const T &t) { std::cout << "=(T&)\n"; return *this; }
// T(const T &t) = delete;
// T & operator=(const T &t) = delete;
T(T &&t) : _t{t._t} { std::cout << "T(&&)\n"; }
T & operator=(T &&t) { std::cout << "=(T&&)\n"; return *this; }
// T(T &&) = delete;
// T & operator=(T &&) = delete;
private:
int _t;
};
T getT(void)
{
T t{1};
return t;
}
void fun(T && t)
{
// You want to use an rvalue reference argument when moving the value inside
// the function, you can get away with a normal reference, but the type is
// less descriptive (i.e., doesn't communicate the move to the caller).
// T t2 = std::move(t);
std::cout << "fun(T&&)\n";
return;
}
// Note! RValue references must not be named! point of move( x ) is to remove
// name from scope to force a rvalue reference.
int main(void)
{
// lvalue
int a; // cell (s1) + capability to access it ('a').
// rvalue
(void) 1; // literal value 1, no capability to access it / identify it beyond
// the semicolumn.
// lvalue + rvalue
a = 1; // store rvalue (1) into cell (s1) using capability 'a'.
// Notes: values (rvalues) can be stored into a cell through a capability
// (lvalue).
// lvalue (pointers)
int *b; // cell (s2 [for pointer val] + capability to access it ('b')
// + 'derefernce' operation on capability
// best to think of pointers as a type that stores a capability.
// I.e., it reifies as a value a capability. So while 'a' is a
// capabilty to access the cell s1, 'b' is a capability to access the
// cell s2, which itself can store a capability.
//
// 'dereference' operation, invokes the capability stored in s2,
// access the cell it identifies.
// *b = 0 // error as we have yet to store a capability in cell s2.
(void) &a; // reify capability 'a' into a rvalue.
b = &a; // store capability 'a' into cell s2 using capability 'b'.
// &9; // error as can't derive a new capability (lvalue) from an rvalue....
// what cell would it be for?
// lvalue references
int &c = a; // creates a new capability 'a' to access the cell s1
// identified by capability 'a'.
// int &c; // error as need to refer to an existing capability when creating
// new one.
int &c1 = c; // create another capability 'c1' to access cell s1
c = 0; // update cell (s1) to store the rvalue 0 using capability 'c'.
a = 0; // equivalent to above, but using capability 'a'.
// Note: the cell that a capability identifies can't be changed after
// declaration. Pointers provide an ability to achieve operations that
// utilize this feature, but they do so through a layer of indirection where
// a capability has been reified into a rvalue stored in the cell that the
// pointer type capability identifies.
int d = a; // creates cell (s3) with capability 'd' to access it + stores a
// copy of the rvalue in cell s1 referenced by capability 'a'.
// lvalue references (more)
// int &e = 0; // error as 0 is an rvalue, and we need an lvalue to create a
// new capability, since what cell would 'e' be a capability
// for in this situation?
const int &e = 0; // OK as since 'e' is a capability to only access (but not
// modify) a cell, we can create it from an rvalue.
// Why want? If the type was expensive to copy, this gives
// us a constant reference to a literal.
// (int&) e = 1; // may work or fail depending on how the compiler allocated '0'.
// const int &e = GLOB;
// (int&) e = 1; // extremely likely to segfault as GLOB allocated in
// read-only text section.
// rvalue references
int &&f = 0; // create cell (s4) and capability to access it 'f' + store 0;
f = 1;
// rvalue references (move)
int &&g = 1;
int &h = g;
int &&i = std::move(g);
int &&j = 2;
std::cout << "&g: " << &g << std::endl;
std::cout << "&h: " << &h << std::endl;
std::cout << "&i: " << &i << std::endl;
std::cout << "j: " << j << std::endl;
std::cout << "&j: " << &j << std::endl;
j = std::move(g);
std::cout << "j: " << j << std::endl;
std::cout << "&j: " << &j << std::endl;
// why rvalue references?
T&& t = getT();
std::cout << "end...\n";
fun(std::move(t));
return 0;
}
<|endoftext|> |
<commit_before>#pragma once
#include <cstddef> // std::size_t
#include <new> // std::bad_array_new_length
#include <limits> // std::numeric_limits
namespace cdp
{
// Allocator requirements: 17.6.3.5
/// A basic reference C++11 allocator mostly for testing and documenting requirements from the standard
template <typename T>
class ReferenceAllocator
{
public:
using value_type = T;
/// Default constructor
ReferenceAllocator(...) noexcept {}
/// Copy constructor
ReferenceAllocator(const ReferenceAllocator& original) = default;
/// Move constructor
ReferenceAllocator(ReferenceAllocator&& original) = default;
/// Destructor
~ReferenceAllocator() = default;
/// Copy assignment operator
ReferenceAllocator& operator = (const ReferenceAllocator& rhs) = default;
/// Move assignment operator
ReferenceAllocator& operator = (ReferenceAllocator&& rhs) = default;
/// Rebind constructor
template <typename U>
ReferenceAllocator(const ReferenceAllocator<U>& original) noexcept {}
T* allocate(const std::size_t n) const
{
if (n > std::numeric_limits<std::size_t>::max()/sizeof(T))
throw std::bad_array_new_length{};
// 18.6.1.1/3 and 18.6.1.2: returns properly-aligned pointer, throws std::bad_alloc on error
return static_cast<T*>(::operator new[](sizeof(T)*n));
}
void deallocate(T* const p, std::size_t) const noexcept
{
::operator delete[](p); // 18.6.1.2: doesn't throw
}
};
template <typename T, typename U>
inline bool operator == (const ReferenceAllocator<T>& lhs, const ReferenceAllocator<U>& rhs) noexcept
{
return true;
}
template <typename T, typename U>
inline bool operator != (const ReferenceAllocator<T>& lhs, const ReferenceAllocator<U>& rhs) noexcept
{
return false;
}
}<commit_msg>Added non-const check to T of ReferenceAllocator<T><commit_after>#pragma once
#include <cstddef> // std::size_t
#include <new> // std::bad_array_new_length
#include <limits> // std::numeric_limits
#include <type_traits> // std::is_const
namespace cdp
{
// Allocator requirements: 17.6.3.5
/// A basic reference C++11 allocator mostly for testing and documenting requirements from the standard
template <typename T>
class ReferenceAllocator
{
static_assert(!std::is_const<T>::value, "Allocated type must be non-const (17.6.3.5/2)");
public:
using value_type = T;
/// Default constructor
ReferenceAllocator(...) noexcept {}
/// Copy constructor
ReferenceAllocator(const ReferenceAllocator& original) = default;
/// Move constructor
ReferenceAllocator(ReferenceAllocator&& original) = default;
/// Destructor
~ReferenceAllocator() = default;
/// Copy assignment operator
ReferenceAllocator& operator = (const ReferenceAllocator& rhs) = default;
/// Move assignment operator
ReferenceAllocator& operator = (ReferenceAllocator&& rhs) = default;
/// Rebind constructor
template <typename U>
ReferenceAllocator(const ReferenceAllocator<U>& original) noexcept {}
T* allocate(const std::size_t n) const
{
if (n > std::numeric_limits<std::size_t>::max()/sizeof(T))
throw std::bad_array_new_length{};
// 18.6.1.1/3 and 18.6.1.2: returns properly-aligned pointer, throws std::bad_alloc on error
return static_cast<T*>(::operator new[](sizeof(T)*n));
}
void deallocate(T* const p, std::size_t) const noexcept
{
::operator delete[](p); // 18.6.1.2: doesn't throw
}
};
template <typename T, typename U>
inline bool operator == (const ReferenceAllocator<T>& lhs, const ReferenceAllocator<U>& rhs) noexcept
{
return true;
}
template <typename T, typename U>
inline bool operator != (const ReferenceAllocator<T>& lhs, const ReferenceAllocator<U>& rhs) noexcept
{
return false;
}
}<|endoftext|> |
<commit_before>/**
*
* HX711 library for Arduino
* https://github.com/bogde/HX711
*
* MIT License
* (c) 2018 Bogdan Necula
*
**/
#include <Arduino.h>
#include <HX711.h>
#if defined(ARDUINO) && ARDUINO <= 106
// "yield" is not implemented as noop in older Arduino Core releases, so let's define it.
// See also: https://stackoverflow.com/questions/34497758/what-is-the-secret-of-the-arduino-yieldfunction/34498165#34498165
void yield(void) {};
#endif
#if defined(ESP_H) || defined(CORE_TEENSY)
// Make shiftIn() be aware of clockspeed for ESP32, Teensy 3.x and friends
// https://github.com/bogde/HX711/issues/75
// https://github.com/arduino/Arduino/issues/6561
// https://community.hiveeyes.org/t/using-bogdans-canonical-hx711-library-on-the-esp32/539
uint8_t shiftInSlow(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder) {
uint8_t value = 0;
uint8_t i;
for(i = 0; i < 8; ++i) {
digitalWrite(clockPin, HIGH);
delayMicroseconds(1);
if(bitOrder == LSBFIRST)
value |= digitalRead(dataPin) << i;
else
value |= digitalRead(dataPin) << (7 - i);
digitalWrite(clockPin, LOW);
delayMicroseconds(1);
}
return value;
}
#define SHIFTIN_WITH_SPEED_SUPPORT(data,clock,order) shiftInSlow(data,clock,order)
#else
#define SHIFTIN_WITH_SPEED_SUPPORT(data,clock,order) shiftIn(data,clock,order)
#endif
HX711::HX711() {
}
HX711::~HX711() {
}
void HX711::begin(byte dout, byte pd_sck, byte gain) {
PD_SCK = pd_sck;
DOUT = dout;
pinMode(PD_SCK, OUTPUT);
pinMode(DOUT, INPUT);
set_gain(gain);
}
bool HX711::is_ready() {
return digitalRead(DOUT) == LOW;
}
void HX711::set_gain(byte gain) {
switch (gain) {
case 128: // channel A, gain factor 128
GAIN = 1;
break;
case 64: // channel A, gain factor 64
GAIN = 3;
break;
case 32: // channel B, gain factor 32
GAIN = 2;
break;
}
digitalWrite(PD_SCK, LOW);
read();
}
long HX711::read() {
// wait for the chip to become ready
while (!is_ready()) {
// Will do nothing on Arduino but prevent resets of ESP8266 (Watchdog Issue)
yield();
}
unsigned long value = 0;
uint8_t data[3] = { 0 };
uint8_t filler = 0x00;
#ifdef ESP_H
// Begin of critical section.
// Critical sections are used as a valid protection method
// against simultaneous access in vanilla FreeRTOS.
// Disable the scheduler and call portDISABLE_INTERRUPTS. This prevents
// context switches and servicing of ISRs during a critical section.
portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;
portENTER_CRITICAL(&mux);
#endif
// pulse the clock pin 24 times to read the data
data[2] = SHIFTIN_WITH_SPEED_SUPPORT(DOUT, PD_SCK, MSBFIRST);
data[1] = SHIFTIN_WITH_SPEED_SUPPORT(DOUT, PD_SCK, MSBFIRST);
data[0] = SHIFTIN_WITH_SPEED_SUPPORT(DOUT, PD_SCK, MSBFIRST);
// set the channel and the gain factor for the next reading using the clock pin
for (unsigned int i = 0; i < GAIN; i++) {
digitalWrite(PD_SCK, HIGH);
#ifdef ESP_H
delayMicroseconds(1);
#endif
digitalWrite(PD_SCK, LOW);
#ifdef ESP_H
delayMicroseconds(1);
#endif
}
#ifdef ESP_H
// End of critical section.
portEXIT_CRITICAL(&mux);
#endif
// Replicate the most significant bit to pad out a 32-bit signed integer
if (data[2] & 0x80) {
filler = 0xFF;
} else {
filler = 0x00;
}
// Construct a 32-bit signed integer
value = ( static_cast<unsigned long>(filler) << 24
| static_cast<unsigned long>(data[2]) << 16
| static_cast<unsigned long>(data[1]) << 8
| static_cast<unsigned long>(data[0]) );
return static_cast<long>(value);
}
long HX711::read_average(byte times) {
long sum = 0;
for (byte i = 0; i < times; i++) {
sum += read();
yield();
}
return sum / times;
}
double HX711::get_value(byte times) {
return read_average(times) - OFFSET;
}
float HX711::get_units(byte times) {
return get_value(times) / SCALE;
}
void HX711::tare(byte times) {
double sum = read_average(times);
set_offset(sum);
}
void HX711::set_scale(float scale) {
SCALE = scale;
}
float HX711::get_scale() {
return SCALE;
}
void HX711::set_offset(long offset) {
OFFSET = offset;
}
long HX711::get_offset() {
return OFFSET;
}
void HX711::power_down() {
digitalWrite(PD_SCK, LOW);
digitalWrite(PD_SCK, HIGH);
}
void HX711::power_up() {
digitalWrite(PD_SCK, LOW);
}
<commit_msg>Prevent ints from corrupting the read sequence<commit_after>/**
*
* HX711 library for Arduino
* https://github.com/bogde/HX711
*
* MIT License
* (c) 2018 Bogdan Necula
*
**/
#include <Arduino.h>
#include <HX711.h>
#ifdef AVR
// Acquire AVR-specific ATOMIC_BLOCK(ATOMIC_RESTORESTATE) macro
#include <util/atomic.h>
#endif
#if defined(ARDUINO) && ARDUINO <= 106
// "yield" is not implemented as noop in older Arduino Core releases, so let's define it.
// See also: https://stackoverflow.com/questions/34497758/what-is-the-secret-of-the-arduino-yieldfunction/34498165#34498165
void yield(void) {};
#endif
#if defined(ESP_H) || defined(CORE_TEENSY)
// Make shiftIn() be aware of clockspeed for ESP32, Teensy 3.x and friends
// https://github.com/bogde/HX711/issues/75
// https://github.com/arduino/Arduino/issues/6561
// https://community.hiveeyes.org/t/using-bogdans-canonical-hx711-library-on-the-esp32/539
uint8_t shiftInSlow(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder) {
uint8_t value = 0;
uint8_t i;
for(i = 0; i < 8; ++i) {
digitalWrite(clockPin, HIGH);
delayMicroseconds(1);
if(bitOrder == LSBFIRST)
value |= digitalRead(dataPin) << i;
else
value |= digitalRead(dataPin) << (7 - i);
digitalWrite(clockPin, LOW);
delayMicroseconds(1);
}
return value;
}
#define SHIFTIN_WITH_SPEED_SUPPORT(data,clock,order) shiftInSlow(data,clock,order)
#else
#define SHIFTIN_WITH_SPEED_SUPPORT(data,clock,order) shiftIn(data,clock,order)
#endif
HX711::HX711() {
}
HX711::~HX711() {
}
void HX711::begin(byte dout, byte pd_sck, byte gain) {
PD_SCK = pd_sck;
DOUT = dout;
pinMode(PD_SCK, OUTPUT);
pinMode(DOUT, INPUT);
set_gain(gain);
}
bool HX711::is_ready() {
return digitalRead(DOUT) == LOW;
}
void HX711::set_gain(byte gain) {
switch (gain) {
case 128: // channel A, gain factor 128
GAIN = 1;
break;
case 64: // channel A, gain factor 64
GAIN = 3;
break;
case 32: // channel B, gain factor 32
GAIN = 2;
break;
}
digitalWrite(PD_SCK, LOW);
read();
}
long HX711::read() {
// wait for the chip to become ready
while (!is_ready()) {
// Will do nothing on Arduino but prevent resets of ESP8266 (Watchdog Issue)
yield();
}
unsigned long value = 0;
uint8_t data[3] = { 0 };
uint8_t filler = 0x00;
// Protect the read sequence from system interrupts. If an interrupt occurs during
// the time the PD_SCK signal is high it will stretch the length of the clock pulse.
// If the total pulse time exceeds 60 uSec this will cause the HX711 to enter
// power down mode during the middle of the read sequence. While the device will
// wake up when PD_SCK goes low again, the reset starts a new conversion cycle which
// forces DOUT high until that cycle is completed.
//
// The result is that all subsequent bits read by shiftIn() will read back as 1,
// corrupting the value returned by read(). The ATOMIC_BLOCK macro disables
// interrupts during the sequence and then restores the interrupt mask to its previous
// state after the sequence completes, insuring that the entire read-and-gain-set
// sequence is not interrupted. The macro has a few minor advantages over bracketing
// the sequence between NoInterrupts() and interrupts() calls.
#ifdef AVR
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
#endif
#ifdef ESP_H
// Begin of critical section.
// Critical sections are used as a valid protection method
// against simultaneous access in vanilla FreeRTOS.
// Disable the scheduler and call portDISABLE_INTERRUPTS. This prevents
// context switches and servicing of ISRs during a critical section.
portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;
portENTER_CRITICAL(&mux);
#endif
// pulse the clock pin 24 times to read the data
data[2] = SHIFTIN_WITH_SPEED_SUPPORT(DOUT, PD_SCK, MSBFIRST);
data[1] = SHIFTIN_WITH_SPEED_SUPPORT(DOUT, PD_SCK, MSBFIRST);
data[0] = SHIFTIN_WITH_SPEED_SUPPORT(DOUT, PD_SCK, MSBFIRST);
// set the channel and the gain factor for the next reading using the clock pin
for (unsigned int i = 0; i < GAIN; i++) {
digitalWrite(PD_SCK, HIGH);
#ifdef ESP_H
delayMicroseconds(1);
#endif
digitalWrite(PD_SCK, LOW);
#ifdef ESP_H
delayMicroseconds(1);
#endif
}
#ifdef ESP_H
// End of critical section.
portEXIT_CRITICAL(&mux);
#endif
#ifdef AVR
}
#endif
// Replicate the most significant bit to pad out a 32-bit signed integer
if (data[2] & 0x80) {
filler = 0xFF;
} else {
filler = 0x00;
}
// Construct a 32-bit signed integer
value = ( static_cast<unsigned long>(filler) << 24
| static_cast<unsigned long>(data[2]) << 16
| static_cast<unsigned long>(data[1]) << 8
| static_cast<unsigned long>(data[0]) );
return static_cast<long>(value);
}
long HX711::read_average(byte times) {
long sum = 0;
for (byte i = 0; i < times; i++) {
sum += read();
yield();
}
return sum / times;
}
double HX711::get_value(byte times) {
return read_average(times) - OFFSET;
}
float HX711::get_units(byte times) {
return get_value(times) / SCALE;
}
void HX711::tare(byte times) {
double sum = read_average(times);
set_offset(sum);
}
void HX711::set_scale(float scale) {
SCALE = scale;
}
float HX711::get_scale() {
return SCALE;
}
void HX711::set_offset(long offset) {
OFFSET = offset;
}
long HX711::get_offset() {
return OFFSET;
}
void HX711::power_down() {
digitalWrite(PD_SCK, LOW);
digitalWrite(PD_SCK, HIGH);
}
void HX711::power_up() {
digitalWrite(PD_SCK, LOW);
}
<|endoftext|> |
<commit_before>//
// Copyright (C) 2005 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2005 Pingtel Corp.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
//////////////////////////////////////////////////////////////////////////////
// SYSTEM INCLUDES
// APPLICATION INCLUDES
#include "os/OsSysLog.h"
#include "resiprocateLib/sipXexternalLogger.h"
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
// STATICS
/* //////////////////////////// PUBLIC //////////////////////////////////// */
bool SipXExternalLogger::operator()(resip::Log::Level level,
const resip::Subsystem& subsystem,
const resip::Data& appName,
const char* file,
int line,
const resip::Data& message,
const resip::Data& messageWithHeaders)
{
OsSysLog::add(FAC_CONFERENCE, toPriority(level), "%s", messageWithHeaders.c_str());
return false;
}
OsSysLogPriority SipXExternalLogger::toPriority(resip::Log::Level level)
{
switch (level)
{
case resip::Log::Crit:
return PRI_CRIT;
case resip::Log::Err:
return PRI_ERR;
case resip::Log::Warning:
return PRI_WARNING;
case resip::Log::Info:
return PRI_INFO;
case resip::Log::Debug:
case resip::Log::Stack:
default:
return PRI_DEBUG;
}
}
<commit_msg>- change for windows builds only<commit_after>//
// Copyright (C) 2005 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2005 Pingtel Corp.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
//////////////////////////////////////////////////////////////////////////////
// SYSTEM INCLUDES
// APPLICATION INCLUDES
#if defined(_WIN32)
# include <winsock2.h>
#endif
#include "os/OsSysLog.h"
#include "resiprocateLib/sipXexternalLogger.h"
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
// STATICS
/* //////////////////////////// PUBLIC //////////////////////////////////// */
bool SipXExternalLogger::operator()(resip::Log::Level level,
const resip::Subsystem& subsystem,
const resip::Data& appName,
const char* file,
int line,
const resip::Data& message,
const resip::Data& messageWithHeaders)
{
OsSysLog::add(FAC_CONFERENCE, toPriority(level), "%s", messageWithHeaders.c_str());
return false;
}
OsSysLogPriority SipXExternalLogger::toPriority(resip::Log::Level level)
{
switch (level)
{
case resip::Log::Crit:
return PRI_CRIT;
case resip::Log::Err:
return PRI_ERR;
case resip::Log::Warning:
return PRI_WARNING;
case resip::Log::Info:
return PRI_INFO;
case resip::Log::Debug:
case resip::Log::Stack:
default:
return PRI_DEBUG;
}
}
<|endoftext|> |
<commit_before>/*
** Author: Abhilash
** Date: 18.04.2015
*/
// Bottom up computation
//
#include <bits/stdc++.h>
#define sf scanf
#define pf printf
typedef long long ll;
using namespace std;
const ll N = 1e6+3;
const ll inf = 1e18;
ll DP[N][3];
ll cost[N][3];
ll n;
ll move[4][2] = {{1, -1}, {0, 1}, {1, 1}, {1, 0}};
ll dp() {
DP[n][0] = cost[n][0]+cost[n][1];
DP[n][1] = cost[n][1];
DP[n][2] = inf;
ll r, c, ans;
for (int i = n-1; i >= 1; --i) {
for (int j = 2; j >= 0; --j) {
ans = inf;
for (int k = 0; k < 4; ++k) {
r = i + move[k][0];
c = j + move[k][1];
if (c >= 0 && c <= 2) {
ans = min(ans, cost[i][j] + DP[r][c]);
}
}
DP[i][j] = ans;
}
}
return DP[1][1];
}
int main() {
sf("%lld", &n);
ll T = 1;
while (n) {
for (int i = 0; i < n; ++i)
sf("%lld %lld %lld", &cost[i+1][0],
&cost[i+1][1],
&cost[i+1][2]);
pf("%lld. %lld\n", T++, dp());
sf("%lld", &n);
}
return 0;
}
<commit_msg>Update ACPC10D.cpp<commit_after>/*
** Author: Abhilash
** Date: 18.04.2015
*/
// Bottom up computation
//
#include <bits/stdc++.h>
#define sf scanf
#define pf printf
typedef long long ll;
using namespace std;
const ll N = 1e6+3;
const ll inf = 1e18;
ll DP[N][3];
ll cost[N][3];
ll n;
ll move[4][2] = {{1, -1}, {0, 1}, {1, 1}, {1, 0}};
ll dp() {
DP[n][0] = cost[n][0]+cost[n][1];
DP[n][1] = cost[n][1];
DP[n][2] = inf;
ll r, c, ans;
for (int i = n-1; i >= 1; --i) {
for (int j = 2; j >= 0; --j) {
ans = inf;
for (int k = 0; k < 4; ++k) {
r = i + move[k][0];
c = j + move[k][1];
if (c >= 0 && c <= 2) {
ans = min(ans, cost[i][j] + DP[r][c]);
}
}
DP[i][j] = ans;
}
}
return DP[1][1];
}
int main() {
sf("%lld", &n);
ll T = 1;
while (n) {
for (int i = 0; i < n; ++i)
sf("%lld %lld %lld", &cost[i+1][0],
&cost[i+1][1],
&cost[i+1][2]);
pf("%lld. %lld\n", T++, dp());
sf("%lld", &n);
}
return 0;
}
<|endoftext|> |
<commit_before>//******************************************************************
//
// Copyright 2016 Samsung Electronics 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 <iostream>
#include <vector>
#include <algorithm>
#include "OCPlatform.h"
#include "RCSDiscoveryManager.h"
#include "RCSRemoteResourceObject.h"
#include "RCSAddress.h"
#include "RemoteSceneList.h"
using namespace OC;
using namespace OIC::Service;
typedef std::function< void() > Run;
enum Menu
{
CREATE_REMOTE_SCENE_LIST = 1, CREATE_REMOTE_SCENE_COLLECTION,
CREATE_REMOTE_SCENE, CREATE_REMOTE_SCENE_ACTION, EXECUTE_REMOTE_SCENE
};
constexpr int SCENE_RESULT_OK = 200;
constexpr int numMenu = 1;
const std::string scene_name = "Going Out";
const std::string relativetUri = OC_RSRVD_WELL_KNOWN_URI;
const std::vector<std::string> resourceTypes{ "oic.wk.scenelist", "core.light", "core.fan" };
std::mutex g_mtx;
std::mutex g_discoverymtx;
std::condition_variable g_cond;
std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> g_discoveryTask;
RCSRemoteResourceObject::Ptr g_foundListResource;
RCSRemoteResourceObject::Ptr g_foundLightResource;
RCSRemoteResourceObject::Ptr g_foundFanResource;
RemoteSceneList::Ptr g_sceneList;
RemoteSceneCollection::Ptr g_sceneCollection;
RemoteScene::Ptr g_scene;
void displaySceneList();
void displaySceneCollection();
void displayScene();
void displaySceneAction();
void runMenu(Menu);
// Scene Manager Remote API sample ---
void onRemoteSceneListCreated(RemoteSceneList::Ptr remoteSceneList, int eCode)
{
std::cout << __func__ << " - error code : " << eCode << std::endl;
if (eCode == SCENE_RESULT_OK)
{
g_sceneList = std::move(remoteSceneList);
displaySceneList();
runMenu(CREATE_REMOTE_SCENE_COLLECTION);
}
else
{
std::cout << "Create Remote scene list failed." << std::endl;
runMenu(CREATE_REMOTE_SCENE_LIST);
}
}
void onRemoteSceneCollectionCreated(RemoteSceneCollection::Ptr remoteSceneCol, int eCode)
{
std::cout << __func__ << " - error code : " << eCode << std::endl;
if (eCode == SCENE_RESULT_OK)
{
g_sceneCollection = remoteSceneCol;
displaySceneList();
displaySceneCollection();
runMenu(CREATE_REMOTE_SCENE);
}
else
{
std::cout << "Create Remote scene collection failed." << std::endl;
runMenu(CREATE_REMOTE_SCENE_COLLECTION);
}
}
void onRemoteSceneCreated(RemoteScene::Ptr remoteScene, int eCode)
{
std::cout << __func__ << " - error code : " << eCode << std::endl;
if (eCode == SCENE_RESULT_OK)
{
g_scene = remoteScene;
displaySceneList();
displaySceneCollection();
displayScene();
runMenu(CREATE_REMOTE_SCENE_ACTION);
}
else
{
std::cout << "Create Remote scene failed." << std::endl;
runMenu(CREATE_REMOTE_SCENE);
}
}
void onRemoteSceneActionCreated(RemoteSceneAction::Ptr, int eCode)
{
std::cout << __func__ << " - error code : " << eCode << std::endl;
if (eCode == SCENE_RESULT_OK)
{
displaySceneList();
displaySceneCollection();
displaySceneAction();
runMenu(EXECUTE_REMOTE_SCENE);
}
else
{
std::cout << "Create Remote scene action failed." << std::endl;
runMenu(CREATE_REMOTE_SCENE_ACTION);
}
}
void onRemoteSceneExecuted(const std::string &sceneName, int eCode)
{
std::cout << __func__ << " - scene name : " << sceneName
<< ", error code : " << eCode << std::endl;
if (eCode != SCENE_RESULT_OK)
{
std::cout << "Execute scene failed." << std::endl;
}
runMenu(EXECUTE_REMOTE_SCENE);
}
void createRemoteSceneList()
{
if (g_foundListResource)
{
RemoteSceneList::createInstance(g_foundListResource, onRemoteSceneListCreated);
}
else
{
std::cout << "Scene List Resource is not discovered." << std::endl;
runMenu(CREATE_REMOTE_SCENE_LIST);
}
}
void createRemoteSceneCollection()
{
if (!g_sceneList) return;
g_sceneList->addNewSceneCollection(onRemoteSceneCollectionCreated);
}
void createRemoteScene()
{
if (!g_sceneCollection) return;
g_sceneCollection->addNewScene(scene_name, onRemoteSceneCreated);
}
void createRemoteSceneAction(
RemoteScene::Ptr scene, RCSRemoteResourceObject::Ptr member,
const std::string &key, const std::string &value)
{
if (scene && member)
{
g_scene->addNewSceneAction(member, key, RCSResourceAttributes::Value(value),
onRemoteSceneActionCreated);
}
}
void createRemoteSceneActions()
{
createRemoteSceneAction(g_scene, g_foundLightResource, "power", "off");
createRemoteSceneAction(g_scene, g_foundFanResource, "speed", "0");
}
void executeScene()
{
displaySceneList();
displaySceneCollection();
displaySceneAction();
if (g_scene)
{
g_scene->execute(onRemoteSceneExecuted);
std::cout << "\n\t'" << g_scene->getName() << "' is executed!\n" << std::endl;
}
}
// --- Scene Manager Remote API sample
void configurePlatform()
{
PlatformConfig config
{
OC::ServiceType::InProc, ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos
};
OCPlatform::Configure(config);
}
void processUserInput(int min, int max)
{
assert(min <= max);
int input;
std::cin >> input;
if (!std::cin.fail())
{
if (input == max + 1) exit(0);
if (min <= input && input <= max) return;
}
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
throw std::runtime_error("Invalid Input, please try again");
}
void excecuteCommand(std::string str, Run runFunc)
{
std::cout << "\n========================================================\n";
std::cout << "1. " << str << "\n";
std::cout << "2. Quit \n";
std::cout << "======================================================== \n";
try
{
processUserInput(1, numMenu);
runFunc();
}
catch(std::exception & e)
{
std::cout << e.what() << std::endl;
}
}
void runMenu(Menu menu)
{
std::string strMenu;
Run runFunc;
switch (menu)
{
case CREATE_REMOTE_SCENE_LIST:
strMenu = "Create a RemoteSceneList";
runFunc = createRemoteSceneList;
break;
case CREATE_REMOTE_SCENE_COLLECTION:
strMenu = "Create a RemoteSceneCollection";
runFunc = createRemoteSceneCollection;
break;
case CREATE_REMOTE_SCENE:
strMenu = "Create a RemoteScene";
runFunc = createRemoteScene;
break;
case CREATE_REMOTE_SCENE_ACTION:
strMenu = "Create RemoteSceneActions";
runFunc = createRemoteSceneActions;
break;
case EXECUTE_REMOTE_SCENE:
strMenu = "Execute RemoteScene";
runFunc = executeScene;
break;
default:
return;
}
excecuteCommand(strMenu, runFunc);
}
void displaySceneList()
{
if (g_sceneList)
{
std::cout << "\tSceneList" << "\n\t |_ _ _ ";
std::cout << g_sceneList->getName() << std::endl;
}
}
void displaySceneCollection()
{
if (g_sceneCollection)
{
std::cout << "\t\t |_ _ _ " << g_sceneCollection->getId()
<< " (SceneCollection)" << std::endl;
}
}
void displayScene()
{
if (g_scene)
{
std::cout << "\t\t\t |_ _ _ " << g_scene->getName() << " (Scene)" << std::endl;
}
}
void displaySceneAction()
{
if (!g_scene) return;
displayScene();
auto sceneActionList = g_scene->getRemoteSceneActions();
for (const auto &it : sceneActionList)
{
auto attr = it->getExecutionParameter();
for (const auto &att : attr)
{
std::cout << "\t\t\t \t\t|_ _ _ ";
std::cout << it->getRemoteResourceObject()->getUri() << " : ";
std::cout << att.key() << " - " << att.value().toString() << std::endl;
}
}
}
void onResourceDiscovered(std::shared_ptr<RCSRemoteResourceObject> foundResource)
{
std::lock_guard< std::mutex > lock(g_discoverymtx);
std::cout << "onResourceDiscovered callback" << std::endl;
std::string resourceURI = foundResource->getUri();
std::string hostAddress = foundResource->getAddress();
std::vector< std::string > vecRTs = foundResource->getTypes();
std::cout << "\t\tResource URI : " << resourceURI << std::endl;
std::cout << "\t\tResource Host : " << hostAddress << std::endl;
// if the found resource is a scene list resource
if (std::find(vecRTs.begin(), vecRTs.end(), "oic.wk.scenelist") != vecRTs.end())
g_foundListResource = foundResource;
// if the found resource is a light resource
else if (std::find(vecRTs.begin(), vecRTs.end(), "core.light") != vecRTs.end())
{
g_foundLightResource = foundResource;
}
// if the found resource is a fan resource
else if (std::find(vecRTs.begin(), vecRTs.end(), "core.fan") != vecRTs.end())
{
g_foundFanResource = foundResource;
}
if (g_foundListResource && g_foundLightResource && g_foundFanResource)
{
g_discoveryTask->cancel();
return;
}
g_cond.notify_all();
}
void discoverResource()
{
std::cout << "Wait 2 seconds until discovered." << std::endl;
try
{
g_discoveryTask
= RCSDiscoveryManager::getInstance()->discoverResourceByTypes(RCSAddress::multicast(),
relativetUri, resourceTypes, &onResourceDiscovered);
}
catch (const RCSPlatformException &e)
{
std::cout << e.what() << std::endl;
}
std::unique_lock<std::mutex> lck(g_mtx);
g_cond.wait_for(lck, std::chrono::seconds(4));
return;
}
int main()
{
configurePlatform();
try
{
discoverResource();
}
catch(std::exception &e)
{
std::cout << e.what() << std::endl;
return 0;
}
try
{
runMenu(CREATE_REMOTE_SCENE_LIST);
}
catch(std::exception &e)
{
std::cout << e.what() << std::endl;
return 0;
}
while (true) { }
std::cout << "Stopping the scene client" << std::endl;
return 0;
}
<commit_msg>Enrich a sceneclient sample application for executing an existing scene at remote device<commit_after>//******************************************************************
//
// Copyright 2016 Samsung Electronics 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 <iostream>
#include <vector>
#include <algorithm>
#include "OCPlatform.h"
#include "RCSDiscoveryManager.h"
#include "RCSRemoteResourceObject.h"
#include "RCSAddress.h"
#include "RemoteSceneList.h"
using namespace OC;
using namespace OIC::Service;
constexpr int CREATE_REMOTE_SCENE_LIST = 1;
constexpr int CREATE_REMOTE_SCENE_COLLECTION = 1;
constexpr int SHOW_REMOTE_SCENE_COLLECTION = 2;
constexpr int CREATE_REMOTE_SCENE = 1;
constexpr int CREATE_REMOTE_SCENE_ACTION = 1;
constexpr int EXECUTE_REMOTE_SCENE = 1;
constexpr int SCENE_RESULT_OK = 200;
constexpr int numCreatedSceneAction = 2;
static int numRecvSceneActionCreationResp = 0;
typedef std::function< void() > Run;
Run g_currentRun;
const std::string scene_name = "Night mode";
const std::string relativetUri = OC_RSRVD_WELL_KNOWN_URI;
const std::vector<std::string> resourceTypes{ "oic.wk.scenelist", "core.light", "core.fan" };
std::mutex g_mtx;
std::mutex g_discoverymtx;
std::condition_variable g_cond;
std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> g_discoveryTask;
RCSRemoteResourceObject::Ptr g_foundListResource;
RCSRemoteResourceObject::Ptr g_foundLightResource;
RCSRemoteResourceObject::Ptr g_foundFanResource;
RemoteSceneList::Ptr g_sceneList;
RemoteSceneCollection::Ptr g_sceneCollection;
RemoteScene::Ptr g_scene;
void displaySceneList();
void runCreateRemoteSceneList();
void runRemoteSceneCollection();
void runCreateRemoteScene();
void runCreateRemoteSceneAction();
void runExecuteCreatedRemoteScene();
void runExecuteExistingRemoteScene();
// Scene Manager Remote API sample ---
void onRemoteSceneListCreated(RemoteSceneList::Ptr remoteSceneList, int eCode)
{
std::cout << __func__ << " - error code : " << eCode << std::endl;
if (eCode == SCENE_RESULT_OK)
{
g_sceneList = std::move(remoteSceneList);
g_currentRun = runRemoteSceneCollection;
}
else
{
std::cout << "Create Remote scene list failed." << std::endl;
g_currentRun = runCreateRemoteSceneList;
}
g_currentRun();
}
void onRemoteSceneCollectionCreated(RemoteSceneCollection::Ptr remoteSceneCol, int eCode)
{
std::cout << __func__ << " - error code : " << eCode << std::endl;
if (eCode == SCENE_RESULT_OK)
{
g_sceneCollection = remoteSceneCol;
g_currentRun = runCreateRemoteScene;
}
else
{
std::cout << "Create Remote scene collection failed." << std::endl;
g_currentRun = runRemoteSceneCollection;
}
g_currentRun();
}
void onRemoteSceneCreated(RemoteScene::Ptr remoteScene, int eCode)
{
std::cout << __func__ << " - error code : " << eCode << std::endl;
if (eCode == SCENE_RESULT_OK)
{
g_scene = remoteScene;
g_currentRun = runCreateRemoteSceneAction;
}
else
{
std::cout << "Create Remote scene failed." << std::endl;
g_currentRun = runCreateRemoteScene;
}
g_currentRun();
}
void onRemoteSceneActionCreated(RemoteSceneAction::Ptr, int eCode)
{
std::cout << __func__ << " - error code : " << eCode << std::endl;
if (eCode == SCENE_RESULT_OK)
{
g_currentRun = runExecuteCreatedRemoteScene;
}
else
{
std::cout << "Create Remote scene action failed." << std::endl;
g_currentRun = runCreateRemoteSceneAction;
}
numRecvSceneActionCreationResp++;
if(numCreatedSceneAction == numRecvSceneActionCreationResp)
g_currentRun();
}
void onRemoteSceneExecuted(const std::string &sceneName, int eCode)
{
std::cout << __func__ << " - scene name : " << sceneName
<< ", error code : " << eCode << std::endl;
if (eCode != SCENE_RESULT_OK)
{
std::cout << "Execute scene failed." << std::endl;
}
g_currentRun();
}
// --- Scene Manager Remote API sample
void createRemoteSceneList()
{
if (g_foundListResource)
{
RemoteSceneList::createInstance(g_foundListResource, onRemoteSceneListCreated);
}
else
{
std::cout << "Scene List Resource is not discovered." << std::endl;
g_currentRun();
}
}
void createRemoteSceneCollection()
{
if (!g_sceneList) return;
g_sceneList->addNewSceneCollection(onRemoteSceneCollectionCreated);
}
void showRemoteSceneCollection()
{
if (!g_sceneList) return;
if (g_sceneList->getRemoteSceneCollections().size() == 0) return;
g_sceneCollection = g_sceneList->getRemoteSceneCollections().at(0);
if( g_sceneCollection->getRemoteScenes().size() == 0) return;
g_scene = g_sceneCollection->getRemoteScenes().begin()->second;
}
void createRemoteScene()
{
if (!g_sceneCollection) return;
g_sceneCollection->addNewScene(scene_name, onRemoteSceneCreated);
}
void createRemoteSceneAction(
RemoteScene::Ptr scene, RCSRemoteResourceObject::Ptr member,
const std::string &key, const std::string &value)
{
if (scene && member)
{
g_scene->addNewSceneAction(member, key, RCSResourceAttributes::Value(value),
onRemoteSceneActionCreated);
}
}
void createRemoteSceneActions()
{
createRemoteSceneAction(g_scene, g_foundLightResource, "power", "on");
createRemoteSceneAction(g_scene, g_foundFanResource, "speed", "50");
}
void executeScene()
{
displaySceneList();
if (g_scene)
{
g_scene->execute(onRemoteSceneExecuted);
std::cout << "\n\t'" << g_scene->getName() << "' is executed!\n" << std::endl;
}
}
// --- Scene Manager Remote API sample
void configurePlatform()
{
PlatformConfig config
{
OC::ServiceType::InProc, ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos
};
OCPlatform::Configure(config);
}
int processUserInput(int min, int max)
{
assert(min <= max);
int input;
std::cin >> input;
if (!std::cin.fail())
{
if (input == max + 1) exit(0);
if (min <= input && input <= max) return input;
}
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
throw std::runtime_error("Invalid Input, please try again");
}
void displaySceneList()
{
if (!g_sceneList) return;
std::cout << "\t" << g_sceneList->getName() << "(SceneList)" << std::endl;
if (!g_sceneCollection) return;
std::cout << "\t\t |_ _ _ " << g_sceneCollection->getId() << " (SceneCollection)" << std::endl;
for( const auto &it_scene : g_sceneCollection->getRemoteScenes() )
{
std::cout << "\t\t\t |_ _ _ " << it_scene.first << " (Scene)" << std::endl;
auto sceneActionList = it_scene.second->getRemoteSceneActions();
for (const auto &it : sceneActionList)
{
auto attr = it->getExecutionParameter();
for (const auto &att : attr)
{
std::cout << "\t\t\t \t\t|_ _ _ ";
std::cout << it->getRemoteResourceObject()->getUri() << " : ";
std::cout << att.key() << " - " << att.value().toString() << std::endl;
}
}
}
}
void displayClear(Run runFunc)
{
auto ret = std::system("/usr/bin/clear");
if(ret == -1)
{
std::cout << "clear error!" << std::endl;
}
g_currentRun = runFunc;
}
void displayCreateRemoteSceneListMenu()
{
std::cout << "========================================================\n";
std::cout << CREATE_REMOTE_SCENE_LIST << ". Create a RemoteSceneList \n";
std::cout << CREATE_REMOTE_SCENE_LIST + 1 << ". Quit \n";
std::cout << "========================================================\n";
}
void displayRemoteSceneCollectionMenu()
{
std::cout << "======================================================== \n";
std::cout << CREATE_REMOTE_SCENE_COLLECTION << ". Create a RemoteSceneCollection \n";
std::cout << SHOW_REMOTE_SCENE_COLLECTION << ". Show existing RemoteSceneCollection \n";
std::cout << SHOW_REMOTE_SCENE_COLLECTION + 1 << ". Quit \n";
std::cout << "======================================================== \n";
}
void displayRemoteSceneCreationMenu()
{
std::cout << "========================================================\n";
std::cout << CREATE_REMOTE_SCENE << ". Create a RemoteScene \n";
std::cout << CREATE_REMOTE_SCENE + 1 << ". Quit \n";
std::cout << "========================================================\n";
}
void displayRemoteSceneActionCreationMenu()
{
std::cout << "======================================================== \n";
std::cout << CREATE_REMOTE_SCENE_ACTION << ". Create RemoteSceneActions \n";
std::cout << CREATE_REMOTE_SCENE_ACTION + 1 << ". Quit \n";
std::cout << "======================================================== \n";
}
void displayExecuteCreatedRemoteSceneCreationMenu()
{
std::cout << "========================================================\n";
std::cout << EXECUTE_REMOTE_SCENE << ". Execute RemoteScene \n";
std::cout << EXECUTE_REMOTE_SCENE + 1 << ". Quit \n";
std::cout << "========================================================\n";
}
void displayExecuteExistingRemoteSceneCreationMenu()
{
std::cout << "========================================================\n";
std::cout << EXECUTE_REMOTE_SCENE << ". Execute a first RemoteScene \n";
std::cout << EXECUTE_REMOTE_SCENE + 1 << ". Quit \n";
std::cout << "========================================================\n";
}
void runExecuteExistingRemoteScene()
{
displaySceneList();
displayExecuteExistingRemoteSceneCreationMenu();
try
{
int command = processUserInput(EXECUTE_REMOTE_SCENE, EXECUTE_REMOTE_SCENE);
switch(command)
{
case EXECUTE_REMOTE_SCENE:
executeScene();
displayClear(runExecuteExistingRemoteScene);
break;
}
} catch (std::exception &e)
{
std::cout << e.what() << std::endl;
g_currentRun();
}
}
void runExecuteCreatedRemoteScene()
{
displaySceneList();
displayExecuteCreatedRemoteSceneCreationMenu();
try
{
int command = processUserInput(EXECUTE_REMOTE_SCENE, EXECUTE_REMOTE_SCENE);
switch(command)
{
case EXECUTE_REMOTE_SCENE:
executeScene();
displayClear(runExecuteCreatedRemoteScene);
break;
}
} catch (std::exception &e)
{
std::cout << e.what() << std::endl;
g_currentRun();
}
}
void runCreateRemoteSceneAction()
{
displaySceneList();
displayRemoteSceneActionCreationMenu();
try
{
int command = processUserInput(CREATE_REMOTE_SCENE_ACTION, CREATE_REMOTE_SCENE_ACTION);
switch(command)
{
case CREATE_REMOTE_SCENE_ACTION:
createRemoteSceneActions();
displayClear(runExecuteCreatedRemoteScene);
break;
}
} catch (std::exception &e)
{
std::cout << e.what() << std::endl;
g_currentRun();
}
}
void runCreateRemoteScene()
{
displaySceneList();
displayRemoteSceneCreationMenu();
try
{
int command = processUserInput(CREATE_REMOTE_SCENE, CREATE_REMOTE_SCENE);
switch(command)
{
case CREATE_REMOTE_SCENE:
createRemoteScene();
displayClear(runCreateRemoteSceneAction);
break;
}
} catch (std::exception &e)
{
std::cout << e.what() << std::endl;
g_currentRun();
}
}
void runRemoteSceneCollection()
{
displaySceneList();
displayRemoteSceneCollectionMenu();
try
{
int command = processUserInput(CREATE_REMOTE_SCENE_COLLECTION, SHOW_REMOTE_SCENE_COLLECTION);
switch(command)
{
case CREATE_REMOTE_SCENE_COLLECTION:
createRemoteSceneCollection();
displayClear(runCreateRemoteScene);
break;
case SHOW_REMOTE_SCENE_COLLECTION:
showRemoteSceneCollection();
displayClear(runExecuteExistingRemoteScene);
g_currentRun();
break;
}
} catch (std::exception &e)
{
std::cout << e.what() << std::endl;
g_currentRun();
}
}
void runCreateRemoteSceneList()
{
displayCreateRemoteSceneListMenu();
try
{
int command = processUserInput(CREATE_REMOTE_SCENE_LIST, CREATE_REMOTE_SCENE_LIST);
switch(command)
{
case CREATE_REMOTE_SCENE_LIST:
createRemoteSceneList();
displayClear(runRemoteSceneCollection);
break;
}
} catch (std::exception &e)
{
std::cout << e.what() << std::endl;
g_currentRun();
}
}
void onResourceDiscovered(std::shared_ptr<RCSRemoteResourceObject> foundResource)
{
std::lock_guard< std::mutex > lock(g_discoverymtx);
std::cout << "onResourceDiscovered callback" << std::endl;
std::string resourceURI = foundResource->getUri();
std::string hostAddress = foundResource->getAddress();
std::vector< std::string > vecRTs = foundResource->getTypes();
std::cout << "\t\tResource URI : " << resourceURI << std::endl;
std::cout << "\t\tResource Host : " << hostAddress << std::endl;
// if the found resource is a scene list resource
if (std::find(vecRTs.begin(), vecRTs.end(), "oic.wk.scenelist") != vecRTs.end())
g_foundListResource = foundResource;
// if the found resource is a light resource
else if (std::find(vecRTs.begin(), vecRTs.end(), "core.light") != vecRTs.end())
{
g_foundLightResource = foundResource;
}
// if the found resource is a fan resource
else if (std::find(vecRTs.begin(), vecRTs.end(), "core.fan") != vecRTs.end())
{
g_foundFanResource = foundResource;
}
if (g_foundListResource && g_foundLightResource && g_foundFanResource)
{
g_discoveryTask->cancel();
return;
}
g_cond.notify_all();
}
void discoverResource()
{
std::cout << "Wait 2 seconds until discovered." << std::endl;
try
{
g_discoveryTask
= RCSDiscoveryManager::getInstance()->discoverResourceByTypes(RCSAddress::multicast(),
relativetUri, resourceTypes, &onResourceDiscovered);
}
catch (const RCSPlatformException &e)
{
std::cout << e.what() << std::endl;
}
std::unique_lock<std::mutex> lck(g_mtx);
g_cond.wait_for(lck, std::chrono::seconds(4));
return;
}
int main()
{
configurePlatform();
try
{
discoverResource();
}
catch(std::exception &e)
{
std::cout << e.what() << std::endl;
return 0;
}
try
{
g_currentRun = runCreateRemoteSceneList;
g_currentRun();
}
catch(std::exception &e)
{
std::cout << e.what() << std::endl;
return 0;
}
while (true) { }
std::cout << "Stopping the scene client" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/** \copyright
* Copyright (c) 2019, Mike Dunston
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file Esp32HardwareCanAdapter.hxx
*
* ESP32 Hardware CAN adapter code. This utilizes the built in CAN controller
* to translate the can_frame in OpenMRN to the ESP32 can_message_t used by the
* ESP-IDF CAN controller code. The ESP32 will still require an external CAN
* transceiver (MCP2551 or SN65HVD230 as example).
*
* @author Mike Dunston
* @date 19 January 2019
*/
#ifndef _FREERTOS_DRIVERS_ESP32_ESP32HWCAN_HXX_
#define _FREERTOS_DRIVERS_ESP32_ESP32HWCAN_HXX_
#include "freertos_drivers/arduino/Can.hxx"
#include <driver/can.h>
#include <driver/gpio.h>
#include <esp_task_wdt.h>
/// ESP32 CAN bus status strings, used for periodic status reporting
static const char *ESP32_CAN_STATUS_STRINGS[] = {
"STOPPED", // CAN_STATE_STOPPED
"RUNNING", // CAN_STATE_RUNNING
"OFF / RECOVERY NEEDED", // CAN_STATE_BUS_OFF
"RECOVERY UNDERWAY" // CAN_STATE_RECOVERING
};
class Esp32HardwareCan : public Can
{
public:
/// Constructor.
///
/// @param name is the name for the CAN adapter, this is currently not used.
/// @param rxPin is the ESP32 pin that is connected to the external
/// transceiver RX.
/// @param txPin is the ESP32 pin that is connected to the external
/// transceiver TX.
Esp32HardwareCan(const char *name, gpio_num_t rxPin, gpio_num_t txPin, bool reportStats=true)
: Can(name), reportStats_(reportStats)
{
// Configure the ESP32 CAN driver to use 125kbps.
can_timing_config_t can_timing_config = CAN_TIMING_CONFIG_125KBITS();
// By default we accept all CAN frames.
can_filter_config_t can_filter_config = CAN_FILTER_CONFIG_ACCEPT_ALL();
// Note: not using the CAN_GENERAL_CONFIG_DEFAULT macro due to a missing
// cast for CAN_IO_UNUSED.
can_general_config_t can_general_config = {.mode = CAN_MODE_NORMAL,
.tx_io = txPin,
.rx_io = rxPin,
.clkout_io = (gpio_num_t)CAN_IO_UNUSED,
.bus_off_io = (gpio_num_t)CAN_IO_UNUSED,
.tx_queue_len = (uint32_t)config_can_tx_buffer_size() / 2,
.rx_queue_len = (uint32_t)config_can_rx_buffer_size() / 2,
.alerts_enabled = CAN_ALERT_NONE,
.clkout_divider = 0};
LOG(VERBOSE,
"ESP32-CAN driver configured using RX: %d, TX: %d, TX-Q: %d, "
"RX-Q: %d",
can_general_config.rx_io, can_general_config.tx_io,
can_general_config.rx_queue_len, can_general_config.tx_queue_len);
ESP_ERROR_CHECK(can_driver_install(
&can_general_config, &can_timing_config, &can_filter_config));
xTaskCreatePinnedToCore(rx_task, "ESP32-CAN RX", OPENMRN_STACK_SIZE,
this, RX_TASK_PRIORITY, &rxTaskHandle_, tskNO_AFFINITY);
xTaskCreatePinnedToCore(tx_task, "ESP32-CAN TX", OPENMRN_STACK_SIZE,
this, TX_TASK_PRIORITY, &txTaskHandle_, tskNO_AFFINITY);
}
~Esp32HardwareCan()
{
}
/// Enables the ESP32 CAN driver
virtual void enable()
{
ESP_ERROR_CHECK(can_start());
LOG(VERBOSE, "ESP32-CAN driver enabled");
}
/// Disables the ESP32 CAN driver
virtual void disable()
{
ESP_ERROR_CHECK(can_stop());
LOG(VERBOSE, "ESP32-CAN driver disabled");
}
protected:
/// function to try and transmit a message
void tx_msg() override
{
// wake up the tx_task so it can consume any can_frames from txBuf.
xTaskNotifyGive(txTaskHandle_);
}
private:
/// Default constructor.
Esp32HardwareCan();
/// Enables/Disables the periodic reporting of CAN bus statistics to the
/// default serial stream.
bool reportStats_;
/// Handle for the tx_task that converts and transmits can_frame to the
/// native can driver.
TaskHandle_t txTaskHandle_;
/// Handle for the rx_task that receives and converts the native can driver
/// frames to can_frame.
TaskHandle_t rxTaskHandle_;
/// Interval at which to print the ESP32 CAN bus status.
static constexpr TickType_t STATUS_PRINT_INTERVAL = pdMS_TO_TICKS(10000);
/// Interval to wait between iterations when the bus is recovering, a
/// transmit failure or there is nothing to transmit.
static constexpr TickType_t TX_DEFAULT_DELAY = pdMS_TO_TICKS(250);
/// Priority to use for the rx_task. This needs to be higher than the
/// tx_task and lower than @ref OPENMRN_TASK_PRIORITY.
static constexpr UBaseType_t RX_TASK_PRIORITY = ESP_TASK_TCPIP_PRIO - 1;
/// Priority to use for the tx_task. This should be lower than
/// @ref RX_TASK_PRIORITY and @ref OPENMRN_TASK_PRIORITY.
static constexpr UBaseType_t TX_TASK_PRIORITY = ESP_TASK_TCPIP_PRIO - 2;
/// Background task that takes care of the conversion of the @ref can_frame
/// provided by the @ref txBuf into an ESP32 can_message_t which can be
/// processed by the native CAN driver. This task also covers the periodic
/// status reporting and BUS recovery when necessary.
static void tx_task(void *can)
{
/// Get handle to our parent Esp32HardwareCan object to access the
/// txBuf.
Esp32HardwareCan *parent = reinterpret_cast<Esp32HardwareCan *>(can);
// Add this task to the WDT
esp_task_wdt_add(parent->txTaskHandle_);
/// Tracks the last time that we displayed the CAN driver status.
TickType_t next_status_display_tick_count = 0;
while (true)
{
// Feed the watchdog so it doesn't reset the ESP32
esp_task_wdt_reset();
// periodic CAN driver monitoring and reporting, this takes care of
// bus recovery when the CAN driver disables the bus due to error
// conditions exceeding thresholds.
can_status_info_t status;
can_get_status_info(&status);
auto current_tick_count = xTaskGetTickCount();
if ((next_status_display_tick_count == 0 ||
current_tick_count >= next_status_display_tick_count) &&
parent->reportStats_)
{
next_status_display_tick_count =
current_tick_count + STATUS_PRINT_INTERVAL;
LOG(INFO,
"ESP32-CAN: rx-q:%d, tx-q:%d, rx-err:%d, tx-err:%d, "
"arb-lost:%d, bus-err:%d, state: %s",
status.msgs_to_rx, status.msgs_to_tx,
status.rx_error_counter, status.tx_error_counter,
status.arb_lost_count, status.bus_error_count,
ESP32_CAN_STATUS_STRINGS[status.state]);
}
if (status.state == CAN_STATE_BUS_OFF)
{
// When the bus is OFF we need to initiate recovery, transmit is
// not possible when in this state.
LOG(WARNING, "ESP32-CAN: initiating recovery");
can_initiate_recovery();
continue;
}
else if (status.state == CAN_STATE_RECOVERING)
{
// when the bus is in recovery mode transmit is not possible.
vTaskDelay(TX_DEFAULT_DELAY);
continue;
}
// check txBuf for any message to transmit.
unsigned count;
struct can_frame *can_frame = nullptr;
{
AtomicHolder h(parent);
count = parent->txBuf->data_read_pointer(&can_frame);
}
if (!count || !can_frame)
{
// tx Buf empty; wait for tx_msg to be called.
ulTaskNotifyTake(pdTRUE, // clear on exit
TX_DEFAULT_DELAY);
continue;
}
/// ESP32 native CAN driver frame
can_message_t msg = {0};
msg.flags = CAN_MSG_FLAG_NONE;
msg.identifier = can_frame->can_id;
msg.data_length_code = can_frame->can_dlc;
for (int i = 0; i < can_frame->can_dlc; i++)
{
msg.data[i] = can_frame->data[i];
}
if (IS_CAN_FRAME_EFF(*can_frame))
{
msg.flags |= CAN_MSG_FLAG_EXTD;
}
if (IS_CAN_FRAME_RTR(*can_frame))
{
msg.flags |= CAN_MSG_FLAG_RTR;
}
// Pass the converted CAN frame to the native driver
// for transmit, if the TX queue is full this will
// return ESP_ERR_TIMEOUT which will result in the
// the message being left in txBuf for the next iteration.
// if this call returns ESP_OK we consider the frame as
// transmitted by the driver and remove it from txBuf.
esp_err_t tx_res = can_transmit(&msg, pdMS_TO_TICKS(100));
if (tx_res == ESP_OK)
{
LOG(VERBOSE,
"ESP32-CAN-TX OK id:%08x, flags:%04x, dlc:%02d, "
"data:%02x%02x%02x%02x%02x%02x%02x%02x",
msg.identifier, msg.flags, msg.data_length_code,
msg.data[0], msg.data[1], msg.data[2], msg.data[3],
msg.data[4], msg.data[5], msg.data[6], msg.data[7]);
AtomicHolder h(parent);
parent->txBuf->consume(1);
parent->txBuf->signal_condition();
}
else if (tx_res != ESP_ERR_TIMEOUT)
{
LOG(WARNING, "ESP32-CAN-TX: %s", esp_err_to_name(tx_res));
vTaskDelay(TX_DEFAULT_DELAY);
}
} // loop on task
}
/// Background task that takes care of receiving can_message_t objects from
/// the ESP32 native CAN driver, when they are available, converting them to
/// a @ref can_frame and pushing them to the @ref rxBuf.
static void rx_task(void *can)
{
/// Get handle to our parent Esp32HardwareCan object to access the rxBuf
Esp32HardwareCan *parent = reinterpret_cast<Esp32HardwareCan *>(can);
// Add this task to the WDT
esp_task_wdt_add(parent->rxTaskHandle_);
while (true)
{
// Feed the watchdog so it doesn't reset the ESP32
esp_task_wdt_reset();
/// ESP32 native CAN driver frame
can_message_t msg = {0};
if (can_receive(&msg, pdMS_TO_TICKS(250)) == ESP_OK)
{
// frame retrieved from the driver, convert to OpenMRN can_frame
if (msg.flags & CAN_MSG_FLAG_DLC_NON_COMP)
{
LOG(WARNING,
"ESP32-CAN-RX: received non-compliant CAN frame, frame "
"dropped!");
}
else
{
LOG(VERBOSE,
"ESP32-CAN-RX id:%08x, flags:%04x, dlc:%02d, "
"data:%02x%02x%02x%02x%02x%02x%02x%02x",
msg.identifier, msg.flags, msg.data_length_code,
msg.data[0], msg.data[1], msg.data[2], msg.data[3],
msg.data[4], msg.data[5], msg.data[6], msg.data[7]);
AtomicHolder h(parent);
struct can_frame *can_frame = nullptr;
if (parent->rxBuf->data_write_pointer(&can_frame) &&
can_frame != nullptr)
{
LOG(VERBOSE, "ESP32-CAN-RX: converting to can_frame");
memset(can_frame, 0, sizeof(struct can_frame));
can_frame->can_id = msg.identifier;
can_frame->can_dlc = msg.data_length_code;
for (int i = 0; i < msg.data_length_code; i++)
{
can_frame->data[i] = msg.data[i];
}
if (msg.flags & CAN_MSG_FLAG_EXTD)
{
can_frame->can_eff = 1;
}
if (msg.flags & CAN_MSG_FLAG_RTR)
{
can_frame->can_rtr = 1;
}
parent->rxBuf->advance(1);
parent->rxBuf->signal_condition();
}
else
{
LOG(WARNING,
"ESP32-CAN-RX: buffer overrun, frame dropped!");
parent->overrunCount++;
}
}
}
}
}
DISALLOW_COPY_AND_ASSIGN(Esp32HardwareCan);
};
#endif /* _FREERTOS_DRIVERS_ARDUINO_ESP32HWCAN_HXX_ */
<commit_msg>review comments<commit_after>/** \copyright
* Copyright (c) 2019, Mike Dunston
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file Esp32HardwareCanAdapter.hxx
*
* ESP32 Hardware CAN adapter code. This utilizes the built in CAN controller
* to translate the can_frame in OpenMRN to the ESP32 can_message_t used by the
* ESP-IDF CAN controller code. The ESP32 will still require an external CAN
* transceiver (MCP2551 or SN65HVD230 as example).
*
* @author Mike Dunston
* @date 19 January 2019
*/
#ifndef _FREERTOS_DRIVERS_ESP32_ESP32HWCAN_HXX_
#define _FREERTOS_DRIVERS_ESP32_ESP32HWCAN_HXX_
#include "freertos_drivers/arduino/Can.hxx"
#include <driver/can.h>
#include <driver/gpio.h>
#include <esp_task_wdt.h>
/// ESP32 CAN bus status strings, used for periodic status reporting
static const char *ESP32_CAN_STATUS_STRINGS[] = {
"STOPPED", // CAN_STATE_STOPPED
"RUNNING", // CAN_STATE_RUNNING
"OFF / RECOVERY NEEDED", // CAN_STATE_BUS_OFF
"RECOVERY UNDERWAY" // CAN_STATE_RECOVERING
};
class Esp32HardwareCan : public Can
{
public:
/// Constructor.
///
/// @param name is the name for the CAN adapter, this is currently not used.
/// @param rxPin is the ESP32 pin that is connected to the external
/// transceiver RX.
/// @param txPin is the ESP32 pin that is connected to the external
/// transceiver TX.
Esp32HardwareCan(const char *name, gpio_num_t rxPin, gpio_num_t txPin, bool reportStats=true)
: Can(name), reportStats_(reportStats)
{
// Configure the ESP32 CAN driver to use 125kbps.
can_timing_config_t can_timing_config = CAN_TIMING_CONFIG_125KBITS();
// By default we accept all CAN frames.
can_filter_config_t can_filter_config = CAN_FILTER_CONFIG_ACCEPT_ALL();
// Note: not using the CAN_GENERAL_CONFIG_DEFAULT macro due to a missing
// cast for CAN_IO_UNUSED.
can_general_config_t can_general_config = {.mode = CAN_MODE_NORMAL,
.tx_io = txPin,
.rx_io = rxPin,
.clkout_io = (gpio_num_t)CAN_IO_UNUSED,
.bus_off_io = (gpio_num_t)CAN_IO_UNUSED,
.tx_queue_len = (uint32_t)config_can_tx_buffer_size() / 2,
.rx_queue_len = (uint32_t)config_can_rx_buffer_size() / 2,
.alerts_enabled = CAN_ALERT_NONE,
.clkout_divider = 0};
LOG(VERBOSE,
"ESP32-CAN driver configured using RX: %d, TX: %d, RX-Q: %d, "
"TX-Q: %d",
can_general_config.rx_io, can_general_config.tx_io,
can_general_config.rx_queue_len, can_general_config.tx_queue_len);
ESP_ERROR_CHECK(can_driver_install(
&can_general_config, &can_timing_config, &can_filter_config));
xTaskCreatePinnedToCore(rx_task, "ESP32-CAN RX", OPENMRN_STACK_SIZE,
this, RX_TASK_PRIORITY, &rxTaskHandle_, tskNO_AFFINITY);
xTaskCreatePinnedToCore(tx_task, "ESP32-CAN TX", OPENMRN_STACK_SIZE,
this, TX_TASK_PRIORITY, &txTaskHandle_, tskNO_AFFINITY);
}
~Esp32HardwareCan()
{
}
/// Enables the ESP32 CAN driver
virtual void enable()
{
ESP_ERROR_CHECK(can_start());
LOG(VERBOSE, "ESP32-CAN driver enabled");
}
/// Disables the ESP32 CAN driver
virtual void disable()
{
ESP_ERROR_CHECK(can_stop());
LOG(VERBOSE, "ESP32-CAN driver disabled");
}
protected:
/// function to try and transmit a message
void tx_msg() override
{
// wake up the tx_task so it can consume any can_frames from txBuf.
xTaskNotifyGive(txTaskHandle_);
}
private:
/// Default constructor.
Esp32HardwareCan();
/// Enables/Disables the periodic reporting of CAN bus statistics to the
/// default serial stream.
bool reportStats_;
/// Handle for the tx_task that converts and transmits can_frame to the
/// native can driver.
TaskHandle_t txTaskHandle_;
/// Handle for the rx_task that receives and converts the native can driver
/// frames to can_frame.
TaskHandle_t rxTaskHandle_;
/// Interval at which to print the ESP32 CAN bus status.
static constexpr TickType_t STATUS_PRINT_INTERVAL = pdMS_TO_TICKS(10000);
/// Interval to wait between iterations when the bus is recovering, a
/// transmit failure or there is nothing to transmit.
static constexpr TickType_t TX_DEFAULT_DELAY = pdMS_TO_TICKS(250);
/// Priority to use for the rx_task. This needs to be higher than the
/// tx_task and lower than @ref OPENMRN_TASK_PRIORITY.
static constexpr UBaseType_t RX_TASK_PRIORITY = ESP_TASK_TCPIP_PRIO - 1;
/// Priority to use for the tx_task. This should be lower than
/// @ref RX_TASK_PRIORITY and @ref OPENMRN_TASK_PRIORITY.
static constexpr UBaseType_t TX_TASK_PRIORITY = ESP_TASK_TCPIP_PRIO - 2;
/// Background task that takes care of the conversion of the @ref can_frame
/// provided by the @ref txBuf into an ESP32 can_message_t which can be
/// processed by the native CAN driver. This task also covers the periodic
/// status reporting and BUS recovery when necessary.
static void tx_task(void *can)
{
/// Get handle to our parent Esp32HardwareCan object to access the
/// txBuf.
Esp32HardwareCan *parent = reinterpret_cast<Esp32HardwareCan *>(can);
// Add this task to the WDT
esp_task_wdt_add(parent->txTaskHandle_);
/// Tracks the last time that we displayed the CAN driver status.
TickType_t next_status_display_tick_count = 0;
while (true)
{
// Feed the watchdog so it doesn't reset the ESP32
esp_task_wdt_reset();
// periodic CAN driver monitoring and reporting, this takes care of
// bus recovery when the CAN driver disables the bus due to error
// conditions exceeding thresholds.
can_status_info_t status;
can_get_status_info(&status);
auto current_tick_count = xTaskGetTickCount();
if ((next_status_display_tick_count == 0 ||
current_tick_count >= next_status_display_tick_count) &&
parent->reportStats_)
{
next_status_display_tick_count =
current_tick_count + STATUS_PRINT_INTERVAL;
LOG(INFO,
"ESP32-CAN: rx-q:%d, tx-q:%d, rx-err:%d, tx-err:%d, "
"arb-lost:%d, bus-err:%d, state: %s",
status.msgs_to_rx, status.msgs_to_tx,
status.rx_error_counter, status.tx_error_counter,
status.arb_lost_count, status.bus_error_count,
ESP32_CAN_STATUS_STRINGS[status.state]);
}
if (status.state == CAN_STATE_BUS_OFF)
{
// When the bus is OFF we need to initiate recovery, transmit is
// not possible when in this state.
LOG(WARNING, "ESP32-CAN: initiating recovery");
can_initiate_recovery();
continue;
}
else if (status.state == CAN_STATE_RECOVERING)
{
// when the bus is in recovery mode transmit is not possible.
vTaskDelay(TX_DEFAULT_DELAY);
continue;
}
// check txBuf for any message to transmit.
unsigned count;
struct can_frame *can_frame = nullptr;
{
AtomicHolder h(parent);
count = parent->txBuf->data_read_pointer(&can_frame);
}
if (!count || !can_frame)
{
// tx Buf empty; wait for tx_msg to be called.
ulTaskNotifyTake(pdTRUE, // clear on exit
TX_DEFAULT_DELAY);
continue;
}
/// ESP32 native CAN driver frame
can_message_t msg = {0};
msg.flags = CAN_MSG_FLAG_NONE;
msg.identifier = can_frame->can_id;
msg.data_length_code = can_frame->can_dlc;
for (int i = 0; i < can_frame->can_dlc; i++)
{
msg.data[i] = can_frame->data[i];
}
if (IS_CAN_FRAME_EFF(*can_frame))
{
msg.flags |= CAN_MSG_FLAG_EXTD;
}
if (IS_CAN_FRAME_RTR(*can_frame))
{
msg.flags |= CAN_MSG_FLAG_RTR;
}
// Pass the converted CAN frame to the native driver
// for transmit, if the TX queue is full this will
// return ESP_ERR_TIMEOUT which will result in the
// the message being left in txBuf for the next iteration.
// if this call returns ESP_OK we consider the frame as
// transmitted by the driver and remove it from txBuf.
esp_err_t tx_res = can_transmit(&msg, pdMS_TO_TICKS(100));
if (tx_res == ESP_OK)
{
LOG(VERBOSE,
"ESP32-CAN-TX OK id:%08x, flags:%04x, dlc:%02d, "
"data:%02x%02x%02x%02x%02x%02x%02x%02x",
msg.identifier, msg.flags, msg.data_length_code,
msg.data[0], msg.data[1], msg.data[2], msg.data[3],
msg.data[4], msg.data[5], msg.data[6], msg.data[7]);
AtomicHolder h(parent);
parent->txBuf->consume(1);
parent->txBuf->signal_condition();
}
else if (tx_res != ESP_ERR_TIMEOUT)
{
LOG(WARNING, "ESP32-CAN-TX: %s", esp_err_to_name(tx_res));
vTaskDelay(TX_DEFAULT_DELAY);
}
} // loop on task
}
/// Background task that takes care of receiving can_message_t objects from
/// the ESP32 native CAN driver, when they are available, converting them to
/// a @ref can_frame and pushing them to the @ref rxBuf.
static void rx_task(void *can)
{
/// Get handle to our parent Esp32HardwareCan object to access the rxBuf
Esp32HardwareCan *parent = reinterpret_cast<Esp32HardwareCan *>(can);
// Add this task to the WDT
esp_task_wdt_add(parent->rxTaskHandle_);
while (true)
{
// Feed the watchdog so it doesn't reset the ESP32
esp_task_wdt_reset();
/// ESP32 native CAN driver frame
can_message_t msg = {0};
if (can_receive(&msg, pdMS_TO_TICKS(250)) != ESP_OK)
{
// native CAN driver did not give us a frame.
continue;
}
// we have received a frame from the native CAN driver, verify if
// it is a standard frame, if not we drop it.
if (msg.flags & CAN_MSG_FLAG_DLC_NON_COMP)
{
LOG(WARNING,
"ESP32-CAN-RX: received non-compliant CAN frame, frame "
"dropped!");
continue;
}
LOG(VERBOSE,
"ESP32-CAN-RX id:%08x, flags:%04x, dlc:%02d, "
"data:%02x%02x%02x%02x%02x%02x%02x%02x",
msg.identifier, msg.flags, msg.data_length_code,
msg.data[0], msg.data[1], msg.data[2], msg.data[3],
msg.data[4], msg.data[5], msg.data[6], msg.data[7]);
AtomicHolder h(parent);
struct can_frame *can_frame = nullptr;
// verify if we have space in the rxBuf, if not drop the frame and
// record the overrun.
if (!parent->rxBuf->data_write_pointer(&can_frame) ||
can_frame == nullptr)
{
LOG(WARNING,
"ESP32-CAN-RX: buffer overrun, frame dropped!");
parent->overrunCount++;
continue;
}
// we have space in the rxBuf, start conversion
LOG(VERBOSE, "ESP32-CAN-RX: converting to can_frame");
memset(can_frame, 0, sizeof(struct can_frame));
can_frame->can_id = msg.identifier;
can_frame->can_dlc = msg.data_length_code;
for (int i = 0; i < msg.data_length_code; i++)
{
can_frame->data[i] = msg.data[i];
}
if (msg.flags & CAN_MSG_FLAG_EXTD)
{
SET_CAN_FRAME_EFF(*can_frame);
}
if (msg.flags & CAN_MSG_FLAG_RTR)
{
SET_CAN_FRAME_RTR(*can_frame);
}
parent->rxBuf->advance(1);
parent->rxBuf->signal_condition();
}
}
DISALLOW_COPY_AND_ASSIGN(Esp32HardwareCan);
};
#endif /* _FREERTOS_DRIVERS_ARDUINO_ESP32HWCAN_HXX_ */
<|endoftext|> |
<commit_before>/*****************************************************************************
* utils.cpp: ActiveX control for VLC
*****************************************************************************
* Copyright (C) 2005 the VideoLAN team
*
* Authors: Damien Fouilleul <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "utils.h"
/*
** conversion facilities
*/
using namespace std;
char *CStrFromBSTR(UINT codePage, BSTR bstr)
{
UINT len = SysStringLen(bstr);
if( len > 0 )
{
size_t mblen = WideCharToMultiByte(codePage,
0, bstr, len, NULL, 0, NULL, NULL);
if( mblen > 0 )
{
char *buffer = (char *)CoTaskMemAlloc(mblen+1);
ZeroMemory(buffer, mblen+1);
if( WideCharToMultiByte(codePage, 0, bstr, len, buffer, mblen, NULL, NULL) )
{
buffer[mblen] = '\0';
return buffer;
}
}
}
return NULL;
};
BSTR BSTRFromCStr(UINT codePage, LPCSTR s)
{
int wideLen = MultiByteToWideChar(codePage, 0, s, -1, NULL, 0);
if( wideLen > 0 )
{
WCHAR* wideStr = (WCHAR*)CoTaskMemAlloc(wideLen*sizeof(WCHAR));
if( NULL != wideStr )
{
BSTR bstr;
ZeroMemory(wideStr, wideLen*sizeof(WCHAR));
MultiByteToWideChar(codePage, 0, s, -1, wideStr, wideLen);
bstr = SysAllocStringLen(wideStr, wideLen);
free(wideStr);
return bstr;
}
}
return NULL;
};
/*
** properties
*/
HRESULT GetObjectProperty(LPUNKNOWN object, DISPID dispID, VARIANT& v)
{
IDispatch *pDisp;
HRESULT hr = object->QueryInterface(IID_IDispatch, (LPVOID *)&pDisp);
if( SUCCEEDED(hr) )
{
DISPPARAMS dispparamsNoArgs = {NULL, NULL, 0, 0};
VARIANT vres;
VariantInit(&vres);
hr = pDisp->Invoke(dispID, IID_NULL, LOCALE_USER_DEFAULT,
DISPATCH_PROPERTYGET, &dispparamsNoArgs, &vres, NULL, NULL);
if( SUCCEEDED(hr) )
{
if( V_VT(&v) != V_VT(&vres) )
{
hr = VariantChangeType(&v, &vres, 0, V_VT(&v));
VariantClear(&vres);
}
else
{
v = vres;
}
}
pDisp->Release();
}
return hr;
};
HDC CreateDevDC(DVTARGETDEVICE *ptd)
{
HDC hdc=NULL;
LPDEVNAMES lpDevNames;
LPDEVMODE lpDevMode;
LPTSTR lpszDriverName;
LPTSTR lpszDeviceName;
LPTSTR lpszPortName;
if (ptd == NULL) {
hdc = CreateDC(TEXT("DISPLAY"), NULL, NULL, NULL);
goto errReturn;
}
lpDevNames = (LPDEVNAMES) ptd; // offset for size field
if (ptd->tdExtDevmodeOffset == 0) {
lpDevMode = NULL;
}else{
lpDevMode = (LPDEVMODE) ((LPTSTR)ptd + ptd->tdExtDevmodeOffset);
}
lpszDriverName = (LPTSTR) lpDevNames + ptd->tdDriverNameOffset;
lpszDeviceName = (LPTSTR) lpDevNames + ptd->tdDeviceNameOffset;
lpszPortName = (LPTSTR) lpDevNames + ptd->tdPortNameOffset;
hdc = CreateDC(lpszDriverName, lpszDeviceName, lpszPortName, lpDevMode);
errReturn:
return hdc;
};
#define HIMETRIC_PER_INCH 2540
void DPFromHimetric(HDC hdc, LPPOINT pt, int count)
{
LONG lpX = GetDeviceCaps(hdc, LOGPIXELSX);
LONG lpY = GetDeviceCaps(hdc, LOGPIXELSY);
while( count-- )
{
pt->x = pt->x*lpX/HIMETRIC_PER_INCH;
pt->y = pt->y*lpY/HIMETRIC_PER_INCH;
++pt;
}
};
void HimetricFromDP(HDC hdc, LPPOINT pt, int count)
{
LONG lpX = GetDeviceCaps(hdc, LOGPIXELSX);
LONG lpY = GetDeviceCaps(hdc, LOGPIXELSY);
while( count-- )
{
pt->x = pt->x*HIMETRIC_PER_INCH/lpX;
pt->y = pt->y*HIMETRIC_PER_INCH/lpY;
++pt;
}
};
<commit_msg>- minor fixes<commit_after>/*****************************************************************************
* utils.cpp: ActiveX control for VLC
*****************************************************************************
* Copyright (C) 2005 the VideoLAN team
*
* Authors: Damien Fouilleul <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "utils.h"
/*
** conversion facilities
*/
using namespace std;
char *CStrFromBSTR(UINT codePage, BSTR bstr)
{
UINT len = SysStringLen(bstr);
if( len > 0 )
{
size_t mblen = WideCharToMultiByte(codePage,
0, bstr, len, NULL, 0, NULL, NULL);
if( mblen > 0 )
{
char *buffer = (char *)CoTaskMemAlloc(mblen+1);
ZeroMemory(buffer, mblen+1);
if( WideCharToMultiByte(codePage, 0, bstr, len, buffer, mblen, NULL, NULL) )
{
buffer[mblen] = '\0';
return buffer;
}
}
}
return NULL;
};
BSTR BSTRFromCStr(UINT codePage, LPCSTR s)
{
int wideLen = MultiByteToWideChar(codePage, 0, s, -1, NULL, 0);
if( wideLen > 0 )
{
WCHAR* wideStr = (WCHAR*)CoTaskMemAlloc(wideLen*sizeof(WCHAR));
if( NULL != wideStr )
{
BSTR bstr;
ZeroMemory(wideStr, wideLen*sizeof(WCHAR));
MultiByteToWideChar(codePage, 0, s, -1, wideStr, wideLen);
bstr = SysAllocStringLen(wideStr, wideLen);
CoTaskMemFree(wideStr);
return bstr;
}
}
return NULL;
};
/*
** properties
*/
HRESULT GetObjectProperty(LPUNKNOWN object, DISPID dispID, VARIANT& v)
{
IDispatch *pDisp;
HRESULT hr = object->QueryInterface(IID_IDispatch, (LPVOID *)&pDisp);
if( SUCCEEDED(hr) )
{
DISPPARAMS dispparamsNoArgs = {NULL, NULL, 0, 0};
VARIANT vres;
VariantInit(&vres);
hr = pDisp->Invoke(dispID, IID_NULL, LOCALE_USER_DEFAULT,
DISPATCH_PROPERTYGET, &dispparamsNoArgs, &vres, NULL, NULL);
if( SUCCEEDED(hr) )
{
if( V_VT(&v) != V_VT(&vres) )
{
hr = VariantChangeType(&v, &vres, 0, V_VT(&v));
VariantClear(&vres);
}
else
{
v = vres;
}
}
pDisp->Release();
}
return hr;
};
HDC CreateDevDC(DVTARGETDEVICE *ptd)
{
HDC hdc=NULL;
if( NULL == ptd )
{
hdc = CreateDC(TEXT("DISPLAY"), NULL, NULL, NULL);
}
else
{
LPDEVNAMES lpDevNames;
LPDEVMODE lpDevMode;
LPTSTR lpszDriverName;
LPTSTR lpszDeviceName;
LPTSTR lpszPortName;
lpDevNames = (LPDEVNAMES) ptd; // offset for size field
if (ptd->tdExtDevmodeOffset == 0)
{
lpDevMode = NULL;
}
else
{
lpDevMode = (LPDEVMODE) ((LPTSTR)ptd + ptd->tdExtDevmodeOffset);
}
lpszDriverName = (LPTSTR) lpDevNames + ptd->tdDriverNameOffset;
lpszDeviceName = (LPTSTR) lpDevNames + ptd->tdDeviceNameOffset;
lpszPortName = (LPTSTR) lpDevNames + ptd->tdPortNameOffset;
hdc = CreateDC(lpszDriverName, lpszDeviceName, lpszPortName, lpDevMode);
}
return hdc;
};
#define HIMETRIC_PER_INCH 2540
void DPFromHimetric(HDC hdc, LPPOINT pt, int count)
{
LONG lpX = GetDeviceCaps(hdc, LOGPIXELSX);
LONG lpY = GetDeviceCaps(hdc, LOGPIXELSY);
while( count-- )
{
pt->x = pt->x*lpX/HIMETRIC_PER_INCH;
pt->y = pt->y*lpY/HIMETRIC_PER_INCH;
++pt;
}
};
void HimetricFromDP(HDC hdc, LPPOINT pt, int count)
{
LONG lpX = GetDeviceCaps(hdc, LOGPIXELSX);
LONG lpY = GetDeviceCaps(hdc, LOGPIXELSY);
while( count-- )
{
pt->x = pt->x*HIMETRIC_PER_INCH/lpX;
pt->y = pt->y*HIMETRIC_PER_INCH/lpY;
++pt;
}
};
<|endoftext|> |
<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "core/graph/function_impl.h"
#include "core/graph/graph_viewer.h"
#include "core/graph/model.h"
#include "onnx/shape_inference/implementation.h"
namespace onnxruntime {
// Auto inferred and generate an opschema for stand-alone functions
// TODO: revisit to see if we can eliminate typeconstraint step
void IOTypeConstraintHelper(const ONNX_NAMESPACE::FunctionProto* onnx_func_proto_,
std::unique_ptr<ONNX_NAMESPACE::OpSchema>& op_schema_,
const std::unordered_map<std::string, int>& input_name_idx_map,
const std::unordered_map<std::string, int>& output_name_idx_map) {
std::vector<std::pair<std::string, std::string>> input_types_list(onnx_func_proto_->input_size());
std::vector<std::pair<std::string, std::string>> output_types_list(onnx_func_proto_->output_size());
std::unordered_map<std::string, std::vector<std::string>> type_constraint_map;
std::unordered_map<std::string, ONNX_NAMESPACE::AttributeProto_AttributeType> attribute_type_map;
auto schema_registry = ONNX_NAMESPACE::OpSchemaRegistry::Instance();
for (auto& node : onnx_func_proto_->node()) {
const auto node_op_schema =
schema_registry->GetSchema(node.op_type(), static_cast<int>(onnx_func_proto_->since_version()), node.domain());
for (int i = 0; i < node.input_size(); ++i) {
auto& in_name = node.input().Get(i);
auto iter = input_name_idx_map.find(in_name);
if (iter != input_name_idx_map.end()) {
int idx = iter->second;
const auto& p = node_op_schema->inputs().at(i);
std::string type_str = p.GetTypeStr() + "in" + std::to_string(i);
input_types_list[idx] = std::make_pair(in_name, type_str);
if (!type_constraint_map.count(type_str)) {
for (auto s : p.GetTypes()) {
type_constraint_map[type_str].emplace_back(*s);
}
}
}
}
for (int i = 0; i < node.output_size(); ++i) {
auto& out_name = node.output().Get(i);
auto iter = output_name_idx_map.find(out_name);
if (iter != output_name_idx_map.end()) {
int idx = iter->second;
const auto& p = node_op_schema->outputs().at(i);
std::string type_str = p.GetTypeStr() + "out" + std::to_string(i);
output_types_list[idx] = std::make_pair(out_name, type_str);
if (!type_constraint_map.count(type_str)) {
for (auto s : p.GetTypes()) {
type_constraint_map[type_str].emplace_back(*s);
}
}
}
}
// If an subgraph node attribute has a specified
// type attribute, we add its referenced attribute
// into the op's schema
for (auto& attr : node.attribute()) {
if (attr.has_ref_attr_name() && attr.has_type())
attribute_type_map[attr.ref_attr_name()] = attr.type();
}
}
int i = 0;
for (auto& input : input_types_list) {
op_schema_->Input(i, input.first, "", input.second);
++i;
}
i = 0;
for (auto& output : output_types_list) {
op_schema_->Output(i, output.first, "", output.second);
++i;
}
for (auto& tc : type_constraint_map) {
op_schema_->TypeConstraint(tc.first, tc.second, "");
}
for (auto& attribute_name : onnx_func_proto_->attribute()) {
if (attribute_type_map.count(attribute_name))
op_schema_->Attr(attribute_name, "", attribute_type_map[attribute_name], false);
}
}
FunctionImpl::FunctionImpl(const onnxruntime::Graph& graph,
std::unique_ptr<IndexedSubGraph> customized_func)
: parent_graph_(&graph), onnx_func_proto_{nullptr} {
customized_func_body_ = std::move(customized_func);
// Construct body.
body_ = std::make_unique<onnxruntime::Model>("fused_function_subgraph", false, onnxruntime::ModelMetaData(),
IOnnxRuntimeOpSchemaRegistryList({graph.GetSchemaRegistry()}),
graph.DomainToVersionMap());
auto& sub_graph = body_->MainGraph();
auto meta_def = customized_func_body_->GetMetaDef();
op_schema_ = std::make_unique<ONNX_NAMESPACE::OpSchema>();
op_schema_->SetName(meta_def->name);
op_schema_->SetDomain(meta_def->domain);
op_schema_->SetDoc(meta_def->doc_string);
op_schema_->SinceVersion(meta_def->since_version);
int i = 0;
std::vector<const NodeArg*> sub_graph_inputs;
sub_graph_inputs.resize(meta_def->inputs.size());
for (auto& input : meta_def->inputs) {
auto input_arg = parent_graph_->GetNodeArg(input);
auto& sub_graph_input_arg = sub_graph.GetOrCreateNodeArg(input_arg->Name(), input_arg->TypeAsProto());
sub_graph_inputs[i] = &sub_graph_input_arg;
op_schema_->Input(i, input, "", *input_arg->Type());
++i;
}
i = 0;
std::vector<const NodeArg*> sub_graph_outputs;
sub_graph_outputs.resize(meta_def->outputs.size());
for (auto& output : meta_def->outputs) {
auto output_arg = parent_graph_->GetNodeArg(output);
auto& sub_graph_output_arg = sub_graph.GetOrCreateNodeArg(output_arg->Name(), output_arg->TypeAsProto());
sub_graph_outputs[i] = &sub_graph_output_arg;
op_schema_->Output(i, output, "", *output_arg->Type());
++i;
}
op_schema_->Finalize();
sub_graph.SetInputs(sub_graph_inputs);
sub_graph.SetOutputs(sub_graph_outputs);
//Add node and node args
//TODO: for better performance, we could try to transfer the nodes in parent graph to sub-graph directly,
//instead of create new nodes.
for (auto& node_index : customized_func_body_->nodes) {
auto node = parent_graph_->GetNode(node_index);
std::vector<onnxruntime::NodeArg*> inputs;
std::vector<onnxruntime::NodeArg*> outputs;
for (auto input : node->InputDefs()) {
auto& n_input = sub_graph.GetOrCreateNodeArg(input->Name(), input->TypeAsProto());
inputs.push_back(&n_input);
}
for (auto output : node->OutputDefs()) {
auto& n_output = sub_graph.GetOrCreateNodeArg(output->Name(), output->TypeAsProto());
outputs.push_back(&n_output);
}
sub_graph.AddNode(node->Name(), node->OpType(), node->Description(), inputs, outputs, &node->GetAttributes(), node->Domain());
}
for (const auto& input : meta_def->inputs) {
const ONNX_NAMESPACE::TensorProto* initializer = nullptr;
if (graph.GetInitializedTensor(input, initializer)) {
sub_graph.AddInitializedTensor(*initializer);
}
}
//TODO: if we reuse the nodes in parent graph, maybe we don't need to resolve it.
auto status = sub_graph.Resolve();
ORT_ENFORCE(status.IsOK(), status.ErrorMessage());
}
FunctionImpl::FunctionImpl(const onnxruntime::Graph& graph,
const onnxruntime::NodeIndex& node_index,
const ONNX_NAMESPACE::FunctionProto* onnx_func_proto)
: parent_graph_(&graph) {
onnx_func_proto_ = onnx_func_proto;
auto node_in_parent_graph = parent_graph_->GetNode(node_index);
op_schema_ = std::make_unique<ONNX_NAMESPACE::OpSchema>();
op_schema_->SetName(onnx_func_proto_->name());
op_schema_->SetDomain(onnx_func_proto_->node().Get(0).domain());
op_schema_->SetDoc(onnx_func_proto_->doc_string());
op_schema_->SinceVersion(static_cast<ONNX_NAMESPACE::OperatorSetVersion>(onnx_func_proto_->since_version()));
std::unordered_map<std::string, int> input_name_idx_map;
std::unordered_map<std::string, int> output_name_idx_map;
for (int i = 0; i < onnx_func_proto_->input_size(); ++i) {
input_name_idx_map[onnx_func_proto_->input().Get(i)] = i;
}
for (int i = 0; i < onnx_func_proto_->output_size(); ++i) {
output_name_idx_map[onnx_func_proto_->output().Get(i)] = i;
}
auto cached_op_schema = node_in_parent_graph->Op();
if (!cached_op_schema) {
// Infer a op_schema for stand-alone functions.
IOTypeConstraintHelper(onnx_func_proto_, this->op_schema_, input_name_idx_map, output_name_idx_map);
} else {
auto type_constraint_params = cached_op_schema->typeConstraintParams();
for (auto& type_constraint_param : type_constraint_params) {
op_schema_->TypeConstraint(
type_constraint_param.type_param_str,
type_constraint_param.allowed_type_strs,
type_constraint_param.description);
}
int i = 0;
for (auto& input : cached_op_schema->inputs()) {
op_schema_->Input(i, input.GetName(), input.GetDescription(), input.GetTypeStr());
++i;
}
i = 0;
for (auto& output : cached_op_schema->outputs()) {
op_schema_->Output(i, output.GetName(), output.GetDescription(), output.GetTypeStr());
++i;
}
for (auto& attribute : cached_op_schema->attributes()) {
op_schema_->Attr(attribute.second);
}
}
if (!cached_op_schema || !cached_op_schema->has_type_and_shape_inference_function()) {
op_schema_->TypeAndShapeInferenceFunction(
[this](ONNX_NAMESPACE::InferenceContext& ctx) {
auto schema_registry = ONNX_NAMESPACE::OpSchemaRegistry::Instance();
const ONNX_NAMESPACE::FunctionProto* func_ptr = this->GetFuncProto();
if (nullptr != func_ptr) {
ONNX_NAMESPACE::shape_inference::InferShapeForFunctionNode(func_ptr, schema_registry, ctx);
}
});
} else {
op_schema_->TypeAndShapeInferenceFunction(cached_op_schema->GetTypeAndShapeInferenceFunction());
}
op_schema_->Finalize();
//construct body
std::unordered_map<std::string, int> domain_to_version;
//TODO: set correct domain and version
domain_to_version[onnxruntime::kOnnxDomain] = static_cast<int>(onnx_func_proto_->since_version());
body_ = std::make_unique<onnxruntime::Model>(onnx_func_proto_->name(), false, onnxruntime::ModelMetaData(),
IOnnxRuntimeOpSchemaRegistryList(), domain_to_version);
auto& sub_graph = body_->MainGraph();
// Add node and node args into subgraph
// The subgraph preserved the input/output tensor names
// in the parent graph for later inlining purpose
auto attr_map = node_in_parent_graph->GetAttributes();
for (auto& node : onnx_func_proto_->node()) {
std::vector<onnxruntime::NodeArg*> inputs;
std::vector<onnxruntime::NodeArg*> outputs;
std::string uniq_identifier = node.name();
if (!node.has_name()) {
std::stringstream ss;
ss << static_cast<const void*>(&node);
uniq_identifier = ss.str();
}
for (int idx = 0; idx < node.input_size(); ++idx) {
std::string tensor_name = node.input().Get(idx);
auto iter = input_name_idx_map.find(tensor_name);
if (iter != input_name_idx_map.end()) {
// Preserving NodeArg and input/output names
ONNX_NAMESPACE::NodeProto temp_node_proto;
node_in_parent_graph->ToProto(temp_node_proto);
const onnxruntime::NodeArg* node_arg = parent_graph_->GetNodeArg(temp_node_proto.input().Get(input_name_idx_map[tensor_name]));
auto& n_input = sub_graph.GetOrCreateNodeArg(
temp_node_proto.input().Get(iter->second), node_arg->TypeAsProto());
inputs.push_back(&n_input);
} else {
auto& n_input = sub_graph.GetOrCreateNodeArg(
tensor_name + "_" + std::to_string(node_index), nullptr);
inputs.push_back(&n_input);
}
}
for (int idx = 0; idx < node.output_size(); ++idx) {
std::string tensor_name = node.output().Get(idx);
auto iter = output_name_idx_map.find(tensor_name);
if (iter != output_name_idx_map.end()) {
// Preserving NodeArg and input/output names
ONNX_NAMESPACE::NodeProto temp_node_proto;
node_in_parent_graph->ToProto(temp_node_proto);
const onnxruntime::NodeArg* node_arg = parent_graph_->GetNodeArg(temp_node_proto.output().Get(output_name_idx_map[tensor_name]));
auto& n_output = sub_graph.GetOrCreateNodeArg(
temp_node_proto.output().Get(iter->second), node_arg->TypeAsProto());
outputs.push_back(&n_output);
} else {
auto& n_output = sub_graph.GetOrCreateNodeArg(
tensor_name + "_" + std::to_string(node_index), nullptr);
outputs.push_back(&n_output);
}
}
onnxruntime::NodeAttributes new_attr_map;
for (auto& attr : node.attribute()) {
if (attr.has_ref_attr_name()) {
if (attr_map.count(attr.ref_attr_name())) {
new_attr_map[attr.name()] = attr_map[attr.ref_attr_name()];
}
} else {
new_attr_map[attr.name()] = attr;
}
}
sub_graph.AddNode(uniq_identifier + "_" + std::to_string(node_index), node.op_type(), node.doc_string(), inputs, outputs, &new_attr_map, node.domain());
}
auto status = sub_graph.Resolve();
ORT_ENFORCE(status.IsOK(), "Resolve subgraph failed:", status.ErrorMessage());
}
FunctionImpl::~FunctionImpl() = default;
const ONNX_NAMESPACE::OpSchema& FunctionImpl::OpSchema() const {
return *op_schema_;
}
const onnxruntime::Graph& FunctionImpl::Body() const {
return body_->MainGraph();
}
const IndexedSubGraph& FunctionImpl::GetIndexedSubGraph() const {
return *customized_func_body_;
}
const ONNX_NAMESPACE::FunctionProto* FunctionImpl::GetFuncProto() const {
return onnx_func_proto_;
}
std::unique_ptr<Function> MakeFunction(const onnxruntime::Graph& graph,
std::unique_ptr<IndexedSubGraph> customized_func) {
return std::make_unique<FunctionImpl>(graph, std::move(customized_func));
}
} // namespace onnxruntime
<commit_msg>Temp fix for a crash in fused graph (#1488)<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "core/graph/function_impl.h"
#include "core/graph/graph_viewer.h"
#include "core/graph/model.h"
#include "onnx/shape_inference/implementation.h"
namespace onnxruntime {
// Auto inferred and generate an opschema for stand-alone functions
// TODO: revisit to see if we can eliminate typeconstraint step
void IOTypeConstraintHelper(const ONNX_NAMESPACE::FunctionProto* onnx_func_proto_,
std::unique_ptr<ONNX_NAMESPACE::OpSchema>& op_schema_,
const std::unordered_map<std::string, int>& input_name_idx_map,
const std::unordered_map<std::string, int>& output_name_idx_map) {
std::vector<std::pair<std::string, std::string>> input_types_list(onnx_func_proto_->input_size());
std::vector<std::pair<std::string, std::string>> output_types_list(onnx_func_proto_->output_size());
std::unordered_map<std::string, std::vector<std::string>> type_constraint_map;
std::unordered_map<std::string, ONNX_NAMESPACE::AttributeProto_AttributeType> attribute_type_map;
auto schema_registry = ONNX_NAMESPACE::OpSchemaRegistry::Instance();
for (auto& node : onnx_func_proto_->node()) {
const auto node_op_schema =
schema_registry->GetSchema(node.op_type(), static_cast<int>(onnx_func_proto_->since_version()), node.domain());
for (int i = 0; i < node.input_size(); ++i) {
auto& in_name = node.input().Get(i);
auto iter = input_name_idx_map.find(in_name);
if (iter != input_name_idx_map.end()) {
int idx = iter->second;
const auto& p = node_op_schema->inputs().at(i);
std::string type_str = p.GetTypeStr() + "in" + std::to_string(i);
input_types_list[idx] = std::make_pair(in_name, type_str);
if (!type_constraint_map.count(type_str)) {
for (auto s : p.GetTypes()) {
type_constraint_map[type_str].emplace_back(*s);
}
}
}
}
for (int i = 0; i < node.output_size(); ++i) {
auto& out_name = node.output().Get(i);
auto iter = output_name_idx_map.find(out_name);
if (iter != output_name_idx_map.end()) {
int idx = iter->second;
const auto& p = node_op_schema->outputs().at(i);
std::string type_str = p.GetTypeStr() + "out" + std::to_string(i);
output_types_list[idx] = std::make_pair(out_name, type_str);
if (!type_constraint_map.count(type_str)) {
for (auto s : p.GetTypes()) {
type_constraint_map[type_str].emplace_back(*s);
}
}
}
}
// If an subgraph node attribute has a specified
// type attribute, we add its referenced attribute
// into the op's schema
for (auto& attr : node.attribute()) {
if (attr.has_ref_attr_name() && attr.has_type())
attribute_type_map[attr.ref_attr_name()] = attr.type();
}
}
int i = 0;
for (auto& input : input_types_list) {
op_schema_->Input(i, input.first, "", input.second);
++i;
}
i = 0;
for (auto& output : output_types_list) {
op_schema_->Output(i, output.first, "", output.second);
++i;
}
for (auto& tc : type_constraint_map) {
op_schema_->TypeConstraint(tc.first, tc.second, "");
}
for (auto& attribute_name : onnx_func_proto_->attribute()) {
if (attribute_type_map.count(attribute_name))
op_schema_->Attr(attribute_name, "", attribute_type_map[attribute_name], false);
}
}
FunctionImpl::FunctionImpl(const onnxruntime::Graph& graph,
std::unique_ptr<IndexedSubGraph> customized_func)
: parent_graph_(&graph), onnx_func_proto_{nullptr} {
customized_func_body_ = std::move(customized_func);
// Construct body.
body_ = std::make_unique<onnxruntime::Model>("fused_function_subgraph", false, onnxruntime::ModelMetaData(),
IOnnxRuntimeOpSchemaRegistryList({graph.GetSchemaRegistry()}),
graph.DomainToVersionMap());
auto& sub_graph = body_->MainGraph();
auto meta_def = customized_func_body_->GetMetaDef();
op_schema_ = std::make_unique<ONNX_NAMESPACE::OpSchema>();
op_schema_->SetName(meta_def->name);
op_schema_->SetDomain(meta_def->domain);
op_schema_->SetDoc(meta_def->doc_string);
op_schema_->SinceVersion(meta_def->since_version);
int i = 0;
std::vector<const NodeArg*> sub_graph_inputs;
sub_graph_inputs.resize(meta_def->inputs.size());
for (auto& input : meta_def->inputs) {
auto input_arg = parent_graph_->GetNodeArg(input);
auto& sub_graph_input_arg = sub_graph.GetOrCreateNodeArg(input_arg->Name(), input_arg->TypeAsProto());
sub_graph_inputs[i] = &sub_graph_input_arg;
ORT_ENFORCE(input_arg->Type() != nullptr);
op_schema_->Input(i, input, "", *input_arg->Type());
++i;
}
i = 0;
std::vector<const NodeArg*> sub_graph_outputs;
sub_graph_outputs.resize(meta_def->outputs.size());
for (auto& output : meta_def->outputs) {
auto output_arg = parent_graph_->GetNodeArg(output);
auto& sub_graph_output_arg = sub_graph.GetOrCreateNodeArg(output_arg->Name(), output_arg->TypeAsProto());
sub_graph_outputs[i] = &sub_graph_output_arg;
op_schema_->Output(i, output, "", *output_arg->Type());
++i;
}
op_schema_->Finalize();
sub_graph.SetInputs(sub_graph_inputs);
sub_graph.SetOutputs(sub_graph_outputs);
//Add node and node args
//TODO: for better performance, we could try to transfer the nodes in parent graph to sub-graph directly,
//instead of create new nodes.
for (auto& node_index : customized_func_body_->nodes) {
auto node = parent_graph_->GetNode(node_index);
std::vector<onnxruntime::NodeArg*> inputs;
std::vector<onnxruntime::NodeArg*> outputs;
for (auto input : node->InputDefs()) {
auto& n_input = sub_graph.GetOrCreateNodeArg(input->Name(), input->TypeAsProto());
inputs.push_back(&n_input);
}
for (auto output : node->OutputDefs()) {
auto& n_output = sub_graph.GetOrCreateNodeArg(output->Name(), output->TypeAsProto());
outputs.push_back(&n_output);
}
sub_graph.AddNode(node->Name(), node->OpType(), node->Description(), inputs, outputs, &node->GetAttributes(), node->Domain());
}
for (const auto& input : meta_def->inputs) {
const ONNX_NAMESPACE::TensorProto* initializer = nullptr;
if (graph.GetInitializedTensor(input, initializer)) {
sub_graph.AddInitializedTensor(*initializer);
}
}
//TODO: if we reuse the nodes in parent graph, maybe we don't need to resolve it.
auto status = sub_graph.Resolve();
ORT_ENFORCE(status.IsOK(), status.ErrorMessage());
}
FunctionImpl::FunctionImpl(const onnxruntime::Graph& graph,
const onnxruntime::NodeIndex& node_index,
const ONNX_NAMESPACE::FunctionProto* onnx_func_proto)
: parent_graph_(&graph) {
onnx_func_proto_ = onnx_func_proto;
auto node_in_parent_graph = parent_graph_->GetNode(node_index);
op_schema_ = std::make_unique<ONNX_NAMESPACE::OpSchema>();
op_schema_->SetName(onnx_func_proto_->name());
op_schema_->SetDomain(onnx_func_proto_->node().Get(0).domain());
op_schema_->SetDoc(onnx_func_proto_->doc_string());
op_schema_->SinceVersion(static_cast<ONNX_NAMESPACE::OperatorSetVersion>(onnx_func_proto_->since_version()));
std::unordered_map<std::string, int> input_name_idx_map;
std::unordered_map<std::string, int> output_name_idx_map;
for (int i = 0; i < onnx_func_proto_->input_size(); ++i) {
input_name_idx_map[onnx_func_proto_->input().Get(i)] = i;
}
for (int i = 0; i < onnx_func_proto_->output_size(); ++i) {
output_name_idx_map[onnx_func_proto_->output().Get(i)] = i;
}
auto cached_op_schema = node_in_parent_graph->Op();
if (!cached_op_schema) {
// Infer a op_schema for stand-alone functions.
IOTypeConstraintHelper(onnx_func_proto_, this->op_schema_, input_name_idx_map, output_name_idx_map);
} else {
auto type_constraint_params = cached_op_schema->typeConstraintParams();
for (auto& type_constraint_param : type_constraint_params) {
op_schema_->TypeConstraint(
type_constraint_param.type_param_str,
type_constraint_param.allowed_type_strs,
type_constraint_param.description);
}
int i = 0;
for (auto& input : cached_op_schema->inputs()) {
op_schema_->Input(i, input.GetName(), input.GetDescription(), input.GetTypeStr());
++i;
}
i = 0;
for (auto& output : cached_op_schema->outputs()) {
op_schema_->Output(i, output.GetName(), output.GetDescription(), output.GetTypeStr());
++i;
}
for (auto& attribute : cached_op_schema->attributes()) {
op_schema_->Attr(attribute.second);
}
}
if (!cached_op_schema || !cached_op_schema->has_type_and_shape_inference_function()) {
op_schema_->TypeAndShapeInferenceFunction(
[this](ONNX_NAMESPACE::InferenceContext& ctx) {
auto schema_registry = ONNX_NAMESPACE::OpSchemaRegistry::Instance();
const ONNX_NAMESPACE::FunctionProto* func_ptr = this->GetFuncProto();
if (nullptr != func_ptr) {
ONNX_NAMESPACE::shape_inference::InferShapeForFunctionNode(func_ptr, schema_registry, ctx);
}
});
} else {
op_schema_->TypeAndShapeInferenceFunction(cached_op_schema->GetTypeAndShapeInferenceFunction());
}
op_schema_->Finalize();
//construct body
std::unordered_map<std::string, int> domain_to_version;
//TODO: set correct domain and version
domain_to_version[onnxruntime::kOnnxDomain] = static_cast<int>(onnx_func_proto_->since_version());
body_ = std::make_unique<onnxruntime::Model>(onnx_func_proto_->name(), false, onnxruntime::ModelMetaData(),
IOnnxRuntimeOpSchemaRegistryList(), domain_to_version);
auto& sub_graph = body_->MainGraph();
// Add node and node args into subgraph
// The subgraph preserved the input/output tensor names
// in the parent graph for later inlining purpose
auto attr_map = node_in_parent_graph->GetAttributes();
for (auto& node : onnx_func_proto_->node()) {
std::vector<onnxruntime::NodeArg*> inputs;
std::vector<onnxruntime::NodeArg*> outputs;
std::string uniq_identifier = node.name();
if (!node.has_name()) {
std::stringstream ss;
ss << static_cast<const void*>(&node);
uniq_identifier = ss.str();
}
for (int idx = 0; idx < node.input_size(); ++idx) {
std::string tensor_name = node.input().Get(idx);
auto iter = input_name_idx_map.find(tensor_name);
if (iter != input_name_idx_map.end()) {
// Preserving NodeArg and input/output names
ONNX_NAMESPACE::NodeProto temp_node_proto;
node_in_parent_graph->ToProto(temp_node_proto);
const onnxruntime::NodeArg* node_arg = parent_graph_->GetNodeArg(temp_node_proto.input().Get(input_name_idx_map[tensor_name]));
auto& n_input = sub_graph.GetOrCreateNodeArg(
temp_node_proto.input().Get(iter->second), node_arg->TypeAsProto());
inputs.push_back(&n_input);
} else {
auto& n_input = sub_graph.GetOrCreateNodeArg(
tensor_name + "_" + std::to_string(node_index), nullptr);
inputs.push_back(&n_input);
}
}
for (int idx = 0; idx < node.output_size(); ++idx) {
std::string tensor_name = node.output().Get(idx);
auto iter = output_name_idx_map.find(tensor_name);
if (iter != output_name_idx_map.end()) {
// Preserving NodeArg and input/output names
ONNX_NAMESPACE::NodeProto temp_node_proto;
node_in_parent_graph->ToProto(temp_node_proto);
const onnxruntime::NodeArg* node_arg = parent_graph_->GetNodeArg(temp_node_proto.output().Get(output_name_idx_map[tensor_name]));
auto& n_output = sub_graph.GetOrCreateNodeArg(
temp_node_proto.output().Get(iter->second), node_arg->TypeAsProto());
outputs.push_back(&n_output);
} else {
auto& n_output = sub_graph.GetOrCreateNodeArg(
tensor_name + "_" + std::to_string(node_index), nullptr);
outputs.push_back(&n_output);
}
}
onnxruntime::NodeAttributes new_attr_map;
for (auto& attr : node.attribute()) {
if (attr.has_ref_attr_name()) {
if (attr_map.count(attr.ref_attr_name())) {
new_attr_map[attr.name()] = attr_map[attr.ref_attr_name()];
}
} else {
new_attr_map[attr.name()] = attr;
}
}
sub_graph.AddNode(uniq_identifier + "_" + std::to_string(node_index), node.op_type(), node.doc_string(), inputs, outputs, &new_attr_map, node.domain());
}
auto status = sub_graph.Resolve();
ORT_ENFORCE(status.IsOK(), "Resolve subgraph failed:", status.ErrorMessage());
}
FunctionImpl::~FunctionImpl() = default;
const ONNX_NAMESPACE::OpSchema& FunctionImpl::OpSchema() const {
return *op_schema_;
}
const onnxruntime::Graph& FunctionImpl::Body() const {
return body_->MainGraph();
}
const IndexedSubGraph& FunctionImpl::GetIndexedSubGraph() const {
return *customized_func_body_;
}
const ONNX_NAMESPACE::FunctionProto* FunctionImpl::GetFuncProto() const {
return onnx_func_proto_;
}
std::unique_ptr<Function> MakeFunction(const onnxruntime::Graph& graph,
std::unique_ptr<IndexedSubGraph> customized_func) {
return std::make_unique<FunctionImpl>(graph, std::move(customized_func));
}
} // namespace onnxruntime
<|endoftext|> |
<commit_before>#include <b9/interpreter.hpp>
#include <b9/jit.hpp>
#include <b9/loader.hpp>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
/// B9run's usage string. Printed when run with -help.
static const char* usage =
"Usage: b9run [<option>...] [--] <module> [<main>]\n"
" Or: b9run -help\n"
"Jit Options:\n"
" -jit: Enable the jit\n"
" -directcall: make direct jit to jit calls\n"
" -passparam: Pass arguments in CPU registers\n"
" -lazyvmstate: Only update the VM state as needed\n"
"Run Options:\n"
" -loop <n>: Run the program <n> times\n"
" -inline <n>: Enable inlining\n"
" -debug: Enable debug code\n"
" -verbose: Run with verbose printing\n"
" -help: Print this help message";
/// The b9run program's global configuration.
struct RunConfig {
b9::Config b9;
const char* moduleName = "";
const char* mainFunction = "b9main";
std::size_t loopCount = 1;
bool verbose = false;
std::vector<b9::StackElement> usrArgs;
};
/// Parse CLI arguments and set up the config.
static bool parseArguments(RunConfig& cfg, const int argc, char* argv[]) {
std::size_t i = 1;
for (; i < argc; i++) {
const char* arg = argv[i];
if (strcmp(arg, "-help") == 0) {
std::cout << usage << std::endl;
exit(EXIT_SUCCESS);
} else if (strcmp(arg, "-loop") == 0) {
cfg.loopCount = atoi(argv[++i]);
} else if (strcmp(arg, "-inline") == 0) {
cfg.b9.maxInlineDepth = atoi(argv[++i]);
} else if (strcmp(arg, "-verbose") == 0) {
cfg.verbose = true;
cfg.b9.verbose = true;
} else if (strcmp(arg, "-debug") == 0) {
cfg.b9.debug = true;
} else if (strcmp(arg, "-function") == 0) {
cfg.mainFunction = argv[++i];
} else if (strcmp(arg, "-jit") == 0) {
cfg.b9.jit = true;
} else if (strcmp(arg, "-directcall") == 0) {
cfg.b9.directCall = true;
} else if (strcmp(arg, "-passparam") == 0) {
cfg.b9.passParam = true;
} else if (strcmp(arg, "-lazyvmstate") == 0) {
cfg.b9.lazyVmState = true;
} else if (strcmp(arg, "--") == 0) {
i++;
break;
} else if (strcmp(arg, "-") == 0) {
std::cerr << "Unrecognized option: " << arg << std::endl;
return false;
} else {
break;
}
}
// check for user defined module
if (i < argc) {
cfg.moduleName = argv[i++];
} else {
std::cerr << "No module name given to b9run" << std::endl;
return false;
}
// check for user defined arguments
for (; i < argc; i++) {
cfg.usrArgs.push_back(std::atoi(argv[i]));
}
return true;
}
static void run(const RunConfig& cfg) {
b9::VirtualMachine vm{cfg.b9};
b9::DlLoader loader{true};
auto module = loader.loadModule(cfg.moduleName);
if (module->functions.size() == 0) {
throw b9::DlException{"Empty module"};
}
vm.load(module);
if (cfg.b9.jit) vm.generateAllCode();
size_t functionIndex = module->findFunction(cfg.mainFunction);
if (cfg.loopCount == 1) {
b9::StackElement returnVal = vm.run(functionIndex, cfg.usrArgs);
std::cout << std::endl
<< cfg.mainFunction << " returned: " << returnVal << std::endl;
} else {
b9::StackElement returnVal;
std::cout << "\nRunning " << cfg.mainFunction << " " << cfg.loopCount
<< " times:" << std::endl;
for (std::size_t i = 1; i <= cfg.loopCount; i++) {
returnVal = vm.run(functionIndex, cfg.usrArgs);
std::cout << "Return value of iteration " << i << ": " << returnVal
<< std::endl;
}
}
}
int main(int argc, char* argv[]) {
RunConfig cfg;
if (!parseArguments(cfg, argc, argv)) {
std::cerr << usage << std::endl;
exit(EXIT_FAILURE);
}
try {
run(cfg);
} catch (const b9::DlException& e) {
std::cerr << "Failed to load module: " << e.what() << std::endl;
exit(EXIT_FAILURE);
} catch (const b9::FunctionNotFoundException& e) {
std::cerr << "Failed to find function: " << e.what() << std::endl;
exit(EXIT_FAILURE);
} catch (const b9::BadFunctionCallException& e) {
std::cerr << "Failed to call function " << e.what() << std::endl;
exit(EXIT_FAILURE);
} catch (const b9::CompilationException& e) {
std::cerr << "Failed to compile function: " << e.what() << std::endl;
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
<commit_msg>Do not check that the module is empty<commit_after>#include <b9/interpreter.hpp>
#include <b9/jit.hpp>
#include <b9/loader.hpp>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
/// B9run's usage string. Printed when run with -help.
static const char* usage =
"Usage: b9run [<option>...] [--] <module> [<main>]\n"
" Or: b9run -help\n"
"Jit Options:\n"
" -jit: Enable the jit\n"
" -directcall: make direct jit to jit calls\n"
" -passparam: Pass arguments in CPU registers\n"
" -lazyvmstate: Only update the VM state as needed\n"
"Run Options:\n"
" -loop <n>: Run the program <n> times\n"
" -inline <n>: Enable inlining\n"
" -debug: Enable debug code\n"
" -verbose: Run with verbose printing\n"
" -help: Print this help message";
/// The b9run program's global configuration.
struct RunConfig {
b9::Config b9;
const char* moduleName = "";
const char* mainFunction = "b9main";
std::size_t loopCount = 1;
bool verbose = false;
std::vector<b9::StackElement> usrArgs;
};
/// Parse CLI arguments and set up the config.
static bool parseArguments(RunConfig& cfg, const int argc, char* argv[]) {
std::size_t i = 1;
for (; i < argc; i++) {
const char* arg = argv[i];
if (strcmp(arg, "-help") == 0) {
std::cout << usage << std::endl;
exit(EXIT_SUCCESS);
} else if (strcmp(arg, "-loop") == 0) {
cfg.loopCount = atoi(argv[++i]);
} else if (strcmp(arg, "-inline") == 0) {
cfg.b9.maxInlineDepth = atoi(argv[++i]);
} else if (strcmp(arg, "-verbose") == 0) {
cfg.verbose = true;
cfg.b9.verbose = true;
} else if (strcmp(arg, "-debug") == 0) {
cfg.b9.debug = true;
} else if (strcmp(arg, "-function") == 0) {
cfg.mainFunction = argv[++i];
} else if (strcmp(arg, "-jit") == 0) {
cfg.b9.jit = true;
} else if (strcmp(arg, "-directcall") == 0) {
cfg.b9.directCall = true;
} else if (strcmp(arg, "-passparam") == 0) {
cfg.b9.passParam = true;
} else if (strcmp(arg, "-lazyvmstate") == 0) {
cfg.b9.lazyVmState = true;
} else if (strcmp(arg, "--") == 0) {
i++;
break;
} else if (strcmp(arg, "-") == 0) {
std::cerr << "Unrecognized option: " << arg << std::endl;
return false;
} else {
break;
}
}
// check for user defined module
if (i < argc) {
cfg.moduleName = argv[i++];
} else {
std::cerr << "No module name given to b9run" << std::endl;
return false;
}
// check for user defined arguments
for (; i < argc; i++) {
cfg.usrArgs.push_back(std::atoi(argv[i]));
}
return true;
}
static void run(const RunConfig& cfg) {
b9::VirtualMachine vm{cfg.b9};
b9::DlLoader loader{true};
auto module = loader.loadModule(cfg.moduleName);
vm.load(module);
if (cfg.b9.jit) vm.generateAllCode();
size_t functionIndex = module->findFunction(cfg.mainFunction);
if (cfg.loopCount == 1) {
b9::StackElement returnVal = vm.run(functionIndex, cfg.usrArgs);
std::cout << std::endl
<< cfg.mainFunction << " returned: " << returnVal << std::endl;
} else {
b9::StackElement returnVal;
std::cout << "\nRunning " << cfg.mainFunction << " " << cfg.loopCount
<< " times:" << std::endl;
for (std::size_t i = 1; i <= cfg.loopCount; i++) {
returnVal = vm.run(functionIndex, cfg.usrArgs);
std::cout << "Return value of iteration " << i << ": " << returnVal
<< std::endl;
}
}
}
int main(int argc, char* argv[]) {
RunConfig cfg;
if (!parseArguments(cfg, argc, argv)) {
std::cerr << usage << std::endl;
exit(EXIT_FAILURE);
}
try {
run(cfg);
} catch (const b9::DlException& e) {
std::cerr << "Failed to load module: " << e.what() << std::endl;
exit(EXIT_FAILURE);
} catch (const b9::FunctionNotFoundException& e) {
std::cerr << "Failed to find function: " << e.what() << std::endl;
exit(EXIT_FAILURE);
} catch (const b9::BadFunctionCallException& e) {
std::cerr << "Failed to call function " << e.what() << std::endl;
exit(EXIT_FAILURE);
} catch (const b9::CompilationException& e) {
std::cerr << "Failed to compile function: " << e.what() << std::endl;
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
<|endoftext|> |
<commit_before>#include "WorldDragWidget.h"
#include <KrisLibrary/GLdraw/drawextra.h>
using namespace GLDraw;
using namespace Klampt;
WorldDragWidget::WorldDragWidget(WorldModel* _world)
:world(_world),active(true),robotsActive(true),objectsActive(true),terrainsActive(false),
highlightColor(1,1,1,0.3),lineColor(1,0.5,0),lineWidth(5.0),dragging(false),hoverID(-1),highlightID(-1)
{}
void WorldDragWidget::Set(WorldModel* _world)
{
world = _world;
}
void WorldDragWidget::Enable(bool _active)
{
active = _active;
}
void WorldDragWidget::SetHighlight(bool value)
{
hasHighlight = value;
if(hasHighlight && hoverID >= 0) {
//update the object's color
originalFaceColor = world->GetAppearance(hoverID)->faceColor;
world->GetAppearance(hoverID)->faceColor.blend(originalFaceColor,highlightColor,highlightColor.rgba[3]);
highlightID = hoverID;
}
else if(!hasHighlight && highlightID >= 0) {
//restore the object's color
world->GetAppearance(highlightID)->faceColor = originalFaceColor;
}
}
bool WorldDragWidget::Hover(int x,int y,Camera::Viewport& viewport,double& distance)
{
if(!active) return false;
Ray3D r;
viewport.getClickSource(x,y,r.source);
viewport.getClickVector(x,y,r.direction);
hoverID = -1;
distance = Inf;
if(robotsActive) {
int body;
Vector3 localpt;
RobotModel* rob = world->RayCastRobot(r,body,localpt);
if(rob) {
hoverPt = localpt;
int index = -1;
for(size_t i=0;i<world->robots.size();i++)
if(rob == world->robots[i].get()) { index=(int)i; break; }
hoverID = world->RobotLinkID(index,body);
auto geom = world->GetGeometry(hoverID);
Vector3 worldpt = geom->GetTransform()*localpt;
distance = worldpt.distance(r.source);
dragPt = worldpt;
}
}
if(objectsActive) {
Vector3 localpt;
RigidObjectModel* obj = world->RayCastObject(r,localpt);
if(obj) {
Vector3 worldpt = obj->T*localpt;
Real d=worldpt.distance(r.source);
if(d < distance) {
distance = d;
hoverPt = localpt;
int index = -1;
for(size_t i=0;i<world->rigidObjects.size();i++)
if(obj == world->rigidObjects[i].get()) { index=(int)i; break; }
hoverID = world->RigidObjectID(index);
dragPt = worldpt;
}
}
}
hoverDistance = distance;
if(hoverID >= 0) {
return true;
}
return false;
}
bool WorldDragWidget::BeginDrag(int x,int y,Camera::Viewport& viewport,double& distance)
{
if(!Hover(x,y,viewport,distance)) return false;
dragging = true;
return true;
}
void WorldDragWidget::Drag(int dx,int dy,Camera::Viewport& viewport)
{
Vector3 v;
viewport.getMovementVectorAtDistance(dx,dy,hoverDistance,v);
dragPt += v;
}
void WorldDragWidget::EndDrag()
{
dragging = false;
}
void WorldDragWidget::DrawGL(Camera::Viewport& viewport)
{
if(hoverID < 0) return;
requestRedraw = false;
if(hasFocus) {
auto geom = world->GetGeometry(hoverID);
glDisable(GL_LIGHTING);
lineColor.setCurrentGL();
glLineWidth(lineWidth);
glBegin(GL_LINES);
glVertex3v(geom->GetTransform()*hoverPt);
glVertex3v(dragPt);
glEnd();
glLineWidth(1);
}
}
<commit_msg>Fixed problem with force application mode turning items transprent<commit_after>#include "WorldDragWidget.h"
#include <KrisLibrary/GLdraw/drawextra.h>
using namespace GLDraw;
using namespace Klampt;
WorldDragWidget::WorldDragWidget(WorldModel* _world)
:world(_world),active(true),robotsActive(true),objectsActive(true),terrainsActive(false),
highlightColor(1,1,1,1.0),lineColor(1,0.5,0),lineWidth(5.0),dragging(false),hoverID(-1),highlightID(-1)
{}
void WorldDragWidget::Set(WorldModel* _world)
{
world = _world;
}
void WorldDragWidget::Enable(bool _active)
{
active = _active;
}
void WorldDragWidget::SetHighlight(bool value)
{
hasHighlight = value;
if(hasHighlight && hoverID >= 0) {
//update the object's color
originalFaceColor = world->GetAppearance(hoverID)->tintColor;
world->GetAppearance(hoverID)->SetTintColor(highlightColor,0.3);
highlightID = hoverID;
}
else if(!hasHighlight && highlightID >= 0) {
//restore the object's color
world->GetAppearance(highlightID)->tintColor = originalFaceColor;
world->GetAppearance(highlightID)->tintStrength = 0.0;
}
}
bool WorldDragWidget::Hover(int x,int y,Camera::Viewport& viewport,double& distance)
{
if(!active) return false;
Ray3D r;
viewport.getClickSource(x,y,r.source);
viewport.getClickVector(x,y,r.direction);
hoverID = -1;
distance = Inf;
if(robotsActive) {
int body;
Vector3 localpt;
RobotModel* rob = world->RayCastRobot(r,body,localpt);
if(rob) {
hoverPt = localpt;
int index = -1;
for(size_t i=0;i<world->robots.size();i++)
if(rob == world->robots[i].get()) { index=(int)i; break; }
hoverID = world->RobotLinkID(index,body);
auto geom = world->GetGeometry(hoverID);
Vector3 worldpt = geom->GetTransform()*localpt;
distance = worldpt.distance(r.source);
dragPt = worldpt;
}
}
if(objectsActive) {
Vector3 localpt;
RigidObjectModel* obj = world->RayCastObject(r,localpt);
if(obj) {
Vector3 worldpt = obj->T*localpt;
Real d=worldpt.distance(r.source);
if(d < distance) {
distance = d;
hoverPt = localpt;
int index = -1;
for(size_t i=0;i<world->rigidObjects.size();i++)
if(obj == world->rigidObjects[i].get()) { index=(int)i; break; }
hoverID = world->RigidObjectID(index);
dragPt = worldpt;
}
}
}
hoverDistance = distance;
if(hoverID >= 0) {
return true;
}
return false;
}
bool WorldDragWidget::BeginDrag(int x,int y,Camera::Viewport& viewport,double& distance)
{
if(!Hover(x,y,viewport,distance)) return false;
dragging = true;
return true;
}
void WorldDragWidget::Drag(int dx,int dy,Camera::Viewport& viewport)
{
Vector3 v;
viewport.getMovementVectorAtDistance(dx,dy,hoverDistance,v);
dragPt += v;
}
void WorldDragWidget::EndDrag()
{
dragging = false;
}
void WorldDragWidget::DrawGL(Camera::Viewport& viewport)
{
if(hoverID < 0) return;
requestRedraw = false;
if(hasFocus) {
auto geom = world->GetGeometry(hoverID);
glDisable(GL_LIGHTING);
lineColor.setCurrentGL();
glLineWidth(lineWidth);
glBegin(GL_LINES);
glVertex3v(geom->GetTransform()*hoverPt);
glVertex3v(dragPt);
glEnd();
glLineWidth(1);
}
}
<|endoftext|> |
<commit_before>/**
* This file is part of the CernVM File System.
*/
#include "gtest/gtest.h"
#include <unistd.h>
#include <cstdio>
#include "../../cvmfs/compression.h"
#include "../../cvmfs/download.h"
#include "../../cvmfs/hash.h"
#include "../../cvmfs/prng.h"
#include "../../cvmfs/sink.h"
#include "../../cvmfs/statistics.h"
#include "../../cvmfs/util.h"
using namespace std; // NOLINT
namespace download {
class T_Download : public ::testing::Test {
protected:
virtual void SetUp() {
download_mgr.Init(8, false, /* use_system_proxy */
&statistics);
ffoo = CreateTempFile("./cvmfs_ut_download", 0600, "w+", &foo_path);
assert(ffoo);
foo_url = "file://" + foo_path;
}
virtual ~T_Download() {
download_mgr.Fini();
fclose(ffoo);
unlink(foo_path.c_str());
}
perf::Statistics statistics;
DownloadManager download_mgr;
FILE *ffoo;
string foo_path;
string foo_url;
};
class TestSink : public cvmfs::Sink {
public:
TestSink() {
FILE *f = CreateTempFile("./cvmfs_ut_download", 0600, "w+", &path);
assert(f);
fd = dup(fileno(f));
assert(f >= 0);
fclose(f);
}
virtual int64_t Write(const void *buf, uint64_t size) {
return write(fd, buf, size);
}
virtual int Reset() {
int retval = ftruncate(fd, 0);
assert(retval == 0);
return 0;
}
~TestSink() {
close(fd);
unlink(path.c_str());
}
int fd;
string path;
};
//------------------------------------------------------------------------------
// A placeholder test for future unit testing of the download module
TEST_F(T_Download, File) {
string dest_path;
FILE *fdest = CreateTempFile("./cvmfs_ut_download", 0600, "w+", &dest_path);
ASSERT_TRUE(fdest != NULL);
UnlinkGuard unlink_guard(dest_path);
JobInfo info(&foo_url, false /* compressed */, false /* probe hosts */,
fdest, NULL);
download_mgr.Fetch(&info);
EXPECT_EQ(info.error_code, kFailOk);
fclose(fdest);
}
TEST_F(T_Download, LocalFile2Mem) {
string dest_path;
FILE *fdest = CreateTempFile("./cvmfs_ut_download", 0600, "w+", &dest_path);
ASSERT_TRUE(fdest != NULL);
UnlinkGuard unlink_guard(dest_path);
char buf = '1';
fwrite(&buf, 1, 1, fdest);
fclose(fdest);
string url = "file://" + dest_path;
JobInfo info(&url, false /* compressed */, false /* probe hosts */, NULL);
download_mgr.Fetch(&info);
ASSERT_EQ(info.error_code, kFailOk);
ASSERT_EQ(info.destination_mem.size, 1U);
EXPECT_EQ(info.destination_mem.data[0], '1');
}
TEST_F(T_Download, LocalFile2Sink) {
string dest_path;
FILE *fdest = CreateTempFile("./cvmfs_ut_download", 0600, "w+", &dest_path);
ASSERT_TRUE(fdest != NULL);
UnlinkGuard unlink_guard(dest_path);
char buf = '1';
fwrite(&buf, 1, 1, fdest);
fflush(fdest);
TestSink test_sink;
string url = "file://" + dest_path;
JobInfo info(&url, false /* compressed */, false /* probe hosts */,
&test_sink, NULL /* expected hash */);
download_mgr.Fetch(&info);
EXPECT_EQ(info.error_code, kFailOk);
EXPECT_EQ(1, pread(test_sink.fd, &buf, 1, 0));
EXPECT_EQ('1', buf);
rewind(fdest);
Prng prng;
prng.InitLocaltime();
unsigned N = 16*1024;
unsigned size = N*sizeof(uint32_t);
uint32_t rnd_buf[N]; // 64kB
for (unsigned i = 0; i < N; ++i)
rnd_buf[i] = prng.Next(2147483647);
shash::Any checksum(shash::kMd5);
EXPECT_TRUE(
zlib::CompressMem2File(reinterpret_cast<const unsigned char *>(rnd_buf),
size, fdest, &checksum));
fclose(fdest);
TestSink test_sink2;
JobInfo info2(&url, true /* compressed */, false /* probe hosts */,
&test_sink2, &checksum /* expected hash */);
download_mgr.Fetch(&info2);
EXPECT_EQ(info2.error_code, kFailOk);
EXPECT_EQ(size, GetFileSize(test_sink2.path));
uint32_t validation[N];
EXPECT_EQ(static_cast<int>(size),
pread(test_sink2.fd, &validation, size, 0));
EXPECT_EQ(0, memcmp(validation, rnd_buf, size));
}
TEST_F(T_Download, StripDirect) {
string cleaned = "FALSE";
EXPECT_FALSE(download_mgr.StripDirect("", &cleaned));
EXPECT_EQ("", cleaned);
EXPECT_TRUE(download_mgr.StripDirect("DIRECT", &cleaned));
EXPECT_EQ("", cleaned);
EXPECT_TRUE(download_mgr.StripDirect("DIRECT;DIRECT", &cleaned));
EXPECT_EQ("", cleaned);
EXPECT_TRUE(download_mgr.StripDirect("DIRECT;DIRECT|DIRECT", &cleaned));
EXPECT_EQ("", cleaned);
EXPECT_TRUE(download_mgr.StripDirect("DIRECT;DIRECT|", &cleaned));
EXPECT_EQ("", cleaned);
EXPECT_TRUE(download_mgr.StripDirect(";", &cleaned));
EXPECT_EQ("", cleaned);
EXPECT_TRUE(download_mgr.StripDirect(";||;;;|||", &cleaned));
EXPECT_EQ("", cleaned);
EXPECT_FALSE(download_mgr.StripDirect("A|B", &cleaned));
EXPECT_EQ("A|B", cleaned);
EXPECT_FALSE(download_mgr.StripDirect("A|B;C|D;E|F|G", &cleaned));
EXPECT_EQ("A|B;C|D;E|F|G", cleaned);
EXPECT_TRUE(download_mgr.StripDirect("A|DIRECT;C|D;E|F;DIRECT", &cleaned));
EXPECT_EQ("A;C|D;E|F", cleaned);
}
TEST_F(T_Download, ValidateGeoReply) {
vector<uint64_t> geo_order;
EXPECT_FALSE(download_mgr.ValidateGeoReply("", geo_order.size(), &geo_order));
geo_order.push_back(0);
EXPECT_FALSE(
download_mgr.ValidateGeoReply("a", geo_order.size(), &geo_order));
EXPECT_FALSE(
download_mgr.ValidateGeoReply("1,1", geo_order.size(), &geo_order));
EXPECT_FALSE(
download_mgr.ValidateGeoReply("1,3", geo_order.size(), &geo_order));
EXPECT_FALSE(
download_mgr.ValidateGeoReply("2,3", geo_order.size(), &geo_order));
EXPECT_FALSE(
download_mgr.ValidateGeoReply("2", geo_order.size(), &geo_order));
EXPECT_TRUE(
download_mgr.ValidateGeoReply("1", geo_order.size(), &geo_order));
EXPECT_EQ(geo_order.size(), 1U);
EXPECT_EQ(geo_order[0], 0U);
geo_order.push_back(0);
EXPECT_FALSE(
download_mgr.ValidateGeoReply(",", geo_order.size(), &geo_order));
EXPECT_FALSE(
download_mgr.ValidateGeoReply("2,", geo_order.size(), &geo_order));
EXPECT_FALSE(
download_mgr.ValidateGeoReply("1", geo_order.size(), &geo_order));
EXPECT_FALSE(
download_mgr.ValidateGeoReply("3,2,1", geo_order.size(), &geo_order));
EXPECT_TRUE(
download_mgr.ValidateGeoReply("2,1", geo_order.size(), &geo_order));
EXPECT_EQ(geo_order.size(), 2U);
EXPECT_EQ(geo_order[0], 1U);
EXPECT_EQ(geo_order[1], 0U);
EXPECT_TRUE(
download_mgr.ValidateGeoReply("2,1\n", geo_order.size(), &geo_order));
EXPECT_EQ(geo_order.size(), 2U);
EXPECT_EQ(geo_order[0], 1U);
EXPECT_EQ(geo_order[1], 0U);
geo_order.push_back(0);
geo_order.push_back(0);
EXPECT_TRUE(
download_mgr.ValidateGeoReply("4,3,1,2\n", geo_order.size(), &geo_order));
EXPECT_EQ(geo_order.size(), 4U);
EXPECT_EQ(geo_order[0], 3U);
EXPECT_EQ(geo_order[1], 2U);
EXPECT_EQ(geo_order[2], 0U);
EXPECT_EQ(geo_order[3], 1U);
}
} // namespace download
<commit_msg>FIX: T_Download depends on absolute paths<commit_after>/**
* This file is part of the CernVM File System.
*/
#include "gtest/gtest.h"
#include <unistd.h>
#include <cstdio>
#include "../../cvmfs/compression.h"
#include "../../cvmfs/download.h"
#include "../../cvmfs/hash.h"
#include "../../cvmfs/prng.h"
#include "../../cvmfs/sink.h"
#include "../../cvmfs/statistics.h"
#include "../../cvmfs/util.h"
using namespace std; // NOLINT
namespace download {
class T_Download : public ::testing::Test {
protected:
virtual void SetUp() {
download_mgr.Init(8, false, /* use_system_proxy */
&statistics);
ffoo = CreateTemporaryFile(&foo_path);
assert(ffoo);
foo_url = "file://" + foo_path;
}
virtual ~T_Download() {
download_mgr.Fini();
fclose(ffoo);
unlink(foo_path.c_str());
}
FILE *CreateTemporaryFile(std::string *path) const {
return CreateTempFile(GetCurrentWorkingDirectory() + "/cvmfs_ut_download",
0600, "w+", path);
}
perf::Statistics statistics;
DownloadManager download_mgr;
FILE *ffoo;
string foo_path;
string foo_url;
};
class TestSink : public cvmfs::Sink {
public:
TestSink() {
FILE *f = CreateTempFile("./cvmfs_ut_download", 0600, "w+", &path);
assert(f);
fd = dup(fileno(f));
assert(f >= 0);
fclose(f);
}
virtual int64_t Write(const void *buf, uint64_t size) {
return write(fd, buf, size);
}
virtual int Reset() {
int retval = ftruncate(fd, 0);
assert(retval == 0);
return 0;
}
~TestSink() {
close(fd);
unlink(path.c_str());
}
int fd;
string path;
};
//------------------------------------------------------------------------------
// A placeholder test for future unit testing of the download module
TEST_F(T_Download, File) {
string dest_path;
FILE *fdest = CreateTemporaryFile(&dest_path);
ASSERT_TRUE(fdest != NULL);
UnlinkGuard unlink_guard(dest_path);
JobInfo info(&foo_url, false /* compressed */, false /* probe hosts */,
fdest, NULL);
download_mgr.Fetch(&info);
EXPECT_EQ(info.error_code, kFailOk);
fclose(fdest);
}
TEST_F(T_Download, LocalFile2Mem) {
string dest_path;
FILE *fdest = CreateTemporaryFile(&dest_path);
ASSERT_TRUE(fdest != NULL);
UnlinkGuard unlink_guard(dest_path);
char buf = '1';
fwrite(&buf, 1, 1, fdest);
fclose(fdest);
string url = "file://" + dest_path;
JobInfo info(&url, false /* compressed */, false /* probe hosts */, NULL);
download_mgr.Fetch(&info);
ASSERT_EQ(info.error_code, kFailOk);
ASSERT_EQ(info.destination_mem.size, 1U);
EXPECT_EQ(info.destination_mem.data[0], '1');
}
TEST_F(T_Download, LocalFile2Sink) {
string dest_path;
FILE *fdest = CreateTemporaryFile(&dest_path);
ASSERT_TRUE(fdest != NULL);
UnlinkGuard unlink_guard(dest_path);
char buf = '1';
fwrite(&buf, 1, 1, fdest);
fflush(fdest);
TestSink test_sink;
string url = "file://" + dest_path;
JobInfo info(&url, false /* compressed */, false /* probe hosts */,
&test_sink, NULL /* expected hash */);
download_mgr.Fetch(&info);
EXPECT_EQ(info.error_code, kFailOk);
EXPECT_EQ(1, pread(test_sink.fd, &buf, 1, 0));
EXPECT_EQ('1', buf);
rewind(fdest);
Prng prng;
prng.InitLocaltime();
unsigned N = 16*1024;
unsigned size = N*sizeof(uint32_t);
uint32_t rnd_buf[N]; // 64kB
for (unsigned i = 0; i < N; ++i)
rnd_buf[i] = prng.Next(2147483647);
shash::Any checksum(shash::kMd5);
EXPECT_TRUE(
zlib::CompressMem2File(reinterpret_cast<const unsigned char *>(rnd_buf),
size, fdest, &checksum));
fclose(fdest);
TestSink test_sink2;
JobInfo info2(&url, true /* compressed */, false /* probe hosts */,
&test_sink2, &checksum /* expected hash */);
download_mgr.Fetch(&info2);
EXPECT_EQ(info2.error_code, kFailOk);
EXPECT_EQ(size, GetFileSize(test_sink2.path));
uint32_t validation[N];
EXPECT_EQ(static_cast<int>(size),
pread(test_sink2.fd, &validation, size, 0));
EXPECT_EQ(0, memcmp(validation, rnd_buf, size));
}
TEST_F(T_Download, StripDirect) {
string cleaned = "FALSE";
EXPECT_FALSE(download_mgr.StripDirect("", &cleaned));
EXPECT_EQ("", cleaned);
EXPECT_TRUE(download_mgr.StripDirect("DIRECT", &cleaned));
EXPECT_EQ("", cleaned);
EXPECT_TRUE(download_mgr.StripDirect("DIRECT;DIRECT", &cleaned));
EXPECT_EQ("", cleaned);
EXPECT_TRUE(download_mgr.StripDirect("DIRECT;DIRECT|DIRECT", &cleaned));
EXPECT_EQ("", cleaned);
EXPECT_TRUE(download_mgr.StripDirect("DIRECT;DIRECT|", &cleaned));
EXPECT_EQ("", cleaned);
EXPECT_TRUE(download_mgr.StripDirect(";", &cleaned));
EXPECT_EQ("", cleaned);
EXPECT_TRUE(download_mgr.StripDirect(";||;;;|||", &cleaned));
EXPECT_EQ("", cleaned);
EXPECT_FALSE(download_mgr.StripDirect("A|B", &cleaned));
EXPECT_EQ("A|B", cleaned);
EXPECT_FALSE(download_mgr.StripDirect("A|B;C|D;E|F|G", &cleaned));
EXPECT_EQ("A|B;C|D;E|F|G", cleaned);
EXPECT_TRUE(download_mgr.StripDirect("A|DIRECT;C|D;E|F;DIRECT", &cleaned));
EXPECT_EQ("A;C|D;E|F", cleaned);
}
TEST_F(T_Download, ValidateGeoReply) {
vector<uint64_t> geo_order;
EXPECT_FALSE(download_mgr.ValidateGeoReply("", geo_order.size(), &geo_order));
geo_order.push_back(0);
EXPECT_FALSE(
download_mgr.ValidateGeoReply("a", geo_order.size(), &geo_order));
EXPECT_FALSE(
download_mgr.ValidateGeoReply("1,1", geo_order.size(), &geo_order));
EXPECT_FALSE(
download_mgr.ValidateGeoReply("1,3", geo_order.size(), &geo_order));
EXPECT_FALSE(
download_mgr.ValidateGeoReply("2,3", geo_order.size(), &geo_order));
EXPECT_FALSE(
download_mgr.ValidateGeoReply("2", geo_order.size(), &geo_order));
EXPECT_TRUE(
download_mgr.ValidateGeoReply("1", geo_order.size(), &geo_order));
EXPECT_EQ(geo_order.size(), 1U);
EXPECT_EQ(geo_order[0], 0U);
geo_order.push_back(0);
EXPECT_FALSE(
download_mgr.ValidateGeoReply(",", geo_order.size(), &geo_order));
EXPECT_FALSE(
download_mgr.ValidateGeoReply("2,", geo_order.size(), &geo_order));
EXPECT_FALSE(
download_mgr.ValidateGeoReply("1", geo_order.size(), &geo_order));
EXPECT_FALSE(
download_mgr.ValidateGeoReply("3,2,1", geo_order.size(), &geo_order));
EXPECT_TRUE(
download_mgr.ValidateGeoReply("2,1", geo_order.size(), &geo_order));
EXPECT_EQ(geo_order.size(), 2U);
EXPECT_EQ(geo_order[0], 1U);
EXPECT_EQ(geo_order[1], 0U);
EXPECT_TRUE(
download_mgr.ValidateGeoReply("2,1\n", geo_order.size(), &geo_order));
EXPECT_EQ(geo_order.size(), 2U);
EXPECT_EQ(geo_order[0], 1U);
EXPECT_EQ(geo_order[1], 0U);
geo_order.push_back(0);
geo_order.push_back(0);
EXPECT_TRUE(
download_mgr.ValidateGeoReply("4,3,1,2\n", geo_order.size(), &geo_order));
EXPECT_EQ(geo_order.size(), 4U);
EXPECT_EQ(geo_order[0], 3U);
EXPECT_EQ(geo_order[1], 2U);
EXPECT_EQ(geo_order[2], 0U);
EXPECT_EQ(geo_order[3], 1U);
}
} // namespace download
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/common/include/p9_mc_scom_addresses_fld_fixes.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mc_scom_addresses_fld_fixes.H
/// @brief The *scom_addresses_fld.H files are generated form figtree,
/// but the figree can be wrong. This file is included in
/// *_scom_addresses_fld.H and allows incorrect constants to be
/// fixed manually.
///
// *HWP HWP Owner: Ben Gass <[email protected]>
// *HWP FW Owner: ? <?>
// *HWP Team: SAO
// *HWP Level: 1
// *HWP Consumed by: FSP:HB:HS:OCC:SBE:CME:SGPE:PGPE:FPPE:IPPE
#ifndef __P9_MC_SCOM_ADDRESSES_FLD_FIXES_H
#define __P9_MC_SCOM_ADDRESSES_FLD_FIXES_H
//Example
//Copy the whole line from the *scom_addresses_fld.H file. Then add FIX in front of REG
//and add another paramter that is the new value you want.
//
//FIXREG64_FLD( PU_ALTD_CMD_REG_FBC_WITH_TM_QUIESCE, 24, SH_UNT, SH_ACS_SCOM, SH_FLD_FBC_WITH_TM_QUIESCE,
// 12);
static const uint64_t SH_FLD_COMMAND_LIST_TIMEOUT_SPEC = 99990000;
static const uint64_t SH_FLD_CFG_PAUSE_ON_MCE = 99990001;
REG64_FLD( MCA_DDRPHY_DP16_SYSCLK_PR0_P0_0_01_ENABLE , 48 , SH_UNT_MCA , SH_ACS_SCOM_RW ,
0 );
REG64_FLD( MCA_DDRPHY_WC_RTT_WL_SWAP_ENABLE_P0 , 48 , SH_UNT_MCA , SH_ACS_SCOM_RW ,
0 );
REG64_FLD( MCA_DDRPHY_WC_RTT_WR_CTL_SWAP_ENABLE_P0 , 49 , SH_UNT_MCA , SH_ACS_SCOM_RW ,
0 );
REG64_FLD( MCBIST_MCBCFGQ_CFG_MCBIST_CFG_FORCE_PAUSE_AFTER_RANK , 34 , SH_UNT_MCA , SH_ACS_SCOM_RW ,
0 );
REG64_FLD( MCBIST_MBSTRQ_CFG_PAUSE_ON_MCE , 33 , SH_UNT_MCBIST , SH_ACS_SCOM_RW ,
SH_FLD_CFG_PAUSE_ON_MCE );
#endif
<commit_msg>p9_mss_setup_bars -- customize interleave granularity<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/common/include/p9_mc_scom_addresses_fld_fixes.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mc_scom_addresses_fld_fixes.H
/// @brief The *scom_addresses_fld.H files are generated form figtree,
/// but the figree can be wrong. This file is included in
/// *_scom_addresses_fld.H and allows incorrect constants to be
/// fixed manually.
///
// *HWP HWP Owner: Ben Gass <[email protected]>
// *HWP FW Owner: ? <?>
// *HWP Team: SAO
// *HWP Level: 1
// *HWP Consumed by: FSP:HB:HS:OCC:SBE:CME:SGPE:PGPE:FPPE:IPPE
#ifndef __P9_MC_SCOM_ADDRESSES_FLD_FIXES_H
#define __P9_MC_SCOM_ADDRESSES_FLD_FIXES_H
//Example
//Copy the whole line from the *scom_addresses_fld.H file. Then add FIX in front of REG
//and add another paramter that is the new value you want.
//
//FIXREG64_FLD( PU_ALTD_CMD_REG_FBC_WITH_TM_QUIESCE, 24, SH_UNT, SH_ACS_SCOM, SH_FLD_FBC_WITH_TM_QUIESCE,
// 12);
static const uint64_t SH_FLD_COMMAND_LIST_TIMEOUT_SPEC = 99990000;
static const uint64_t SH_FLD_CFG_PAUSE_ON_MCE = 99990001;
REG64_FLD( MCA_DDRPHY_DP16_SYSCLK_PR0_P0_0_01_ENABLE , 48 , SH_UNT_MCA , SH_ACS_SCOM_RW ,
0 );
REG64_FLD( MCA_DDRPHY_WC_RTT_WL_SWAP_ENABLE_P0 , 48 , SH_UNT_MCA , SH_ACS_SCOM_RW ,
0 );
REG64_FLD( MCA_DDRPHY_WC_RTT_WR_CTL_SWAP_ENABLE_P0 , 49 , SH_UNT_MCA , SH_ACS_SCOM_RW ,
0 );
REG64_FLD( MCBIST_MCBCFGQ_CFG_MCBIST_CFG_FORCE_PAUSE_AFTER_RANK , 34 , SH_UNT_MCA , SH_ACS_SCOM_RW ,
0 );
REG64_FLD( MCBIST_MBSTRQ_CFG_PAUSE_ON_MCE , 33 , SH_UNT_MCBIST , SH_ACS_SCOM_RW ,
SH_FLD_CFG_PAUSE_ON_MCE );
REG64_FLD( MCS_MCMODE0_GROUP_INTERLEAVE_GRANULARITY , 52 , SH_UNT_MCS , SH_ACS_SCOM_RW ,
0 );
REG64_FLD( MCS_MCMODE0_GROUP_INTERLEAVE_GRANULARITY_LEN , 4 , SH_UNT_MCS , SH_ACS_SCOM_RW ,
0 );
#endif
<|endoftext|> |
<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "core/graph/function_impl.h"
#include "core/graph/graph_viewer.h"
#include "core/graph/model.h"
#include "onnx/shape_inference/implementation.h"
namespace onnxruntime {
void TypeConstraintHelper(const ONNX_NAMESPACE::FunctionProto* onnx_func_proto_,
std::unique_ptr<ONNX_NAMESPACE::OpSchema>& op_schema_,
/*out*/
std::unordered_map<std::string, int>& input_name_idx_map,
std::unordered_map<std::string, int>& output_name_idx_map) {
std::vector<std::pair<std::string, std::string>> input_types_list(onnx_func_proto_->input_size());
std::vector<std::pair<std::string, std::string>> output_types_list(onnx_func_proto_->output_size());
std::unordered_map<std::string, std::vector<std::string>> type_constraint_map;
for (int i = 0; i < onnx_func_proto_->input_size(); ++i) {
input_name_idx_map[onnx_func_proto_->input().Get(i)] = i;
}
for (int i = 0; i < onnx_func_proto_->output_size(); ++i) {
output_name_idx_map[onnx_func_proto_->output().Get(i)] = i;
}
auto schema_registry = ONNX_NAMESPACE::OpSchemaRegistry::Instance();
for (auto& node : onnx_func_proto_->node()) {
const auto node_op_schema = schema_registry->GetSchema(node.op_type(), (int)onnx_func_proto_->since_version(), node.domain());
for (int i = 0; i < node.input_size(); ++i) {
auto& in_name = node.input().Get(i);
auto iter = input_name_idx_map.find(in_name);
if (iter != input_name_idx_map.end()) {
int idx = iter->second;
const auto& p = node_op_schema->inputs().at(i);
std::string type_str = p.GetTypeStr() + "in" + std::to_string(i);
input_types_list[idx] = std::make_pair(in_name, type_str);
if (!type_constraint_map.count(type_str)) {
for (auto s : p.GetTypes()) {
type_constraint_map[type_str].emplace_back(*s);
}
}
}
}
for (int i = 0; i < node.output_size(); ++i) {
auto& out_name = node.output().Get(i);
auto iter = output_name_idx_map.find(out_name);
if (iter != output_name_idx_map.end()) {
int idx = iter->second;
const auto& p = node_op_schema->outputs().at(i);
std::string type_str = p.GetTypeStr() + "out" + std::to_string(i);
output_types_list[idx] = std::make_pair(out_name, type_str);
if (!type_constraint_map.count(type_str)) {
for (auto s : p.GetTypes()) {
type_constraint_map[type_str].emplace_back(*s);
}
}
}
}
}
int i = 0;
for (auto& input : input_types_list) {
op_schema_->Input(i, input.first, "", input.second);
++i;
}
i = 0;
for (auto& output : output_types_list) {
op_schema_->Output(i, output.first, "", output.second);
++i;
}
for (auto& tc : type_constraint_map) {
op_schema_->TypeConstraint(tc.first, tc.second, "");
}
}
FunctionImpl::FunctionImpl(const onnxruntime::Graph& graph,
std::unique_ptr<IndexedSubGraph> customized_func)
: parent_graph_(&graph), onnx_func_proto_{nullptr} {
customized_func_body_ = std::move(customized_func);
auto meta_def = customized_func_body_->GetMetaDef();
op_schema_ = std::make_unique<ONNX_NAMESPACE::OpSchema>();
op_schema_->SetName(meta_def->name);
op_schema_->SetDomain(meta_def->domain);
op_schema_->SetDoc(meta_def->doc_string);
op_schema_->SinceVersion(meta_def->since_version);
int i = 0;
for (auto& input : meta_def->inputs) {
auto input_type = parent_graph_->GetNodeArg(input)->Type();
op_schema_->Input(i, input, "", *input_type);
++i;
}
i = 0;
for (auto& output : meta_def->outputs) {
auto output_type = parent_graph_->GetNodeArg(output)->Type();
op_schema_->Output(i, output, "", *output_type);
++i;
}
op_schema_->Finalize();
//construct body
body_ = std::make_unique<onnxruntime::Model>("fused_function_subgraph", false, onnxruntime::ModelMetaData(),
IOnnxRuntimeOpSchemaRegistryList({graph.GetSchemaRegistry()}),
graph.DomainToVersionMap());
auto& sub_graph = body_->MainGraph();
//Add node and node args
//TODO: for better performance, we could try to transfer the nodes in parent graph to sub-graph directly,
//instead of create new nodes.
for (auto& node_index : customized_func_body_->nodes) {
auto node = parent_graph_->GetNode(node_index);
std::vector<onnxruntime::NodeArg*> inputs, outputs;
for (auto input : node->InputDefs()) {
auto& n_input = sub_graph.GetOrCreateNodeArg(input->Name(), input->TypeAsProto());
inputs.push_back(&n_input);
}
for (auto output : node->OutputDefs()) {
auto& n_output = sub_graph.GetOrCreateNodeArg(output->Name(), output->TypeAsProto());
outputs.push_back(&n_output);
}
sub_graph.AddNode(node->Name(), node->OpType(), node->Description(), inputs, outputs, &node->GetAttributes(), node->Domain());
}
//TODO: if we reuse the nodes in parent graph, maybe we don't need to resolve it.
ORT_ENFORCE(sub_graph.Resolve().IsOK());
}
FunctionImpl::FunctionImpl(const onnxruntime::Graph& graph,
const onnxruntime::NodeIndex& node_index,
const ONNX_NAMESPACE::FunctionProto* onnx_func_proto)
: parent_graph_(&graph) {
onnx_func_proto_ = onnx_func_proto;
auto node_in_parent_graph = parent_graph_->GetNode(node_index);
op_schema_ = std::make_unique<onnx::OpSchema>();
op_schema_->SetName(onnx_func_proto_->name());
op_schema_->SetDomain(onnx_func_proto_->node().Get(0).domain());
op_schema_->SetDoc(onnx_func_proto_->doc_string());
op_schema_->SinceVersion((ONNX_NAMESPACE::OperatorSetVersion)onnx_func_proto_->since_version());
std::unordered_map<std::string, int> input_name_idx_map;
std::unordered_map<std::string, int> output_name_idx_map;
TypeConstraintHelper(onnx_func_proto_, this->op_schema_, input_name_idx_map, output_name_idx_map);
op_schema_->TypeAndShapeInferenceFunction(
[this](ONNX_NAMESPACE::InferenceContext& ctx) {
auto schema_registry = ONNX_NAMESPACE::OpSchemaRegistry::Instance();
const ONNX_NAMESPACE::FunctionProto* func_ptr = this->GetFuncProto();
if (nullptr != func_ptr) {
ONNX_NAMESPACE::shape_inference::InferShapeForFunctionNode(*func_ptr, schema_registry, ctx);
}
});
op_schema_->Finalize();
//construct body
std::unordered_map<std::string, int> domain_to_version;
//TODO: set correct domain and version
domain_to_version[onnxruntime::kOnnxDomain] = (int)onnx_func_proto_->since_version();
body_ = std::make_unique<onnxruntime::Model>(onnx_func_proto_->name(), false, onnxruntime::ModelMetaData(),
IOnnxRuntimeOpSchemaRegistryList(), domain_to_version);
auto& sub_graph = body_->MainGraph();
// Add node and node args into subgraph
// The subgraph preserved the input/output tensor names
// in the parent graph for later inlining purpose
auto attr_map = node_in_parent_graph->GetAttributes();
for (auto& node : onnx_func_proto_->node()) {
std::vector<onnxruntime::NodeArg*> inputs, outputs;
for (int idx = 0; idx < node.input_size(); ++idx) {
std::string tensor_name = node.input().Get(idx);
auto iter = input_name_idx_map.find(tensor_name);
if (iter != input_name_idx_map.end()) {
// Preserving NodeArg and input/output names
ONNX_NAMESPACE::NodeProto temp_node_proto;
node_in_parent_graph->ToProto(temp_node_proto);
const onnxruntime::NodeArg* node_arg = parent_graph_->GetNodeArg(temp_node_proto.input().Get(input_name_idx_map[tensor_name]));
auto& n_input = sub_graph.GetOrCreateNodeArg(
temp_node_proto.input().Get(iter->second), node_arg->TypeAsProto());
inputs.push_back(&n_input);
} else {
auto& n_input = sub_graph.GetOrCreateNodeArg(
tensor_name + "_" + std::to_string(node_index), nullptr);
inputs.push_back(&n_input);
}
}
for (int idx = 0; idx < node.output_size(); ++idx) {
std::string tensor_name = node.output().Get(idx);
auto iter = output_name_idx_map.find(tensor_name);
if (iter != output_name_idx_map.end()) {
// Preserving NodeArg and input/output names
ONNX_NAMESPACE::NodeProto temp_node_proto;
node_in_parent_graph->ToProto(temp_node_proto);
const onnxruntime::NodeArg* node_arg = parent_graph_->GetNodeArg(temp_node_proto.output().Get(output_name_idx_map[tensor_name]));
auto& n_output = sub_graph.GetOrCreateNodeArg(
temp_node_proto.output().Get(iter->second), node_arg->TypeAsProto());
outputs.push_back(&n_output);
} else {
auto& n_output = sub_graph.GetOrCreateNodeArg(
tensor_name + "_" + std::to_string(node_index), nullptr);
outputs.push_back(&n_output);
}
}
onnxruntime::NodeAttributes new_attr_map;
for (auto& attr : node.attribute()) {
if (attr.has_ref_attr_name()) {
if (attr_map.count(attr.ref_attr_name())) {
new_attr_map[attr.name()] = attr_map[attr.ref_attr_name()];
}
} else {
new_attr_map[attr.name()] = attr;
}
}
sub_graph.AddNode(node.name() + "_" + std::to_string(node_index), node.op_type(), node.doc_string(), inputs, outputs, &new_attr_map, node.domain());
}
auto status = sub_graph.Resolve();
ORT_ENFORCE(status.IsOK());
}
FunctionImpl::~FunctionImpl() = default;
const ONNX_NAMESPACE::OpSchema& FunctionImpl::OpSchema() const {
return *op_schema_;
}
const onnxruntime::Graph& FunctionImpl::Body() const {
return body_->MainGraph();
}
const IndexedSubGraph& FunctionImpl::GetIndexedSubGraph() const {
return *customized_func_body_;
}
const ONNX_NAMESPACE::FunctionProto* FunctionImpl::GetFuncProto() const {
return onnx_func_proto_;
}
std::unique_ptr<Function> MakeFunction(const onnxruntime::Graph& graph,
std::unique_ptr<IndexedSubGraph> customized_func) {
return std::make_unique<FunctionImpl>(graph, std::move(customized_func));
}
} // namespace onnxruntime
<commit_msg>add initializer for sub-graph. (#269)<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "core/graph/function_impl.h"
#include "core/graph/graph_viewer.h"
#include "core/graph/model.h"
#include "onnx/shape_inference/implementation.h"
namespace onnxruntime {
void TypeConstraintHelper(const ONNX_NAMESPACE::FunctionProto* onnx_func_proto_,
std::unique_ptr<ONNX_NAMESPACE::OpSchema>& op_schema_,
/*out*/
std::unordered_map<std::string, int>& input_name_idx_map,
std::unordered_map<std::string, int>& output_name_idx_map) {
std::vector<std::pair<std::string, std::string>> input_types_list(onnx_func_proto_->input_size());
std::vector<std::pair<std::string, std::string>> output_types_list(onnx_func_proto_->output_size());
std::unordered_map<std::string, std::vector<std::string>> type_constraint_map;
for (int i = 0; i < onnx_func_proto_->input_size(); ++i) {
input_name_idx_map[onnx_func_proto_->input().Get(i)] = i;
}
for (int i = 0; i < onnx_func_proto_->output_size(); ++i) {
output_name_idx_map[onnx_func_proto_->output().Get(i)] = i;
}
auto schema_registry = ONNX_NAMESPACE::OpSchemaRegistry::Instance();
for (auto& node : onnx_func_proto_->node()) {
const auto node_op_schema = schema_registry->GetSchema(node.op_type(), (int)onnx_func_proto_->since_version(), node.domain());
for (int i = 0; i < node.input_size(); ++i) {
auto& in_name = node.input().Get(i);
auto iter = input_name_idx_map.find(in_name);
if (iter != input_name_idx_map.end()) {
int idx = iter->second;
const auto& p = node_op_schema->inputs().at(i);
std::string type_str = p.GetTypeStr() + "in" + std::to_string(i);
input_types_list[idx] = std::make_pair(in_name, type_str);
if (!type_constraint_map.count(type_str)) {
for (auto s : p.GetTypes()) {
type_constraint_map[type_str].emplace_back(*s);
}
}
}
}
for (int i = 0; i < node.output_size(); ++i) {
auto& out_name = node.output().Get(i);
auto iter = output_name_idx_map.find(out_name);
if (iter != output_name_idx_map.end()) {
int idx = iter->second;
const auto& p = node_op_schema->outputs().at(i);
std::string type_str = p.GetTypeStr() + "out" + std::to_string(i);
output_types_list[idx] = std::make_pair(out_name, type_str);
if (!type_constraint_map.count(type_str)) {
for (auto s : p.GetTypes()) {
type_constraint_map[type_str].emplace_back(*s);
}
}
}
}
}
int i = 0;
for (auto& input : input_types_list) {
op_schema_->Input(i, input.first, "", input.second);
++i;
}
i = 0;
for (auto& output : output_types_list) {
op_schema_->Output(i, output.first, "", output.second);
++i;
}
for (auto& tc : type_constraint_map) {
op_schema_->TypeConstraint(tc.first, tc.second, "");
}
}
FunctionImpl::FunctionImpl(const onnxruntime::Graph& graph,
std::unique_ptr<IndexedSubGraph> customized_func)
: parent_graph_(&graph), onnx_func_proto_{nullptr} {
customized_func_body_ = std::move(customized_func);
auto meta_def = customized_func_body_->GetMetaDef();
op_schema_ = std::make_unique<ONNX_NAMESPACE::OpSchema>();
op_schema_->SetName(meta_def->name);
op_schema_->SetDomain(meta_def->domain);
op_schema_->SetDoc(meta_def->doc_string);
op_schema_->SinceVersion(meta_def->since_version);
int i = 0;
for (auto& input : meta_def->inputs) {
auto input_type = parent_graph_->GetNodeArg(input)->Type();
op_schema_->Input(i, input, "", *input_type);
++i;
}
i = 0;
for (auto& output : meta_def->outputs) {
auto output_type = parent_graph_->GetNodeArg(output)->Type();
op_schema_->Output(i, output, "", *output_type);
++i;
}
op_schema_->Finalize();
//construct body
body_ = std::make_unique<onnxruntime::Model>("fused_function_subgraph", false, onnxruntime::ModelMetaData(),
IOnnxRuntimeOpSchemaRegistryList({graph.GetSchemaRegistry()}),
graph.DomainToVersionMap());
auto& sub_graph = body_->MainGraph();
//Add node and node args
//TODO: for better performance, we could try to transfer the nodes in parent graph to sub-graph directly,
//instead of create new nodes.
for (auto& node_index : customized_func_body_->nodes) {
auto node = parent_graph_->GetNode(node_index);
std::vector<onnxruntime::NodeArg*> inputs, outputs;
for (auto input : node->InputDefs()) {
auto& n_input = sub_graph.GetOrCreateNodeArg(input->Name(), input->TypeAsProto());
inputs.push_back(&n_input);
}
for (auto output : node->OutputDefs()) {
auto& n_output = sub_graph.GetOrCreateNodeArg(output->Name(), output->TypeAsProto());
outputs.push_back(&n_output);
}
sub_graph.AddNode(node->Name(), node->OpType(), node->Description(), inputs, outputs, &node->GetAttributes(), node->Domain());
}
for (auto input : meta_def->inputs) {
const onnx::TensorProto* initializer = nullptr;
if (graph.GetInitializedTensor(input, initializer)) {
sub_graph.AddInitializedTensor(*initializer);
}
}
//TODO: if we reuse the nodes in parent graph, maybe we don't need to resolve it.
ORT_ENFORCE(sub_graph.Resolve().IsOK());
}
FunctionImpl::FunctionImpl(const onnxruntime::Graph& graph,
const onnxruntime::NodeIndex& node_index,
const ONNX_NAMESPACE::FunctionProto* onnx_func_proto)
: parent_graph_(&graph) {
onnx_func_proto_ = onnx_func_proto;
auto node_in_parent_graph = parent_graph_->GetNode(node_index);
op_schema_ = std::make_unique<onnx::OpSchema>();
op_schema_->SetName(onnx_func_proto_->name());
op_schema_->SetDomain(onnx_func_proto_->node().Get(0).domain());
op_schema_->SetDoc(onnx_func_proto_->doc_string());
op_schema_->SinceVersion((ONNX_NAMESPACE::OperatorSetVersion)onnx_func_proto_->since_version());
std::unordered_map<std::string, int> input_name_idx_map;
std::unordered_map<std::string, int> output_name_idx_map;
TypeConstraintHelper(onnx_func_proto_, this->op_schema_, input_name_idx_map, output_name_idx_map);
op_schema_->TypeAndShapeInferenceFunction(
[this](ONNX_NAMESPACE::InferenceContext& ctx) {
auto schema_registry = ONNX_NAMESPACE::OpSchemaRegistry::Instance();
const ONNX_NAMESPACE::FunctionProto* func_ptr = this->GetFuncProto();
if (nullptr != func_ptr) {
ONNX_NAMESPACE::shape_inference::InferShapeForFunctionNode(*func_ptr, schema_registry, ctx);
}
});
op_schema_->Finalize();
//construct body
std::unordered_map<std::string, int> domain_to_version;
//TODO: set correct domain and version
domain_to_version[onnxruntime::kOnnxDomain] = (int)onnx_func_proto_->since_version();
body_ = std::make_unique<onnxruntime::Model>(onnx_func_proto_->name(), false, onnxruntime::ModelMetaData(),
IOnnxRuntimeOpSchemaRegistryList(), domain_to_version);
auto& sub_graph = body_->MainGraph();
// Add node and node args into subgraph
// The subgraph preserved the input/output tensor names
// in the parent graph for later inlining purpose
auto attr_map = node_in_parent_graph->GetAttributes();
for (auto& node : onnx_func_proto_->node()) {
std::vector<onnxruntime::NodeArg*> inputs, outputs;
for (int idx = 0; idx < node.input_size(); ++idx) {
std::string tensor_name = node.input().Get(idx);
auto iter = input_name_idx_map.find(tensor_name);
if (iter != input_name_idx_map.end()) {
// Preserving NodeArg and input/output names
ONNX_NAMESPACE::NodeProto temp_node_proto;
node_in_parent_graph->ToProto(temp_node_proto);
const onnxruntime::NodeArg* node_arg = parent_graph_->GetNodeArg(temp_node_proto.input().Get(input_name_idx_map[tensor_name]));
auto& n_input = sub_graph.GetOrCreateNodeArg(
temp_node_proto.input().Get(iter->second), node_arg->TypeAsProto());
inputs.push_back(&n_input);
} else {
auto& n_input = sub_graph.GetOrCreateNodeArg(
tensor_name + "_" + std::to_string(node_index), nullptr);
inputs.push_back(&n_input);
}
}
for (int idx = 0; idx < node.output_size(); ++idx) {
std::string tensor_name = node.output().Get(idx);
auto iter = output_name_idx_map.find(tensor_name);
if (iter != output_name_idx_map.end()) {
// Preserving NodeArg and input/output names
ONNX_NAMESPACE::NodeProto temp_node_proto;
node_in_parent_graph->ToProto(temp_node_proto);
const onnxruntime::NodeArg* node_arg = parent_graph_->GetNodeArg(temp_node_proto.output().Get(output_name_idx_map[tensor_name]));
auto& n_output = sub_graph.GetOrCreateNodeArg(
temp_node_proto.output().Get(iter->second), node_arg->TypeAsProto());
outputs.push_back(&n_output);
} else {
auto& n_output = sub_graph.GetOrCreateNodeArg(
tensor_name + "_" + std::to_string(node_index), nullptr);
outputs.push_back(&n_output);
}
}
onnxruntime::NodeAttributes new_attr_map;
for (auto& attr : node.attribute()) {
if (attr.has_ref_attr_name()) {
if (attr_map.count(attr.ref_attr_name())) {
new_attr_map[attr.name()] = attr_map[attr.ref_attr_name()];
}
} else {
new_attr_map[attr.name()] = attr;
}
}
sub_graph.AddNode(node.name() + "_" + std::to_string(node_index), node.op_type(), node.doc_string(), inputs, outputs, &new_attr_map, node.domain());
}
auto status = sub_graph.Resolve();
ORT_ENFORCE(status.IsOK());
}
FunctionImpl::~FunctionImpl() = default;
const ONNX_NAMESPACE::OpSchema& FunctionImpl::OpSchema() const {
return *op_schema_;
}
const onnxruntime::Graph& FunctionImpl::Body() const {
return body_->MainGraph();
}
const IndexedSubGraph& FunctionImpl::GetIndexedSubGraph() const {
return *customized_func_body_;
}
const ONNX_NAMESPACE::FunctionProto* FunctionImpl::GetFuncProto() const {
return onnx_func_proto_;
}
std::unique_ptr<Function> MakeFunction(const onnxruntime::Graph& graph,
std::unique_ptr<IndexedSubGraph> customized_func) {
return std::make_unique<FunctionImpl>(graph, std::move(customized_func));
}
} // namespace onnxruntime
<|endoftext|> |
<commit_before>#include <b9.hpp>
#include <b9/loader.hpp>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
/// B9run's usage string. Printed when run with -help.
static const char* usage =
"Usage: b9run [<option>...] [--] [<module> [<main>]]\n"
" Or: b9run -help\n"
"Options:\n"
" -callstyle <style>: Set the calling style. One of:\n"
" interpreter: Calls are made through the interpreter\n"
" direct: Calls are made directly, but parameters are on the "
"operand stack\n"
" passparameter: Direct calls, with parameters passed in CPU "
"registers\n"
" operandstack: Like passparam, but will keep the VM operand stack "
"updated\n"
" -loop <n>: Run the program <n> times\n"
" -inline <n>: Enable inlining\n"
" -debug: Enable debug code\n"
" -verbose: Run with verbose printing\n"
" -help: Print this help message";
/// The b9run program's global configuration.
struct RunConfig {
b9::VirtualMachineConfig vm;
const char* module = "program.so";
const char* mainFunction = "b9main";
std::size_t loopCount = 1;
bool verbose = false;
};
/// Print the configuration summary.
std::ostream& operator<<(std::ostream& out, const RunConfig& cfg) {
return out << "Loading: " << cfg.module << std::endl
<< "Executing: " << cfg.mainFunction << std::endl
<< "Call Style: " << cfg.vm.jit.callStyle << std::endl
<< "Looping: " << cfg.loopCount << " times" << std::endl
<< "Inline depth: " << cfg.vm.jit.maxInlineDepth;
}
/// Parse CLI arguments and set up the config.
static bool parseArguments(RunConfig& cfg, const int argc, char* argv[]) {
std::size_t i = 1;
for (; i < argc; i++) {
const char* arg = argv[i];
if (strcmp(arg, "-help") == 0) {
std::cout << usage << std::endl;
exit(EXIT_SUCCESS);
} else if (strcmp(arg, "-loop") == 0) {
cfg.loopCount = atoi(argv[++i]);
} else if (strcmp(arg, "-inline") == 0) {
cfg.vm.jit.maxInlineDepth = atoi(argv[++i]);
} else if (strcmp(arg, "-verbose") == 0) {
cfg.verbose = true;
cfg.vm.verbose = true;
cfg.vm.jit.verbose = true;
} else if (strcmp(arg, "-debug") == 0) {
cfg.vm.debug = true;
cfg.vm.jit.debug = true;
} else if (strcmp(arg, "-callstyle") == 0) {
i += 1;
auto callStyle = argv[i];
if (strcmp("interpreter", callStyle) == 0) {
cfg.vm.jit.callStyle = b9::CallStyle::interpreter;
} else if (strcmp("direct", callStyle) == 0) {
cfg.vm.jit.callStyle = b9::CallStyle::direct;
} else if (strcmp("passparameter", callStyle) == 0) {
cfg.vm.jit.callStyle = b9::CallStyle::passParameter;
} else if (strcmp("operandstack", callStyle) == 0) {
cfg.vm.jit.callStyle = b9::CallStyle::operandStack;
}
} else if (strcmp(arg, "--") == 0) {
i++;
break;
} else if (strcmp(arg, "-") == 0) {
std::cerr << "Unrecognized option: " << arg << std::endl;
return false;
} else {
break;
}
}
// positional
if (i < argc) {
cfg.module = argv[i++];
if (i < argc) {
cfg.mainFunction = argv[i++];
}
}
return true;
}
static void run(const RunConfig& cfg) {
b9::VirtualMachine vm{cfg.vm};
vm.initialize();
b9::DlLoader loader{true};
auto module = loader.loadModule(cfg.module);
if (module->functions.size() == 0) {
throw b9::DlException{"Empty module"};
}
vm.load(module);
for (std::size_t i = 0; i < cfg.loopCount; i++) {
vm.run(cfg.mainFunction);
}
}
int main(int argc, char* argv[]) {
RunConfig cfg;
if (!parseArguments(cfg, argc, argv)) {
exit(EXIT_FAILURE);
}
if (cfg.verbose) {
std::cout << cfg << std::endl;
}
try {
run(cfg);
} catch (const b9::DlException& e) {
std::cerr << "Failed to load module: " << e.what() << std::endl;
exit(EXIT_FAILURE);
} catch (const b9::FunctionNotFoundException& e) {
std::cerr << "Failed to find function: " << e.what() << std::endl;
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
<commit_msg>Move call to findFunction for -loop option<commit_after>#include <b9.hpp>
#include <b9/loader.hpp>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
/// B9run's usage string. Printed when run with -help.
static const char* usage =
"Usage: b9run [<option>...] [--] [<module> [<main>]]\n"
" Or: b9run -help\n"
"Options:\n"
" -callstyle <style>: Set the calling style. One of:\n"
" interpreter: Calls are made through the interpreter\n"
" direct: Calls are made directly, but parameters are on the "
"operand stack\n"
" passparameter: Direct calls, with parameters passed in CPU "
"registers\n"
" operandstack: Like passparam, but will keep the VM operand stack "
"updated\n"
" -loop <n>: Run the program <n> times\n"
" -inline <n>: Enable inlining\n"
" -debug: Enable debug code\n"
" -verbose: Run with verbose printing\n"
" -help: Print this help message";
/// The b9run program's global configuration.
struct RunConfig {
b9::VirtualMachineConfig vm;
const char* module = "program.so";
const char* mainFunction = "b9main";
std::size_t loopCount = 1;
bool verbose = false;
};
/// Print the configuration summary.
std::ostream& operator<<(std::ostream& out, const RunConfig& cfg) {
return out << "Loading: " << cfg.module << std::endl
<< "Executing: " << cfg.mainFunction << std::endl
<< "Call Style: " << cfg.vm.jit.callStyle << std::endl
<< "Looping: " << cfg.loopCount << " times" << std::endl
<< "Inline depth: " << cfg.vm.jit.maxInlineDepth;
}
/// Parse CLI arguments and set up the config.
static bool parseArguments(RunConfig& cfg, const int argc, char* argv[]) {
std::size_t i = 1;
for (; i < argc; i++) {
const char* arg = argv[i];
if (strcmp(arg, "-help") == 0) {
std::cout << usage << std::endl;
exit(EXIT_SUCCESS);
} else if (strcmp(arg, "-loop") == 0) {
cfg.loopCount = atoi(argv[++i]);
} else if (strcmp(arg, "-inline") == 0) {
cfg.vm.jit.maxInlineDepth = atoi(argv[++i]);
} else if (strcmp(arg, "-verbose") == 0) {
cfg.verbose = true;
cfg.vm.verbose = true;
cfg.vm.jit.verbose = true;
} else if (strcmp(arg, "-debug") == 0) {
cfg.vm.debug = true;
cfg.vm.jit.debug = true;
} else if (strcmp(arg, "-callstyle") == 0) {
i += 1;
auto callStyle = argv[i];
if (strcmp("interpreter", callStyle) == 0) {
cfg.vm.jit.callStyle = b9::CallStyle::interpreter;
} else if (strcmp("direct", callStyle) == 0) {
cfg.vm.jit.callStyle = b9::CallStyle::direct;
} else if (strcmp("passparameter", callStyle) == 0) {
cfg.vm.jit.callStyle = b9::CallStyle::passParameter;
} else if (strcmp("operandstack", callStyle) == 0) {
cfg.vm.jit.callStyle = b9::CallStyle::operandStack;
}
} else if (strcmp(arg, "--") == 0) {
i++;
break;
} else if (strcmp(arg, "-") == 0) {
std::cerr << "Unrecognized option: " << arg << std::endl;
return false;
} else {
break;
}
}
// positional
if (i < argc) {
cfg.module = argv[i++];
if (i < argc) {
cfg.mainFunction = argv[i++];
}
}
return true;
}
static void run(const RunConfig& cfg) {
b9::VirtualMachine vm{cfg.vm};
vm.initialize();
b9::DlLoader loader{true};
auto module = loader.loadModule(cfg.module);
if (module->functions.size() == 0) {
throw b9::DlException{"Empty module"};
}
vm.load(module);
size_t functionIndex = module->findFunction(cfg.mainFunction);
for (std::size_t i = 0; i < cfg.loopCount; i++) {
vm.run(functionIndex);
}
}
int main(int argc, char* argv[]) {
RunConfig cfg;
if (!parseArguments(cfg, argc, argv)) {
exit(EXIT_FAILURE);
}
if (cfg.verbose) {
std::cout << cfg << std::endl;
}
try {
run(cfg);
} catch (const b9::DlException& e) {
std::cerr << "Failed to load module: " << e.what() << std::endl;
exit(EXIT_FAILURE);
} catch (const b9::FunctionNotFoundException& e) {
std::cerr << "Failed to find function: " << e.what() << std::endl;
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
<|endoftext|> |
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra. Eigen itself is part of the KDE project.
//
// Copyright (C) 2008 Gael Guennebaud <[email protected]>
//
// Eigen 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 3 of the License, or (at your option) any later version.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
#include <typeinfo>
template<typename Dst, typename Src>
bool test_assign(const Dst&, const Src&, int vectorization, int unrolling)
{
return ei_assign_traits<Dst,Src>::Vectorization==vectorization
&& ei_assign_traits<Dst,Src>::Unrolling==unrolling;
}
template<typename Xpr>
bool test_sum(const Xpr&, int vectorization, int unrolling)
{
return ei_sum_traits<Xpr>::Vectorization==vectorization
&& ei_sum_traits<Xpr>::Unrolling==unrolling;
}
void test_vectorization_logic()
{
#ifdef EIGEN_VECTORIZE
VERIFY(test_assign(Vector4f(),Vector4f(),
InnerVectorization,CompleteUnrolling));
VERIFY(test_assign(Vector4f(),Vector4f()+Vector4f(),
InnerVectorization,CompleteUnrolling));
VERIFY(test_assign(Vector4f(),Vector4f().cwise() * Vector4f(),
InnerVectorization,CompleteUnrolling));
VERIFY(test_assign(Matrix4f(),Matrix4f(),
InnerVectorization,CompleteUnrolling));
VERIFY(test_assign(Matrix4f(),Matrix4f()+Matrix4f(),
InnerVectorization,CompleteUnrolling));
VERIFY(test_assign(Matrix4f(),Matrix4f().cwise() * Matrix4f(),
InnerVectorization,CompleteUnrolling));
VERIFY(test_assign(Matrix<float,16,16>(),Matrix<float,16,16>()+Matrix<float,16,16>(),
InnerVectorization,InnerUnrolling));
VERIFY(test_assign(Matrix<float,16,16,DontAlign>(),Matrix<float,16,16>()+Matrix<float,16,16>(),
NoVectorization,InnerUnrolling));
VERIFY(test_assign(Matrix<float,6,2>(),Matrix<float,6,2>().cwise() / Matrix<float,6,2>(),
LinearVectorization,CompleteUnrolling));
VERIFY(test_assign(Matrix<float,17,17>(),Matrix<float,17,17>()+Matrix<float,17,17>(),
NoVectorization,InnerUnrolling));
VERIFY(test_assign(Matrix<float,4,4>(),Matrix<float,17,17>().block<4,4>(2,3)+Matrix<float,17,17>().block<4,4>(10,4),
NoVectorization,CompleteUnrolling));
VERIFY(test_assign(MatrixXf(10,10),MatrixXf(20,20).block(10,10,2,3),
SliceVectorization,NoUnrolling));
VERIFY(test_sum(VectorXf(10),
LinearVectorization,NoUnrolling));
VERIFY(test_sum(Matrix<float,5,2>(),
NoVectorization,CompleteUnrolling));
VERIFY(test_sum(Matrix<float,6,2>(),
LinearVectorization,CompleteUnrolling));
VERIFY(test_sum(Matrix<float,16,16>(),
LinearVectorization,NoUnrolling));
VERIFY(test_sum(Matrix<float,16,16>().block<4,4>(1,2),
NoVectorization,CompleteUnrolling));
VERIFY(test_sum(Matrix<float,16,16>().block<8,1>(1,2),
LinearVectorization,CompleteUnrolling));
VERIFY(test_sum(Matrix<double,7,3>(),
NoVectorization,CompleteUnrolling));
#endif // EIGEN_VECTORIZE
}
<commit_msg>update vectorization_logic unit test wrt previous sum/redux change<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra. Eigen itself is part of the KDE project.
//
// Copyright (C) 2008 Gael Guennebaud <[email protected]>
//
// Eigen 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 3 of the License, or (at your option) any later version.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
#include <typeinfo>
template<typename Dst, typename Src>
bool test_assign(const Dst&, const Src&, int vectorization, int unrolling)
{
return ei_assign_traits<Dst,Src>::Vectorization==vectorization
&& ei_assign_traits<Dst,Src>::Unrolling==unrolling;
}
template<typename Xpr>
bool test_redux(const Xpr&, int vectorization, int unrolling)
{
typedef ei_redux_traits<ei_scalar_sum_op<typename Xpr::Scalar>,Xpr> traits;
return traits::Vectorization==vectorization && traits::Unrolling==unrolling;
}
void test_vectorization_logic()
{
#ifdef EIGEN_VECTORIZE
VERIFY(test_assign(Vector4f(),Vector4f(),
InnerVectorization,CompleteUnrolling));
VERIFY(test_assign(Vector4f(),Vector4f()+Vector4f(),
InnerVectorization,CompleteUnrolling));
VERIFY(test_assign(Vector4f(),Vector4f().cwise() * Vector4f(),
InnerVectorization,CompleteUnrolling));
VERIFY(test_assign(Matrix4f(),Matrix4f(),
InnerVectorization,CompleteUnrolling));
VERIFY(test_assign(Matrix4f(),Matrix4f()+Matrix4f(),
InnerVectorization,CompleteUnrolling));
VERIFY(test_assign(Matrix4f(),Matrix4f().cwise() * Matrix4f(),
InnerVectorization,CompleteUnrolling));
VERIFY(test_assign(Matrix<float,16,16>(),Matrix<float,16,16>()+Matrix<float,16,16>(),
InnerVectorization,InnerUnrolling));
VERIFY(test_assign(Matrix<float,16,16,DontAlign>(),Matrix<float,16,16>()+Matrix<float,16,16>(),
NoVectorization,InnerUnrolling));
VERIFY(test_assign(Matrix<float,6,2>(),Matrix<float,6,2>().cwise() / Matrix<float,6,2>(),
LinearVectorization,CompleteUnrolling));
VERIFY(test_assign(Matrix<float,17,17>(),Matrix<float,17,17>()+Matrix<float,17,17>(),
NoVectorization,InnerUnrolling));
VERIFY(test_assign(Matrix<float,4,4>(),Matrix<float,17,17>().block<4,4>(2,3)+Matrix<float,17,17>().block<4,4>(10,4),
NoVectorization,CompleteUnrolling));
VERIFY(test_assign(MatrixXf(10,10),MatrixXf(20,20).block(10,10,2,3),
SliceVectorization,NoUnrolling));
VERIFY(test_redux(VectorXf(10),
LinearVectorization,NoUnrolling));
VERIFY(test_redux(Matrix<float,5,2>(),
NoVectorization,CompleteUnrolling));
VERIFY(test_redux(Matrix<float,6,2>(),
LinearVectorization,CompleteUnrolling));
VERIFY(test_redux(Matrix<float,16,16>(),
LinearVectorization,NoUnrolling));
VERIFY(test_redux(Matrix<float,16,16>().block<4,4>(1,2),
NoVectorization,CompleteUnrolling));
VERIFY(test_redux(Matrix<float,16,16>().block<8,1>(1,2),
LinearVectorization,CompleteUnrolling));
VERIFY(test_redux(Matrix<double,7,3>(),
NoVectorization,CompleteUnrolling));
#endif // EIGEN_VECTORIZE
}
<|endoftext|> |
<commit_before>// Copyright 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ozone/ui/events/event_converter_in_process.h"
#include <sys/mman.h>
#include "base/bind.h"
#include "base/thread_task_runner_handle.h"
#include "ozone/ui/events/event_factory_ozone_wayland.h"
#include "ozone/ui/events/ime_change_observer.h"
#include "ozone/ui/events/output_change_observer.h"
#include "ozone/ui/events/window_change_observer.h"
#include "ozone/ui/public/messages.h"
#include "ui/events/event_utils.h"
#include "ui/events/ozone/layout/keyboard_layout_engine_manager.h"
#include "ui/ozone/platform/drm/host/drm_gpu_platform_support_host.h"
namespace ui {
EventConverterInProcess::EventConverterInProcess(
DrmGpuPlatformSupportHost* proxy)
: EventConverterOzoneWayland(),
proxy_(proxy),
keyboard_(&modifiers_,
KeyboardLayoutEngineManager::GetKeyboardLayoutEngine(),
base::Bind(&EventConverterInProcess::PostUiEvent,
base::Unretained(this))),
weak_ptr_factory_(this) {
proxy_->RegisterHandler(this);
}
EventConverterInProcess::~EventConverterInProcess() {
}
void EventConverterInProcess::OnChannelEstablished(
int host_id, scoped_refptr<base::SingleThreadTaskRunner> send_runner,
const base::Callback<void(IPC::Message*)>& send_callback) {
}
void EventConverterInProcess::OnChannelDestroyed(int host_id) {
}
bool EventConverterInProcess::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(EventConverterInProcess, message)
IPC_MESSAGE_HANDLER(WaylandInput_MotionNotify, MotionNotify)
IPC_MESSAGE_HANDLER(WaylandInput_ButtonNotify, ButtonNotify)
IPC_MESSAGE_HANDLER(WaylandInput_TouchNotify, TouchNotify)
IPC_MESSAGE_HANDLER(WaylandInput_AxisNotify, AxisNotify)
IPC_MESSAGE_HANDLER(WaylandInput_PointerEnter, PointerEnter)
IPC_MESSAGE_HANDLER(WaylandInput_PointerLeave, PointerLeave)
IPC_MESSAGE_HANDLER(WaylandInput_KeyNotify, KeyNotify)
IPC_MESSAGE_HANDLER(WaylandInput_VirtualKeyNotify, VirtualKeyNotify)
IPC_MESSAGE_HANDLER(WaylandInput_OutputSize, OutputSizeChanged)
IPC_MESSAGE_HANDLER(WaylandInput_CloseWidget, CloseWidget)
IPC_MESSAGE_HANDLER(WaylandWindow_Resized, WindowResized)
IPC_MESSAGE_HANDLER(WaylandWindow_Activated, WindowActivated)
IPC_MESSAGE_HANDLER(WaylandWindow_DeActivated, WindowDeActivated)
IPC_MESSAGE_HANDLER(WaylandWindow_Unminimized, WindowUnminimized)
IPC_MESSAGE_HANDLER(WaylandInput_Commit, Commit)
IPC_MESSAGE_HANDLER(WaylandInput_PreeditChanged, PreeditChanged)
IPC_MESSAGE_HANDLER(WaylandInput_PreeditEnd, PreeditEnd)
IPC_MESSAGE_HANDLER(WaylandInput_PreeditStart, PreeditStart)
IPC_MESSAGE_HANDLER(WaylandInput_InitializeXKB, InitializeXKB)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void EventConverterInProcess::MotionNotify(float x, float y) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyMotion,
weak_ptr_factory_.GetWeakPtr(), x, y));
}
void EventConverterInProcess::ButtonNotify(unsigned handle,
ui::EventType type,
ui::EventFlags flags,
float x,
float y) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyButtonPress,
weak_ptr_factory_.GetWeakPtr(), handle, type, flags, x, y));
}
void EventConverterInProcess::AxisNotify(float x,
float y,
int xoffset,
int yoffset) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyAxis,
weak_ptr_factory_.GetWeakPtr(), x, y, xoffset, yoffset));
}
void EventConverterInProcess::PointerEnter(unsigned handle,
float x,
float y) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyPointerEnter,
weak_ptr_factory_.GetWeakPtr(), handle, x, y));
}
void EventConverterInProcess::PointerLeave(unsigned handle,
float x,
float y) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyPointerLeave,
weak_ptr_factory_.GetWeakPtr(), handle, x, y));
}
void EventConverterInProcess::KeyNotify(ui::EventType type,
unsigned code,
int device_id) {
VirtualKeyNotify(type, code, device_id);
}
void EventConverterInProcess::VirtualKeyNotify(ui::EventType type,
uint32_t key,
int device_id) {
keyboard_.OnKeyChange(key,
type != ui::ET_KEY_RELEASED,
ui::EventTimeForNow(),
device_id);
}
void EventConverterInProcess::TouchNotify(ui::EventType type,
float x,
float y,
int32_t touch_id,
uint32_t time_stamp) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyTouchEvent,
weak_ptr_factory_.GetWeakPtr(), type, x, y, touch_id, time_stamp));
}
void EventConverterInProcess::CloseWidget(unsigned handle) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyCloseWidget,
weak_ptr_factory_.GetWeakPtr(), handle));
}
void EventConverterInProcess::OutputSizeChanged(unsigned width,
unsigned height) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyOutputSizeChanged,
weak_ptr_factory_.GetWeakPtr(), width, height));
}
void EventConverterInProcess::WindowResized(unsigned handle,
unsigned width,
unsigned height) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyWindowResized,
weak_ptr_factory_.GetWeakPtr(), handle, width, height));
}
void EventConverterInProcess::WindowUnminimized(unsigned handle) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyWindowUnminimized,
weak_ptr_factory_.GetWeakPtr(), handle));
}
void EventConverterInProcess::WindowDeActivated(unsigned windowhandle) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyWindowDeActivated,
weak_ptr_factory_.GetWeakPtr(), windowhandle));
}
void EventConverterInProcess::WindowActivated(unsigned windowhandle) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyWindowActivated,
weak_ptr_factory_.GetWeakPtr(), windowhandle));
}
void EventConverterInProcess::Commit(unsigned handle, const std::string& text) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyCommit,
weak_ptr_factory_.GetWeakPtr(), handle, text));
}
void EventConverterInProcess::PreeditChanged(unsigned handle,
const std::string& text,
const std::string& commit) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyPreeditChanged,
weak_ptr_factory_.GetWeakPtr(), handle, text, commit));
}
void EventConverterInProcess::PreeditEnd() {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyPreeditEnd,
weak_ptr_factory_.GetWeakPtr()));
}
void EventConverterInProcess::PreeditStart() {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyPreeditStart,
weak_ptr_factory_.GetWeakPtr()));
}
void EventConverterInProcess::InitializeXKB(base::SharedMemoryHandle fd,
uint32_t size) {
char* map_str =
reinterpret_cast<char*>(mmap(NULL,
size,
PROT_READ,
MAP_SHARED,
fd.fd,
0));
if (map_str == MAP_FAILED)
return;
KeyboardLayoutEngineManager::GetKeyboardLayoutEngine()->
SetCurrentLayoutByName(map_str);
munmap(map_str, size);
close(fd.fd);
}
void EventConverterInProcess::PostUiEvent(Event* event) {
DispatchEvent(event);
}
void EventConverterInProcess::DispatchUiEventTask(scoped_ptr<Event> event) {
DispatchEvent(event.get());
}
void EventConverterInProcess::OnDispatcherListChanged() {
}
void EventConverterInProcess::NotifyMotion(float x,
float y) {
gfx::Point position(x, y);
ui::MouseEvent mouseev(ui::ET_MOUSE_MOVED,
position,
position,
ui::EventTimeForNow(),
0,
0);
DispatchEvent(&mouseev);
}
void EventConverterInProcess::NotifyButtonPress(unsigned handle,
ui::EventType type,
ui::EventFlags flags,
float x,
float y) {
gfx::Point position(x, y);
ui::MouseEvent mouseev(type,
position,
position,
ui::EventTimeForNow(),
flags,
flags);
DispatchEvent(&mouseev);
if (type == ui::ET_MOUSE_RELEASED) {
ui::WindowChangeObserver* observer =
ui::EventFactoryOzoneWayland::GetInstance()->
GetWindowChangeObserver();
if (observer)
observer->OnWindowFocused(handle);
}
}
void EventConverterInProcess::NotifyAxis(float x,
float y,
int xoffset,
int yoffset) {
gfx::Point position(x, y);
ui::MouseEvent mouseev(ui::ET_MOUSEWHEEL,
position,
position,
ui::EventTimeForNow(),
0,
0);
ui::MouseWheelEvent wheelev(mouseev, xoffset, yoffset);
DispatchEvent(&wheelev);
}
void EventConverterInProcess::NotifyPointerEnter(unsigned handle,
float x,
float y) {
ui::WindowChangeObserver* observer =
ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
if (observer)
observer->OnWindowEnter(handle);
gfx::Point position(x, y);
ui::MouseEvent mouseev(ui::ET_MOUSE_ENTERED,
position,
position,
ui::EventTimeForNow(),
0,
0);
DispatchEvent(&mouseev);
}
void EventConverterInProcess::NotifyPointerLeave(unsigned handle,
float x,
float y) {
ui::WindowChangeObserver* observer =
ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
if (observer)
observer->OnWindowLeave(handle);
gfx::Point position(x, y);
ui::MouseEvent mouseev(ui::ET_MOUSE_EXITED,
position,
position,
ui::EventTimeForNow(),
0,
0);
DispatchEvent(&mouseev);
}
void EventConverterInProcess::NotifyTouchEvent(ui::EventType type,
float x,
float y,
int32_t touch_id,
uint32_t time_stamp) {
gfx::Point position(x, y);
base::TimeDelta time_delta = base::TimeDelta::FromMilliseconds(time_stamp);
ui::TouchEvent touchev(type, position, touch_id, time_delta);
DispatchEvent(&touchev);
}
void EventConverterInProcess::NotifyCloseWidget(unsigned handle) {
ui::WindowChangeObserver* observer =
ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
if (observer)
observer->OnWindowClose(handle);
}
void EventConverterInProcess::NotifyOutputSizeChanged(unsigned width,
unsigned height) {
ui::OutputChangeObserver* observer =
ui::EventFactoryOzoneWayland::GetInstance()->GetOutputChangeObserver();
if (observer)
observer->OnOutputSizeChanged(width, height);
}
void EventConverterInProcess::NotifyWindowResized(unsigned handle,
unsigned width,
unsigned height) {
ui::WindowChangeObserver* observer =
ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
if (observer)
observer->OnWindowResized(handle, width, height);
}
void EventConverterInProcess::NotifyWindowUnminimized(unsigned handle) {
ui::WindowChangeObserver* observer =
ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
if (observer)
observer->OnWindowUnminimized(handle);
}
void EventConverterInProcess::NotifyWindowDeActivated(unsigned handle) {
ui::WindowChangeObserver* observer =
ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
if (observer)
observer->OnWindowDeActivated(handle);
}
void EventConverterInProcess::NotifyWindowActivated(unsigned handle) {
ui::WindowChangeObserver* observer =
ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
if (observer)
observer->OnWindowActivated(handle);
}
void EventConverterInProcess::NotifyCommit(unsigned handle,
const std::string& text) {
ui::IMEChangeObserver* observer =
ui::EventFactoryOzoneWayland::GetInstance()->GetIMEChangeObserver();
if (observer)
observer->OnCommit(handle, text);
}
void EventConverterInProcess::NotifyPreeditChanged(unsigned handle,
const std::string& text,
const std::string& commit) {
ui::IMEChangeObserver* observer =
ui::EventFactoryOzoneWayland::GetInstance()->GetIMEChangeObserver();
if (observer)
observer->OnPreeditChanged(handle, text, commit);
}
void EventConverterInProcess::NotifyPreeditEnd() {
}
void EventConverterInProcess::NotifyPreeditStart() {
}
} // namespace ui
<commit_msg>Gardening: Adopt to https://codereview.chromium.org/1166113003/<commit_after>// Copyright 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ozone/ui/events/event_converter_in_process.h"
#include <sys/mman.h>
#include "base/bind.h"
#include "base/thread_task_runner_handle.h"
#include "ozone/ui/events/event_factory_ozone_wayland.h"
#include "ozone/ui/events/ime_change_observer.h"
#include "ozone/ui/events/output_change_observer.h"
#include "ozone/ui/events/window_change_observer.h"
#include "ozone/ui/public/messages.h"
#include "ui/events/event_utils.h"
#include "ui/events/ozone/layout/keyboard_layout_engine_manager.h"
#include "ui/ozone/platform/drm/host/drm_gpu_platform_support_host.h"
namespace ui {
EventConverterInProcess::EventConverterInProcess(
DrmGpuPlatformSupportHost* proxy)
: EventConverterOzoneWayland(),
proxy_(proxy),
keyboard_(&modifiers_,
KeyboardLayoutEngineManager::GetKeyboardLayoutEngine(),
base::Bind(&EventConverterInProcess::PostUiEvent,
base::Unretained(this))),
weak_ptr_factory_(this) {
proxy_->RegisterHandler(this);
}
EventConverterInProcess::~EventConverterInProcess() {
}
void EventConverterInProcess::OnChannelEstablished(
int host_id, scoped_refptr<base::SingleThreadTaskRunner> send_runner,
const base::Callback<void(IPC::Message*)>& send_callback) {
}
void EventConverterInProcess::OnChannelDestroyed(int host_id) {
}
bool EventConverterInProcess::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(EventConverterInProcess, message)
IPC_MESSAGE_HANDLER(WaylandInput_MotionNotify, MotionNotify)
IPC_MESSAGE_HANDLER(WaylandInput_ButtonNotify, ButtonNotify)
IPC_MESSAGE_HANDLER(WaylandInput_TouchNotify, TouchNotify)
IPC_MESSAGE_HANDLER(WaylandInput_AxisNotify, AxisNotify)
IPC_MESSAGE_HANDLER(WaylandInput_PointerEnter, PointerEnter)
IPC_MESSAGE_HANDLER(WaylandInput_PointerLeave, PointerLeave)
IPC_MESSAGE_HANDLER(WaylandInput_KeyNotify, KeyNotify)
IPC_MESSAGE_HANDLER(WaylandInput_VirtualKeyNotify, VirtualKeyNotify)
IPC_MESSAGE_HANDLER(WaylandInput_OutputSize, OutputSizeChanged)
IPC_MESSAGE_HANDLER(WaylandInput_CloseWidget, CloseWidget)
IPC_MESSAGE_HANDLER(WaylandWindow_Resized, WindowResized)
IPC_MESSAGE_HANDLER(WaylandWindow_Activated, WindowActivated)
IPC_MESSAGE_HANDLER(WaylandWindow_DeActivated, WindowDeActivated)
IPC_MESSAGE_HANDLER(WaylandWindow_Unminimized, WindowUnminimized)
IPC_MESSAGE_HANDLER(WaylandInput_Commit, Commit)
IPC_MESSAGE_HANDLER(WaylandInput_PreeditChanged, PreeditChanged)
IPC_MESSAGE_HANDLER(WaylandInput_PreeditEnd, PreeditEnd)
IPC_MESSAGE_HANDLER(WaylandInput_PreeditStart, PreeditStart)
IPC_MESSAGE_HANDLER(WaylandInput_InitializeXKB, InitializeXKB)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void EventConverterInProcess::MotionNotify(float x, float y) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyMotion,
weak_ptr_factory_.GetWeakPtr(), x, y));
}
void EventConverterInProcess::ButtonNotify(unsigned handle,
ui::EventType type,
ui::EventFlags flags,
float x,
float y) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyButtonPress,
weak_ptr_factory_.GetWeakPtr(), handle, type, flags, x, y));
}
void EventConverterInProcess::AxisNotify(float x,
float y,
int xoffset,
int yoffset) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyAxis,
weak_ptr_factory_.GetWeakPtr(), x, y, xoffset, yoffset));
}
void EventConverterInProcess::PointerEnter(unsigned handle,
float x,
float y) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyPointerEnter,
weak_ptr_factory_.GetWeakPtr(), handle, x, y));
}
void EventConverterInProcess::PointerLeave(unsigned handle,
float x,
float y) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyPointerLeave,
weak_ptr_factory_.GetWeakPtr(), handle, x, y));
}
void EventConverterInProcess::KeyNotify(ui::EventType type,
unsigned code,
int device_id) {
VirtualKeyNotify(type, code, device_id);
}
void EventConverterInProcess::VirtualKeyNotify(ui::EventType type,
uint32_t key,
int device_id) {
keyboard_.OnKeyChange(key,
type != ui::ET_KEY_RELEASED,
false,
ui::EventTimeForNow(),
device_id);
}
void EventConverterInProcess::TouchNotify(ui::EventType type,
float x,
float y,
int32_t touch_id,
uint32_t time_stamp) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyTouchEvent,
weak_ptr_factory_.GetWeakPtr(), type, x, y, touch_id, time_stamp));
}
void EventConverterInProcess::CloseWidget(unsigned handle) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyCloseWidget,
weak_ptr_factory_.GetWeakPtr(), handle));
}
void EventConverterInProcess::OutputSizeChanged(unsigned width,
unsigned height) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyOutputSizeChanged,
weak_ptr_factory_.GetWeakPtr(), width, height));
}
void EventConverterInProcess::WindowResized(unsigned handle,
unsigned width,
unsigned height) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyWindowResized,
weak_ptr_factory_.GetWeakPtr(), handle, width, height));
}
void EventConverterInProcess::WindowUnminimized(unsigned handle) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyWindowUnminimized,
weak_ptr_factory_.GetWeakPtr(), handle));
}
void EventConverterInProcess::WindowDeActivated(unsigned windowhandle) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyWindowDeActivated,
weak_ptr_factory_.GetWeakPtr(), windowhandle));
}
void EventConverterInProcess::WindowActivated(unsigned windowhandle) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyWindowActivated,
weak_ptr_factory_.GetWeakPtr(), windowhandle));
}
void EventConverterInProcess::Commit(unsigned handle, const std::string& text) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyCommit,
weak_ptr_factory_.GetWeakPtr(), handle, text));
}
void EventConverterInProcess::PreeditChanged(unsigned handle,
const std::string& text,
const std::string& commit) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyPreeditChanged,
weak_ptr_factory_.GetWeakPtr(), handle, text, commit));
}
void EventConverterInProcess::PreeditEnd() {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyPreeditEnd,
weak_ptr_factory_.GetWeakPtr()));
}
void EventConverterInProcess::PreeditStart() {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&EventConverterInProcess::NotifyPreeditStart,
weak_ptr_factory_.GetWeakPtr()));
}
void EventConverterInProcess::InitializeXKB(base::SharedMemoryHandle fd,
uint32_t size) {
char* map_str =
reinterpret_cast<char*>(mmap(NULL,
size,
PROT_READ,
MAP_SHARED,
fd.fd,
0));
if (map_str == MAP_FAILED)
return;
KeyboardLayoutEngineManager::GetKeyboardLayoutEngine()->
SetCurrentLayoutByName(map_str);
munmap(map_str, size);
close(fd.fd);
}
void EventConverterInProcess::PostUiEvent(Event* event) {
DispatchEvent(event);
}
void EventConverterInProcess::DispatchUiEventTask(scoped_ptr<Event> event) {
DispatchEvent(event.get());
}
void EventConverterInProcess::OnDispatcherListChanged() {
}
void EventConverterInProcess::NotifyMotion(float x,
float y) {
gfx::Point position(x, y);
ui::MouseEvent mouseev(ui::ET_MOUSE_MOVED,
position,
position,
ui::EventTimeForNow(),
0,
0);
DispatchEvent(&mouseev);
}
void EventConverterInProcess::NotifyButtonPress(unsigned handle,
ui::EventType type,
ui::EventFlags flags,
float x,
float y) {
gfx::Point position(x, y);
ui::MouseEvent mouseev(type,
position,
position,
ui::EventTimeForNow(),
flags,
flags);
DispatchEvent(&mouseev);
if (type == ui::ET_MOUSE_RELEASED) {
ui::WindowChangeObserver* observer =
ui::EventFactoryOzoneWayland::GetInstance()->
GetWindowChangeObserver();
if (observer)
observer->OnWindowFocused(handle);
}
}
void EventConverterInProcess::NotifyAxis(float x,
float y,
int xoffset,
int yoffset) {
gfx::Point position(x, y);
ui::MouseEvent mouseev(ui::ET_MOUSEWHEEL,
position,
position,
ui::EventTimeForNow(),
0,
0);
ui::MouseWheelEvent wheelev(mouseev, xoffset, yoffset);
DispatchEvent(&wheelev);
}
void EventConverterInProcess::NotifyPointerEnter(unsigned handle,
float x,
float y) {
ui::WindowChangeObserver* observer =
ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
if (observer)
observer->OnWindowEnter(handle);
gfx::Point position(x, y);
ui::MouseEvent mouseev(ui::ET_MOUSE_ENTERED,
position,
position,
ui::EventTimeForNow(),
0,
0);
DispatchEvent(&mouseev);
}
void EventConverterInProcess::NotifyPointerLeave(unsigned handle,
float x,
float y) {
ui::WindowChangeObserver* observer =
ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
if (observer)
observer->OnWindowLeave(handle);
gfx::Point position(x, y);
ui::MouseEvent mouseev(ui::ET_MOUSE_EXITED,
position,
position,
ui::EventTimeForNow(),
0,
0);
DispatchEvent(&mouseev);
}
void EventConverterInProcess::NotifyTouchEvent(ui::EventType type,
float x,
float y,
int32_t touch_id,
uint32_t time_stamp) {
gfx::Point position(x, y);
base::TimeDelta time_delta = base::TimeDelta::FromMilliseconds(time_stamp);
ui::TouchEvent touchev(type, position, touch_id, time_delta);
DispatchEvent(&touchev);
}
void EventConverterInProcess::NotifyCloseWidget(unsigned handle) {
ui::WindowChangeObserver* observer =
ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
if (observer)
observer->OnWindowClose(handle);
}
void EventConverterInProcess::NotifyOutputSizeChanged(unsigned width,
unsigned height) {
ui::OutputChangeObserver* observer =
ui::EventFactoryOzoneWayland::GetInstance()->GetOutputChangeObserver();
if (observer)
observer->OnOutputSizeChanged(width, height);
}
void EventConverterInProcess::NotifyWindowResized(unsigned handle,
unsigned width,
unsigned height) {
ui::WindowChangeObserver* observer =
ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
if (observer)
observer->OnWindowResized(handle, width, height);
}
void EventConverterInProcess::NotifyWindowUnminimized(unsigned handle) {
ui::WindowChangeObserver* observer =
ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
if (observer)
observer->OnWindowUnminimized(handle);
}
void EventConverterInProcess::NotifyWindowDeActivated(unsigned handle) {
ui::WindowChangeObserver* observer =
ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
if (observer)
observer->OnWindowDeActivated(handle);
}
void EventConverterInProcess::NotifyWindowActivated(unsigned handle) {
ui::WindowChangeObserver* observer =
ui::EventFactoryOzoneWayland::GetInstance()->GetWindowChangeObserver();
if (observer)
observer->OnWindowActivated(handle);
}
void EventConverterInProcess::NotifyCommit(unsigned handle,
const std::string& text) {
ui::IMEChangeObserver* observer =
ui::EventFactoryOzoneWayland::GetInstance()->GetIMEChangeObserver();
if (observer)
observer->OnCommit(handle, text);
}
void EventConverterInProcess::NotifyPreeditChanged(unsigned handle,
const std::string& text,
const std::string& commit) {
ui::IMEChangeObserver* observer =
ui::EventFactoryOzoneWayland::GetInstance()->GetIMEChangeObserver();
if (observer)
observer->OnPreeditChanged(handle, text, commit);
}
void EventConverterInProcess::NotifyPreeditEnd() {
}
void EventConverterInProcess::NotifyPreeditStart() {
}
} // namespace ui
<|endoftext|> |
<commit_before>// Copyright 2021 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 "open_spiel/bots/human/human_bot.h"
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <string>
#include <unordered_map>
#include <utility>
#include "open_spiel/abseil-cpp/absl/strings/numbers.h"
namespace open_spiel {
namespace {
const int kMaxWidth = 80;
const int kPadding = 2;
void PrintColumns(const std::vector<std::string> &strings) {
std::string padding_string(kPadding, ' ');
int longest_string_length = 0;
for (const std::string &string : strings) {
if (string.length() > longest_string_length) {
longest_string_length = string.length();
}
}
int max_columns = (kMaxWidth - 1) / (longest_string_length + 2 * kPadding);
int rows = ceil((float)strings.size() / (float)max_columns);
int columns = ceil((float)strings.size() / (float)rows);
for (int row = 0; row < rows; ++row) {
for (int column = 0; column < columns; ++column) {
int index = row + column * rows;
if (index < strings.size()) {
std::cout << std::left << std::setw(longest_string_length + kPadding)
<< padding_string << strings[index];
}
}
std::cout << std::endl;
}
}
} // namespace
Action HumanBot::Step(const State &state) {
std::vector<Action> legal_actions = state.LegalActions(state.CurrentPlayer());
if (legal_actions.empty()) {
return kInvalidAction;
}
std::unordered_map<std::string, Action> action_map;
for (Action legal_action : legal_actions) {
action_map[state.ActionToString(legal_action)] = legal_action;
}
while (true) {
Action action;
std::string action_string = "";
std::cout << "Choose an action (empty to print legal actions): ";
std::getline(std::cin, action_string);
// Print the legal actions if no action is given.
if (action_string.empty()) {
std::cout << "Legal action(s):" << std::endl;
std::vector<std::string> legal_action_strings;
std::vector<std::pair<std::string, Action>> sorted_action_map(
action_map.begin(), action_map.end());
std::sort(sorted_action_map.begin(), sorted_action_map.end(),
[](const auto &left, const auto &right) {
return left.first.compare(right.first);
});
int longest_action_length = 0;
for (const Action &legal_action : legal_actions) {
int action_length = std::to_string(legal_action).length();
if (action_length > longest_action_length) {
longest_action_length = action_length;
}
}
for (const auto &string_action_pair : sorted_action_map) {
std::string action_string = string_action_pair.first;
std::string action_int_string =
std::to_string(string_action_pair.second);
std::string action_padding(
longest_action_length - action_int_string.length(), ' ');
legal_action_strings.push_back(absl::StrCat(
action_padding, action_int_string, ": ", action_string));
}
PrintColumns(legal_action_strings);
continue;
}
// Return the action if a valid string is given.
if (action_map.find(action_string) != action_map.end()) {
return action_map[action_string];
}
// Return the action if a valid integer is given.
bool parse_succeeded = absl::SimpleAtoi(action_string, &action);
if (!parse_succeeded) {
std::cout << "Could not parse the action: " << action_string << std::endl;
continue;
}
for (Action legal_action : legal_actions) {
if (action == legal_action) {
return action;
}
}
// The input was not valid.
std::cout << "Illegal action selected: " << action_string << std::endl;
}
}
} // namespace open_spiel
<commit_msg>Fix comparator, std::basic_string::compare returns an int, not bool.<commit_after>// Copyright 2021 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 "open_spiel/bots/human/human_bot.h"
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <string>
#include <unordered_map>
#include <utility>
#include "open_spiel/abseil-cpp/absl/strings/numbers.h"
namespace open_spiel {
namespace {
const int kMaxWidth = 80;
const int kPadding = 2;
void PrintColumns(const std::vector<std::string> &strings) {
std::string padding_string(kPadding, ' ');
int longest_string_length = 0;
for (const std::string &string : strings) {
if (string.length() > longest_string_length) {
longest_string_length = string.length();
}
}
int max_columns = (kMaxWidth - 1) / (longest_string_length + 2 * kPadding);
int rows = ceil((float)strings.size() / (float)max_columns);
int columns = ceil((float)strings.size() / (float)rows);
for (int row = 0; row < rows; ++row) {
for (int column = 0; column < columns; ++column) {
int index = row + column * rows;
if (index < strings.size()) {
std::cout << std::left << std::setw(longest_string_length + kPadding)
<< padding_string << strings[index];
}
}
std::cout << std::endl;
}
}
} // namespace
Action HumanBot::Step(const State &state) {
std::vector<Action> legal_actions = state.LegalActions(state.CurrentPlayer());
if (legal_actions.empty()) {
return kInvalidAction;
}
std::unordered_map<std::string, Action> action_map;
for (Action legal_action : legal_actions) {
action_map[state.ActionToString(legal_action)] = legal_action;
}
while (true) {
Action action;
std::string action_string = "";
std::cout << "Choose an action (empty to print legal actions): ";
std::getline(std::cin, action_string);
// Print the legal actions if no action is given.
if (action_string.empty()) {
std::cout << "Legal action(s):" << std::endl;
std::vector<std::string> legal_action_strings;
std::vector<std::pair<std::string, Action>> sorted_action_map(
action_map.begin(), action_map.end());
std::sort(sorted_action_map.begin(), sorted_action_map.end(),
[](const auto &left, const auto &right) {
return left.first < right.first;
});
int longest_action_length = 0;
for (const Action &legal_action : legal_actions) {
int action_length = std::to_string(legal_action).length();
if (action_length > longest_action_length) {
longest_action_length = action_length;
}
}
for (const auto &string_action_pair : sorted_action_map) {
std::string action_string = string_action_pair.first;
std::string action_int_string =
std::to_string(string_action_pair.second);
std::string action_padding(
longest_action_length - action_int_string.length(), ' ');
legal_action_strings.push_back(absl::StrCat(
action_padding, action_int_string, ": ", action_string));
}
PrintColumns(legal_action_strings);
continue;
}
// Return the action if a valid string is given.
if (action_map.find(action_string) != action_map.end()) {
return action_map[action_string];
}
// Return the action if a valid integer is given.
bool parse_succeeded = absl::SimpleAtoi(action_string, &action);
if (!parse_succeeded) {
std::cout << "Could not parse the action: " << action_string << std::endl;
continue;
}
for (Action legal_action : legal_actions) {
if (action == legal_action) {
return action;
}
}
// The input was not valid.
std::cout << "Illegal action selected: " << action_string << std::endl;
}
}
} // namespace open_spiel
<|endoftext|> |
<commit_before>// A fuzzer for floating-point formatter.
// For the license information refer to format.h.
#include <cstdint>
#include <cstdlib>
#include <stdexcept>
#include <limits>
#include <fmt/format.h>
#include "fuzzer-common.h"
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
if (size <= sizeof(double) || !std::numeric_limits<double>::is_iec559)
return 0;
auto value = assign_from_buf<double>(data);
auto buffer = fmt::memory_buffer();
fmt::format_to(buffer, "{}", value);
// Check a round trip.
if (std::isnan(value)) {
auto nan = std::signbit(value) ? "-nan" : "nan";
if (fmt::string_view(buffer.data(), buffer.size()) != nan)
throw std::runtime_error("round trip failure");
return 0;
}
buffer.push_back('\0');
char* ptr = nullptr;
if (std::strtod(buffer.data(), &ptr) != value)
throw std::runtime_error("round trip failure");
if (ptr != buffer.end())
throw std::runtime_error("unparsed output");
return 0;
}
<commit_msg>Fix float fuzzer<commit_after>// A fuzzer for floating-point formatter.
// For the license information refer to format.h.
#include <cstdint>
#include <cstdlib>
#include <stdexcept>
#include <limits>
#include <fmt/format.h>
#include "fuzzer-common.h"
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
if (size <= sizeof(double) || !std::numeric_limits<double>::is_iec559)
return 0;
auto value = assign_from_buf<double>(data);
auto buffer = fmt::memory_buffer();
fmt::format_to(buffer, "{}", value);
// Check a round trip.
if (std::isnan(value)) {
auto nan = std::signbit(value) ? "-nan" : "nan";
if (fmt::string_view(buffer.data(), buffer.size()) != nan)
throw std::runtime_error("round trip failure");
return 0;
}
buffer.push_back('\0');
char* ptr = nullptr;
if (std::strtod(buffer.data(), &ptr) != value)
throw std::runtime_error("round trip failure");
if (ptr + 1 != buffer.end())
throw std::runtime_error("unparsed output");
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2016 Doyub Kim
#include <pch.h>
#include <physics_helpers.h>
#include <jet/array_utils.h>
#include <jet/grid_fractional_boundary_condition_solver3.h>
#include <jet/level_set_utils.h>
#include <jet/surface_to_implicit3.h>
#include <algorithm>
using namespace jet;
GridFractionalBoundaryConditionSolver3
::GridFractionalBoundaryConditionSolver3() {
}
GridFractionalBoundaryConditionSolver3::
~GridFractionalBoundaryConditionSolver3() {
}
void GridFractionalBoundaryConditionSolver3::constrainVelocity(
FaceCenteredGrid3* velocity,
unsigned int extrapolationDepth) {
Size3 size = velocity->resolution();
if (_colliderSdf.resolution() != size) {
updateCollider(
collider(),
size,
velocity->gridSpacing(),
velocity->origin());
}
auto u = velocity->uAccessor();
auto v = velocity->vAccessor();
auto w = velocity->wAccessor();
auto uPos = velocity->uPosition();
auto vPos = velocity->vPosition();
auto wPos = velocity->wPosition();
Array3<double> uTemp(u.size());
Array3<double> vTemp(v.size());
Array3<double> wTemp(w.size());
Array3<char> uMarker(u.size(), 1);
Array3<char> vMarker(v.size(), 1);
Array3<char> wMarker(w.size(), 1);
Vector3D h = velocity->gridSpacing();
// Assign collider's velocity first and initialize markers
velocity->parallelForEachUIndex([&](size_t i, size_t j, size_t k) {
Vector3D pt = uPos(i, j, k);
double phi0 = _colliderSdf.sample(pt - Vector3D(0.5 * h.x, 0.0, 0.0));
double phi1 = _colliderSdf.sample(pt + Vector3D(0.5 * h.x, 0.0, 0.0));
double frac = fractionInsideSdf(phi0, phi1);
frac = 1.0 - clamp(frac, 0.0, 1.0);
if (frac > 0.0) {
uMarker(i, j, k) = 1;
} else {
Vector3D colliderVel = collider()->velocityAt(pt);
u(i, j, k) = colliderVel.x;
uMarker(i, j, k) = 0;
}
});
velocity->parallelForEachVIndex([&](size_t i, size_t j, size_t k) {
Vector3D pt = vPos(i, j, k);
double phi0 = _colliderSdf.sample(pt - Vector3D(0.0, 0.5 * h.y, 0.0));
double phi1 = _colliderSdf.sample(pt + Vector3D(0.0, 0.5 * h.y, 0.0));
double frac = fractionInsideSdf(phi0, phi1);
frac = 1.0 - clamp(frac, 0.0, 1.0);
if (frac > 0.0) {
vMarker(i, j, k) = 1;
} else {
Vector3D colliderVel = collider()->velocityAt(pt);
v(i, j, k) = colliderVel.y;
vMarker(i, j, k) = 0;
}
});
velocity->parallelForEachWIndex([&](size_t i, size_t j, size_t k) {
Vector3D pt = wPos(i, j, k);
double phi0 = _colliderSdf.sample(pt - Vector3D(0.0, 0.0, 0.5 * h.z));
double phi1 = _colliderSdf.sample(pt + Vector3D(0.0, 0.0, 0.5 * h.z));
double frac = fractionInsideSdf(phi0, phi1);
frac = 1.0 - clamp(frac, 0.0, 1.0);
if (frac > 0.0) {
wMarker(i, j, k) = 1;
} else {
Vector3D colliderVel = collider()->velocityAt(pt);
w(i, j, k) = colliderVel.z;
wMarker(i, j, k) = 0;
}
});
// Free-slip: Extrapolate fluid velocity into the collider
extrapolateToRegion(
velocity->uConstAccessor(), uMarker, extrapolationDepth, u);
extrapolateToRegion(
velocity->vConstAccessor(), vMarker, extrapolationDepth, v);
extrapolateToRegion(
velocity->wConstAccessor(), wMarker, extrapolationDepth, w);
// No-flux: project the extrapolated velocity to the collider's surface
// normal
velocity->parallelForEachUIndex([&](size_t i, size_t j, size_t k) {
Vector3D pt = uPos(i, j, k);
if (isInsideSdf(_colliderSdf.sample(pt))) {
Vector3D colliderVel = collider()->velocityAt(pt);
Vector3D vel = velocity->sample(pt);
Vector3D g = _colliderSdf.gradient(pt);
if (g.lengthSquared() > 0.0) {
Vector3D n = g.normalized();
Vector3D velr = vel - colliderVel;
Vector3D velt = projectAndApplyFriction(
velr, n, collider()->frictionCoefficient());
Vector3D velp = velt + colliderVel;
uTemp(i, j, k) = velp.x;
} else {
uTemp(i, j, k) = colliderVel.x;
}
} else {
uTemp(i, j, k) = u(i, j, k);
}
});
velocity->parallelForEachVIndex([&](size_t i, size_t j, size_t k) {
Vector3D pt = vPos(i, j, k);
if (isInsideSdf(_colliderSdf.sample(pt))) {
Vector3D colliderVel = collider()->velocityAt(pt);
Vector3D vel = velocity->sample(pt);
Vector3D g = _colliderSdf.gradient(pt);
if (g.lengthSquared() > 0.0) {
Vector3D n = g.normalized();
Vector3D velr = vel - colliderVel;
Vector3D velt = projectAndApplyFriction(
velr, n, collider()->frictionCoefficient());
Vector3D velp = velt + colliderVel;
vTemp(i, j, k) = velp.y;
} else {
vTemp(i, j, k) = colliderVel.y;
}
} else {
vTemp(i, j, k) = v(i, j, k);
}
});
velocity->parallelForEachWIndex([&](size_t i, size_t j, size_t k) {
Vector3D pt = wPos(i, j, k);
if (isInsideSdf(_colliderSdf.sample(pt))) {
Vector3D colliderVel = collider()->velocityAt(pt);
Vector3D vel = velocity->sample(pt);
Vector3D g = _colliderSdf.gradient(pt);
if (g.lengthSquared() > 0.0) {
Vector3D n = g.normalized();
Vector3D velr = vel - colliderVel;
Vector3D velt = projectAndApplyFriction(
velr, n, collider()->frictionCoefficient());
Vector3D velp = velt + colliderVel;
wTemp(i, j, k) = velp.z;
} else {
wTemp(i, j, k) = colliderVel.z;
}
} else {
wTemp(i, j, k) = v(i, j, k);
}
});
// Transfer results
u.parallelForEachIndex([&](size_t i, size_t j, size_t k) {
u(i, j, k) = uTemp(i, j, k);
});
v.parallelForEachIndex([&](size_t i, size_t j, size_t k) {
v(i, j, k) = vTemp(i, j, k);
});
w.parallelForEachIndex([&](size_t i, size_t j, size_t k) {
w(i, j, k) = wTemp(i, j, k);
});
// No-flux: Project velocity on the domain boundary if closed
if (closedDomainBoundaryFlag() & kDirectionLeft) {
for (size_t k = 0; k < u.size().z; ++k) {
for (size_t j = 0; j < u.size().y; ++j) {
u(0, j, k) = 0;
}
}
}
if (closedDomainBoundaryFlag() & kDirectionRight) {
for (size_t k = 0; k < u.size().z; ++k) {
for (size_t j = 0; j < u.size().y; ++j) {
u(u.size().x - 1, j, k) = 0;
}
}
}
if (closedDomainBoundaryFlag() & kDirectionDown) {
for (size_t k = 0; k < v.size().z; ++k) {
for (size_t i = 0; i < v.size().x; ++i) {
v(i, 0, k) = 0;
}
}
}
if (closedDomainBoundaryFlag() & kDirectionUp) {
for (size_t k = 0; k < v.size().z; ++k) {
for (size_t i = 0; i < v.size().x; ++i) {
v(i, v.size().y - 1, k) = 0;
}
}
}
if (closedDomainBoundaryFlag() & kDirectionBack) {
for (size_t j = 0; j < w.size().y; ++j) {
for (size_t i = 0; i < w.size().x; ++i) {
w(i, j, 0) = 0;
}
}
}
if (closedDomainBoundaryFlag() & kDirectionFront) {
for (size_t j = 0; j < w.size().y; ++j) {
for (size_t i = 0; i < w.size().x; ++i) {
w(i, j, w.size().z - 1) = 0;
}
}
}
}
const CellCenteredScalarGrid3&
GridFractionalBoundaryConditionSolver3::colliderSdf() const {
return _colliderSdf;
}
void GridFractionalBoundaryConditionSolver3::onColliderUpdated(
const Size3& gridSize,
const Vector3D& gridSpacing,
const Vector3D& gridOrigin) {
_colliderSdf.resize(gridSize, gridSpacing, gridOrigin);
if (collider() != nullptr) {
Surface3Ptr surface = collider()->surface();
ImplicitSurface3Ptr implicitSurface
= std::dynamic_pointer_cast<ImplicitSurface3>(surface);
if (implicitSurface == nullptr) {
implicitSurface = std::make_shared<SurfaceToImplicit3>(surface);
}
_colliderSdf.fill([&](const Vector3D& pt) {
return implicitSurface->signedDistance(pt);
});
} else {
_colliderSdf.fill(kMaxD);
}
}
<commit_msg>Fix wrong array accessor problem<commit_after>// Copyright (c) 2016 Doyub Kim
#include <pch.h>
#include <physics_helpers.h>
#include <jet/array_utils.h>
#include <jet/grid_fractional_boundary_condition_solver3.h>
#include <jet/level_set_utils.h>
#include <jet/surface_to_implicit3.h>
#include <algorithm>
using namespace jet;
GridFractionalBoundaryConditionSolver3
::GridFractionalBoundaryConditionSolver3() {
}
GridFractionalBoundaryConditionSolver3::
~GridFractionalBoundaryConditionSolver3() {
}
void GridFractionalBoundaryConditionSolver3::constrainVelocity(
FaceCenteredGrid3* velocity,
unsigned int extrapolationDepth) {
Size3 size = velocity->resolution();
if (_colliderSdf.resolution() != size) {
updateCollider(
collider(),
size,
velocity->gridSpacing(),
velocity->origin());
}
auto u = velocity->uAccessor();
auto v = velocity->vAccessor();
auto w = velocity->wAccessor();
auto uPos = velocity->uPosition();
auto vPos = velocity->vPosition();
auto wPos = velocity->wPosition();
Array3<double> uTemp(u.size());
Array3<double> vTemp(v.size());
Array3<double> wTemp(w.size());
Array3<char> uMarker(u.size(), 1);
Array3<char> vMarker(v.size(), 1);
Array3<char> wMarker(w.size(), 1);
Vector3D h = velocity->gridSpacing();
// Assign collider's velocity first and initialize markers
velocity->parallelForEachUIndex([&](size_t i, size_t j, size_t k) {
Vector3D pt = uPos(i, j, k);
double phi0 = _colliderSdf.sample(pt - Vector3D(0.5 * h.x, 0.0, 0.0));
double phi1 = _colliderSdf.sample(pt + Vector3D(0.5 * h.x, 0.0, 0.0));
double frac = fractionInsideSdf(phi0, phi1);
frac = 1.0 - clamp(frac, 0.0, 1.0);
if (frac > 0.0) {
uMarker(i, j, k) = 1;
} else {
Vector3D colliderVel = collider()->velocityAt(pt);
u(i, j, k) = colliderVel.x;
uMarker(i, j, k) = 0;
}
});
velocity->parallelForEachVIndex([&](size_t i, size_t j, size_t k) {
Vector3D pt = vPos(i, j, k);
double phi0 = _colliderSdf.sample(pt - Vector3D(0.0, 0.5 * h.y, 0.0));
double phi1 = _colliderSdf.sample(pt + Vector3D(0.0, 0.5 * h.y, 0.0));
double frac = fractionInsideSdf(phi0, phi1);
frac = 1.0 - clamp(frac, 0.0, 1.0);
if (frac > 0.0) {
vMarker(i, j, k) = 1;
} else {
Vector3D colliderVel = collider()->velocityAt(pt);
v(i, j, k) = colliderVel.y;
vMarker(i, j, k) = 0;
}
});
velocity->parallelForEachWIndex([&](size_t i, size_t j, size_t k) {
Vector3D pt = wPos(i, j, k);
double phi0 = _colliderSdf.sample(pt - Vector3D(0.0, 0.0, 0.5 * h.z));
double phi1 = _colliderSdf.sample(pt + Vector3D(0.0, 0.0, 0.5 * h.z));
double frac = fractionInsideSdf(phi0, phi1);
frac = 1.0 - clamp(frac, 0.0, 1.0);
if (frac > 0.0) {
wMarker(i, j, k) = 1;
} else {
Vector3D colliderVel = collider()->velocityAt(pt);
w(i, j, k) = colliderVel.z;
wMarker(i, j, k) = 0;
}
});
// Free-slip: Extrapolate fluid velocity into the collider
extrapolateToRegion(
velocity->uConstAccessor(), uMarker, extrapolationDepth, u);
extrapolateToRegion(
velocity->vConstAccessor(), vMarker, extrapolationDepth, v);
extrapolateToRegion(
velocity->wConstAccessor(), wMarker, extrapolationDepth, w);
// No-flux: project the extrapolated velocity to the collider's surface
// normal
velocity->parallelForEachUIndex([&](size_t i, size_t j, size_t k) {
Vector3D pt = uPos(i, j, k);
if (isInsideSdf(_colliderSdf.sample(pt))) {
Vector3D colliderVel = collider()->velocityAt(pt);
Vector3D vel = velocity->sample(pt);
Vector3D g = _colliderSdf.gradient(pt);
if (g.lengthSquared() > 0.0) {
Vector3D n = g.normalized();
Vector3D velr = vel - colliderVel;
Vector3D velt = projectAndApplyFriction(
velr, n, collider()->frictionCoefficient());
Vector3D velp = velt + colliderVel;
uTemp(i, j, k) = velp.x;
} else {
uTemp(i, j, k) = colliderVel.x;
}
} else {
uTemp(i, j, k) = u(i, j, k);
}
});
velocity->parallelForEachVIndex([&](size_t i, size_t j, size_t k) {
Vector3D pt = vPos(i, j, k);
if (isInsideSdf(_colliderSdf.sample(pt))) {
Vector3D colliderVel = collider()->velocityAt(pt);
Vector3D vel = velocity->sample(pt);
Vector3D g = _colliderSdf.gradient(pt);
if (g.lengthSquared() > 0.0) {
Vector3D n = g.normalized();
Vector3D velr = vel - colliderVel;
Vector3D velt = projectAndApplyFriction(
velr, n, collider()->frictionCoefficient());
Vector3D velp = velt + colliderVel;
vTemp(i, j, k) = velp.y;
} else {
vTemp(i, j, k) = colliderVel.y;
}
} else {
vTemp(i, j, k) = v(i, j, k);
}
});
velocity->parallelForEachWIndex([&](size_t i, size_t j, size_t k) {
Vector3D pt = wPos(i, j, k);
if (isInsideSdf(_colliderSdf.sample(pt))) {
Vector3D colliderVel = collider()->velocityAt(pt);
Vector3D vel = velocity->sample(pt);
Vector3D g = _colliderSdf.gradient(pt);
if (g.lengthSquared() > 0.0) {
Vector3D n = g.normalized();
Vector3D velr = vel - colliderVel;
Vector3D velt = projectAndApplyFriction(
velr, n, collider()->frictionCoefficient());
Vector3D velp = velt + colliderVel;
wTemp(i, j, k) = velp.z;
} else {
wTemp(i, j, k) = colliderVel.z;
}
} else {
wTemp(i, j, k) = w(i, j, k);
}
});
// Transfer results
u.parallelForEachIndex([&](size_t i, size_t j, size_t k) {
u(i, j, k) = uTemp(i, j, k);
});
v.parallelForEachIndex([&](size_t i, size_t j, size_t k) {
v(i, j, k) = vTemp(i, j, k);
});
w.parallelForEachIndex([&](size_t i, size_t j, size_t k) {
w(i, j, k) = wTemp(i, j, k);
});
// No-flux: Project velocity on the domain boundary if closed
if (closedDomainBoundaryFlag() & kDirectionLeft) {
for (size_t k = 0; k < u.size().z; ++k) {
for (size_t j = 0; j < u.size().y; ++j) {
u(0, j, k) = 0;
}
}
}
if (closedDomainBoundaryFlag() & kDirectionRight) {
for (size_t k = 0; k < u.size().z; ++k) {
for (size_t j = 0; j < u.size().y; ++j) {
u(u.size().x - 1, j, k) = 0;
}
}
}
if (closedDomainBoundaryFlag() & kDirectionDown) {
for (size_t k = 0; k < v.size().z; ++k) {
for (size_t i = 0; i < v.size().x; ++i) {
v(i, 0, k) = 0;
}
}
}
if (closedDomainBoundaryFlag() & kDirectionUp) {
for (size_t k = 0; k < v.size().z; ++k) {
for (size_t i = 0; i < v.size().x; ++i) {
v(i, v.size().y - 1, k) = 0;
}
}
}
if (closedDomainBoundaryFlag() & kDirectionBack) {
for (size_t j = 0; j < w.size().y; ++j) {
for (size_t i = 0; i < w.size().x; ++i) {
w(i, j, 0) = 0;
}
}
}
if (closedDomainBoundaryFlag() & kDirectionFront) {
for (size_t j = 0; j < w.size().y; ++j) {
for (size_t i = 0; i < w.size().x; ++i) {
w(i, j, w.size().z - 1) = 0;
}
}
}
}
const CellCenteredScalarGrid3&
GridFractionalBoundaryConditionSolver3::colliderSdf() const {
return _colliderSdf;
}
void GridFractionalBoundaryConditionSolver3::onColliderUpdated(
const Size3& gridSize,
const Vector3D& gridSpacing,
const Vector3D& gridOrigin) {
_colliderSdf.resize(gridSize, gridSpacing, gridOrigin);
if (collider() != nullptr) {
Surface3Ptr surface = collider()->surface();
ImplicitSurface3Ptr implicitSurface
= std::dynamic_pointer_cast<ImplicitSurface3>(surface);
if (implicitSurface == nullptr) {
implicitSurface = std::make_shared<SurfaceToImplicit3>(surface);
}
_colliderSdf.fill([&](const Vector3D& pt) {
return implicitSurface->signedDistance(pt);
});
} else {
_colliderSdf.fill(kMaxD);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: opostponedtruncationstream.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-10-19 14:34:37 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SFX_OPOSTPONEDTRUNCATIONFILESTREAM_HXX
#define _SFX_OPOSTPONEDTRUNCATIONFILESTREAM_HXX
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_
#include <com/sun/star/io/XSeekable.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XTRUNCATE_HPP_
#include <com/sun/star/io/XTruncate.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_
#include <com/sun/star/io/XStream.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XTRANSACTEDOBJECT_HPP_
#include <com/sun/star/embed/XTransactedObject.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XSIMPLEFILEACCESS_HPP_
#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XASYNCOUTPUTMONITOR_HPP_
#include <com/sun/star/io/XAsyncOutputMonitor.hpp>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE6_HXX_
#include <cppuhelper/implbase6.hxx>
#endif
#ifndef INCLUDED_SFX2_DLLAPI_H
#include "sfx2/dllapi.h"
#endif
//==================================================================
// OPostponedTruncationFileStream
//
// Allows to get stream access to a file, where the first truncation
// of the file is postponed till the first writing. If no writing happens
// after the first truncation/creation, it has no effect. ( The postponing of
// the creation can be switched off during initialization. Here the postponing
// of the creation means that the file will be created immediatelly, but
// if nothing is written into it, it will be removed during destruction
// of the object. )
//
// On creation of this object the target file is scheduled for
// creation/truncation. But the action happens only during the first
// write access. After the first write access the object behaves
// itself as the original stream.
//==================================================================
struct PTFStreamData_Impl;
class SFX2_DLLPUBLIC OPostponedTruncationFileStream
: public ::cppu::WeakImplHelper6 <
::com::sun::star::io::XStream,
::com::sun::star::io::XInputStream,
::com::sun::star::io::XOutputStream,
::com::sun::star::io::XTruncate,
::com::sun::star::io::XSeekable,
::com::sun::star::io::XAsyncOutputMonitor >
{
::osl::Mutex m_aMutex;
PTFStreamData_Impl* m_pStreamData;
void CloseAll_Impl();
void CheckScheduledTruncation_Impl();
public:
OPostponedTruncationFileStream(
const ::rtl::OUString& aURL,
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory,
const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess >& xFileAccess,
sal_Bool bDeleteNewIfNotWritten );
~OPostponedTruncationFileStream();
// com::sun::star::io::XStream
virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > SAL_CALL getOutputStream( ) throw (::com::sun::star::uno::RuntimeException);
// com::sun::star::io::XInputStream
virtual ::sal_Int32 SAL_CALL readBytes( ::com::sun::star::uno::Sequence< ::sal_Int8 >& aData, ::sal_Int32 nBytesToRead ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual ::sal_Int32 SAL_CALL readSomeBytes( ::com::sun::star::uno::Sequence< ::sal_Int8 >& aData, ::sal_Int32 nMaxBytesToRead ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL skipBytes( ::sal_Int32 nBytesToSkip ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual ::sal_Int32 SAL_CALL available( ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL closeInput( ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
// com::sun::star::io::XOutputStream
virtual void SAL_CALL writeBytes( const ::com::sun::star::uno::Sequence< ::sal_Int8 >& aData ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL flush( ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL closeOutput( ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
// com::sun::star::io::XTruncate
virtual void SAL_CALL truncate( ) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
// com::sun::star::io::XSeekable
virtual void SAL_CALL seek( ::sal_Int64 location ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual ::sal_Int64 SAL_CALL getPosition( ) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual ::sal_Int64 SAL_CALL getLength( ) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::io::XAsyncOutputMonitor
virtual void SAL_CALL waitForCompletion( ) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
};
#endif //_SFX_OPOSTPONEDTRUNCATIONFILESTREAM_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.3.710); FILE MERGED 2008/04/01 15:39:21 thb 1.3.710.3: #i85898# Stripping all external header guards 2008/04/01 12:40:49 thb 1.3.710.2: #i85898# Stripping all external header guards 2008/03/31 13:38:29 rt 1.3.710.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: opostponedtruncationstream.hxx,v $
* $Revision: 1.4 $
*
* 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 _SFX_OPOSTPONEDTRUNCATIONFILESTREAM_HXX
#define _SFX_OPOSTPONEDTRUNCATIONFILESTREAM_HXX
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XSeekable.hpp>
#include <com/sun/star/io/XTruncate.hpp>
#include <com/sun/star/io/XStream.hpp>
#include <com/sun/star/embed/XTransactedObject.hpp>
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#include <com/sun/star/io/XAsyncOutputMonitor.hpp>
#include <osl/mutex.hxx>
#include <cppuhelper/implbase6.hxx>
#include "sfx2/dllapi.h"
//==================================================================
// OPostponedTruncationFileStream
//
// Allows to get stream access to a file, where the first truncation
// of the file is postponed till the first writing. If no writing happens
// after the first truncation/creation, it has no effect. ( The postponing of
// the creation can be switched off during initialization. Here the postponing
// of the creation means that the file will be created immediatelly, but
// if nothing is written into it, it will be removed during destruction
// of the object. )
//
// On creation of this object the target file is scheduled for
// creation/truncation. But the action happens only during the first
// write access. After the first write access the object behaves
// itself as the original stream.
//==================================================================
struct PTFStreamData_Impl;
class SFX2_DLLPUBLIC OPostponedTruncationFileStream
: public ::cppu::WeakImplHelper6 <
::com::sun::star::io::XStream,
::com::sun::star::io::XInputStream,
::com::sun::star::io::XOutputStream,
::com::sun::star::io::XTruncate,
::com::sun::star::io::XSeekable,
::com::sun::star::io::XAsyncOutputMonitor >
{
::osl::Mutex m_aMutex;
PTFStreamData_Impl* m_pStreamData;
void CloseAll_Impl();
void CheckScheduledTruncation_Impl();
public:
OPostponedTruncationFileStream(
const ::rtl::OUString& aURL,
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory,
const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess >& xFileAccess,
sal_Bool bDeleteNewIfNotWritten );
~OPostponedTruncationFileStream();
// com::sun::star::io::XStream
virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > SAL_CALL getOutputStream( ) throw (::com::sun::star::uno::RuntimeException);
// com::sun::star::io::XInputStream
virtual ::sal_Int32 SAL_CALL readBytes( ::com::sun::star::uno::Sequence< ::sal_Int8 >& aData, ::sal_Int32 nBytesToRead ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual ::sal_Int32 SAL_CALL readSomeBytes( ::com::sun::star::uno::Sequence< ::sal_Int8 >& aData, ::sal_Int32 nMaxBytesToRead ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL skipBytes( ::sal_Int32 nBytesToSkip ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual ::sal_Int32 SAL_CALL available( ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL closeInput( ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
// com::sun::star::io::XOutputStream
virtual void SAL_CALL writeBytes( const ::com::sun::star::uno::Sequence< ::sal_Int8 >& aData ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL flush( ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL closeOutput( ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
// com::sun::star::io::XTruncate
virtual void SAL_CALL truncate( ) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
// com::sun::star::io::XSeekable
virtual void SAL_CALL seek( ::sal_Int64 location ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual ::sal_Int64 SAL_CALL getPosition( ) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual ::sal_Int64 SAL_CALL getLength( ) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::io::XAsyncOutputMonitor
virtual void SAL_CALL waitForCompletion( ) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
};
#endif //_SFX_OPOSTPONEDTRUNCATIONFILESTREAM_HXX
<|endoftext|> |
<commit_before>/*
* Copyright 2016-2019 libfptu authors: please see AUTHORS file.
*
* This file is part of libfptu, aka "Fast Positive Tuples".
*
* libfptu 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.
*
* libfptu 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 libfptu. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../fptu_test.h"
#include "fast_positive/details/cpu_features.h"
#include <array>
#include <vector>
#include "fast_positive/details/warnings_push_pt.h"
//------------------------------------------------------------------------------
#pragma pack(push, 1)
struct Foo {
char x;
int Bar;
};
#pragma pack(pop)
struct MyToken_FooBar_int : public FPTU_TOKEN(Foo, Bar) {
MyToken_FooBar_int() noexcept {
static_assert(static_offset == 1, "WTF?");
static_assert(std::is_base_of<::fptu::details::token_static_tag,
MyToken_FooBar_int>::value,
"WTF?");
static_assert(MyToken_FooBar_int::is_static_token::value, "WTF?");
}
};
FPTU_TEMPLATE_FOR_STATIC_TOKEN
bool probe2static(const TOKEN &token) {
(void)token;
return true;
}
bool probe2static(const fptu::token &token) {
(void)token;
return false;
}
TEST(Token, StaticPreplaced) {
MyToken_FooBar_int token;
EXPECT_TRUE(token.is_preplaced());
EXPECT_FALSE(token.is_loose());
EXPECT_FALSE(token.is_inlay());
EXPECT_FALSE(token.is_collection());
EXPECT_EQ(fptu::genus::i32, token.type());
EXPECT_TRUE(probe2static(token));
EXPECT_TRUE(MyToken_FooBar_int::is_static_preplaced());
EXPECT_TRUE(MyToken_FooBar_int::is_static_token::value);
#ifndef __clang__
const fptu::tuple_ro_weak tuple_ro;
/* FIXME: CLANG ?-6-7-8 WTF? */
EXPECT_THROW(tuple_ro.collection(token).empty(), ::fptu::collection_required);
#endif
}
#ifdef __clang__
TEST(clang_WTF, DISABLED_ExceptionHandling) {
#else
TEST(clang_WTF, ExceptionHandling) {
#endif
try {
bool got_collection_required_exception = false;
try {
// fptu::throw_collection_required();
const fptu::tuple_ro_weak tuple_ro;
MyToken_FooBar_int token;
tuple_ro.collection(token).empty();
} catch (const ::fptu::collection_required &) {
got_collection_required_exception = true;
}
EXPECT_TRUE(got_collection_required_exception);
} catch (const ::std::exception &e) {
std::string msg = fptu::format("Unexpected exception type '%s': %s",
typeid(e).name(), e.what());
GTEST_FATAL_FAILURE_(msg.c_str());
} catch (...) {
GTEST_FATAL_FAILURE_("Unknown NOT std::exception");
}
}
//------------------------------------------------------------------------------
TEST(Smoke, trivia_set) {
fptu::tuple_rw_managed rw;
fptu::token token(fptu::u16, 0);
rw.set_u16(token, 42);
auto value = rw.get_u16(token);
EXPECT_EQ(42, value);
}
TEST(Smoke, trivia_autogrowth) {
fptu::tuple_rw_managed rw;
fptu::token token(fptu::text, 0, true);
EXPECT_GT(size_t(fptu::max_tuple_bytes_netto), rw.capacity());
for (int i = 1; i < 555; ++i)
rw.insert_string(token,
fptu::format("This is the string #%*d.", i - 555, i));
EXPECT_EQ(size_t(fptu::max_tuple_bytes_netto), rw.capacity());
}
TEST(Smoke, trivia_managing) {
cxx14_constexpr fptu::token token_utc32(fptu::genus::datetime_utc, 0);
cxx14_constexpr fptu::token token_datetime64(fptu::genus::datetime_utc, 0);
cxx14_constexpr fptu::token token_i64(fptu::i64, 0);
fptu::tuple_rw_fixed rw_fixed;
rw_fixed.set_datetime(token_utc32, fptu::datetime_t::now());
rw_fixed.set_datetime(token_utc32, fptu::datetime_t::now_coarse());
rw_fixed.set_datetime(token_datetime64, fptu::datetime_t::now_fine());
rw_fixed.set_integer(token_i64, INT64_MIN);
rw_fixed.set_integer(token_i64, INT64_MAX);
fptu::tuple_ro_weak ro_weak = rw_fixed.take_weak().first;
EXPECT_FALSE(ro_weak.empty());
EXPECT_TRUE(ro_weak.is_present(token_utc32));
EXPECT_TRUE(ro_weak.is_present(token_datetime64));
EXPECT_TRUE(ro_weak.is_present(token_i64));
fptu::tuple_ro_managed ro_managed = rw_fixed.take_managed_clone().first;
EXPECT_EQ(ro_weak.size(), ro_managed.size());
EXPECT_EQ(0,
std::memcmp(ro_weak.data(), ro_managed.data(), ro_managed.size()));
ro_managed = rw_fixed.move_to_ro();
EXPECT_EQ(ro_weak.size(), ro_managed.size());
EXPECT_EQ(0,
std::memcmp(ro_weak.data(), ro_managed.data(), ro_managed.size()));
rw_fixed = std::move(ro_managed);
ro_managed = rw_fixed.take_managed_clone().first;
EXPECT_EQ(ro_weak.size(), ro_managed.size());
EXPECT_EQ(0,
std::memcmp(ro_weak.data(), ro_managed.data(), ro_managed.size()));
rw_fixed = fptu::tuple_rw_fixed::clone(ro_managed);
ro_weak = rw_fixed.take_weak().first;
EXPECT_EQ(ro_weak.size(), ro_managed.size());
EXPECT_EQ(0,
std::memcmp(ro_weak.data(), ro_managed.data(), ro_managed.size()));
rw_fixed = fptu::tuple_rw_fixed::clone(ro_weak);
ro_weak = rw_fixed.take_weak().first;
EXPECT_EQ(ro_weak.size(), ro_managed.size());
EXPECT_EQ(0,
std::memcmp(ro_weak.data(), ro_managed.data(), ro_managed.size()));
EXPECT_EQ(1, ro_managed.get_buffer()->ref_counter);
auto ro_managed2 = ro_managed;
EXPECT_EQ(2, ro_managed.get_buffer()->ref_counter);
ro_managed.purge();
EXPECT_FALSE(ro_managed);
EXPECT_EQ(1, ro_managed2.get_buffer()->ref_counter);
}
//------------------------------------------------------------------------------
TEST(Smoke, trivia_schema_definition) {
auto schema = fptu::schema::create();
for (unsigned n = 0; n < 42; ++n)
for (fptu::genus type = fptu::genus(0); type != fptu::genus::hole;
type = fptu::genus(type + 1))
schema->define_field(
false, fptu::format("#%u of %s", n, std::to_string(type).c_str()),
type);
std::set<std::string> names = {"datafield1", "event_src.host",
"event_src.ip", "event_src.title",
"generator", "id",
"mime", "object.name",
"reason", "subject.group",
"subject.id", "tag",
"type"};
for (auto item : names)
schema->define_field(item == "generator", std::move(item),
fptu::genus::text);
fptu::defaults::setup(fptu::initiation_scale::small, std::move(schema));
fptu::tuple_rw_managed rw;
rw.set_string(fptu::defaults::schema->get_token("datafield1"),
std::string("229099411"));
rw.set_string(fptu::defaults::schema->get_token("event_src.host"),
std::string("91.142.135.113"));
rw.set_string(fptu::defaults::schema->get_token("event_src.ip"),
std::string("91.142.135.113"));
rw.set_string(fptu::defaults::schema->get_token("event_src.title"),
std::string("unix_like"));
rw.set_string(fptu::defaults::schema->get_token("generator"),
std::string("N8.0.1309"));
rw.set_string(fptu::defaults::schema->get_token("id"),
std::string("PT_UNIX_like_auditd_syslog_path_msg"));
rw.set_string(fptu::defaults::schema->get_token("mime"),
std::string("text/plain"));
rw.set_string(fptu::defaults::schema->get_token("object.name"),
std::string("/proc/1/comm"));
rw.set_string(fptu::defaults::schema->get_token("reason"),
std::string("File was created or deleted"));
rw.set_string(fptu::defaults::schema->get_token("subject.group"),
std::string("0"));
rw.set_string(fptu::defaults::schema->get_token("subject.id"),
std::string("0"));
rw.set_string(fptu::defaults::schema->get_token("tag"),
std::string("syslog"));
rw.set_string(fptu::defaults::schema->get_token("type"), std::string("norm"));
rw.take_managed_clone_optimized();
}
//------------------------------------------------------------------------------
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>fptu-tests: add smoke-autogrowth_with_preplaced.<commit_after>/*
* Copyright 2016-2019 libfptu authors: please see AUTHORS file.
*
* This file is part of libfptu, aka "Fast Positive Tuples".
*
* libfptu 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.
*
* libfptu 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 libfptu. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../fptu_test.h"
#include "fast_positive/details/cpu_features.h"
#include <array>
#include <vector>
#include "fast_positive/details/warnings_push_pt.h"
//------------------------------------------------------------------------------
#pragma pack(push, 1)
struct Foo {
char x;
int Bar;
};
#pragma pack(pop)
struct MyToken_FooBar_int : public FPTU_TOKEN(Foo, Bar) {
MyToken_FooBar_int() noexcept {
static_assert(static_offset == 1, "WTF?");
static_assert(std::is_base_of<::fptu::details::token_static_tag,
MyToken_FooBar_int>::value,
"WTF?");
static_assert(MyToken_FooBar_int::is_static_token::value, "WTF?");
}
};
FPTU_TEMPLATE_FOR_STATIC_TOKEN
bool probe2static(const TOKEN &token) {
(void)token;
return true;
}
bool probe2static(const fptu::token &token) {
(void)token;
return false;
}
TEST(Token, StaticPreplaced) {
MyToken_FooBar_int token;
EXPECT_TRUE(token.is_preplaced());
EXPECT_FALSE(token.is_loose());
EXPECT_FALSE(token.is_inlay());
EXPECT_FALSE(token.is_collection());
EXPECT_EQ(fptu::genus::i32, token.type());
EXPECT_TRUE(probe2static(token));
EXPECT_TRUE(MyToken_FooBar_int::is_static_preplaced());
EXPECT_TRUE(MyToken_FooBar_int::is_static_token::value);
#ifndef __clang__
const fptu::tuple_ro_weak tuple_ro;
/* FIXME: CLANG ?-6-7-8 WTF? */
EXPECT_THROW(tuple_ro.collection(token).empty(), ::fptu::collection_required);
#endif
}
#ifdef __clang__
TEST(clang_WTF, DISABLED_ExceptionHandling) {
#else
TEST(clang_WTF, ExceptionHandling) {
#endif
try {
bool got_collection_required_exception = false;
try {
// fptu::throw_collection_required();
const fptu::tuple_ro_weak tuple_ro;
MyToken_FooBar_int token;
tuple_ro.collection(token).empty();
} catch (const ::fptu::collection_required &) {
got_collection_required_exception = true;
}
EXPECT_TRUE(got_collection_required_exception);
} catch (const ::std::exception &e) {
std::string msg = fptu::format("Unexpected exception type '%s': %s",
typeid(e).name(), e.what());
GTEST_FATAL_FAILURE_(msg.c_str());
} catch (...) {
GTEST_FATAL_FAILURE_("Unknown NOT std::exception");
}
}
//------------------------------------------------------------------------------
TEST(Smoke, trivia_set) {
fptu::tuple_rw_managed rw;
fptu::token token(fptu::u16, 0);
rw.set_u16(token, 42);
auto value = rw.get_u16(token);
EXPECT_EQ(42, value);
}
TEST(Smoke, trivia_autogrowth) {
fptu::tuple_rw_managed rw;
fptu::token token(fptu::text, 0, true);
EXPECT_GT(size_t(fptu::max_tuple_bytes_netto), rw.capacity());
for (int i = 1; i < 555; ++i)
rw.insert_string(token,
fptu::format("This is the string #%*d.", i - 555, i));
EXPECT_EQ(size_t(fptu::max_tuple_bytes_netto), rw.capacity());
}
TEST(Smoke, autogrowth_with_preplaced) {
auto schema = fptu::schema::create();
std::vector<std::pair<std::string, std::size_t>> values = {
{"event_src.host", 16},
{"event_src.hostname", 16},
{"event_src.subsys", 8},
{"event_src.title", 7},
{"event_src.vendor", 9}, /*{"generator", 9},*/
{"id", 53},
{"mime", 25},
{"msgid", 4},
{"object.id", 1037}};
for (auto p : values)
schema->define_loose(std::move(p.first), fptu::genus::text);
schema->define_preplaced("generator", fptu::genus::text);
fptu::defaults::setup(fptu::initiation_scale::small, std::move(schema));
fptu::tuple_rw_managed rw;
for (auto p : values) {
std::string stub{};
stub.resize(p.second, 'a');
rw.set_string(fptu::defaults::schema->get_token(p.first.data()), stub);
}
rw.take_managed_clone_optimized();
}
TEST(Smoke, trivia_managing) {
cxx14_constexpr fptu::token token_utc32(fptu::genus::datetime_utc, 0);
cxx14_constexpr fptu::token token_datetime64(fptu::genus::datetime_utc, 0);
cxx14_constexpr fptu::token token_i64(fptu::i64, 0);
fptu::tuple_rw_fixed rw_fixed;
rw_fixed.set_datetime(token_utc32, fptu::datetime_t::now());
rw_fixed.set_datetime(token_utc32, fptu::datetime_t::now_coarse());
rw_fixed.set_datetime(token_datetime64, fptu::datetime_t::now_fine());
rw_fixed.set_integer(token_i64, INT64_MIN);
rw_fixed.set_integer(token_i64, INT64_MAX);
fptu::tuple_ro_weak ro_weak = rw_fixed.take_weak().first;
EXPECT_FALSE(ro_weak.empty());
EXPECT_TRUE(ro_weak.is_present(token_utc32));
EXPECT_TRUE(ro_weak.is_present(token_datetime64));
EXPECT_TRUE(ro_weak.is_present(token_i64));
fptu::tuple_ro_managed ro_managed = rw_fixed.take_managed_clone().first;
EXPECT_EQ(ro_weak.size(), ro_managed.size());
EXPECT_EQ(0,
std::memcmp(ro_weak.data(), ro_managed.data(), ro_managed.size()));
ro_managed = rw_fixed.move_to_ro();
EXPECT_EQ(ro_weak.size(), ro_managed.size());
EXPECT_EQ(0,
std::memcmp(ro_weak.data(), ro_managed.data(), ro_managed.size()));
rw_fixed = std::move(ro_managed);
ro_managed = rw_fixed.take_managed_clone().first;
EXPECT_EQ(ro_weak.size(), ro_managed.size());
EXPECT_EQ(0,
std::memcmp(ro_weak.data(), ro_managed.data(), ro_managed.size()));
rw_fixed = fptu::tuple_rw_fixed::clone(ro_managed);
ro_weak = rw_fixed.take_weak().first;
EXPECT_EQ(ro_weak.size(), ro_managed.size());
EXPECT_EQ(0,
std::memcmp(ro_weak.data(), ro_managed.data(), ro_managed.size()));
rw_fixed = fptu::tuple_rw_fixed::clone(ro_weak);
ro_weak = rw_fixed.take_weak().first;
EXPECT_EQ(ro_weak.size(), ro_managed.size());
EXPECT_EQ(0,
std::memcmp(ro_weak.data(), ro_managed.data(), ro_managed.size()));
EXPECT_EQ(1, ro_managed.get_buffer()->ref_counter);
auto ro_managed2 = ro_managed;
EXPECT_EQ(2, ro_managed.get_buffer()->ref_counter);
ro_managed.purge();
EXPECT_FALSE(ro_managed);
EXPECT_EQ(1, ro_managed2.get_buffer()->ref_counter);
}
//------------------------------------------------------------------------------
TEST(Smoke, trivia_schema_definition) {
auto schema = fptu::schema::create();
for (unsigned n = 0; n < 42; ++n)
for (fptu::genus type = fptu::genus(0); type != fptu::genus::hole;
type = fptu::genus(type + 1))
schema->define_field(
false, fptu::format("#%u of %s", n, std::to_string(type).c_str()),
type);
std::set<std::string> names = {"datafield1", "event_src.host",
"event_src.ip", "event_src.title",
"generator", "id",
"mime", "object.name",
"reason", "subject.group",
"subject.id", "tag",
"type"};
for (auto item : names)
schema->define_field(item == "generator", std::move(item),
fptu::genus::text);
fptu::defaults::setup(fptu::initiation_scale::small, std::move(schema));
fptu::tuple_rw_managed rw;
rw.set_string(fptu::defaults::schema->get_token("datafield1"),
std::string("229099411"));
rw.set_string(fptu::defaults::schema->get_token("event_src.host"),
std::string("91.142.135.113"));
rw.set_string(fptu::defaults::schema->get_token("event_src.ip"),
std::string("91.142.135.113"));
rw.set_string(fptu::defaults::schema->get_token("event_src.title"),
std::string("unix_like"));
rw.set_string(fptu::defaults::schema->get_token("generator"),
std::string("N8.0.1309"));
rw.set_string(fptu::defaults::schema->get_token("id"),
std::string("PT_UNIX_like_auditd_syslog_path_msg"));
rw.set_string(fptu::defaults::schema->get_token("mime"),
std::string("text/plain"));
rw.set_string(fptu::defaults::schema->get_token("object.name"),
std::string("/proc/1/comm"));
rw.set_string(fptu::defaults::schema->get_token("reason"),
std::string("File was created or deleted"));
rw.set_string(fptu::defaults::schema->get_token("subject.group"),
std::string("0"));
rw.set_string(fptu::defaults::schema->get_token("subject.id"),
std::string("0"));
rw.set_string(fptu::defaults::schema->get_token("tag"),
std::string("syslog"));
rw.set_string(fptu::defaults::schema->get_token("type"), std::string("norm"));
rw.take_managed_clone_optimized();
}
//------------------------------------------------------------------------------
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Gael Guennebaud <[email protected]>
//
// Eigen 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 3 of the License, or (at your option) any later version.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
template<int OtherSize> struct symm_extra {
template<typename M1, typename M2, typename Scalar>
static void run(M1& m1, M1& m2, M2& rhs2, M2& rhs22, M2& rhs23, Scalar s1, Scalar s2)
{
m2 = m1.template triangularView<Lower>();
VERIFY_IS_APPROX(rhs22 = (rhs2) * (m2).template selfadjointView<Lower>(),
rhs23 = (rhs2) * (m1));
VERIFY_IS_APPROX(rhs22 = (s2*rhs2) * (s1*m2).template selfadjointView<Lower>(),
rhs23 = (s2*rhs2) * (s1*m1));
}
};
template<> struct symm_extra<1> {
template<typename M1, typename M2, typename Scalar>
static void run(M1&, M1&, M2&, M2&, M2&, Scalar, Scalar) {}
};
template<typename Scalar, int Size, int OtherSize> void symm(int size = Size, int othersize = OtherSize)
{
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Matrix<Scalar, Size, Size> MatrixType;
typedef Matrix<Scalar, Size, OtherSize> Rhs1;
typedef Matrix<Scalar, OtherSize, Size> Rhs2;
enum { order = OtherSize==1 ? 0 : RowMajor };
typedef Matrix<Scalar, Size, OtherSize,order> Rhs3;
typedef MatrixType::Index Index;
Index rows = size;
Index cols = size;
MatrixType m1 = MatrixType::Random(rows, cols),
m2 = MatrixType::Random(rows, cols), m3;
m1 = (m1+m1.adjoint()).eval();
Rhs1 rhs1 = Rhs1::Random(cols, othersize), rhs12(cols, othersize), rhs13(cols, othersize);
Rhs2 rhs2 = Rhs2::Random(othersize, rows), rhs22(othersize, rows), rhs23(othersize, rows);
Rhs3 rhs3 = Rhs3::Random(cols, othersize), rhs32(cols, othersize), rhs33(cols, othersize);
Scalar s1 = ei_random<Scalar>(),
s2 = ei_random<Scalar>();
m2 = m1.template triangularView<Lower>();
m3 = m2.template selfadjointView<Lower>();
VERIFY_IS_EQUAL(m1, m3);
VERIFY_IS_APPROX(rhs12 = (s1*m2).template selfadjointView<Lower>() * (s2*rhs1),
rhs13 = (s1*m1) * (s2*rhs1));
m2 = m1.template triangularView<Upper>(); rhs12.setRandom(); rhs13 = rhs12;
m3 = m2.template selfadjointView<Upper>();
VERIFY_IS_EQUAL(m1, m3);
VERIFY_IS_APPROX(rhs12 += (s1*m2).template selfadjointView<Upper>() * (s2*rhs1),
rhs13 += (s1*m1) * (s2*rhs1));
m2 = m1.template triangularView<Lower>();
VERIFY_IS_APPROX(rhs12 = (s1*m2).template selfadjointView<Lower>() * (s2*rhs2.adjoint()),
rhs13 = (s1*m1) * (s2*rhs2.adjoint()));
m2 = m1.template triangularView<Upper>();
VERIFY_IS_APPROX(rhs12 = (s1*m2).template selfadjointView<Upper>() * (s2*rhs2.adjoint()),
rhs13 = (s1*m1) * (s2*rhs2.adjoint()));
m2 = m1.template triangularView<Upper>();
VERIFY_IS_APPROX(rhs12 = (s1*m2.adjoint()).template selfadjointView<Lower>() * (s2*rhs2.adjoint()),
rhs13 = (s1*m1.adjoint()) * (s2*rhs2.adjoint()));
// test row major = <...>
m2 = m1.template triangularView<Lower>(); rhs12.setRandom(); rhs13 = rhs12;
VERIFY_IS_APPROX(rhs12 -= (s1*m2).template selfadjointView<Lower>() * (s2*rhs3),
rhs13 -= (s1*m1) * (s2 * rhs3));
m2 = m1.template triangularView<Upper>();
VERIFY_IS_APPROX(rhs12 = (s1*m2.adjoint()).template selfadjointView<Lower>() * (s2*rhs3).conjugate(),
rhs13 = (s1*m1.adjoint()) * (s2*rhs3).conjugate());
m2 = m1.template triangularView<Upper>(); rhs13 = rhs12;
VERIFY_IS_APPROX(rhs12.noalias() += s1 * ((m2.adjoint()).template selfadjointView<Lower>() * (s2*rhs3).conjugate()),
rhs13 += (s1*m1.adjoint()) * (s2*rhs3).conjugate());
// test matrix * selfadjoint
symm_extra<OtherSize>::run(m1,m2,rhs2,rhs22,rhs23,s1,s2);
}
void test_product_symm()
{
for(int i = 0; i < g_repeat ; i++)
{
CALL_SUBTEST_1(( symm<float,Dynamic,Dynamic>(ei_random<int>(10,320),ei_random<int>(10,320)) ));
CALL_SUBTEST_2(( symm<double,Dynamic,Dynamic>(ei_random<int>(10,320),ei_random<int>(10,320)) ));
CALL_SUBTEST_3(( symm<std::complex<double>,Dynamic,Dynamic>(ei_random<int>(10,320),ei_random<int>(10,320)) ));
CALL_SUBTEST_4(( symm<float,Dynamic,1>(ei_random<int>(10,320)) ));
CALL_SUBTEST_5(( symm<double,Dynamic,1>(ei_random<int>(10,320)) ));
CALL_SUBTEST_6(( symm<std::complex<double>,Dynamic,1>(ei_random<int>(10,320)) ));
}
}
<commit_msg>add missing typename<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Gael Guennebaud <[email protected]>
//
// Eigen 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 3 of the License, or (at your option) any later version.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
template<int OtherSize> struct symm_extra {
template<typename M1, typename M2, typename Scalar>
static void run(M1& m1, M1& m2, M2& rhs2, M2& rhs22, M2& rhs23, Scalar s1, Scalar s2)
{
m2 = m1.template triangularView<Lower>();
VERIFY_IS_APPROX(rhs22 = (rhs2) * (m2).template selfadjointView<Lower>(),
rhs23 = (rhs2) * (m1));
VERIFY_IS_APPROX(rhs22 = (s2*rhs2) * (s1*m2).template selfadjointView<Lower>(),
rhs23 = (s2*rhs2) * (s1*m1));
}
};
template<> struct symm_extra<1> {
template<typename M1, typename M2, typename Scalar>
static void run(M1&, M1&, M2&, M2&, M2&, Scalar, Scalar) {}
};
template<typename Scalar, int Size, int OtherSize> void symm(int size = Size, int othersize = OtherSize)
{
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Matrix<Scalar, Size, Size> MatrixType;
typedef Matrix<Scalar, Size, OtherSize> Rhs1;
typedef Matrix<Scalar, OtherSize, Size> Rhs2;
enum { order = OtherSize==1 ? 0 : RowMajor };
typedef Matrix<Scalar, Size, OtherSize,order> Rhs3;
typedef typename MatrixType::Index Index;
Index rows = size;
Index cols = size;
MatrixType m1 = MatrixType::Random(rows, cols),
m2 = MatrixType::Random(rows, cols), m3;
m1 = (m1+m1.adjoint()).eval();
Rhs1 rhs1 = Rhs1::Random(cols, othersize), rhs12(cols, othersize), rhs13(cols, othersize);
Rhs2 rhs2 = Rhs2::Random(othersize, rows), rhs22(othersize, rows), rhs23(othersize, rows);
Rhs3 rhs3 = Rhs3::Random(cols, othersize), rhs32(cols, othersize), rhs33(cols, othersize);
Scalar s1 = ei_random<Scalar>(),
s2 = ei_random<Scalar>();
m2 = m1.template triangularView<Lower>();
m3 = m2.template selfadjointView<Lower>();
VERIFY_IS_EQUAL(m1, m3);
VERIFY_IS_APPROX(rhs12 = (s1*m2).template selfadjointView<Lower>() * (s2*rhs1),
rhs13 = (s1*m1) * (s2*rhs1));
m2 = m1.template triangularView<Upper>(); rhs12.setRandom(); rhs13 = rhs12;
m3 = m2.template selfadjointView<Upper>();
VERIFY_IS_EQUAL(m1, m3);
VERIFY_IS_APPROX(rhs12 += (s1*m2).template selfadjointView<Upper>() * (s2*rhs1),
rhs13 += (s1*m1) * (s2*rhs1));
m2 = m1.template triangularView<Lower>();
VERIFY_IS_APPROX(rhs12 = (s1*m2).template selfadjointView<Lower>() * (s2*rhs2.adjoint()),
rhs13 = (s1*m1) * (s2*rhs2.adjoint()));
m2 = m1.template triangularView<Upper>();
VERIFY_IS_APPROX(rhs12 = (s1*m2).template selfadjointView<Upper>() * (s2*rhs2.adjoint()),
rhs13 = (s1*m1) * (s2*rhs2.adjoint()));
m2 = m1.template triangularView<Upper>();
VERIFY_IS_APPROX(rhs12 = (s1*m2.adjoint()).template selfadjointView<Lower>() * (s2*rhs2.adjoint()),
rhs13 = (s1*m1.adjoint()) * (s2*rhs2.adjoint()));
// test row major = <...>
m2 = m1.template triangularView<Lower>(); rhs12.setRandom(); rhs13 = rhs12;
VERIFY_IS_APPROX(rhs12 -= (s1*m2).template selfadjointView<Lower>() * (s2*rhs3),
rhs13 -= (s1*m1) * (s2 * rhs3));
m2 = m1.template triangularView<Upper>();
VERIFY_IS_APPROX(rhs12 = (s1*m2.adjoint()).template selfadjointView<Lower>() * (s2*rhs3).conjugate(),
rhs13 = (s1*m1.adjoint()) * (s2*rhs3).conjugate());
m2 = m1.template triangularView<Upper>(); rhs13 = rhs12;
VERIFY_IS_APPROX(rhs12.noalias() += s1 * ((m2.adjoint()).template selfadjointView<Lower>() * (s2*rhs3).conjugate()),
rhs13 += (s1*m1.adjoint()) * (s2*rhs3).conjugate());
// test matrix * selfadjoint
symm_extra<OtherSize>::run(m1,m2,rhs2,rhs22,rhs23,s1,s2);
}
void test_product_symm()
{
for(int i = 0; i < g_repeat ; i++)
{
CALL_SUBTEST_1(( symm<float,Dynamic,Dynamic>(ei_random<int>(10,320),ei_random<int>(10,320)) ));
CALL_SUBTEST_2(( symm<double,Dynamic,Dynamic>(ei_random<int>(10,320),ei_random<int>(10,320)) ));
CALL_SUBTEST_3(( symm<std::complex<double>,Dynamic,Dynamic>(ei_random<int>(10,320),ei_random<int>(10,320)) ));
CALL_SUBTEST_4(( symm<float,Dynamic,1>(ei_random<int>(10,320)) ));
CALL_SUBTEST_5(( symm<double,Dynamic,1>(ei_random<int>(10,320)) ));
CALL_SUBTEST_6(( symm<std::complex<double>,Dynamic,1>(ei_random<int>(10,320)) ));
}
}
<|endoftext|> |
<commit_before>#include "enchanthighlighter.hh"
#include <enchant++.h>
#include <QDebug>
EnchantHighlighter::EnchantHighlighter(QTextDocument *parent) :
QSyntaxHighlighter(parent)
{
format.setUnderlineColor(QColor(Qt::red));
format.setUnderlineStyle(QTextCharFormat::SpellCheckUnderline);
}
EnchantHighlighter::~EnchantHighlighter() {}
void EnchantHighlighter::check(const QString &text, int begin, int i) {
QStringRef sub(&text, begin, i-begin);
auto ba = sub.toUtf8();
if(!dict->check(std::string {ba.data(), (std::string::size_type)ba.size()}))
setFormat(begin, i-begin, format);
}
void EnchantHighlighter::highlightBlock(const QString& text) {
if(!dict)
return;
int begin = 0;
int i = 0;
for(; i<text.length(); ++i) {
auto ch = text.at(i);
if(ch < 'A') {
if(begin >= i)
begin++;
else if(begin<i) {
check(text, begin, i);
begin = i+1;
}
}
}
if(begin < i)
check(text, begin, i);
}
bool EnchantHighlighter::setLanguage(const std::string &lang) {
if(!enchant::Broker::instance()->dict_exists(lang))
return false;
dict.reset(enchant::Broker::instance()->request_dict(lang));
return true;
}
<commit_msg>Don't import QDebug<commit_after>#include "enchanthighlighter.hh"
#include <enchant++.h>
EnchantHighlighter::EnchantHighlighter(QTextDocument *parent) :
QSyntaxHighlighter(parent)
{
format.setUnderlineColor(QColor(Qt::red));
format.setUnderlineStyle(QTextCharFormat::SpellCheckUnderline);
}
EnchantHighlighter::~EnchantHighlighter() {}
void EnchantHighlighter::check(const QString &text, int begin, int i) {
QStringRef sub(&text, begin, i-begin);
auto ba = sub.toUtf8();
if(!dict->check(std::string {ba.data(), (std::string::size_type)ba.size()}))
setFormat(begin, i-begin, format);
}
void EnchantHighlighter::highlightBlock(const QString& text) {
if(!dict)
return;
int begin = 0;
int i = 0;
for(; i<text.length(); ++i) {
auto ch = text.at(i);
if(ch < 'A') {
if(begin >= i)
begin++;
else if(begin<i) {
check(text, begin, i);
begin = i+1;
}
}
}
if(begin < i)
check(text, begin, i);
}
bool EnchantHighlighter::setLanguage(const std::string &lang) {
if(!enchant::Broker::instance()->dict_exists(lang))
return false;
dict.reset(enchant::Broker::instance()->request_dict(lang));
return true;
}
<|endoftext|> |
<commit_before>#include "internal.hh"
#include <cstring>
using namespace std;
DWARFPP_BEGIN_NAMESPACE
sec_offset
value::get_section_offset() const
{
return cu->info.offset + offset;
}
taddr
value::as_address() const
{
if (form != DW_FORM::addr)
throw value_type_mismatch("cannot read " + to_string(typ) + " as address");
cursor cur(cu->subsec, offset);
return cur.address();
}
const void *
value::as_block(size_t *size_out) const
{
// XXX It appears that expressions are often encoded as
// blocks, not as exprlocs. Need DW_AT-aware types?
// XXX Blocks can contain all sorts of things, including
// references, which couldn't be resolved by callers in the
// current minimal API.
// XXX Does automatic coercion
cursor cur(cu->subsec, offset);
switch (form) {
case DW_FORM::block1:
*size_out = cur.fixed<uint8_t>();
break;
case DW_FORM::block2:
*size_out = cur.fixed<uint16_t>();
break;
case DW_FORM::block4:
*size_out = cur.fixed<uint32_t>();
break;
case DW_FORM::block:
case DW_FORM::exprloc:
*size_out = cur.uleb128();
break;
default:
throw value_type_mismatch("cannot read " + to_string(typ) + " as block");
}
cur.ensure(*size_out);
return cur.pos;
}
uint64_t
value::as_uconstant() const
{
// XXX Does automatic coercion
cursor cur(cu->subsec, offset);
switch (form) {
case DW_FORM::data1:
return cur.fixed<uint8_t>();
case DW_FORM::data2:
return cur.fixed<uint16_t>();
case DW_FORM::data4:
return cur.fixed<uint32_t>();
case DW_FORM::data8:
return cur.fixed<uint64_t>();
case DW_FORM::udata:
return cur.uleb128();
default:
throw value_type_mismatch("cannot read " + to_string(typ) + " as uconstant");
}
}
int64_t
value::as_sconstant() const
{
// XXX Does automatic coercion
cursor cur(cu->subsec, offset);
switch (form) {
case DW_FORM::data1:
return cur.fixed<int8_t>();
case DW_FORM::data2:
return cur.fixed<int16_t>();
case DW_FORM::data4:
return cur.fixed<int32_t>();
case DW_FORM::data8:
return cur.fixed<int64_t>();
case DW_FORM::sdata:
return cur.sleb128();
default:
throw value_type_mismatch("cannot read " + to_string(typ) + " as sconstant");
}
}
expr
value::as_exprloc() const
{
// XXX Does automatic coercion
cursor cur(cu->subsec, offset);
size_t size;
// Prior to DWARF 4, exprlocs were encoded as blocks.
switch (form) {
case DW_FORM::exprloc:
case DW_FORM::block:
size = cur.uleb128();
break;
case DW_FORM::block1:
size = cur.fixed<uint8_t>();
break;
case DW_FORM::block2:
size = cur.fixed<uint16_t>();
break;
case DW_FORM::block4:
size = cur.fixed<uint32_t>();
break;
default:
throw value_type_mismatch("cannot read " + to_string(typ) + " as exprloc");
}
return expr(cu, cur.section_offset(), size);
}
bool
value::as_flag() const
{
switch (form) {
case DW_FORM::flag: {
cursor cur(cu->subsec, offset);
return cur.fixed<ubyte>() != 0;
}
case DW_FORM::flag_present:
return true;
default:
throw value_type_mismatch("cannot read " + to_string(typ) + " as flag");
}
}
die
value::as_reference() const
{
sec_offset off;
// XXX Would be nice if we could avoid this. The cursor is
// all overhead here.
cursor cur(cu->subsec, offset);
switch (form) {
case DW_FORM::ref1:
off = cur.fixed<ubyte>();
break;
case DW_FORM::ref2:
off = cur.fixed<uhalf>();
break;
case DW_FORM::ref4:
off = cur.fixed<uword>();
break;
case DW_FORM::ref8:
off = cur.fixed<uint64_t>();
break;
case DW_FORM::ref_udata:
off = cur.uleb128();
break;
// XXX Implement
case DW_FORM::ref_addr:
throw runtime_error("DW_FORM::ref_addr not implemented");
case DW_FORM::ref_sig8:
throw runtime_error("DW_FORM::ref_sig8 not implemented");
default:
throw value_type_mismatch("cannot read " + to_string(typ) + " as reference");
}
die d(cu);
d.read(off);
return d;
}
void
value::as_string(string &buf) const
{
size_t size;
const char *p = as_cstr(&size);
buf.resize(size);
memmove(&buf.front(), p, size);
}
string
value::as_string() const
{
size_t size;
const char *s = as_cstr(&size);
return string(s, size);
}
const char *
value::as_cstr(size_t *size_out) const
{
cursor cur(cu->subsec, offset);
switch (form) {
case DW_FORM::string:
return cur.cstr(size_out);
case DW_FORM::strp: {
sec_offset off = cur.offset();
cursor scur(cu->file->get_sec_str(), off);
return scur.cstr(size_out);
}
default:
throw value_type_mismatch("cannot read " + to_string(typ) + " as string");
}
}
sec_offset
value::as_sec_offset() const
{
// Prior to DWARF 4, sec_offsets were encoded as data4 or
// data8.
cursor cur(cu->subsec, offset);
switch (form) {
case DW_FORM::data4:
return cur.fixed<uint32_t>();
case DW_FORM::data8:
return cur.fixed<uint64_t>();
case DW_FORM::sec_offset:
return cur.offset();
default:
throw value_type_mismatch("cannot read " + to_string(typ) + " as sec_offset");
}
}
void
value::resolve_indirect(DW_AT name)
{
if (form != DW_FORM::indirect)
return;
cursor c(cu->subsec, offset);
DW_FORM form;
do {
form = (DW_FORM)c.uleb128();
} while (form == DW_FORM::indirect);
typ = attribute_spec(name, form).type;
offset = c.section_offset();
}
string
to_string(const value &v)
{
switch (v.get_type()) {
case value::type::invalid:
return "<invalid value type>";
case value::type::address:
return "0x" + to_hex(v.as_address());
case value::type::block: {
size_t size;
const char *b = (const char*)v.as_block(&size);
string res = ::to_string(size) + " byte block:";
for (size_t pos = 0; pos < size; ++pos) {
res += ' ';
res += to_hex(b[pos]);
}
return res;
}
case value::type::constant:
return "0x" + to_hex(v.as_uconstant());
case value::type::uconstant:
return ::to_string(v.as_uconstant());
case value::type::sconstant:
return ::to_string(v.as_sconstant());
case value::type::exprloc:
// XXX
return "<exprloc>";
case value::type::flag:
return v.as_flag() ? "true" : "false";
case value::type::reference:
return "<0x" + to_hex(v.as_reference().get_section_offset()) + ">";
case value::type::string:
return v.as_string();
default:
return "<to_string of " + to_string(v.get_type()) + " not implemented>";
}
}
DWARFPP_END_NAMESPACE
<commit_msg>Finish value to_string<commit_after>#include "internal.hh"
#include <cstring>
using namespace std;
DWARFPP_BEGIN_NAMESPACE
sec_offset
value::get_section_offset() const
{
return cu->info.offset + offset;
}
taddr
value::as_address() const
{
if (form != DW_FORM::addr)
throw value_type_mismatch("cannot read " + to_string(typ) + " as address");
cursor cur(cu->subsec, offset);
return cur.address();
}
const void *
value::as_block(size_t *size_out) const
{
// XXX It appears that expressions are often encoded as
// blocks, not as exprlocs. Need DW_AT-aware types?
// XXX Blocks can contain all sorts of things, including
// references, which couldn't be resolved by callers in the
// current minimal API.
// XXX Does automatic coercion
cursor cur(cu->subsec, offset);
switch (form) {
case DW_FORM::block1:
*size_out = cur.fixed<uint8_t>();
break;
case DW_FORM::block2:
*size_out = cur.fixed<uint16_t>();
break;
case DW_FORM::block4:
*size_out = cur.fixed<uint32_t>();
break;
case DW_FORM::block:
case DW_FORM::exprloc:
*size_out = cur.uleb128();
break;
default:
throw value_type_mismatch("cannot read " + to_string(typ) + " as block");
}
cur.ensure(*size_out);
return cur.pos;
}
uint64_t
value::as_uconstant() const
{
// XXX Does automatic coercion
cursor cur(cu->subsec, offset);
switch (form) {
case DW_FORM::data1:
return cur.fixed<uint8_t>();
case DW_FORM::data2:
return cur.fixed<uint16_t>();
case DW_FORM::data4:
return cur.fixed<uint32_t>();
case DW_FORM::data8:
return cur.fixed<uint64_t>();
case DW_FORM::udata:
return cur.uleb128();
default:
throw value_type_mismatch("cannot read " + to_string(typ) + " as uconstant");
}
}
int64_t
value::as_sconstant() const
{
// XXX Does automatic coercion
cursor cur(cu->subsec, offset);
switch (form) {
case DW_FORM::data1:
return cur.fixed<int8_t>();
case DW_FORM::data2:
return cur.fixed<int16_t>();
case DW_FORM::data4:
return cur.fixed<int32_t>();
case DW_FORM::data8:
return cur.fixed<int64_t>();
case DW_FORM::sdata:
return cur.sleb128();
default:
throw value_type_mismatch("cannot read " + to_string(typ) + " as sconstant");
}
}
expr
value::as_exprloc() const
{
// XXX Does automatic coercion
cursor cur(cu->subsec, offset);
size_t size;
// Prior to DWARF 4, exprlocs were encoded as blocks.
switch (form) {
case DW_FORM::exprloc:
case DW_FORM::block:
size = cur.uleb128();
break;
case DW_FORM::block1:
size = cur.fixed<uint8_t>();
break;
case DW_FORM::block2:
size = cur.fixed<uint16_t>();
break;
case DW_FORM::block4:
size = cur.fixed<uint32_t>();
break;
default:
throw value_type_mismatch("cannot read " + to_string(typ) + " as exprloc");
}
return expr(cu, cur.section_offset(), size);
}
bool
value::as_flag() const
{
switch (form) {
case DW_FORM::flag: {
cursor cur(cu->subsec, offset);
return cur.fixed<ubyte>() != 0;
}
case DW_FORM::flag_present:
return true;
default:
throw value_type_mismatch("cannot read " + to_string(typ) + " as flag");
}
}
die
value::as_reference() const
{
sec_offset off;
// XXX Would be nice if we could avoid this. The cursor is
// all overhead here.
cursor cur(cu->subsec, offset);
switch (form) {
case DW_FORM::ref1:
off = cur.fixed<ubyte>();
break;
case DW_FORM::ref2:
off = cur.fixed<uhalf>();
break;
case DW_FORM::ref4:
off = cur.fixed<uword>();
break;
case DW_FORM::ref8:
off = cur.fixed<uint64_t>();
break;
case DW_FORM::ref_udata:
off = cur.uleb128();
break;
// XXX Implement
case DW_FORM::ref_addr:
throw runtime_error("DW_FORM::ref_addr not implemented");
case DW_FORM::ref_sig8:
throw runtime_error("DW_FORM::ref_sig8 not implemented");
default:
throw value_type_mismatch("cannot read " + to_string(typ) + " as reference");
}
die d(cu);
d.read(off);
return d;
}
void
value::as_string(string &buf) const
{
size_t size;
const char *p = as_cstr(&size);
buf.resize(size);
memmove(&buf.front(), p, size);
}
string
value::as_string() const
{
size_t size;
const char *s = as_cstr(&size);
return string(s, size);
}
const char *
value::as_cstr(size_t *size_out) const
{
cursor cur(cu->subsec, offset);
switch (form) {
case DW_FORM::string:
return cur.cstr(size_out);
case DW_FORM::strp: {
sec_offset off = cur.offset();
cursor scur(cu->file->get_sec_str(), off);
return scur.cstr(size_out);
}
default:
throw value_type_mismatch("cannot read " + to_string(typ) + " as string");
}
}
sec_offset
value::as_sec_offset() const
{
// Prior to DWARF 4, sec_offsets were encoded as data4 or
// data8.
cursor cur(cu->subsec, offset);
switch (form) {
case DW_FORM::data4:
return cur.fixed<uint32_t>();
case DW_FORM::data8:
return cur.fixed<uint64_t>();
case DW_FORM::sec_offset:
return cur.offset();
default:
throw value_type_mismatch("cannot read " + to_string(typ) + " as sec_offset");
}
}
void
value::resolve_indirect(DW_AT name)
{
if (form != DW_FORM::indirect)
return;
cursor c(cu->subsec, offset);
DW_FORM form;
do {
form = (DW_FORM)c.uleb128();
} while (form == DW_FORM::indirect);
typ = attribute_spec(name, form).type;
offset = c.section_offset();
}
string
to_string(const value &v)
{
switch (v.get_type()) {
case value::type::invalid:
return "<invalid value type>";
case value::type::address:
return "0x" + to_hex(v.as_address());
case value::type::block: {
size_t size;
const char *b = (const char*)v.as_block(&size);
string res = ::to_string(size) + " byte block:";
for (size_t pos = 0; pos < size; ++pos) {
res += ' ';
res += to_hex(b[pos]);
}
return res;
}
case value::type::constant:
return "0x" + to_hex(v.as_uconstant());
case value::type::uconstant:
return ::to_string(v.as_uconstant());
case value::type::sconstant:
return ::to_string(v.as_sconstant());
case value::type::exprloc:
// XXX
return "<exprloc>";
case value::type::flag:
return v.as_flag() ? "true" : "false";
case value::type::lineptr:
return "<lineptr 0x" + to_hex(v.as_sec_offset()) + ">";
case value::type::loclistptr:
return "<loclistptr 0x" + to_hex(v.as_sec_offset()) + ">";
case value::type::macptr:
return "<macptr 0x" + to_hex(v.as_sec_offset()) + ">";
case value::type::rangelistptr:
return "<rangelistptr 0x" + to_hex(v.as_sec_offset()) + ">";
case value::type::reference:
return "<0x" + to_hex(v.as_reference().get_section_offset()) + ">";
case value::type::string:
return v.as_string();
}
return "<unexpected value type " + to_string(v.get_type()) + ">";
}
DWARFPP_END_NAMESPACE
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DialogListBox.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 03:36:37 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "DialogListBox.hxx"
namespace sd
{
DialogListBox::DialogListBox( Window* pParent, WinBits nWinStyle ) :
Control( pParent, nWinStyle ),
mpChild( 0 )
{
mpVScrollBar = new ScrollBar( this, WB_VSCROLL | WB_DRAG );
mpHScrollBar = new ScrollBar( this, WB_HSCROLL | WB_DRAG );
mpScrollBarBox = new ScrollBarBox( this );
Link aLink( LINK( this, DialogListBox, ScrollBarHdl ) );
mpVScrollBar->SetScrollHdl( aLink );
mpHScrollBar->SetScrollHdl( aLink );
mbVScroll = false;
mbHScroll = false;
mbAutoHScroll = ( nWinStyle & WB_AUTOHSCROLL ) ? true : false;
}
// -----------------------------------------------------------------------
DialogListBox::~DialogListBox()
{
delete mpHScrollBar;
delete mpVScrollBar;
delete mpScrollBarBox;
delete mpChild;
}
// -----------------------------------------------------------------------
void DialogListBox::SetChildWindow( Window* pChild, const Size& rMinSize )
{
if( mpChild )
delete mpChild;
mpChild = pChild;
maMinSize = rMinSize;
ImplResizeControls();
ImplCheckScrollBars();
}
// -----------------------------------------------------------------------
void DialogListBox::GetFocus()
{
if( mpChild )
mpChild->GrabFocus();
}
// -----------------------------------------------------------------------
::Window* DialogListBox::GetPreferredKeyInputWindow()
{
if( mpChild )
return mpChild;
else
return this;
}
// -----------------------------------------------------------------------
void DialogListBox::Resize()
{
Control::Resize();
ImplResizeControls();
ImplCheckScrollBars();
}
// -----------------------------------------------------------------------
IMPL_LINK( DialogListBox, ScrollBarHdl, ScrollBar*, pSB )
{
ImplResizeChild();
return 1;
}
// -----------------------------------------------------------------------
void DialogListBox::ImplCheckScrollBars()
{
bool bArrange = false;
Size aOutSz = GetOutputSizePixel();
// vert. ScrollBar
if( aOutSz.Height() < maMinSize.Height() )
{
if( !mbVScroll )
bArrange = true;
mbVScroll = true;
}
else
{
if( mbVScroll )
bArrange = true;
mbVScroll = false;
}
// horz. ScrollBar
if( mbAutoHScroll )
{
long nWidth = aOutSz.Width();
if ( mbVScroll )
nWidth -= mpVScrollBar->GetSizePixel().Width();
if( nWidth < maMinSize.Width() )
{
if( !mbHScroll )
bArrange = true;
mbHScroll = true;
if ( !mbVScroll )
{
int nHeight = aOutSz.Height() - mpHScrollBar->GetSizePixel().Height();
if( nHeight < maMinSize.Height() )
{
if( !mbVScroll )
bArrange = true;
mbVScroll = true;
}
}
}
else
{
if( mbHScroll )
bArrange = true;
mbHScroll = false;
}
}
if( bArrange )
ImplResizeControls();
ImplInitScrollBars();
}
// -----------------------------------------------------------------------
void DialogListBox::ImplInitScrollBars()
{
if( mpChild )
{
Size aOutSize( GetOutputSizePixel() );
if( mbHScroll ) aOutSize.Height() -= mpHScrollBar->GetSizePixel().Height();
if( mbVScroll ) aOutSize.Width() -= mpVScrollBar->GetSizePixel().Width();
if ( mbVScroll )
{
mpVScrollBar->SetRangeMax( maMinSize.Height() );
mpVScrollBar->SetVisibleSize( aOutSize.Height() );
mpVScrollBar->SetPageSize( 16 );
}
if ( mbHScroll )
{
mpHScrollBar->SetRangeMax( maMinSize.Width() );
mpHScrollBar->SetVisibleSize( aOutSize.Width() );
mpHScrollBar->SetPageSize( 16 );
}
}
}
// -----------------------------------------------------------------------
void DialogListBox::ImplResizeControls()
{
Size aOutSz( GetOutputSizePixel() );
long nSBWidth = GetSettings().GetStyleSettings().GetScrollBarSize();
nSBWidth = CalcZoom( nSBWidth );
maInnerSize = aOutSz;
if ( mbVScroll )
maInnerSize.Width() -= nSBWidth;
if ( mbHScroll )
maInnerSize.Height() -= nSBWidth;
// ScrollBarBox
if( mbVScroll && mbHScroll )
{
Point aBoxPos( maInnerSize.Width(), maInnerSize.Height() );
mpScrollBarBox->SetPosSizePixel( aBoxPos, Size( nSBWidth, nSBWidth ) );
mpScrollBarBox->Show();
}
else
{
mpScrollBarBox->Hide();
}
// vert. ScrollBar
if( mbVScroll )
{
// Scrollbar on left or right side?
Point aVPos( aOutSz.Width() - nSBWidth, 0 );
mpVScrollBar->SetPosSizePixel( aVPos, Size( nSBWidth, maInnerSize.Height() ) );
mpVScrollBar->Show();
}
else
{
mpVScrollBar->Hide();
}
// horz. ScrollBar
if( mbHScroll )
{
Point aHPos( 0, aOutSz.Height() - nSBWidth );
mpHScrollBar->SetPosSizePixel( aHPos, Size( maInnerSize.Width(), nSBWidth ) );
mpHScrollBar->Show();
}
else
{
mpHScrollBar->Hide();
}
ImplResizeChild();
}
void DialogListBox::ImplResizeChild()
{
Point aWinPos;
Size aSize( maInnerSize );
int nOffset;
if( mbHScroll )
{
nOffset = mpHScrollBar->GetThumbPos();
aWinPos.X() = -nOffset;
aSize.Width() += nOffset;
}
if( mbVScroll )
{
nOffset = mpVScrollBar->GetThumbPos();
aWinPos.Y() = -nOffset;
aSize.Height() += nOffset;
}
mpChild->SetPosSizePixel( aWinPos, aSize );
}
// -----------------------------------------------------------------------
void DialogListBox::StateChanged( StateChangedType nType )
{
if ( nType == STATE_CHANGE_INITSHOW )
{
ImplCheckScrollBars();
}
else if ( ( nType == STATE_CHANGE_UPDATEMODE ) || ( nType == STATE_CHANGE_DATA ) )
{
BOOL bUpdate = IsUpdateMode();
mpChild->SetUpdateMode( bUpdate );
if ( bUpdate && IsReallyVisible() )
ImplCheckScrollBars();
}
else if( nType == STATE_CHANGE_ENABLE )
{
mpHScrollBar->Enable( IsEnabled() );
mpVScrollBar->Enable( IsEnabled() );
mpScrollBarBox->Enable( IsEnabled() );
Invalidate();
}
else if ( nType == STATE_CHANGE_ZOOM )
{
mpChild->SetZoom( GetZoom() );
Resize();
}
else if ( nType == STATE_CHANGE_CONTROLFONT )
{
mpChild->SetControlFont( GetControlFont() );
}
else if ( nType == STATE_CHANGE_CONTROLFOREGROUND )
{
mpChild->SetControlForeground( GetControlForeground() );
}
else if ( nType == STATE_CHANGE_CONTROLBACKGROUND )
{
mpChild->SetControlBackground( GetControlBackground() );
}
Control::StateChanged( nType );
}
// -----------------------------------------------------------------------
long DialogListBox::Notify( NotifyEvent& rNEvt )
{
long nDone = 0;
if ( rNEvt.GetType() == EVENT_COMMAND )
{
const CommandEvent& rCEvt = *rNEvt.GetCommandEvent();
if ( rCEvt.GetCommand() == COMMAND_WHEEL )
{
const CommandWheelData* pData = rCEvt.GetWheelData();
if( !pData->GetModifier() && ( pData->GetMode() == COMMAND_WHEEL_SCROLL ) )
{
nDone = HandleScrollCommand( rCEvt, mpHScrollBar, mpVScrollBar );
}
}
}
return nDone ? nDone : Window::Notify( rNEvt );
}
} // namespace sd
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.282); FILE MERGED 2006/09/01 17:36:53 kaib 1.3.282.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DialogListBox.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-16 18:29:36 $
*
* 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_sd.hxx"
#include "DialogListBox.hxx"
namespace sd
{
DialogListBox::DialogListBox( Window* pParent, WinBits nWinStyle ) :
Control( pParent, nWinStyle ),
mpChild( 0 )
{
mpVScrollBar = new ScrollBar( this, WB_VSCROLL | WB_DRAG );
mpHScrollBar = new ScrollBar( this, WB_HSCROLL | WB_DRAG );
mpScrollBarBox = new ScrollBarBox( this );
Link aLink( LINK( this, DialogListBox, ScrollBarHdl ) );
mpVScrollBar->SetScrollHdl( aLink );
mpHScrollBar->SetScrollHdl( aLink );
mbVScroll = false;
mbHScroll = false;
mbAutoHScroll = ( nWinStyle & WB_AUTOHSCROLL ) ? true : false;
}
// -----------------------------------------------------------------------
DialogListBox::~DialogListBox()
{
delete mpHScrollBar;
delete mpVScrollBar;
delete mpScrollBarBox;
delete mpChild;
}
// -----------------------------------------------------------------------
void DialogListBox::SetChildWindow( Window* pChild, const Size& rMinSize )
{
if( mpChild )
delete mpChild;
mpChild = pChild;
maMinSize = rMinSize;
ImplResizeControls();
ImplCheckScrollBars();
}
// -----------------------------------------------------------------------
void DialogListBox::GetFocus()
{
if( mpChild )
mpChild->GrabFocus();
}
// -----------------------------------------------------------------------
::Window* DialogListBox::GetPreferredKeyInputWindow()
{
if( mpChild )
return mpChild;
else
return this;
}
// -----------------------------------------------------------------------
void DialogListBox::Resize()
{
Control::Resize();
ImplResizeControls();
ImplCheckScrollBars();
}
// -----------------------------------------------------------------------
IMPL_LINK( DialogListBox, ScrollBarHdl, ScrollBar*, pSB )
{
ImplResizeChild();
return 1;
}
// -----------------------------------------------------------------------
void DialogListBox::ImplCheckScrollBars()
{
bool bArrange = false;
Size aOutSz = GetOutputSizePixel();
// vert. ScrollBar
if( aOutSz.Height() < maMinSize.Height() )
{
if( !mbVScroll )
bArrange = true;
mbVScroll = true;
}
else
{
if( mbVScroll )
bArrange = true;
mbVScroll = false;
}
// horz. ScrollBar
if( mbAutoHScroll )
{
long nWidth = aOutSz.Width();
if ( mbVScroll )
nWidth -= mpVScrollBar->GetSizePixel().Width();
if( nWidth < maMinSize.Width() )
{
if( !mbHScroll )
bArrange = true;
mbHScroll = true;
if ( !mbVScroll )
{
int nHeight = aOutSz.Height() - mpHScrollBar->GetSizePixel().Height();
if( nHeight < maMinSize.Height() )
{
if( !mbVScroll )
bArrange = true;
mbVScroll = true;
}
}
}
else
{
if( mbHScroll )
bArrange = true;
mbHScroll = false;
}
}
if( bArrange )
ImplResizeControls();
ImplInitScrollBars();
}
// -----------------------------------------------------------------------
void DialogListBox::ImplInitScrollBars()
{
if( mpChild )
{
Size aOutSize( GetOutputSizePixel() );
if( mbHScroll ) aOutSize.Height() -= mpHScrollBar->GetSizePixel().Height();
if( mbVScroll ) aOutSize.Width() -= mpVScrollBar->GetSizePixel().Width();
if ( mbVScroll )
{
mpVScrollBar->SetRangeMax( maMinSize.Height() );
mpVScrollBar->SetVisibleSize( aOutSize.Height() );
mpVScrollBar->SetPageSize( 16 );
}
if ( mbHScroll )
{
mpHScrollBar->SetRangeMax( maMinSize.Width() );
mpHScrollBar->SetVisibleSize( aOutSize.Width() );
mpHScrollBar->SetPageSize( 16 );
}
}
}
// -----------------------------------------------------------------------
void DialogListBox::ImplResizeControls()
{
Size aOutSz( GetOutputSizePixel() );
long nSBWidth = GetSettings().GetStyleSettings().GetScrollBarSize();
nSBWidth = CalcZoom( nSBWidth );
maInnerSize = aOutSz;
if ( mbVScroll )
maInnerSize.Width() -= nSBWidth;
if ( mbHScroll )
maInnerSize.Height() -= nSBWidth;
// ScrollBarBox
if( mbVScroll && mbHScroll )
{
Point aBoxPos( maInnerSize.Width(), maInnerSize.Height() );
mpScrollBarBox->SetPosSizePixel( aBoxPos, Size( nSBWidth, nSBWidth ) );
mpScrollBarBox->Show();
}
else
{
mpScrollBarBox->Hide();
}
// vert. ScrollBar
if( mbVScroll )
{
// Scrollbar on left or right side?
Point aVPos( aOutSz.Width() - nSBWidth, 0 );
mpVScrollBar->SetPosSizePixel( aVPos, Size( nSBWidth, maInnerSize.Height() ) );
mpVScrollBar->Show();
}
else
{
mpVScrollBar->Hide();
}
// horz. ScrollBar
if( mbHScroll )
{
Point aHPos( 0, aOutSz.Height() - nSBWidth );
mpHScrollBar->SetPosSizePixel( aHPos, Size( maInnerSize.Width(), nSBWidth ) );
mpHScrollBar->Show();
}
else
{
mpHScrollBar->Hide();
}
ImplResizeChild();
}
void DialogListBox::ImplResizeChild()
{
Point aWinPos;
Size aSize( maInnerSize );
int nOffset;
if( mbHScroll )
{
nOffset = mpHScrollBar->GetThumbPos();
aWinPos.X() = -nOffset;
aSize.Width() += nOffset;
}
if( mbVScroll )
{
nOffset = mpVScrollBar->GetThumbPos();
aWinPos.Y() = -nOffset;
aSize.Height() += nOffset;
}
mpChild->SetPosSizePixel( aWinPos, aSize );
}
// -----------------------------------------------------------------------
void DialogListBox::StateChanged( StateChangedType nType )
{
if ( nType == STATE_CHANGE_INITSHOW )
{
ImplCheckScrollBars();
}
else if ( ( nType == STATE_CHANGE_UPDATEMODE ) || ( nType == STATE_CHANGE_DATA ) )
{
BOOL bUpdate = IsUpdateMode();
mpChild->SetUpdateMode( bUpdate );
if ( bUpdate && IsReallyVisible() )
ImplCheckScrollBars();
}
else if( nType == STATE_CHANGE_ENABLE )
{
mpHScrollBar->Enable( IsEnabled() );
mpVScrollBar->Enable( IsEnabled() );
mpScrollBarBox->Enable( IsEnabled() );
Invalidate();
}
else if ( nType == STATE_CHANGE_ZOOM )
{
mpChild->SetZoom( GetZoom() );
Resize();
}
else if ( nType == STATE_CHANGE_CONTROLFONT )
{
mpChild->SetControlFont( GetControlFont() );
}
else if ( nType == STATE_CHANGE_CONTROLFOREGROUND )
{
mpChild->SetControlForeground( GetControlForeground() );
}
else if ( nType == STATE_CHANGE_CONTROLBACKGROUND )
{
mpChild->SetControlBackground( GetControlBackground() );
}
Control::StateChanged( nType );
}
// -----------------------------------------------------------------------
long DialogListBox::Notify( NotifyEvent& rNEvt )
{
long nDone = 0;
if ( rNEvt.GetType() == EVENT_COMMAND )
{
const CommandEvent& rCEvt = *rNEvt.GetCommandEvent();
if ( rCEvt.GetCommand() == COMMAND_WHEEL )
{
const CommandWheelData* pData = rCEvt.GetWheelData();
if( !pData->GetModifier() && ( pData->GetMode() == COMMAND_WHEEL_SCROLL ) )
{
nDone = HandleScrollCommand( rCEvt, mpHScrollBar, mpVScrollBar );
}
}
}
return nDone ? nDone : Window::Notify( rNEvt );
}
} // namespace sd
<|endoftext|> |
<commit_before>#include <gmi_mesh.h>
#include <apf.h>
#include <apfMesh2.h>
#include <apfMDS.h>
#include <PCU.h>
#include <parma.h>
namespace {
const char* modelFile = 0;
const char* meshFile = 0;
const char* outFile = 0;
int partitionFactor = 1;
apf::Mesh2* readMesh()
{
double t0 = MPI_Wtime();
apf::Mesh2* m = apf::loadMdsMesh(modelFile,meshFile);
double t1 = MPI_Wtime();
if ( ! PCU_Comm_Self())
printf("time to load %s and %s: %f seconds\n",modelFile,meshFile,t1-t0);
return m;
}
void freeMesh(apf::Mesh* m)
{
m->destroyNative();
apf::destroyMesh(m);
}
apf::Migration* getPlan(apf::Mesh* m)
{
apf::Splitter* splitter = Parma_MakeRibSplitter(m);
double t0 = MPI_Wtime();
apf::MeshTag* weights = Parma_WeighByMemory(m);
apf::Migration* plan = splitter->split(weights, 1.10, partitionFactor);
m->destroyTag(weights);
double t1 = MPI_Wtime();
delete splitter;
if ( ! PCU_Comm_Self())
printf("time to run RIB: %f seconds\n",t1-t0);
return plan;
}
void runAfter(apf::Mesh2* m)
{
m->verify();
double t2 = MPI_Wtime();
m->writeNative(outFile);
double t3 = MPI_Wtime();
if ( ! PCU_Comm_Self())
printf("time to write %s: %f seconds\n",outFile,t3-t2);
freeMesh(m);
}
void getConfig(int argc, char** argv)
{
assert(argc==5);
modelFile = argv[1];
meshFile = argv[2];
outFile = argv[3];
partitionFactor = atoi(argv[4]);
}
}
int main(int argc, char** argv)
{
int provided;
MPI_Init_thread(&argc,&argv,MPI_THREAD_MULTIPLE,&provided);
assert(provided==MPI_THREAD_MULTIPLE);
PCU_Comm_Init();
gmi_register_mesh();
PCU_Protect();
getConfig(argc,argv);
apf::Mesh2* m = readMesh();
splitMdsMesh(m, getPlan(m), partitionFactor, runAfter);
PCU_Comm_Free();
MPI_Finalize();
}
<commit_msg>removed timers and verify from split, timers moved<commit_after>#include <gmi_mesh.h>
#include <apf.h>
#include <apfMesh2.h>
#include <apfMDS.h>
#include <PCU.h>
#include <parma.h>
namespace {
const char* modelFile = 0;
const char* meshFile = 0;
const char* outFile = 0;
int partitionFactor = 1;
void freeMesh(apf::Mesh* m)
{
m->destroyNative();
apf::destroyMesh(m);
}
apf::Migration* getPlan(apf::Mesh* m)
{
apf::Splitter* splitter = Parma_MakeRibSplitter(m);
apf::MeshTag* weights = Parma_WeighByMemory(m);
apf::Migration* plan = splitter->split(weights, 1.10, partitionFactor);
m->destroyTag(weights);
delete splitter;
return plan;
}
void runAfter(apf::Mesh2* m)
{
m->writeNative(outFile);
freeMesh(m);
}
void getConfig(int argc, char** argv)
{
assert(argc==5);
modelFile = argv[1];
meshFile = argv[2];
outFile = argv[3];
partitionFactor = atoi(argv[4]);
}
}
int main(int argc, char** argv)
{
int provided;
MPI_Init_thread(&argc,&argv,MPI_THREAD_MULTIPLE,&provided);
assert(provided==MPI_THREAD_MULTIPLE);
PCU_Comm_Init();
gmi_register_mesh();
PCU_Protect();
getConfig(argc,argv);
apf::Mesh2* m = apf::loadMdsMesh(modelFile,meshFile);
splitMdsMesh(m, getPlan(m), partitionFactor, runAfter);
PCU_Comm_Free();
MPI_Finalize();
}
<|endoftext|> |
<commit_before>#include <x0/http/HttpRangeDef.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <iostream>
#include <cstdlib>
#include <cctype>
#include <cassert>
#include <strings.h>
class range_def_test :
public CPPUNIT_NS::TestFixture
{
public:
CPPUNIT_TEST_SUITE(range_def_test);
CPPUNIT_TEST(range1);
CPPUNIT_TEST(range2);
CPPUNIT_TEST(range3);
CPPUNIT_TEST(range4);
CPPUNIT_TEST(range5);
CPPUNIT_TEST(range6);
CPPUNIT_TEST_SUITE_END();
private:
void range1()
{
x0::HttpRangeDef r;
x0::ConstBuffer spec("bytes=0-499");
r.parse(spec);
CPPUNIT_ASSERT(r.unit_name() == "bytes");
CPPUNIT_ASSERT(r.size() == 1);
CPPUNIT_ASSERT(r[0].first == 0);
CPPUNIT_ASSERT(r[0].second == 499);
}
void range2()
{
x0::HttpRangeDef r;
x0::ConstBuffer spec("bytes=500-999");
r.parse(spec);
CPPUNIT_ASSERT(r.unit_name() == "bytes");
CPPUNIT_ASSERT(r.size() == 1);
CPPUNIT_ASSERT(r[0].first == 500);
CPPUNIT_ASSERT(r[0].second == 999);
}
void range3()
{
x0::HttpRangeDef r;
x0::ConstBuffer spec("bytes=-500");
r.parse(spec);
CPPUNIT_ASSERT(r.unit_name() == "bytes");
CPPUNIT_ASSERT(r.size() == 1);
CPPUNIT_ASSERT(r[0].first == x0::HttpRangeDef::npos);
CPPUNIT_ASSERT(r[0].second == 500);
}
void range4()
{
x0::HttpRangeDef r;
x0::ConstBuffer spec("bytes=9500-");
r.parse(spec);
CPPUNIT_ASSERT(r.unit_name() == "bytes");
CPPUNIT_ASSERT(r.size() == 1);
CPPUNIT_ASSERT(r[0].first == 9500);
CPPUNIT_ASSERT(r[0].second == x0::HttpRangeDef::npos);
}
void range5()
{
x0::HttpRangeDef r;
x0::ConstBuffer spec("bytes=0-0,-1");
r.parse(spec);
CPPUNIT_ASSERT(r.unit_name() == "bytes");
CPPUNIT_ASSERT(r.size() == 2);
CPPUNIT_ASSERT(r[0].first == 0);
CPPUNIT_ASSERT(r[0].second == 0);
CPPUNIT_ASSERT(r[1].first == x0::HttpRangeDef::npos);
CPPUNIT_ASSERT(r[1].second == 1);
}
void range6()
{
x0::HttpRangeDef r;
x0::ConstBuffer spec("bytes=500-700,601-999");
r.parse(spec);
CPPUNIT_ASSERT(r.unit_name() == "bytes");
CPPUNIT_ASSERT(r.size() == 2);
CPPUNIT_ASSERT(r[0].first == 500);
CPPUNIT_ASSERT(r[0].second == 700);
CPPUNIT_ASSERT(r[1].first == 601);
CPPUNIT_ASSERT(r[1].second == 999);
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(range_def_test);
<commit_msg>adapted to API changes in previous commit.<commit_after>#include <x0/http/HttpRangeDef.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <iostream>
#include <cstdlib>
#include <cctype>
#include <cassert>
#include <strings.h>
class range_def_test :
public CPPUNIT_NS::TestFixture
{
public:
CPPUNIT_TEST_SUITE(range_def_test);
CPPUNIT_TEST(range1);
CPPUNIT_TEST(range2);
CPPUNIT_TEST(range3);
CPPUNIT_TEST(range4);
CPPUNIT_TEST(range5);
CPPUNIT_TEST(range6);
CPPUNIT_TEST_SUITE_END();
private:
void range1()
{
x0::HttpRangeDef r;
x0::ConstBuffer spec("bytes=0-499");
r.parse(spec);
CPPUNIT_ASSERT(r.unitName() == "bytes");
CPPUNIT_ASSERT(r.size() == 1);
CPPUNIT_ASSERT(r[0].first == 0);
CPPUNIT_ASSERT(r[0].second == 499);
}
void range2()
{
x0::HttpRangeDef r;
x0::ConstBuffer spec("bytes=500-999");
r.parse(spec);
CPPUNIT_ASSERT(r.unitName() == "bytes");
CPPUNIT_ASSERT(r.size() == 1);
CPPUNIT_ASSERT(r[0].first == 500);
CPPUNIT_ASSERT(r[0].second == 999);
}
void range3()
{
x0::HttpRangeDef r;
x0::ConstBuffer spec("bytes=-500");
r.parse(spec);
CPPUNIT_ASSERT(r.unitName() == "bytes");
CPPUNIT_ASSERT(r.size() == 1);
CPPUNIT_ASSERT(r[0].first == x0::HttpRangeDef::npos);
CPPUNIT_ASSERT(r[0].second == 500);
}
void range4()
{
x0::HttpRangeDef r;
x0::ConstBuffer spec("bytes=9500-");
r.parse(spec);
CPPUNIT_ASSERT(r.unitName() == "bytes");
CPPUNIT_ASSERT(r.size() == 1);
CPPUNIT_ASSERT(r[0].first == 9500);
CPPUNIT_ASSERT(r[0].second == x0::HttpRangeDef::npos);
}
void range5()
{
x0::HttpRangeDef r;
x0::ConstBuffer spec("bytes=0-0,-1");
r.parse(spec);
CPPUNIT_ASSERT(r.unitName() == "bytes");
CPPUNIT_ASSERT(r.size() == 2);
CPPUNIT_ASSERT(r[0].first == 0);
CPPUNIT_ASSERT(r[0].second == 0);
CPPUNIT_ASSERT(r[1].first == x0::HttpRangeDef::npos);
CPPUNIT_ASSERT(r[1].second == 1);
}
void range6()
{
x0::HttpRangeDef r;
x0::ConstBuffer spec("bytes=500-700,601-999");
r.parse(spec);
CPPUNIT_ASSERT(r.unitName() == "bytes");
CPPUNIT_ASSERT(r.size() == 2);
CPPUNIT_ASSERT(r[0].first == 500);
CPPUNIT_ASSERT(r[0].second == 700);
CPPUNIT_ASSERT(r[1].first == 601);
CPPUNIT_ASSERT(r[1].second == 999);
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(range_def_test);
<|endoftext|> |
<commit_before>// Copyright (c) 2006-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 "base/thread.h"
#include "base/lazy_instance.h"
#include "base/string_util.h"
#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
#include "base/thread_local.h"
#include "base/waitable_event.h"
namespace base {
// This task is used to trigger the message loop to exit.
class ThreadQuitTask : public Task {
public:
virtual void Run() {
MessageLoop::current()->Quit();
Thread::SetThreadWasQuitProperly(true);
}
};
// Used to pass data to ThreadMain. This structure is allocated on the stack
// from within StartWithOptions.
struct Thread::StartupData {
// We get away with a const reference here because of how we are allocated.
const Thread::Options& options;
// Used to synchronize thread startup.
WaitableEvent event;
explicit StartupData(const Options& opt)
: options(opt),
event(false, false) {}
};
Thread::Thread(const char* name)
: stopping_(false),
startup_data_(NULL),
thread_(0),
message_loop_(NULL),
thread_id_(0),
name_(name) {
}
Thread::~Thread() {
Stop();
}
namespace {
// We use this thread-local variable to record whether or not a thread exited
// because its Stop method was called. This allows us to catch cases where
// MessageLoop::Quit() is called directly, which is unexpected when using a
// Thread to setup and run a MessageLoop.
base::LazyInstance<base::ThreadLocalBoolean> lazy_tls_bool(
base::LINKER_INITIALIZED);
} // namespace
void Thread::SetThreadWasQuitProperly(bool flag) {
lazy_tls_bool.Pointer()->Set(flag);
}
bool Thread::GetThreadWasQuitProperly() {
bool quit_properly = true;
#ifndef NDEBUG
quit_properly = lazy_tls_bool.Pointer()->Get();
#endif
return quit_properly;
}
bool Thread::Start() {
return StartWithOptions(Options());
}
bool Thread::StartWithOptions(const Options& options) {
DCHECK(!message_loop_);
SetThreadWasQuitProperly(false);
StartupData startup_data(options);
startup_data_ = &startup_data;
if (!PlatformThread::Create(options.stack_size, this, &thread_)) {
DLOG(ERROR) << "failed to create thread";
startup_data_ = NULL; // Record that we failed to start.
return false;
}
// Wait for the thread to start and initialize message_loop_
startup_data.event.Wait();
DCHECK(message_loop_);
return true;
}
void Thread::Stop() {
if (!thread_was_started())
return;
StopSoon();
// Wait for the thread to exit.
//
// TODO(darin): Unfortunately, we need to keep message_loop_ around until
// the thread exits. Some consumers are abusing the API. Make them stop.
//
PlatformThread::Join(thread_);
// The thread should NULL message_loop_ on exit.
DCHECK(!message_loop_);
// The thread no longer needs to be joined.
startup_data_ = NULL;
stopping_ = false;
}
void Thread::StopSoon() {
// We should only be called on the same thread that started us.
DCHECK_NE(thread_id_, PlatformThread::CurrentId());
if (stopping_ || !message_loop_)
return;
stopping_ = true;
message_loop_->PostTask(FROM_HERE, new ThreadQuitTask());
}
void Thread::Run(MessageLoop* message_loop) {
message_loop->Run();
}
void Thread::ThreadMain() {
{
// The message loop for this thread.
MessageLoop message_loop(startup_data_->options.message_loop_type);
// Complete the initialization of our Thread object.
thread_id_ = PlatformThread::CurrentId();
PlatformThread::SetName(name_.c_str());
ANNOTATE_THREAD_NAME(name_.c_str()); // Tell the name to race detector.
message_loop.set_thread_name(name_);
message_loop_ = &message_loop;
message_loop_proxy_ = MessageLoopProxy::CreateForCurrentThread();
// Let the thread do extra initialization.
// Let's do this before signaling we are started.
Init();
startup_data_->event.Signal();
// startup_data_ can't be touched anymore since the starting thread is now
// unlocked.
Run(message_loop_);
// Let the thread do extra cleanup.
CleanUp();
// Assert that MessageLoop::Quit was called by ThreadQuitTask.
DCHECK(GetThreadWasQuitProperly());
// We can't receive messages anymore.
message_loop_ = NULL;
message_loop_proxy_ = NULL;
}
CleanUpAfterMessageLoopDestruction();
thread_id_ = 0;
}
} // namespace base
<commit_msg>Annotate a benign data race in Thread::StopSoon BUG=23245 TEST=TSan bots Review URL: http://codereview.chromium.org/2136013<commit_after>// Copyright (c) 2006-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 "base/thread.h"
#include "base/lazy_instance.h"
#include "base/string_util.h"
#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
#include "base/thread_local.h"
#include "base/waitable_event.h"
namespace base {
// This task is used to trigger the message loop to exit.
class ThreadQuitTask : public Task {
public:
virtual void Run() {
MessageLoop::current()->Quit();
Thread::SetThreadWasQuitProperly(true);
}
};
// Used to pass data to ThreadMain. This structure is allocated on the stack
// from within StartWithOptions.
struct Thread::StartupData {
// We get away with a const reference here because of how we are allocated.
const Thread::Options& options;
// Used to synchronize thread startup.
WaitableEvent event;
explicit StartupData(const Options& opt)
: options(opt),
event(false, false) {}
};
Thread::Thread(const char* name)
: stopping_(false),
startup_data_(NULL),
thread_(0),
message_loop_(NULL),
thread_id_(0),
name_(name) {
}
Thread::~Thread() {
Stop();
}
namespace {
// We use this thread-local variable to record whether or not a thread exited
// because its Stop method was called. This allows us to catch cases where
// MessageLoop::Quit() is called directly, which is unexpected when using a
// Thread to setup and run a MessageLoop.
base::LazyInstance<base::ThreadLocalBoolean> lazy_tls_bool(
base::LINKER_INITIALIZED);
} // namespace
void Thread::SetThreadWasQuitProperly(bool flag) {
lazy_tls_bool.Pointer()->Set(flag);
}
bool Thread::GetThreadWasQuitProperly() {
bool quit_properly = true;
#ifndef NDEBUG
quit_properly = lazy_tls_bool.Pointer()->Get();
#endif
return quit_properly;
}
bool Thread::Start() {
return StartWithOptions(Options());
}
bool Thread::StartWithOptions(const Options& options) {
DCHECK(!message_loop_);
SetThreadWasQuitProperly(false);
StartupData startup_data(options);
startup_data_ = &startup_data;
if (!PlatformThread::Create(options.stack_size, this, &thread_)) {
DLOG(ERROR) << "failed to create thread";
startup_data_ = NULL; // Record that we failed to start.
return false;
}
// Wait for the thread to start and initialize message_loop_
startup_data.event.Wait();
DCHECK(message_loop_);
return true;
}
void Thread::Stop() {
if (!thread_was_started())
return;
StopSoon();
// Wait for the thread to exit.
//
// TODO(darin): Unfortunately, we need to keep message_loop_ around until
// the thread exits. Some consumers are abusing the API. Make them stop.
//
PlatformThread::Join(thread_);
// The thread should NULL message_loop_ on exit.
DCHECK(!message_loop_);
// The thread no longer needs to be joined.
startup_data_ = NULL;
stopping_ = false;
}
void Thread::StopSoon() {
// We should only be called on the same thread that started us.
// Reading thread_id_ without a lock can lead to a benign data race
// with ThreadMain, so we annotate it to stay silent under ThreadSanitizer.
DCHECK_NE(ANNOTATE_UNPROTECTED_READ(thread_id_), PlatformThread::CurrentId());
if (stopping_ || !message_loop_)
return;
stopping_ = true;
message_loop_->PostTask(FROM_HERE, new ThreadQuitTask());
}
void Thread::Run(MessageLoop* message_loop) {
message_loop->Run();
}
void Thread::ThreadMain() {
{
// The message loop for this thread.
MessageLoop message_loop(startup_data_->options.message_loop_type);
// Complete the initialization of our Thread object.
thread_id_ = PlatformThread::CurrentId();
PlatformThread::SetName(name_.c_str());
ANNOTATE_THREAD_NAME(name_.c_str()); // Tell the name to race detector.
message_loop.set_thread_name(name_);
message_loop_ = &message_loop;
message_loop_proxy_ = MessageLoopProxy::CreateForCurrentThread();
// Let the thread do extra initialization.
// Let's do this before signaling we are started.
Init();
startup_data_->event.Signal();
// startup_data_ can't be touched anymore since the starting thread is now
// unlocked.
Run(message_loop_);
// Let the thread do extra cleanup.
CleanUp();
// Assert that MessageLoop::Quit was called by ThreadQuitTask.
DCHECK(GetThreadWasQuitProperly());
// We can't receive messages anymore.
message_loop_ = NULL;
message_loop_proxy_ = NULL;
}
CleanUpAfterMessageLoopDestruction();
thread_id_ = 0;
}
} // namespace base
<|endoftext|> |
<commit_before>/*!
* \file glyph_render_data_restricted_rays.hpp
* \brief file glyph_render_data_restricted_rays.hpp
*
* Copyright 2018 by Intel.
*
* Contact: [email protected]
*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with
* this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* \author Kevin Rogovin <[email protected]>
*
*/
#pragma once
#include <fastuidraw/util/rect.hpp>
#include <fastuidraw/text/glyph_render_data.hpp>
#include <fastuidraw/painter/painter_enums.hpp>
namespace fastuidraw
{
/*!\addtogroup Text
* @{
*/
/*!
* A GlyphRenderDataRestrictedRays represents the data needed to
* build a glyph to render it with a modification to the technique
* of "GPU-Centered Font Rendering Directly from Glyph Outlines"
* by Eric Lengyel. The modifications we have to the technique are
* as follows.
* - We break the glyph's box into a hierarchy of boxes where
* each leaf node has a list of what curves are in the box
* together with a single sample point inside the box giving
* the winding number at the sample point.
* - To compute the winding number, one runs the technique
* on the ray connecting the fragment position to the winding
* sample position and increment the value by the winding value
* of the sample. Here the main caveat is that one needs to
* ignore any intersection that are not between the fragment
* position and the sample position.
* - The shader (which can be fetched with the function
* fastuidraw::glsl::restricted_rays_compute_coverage())
* tracks the closest curve (in a local L1-metric scaled to
* window coordinates) to the fragment position that increments
* the winding value and also tracks the closest curve that
* decrements the winding value. Using those two values together
* with the winding value allows the shader to compute a coverage
* value to perform anti-aliasing.
*/
class GlyphRenderDataRestrictedRays:public GlyphRenderData
{
public:
/*!
* Enumeration to describe the hierarchy of bounding
* boxes as packed into the data. A node in the
* hierarchy is a single 32-bit value. A leaf in the
* hierarchy is a single 32-bit value followed by a
* single sample point which has a winding value
* and offset position packed as according to \ref
* winding_sample_packing_t.
*/
enum hierarchy_packing_t
{
/*!
* This is the number of bits used to store the
* offsets to a child node.
*/
hierarchy_child_offset_numbits = 15u,
/*!
* For case where the element is leaf, i.e. the
* bit \ref hierarchy_is_node_bit is down. This
* is the number bit used to encode the offset
* to where the list of curves for the box is
* located. The list of curves is packed as
* according to \ref curve_list_packing_t.
*/
hierarchy_leaf_curve_list_numbits = 16u,
/*!
* For case where the element is leaf, i.e. the
* bit \ref hierarchy_is_node_bit is down. This
* is the number of bits used to encode the size
* of the list of curves for the box is located.
* The list of curves is packed as according to
* \ref curve_list_packing_t.
*/
hierarchy_leaf_curve_list_size_numbits = 15u,
/*!
* If this bit is up, indicates that the 32-bit value
* is holding node data. If the bit is down indicates
* that the element is a leaf and the value holds the
* properties of the curve list in the box and the next
* value holds the winding sample information for the
* box and are packed as according to \ref
* winding_sample_packing_t.
*/
hierarchy_is_node_bit = 0u,
/*!
* For case where the element is a node, i.e. the
* bit \ref hierarchy_is_node_bit is up. This bit
* indicates if the split of the node is horizontal
* of verical. A value of 0 indicates that the split
* happens in the x-coordinate (i.e. the child nodes
* have the same values for min-y and max-y) and a
* value of 1 indicates the split happens in the
* y-coordinate.
*/
hierarchy_splitting_coordinate_bit = hierarchy_is_node_bit + 1u,
/*!
* For case where the element is a node, i.e. the
* bit \ref hierarchy_is_node_bit is up. This is
* the first bit holding the offset from the start
* of the geomertic data of the glyph for the child
* node which comes before the split, i.e. the child
* on the left or bottom side.
*/
hierarchy_child0_offset_bit0 = hierarchy_splitting_coordinate_bit + 1u,
/*!
* For case where the element is a node, i.e. the
* bit \ref hierarchy_is_node_bit is up. This is
* the first bit holding the offset from the start
* of the geomertic data of the glyph for the child
* node which comes after the split, i.e. the child
* on the right or top side.
*/
hierarchy_child1_offset_bit0 = hierarchy_child0_offset_bit0 + hierarchy_child_offset_numbits,
/*!
* For case where the element is leaf, i.e. the
* bit \ref hierarchy_is_node_bit is down. This
* is the first bit used to encode the offset
* to where the list of curves for the box is
* located. The list of curves is packed as
* according to \ref curve_list_packing_t.
*/
hierarchy_leaf_curve_list_bit0 = hierarchy_is_node_bit + 1u,
/*!
* For case where the element is leaf, i.e. the
* bit \ref hierarchy_is_node_bit is down. This
* is the first bit used to encode the size
* of the list of curves for the box is located.
* The list of curves is packed as according to
* \ref curve_list_packing_t.
*/
hierarchy_leaf_curve_list_size_bit0 = hierarchy_leaf_curve_list_bit0 + hierarchy_leaf_curve_list_numbits,
};
/*!
* Enumeration to describe how the winding samples
* of a leaf-box of the hierarchy are packed. The
* position of the sample is the bottom left corner
* of the node offset by a delta:
* $ Delta = RelativeDelta * BoxDimensions / DeltaFactor $
* where PackedDelta is extracted from the 32-bit
* value as a pair of 8-bit values located at bits
* \ref delta_x_bit0 and \ref delta_y_bit0; DeltaFactor
* is given by \ref delta_div_factor and BoxDimensions
* is the width and height of the box of the leaf.
*/
enum winding_sample_packing_t
{
/*!
* Winding values are stored biased (in order
* to be able to store negative winding values)
* This is the value to add to the unpacked
* winding number found at bit \ref
* winding_value_bit0
*/
winding_bias = 32768u,
/*!
* The first bit used to encode the winding value
* (which is stored biased by \ref winding_bias).
*/
winding_value_bit0 = 0u,
/*!
* The number of bits used to encode the winding value
* (which is stored biased by \ref winding_bias).
*/
winding_value_numbits = 16u,
/*!
* The amount by which to divide the delta
*/
delta_div_factor = 256,
/*!
* The first bit used to store the delta x-coordinate
*/
delta_x_bit0 = 16u,
/*!
* The first bit used to store the delta y-coordinate
*/
delta_y_bit0 = 24u,
/*!
* The number of bits used to store the delta x-coordinate
* and delta y-coordinate values.
*/
delta_numbits = 8u,
};
/*!
* Enumeration to describe how a list of curves is packed.
* Each 32-bit value holds the data for two curves.
* A curve entry is 16-bit value whose highest bit gives the
* degree of the curve and the remaining 15-bits give the
* offset to the location of the curve's control points.
*/
enum curve_list_packing_t
{
/*!
* The number of bits to store a single curve entry.
*/
curve_numbits = 16u,
/*!
* The first bit used for the first curve of the entry.
*/
curve_entry0_bit0 = 0u,
/*!
* The first bit used for the second curve of the entry.
*/
curve_entry1_bit0 = 16u,
/*!
* Given an unpacked curve entry (which is 16-bits wide),
* if this bit of the value is up, then the curve referenced
* is a quadratic Bezier curve having control points. Otherwise,
* it is a line segment connecting its two points.
*/
curve_is_quadratic_bit = 15u,
/*!
* Given an unpacked curve entry (which is 16-bits wide),
* this is the first bit used to store the offset to the
* location of the points of the curve (packed as according
* to \ref point_packing_t).
*/
curve_location_bit0 = 0u,
/*!
* Given an unpacked curve entry (which is 16-bits wide),
* this is the number of bits used to store the offset to the
* location of the points of the curve (packed as according
* to \ref point_packing_t).
*/
curve_location_numbits = 15u,
};
/*!
* Points are packed as (fp16, fp16) pairs.
*/
enum point_packing_t
{
};
enum
{
/* The glyph coordinate value in each coordiante varies
* from -\ref glyph_coord_value to +\ref glyph_coord_value
*/
glyph_coord_value = 32,
};
/*!
* This enumeration describes the meaning of the
* attributes. The glyph shader is to assume that
* the glyph-coordinates at the min-corner is
* (-\ref glyph_coord_value, -\ref glyph_coord_value)
* and the glyph coordiantes at the max-corner is
* (+\ref glyph_coord_value, +\ref glyph_coord_value)
*/
enum attribute_values_t
{
/*!
* Value is 0 if on min-x side of glyph, value is
* 1 if on max-x side of glyph; packed as uint.
*/
glyph_normalized_x,
/*!
* Value is 0 if on min-y side of glyph, value is
* 1 if on max-y side of glyph; packed as uint.
*/
glyph_normalized_y,
/*!
* the index into GlyphAttribute::m_data storing
* the fill rule and the offset into the store for
* the glyph data. The offset is encoded in the
* lower 31 bits (i.e. just mask off bit31) and
* the fill rule is non-zero fill rule if bit31
* is down and the odd-even fill rule if bit31 is
* up.
*/
glyph_offset,
/*!
* Number attribute values needed.
*/
glyph_num_attributes
};
/*!
* Ctor.
*/
GlyphRenderDataRestrictedRays(void);
~GlyphRenderDataRestrictedRays();
/*!
* Start a contour. Before starting a new contour
* the previous contour must be closed by calling
* line_to() or quadratic_to() connecting to the
* start point of the previous contour.
* \param pt start point of the new contour
*/
void
move_to(ivec2 pt);
/*!
* Add a line segment connecting the end point of the
* last curve or line segment of the current contour to
* a given point.
* \param pt end point of the new line segment
*/
void
line_to(ivec2 pt);
/*!
* Add a quadratic curveconnecting the end point of the
* last curve or line segment of the current contour
* \param ct control point of the quadratic curve
* \param pt end point of the quadratic curve
*/
void
quadratic_to(ivec2 ct, ivec2 pt);
/*!
* Finalize the input data after which no more contours or curves may be added;
* all added contours must be closed before calling finalize(). Once finalize()
* is called, no further data can be added. How the data is broken into bounding
* boxes is specified by
* - units_per_EM argument (see below)
* - GlyphGenerateParams::restricted_rays_minimum_render_size()
* - GlyphGenerateParams::restricted_rays_split_thresh()
* - GlyphGenerateParams::restricted_rays_max_recursion()
* All contours added must be closed as well.
* \param f fill rule to use for rendering, must be one of
* PainterEnums::nonzero_fill_rule or \ref
* PainterEnums::odd_even_fill_rule.
* \param glyph_rect the rect of the glyph
* \param units_per_EM the units per EM for the glyph; this value together with
* GlyphGenerateParams::restricted_rays_minimum_render_size()
* is used to decide how close a curve may be to a bounding
* box to decide if it is included.
*/
void
finalize(enum PainterEnums::fill_rule_t f, const RectT<int> &glyph_rect,
float units_per_EM);
/*!
* Finalize the input data after which no more contours or curves may be added;
* all added contours must be closed before calling finale(). Once finalize()
* is called, no further data can be added. Instead of using methods from
* \ref GlyphGenerateParams, directly specify how the data is broken into
* boxes.
* \param f fill rule to use for rendering, must be one of
* PainterEnums::nonzero_fill_rule or \ref
* PainterEnums::odd_even_fill_rule.
* \param glyph_rect the rect of the glyph
* \param split_thresh if the number of curves within a box is greater than
* this value, the box is split
* \param max_recursion the maximum level of recursion allowed in splitting
* the data into boxes
* \param near_thresh horizontal and vertical threshhold to decide if a curve
* outside of a box should be added to a box
*/
void
finalize(enum PainterEnums::fill_rule_t f, const RectT<int> &glyph_rect,
int split_thresh, int max_recursion, vec2 near_thresh);
/*!
* Query the data; may only be called after finalize(). Returns
* \ref routine_fail if finalize() has not yet been called.
* \param gpu_data location to which to write a c_array to the
* GPU data.
*/
enum return_code
query(c_array<const fastuidraw::generic_data> *gpu_data) const;
virtual
enum fastuidraw::return_code
upload_to_atlas(GlyphAtlasProxy &atlas_proxy,
GlyphAttribute::Array &attributes) const;
private:
void *m_d;
};
/*! @} */
}
<commit_msg>fastuidraw/text/glyph_render_data_restricted_rays: make the fixed value much larger, with the previous smaller fixed-coordinate value extreme magnification can result in bizarre bleeding<commit_after>/*!
* \file glyph_render_data_restricted_rays.hpp
* \brief file glyph_render_data_restricted_rays.hpp
*
* Copyright 2018 by Intel.
*
* Contact: [email protected]
*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with
* this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* \author Kevin Rogovin <[email protected]>
*
*/
#pragma once
#include <fastuidraw/util/rect.hpp>
#include <fastuidraw/text/glyph_render_data.hpp>
#include <fastuidraw/painter/painter_enums.hpp>
namespace fastuidraw
{
/*!\addtogroup Text
* @{
*/
/*!
* A GlyphRenderDataRestrictedRays represents the data needed to
* build a glyph to render it with a modification to the technique
* of "GPU-Centered Font Rendering Directly from Glyph Outlines"
* by Eric Lengyel. The modifications we have to the technique are
* as follows.
* - We break the glyph's box into a hierarchy of boxes where
* each leaf node has a list of what curves are in the box
* together with a single sample point inside the box giving
* the winding number at the sample point.
* - To compute the winding number, one runs the technique
* on the ray connecting the fragment position to the winding
* sample position and increment the value by the winding value
* of the sample. Here the main caveat is that one needs to
* ignore any intersection that are not between the fragment
* position and the sample position.
* - The shader (which can be fetched with the function
* fastuidraw::glsl::restricted_rays_compute_coverage())
* tracks the closest curve (in a local L1-metric scaled to
* window coordinates) to the fragment position that increments
* the winding value and also tracks the closest curve that
* decrements the winding value. Using those two values together
* with the winding value allows the shader to compute a coverage
* value to perform anti-aliasing.
*/
class GlyphRenderDataRestrictedRays:public GlyphRenderData
{
public:
/*!
* Enumeration to describe the hierarchy of bounding
* boxes as packed into the data. A node in the
* hierarchy is a single 32-bit value. A leaf in the
* hierarchy is a single 32-bit value followed by a
* single sample point which has a winding value
* and offset position packed as according to \ref
* winding_sample_packing_t.
*/
enum hierarchy_packing_t
{
/*!
* This is the number of bits used to store the
* offsets to a child node.
*/
hierarchy_child_offset_numbits = 15u,
/*!
* For case where the element is leaf, i.e. the
* bit \ref hierarchy_is_node_bit is down. This
* is the number bit used to encode the offset
* to where the list of curves for the box is
* located. The list of curves is packed as
* according to \ref curve_list_packing_t.
*/
hierarchy_leaf_curve_list_numbits = 16u,
/*!
* For case where the element is leaf, i.e. the
* bit \ref hierarchy_is_node_bit is down. This
* is the number of bits used to encode the size
* of the list of curves for the box is located.
* The list of curves is packed as according to
* \ref curve_list_packing_t.
*/
hierarchy_leaf_curve_list_size_numbits = 15u,
/*!
* If this bit is up, indicates that the 32-bit value
* is holding node data. If the bit is down indicates
* that the element is a leaf and the value holds the
* properties of the curve list in the box and the next
* value holds the winding sample information for the
* box and are packed as according to \ref
* winding_sample_packing_t.
*/
hierarchy_is_node_bit = 0u,
/*!
* For case where the element is a node, i.e. the
* bit \ref hierarchy_is_node_bit is up. This bit
* indicates if the split of the node is horizontal
* of verical. A value of 0 indicates that the split
* happens in the x-coordinate (i.e. the child nodes
* have the same values for min-y and max-y) and a
* value of 1 indicates the split happens in the
* y-coordinate.
*/
hierarchy_splitting_coordinate_bit = hierarchy_is_node_bit + 1u,
/*!
* For case where the element is a node, i.e. the
* bit \ref hierarchy_is_node_bit is up. This is
* the first bit holding the offset from the start
* of the geomertic data of the glyph for the child
* node which comes before the split, i.e. the child
* on the left or bottom side.
*/
hierarchy_child0_offset_bit0 = hierarchy_splitting_coordinate_bit + 1u,
/*!
* For case where the element is a node, i.e. the
* bit \ref hierarchy_is_node_bit is up. This is
* the first bit holding the offset from the start
* of the geomertic data of the glyph for the child
* node which comes after the split, i.e. the child
* on the right or top side.
*/
hierarchy_child1_offset_bit0 = hierarchy_child0_offset_bit0 + hierarchy_child_offset_numbits,
/*!
* For case where the element is leaf, i.e. the
* bit \ref hierarchy_is_node_bit is down. This
* is the first bit used to encode the offset
* to where the list of curves for the box is
* located. The list of curves is packed as
* according to \ref curve_list_packing_t.
*/
hierarchy_leaf_curve_list_bit0 = hierarchy_is_node_bit + 1u,
/*!
* For case where the element is leaf, i.e. the
* bit \ref hierarchy_is_node_bit is down. This
* is the first bit used to encode the size
* of the list of curves for the box is located.
* The list of curves is packed as according to
* \ref curve_list_packing_t.
*/
hierarchy_leaf_curve_list_size_bit0 = hierarchy_leaf_curve_list_bit0 + hierarchy_leaf_curve_list_numbits,
};
/*!
* Enumeration to describe how the winding samples
* of a leaf-box of the hierarchy are packed. The
* position of the sample is the bottom left corner
* of the node offset by a delta:
* $ Delta = RelativeDelta * BoxDimensions / DeltaFactor $
* where PackedDelta is extracted from the 32-bit
* value as a pair of 8-bit values located at bits
* \ref delta_x_bit0 and \ref delta_y_bit0; DeltaFactor
* is given by \ref delta_div_factor and BoxDimensions
* is the width and height of the box of the leaf.
*/
enum winding_sample_packing_t
{
/*!
* Winding values are stored biased (in order
* to be able to store negative winding values)
* This is the value to add to the unpacked
* winding number found at bit \ref
* winding_value_bit0
*/
winding_bias = 32768u,
/*!
* The first bit used to encode the winding value
* (which is stored biased by \ref winding_bias).
*/
winding_value_bit0 = 0u,
/*!
* The number of bits used to encode the winding value
* (which is stored biased by \ref winding_bias).
*/
winding_value_numbits = 16u,
/*!
* The amount by which to divide the delta
*/
delta_div_factor = 256,
/*!
* The first bit used to store the delta x-coordinate
*/
delta_x_bit0 = 16u,
/*!
* The first bit used to store the delta y-coordinate
*/
delta_y_bit0 = 24u,
/*!
* The number of bits used to store the delta x-coordinate
* and delta y-coordinate values.
*/
delta_numbits = 8u,
};
/*!
* Enumeration to describe how a list of curves is packed.
* Each 32-bit value holds the data for two curves.
* A curve entry is 16-bit value whose highest bit gives the
* degree of the curve and the remaining 15-bits give the
* offset to the location of the curve's control points.
*/
enum curve_list_packing_t
{
/*!
* The number of bits to store a single curve entry.
*/
curve_numbits = 16u,
/*!
* The first bit used for the first curve of the entry.
*/
curve_entry0_bit0 = 0u,
/*!
* The first bit used for the second curve of the entry.
*/
curve_entry1_bit0 = 16u,
/*!
* Given an unpacked curve entry (which is 16-bits wide),
* if this bit of the value is up, then the curve referenced
* is a quadratic Bezier curve having control points. Otherwise,
* it is a line segment connecting its two points.
*/
curve_is_quadratic_bit = 15u,
/*!
* Given an unpacked curve entry (which is 16-bits wide),
* this is the first bit used to store the offset to the
* location of the points of the curve (packed as according
* to \ref point_packing_t).
*/
curve_location_bit0 = 0u,
/*!
* Given an unpacked curve entry (which is 16-bits wide),
* this is the number of bits used to store the offset to the
* location of the points of the curve (packed as according
* to \ref point_packing_t).
*/
curve_location_numbits = 15u,
};
/*!
* Points are packed as (fp16, fp16) pairs.
*/
enum point_packing_t
{
};
enum
{
/* The glyph coordinate value in each coordiante varies
* from -\ref glyph_coord_value to +\ref glyph_coord_value
*/
glyph_coord_value = 2048,
};
/*!
* This enumeration describes the meaning of the
* attributes. The glyph shader is to assume that
* the glyph-coordinates at the min-corner is
* (-\ref glyph_coord_value, -\ref glyph_coord_value)
* and the glyph coordiantes at the max-corner is
* (+\ref glyph_coord_value, +\ref glyph_coord_value)
*/
enum attribute_values_t
{
/*!
* Value is 0 if on min-x side of glyph, value is
* 1 if on max-x side of glyph; packed as uint.
*/
glyph_normalized_x,
/*!
* Value is 0 if on min-y side of glyph, value is
* 1 if on max-y side of glyph; packed as uint.
*/
glyph_normalized_y,
/*!
* the index into GlyphAttribute::m_data storing
* the fill rule and the offset into the store for
* the glyph data. The offset is encoded in the
* lower 31 bits (i.e. just mask off bit31) and
* the fill rule is non-zero fill rule if bit31
* is down and the odd-even fill rule if bit31 is
* up.
*/
glyph_offset,
/*!
* Number attribute values needed.
*/
glyph_num_attributes
};
/*!
* Ctor.
*/
GlyphRenderDataRestrictedRays(void);
~GlyphRenderDataRestrictedRays();
/*!
* Start a contour. Before starting a new contour
* the previous contour must be closed by calling
* line_to() or quadratic_to() connecting to the
* start point of the previous contour.
* \param pt start point of the new contour
*/
void
move_to(ivec2 pt);
/*!
* Add a line segment connecting the end point of the
* last curve or line segment of the current contour to
* a given point.
* \param pt end point of the new line segment
*/
void
line_to(ivec2 pt);
/*!
* Add a quadratic curveconnecting the end point of the
* last curve or line segment of the current contour
* \param ct control point of the quadratic curve
* \param pt end point of the quadratic curve
*/
void
quadratic_to(ivec2 ct, ivec2 pt);
/*!
* Finalize the input data after which no more contours or curves may be added;
* all added contours must be closed before calling finalize(). Once finalize()
* is called, no further data can be added. How the data is broken into bounding
* boxes is specified by
* - units_per_EM argument (see below)
* - GlyphGenerateParams::restricted_rays_minimum_render_size()
* - GlyphGenerateParams::restricted_rays_split_thresh()
* - GlyphGenerateParams::restricted_rays_max_recursion()
* All contours added must be closed as well.
* \param f fill rule to use for rendering, must be one of
* PainterEnums::nonzero_fill_rule or \ref
* PainterEnums::odd_even_fill_rule.
* \param glyph_rect the rect of the glyph
* \param units_per_EM the units per EM for the glyph; this value together with
* GlyphGenerateParams::restricted_rays_minimum_render_size()
* is used to decide how close a curve may be to a bounding
* box to decide if it is included.
*/
void
finalize(enum PainterEnums::fill_rule_t f, const RectT<int> &glyph_rect,
float units_per_EM);
/*!
* Finalize the input data after which no more contours or curves may be added;
* all added contours must be closed before calling finale(). Once finalize()
* is called, no further data can be added. Instead of using methods from
* \ref GlyphGenerateParams, directly specify how the data is broken into
* boxes.
* \param f fill rule to use for rendering, must be one of
* PainterEnums::nonzero_fill_rule or \ref
* PainterEnums::odd_even_fill_rule.
* \param glyph_rect the rect of the glyph
* \param split_thresh if the number of curves within a box is greater than
* this value, the box is split
* \param max_recursion the maximum level of recursion allowed in splitting
* the data into boxes
* \param near_thresh horizontal and vertical threshhold to decide if a curve
* outside of a box should be added to a box
*/
void
finalize(enum PainterEnums::fill_rule_t f, const RectT<int> &glyph_rect,
int split_thresh, int max_recursion, vec2 near_thresh);
/*!
* Query the data; may only be called after finalize(). Returns
* \ref routine_fail if finalize() has not yet been called.
* \param gpu_data location to which to write a c_array to the
* GPU data.
*/
enum return_code
query(c_array<const fastuidraw::generic_data> *gpu_data) const;
virtual
enum fastuidraw::return_code
upload_to_atlas(GlyphAtlasProxy &atlas_proxy,
GlyphAttribute::Array &attributes) const;
private:
void *m_d;
};
/*! @} */
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <iomanip>
#include <unistd.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <test.h>
///////////////////////////////////////////////////////////////////////////////
UnitTest::UnitTest ()
: _planned (0)
, _counter (0)
, _passed (0)
, _failed (0)
, _skipped (0)
{
}
///////////////////////////////////////////////////////////////////////////////
UnitTest::UnitTest (int planned)
: _planned (planned)
, _counter (0)
, _passed (0)
, _failed (0)
, _skipped (0)
{
std::cout << "1.." << _planned << "\n";
}
///////////////////////////////////////////////////////////////////////////////
UnitTest::~UnitTest ()
{
float percentPassed = 0.0;
if (_planned > 0)
percentPassed = (100.0 * _passed) / std::max (_planned, _passed + _failed + _skipped);
if (_counter < _planned)
{
std::cout << "# Only "
<< _counter
<< " tests, out of a planned "
<< _planned
<< " were run.\n";
_skipped += _planned - _counter;
}
else if (_counter > _planned)
std::cout << "# "
<< _counter
<< " tests were run, but only "
<< _planned
<< " were planned.\n";
std::cout << "# "
<< _passed
<< " passed, "
<< _failed
<< " failed, "
<< _skipped
<< " skipped. "
<< std::setprecision (3) << percentPassed
<< "% passed.\n";
exit (_failed > 0);
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::plan (int planned)
{
_planned = planned;
_counter = 0;
_passed = 0;
_failed = 0;
_skipped = 0;
std::cout << "1.." << _planned << "\n";
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::planMore (int extra)
{
_planned += extra;
std::cout << "1.." << _planned << "\n";
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::ok (bool expression, const std::string& name)
{
++_counter;
if (expression)
{
++_passed;
std::cout << green ("ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
else
{
++_failed;
std::cout << red ("not ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::notok (bool expression, const std::string& name)
{
++_counter;
if (!expression)
{
++_passed;
std::cout << green ("ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
else
{
++_failed;
std::cout << red ("not ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::is (bool actual, bool expected, const std::string& name)
{
++_counter;
if (actual == expected)
{
++_passed;
std::cout << green ("ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
else
{
++_failed;
std::cout << red ("not ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n# expected: "
<< expected
<< "\n# got: "
<< actual
<< "\n";
}
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::is (size_t actual, size_t expected, const std::string& name)
{
++_counter;
if (actual == expected)
{
++_passed;
std::cout << green ("ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
else
{
++_failed;
std::cout << red ("not ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n# expected: "
<< expected
<< "\n# got: "
<< actual
<< "\n";
}
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::is (int actual, int expected, const std::string& name)
{
++_counter;
if (actual == expected)
{
++_passed;
std::cout << green ("ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
else
{
++_failed;
std::cout << red ("not ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n# expected: "
<< expected
<< "\n# got: "
<< actual
<< "\n";
}
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::is (double actual, double expected, const std::string& name)
{
++_counter;
if (actual == expected)
{
++_passed;
std::cout << green ("ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
else
{
++_failed;
std::cout << red ("not ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n# expected: "
<< expected
<< "\n# got: "
<< actual
<< "\n";
}
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::is (double actual, double expected, double tolerance, const std::string& name)
{
++_counter;
if (fabs (actual - expected) <= tolerance)
{
++_passed;
std::cout << green ("ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
else
{
++_failed;
std::cout << red ("not ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n# expected: "
<< expected
<< "\n# got: "
<< actual
<< "\n";
}
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::is (unsigned char actual, unsigned char expected, const std::string& name)
{
++_counter;
if (actual == expected)
{
++_passed;
std::cout << green ("ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
else
{
++_failed;
std::cout << red ("not ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n# expected: "
<< expected
<< "\n# got: "
<< actual
<< "\n";
}
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::is (
const std::string& actual,
const std::string& expected,
const std::string& name)
{
++_counter;
if (actual == expected)
{
++_passed;
std::cout << green ("ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
else
{
++_failed;
std::cout << red ("not ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n# expected: '"
<< expected
<< "'"
<< "\n# got: '"
<< actual
<< "'\n";
}
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::is (
const char* actual,
const char* expected,
const std::string& name)
{
++_counter;
if (! strcmp (actual, expected))
{
++_passed;
std::cout << green ("ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
else
{
++_failed;
std::cout << red ("not ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n# expected: '"
<< expected
<< "'"
<< "\n# got: '"
<< actual
<< "'\n";
}
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::diag (const std::string& text)
{
auto start = text.find_first_not_of (" \t\n\r\f");
auto end = text.find_last_not_of (" \t\n\r\f");
std::cout << "# " << text.substr (start, end - start + 1) << "\n";
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::pass (const std::string& text)
{
++_counter;
++_passed;
std::cout << green ("ok")
<< " "
<< _counter
<< " - "
<< text
<< "\n";
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::fail (const std::string& text)
{
++_counter;
++_failed;
std::cout << red ("not ok")
<< " "
<< _counter
<< " - "
<< text
<< "\n";
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::skip (const std::string& text)
{
++_counter;
++_skipped;
std::cout << yellow ("skip")
<< " "
<< _counter
<< " - "
<< text
<< "\n";
}
///////////////////////////////////////////////////////////////////////////////
std::string UnitTest::red (const std::string& input)
{
if (isatty (fileno (stdout)))
return std::string ("\033[31m" + input + "\033[0m");
return input;
}
///////////////////////////////////////////////////////////////////////////////
std::string UnitTest::green (const std::string& input)
{
if (isatty (fileno (stdout)))
return std::string ("\033[32m" + input + "\033[0m");
return input;
}
///////////////////////////////////////////////////////////////////////////////
std::string UnitTest::yellow (const std::string& input)
{
if (isatty (fileno (stdout)))
return std::string ("\033[33m" + input + "\033[0m");
return input;
}
///////////////////////////////////////////////////////////////////////////////
<commit_msg>Test: Added missing include for Cygwin<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <iomanip>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <test.h>
///////////////////////////////////////////////////////////////////////////////
UnitTest::UnitTest ()
: _planned (0)
, _counter (0)
, _passed (0)
, _failed (0)
, _skipped (0)
{
}
///////////////////////////////////////////////////////////////////////////////
UnitTest::UnitTest (int planned)
: _planned (planned)
, _counter (0)
, _passed (0)
, _failed (0)
, _skipped (0)
{
std::cout << "1.." << _planned << "\n";
}
///////////////////////////////////////////////////////////////////////////////
UnitTest::~UnitTest ()
{
float percentPassed = 0.0;
if (_planned > 0)
percentPassed = (100.0 * _passed) / std::max (_planned, _passed + _failed + _skipped);
if (_counter < _planned)
{
std::cout << "# Only "
<< _counter
<< " tests, out of a planned "
<< _planned
<< " were run.\n";
_skipped += _planned - _counter;
}
else if (_counter > _planned)
std::cout << "# "
<< _counter
<< " tests were run, but only "
<< _planned
<< " were planned.\n";
std::cout << "# "
<< _passed
<< " passed, "
<< _failed
<< " failed, "
<< _skipped
<< " skipped. "
<< std::setprecision (3) << percentPassed
<< "% passed.\n";
exit (_failed > 0);
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::plan (int planned)
{
_planned = planned;
_counter = 0;
_passed = 0;
_failed = 0;
_skipped = 0;
std::cout << "1.." << _planned << "\n";
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::planMore (int extra)
{
_planned += extra;
std::cout << "1.." << _planned << "\n";
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::ok (bool expression, const std::string& name)
{
++_counter;
if (expression)
{
++_passed;
std::cout << green ("ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
else
{
++_failed;
std::cout << red ("not ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::notok (bool expression, const std::string& name)
{
++_counter;
if (!expression)
{
++_passed;
std::cout << green ("ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
else
{
++_failed;
std::cout << red ("not ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::is (bool actual, bool expected, const std::string& name)
{
++_counter;
if (actual == expected)
{
++_passed;
std::cout << green ("ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
else
{
++_failed;
std::cout << red ("not ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n# expected: "
<< expected
<< "\n# got: "
<< actual
<< "\n";
}
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::is (size_t actual, size_t expected, const std::string& name)
{
++_counter;
if (actual == expected)
{
++_passed;
std::cout << green ("ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
else
{
++_failed;
std::cout << red ("not ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n# expected: "
<< expected
<< "\n# got: "
<< actual
<< "\n";
}
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::is (int actual, int expected, const std::string& name)
{
++_counter;
if (actual == expected)
{
++_passed;
std::cout << green ("ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
else
{
++_failed;
std::cout << red ("not ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n# expected: "
<< expected
<< "\n# got: "
<< actual
<< "\n";
}
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::is (double actual, double expected, const std::string& name)
{
++_counter;
if (actual == expected)
{
++_passed;
std::cout << green ("ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
else
{
++_failed;
std::cout << red ("not ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n# expected: "
<< expected
<< "\n# got: "
<< actual
<< "\n";
}
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::is (double actual, double expected, double tolerance, const std::string& name)
{
++_counter;
if (fabs (actual - expected) <= tolerance)
{
++_passed;
std::cout << green ("ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
else
{
++_failed;
std::cout << red ("not ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n# expected: "
<< expected
<< "\n# got: "
<< actual
<< "\n";
}
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::is (unsigned char actual, unsigned char expected, const std::string& name)
{
++_counter;
if (actual == expected)
{
++_passed;
std::cout << green ("ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
else
{
++_failed;
std::cout << red ("not ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n# expected: "
<< expected
<< "\n# got: "
<< actual
<< "\n";
}
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::is (
const std::string& actual,
const std::string& expected,
const std::string& name)
{
++_counter;
if (actual == expected)
{
++_passed;
std::cout << green ("ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
else
{
++_failed;
std::cout << red ("not ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n# expected: '"
<< expected
<< "'"
<< "\n# got: '"
<< actual
<< "'\n";
}
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::is (
const char* actual,
const char* expected,
const std::string& name)
{
++_counter;
if (! strcmp (actual, expected))
{
++_passed;
std::cout << green ("ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n";
}
else
{
++_failed;
std::cout << red ("not ok")
<< " "
<< _counter
<< " - "
<< name
<< "\n# expected: '"
<< expected
<< "'"
<< "\n# got: '"
<< actual
<< "'\n";
}
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::diag (const std::string& text)
{
auto start = text.find_first_not_of (" \t\n\r\f");
auto end = text.find_last_not_of (" \t\n\r\f");
std::cout << "# " << text.substr (start, end - start + 1) << "\n";
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::pass (const std::string& text)
{
++_counter;
++_passed;
std::cout << green ("ok")
<< " "
<< _counter
<< " - "
<< text
<< "\n";
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::fail (const std::string& text)
{
++_counter;
++_failed;
std::cout << red ("not ok")
<< " "
<< _counter
<< " - "
<< text
<< "\n";
}
///////////////////////////////////////////////////////////////////////////////
void UnitTest::skip (const std::string& text)
{
++_counter;
++_skipped;
std::cout << yellow ("skip")
<< " "
<< _counter
<< " - "
<< text
<< "\n";
}
///////////////////////////////////////////////////////////////////////////////
std::string UnitTest::red (const std::string& input)
{
if (isatty (fileno (stdout)))
return std::string ("\033[31m" + input + "\033[0m");
return input;
}
///////////////////////////////////////////////////////////////////////////////
std::string UnitTest::green (const std::string& input)
{
if (isatty (fileno (stdout)))
return std::string ("\033[32m" + input + "\033[0m");
return input;
}
///////////////////////////////////////////////////////////////////////////////
std::string UnitTest::yellow (const std::string& input)
{
if (isatty (fileno (stdout)))
return std::string ("\033[33m" + input + "\033[0m");
return input;
}
///////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>#include <cassert>
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <vector>
#include <deque>
#include "gemmbitserial.hpp"
#include "mnistdata.h"
using namespace std;
using namespace gemmbitserial;
#define VERBOSE_TEST(x) ;
//#define VERBOSE_TEST(x) x
// Generate a random vector of -1 and +1 values of given dimension
template <typename T>
void generateRandomVector_Bipolar(size_t dim, T * ret) {
for(size_t i = 0; i < dim; i++) {
ret[i] = (rand() % 2 == 0) ? 1 : -1;
}
}
/**
* Generate a random vector with given dimension and number of bits
*/
template <typename T>
void generateRandomVector(size_t bits, size_t dim, T * ret, bool allowNeg = false) {
assert(bits <= (sizeof(T) * 8));
if(bits == 1 && allowNeg) {
// generate bipolar values
generateRandomVector_Bipolar(dim, ret);
return;
}
int32_t minVal = 0;
int32_t maxVal = (1 << bits);
for(size_t i = 0; i < dim; i++) {
ret[i] = (rand() % maxVal) - (allowNeg ? maxVal/2 : 0);
}
}
template <typename LHSType, typename RHSType>
void naive_int_gemm(LHSType * lhs, RHSType * rhs, int32_t * res, int rows, int depth, int cols) {
for(int k = 0; k < cols; k++) {
for(int i = 0; i < rows; i++) {
int32_t acc = 0;
for(int j = 0; j < depth; j++) {
acc += lhs[i * depth + j] * rhs[k * depth + j];
}
res[k * rows + i] = acc;
}
}
}
template <typename T>
void naive_sum_rows(T * m, int32_t * res, int rows, int cols) {
for(int i = 0; i < rows; i++) {
int32_t acc = 0;
for(int k = 0; k < cols; k++) {
acc += m[i * cols + k];
}
res[i] = acc;
}
}
template <typename T>
void printmatrix(T * mat, int rows, int cols) {
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
cout << (int) mat[i * cols + j] << " ";
}
cout << endl;
}
cout << endl;
}
template <typename T>
void printmatrixdiff(const T * mat1, const T * mat2, int rows, int cols) {
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
if(mat1[i * cols + j] != mat2[i * cols + j]) {
cout << "Difference at (i,j) = " << i << " " << j << " Mat1: " << (int)mat1[i * cols + j] << " Mat2: " << mat2[i * cols + j] << endl;
}
}
}
cout << endl;
}
void printBitSerialMatrix(BitSerialMatrix * bsm) {
cout << "BitSerialMatrix with bits " << bsm->nbits << " rows " << bsm->nrows << " cols " << bsm->ncols << endl;
for(int b = 0; b < bsm->nbits; b++) {
cout << "bit " << b << ":" << endl;
for(int r = 0; r < bsm->nrows; r++) {
for(int c = 0; c < bsm->ncols; c++) {
cout << (bsm->get(b,r,c) ? 1 : 0) << " ";
}
cout << endl << endl;
}
}
}
bool test_rowwise_sum() {
vector<size_t> param_bits {1, 2, 3, 4};
vector<size_t> param_dims {4, 16, 17, 32, 77, 100, 1023};
vector<int> param_signed {1, 0};
unsigned int numConfigs = 0, ok = 0, nok = 0;
for(auto & b: param_bits) {
for(auto & d: param_dims) {
for(auto & sgnd: param_signed) {
bool isSigned = (bool) sgnd;
int8_t * rnd_mat = new int8_t[d*d];
int32_t * res_ret = new int32_t[d];
int32_t * res_golden = new int32_t[d];
generateRandomVector(b, d*d, rnd_mat, isSigned);
BitSerialMatrix bsm = BitSerialMatrix::alloc(b, d, d, isSigned);
bsm.importRegular(rnd_mat);
sumRows(bsm, res_ret);
naive_sum_rows(rnd_mat, res_golden, d, d);
int res = memcmp(res_ret, res_golden, d);
if(res == 0) {
ok++;
} else {
nok++;
}
//printmatrix(rnd_mat, d, d);
//printmatrix(res_golden, d, 1);
//printmatrix(res_ret, d, 1);
BitSerialMatrix::dealloc(bsm);
delete [] rnd_mat;
delete [] res_golden;
delete [] res_ret;
numConfigs++;
VERBOSE_TEST(cout << "Bits = " << b << " dim = " << d << " result = " << res << endl);
}
}
}
cout << "Row-wise sum tests: " << ok << " OK, " << nok << " NOK" << endl;
return ok == numConfigs;
}
bool test_conversions() {
vector<size_t> param_bits {1, 2, 3, 7};
vector<size_t> param_dims {4, 16, 17, 32, 77, 100, 1023};
vector<int> param_signed {1, 0};
unsigned int numConfigs = 0, ok = 0, nok = 0;
for(auto & b: param_bits) {
for(auto & d: param_dims) {
for(auto & sgnd: param_signed) {
int8_t * res_chk = new int8_t[d*d];
int8_t * rnd_vec = new int8_t[d*d];
assert(res_chk != 0 && rnd_vec != 0);
generateRandomVector(b, d*d, rnd_vec, (bool) sgnd);
BitSerialMatrix bsm = BitSerialMatrix::alloc(b, d, d, (bool) sgnd);
bsm.importRegular(rnd_vec);
bsm.exportRegular(res_chk);
//printmatrix(rnd_vec, d, d);
//printmatrix(res_chk, d, d);
int res = memcmp(rnd_vec, res_chk, d);
if(res == 0) {
ok++;
} else {
nok++;
}
delete [] rnd_vec;
delete [] res_chk;
BitSerialMatrix::dealloc(bsm);
numConfigs++;
VERBOSE_TEST(cout << "Bits = " << b << " dim = " << d << " result = " << res << endl);
}
}
}
cout << "Conversion tests: " << ok << " OK, " << nok << " NOK" << endl;
return ok == numConfigs;
}
bool test_matrix_matrix() {
vector<size_t> param_bits {2, 3, 4};
vector<size_t> param_dims {3, 5, 7, 16, 17, 18, 30, 31, 32, 100, 177, 256};
deque<bool> param_allow_neg {false, true};
unsigned int numConfigs = 0, ok = 0, nok = 0;
for(auto & b: param_bits) {
for(auto & d: param_dims) {
uint8_t * rnd_mat_a = new uint8_t[d*d*2];
uint8_t * rnd_mat_b = new uint8_t[2*d*d*3];
int32_t * res_mat_golden = new int32_t[d*d*3];
generateRandomVector(b, d*d*2, rnd_mat_a);
generateRandomVector(b, 2*d*d*3, rnd_mat_b);
naive_int_gemm(rnd_mat_a, rnd_mat_b, res_mat_golden, d, 2*d, d*3);
GEMMContext ctx = allocGEMMContext(d, 2*d, 3*d, b, b, false, false);
ctx.lhs.importRegular(rnd_mat_a);
ctx.rhs.importRegular(rnd_mat_b);
gemmBitSerial(ctx);
//ctx.printSummary();
//printmatrix(rnd_mat_a, d, d*2);
//printmatrix(rnd_mat_b, d*3, d*2);
//printmatrix(res_mat_golden, d*3, d);
//printmatrix(ctx.res, d*3, d);
int rbytes = d*d*3*sizeof(int32_t);
int res = memcmp(ctx.res, res_mat_golden, rbytes);
if(res == 0) {
ok++;
} else {
nok++;
//printmatrixdiff(res_mat, res_mat_golden, 3*d, d);
}
delete [] rnd_mat_a;
delete [] rnd_mat_b;
delete [] res_mat_golden;
deallocGEMMContext(ctx);
numConfigs++;
VERBOSE_TEST(cout << "Bits = " << b << " dim = " << d << " result = " << res << endl);
}
}
cout << "Matrix matrix multiplication tests: " << ok << " OK, " << nok << " NOK" << endl;
return ok == numConfigs;
}
bool test_mnist() {
// test bit serial gemm using real-life matrix data from a MNIST neural net
GEMMContext ctx = allocGEMMContext(
MNIST_OUT, MNIST_IN, 1, MNIST_WBITS, MNIST_ABITS, MNIST_WSIGN, MNIST_ASIGN
);
ctx.lhs.importRegular(mnist_weights);
ctx.rhs.importRegular(mnist_in);
gemmBitSerial(ctx);
int res = memcmp(ctx.res, mnist_res_golden, MNIST_OUT*sizeof(int32_t));
cout << "MNIST matrix-vector: " << (res == 0 ? "OK" : "NOK") << endl;
if(res != 0) {
printmatrixdiff(ctx.res, mnist_res_golden, 1, MNIST_OUT);
}
deallocGEMMContext(ctx);
return res == 0;
}
bool test_bipolar() {
unsigned int numConfigs = 0, ok = 0, nok = 0;
size_t d = 4, dc = 4;
size_t lhs_bits = 1, rhs_bits = 2;
bool lhs_sign = true, rhs_sign = false;
int8_t * bipolar_mat = new int8_t[d*d];
uint8_t * regular_mat = new uint8_t[d*dc];
int32_t * res_golden = new int32_t[d*dc];
int32_t * res_chk = new int32_t[d*dc];
GEMMContext ctx = allocGEMMContext(
d, d, dc, lhs_bits, rhs_bits, lhs_sign, rhs_sign
);
generateRandomVector_Bipolar(d*d, bipolar_mat);
generateRandomVector(rhs_bits, d*dc, regular_mat);
ctx.lhs.importRegular(bipolar_mat);
ctx.rhs.importRegular(regular_mat);
gemmBitSerial(ctx);
naive_int_gemm(bipolar_mat, regular_mat, res_golden, d, d, dc);
//printmatrix(bipolar_mat, d, d);
//printmatrix(regular_mat, dc, d);
//printmatrix(res_golden, dc, d);
//printmatrix(ctx.res, dc, d);
int res = memcmp(res_golden, ctx.res, sizeof(int32_t)*d*dc);
if(res == 0) {
ok++;
} else {
nok++;
}
numConfigs++;
delete [] bipolar_mat;
delete [] regular_mat;
delete [] res_golden;
delete [] res_chk;
deallocGEMMContext(ctx);
cout << "Bipolar matrix matrix multiplication tests: " << ok << " OK, " << nok << " NOK" << endl;
return ok == numConfigs;
}
int main(int argc, char const *argv[]) {
srand(time(NULL));
bool all_ok = true;
all_ok &= test_conversions();
all_ok &= test_rowwise_sum();
all_ok &= test_mnist();
all_ok &= test_matrix_matrix();
all_ok &= test_bipolar();
if(all_ok) {
cout << "All tests completed successfully" << endl;
} else {
cout << "Some tests failed" << endl;
}
return 0;
}
<commit_msg>add more bipolar times regular tests<commit_after>#include <cassert>
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <vector>
#include <deque>
#include "gemmbitserial.hpp"
#include "mnistdata.h"
using namespace std;
using namespace gemmbitserial;
#define VERBOSE_TEST(x) ;
//#define VERBOSE_TEST(x) x
// Generate a random vector of -1 and +1 values of given dimension
template <typename T>
void generateRandomVector_Bipolar(size_t dim, T * ret) {
for(size_t i = 0; i < dim; i++) {
ret[i] = (rand() % 2 == 0) ? 1 : -1;
}
}
/**
* Generate a random vector with given dimension and number of bits
*/
template <typename T>
void generateRandomVector(size_t bits, size_t dim, T * ret, bool allowNeg = false) {
assert(bits <= (sizeof(T) * 8));
if(bits == 1 && allowNeg) {
// generate bipolar values
generateRandomVector_Bipolar(dim, ret);
return;
}
int32_t minVal = 0;
int32_t maxVal = (1 << bits);
for(size_t i = 0; i < dim; i++) {
ret[i] = (rand() % maxVal) - (allowNeg ? maxVal/2 : 0);
}
}
template <typename LHSType, typename RHSType>
void naive_int_gemm(LHSType * lhs, RHSType * rhs, int32_t * res, int rows, int depth, int cols) {
for(int k = 0; k < cols; k++) {
for(int i = 0; i < rows; i++) {
int32_t acc = 0;
for(int j = 0; j < depth; j++) {
acc += lhs[i * depth + j] * rhs[k * depth + j];
}
res[k * rows + i] = acc;
}
}
}
template <typename T>
void naive_sum_rows(T * m, int32_t * res, int rows, int cols) {
for(int i = 0; i < rows; i++) {
int32_t acc = 0;
for(int k = 0; k < cols; k++) {
acc += m[i * cols + k];
}
res[i] = acc;
}
}
template <typename T>
void printmatrix(T * mat, int rows, int cols) {
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
cout << (int) mat[i * cols + j] << " ";
}
cout << endl;
}
cout << endl;
}
template <typename T>
void printmatrixdiff(const T * mat1, const T * mat2, int rows, int cols) {
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
if(mat1[i * cols + j] != mat2[i * cols + j]) {
cout << "Difference at (i,j) = " << i << " " << j << " Mat1: " << (int)mat1[i * cols + j] << " Mat2: " << mat2[i * cols + j] << endl;
}
}
}
cout << endl;
}
void printBitSerialMatrix(BitSerialMatrix * bsm) {
cout << "BitSerialMatrix with bits " << bsm->nbits << " rows " << bsm->nrows << " cols " << bsm->ncols << endl;
for(int b = 0; b < bsm->nbits; b++) {
cout << "bit " << b << ":" << endl;
for(int r = 0; r < bsm->nrows; r++) {
for(int c = 0; c < bsm->ncols; c++) {
cout << (bsm->get(b,r,c) ? 1 : 0) << " ";
}
cout << endl << endl;
}
}
}
bool test_rowwise_sum() {
vector<size_t> param_bits {1, 2, 3, 4};
vector<size_t> param_dims {4, 16, 17, 32, 77, 100, 1023};
vector<int> param_signed {1, 0};
unsigned int numConfigs = 0, ok = 0, nok = 0;
for(auto & b: param_bits) {
for(auto & d: param_dims) {
for(auto & sgnd: param_signed) {
bool isSigned = (bool) sgnd;
int8_t * rnd_mat = new int8_t[d*d];
int32_t * res_ret = new int32_t[d];
int32_t * res_golden = new int32_t[d];
generateRandomVector(b, d*d, rnd_mat, isSigned);
BitSerialMatrix bsm = BitSerialMatrix::alloc(b, d, d, isSigned);
bsm.importRegular(rnd_mat);
sumRows(bsm, res_ret);
naive_sum_rows(rnd_mat, res_golden, d, d);
int res = memcmp(res_ret, res_golden, d);
if(res == 0) {
ok++;
} else {
nok++;
}
//printmatrix(rnd_mat, d, d);
//printmatrix(res_golden, d, 1);
//printmatrix(res_ret, d, 1);
BitSerialMatrix::dealloc(bsm);
delete [] rnd_mat;
delete [] res_golden;
delete [] res_ret;
numConfigs++;
VERBOSE_TEST(cout << "Bits = " << b << " dim = " << d << " result = " << res << endl);
}
}
}
cout << "Row-wise sum tests: " << ok << " OK, " << nok << " NOK" << endl;
return ok == numConfigs;
}
bool test_conversions() {
vector<size_t> param_bits {1, 2, 3, 7};
vector<size_t> param_dims {4, 16, 17, 32, 77, 100, 1023};
vector<int> param_signed {1, 0};
unsigned int numConfigs = 0, ok = 0, nok = 0;
for(auto & b: param_bits) {
for(auto & d: param_dims) {
for(auto & sgnd: param_signed) {
int8_t * res_chk = new int8_t[d*d];
int8_t * rnd_vec = new int8_t[d*d];
assert(res_chk != 0 && rnd_vec != 0);
generateRandomVector(b, d*d, rnd_vec, (bool) sgnd);
BitSerialMatrix bsm = BitSerialMatrix::alloc(b, d, d, (bool) sgnd);
bsm.importRegular(rnd_vec);
bsm.exportRegular(res_chk);
//printmatrix(rnd_vec, d, d);
//printmatrix(res_chk, d, d);
int res = memcmp(rnd_vec, res_chk, d);
if(res == 0) {
ok++;
} else {
nok++;
}
delete [] rnd_vec;
delete [] res_chk;
BitSerialMatrix::dealloc(bsm);
numConfigs++;
VERBOSE_TEST(cout << "Bits = " << b << " dim = " << d << " result = " << res << endl);
}
}
}
cout << "Conversion tests: " << ok << " OK, " << nok << " NOK" << endl;
return ok == numConfigs;
}
bool test_matrix_matrix() {
vector<size_t> param_bits {2, 3, 4};
vector<size_t> param_dims {3, 5, 7, 16, 17, 18, 30, 31, 32, 100, 177, 256};
deque<bool> param_allow_neg {false, true};
unsigned int numConfigs = 0, ok = 0, nok = 0;
for(auto & b: param_bits) {
for(auto & d: param_dims) {
uint8_t * rnd_mat_a = new uint8_t[d*d*2];
uint8_t * rnd_mat_b = new uint8_t[2*d*d*3];
int32_t * res_mat_golden = new int32_t[d*d*3];
generateRandomVector(b, d*d*2, rnd_mat_a);
generateRandomVector(b, 2*d*d*3, rnd_mat_b);
naive_int_gemm(rnd_mat_a, rnd_mat_b, res_mat_golden, d, 2*d, d*3);
GEMMContext ctx = allocGEMMContext(d, 2*d, 3*d, b, b, false, false);
ctx.lhs.importRegular(rnd_mat_a);
ctx.rhs.importRegular(rnd_mat_b);
gemmBitSerial(ctx);
//ctx.printSummary();
//printmatrix(rnd_mat_a, d, d*2);
//printmatrix(rnd_mat_b, d*3, d*2);
//printmatrix(res_mat_golden, d*3, d);
//printmatrix(ctx.res, d*3, d);
int rbytes = d*d*3*sizeof(int32_t);
int res = memcmp(ctx.res, res_mat_golden, rbytes);
if(res == 0) {
ok++;
} else {
nok++;
//printmatrixdiff(res_mat, res_mat_golden, 3*d, d);
}
delete [] rnd_mat_a;
delete [] rnd_mat_b;
delete [] res_mat_golden;
deallocGEMMContext(ctx);
numConfigs++;
VERBOSE_TEST(cout << "Bits = " << b << " dim = " << d << " result = " << res << endl);
}
}
cout << "Matrix matrix multiplication tests: " << ok << " OK, " << nok << " NOK" << endl;
return ok == numConfigs;
}
bool test_mnist() {
// test bit serial gemm using real-life matrix data from a MNIST neural net
GEMMContext ctx = allocGEMMContext(
MNIST_OUT, MNIST_IN, 1, MNIST_WBITS, MNIST_ABITS, MNIST_WSIGN, MNIST_ASIGN
);
ctx.lhs.importRegular(mnist_weights);
ctx.rhs.importRegular(mnist_in);
gemmBitSerial(ctx);
int res = memcmp(ctx.res, mnist_res_golden, MNIST_OUT*sizeof(int32_t));
cout << "MNIST matrix-vector: " << (res == 0 ? "OK" : "NOK") << endl;
if(res != 0) {
printmatrixdiff(ctx.res, mnist_res_golden, 1, MNIST_OUT);
}
deallocGEMMContext(ctx);
return res == 0;
}
bool test_bipolar_times_regular() {
vector<size_t> param_regularmatrix_bits {2, 3, 4};
vector<size_t> param_dims {3, 5, 7, 16, 17, 18, 30, 31, 32, 100, 177, 256};
vector<int> param_signed {1, 0};
unsigned int numConfigs = 0, ok = 0, nok = 0;
// TODO when bipolar times bipolar is covered, merge into matrix matrix
for(auto & rhs_bits: param_regularmatrix_bits) {
for(auto & d: param_dims) {
for(auto & sgnd: param_signed) {
const size_t lhs_bits = 1;
const bool lhs_sign = true;
const bool rhs_sign = (bool) sgnd;
int8_t * bipolar_mat = new int8_t[d*d];
int8_t * regular_mat = new int8_t[d*d];
int32_t * res_golden = new int32_t[d*d];
int32_t * res_chk = new int32_t[d*d];
GEMMContext ctx = allocGEMMContext(
d, d, d, lhs_bits, rhs_bits, lhs_sign, rhs_sign
);
generateRandomVector_Bipolar(d*d, bipolar_mat);
generateRandomVector(rhs_bits, d*d, regular_mat, rhs_sign);
ctx.lhs.importRegular(bipolar_mat);
ctx.rhs.importRegular(regular_mat);
gemmBitSerial(ctx);
naive_int_gemm(bipolar_mat, regular_mat, res_golden, d, d, d);
//printmatrix(bipolar_mat, d, d);
//printmatrix(regular_mat, d, d);
//printmatrix(res_golden, d, d);
//printmatrix(ctx.res, d, d);
int res = memcmp(res_golden, ctx.res, sizeof(int32_t)*d*d);
if(res == 0) {
ok++;
} else {
nok++;
}
numConfigs++;
delete [] bipolar_mat;
delete [] regular_mat;
delete [] res_golden;
delete [] res_chk;
deallocGEMMContext(ctx);
}
}
}
cout << "Bipolar matrix matrix multiplication tests: " << ok << " OK, " << nok << " NOK" << endl;
return ok == numConfigs;
}
int main(int argc, char const *argv[]) {
srand(time(NULL));
bool all_ok = true;
all_ok &= test_conversions();
all_ok &= test_rowwise_sum();
all_ok &= test_mnist();
all_ok &= test_matrix_matrix();
all_ok &= test_bipolar_times_regular();
if(all_ok) {
cout << "All tests completed successfully" << endl;
} else {
cout << "Some tests failed" << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
///////////////////////////////////////////////////////////////////////////////
// //
// ALICE Reconstruction parameterization: //
// //
// //
// Base Class for Detector reconstruction parameters //
// Revision: [email protected] 12/06/2008 //
// Its structure has been revised and it is interfaced to AliEventInfo. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "TClass.h"
#include "TObjArray.h"
#include "TMath.h"
#include "THashTable.h"
#include "AliDetectorRecoParam.h"
#include "AliLog.h"
#include "AliRecoParam.h"
#include "AliRunInfo.h"
#include "AliEventInfo.h"
#include "AliLog.h"
ClassImp(AliRecoParam)
TString AliRecoParam::fkgEventSpecieName[] = {"Default", "LowMultiplicity", "HighMultiplicity", "Cosmic", "Calib", "Unknown"} ;
AliRecoParam::AliRecoParam():
TObject(),
fEventSpecie(kDefault)
{
// Default constructor
// ...
for(Int_t iDet = 0; iDet < kNDetectors; iDet++)
fDetRecoParams[iDet] = NULL;
for(Int_t iSpecie = 0; iSpecie < kNSpecies; iSpecie++) {
for(Int_t iDet = 0; iDet < kNDetectors; iDet++) {
fDetRecoParamsIndex[iSpecie][iDet] = -1;
}
}
}
AliRecoParam::AliRecoParam(const AliRecoParam& par) :
TObject(),
fEventSpecie(par.fEventSpecie)
{
// copy constructor
for(Int_t iDet = 0; iDet < kNDetectors; iDet++) {
if (par.fDetRecoParams[iDet])
fDetRecoParams[iDet] = (TObjArray*)(par.fDetRecoParams[iDet]->Clone());
else
fDetRecoParams[iDet] = NULL;
}
for(Int_t iSpecie = 0; iSpecie < kNSpecies; iSpecie++) {
for(Int_t iDet = 0; iDet < kNDetectors; iDet++) {
fDetRecoParamsIndex[iSpecie][iDet] = par.fDetRecoParamsIndex[iSpecie][iDet];
}
}
}
//_____________________________________________________________________________
AliRecoParam& AliRecoParam::operator = (const AliRecoParam& par)
{
// assignment operator
if(&par == this) return *this;
this->~AliRecoParam();
new(this) AliRecoParam(par);
return *this;
}
AliRecoParam::~AliRecoParam(){
// Destructor
// ...
// Delete the array with the reco-param objects
for(Int_t iDet = 0; iDet < kNDetectors; iDet++) {
if (fDetRecoParams[iDet]){
fDetRecoParams[iDet]->Delete();
delete fDetRecoParams[iDet];
}
}
}
Int_t AliRecoParam::AConvert(EventSpecie_t es)
{
//Converts EventSpecie_t into int
Int_t rv = -1 ;
switch (es) {
case kDefault:
rv = 0 ;
break;
case kLowMult:
rv = 1 ;
break;
case kHighMult:
rv = 2 ;
break;
case kCosmic:
rv = 3 ;
break;
case kCalib:
rv = 4 ;
break;
default:
break;
}
if (rv < 0)
AliFatalClass(Form("Wrong event specie conversion %d", es)) ;
return rv ;
}
AliRecoParam::EventSpecie_t AliRecoParam::Convert(Int_t ies)
{
//Converts int into EventSpecie_t
AliRecoParam::EventSpecie_t es = kDefault ;
if ( ies >> 1)
es = kLowMult ;
if ( ies >> 2)
es = kHighMult ;
if ( ies >> 3)
es = kCosmic ;
if ( ies >> 4)
es = kCalib ;
return es ;
}
AliRecoParam::EventSpecie_t AliRecoParam::ConvertIndex(Int_t index)
{
//Converts index of lists into eventspecie
EventSpecie_t es = kDefault ;
switch (index) {
case 0:
es = kDefault ;
break;
case 1:
es = kLowMult ;
break;
case 2:
es = kHighMult ;
break;
case 3:
es = kCosmic ;
break;
case 4:
es = kCalib ;
break;
default:
break;
}
return es ;
}
void AliRecoParam::Print(Option_t *option) const {
//
// Print reconstruction setup
//
for(Int_t iDet = 0; iDet < kNDetectors; iDet++) {
if (fDetRecoParams[iDet]){
printf("AliDetectorRecoParam objects for detector %d:\n",iDet);
Int_t nparam = fDetRecoParams[iDet]->GetEntriesFast();
for (Int_t iparam=0; iparam<nparam; iparam++){
AliDetectorRecoParam * param = (AliDetectorRecoParam *)fDetRecoParams[iDet]->At(iparam);
if (!param) continue;
param->Print(option);
}
}
else {
printf("No AliDetectorRecoParam objects specified for detector %d\n",iDet);
}
}
}
void AliRecoParam::SetEventSpecie(const AliRunInfo *runInfo, const AliEventInfo &evInfo,
const THashTable *cosmicTriggersList)
{
// Implemented according to the discussions
// and meetings with physics and trigger coordination
fEventSpecie = kDefault;
if (strcmp(runInfo->GetRunType(),"PHYSICS")) {
// Not a physics run, the event specie is set to kCalib
fEventSpecie = kCalib;
return;
}
// Special DAQ events considered as calibration events
if (evInfo.GetEventType() != 7) {
// START_OF_*, END_OF_*, CALIBRATION etc events
fEventSpecie = kCalib;
return;
}
if ((strcmp(runInfo->GetLHCState(),"STABLE_BEAMS") == 0) &&
((strcmp(runInfo->GetBeamType(),"A-A") == 0) ||
(strcmp(runInfo->GetBeamType(),"A-") == 0) ||
(strcmp(runInfo->GetBeamType(),"-A") == 0))) {
// Heavy ion run (any beam that is not pp, the event specie is set to kHighMult
fEventSpecie = kHighMult;
}
else if ((strcmp(runInfo->GetLHCState(),"STABLE_BEAMS") == 0) &&
((strcmp(runInfo->GetBeamType(),"p-p") == 0) ||
(strcmp(runInfo->GetBeamType(),"p-") == 0) ||
(strcmp(runInfo->GetBeamType(),"-p") == 0) ||
(strcmp(runInfo->GetBeamType(),"P-P") == 0) ||
(strcmp(runInfo->GetBeamType(),"P-") == 0) ||
(strcmp(runInfo->GetBeamType(),"-P") == 0))) {
// Proton run, the event specie is set to kLowMult
fEventSpecie = kLowMult;
}
else if (strcmp(runInfo->GetBeamType(),"-") == 0) {
// No beams, we assume cosmic data
fEventSpecie = kCosmic;
}
// Now we look into the trigger type in order to decide
// on the remaining cases (cosmic event within LHC run,
// calibration, for example TPC laser, triggers within physics run
TString triggerClasses = evInfo.GetTriggerClasses();
TObjArray* trClassArray = triggerClasses.Tokenize(" ");
Int_t nTrClasses = trClassArray->GetEntriesFast();
Bool_t cosmicTrigger = kFALSE,
calibTrigger = kFALSE,
otherTrigger = kFALSE;
for( Int_t i=0; i<nTrClasses; ++i ) {
TString trClass = ((TObjString*)trClassArray->At(i))->String();
if (trClass.BeginsWith("C0L")) {
// Calibration triggers always start with C0L
calibTrigger = kTRUE;
continue;
}
if (cosmicTriggersList) {
if (cosmicTriggersList->FindObject(trClass.Data())) {
// Cosmic trigger accorind to the table
// provided in OCDB
cosmicTrigger = kTRUE;
AliDebug(1,Form("Trigger %s identified as cosmic according to the list defined in OCDB.",
trClass.Data()));
continue;
}
}
else {
AliDebug(1,"Cosmic trigger list is not provided, cosmic event specie is effectively disabled!");
}
otherTrigger = kTRUE;
}
delete trClassArray;
if (calibTrigger) {
fEventSpecie = kCalib;
return;
}
if (cosmicTrigger && !otherTrigger) {
fEventSpecie = kCosmic;
return;
}
// Here we have to add if we have other cases
// and also HLT info if any...
}
const AliDetectorRecoParam *AliRecoParam::GetDetRecoParam(Int_t iDet) const
{
// Return AliDetectorRecoParam object for a given detector
// according to the event specie provided as an argument
if ( iDet >= kNDetectors) return NULL;
if (!fDetRecoParams[iDet]) return NULL;
if (fDetRecoParams[iDet]->GetEntries() == 0) return NULL;
for(Int_t iBit = 0; iBit < kNSpecies; iBit++) {
if (fEventSpecie & (1 << iBit)) {
if (fDetRecoParamsIndex[iBit][iDet] >= 0)
return (AliDetectorRecoParam *)fDetRecoParams[iDet]->At(fDetRecoParamsIndex[iBit][iDet]);
else if (fDetRecoParamsIndex[0][iDet] >= 0)
return (AliDetectorRecoParam *)fDetRecoParams[iDet]->At(fDetRecoParamsIndex[0][iDet]);
else {
AliError(Form("no RecoParam set for detector %d", iDet));
return NULL;
}
}
}
// Default one
AliError(Form("Invalid event specie: %d!",fEventSpecie));
if (fDetRecoParamsIndex[0][iDet] >= 0)
return (AliDetectorRecoParam *)fDetRecoParams[iDet]->At(fDetRecoParamsIndex[0][iDet]);
AliError(Form("no RecoParam set for detector %d", iDet));
return NULL;
}
void AliRecoParam::AddDetRecoParam(Int_t iDet, AliDetectorRecoParam* param)
{
// Add an instance of reco params object into
// the fDetRecoParams for detector iDet
// Updates the fDetRecoParams index
if (!fDetRecoParams[iDet]) fDetRecoParams[iDet] = new TObjArray;
fDetRecoParams[iDet]->AddLast(param);
Int_t index = fDetRecoParams[iDet]->GetLast();
// Index
Int_t specie = param->GetEventSpecie();
for(Int_t iBit = 0; iBit < kNSpecies; iBit++) {
if (specie & (1 << iBit)) {
fDetRecoParamsIndex[iBit][iDet] = index;
}
}
}
Bool_t AliRecoParam::AddDetRecoParamArray(Int_t iDet, TObjArray* parArray)
{
// Add an array of reconstruction parameter objects
// for a given detector
// Basic check on the consistency of the array
Bool_t defaultFound = kFALSE;
for(Int_t i = 0; i < parArray->GetEntriesFast(); i++) {
AliDetectorRecoParam *par = (AliDetectorRecoParam*)parArray->At(i);
if (!par) continue;
if (par->IsDefault()) defaultFound = kTRUE;
Int_t specie = par->GetEventSpecie();
for(Int_t iBit = 0; iBit < kNSpecies; iBit++) {
if (specie & (1 << iBit)) {
fDetRecoParamsIndex[iBit][iDet] = i;
}
}
}
fDetRecoParams[iDet] = parArray;
return defaultFound;
}
const char* AliRecoParam::PrintEventSpecie() const
{
// Print the current
// event specie
switch (fEventSpecie) {
case kDefault:
return fkgEventSpecieName[0].Data() ;
break;
case kLowMult:
return fkgEventSpecieName[1].Data() ;
break;
case kHighMult:
return fkgEventSpecieName[2].Data() ;
break;
case kCosmic:
return fkgEventSpecieName[3].Data() ;
break;
case kCalib:
return fkgEventSpecieName[4].Data() ;
break;
default:
return fkgEventSpecieName[5].Data() ;
break;
}
}
const char * AliRecoParam::GetEventSpecieName(EventSpecie_t es)
{
switch (es) {
case kDefault:
return fkgEventSpecieName[0].Data() ;
break;
case kLowMult:
return fkgEventSpecieName[1].Data() ;
break;
case kHighMult:
return fkgEventSpecieName[2].Data() ;
break;
case kCosmic:
return fkgEventSpecieName[3].Data() ;
break;
case kCalib:
return fkgEventSpecieName[4].Data() ;
break;
default:
return fkgEventSpecieName[5].Data() ;
break;
}
}
const char * AliRecoParam::GetEventSpecieName(Int_t esIndex)
{
if ( esIndex >= 0 && esIndex < kNSpecies)
return fkgEventSpecieName[esIndex].Data() ;
else
return fkgEventSpecieName[kNSpecies].Data() ;
}
<commit_msg>Allowing another syntax of the stable beams lhc state. To be ported to the releases.<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
///////////////////////////////////////////////////////////////////////////////
// //
// ALICE Reconstruction parameterization: //
// //
// //
// Base Class for Detector reconstruction parameters //
// Revision: [email protected] 12/06/2008 //
// Its structure has been revised and it is interfaced to AliEventInfo. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "TClass.h"
#include "TObjArray.h"
#include "TMath.h"
#include "THashTable.h"
#include "AliDetectorRecoParam.h"
#include "AliLog.h"
#include "AliRecoParam.h"
#include "AliRunInfo.h"
#include "AliEventInfo.h"
#include "AliLog.h"
ClassImp(AliRecoParam)
TString AliRecoParam::fkgEventSpecieName[] = {"Default", "LowMultiplicity", "HighMultiplicity", "Cosmic", "Calib", "Unknown"} ;
AliRecoParam::AliRecoParam():
TObject(),
fEventSpecie(kDefault)
{
// Default constructor
// ...
for(Int_t iDet = 0; iDet < kNDetectors; iDet++)
fDetRecoParams[iDet] = NULL;
for(Int_t iSpecie = 0; iSpecie < kNSpecies; iSpecie++) {
for(Int_t iDet = 0; iDet < kNDetectors; iDet++) {
fDetRecoParamsIndex[iSpecie][iDet] = -1;
}
}
}
AliRecoParam::AliRecoParam(const AliRecoParam& par) :
TObject(),
fEventSpecie(par.fEventSpecie)
{
// copy constructor
for(Int_t iDet = 0; iDet < kNDetectors; iDet++) {
if (par.fDetRecoParams[iDet])
fDetRecoParams[iDet] = (TObjArray*)(par.fDetRecoParams[iDet]->Clone());
else
fDetRecoParams[iDet] = NULL;
}
for(Int_t iSpecie = 0; iSpecie < kNSpecies; iSpecie++) {
for(Int_t iDet = 0; iDet < kNDetectors; iDet++) {
fDetRecoParamsIndex[iSpecie][iDet] = par.fDetRecoParamsIndex[iSpecie][iDet];
}
}
}
//_____________________________________________________________________________
AliRecoParam& AliRecoParam::operator = (const AliRecoParam& par)
{
// assignment operator
if(&par == this) return *this;
this->~AliRecoParam();
new(this) AliRecoParam(par);
return *this;
}
AliRecoParam::~AliRecoParam(){
// Destructor
// ...
// Delete the array with the reco-param objects
for(Int_t iDet = 0; iDet < kNDetectors; iDet++) {
if (fDetRecoParams[iDet]){
fDetRecoParams[iDet]->Delete();
delete fDetRecoParams[iDet];
}
}
}
Int_t AliRecoParam::AConvert(EventSpecie_t es)
{
//Converts EventSpecie_t into int
Int_t rv = -1 ;
switch (es) {
case kDefault:
rv = 0 ;
break;
case kLowMult:
rv = 1 ;
break;
case kHighMult:
rv = 2 ;
break;
case kCosmic:
rv = 3 ;
break;
case kCalib:
rv = 4 ;
break;
default:
break;
}
if (rv < 0)
AliFatalClass(Form("Wrong event specie conversion %d", es)) ;
return rv ;
}
AliRecoParam::EventSpecie_t AliRecoParam::Convert(Int_t ies)
{
//Converts int into EventSpecie_t
AliRecoParam::EventSpecie_t es = kDefault ;
if ( ies >> 1)
es = kLowMult ;
if ( ies >> 2)
es = kHighMult ;
if ( ies >> 3)
es = kCosmic ;
if ( ies >> 4)
es = kCalib ;
return es ;
}
AliRecoParam::EventSpecie_t AliRecoParam::ConvertIndex(Int_t index)
{
//Converts index of lists into eventspecie
EventSpecie_t es = kDefault ;
switch (index) {
case 0:
es = kDefault ;
break;
case 1:
es = kLowMult ;
break;
case 2:
es = kHighMult ;
break;
case 3:
es = kCosmic ;
break;
case 4:
es = kCalib ;
break;
default:
break;
}
return es ;
}
void AliRecoParam::Print(Option_t *option) const {
//
// Print reconstruction setup
//
for(Int_t iDet = 0; iDet < kNDetectors; iDet++) {
if (fDetRecoParams[iDet]){
printf("AliDetectorRecoParam objects for detector %d:\n",iDet);
Int_t nparam = fDetRecoParams[iDet]->GetEntriesFast();
for (Int_t iparam=0; iparam<nparam; iparam++){
AliDetectorRecoParam * param = (AliDetectorRecoParam *)fDetRecoParams[iDet]->At(iparam);
if (!param) continue;
param->Print(option);
}
}
else {
printf("No AliDetectorRecoParam objects specified for detector %d\n",iDet);
}
}
}
void AliRecoParam::SetEventSpecie(const AliRunInfo *runInfo, const AliEventInfo &evInfo,
const THashTable *cosmicTriggersList)
{
// Implemented according to the discussions
// and meetings with physics and trigger coordination
fEventSpecie = kDefault;
if (strcmp(runInfo->GetRunType(),"PHYSICS")) {
// Not a physics run, the event specie is set to kCalib
fEventSpecie = kCalib;
return;
}
// Special DAQ events considered as calibration events
if (evInfo.GetEventType() != 7) {
// START_OF_*, END_OF_*, CALIBRATION etc events
fEventSpecie = kCalib;
return;
}
if (((strcmp(runInfo->GetLHCState(),"STABLE_BEAMS") == 0) ||
(strcmp(runInfo->GetLHCState(),"STABLE BEAMS") == 0)) &&
((strcmp(runInfo->GetBeamType(),"A-A") == 0) ||
(strcmp(runInfo->GetBeamType(),"A-") == 0) ||
(strcmp(runInfo->GetBeamType(),"-A") == 0))) {
// Heavy ion run (any beam that is not pp, the event specie is set to kHighMult
fEventSpecie = kHighMult;
}
else if (((strcmp(runInfo->GetLHCState(),"STABLE_BEAMS") == 0) ||
(strcmp(runInfo->GetLHCState(),"STABLE BEAMS") == 0)) &&
((strcmp(runInfo->GetBeamType(),"p-p") == 0) ||
(strcmp(runInfo->GetBeamType(),"p-") == 0) ||
(strcmp(runInfo->GetBeamType(),"-p") == 0) ||
(strcmp(runInfo->GetBeamType(),"P-P") == 0) ||
(strcmp(runInfo->GetBeamType(),"P-") == 0) ||
(strcmp(runInfo->GetBeamType(),"-P") == 0))) {
// Proton run, the event specie is set to kLowMult
fEventSpecie = kLowMult;
}
else if (strcmp(runInfo->GetBeamType(),"-") == 0) {
// No beams, we assume cosmic data
fEventSpecie = kCosmic;
}
// Now we look into the trigger type in order to decide
// on the remaining cases (cosmic event within LHC run,
// calibration, for example TPC laser, triggers within physics run
TString triggerClasses = evInfo.GetTriggerClasses();
TObjArray* trClassArray = triggerClasses.Tokenize(" ");
Int_t nTrClasses = trClassArray->GetEntriesFast();
Bool_t cosmicTrigger = kFALSE,
calibTrigger = kFALSE,
otherTrigger = kFALSE;
for( Int_t i=0; i<nTrClasses; ++i ) {
TString trClass = ((TObjString*)trClassArray->At(i))->String();
if (trClass.BeginsWith("C0L")) {
// Calibration triggers always start with C0L
calibTrigger = kTRUE;
continue;
}
if (cosmicTriggersList) {
if (cosmicTriggersList->FindObject(trClass.Data())) {
// Cosmic trigger accorind to the table
// provided in OCDB
cosmicTrigger = kTRUE;
AliDebug(1,Form("Trigger %s identified as cosmic according to the list defined in OCDB.",
trClass.Data()));
continue;
}
}
else {
AliDebug(1,"Cosmic trigger list is not provided, cosmic event specie is effectively disabled!");
}
otherTrigger = kTRUE;
}
delete trClassArray;
if (calibTrigger) {
fEventSpecie = kCalib;
return;
}
if (cosmicTrigger && !otherTrigger) {
fEventSpecie = kCosmic;
return;
}
// Here we have to add if we have other cases
// and also HLT info if any...
}
const AliDetectorRecoParam *AliRecoParam::GetDetRecoParam(Int_t iDet) const
{
// Return AliDetectorRecoParam object for a given detector
// according to the event specie provided as an argument
if ( iDet >= kNDetectors) return NULL;
if (!fDetRecoParams[iDet]) return NULL;
if (fDetRecoParams[iDet]->GetEntries() == 0) return NULL;
for(Int_t iBit = 0; iBit < kNSpecies; iBit++) {
if (fEventSpecie & (1 << iBit)) {
if (fDetRecoParamsIndex[iBit][iDet] >= 0)
return (AliDetectorRecoParam *)fDetRecoParams[iDet]->At(fDetRecoParamsIndex[iBit][iDet]);
else if (fDetRecoParamsIndex[0][iDet] >= 0)
return (AliDetectorRecoParam *)fDetRecoParams[iDet]->At(fDetRecoParamsIndex[0][iDet]);
else {
AliError(Form("no RecoParam set for detector %d", iDet));
return NULL;
}
}
}
// Default one
AliError(Form("Invalid event specie: %d!",fEventSpecie));
if (fDetRecoParamsIndex[0][iDet] >= 0)
return (AliDetectorRecoParam *)fDetRecoParams[iDet]->At(fDetRecoParamsIndex[0][iDet]);
AliError(Form("no RecoParam set for detector %d", iDet));
return NULL;
}
void AliRecoParam::AddDetRecoParam(Int_t iDet, AliDetectorRecoParam* param)
{
// Add an instance of reco params object into
// the fDetRecoParams for detector iDet
// Updates the fDetRecoParams index
if (!fDetRecoParams[iDet]) fDetRecoParams[iDet] = new TObjArray;
fDetRecoParams[iDet]->AddLast(param);
Int_t index = fDetRecoParams[iDet]->GetLast();
// Index
Int_t specie = param->GetEventSpecie();
for(Int_t iBit = 0; iBit < kNSpecies; iBit++) {
if (specie & (1 << iBit)) {
fDetRecoParamsIndex[iBit][iDet] = index;
}
}
}
Bool_t AliRecoParam::AddDetRecoParamArray(Int_t iDet, TObjArray* parArray)
{
// Add an array of reconstruction parameter objects
// for a given detector
// Basic check on the consistency of the array
Bool_t defaultFound = kFALSE;
for(Int_t i = 0; i < parArray->GetEntriesFast(); i++) {
AliDetectorRecoParam *par = (AliDetectorRecoParam*)parArray->At(i);
if (!par) continue;
if (par->IsDefault()) defaultFound = kTRUE;
Int_t specie = par->GetEventSpecie();
for(Int_t iBit = 0; iBit < kNSpecies; iBit++) {
if (specie & (1 << iBit)) {
fDetRecoParamsIndex[iBit][iDet] = i;
}
}
}
fDetRecoParams[iDet] = parArray;
return defaultFound;
}
const char* AliRecoParam::PrintEventSpecie() const
{
// Print the current
// event specie
switch (fEventSpecie) {
case kDefault:
return fkgEventSpecieName[0].Data() ;
break;
case kLowMult:
return fkgEventSpecieName[1].Data() ;
break;
case kHighMult:
return fkgEventSpecieName[2].Data() ;
break;
case kCosmic:
return fkgEventSpecieName[3].Data() ;
break;
case kCalib:
return fkgEventSpecieName[4].Data() ;
break;
default:
return fkgEventSpecieName[5].Data() ;
break;
}
}
const char * AliRecoParam::GetEventSpecieName(EventSpecie_t es)
{
switch (es) {
case kDefault:
return fkgEventSpecieName[0].Data() ;
break;
case kLowMult:
return fkgEventSpecieName[1].Data() ;
break;
case kHighMult:
return fkgEventSpecieName[2].Data() ;
break;
case kCosmic:
return fkgEventSpecieName[3].Data() ;
break;
case kCalib:
return fkgEventSpecieName[4].Data() ;
break;
default:
return fkgEventSpecieName[5].Data() ;
break;
}
}
const char * AliRecoParam::GetEventSpecieName(Int_t esIndex)
{
if ( esIndex >= 0 && esIndex < kNSpecies)
return fkgEventSpecieName[esIndex].Data() ;
else
return fkgEventSpecieName[kNSpecies].Data() ;
}
<|endoftext|> |
<commit_before>#include "optional.h"
#include "variant.h"
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "doctest.h"
#include <string>
#include <vector>
#include <type_traits>
TEST_CASE("std::variant<T...> traits")
{
typedef std::variant<bool, float> bool_float_variant;
typedef std::variant<int, double, std::string> int_double_string_variant;
CHECK(std::variant_size<bool_float_variant>::value == 2);
CHECK(std::variant_size<const bool_float_variant>::value == 2);
CHECK(std::variant_size<volatile bool_float_variant>::value == 2);
CHECK(std::variant_size<const volatile bool_float_variant>::value == 2);
CHECK(std::variant_size<int_double_string_variant>::value == 3);
CHECK(std::variant_size<const int_double_string_variant>::value == 3);
CHECK(std::variant_size<volatile int_double_string_variant>::value == 3);
CHECK(std::variant_size<const volatile int_double_string_variant>::value == 3);
CHECK(typeid(std::variant_alternative_t<0, std::variant<bool, float>> *) == typeid(bool *));
CHECK(typeid(std::variant_alternative_t<1, std::variant<bool, float>> *) == typeid(float *));
CHECK(typeid(std::variant_alternative_t<0, const std::variant<bool, float>> *) == typeid(const bool *));
CHECK(typeid(std::variant_alternative_t<1, const std::variant<bool, float>> *) == typeid(const float *));
CHECK(typeid(std::variant_alternative_t<0, volatile std::variant<bool, float>> *) == typeid(volatile bool *));
CHECK(typeid(std::variant_alternative_t<1, volatile std::variant<bool, float>> *) == typeid(volatile float *));
CHECK(typeid(std::variant_alternative_t<0, const volatile std::variant<bool, float>> *) == typeid(const volatile bool *));
CHECK(typeid(std::variant_alternative_t<1, const volatile std::variant<bool, float>> *) == typeid(const volatile float *));
CHECK(typeid(std::variant_alternative_t<0, std::variant<int, double, std::string>> *) == typeid(int *));
CHECK(typeid(std::variant_alternative_t<1, std::variant<int, double, std::string>> *) == typeid(double *));
CHECK(typeid(std::variant_alternative_t<2, std::variant<int, double, std::string>> *) == typeid(std::string *));
CHECK(typeid(std::variant_alternative_t<0, const std::variant<int, double, std::string>> *) == typeid(const int *));
CHECK(typeid(std::variant_alternative_t<1, const std::variant<int, double, std::string>> *) == typeid(const double *));
CHECK(typeid(std::variant_alternative_t<2, const std::variant<int, double, std::string>> *) == typeid(const std::string *));
CHECK(typeid(std::variant_alternative_t<0, volatile std::variant<int, double, std::string>> *) == typeid(volatile int *));
CHECK(typeid(std::variant_alternative_t<1, volatile std::variant<int, double, std::string>> *) == typeid(volatile double *));
CHECK(typeid(std::variant_alternative_t<2, volatile std::variant<int, double, std::string>> *) == typeid(volatile std::string *));
CHECK(typeid(std::variant_alternative_t<0, const volatile std::variant<int, double, std::string>> *) == typeid(const volatile int *));
CHECK(typeid(std::variant_alternative_t<1, const volatile std::variant<int, double, std::string>> *) == typeid(const volatile double *));
CHECK(typeid(std::variant_alternative_t<2, const volatile std::variant<int, double, std::string>> *) == typeid(const volatile std::string *));
}
TEST_CASE("construct std::variant<T...>")
{
std::variant<int, double, std::string> a;
std::variant<int, double, std::string> b {55};
std::variant<int, double, std::string> c {3.14};
std::variant<int, double, std::string> d {"Hello world!"};
CHECK(!a.valueless_by_exception());
CHECK(!b.valueless_by_exception());
CHECK(!c.valueless_by_exception());
CHECK(!d.valueless_by_exception());
CHECK(a.index() == 0);
CHECK(b.index() == 0);
CHECK(c.index() == 1);
CHECK(d.index() == 2);
CHECK(std::get<0>(a) == int{0});
CHECK(std::get<0>(b) == int{55});
CHECK(std::get<1>(c) == double{3.14});
CHECK(std::get<2>(d) == std::string{"Hello world!"});
b = d;
CHECK(!b.valueless_by_exception());
CHECK(b.index() == 2);
CHECK(std::get<2>(b) == std::string{"Hello world!"});
d = c;
CHECK(!d.valueless_by_exception());
CHECK(d.index() == 1);
CHECK(std::get<1>(d) == double{3.14});
}
TEST_CASE("variant move and copy construction and assignment")
{
typedef std::variant<int, std::vector<double>> variant_t;
// Construct an int alternative
variant_t a {5};
CHECK(a.index() == 0);
CHECK(std::get<0>(a) == 5);
// Construct a std::vector<double> alternative
variant_t b {std::vector<double>{1,2,3,4,5,6,7,8,9,10}};
CHECK(b.index() == 1);
CHECK(std::get<1>(b).size() == 10);
// Copy construct from b, which should leave b unchanged
variant_t c {b};
CHECK(c.index() == 1);
CHECK(std::get<1>(c).size() == 10);
CHECK(b.index() == 1);
CHECK(std::get<1>(b).size() == 10);
// Move construct from b, which should leave b representing a moved-from std::vector<double>
variant_t d {std::move(b)};
CHECK(d.index() == 1);
CHECK(std::get<1>(d).size() == 10);
CHECK(b.index() == 1);
CHECK(std::get<1>(b).size() == 0);
// Now copy a into b, which should change b to represent an int
b = a;
CHECK(b.index() == 0);
CHECK(std::get<0>(b) == 5);
CHECK(a.index() == 0);
CHECK(std::get<0>(a) == 5);
// Now move d into a, which should change a to represent a std::vector<double> and leave d as a moved-from std::vector<double>
a = std::move(d);
CHECK(a.index() == 1);
CHECK(std::get<1>(a).size() == 10);
CHECK(d.index() == 1);
CHECK(std::get<1>(d).size() == 0);
}
TEST_CASE("variant emplace()")
{
// Default-construct several variants
std::variant<int, std::vector<double>> a, b, c, d;
CHECK(a.index() == 0);
CHECK(std::get<0>(a) == 0);
// Emplace the first alternative by index
a.emplace<0>(55);
CHECK(a.index() == 0);
CHECK(std::get<0>(a) == 55);
// Emplace the second alternative by index
b.emplace<1>(std::vector<double>{1,2,3,4,5});
CHECK(b.index() == 1);
CHECK(std::get<1>(b).size() == 5);
// Emplace the first alternative by type
c.emplace<int>(72);
CHECK(c.index() == 0);
CHECK(std::get<0>(c) == 72);
// Emplace the second alternative by type
d.emplace<std::vector<double>>(std::vector<double>{3,2,1});
CHECK(d.index() == 1);
CHECK(std::get<1>(d).size() == 3);
}
TEST_CASE("construct null std::optional<T>")
{
const std::optional<int> a;
CHECK(!a);
CHECK(!a.has_value());
CHECK(a == std::nullopt);
CHECK(std::nullopt == a);
const std::optional<std::string> b {std::nullopt};
CHECK(!b);
CHECK(!b.has_value());
CHECK(b == std::nullopt);
CHECK(std::nullopt == b);
}
TEST_CASE("construct std::optional<T> with a value")
{
const std::optional<int> a {55};
CHECK(a);
CHECK(a.has_value());
CHECK(a.value() == 55);
CHECK(a == 55);
CHECK(55 == a);
const std::optional<std::string> b {"Hello world!"};
CHECK(b);
CHECK(b.has_value());
const std::string s {"Hello world!"};
CHECK(b.value() == s);
CHECK(b == s);
CHECK(s == b);
}<commit_msg>More tests.<commit_after>#include "optional.h"
#include "variant.h"
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "doctest.h"
#include <string>
#include <vector>
#include <type_traits>
TEST_CASE("std::variant<T...> traits")
{
typedef std::variant<bool, float> bool_float_variant;
typedef std::variant<int, double, std::string> int_double_string_variant;
CHECK(std::variant_size<bool_float_variant>::value == 2);
CHECK(std::variant_size<const bool_float_variant>::value == 2);
CHECK(std::variant_size<volatile bool_float_variant>::value == 2);
CHECK(std::variant_size<const volatile bool_float_variant>::value == 2);
CHECK(std::variant_size<int_double_string_variant>::value == 3);
CHECK(std::variant_size<const int_double_string_variant>::value == 3);
CHECK(std::variant_size<volatile int_double_string_variant>::value == 3);
CHECK(std::variant_size<const volatile int_double_string_variant>::value == 3);
CHECK(typeid(std::variant_alternative_t<0, std::variant<bool, float>> *) == typeid(bool *));
CHECK(typeid(std::variant_alternative_t<1, std::variant<bool, float>> *) == typeid(float *));
CHECK(typeid(std::variant_alternative_t<0, const std::variant<bool, float>> *) == typeid(const bool *));
CHECK(typeid(std::variant_alternative_t<1, const std::variant<bool, float>> *) == typeid(const float *));
CHECK(typeid(std::variant_alternative_t<0, volatile std::variant<bool, float>> *) == typeid(volatile bool *));
CHECK(typeid(std::variant_alternative_t<1, volatile std::variant<bool, float>> *) == typeid(volatile float *));
CHECK(typeid(std::variant_alternative_t<0, const volatile std::variant<bool, float>> *) == typeid(const volatile bool *));
CHECK(typeid(std::variant_alternative_t<1, const volatile std::variant<bool, float>> *) == typeid(const volatile float *));
CHECK(typeid(std::variant_alternative_t<0, std::variant<int, double, std::string>> *) == typeid(int *));
CHECK(typeid(std::variant_alternative_t<1, std::variant<int, double, std::string>> *) == typeid(double *));
CHECK(typeid(std::variant_alternative_t<2, std::variant<int, double, std::string>> *) == typeid(std::string *));
CHECK(typeid(std::variant_alternative_t<0, const std::variant<int, double, std::string>> *) == typeid(const int *));
CHECK(typeid(std::variant_alternative_t<1, const std::variant<int, double, std::string>> *) == typeid(const double *));
CHECK(typeid(std::variant_alternative_t<2, const std::variant<int, double, std::string>> *) == typeid(const std::string *));
CHECK(typeid(std::variant_alternative_t<0, volatile std::variant<int, double, std::string>> *) == typeid(volatile int *));
CHECK(typeid(std::variant_alternative_t<1, volatile std::variant<int, double, std::string>> *) == typeid(volatile double *));
CHECK(typeid(std::variant_alternative_t<2, volatile std::variant<int, double, std::string>> *) == typeid(volatile std::string *));
CHECK(typeid(std::variant_alternative_t<0, const volatile std::variant<int, double, std::string>> *) == typeid(const volatile int *));
CHECK(typeid(std::variant_alternative_t<1, const volatile std::variant<int, double, std::string>> *) == typeid(const volatile double *));
CHECK(typeid(std::variant_alternative_t<2, const volatile std::variant<int, double, std::string>> *) == typeid(const volatile std::string *));
}
TEST_CASE("construct std::variant<T...>")
{
std::variant<int, double, std::string> a;
std::variant<int, double, std::string> b {55};
std::variant<int, double, std::string> c {3.14};
std::variant<int, double, std::string> d {"Hello world!"};
CHECK(!a.valueless_by_exception());
CHECK(!b.valueless_by_exception());
CHECK(!c.valueless_by_exception());
CHECK(!d.valueless_by_exception());
CHECK(a.index() == 0);
CHECK(b.index() == 0);
CHECK(c.index() == 1);
CHECK(d.index() == 2);
CHECK(std::get<0>(a) == int{0});
CHECK(std::get<0>(b) == int{55});
CHECK(std::get<1>(c) == double{3.14});
CHECK(std::get<2>(d) == std::string{"Hello world!"});
b = d;
CHECK(!b.valueless_by_exception());
CHECK(b.index() == 2);
CHECK(std::get<2>(b) == std::string{"Hello world!"});
d = c;
CHECK(!d.valueless_by_exception());
CHECK(d.index() == 1);
CHECK(std::get<1>(d) == double{3.14});
}
TEST_CASE("variant move and copy construction and assignment")
{
typedef std::variant<int, std::vector<double>> variant_t;
// Construct an int alternative
variant_t a {5};
CHECK(a.index() == 0);
CHECK(std::get<0>(a) == 5);
// Construct a std::vector<double> alternative
variant_t b {std::vector<double>{1,2,3,4,5,6,7,8,9,10}};
CHECK(b.index() == 1);
CHECK(std::get<1>(b).size() == 10);
// Copy construct from b, which should leave b unchanged
variant_t c {b};
CHECK(c.index() == 1);
CHECK(std::get<1>(c).size() == 10);
CHECK(b.index() == 1);
CHECK(std::get<1>(b).size() == 10);
// Move construct from b, which should leave b representing a moved-from std::vector<double>
variant_t d {std::move(b)};
CHECK(d.index() == 1);
CHECK(std::get<1>(d).size() == 10);
CHECK(b.index() == 1);
CHECK(std::get<1>(b).size() == 0);
// Now copy a into b, which should change b to represent an int
b = a;
CHECK(b.index() == 0);
CHECK(std::get<0>(b) == 5);
CHECK(a.index() == 0);
CHECK(std::get<0>(a) == 5);
// Now move d into a, which should change a to represent a std::vector<double> and leave d as a moved-from std::vector<double>
a = std::move(d);
CHECK(a.index() == 1);
CHECK(std::get<1>(a).size() == 10);
CHECK(d.index() == 1);
CHECK(std::get<1>(d).size() == 0);
}
TEST_CASE("variant emplace()")
{
// Default-construct several variants
std::variant<int, std::vector<double>> a, b, c, d;
CHECK(a.index() == 0);
CHECK(std::get<0>(a) == 0);
// Emplace the first alternative by index
a.emplace<0>(55);
CHECK(a.index() == 0);
CHECK(std::get<0>(a) == 55);
// Emplace the second alternative by index
b.emplace<1>(std::vector<double>{1,2,3,4,5});
CHECK(b.index() == 1);
CHECK(std::get<1>(b).size() == 5);
// Emplace the first alternative by type
c.emplace<int>(72);
CHECK(c.index() == 0);
CHECK(std::get<0>(c) == 72);
// Emplace the second alternative by type
d.emplace<std::vector<double>>(std::vector<double>{3,2,1});
CHECK(d.index() == 1);
CHECK(std::get<1>(d).size() == 3);
}
TEST_CASE("visit variant")
{
// Construct some variants
std::variant<int, double, std::string> a {5}, b {3.14}, c {"foo"};
// Create a visitor that prints to a stream
std::ostringstream ss;
const auto print = [&ss](const auto & x) { ss << x; };
// Visit a, which should print the int alternative
ss.str("");
visit(print, a);
CHECK(ss.str() == "5");
// Visit b, which should print the double alternative
ss.str("");
visit(print, b);
CHECK(ss.str() == "3.14");
// Visit c, which should print the string alternative
ss.str("");
visit(print, c);
CHECK(ss.str() == "foo");
// Visit all three variants at once
ss.str("");
visit([&ss](auto x, auto y, auto z)
{
ss << x << ' ' << y << ' ' << z;
}, a, b, c);
CHECK(ss.str() == "5 3.14 foo");
// Use a modifying visitor on all three variants
const auto add_letter_a = [](auto & x) { x += 'A'; };
visit(add_letter_a, a);
visit(add_letter_a, b);
visit(add_letter_a, c);
CHECK(std::get<0>(a) == 5 + 'A');
CHECK(std::get<1>(b) == 3.14 + 'A');
CHECK(std::get<2>(c) == "fooA");
}
TEST_CASE("construct null std::optional<T>")
{
const std::optional<int> a;
CHECK(!a);
CHECK(!a.has_value());
CHECK(a == std::nullopt);
CHECK(std::nullopt == a);
const std::optional<std::string> b {std::nullopt};
CHECK(!b);
CHECK(!b.has_value());
CHECK(b == std::nullopt);
CHECK(std::nullopt == b);
}
TEST_CASE("construct std::optional<T> with a value")
{
const std::optional<int> a {55};
CHECK(a);
CHECK(a.has_value());
CHECK(a.value() == 55);
CHECK(a == 55);
CHECK(55 == a);
const std::optional<std::string> b {"Hello world!"};
CHECK(b);
CHECK(b.has_value());
const std::string s {"Hello world!"};
CHECK(b.value() == s);
CHECK(b == s);
CHECK(s == b);
}<|endoftext|> |
<commit_before>#include "master.hpp"
namespace factor {
factor_vm::factor_vm(THREADHANDLE thread)
: ctx(NULL),
nursery(0, 0),
faulting_p(false),
thread(thread),
#if defined(WINDOWS)
thread_id(GetCurrentThreadId()),
ctrl_break_thread(NULL),
#endif
callback_id(0),
c_to_factor_func(NULL),
sampling_profiler_p(false),
signal_pipe_input(0),
signal_pipe_output(0),
current_sample(0, 0, 0, 0, 0),
gc_off(false),
data(NULL), code(NULL), callbacks(NULL),
current_gc(NULL),
current_gc_p(false),
current_jit_count(0),
gc_events(NULL),
fep_p(false),
fep_help_was_shown(false),
fep_disabled(false),
full_output(false),
last_nano_count(0),
signal_callstack_seg(NULL),
safepoint_fep_p(false),
stop_on_ctrl_break(false) {
primitive_reset_dispatch_stats();
}
factor_vm::~factor_vm() {
free(alien_offset(special_objects[OBJ_EXECUTABLE]));
free(alien_offset(special_objects[OBJ_IMAGE]));
close_console();
FACTOR_ASSERT(!ctx);
FACTOR_FOR_EACH(unused_contexts) {
delete *iter;
}
FACTOR_FOR_EACH(active_contexts) {
delete *iter;
}
if (callbacks)
delete callbacks;
if (data)
delete data;
if (code)
delete code;
if (signal_callstack_seg) {
delete signal_callstack_seg;
signal_callstack_seg = NULL;
}
FACTOR_FOR_EACH(function_descriptors) {
delete[] * iter;
}
}
}
<commit_msg>VM: init object_counter, silences valgrind #1886<commit_after>#include "master.hpp"
namespace factor {
factor_vm::factor_vm(THREADHANDLE thread)
: ctx(NULL),
nursery(0, 0),
faulting_p(false),
thread(thread),
#if defined(WINDOWS)
thread_id(GetCurrentThreadId()),
ctrl_break_thread(NULL),
#endif
callback_id(0),
c_to_factor_func(NULL),
sampling_profiler_p(false),
signal_pipe_input(0),
signal_pipe_output(0),
current_sample(0, 0, 0, 0, 0),
gc_off(false),
data(NULL), code(NULL), callbacks(NULL),
current_gc(NULL),
current_gc_p(false),
current_jit_count(0),
gc_events(NULL),
fep_p(false),
fep_help_was_shown(false),
fep_disabled(false),
full_output(false),
object_counter(0),
last_nano_count(0),
signal_callstack_seg(NULL),
safepoint_fep_p(false),
stop_on_ctrl_break(false) {
primitive_reset_dispatch_stats();
}
factor_vm::~factor_vm() {
free(alien_offset(special_objects[OBJ_EXECUTABLE]));
free(alien_offset(special_objects[OBJ_IMAGE]));
close_console();
FACTOR_ASSERT(!ctx);
FACTOR_FOR_EACH(unused_contexts) {
delete *iter;
}
FACTOR_FOR_EACH(active_contexts) {
delete *iter;
}
if (callbacks)
delete callbacks;
if (data)
delete data;
if (code)
delete code;
if (signal_callstack_seg) {
delete signal_callstack_seg;
signal_callstack_seg = NULL;
}
FACTOR_FOR_EACH(function_descriptors) {
delete[] * iter;
}
}
}
<|endoftext|> |
<commit_before>#include "vm.hpp"
#include "objectmemory.hpp"
#include "objects.hpp"
#include "event.hpp"
#include "global_cache.hpp"
#include "llvm.hpp"
#include "builtin/class.hpp"
#include "builtin/contexts.hpp"
#include "builtin/fixnum.hpp"
#include "builtin/list.hpp"
#include "builtin/symbol.hpp"
#include "builtin/thread.hpp"
#include "builtin/tuple.hpp"
#include "builtin/string.hpp"
#include "config.hpp"
#include <iostream>
namespace rubinius {
VM::VM(size_t bytes) : probe(NULL), wait_events(false) {
config.compile_up_front = false;
context_cache = NULL;
user_config = new ConfigParser();
om = new ObjectMemory(bytes);
MethodContext::initialize_cache(this);
bootstrap_ontology();
events = new event::Loop(EVFLAG_FORKCHECK);
global_cache = new GlobalCache;
VMLLVMMethod::init("vm/instructions.bc");
boot_threads();
}
VM::~VM() {
delete om;
delete events;
delete global_cache;
llvm_cleanup();
}
void VM::boot_threads() {
Thread* thr = Thread::create(this);
thr->boot_task(this);
activate_thread(thr);
}
OBJECT VM::new_object(Class *cls) {
return om->new_object(cls, cls->instance_fields->to_native());
}
SYMBOL VM::symbol(const char* str) {
return symbols.lookup(this, str);
}
SYMBOL VM::symbol(String* str) {
return symbols.lookup(this, str);
}
SYMBOL VM::symbol(std::string str) {
return symbols.lookup(this, str);
}
OBJECT VM::new_struct(Class* cls, size_t bytes) {
return om->new_object_bytes(cls, bytes);
}
void type_assert(OBJECT obj, object_type type, const char* reason) {
if(obj->reference_p() && obj->obj_type != type) {
TypeError::raise(type, obj, reason);
} else if(type == FixnumType && !obj->fixnum_p()) {
TypeError::raise(type, obj, reason);
}
}
void VM::add_type_info(TypeInfo* ti) {
om->add_type_info(ti);
ti->state = this;
}
TypeInfo* VM::find_type(int type) {
return om->type_info[type];
}
Thread *VM::current_thread() {
return globals.current_thread.get();
}
void VM::collect() {
om->collect_young(globals.roots);
om->collect_mature(globals.roots);
}
void VM::run_best_thread() {
Thread* next = NULL;
events->poll();
for(size_t i = globals.scheduled_threads->field_count - 1; i > 0; i--) {
List* lst = as<List>(globals.scheduled_threads->at(i));
if(lst->empty_p()) continue;
next = as<Thread>(lst->shift(this));
break;
}
if(!next) {
if(events->num_of_events() == 0) {
throw DeadLock("no runnable threads, present or future.");
}
wait_events = true;
return;
}
activate_thread(next);
}
void VM::return_value(OBJECT val) {
globals.current_task->push(val);
}
void VM::queue_thread(Thread* thread) {
List* lst = as<List>(globals.scheduled_threads->at(thread->priority->to_native()));
lst->append(this, thread);
}
void VM::activate_thread(Thread* thread) {
globals.current_thread.set(thread);
globals.current_task.set(thread->task);
}
OBJECT VM::current_block() {
return globals.current_task->active->block;
}
void VM::raise_from_errno(const char* msg) {
// TODO: implement me
}
void VM::raise_exception(Exception* exc) {
// TODO: implement me
}
void VM::inspect(OBJECT obj) {
if(obj->symbol_p()) {
String* str = as<Symbol>(obj)->to_str(this);
std::cout << "<Symbol :" << (char*)*str << ">" << std::endl;
} else if(obj->fixnum_p()) {
std::cout << "<Fixnum " << as<Fixnum>(obj)->to_native() << ">" << std::endl;
} else {
std::cout << "<Object: " << (void*)obj << ">" << std::endl;
}
}
void VM::set_const(const char* name, OBJECT val) {
globals.object->set_const(this, (char*)name, val);
}
void VM::set_const(Module* mod, const char* name, OBJECT val) {
mod->set_const(this, (char*)name, val);
}
void VM::print_backtrace() {
MethodContext* ctx = globals.current_task.get()->active;
while(!ctx->nil_p()) {
std::cout << (void*)ctx << ": ";
// HACK reports Object#[] instead of Hash::[], etc
std::cout << *ctx->module->name->to_str(this) << "#";
SYMBOL name = try_as<Symbol>(ctx->name);
if(name) {
std::cout << *name->to_str(this);
} else {
std::cout << *ctx->cm->name->to_str(this);
}
std::cout << ":" << ctx->line() << " in " << *ctx->cm->file->to_str(this);
std::cout << "\n";
ctx = ctx->sender;
}
}
Task* VM::new_task() {
Task* task = Task::create(this);
globals.current_task.set(task);
return task;
}
/* For debugging. */
extern "C" {
void __printbt__(STATE) {
state->print_backtrace();
}
}
};
<commit_msg>Handle BlockContext in the ruby backtrace<commit_after>#include "vm.hpp"
#include "objectmemory.hpp"
#include "objects.hpp"
#include "event.hpp"
#include "global_cache.hpp"
#include "llvm.hpp"
#include "builtin/class.hpp"
#include "builtin/contexts.hpp"
#include "builtin/fixnum.hpp"
#include "builtin/list.hpp"
#include "builtin/symbol.hpp"
#include "builtin/thread.hpp"
#include "builtin/tuple.hpp"
#include "builtin/string.hpp"
#include "config.hpp"
#include <iostream>
namespace rubinius {
VM::VM(size_t bytes) : probe(NULL), wait_events(false) {
config.compile_up_front = false;
context_cache = NULL;
user_config = new ConfigParser();
om = new ObjectMemory(bytes);
MethodContext::initialize_cache(this);
bootstrap_ontology();
events = new event::Loop(EVFLAG_FORKCHECK);
global_cache = new GlobalCache;
VMLLVMMethod::init("vm/instructions.bc");
boot_threads();
}
VM::~VM() {
delete om;
delete events;
delete global_cache;
llvm_cleanup();
}
void VM::boot_threads() {
Thread* thr = Thread::create(this);
thr->boot_task(this);
activate_thread(thr);
}
OBJECT VM::new_object(Class *cls) {
return om->new_object(cls, cls->instance_fields->to_native());
}
SYMBOL VM::symbol(const char* str) {
return symbols.lookup(this, str);
}
SYMBOL VM::symbol(String* str) {
return symbols.lookup(this, str);
}
SYMBOL VM::symbol(std::string str) {
return symbols.lookup(this, str);
}
OBJECT VM::new_struct(Class* cls, size_t bytes) {
return om->new_object_bytes(cls, bytes);
}
void type_assert(OBJECT obj, object_type type, const char* reason) {
if(obj->reference_p() && obj->obj_type != type) {
TypeError::raise(type, obj, reason);
} else if(type == FixnumType && !obj->fixnum_p()) {
TypeError::raise(type, obj, reason);
}
}
void VM::add_type_info(TypeInfo* ti) {
om->add_type_info(ti);
ti->state = this;
}
TypeInfo* VM::find_type(int type) {
return om->type_info[type];
}
Thread *VM::current_thread() {
return globals.current_thread.get();
}
void VM::collect() {
om->collect_young(globals.roots);
om->collect_mature(globals.roots);
}
void VM::run_best_thread() {
Thread* next = NULL;
events->poll();
for(size_t i = globals.scheduled_threads->field_count - 1; i > 0; i--) {
List* lst = as<List>(globals.scheduled_threads->at(i));
if(lst->empty_p()) continue;
next = as<Thread>(lst->shift(this));
break;
}
if(!next) {
if(events->num_of_events() == 0) {
throw DeadLock("no runnable threads, present or future.");
}
wait_events = true;
return;
}
activate_thread(next);
}
void VM::return_value(OBJECT val) {
globals.current_task->push(val);
}
void VM::queue_thread(Thread* thread) {
List* lst = as<List>(globals.scheduled_threads->at(thread->priority->to_native()));
lst->append(this, thread);
}
void VM::activate_thread(Thread* thread) {
globals.current_thread.set(thread);
globals.current_task.set(thread->task);
}
OBJECT VM::current_block() {
return globals.current_task->active->block;
}
void VM::raise_from_errno(const char* msg) {
// TODO: implement me
}
void VM::raise_exception(Exception* exc) {
// TODO: implement me
}
void VM::inspect(OBJECT obj) {
if(obj->symbol_p()) {
String* str = as<Symbol>(obj)->to_str(this);
std::cout << "<Symbol :" << (char*)*str << ">" << std::endl;
} else if(obj->fixnum_p()) {
std::cout << "<Fixnum " << as<Fixnum>(obj)->to_native() << ">" << std::endl;
} else {
std::cout << "<Object: " << (void*)obj << ">" << std::endl;
}
}
void VM::set_const(const char* name, OBJECT val) {
globals.object->set_const(this, (char*)name, val);
}
void VM::set_const(Module* mod, const char* name, OBJECT val) {
mod->set_const(this, (char*)name, val);
}
void VM::print_backtrace() {
MethodContext* ctx = globals.current_task.get()->active;
while(!ctx->nil_p()) {
std::cout << (void*)ctx << ": ";
if(kind_of<BlockContext>(ctx)) {
std::cout << "__block__";
} else {
// HACK reports Object#[] instead of Hash::[], etc
std::cout << *ctx->module->name->to_str(this) << "#";
SYMBOL name = try_as<Symbol>(ctx->name);
if(name) {
std::cout << *name->to_str(this);
} else {
std::cout << *ctx->cm->name->to_str(this);
}
}
std::cout << ":" << ctx->line() << " in " << *ctx->cm->file->to_str(this);
std::cout << "\n";
ctx = ctx->sender;
}
}
Task* VM::new_task() {
Task* task = Task::create(this);
globals.current_task.set(task);
return task;
}
/* For debugging. */
extern "C" {
void __printbt__(STATE) {
state->print_backtrace();
}
}
};
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <climits>
#include <fstream>
#include <ios>
#include <string>
#include <libport/bind.hh>
#include <libport/export.hh>
#include <libport/hierarchy.hh>
#include <libport/unit-test.hh>
#include <serialize/serialize.hh>
using libport::test_suite;
using namespace libport::serialize;
#define BASE "tests/serialize/"
#define SERIALIZE(Type, Value) \
BOOST_CHECK_NO_THROW(ser.serialize<Type>("test", Value))
#define UNSERIALIZE(Type, Value) \
BOOST_CHECK_EQUAL(ser.unserialize<Type>("test"), Value);
GD_INIT();
void binary_pod()
{
{
std::ofstream f(BASE "binary_pod");
BinaryOSerializer ser(f);
SERIALIZE(int, 42);
SERIALIZE(bool, true);
SERIALIZE(bool, false);
SERIALIZE(std::string, "string ");
int* p1 = new int(51);
int* p2 = new int(69);
SERIALIZE(int*, p1);
SERIALIZE(int*, p2);
SERIALIZE(int*, p2);
SERIALIZE(int*, p1);
SERIALIZE(int*, NULL);
}
{
std::ifstream f(BASE "binary_pod");
BOOST_CHECK(f.good());
BinaryISerializer ser(f);
UNSERIALIZE(int, 42);
UNSERIALIZE(bool, true);
UNSERIALIZE(bool, false);
UNSERIALIZE(std::string, "string ");
int* p1 = ser.unserialize<int*>("test");
int* p2 = ser.unserialize<int*>("test");
int* p3 = ser.unserialize<int*>("test");
int* p4 = ser.unserialize<int*>("test");
int* p5 = ser.unserialize<int*>("test");
BOOST_CHECK_EQUAL(*p1, 51);
BOOST_CHECK_EQUAL(*p2, 69);
BOOST_CHECK_EQUAL(p1, p4);
BOOST_CHECK_EQUAL(p2, p3);
BOOST_CHECK_EQUAL(p5, reinterpret_cast<int*>(NULL));
}
}
void binary_integers_size()
{
{
std::ofstream f(BASE "binary_integers_size");
BinaryOSerializer ser(f);
SERIALIZE(unsigned short, USHRT_MAX / 2);
SERIALIZE(unsigned int, UINT_MAX / 2);
SERIALIZE(unsigned long, ULONG_MAX / 2);
SERIALIZE(unsigned long long, ULONG_LONG_MAX / 2);
}
{
std::ifstream f(BASE "binary_integers_size");
BOOST_CHECK(f.good());
BinaryISerializer ser(f);
UNSERIALIZE(unsigned short, USHRT_MAX / 2);
UNSERIALIZE(unsigned int, UINT_MAX / 2);
UNSERIALIZE(unsigned long, ULONG_MAX / 2);
UNSERIALIZE(unsigned long long, ULONG_LONG_MAX / 2);
}
}
void binary_integers_size_portability()
{
// Simulate fancy short size.
{
std::ofstream f(BASE "binary_integers_size");
BinaryOSerializer ser(f);
// Change integers size.
char sizes[] = {0x4, 0x4, 0x4, 0x8,};
f.flush();
f.seekp(std::ios_base::beg);
f.write(sizes, sizeof(sizes));
f.flush();
SERIALIZE(uint32_t, 0);
SERIALIZE(uint32_t, 42);
SERIALIZE(uint32_t, USHRT_MAX + 1);
SERIALIZE(uint32_t, USHRT_MAX);
f.flush();
f.close();
}
{
std::ifstream f(BASE "binary_integers_size");
BOOST_CHECK(f.good());
BinaryISerializer ser(f);
UNSERIALIZE(unsigned short, 0);
UNSERIALIZE(unsigned short, 42);
BOOST_CHECK_THROW(ser.unserialize<unsigned short>(),
libport::serialize::Exception);
UNSERIALIZE(unsigned short, USHRT_MAX);
}
}
struct Person
{
Person(const std::string& name, const std::string& surname)
: name_(name)
, surname_(surname)
{}
template <typename S>
Person(ISerializer<S>& input)
: name_(input.template unserialize<std::string>("name"))
, surname_(input.template unserialize<std::string>("surname"))
{
}
template <typename S>
void serialize(OSerializer<S>& output) const
{
output.serialize<std::string>("name", name_);
output.serialize<std::string>("surname", surname_);
}
std::string name_, surname_;
};
void binary_class()
{
{
std::ofstream f(BASE "binary_class");
BinaryOSerializer ser(f);
Person ed("Draven", "Eric");
Person cs("Slade", "Cutter");
ser.serialize<Person>("test", ed);
ser.serialize<Person>("test", cs);
}
{
std::ifstream f(BASE "binary_class");
BinaryISerializer ser(f);
Person ed = ser.unserialize<Person>("test");
Person cs = ser.unserialize<Person>("test");
BOOST_CHECK_EQUAL(ed.name_, "Draven");
BOOST_CHECK_EQUAL(ed.surname_, "Eric");
BOOST_CHECK_EQUAL(cs.name_, "Slade");
BOOST_CHECK_EQUAL(cs.surname_, "Cutter");
}
}
class Unix;
class Linux;
class Gentoo;
class Debian;
class Unix: public libport::meta::Hierarchy<Unix, TYPELIST_2(Gentoo, Debian)>
{
};
struct Linux: public Unix
{
Linux(const std::string& k)
: kernel(k)
{}
template <typename T>
Linux(ISerializer<T>& ser)
{
kernel = ser.template unserialize<std::string>("kernel");
}
template <typename T>
void serialize(OSerializer<T>& ser) const
{
ser.template serialize<std::string>("kernel", kernel);
}
std::string kernel;
};
struct Debian: public Linux
{
Debian(const std::string& kernel, const std::string& v)
: Linux(kernel)
, version(v)
{}
template <typename T>
Debian(ISerializer<T>& ser)
: Linux(ser)
{
version = ser.template unserialize<std::string>("version");
}
template <typename T>
void serialize(OSerializer<T>& ser) const
{
Linux::serialize(ser);
ser.serialize<std::string>("version", version);
}
std::string version;
};
struct Gentoo: public Linux
{
Gentoo(const std::string& kernel, int v)
: Linux(kernel)
, version(v)
{}
template <typename T>
Gentoo(ISerializer<T>& ser)
: Linux(ser)
{
version = ser.template unserialize<int>("version");
}
template <typename T>
void serialize(OSerializer<T>& ser) const
{
Linux::serialize(ser);
ser.serialize<int>("version", version);
}
int version;
};
void binary_hierarchy()
{
{
std::ofstream f(BASE "binary_hier");
BinaryOSerializer ser(f);
Debian d("2.4", "sarge");
Gentoo g("2.6", 2008);
ser.serialize<Debian>("test", d);
ser.serialize<Gentoo>("test", g);
}
{
std::ifstream f(BASE "binary_hier");
BinaryISerializer ser(f);
Unix* d_ = ser.unserialize<Unix>("test");
Unix* g_ = ser.unserialize<Unix>("test");
Debian* d = dynamic_cast<Debian*>(d_ );
Gentoo* g = dynamic_cast<Gentoo*>(g_) ;
BOOST_CHECK(d);
BOOST_CHECK(g);
BOOST_CHECK_EQUAL(d->kernel, "2.4");
BOOST_CHECK_EQUAL(d->version, "sarge");
BOOST_CHECK_EQUAL(g->kernel, "2.6");
BOOST_CHECK_EQUAL(g->version, 2008);
}
}
test_suite*
init_test_suite()
{
test_suite* suite = BOOST_TEST_SUITE("Serialization test suite");
suite->add(BOOST_TEST_CASE(binary_pod));
suite->add(BOOST_TEST_CASE(binary_integers_size));
suite->add(BOOST_TEST_CASE(binary_integers_size_portability));
suite->add(BOOST_TEST_CASE(binary_class));
suite->add(BOOST_TEST_CASE(binary_hierarchy));
return suite;
}
<commit_msg>serialize: better tests.<commit_after>/*
* Copyright (C) 2009-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <climits>
#include <fstream>
#include <ios>
#include <string>
#include <libport/debug.hh>
#include <libport/bind.hh>
#include <libport/export.hh>
#include <libport/hierarchy.hh>
#include <libport/unit-test.hh>
#include <serialize/serialize.hh>
using libport::test_suite;
using namespace libport::serialize;
#define BASE "tests/serialize/"
#define SERIALIZE(Type, Value) \
BOOST_CHECK_NO_THROW(ser.serialize<Type>("test", Value))
#define UNSERIALIZE(Type, Value) \
BOOST_CHECK_EQUAL(ser.unserialize<Type>("test"), Value);
GD_INIT();
void binary_pod()
{
{
std::ofstream f(BASE "binary_pod");
BinaryOSerializer ser(f);
SERIALIZE(int, 42);
SERIALIZE(bool, true);
SERIALIZE(bool, false);
SERIALIZE(std::string, "string ");
int* p1 = new int(51);
int* p2 = new int(69);
SERIALIZE(int*, p1);
SERIALIZE(int*, p2);
SERIALIZE(int*, p2);
SERIALIZE(int*, p1);
SERIALIZE(int*, NULL);
}
{
std::ifstream f(BASE "binary_pod");
BOOST_CHECK(f.good());
BinaryISerializer ser(f);
UNSERIALIZE(int, 42);
UNSERIALIZE(bool, true);
UNSERIALIZE(bool, false);
UNSERIALIZE(std::string, "string ");
int* p1 = ser.unserialize<int*>("test");
int* p2 = ser.unserialize<int*>("test");
int* p3 = ser.unserialize<int*>("test");
int* p4 = ser.unserialize<int*>("test");
int* p5 = ser.unserialize<int*>("test");
BOOST_CHECK_EQUAL(*p1, 51);
BOOST_CHECK_EQUAL(*p2, 69);
BOOST_CHECK_EQUAL(p1, p4);
BOOST_CHECK_EQUAL(p2, p3);
BOOST_CHECK_EQUAL(p5, reinterpret_cast<int*>(NULL));
}
}
void binary_integers_size()
{
const char *fn = BASE "binary_integers_size";
#define CHECK(Type) \
do { \
{ \
std::ofstream f(fn); \
BinaryOSerializer ser(f); \
SERIALIZE(Type, (Type) (std::numeric_limits<Type>::max() / 2)); \
} \
{ \
std::ifstream f(fn); \
BOOST_CHECK(f.good()); \
BinaryISerializer ser(f); \
UNSERIALIZE(Type, (Type) (std::numeric_limits<Type>::max() / 2)); \
f.peek(); \
BOOST_CHECK(f.eof()); \
} \
} while (false)
CHECK(unsigned short);
CHECK(unsigned int);
CHECK(unsigned long);
CHECK(unsigned long long);
#undef CHECK
}
void binary_integers_size_portability()
{
// Simulate fancy short size.
{
std::ofstream f(BASE "binary_integers_size");
BinaryOSerializer ser(f);
// Change integers size.
char sizes[] = {0x4, 0x4, 0x4, 0x8,};
f.flush();
f.seekp(std::ios_base::beg);
f.write(sizes, sizeof(sizes));
f.flush();
SERIALIZE(uint32_t, 0);
SERIALIZE(uint32_t, 42);
SERIALIZE(uint32_t, USHRT_MAX + 1);
SERIALIZE(uint32_t, USHRT_MAX);
f.flush();
f.close();
}
{
std::ifstream f(BASE "binary_integers_size");
BOOST_CHECK(f.good());
BinaryISerializer ser(f);
UNSERIALIZE(unsigned short, 0);
UNSERIALIZE(unsigned short, 42);
BOOST_CHECK_THROW(ser.unserialize<unsigned short>(),
libport::serialize::Exception);
UNSERIALIZE(unsigned short, USHRT_MAX);
}
}
struct Person
{
Person(const std::string& name, const std::string& surname)
: name_(name)
, surname_(surname)
{}
template <typename S>
Person(ISerializer<S>& input)
: name_(input.template unserialize<std::string>("name"))
, surname_(input.template unserialize<std::string>("surname"))
{
}
template <typename S>
void serialize(OSerializer<S>& output) const
{
output.serialize<std::string>("name", name_);
output.serialize<std::string>("surname", surname_);
}
std::string name_, surname_;
};
void binary_class()
{
{
std::ofstream f(BASE "binary_class");
BinaryOSerializer ser(f);
Person ed("Draven", "Eric");
Person cs("Slade", "Cutter");
ser.serialize<Person>("test", ed);
ser.serialize<Person>("test", cs);
}
{
std::ifstream f(BASE "binary_class");
BinaryISerializer ser(f);
Person ed = ser.unserialize<Person>("test");
Person cs = ser.unserialize<Person>("test");
BOOST_CHECK_EQUAL(ed.name_, "Draven");
BOOST_CHECK_EQUAL(ed.surname_, "Eric");
BOOST_CHECK_EQUAL(cs.name_, "Slade");
BOOST_CHECK_EQUAL(cs.surname_, "Cutter");
}
}
class Unix;
class Linux;
class Gentoo;
class Debian;
class Unix: public libport::meta::Hierarchy<Unix, TYPELIST_2(Gentoo, Debian)>
{
};
struct Linux: public Unix
{
Linux(const std::string& k)
: kernel(k)
{}
template <typename T>
Linux(ISerializer<T>& ser)
{
kernel = ser.template unserialize<std::string>("kernel");
}
template <typename T>
void serialize(OSerializer<T>& ser) const
{
ser.template serialize<std::string>("kernel", kernel);
}
std::string kernel;
};
struct Debian: public Linux
{
Debian(const std::string& kernel, const std::string& v)
: Linux(kernel)
, version(v)
{}
template <typename T>
Debian(ISerializer<T>& ser)
: Linux(ser)
{
version = ser.template unserialize<std::string>("version");
}
template <typename T>
void serialize(OSerializer<T>& ser) const
{
Linux::serialize(ser);
ser.serialize<std::string>("version", version);
}
std::string version;
};
struct Gentoo: public Linux
{
Gentoo(const std::string& kernel, int v)
: Linux(kernel)
, version(v)
{}
template <typename T>
Gentoo(ISerializer<T>& ser)
: Linux(ser)
{
version = ser.template unserialize<int>("version");
}
template <typename T>
void serialize(OSerializer<T>& ser) const
{
Linux::serialize(ser);
ser.serialize<int>("version", version);
}
int version;
};
void binary_hierarchy()
{
{
std::ofstream f(BASE "binary_hier");
BinaryOSerializer ser(f);
Debian d("2.4", "sarge");
Gentoo g("2.6", 2008);
ser.serialize<Debian>("test", d);
ser.serialize<Gentoo>("test", g);
}
{
std::ifstream f(BASE "binary_hier");
BinaryISerializer ser(f);
Unix* d_ = ser.unserialize<Unix>("test");
Unix* g_ = ser.unserialize<Unix>("test");
Debian* d = dynamic_cast<Debian*>(d_ );
Gentoo* g = dynamic_cast<Gentoo*>(g_) ;
BOOST_CHECK(d);
BOOST_CHECK(g);
BOOST_CHECK_EQUAL(d->kernel, "2.4");
BOOST_CHECK_EQUAL(d->version, "sarge");
BOOST_CHECK_EQUAL(g->kernel, "2.6");
BOOST_CHECK_EQUAL(g->version, 2008);
}
}
test_suite*
init_test_suite()
{
test_suite* suite = BOOST_TEST_SUITE("Serialization test suite");
suite->add(BOOST_TEST_CASE(binary_pod));
suite->add(BOOST_TEST_CASE(binary_integers_size));
suite->add(BOOST_TEST_CASE(binary_integers_size_portability));
suite->add(BOOST_TEST_CASE(binary_class));
suite->add(BOOST_TEST_CASE(binary_hierarchy));
return suite;
}
<|endoftext|> |
<commit_before>#include <utils/logger.h>
#include <algorithm>
#include "DaedalusDialogManager.h"
#include "DaedalusVM.h"
#include "DaedalusStdlib.h"
using namespace Daedalus;
using namespace GameState;
using namespace ZenLoad;
DaedalusDialogManager::DaedalusDialogManager(Daedalus::DaedalusVM& vm,const std::string& ou_bin)
: m_VM(vm),
m_MessageLib(ou_bin)
{
gatherNpcInformation();
}
void DaedalusDialogManager::registerExternals(
std::function<void(NpcHandle, NpcHandle, const ZenLoad::oCMsgConversationData&)> onAIOutput,
std::function<void(NpcHandle, std::vector<InfoHandle>)> onStartConversation)
{
m_OnAIOutput = onAIOutput;
m_OnStartConversation = onStartConversation;
m_VM.registerExternalFunction("ai_output", [&](Daedalus::DaedalusVM& vm){
std::string outputname = vm.popString();
uint32_t target = vm.popVar();
uint32_t self = vm.popVar();
auto& message = m_MessageLib.getMessageByName(outputname);
NpcHandle hself = ZMemory::handleCast<NpcHandle>(m_VM.getDATFile().getSymbolByIndex(self).instanceDataHandle);
NpcHandle htarget = ZMemory::handleCast<NpcHandle>(m_VM.getDATFile().getSymbolByIndex(target).instanceDataHandle);
// Notify user
m_OnAIOutput(hself, htarget, message);
});
m_VM.registerExternalFunction("AI_ProcessInfos", [&](Daedalus::DaedalusVM& vm){
uint32_t self = vm.popVar();
NpcHandle hself = ZMemory::handleCast<NpcHandle>(m_VM.getDATFile().getSymbolByIndex(self).instanceDataHandle);
Daedalus::GEngineClasses::C_Npc& npc = m_VM.getGameState().getNpc(hself);
auto& info = m_NpcInfosByNpcSymbols[npc.instanceSymbol];
// Notify user
m_OnStartConversation(hself, info);
});
m_VM.registerExternalFunction("InfoManager_HasFinished", [](Daedalus::DaedalusVM& vm){
// TODO: Implement this
vm.setReturn(1);
});
m_VM.registerExternalFunction("npc_knowsinfo", [&](Daedalus::DaedalusVM& vm){
int32_t infoinstance = vm.popDataValue();
int32_t self = vm.popVar();
NpcHandle hself = ZMemory::handleCast<NpcHandle>(m_VM.getDATFile().getSymbolByIndex(self).instanceDataHandle);
Daedalus::GEngineClasses::C_Npc& npc = m_VM.getGameState().getNpc(hself);
auto& l = m_KnownNpcInfoSymbolsByNpcSymbols[npc.instanceSymbol];
int32_t knows = l.find(infoinstance) != l.end() ? 1 : 0;
//LogInfo() << "Does he kow? (" << vm.getDATFile().getSymbolByIndex(npc.instanceSymbol).name << " -> " << vm.getDATFile().getSymbolByIndex(infoinstance).name << "): " << knows;
vm.setReturn(knows);
});
}
void DaedalusDialogManager::gatherNpcInformation()
{
m_VM.getDATFile().iterateSymbolsOfClass("C_Info", [&](size_t i, Daedalus::PARSymbol& s){
// Create new info-object
InfoHandle h = m_VM.getGameState().createInfo();
Daedalus::GEngineClasses::C_Info& info = m_VM.getGameState().getInfo(h);
m_VM.initializeInstance(ZMemory::toBigHandle(h), i, Daedalus::IC_Info);
// Add to map
m_NpcInfosByNpcSymbols[info.npc].push_back(h);
});
// Messages are in wrong order. Fix this.
for(auto& v : m_NpcInfosByNpcSymbols)
{
std::reverse(v.second.begin(),v.second.end());
}
}
void DaedalusDialogManager::setNpcInfoKnown(size_t npcInstance, size_t infoInstance)
{
//LogInfo() << "He knows! (" << m_VM.getDATFile().getSymbolByIndex(npcInstance).name << " -> " << m_VM.getDATFile().getSymbolByIndex(infoInstance).name << ")!";
m_KnownNpcInfoSymbolsByNpcSymbols[npcInstance].insert(infoInstance);
}
void DaedalusDialogManager::processInfosFor(NpcHandle hnpc)
{
Daedalus::GEngineClasses::C_Npc& npc = m_VM.getGameState().getNpc(hnpc);
auto& info = m_NpcInfosByNpcSymbols[npc.instanceSymbol];
// Notify user
m_OnStartConversation(hnpc, info);
}
bool DaedalusDialogManager::doesNpcKnowInfo(size_t npcInstance, size_t infoInstance)
{
const auto& m = m_KnownNpcInfoSymbolsByNpcSymbols[npcInstance];
return m.find(infoInstance) != m.end();
}
<commit_msg>Not registering InfoManager_HasFinished anymore<commit_after>#include <utils/logger.h>
#include <algorithm>
#include "DaedalusDialogManager.h"
#include "DaedalusVM.h"
#include "DaedalusStdlib.h"
using namespace Daedalus;
using namespace GameState;
using namespace ZenLoad;
DaedalusDialogManager::DaedalusDialogManager(Daedalus::DaedalusVM& vm,const std::string& ou_bin)
: m_VM(vm),
m_MessageLib(ou_bin)
{
gatherNpcInformation();
}
void DaedalusDialogManager::registerExternals(
std::function<void(NpcHandle, NpcHandle, const ZenLoad::oCMsgConversationData&)> onAIOutput,
std::function<void(NpcHandle, std::vector<InfoHandle>)> onStartConversation)
{
m_OnAIOutput = onAIOutput;
m_OnStartConversation = onStartConversation;
m_VM.registerExternalFunction("ai_output", [&](Daedalus::DaedalusVM& vm){
std::string outputname = vm.popString();
uint32_t target = vm.popVar();
uint32_t self = vm.popVar();
auto& message = m_MessageLib.getMessageByName(outputname);
NpcHandle hself = ZMemory::handleCast<NpcHandle>(m_VM.getDATFile().getSymbolByIndex(self).instanceDataHandle);
NpcHandle htarget = ZMemory::handleCast<NpcHandle>(m_VM.getDATFile().getSymbolByIndex(target).instanceDataHandle);
// Notify user
m_OnAIOutput(hself, htarget, message);
});
m_VM.registerExternalFunction("AI_ProcessInfos", [&](Daedalus::DaedalusVM& vm){
uint32_t self = vm.popVar();
NpcHandle hself = ZMemory::handleCast<NpcHandle>(m_VM.getDATFile().getSymbolByIndex(self).instanceDataHandle);
Daedalus::GEngineClasses::C_Npc& npc = m_VM.getGameState().getNpc(hself);
auto& info = m_NpcInfosByNpcSymbols[npc.instanceSymbol];
// Notify user
m_OnStartConversation(hself, info);
});
m_VM.registerExternalFunction("npc_knowsinfo", [&](Daedalus::DaedalusVM& vm){
int32_t infoinstance = vm.popDataValue();
int32_t self = vm.popVar();
NpcHandle hself = ZMemory::handleCast<NpcHandle>(m_VM.getDATFile().getSymbolByIndex(self).instanceDataHandle);
Daedalus::GEngineClasses::C_Npc& npc = m_VM.getGameState().getNpc(hself);
auto& l = m_KnownNpcInfoSymbolsByNpcSymbols[npc.instanceSymbol];
int32_t knows = l.find(infoinstance) != l.end() ? 1 : 0;
//LogInfo() << "Does he kow? (" << vm.getDATFile().getSymbolByIndex(npc.instanceSymbol).name << " -> " << vm.getDATFile().getSymbolByIndex(infoinstance).name << "): " << knows;
vm.setReturn(knows);
});
}
void DaedalusDialogManager::gatherNpcInformation()
{
m_VM.getDATFile().iterateSymbolsOfClass("C_Info", [&](size_t i, Daedalus::PARSymbol& s){
// Create new info-object
InfoHandle h = m_VM.getGameState().createInfo();
Daedalus::GEngineClasses::C_Info& info = m_VM.getGameState().getInfo(h);
m_VM.initializeInstance(ZMemory::toBigHandle(h), i, Daedalus::IC_Info);
// Add to map
m_NpcInfosByNpcSymbols[info.npc].push_back(h);
});
// Messages are in wrong order. Fix this.
for(auto& v : m_NpcInfosByNpcSymbols)
{
std::reverse(v.second.begin(),v.second.end());
}
}
void DaedalusDialogManager::setNpcInfoKnown(size_t npcInstance, size_t infoInstance)
{
//LogInfo() << "He knows! (" << m_VM.getDATFile().getSymbolByIndex(npcInstance).name << " -> " << m_VM.getDATFile().getSymbolByIndex(infoInstance).name << ")!";
m_KnownNpcInfoSymbolsByNpcSymbols[npcInstance].insert(infoInstance);
}
void DaedalusDialogManager::processInfosFor(NpcHandle hnpc)
{
Daedalus::GEngineClasses::C_Npc& npc = m_VM.getGameState().getNpc(hnpc);
auto& info = m_NpcInfosByNpcSymbols[npc.instanceSymbol];
// Notify user
m_OnStartConversation(hnpc, info);
}
bool DaedalusDialogManager::doesNpcKnowInfo(size_t npcInstance, size_t infoInstance)
{
const auto& m = m_KnownNpcInfoSymbolsByNpcSymbols[npcInstance];
return m.find(infoInstance) != m.end();
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdint.h>
#include <chrono>
#ifdef LOWSTAR
#include "Low_GCMencrypt.h"
#endif // LOWSTAR
typedef unsigned char byte;
struct args
{
byte *plain_ptr;
uint64_t plain_num_bytes;
byte *auth_ptr;
uint64_t auth_num_bytes;
byte *iv_ptr;
byte *expanded_key_ptr;
byte *out_ptr;
byte *tag_ptr;
};
extern "C" void aes128_key_expansion(byte *key_ptr, byte *key_expansion_ptr);
extern "C" void gcm128_encrypt(args *a);
extern "C" int gcm128_decrypt(args *a);
extern "C" void aes256_key_expansion(byte *key_ptr, byte *key_expansion_ptr);
extern "C" void gcm256_encrypt(args *a);
extern "C" int gcm256_decrypt(args *a);
byte key[32] =
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16,17,18,19,20,21,22,23,24,25, 26, 27, 28, 29, 30, 31 };
byte key_expansion[15 * (128/8)];
byte plain[32] =
{ 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215,
216, 217, 218, 99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
byte auth[1]; // actually size 0
byte iv[16] =
{ 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 0, 0, 0, 0 };
byte out[32];
byte tag[16];
void printbytes(char *label, byte *b, int len)
{
printf("%s:", label);
for (int i = 0; i < len; i++) printf(" %2x", unsigned(b[i]));
printf("\n");
}
void test(void (*aes_key_expansion) (byte*, byte*),
void (*gcm_encrypt) (args*),
int (*gcm_decrypt) (args*),
int num_rounds)
{
args a;
a.plain_ptr = plain;
a.plain_num_bytes = 19;
a.auth_ptr = auth;
a.auth_num_bytes = 0;
a.iv_ptr = iv;
a.expanded_key_ptr = key_expansion;
a.out_ptr = out;
a.tag_ptr = tag;
printbytes((char*)"original plaintext", plain, 19);
printbytes((char*)"key", key, 16);
aes_key_expansion(key, key_expansion);
printbytes((char*)"key_expansion", key_expansion, (num_rounds + 1) * 16);
gcm_encrypt(&a);
printbytes((char*)"cipher", out, 19);
printbytes((char*)"tag", tag, 16);
a.out_ptr = plain;
a.plain_ptr = out;
int ret = gcm_decrypt(&a);
printf("gcm_decrypt returned %d\n", ret);
printbytes((char*)"plaintext", plain, 19);
int nblocks = 256;
byte *plain2 = new byte[nblocks * 16];
byte *out2 = new byte[nblocks * 16];
for (int i = 0; i < nblocks * 16; i++)
{
plain2[i] = i % 256;
}
a.plain_ptr = plain2;
a.plain_num_bytes = nblocks * 16;
a.out_ptr = out2;
for (int i = 0; i < 10; i++)
{
auto time1 = std::chrono::high_resolution_clock::now();
int n = 10000;
for (int j = 0; j < n; j++)
{
gcm_encrypt(&a);
}
auto time2 = std::chrono::high_resolution_clock::now();
int dt = std::chrono::duration_cast<std::chrono::microseconds>(time2 - time1).count();
printf("time = %d microseconds for %d iterations (%lf MB/s)\n", dt, n, double(n) * (nblocks * 16) / dt);
}
printbytes((char*)"cipher", out2, 16);
printbytes((char*)"tag", tag, 16);
}
#ifdef LOWSTAR
void test_lowstar() {
byte iv_backup[16];
// Save a copy of iv, since Low* version modifies it
memcpy(iv_backup, iv, 16);
int auth_num_bytes = 0;
int plain_num_bytes = 19;
int num_rounds = 10;
args a;
a.plain_ptr = plain;
a.plain_num_bytes = plain_num_bytes;
a.auth_ptr = auth;
a.auth_num_bytes = auth_num_bytes;
a.iv_ptr = iv;
a.expanded_key_ptr = key_expansion;
a.out_ptr = out;
a.tag_ptr = tag;
printbytes((char*)"original plaintext", plain, 19);
printbytes((char*)"key", key, 16);
aes128_key_expansion(key, key_expansion);
printbytes((char*)"key_expansion", key_expansion, (num_rounds + 1) * 16);
// Encrypt using Low* version
Low_GCMencrypt_gcm_core(plain, plain_num_bytes, auth, auth_num_bytes, iv, key_expansion, out, tag);
//gcm_encrypt(&a);
printbytes((char*)"cipher", out, 19);
printbytes((char*)"tag", tag, 16);
// Restore iv
memcpy(iv, iv_backup, 16);
a.out_ptr = plain;
a.plain_ptr = out;
// Decrypt using Vale version
int ret = gcm128_decrypt(&a);
printf("gcm_decrypt returned %d\n", ret);
printbytes((char*)"decrypted plaintext", plain, 19);
int nblocks = 256;
byte *plain2 = new byte[nblocks * 16];
byte *out2 = new byte[nblocks * 16];
for (int i = 0; i < nblocks * 16; i++)
{
plain2[i] = i % 256;
}
for (int i = 0; i < 10; i++)
{
auto time1 = std::chrono::high_resolution_clock::now();
int n = 10000;
for (int j = 0; j < n; j++)
{
Low_GCMencrypt_gcm_core(plain2, nblocks * 16, auth, auth_num_bytes, iv, key_expansion, out2, tag);
}
auto time2 = std::chrono::high_resolution_clock::now();
int dt = std::chrono::duration_cast<std::chrono::microseconds>(time2 - time1).count();
printf("time = %d microseconds for %d iterations (%lf MB/s)\n", dt, n, double(n) * (nblocks * 16) / dt);
}
printbytes((char*)"cipher", out2, 16);
printbytes((char*)"tag", tag, 16);
}
#endif // LOWSTAR
int main()
{
printf("hello\n");
#ifdef LOWSTAR
test_lowstar();
#else // !LOWSTAR
printf("\nBeginning 128-bit test...\n");
test(aes128_key_expansion,
gcm128_encrypt,
gcm128_decrypt,
10);
printf("\nBeginning 256-bit test...\n");
test(aes256_key_expansion,
gcm256_encrypt,
gcm256_decrypt,
14);
#endif // LOWSTAR
printf("goodbye\n");
return 0;
}
<commit_msg>Add additional alignment directives and profiling support<commit_after>#include <stdio.h>
#include <stdint.h>
#include <chrono>
#include <math.h>
#ifdef LOWSTAR
#include "Low_GCMencrypt.h"
#endif // LOWSTAR
typedef unsigned char byte;
double cpuFreq;
struct args
{
byte *plain_ptr;
uint64_t plain_num_bytes;
byte *auth_ptr;
uint64_t auth_num_bytes;
byte *iv_ptr;
byte *expanded_key_ptr;
byte *out_ptr;
byte *tag_ptr;
};
extern "C" void aes128_key_expansion(byte *key_ptr, byte *key_expansion_ptr);
extern "C" void gcm128_encrypt(args *a);
extern "C" int gcm128_decrypt(args *a);
extern "C" void aes256_key_expansion(byte *key_ptr, byte *key_expansion_ptr);
extern "C" void gcm256_encrypt(args *a);
extern "C" int gcm256_decrypt(args *a);
#ifdef _WIN32
#include <intrin.h>
#include <Windows.h>
#pragma intrinsic(__rdtsc)
#else
#include <unistd.h> /* For sleep() */
#define Sleep(x) usleep(x*1000)
#endif
alignas(128) byte key[32] =
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16,17,18,19,20,21,22,23,24,25, 26, 27, 28, 29, 30, 31 };
alignas(128) byte key_expansion[15 * (128/8)];
alignas(128) byte plain[32] =
{ 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215,
216, 217, 218, 99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
alignas(128) byte auth[1]; // actually size 0
alignas(128) byte iv[16] =
{ 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 0, 0, 0, 0 };
alignas(128) byte out[32] ;
alignas(128) byte tag[16] ;
void printbytes(char *label, byte *b, int len)
{
printf("%s:", label);
for (int i = 0; i < len; i++) printf(" %2x", unsigned(b[i]));
printf("\n");
}
uint64_t GetRDTSC() {
//VS on x64 doesn't support inline assembly
//__asm {
// ; Flush the pipeline
// XOR eax, eax
// CPUID
// ; Get RDTSC counter in edx:eax
// RDTSC
//}
#ifdef _WIN32
int CPUInfo[4];
int InfoType = 0;
__cpuid(CPUInfo, InfoType); // Serialize the pipeline
return (unsigned __int64)__rdtsc();
#else
// uint64_t rv;
// __asm__ (
// "push %%rbx;"
// "cpuid;"
// "pop %%rbx;"
// :::"%rax","%rcx","%rdx");
// __asm__ __volatile__ ("rdtsc" : "=A" (rv));
// return (rv);
unsigned int tickl, tickh;
__asm__ __volatile__("rdtsc":"=a"(tickl),"=d"(tickh));
return ((unsigned long long)tickh << 32)|tickl;
#endif // _WIN32
}
void test(void (*aes_key_expansion) (byte*, byte*),
void (*gcm_encrypt) (args*),
int (*gcm_decrypt) (args*),
int num_rounds)
{
args a;
a.plain_ptr = plain;
a.plain_num_bytes = 19;
a.auth_ptr = auth;
a.auth_num_bytes = 0;
a.iv_ptr = iv;
a.expanded_key_ptr = key_expansion;
a.out_ptr = out;
a.tag_ptr = tag;
printbytes((char*)"original plaintext", plain, 19);
printbytes((char*)"key", key, 16);
aes_key_expansion(key, key_expansion);
printbytes((char*)"key_expansion", key_expansion, (num_rounds + 1) * 16);
gcm_encrypt(&a);
printbytes((char*)"cipher", out, 19);
printbytes((char*)"tag", tag, 16);
a.out_ptr = plain;
a.plain_ptr = out;
int ret = gcm_decrypt(&a);
printf("gcm_decrypt returned %d\n", ret);
printbytes((char*)"plaintext", plain, 19);
int nblocks = 256;
byte *plain2 = new byte[nblocks * 16+128];
byte *out2 = new byte[nblocks * 16+128];
// Make sure the buffers are 128-bit aligned
int byte_offset = 128 - (((unsigned long long) plain2) % 128);
plain2 = (byte*) (((unsigned long long) plain2) + byte_offset);
byte_offset = 128 - (((unsigned long long) out2) % 128);
out2 = (byte*) (((unsigned long long) out2) + byte_offset);
printf("\nout2 pointer: %llx\n", (unsigned long long)out2);
printf("\nplain2 pointer: %llx\n", (unsigned long long)plain2);
printf("\nkey_expansion pointer: %llx\n", (unsigned long long)key_expansion);
for (int i = 0; i < nblocks * 16; i++)
{
plain2[i] = i % 256;
}
a.plain_ptr = plain2;
a.plain_num_bytes = nblocks * 16;
a.out_ptr = out2;
for (int i = 0; i < 10; i++)
{
auto time1 = std::chrono::high_resolution_clock::now();
uint64_t start = GetRDTSC();
int n = 10000;
for (int j = 0; j < n; j++)
{
gcm_encrypt(&a);
}
uint64_t end = GetRDTSC();
auto time2 = std::chrono::high_resolution_clock::now();
int dt = std::chrono::duration_cast<std::chrono::microseconds>(time2 - time1).count();
printf("time = %d microseconds for %d iterations (%lf MB/s)\n", dt, n, double(n) * (nblocks * 16) / dt);
printf("cycle diff = %llu, time = %fs\n", end - start, (end - start) / cpuFreq);
}
printbytes((char*)"cipher", out2, 16);
printbytes((char*)"tag", tag, 16);
}
#ifdef LOWSTAR
void test_lowstar() {
byte iv_backup[16];
// Save a copy of iv, since Low* version modifies it
memcpy(iv_backup, iv, 16);
int auth_num_bytes = 0;
int plain_num_bytes = 19;
int num_rounds = 10;
args a;
a.plain_ptr = plain;
a.plain_num_bytes = plain_num_bytes;
a.auth_ptr = auth;
a.auth_num_bytes = auth_num_bytes;
a.iv_ptr = iv;
a.expanded_key_ptr = key_expansion;
a.out_ptr = out;
a.tag_ptr = tag;
printbytes((char*)"original plaintext", plain, 19);
printbytes((char*)"key", key, 16);
aes128_key_expansion(key, key_expansion);
printbytes((char*)"key_expansion", key_expansion, (num_rounds + 1) * 16);
// Encrypt using Low* version
Low_GCMencrypt_gcm_core(plain, plain_num_bytes, auth, auth_num_bytes, iv, key_expansion, out, tag);
//gcm_encrypt(&a);
printbytes((char*)"cipher", out, 19);
printbytes((char*)"tag", tag, 16);
// Restore iv
memcpy(iv, iv_backup, 16);
a.out_ptr = plain;
a.plain_ptr = out;
// Decrypt using Vale version
int ret = gcm128_decrypt(&a);
printf("gcm_decrypt returned %d\n", ret);
printbytes((char*)"decrypted plaintext", plain, 19);
int nblocks = 256;
byte *plain2 = new byte[nblocks * 16];
byte *out2 = new byte[nblocks * 16];
for (int i = 0; i < nblocks * 16; i++)
{
plain2[i] = i % 256;
}
for (int i = 0; i < 10; i++)
{
auto time1 = std::chrono::high_resolution_clock::now();
int n = 10000;
for (int j = 0; j < n; j++)
{
Low_GCMencrypt_gcm_core(plain2, nblocks * 16, auth, auth_num_bytes, iv, key_expansion, out2, tag);
}
auto time2 = std::chrono::high_resolution_clock::now();
int dt = std::chrono::duration_cast<std::chrono::microseconds>(time2 - time1).count();
printf("time = %d microseconds for %d iterations (%lf MB/s)\n", dt, n, double(n) * (nblocks * 16) / dt);
}
printbytes((char*)"cipher", out2, 16);
printbytes((char*)"tag", tag, 16);
}
#endif // LOWSTAR
int main()
{
printf("hello\n");
// Calibrate frequency
uint64_t startTime = GetRDTSC();
Sleep(200); // Sleep for 200ms
uint64_t stopTime = GetRDTSC();
cpuFreq = (stopTime - startTime) / (200 / 1000.0);
printf("Measured CPU at %f GHz\n", cpuFreq/pow(10.0, 9));
#ifdef LOWSTAR
test_lowstar();
#else // !LOWSTAR
printf("\nBeginning 128-bit test...\n");
test(aes128_key_expansion,
gcm128_encrypt,
gcm128_decrypt,
10);
printf("\nBeginning 256-bit test...\n");
test(aes256_key_expansion,
gcm256_encrypt,
gcm256_decrypt,
14);
#endif // LOWSTAR
printf("goodbye\n");
return 0;
}
<|endoftext|> |
<commit_before>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// author: Axel Naumann <[email protected]>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "IncrementalExecutor.h"
#include "IncrementalJIT.h"
#include "Threading.h"
#include "cling/Interpreter/Value.h"
#include "cling/Interpreter/Transaction.h"
#include "cling/Utils/AST.h"
#include "cling/Utils/Output.h"
#include "cling/Utils/Platform.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Frontend/CodeGenOptions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Target/TargetMachine.h"
using namespace llvm;
namespace cling {
namespace {
static std::unique_ptr<TargetMachine>
CreateHostTargetMachine(const clang::CompilerInstance& CI) {
const clang::TargetOptions& TargetOpts = CI.getTargetOpts();
const clang::CodeGenOptions& CGOpt = CI.getCodeGenOpts();
const std::string& Triple = TargetOpts.Triple;
std::string Error;
const Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
if (!TheTarget) {
cling::errs() << "cling::IncrementalExecutor: unable to find target:\n"
<< Error;
return std::unique_ptr<TargetMachine>();
}
// We have to use large code model for PowerPC64 because TOC and text sections
// can be more than 2GB apart.
#if defined(__powerpc64__) || defined(__PPC64__)
CodeModel::Model CMModel = CodeModel::Large;
#else
CodeModel::Model CMModel = CodeModel::JITDefault;
#endif
CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
switch (CGOpt.OptimizationLevel) {
case 0: OptLevel = CodeGenOpt::None; break;
case 1: OptLevel = CodeGenOpt::Less; break;
case 2: OptLevel = CodeGenOpt::Default; break;
case 3: OptLevel = CodeGenOpt::Aggressive; break;
default: OptLevel = CodeGenOpt::Default;
}
std::string MCPU;
std::string FeaturesStr;
auto TM = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(Triple,
MCPU, FeaturesStr,
llvm::TargetOptions(),
Optional<Reloc::Model>(), CMModel,
OptLevel));
TM->Options.EmulatedTLS = true;
return TM;
}
} // anonymous namespace
IncrementalExecutor::IncrementalExecutor(clang::DiagnosticsEngine& diags,
const clang::CompilerInstance& CI):
m_Callbacks(nullptr), m_externalIncrementalExecutor(nullptr)
#if 0
: m_Diags(diags)
#endif
{
// MSVC doesn't support m_AtExitFuncsSpinLock=ATOMIC_FLAG_INIT; in the class definition
std::atomic_flag_clear( &m_AtExitFuncsSpinLock );
std::unique_ptr<TargetMachine> TM(CreateHostTargetMachine(CI));
m_BackendPasses.reset(new BackendPasses(CI.getCodeGenOpts(),
CI.getTargetOpts(),
CI.getLangOpts(),
*TM));
m_JIT.reset(new IncrementalJIT(*this, std::move(TM)));
}
// Keep in source: ~unique_ptr<ClingJIT> needs ClingJIT
IncrementalExecutor::~IncrementalExecutor() {}
void IncrementalExecutor::shuttingDown() {
// It is legal to register an atexit handler from within another atexit
// handler and furthor-more the standard says they need to run in reverse
// order, so this function must be recursion safe.
AtExitFunctions Local;
{
cling::internal::SpinLockGuard slg(m_AtExitFuncsSpinLock);
// Check this case first, to avoid the swap all-together.
if (m_AtExitFuncs.empty())
return;
Local.swap(m_AtExitFuncs);
}
for (auto&& Ordered : llvm::reverse(Local.ordered())) {
for (auto&& AtExit : llvm::reverse(Ordered->second))
AtExit();
// The standard says that they need to run in reverse order, which means
// anything added from 'AtExit()' must now be run!
shuttingDown();
}
}
void IncrementalExecutor::AddAtExitFunc(void (*func)(void*), void* arg,
const std::shared_ptr<llvm::Module>& M) {
// Register a CXAAtExit function
cling::internal::SpinLockGuard slg(m_AtExitFuncsSpinLock);
m_AtExitFuncs[M].emplace_back(func, arg);
}
void unresolvedSymbol()
{
// This might get called recursively, or a billion of times. Do not generate
// useless output; unresolvedSymbol() is always handed out with an error
// message - that's enough.
//cling::errs() << "IncrementalExecutor: calling unresolved symbol, "
// "see previous error message!\n";
// throw exception instead?
}
void* IncrementalExecutor::HandleMissingFunction(const std::string& mangled_name)
{
// Not found in the map, add the symbol in the list of unresolved symbols
if (m_unresolvedSymbols.insert(mangled_name).second) {
//cling::errs() << "IncrementalExecutor: use of undefined symbol '"
// << mangled_name << "'!\n";
}
return utils::FunctionToVoidPtr(&unresolvedSymbol);
}
void* IncrementalExecutor::NotifyLazyFunctionCreators(const std::string& mangled_name)
{
for (std::vector<LazyFunctionCreatorFunc_t>::iterator it
= m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end();
it != et; ++it) {
void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name);
if (ret)
return ret;
}
void *address = nullptr;
if (m_externalIncrementalExecutor)
address = m_externalIncrementalExecutor->getAddressOfGlobal(mangled_name);
return (address ? address : HandleMissingFunction(mangled_name));
}
#if 0
// FIXME: employ to empty module dependencies *within* the *current* module.
static void
freeCallersOfUnresolvedSymbols(llvm::SmallVectorImpl<llvm::Function*>&
funcsToFree, llvm::ExecutionEngine* engine) {
llvm::SmallPtrSet<llvm::Function*, 40> funcsToFreeUnique;
for (size_t i = 0; i < funcsToFree.size(); ++i) {
llvm::Function* func = funcsToFree[i];
assert(func && "Cannot free NULL function");
if (funcsToFreeUnique.insert(func).second) {
for (llvm::Value::use_iterator IU = func->use_begin(),
EU = func->use_end(); IU != EU; ++IU) {
llvm::Instruction* instUser = llvm::dyn_cast<llvm::Instruction>(*IU);
if (!instUser) continue;
if (!instUser->getParent()) continue;
if (llvm::Function* userFunc = instUser->getParent()->getParent())
funcsToFree.push_back(userFunc);
}
}
}
for (llvm::SmallPtrSet<llvm::Function*, 40>::iterator
I = funcsToFreeUnique.begin(), E = funcsToFreeUnique.end();
I != E; ++I) {
// This should force the JIT to recompile the function. But the stubs stay,
// and the JIT reuses the stubs now pointing nowhere, i.e. without updating
// the machine code address. Fix the JIT, or hope that MCJIT helps.
//engine->freeMachineCodeForFunction(*I);
engine->updateGlobalMapping(*I, 0);
}
}
#endif
IncrementalExecutor::ExecutionResult
IncrementalExecutor::runStaticInitializersOnce(const Transaction& T) {
auto m = T.getModule();
assert(m.get() && "Module must not be null");
// We don't care whether something was unresolved before.
m_unresolvedSymbols.clear();
// check if there is any unresolved symbol in the list
if (diagnoseUnresolvedSymbols("static initializers"))
return kExeUnresolvedSymbols;
llvm::GlobalVariable* GV
= m->getGlobalVariable("llvm.global_ctors", true);
// Nothing to do is good, too.
if (!GV) return kExeSuccess;
// Close similarity to
// m_engine->runStaticConstructorsDestructors(false) aka
// llvm::ExecutionEngine::runStaticConstructorsDestructors()
// is intentional; we do an extra pass to check whether the JIT
// managed to collect all the symbols needed by the niitializers.
// Should be an array of '{ i32, void ()* }' structs. The first value is
// the init priority, which we ignore.
llvm::ConstantArray *InitList
= llvm::dyn_cast<llvm::ConstantArray>(GV->getInitializer());
// We need to delete it here just in case we have recursive inits, otherwise
// it will call inits multiple times.
GV->eraseFromParent();
if (InitList == 0)
return kExeSuccess;
//SmallVector<Function*, 2> initFuncs;
for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
llvm::ConstantStruct *CS
= llvm::dyn_cast<llvm::ConstantStruct>(InitList->getOperand(i));
if (CS == 0) continue;
llvm::Constant *FP = CS->getOperand(1);
if (FP->isNullValue())
continue; // Found a sentinal value, ignore.
// Strip off constant expression casts.
if (llvm::ConstantExpr *CE = llvm::dyn_cast<llvm::ConstantExpr>(FP))
if (CE->isCast())
FP = CE->getOperand(0);
// Execute the ctor/dtor function!
if (llvm::Function *F = llvm::dyn_cast<llvm::Function>(FP)) {
const llvm::StringRef fName = F->getName();
executeInit(fName);
/*
initFuncs.push_back(F);
if (fName.startswith("_GLOBAL__sub_I_")) {
BasicBlock& BB = F->getEntryBlock();
for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
if (CallInst* call = dyn_cast<CallInst>(I))
initFuncs.push_back(call->getCalledFunction());
}
*/
}
}
/*
for (SmallVector<Function*,2>::iterator I = initFuncs.begin(),
E = initFuncs.end(); I != E; ++I) {
// Cleanup also the dangling init functions. They are in the form:
// define internal void @_GLOBAL__I_aN() section "..."{
// entry:
// call void @__cxx_global_var_init(N-1)()
// call void @__cxx_global_var_initM()
// ret void
// }
//
// define internal void @__cxx_global_var_init(N-1)() section "..." {
// entry:
// call void @_ZN7MyClassC1Ev(%struct.MyClass* @n)
// ret void
// }
// Erase __cxx_global_var_init(N-1)() first.
(*I)->removeDeadConstantUsers();
(*I)->eraseFromParent();
}
*/
return kExeSuccess;
}
void IncrementalExecutor::runAndRemoveStaticDestructors(Transaction* T) {
assert(T && "Must be set");
// Collect all the dtors bound to this transaction.
AtExitFunctions::mapped_type Local;
{
cling::internal::SpinLockGuard slg(m_AtExitFuncsSpinLock);
auto Itr = m_AtExitFuncs.find(T->getModule());
if (Itr == m_AtExitFuncs.end()) return;
m_AtExitFuncs.erase(Itr, &Local);
} // end of spin lock lifetime block.
// 'Unload' the cxa_atexit, atexit entities.
for (auto&& AtExit : llvm::reverse(Local)) {
AtExit();
// Run anything that was just registered in 'AtExit()'
runAndRemoveStaticDestructors(T);
}
}
void
IncrementalExecutor::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp)
{
m_lazyFuncCreator.push_back(fp);
}
bool
IncrementalExecutor::addSymbol(const char* Name, void* Addr,
bool Jit) {
return m_JIT->lookupSymbol(Name, Addr, Jit).second;
}
void* IncrementalExecutor::getAddressOfGlobal(llvm::StringRef symbolName,
bool* fromJIT /*=0*/) {
// Return a symbol's address, and whether it was jitted.
void* address = m_JIT->lookupSymbol(symbolName).first;
// It's not from the JIT if it's in a dylib.
if (fromJIT)
*fromJIT = !address;
if (!address)
return (void*)m_JIT->getSymbolAddress(symbolName, false /*no dlsym*/);
return address;
}
void*
IncrementalExecutor::getPointerToGlobalFromJIT(const llvm::GlobalValue& GV) {
// Get the function / variable pointer referenced by GV.
// We don't care whether something was unresolved before.
m_unresolvedSymbols.clear();
void* addr = (void*)m_JIT->getSymbolAddress(GV.getName(),
false /*no dlsym*/);
if (diagnoseUnresolvedSymbols(GV.getName(), "symbol"))
return 0;
return addr;
}
bool IncrementalExecutor::diagnoseUnresolvedSymbols(llvm::StringRef trigger,
llvm::StringRef title) {
if (m_unresolvedSymbols.empty())
return false;
llvm::SmallVector<llvm::Function*, 128> funcsToFree;
for (const std::string& sym : m_unresolvedSymbols) {
#if 0
// FIXME: This causes a lot of test failures, for some reason it causes
// the call to HandleMissingFunction to be elided.
unsigned diagID = m_Diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
"%0 unresolved while jitting %1");
(void)diagID;
//m_Diags.Report(diagID) << sym << funcname; // TODO: demangle the names.
#endif
cling::errs() << "IncrementalExecutor::executeFunction: symbol '" << sym
<< "' unresolved while linking ";
if (trigger.find(utils::Synthesize::UniquePrefix) != llvm::StringRef::npos)
cling::errs() << "[cling interface function]";
else {
if (!title.empty())
cling::errs() << title << " '";
cling::errs() << trigger;
if (!title.empty())
cling::errs() << "'";
}
cling::errs() << "!\n";
// Be helpful, demangle!
std::string demangledName = platform::Demangle(sym);
if (!demangledName.empty()) {
cling::errs()
<< "You are probably missing the definition of "
<< demangledName << "\n"
<< "Maybe you need to load the corresponding shared library?\n";
}
//llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str());
// i could also reference a global variable, in which case ff == 0.
//if (ff)
// funcsToFree.push_back(ff);
}
//freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get());
m_unresolvedSymbols.clear();
return true;
}
}// end namespace cling
<commit_msg>Fix formatting of the TLS commit<commit_after>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// author: Axel Naumann <[email protected]>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "IncrementalExecutor.h"
#include "IncrementalJIT.h"
#include "Threading.h"
#include "cling/Interpreter/Value.h"
#include "cling/Interpreter/Transaction.h"
#include "cling/Utils/AST.h"
#include "cling/Utils/Output.h"
#include "cling/Utils/Platform.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Frontend/CodeGenOptions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Target/TargetMachine.h"
using namespace llvm;
namespace cling {
namespace {
static std::unique_ptr<TargetMachine>
CreateHostTargetMachine(const clang::CompilerInstance& CI) {
const clang::TargetOptions& TargetOpts = CI.getTargetOpts();
const clang::CodeGenOptions& CGOpt = CI.getCodeGenOpts();
const std::string& Triple = TargetOpts.Triple;
std::string Error;
const Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
if (!TheTarget) {
cling::errs() << "cling::IncrementalExecutor: unable to find target:\n"
<< Error;
return std::unique_ptr<TargetMachine>();
}
// We have to use large code model for PowerPC64 because TOC and text sections
// can be more than 2GB apart.
#if defined(__powerpc64__) || defined(__PPC64__)
CodeModel::Model CMModel = CodeModel::Large;
#else
CodeModel::Model CMModel = CodeModel::JITDefault;
#endif
CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
switch (CGOpt.OptimizationLevel) {
case 0: OptLevel = CodeGenOpt::None; break;
case 1: OptLevel = CodeGenOpt::Less; break;
case 2: OptLevel = CodeGenOpt::Default; break;
case 3: OptLevel = CodeGenOpt::Aggressive; break;
default: OptLevel = CodeGenOpt::Default;
}
std::string MCPU;
std::string FeaturesStr;
auto TM = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
Triple, MCPU, FeaturesStr, llvm::TargetOptions(),
Optional<Reloc::Model>(), CMModel, OptLevel));
TM->Options.EmulatedTLS = true;
return TM;
}
} // anonymous namespace
IncrementalExecutor::IncrementalExecutor(clang::DiagnosticsEngine& diags,
const clang::CompilerInstance& CI):
m_Callbacks(nullptr), m_externalIncrementalExecutor(nullptr)
#if 0
: m_Diags(diags)
#endif
{
// MSVC doesn't support m_AtExitFuncsSpinLock=ATOMIC_FLAG_INIT; in the class definition
std::atomic_flag_clear( &m_AtExitFuncsSpinLock );
std::unique_ptr<TargetMachine> TM(CreateHostTargetMachine(CI));
m_BackendPasses.reset(new BackendPasses(CI.getCodeGenOpts(),
CI.getTargetOpts(),
CI.getLangOpts(),
*TM));
m_JIT.reset(new IncrementalJIT(*this, std::move(TM)));
}
// Keep in source: ~unique_ptr<ClingJIT> needs ClingJIT
IncrementalExecutor::~IncrementalExecutor() {}
void IncrementalExecutor::shuttingDown() {
// It is legal to register an atexit handler from within another atexit
// handler and furthor-more the standard says they need to run in reverse
// order, so this function must be recursion safe.
AtExitFunctions Local;
{
cling::internal::SpinLockGuard slg(m_AtExitFuncsSpinLock);
// Check this case first, to avoid the swap all-together.
if (m_AtExitFuncs.empty())
return;
Local.swap(m_AtExitFuncs);
}
for (auto&& Ordered : llvm::reverse(Local.ordered())) {
for (auto&& AtExit : llvm::reverse(Ordered->second))
AtExit();
// The standard says that they need to run in reverse order, which means
// anything added from 'AtExit()' must now be run!
shuttingDown();
}
}
void IncrementalExecutor::AddAtExitFunc(void (*func)(void*), void* arg,
const std::shared_ptr<llvm::Module>& M) {
// Register a CXAAtExit function
cling::internal::SpinLockGuard slg(m_AtExitFuncsSpinLock);
m_AtExitFuncs[M].emplace_back(func, arg);
}
void unresolvedSymbol()
{
// This might get called recursively, or a billion of times. Do not generate
// useless output; unresolvedSymbol() is always handed out with an error
// message - that's enough.
//cling::errs() << "IncrementalExecutor: calling unresolved symbol, "
// "see previous error message!\n";
// throw exception instead?
}
void* IncrementalExecutor::HandleMissingFunction(const std::string& mangled_name)
{
// Not found in the map, add the symbol in the list of unresolved symbols
if (m_unresolvedSymbols.insert(mangled_name).second) {
//cling::errs() << "IncrementalExecutor: use of undefined symbol '"
// << mangled_name << "'!\n";
}
return utils::FunctionToVoidPtr(&unresolvedSymbol);
}
void* IncrementalExecutor::NotifyLazyFunctionCreators(const std::string& mangled_name)
{
for (std::vector<LazyFunctionCreatorFunc_t>::iterator it
= m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end();
it != et; ++it) {
void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name);
if (ret)
return ret;
}
void *address = nullptr;
if (m_externalIncrementalExecutor)
address = m_externalIncrementalExecutor->getAddressOfGlobal(mangled_name);
return (address ? address : HandleMissingFunction(mangled_name));
}
#if 0
// FIXME: employ to empty module dependencies *within* the *current* module.
static void
freeCallersOfUnresolvedSymbols(llvm::SmallVectorImpl<llvm::Function*>&
funcsToFree, llvm::ExecutionEngine* engine) {
llvm::SmallPtrSet<llvm::Function*, 40> funcsToFreeUnique;
for (size_t i = 0; i < funcsToFree.size(); ++i) {
llvm::Function* func = funcsToFree[i];
assert(func && "Cannot free NULL function");
if (funcsToFreeUnique.insert(func).second) {
for (llvm::Value::use_iterator IU = func->use_begin(),
EU = func->use_end(); IU != EU; ++IU) {
llvm::Instruction* instUser = llvm::dyn_cast<llvm::Instruction>(*IU);
if (!instUser) continue;
if (!instUser->getParent()) continue;
if (llvm::Function* userFunc = instUser->getParent()->getParent())
funcsToFree.push_back(userFunc);
}
}
}
for (llvm::SmallPtrSet<llvm::Function*, 40>::iterator
I = funcsToFreeUnique.begin(), E = funcsToFreeUnique.end();
I != E; ++I) {
// This should force the JIT to recompile the function. But the stubs stay,
// and the JIT reuses the stubs now pointing nowhere, i.e. without updating
// the machine code address. Fix the JIT, or hope that MCJIT helps.
//engine->freeMachineCodeForFunction(*I);
engine->updateGlobalMapping(*I, 0);
}
}
#endif
IncrementalExecutor::ExecutionResult
IncrementalExecutor::runStaticInitializersOnce(const Transaction& T) {
auto m = T.getModule();
assert(m.get() && "Module must not be null");
// We don't care whether something was unresolved before.
m_unresolvedSymbols.clear();
// check if there is any unresolved symbol in the list
if (diagnoseUnresolvedSymbols("static initializers"))
return kExeUnresolvedSymbols;
llvm::GlobalVariable* GV
= m->getGlobalVariable("llvm.global_ctors", true);
// Nothing to do is good, too.
if (!GV) return kExeSuccess;
// Close similarity to
// m_engine->runStaticConstructorsDestructors(false) aka
// llvm::ExecutionEngine::runStaticConstructorsDestructors()
// is intentional; we do an extra pass to check whether the JIT
// managed to collect all the symbols needed by the niitializers.
// Should be an array of '{ i32, void ()* }' structs. The first value is
// the init priority, which we ignore.
llvm::ConstantArray *InitList
= llvm::dyn_cast<llvm::ConstantArray>(GV->getInitializer());
// We need to delete it here just in case we have recursive inits, otherwise
// it will call inits multiple times.
GV->eraseFromParent();
if (InitList == 0)
return kExeSuccess;
//SmallVector<Function*, 2> initFuncs;
for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
llvm::ConstantStruct *CS
= llvm::dyn_cast<llvm::ConstantStruct>(InitList->getOperand(i));
if (CS == 0) continue;
llvm::Constant *FP = CS->getOperand(1);
if (FP->isNullValue())
continue; // Found a sentinal value, ignore.
// Strip off constant expression casts.
if (llvm::ConstantExpr *CE = llvm::dyn_cast<llvm::ConstantExpr>(FP))
if (CE->isCast())
FP = CE->getOperand(0);
// Execute the ctor/dtor function!
if (llvm::Function *F = llvm::dyn_cast<llvm::Function>(FP)) {
const llvm::StringRef fName = F->getName();
executeInit(fName);
/*
initFuncs.push_back(F);
if (fName.startswith("_GLOBAL__sub_I_")) {
BasicBlock& BB = F->getEntryBlock();
for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
if (CallInst* call = dyn_cast<CallInst>(I))
initFuncs.push_back(call->getCalledFunction());
}
*/
}
}
/*
for (SmallVector<Function*,2>::iterator I = initFuncs.begin(),
E = initFuncs.end(); I != E; ++I) {
// Cleanup also the dangling init functions. They are in the form:
// define internal void @_GLOBAL__I_aN() section "..."{
// entry:
// call void @__cxx_global_var_init(N-1)()
// call void @__cxx_global_var_initM()
// ret void
// }
//
// define internal void @__cxx_global_var_init(N-1)() section "..." {
// entry:
// call void @_ZN7MyClassC1Ev(%struct.MyClass* @n)
// ret void
// }
// Erase __cxx_global_var_init(N-1)() first.
(*I)->removeDeadConstantUsers();
(*I)->eraseFromParent();
}
*/
return kExeSuccess;
}
void IncrementalExecutor::runAndRemoveStaticDestructors(Transaction* T) {
assert(T && "Must be set");
// Collect all the dtors bound to this transaction.
AtExitFunctions::mapped_type Local;
{
cling::internal::SpinLockGuard slg(m_AtExitFuncsSpinLock);
auto Itr = m_AtExitFuncs.find(T->getModule());
if (Itr == m_AtExitFuncs.end()) return;
m_AtExitFuncs.erase(Itr, &Local);
} // end of spin lock lifetime block.
// 'Unload' the cxa_atexit, atexit entities.
for (auto&& AtExit : llvm::reverse(Local)) {
AtExit();
// Run anything that was just registered in 'AtExit()'
runAndRemoveStaticDestructors(T);
}
}
void
IncrementalExecutor::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp)
{
m_lazyFuncCreator.push_back(fp);
}
bool
IncrementalExecutor::addSymbol(const char* Name, void* Addr,
bool Jit) {
return m_JIT->lookupSymbol(Name, Addr, Jit).second;
}
void* IncrementalExecutor::getAddressOfGlobal(llvm::StringRef symbolName,
bool* fromJIT /*=0*/) {
// Return a symbol's address, and whether it was jitted.
void* address = m_JIT->lookupSymbol(symbolName).first;
// It's not from the JIT if it's in a dylib.
if (fromJIT)
*fromJIT = !address;
if (!address)
return (void*)m_JIT->getSymbolAddress(symbolName, false /*no dlsym*/);
return address;
}
void*
IncrementalExecutor::getPointerToGlobalFromJIT(const llvm::GlobalValue& GV) {
// Get the function / variable pointer referenced by GV.
// We don't care whether something was unresolved before.
m_unresolvedSymbols.clear();
void* addr = (void*)m_JIT->getSymbolAddress(GV.getName(),
false /*no dlsym*/);
if (diagnoseUnresolvedSymbols(GV.getName(), "symbol"))
return 0;
return addr;
}
bool IncrementalExecutor::diagnoseUnresolvedSymbols(llvm::StringRef trigger,
llvm::StringRef title) {
if (m_unresolvedSymbols.empty())
return false;
llvm::SmallVector<llvm::Function*, 128> funcsToFree;
for (const std::string& sym : m_unresolvedSymbols) {
#if 0
// FIXME: This causes a lot of test failures, for some reason it causes
// the call to HandleMissingFunction to be elided.
unsigned diagID = m_Diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
"%0 unresolved while jitting %1");
(void)diagID;
//m_Diags.Report(diagID) << sym << funcname; // TODO: demangle the names.
#endif
cling::errs() << "IncrementalExecutor::executeFunction: symbol '" << sym
<< "' unresolved while linking ";
if (trigger.find(utils::Synthesize::UniquePrefix) != llvm::StringRef::npos)
cling::errs() << "[cling interface function]";
else {
if (!title.empty())
cling::errs() << title << " '";
cling::errs() << trigger;
if (!title.empty())
cling::errs() << "'";
}
cling::errs() << "!\n";
// Be helpful, demangle!
std::string demangledName = platform::Demangle(sym);
if (!demangledName.empty()) {
cling::errs()
<< "You are probably missing the definition of "
<< demangledName << "\n"
<< "Maybe you need to load the corresponding shared library?\n";
}
//llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str());
// i could also reference a global variable, in which case ff == 0.
//if (ff)
// funcsToFree.push_back(ff);
}
//freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get());
m_unresolvedSymbols.clear();
return true;
}
}// end namespace cling
<|endoftext|> |
<commit_before>/*
* copyright: (c) RDO-Team, 2011
* filename : procgui.cpp
* author :
* date : 22.04.2011
* bref :
* indent : 4T
*/
// ====================================================================== PCH
// ====================================================================== INCLUDES
// ====================================================================== SYNOPSIS
#include "rdo_lib/rdo_simulator/ProcGUI.h"
#include "rdo_lib/rdo_mbuilder/rdo_resources.h"
// ===============================================================================
// --------------------------------------------------------------------
// ---------- ProcGUIBlock
// --------------------------------------------------------------------
ProcGUIBlock::ProcGUIBlock(PTR(rdoParse::RDOParser) pParser, PTR(rdoRuntime::RDORuntime) pRuntime)
: m_pParser (pParser )
, m_pRuntime(pRuntime)
{
//!
m_pProcess = F(rdoRuntime::RDOPROCProcess)::create(_T("GuiProcess"), m_pRuntime);
ASSERT(m_pProcess);
m_pProcess.query_cast<ILogic>()->init(m_pRuntime);
}
ProcGUIBlock::~ProcGUIBlock()
{}
void ProcGUIBlock::Create()
{
tstring rtp_name = _T("");
tstring rtp_param_name = _T("_");
//!
rdoMBuilder::RDOResTypeList rtpList(m_pParser);
//! , ,
if (!rtpList[rtp_name].exist())
{
//!
rdoMBuilder::RDOResType rtp(rtp_name);
//! _
rtp.m_params.append(rdoMBuilder::RDOResType::Param(rtp_param_name, rdo::Factory<rdoParse::RDOType__real>::create()));
//!
rdoRuntime::RDOPROCTransact::typeID = rtp.id();
}
else
{
CREF(rdoMBuilder::RDOResType) rtp = rtpList[rtp_name];
rdoRuntime::RDOPROCTransact::typeID = rtp.id();
}
//! GENERATE
rdoRuntime::LPRDOCalcConst pCalc = rdo::Factory<rdoRuntime::RDOCalcConst>::create(4);
LPIPROCBlock pBlock = F(rdoRuntime::RDOPROCGenerate)::create(m_pProcess, pCalc);
ASSERT(pBlock);
//! TERMINATE
pBlock = F(rdoRuntime::RDOPROCTerminate)::create(m_pProcess, 1);
ASSERT(pBlock);
}
<commit_msg> - форматирование<commit_after>/*
* copyright: (c) RDO-Team, 2011
* filename : procgui.cpp
* author :
* date : 22.04.2011
* bref :
* indent : 4T
*/
// ====================================================================== PCH
// ====================================================================== INCLUDES
// ====================================================================== SYNOPSIS
#include "rdo_lib/rdo_simulator/ProcGUI.h"
#include "rdo_lib/rdo_mbuilder/rdo_resources.h"
// ===============================================================================
// --------------------------------------------------------------------
// ---------- ProcGUIBlock
// --------------------------------------------------------------------
ProcGUIBlock::ProcGUIBlock(PTR(rdoParse::RDOParser) pParser, PTR(rdoRuntime::RDORuntime) pRuntime)
: m_pParser (pParser )
, m_pRuntime(pRuntime)
{
ASSERT(m_pParser );
ASSERT(m_pRuntime);
//!
m_pProcess = F(rdoRuntime::RDOPROCProcess)::create(_T("GuiProcess"), m_pRuntime);
ASSERT(m_pProcess);
m_pProcess.query_cast<ILogic>()->init(m_pRuntime);
}
ProcGUIBlock::~ProcGUIBlock()
{}
void ProcGUIBlock::Create()
{
tstring rtp_name = _T("");
tstring rtp_param_name = _T("_");
//!
rdoMBuilder::RDOResTypeList rtpList(m_pParser);
//! , ,
if (!rtpList[rtp_name].exist())
{
//!
rdoMBuilder::RDOResType rtp(rtp_name);
//! _
rtp.m_params.append(rdoMBuilder::RDOResType::Param(rtp_param_name, rdo::Factory<rdoParse::RDOType__real>::create()));
//!
rdoRuntime::RDOPROCTransact::typeID = rtp.id();
}
else
{
CREF(rdoMBuilder::RDOResType) rtp = rtpList[rtp_name];
rdoRuntime::RDOPROCTransact::typeID = rtp.id();
}
//! GENERATE
rdoRuntime::LPRDOCalcConst pCalc = rdo::Factory<rdoRuntime::RDOCalcConst>::create(4);
LPIPROCBlock pBlock = F(rdoRuntime::RDOPROCGenerate)::create(m_pProcess, pCalc);
ASSERT(pBlock);
//! TERMINATE
pBlock = F(rdoRuntime::RDOPROCTerminate)::create(m_pProcess, 1);
ASSERT(pBlock);
}
<|endoftext|> |
<commit_before>/* vim: set sw=4 sts=4 et foldmethod=syntax : */
#include <max_clique/mpicco_max_clique.hh>
#include <max_clique/cco_base.hh>
#include <graph/template_voodoo.hh>
#include <boost/mpi.hpp>
#include <algorithm>
#include <thread>
#include <mutex>
using namespace parasols;
namespace mpi = boost::mpi;
namespace
{
template <CCOPermutations perm_, CCOInference inference_, unsigned size_, typename VertexType_>
struct MPICCO : CCOBase<perm_, inference_, size_, VertexType_, MPICCO<perm_, inference_, size_, VertexType_> >
{
using MyCCOBase = CCOBase<perm_, inference_, size_, VertexType_, MPICCO<perm_, inference_, size_, VertexType_> >;
using MyCCOBase::graph;
using MyCCOBase::params;
using MyCCOBase::expand;
using MyCCOBase::order;
using MyCCOBase::colour_class_order;
mpi::environment & env;
mpi::communicator & world;
MaxCliqueResult result;
MPICCO(const Graph & g, const MaxCliqueParams & p, mpi::environment & e, mpi::communicator & w) :
MyCCOBase(g, p),
env(e),
world(w)
{
}
auto run() -> MaxCliqueResult
{
result.size = params.initial_bound;
if (0 == world.rank())
return run_master();
else
return run_slave();
}
auto run_slave() -> MaxCliqueResult
{
while (true)
{
/* ask for something to do */
int message = 0;
world.send(0, 1000, message);
/* get a subproblem */
std::vector<int> subproblem;
world.recv(0, 1001, subproblem);
if (subproblem.empty())
break;
std::vector<unsigned> c;
c.reserve(graph.size());
FixedBitSet<size_> p; // potential additions
p.resize(graph.size());
p.set_all();
std::vector<int> positions;
positions.reserve(graph.size());
positions.push_back(0);
// initial colouring
std::array<VertexType_, size_ * bits_per_word> initial_p_order;
std::array<VertexType_, size_ * bits_per_word> initial_colours;
colour_class_order(SelectColourClassOrderOverload<perm_>(), p, initial_p_order, initial_colours);
// go!
expand(c, p, initial_p_order, initial_colours, positions, subproblem);
}
/* send result */
world.send(0, 1002, result.size);
std::vector<int> result_members{ result.members.begin(), result.members.end() };
world.send(0, 1003, result_members);
world.send(0, 1004, result.nodes);
return result;
}
auto run_master() -> MaxCliqueResult
{
int s1 = 0, s2 = 0, n_finishes_sent = 0;
while (n_finishes_sent < world.size() - 1) {
/* request from anyone */
int message;
auto status = world.recv(mpi::any_source, 1000, message);
if (s1 < graph.size()) {
/* send subproblem */
std::cerr << "sending subproblem " << s1 << " " << s2 << " to " << status.source() << std::endl;
std::vector<int> subproblem_vector = { s1, s2 };
world.send(status.source(), 1001, subproblem_vector);
if (++s2 == graph.size()) {
s2 = 0;
++s1;
}
}
else {
/* send finish */
std::cerr << "sending finish to " << status.source() << std::endl;
std::vector<int> subproblem_vector;
world.send(status.source(), 1001, subproblem_vector);
++n_finishes_sent;
/* read result */
MaxCliqueResult sub_result;
std::vector<int> sub_result_members;
world.recv(status.source(), 1002, sub_result.size);
world.recv(status.source(), 1003, sub_result_members);
sub_result.members = std::set<int>{ sub_result_members.begin(), sub_result_members.end() };
world.recv(status.source(), 1004, sub_result.nodes);
result.merge(sub_result);
}
}
std::cerr << "all finishes sent" << std::endl;
return result;
}
auto increment_nodes(std::vector<int> &) -> void
{
++result.nodes;
}
auto recurse(
std::vector<unsigned> & c, // current candidate clique
FixedBitSet<size_> & p,
const std::array<VertexType_, size_ * bits_per_word> & p_order,
const std::array<VertexType_, size_ * bits_per_word> & colours,
std::vector<int> & position,
std::vector<int> & subproblem
) -> bool
{
expand(c, p, p_order, colours, position, subproblem);
return true;
}
auto potential_new_best(
const std::vector<unsigned> & c,
const std::vector<int> &,
std::vector<int> &) -> void
{
// potential new best
if (c.size() > result.size) {
result.size = c.size();
result.members.clear();
for (auto & v : c)
result.members.insert(order[v]);
}
}
auto get_best_anywhere_value() -> unsigned
{
return result.size;
}
auto get_skip(unsigned c_popcount, std::vector<int> & subproblem, int & skip, bool & keep_going) -> void
{
if (c_popcount < subproblem.size()) {
skip = subproblem.at(c_popcount);
keep_going = false;
}
}
};
}
template <CCOPermutations perm_, CCOInference inference_>
auto parasols::detail::mpicco_max_clique(
mpi::environment & env,
mpi::communicator & world,
const Graph & graph,
const MaxCliqueParams & params) -> MaxCliqueResult
{
return select_graph_size<ApplyPermInference<MPICCO, perm_, inference_>::template Type, MaxCliqueResult>(
AllGraphSizes(), graph, params, env, world);
}
template auto parasols::detail::mpicco_max_clique<CCOPermutations::None, CCOInference::None>(
mpi::environment &, mpi::communicator &, const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
<commit_msg>Record worker runtimes<commit_after>/* vim: set sw=4 sts=4 et foldmethod=syntax : */
#include <max_clique/mpicco_max_clique.hh>
#include <max_clique/cco_base.hh>
#include <graph/template_voodoo.hh>
#include <boost/mpi.hpp>
#include <algorithm>
#include <thread>
#include <mutex>
using namespace parasols;
namespace mpi = boost::mpi;
using std::chrono::steady_clock;
using std::chrono::duration_cast;
using std::chrono::milliseconds;
namespace
{
template <CCOPermutations perm_, CCOInference inference_, unsigned size_, typename VertexType_>
struct MPICCO : CCOBase<perm_, inference_, size_, VertexType_, MPICCO<perm_, inference_, size_, VertexType_> >
{
using MyCCOBase = CCOBase<perm_, inference_, size_, VertexType_, MPICCO<perm_, inference_, size_, VertexType_> >;
using MyCCOBase::graph;
using MyCCOBase::params;
using MyCCOBase::expand;
using MyCCOBase::order;
using MyCCOBase::colour_class_order;
mpi::environment & env;
mpi::communicator & world;
MaxCliqueResult result;
MPICCO(const Graph & g, const MaxCliqueParams & p, mpi::environment & e, mpi::communicator & w) :
MyCCOBase(g, p),
env(e),
world(w)
{
}
auto run() -> MaxCliqueResult
{
result.size = params.initial_bound;
if (0 == world.rank())
return run_master();
else
return run_slave();
}
auto run_slave() -> MaxCliqueResult
{
while (true)
{
/* ask for something to do */
int message = 0;
world.send(0, 1000, message);
/* get a subproblem */
std::vector<int> subproblem;
world.recv(0, 1001, subproblem);
if (subproblem.empty())
break;
std::vector<unsigned> c;
c.reserve(graph.size());
FixedBitSet<size_> p; // potential additions
p.resize(graph.size());
p.set_all();
std::vector<int> positions;
positions.reserve(graph.size());
positions.push_back(0);
// initial colouring
std::array<VertexType_, size_ * bits_per_word> initial_p_order;
std::array<VertexType_, size_ * bits_per_word> initial_colours;
colour_class_order(SelectColourClassOrderOverload<perm_>(), p, initial_p_order, initial_colours);
// go!
expand(c, p, initial_p_order, initial_colours, positions, subproblem);
}
/* send result */
world.send(0, 1002, result.size);
std::vector<int> result_members{ result.members.begin(), result.members.end() };
world.send(0, 1003, result_members);
world.send(0, 1004, result.nodes);
return result;
}
auto run_master() -> MaxCliqueResult
{
auto start_time = steady_clock::now(); // local start time
int s1 = 0, s2 = 0, n_finishes_sent = 0;
while (n_finishes_sent < world.size() - 1) {
/* request from anyone */
int message;
auto status = world.recv(mpi::any_source, 1000, message);
if (s1 < graph.size()) {
/* send subproblem */
std::cerr << "sending subproblem " << s1 << " " << s2 << " to " << status.source() << std::endl;
std::vector<int> subproblem_vector = { s1, s2 };
world.send(status.source(), 1001, subproblem_vector);
if (++s2 == graph.size()) {
s2 = 0;
++s1;
}
}
else {
/* send finish */
std::cerr << "sending finish to " << status.source() << std::endl;
std::vector<int> subproblem_vector;
world.send(status.source(), 1001, subproblem_vector);
++n_finishes_sent;
auto overall_time = duration_cast<milliseconds>(steady_clock::now() - start_time);
result.times.push_back(overall_time);
/* read result */
MaxCliqueResult sub_result;
std::vector<int> sub_result_members;
world.recv(status.source(), 1002, sub_result.size);
world.recv(status.source(), 1003, sub_result_members);
sub_result.members = std::set<int>{ sub_result_members.begin(), sub_result_members.end() };
world.recv(status.source(), 1004, sub_result.nodes);
result.merge(sub_result);
}
}
std::cerr << "all finishes sent" << std::endl;
return result;
}
auto increment_nodes(std::vector<int> &) -> void
{
++result.nodes;
}
auto recurse(
std::vector<unsigned> & c, // current candidate clique
FixedBitSet<size_> & p,
const std::array<VertexType_, size_ * bits_per_word> & p_order,
const std::array<VertexType_, size_ * bits_per_word> & colours,
std::vector<int> & position,
std::vector<int> & subproblem
) -> bool
{
expand(c, p, p_order, colours, position, subproblem);
return true;
}
auto potential_new_best(
const std::vector<unsigned> & c,
const std::vector<int> &,
std::vector<int> &) -> void
{
// potential new best
if (c.size() > result.size) {
result.size = c.size();
result.members.clear();
for (auto & v : c)
result.members.insert(order[v]);
}
}
auto get_best_anywhere_value() -> unsigned
{
return result.size;
}
auto get_skip(unsigned c_popcount, std::vector<int> & subproblem, int & skip, bool & keep_going) -> void
{
if (c_popcount < subproblem.size()) {
skip = subproblem.at(c_popcount);
keep_going = false;
}
}
};
}
template <CCOPermutations perm_, CCOInference inference_>
auto parasols::detail::mpicco_max_clique(
mpi::environment & env,
mpi::communicator & world,
const Graph & graph,
const MaxCliqueParams & params) -> MaxCliqueResult
{
return select_graph_size<ApplyPermInference<MPICCO, perm_, inference_>::template Type, MaxCliqueResult>(
AllGraphSizes(), graph, params, env, world);
}
template auto parasols::detail::mpicco_max_clique<CCOPermutations::None, CCOInference::None>(
mpi::environment &, mpi::communicator &, const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
<|endoftext|> |
<commit_before>#include <deque>
using namespace std;
#include <gtest/gtest.h>
#include "../src/pulseTrain.hpp"
class defaultPulseTrain : public ::testing::Test {
protected:
pulseTrain myTrain;
};
class filledPulseTrain : public ::testing::Test {
protected:
virtual void SetUp() {
firstPulse = freqPulse(10, 20, 30, true, true);
secondPulse = freqPulse(1, 2, 3, false, true);
initialQueue.push_back(firstPulse);
initialQueue.push_back(secondPulse);
initialShift = 3.14;
testTrain = pulseTrain(initialShift, initialQueue);
}
double initialShift;
pulseTrain testTrain;
freqPulse firstPulse, secondPulse;
std::deque<freqPulse> initialQueue;
};
class pulseTrainOutputs : public ::testing::Test {
protected:
pulseTrainOutputs() :
firstPulse(freqPulse(100, 1.0, 10, true, false)),
secondPulse(freqPulse(130, 1.0, 10, 1.57079632679, false, true)),
samplePeriodGHz(1.0),
samplePeriodFull(1.0/1.024),
expectPtsGHz(21),
expectPtsFull(21),
expectPtsExact(20),
expectShiftGHz(3),
expectShiftFull(4),
shiftSize(3.45) {
testTrain.pushPulse(firstPulse);
testTrain.pushPulse(secondPulse);
};
pulseTrain testTrain;
freqPulse firstPulse, secondPulse;
const double samplePeriodGHz;
const double samplePeriodFull;
const unsigned int expectPtsGHz;
const unsigned int expectPtsFull;
const unsigned int expectPtsExact;
const unsigned int expectShiftGHz;
const unsigned int expectShiftFull;
const double shiftSize;
};
TEST_F(defaultPulseTrain, CorrectContents) {
deque<freqPulse> emptyPulseQueue;
EXPECT_EQ(0, myTrain.getShift());
EXPECT_EQ(emptyPulseQueue, myTrain.getPulses());
}
TEST_F(filledPulseTrain, size) {
EXPECT_EQ(initialQueue.size(), testTrain.size());
}
TEST_F(filledPulseTrain, front) {
EXPECT_EQ(initialQueue.front(), testTrain.front());
}
TEST_F(filledPulseTrain, pop) {
initialQueue.pop_front();
testTrain.pop();
EXPECT_EQ(initialQueue, testTrain.getPulses());
}
TEST_F(filledPulseTrain, push) {
freqPulse toPush(3.1,4,5,false,true);
initialQueue.push_back(toPush);
testTrain.pushPulse(toPush);;
EXPECT_EQ(initialQueue, testTrain.getPulses());
}
TEST_F(filledPulseTrain, empty) {
EXPECT_FALSE(testTrain.empty());
EXPECT_EQ(initialQueue.empty(), testTrain.empty());
initialQueue.pop_front();
testTrain.pop();
initialQueue.pop_front();
testTrain.pop();
EXPECT_TRUE(testTrain.empty());
EXPECT_EQ(initialQueue.empty(), testTrain.empty());
}
TEST(pulseTrainExplicitConstructor, JustDelay) {
pulseTrain testTrain(1.0);
deque<freqPulse> emptyPulseQueue;
EXPECT_EQ(1.0, testTrain.getShift());
EXPECT_EQ(emptyPulseQueue, testTrain.getPulses());
}
TEST(pulseTrainExplicitConstructor, FullConstructor) {
deque<freqPulse> pulseQueue;
pulseQueue.push_back(freqPulse());
pulseTrain testTrain(1.0, pulseQueue);
EXPECT_EQ(1.0, testTrain.getShift());
EXPECT_EQ(pulseQueue, testTrain.getPulses());
}
TEST(pulseTrainShift, SetShift) {
pulseTrain testTrain;
double testShift = 3.14;
testTrain.setShift(testShift);
EXPECT_EQ(testShift, testTrain.getShift());
}
TEST_F(pulseTrainOutputs, getNumPoints) {
EXPECT_EQ(expectPtsExact, testTrain.getNumPoints(samplePeriodGHz, false));
EXPECT_EQ(expectPtsExact, testTrain.getNumPoints(samplePeriodFull, false));
EXPECT_EQ(expectPtsGHz, testTrain.getNumPoints(samplePeriodGHz));
EXPECT_EQ(expectPtsFull, testTrain.getNumPoints(samplePeriodFull));
}
TEST_F(pulseTrainOutputs, getMarkerChars) {
unsigned int startLength = 5;
string expectedMarker = string(startLength, (char) 0x02) + string(10 - startLength, (char) 0x00) + string(11, (char) 0x01);
unsigned int testLen = expectedMarker.length();
string shiftMarkerGHz = expectedMarker.substr(testLen-expectShiftGHz) + expectedMarker.substr(0, testLen-expectShiftGHz);
string shiftMarkerFull = expectedMarker.substr(testLen-expectShiftFull) + expectedMarker.substr(0, testLen-expectShiftFull);
string negMarkerGHz = expectedMarker.substr(expectShiftGHz ) + expectedMarker.substr(0, expectShiftGHz);
string negMarkerFull= expectedMarker.substr(expectShiftFull) + expectedMarker.substr(0, expectShiftFull);
EXPECT_EQ(expectedMarker, testTrain.getMarkerChars(samplePeriodGHz, expectPtsGHz, true, startLength));
EXPECT_EQ(expectedMarker, testTrain.getMarkerChars(samplePeriodFull, expectPtsFull, true, startLength));
EXPECT_EQ(expectedMarker.substr(0, expectPtsExact), testTrain.getMarkerChars(samplePeriodGHz, expectPtsExact, false, startLength));
EXPECT_EQ(expectedMarker.substr(0, expectPtsExact), testTrain.getMarkerChars(samplePeriodFull, expectPtsExact, false, startLength));
testTrain.setShift(shiftSize);
EXPECT_EQ(shiftMarkerGHz, testTrain.getMarkerChars(samplePeriodGHz, expectPtsGHz, true, startLength));
EXPECT_EQ(shiftMarkerFull, testTrain.getMarkerChars(samplePeriodFull, expectPtsFull, true, startLength));
testTrain.setShift(-shiftSize);
EXPECT_EQ(negMarkerGHz, testTrain.getMarkerChars(samplePeriodGHz, expectPtsGHz, true, startLength));
EXPECT_EQ(negMarkerFull, testTrain.getMarkerChars(samplePeriodFull, expectPtsFull, true, startLength));
}
TEST_F(pulseTrainOutputs, getWaveChars) {
string expectExactGHz = "\x7F\xCA\xF8\xF8\xCA\x7F\x34\x06\x06\x34\xD9\xFE\xD3\x73\x1B\x02\x38\x9B\xEC\xF9";
string expectExactFull = "\x7F\xC8\xF7\xF9\xD0\x88\x3E\x0B\x02\x27\xD9\xFE\xD7\x7A\x21\x00\x2C\x8A\xE1\xFD";
string expectGHz = "\x7F\xCA\xF8\xF8\xCA\x7F\x34\x06\x06\x34\xD9\xFE\xD3\x73\x1B\x02\x38\x9B\xEC\xF9\xB9";
string expectFull = "\x7F\xC8\xF7\xF9\xD0\x88\x3E\x0B\x02\x27\xD9\xFE\xD7\x7A\x21\x00\x2C\x8A\xE1\xFD\xCD";
string expectShiftGHz = "\xEC\xF9\xB9\x7F\xCA\xF8\xF8\xCA\x7F\x34\x06\x06\x34\xD9\xFE\xD3\x73\x1B\x02\x38\x9B";
string expectShiftFull = "\x8A\xE1\xFD\xCD\x7F\xC8\xF7\xF9\xD0\x88\x3E\x0B\x02\x27\xD9\xFE\xD7\x7A\x21\x00\x2C";
string expectNegGHz = "\xF8\xCA\x7F\x34\x06\x06\x34\xD9\xFE\xD3\x73\x1B\x02\x38\x9B\xEC\xF9\xB9\x7F\xCA\xF8";
string expectNegFull = "\xD0\x88\x3E\x0B\x02\x27\xD9\xFE\xD7\x7A\x21\x00\x2C\x8A\xE1\xFD\xCD\x7F\xC8\xF7\xF9";
EXPECT_EQ(expectExactGHz, testTrain.getWaveChars(samplePeriodGHz, expectPtsExact, false));
EXPECT_EQ(expectExactFull, testTrain.getWaveChars(samplePeriodFull, expectPtsExact, false));
EXPECT_EQ(expectGHz, testTrain.getWaveChars(samplePeriodGHz, expectPtsGHz, true));
EXPECT_EQ(expectFull, testTrain.getWaveChars(samplePeriodFull, expectPtsFull, true));
testTrain.setShift(shiftSize);
EXPECT_EQ(expectShiftGHz, testTrain.getWaveChars(samplePeriodGHz, expectPtsGHz, true));
EXPECT_EQ(expectShiftFull, testTrain.getWaveChars(samplePeriodFull, expectPtsFull, true));
testTrain.setShift(-shiftSize);
EXPECT_EQ(expectNegGHz, testTrain.getWaveChars(samplePeriodGHz, expectPtsGHz, true));
EXPECT_EQ(expectNegFull, testTrain.getWaveChars(samplePeriodFull, expectPtsFull, true));
}
int main(int argc, char * argv[] ) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Add missing phase of 0 to freqPulse constructors.<commit_after>#include <deque>
using namespace std;
#include <gtest/gtest.h>
#include "../src/pulseTrain.hpp"
class defaultPulseTrain : public ::testing::Test {
protected:
pulseTrain myTrain;
};
class filledPulseTrain : public ::testing::Test {
protected:
virtual void SetUp() {
firstPulse = freqPulse(10, 20, 30, 0.0, true, true);
secondPulse = freqPulse(1, 2, 3, 0.0, false, true);
initialQueue.push_back(firstPulse);
initialQueue.push_back(secondPulse);
initialShift = 3.14;
testTrain = pulseTrain(initialShift, initialQueue);
}
double initialShift;
pulseTrain testTrain;
freqPulse firstPulse, secondPulse;
std::deque<freqPulse> initialQueue;
};
class pulseTrainOutputs : public ::testing::Test {
protected:
pulseTrainOutputs() :
firstPulse(freqPulse(100, 1.0, 10, 0.0, true, false)),
secondPulse(freqPulse(130, 1.0, 10, 1.57079632679, false, true)),
samplePeriodGHz(1.0),
samplePeriodFull(1.0/1.024),
expectPtsGHz(21),
expectPtsFull(21),
expectPtsExact(20),
expectShiftGHz(3),
expectShiftFull(4),
shiftSize(3.45) {
testTrain.pushPulse(firstPulse);
testTrain.pushPulse(secondPulse);
};
pulseTrain testTrain;
freqPulse firstPulse, secondPulse;
const double samplePeriodGHz;
const double samplePeriodFull;
const unsigned int expectPtsGHz;
const unsigned int expectPtsFull;
const unsigned int expectPtsExact;
const unsigned int expectShiftGHz;
const unsigned int expectShiftFull;
const double shiftSize;
};
TEST_F(defaultPulseTrain, CorrectContents) {
deque<freqPulse> emptyPulseQueue;
EXPECT_EQ(0, myTrain.getShift());
EXPECT_EQ(emptyPulseQueue, myTrain.getPulses());
}
TEST_F(filledPulseTrain, size) {
EXPECT_EQ(initialQueue.size(), testTrain.size());
}
TEST_F(filledPulseTrain, front) {
EXPECT_EQ(initialQueue.front(), testTrain.front());
}
TEST_F(filledPulseTrain, pop) {
initialQueue.pop_front();
testTrain.pop();
EXPECT_EQ(initialQueue, testTrain.getPulses());
}
TEST_F(filledPulseTrain, push) {
freqPulse toPush(3.1,4,5,false,true);
initialQueue.push_back(toPush);
testTrain.pushPulse(toPush);;
EXPECT_EQ(initialQueue, testTrain.getPulses());
}
TEST_F(filledPulseTrain, empty) {
EXPECT_FALSE(testTrain.empty());
EXPECT_EQ(initialQueue.empty(), testTrain.empty());
initialQueue.pop_front();
testTrain.pop();
initialQueue.pop_front();
testTrain.pop();
EXPECT_TRUE(testTrain.empty());
EXPECT_EQ(initialQueue.empty(), testTrain.empty());
}
TEST(pulseTrainExplicitConstructor, JustDelay) {
pulseTrain testTrain(1.0);
deque<freqPulse> emptyPulseQueue;
EXPECT_EQ(1.0, testTrain.getShift());
EXPECT_EQ(emptyPulseQueue, testTrain.getPulses());
}
TEST(pulseTrainExplicitConstructor, FullConstructor) {
deque<freqPulse> pulseQueue;
pulseQueue.push_back(freqPulse());
pulseTrain testTrain(1.0, pulseQueue);
EXPECT_EQ(1.0, testTrain.getShift());
EXPECT_EQ(pulseQueue, testTrain.getPulses());
}
TEST(pulseTrainShift, SetShift) {
pulseTrain testTrain;
double testShift = 3.14;
testTrain.setShift(testShift);
EXPECT_EQ(testShift, testTrain.getShift());
}
TEST_F(pulseTrainOutputs, getNumPoints) {
EXPECT_EQ(expectPtsExact, testTrain.getNumPoints(samplePeriodGHz, false));
EXPECT_EQ(expectPtsExact, testTrain.getNumPoints(samplePeriodFull, false));
EXPECT_EQ(expectPtsGHz, testTrain.getNumPoints(samplePeriodGHz));
EXPECT_EQ(expectPtsFull, testTrain.getNumPoints(samplePeriodFull));
}
TEST_F(pulseTrainOutputs, getMarkerChars) {
unsigned int startLength = 5;
string expectedMarker = string(startLength, (char) 0x02) + string(10 - startLength, (char) 0x00) + string(11, (char) 0x01);
unsigned int testLen = expectedMarker.length();
string shiftMarkerGHz = expectedMarker.substr(testLen-expectShiftGHz) + expectedMarker.substr(0, testLen-expectShiftGHz);
string shiftMarkerFull = expectedMarker.substr(testLen-expectShiftFull) + expectedMarker.substr(0, testLen-expectShiftFull);
string negMarkerGHz = expectedMarker.substr(expectShiftGHz ) + expectedMarker.substr(0, expectShiftGHz);
string negMarkerFull= expectedMarker.substr(expectShiftFull) + expectedMarker.substr(0, expectShiftFull);
EXPECT_EQ(expectedMarker, testTrain.getMarkerChars(samplePeriodGHz, expectPtsGHz, true, startLength));
EXPECT_EQ(expectedMarker, testTrain.getMarkerChars(samplePeriodFull, expectPtsFull, true, startLength));
EXPECT_EQ(expectedMarker.substr(0, expectPtsExact), testTrain.getMarkerChars(samplePeriodGHz, expectPtsExact, false, startLength));
EXPECT_EQ(expectedMarker.substr(0, expectPtsExact), testTrain.getMarkerChars(samplePeriodFull, expectPtsExact, false, startLength));
testTrain.setShift(shiftSize);
EXPECT_EQ(shiftMarkerGHz, testTrain.getMarkerChars(samplePeriodGHz, expectPtsGHz, true, startLength));
EXPECT_EQ(shiftMarkerFull, testTrain.getMarkerChars(samplePeriodFull, expectPtsFull, true, startLength));
testTrain.setShift(-shiftSize);
EXPECT_EQ(negMarkerGHz, testTrain.getMarkerChars(samplePeriodGHz, expectPtsGHz, true, startLength));
EXPECT_EQ(negMarkerFull, testTrain.getMarkerChars(samplePeriodFull, expectPtsFull, true, startLength));
}
TEST_F(pulseTrainOutputs, getWaveChars) {
string expectExactGHz = "\x7F\xCA\xF8\xF8\xCA\x7F\x34\x06\x06\x34\xD9\xFE\xD3\x73\x1B\x02\x38\x9B\xEC\xF9";
string expectExactFull = "\x7F\xC8\xF7\xF9\xD0\x88\x3E\x0B\x02\x27\xD9\xFE\xD7\x7A\x21\x00\x2C\x8A\xE1\xFD";
string expectGHz = "\x7F\xCA\xF8\xF8\xCA\x7F\x34\x06\x06\x34\xD9\xFE\xD3\x73\x1B\x02\x38\x9B\xEC\xF9\xB9";
string expectFull = "\x7F\xC8\xF7\xF9\xD0\x88\x3E\x0B\x02\x27\xD9\xFE\xD7\x7A\x21\x00\x2C\x8A\xE1\xFD\xCD";
string expectShiftGHz = "\xEC\xF9\xB9\x7F\xCA\xF8\xF8\xCA\x7F\x34\x06\x06\x34\xD9\xFE\xD3\x73\x1B\x02\x38\x9B";
string expectShiftFull = "\x8A\xE1\xFD\xCD\x7F\xC8\xF7\xF9\xD0\x88\x3E\x0B\x02\x27\xD9\xFE\xD7\x7A\x21\x00\x2C";
string expectNegGHz = "\xF8\xCA\x7F\x34\x06\x06\x34\xD9\xFE\xD3\x73\x1B\x02\x38\x9B\xEC\xF9\xB9\x7F\xCA\xF8";
string expectNegFull = "\xD0\x88\x3E\x0B\x02\x27\xD9\xFE\xD7\x7A\x21\x00\x2C\x8A\xE1\xFD\xCD\x7F\xC8\xF7\xF9";
EXPECT_EQ(expectExactGHz, testTrain.getWaveChars(samplePeriodGHz, expectPtsExact, false));
EXPECT_EQ(expectExactFull, testTrain.getWaveChars(samplePeriodFull, expectPtsExact, false));
EXPECT_EQ(expectGHz, testTrain.getWaveChars(samplePeriodGHz, expectPtsGHz, true));
EXPECT_EQ(expectFull, testTrain.getWaveChars(samplePeriodFull, expectPtsFull, true));
testTrain.setShift(shiftSize);
EXPECT_EQ(expectShiftGHz, testTrain.getWaveChars(samplePeriodGHz, expectPtsGHz, true));
EXPECT_EQ(expectShiftFull, testTrain.getWaveChars(samplePeriodFull, expectPtsFull, true));
testTrain.setShift(-shiftSize);
EXPECT_EQ(expectNegGHz, testTrain.getWaveChars(samplePeriodGHz, expectPtsGHz, true));
EXPECT_EQ(expectNegFull, testTrain.getWaveChars(samplePeriodFull, expectPtsFull, true));
}
int main(int argc, char * argv[] ) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>// Scintilla source code edit control
/** @file LexerModule.cxx
** Colourise for particular languages.
**/
// Copyright 1998-2010 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>
#include <string>
#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "PropSetSimple.h"
#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "LexerModule.h"
#include "LexerBase.h"
#include "LexerSimple.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
LexerModule::LexerModule(int language_,
LexerFunction fnLexer_,
const char *languageName_,
LexerFunction fnFolder_,
const char *const wordListDescriptions_[],
int styleBits_) :
language(language_),
fnLexer(fnLexer_),
fnFolder(fnFolder_),
fnFactory(0),
wordListDescriptions(wordListDescriptions_),
styleBits(styleBits_),
languageName(languageName_) {
}
LexerModule::LexerModule(int language_,
LexerFactoryFunction fnFactory_,
const char *languageName_,
const char * const wordListDescriptions_[],
int styleBits_) :
language(language_),
fnLexer(0),
fnFolder(0),
fnFactory(fnFactory_),
wordListDescriptions(wordListDescriptions_),
styleBits(styleBits_),
languageName(languageName_) {
}
int LexerModule::GetNumWordLists() const {
if (wordListDescriptions == NULL) {
return -1;
} else {
int numWordLists = 0;
while (wordListDescriptions[numWordLists]) {
++numWordLists;
}
return numWordLists;
}
}
const char *LexerModule::GetWordListDescription(int index) const {
static const char *emptyStr = "";
assert(index < GetNumWordLists());
if (index >= GetNumWordLists()) {
return emptyStr;
} else {
return wordListDescriptions[index];
}
}
int LexerModule::GetStyleBitsNeeded() const {
return styleBits;
}
ILexer *LexerModule::Create() const {
if (fnFactory)
return fnFactory();
else
return new LexerSimple(this);
}
void LexerModule::Lex(unsigned int startPos, int lengthDoc, int initStyle,
WordList *keywordlists[], Accessor &styler) const {
if (fnLexer)
fnLexer(startPos, lengthDoc, initStyle, keywordlists, styler);
}
void LexerModule::Fold(unsigned int startPos, int lengthDoc, int initStyle,
WordList *keywordlists[], Accessor &styler) const {
if (fnFolder) {
int lineCurrent = styler.GetLine(startPos);
// Move back one line in case deletion wrecked current line fold state
if (lineCurrent > 0) {
lineCurrent--;
int newStartPos = styler.LineStart(lineCurrent);
lengthDoc += startPos - newStartPos;
startPos = newStartPos;
initStyle = 0;
if (startPos > 0) {
initStyle = styler.StyleAt(startPos - 1);
}
}
fnFolder(startPos, lengthDoc, initStyle, keywordlists, styler);
}
}
<commit_msg>Variable not needed.<commit_after>// Scintilla source code edit control
/** @file LexerModule.cxx
** Colourise for particular languages.
**/
// Copyright 1998-2010 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>
#include <string>
#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "PropSetSimple.h"
#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "LexerModule.h"
#include "LexerBase.h"
#include "LexerSimple.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
LexerModule::LexerModule(int language_,
LexerFunction fnLexer_,
const char *languageName_,
LexerFunction fnFolder_,
const char *const wordListDescriptions_[],
int styleBits_) :
language(language_),
fnLexer(fnLexer_),
fnFolder(fnFolder_),
fnFactory(0),
wordListDescriptions(wordListDescriptions_),
styleBits(styleBits_),
languageName(languageName_) {
}
LexerModule::LexerModule(int language_,
LexerFactoryFunction fnFactory_,
const char *languageName_,
const char * const wordListDescriptions_[],
int styleBits_) :
language(language_),
fnLexer(0),
fnFolder(0),
fnFactory(fnFactory_),
wordListDescriptions(wordListDescriptions_),
styleBits(styleBits_),
languageName(languageName_) {
}
int LexerModule::GetNumWordLists() const {
if (wordListDescriptions == NULL) {
return -1;
} else {
int numWordLists = 0;
while (wordListDescriptions[numWordLists]) {
++numWordLists;
}
return numWordLists;
}
}
const char *LexerModule::GetWordListDescription(int index) const {
assert(index < GetNumWordLists());
if (index >= GetNumWordLists()) {
return "";
} else {
return wordListDescriptions[index];
}
}
int LexerModule::GetStyleBitsNeeded() const {
return styleBits;
}
ILexer *LexerModule::Create() const {
if (fnFactory)
return fnFactory();
else
return new LexerSimple(this);
}
void LexerModule::Lex(unsigned int startPos, int lengthDoc, int initStyle,
WordList *keywordlists[], Accessor &styler) const {
if (fnLexer)
fnLexer(startPos, lengthDoc, initStyle, keywordlists, styler);
}
void LexerModule::Fold(unsigned int startPos, int lengthDoc, int initStyle,
WordList *keywordlists[], Accessor &styler) const {
if (fnFolder) {
int lineCurrent = styler.GetLine(startPos);
// Move back one line in case deletion wrecked current line fold state
if (lineCurrent > 0) {
lineCurrent--;
int newStartPos = styler.LineStart(lineCurrent);
lengthDoc += startPos - newStartPos;
startPos = newStartPos;
initStyle = 0;
if (startPos > 0) {
initStyle = styler.StyleAt(startPos - 1);
}
}
fnFolder(startPos, lengthDoc, initStyle, keywordlists, styler);
}
}
<|endoftext|> |
<commit_before>// Test under-development. Calls async mem-copy API, experiment with functionality.
#include "hip_runtime.h"
#include "test_common.h"
unsigned p_streams = 2;
void simpleNegTest()
{
printf ("testing: %s\n",__func__);
hipError_t e;
float *A_malloc, *A_pinned, *A_d;
size_t Nbytes = N*sizeof(float);
A_malloc = (float*)malloc(Nbytes);
HIPCHECK(hipMallocHost(&A_pinned, Nbytes));
HIPCHECK(hipMalloc(&A_d, Nbytes));
// Can't use default with async copy
e = hipMemcpyAsync(A_pinned, A_d, Nbytes, hipMemcpyDefault, NULL);
HIPASSERT (e==hipErrorInvalidMemcpyDirection);
// Not sure what happens here, the memory must be pinned.
e = hipMemcpyAsync(A_malloc, A_d, Nbytes, hipMemcpyHostToDevice, NULL);
printf (" async memcpy of A_malloc to A_d. Result=%d\n", e);
//HIPASSERT (e==hipErrorInvalidValue);
}
//---
//Classic example showing how to overlap data transfer with compute.
//We divide the work into "chunks" and create a stream for each chunk.
//Each chunk then runs a H2D copy, followed by kernel execution, followed by D2H copyback.
//Work in separate streams is independent which enables concurrency.
// IN: nStreams : number of streams to use for the test
// IN :useNullStream - use NULL stream. Synchronizes everything.
// IN: useSyncMemcpyH2D - use sync memcpy (no overlap) for H2D
// IN: useSyncMemcpyD2H - use sync memcpy (no overlap) for D2H
void chunkedAsyncExample(int nStreams, bool useNullStream, bool useSyncMemcpyH2D, bool useSyncMemcpyD2H)
{
size_t Nbytes = N*sizeof(int);
printf ("testing: %s(useNullStream=%d, useSyncMemcpyH2D=%d, useSyncMemcpyD2H=%d) ",__func__, useNullStream, useSyncMemcpyH2D, useSyncMemcpyD2H);
printf ("Nbytes=%zu (%6.1f MB)\n", Nbytes, (double)(Nbytes)/1024.0/1024.0);
int *A_d, *B_d, *C_d;
int *A_h, *B_h, *C_h;
HipTest::initArrays (&A_d, &B_d, &C_d, &A_h, &B_h, &C_h, N, true);
unsigned blocks = HipTest::setNumBlocks(blocksPerCU, threadsPerBlock, N);
hipStream_t *stream = (hipStream_t*)malloc(sizeof(hipStream_t) * nStreams);
if (useNullStream) {
nStreams = 1;
stream[0] = NULL;
} else {
for (int i = 0; i < nStreams; ++i) {
HIPCHECK (hipStreamCreate(&stream[i]));
}
}
size_t workLeft = N;
size_t workPerStream = N / nStreams;
for (int i = 0; i < nStreams; ++i) {
size_t work = (workLeft < workPerStream) ? workLeft : workPerStream;
size_t workBytes = work * sizeof(int);
size_t offset = i*workPerStream;
if (useSyncMemcpyH2D) {
HIPCHECK ( hipMemcpy(&A_d[offset], &A_h[offset], workBytes, hipMemcpyHostToDevice));
HIPCHECK ( hipMemcpy(&B_d[offset], &B_h[offset], workBytes, hipMemcpyHostToDevice));
} else {
HIPCHECK ( hipMemcpyAsync(&A_d[offset], &A_h[offset], workBytes, hipMemcpyHostToDevice, stream[i]));
HIPCHECK ( hipMemcpyAsync(&B_d[offset], &B_h[offset], workBytes, hipMemcpyHostToDevice, stream[i]));
};
hipLaunchKernel(HipTest::vectorADD, dim3(blocks), dim3(threadsPerBlock), 0, stream[i], &A_d[offset], &B_d[offset], &C_d[offset], work);
if (useSyncMemcpyD2H) {
HIPCHECK ( hipMemcpy(&C_h[offset], &C_d[offset], workBytes, hipMemcpyDeviceToHost));
} else {
HIPCHECK ( hipMemcpyAsync(&C_h[offset], &C_d[offset], workBytes, hipMemcpyDeviceToHost, stream[i]));
}
}
HIPCHECK (hipDeviceSynchronize());
HipTest::checkVectorADD(A_h, B_h, C_h, N);
HipTest::freeArrays (A_d, B_d, C_d, A_h, B_h, C_h, true);
};
//---
//Parse arguments specific to this test.
void parseMyArguments(int argc, char *argv[])
{
int more_argc = HipTest::parseStandardArguments(argc, argv, false);
// parse args for this test:
for (int i = 1; i < more_argc; i++) {
const char *arg = argv[i];
if (!strcmp(arg, "--streams")) {
if (++i >= argc || !HipTest::parseUInt(argv[i], &p_streams)) {
failed("Bad streams argument");
}
} else {
failed("Bad argument '%s'", arg);
}
};
};
int main(int argc, char *argv[])
{
HipTest::parseStandardArguments(argc, argv, true);
parseMyArguments(argc, argv);
printf ("info: set device to %d\n", p_gpuDevice);
HIPCHECK(hipSetDevice(p_gpuDevice));
simpleNegTest();
chunkedAsyncExample(p_streams, true, true, true); // Easy sync version
chunkedAsyncExample(p_streams, false, true, true); // Easy sync version
chunkedAsyncExample(p_streams, false, false, true); // Some async
chunkedAsyncExample(p_streams, false, false, false); // All async
passed();
}
<commit_msg>Describe how to update HTML docs<commit_after>// Test under-development. Calls async mem-copy API, experiment with functionality.
#include "hip_runtime.h"
#include "test_common.h"
unsigned p_streams = 2;
void simpleNegTest()
{
printf ("testing: %s\n",__func__);
hipError_t e;
float *A_malloc, *A_pinned, *A_d;
size_t Nbytes = N*sizeof(float);
A_malloc = (float*)malloc(Nbytes);
HIPCHECK(hipMallocHost(&A_pinned, Nbytes));
HIPCHECK(hipMalloc(&A_d, Nbytes));
// Can't use default with async copy
e = hipMemcpyAsync(A_pinned, A_d, Nbytes, hipMemcpyDefault, NULL);
HIPASSERT (e==hipErrorInvalidMemcpyDirection); // TODO
HIPASSERT (e!= hipSuccess);
// Not sure what happens here, the memory must be pinned.
e = hipMemcpyAsync(A_malloc, A_d, Nbytes, hipMemcpyHostToDevice, NULL);
printf (" async memcpy of A_malloc to A_d. Result=%d\n", e);
//HIPASSERT (e==hipErrorInvalidValue);
}
//---
//Send many async copies to the same stream.
//This requires runtime to keep track of many outstanding commands, and in the case of HCC requires growing/tracking the signal pool:
template<typename T>
void test_manyCopies(int nElements, size_t numCopies, int nStreams)
{
size_t Nbytes = nElements*sizeof(T);
printf ("Nbytes=%zu (%6.1f MB)\n", Nbytes, (double)(Nbytes)/1024.0/1024.0);
int *A_d, *B_d, *C_d;
int *A_h, *B_h, *C_h;
HipTest::initArrays (&A_d, &B_d, &C_d, &A_h, &B_h, &C_h, N, true);
size_t eachCopyBytes = Nbytes / numCopies;
for (size_t i=0; i<Nbytes; i++)
{
}
HipTest::freeArrays (A_d, B_d, C_d, A_h, B_h, C_h, true);
}
//---
//Classic example showing how to overlap data transfer with compute.
//We divide the work into "chunks" and create a stream for each chunk.
//Each chunk then runs a H2D copy, followed by kernel execution, followed by D2H copyback.
//Work in separate streams is independent which enables concurrency.
// IN: nStreams : number of streams to use for the test
// IN :useNullStream - use NULL stream. Synchronizes everything.
// IN: useSyncMemcpyH2D - use sync memcpy (no overlap) for H2D
// IN: useSyncMemcpyD2H - use sync memcpy (no overlap) for D2H
void test_chunkedAsyncExample(int nStreams, bool useNullStream, bool useSyncMemcpyH2D, bool useSyncMemcpyD2H)
{
size_t Nbytes = N*sizeof(int);
printf ("testing: %s(useNullStream=%d, useSyncMemcpyH2D=%d, useSyncMemcpyD2H=%d) ",__func__, useNullStream, useSyncMemcpyH2D, useSyncMemcpyD2H);
printf ("Nbytes=%zu (%6.1f MB)\n", Nbytes, (double)(Nbytes)/1024.0/1024.0);
int *A_d, *B_d, *C_d;
int *A_h, *B_h, *C_h;
HipTest::initArrays (&A_d, &B_d, &C_d, &A_h, &B_h, &C_h, N, true);
unsigned blocks = HipTest::setNumBlocks(blocksPerCU, threadsPerBlock, N);
hipStream_t *stream = (hipStream_t*)malloc(sizeof(hipStream_t) * nStreams);
if (useNullStream) {
nStreams = 1;
stream[0] = NULL;
} else {
for (int i = 0; i < nStreams; ++i) {
HIPCHECK (hipStreamCreate(&stream[i]));
}
}
size_t workLeft = N;
size_t workPerStream = N / nStreams;
for (int i = 0; i < nStreams; ++i) {
size_t work = (workLeft < workPerStream) ? workLeft : workPerStream;
size_t workBytes = work * sizeof(int);
size_t offset = i*workPerStream;
if (useSyncMemcpyH2D) {
HIPCHECK ( hipMemcpy(&A_d[offset], &A_h[offset], workBytes, hipMemcpyHostToDevice));
HIPCHECK ( hipMemcpy(&B_d[offset], &B_h[offset], workBytes, hipMemcpyHostToDevice));
} else {
HIPCHECK ( hipMemcpyAsync(&A_d[offset], &A_h[offset], workBytes, hipMemcpyHostToDevice, stream[i]));
HIPCHECK ( hipMemcpyAsync(&B_d[offset], &B_h[offset], workBytes, hipMemcpyHostToDevice, stream[i]));
};
hipLaunchKernel(HipTest::vectorADD, dim3(blocks), dim3(threadsPerBlock), 0, stream[i], &A_d[offset], &B_d[offset], &C_d[offset], work);
if (useSyncMemcpyD2H) {
HIPCHECK ( hipMemcpy(&C_h[offset], &C_d[offset], workBytes, hipMemcpyDeviceToHost));
} else {
HIPCHECK ( hipMemcpyAsync(&C_h[offset], &C_d[offset], workBytes, hipMemcpyDeviceToHost, stream[i]));
}
}
HIPCHECK (hipDeviceSynchronize());
HipTest::checkVectorADD(A_h, B_h, C_h, N);
HipTest::freeArrays (A_d, B_d, C_d, A_h, B_h, C_h, true);
};
//---
//Parse arguments specific to this test.
void parseMyArguments(int argc, char *argv[])
{
int more_argc = HipTest::parseStandardArguments(argc, argv, false);
// parse args for this test:
for (int i = 1; i < more_argc; i++) {
const char *arg = argv[i];
if (!strcmp(arg, "--streams")) {
if (++i >= argc || !HipTest::parseUInt(argv[i], &p_streams)) {
failed("Bad streams argument");
}
} else {
failed("Bad argument '%s'", arg);
}
};
};
int main(int argc, char *argv[])
{
HipTest::parseStandardArguments(argc, argv, true);
parseMyArguments(argc, argv);
printf ("info: set device to %d\n", p_gpuDevice);
HIPCHECK(hipSetDevice(p_gpuDevice));
simpleNegTest();
test_chunkedAsyncExample(p_streams, true, true, true); // Easy sync version
test_chunkedAsyncExample(p_streams, false, true, true); // Easy sync version
test_chunkedAsyncExample(p_streams, false, false, true); // Some async
test_chunkedAsyncExample(p_streams, false, false, false); // All async
passed();
}
<|endoftext|> |
<commit_before>#include <geometry/camera.h>
#include <geometry/camera_functions.h>
#include <iostream>
Camera Camera::CreatePerspectiveCamera(double focal, double k1, double k2) {
Camera camera;
camera.type_ = ProjectionType::PERSPECTIVE;
camera.parameters_[Camera::Parameters::Focal] = focal;
camera.parameters_[Camera::Parameters::K1] = k1;
camera.parameters_[Camera::Parameters::K2] = k2;
return camera;
};
Camera Camera::CreateBrownCamera(double focal, double aspect_ratio,
const Vec2d& principal_point,
const VecXd& distortion) {
Camera camera;
if (distortion.size() != 5) {
throw std::runtime_error("Invalid distortion coefficients size");
}
camera.type_ = ProjectionType::BROWN;
camera.parameters_[Camera::Parameters::Focal] = focal;
camera.parameters_[Camera::Parameters::AspectRatio] = aspect_ratio;
camera.parameters_[Camera::Parameters::K1] = distortion(0);
camera.parameters_[Camera::Parameters::K2] = distortion(1);
camera.parameters_[Camera::Parameters::K3] = distortion(2);
camera.parameters_[Camera::Parameters::P1] = distortion(3);
camera.parameters_[Camera::Parameters::P2] = distortion(4);
camera.parameters_[Camera::Parameters::Cx] = principal_point(0);
camera.parameters_[Camera::Parameters::Cy] = principal_point(1);
};
Camera Camera::CreateFisheyeCamera(double focal, double k1, double k2) {
Camera camera;
camera.type_ = ProjectionType::FISHEYE;
camera.parameters_[Camera::Parameters::Focal] = focal;
camera.parameters_[Camera::Parameters::K1] = k1;
camera.parameters_[Camera::Parameters::K2] = k2;
return camera;
};
Camera Camera::CreateDualCamera(double transition, double focal, double k1,
double k2) {
Camera camera;
camera.type_ = ProjectionType::DUAL;
camera.parameters_[Camera::Parameters::Focal] = focal;
camera.parameters_[Camera::Parameters::K1] = k1;
camera.parameters_[Camera::Parameters::K2] = k2;
camera.parameters_[Camera::Parameters::Transition] = transition;
return camera;
};
Camera Camera::CreateSphericalCamera() {
Camera camera;
camera.type_ = ProjectionType::SPHERICAL;
camera.parameters_[Camera::Parameters::None] = 0.;
return camera;
};
std::vector<Camera::Parameters> Camera::GetParametersTypes() const {
std::vector<Camera::Parameters> types;
for (const auto p : parameters_) {
types.push_back(p.first);
}
return types;
}
VecXd Camera::GetParametersValues() const {
VecXd values(parameters_.size());
int count = 0;
for (const auto p : parameters_) {
values[count++] = p.second;
}
return values;
}
bool Camera::SetParameterValue(const Parameters& parameter, double value) {
if (parameters_.find(parameter) == parameters_.end()) {
throw std::runtime_error("Unknown parameter for this camera model");
}
parameters_[parameter] = value;
}
ProjectionType Camera::GetProjectionType() const { return type_; }
std::string Camera::GetProjectionString() const {
switch (type_) {
case ProjectionType::PERSPECTIVE:
return "perspective";
case ProjectionType::BROWN:
return "brown";
case ProjectionType::FISHEYE:
return "fisheye";
case ProjectionType::DUAL:
return "dual";
case ProjectionType::SPHERICAL:
return "spherical";
default:
throw std::runtime_error("Invalid ProjectionType");
}
}
Mat3d Camera::GetProjectionMatrix() const {
Mat3d unnormalized = Mat3d::Zero();
double focal = 1.0;
const auto find_focal = parameters_.find(Camera::Parameters::Focal);
if(find_focal != parameters_.end()){
focal = find_focal->second;
}
double aspect_ratio = 1.0;
const auto find_aspect_ratio = parameters_.find(Camera::Parameters::AspectRatio);
if(find_aspect_ratio != parameters_.end()){
aspect_ratio = find_aspect_ratio->second;
}
Vec2d principal_point = Vec2d::Zero();
const auto find_principal_point_x = parameters_.find(Camera::Parameters::Cx);
if(find_principal_point_x != parameters_.end()){
principal_point(0) = find_principal_point_x->second;
}
const auto find_principal_point_y = parameters_.find(Camera::Parameters::Cy);
if(find_principal_point_y != parameters_.end()){
principal_point(1) = find_principal_point_y->second;
}
unnormalized(0, 0) = focal;
unnormalized(1, 1) = focal*aspect_ratio;
unnormalized.col(2) << principal_point, 1.0;
return unnormalized;
}
Mat3d Camera::GetProjectionMatrixScaled(int width, int height) const {
const auto unnormalizer = std::max(width, height);
Mat3d unnormalized = Mat3d::Zero();
const auto projection_matrix = GetProjectionMatrix();
unnormalized.block<2, 2>(0, 0) << unnormalizer * unnormalized.block<2, 2>(0, 0);
unnormalized.col(2) << projection_matrix(0, 2) * unnormalizer + 0.5 * width,
projection_matrix(1, 2) * unnormalizer + 0.5 * height, 1.0;
return unnormalized;
}
Vec2d Camera::Project(const Vec3d& point) const {
Vec2d projected;
const auto parameters = GetParametersValues();
Dispatch<ProjectFunction>(type_, point.data(), parameters.data(),
projected.data());
return projected;
}
Eigen::MatrixX2d Camera::ProjectMany(const Eigen::MatrixX3d& points) const {
Eigen::MatrixX2d projected(points.rows(), 2);
for (int i = 0; i < points.rows(); ++i) {
projected.row(i) = Project(points.row(i));
}
return projected;
}
Vec3d Camera::Bearing(const Vec2d& point) const {
Vec3d bearing;
const auto parameters = GetParametersValues();
Dispatch<BearingFunction>(type_, point.data(), parameters.data(),
bearing.data());
return bearing;
}
Eigen::MatrixX3d Camera::BearingsMany(const Eigen::MatrixX2d& points) const {
Eigen::MatrixX3d projected(points.rows(), 3);
for (int i = 0; i < points.rows(); ++i) {
projected.row(i) = Bearing(points.row(i));
}
return projected;
}
Camera::Camera() : type_(ProjectionType::PERSPECTIVE) {
}
std::pair<MatXf, MatXf> ComputeCameraMapping(const Camera& from, const Camera& to, int width, int height){
const auto normalizer_factor = std::max(width, height);
const auto inv_normalizer_factor = 1.0/normalizer_factor;
MatXf u_from(height, width);
MatXf v_from(height, width);
const auto half_width = width*0.5;
const auto half_height = height*0.5;
for(int v = 0; v < height; ++v){
for(int u = 0; u < width; ++u){
const auto uv = Vec2d(u-half_width, v-half_height);
const Vec2d point_uv_from = normalizer_factor*from.Project(to.Bearing(inv_normalizer_factor*uv));
u_from(v, u) = point_uv_from(0) + half_width;
v_from(v, u) = point_uv_from(1) + half_height;
}
}
return std::make_pair(u_from, v_from);
}
<commit_msg>refactor: fixed bug and more accessors<commit_after>#include <geometry/camera.h>
#include <geometry/camera_functions.h>
#include <iostream>
Camera Camera::CreatePerspectiveCamera(double focal, double k1, double k2) {
Camera camera;
camera.type_ = ProjectionType::PERSPECTIVE;
camera.parameters_[Camera::Parameters::Focal] = focal;
camera.parameters_[Camera::Parameters::K1] = k1;
camera.parameters_[Camera::Parameters::K2] = k2;
return camera;
};
Camera Camera::CreateBrownCamera(double focal, double aspect_ratio,
const Vec2d& principal_point,
const VecXd& distortion) {
Camera camera;
if (distortion.size() != 5) {
throw std::runtime_error("Invalid distortion coefficients size");
}
camera.type_ = ProjectionType::BROWN;
camera.parameters_[Camera::Parameters::Focal] = focal;
camera.parameters_[Camera::Parameters::AspectRatio] = aspect_ratio;
camera.parameters_[Camera::Parameters::K1] = distortion(0);
camera.parameters_[Camera::Parameters::K2] = distortion(1);
camera.parameters_[Camera::Parameters::K3] = distortion(2);
camera.parameters_[Camera::Parameters::P1] = distortion(3);
camera.parameters_[Camera::Parameters::P2] = distortion(4);
camera.parameters_[Camera::Parameters::Cx] = principal_point(0);
camera.parameters_[Camera::Parameters::Cy] = principal_point(1);
return camera;
};
Camera Camera::CreateFisheyeCamera(double focal, double k1, double k2) {
Camera camera;
camera.type_ = ProjectionType::FISHEYE;
camera.parameters_[Camera::Parameters::Focal] = focal;
camera.parameters_[Camera::Parameters::K1] = k1;
camera.parameters_[Camera::Parameters::K2] = k2;
return camera;
};
Camera Camera::CreateDualCamera(double transition, double focal, double k1,
double k2) {
Camera camera;
camera.type_ = ProjectionType::DUAL;
camera.parameters_[Camera::Parameters::Focal] = focal;
camera.parameters_[Camera::Parameters::K1] = k1;
camera.parameters_[Camera::Parameters::K2] = k2;
camera.parameters_[Camera::Parameters::Transition] = transition;
return camera;
};
Camera Camera::CreateSphericalCamera() {
Camera camera;
camera.type_ = ProjectionType::SPHERICAL;
camera.parameters_[Camera::Parameters::None] = 0.;
return camera;
};
std::vector<Camera::Parameters> Camera::GetParametersTypes() const {
std::vector<Camera::Parameters> types;
for (const auto p : parameters_) {
types.push_back(p.first);
}
return types;
}
VecXd Camera::GetParametersValues() const {
VecXd values(parameters_.size());
int count = 0;
for (const auto p : parameters_) {
values[count++] = p.second;
}
return values;
}
std::map<Camera::Parameters, double, Camera::CompParameters>
Camera::GetParametersMap() const {
return parameters_;
}
void Camera::SetParameterValue(const Parameters& parameter, double value) {
if (parameters_.find(parameter) == parameters_.end()) {
throw std::runtime_error("Unknown parameter for this camera model");
}
parameters_[parameter] = value;
}
double Camera::GetParameterValue(const Parameters& parameter) const {
if (parameters_.find(parameter) == parameters_.end()) {
throw std::runtime_error("Unknown parameter for this camera model");
}
return parameters_.at(parameter);
}
ProjectionType Camera::GetProjectionType() const { return type_; }
std::string Camera::GetProjectionString() const {
switch (type_) {
case ProjectionType::PERSPECTIVE:
return "perspective";
case ProjectionType::BROWN:
return "brown";
case ProjectionType::FISHEYE:
return "fisheye";
case ProjectionType::DUAL:
return "dual";
case ProjectionType::SPHERICAL:
return "spherical";
default:
throw std::runtime_error("Invalid ProjectionType");
}
}
Mat3d Camera::GetProjectionMatrix() const {
Mat3d unnormalized = Mat3d::Zero();
double focal = 1.0;
const auto find_focal = parameters_.find(Camera::Parameters::Focal);
if(find_focal != parameters_.end()){
focal = find_focal->second;
}
double aspect_ratio = 1.0;
const auto find_aspect_ratio = parameters_.find(Camera::Parameters::AspectRatio);
if(find_aspect_ratio != parameters_.end()){
aspect_ratio = find_aspect_ratio->second;
}
Vec2d principal_point = Vec2d::Zero();
const auto find_principal_point_x = parameters_.find(Camera::Parameters::Cx);
if(find_principal_point_x != parameters_.end()){
principal_point(0) = find_principal_point_x->second;
}
const auto find_principal_point_y = parameters_.find(Camera::Parameters::Cy);
if(find_principal_point_y != parameters_.end()){
principal_point(1) = find_principal_point_y->second;
}
unnormalized(0, 0) = focal;
unnormalized(1, 1) = focal*aspect_ratio;
unnormalized.col(2) << principal_point, 1.0;
return unnormalized;
}
Mat3d Camera::GetProjectionMatrixScaled(int width, int height) const {
const auto unnormalizer = std::max(width, height);
Mat3d unnormalized = Mat3d::Zero();
const auto projection_matrix = GetProjectionMatrix();
unnormalized.block<2, 2>(0, 0) << unnormalizer * projection_matrix.block<2, 2>(0, 0);
unnormalized.col(2) << projection_matrix(0, 2) * unnormalizer + 0.5 * width,
projection_matrix(1, 2) * unnormalizer + 0.5 * height, 1.0;
return unnormalized;
}
Vec2d Camera::Project(const Vec3d& point) const {
Vec2d projected;
const auto parameters = GetParametersValues();
Dispatch<ProjectFunction>(type_, point.data(), parameters.data(),
projected.data());
return projected;
}
Eigen::MatrixX2d Camera::ProjectMany(const Eigen::MatrixX3d& points) const {
Eigen::MatrixX2d projected(points.rows(), 2);
for (int i = 0; i < points.rows(); ++i) {
projected.row(i) = Project(points.row(i));
}
return projected;
}
Vec3d Camera::Bearing(const Vec2d& point) const {
Vec3d bearing;
const auto parameters = GetParametersValues();
Dispatch<BearingFunction>(type_, point.data(), parameters.data(),
bearing.data());
return bearing;
}
Eigen::MatrixX3d Camera::BearingsMany(const Eigen::MatrixX2d& points) const {
Eigen::MatrixX3d projected(points.rows(), 3);
for (int i = 0; i < points.rows(); ++i) {
projected.row(i) = Bearing(points.row(i));
}
return projected;
}
Camera::Camera() : type_(ProjectionType::PERSPECTIVE) {
}
std::pair<MatXf, MatXf> ComputeCameraMapping(const Camera& from, const Camera& to, int width, int height){
const auto normalizer_factor = std::max(width, height);
const auto inv_normalizer_factor = 1.0/normalizer_factor;
MatXf u_from(height, width);
MatXf v_from(height, width);
const auto half_width = width*0.5;
const auto half_height = height*0.5;
for(int v = 0; v < height; ++v){
for(int u = 0; u < width; ++u){
const auto uv = Vec2d(u-half_width, v-half_height);
const Vec2d point_uv_from = normalizer_factor*from.Project(to.Bearing(inv_normalizer_factor*uv));
u_from(v, u) = point_uv_from(0) + half_width;
v_from(v, u) = point_uv_from(1) + half_height;
}
}
return std::make_pair(u_from, v_from);
}
<|endoftext|> |
<commit_before>#include "General.h"
#include "require.h"
#include "Options.h"
#include "DataSet.h"
#include "RecursiveNN.h"
#include <cstdlib>
#include <cfloat>
#include <ctime>
#include <map>
#include <vector>
#include <fstream>
#include <sstream>
#include <iostream>
using namespace std;
double adjustLearningRate(double curr_error, bool& restore_weights_flag, double& alpha) {
/*** Vogl adaptive acceleration learning method (additive) ***/
static double prev_eta = atof((Options::instance()->get_parameter("eta")).c_str());
static double prev_error = FLT_MAX;
double alpha_0 = 1e-1;
double phi = 1.05, beta = .5, epsilon = 1e-2;
double phi_additive = prev_eta/100;
double curr_eta;
if(curr_error < prev_error) {
curr_eta = phi_additive + prev_eta;
if(curr_eta > 1)
curr_eta = 1;
alpha = alpha_0;
prev_eta = curr_eta;
prev_error = curr_error;
} else if(curr_error < (1 + epsilon) * prev_error) {
curr_eta = beta * prev_eta;
alpha = 0;
prev_eta = curr_eta;
prev_error = curr_error;
} else {
restore_weights_flag = true;
curr_eta = beta * prev_eta;
alpha = 0;
}
return curr_eta;
}
void computeErrorOnDataset();
void train(const string& netname, DataSet* trainingSet, DataSet* validationSet, ostream& os = cout) {
// Get important training parameters
bool onlinelearning = (atoi((Options::instance()->get_parameter("onlinelearning")).c_str()))?true:false;
bool random_net = (atoi((Options::instance()->get_parameter("random_net")).c_str()))?true:false;
int epochs = atoi((Options::instance()->get_parameter("epochs")).c_str());
int savedelta = atoi((Options::instance()->get_parameter("savedelta")).c_str());
/*
* read network in if it exists, otherwise make one from scratch
*/
RecursiveNN<TanH, Sigmoid, MGradientDescent>* rnn;
if(trainingSet->size()) {
os << "Creating new network...";
rnn = new RecursiveNN<TanH, Sigmoid, MGradientDescent>();
os << " Done." << endl;
} else {
os << "Need some data to train network, please specify value for the --training-set argument\n";
return;
}
os << endl << endl;
bool restore_weights_flag = false;
double curr_eta = atof((Options::instance()->get_parameter("eta")).c_str());
double alpha = .9;
double prev_error = FLT_MAX, min_error = FLT_MAX;
int min_error_epoch = -1;
double threshold_error = atof((Options::instance()->get_parameter("threshold_error")).c_str());
for(int epoch = 1; epoch<=epochs; epoch++) {
double error_training_set = .0, error_validation_set = .0;
os << endl << "Epoch " << epoch << '\t';
for(DataSet::iterator it=trainingSet->begin(); it!=trainingSet->end(); ++it) {
// (*it)->print(os);
rnn->propagateStructuredInput(*it);
rnn->backPropagateError(*it);
/* stochastic (i.e. online) gradient descent */
if(onlinelearning) {
if(restore_weights_flag)
rnn->restorePrevWeights();
rnn->adjustWeights(curr_eta, alpha);
//curr_eta = adjustLearningRate(curr_train_error, restore_weights_flag, alpha);
}
}
/* batch weight update */
if(!onlinelearning) {
if(restore_weights_flag)
rnn->restorePrevWeights();
rnn->adjustWeights(curr_eta, alpha);
//curr_eta = adjustLearningRate(curr_train_error, restore_weights_flag, alpha);
}
double error;
double error_training_set = rnn->computeErrorOnDataset(trainingSet);
os << "E_training = " << error_training_set << '\t';
if(validationSet) {
double error_validation_set = rnn->computeErrorOnDataset(validationSet);
error = error_validation_set;
os << "E_validation = " << error_validation_set;
} else
error = error_training_set;
os << endl;
if(min_error > error) {
min_error = error;
min_error_epoch = epoch;
rnn->saveParameters(netname.c_str());
}
// stopping criterion based on error threshold
if(fabs(prev_error - error) < threshold_error) {
os << endl << << endl << "Network error decay below given threshold. Stopping training..." << endl;
break;
}
prev_error = error;
// save network every 'savedelta' epochs
if(!(epoch % savedelta)) {
ostringstream oss;
oss << netname << '.' << epoch;
rnn->saveParameters((oss.str()).c_str());
}
}
os << endl << flush;
// deallocate Recursive Neural Network instace
delete rnn; rnn = 0;
}
int main(int argc, char* argv[]) {
setenv("RNNOPTIONTYPE", "train", 1);
DataSet *trainingSet = NULL, *testSet = NULL, *validationSet = NULL;
string netname;
try {
Options::instance()->parse_args(argc,argv);
netname = Options::instance()->get_parameter("netname");
if(!netname.length()) {
cerr << "Must specify a network file" << endl << endl;
throw Options::BadOptionSetting(Options::instance()->usage());
}
string training_set_fname = Options::instance()->get_parameter("training_set");
if(training_set_fname.length()) {
cout << "Creating training set. " << flush;
trainingSet = new DataSet(training_set_fname.c_str());
cout << "Done." << flush << endl;
} else
cout << "Training set not specified. Skipping training..." << endl;
string test_set_fname = Options::instance()->get_parameter("test_set");
if(test_set_fname.length()) {
cout << "Creating test set. " << flush;
testSet = new DataSet(test_set_fname.c_str());
cout << "Done." << flush << endl;
} else
cout << "Test set not specified. Skipping testing..." << endl;
string validation_set_fname = Options::instance()->get_parameter("validation_set");
if(validation_set_fname.length()) {
cout << "Creating validation set. " << flush;
validationSet = new DataSet(validation_set_fname.c_str());
cout << "Done." << flush << endl;
}
} catch(Options::BadOptionSetting e) {
cerr << e.what() << endl;
exit(EXIT_FAILURE);
}
/*** Train the network and save results ***/
if(trainingSet) {
cout << "Training set has " << (trainingSet->size()) << " instances." << endl;
if(validationSet) {
cout << "Training network with validation set." << endl;
cout << "Validation set has " << validationSet->size() << " instances." << endl;
}
else
cout << "Training without validation set." << endl;
train(netname, trainingSet, validationSet);
cout << "RNN model saved to file " << netname << endl;
/*
* TODO
* predict(netname, trainingSet, "training.pred");
* predict(netname, validationSet, "validation.pred");
*/
delete trainingSet;
if(validationSet)
delete validationSet;
} else if(validationSet) {
cerr << "Cannot use validation set without training set. Skipping training..." << endl;
delete validationSet;
}
if(testSet) {
cout << "Test set has " << testSet->size() << " instances." << endl
<< "Evaluating test set performance using network defined in file " << netname << endl;
/*
* TODO
* predict(netname, testSet, "test.pred");
*/
delete testSet;
}
return EXIT_SUCCESS;
}
<commit_msg>Always start training with a network with randomised weights. Syntax error.<commit_after>#include "General.h"
#include "require.h"
#include "Options.h"
#include "DataSet.h"
#include "RecursiveNN.h"
#include <cstdlib>
#include <cfloat>
#include <ctime>
#include <map>
#include <vector>
#include <fstream>
#include <sstream>
#include <iostream>
using namespace std;
double adjustLearningRate(double curr_error, bool& restore_weights_flag, double& alpha) {
/*** Vogl adaptive acceleration learning method (additive) ***/
static double prev_eta = atof((Options::instance()->get_parameter("eta")).c_str());
static double prev_error = FLT_MAX;
double alpha_0 = 1e-1;
double phi = 1.05, beta = .5, epsilon = 1e-2;
double phi_additive = prev_eta/100;
double curr_eta;
if(curr_error < prev_error) {
curr_eta = phi_additive + prev_eta;
if(curr_eta > 1)
curr_eta = 1;
alpha = alpha_0;
prev_eta = curr_eta;
prev_error = curr_error;
} else if(curr_error < (1 + epsilon) * prev_error) {
curr_eta = beta * prev_eta;
alpha = 0;
prev_eta = curr_eta;
prev_error = curr_error;
} else {
restore_weights_flag = true;
curr_eta = beta * prev_eta;
alpha = 0;
}
return curr_eta;
}
void computeErrorOnDataset();
void train(const string& netname, DataSet* trainingSet, DataSet* validationSet, ostream& os = cout) {
// Get important training parameters
bool onlinelearning = (atoi((Options::instance()->get_parameter("onlinelearning")).c_str()))?true:false;
// bool random_net = (atoi((Options::instance()->get_parameter("random_net")).c_str()))?true:false;
int epochs = atoi((Options::instance()->get_parameter("epochs")).c_str());
int savedelta = atoi((Options::instance()->get_parameter("savedelta")).c_str());
/*
* read network in if it exists, otherwise make one from scratch
*/
RecursiveNN<TanH, Sigmoid, MGradientDescent>* rnn;
if(trainingSet->size()) {
os << "Creating new network...";
rnn = new RecursiveNN<TanH, Sigmoid, MGradientDescent>();
os << " Done." << endl;
} else {
os << "Need some data to train network, please specify value for the --training-set argument\n";
return;
}
os << endl << endl;
bool restore_weights_flag = false;
double curr_eta = atof((Options::instance()->get_parameter("eta")).c_str());
double alpha = .9;
double prev_error = FLT_MAX, min_error = FLT_MAX;
int min_error_epoch = -1;
double threshold_error = atof((Options::instance()->get_parameter("threshold_error")).c_str());
for(int epoch = 1; epoch<=epochs; epoch++) {
os << "Epoch " << epoch << '\t';
for(DataSet::iterator it=trainingSet->begin(); it!=trainingSet->end(); ++it) {
// (*it)->print(os);
rnn->propagateStructuredInput(*it);
rnn->backPropagateError(*it);
/* stochastic (i.e. online) gradient descent */
if(onlinelearning) {
if(restore_weights_flag)
rnn->restorePrevWeights();
rnn->adjustWeights(curr_eta, alpha);
//curr_eta = adjustLearningRate(curr_train_error, restore_weights_flag, alpha);
}
}
/* batch weight update */
if(!onlinelearning) {
if(restore_weights_flag)
rnn->restorePrevWeights();
rnn->adjustWeights(curr_eta, alpha);
//curr_eta = adjustLearningRate(curr_train_error, restore_weights_flag, alpha);
}
double error;
double error_training_set = rnn->computeErrorOnDataset(trainingSet);
os << "E_training = " << error_training_set << '\t';
if(validationSet) {
double error_validation_set = rnn->computeErrorOnDataset(validationSet);
error = error_validation_set;
os << "E_validation = " << error_validation_set;
} else
error = error_training_set;
os << endl;
if(min_error > error) {
min_error = error;
min_error_epoch = epoch;
rnn->saveParameters(netname.c_str());
}
// stopping criterion based on error threshold
if(fabs(prev_error - error) < threshold_error) {
os << endl << endl << "Network error decay below given threshold. Stopping training..." << endl;
break;
}
prev_error = error;
// save network every 'savedelta' epochs
if(!(epoch % savedelta)) {
ostringstream oss;
oss << netname << '.' << epoch;
rnn->saveParameters((oss.str()).c_str());
}
}
os << endl << flush;
// deallocate Recursive Neural Network instace
delete rnn; rnn = 0;
}
int main(int argc, char* argv[]) {
setenv("RNNOPTIONTYPE", "train", 1);
DataSet *trainingSet = NULL, *testSet = NULL, *validationSet = NULL;
string netname;
try {
Options::instance()->parse_args(argc,argv);
netname = Options::instance()->get_parameter("netname");
if(!netname.length()) {
cerr << "Must specify a network file" << endl << endl;
throw Options::BadOptionSetting(Options::instance()->usage());
}
string training_set_fname = Options::instance()->get_parameter("training_set");
if(training_set_fname.length()) {
cout << "Creating training set. " << flush;
trainingSet = new DataSet(training_set_fname.c_str());
cout << "Done." << flush << endl;
} else
cout << "Training set not specified. Skipping training..." << endl;
string test_set_fname = Options::instance()->get_parameter("test_set");
if(test_set_fname.length()) {
cout << "Creating test set. " << flush;
testSet = new DataSet(test_set_fname.c_str());
cout << "Done." << flush << endl;
} else
cout << "Test set not specified. Skipping testing..." << endl;
string validation_set_fname = Options::instance()->get_parameter("validation_set");
if(validation_set_fname.length()) {
cout << "Creating validation set. " << flush;
validationSet = new DataSet(validation_set_fname.c_str());
cout << "Done." << flush << endl;
}
} catch(Options::BadOptionSetting e) {
cerr << e.what() << endl;
exit(EXIT_FAILURE);
}
/*** Train the network and save results ***/
if(trainingSet) {
cout << "Training set has " << (trainingSet->size()) << " instances." << endl;
if(validationSet) {
cout << "Training network with validation set." << endl;
cout << "Validation set has " << validationSet->size() << " instances." << endl;
}
else
cout << "Training without validation set." << endl;
train(netname, trainingSet, validationSet);
cout << "RNN model saved to file " << netname << endl;
/*
* TODO
* predict(netname, trainingSet, "training.pred");
* predict(netname, validationSet, "validation.pred");
*/
delete trainingSet;
if(validationSet)
delete validationSet;
} else if(validationSet) {
cerr << "Cannot use validation set without training set. Skipping training..." << endl;
delete validationSet;
}
if(testSet) {
cout << "Test set has " << testSet->size() << " instances." << endl
<< "Evaluating test set performance using network defined in file " << netname << endl;
/*
* TODO
* predict(netname, testSet, "test.pred");
*/
delete testSet;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before><commit_msg>Sat: sync code<commit_after><|endoftext|> |
<commit_before>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "SceneGraph.h"
#include "Quaternion.h"
#include "Allocator.h"
#include <string.h>
#include "Hash.h"
#include "StringUtils.h"
namespace crown
{
//-----------------------------------------------------------------------------
SceneGraph::SceneGraph(Allocator& a, uint32_t index)
: m_allocator(&a)
, m_index(index)
, m_num_nodes(0)
, m_world_poses(NULL)
, m_local_poses(NULL)
, m_parents(NULL)
, m_names(NULL)
{
}
//-----------------------------------------------------------------------------
void SceneGraph::create(uint32_t count, const StringId32* name, const Matrix4x4* local, int32_t* parent)
{
char* mem = (char*) m_allocator->allocate(count * (sizeof(StringId32) + sizeof(Matrix4x4) + sizeof(Matrix4x4) + sizeof(int32_t)));
m_num_nodes = count;
m_world_poses = (Matrix4x4*) mem; mem += sizeof(Matrix4x4) * count;
m_local_poses = (Matrix4x4*) mem; mem += sizeof(Matrix4x4) * count;
m_parents = (int32_t*) mem; mem += sizeof(int32_t) * count;
m_names = (StringId32*) mem; mem += sizeof(StringId32) * count;
memcpy(m_local_poses, local, count* sizeof(Matrix4x4));
memcpy(m_parents, parent, count * sizeof(int32_t));
memcpy(m_names, name, count * sizeof(StringId32));
}
//-----------------------------------------------------------------------------
void SceneGraph::destroy()
{
// m_world_poses is the start of allocated memory
m_allocator->deallocate(m_world_poses);
}
//-----------------------------------------------------------------------------
int32_t SceneGraph::node(const char* name) const
{
StringId32 name_hash = hash::murmur2_32(name, string::strlen(name), 0);
for (uint32_t i = 0; i < m_num_nodes; i++)
{
if (m_names[i] == name_hash)
{
return i;
}
}
CE_ASSERT(false, "Node not found: '%s'", name);
}
//-----------------------------------------------------------------------------
bool SceneGraph::has_node(const char* name) const
{
StringId32 name_hash = hash::murmur2_32(name, string::strlen(name), 0);
for (uint32_t i = 0; i < m_num_nodes; i++)
{
if (m_names[i] == name_hash)
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
uint32_t SceneGraph::num_nodes() const
{
return m_num_nodes;
}
//-----------------------------------------------------------------------------
void SceneGraph::link(int32_t child, int32_t parent)
{
CE_ASSERT(child < (int32_t) m_num_nodes, "Child node does not exist");
CE_ASSERT(parent < (int32_t) m_num_nodes, "Parent node does not exist");
CE_ASSERT(parent < child, "Parent must be < child");
m_world_poses[child] = Matrix4x4::IDENTITY;
m_local_poses[child] = Matrix4x4::IDENTITY;
m_parents[child] = parent;
}
//-----------------------------------------------------------------------------
void SceneGraph::unlink(int32_t child)
{
CE_ASSERT(child < (int32_t) m_num_nodes, "Child node does not exist");
if (m_parents[child] != -1)
{
// Copy world pose before unlinking from parent
m_local_poses[child] = m_world_poses[child];
m_parents[child] = -1;
}
}
//-----------------------------------------------------------------------------
void SceneGraph::set_local_position(int32_t node, const Vector3& pos)
{
CE_ASSERT(node < (int32_t) m_num_nodes, "Node does not exist");
Matrix4x4& local_pose = m_local_poses[node];
local_pose.set_translation(pos);
}
//-----------------------------------------------------------------------------
void SceneGraph::set_local_rotation(int32_t node, const Quaternion& rot)
{
CE_ASSERT(node < (int32_t) m_num_nodes, "Node does not exist");
Matrix4x4& local_pose = m_local_poses[node];
Vector3 local_translation = local_pose.translation();
local_pose = rot.to_matrix4x4();
local_pose.set_translation(local_translation);
}
//-----------------------------------------------------------------------------
void SceneGraph::set_local_pose(int32_t node, const Matrix4x4& pose)
{
CE_ASSERT(node < (int32_t) m_num_nodes, "Node does not exist");
m_local_poses[node] = pose;
}
//-----------------------------------------------------------------------------
Vector3 SceneGraph::local_position(int32_t node) const
{
CE_ASSERT(node < (int32_t) m_num_nodes, "Node does not exist");
return m_local_poses[node].translation();
}
//-----------------------------------------------------------------------------
Quaternion SceneGraph::local_rotation(int32_t node) const
{
CE_ASSERT(node < (int32_t) m_num_nodes, "Node does not exist");
return m_local_poses[node].to_quaternion();
}
//-----------------------------------------------------------------------------
Matrix4x4 SceneGraph::local_pose(int32_t node) const
{
CE_ASSERT(node < (int32_t) m_num_nodes, "Node does not exist");
return m_local_poses[node];
}
//-----------------------------------------------------------------------------
Vector3 SceneGraph::world_position(int32_t node) const
{
CE_ASSERT(node < (int32_t) m_num_nodes, "Node does not exist");
return m_world_poses[node].translation();
}
//-----------------------------------------------------------------------------
Quaternion SceneGraph::world_rotation(int32_t node) const
{
CE_ASSERT(node < (int32_t) m_num_nodes, "Node does not exist");
return m_world_poses[node].to_quaternion();
}
//-----------------------------------------------------------------------------
Matrix4x4 SceneGraph::world_pose(int32_t node) const
{
CE_ASSERT(node < (int32_t) m_num_nodes, "Node does not exist");
return m_world_poses[node];
}
//-----------------------------------------------------------------------------
void SceneGraph::update()
{
for (uint32_t i = 0; i < m_num_nodes; i++)
{
if (m_parents[i] == -1)
{
m_world_poses[i] = m_local_poses[i];
}
else
{
m_world_poses[i] = m_local_poses[m_parents[i]] * m_local_poses[i];
}
}
}
} // namespace crown
<commit_msg>Fix SceneGraph wrong matrix selection<commit_after>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "SceneGraph.h"
#include "Quaternion.h"
#include "Allocator.h"
#include <string.h>
#include "Hash.h"
#include "StringUtils.h"
namespace crown
{
//-----------------------------------------------------------------------------
SceneGraph::SceneGraph(Allocator& a, uint32_t index)
: m_allocator(&a)
, m_index(index)
, m_num_nodes(0)
, m_world_poses(NULL)
, m_local_poses(NULL)
, m_parents(NULL)
, m_names(NULL)
{
}
//-----------------------------------------------------------------------------
void SceneGraph::create(uint32_t count, const StringId32* name, const Matrix4x4* local, int32_t* parent)
{
char* mem = (char*) m_allocator->allocate(count * (sizeof(StringId32) + sizeof(Matrix4x4) + sizeof(Matrix4x4) + sizeof(int32_t)));
m_num_nodes = count;
m_world_poses = (Matrix4x4*) mem; mem += sizeof(Matrix4x4) * count;
m_local_poses = (Matrix4x4*) mem; mem += sizeof(Matrix4x4) * count;
m_parents = (int32_t*) mem; mem += sizeof(int32_t) * count;
m_names = (StringId32*) mem; mem += sizeof(StringId32) * count;
memcpy(m_local_poses, local, count* sizeof(Matrix4x4));
memcpy(m_parents, parent, count * sizeof(int32_t));
memcpy(m_names, name, count * sizeof(StringId32));
}
//-----------------------------------------------------------------------------
void SceneGraph::destroy()
{
// m_world_poses is the start of allocated memory
m_allocator->deallocate(m_world_poses);
}
//-----------------------------------------------------------------------------
int32_t SceneGraph::node(const char* name) const
{
StringId32 name_hash = hash::murmur2_32(name, string::strlen(name), 0);
for (uint32_t i = 0; i < m_num_nodes; i++)
{
if (m_names[i] == name_hash)
{
return i;
}
}
CE_ASSERT(false, "Node not found: '%s'", name);
}
//-----------------------------------------------------------------------------
bool SceneGraph::has_node(const char* name) const
{
StringId32 name_hash = hash::murmur2_32(name, string::strlen(name), 0);
for (uint32_t i = 0; i < m_num_nodes; i++)
{
if (m_names[i] == name_hash)
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
uint32_t SceneGraph::num_nodes() const
{
return m_num_nodes;
}
//-----------------------------------------------------------------------------
void SceneGraph::link(int32_t child, int32_t parent)
{
CE_ASSERT(child < (int32_t) m_num_nodes, "Child node does not exist");
CE_ASSERT(parent < (int32_t) m_num_nodes, "Parent node does not exist");
CE_ASSERT(parent < child, "Parent must be < child");
m_world_poses[child] = Matrix4x4::IDENTITY;
m_local_poses[child] = Matrix4x4::IDENTITY;
m_parents[child] = parent;
}
//-----------------------------------------------------------------------------
void SceneGraph::unlink(int32_t child)
{
CE_ASSERT(child < (int32_t) m_num_nodes, "Child node does not exist");
if (m_parents[child] != -1)
{
// Copy world pose before unlinking from parent
m_local_poses[child] = m_world_poses[child];
m_parents[child] = -1;
}
}
//-----------------------------------------------------------------------------
void SceneGraph::set_local_position(int32_t node, const Vector3& pos)
{
CE_ASSERT(node < (int32_t) m_num_nodes, "Node does not exist");
Matrix4x4& local_pose = m_local_poses[node];
local_pose.set_translation(pos);
}
//-----------------------------------------------------------------------------
void SceneGraph::set_local_rotation(int32_t node, const Quaternion& rot)
{
CE_ASSERT(node < (int32_t) m_num_nodes, "Node does not exist");
Matrix4x4& local_pose = m_local_poses[node];
Vector3 local_translation = local_pose.translation();
local_pose = rot.to_matrix4x4();
local_pose.set_translation(local_translation);
}
//-----------------------------------------------------------------------------
void SceneGraph::set_local_pose(int32_t node, const Matrix4x4& pose)
{
CE_ASSERT(node < (int32_t) m_num_nodes, "Node does not exist");
m_local_poses[node] = pose;
}
//-----------------------------------------------------------------------------
Vector3 SceneGraph::local_position(int32_t node) const
{
CE_ASSERT(node < (int32_t) m_num_nodes, "Node does not exist");
return m_local_poses[node].translation();
}
//-----------------------------------------------------------------------------
Quaternion SceneGraph::local_rotation(int32_t node) const
{
CE_ASSERT(node < (int32_t) m_num_nodes, "Node does not exist");
return m_local_poses[node].to_quaternion();
}
//-----------------------------------------------------------------------------
Matrix4x4 SceneGraph::local_pose(int32_t node) const
{
CE_ASSERT(node < (int32_t) m_num_nodes, "Node does not exist");
return m_local_poses[node];
}
//-----------------------------------------------------------------------------
Vector3 SceneGraph::world_position(int32_t node) const
{
CE_ASSERT(node < (int32_t) m_num_nodes, "Node does not exist");
return m_world_poses[node].translation();
}
//-----------------------------------------------------------------------------
Quaternion SceneGraph::world_rotation(int32_t node) const
{
CE_ASSERT(node < (int32_t) m_num_nodes, "Node does not exist");
return m_world_poses[node].to_quaternion();
}
//-----------------------------------------------------------------------------
Matrix4x4 SceneGraph::world_pose(int32_t node) const
{
CE_ASSERT(node < (int32_t) m_num_nodes, "Node does not exist");
return m_world_poses[node];
}
//-----------------------------------------------------------------------------
void SceneGraph::update()
{
for (uint32_t i = 0; i < m_num_nodes; i++)
{
if (m_parents[i] == -1)
{
m_world_poses[i] = m_local_poses[i];
}
else
{
m_world_poses[i] = m_world_poses[m_parents[i]] * m_local_poses[i];
}
}
}
} // namespace crown
<|endoftext|> |
<commit_before>#include <iostream>
#include <algorithm>
#include "vtrc-transformer-iface.h"
#include "vtrc-random-device.h"
#include "vtrc-hash-iface.h"
#include "vtrc-memory.h"
#include "crypt/chacha/ecrypt-sync.h"
namespace vtrc { namespace common {
namespace {
struct transformer_chacha: public transformer_iface {
ECRYPT_ctx ctx_;
//// need poly!!!
transformer_chacha( const char *transform_key, size_t t_length )
{
std::string key;
key.reserve( 32 );
size_t max = 32;
static const size_t input_len = sizeof(ctx_.input) /
sizeof(ctx_.input[0]);
for( size_t i=0; i<input_len; ++i ) {
ctx_.input[i] = 0;
}
if( t_length < 32 ) {
while( max < 32 ) {
size_t next_len = std::min( 32 - max, t_length );
key.append( transform_key + max, next_len );
max += next_len;
}
} else {
key.assign( transform_key, transform_key + 32 );
}
// std::cout << "Key is! "
// << transform_key << ":" << t_length
// << "\n";
ECRYPT_keysetup( &ctx_,
reinterpret_cast<const uint8_t *>(key.c_str( )),
key.size( ) * 8, 0);
}
void transform( std::string &data )
{
char s;
char *ptr = data.empty( ) ? &s : &data[0];
ECRYPT_encrypt_bytes( &ctx_,
reinterpret_cast<const uint8_t *>( ptr ),
reinterpret_cast< uint8_t *>( ptr ),
data.size( ) );
}
};
}
namespace transformers { namespace chacha {
transformer_iface *create( const char *transform_key, size_t length )
{
return new transformer_chacha( transform_key, length );
}
}}
}}
<commit_msg>defaults<commit_after>#include <iostream>
#include <algorithm>
#include "vtrc-transformer-iface.h"
#include "vtrc-random-device.h"
#include "vtrc-hash-iface.h"
#include "vtrc-memory.h"
#include "crypt/chacha/ecrypt-sync.h"
namespace vtrc { namespace common {
namespace {
struct transformer_chacha: public transformer_iface {
ECRYPT_ctx ctx_;
//// need poly!!!
transformer_chacha( const char *transform_key, size_t t_length )
{
std::string key;
key.reserve( 32 );
size_t max = 32;
static const size_t input_len = sizeof(ctx_.input) /
sizeof(ctx_.input[0]);
for( size_t i=0; i<input_len; ++i ) {
ctx_.input[i] = 0;
}
if( t_length < 32 ) {
while( max < 32 ) {
size_t next_len = std::min( 32 - max, t_length );
key.append( transform_key + max, next_len );
max += next_len;
}
} else {
key.assign( transform_key, transform_key + 32 );
}
ECRYPT_keysetup( &ctx_,
reinterpret_cast<const uint8_t *>(key.c_str( )),
key.size( ) * 8, 0);
}
void transform( std::string &data )
{
char s;
char *ptr = data.empty( ) ? &s : &data[0];
ECRYPT_encrypt_bytes( &ctx_,
reinterpret_cast<const uint8_t *>( ptr ),
reinterpret_cast< uint8_t *>( ptr ),
data.size( ) );
}
};
}
namespace transformers { namespace chacha {
transformer_iface *create( const char *transform_key, size_t length )
{
return new transformer_chacha( transform_key, length );
}
}}
}}
<|endoftext|> |
<commit_before>// Time: O(nlogn)
// Space: O(1)
/**
* class Compare {
* public:
* static int cmp(int a, int b);
* };
* You can use Compare::cmp(a, b) to compare nuts "a" and bolts "b",
* if "a" is bigger than "b", it will return 1, else if they are equal,
* it will return 0, else if "a" is smaller than "b", it will return -1.
* When "a" is not a nut or "b" is not a bolt, it will return 2, which is not valid.
*/
class Solution {
public:
typedef enum { SMALLER = -1, EQUAL = 0, BIGGER = 1, REVERSE = 2 } CompareResult;
/**
* @param nuts: a vector of integers
* @param bolts: a vector of integers
* @return: nothing
*/
void sortNutsAndBolts(vector<int> &nuts, vector<int> &bolts) {
quickSort(nuts, bolts, 0, nuts.size() - 1);
}
private:
// Method which works just like quick sort
void quickSort(vector<int>& nuts, vector<int>& bolts, int left, int right) {
if (left < right) {
// Randomly choose a bolt as a pivot for nuts partition.
default_random_engine gen((random_device())());
uniform_int_distribution<int> dis(left, right);
int pivot = dis(gen);
// Use the pivot bolt to make a partition of nuts.
// The we could know the index where the pivot (bolt, nut) pair should be in sorted order.
pivot = partition(nuts, left, right, bolts[pivot]);
// Using the nut in the pivot bolt to make a partition of bolts.
partition(bolts, left, right, nuts[pivot]);
// Now, both nuts and bolts are partitioned by the pivot nut-bolt pair.
// The pivot nut-bolt pair is also in the correct index of the sorted order.
// Recursively do the same thing in the left and right side of the pivot.
quickSort(nuts, bolts, left, pivot - 1);
quickSort(nuts, bolts, pivot + 1, right);
}
}
// All the smaller elements should be in the left side of the pivot,
// and all the bigger elements should in the right side of the pivot.
int partition(vector<int>& arr, int left, int right, int pivot) {
for (int i = left; i < right; ) {
if (Compare::cmp(arr[i], pivot) == SMALLER || // Smaller.
(Compare::cmp(arr[i], pivot) == REVERSE &&
Compare::cmp(pivot, arr[i]) == BIGGER)) {
swap(arr[left++], arr[i++]);
} else if (Compare::cmp(arr[i], pivot) == BIGGER || // Bigger.
(Compare::cmp(arr[i], pivot) == REVERSE &&
Compare::cmp(pivot, arr[i]) == SMALLER)) {
++i;
} else { // Equal.
swap(arr[i], arr[right]);
}
}
// Put the pivot to the partition index.
swap(arr[left], arr[right]);
// Return the partition index of an array.
return left;
}
};
<commit_msg>Update nuts-bolts-problem.cpp<commit_after>// Time: O(nlogn)
// Space: O(1)
/**
* class Comparator {
* public:
* int cmp(string a, string b);
* };
* You can use compare.cmp(a, b) to compare nuts "a" and bolts "b",
* if "a" is bigger than "b", it will return 1, else if they are equal,
* it will return 0, else if "a" is smaller than "b", it will return -1.
* When "a" is not a nut or "b" is not a bolt, it will return 2, which is not valid.
*/
class Solution {
public:
typedef enum { SMALLER = -1, EQUAL = 0,
BIGGER = 1, REVERSE = 2 } CompareResult;
/**
* @param nuts: a vector of integers
* @param bolts: a vector of integers
* @param compare: a instance of Comparator
* @return: nothing
*/
void sortNutsAndBolts(vector<string> &nuts, vector<string> &bolts,
Comparator compare) {
quickSort(nuts, bolts, 0, nuts.size() - 1, compare);
}
// Method which works just like quick sort
void quickSort(vector<string>& nuts, vector<string>& bolts,
int left, int right,
Comparator& compare) {
if (left < right) {
// Randomly choose a bolt as a pivot for nuts partition.
default_random_engine gen((random_device())());
uniform_int_distribution<int> dis(left, right);
int pivot = dis(gen);
// Use the pivot bolt to make a partition of nuts.
// The we could know the index where the pivot (bolt, nut)
// pair should be in sorted order.
pivot = partition(nuts, left, right, bolts[pivot], compare);
// Using the nut in the pivot bolt to make a partition of bolts.
partition(bolts, left, right, nuts[pivot], compare);
// Now, both nuts and bolts are partitioned by the pivot nut-bolt pair.
// The pivot nut-bolt pair is also in the correct index of the sorted order.
// Recursively do the same thing in the left and right side of the pivot.
quickSort(nuts, bolts, left, pivot - 1, compare);
quickSort(nuts, bolts, pivot + 1, right, compare);
}
}
// All the smaller elements should be in the left side of the pivot,
// and all the bigger elements should in the right side of the pivot.
int partition(vector<string>& arr,
int left, int right, const string& pivot,
Comparator& compare) {
for (int i = left; i < right; ) {
if (compare.cmp(arr[i], pivot) == SMALLER || // Smaller.
(compare.cmp(arr[i], pivot) == REVERSE &&
compare.cmp(pivot, arr[i]) == BIGGER)) {
swap(arr[left++], arr[i++]);
} else if (compare.cmp(arr[i], pivot) == BIGGER || // Bigger.
(compare.cmp(arr[i], pivot) == REVERSE &&
compare.cmp(pivot, arr[i]) == SMALLER)) {
++i;
} else { // Equal.
swap(arr[i], arr[right]);
}
}
// Put the pivot to the partition index.
swap(arr[left], arr[right]);
// Return the partition index of an array.
return left;
}
};
<|endoftext|> |
<commit_before>#include <stan/math/error_handling/matrix/check_ordered.hpp>
#include <gtest/gtest.h>
using stan::math::check_ordered;
TEST(MathErrorHandlingMatrix, checkOrdered) {
double result;
Eigen::Matrix<double, Eigen::Dynamic, 1> y;
y.resize(3);
y << 0, 1, 2;
EXPECT_TRUE(check_ordered("check_ordered(%1%)", y, "y", &result));
y << 0, 10, std::numeric_limits<double>::infinity();
EXPECT_TRUE(check_ordered("check_ordered(%1%)", y, "y", &result));
y << -10, 10, std::numeric_limits<double>::infinity();
EXPECT_TRUE(check_ordered("check_ordered(%1%)", y, "y", &result));
y << -std::numeric_limits<double>::infinity(), 10, std::numeric_limits<double>::infinity();
EXPECT_TRUE(check_ordered("check_ordered(%1%)", y, "y", &result));
y << 0, 0, 0;
EXPECT_THROW(check_ordered("check_ordered(%1%)", y, "y", &result),
std::domain_error);
y << 0, std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity();
EXPECT_THROW(check_ordered("check_ordered(%1%)", y, "y", &result),
std::domain_error);
y << -1, 3, 2;
EXPECT_THROW(check_ordered("check_ordered(%1%)", y, "y", &result),
std::domain_error);
}
TEST(MathErrorHandlingMatrix, checkOrdered_one_indexed_message) {
std::string message;
double result;
Eigen::Matrix<double, Eigen::Dynamic, 1> y;
y.resize(3);
y << 0, 5, 1;
try {
check_ordered("check_ordered(%1%)", y, "y", &result);
FAIL() << "should have thrown";
} catch (std::domain_error& e) {
message = e.what();
} catch (...) {
FAIL() << "threw the wrong error";
}
EXPECT_NE(std::string::npos, message.find("element at 3"))
<< message;
}
<commit_msg>added NaN test for check_ordered<commit_after>#include <stan/math/error_handling/matrix/check_ordered.hpp>
#include <gtest/gtest.h>
using stan::math::check_ordered;
TEST(MathErrorHandlingMatrix, checkOrdered) {
double result;
Eigen::Matrix<double, Eigen::Dynamic, 1> y;
y.resize(3);
y << 0, 1, 2;
EXPECT_TRUE(check_ordered("check_ordered(%1%)", y, "y", &result));
y << 0, 10, std::numeric_limits<double>::infinity();
EXPECT_TRUE(check_ordered("check_ordered(%1%)", y, "y", &result));
y << -10, 10, std::numeric_limits<double>::infinity();
EXPECT_TRUE(check_ordered("check_ordered(%1%)", y, "y", &result));
y << -std::numeric_limits<double>::infinity(), 10, std::numeric_limits<double>::infinity();
EXPECT_TRUE(check_ordered("check_ordered(%1%)", y, "y", &result));
y << 0, 0, 0;
EXPECT_THROW(check_ordered("check_ordered(%1%)", y, "y", &result),
std::domain_error);
y << 0, std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity();
EXPECT_THROW(check_ordered("check_ordered(%1%)", y, "y", &result),
std::domain_error);
y << -1, 3, 2;
EXPECT_THROW(check_ordered("check_ordered(%1%)", y, "y", &result),
std::domain_error);
}
TEST(MathErrorHandlingMatrix, checkOrdered_one_indexed_message) {
std::string message;
double result;
Eigen::Matrix<double, Eigen::Dynamic, 1> y;
y.resize(3);
y << 0, 5, 1;
try {
check_ordered("check_ordered(%1%)", y, "y", &result);
FAIL() << "should have thrown";
} catch (std::domain_error& e) {
message = e.what();
} catch (...) {
FAIL() << "threw the wrong error";
}
EXPECT_NE(std::string::npos, message.find("element at 3"))
<< message;
}
TEST(MathErrorHandlingMatrix, checkOrdered_nan) {
double result;
Eigen::Matrix<double, Eigen::Dynamic, 1> y;
double nan = std::numeric_limits<double>::quiet_NaN();
y.resize(3);
y << 0, 1, 2;
for (int i = 0; i < y.size(); i++) {
y[i] = nan;
EXPECT_THROW(check_ordered("check_ordered(%1%)", y, "y", &result),
std::domain_error);
y[i] = i;
}
for (int i = 0; i < y.size(); i++) {
y << 0, 10, std::numeric_limits<double>::infinity();
y[i] = nan;
EXPECT_THROW(check_ordered("check_ordered(%1%)", y, "y", &result),
std::domain_error);
y[i] = i;
}
}
<|endoftext|> |
<commit_before>//===-- Passes.cpp - Target independent code generation passes ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines interfaces to access the target independent code
// generation passes provided by the LLVM backend.
//
//===---------------------------------------------------------------------===//
#include "llvm/CodeGen/RegAllocRegistry.h"
#include "llvm/CodeGen/Passes.h"
using namespace llvm;
//===---------------------------------------------------------------------===//
///
/// RegisterRegAlloc class - Track the registration of register allocators.
///
//===---------------------------------------------------------------------===//
MachinePassRegistry RegisterRegAlloc::Registry;
static FunctionPass *createDefaultRegisterAllocator() { return 0; }
static RegisterRegAlloc
defaultRegAlloc("default",
"pick register allocator based on -O option",
createDefaultRegisterAllocator);
//===---------------------------------------------------------------------===//
///
/// RegAlloc command line options.
///
//===---------------------------------------------------------------------===//
static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
RegisterPassParser<RegisterRegAlloc> >
RegAlloc("regalloc",
cl::init(&createDefaultRegisterAllocator),
cl::desc("Register allocator to use"));
//===---------------------------------------------------------------------===//
///
/// createRegisterAllocator - choose the appropriate register allocator.
///
//===---------------------------------------------------------------------===//
FunctionPass *llvm::createRegisterAllocator(CodeGenOpt::Level OptLevel) {
RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
if (!Ctor) {
Ctor = RegAlloc;
RegisterRegAlloc::setDefault(RegAlloc);
}
if (Ctor != createDefaultRegisterAllocator)
return Ctor();
// When the 'default' allocator is requested, pick one based on OptLevel.
switch (OptLevel) {
case CodeGenOpt::None:
return createLocalRegisterAllocator();
default:
return createLinearScanRegisterAllocator();
}
}
<commit_msg>Use the fast register allocator by default for -O0 builds.<commit_after>//===-- Passes.cpp - Target independent code generation passes ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines interfaces to access the target independent code
// generation passes provided by the LLVM backend.
//
//===---------------------------------------------------------------------===//
#include "llvm/CodeGen/RegAllocRegistry.h"
#include "llvm/CodeGen/Passes.h"
using namespace llvm;
//===---------------------------------------------------------------------===//
///
/// RegisterRegAlloc class - Track the registration of register allocators.
///
//===---------------------------------------------------------------------===//
MachinePassRegistry RegisterRegAlloc::Registry;
static FunctionPass *createDefaultRegisterAllocator() { return 0; }
static RegisterRegAlloc
defaultRegAlloc("default",
"pick register allocator based on -O option",
createDefaultRegisterAllocator);
//===---------------------------------------------------------------------===//
///
/// RegAlloc command line options.
///
//===---------------------------------------------------------------------===//
static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
RegisterPassParser<RegisterRegAlloc> >
RegAlloc("regalloc",
cl::init(&createDefaultRegisterAllocator),
cl::desc("Register allocator to use"));
//===---------------------------------------------------------------------===//
///
/// createRegisterAllocator - choose the appropriate register allocator.
///
//===---------------------------------------------------------------------===//
FunctionPass *llvm::createRegisterAllocator(CodeGenOpt::Level OptLevel) {
RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
if (!Ctor) {
Ctor = RegAlloc;
RegisterRegAlloc::setDefault(RegAlloc);
}
if (Ctor != createDefaultRegisterAllocator)
return Ctor();
// When the 'default' allocator is requested, pick one based on OptLevel.
switch (OptLevel) {
case CodeGenOpt::None:
return createFastRegisterAllocator();
default:
return createLinearScanRegisterAllocator();
}
}
<|endoftext|> |
<commit_before>// Copyright (C) 2014 The Regents of the University of California (Regents).
// 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 Regents or University of California 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 HOLDERS 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.
//
// Please contact the author of this library if you have any questions.
// Author: Chris Sweeney ([email protected])
#include "theia/sfm/estimators/estimate_uncalibrated_relative_pose.h"
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <limits>
#include <memory>
#include <vector>
#include "theia/matching/feature_correspondence.h"
#include "theia/sfm/create_and_initialize_ransac_variant.h"
#include "theia/sfm/pose/eight_point_fundamental_matrix.h"
#include "theia/sfm/pose/essential_matrix_utils.h"
#include "theia/sfm/pose/fundamental_matrix_util.h"
#include "theia/sfm/pose/util.h"
#include "theia/sfm/triangulation/triangulation.h"
#include "theia/solvers/estimator.h"
#include "theia/solvers/sample_consensus_estimator.h"
#include "theia/util/util.h"
namespace theia {
using Eigen::Matrix3d;
using Eigen::Vector3d;
namespace {
// An estimator for computing the relative pose from 8 feature correspondences
// (via decomposition of the fundamental matrix).
//
// NOTE: Feature correspondences must be in pixel coordinates with the principal
// point removed i.e. principal point at (0, 0). This also assumes negligible
// skew (which is reasonable for most cameras).
class UncalibratedRelativePoseEstimator
: public Estimator<FeatureCorrespondence, UncalibratedRelativePose> {
public:
UncalibratedRelativePoseEstimator() {}
// 8 correspondences are needed to determine a fundamental matrix and thus a
// relative pose.
double SampleSize() const { return 8; }
// Estimates candidate relative poses from correspondences.
bool EstimateModel(
const std::vector<FeatureCorrespondence>& centered_correspondences,
std::vector<UncalibratedRelativePose>* relative_poses) const {
std::vector<Eigen::Vector2d> image1_points, image2_points;
for (int i = 0; i < 8; i++) {
image1_points.emplace_back(centered_correspondences[i].feature1);
image2_points.emplace_back(centered_correspondences[i].feature2);
}
UncalibratedRelativePose relative_pose;
if (!NormalizedEightPointFundamentalMatrix(
image1_points, image2_points, &relative_pose.fundamental_matrix)) {
return false;
}
// Only consider fundamental matrices that we can decompose focal lengths
// from.
if (!FocalLengthsFromFundamentalMatrix(
relative_pose.fundamental_matrix.data(),
&relative_pose.focal_length1,
&relative_pose.focal_length2)) {
return false;
}
// TODO(cmsweeney): Should we check if the focal lengths are reasonable?
// Compose the essential matrix from the fundamental matrix and focal
// lengths.
const Matrix3d essential_matrix =
Eigen::DiagonalMatrix<double, 3>(relative_pose.focal_length2,
relative_pose.focal_length2,
1.0) *
relative_pose.fundamental_matrix *
Eigen::DiagonalMatrix<double, 3>(relative_pose.focal_length1,
relative_pose.focal_length1,
1.0);
// Normalize the centered_correspondences.
std::vector<FeatureCorrespondence> normalized_correspondences(
centered_correspondences.size());
for (int i = 0; i < centered_correspondences.size(); i++) {
normalized_correspondences[i].feature1 =
centered_correspondences[i].feature1 / relative_pose.focal_length1;
normalized_correspondences[i].feature2 =
centered_correspondences[i].feature2 / relative_pose.focal_length2;
}
GetBestPoseFromEssentialMatrix(essential_matrix,
normalized_correspondences,
&relative_pose.rotation,
&relative_pose.position);
relative_poses->emplace_back(relative_pose);
return true;
}
// The error for a correspondences given a model. This is the squared sampson
// error.
double Error(const FeatureCorrespondence& centered_correspondence,
const UncalibratedRelativePose& relative_pose) const {
return SquaredSampsonDistance(relative_pose.fundamental_matrix,
centered_correspondence.feature1,
centered_correspondence.feature2);
}
private:
DISALLOW_COPY_AND_ASSIGN(UncalibratedRelativePoseEstimator);
};
} // namespace
bool EstimateUncalibratedRelativePose(
const RansacParameters& ransac_params,
const RansacType& ransac_type,
const std::vector<FeatureCorrespondence>& centered_correspondences,
UncalibratedRelativePose* relative_pose,
RansacSummary* ransac_summary) {
UncalibratedRelativePoseEstimator relative_pose_estimator;
std::unique_ptr<SampleConsensusEstimator<UncalibratedRelativePoseEstimator> >
ransac = CreateAndInitializeRansacVariant(ransac_type,
ransac_params,
relative_pose_estimator);
// Estimate essential matrix.
return ransac->Estimate(centered_correspondences,
relative_pose,
ransac_summary);
}
} // namespace theia
<commit_msg>Add cheirality check for fundamental matrix estimation<commit_after>// Copyright (C) 2014 The Regents of the University of California (Regents).
// 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 Regents or University of California 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 HOLDERS 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.
//
// Please contact the author of this library if you have any questions.
// Author: Chris Sweeney ([email protected])
#include "theia/sfm/estimators/estimate_uncalibrated_relative_pose.h"
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <limits>
#include <memory>
#include <vector>
#include "theia/matching/feature_correspondence.h"
#include "theia/sfm/create_and_initialize_ransac_variant.h"
#include "theia/sfm/pose/eight_point_fundamental_matrix.h"
#include "theia/sfm/pose/essential_matrix_utils.h"
#include "theia/sfm/pose/fundamental_matrix_util.h"
#include "theia/sfm/pose/util.h"
#include "theia/sfm/triangulation/triangulation.h"
#include "theia/solvers/estimator.h"
#include "theia/solvers/sample_consensus_estimator.h"
#include "theia/util/util.h"
namespace theia {
using Eigen::Matrix3d;
using Eigen::Vector3d;
namespace {
// An estimator for computing the relative pose from 8 feature correspondences
// (via decomposition of the fundamental matrix).
//
// NOTE: Feature correspondences must be in pixel coordinates with the principal
// point removed i.e. principal point at (0, 0). This also assumes negligible
// skew (which is reasonable for most cameras).
class UncalibratedRelativePoseEstimator
: public Estimator<FeatureCorrespondence, UncalibratedRelativePose> {
public:
UncalibratedRelativePoseEstimator() {}
// 8 correspondences are needed to determine a fundamental matrix and thus a
// relative pose.
double SampleSize() const { return 8; }
// Estimates candidate relative poses from correspondences.
bool EstimateModel(
const std::vector<FeatureCorrespondence>& centered_correspondences,
std::vector<UncalibratedRelativePose>* relative_poses) const {
std::vector<Eigen::Vector2d> image1_points, image2_points;
for (int i = 0; i < 8; i++) {
image1_points.emplace_back(centered_correspondences[i].feature1);
image2_points.emplace_back(centered_correspondences[i].feature2);
}
UncalibratedRelativePose relative_pose;
if (!NormalizedEightPointFundamentalMatrix(
image1_points, image2_points, &relative_pose.fundamental_matrix)) {
return false;
}
// Only consider fundamental matrices that we can decompose focal lengths
// from.
if (!FocalLengthsFromFundamentalMatrix(
relative_pose.fundamental_matrix.data(),
&relative_pose.focal_length1,
&relative_pose.focal_length2)) {
return false;
}
// TODO(cmsweeney): Should we check if the focal lengths are reasonable?
// Compose the essential matrix from the fundamental matrix and focal
// lengths.
const Matrix3d essential_matrix =
Eigen::DiagonalMatrix<double, 3>(relative_pose.focal_length2,
relative_pose.focal_length2,
1.0) *
relative_pose.fundamental_matrix *
Eigen::DiagonalMatrix<double, 3>(relative_pose.focal_length1,
relative_pose.focal_length1,
1.0);
// Normalize the centered_correspondences.
std::vector<FeatureCorrespondence> normalized_correspondences(
centered_correspondences.size());
for (int i = 0; i < centered_correspondences.size(); i++) {
normalized_correspondences[i].feature1 =
centered_correspondences[i].feature1 / relative_pose.focal_length1;
normalized_correspondences[i].feature2 =
centered_correspondences[i].feature2 / relative_pose.focal_length2;
}
GetBestPoseFromEssentialMatrix(essential_matrix,
normalized_correspondences,
&relative_pose.rotation,
&relative_pose.position);
relative_poses->emplace_back(relative_pose);
return true;
}
// The error for a correspondences given a model. This is the squared sampson
// error.
double Error(const FeatureCorrespondence& centered_correspondence,
const UncalibratedRelativePose& relative_pose) const {
FeatureCorrespondence normalized_correspondence;
normalized_correspondence.feature1 =
centered_correspondence.feature1 / relative_pose.focal_length1;
normalized_correspondence.feature2 =
centered_correspondence.feature2 / relative_pose.focal_length2;
if (!IsTriangulatedPointInFrontOfCameras(normalized_correspondence,
relative_pose.rotation,
relative_pose.position)) {
return std::numeric_limits<double>::max();
}
return SquaredSampsonDistance(relative_pose.fundamental_matrix,
centered_correspondence.feature1,
centered_correspondence.feature2);
}
private:
DISALLOW_COPY_AND_ASSIGN(UncalibratedRelativePoseEstimator);
};
} // namespace
bool EstimateUncalibratedRelativePose(
const RansacParameters& ransac_params,
const RansacType& ransac_type,
const std::vector<FeatureCorrespondence>& centered_correspondences,
UncalibratedRelativePose* relative_pose,
RansacSummary* ransac_summary) {
UncalibratedRelativePoseEstimator relative_pose_estimator;
std::unique_ptr<SampleConsensusEstimator<UncalibratedRelativePoseEstimator> >
ransac = CreateAndInitializeRansacVariant(ransac_type,
ransac_params,
relative_pose_estimator);
// Estimate essential matrix.
return ransac->Estimate(centered_correspondences,
relative_pose,
ransac_summary);
}
} // namespace theia
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2012 Intel Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/page/PerformanceUserTiming.h"
#include "bindings/v8/ExceptionState.h"
#include "core/dom/ExceptionCode.h"
#include "core/page/Performance.h"
#include "core/page/PerformanceMark.h"
#include "core/page/PerformanceMeasure.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
namespace {
typedef HashMap<String, NavigationTimingFunction> RestrictedKeyMap;
static RestrictedKeyMap restrictedKeyMap()
{
DEFINE_STATIC_LOCAL(RestrictedKeyMap, map, ());
if (map.isEmpty()) {
map.add("navigationStart", &PerformanceTiming::navigationStart);
map.add("unloadEventStart", &PerformanceTiming::unloadEventStart);
map.add("unloadEventEnd", &PerformanceTiming::unloadEventEnd);
map.add("redirectStart", &PerformanceTiming::redirectStart);
map.add("redirectEnd", &PerformanceTiming::redirectEnd);
map.add("fetchStart", &PerformanceTiming::fetchStart);
map.add("domainLookupStart", &PerformanceTiming::domainLookupStart);
map.add("domainLookupEnd", &PerformanceTiming::domainLookupEnd);
map.add("connectStart", &PerformanceTiming::connectStart);
map.add("connectEnd", &PerformanceTiming::connectEnd);
map.add("secureConnectionStart", &PerformanceTiming::secureConnectionStart);
map.add("requestStart", &PerformanceTiming::requestStart);
map.add("responseStart", &PerformanceTiming::responseStart);
map.add("responseEnd", &PerformanceTiming::responseEnd);
map.add("domLoading", &PerformanceTiming::domLoading);
map.add("domInteractive", &PerformanceTiming::domInteractive);
map.add("domContentLoadedEventStart", &PerformanceTiming::domContentLoadedEventStart);
map.add("domContentLoadedEventEnd", &PerformanceTiming::domContentLoadedEventEnd);
map.add("domComplete", &PerformanceTiming::domComplete);
map.add("loadEventStart", &PerformanceTiming::loadEventStart);
map.add("loadEventEnd", &PerformanceTiming::loadEventEnd);
}
return map;
}
} // namespace anonymous
UserTiming::UserTiming(Performance* performance)
: m_performance(performance)
{
}
static void insertPerformanceEntry(PerformanceEntryMap& performanceEntryMap, PassRefPtr<PerformanceEntry> performanceEntry)
{
RefPtr<PerformanceEntry> entry = performanceEntry;
PerformanceEntryMap::iterator it = performanceEntryMap.find(entry->name());
if (it != performanceEntryMap.end())
it->value.append(entry);
else {
Vector<RefPtr<PerformanceEntry> > v(1);
v[0] = entry;
performanceEntryMap.set(entry->name(), v);
}
}
static void clearPeformanceEntries(PerformanceEntryMap& performanceEntryMap, const String& name)
{
if (name.isNull()) {
performanceEntryMap.clear();
return;
}
if (performanceEntryMap.contains(name))
performanceEntryMap.remove(name);
}
void UserTiming::mark(const String& markName, ExceptionState& es)
{
if (restrictedKeyMap().contains(markName)) {
es.throwDOMException(SyntaxError, "'" + markName + "' is part of the PerformanceTiming interface, and cannot be used as a mark name.");
return;
}
double startTime = m_performance->now();
insertPerformanceEntry(m_marksMap, PerformanceMark::create(markName, startTime));
}
void UserTiming::clearMarks(const String& markName)
{
clearPeformanceEntries(m_marksMap, markName);
}
double UserTiming::findExistingMarkStartTime(const String& markName, ExceptionState& es)
{
if (m_marksMap.contains(markName))
return m_marksMap.get(markName).last()->startTime();
if (restrictedKeyMap().contains(markName)) {
double value = static_cast<double>((m_performance->timing()->*(restrictedKeyMap().get(markName)))());
if (!value) {
es.throwDOMException(InvalidAccessError, "'" + markName + "' is empty: either the event hasn't happened yet, or it would provide cross-origin timing information.");
return 0.0;
}
return value - m_performance->timing()->navigationStart();
}
es.throwDOMException(SyntaxError, "The mark '" + markName + "' does not exist.");
return 0.0;
}
void UserTiming::measure(const String& measureName, const String& startMark, const String& endMark, ExceptionState& es)
{
double startTime = 0.0;
double endTime = 0.0;
if (startMark.isNull())
endTime = m_performance->now();
else if (endMark.isNull()) {
endTime = m_performance->now();
startTime = findExistingMarkStartTime(startMark, es);
if (es.hadException())
return;
} else {
endTime = findExistingMarkStartTime(endMark, es);
if (es.hadException())
return;
startTime = findExistingMarkStartTime(startMark, es);
if (es.hadException())
return;
}
insertPerformanceEntry(m_measuresMap, PerformanceMeasure::create(measureName, startTime, endTime));
}
void UserTiming::clearMeasures(const String& measureName)
{
clearPeformanceEntries(m_measuresMap, measureName);
}
static Vector<RefPtr<PerformanceEntry> > convertToEntrySequence(const PerformanceEntryMap& performanceEntryMap)
{
Vector<RefPtr<PerformanceEntry> > entries;
for (PerformanceEntryMap::const_iterator it = performanceEntryMap.begin(); it != performanceEntryMap.end(); ++it)
entries.append(it->value);
return entries;
}
static Vector<RefPtr<PerformanceEntry> > getEntrySequenceByName(const PerformanceEntryMap& performanceEntryMap, const String& name)
{
Vector<RefPtr<PerformanceEntry> > entries;
PerformanceEntryMap::const_iterator it = performanceEntryMap.find(name);
if (it != performanceEntryMap.end())
entries.append(it->value);
return entries;
}
Vector<RefPtr<PerformanceEntry> > UserTiming::getMarks() const
{
return convertToEntrySequence(m_marksMap);
}
Vector<RefPtr<PerformanceEntry> > UserTiming::getMarks(const String& name) const
{
return getEntrySequenceByName(m_marksMap, name);
}
Vector<RefPtr<PerformanceEntry> > UserTiming::getMeasures() const
{
return convertToEntrySequence(m_measuresMap);
}
Vector<RefPtr<PerformanceEntry> > UserTiming::getMeasures(const String& name) const
{
return getEntrySequenceByName(m_measuresMap, name);
}
} // namespace WebCore
<commit_msg>Added UMA instrumentation for site-instrumented user timing marks and measures<commit_after>/*
* Copyright (C) 2012 Intel Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/page/PerformanceUserTiming.h"
#include "bindings/v8/ExceptionState.h"
#include "core/dom/ExceptionCode.h"
#include "core/page/Performance.h"
#include "core/page/PerformanceMark.h"
#include "core/page/PerformanceMeasure.h"
#include "core/platform/HistogramSupport.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
namespace {
typedef HashMap<String, NavigationTimingFunction> RestrictedKeyMap;
static RestrictedKeyMap restrictedKeyMap()
{
DEFINE_STATIC_LOCAL(RestrictedKeyMap, map, ());
if (map.isEmpty()) {
map.add("navigationStart", &PerformanceTiming::navigationStart);
map.add("unloadEventStart", &PerformanceTiming::unloadEventStart);
map.add("unloadEventEnd", &PerformanceTiming::unloadEventEnd);
map.add("redirectStart", &PerformanceTiming::redirectStart);
map.add("redirectEnd", &PerformanceTiming::redirectEnd);
map.add("fetchStart", &PerformanceTiming::fetchStart);
map.add("domainLookupStart", &PerformanceTiming::domainLookupStart);
map.add("domainLookupEnd", &PerformanceTiming::domainLookupEnd);
map.add("connectStart", &PerformanceTiming::connectStart);
map.add("connectEnd", &PerformanceTiming::connectEnd);
map.add("secureConnectionStart", &PerformanceTiming::secureConnectionStart);
map.add("requestStart", &PerformanceTiming::requestStart);
map.add("responseStart", &PerformanceTiming::responseStart);
map.add("responseEnd", &PerformanceTiming::responseEnd);
map.add("domLoading", &PerformanceTiming::domLoading);
map.add("domInteractive", &PerformanceTiming::domInteractive);
map.add("domContentLoadedEventStart", &PerformanceTiming::domContentLoadedEventStart);
map.add("domContentLoadedEventEnd", &PerformanceTiming::domContentLoadedEventEnd);
map.add("domComplete", &PerformanceTiming::domComplete);
map.add("loadEventStart", &PerformanceTiming::loadEventStart);
map.add("loadEventEnd", &PerformanceTiming::loadEventEnd);
}
return map;
}
} // namespace anonymous
UserTiming::UserTiming(Performance* performance)
: m_performance(performance)
{
}
static void insertPerformanceEntry(PerformanceEntryMap& performanceEntryMap, PassRefPtr<PerformanceEntry> performanceEntry)
{
RefPtr<PerformanceEntry> entry = performanceEntry;
PerformanceEntryMap::iterator it = performanceEntryMap.find(entry->name());
if (it != performanceEntryMap.end())
it->value.append(entry);
else {
Vector<RefPtr<PerformanceEntry> > v(1);
v[0] = entry;
performanceEntryMap.set(entry->name(), v);
}
}
static void clearPeformanceEntries(PerformanceEntryMap& performanceEntryMap, const String& name)
{
if (name.isNull()) {
performanceEntryMap.clear();
return;
}
if (performanceEntryMap.contains(name))
performanceEntryMap.remove(name);
}
void UserTiming::mark(const String& markName, ExceptionState& es)
{
if (restrictedKeyMap().contains(markName)) {
es.throwDOMException(SyntaxError, "'" + markName + "' is part of the PerformanceTiming interface, and cannot be used as a mark name.");
return;
}
double startTime = m_performance->now();
insertPerformanceEntry(m_marksMap, PerformanceMark::create(markName, startTime));
HistogramSupport::histogramCustomCounts("PLT.UserTiming_Mark", static_cast<int>(startTime), 0, 600000, 100);
}
void UserTiming::clearMarks(const String& markName)
{
clearPeformanceEntries(m_marksMap, markName);
}
double UserTiming::findExistingMarkStartTime(const String& markName, ExceptionState& es)
{
if (m_marksMap.contains(markName))
return m_marksMap.get(markName).last()->startTime();
if (restrictedKeyMap().contains(markName)) {
double value = static_cast<double>((m_performance->timing()->*(restrictedKeyMap().get(markName)))());
if (!value) {
es.throwDOMException(InvalidAccessError, "'" + markName + "' is empty: either the event hasn't happened yet, or it would provide cross-origin timing information.");
return 0.0;
}
return value - m_performance->timing()->navigationStart();
}
es.throwDOMException(SyntaxError, "The mark '" + markName + "' does not exist.");
return 0.0;
}
void UserTiming::measure(const String& measureName, const String& startMark, const String& endMark, ExceptionState& es)
{
double startTime = 0.0;
double endTime = 0.0;
if (startMark.isNull())
endTime = m_performance->now();
else if (endMark.isNull()) {
endTime = m_performance->now();
startTime = findExistingMarkStartTime(startMark, es);
if (es.hadException())
return;
} else {
endTime = findExistingMarkStartTime(endMark, es);
if (es.hadException())
return;
startTime = findExistingMarkStartTime(startMark, es);
if (es.hadException())
return;
}
insertPerformanceEntry(m_measuresMap, PerformanceMeasure::create(measureName, startTime, endTime));
if (endTime >= startTime)
HistogramSupport::histogramCustomCounts("PLT.UserTiming_MeasureDuration", static_cast<int>(endTime - startTime), 0, 600000, 100);
}
void UserTiming::clearMeasures(const String& measureName)
{
clearPeformanceEntries(m_measuresMap, measureName);
}
static Vector<RefPtr<PerformanceEntry> > convertToEntrySequence(const PerformanceEntryMap& performanceEntryMap)
{
Vector<RefPtr<PerformanceEntry> > entries;
for (PerformanceEntryMap::const_iterator it = performanceEntryMap.begin(); it != performanceEntryMap.end(); ++it)
entries.append(it->value);
return entries;
}
static Vector<RefPtr<PerformanceEntry> > getEntrySequenceByName(const PerformanceEntryMap& performanceEntryMap, const String& name)
{
Vector<RefPtr<PerformanceEntry> > entries;
PerformanceEntryMap::const_iterator it = performanceEntryMap.find(name);
if (it != performanceEntryMap.end())
entries.append(it->value);
return entries;
}
Vector<RefPtr<PerformanceEntry> > UserTiming::getMarks() const
{
return convertToEntrySequence(m_marksMap);
}
Vector<RefPtr<PerformanceEntry> > UserTiming::getMarks(const String& name) const
{
return getEntrySequenceByName(m_marksMap, name);
}
Vector<RefPtr<PerformanceEntry> > UserTiming::getMeasures() const
{
return convertToEntrySequence(m_measuresMap);
}
Vector<RefPtr<PerformanceEntry> > UserTiming::getMeasures(const String& name) const
{
return getEntrySequenceByName(m_measuresMap, name);
}
} // namespace WebCore
<|endoftext|> |
<commit_before>// Copyright 2015-2018 Elviss Strazdins. All rights reserved.
#include "StaticMeshRenderer.hpp"
#include "core/Engine.hpp"
#include "utils/Utils.hpp"
namespace ouzel
{
namespace scene
{
StaticMeshData::StaticMeshData(Box3<float> initBoundingBox,
const std::vector<uint32_t> indices,
const std::vector<graphics::Vertex>& vertices,
const std::shared_ptr<graphics::Material>& initMaterial):
boundingBox(initBoundingBox),
material(initMaterial)
{
indexCount = static_cast<uint32_t>(indices.size());
indexSize = sizeof(uint32_t);
indexBuffer = std::make_shared<graphics::Buffer>(*engine->getRenderer(),
graphics::Buffer::Usage::INDEX, 0,
indices.data(),
static_cast<uint32_t>(getVectorSize(indices)));
vertexBuffer = std::make_shared<graphics::Buffer>(*engine->getRenderer(),
graphics::Buffer::Usage::VERTEX, 0,
vertices.data(),
static_cast<uint32_t>(getVectorSize(vertices)));
}
StaticMeshRenderer::StaticMeshRenderer():
Component(CLASS)
{
}
StaticMeshRenderer::StaticMeshRenderer(const StaticMeshData& meshData):
Component(CLASS)
{
init(meshData);
}
StaticMeshRenderer::StaticMeshRenderer(const std::string& filename):
Component(CLASS)
{
init(filename);
}
void StaticMeshRenderer::init(const StaticMeshData& meshData)
{
boundingBox = meshData.boundingBox;
material = meshData.material;
indexCount = meshData.indexCount;
indexSize = meshData.indexSize;
indexBuffer = meshData.indexBuffer;
vertexBuffer = meshData.vertexBuffer;
}
void StaticMeshRenderer::init(const std::string& filename)
{
init(*engine->getCache().getStaticMeshData(filename));
}
void StaticMeshRenderer::draw(const Matrix4<float>& transformMatrix,
float opacity,
const Matrix4<float>& renderViewProjection,
bool wireframe)
{
Component::draw(transformMatrix,
opacity,
renderViewProjection,
wireframe);
Matrix4<float> modelViewProj = renderViewProjection * transformMatrix;
float colorVector[] = {material->diffuseColor.normR(), material->diffuseColor.normG(), material->diffuseColor.normB(), material->diffuseColor.normA() * opacity * material->opacity};
std::vector<std::vector<float>> fragmentShaderConstants(1);
fragmentShaderConstants[0] = {std::begin(colorVector), std::end(colorVector)};
std::vector<std::vector<float>> vertexShaderConstants(1);
vertexShaderConstants[0] = {std::begin(modelViewProj.m), std::end(modelViewProj.m)};
std::vector<uintptr_t> textures;
for (const std::shared_ptr<graphics::Texture>& texture : material->textures)
textures.push_back(texture ? texture->getResource() : 0);
engine->getRenderer()->setCullMode(material->cullMode);
engine->getRenderer()->setPipelineState(material->blendState->getResource(),
material->shader->getResource());
engine->getRenderer()->setShaderConstants(fragmentShaderConstants,
vertexShaderConstants);
engine->getRenderer()->setTextures(textures);
engine->getRenderer()->draw(indexBuffer->getResource(),
indexCount,
indexSize,
vertexBuffer->getResource(),
graphics::DrawMode::TRIANGLE_LIST,
0);
}
} // namespace scene
} // namespace ouzel
<commit_msg>Use 16-bit index buffer for static meshes if 32-bits are not needed<commit_after>// Copyright 2015-2018 Elviss Strazdins. All rights reserved.
#include <limits>
#include "StaticMeshRenderer.hpp"
#include "core/Engine.hpp"
#include "utils/Utils.hpp"
namespace ouzel
{
namespace scene
{
StaticMeshData::StaticMeshData(Box3<float> initBoundingBox,
const std::vector<uint32_t> indices,
const std::vector<graphics::Vertex>& vertices,
const std::shared_ptr<graphics::Material>& initMaterial):
boundingBox(initBoundingBox),
material(initMaterial)
{
indexCount = static_cast<uint32_t>(indices.size());
indexSize = sizeof(uint16_t);
for (uint32_t index : indices)
if (index > std::numeric_limits<uint16_t>::max())
{
indexSize = sizeof(uint32_t);
break;
}
if (indexSize == sizeof(uint16_t))
{
std::vector<uint16_t> convertedIndices;
convertedIndices.reserve(indices.size());
for (uint32_t index : indices)
convertedIndices.push_back(static_cast<uint16_t>(index));
indexBuffer = std::make_shared<graphics::Buffer>(*engine->getRenderer(),
graphics::Buffer::Usage::INDEX, 0,
convertedIndices.data(),
static_cast<uint32_t>(getVectorSize(convertedIndices)));
}
else if (indexSize == sizeof(uint32_t))
indexBuffer = std::make_shared<graphics::Buffer>(*engine->getRenderer(),
graphics::Buffer::Usage::INDEX, 0,
indices.data(),
static_cast<uint32_t>(getVectorSize(indices)));
vertexBuffer = std::make_shared<graphics::Buffer>(*engine->getRenderer(),
graphics::Buffer::Usage::VERTEX, 0,
vertices.data(),
static_cast<uint32_t>(getVectorSize(vertices)));
}
StaticMeshRenderer::StaticMeshRenderer():
Component(CLASS)
{
}
StaticMeshRenderer::StaticMeshRenderer(const StaticMeshData& meshData):
Component(CLASS)
{
init(meshData);
}
StaticMeshRenderer::StaticMeshRenderer(const std::string& filename):
Component(CLASS)
{
init(filename);
}
void StaticMeshRenderer::init(const StaticMeshData& meshData)
{
boundingBox = meshData.boundingBox;
material = meshData.material;
indexCount = meshData.indexCount;
indexSize = meshData.indexSize;
indexBuffer = meshData.indexBuffer;
vertexBuffer = meshData.vertexBuffer;
}
void StaticMeshRenderer::init(const std::string& filename)
{
init(*engine->getCache().getStaticMeshData(filename));
}
void StaticMeshRenderer::draw(const Matrix4<float>& transformMatrix,
float opacity,
const Matrix4<float>& renderViewProjection,
bool wireframe)
{
Component::draw(transformMatrix,
opacity,
renderViewProjection,
wireframe);
Matrix4<float> modelViewProj = renderViewProjection * transformMatrix;
float colorVector[] = {material->diffuseColor.normR(), material->diffuseColor.normG(), material->diffuseColor.normB(), material->diffuseColor.normA() * opacity * material->opacity};
std::vector<std::vector<float>> fragmentShaderConstants(1);
fragmentShaderConstants[0] = {std::begin(colorVector), std::end(colorVector)};
std::vector<std::vector<float>> vertexShaderConstants(1);
vertexShaderConstants[0] = {std::begin(modelViewProj.m), std::end(modelViewProj.m)};
std::vector<uintptr_t> textures;
for (const std::shared_ptr<graphics::Texture>& texture : material->textures)
textures.push_back(texture ? texture->getResource() : 0);
engine->getRenderer()->setCullMode(material->cullMode);
engine->getRenderer()->setPipelineState(material->blendState->getResource(),
material->shader->getResource());
engine->getRenderer()->setShaderConstants(fragmentShaderConstants,
vertexShaderConstants);
engine->getRenderer()->setTextures(textures);
engine->getRenderer()->draw(indexBuffer->getResource(),
indexCount,
indexSize,
vertexBuffer->getResource(),
graphics::DrawMode::TRIANGLE_LIST,
0);
}
} // namespace scene
} // namespace ouzel
<|endoftext|> |
<commit_before>#include <tests/Base.hh>
#include <cmath>
#include <aleph/geometry/CoverTree.hh>
using namespace aleph::geometry;
template <class T> struct SimpleMetric
{
T operator()( T a, T b )
{
return std::abs( a - b );
}
};
template <class T> void testSimple()
{
ALEPH_TEST_BEGIN( "Simple" );
CoverTree<T,
SimpleMetric<T> > ct;
ct.insert( 7 );
ct.insert( 13 );
ct.insert( 10 );
ct.insert( 8 );
ct.insert( 9 );
ct.insert( 11 );
ct.insert( 12 );
ct.print( std::cerr );
ALEPH_ASSERT_THROW( ct.checkLevelInvariant() );
ALEPH_ASSERT_THROW( ct.checkCoveringInvariant() );
ALEPH_ASSERT_THROW( ct.checkSeparatingInvariant() );
ALEPH_TEST_END();
}
template <class T> void testSimplePermutations()
{
ALEPH_TEST_BEGIN( "Simple (using permutations)" );
std::vector<T> data = {7,8,9,10,11,12,13};
do
{
CoverTree<T,
SimpleMetric<T> > ct;
// Debug output ----------------------------------------------------
std::cerr << "Permutation: ";
for( auto&& x : data )
std::cerr << x << " ";
std::cerr << "\n";
// Check validity of tree ------------------------------------------
for( auto&& x : data )
ct.insert( x );
ALEPH_ASSERT_THROW( ct.checkLevelInvariant() );
ALEPH_ASSERT_THROW( ct.checkCoveringInvariant() );
ALEPH_ASSERT_THROW( ct.checkSeparatingInvariant() );
}
while( std::next_permutation( data.begin(), data.end() ) );
ALEPH_TEST_END();
}
int main( int, char** )
{
testSimple<double>();
testSimple<float> ();
testSimplePermutations<double>();
testSimplePermutations<float> ();
}
<commit_msg>Added 2D test case for cover tree<commit_after>#include <tests/Base.hh>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cmath>
#include <aleph/geometry/CoverTree.hh>
using namespace aleph::geometry;
template <class T> struct SimpleMetric
{
T operator()( T a, T b )
{
return std::abs( a - b );
}
};
template <class T> void testSimple()
{
ALEPH_TEST_BEGIN( "Simple" );
CoverTree<T,
SimpleMetric<T> > ct;
ct.insert( 7 );
ct.insert( 13 );
ct.insert( 10 );
ct.insert( 8 );
ct.insert( 9 );
ct.insert( 11 );
ct.insert( 12 );
ct.print( std::cerr );
ALEPH_ASSERT_THROW( ct.checkLevelInvariant() );
ALEPH_ASSERT_THROW( ct.checkCoveringInvariant() );
ALEPH_ASSERT_THROW( ct.checkSeparatingInvariant() );
ALEPH_TEST_END();
}
template <class T> void testSimplePermutations()
{
ALEPH_TEST_BEGIN( "Simple (using permutations)" );
std::vector<T> data = {7,8,9,10,11,12,13};
do
{
CoverTree<T,
SimpleMetric<T> > ct;
// Debug output ----------------------------------------------------
std::cerr << "Permutation: ";
for( auto&& x : data )
std::cerr << x << " ";
std::cerr << "\n";
// Check validity of tree ------------------------------------------
for( auto&& x : data )
ct.insert( x );
ALEPH_ASSERT_THROW( ct.checkLevelInvariant() );
ALEPH_ASSERT_THROW( ct.checkCoveringInvariant() );
ALEPH_ASSERT_THROW( ct.checkSeparatingInvariant() );
}
while( std::next_permutation( data.begin(), data.end() ) );
ALEPH_TEST_END();
}
template <class T> struct Point
{
T x;
T y;
};
template <class T> std::ostream& operator<<( std::ostream& o, const Point<T>& p )
{
o << p.x << "," << p.y << "\n";
return o;
}
template <class T> struct EuclideanMetric
{
T operator()( Point<T> a, Point<T> b )
{
return std::sqrt( std::pow( a.x - b.x, T(2) ) + std::pow( a.y - b.y, T(2) ) );
}
};
template <class T> void test2D()
{
ALEPH_TEST_BEGIN( "2D" );
using Point = Point<T>;
using Metric = EuclideanMetric<T>;
using CoverTree = CoverTree<Point, Metric>;
CoverTree ct;
std::ifstream in( CMAKE_SOURCE_DIR + std::string( "/tests/input/Cover_tree_simple.txt" ) );
ALEPH_ASSERT_THROW( in );
std::vector<Point> points;
std::string line;
while( std::getline( in, line ) )
{
std::stringstream converter( line );
T x = T();
T y = T();
converter >> x
>> y;
ALEPH_ASSERT_THROW( not converter.fail() );
points.push_back( {x,y} );
}
ALEPH_ASSERT_EQUAL( points.size(), 15 );
for( auto&& p : points )
ct.insert( p );
ct.print( std::cerr );
ALEPH_ASSERT_THROW( ct.isValid() );
ALEPH_TEST_END();
}
int main( int, char** )
{
testSimple<double>();
testSimple<float> ();
testSimplePermutations<double>();
testSimplePermutations<float> ();
test2D<double>();
test2D<float> ();
}
<|endoftext|> |
<commit_before>/*
* Copyright 2015 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
#include "stdafx.h"
#include "ExploreClient.h"
#include "BadRequestException.h"
#include "CdapException.h"
using namespace Cask::CdapOdbc;
namespace {
web::json::value toJson(const utility::string_t* str) {
return (str != nullptr) ? web::json::value::string(*str) : web::json::value::null();
}
utility::string_t toUriPath(const utility::string_t* str) {
if (str == nullptr) {
return L"null";
} else {
return *str;
}
}
}
web::json::value Cask::CdapOdbc::ExploreClient::doRequest(web::http::http_request& request, std::int64_t* sizeInBytes) {
#ifdef TRACE_REQUESTS
TRACE(L"REQUEST: %s\n", request.to_string().c_str());
#endif
auto requestTask = this->httpClient->request(request);
{
PROFILE_FUNCTION(TIMER_QUERY);
requestTask.wait();
}
auto response = requestTask.get();
#ifdef TRACE_REQUESTS
TRACE(L"RESPONSE: %s\n", response.to_string().c_str());
#endif
// TRACE(L"RESPONSE SIZE: %d\n", response.headers().content_length());
if (response.status_code() == web::http::status_codes::OK) {
auto jsonTask = response.extract_json();
{
PROFILE_FUNCTION(TIMER_PARSING);
jsonTask.wait();
}
if (sizeInBytes) {
*sizeInBytes = response.headers().content_length();
}
return jsonTask.get();
} else if (response.status_code() == web::http::status_codes::BadRequest) {
auto errorTask = response.extract_utf16string();
errorTask.wait();
throw BadRequestException(errorTask.get());
} else {
throw CdapException(L"Cannot get the response.");
}
}
web::json::value Cask::CdapOdbc::ExploreClient::doRequest(web::http::method mhd, const utility::string_t& path, const web::json::value* body /* = nullptr */, std::int64_t* sizeInBytes /* = nullptr */) {
web::http::uri_builder requestUri;
web::http::http_request request(mhd);
if (body) {
request.set_body(*body);
}
request.set_request_uri(requestUri.append_path(path).to_uri());
if (this->authToken.size() > 0) {
request.headers().add(web::http::header_names::authorization, L"Bearer " + this->authToken);
}
return this->doRequest(request, sizeInBytes);
}
Cask::CdapOdbc::ExploreClient::ExploreClient(const web::http::uri& baseUri, const std::wstring& namespace_, const SecureString& authToken)
: namespace_(namespace_)
, authToken(authToken) {
this->httpClient = std::make_unique<web::http::client::http_client>(baseUri);
}
bool Cask::CdapOdbc::ExploreClient::isAvailable() {
try {
return (this->doRequest(web::http::methods::GET, L"explore/status").at(L"status").as_string() == L"OK");
} catch (std::exception&) {
return false;
}
}
QueryStatus Cask::CdapOdbc::ExploreClient::getQueryStatus(const QueryHandle& handle) {
auto value = this->doRequest(web::http::methods::GET, L"data/explore/queries/" + handle + L"/status");
return QueryStatus(value);
}
std::vector<ColumnDesc> Cask::CdapOdbc::ExploreClient::getQuerySchema(const QueryHandle& handle) {
std::vector<ColumnDesc> result;
auto value = this->doRequest(web::http::methods::GET, L"data/explore/queries/" + handle + L"/schema");
auto columns = value.as_array();
for (auto& item : columns) {
result.push_back(ColumnDesc(item));
}
return result;
}
QueryResult Cask::CdapOdbc::ExploreClient::getQueryResult(const QueryHandle& handle, int rows) {
web::json::value size;
std::int64_t sizeInBytes = 0L;
size[L"size"] = web::json::value::number(rows);
auto value = this->doRequest(web::http::methods::POST, L"data/explore/queries/" + handle + L"/next", &size, &sizeInBytes);
return QueryResult(value, sizeInBytes);
}
void Cask::CdapOdbc::ExploreClient::closeQuery(const QueryHandle& handle) {
this->doRequest(web::http::methods::DEL, L"data/explore/queries/" + handle);
}
QueryHandle Cask::CdapOdbc::ExploreClient::getCatalogs() {
return this->doRequest(web::http::methods::POST, L"data/explore/jdbc/catalogs").at(L"handle").as_string();
}
QueryHandle Cask::CdapOdbc::ExploreClient::getSchemas(const std::wstring* catalog, const std::wstring* schemaPattern) {
web::json::value schemaArgs;
schemaArgs[L"catalog"] = toJson(catalog);
schemaArgs[L"schemaPattern"] = toJson(schemaPattern);
auto value = this->doRequest(web::http::methods::POST, L"namespaces/" + toUriPath(schemaPattern) + L"/data/explore/jdbc/schemas", &schemaArgs);
return value.at(L"handle").as_string();
}
QueryHandle Cask::CdapOdbc::ExploreClient::getTables(const std::wstring* catalog, const std::wstring* schemaPattern, const std::wstring* tableNamePattern, const std::vector<std::wstring>* tableTypes) {
web::json::value tablesArgs;
tablesArgs[L"catalog"] = toJson(catalog);
tablesArgs[L"schemaPattern"] = toJson(schemaPattern);
tablesArgs[L"tableNamePattern"] = toJson(tableNamePattern);
if (tableTypes) {
std::vector<web::json::value> tableTypeArgs;
for (auto& item : *tableTypes) {
tableTypeArgs.push_back(web::json::value::string(item));
}
tablesArgs[L"tableTypes"] = web::json::value::array(tableTypeArgs);
} else {
tablesArgs[L"tableTypes"] = web::json::value::null();
}
auto value = this->doRequest(web::http::methods::POST, L"namespaces/" + toUriPath(schemaPattern) + L"/data/explore/jdbc/tables", &tablesArgs);
return value.at(L"handle").as_string();
}
QueryResult Cask::CdapOdbc::ExploreClient::getStreams() {
auto value = this->doRequest(web::http::methods::GET, L"namespaces/" + this->namespace_ + L"/streams");
return QueryResult(value);
}
QueryResult Cask::CdapOdbc::ExploreClient::getDatasets() {
auto value = this->doRequest(web::http::methods::GET, L"namespaces/" + this->namespace_ + L"/data/datasets");
return QueryResult(value);
}
QueryResult Cask::CdapOdbc::ExploreClient::getStreamFields(const std::wstring& streamName) {
auto value = this->doRequest(web::http::methods::GET, L"namespaces/" + this->namespace_ + L"/streams/" + streamName);
return QueryResult(value);
}
QueryResult Cask::CdapOdbc::ExploreClient::getDatasetFields(const std::wstring& datasetName) {
auto value = this->doRequest(web::http::methods::GET, L"namespaces/" + this->namespace_ + L"/data/datasets/" + datasetName);
return QueryResult(value);
}
QueryHandle Cask::CdapOdbc::ExploreClient::execute(const std::wstring& statement) {
web::json::value query;
std::wstring stmt_preproc = statement;
std::wstring::size_type found;
/* Remove 'HAVING (COUNT(1) > 0) clause' */
found = stmt_preproc.find(L"HAVING (COUNT(1) > 0)", 0);
if (found != std::wstring::npos) {
stmt_preproc.erase(found, 21);
}
query[L"query"] = toJson(&stmt_preproc);
auto value = this->doRequest(web::http::methods::POST, L"namespaces/" + this->namespace_ + L"/data/explore/queries", &query);
return value.at(L"handle").as_string();
}
<commit_msg>Handling of unathorized response.<commit_after>/*
* Copyright 2015 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
#include "stdafx.h"
#include "ExploreClient.h"
#include "BadRequestException.h"
#include "CdapException.h"
#include "CommunicationLinkFailure.h"
using namespace Cask::CdapOdbc;
namespace {
web::json::value toJson(const utility::string_t* str) {
return (str != nullptr) ? web::json::value::string(*str) : web::json::value::null();
}
utility::string_t toUriPath(const utility::string_t* str) {
if (str == nullptr) {
return L"null";
} else {
return *str;
}
}
}
web::json::value Cask::CdapOdbc::ExploreClient::doRequest(web::http::http_request& request, std::int64_t* sizeInBytes) {
#ifdef TRACE_REQUESTS
TRACE(L"REQUEST: %s\n", request.to_string().c_str());
#endif
auto requestTask = this->httpClient->request(request);
{
PROFILE_FUNCTION(TIMER_QUERY);
requestTask.wait();
}
auto response = requestTask.get();
#ifdef TRACE_REQUESTS
TRACE(L"RESPONSE: %s\n", response.to_string().c_str());
#endif
// TRACE(L"RESPONSE SIZE: %d\n", response.headers().content_length());
if (response.status_code() == web::http::status_codes::OK) {
auto jsonTask = response.extract_json();
{
PROFILE_FUNCTION(TIMER_PARSING);
jsonTask.wait();
}
if (sizeInBytes) {
*sizeInBytes = response.headers().content_length();
}
return jsonTask.get();
} else if (response.status_code() == web::http::status_codes::BadRequest) {
auto errorTask = response.extract_utf16string();
errorTask.wait();
throw BadRequestException(errorTask.get());
} else if (response.status_code() == web::http::status_codes::Unauthorized) {
throw CdapException(L"Wrong authentication token.");
} else {
throw CommunicationLinkFailure();
}
}
web::json::value Cask::CdapOdbc::ExploreClient::doRequest(web::http::method mhd, const utility::string_t& path, const web::json::value* body /* = nullptr */, std::int64_t* sizeInBytes /* = nullptr */) {
web::http::uri_builder requestUri;
web::http::http_request request(mhd);
if (body) {
request.set_body(*body);
}
request.set_request_uri(requestUri.append_path(path).to_uri());
if (this->authToken.size() > 0) {
request.headers().add(web::http::header_names::authorization, L"Bearer " + this->authToken);
}
return this->doRequest(request, sizeInBytes);
}
Cask::CdapOdbc::ExploreClient::ExploreClient(const web::http::uri& baseUri, const std::wstring& namespace_, const SecureString& authToken)
: namespace_(namespace_)
, authToken(authToken) {
this->httpClient = std::make_unique<web::http::client::http_client>(baseUri);
}
bool Cask::CdapOdbc::ExploreClient::isAvailable() {
return (this->doRequest(web::http::methods::GET, L"explore/status").at(L"status").as_string() == L"OK");
}
QueryStatus Cask::CdapOdbc::ExploreClient::getQueryStatus(const QueryHandle& handle) {
auto value = this->doRequest(web::http::methods::GET, L"data/explore/queries/" + handle + L"/status");
return QueryStatus(value);
}
std::vector<ColumnDesc> Cask::CdapOdbc::ExploreClient::getQuerySchema(const QueryHandle& handle) {
std::vector<ColumnDesc> result;
auto value = this->doRequest(web::http::methods::GET, L"data/explore/queries/" + handle + L"/schema");
auto columns = value.as_array();
for (auto& item : columns) {
result.push_back(ColumnDesc(item));
}
return result;
}
QueryResult Cask::CdapOdbc::ExploreClient::getQueryResult(const QueryHandle& handle, int rows) {
web::json::value size;
std::int64_t sizeInBytes = 0L;
size[L"size"] = web::json::value::number(rows);
auto value = this->doRequest(web::http::methods::POST, L"data/explore/queries/" + handle + L"/next", &size, &sizeInBytes);
return QueryResult(value, sizeInBytes);
}
void Cask::CdapOdbc::ExploreClient::closeQuery(const QueryHandle& handle) {
this->doRequest(web::http::methods::DEL, L"data/explore/queries/" + handle);
}
QueryHandle Cask::CdapOdbc::ExploreClient::getCatalogs() {
return this->doRequest(web::http::methods::POST, L"data/explore/jdbc/catalogs").at(L"handle").as_string();
}
QueryHandle Cask::CdapOdbc::ExploreClient::getSchemas(const std::wstring* catalog, const std::wstring* schemaPattern) {
web::json::value schemaArgs;
schemaArgs[L"catalog"] = toJson(catalog);
schemaArgs[L"schemaPattern"] = toJson(schemaPattern);
auto value = this->doRequest(web::http::methods::POST, L"namespaces/" + toUriPath(schemaPattern) + L"/data/explore/jdbc/schemas", &schemaArgs);
return value.at(L"handle").as_string();
}
QueryHandle Cask::CdapOdbc::ExploreClient::getTables(const std::wstring* catalog, const std::wstring* schemaPattern, const std::wstring* tableNamePattern, const std::vector<std::wstring>* tableTypes) {
web::json::value tablesArgs;
tablesArgs[L"catalog"] = toJson(catalog);
tablesArgs[L"schemaPattern"] = toJson(schemaPattern);
tablesArgs[L"tableNamePattern"] = toJson(tableNamePattern);
if (tableTypes) {
std::vector<web::json::value> tableTypeArgs;
for (auto& item : *tableTypes) {
tableTypeArgs.push_back(web::json::value::string(item));
}
tablesArgs[L"tableTypes"] = web::json::value::array(tableTypeArgs);
} else {
tablesArgs[L"tableTypes"] = web::json::value::null();
}
auto value = this->doRequest(web::http::methods::POST, L"namespaces/" + toUriPath(schemaPattern) + L"/data/explore/jdbc/tables", &tablesArgs);
return value.at(L"handle").as_string();
}
QueryResult Cask::CdapOdbc::ExploreClient::getStreams() {
auto value = this->doRequest(web::http::methods::GET, L"namespaces/" + this->namespace_ + L"/streams");
return QueryResult(value);
}
QueryResult Cask::CdapOdbc::ExploreClient::getDatasets() {
auto value = this->doRequest(web::http::methods::GET, L"namespaces/" + this->namespace_ + L"/data/datasets");
return QueryResult(value);
}
QueryResult Cask::CdapOdbc::ExploreClient::getStreamFields(const std::wstring& streamName) {
auto value = this->doRequest(web::http::methods::GET, L"namespaces/" + this->namespace_ + L"/streams/" + streamName);
return QueryResult(value);
}
QueryResult Cask::CdapOdbc::ExploreClient::getDatasetFields(const std::wstring& datasetName) {
auto value = this->doRequest(web::http::methods::GET, L"namespaces/" + this->namespace_ + L"/data/datasets/" + datasetName);
return QueryResult(value);
}
QueryHandle Cask::CdapOdbc::ExploreClient::execute(const std::wstring& statement) {
web::json::value query;
std::wstring stmt_preproc = statement;
std::wstring::size_type found;
/* Remove 'HAVING (COUNT(1) > 0) clause' */
found = stmt_preproc.find(L"HAVING (COUNT(1) > 0)", 0);
if (found != std::wstring::npos) {
stmt_preproc.erase(found, 21);
}
query[L"query"] = toJson(&stmt_preproc);
auto value = this->doRequest(web::http::methods::POST, L"namespaces/" + this->namespace_ + L"/data/explore/queries", &query);
return value.at(L"handle").as_string();
}
<|endoftext|> |
<commit_before>/* Copyright 2021, The TensorFlow Federated Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
==============================================================================*/
#include "tensorflow_federated/cc/core/impl/executors/executor_service.h"
#include <memory>
#include <tuple>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/match.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "tensorflow_federated/cc/core/impl/executors/status_macros.h"
#include "tensorflow_federated/proto/v0/executor.proto.h"
namespace tensorflow_federated {
absl::StatusOr<ValueId> ParseRef(const v0::ValueRef& value_ref_pb) {
ValueId value_id;
if (absl::SimpleAtoi(value_ref_pb.id(), &value_id)) {
return value_id;
}
return absl::InvalidArgumentError(absl::StrCat(
"Could not parse ValueRef from string. Incoming id:", value_ref_pb.id()));
}
absl::StatusOr<std::pair<std::shared_ptr<Executor>, int>>
ExecutorService::RequireExecutor_(std::string method_name) {
absl::ReaderMutexLock reader_lock(&executor_mutex_);
if (executor_and_generation_.first == nullptr) {
return grpc::Status(
grpc::StatusCode::UNAVAILABLE,
absl::StrCat("Attempted to call ExecutorService::", method_name,
" before setting cardinalities."));
}
return executor_and_generation_;
}
ExecutorService::RemoteValueId ExecutorService::CreateRemoteValue_(
ValueId embedded_value_id, int executor_generation) {
return absl::StrCat(embedded_value_id, "-", executor_generation);
}
absl::Status MalformattedValueStatus(absl::string_view bad_id) {
return absl::InvalidArgumentError(
absl::StrCat("Remote value ID ", bad_id,
" malformed: expected to be of the form a-b, where a and "
"b are both ints."));
}
absl::Status ExecutorService::EnsureGeneration_(int reference_generation,
int expected_generation) {
if (reference_generation != expected_generation) {
return absl::InvalidArgumentError(absl::StrCat(
"Remote value refers to a non-live executor generation. "
"Current generation is: ",
expected_generation,
"remote valuerefers to generation: ", reference_generation));
}
return absl::OkStatus();
}
absl::StatusOr<ValueId> ExecutorService::ResolveRemoteValue_(
const v0::ValueRef& remote_value_ref, int expected_generation) {
// Incoming ref should have ID of the form a-b, where a is a
// uint64 and b s an int. a represents the ValueId in the
// service's executor, b represents the generation of this executor.
std::vector<absl::string_view> id_and_generation =
absl::StrSplit(remote_value_ref.id(), '-');
if (id_and_generation.size() != 2) {
return MalformattedValueStatus(remote_value_ref.id());
}
int reference_generation;
if (!absl::SimpleAtoi(id_and_generation[1], &reference_generation)) {
return MalformattedValueStatus(remote_value_ref.id());
}
TFF_TRY(EnsureGeneration_(reference_generation, expected_generation));
ValueId embedded_value_id;
if (!absl::SimpleAtoi(id_and_generation[0], &embedded_value_id)) {
return MalformattedValueStatus(remote_value_ref.id());
}
return embedded_value_id;
}
grpc::Status ExecutorService::CreateValue(grpc::ServerContext* context,
const v0::CreateValueRequest* request,
v0::CreateValueResponse* response) {
std::pair<std::shared_ptr<Executor>, int> executor_and_generation;
auto [live_executor, used_executor_generation] =
TFF_TRY(RequireExecutor_("CreateValue"));
OwnedValueId owned_value_id =
TFF_TRY(live_executor->CreateValue(request->value()));
response->mutable_value_ref()->mutable_id()->assign(
CreateRemoteValue_(owned_value_id.ref(), used_executor_generation));
// We must call forget on the embedded id to prevent the destructor from
// running when the variable goes out of scope. Similar considerations apply
// to the reset of the Create methods below.
owned_value_id.forget();
return grpc::Status::OK;
}
grpc::Status ExecutorService::CreateCall(grpc::ServerContext* context,
const v0::CreateCallRequest* request,
v0::CreateCallResponse* response) {
std::pair<std::shared_ptr<Executor>, int> executor_and_generation;
auto [live_executor, used_executor_generation] =
TFF_TRY(RequireExecutor_("CreateCall"));
ValueId embedded_fn = TFF_TRY(
ResolveRemoteValue_(request->function_ref(), used_executor_generation));
std::optional<ValueId> embedded_arg;
if (request->has_argument_ref()) {
// Callers should avoid setting the argument ref for invocation of a no-arg
// fn.
embedded_arg = TFF_TRY(
ResolveRemoteValue_(request->argument_ref(), used_executor_generation));
}
OwnedValueId called_fn =
TFF_TRY(live_executor->CreateCall(embedded_fn, embedded_arg));
response->mutable_value_ref()->mutable_id()->assign(
CreateRemoteValue_(called_fn.ref(), used_executor_generation));
// We must prevent this destructor from running similarly to CreateValue.
called_fn.forget();
return grpc::Status::OK;
}
grpc::Status ExecutorService::CreateStruct(
grpc::ServerContext* context, const v0::CreateStructRequest* request,
v0::CreateStructResponse* response) {
auto [live_executor, used_executor_generation] =
TFF_TRY(RequireExecutor_("CreateStruct"));
std::vector<ValueId> requested_ids;
requested_ids.reserve(request->element().size());
for (const v0::CreateStructRequest::Element& elem : request->element()) {
requested_ids.emplace_back(TFF_TRY(
ResolveRemoteValue_(elem.value_ref(), used_executor_generation)));
}
OwnedValueId created_struct =
TFF_TRY(live_executor->CreateStruct(requested_ids));
response->mutable_value_ref()->mutable_id()->assign(
CreateRemoteValue_(created_struct.ref(), used_executor_generation));
// We must prevent this destructor from running similarly to CreateValue.
created_struct.forget();
return grpc::Status::OK;
}
grpc::Status ExecutorService::CreateSelection(
grpc::ServerContext* context, const v0::CreateSelectionRequest* request,
v0::CreateSelectionResponse* response) {
auto [live_executor, used_executor_generation] =
TFF_TRY(RequireExecutor_("CreateSelection"));
ValueId selection_source = TFF_TRY(
ResolveRemoteValue_(request->source_ref(), used_executor_generation));
OwnedValueId selected_element = TFF_TRY(
live_executor->CreateSelection(selection_source, request->index()));
response->mutable_value_ref()->mutable_id()->assign(
CreateRemoteValue_(selected_element.ref(), used_executor_generation));
// We must prevent this destructor from running similarly to CreateValue.
selected_element.forget();
return grpc::Status::OK;
}
grpc::Status ExecutorService::Compute(grpc::ServerContext* context,
const v0::ComputeRequest* request,
v0::ComputeResponse* response) {
auto [live_executor, used_executor_generation] =
TFF_TRY(RequireExecutor_("Compute"));
ValueId requested_value = TFF_TRY(
ResolveRemoteValue_(request->value_ref(), used_executor_generation));
absl::Status materialize_status =
live_executor->Materialize(requested_value, response->mutable_value());
if (!materialize_status.ok()) {
return materialize_status;
}
return grpc::Status::OK;
}
grpc::Status ExecutorService::SetCardinalities(
grpc::ServerContext* context, const v0::SetCardinalitiesRequest* request,
v0::SetCardinalitiesResponse* response) {
CardinalityMap cardinality_map;
for (const auto& cardinality : request->cardinalities()) {
cardinality_map.insert(
{cardinality.placement().uri(), cardinality.cardinality()});
}
{
absl::WriterMutexLock writer_lock(&executor_mutex_);
auto new_executor = TFF_TRY(executor_factory_(cardinality_map));
int new_generation = executor_and_generation_.second + 1;
executor_and_generation_ =
std::make_pair(std::move(new_executor), new_generation);
}
return grpc::Status::OK;
}
grpc::Status ExecutorService::ClearExecutor(
grpc::ServerContext* context, const v0::ClearExecutorRequest* request,
v0::ClearExecutorResponse* response) {
{
absl::WriterMutexLock writer_lock(&executor_mutex_);
// Clearing executor should reset executor to null, but without changing the
// executor's generation; this will be incremented by SetCardinalities.
executor_and_generation_ =
std::make_pair(nullptr, executor_and_generation_.second);
}
return grpc::Status::OK;
}
grpc::Status ExecutorService::Dispose(grpc::ServerContext* context,
const v0::DisposeRequest* request,
v0::DisposeResponse* response) {
auto [live_executor, used_executor_generation] =
TFF_TRY(RequireExecutor_("Dispose"));
std::vector<ValueId> embedded_ids_to_dispose;
embedded_ids_to_dispose.reserve(request->value_ref().size());
// Filter the requested IDs to those corresponding to the currently live
// executors. Clients are free to batch these requests however they want or
// let them be called by a GC mechanism, so we do not force the client to only
// dispose of values in the live executor.
for (const v0::ValueRef& disposed_value_ref : request->value_ref()) {
absl::StatusOr<ValueId> embedded_value =
ResolveRemoteValue_(disposed_value_ref, used_executor_generation);
if (embedded_value.ok()) {
TFF_TRY(live_executor->Dispose(embedded_value.ValueOrDie()));
}
}
return grpc::Status::OK;
}
} // namespace tensorflow_federated
<commit_msg>Use TFF_TRY on final materialize in ExecutorService.<commit_after>/* Copyright 2021, The TensorFlow Federated Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
==============================================================================*/
#include "tensorflow_federated/cc/core/impl/executors/executor_service.h"
#include <memory>
#include <tuple>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/match.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "tensorflow_federated/cc/core/impl/executors/status_macros.h"
#include "tensorflow_federated/proto/v0/executor.proto.h"
namespace tensorflow_federated {
absl::StatusOr<ValueId> ParseRef(const v0::ValueRef& value_ref_pb) {
ValueId value_id;
if (absl::SimpleAtoi(value_ref_pb.id(), &value_id)) {
return value_id;
}
return absl::InvalidArgumentError(absl::StrCat(
"Could not parse ValueRef from string. Incoming id:", value_ref_pb.id()));
}
absl::StatusOr<std::pair<std::shared_ptr<Executor>, int>>
ExecutorService::RequireExecutor_(std::string method_name) {
absl::ReaderMutexLock reader_lock(&executor_mutex_);
if (executor_and_generation_.first == nullptr) {
return grpc::Status(
grpc::StatusCode::UNAVAILABLE,
absl::StrCat("Attempted to call ExecutorService::", method_name,
" before setting cardinalities."));
}
return executor_and_generation_;
}
ExecutorService::RemoteValueId ExecutorService::CreateRemoteValue_(
ValueId embedded_value_id, int executor_generation) {
return absl::StrCat(embedded_value_id, "-", executor_generation);
}
absl::Status MalformattedValueStatus(absl::string_view bad_id) {
return absl::InvalidArgumentError(
absl::StrCat("Remote value ID ", bad_id,
" malformed: expected to be of the form a-b, where a and "
"b are both ints."));
}
absl::Status ExecutorService::EnsureGeneration_(int reference_generation,
int expected_generation) {
if (reference_generation != expected_generation) {
return absl::InvalidArgumentError(absl::StrCat(
"Remote value refers to a non-live executor generation. "
"Current generation is: ",
expected_generation,
"remote valuerefers to generation: ", reference_generation));
}
return absl::OkStatus();
}
absl::StatusOr<ValueId> ExecutorService::ResolveRemoteValue_(
const v0::ValueRef& remote_value_ref, int expected_generation) {
// Incoming ref should have ID of the form a-b, where a is a
// uint64 and b s an int. a represents the ValueId in the
// service's executor, b represents the generation of this executor.
std::vector<absl::string_view> id_and_generation =
absl::StrSplit(remote_value_ref.id(), '-');
if (id_and_generation.size() != 2) {
return MalformattedValueStatus(remote_value_ref.id());
}
int reference_generation;
if (!absl::SimpleAtoi(id_and_generation[1], &reference_generation)) {
return MalformattedValueStatus(remote_value_ref.id());
}
TFF_TRY(EnsureGeneration_(reference_generation, expected_generation));
ValueId embedded_value_id;
if (!absl::SimpleAtoi(id_and_generation[0], &embedded_value_id)) {
return MalformattedValueStatus(remote_value_ref.id());
}
return embedded_value_id;
}
grpc::Status ExecutorService::CreateValue(grpc::ServerContext* context,
const v0::CreateValueRequest* request,
v0::CreateValueResponse* response) {
std::pair<std::shared_ptr<Executor>, int> executor_and_generation;
auto [live_executor, used_executor_generation] =
TFF_TRY(RequireExecutor_("CreateValue"));
OwnedValueId owned_value_id =
TFF_TRY(live_executor->CreateValue(request->value()));
response->mutable_value_ref()->mutable_id()->assign(
CreateRemoteValue_(owned_value_id.ref(), used_executor_generation));
// We must call forget on the embedded id to prevent the destructor from
// running when the variable goes out of scope. Similar considerations apply
// to the reset of the Create methods below.
owned_value_id.forget();
return grpc::Status::OK;
}
grpc::Status ExecutorService::CreateCall(grpc::ServerContext* context,
const v0::CreateCallRequest* request,
v0::CreateCallResponse* response) {
std::pair<std::shared_ptr<Executor>, int> executor_and_generation;
auto [live_executor, used_executor_generation] =
TFF_TRY(RequireExecutor_("CreateCall"));
ValueId embedded_fn = TFF_TRY(
ResolveRemoteValue_(request->function_ref(), used_executor_generation));
std::optional<ValueId> embedded_arg;
if (request->has_argument_ref()) {
// Callers should avoid setting the argument ref for invocation of a no-arg
// fn.
embedded_arg = TFF_TRY(
ResolveRemoteValue_(request->argument_ref(), used_executor_generation));
}
OwnedValueId called_fn =
TFF_TRY(live_executor->CreateCall(embedded_fn, embedded_arg));
response->mutable_value_ref()->mutable_id()->assign(
CreateRemoteValue_(called_fn.ref(), used_executor_generation));
// We must prevent this destructor from running similarly to CreateValue.
called_fn.forget();
return grpc::Status::OK;
}
grpc::Status ExecutorService::CreateStruct(
grpc::ServerContext* context, const v0::CreateStructRequest* request,
v0::CreateStructResponse* response) {
auto [live_executor, used_executor_generation] =
TFF_TRY(RequireExecutor_("CreateStruct"));
std::vector<ValueId> requested_ids;
requested_ids.reserve(request->element().size());
for (const v0::CreateStructRequest::Element& elem : request->element()) {
requested_ids.emplace_back(TFF_TRY(
ResolveRemoteValue_(elem.value_ref(), used_executor_generation)));
}
OwnedValueId created_struct =
TFF_TRY(live_executor->CreateStruct(requested_ids));
response->mutable_value_ref()->mutable_id()->assign(
CreateRemoteValue_(created_struct.ref(), used_executor_generation));
// We must prevent this destructor from running similarly to CreateValue.
created_struct.forget();
return grpc::Status::OK;
}
grpc::Status ExecutorService::CreateSelection(
grpc::ServerContext* context, const v0::CreateSelectionRequest* request,
v0::CreateSelectionResponse* response) {
auto [live_executor, used_executor_generation] =
TFF_TRY(RequireExecutor_("CreateSelection"));
ValueId selection_source = TFF_TRY(
ResolveRemoteValue_(request->source_ref(), used_executor_generation));
OwnedValueId selected_element = TFF_TRY(
live_executor->CreateSelection(selection_source, request->index()));
response->mutable_value_ref()->mutable_id()->assign(
CreateRemoteValue_(selected_element.ref(), used_executor_generation));
// We must prevent this destructor from running similarly to CreateValue.
selected_element.forget();
return grpc::Status::OK;
}
grpc::Status ExecutorService::Compute(grpc::ServerContext* context,
const v0::ComputeRequest* request,
v0::ComputeResponse* response) {
auto [live_executor, used_executor_generation] =
TFF_TRY(RequireExecutor_("Compute"));
ValueId requested_value = TFF_TRY(
ResolveRemoteValue_(request->value_ref(), used_executor_generation));
TFF_TRY(
live_executor->Materialize(requested_value, response->mutable_value()));
return grpc::Status::OK;
}
grpc::Status ExecutorService::SetCardinalities(
grpc::ServerContext* context, const v0::SetCardinalitiesRequest* request,
v0::SetCardinalitiesResponse* response) {
CardinalityMap cardinality_map;
for (const auto& cardinality : request->cardinalities()) {
cardinality_map.insert(
{cardinality.placement().uri(), cardinality.cardinality()});
}
{
absl::WriterMutexLock writer_lock(&executor_mutex_);
auto new_executor = TFF_TRY(executor_factory_(cardinality_map));
int new_generation = executor_and_generation_.second + 1;
executor_and_generation_ =
std::make_pair(std::move(new_executor), new_generation);
}
return grpc::Status::OK;
}
grpc::Status ExecutorService::ClearExecutor(
grpc::ServerContext* context, const v0::ClearExecutorRequest* request,
v0::ClearExecutorResponse* response) {
{
absl::WriterMutexLock writer_lock(&executor_mutex_);
// Clearing executor should reset executor to null, but without changing the
// executor's generation; this will be incremented by SetCardinalities.
executor_and_generation_ =
std::make_pair(nullptr, executor_and_generation_.second);
}
return grpc::Status::OK;
}
grpc::Status ExecutorService::Dispose(grpc::ServerContext* context,
const v0::DisposeRequest* request,
v0::DisposeResponse* response) {
auto [live_executor, used_executor_generation] =
TFF_TRY(RequireExecutor_("Dispose"));
std::vector<ValueId> embedded_ids_to_dispose;
embedded_ids_to_dispose.reserve(request->value_ref().size());
// Filter the requested IDs to those corresponding to the currently live
// executors. Clients are free to batch these requests however they want or
// let them be called by a GC mechanism, so we do not force the client to only
// dispose of values in the live executor.
for (const v0::ValueRef& disposed_value_ref : request->value_ref()) {
absl::StatusOr<ValueId> embedded_value =
ResolveRemoteValue_(disposed_value_ref, used_executor_generation);
if (embedded_value.ok()) {
TFF_TRY(live_executor->Dispose(embedded_value.ValueOrDie()));
}
}
return grpc::Status::OK;
}
} // namespace tensorflow_federated
<|endoftext|> |
<commit_before>/*
Resembla: Word-based Japanese similar sentence search library
https://github.com/tuem/resembla
Copyright 2017 Takashi Uemura
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef RESEMBLA_TEXT_CLASSIFICATION_FEATURE_EXTRACTOR_HPP
#define RESEMBLA_TEXT_CLASSIFICATION_FEATURE_EXTRACTOR_HPP
#include <string>
#include <unordered_map>
#include <mutex>
#include <mecab.h>
#include <libsvm/svm.h>
#include "feature_extractor.hpp"
namespace resembla {
struct TextClassificationFeatureExtractor: public FeatureExtractor::Function
{
TextClassificationFeatureExtractor(const std::string& mecab_options,
const std::string& dict_path, const std::string& model_path);
Feature::text_type operator()(const string_type& text) const;
protected:
using Dictionary = std::unordered_map<std::string, int>;
Dictionary dictionary;
std::shared_ptr<MeCab::Tagger> tagger;
mutable std::mutex mutex_tagger;
svm_model *model;
mutable std::mutex mutex_model;
std::vector<svm_node> toNodes(const string_type& x) const;
};
}
#endif
<commit_msg>delete type definition<commit_after>/*
Resembla: Word-based Japanese similar sentence search library
https://github.com/tuem/resembla
Copyright 2017 Takashi Uemura
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef RESEMBLA_TEXT_CLASSIFICATION_FEATURE_EXTRACTOR_HPP
#define RESEMBLA_TEXT_CLASSIFICATION_FEATURE_EXTRACTOR_HPP
#include <string>
#include <unordered_map>
#include <mutex>
#include <mecab.h>
#include <libsvm/svm.h>
#include "feature_extractor.hpp"
namespace resembla {
struct TextClassificationFeatureExtractor: public FeatureExtractor::Function
{
TextClassificationFeatureExtractor(const std::string& mecab_options,
const std::string& dict_path, const std::string& model_path);
Feature::text_type operator()(const string_type& text) const;
protected:
std::unordered_map<std::string, int> dictionary;
std::shared_ptr<MeCab::Tagger> tagger;
mutable std::mutex mutex_tagger;
svm_model *model;
mutable std::mutex mutex_model;
std::vector<svm_node> toNodes(const string_type& x) const;
};
}
#endif
<|endoftext|> |
<commit_before>//===----------------- lib/Jit/options.cpp ----------------------*- C++ -*-===//
//
// LLILC
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Definition of the Options class that encapsulates JIT options
/// extracted from CoreCLR config values.
///
//===----------------------------------------------------------------------===//
#include "earlyincludes.h"
#include "global.h"
#include "jitpch.h"
#include "LLILCJit.h"
#include "jitoptions.h"
// Define a macro for cross-platform UTF-16 string literals.
#if defined(_MSC_VER)
#define UTF16(lit) L##lit
#else
#define UTF16(lit) u##lit
#endif
// For now we're always running as the altjit
#define ALT_JIT 1
// These are the instantiations of the static method sets in Options.h.
// This MethodSets are initialized from CLRConfig values passed through
// the corinfo.h interface.
MethodSet JitOptions::AltJitMethodSet;
MethodSet JitOptions::AltJitNgenMethodSet;
MethodSet JitOptions::ExcludeMethodSet;
MethodSet JitOptions::BreakMethodSet;
MethodSet JitOptions::MSILMethodSet;
MethodSet JitOptions::LLVMMethodSet;
MethodSet JitOptions::CodeRangeMethodSet;
template <typename UTF16CharT>
char16_t *getStringConfigValue(ICorJitInfo *CorInfo, const UTF16CharT *Name) {
static_assert(sizeof(UTF16CharT) == 2, "UTF16CharT is the wrong size!");
return (char16_t *)CorInfo->getStringConfigValue((const wchar_t *)Name);
}
template <typename UTF16CharT>
void freeStringConfigValue(ICorJitInfo *CorInfo, UTF16CharT *Value) {
static_assert(sizeof(UTF16CharT) == 2, "UTF16CharT is the wrong size!");
return CorInfo->freeStringConfigValue((wchar_t *)Value);
}
JitOptions::JitOptions(LLILCJitContext &Context) {
// Set 'IsAltJit' based on environment information.
IsAltJit = queryIsAltJit(Context);
// Set dump level for this JIT invocation.
DumpLevel = queryDumpLevel(Context);
// Set optimization level for this JIT invocation.
OptLevel = queryOptLevel(Context);
EnableOptimization = OptLevel != OptLevel::DEBUG_CODE;
// Set whether to use conservative GC.
UseConservativeGC = queryUseConservativeGC(Context);
// Set whether to insert statepoints.
DoInsertStatepoints = queryDoInsertStatepoints(Context);
DoSIMDIntrinsic = queryDoSIMDIntrinsic(Context);
// Set whether to do tail call opt.
DoTailCallOpt = queryDoTailCallOpt(Context);
LogGcInfo = queryLogGcInfo(Context);
// Set whether to insert failfast in exception handlers.
ExecuteHandlers = queryExecuteHandlers(Context);
IsExcludeMethod = queryIsExcludeMethod(Context);
IsBreakMethod = queryIsBreakMethod(Context);
IsMSILDumpMethod = queryIsMSILDumpMethod(Context);
IsLLVMDumpMethod = queryIsLLVMDumpMethod(Context);
IsCodeRangeMethod = queryIsCodeRangeMethod(Context);
if (IsAltJit) {
PreferredIntrinsicSIMDVectorLength = 0;
} else {
PreferredIntrinsicSIMDVectorLength = 32;
}
// Validate Statepoint and Conservative GC state.
assert(DoInsertStatepoints ||
UseConservativeGC && "Statepoints required for precise-GC");
}
bool JitOptions::queryDoTailCallOpt(LLILCJitContext &Context) {
return (bool)DEFAULT_TAIL_CALL_OPT;
}
bool JitOptions::queryIsAltJit(LLILCJitContext &Context) {
// Initial state is that we are not an alternative jit until proven otherwise;
bool IsAlternateJit = false;
// NDEBUG is !Debug
#if !defined(NDEBUG)
// DEBUG case
// Get/reuse method set that contains the altjit method value.
MethodSet *AltJit = nullptr;
if (Context.Flags & CORJIT_FLG_PREJIT) {
if (!AltJitNgenMethodSet.isInitialized()) {
char16_t *NgenStr =
getStringConfigValue(Context.JitInfo, UTF16("AltJitNgen"));
std::unique_ptr<std::string> NgenUtf8 = Convert::utf16ToUtf8(NgenStr);
AltJitNgenMethodSet.init(std::move(NgenUtf8));
freeStringConfigValue(Context.JitInfo, NgenStr);
}
// Set up AltJitNgen set to be used for AltJit test.
AltJit = &AltJitNgenMethodSet;
} else {
if (!AltJitMethodSet.isInitialized()) {
char16_t *JitStr = getStringConfigValue(Context.JitInfo, UTF16("AltJit"));
// Move this to the UTIL code and ifdef it for platform
std::unique_ptr<std::string> JitUtf8 = Convert::utf16ToUtf8(JitStr);
AltJitMethodSet.init(std::move(JitUtf8));
freeStringConfigValue(Context.JitInfo, JitStr);
}
// Set up AltJit set to be use for AltJit test.
AltJit = &AltJitMethodSet;
}
#ifdef ALT_JIT
const char *ClassName = nullptr;
const char *MethodName = nullptr;
MethodName =
Context.JitInfo->getMethodName(Context.MethodInfo->ftn, &ClassName);
IsAlternateJit =
AltJit->contains(MethodName, ClassName, Context.MethodInfo->args.pSig);
#endif // ALT_JIT
#else
if (Context.Flags & CORJIT_FLG_PREJIT) {
char16_t *NgenStr =
getStringConfigValue(Context.JitInfo, UTF16("AltJitNgen"));
std::unique_ptr<std::string> NgenUtf8 = Convert::utf16ToUtf8(NgenStr);
if (NgenUtf8->compare("*") == 0) {
IsAlternateJit = true;
}
} else {
char16_t *JitStr = getStringConfigValue(Context.JitInfo, UTF16("AltJit"));
std::unique_ptr<std::string> JitUtf8 = Convert::utf16ToUtf8(JitStr);
if (JitUtf8->compare("*") == 0) {
IsAlternateJit = true;
}
}
#endif
return IsAlternateJit;
}
::DumpLevel JitOptions::queryDumpLevel(LLILCJitContext &Context) {
::DumpLevel JitDumpLevel = ::DumpLevel::NODUMP;
char16_t *LevelWStr =
getStringConfigValue(Context.JitInfo, UTF16("DUMPLLVMIR"));
if (LevelWStr) {
std::unique_ptr<std::string> Level = Convert::utf16ToUtf8(LevelWStr);
std::transform(Level->begin(), Level->end(), Level->begin(), ::toupper);
if (Level->compare("VERBOSE") == 0) {
JitDumpLevel = ::DumpLevel::VERBOSE;
} else if (Level->compare("SUMMARY") == 0) {
JitDumpLevel = ::DumpLevel::SUMMARY;
}
}
return JitDumpLevel;
}
bool JitOptions::queryIsExcludeMethod(LLILCJitContext &JitContext) {
return queryMethodSet(JitContext, ExcludeMethodSet,
(const char16_t *)UTF16("AltJitExclude"));
}
bool JitOptions::queryIsBreakMethod(LLILCJitContext &JitContext) {
return queryMethodSet(JitContext, BreakMethodSet,
(const char16_t *)UTF16("AltJitBreakAtJitStart"));
}
bool JitOptions::queryIsMSILDumpMethod(LLILCJitContext &JitContext) {
return queryMethodSet(JitContext, MSILMethodSet,
(const char16_t *)UTF16("AltJitMSILDump"));
}
bool JitOptions::queryIsLLVMDumpMethod(LLILCJitContext &JitContext) {
return queryMethodSet(JitContext, LLVMMethodSet,
(const char16_t *)UTF16("AltJitLLVMDump"));
}
bool JitOptions::queryIsCodeRangeMethod(LLILCJitContext &JitContext) {
return queryMethodSet(JitContext, CodeRangeMethodSet,
(const char16_t *)UTF16("AltJitCodeRangeDump"));
}
bool JitOptions::queryMethodSet(LLILCJitContext &JitContext, MethodSet &TheSet,
const char16_t *Name) {
if (!TheSet.isInitialized()) {
char16_t *ConfigStr = getStringConfigValue(JitContext.JitInfo, Name);
bool NeedFree = true;
if (ConfigStr == nullptr) {
ConfigStr = const_cast<char16_t *>((const char16_t *)UTF16(""));
NeedFree = false;
}
std::unique_ptr<std::string> ConfigUtf8 = Convert::utf16ToUtf8(ConfigStr);
TheSet.init(std::move(ConfigUtf8));
if (NeedFree) {
freeStringConfigValue(JitContext.JitInfo, ConfigStr);
}
}
const char *ClassName = nullptr;
const char *MethodName = nullptr;
MethodName =
JitContext.JitInfo->getMethodName(JitContext.MethodInfo->ftn, &ClassName);
bool IsInMethodSet =
TheSet.contains(MethodName, ClassName, JitContext.MethodInfo->args.pSig);
return IsInMethodSet;
}
bool JitOptions::queryNonNullNonEmpty(LLILCJitContext &JitContext,
const char16_t *Name) {
char16_t *ConfigStr = getStringConfigValue(JitContext.JitInfo, Name);
return (ConfigStr != nullptr) && (*ConfigStr != 0);
}
// Get the GC-Scheme used by the runtime -- conservative/precise
bool JitOptions::queryUseConservativeGC(LLILCJitContext &Context) {
return queryNonNullNonEmpty(Context,
(const char16_t *)UTF16("gcConservative"));
}
// Determine if GC statepoints should be inserted.
bool JitOptions::queryDoInsertStatepoints(LLILCJitContext &Context) {
return queryNonNullNonEmpty(Context,
(const char16_t *)UTF16("INSERTSTATEPOINTS"));
}
// Determine if GCInfo encoding logs should be emitted
bool JitOptions::queryLogGcInfo(LLILCJitContext &Context) {
return queryNonNullNonEmpty(Context,
(const char16_t *)UTF16("JitGCInfoLogging"));
}
// Determine if exception handlers should be executed.
bool JitOptions::queryExecuteHandlers(LLILCJitContext &Context) {
return queryNonNullNonEmpty(Context,
(const char16_t *)UTF16("ExecuteHandlers"));
}
// Determine if SIMD intrinsics should be used.
bool JitOptions::queryDoSIMDIntrinsic(LLILCJitContext &Context) {
return queryNonNullNonEmpty(Context,
(const char16_t *)UTF16("SIMDINTRINSIC"));
}
OptLevel JitOptions::queryOptLevel(LLILCJitContext &Context) {
::OptLevel JitOptLevel = ::OptLevel::BLENDED_CODE;
// Currently we only check for the debug flag but this will be extended
// to account for further opt levels as we move forward.
if ((Context.Flags & CORJIT_FLG_DEBUG_CODE) != 0) {
JitOptLevel = ::OptLevel::DEBUG_CODE;
}
return JitOptLevel;
}
JitOptions::~JitOptions() {}
<commit_msg>Fix build issue on NetBSD: Correct namespace of OptLevel::DEBUG_CODE<commit_after>//===----------------- lib/Jit/options.cpp ----------------------*- C++ -*-===//
//
// LLILC
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Definition of the Options class that encapsulates JIT options
/// extracted from CoreCLR config values.
///
//===----------------------------------------------------------------------===//
#include "earlyincludes.h"
#include "global.h"
#include "jitpch.h"
#include "LLILCJit.h"
#include "jitoptions.h"
// Define a macro for cross-platform UTF-16 string literals.
#if defined(_MSC_VER)
#define UTF16(lit) L##lit
#else
#define UTF16(lit) u##lit
#endif
// For now we're always running as the altjit
#define ALT_JIT 1
// These are the instantiations of the static method sets in Options.h.
// This MethodSets are initialized from CLRConfig values passed through
// the corinfo.h interface.
MethodSet JitOptions::AltJitMethodSet;
MethodSet JitOptions::AltJitNgenMethodSet;
MethodSet JitOptions::ExcludeMethodSet;
MethodSet JitOptions::BreakMethodSet;
MethodSet JitOptions::MSILMethodSet;
MethodSet JitOptions::LLVMMethodSet;
MethodSet JitOptions::CodeRangeMethodSet;
template <typename UTF16CharT>
char16_t *getStringConfigValue(ICorJitInfo *CorInfo, const UTF16CharT *Name) {
static_assert(sizeof(UTF16CharT) == 2, "UTF16CharT is the wrong size!");
return (char16_t *)CorInfo->getStringConfigValue((const wchar_t *)Name);
}
template <typename UTF16CharT>
void freeStringConfigValue(ICorJitInfo *CorInfo, UTF16CharT *Value) {
static_assert(sizeof(UTF16CharT) == 2, "UTF16CharT is the wrong size!");
return CorInfo->freeStringConfigValue((wchar_t *)Value);
}
JitOptions::JitOptions(LLILCJitContext &Context) {
// Set 'IsAltJit' based on environment information.
IsAltJit = queryIsAltJit(Context);
// Set dump level for this JIT invocation.
DumpLevel = queryDumpLevel(Context);
// Set optimization level for this JIT invocation.
OptLevel = queryOptLevel(Context);
EnableOptimization = OptLevel != ::OptLevel::DEBUG_CODE;
// Set whether to use conservative GC.
UseConservativeGC = queryUseConservativeGC(Context);
// Set whether to insert statepoints.
DoInsertStatepoints = queryDoInsertStatepoints(Context);
DoSIMDIntrinsic = queryDoSIMDIntrinsic(Context);
// Set whether to do tail call opt.
DoTailCallOpt = queryDoTailCallOpt(Context);
LogGcInfo = queryLogGcInfo(Context);
// Set whether to insert failfast in exception handlers.
ExecuteHandlers = queryExecuteHandlers(Context);
IsExcludeMethod = queryIsExcludeMethod(Context);
IsBreakMethod = queryIsBreakMethod(Context);
IsMSILDumpMethod = queryIsMSILDumpMethod(Context);
IsLLVMDumpMethod = queryIsLLVMDumpMethod(Context);
IsCodeRangeMethod = queryIsCodeRangeMethod(Context);
if (IsAltJit) {
PreferredIntrinsicSIMDVectorLength = 0;
} else {
PreferredIntrinsicSIMDVectorLength = 32;
}
// Validate Statepoint and Conservative GC state.
assert(DoInsertStatepoints ||
UseConservativeGC && "Statepoints required for precise-GC");
}
bool JitOptions::queryDoTailCallOpt(LLILCJitContext &Context) {
return (bool)DEFAULT_TAIL_CALL_OPT;
}
bool JitOptions::queryIsAltJit(LLILCJitContext &Context) {
// Initial state is that we are not an alternative jit until proven otherwise;
bool IsAlternateJit = false;
// NDEBUG is !Debug
#if !defined(NDEBUG)
// DEBUG case
// Get/reuse method set that contains the altjit method value.
MethodSet *AltJit = nullptr;
if (Context.Flags & CORJIT_FLG_PREJIT) {
if (!AltJitNgenMethodSet.isInitialized()) {
char16_t *NgenStr =
getStringConfigValue(Context.JitInfo, UTF16("AltJitNgen"));
std::unique_ptr<std::string> NgenUtf8 = Convert::utf16ToUtf8(NgenStr);
AltJitNgenMethodSet.init(std::move(NgenUtf8));
freeStringConfigValue(Context.JitInfo, NgenStr);
}
// Set up AltJitNgen set to be used for AltJit test.
AltJit = &AltJitNgenMethodSet;
} else {
if (!AltJitMethodSet.isInitialized()) {
char16_t *JitStr = getStringConfigValue(Context.JitInfo, UTF16("AltJit"));
// Move this to the UTIL code and ifdef it for platform
std::unique_ptr<std::string> JitUtf8 = Convert::utf16ToUtf8(JitStr);
AltJitMethodSet.init(std::move(JitUtf8));
freeStringConfigValue(Context.JitInfo, JitStr);
}
// Set up AltJit set to be use for AltJit test.
AltJit = &AltJitMethodSet;
}
#ifdef ALT_JIT
const char *ClassName = nullptr;
const char *MethodName = nullptr;
MethodName =
Context.JitInfo->getMethodName(Context.MethodInfo->ftn, &ClassName);
IsAlternateJit =
AltJit->contains(MethodName, ClassName, Context.MethodInfo->args.pSig);
#endif // ALT_JIT
#else
if (Context.Flags & CORJIT_FLG_PREJIT) {
char16_t *NgenStr =
getStringConfigValue(Context.JitInfo, UTF16("AltJitNgen"));
std::unique_ptr<std::string> NgenUtf8 = Convert::utf16ToUtf8(NgenStr);
if (NgenUtf8->compare("*") == 0) {
IsAlternateJit = true;
}
} else {
char16_t *JitStr = getStringConfigValue(Context.JitInfo, UTF16("AltJit"));
std::unique_ptr<std::string> JitUtf8 = Convert::utf16ToUtf8(JitStr);
if (JitUtf8->compare("*") == 0) {
IsAlternateJit = true;
}
}
#endif
return IsAlternateJit;
}
::DumpLevel JitOptions::queryDumpLevel(LLILCJitContext &Context) {
::DumpLevel JitDumpLevel = ::DumpLevel::NODUMP;
char16_t *LevelWStr =
getStringConfigValue(Context.JitInfo, UTF16("DUMPLLVMIR"));
if (LevelWStr) {
std::unique_ptr<std::string> Level = Convert::utf16ToUtf8(LevelWStr);
std::transform(Level->begin(), Level->end(), Level->begin(), ::toupper);
if (Level->compare("VERBOSE") == 0) {
JitDumpLevel = ::DumpLevel::VERBOSE;
} else if (Level->compare("SUMMARY") == 0) {
JitDumpLevel = ::DumpLevel::SUMMARY;
}
}
return JitDumpLevel;
}
bool JitOptions::queryIsExcludeMethod(LLILCJitContext &JitContext) {
return queryMethodSet(JitContext, ExcludeMethodSet,
(const char16_t *)UTF16("AltJitExclude"));
}
bool JitOptions::queryIsBreakMethod(LLILCJitContext &JitContext) {
return queryMethodSet(JitContext, BreakMethodSet,
(const char16_t *)UTF16("AltJitBreakAtJitStart"));
}
bool JitOptions::queryIsMSILDumpMethod(LLILCJitContext &JitContext) {
return queryMethodSet(JitContext, MSILMethodSet,
(const char16_t *)UTF16("AltJitMSILDump"));
}
bool JitOptions::queryIsLLVMDumpMethod(LLILCJitContext &JitContext) {
return queryMethodSet(JitContext, LLVMMethodSet,
(const char16_t *)UTF16("AltJitLLVMDump"));
}
bool JitOptions::queryIsCodeRangeMethod(LLILCJitContext &JitContext) {
return queryMethodSet(JitContext, CodeRangeMethodSet,
(const char16_t *)UTF16("AltJitCodeRangeDump"));
}
bool JitOptions::queryMethodSet(LLILCJitContext &JitContext, MethodSet &TheSet,
const char16_t *Name) {
if (!TheSet.isInitialized()) {
char16_t *ConfigStr = getStringConfigValue(JitContext.JitInfo, Name);
bool NeedFree = true;
if (ConfigStr == nullptr) {
ConfigStr = const_cast<char16_t *>((const char16_t *)UTF16(""));
NeedFree = false;
}
std::unique_ptr<std::string> ConfigUtf8 = Convert::utf16ToUtf8(ConfigStr);
TheSet.init(std::move(ConfigUtf8));
if (NeedFree) {
freeStringConfigValue(JitContext.JitInfo, ConfigStr);
}
}
const char *ClassName = nullptr;
const char *MethodName = nullptr;
MethodName =
JitContext.JitInfo->getMethodName(JitContext.MethodInfo->ftn, &ClassName);
bool IsInMethodSet =
TheSet.contains(MethodName, ClassName, JitContext.MethodInfo->args.pSig);
return IsInMethodSet;
}
bool JitOptions::queryNonNullNonEmpty(LLILCJitContext &JitContext,
const char16_t *Name) {
char16_t *ConfigStr = getStringConfigValue(JitContext.JitInfo, Name);
return (ConfigStr != nullptr) && (*ConfigStr != 0);
}
// Get the GC-Scheme used by the runtime -- conservative/precise
bool JitOptions::queryUseConservativeGC(LLILCJitContext &Context) {
return queryNonNullNonEmpty(Context,
(const char16_t *)UTF16("gcConservative"));
}
// Determine if GC statepoints should be inserted.
bool JitOptions::queryDoInsertStatepoints(LLILCJitContext &Context) {
return queryNonNullNonEmpty(Context,
(const char16_t *)UTF16("INSERTSTATEPOINTS"));
}
// Determine if GCInfo encoding logs should be emitted
bool JitOptions::queryLogGcInfo(LLILCJitContext &Context) {
return queryNonNullNonEmpty(Context,
(const char16_t *)UTF16("JitGCInfoLogging"));
}
// Determine if exception handlers should be executed.
bool JitOptions::queryExecuteHandlers(LLILCJitContext &Context) {
return queryNonNullNonEmpty(Context,
(const char16_t *)UTF16("ExecuteHandlers"));
}
// Determine if SIMD intrinsics should be used.
bool JitOptions::queryDoSIMDIntrinsic(LLILCJitContext &Context) {
return queryNonNullNonEmpty(Context,
(const char16_t *)UTF16("SIMDINTRINSIC"));
}
OptLevel JitOptions::queryOptLevel(LLILCJitContext &Context) {
::OptLevel JitOptLevel = ::OptLevel::BLENDED_CODE;
// Currently we only check for the debug flag but this will be extended
// to account for further opt levels as we move forward.
if ((Context.Flags & CORJIT_FLG_DEBUG_CODE) != 0) {
JitOptLevel = ::OptLevel::DEBUG_CODE;
}
return JitOptLevel;
}
JitOptions::~JitOptions() {}
<|endoftext|> |
<commit_before><commit_msg>linux: raise logging level since INFO doesn't show in Release (?)<commit_after><|endoftext|> |
<commit_before><commit_msg>Fix build.<commit_after><|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-2012 Francois Beaune, Jupiter Jazz
//
// 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 "localaccumulationframebuffer.h"
// appleseed.renderer headers.
#include "renderer/kernel/rendering/sample.h"
#include "renderer/modeling/frame/frame.h"
// appleseed.foundation headers.
#include "foundation/image/canvasproperties.h"
#include "foundation/image/image.h"
#include "foundation/image/pixel.h"
#include "foundation/math/scalar.h"
#include "foundation/platform/compiler.h"
#include "foundation/platform/thread.h"
// Standard headers.
#include <cassert>
#include <algorithm>
using namespace boost;
using namespace foundation;
using namespace std;
namespace renderer
{
// If defined, draw each pixel with a shade of gray proportional to the number of samples it contains.
#undef DEBUG_DISPLAY_SAMPLE_COUNT
LocalAccumulationFramebuffer::LocalAccumulationFramebuffer(
const size_t width,
const size_t height)
: AccumulationFramebuffer(width, height)
{
// todo: change to static_assert<>.
assert(sizeof(AccumulationPixel) == 5 * sizeof(float));
const size_t MinSize = 32;
size_t level_width = width;
size_t level_height = height;
do
{
m_levels.push_back(
new Tile(
max(level_width, MinSize),
max(level_height, MinSize),
4 + 1,
PixelFormatFloat));
m_set_pixels.push_back(0);
level_width /= 2;
level_height /= 2;
}
while (level_width > MinSize && level_height > MinSize);
clear();
}
LocalAccumulationFramebuffer::~LocalAccumulationFramebuffer()
{
for (size_t i = 0; i < m_levels.size(); ++i)
delete m_levels[i];
}
void LocalAccumulationFramebuffer::clear()
{
Spinlock::ScopedLock lock(m_spinlock);
AccumulationFramebuffer::clear_no_lock();
for (size_t level = 0; level < m_levels.size(); ++level)
{
Tile* tile = m_levels[level];
AccumulationPixel* pixel = reinterpret_cast<AccumulationPixel*>(tile->pixel(0));
const size_t pixel_count = tile->get_pixel_count();
for (size_t i = 0; i < pixel_count; ++i)
{
pixel[i].m_color.set(0.0f);
pixel[i].m_count = 0;
}
m_set_pixels[level] = 0;
}
m_current_level = m_levels.size() - 1;
}
void LocalAccumulationFramebuffer::store_samples(
const size_t sample_count,
const Sample samples[])
{
Spinlock::ScopedLock lock(m_spinlock);
const Sample* RESTRICT sample_ptr = samples;
const Sample* RESTRICT sample_end = samples + sample_count;
if (m_current_level == 0)
{
Tile* tile = m_levels[0];
const double fb_width = static_cast<double>(tile->get_width());
const double fb_height = static_cast<double>(tile->get_height());
while (sample_ptr < sample_end)
{
const double fx = sample_ptr->m_position.x * fb_width;
const double fy = sample_ptr->m_position.y * fb_height;
const size_t x = truncate<size_t>(fx);
const size_t y = truncate<size_t>(fy);
AccumulationPixel* pixel =
reinterpret_cast<AccumulationPixel*>(tile->pixel(x, y));
pixel->m_color += sample_ptr->m_color;
pixel->m_count += 1;
if (pixel->m_count == 1)
++m_set_pixels[0];
++sample_ptr;
}
}
else
{
while (sample_ptr < sample_end)
{
for (size_t level = 0; level <= m_current_level; ++level)
{
Tile* tile = m_levels[level];
const double fx = sample_ptr->m_position.x * tile->get_width();
const double fy = sample_ptr->m_position.y * tile->get_height();
const size_t x = truncate<size_t>(fx);
const size_t y = truncate<size_t>(fy);
AccumulationPixel* pixel =
reinterpret_cast<AccumulationPixel*>(tile->pixel(x, y));
pixel->m_color += sample_ptr->m_color;
pixel->m_count += 1;
if (pixel->m_count == 1)
{
if (++m_set_pixels[level] == tile->get_pixel_count())
{
--m_current_level;
break;
}
}
}
++sample_ptr;
}
}
m_sample_count += sample_count;
}
void LocalAccumulationFramebuffer::develop_to_frame(Frame& frame) const
{
Image& image = frame.image();
const CanvasProperties& frame_props = image.properties();
assert(frame_props.m_canvas_width == m_width);
assert(frame_props.m_canvas_height == m_height);
assert(frame_props.m_channel_count == 4);
for (size_t ty = 0; ty < frame_props.m_tile_count_y; ++ty)
{
for (size_t tx = 0; tx < frame_props.m_tile_count_x; ++tx)
{
Tile& tile = image.tile(tx, ty);
const size_t origin_x = tx * frame_props.m_tile_width;
const size_t origin_y = ty * frame_props.m_tile_height;
develop_to_tile(tile, origin_x, origin_y, tx, ty);
}
}
}
void LocalAccumulationFramebuffer::develop_to_tile(
Tile& tile,
const size_t origin_x,
const size_t origin_y,
const size_t tile_x,
const size_t tile_y) const
{
const size_t display_level =
m_current_level > 0 || m_set_pixels[0] < m_pixel_count
? min(m_current_level + 1, m_levels.size() - 1)
: 0;
const Tile* src_tile = m_levels[display_level];
const size_t tile_width = tile.get_width();
const size_t tile_height = tile.get_height();
for (size_t y = 0; y < tile_height; ++y)
{
for (size_t x = 0; x < tile_width; ++x)
{
#ifdef DEBUG_DISPLAY_SAMPLE_COUNT
const AccumulationPixel* pixel =
reinterpret_cast<const AccumulationPixel*>(
m_tile->pixel(origin_x + x, origin_y + y));
const float c = saturate(static_cast<float>(pixel->m_count) / 20.0f);
tile.set_pixel(x, y, Color4f(c, c, c, 1.0f));
#else
const size_t src_x = (origin_x + x) * src_tile->get_width() / m_width;
const size_t src_y = (origin_y + y) * src_tile->get_height() / m_height;
const AccumulationPixel* pixel =
reinterpret_cast<const AccumulationPixel*>(
src_tile->pixel(src_x, src_y));
const Color4f color =
pixel->m_count > 0
? pixel->m_color / static_cast<float>(pixel->m_count)
: Color4f(0.0f);
tile.set_pixel(x, y, color);
#endif
}
}
}
} // namespace renderer
<commit_msg>fixed DEBUG_DISPLAY_SAMPLE_COUNT code path, renamed some variables.<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-2012 Francois Beaune, Jupiter Jazz
//
// 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 "localaccumulationframebuffer.h"
// appleseed.renderer headers.
#include "renderer/kernel/rendering/sample.h"
#include "renderer/modeling/frame/frame.h"
// appleseed.foundation headers.
#include "foundation/image/canvasproperties.h"
#include "foundation/image/image.h"
#include "foundation/image/pixel.h"
#include "foundation/math/scalar.h"
#include "foundation/platform/compiler.h"
#include "foundation/platform/thread.h"
// Standard headers.
#include <cassert>
#include <algorithm>
using namespace boost;
using namespace foundation;
using namespace std;
namespace renderer
{
// If defined, draw each pixel with a shade of gray proportional to the number of samples it contains.
#undef DEBUG_DISPLAY_SAMPLE_COUNT
LocalAccumulationFramebuffer::LocalAccumulationFramebuffer(
const size_t width,
const size_t height)
: AccumulationFramebuffer(width, height)
{
// todo: change to static_assert<>.
assert(sizeof(AccumulationPixel) == 5 * sizeof(float));
const size_t MinSize = 32;
size_t level_width = width;
size_t level_height = height;
do
{
m_levels.push_back(
new Tile(
max(level_width, MinSize),
max(level_height, MinSize),
4 + 1,
PixelFormatFloat));
m_set_pixels.push_back(0);
level_width /= 2;
level_height /= 2;
}
while (level_width > MinSize && level_height > MinSize);
clear();
}
LocalAccumulationFramebuffer::~LocalAccumulationFramebuffer()
{
for (size_t i = 0; i < m_levels.size(); ++i)
delete m_levels[i];
}
void LocalAccumulationFramebuffer::clear()
{
Spinlock::ScopedLock lock(m_spinlock);
AccumulationFramebuffer::clear_no_lock();
for (size_t level_index = 0; level_index < m_levels.size(); ++level_index)
{
Tile* level = m_levels[level_index];
AccumulationPixel* pixel = reinterpret_cast<AccumulationPixel*>(level->pixel(0));
const size_t pixel_count = level->get_pixel_count();
for (size_t i = 0; i < pixel_count; ++i)
{
pixel[i].m_color.set(0.0f);
pixel[i].m_count = 0;
}
m_set_pixels[level_index] = 0;
}
m_current_level = m_levels.size() - 1;
}
void LocalAccumulationFramebuffer::store_samples(
const size_t sample_count,
const Sample samples[])
{
Spinlock::ScopedLock lock(m_spinlock);
const Sample* RESTRICT sample_ptr = samples;
const Sample* RESTRICT sample_end = samples + sample_count;
if (m_current_level == 0)
{
Tile* level = m_levels[0];
const double fb_width = static_cast<double>(level->get_width());
const double fb_height = static_cast<double>(level->get_height());
while (sample_ptr < sample_end)
{
const double fx = sample_ptr->m_position.x * fb_width;
const double fy = sample_ptr->m_position.y * fb_height;
const size_t x = truncate<size_t>(fx);
const size_t y = truncate<size_t>(fy);
AccumulationPixel* pixel =
reinterpret_cast<AccumulationPixel*>(level->pixel(x, y));
pixel->m_color += sample_ptr->m_color;
pixel->m_count += 1;
if (pixel->m_count == 1)
++m_set_pixels[0];
++sample_ptr;
}
}
else
{
while (sample_ptr < sample_end)
{
for (size_t level_index = 0; level_index <= m_current_level; ++level_index)
{
Tile* level = m_levels[level_index];
const double fx = sample_ptr->m_position.x * level->get_width();
const double fy = sample_ptr->m_position.y * level->get_height();
const size_t x = truncate<size_t>(fx);
const size_t y = truncate<size_t>(fy);
AccumulationPixel* pixel =
reinterpret_cast<AccumulationPixel*>(level->pixel(x, y));
pixel->m_color += sample_ptr->m_color;
pixel->m_count += 1;
if (pixel->m_count == 1)
{
if (++m_set_pixels[level_index] == level->get_pixel_count())
{
--m_current_level;
break;
}
}
}
++sample_ptr;
}
}
m_sample_count += sample_count;
}
void LocalAccumulationFramebuffer::develop_to_frame(Frame& frame) const
{
Image& image = frame.image();
const CanvasProperties& frame_props = image.properties();
assert(frame_props.m_canvas_width == m_width);
assert(frame_props.m_canvas_height == m_height);
assert(frame_props.m_channel_count == 4);
for (size_t ty = 0; ty < frame_props.m_tile_count_y; ++ty)
{
for (size_t tx = 0; tx < frame_props.m_tile_count_x; ++tx)
{
Tile& tile = image.tile(tx, ty);
const size_t origin_x = tx * frame_props.m_tile_width;
const size_t origin_y = ty * frame_props.m_tile_height;
develop_to_tile(tile, origin_x, origin_y, tx, ty);
}
}
}
void LocalAccumulationFramebuffer::develop_to_tile(
Tile& tile,
const size_t origin_x,
const size_t origin_y,
const size_t tile_x,
const size_t tile_y) const
{
const size_t tile_width = tile.get_width();
const size_t tile_height = tile.get_height();
#ifdef DEBUG_DISPLAY_SAMPLE_COUNT
const Tile* level = m_levels[0];
for (size_t y = 0; y < tile_height; ++y)
{
for (size_t x = 0; x < tile_width; ++x)
{
const AccumulationPixel* pixel =
reinterpret_cast<const AccumulationPixel*>(
level->pixel(
origin_x + x,
origin_y + y));
const float c = saturate(static_cast<float>(pixel->m_count) / 20.0f);
tile.set_pixel(x, y, Color4f(c, c, c, 1.0f));
}
}
#else
const size_t display_level_index =
m_current_level > 0 || m_set_pixels[0] < m_pixel_count
? min(m_current_level + 1, m_levels.size() - 1)
: 0;
const Tile* level = m_levels[display_level_index];
for (size_t y = 0; y < tile_height; ++y)
{
for (size_t x = 0; x < tile_width; ++x)
{
const AccumulationPixel* pixel =
reinterpret_cast<const AccumulationPixel*>(
level->pixel(
(origin_x + x) * level->get_width() / m_width,
(origin_y + y) * level->get_height() / m_height));
const Color4f color =
pixel->m_count > 0
? pixel->m_color / static_cast<float>(pixel->m_count)
: Color4f(0.0f);
tile.set_pixel(x, y, color);
}
}
#endif
}
} // namespace renderer
<|endoftext|> |
<commit_before>//---------------------------- work_stream_03.cc ---------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2006, 2013 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- work_stream_03.cc ---------------------------
// Moritz originally implemented thread local scratch objects for
// WorkStream in r24748 but it led to failures in the testsuite. what
// exactly went on was a mystery and this test is a first step in
// figuring out what happens by running a simplified version of one of
// the failing tests (deal.II/project_q_01) multiple times and
// verifying that it indeed works
#include "../tests.h"
#include <deal.II/base/logstream.h>
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/base/work_stream.h>
#include <deal.II/lac/vector.h>
#include <deal.II/base/parallel.h>
#include <deal.II/grid/tria.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/fe/fe_nothing.h>
#include <deal.II/fe/fe_values.h>
#include <fstream>
#include <vector>
char logname[] = "work_stream_03/output";
template<int dim>
double
value(const Point<dim> &p)
{
double val = 0;
for (unsigned int d = 0; d < dim; ++d)
for (unsigned int i = 0; i <= 1; ++i)
val += std::pow(p[d], 1. * i);
return val;
}
namespace
{
template<int dim>
struct Scratch
{
Scratch(const FiniteElement<dim> &fe, const Quadrature<dim> &quadrature) :
fe_collection(fe), quadrature_collection(quadrature), x_fe_values(
fe_collection, quadrature_collection, update_q_points), rhs_values(
quadrature_collection.size())
{
}
Scratch(const Scratch &data) :
fe_collection(data.fe_collection), quadrature_collection(
data.quadrature_collection), x_fe_values(fe_collection,
quadrature_collection, update_q_points), rhs_values(
data.rhs_values)
{
}
const FiniteElement<dim> &fe_collection;
const Quadrature<dim> &quadrature_collection;
FEValues<dim> x_fe_values;
std::vector<double> rhs_values;
};
struct CopyData
{
std::vector<double> cell_rhs;
};
}
void
zero_subrange(const unsigned int begin, const unsigned int end,
std::vector<double> &dst)
{
for (unsigned int i = begin; i < end; ++i)
dst[i] = 0;
}
template<int dim>
void
mass_assembler(const typename Triangulation<dim>::active_cell_iterator &cell,
Scratch<dim> &data, CopyData ©_data)
{
data.x_fe_values.reinit(cell);
const Point<dim> q = data.x_fe_values.quadrature_point(0);
// this appears to be the key: the following line overwrites some of the memory
// in which we store the quadrature point location. if the line is moved down,
// the comparison in the if() always succeeds...
parallel::apply_to_subranges(0U, copy_data.cell_rhs.size(),
std_cxx1x::bind(&zero_subrange, std_cxx1x::_1, std_cxx1x::_2,
std_cxx1x::ref(copy_data.cell_rhs)), 1);
std::cout << (q != data.x_fe_values.quadrature_point(0) ? '.' : '*')
<< std::flush;
copy_data.cell_rhs[0] = value(data.x_fe_values.quadrature_point(0));
}
void
copy_local_to_global(const CopyData &data, double *sum)
{
*sum += data.cell_rhs[0];
}
void
do_project()
{
static const int dim = 3;
Triangulation < dim > triangulation;
GridGenerator::hyper_cube (triangulation);
triangulation.refine_global(2);
FE_Nothing < dim > fe;
QMidpoint < dim > q;
for (unsigned int i = 0; i < 12; ++i)
{
std::vector<double> tmp;
double sum = 0;
Scratch<dim> assembler_data(fe, q);
CopyData copy_data;
copy_data.cell_rhs.resize(8);
WorkStream::run(triangulation.begin_active(), triangulation.end(),
&mass_assembler<dim>,
std_cxx1x::bind(©_local_to_global, std_cxx1x::_1, &sum),
assembler_data, copy_data, 8, 1);
printf("\nCheck: %5.3f\n", sum);
deallog << sum << std::endl;
}
}
int main()
{
std::ofstream logfile(logname);
deallog << std::setprecision(3);
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-10);
do_project();
}
<commit_msg>Final version of the test.<commit_after>//---------------------------- work_stream_03.cc ---------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2006, 2013 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- work_stream_03.cc ---------------------------
// Moritz originally implemented thread local scratch objects for
// WorkStream in r24748 but it led to failures in the testsuite. what
// exactly went on was a mystery and this test is a first step in
// figuring out what happens by running a simplified version of one of
// the failing tests (deal.II/project_q_01) multiple times and
// verifying that it indeed works
#include "../tests.h"
#include <deal.II/base/logstream.h>
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/base/work_stream.h>
#include <deal.II/lac/vector.h>
#include <deal.II/base/parallel.h>
#include <deal.II/grid/tria.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/fe/fe_nothing.h>
#include <deal.II/fe/fe_values.h>
#include <fstream>
#include <vector>
char logname[] = "work_stream_03/output";
template<int dim>
double
value(const Point<dim> &p)
{
double val = 0;
for (unsigned int d = 0; d < dim; ++d)
for (unsigned int i = 0; i <= 1; ++i)
val += std::pow(p[d], 1. * i);
return val;
}
namespace
{
template<int dim>
struct Scratch
{
Scratch(const FiniteElement<dim> &fe, const Quadrature<dim> &quadrature) :
fe_collection(fe), quadrature_collection(quadrature), x_fe_values(
fe_collection, quadrature_collection, update_q_points), rhs_values(
quadrature_collection.size())
{
}
Scratch(const Scratch &data) :
fe_collection(data.fe_collection), quadrature_collection(
data.quadrature_collection), x_fe_values(fe_collection,
quadrature_collection, update_q_points), rhs_values(
data.rhs_values)
{
}
const FiniteElement<dim> &fe_collection;
const Quadrature<dim> &quadrature_collection;
FEValues<dim> x_fe_values;
std::vector<double> rhs_values;
};
struct CopyData
{
std::vector<double> cell_rhs;
};
}
void
zero_subrange(const unsigned int begin, const unsigned int end,
std::vector<double> &dst)
{
for (unsigned int i = begin; i < end; ++i)
dst[i] = 0;
}
void
zero_element(std::vector<double> &dst,
const unsigned int i)
{
dst[i] = 0;
}
template<int dim>
void
mass_assembler(const typename Triangulation<dim>::active_cell_iterator &cell,
Scratch<dim> &data, CopyData ©_data)
{
data.x_fe_values.reinit(cell);
const Point<dim> q = data.x_fe_values.quadrature_point(0);
// this appears to be the key: the following two ways both overwrite some
// of the memory in which we store the quadrature point location.
parallel::apply_to_subranges(0U, copy_data.cell_rhs.size(),
std_cxx1x::bind(&zero_subrange, std_cxx1x::_1, std_cxx1x::_2,
std_cxx1x::ref(copy_data.cell_rhs)), 1);
Assert(q == data.x_fe_values.quadrature_point(0),
ExcInternalError());
copy_data.cell_rhs[0] = value(data.x_fe_values.quadrature_point(0));
}
void
copy_local_to_global(const CopyData &data, double *sum)
{
*sum += data.cell_rhs[0];
}
void
do_project()
{
static const int dim = 3;
Triangulation < dim > triangulation;
GridGenerator::hyper_cube (triangulation);
triangulation.refine_global(2);
FE_Nothing < dim > fe;
QMidpoint < dim > q;
for (unsigned int i = 0; i < 12; ++i)
{
std::vector<double> tmp;
double sum = 0;
Scratch<dim> assembler_data(fe, q);
CopyData copy_data;
copy_data.cell_rhs.resize(8);
WorkStream::run(triangulation.begin_active(), triangulation.end(),
&mass_assembler<dim>,
std_cxx1x::bind(©_local_to_global, std_cxx1x::_1, &sum),
assembler_data, copy_data, 8, 1);
Assert (std::fabs(sum-288.) < 1e-12, ExcInternalError());
deallog << sum << std::endl;
}
}
int main()
{
std::ofstream logfile(logname);
deallog << std::setprecision(3);
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-10);
do_project();
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (C) 2019 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.
*
****************************************************************************/
#include <px4_arch/io_timer_hw_description.h>
constexpr io_timers_t io_timers[MAX_IO_TIMERS] = {
initIOTimer(Timer::Timer3, DMA{DMA::Index1, DMA::Stream2, DMA::Channel5}),
initIOTimer(Timer::Timer1, DMA{DMA::Index2, DMA::Stream5, DMA::Channel6}),
initIOTimer(Timer::Timer8, DMA{DMA::Index2, DMA::Stream1, DMA::Channel7}),
initIOTimer(Timer::Timer5, DMA{DMA::Index1, DMA::Stream6, DMA::Channel6}),
};
constexpr timer_io_channels_t timer_io_channels[MAX_TIMER_IO_CHANNELS] = {
initIOTimerChannel(io_timers, {Timer::Timer5, Timer::Channel4}, {GPIO::PortA, GPIO::Pin3}),
initIOTimerChannel(io_timers, {Timer::Timer8, Timer::Channel4}, {GPIO::PortC, GPIO::Pin9}),
initIOTimerChannel(io_timers, {Timer::Timer1, Timer::Channel2}, {GPIO::PortE, GPIO::Pin11}),
initIOTimerChannel(io_timers, {Timer::Timer1, Timer::Channel1}, {GPIO::PortE, GPIO::Pin9}),
initIOTimerChannel(io_timers, {Timer::Timer3, Timer::Channel4}, {GPIO::PortB, GPIO::Pin1}),
initIOTimerChannel(io_timers, {Timer::Timer3, Timer::Channel3}, {GPIO::PortB, GPIO::Pin0}),
};
constexpr io_timers_channel_mapping_t io_timers_channel_mapping =
initIOTimerChannelMapping(io_timers, timer_io_channels);
<commit_msg>kakutef7: fix output ordering<commit_after>/****************************************************************************
*
* Copyright (C) 2019 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.
*
****************************************************************************/
#include <px4_arch/io_timer_hw_description.h>
constexpr io_timers_t io_timers[MAX_IO_TIMERS] = {
initIOTimer(Timer::Timer3, DMA{DMA::Index1, DMA::Stream2, DMA::Channel5}),
initIOTimer(Timer::Timer1, DMA{DMA::Index2, DMA::Stream5, DMA::Channel6}),
initIOTimer(Timer::Timer8, DMA{DMA::Index2, DMA::Stream1, DMA::Channel7}),
initIOTimer(Timer::Timer5, DMA{DMA::Index1, DMA::Stream6, DMA::Channel6}),
};
constexpr timer_io_channels_t timer_io_channels[MAX_TIMER_IO_CHANNELS] = {
initIOTimerChannel(io_timers, {Timer::Timer3, Timer::Channel3}, {GPIO::PortB, GPIO::Pin0}),
initIOTimerChannel(io_timers, {Timer::Timer3, Timer::Channel4}, {GPIO::PortB, GPIO::Pin1}),
initIOTimerChannel(io_timers, {Timer::Timer1, Timer::Channel1}, {GPIO::PortE, GPIO::Pin9}),
initIOTimerChannel(io_timers, {Timer::Timer1, Timer::Channel2}, {GPIO::PortE, GPIO::Pin11}),
initIOTimerChannel(io_timers, {Timer::Timer8, Timer::Channel4}, {GPIO::PortC, GPIO::Pin9}),
initIOTimerChannel(io_timers, {Timer::Timer5, Timer::Channel4}, {GPIO::PortA, GPIO::Pin3}),
};
constexpr io_timers_channel_mapping_t io_timers_channel_mapping =
initIOTimerChannelMapping(io_timers, timer_io_channels);
<|endoftext|> |
<commit_before>#include "hand.h"
#include "card.h"
#include "gameExceptions.h"
#include <vector>
Hand::Hand()
{
_cards = std::vector<Card>();
}
Hand::Hand( std::vector<Card> cards )
{
_cards = std::vector<Card>();
_cards.reserve(cards.size());
_cards = cards;
}
unsigned int Hand::GetScore()
{
unsigned int score = 0;
for (std::vector<Card>::const_iterator card = _cards.begin(); card != _cards.end(); ++card)
{
score += card->GetScore();
}
return score;
}
void Hand::AddCard(Card card)
{
if (card.IsValid())
{
_cards.push_back(card);
}
else
{
throw InvalidCardException("Invalid card at Hand::AddCard(Card card)!");
}
}
<commit_msg>Added verification for the Aces cards in the GetScore() method of the hand class.<commit_after>#include "hand.h"
#include "card.h"
#include "gameExceptions.h"
#include <vector>
Hand::Hand()
{
_cards = std::vector<Card>();
}
Hand::Hand( std::vector<Card> cards )
{
_cards = std::vector<Card>();
_cards.reserve(cards.size());
_cards = cards;
}
unsigned int Hand::GetScore()
{
unsigned int score = 0;
bool hasAce = false;
for (std::vector<Card>::const_iterator card = _cards.begin(); card != _cards.end(); ++card)
{
if (card->GetName() != Ace)
score += card->GetScore();
else
hasAce = true;
}
if (hasAce)
for (std::vector<Card>::iterator card = _cards.begin(); card != _cards.end(); ++card)
{
if (card->GetName() == Ace)
if (score + 11 > 21)
{
card->SetScore(11);
score += 11;
}
else
{
card->SetScore(1);
score += 1;
}
}
return score;
}
void Hand::AddCard(Card card)
{
if (card.IsValid())
{
_cards.push_back(card);
}
else
{
throw InvalidCardException("Invalid card at Hand::AddCard(Card card)!");
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: ZipPackageFolder.hxx,v $
*
* $Revision: 1.19 $
*
* last change: $Author: mtg $ $Date: 2001-04-27 14:56:05 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): Martin Gallwey ([email protected])
*
*
************************************************************************/
#ifndef _ZIP_PACKAGE_FOLDER_HXX
#define _ZIP_PACKAGE_FOLDER_HXX
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XENUMERATIONACCESS_HPP_
#include <com/sun/star/container/XEnumerationAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _HASHMAPS_HXX
#include <HashMaps.hxx>
#endif
#ifndef _ZIP_PACKAGE_ENTRY_HXX
#include <ZipPackageEntry.hxx>
#endif
class ZipFile;
class ZipPackage;
class ZipOutputStream;
class ZipPackageFolder : public ZipPackageEntry,
public ::cppu::OWeakObject,
public ::com::sun::star::container::XNameContainer,
public ::com::sun::star::container::XEnumerationAccess
{
protected:
TunnelHash aContents;
public:
ZipPackageFolder ();
virtual ~ZipPackageFolder();
static void copyZipEntry( com::sun::star::packages::ZipEntry &rDest, const com::sun::star::packages::ZipEntry &rSource);
// Recursive functions
void saveContents(rtl::OUString &rPath, std::vector < com::sun::star::uno::Sequence < com::sun::star::beans::PropertyValue > > &rManList, ZipOutputStream & rZipOut)
throw(::com::sun::star::uno::RuntimeException);
void releaseUpwardRef();
// XInterface
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& rType )
throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL acquire( )
throw();
virtual void SAL_CALL release( )
throw();
// XNameContainer
virtual void SAL_CALL insertByName( const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement )
throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::ElementExistException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeByName( const ::rtl::OUString& Name )
throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
// XEnumerationAccess
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XEnumeration > SAL_CALL createEnumeration( )
throw(::com::sun::star::uno::RuntimeException);
// XElementAccess
virtual ::com::sun::star::uno::Type SAL_CALL getElementType( )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL hasElements( )
throw(::com::sun::star::uno::RuntimeException);
// XNameAccess
virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName )
throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames( )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName )
throw(::com::sun::star::uno::RuntimeException);
// XNameReplace
virtual void SAL_CALL replaceByName( const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement )
throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
// XPropertySet
virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue )
throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName )
throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
// XUnoTunnel
static ::com::sun::star::uno::Sequence < sal_Int8 > getUnoTunnelImplementationId( void )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier )
throw(::com::sun::star::uno::RuntimeException);
};
#endif
<commit_msg>Pass the encryption key as a parameter to saveContents<commit_after>/*************************************************************************
*
* $RCSfile: ZipPackageFolder.hxx,v $
*
* $Revision: 1.20 $
*
* last change: $Author: mtg $ $Date: 2001-05-08 13:51:29 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): Martin Gallwey ([email protected])
*
*
************************************************************************/
#ifndef _ZIP_PACKAGE_FOLDER_HXX
#define _ZIP_PACKAGE_FOLDER_HXX
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XENUMERATIONACCESS_HPP_
#include <com/sun/star/container/XEnumerationAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _HASHMAPS_HXX
#include <HashMaps.hxx>
#endif
#ifndef _ZIP_PACKAGE_ENTRY_HXX
#include <ZipPackageEntry.hxx>
#endif
class ZipFile;
class ZipPackage;
class ZipOutputStream;
class ZipPackageFolder : public ZipPackageEntry,
public ::cppu::OWeakObject,
public ::com::sun::star::container::XNameContainer,
public ::com::sun::star::container::XEnumerationAccess
{
protected:
TunnelHash aContents;
public:
ZipPackageFolder ();
virtual ~ZipPackageFolder();
static void copyZipEntry( com::sun::star::packages::ZipEntry &rDest, const com::sun::star::packages::ZipEntry &rSource);
// Recursive functions
void saveContents(rtl::OUString &rPath, std::vector < com::sun::star::uno::Sequence < com::sun::star::beans::PropertyValue > > &rManList, ZipOutputStream & rZipOut, com::sun::star::uno::Sequence < sal_Int8 > &rEncryptionKey)
throw(::com::sun::star::uno::RuntimeException);
void releaseUpwardRef();
// XInterface
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& rType )
throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL acquire( )
throw();
virtual void SAL_CALL release( )
throw();
// XNameContainer
virtual void SAL_CALL insertByName( const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement )
throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::ElementExistException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeByName( const ::rtl::OUString& Name )
throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
// XEnumerationAccess
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XEnumeration > SAL_CALL createEnumeration( )
throw(::com::sun::star::uno::RuntimeException);
// XElementAccess
virtual ::com::sun::star::uno::Type SAL_CALL getElementType( )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL hasElements( )
throw(::com::sun::star::uno::RuntimeException);
// XNameAccess
virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName )
throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames( )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName )
throw(::com::sun::star::uno::RuntimeException);
// XNameReplace
virtual void SAL_CALL replaceByName( const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement )
throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
// XPropertySet
virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue )
throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName )
throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
// XUnoTunnel
static ::com::sun::star::uno::Sequence < sal_Int8 > getUnoTunnelImplementationId( void )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier )
throw(::com::sun::star::uno::RuntimeException);
};
#endif
<|endoftext|> |
<commit_before>#include <numeric>
#include <set>
#include <arbiter/util/time.hpp>
#include <arbiter/arbiter.hpp>
#include <arbiter/util/transforms.hpp>
#include "config.hpp"
#include "gtest/gtest.h"
using namespace arbiter;
TEST(Env, HomeDir)
{
std::string home;
ASSERT_NO_THROW(home = arbiter::fs::expandTilde("~"));
EXPECT_NE(home, "~");
EXPECT_FALSE(home.empty());
}
TEST(Arbiter, HttpDerivation)
{
Arbiter a;
EXPECT_TRUE(a.isHttpDerived("http://arbitercpp.com"));
EXPECT_FALSE(a.isHttpDerived("~/data"));
EXPECT_FALSE(a.isHttpDerived("."));
}
TEST(Arbiter, Time)
{
Time a;
Time b(a.str());
EXPECT_EQ(a.str(), b.str());
EXPECT_EQ(a - b, 0);
Time x("2016-03-18T03:14:42Z");
Time y("2016-03-18T04:24:54Z");
const int64_t delta(1 * 60 * 60 + 10 * 60 + 12);
EXPECT_EQ(y - x, delta);
EXPECT_EQ(x - y, -delta);
}
TEST(Arbiter, Base64)
{
EXPECT_EQ(crypto::encodeBase64(""), "");
EXPECT_EQ(crypto::encodeBase64("f"), "Zg==");
EXPECT_EQ(crypto::encodeBase64("fo"), "Zm8=");
EXPECT_EQ(crypto::encodeBase64("foo"), "Zm9v");
EXPECT_EQ(crypto::encodeBase64("foob"), "Zm9vYg==");
EXPECT_EQ(crypto::encodeBase64("fooba"), "Zm9vYmE=");
EXPECT_EQ(crypto::encodeBase64("foobar"), "Zm9vYmFy");
}
class DriverTest : public ::testing::TestWithParam<std::string> { };
TEST_P(DriverTest, PutGet)
{
Arbiter a;
const std::string root(GetParam());
const std::string path(root + "test.txt");
const std::string data("Testing path " + path);
if (a.isLocal(root)) fs::mkdirp(root);
EXPECT_NO_THROW(a.put(path, data));
EXPECT_EQ(a.get(path), data);
}
TEST_P(DriverTest, HttpRange)
{
Arbiter a;
const std::string root(GetParam());
const std::string path(root + "test.txt");
const std::string data("0123456789");
const http::Headers headers{ { "Range", "bytes=0-5" } };
// Dropbox is slow to update files, so we'd get failures here without a
// timeout since the old file will often be returned. Just skip it.
if (!a.isHttpDerived(root) || a.getDriver(root).type() == "dropbox")
{
return;
}
EXPECT_NO_THROW(a.put(path, data));
EXPECT_EQ(a.get(path, headers), "012345");
}
TEST_P(DriverTest, Glob)
{
using Paths = std::set<std::string>;
Arbiter a;
const std::string rawRoot(GetParam());
// Local directories explicitly prefixed with file:// will be returned
// without that prefix, so strip that off.
const std::string root(
a.isLocal(rawRoot) ? Arbiter::stripType(rawRoot) : rawRoot);
const std::string type(Arbiter::getType(root));
// No `ls` for plain HTTP/s.
if (type == "http" || type == "https") return;
auto put([&a, root](std::string p)
{
EXPECT_NO_THROW(a.put(root + p, p));
});
if (a.isLocal(root))
{
fs::mkdirp(root + "a");
fs::mkdirp(root + "a/b");
}
put("one.txt");
put("two.txt");
put("a/one.txt");
put("a/two.txt");
put("a/b/one.txt");
put("a/b/two.txt");
auto resolve([&a, root](std::string p)
{
const auto v = a.resolve(root + p);
return Paths(v.begin(), v.end());
});
auto check([&](std::string p, Paths exp)
{
const auto got(resolve(p));
EXPECT_GE(got.size(), exp.size());
for (const auto& s : exp)
{
EXPECT_TRUE(got.count(root + s)) << p << ": " << root << s;
}
});
// Non-recursive.
check("*", Paths { "one.txt", "two.txt" });
check("a/*", Paths { "a/one.txt", "a/two.txt" });
check("a/b/*", Paths { "a/b/one.txt", "a/b/two.txt" });
// Recursive.
check("**", Paths {
"one.txt", "two.txt",
"a/one.txt", "a/two.txt",
"a/b/one.txt", "a/b/two.txt"
}
);
check("a/**", Paths {
"a/one.txt", "a/two.txt",
"a/b/one.txt", "a/b/two.txt"
}
);
check("a/b/**", Paths { "a/b/one.txt", "a/b/two.txt" });
// Not globs - files resolve to themselves.
check("", Paths { "" });
check("asdf", Paths { "asdf" });
check("asdf.txt", Paths { "asdf.txt" });
}
const auto tests = std::accumulate(
Config::get().begin(),
Config::get().end(),
std::vector<std::string>(),
[](const std::vector<std::string>& in, const Json::Value& entry)
{
if (in.empty())
{
std::cout << "Testing PUT/GET/LS with:" << std::endl;
}
auto out(in);
const std::string path(entry.asString());
out.push_back(path + (path.back() != '/' ? "/" : ""));
std::cout << "\t" << out.back() << std::endl;
return out;
});
INSTANTIATE_TEST_CASE_P(
ConfiguredTests,
DriverTest,
::testing::ValuesIn(tests));
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Enable ranged dropbox test.<commit_after>#include <numeric>
#include <set>
#include <arbiter/util/time.hpp>
#include <arbiter/arbiter.hpp>
#include <arbiter/util/transforms.hpp>
#include "config.hpp"
#include "gtest/gtest.h"
using namespace arbiter;
TEST(Env, HomeDir)
{
std::string home;
ASSERT_NO_THROW(home = arbiter::fs::expandTilde("~"));
EXPECT_NE(home, "~");
EXPECT_FALSE(home.empty());
}
TEST(Arbiter, HttpDerivation)
{
Arbiter a;
EXPECT_TRUE(a.isHttpDerived("http://arbitercpp.com"));
EXPECT_FALSE(a.isHttpDerived("~/data"));
EXPECT_FALSE(a.isHttpDerived("."));
}
TEST(Arbiter, Time)
{
Time a;
Time b(a.str());
EXPECT_EQ(a.str(), b.str());
EXPECT_EQ(a - b, 0);
Time x("2016-03-18T03:14:42Z");
Time y("2016-03-18T04:24:54Z");
const int64_t delta(1 * 60 * 60 + 10 * 60 + 12);
EXPECT_EQ(y - x, delta);
EXPECT_EQ(x - y, -delta);
}
TEST(Arbiter, Base64)
{
EXPECT_EQ(crypto::encodeBase64(""), "");
EXPECT_EQ(crypto::encodeBase64("f"), "Zg==");
EXPECT_EQ(crypto::encodeBase64("fo"), "Zm8=");
EXPECT_EQ(crypto::encodeBase64("foo"), "Zm9v");
EXPECT_EQ(crypto::encodeBase64("foob"), "Zm9vYg==");
EXPECT_EQ(crypto::encodeBase64("fooba"), "Zm9vYmE=");
EXPECT_EQ(crypto::encodeBase64("foobar"), "Zm9vYmFy");
}
class DriverTest : public ::testing::TestWithParam<std::string> { };
TEST_P(DriverTest, PutGet)
{
Arbiter a;
const std::string root(GetParam());
const std::string path(root + "test.txt");
const std::string data("Testing path " + path);
if (a.isLocal(root)) fs::mkdirp(root);
EXPECT_NO_THROW(a.put(path, data));
EXPECT_EQ(a.get(path), data);
}
TEST_P(DriverTest, HttpRange)
{
Arbiter a;
const std::string root(GetParam());
const std::string path(root + "range.txt");
const std::string data("0123456789");
const http::Headers headers{ { "Range", "bytes=0-5" } };
if (!a.isHttpDerived(root)) return;
EXPECT_NO_THROW(a.put(path, data));
EXPECT_EQ(a.get(path, headers), "012345");
}
TEST_P(DriverTest, Glob)
{
using Paths = std::set<std::string>;
Arbiter a;
const std::string rawRoot(GetParam());
// Local directories explicitly prefixed with file:// will be returned
// without that prefix, so strip that off.
const std::string root(
a.isLocal(rawRoot) ? Arbiter::stripType(rawRoot) : rawRoot);
const std::string type(Arbiter::getType(root));
// No `ls` for plain HTTP/s.
if (type == "http" || type == "https") return;
auto put([&a, root](std::string p)
{
EXPECT_NO_THROW(a.put(root + p, p));
});
if (a.isLocal(root))
{
fs::mkdirp(root + "a");
fs::mkdirp(root + "a/b");
}
put("one.txt");
put("two.txt");
put("a/one.txt");
put("a/two.txt");
put("a/b/one.txt");
put("a/b/two.txt");
auto resolve([&a, root](std::string p)
{
const auto v = a.resolve(root + p);
return Paths(v.begin(), v.end());
});
auto check([&](std::string p, Paths exp)
{
const auto got(resolve(p));
EXPECT_GE(got.size(), exp.size());
for (const auto& s : exp)
{
EXPECT_TRUE(got.count(root + s)) << p << ": " << root << s;
}
});
// Non-recursive.
check("*", Paths { "one.txt", "two.txt" });
check("a/*", Paths { "a/one.txt", "a/two.txt" });
check("a/b/*", Paths { "a/b/one.txt", "a/b/two.txt" });
// Recursive.
check("**", Paths {
"one.txt", "two.txt",
"a/one.txt", "a/two.txt",
"a/b/one.txt", "a/b/two.txt"
}
);
check("a/**", Paths {
"a/one.txt", "a/two.txt",
"a/b/one.txt", "a/b/two.txt"
}
);
check("a/b/**", Paths { "a/b/one.txt", "a/b/two.txt" });
// Not globs - files resolve to themselves.
check("", Paths { "" });
check("asdf", Paths { "asdf" });
check("asdf.txt", Paths { "asdf.txt" });
}
const auto tests = std::accumulate(
Config::get().begin(),
Config::get().end(),
std::vector<std::string>(),
[](const std::vector<std::string>& in, const Json::Value& entry)
{
if (in.empty())
{
std::cout << "Testing PUT/GET/LS with:" << std::endl;
}
auto out(in);
const std::string path(entry.asString());
out.push_back(path + (path.back() != '/' ? "/" : ""));
std::cout << "\t" << out.back() << std::endl;
return out;
});
INSTANTIATE_TEST_CASE_P(
ConfiguredTests,
DriverTest,
::testing::ValuesIn(tests));
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>//===-- WebAssemblyFixFunctionBitcasts.cpp - Fix function bitcasts --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Fix bitcasted functions.
///
/// WebAssembly requires caller and callee signatures to match, however in LLVM,
/// some amount of slop is vaguely permitted. Detect mismatch by looking for
/// bitcasts of functions and rewrite them to use wrapper functions instead.
///
/// This doesn't catch all cases, such as when a function's address is taken in
/// one place and casted in another, but it works for many common cases.
///
/// Note that LLVM already optimizes away function bitcasts in common cases by
/// dropping arguments as needed, so this pass only ends up getting used in less
/// common cases.
///
//===----------------------------------------------------------------------===//
#include "WebAssembly.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
#define DEBUG_TYPE "wasm-fix-function-bitcasts"
namespace {
class FixFunctionBitcasts final : public ModulePass {
StringRef getPassName() const override {
return "WebAssembly Fix Function Bitcasts";
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
ModulePass::getAnalysisUsage(AU);
}
bool runOnModule(Module &M) override;
SmallVector<std::pair<Use *, Function *>, 0> Uses;
public:
static char ID;
FixFunctionBitcasts() : ModulePass(ID) {}
};
} // End anonymous namespace
char FixFunctionBitcasts::ID = 0;
ModulePass *llvm::createWebAssemblyFixFunctionBitcasts() {
return new FixFunctionBitcasts();
}
// Recursively descend the def-use lists from V to find non-bitcast users of
// bitcasts of V.
static void FindUses(Value *V, Function &F,
SmallVectorImpl<std::pair<Use *, Function *>> &Uses) {
for (Use &U : V->uses()) {
if (BitCastOperator *BC = dyn_cast<BitCastOperator>(U.getUser()))
FindUses(BC, F, Uses);
else if (U.get()->getType() != F.getType())
Uses.push_back(std::make_pair(&U, &F));
}
}
// Create a wrapper function with type Ty that calls F (which may have a
// different type). Attempt to support common bitcasted function idioms:
// - Call with more arguments than needed: arguments are dropped
// - Call with fewer arguments than needed: arguments are filled in with undef
// - Return value is not needed: drop it
// - Return value needed but not present: supply an undef
static Function *CreateWrapper(Function *F, FunctionType *Ty) {
Module *M = F->getParent();
Function *Wrapper =
Function::Create(Ty, Function::PrivateLinkage, "bitcast", M);
BasicBlock *BB = BasicBlock::Create(M->getContext(), "body", Wrapper);
// Determine what arguments to pass.
SmallVector<Value *, 4> Args;
Function::arg_iterator AI = Wrapper->arg_begin();
FunctionType::param_iterator PI = F->getFunctionType()->param_begin();
FunctionType::param_iterator PE = F->getFunctionType()->param_end();
for (; AI != Wrapper->arg_end() && PI != PE; ++AI, ++PI) {
assert(AI->getType() == *PI &&
"mismatched argument types not supported yet");
Args.push_back(&*AI);
}
for (; PI != PE; ++PI)
Args.push_back(UndefValue::get(*PI));
CallInst *Call = CallInst::Create(F, Args, "", BB);
// Determine what value to return.
if (Ty->getReturnType()->isVoidTy())
ReturnInst::Create(M->getContext(), BB);
else if (F->getFunctionType()->getReturnType()->isVoidTy())
ReturnInst::Create(M->getContext(), UndefValue::get(Ty->getReturnType()),
BB);
else if (F->getFunctionType()->getReturnType() == Ty->getReturnType())
ReturnInst::Create(M->getContext(), Call, BB);
else
llvm_unreachable("mismatched return types not supported yet");
return Wrapper;
}
bool FixFunctionBitcasts::runOnModule(Module &M) {
// Collect all the places that need wrappers.
for (Function &F : M)
FindUses(&F, F, Uses);
DenseMap<std::pair<Function *, FunctionType *>, Function *> Wrappers;
for (auto &UseFunc : Uses) {
Use *U = UseFunc.first;
Function *F = UseFunc.second;
PointerType *PTy = cast<PointerType>(U->get()->getType());
FunctionType *Ty = dyn_cast<FunctionType>(PTy->getElementType());
// If the function is casted to something like i8* as a "generic pointer"
// to be later casted to something else, we can't generate a wrapper for it.
// Just ignore such casts for now.
if (!Ty)
continue;
auto Pair = Wrappers.insert(std::make_pair(std::make_pair(F, Ty), nullptr));
if (Pair.second)
Pair.first->second = CreateWrapper(F, Ty);
if (isa<Constant>(U->get()))
U->get()->replaceAllUsesWith(Pair.first->second);
else
U->set(Pair.first->second);
}
return true;
}
<commit_msg>[WebAssembly] Move a SmallVector to a more specific scope. NFC.<commit_after>//===-- WebAssemblyFixFunctionBitcasts.cpp - Fix function bitcasts --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Fix bitcasted functions.
///
/// WebAssembly requires caller and callee signatures to match, however in LLVM,
/// some amount of slop is vaguely permitted. Detect mismatch by looking for
/// bitcasts of functions and rewrite them to use wrapper functions instead.
///
/// This doesn't catch all cases, such as when a function's address is taken in
/// one place and casted in another, but it works for many common cases.
///
/// Note that LLVM already optimizes away function bitcasts in common cases by
/// dropping arguments as needed, so this pass only ends up getting used in less
/// common cases.
///
//===----------------------------------------------------------------------===//
#include "WebAssembly.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
#define DEBUG_TYPE "wasm-fix-function-bitcasts"
namespace {
class FixFunctionBitcasts final : public ModulePass {
StringRef getPassName() const override {
return "WebAssembly Fix Function Bitcasts";
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
ModulePass::getAnalysisUsage(AU);
}
bool runOnModule(Module &M) override;
public:
static char ID;
FixFunctionBitcasts() : ModulePass(ID) {}
};
} // End anonymous namespace
char FixFunctionBitcasts::ID = 0;
ModulePass *llvm::createWebAssemblyFixFunctionBitcasts() {
return new FixFunctionBitcasts();
}
// Recursively descend the def-use lists from V to find non-bitcast users of
// bitcasts of V.
static void FindUses(Value *V, Function &F,
SmallVectorImpl<std::pair<Use *, Function *>> &Uses) {
for (Use &U : V->uses()) {
if (BitCastOperator *BC = dyn_cast<BitCastOperator>(U.getUser()))
FindUses(BC, F, Uses);
else if (U.get()->getType() != F.getType())
Uses.push_back(std::make_pair(&U, &F));
}
}
// Create a wrapper function with type Ty that calls F (which may have a
// different type). Attempt to support common bitcasted function idioms:
// - Call with more arguments than needed: arguments are dropped
// - Call with fewer arguments than needed: arguments are filled in with undef
// - Return value is not needed: drop it
// - Return value needed but not present: supply an undef
static Function *CreateWrapper(Function *F, FunctionType *Ty) {
Module *M = F->getParent();
Function *Wrapper =
Function::Create(Ty, Function::PrivateLinkage, "bitcast", M);
BasicBlock *BB = BasicBlock::Create(M->getContext(), "body", Wrapper);
// Determine what arguments to pass.
SmallVector<Value *, 4> Args;
Function::arg_iterator AI = Wrapper->arg_begin();
FunctionType::param_iterator PI = F->getFunctionType()->param_begin();
FunctionType::param_iterator PE = F->getFunctionType()->param_end();
for (; AI != Wrapper->arg_end() && PI != PE; ++AI, ++PI) {
assert(AI->getType() == *PI &&
"mismatched argument types not supported yet");
Args.push_back(&*AI);
}
for (; PI != PE; ++PI)
Args.push_back(UndefValue::get(*PI));
CallInst *Call = CallInst::Create(F, Args, "", BB);
// Determine what value to return.
if (Ty->getReturnType()->isVoidTy())
ReturnInst::Create(M->getContext(), BB);
else if (F->getFunctionType()->getReturnType()->isVoidTy())
ReturnInst::Create(M->getContext(), UndefValue::get(Ty->getReturnType()),
BB);
else if (F->getFunctionType()->getReturnType() == Ty->getReturnType())
ReturnInst::Create(M->getContext(), Call, BB);
else
llvm_unreachable("mismatched return types not supported yet");
return Wrapper;
}
bool FixFunctionBitcasts::runOnModule(Module &M) {
SmallVector<std::pair<Use *, Function *>, 0> Uses;
// Collect all the places that need wrappers.
for (Function &F : M)
FindUses(&F, F, Uses);
DenseMap<std::pair<Function *, FunctionType *>, Function *> Wrappers;
for (auto &UseFunc : Uses) {
Use *U = UseFunc.first;
Function *F = UseFunc.second;
PointerType *PTy = cast<PointerType>(U->get()->getType());
FunctionType *Ty = dyn_cast<FunctionType>(PTy->getElementType());
// If the function is casted to something like i8* as a "generic pointer"
// to be later casted to something else, we can't generate a wrapper for it.
// Just ignore such casts for now.
if (!Ty)
continue;
auto Pair = Wrappers.insert(std::make_pair(std::make_pair(F, Ty), nullptr));
if (Pair.second)
Pair.first->second = CreateWrapper(F, Ty);
if (isa<Constant>(U->get()))
U->get()->replaceAllUsesWith(Pair.first->second);
else
U->set(Pair.first->second);
}
return true;
}
<|endoftext|> |
<commit_before>//-------------------------------------------------------------------------------------------
// Painting with Flowsnakes
// fsnake program modified to use open gl vertex arrays Brian Wyvill October 2012
// added save/restore and postscript driver November 2012
// fixed memory management November 2012 delete works properly now.
// added progress bar to show memory usage.
//-------------------------------------------------------------------------------------------
#include "glwidget.h"
GLWidget::GLWidget(QWidget *parent)
: QGLWidget(parent)
{
double ambience[3] = {0.6,0.6,0.6};
double diffusal[3] = {0.6,0.6,0.6};
double spec[3] = {0.6,0.6,0.6};
double intensity[3] = {0.6,0.6,0.6};
// QVector3D circlepoint(5.0,5.0,5.0);
sceneAmbience = 0.2;
spheres.append(Sphere(QVector3D(5.0,5.0,5.0),1.0,ambience,diffusal,spec));
//spheres.append(Sphere(QVector3D(5.0,7.0,5.0),1.0,ambience,diffusal,spec));
//Spheres.append()
lightBulbs.append(LightBulb(QVector3D(2.0,2.0,4.0),0.5,intensity));
}
GLWidget::~GLWidget()
{
}
void GLWidget::clear()
{
updateGL();
}
void GLWidget::initializeGL()
{
//Background color will be white
glClearColor(1.0, 1.0, 1.0, 1.0);
glShadeModel( GL_FLAT );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glPointSize(5);
}
void GLWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
displayImage();
}
/* 2D */
void GLWidget::resizeGL( int w, int h )
{
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho(0.0,GLdouble(w),0,GLdouble(h),-10.0,10.0);
glFlush();
glMatrixMode(GL_MODELVIEW);
glViewport( 0, 0, (GLint)w, (GLint)h );
cerr << "gl new size "<< w SEP h NL;
renderWidth = w;
renderHeight = h;
}
// no mouse events in this demo
void GLWidget::mousePressEvent( QMouseEvent * )
{
}
void GLWidget::mouseReleaseEvent( QMouseEvent *)
{
}
void GLWidget::mouseMoveEvent ( QMouseEvent * )
{
}
// wheel event
void GLWidget::wheelEvent(QWheelEvent *)
{
}
void GLWidget::openImage(QString fileBuf)
{
QImage myImage;
myImage.load(fileBuf);
prepareImageDisplay(&myImage);
}
void GLWidget::prepareImageDisplay(QImage* myimage)
{
glimage = QGLWidget::convertToGLFormat( *myimage ); // flipped 32bit RGBA stored as mi
updateGL();
}
void GLWidget::displayImage()
{
if (glimage.width()==0) {
cerr << "Null Image\n";
return;
} else {
glRasterPos2i(0,0);
glDrawPixels(glimage.width(), glimage.height(), GL_RGBA, GL_UNSIGNED_BYTE, glimage.bits());
glFlush();
}
}
void GLWidget::saveImage( QString fileBuf )
{
// there is no conversion back toQImage
// hence the need to keep qtimage as well as glimage
qtimage.save ( fileBuf ); // note it is the qtimage in the right format for saving
}
void GLWidget::makeImage( )
{
QImage myimage(renderWidth, renderHeight, QImage::Format_RGB32);
qDebug() << renderWidth;
qDebug() << renderHeight;
double widthratio = 10.0;
double heightratio = renderHeight / (renderWidth/widthratio);
QVector3D camera(widthratio/2, heightratio/2, 20);
qDebug() << camera;
QVector3D pixelposition;
QVector3D ray;
QVector<double> rayTraceResult;
for(int i=0;i<renderWidth;i++)
{
for(int j=0;j<renderHeight;j++)
{
pixelposition = QVector3D(double(i)*widthratio/renderWidth,double(j)*heightratio/renderHeight,10.0);
ray = (pixelposition-camera).normalized();
//qDebug() << "ray: " << ray;
if(i == renderWidth/2 && j == renderHeight/2)
qDebug() << "ray: " << ray;
rayTraceResult = rayTracer(ray,camera);
double r = rayTraceResult[1]*255;
double g = rayTraceResult[2]*255;
double b = rayTraceResult[3]*255;
myimage.setPixel(i,renderHeight-1-j,qRgb(r,g,b));
}
}
//myimage.setPixel(i, j, qRgb(R, G, B));
qtimage=myimage.copy(0, 0, myimage.width(), myimage.height());
prepareImageDisplay(&myimage);
}
QVector<double> GLWidget::intersectionSpheres(QVector3D ray, QVector3D camera, double closestPolygon)
{
QVector<double> result;
QVector3D pointOfIntersection,sphereNormal,lightVector,lightPosition,spherePosition,EO;
result = QVector<double>(5);
double r,cc,v,disc,d, shadeR,shadeG,shadeB;
result[0] = 0;
for(int i=0;i<spheres.length();i++)//sphere index
{
r = spheres[i].radius;
spherePosition = spheres[i].position;
EO = spherePosition-camera;
cc = QVector3D::dotProduct(EO,EO);
v = QVector3D::dotProduct(EO,ray);
disc = r*r - (cc-v*v);
if(disc>0)
{
d = sqrt(disc);
if(v-d<closestPolygon)
{
closestPolygon = v-d;
result[0] = 1;
pointOfIntersection = camera + (v-d)*ray;
//Ambience
shadeR = spheres[i].ambience[0]*sceneAmbience;
shadeG = spheres[i].ambience[1]*sceneAmbience;
shadeB = spheres[i].ambience[2]*sceneAmbience;
for(int j=0;j<lightBulbs.size();j++)
{
lightPosition = lightBulbs[j].position;
//Lambertian
sphereNormal = (pointOfIntersection - spherePosition).normalized();
lightVector = (lightPosition - pointOfIntersection).normalized();
double lightmagnitude = QVector3D::dotProduct(sphereNormal,lightVector);
double l = max(0.0,(lightmagnitude));
shadeR += spheres[i].diffuse[0]*lightBulbs[j].intensity[0]*l;
shadeG += spheres[i].diffuse[1]*lightBulbs[j].intensity[1]*l;
shadeB += spheres[i].diffuse[2]*lightBulbs[j].intensity[2]*l;
}
result[1] = shadeR;
result[2] = shadeG;
result[3] = shadeB;
}
}
}
result[4] = closestPolygon;
return result;
}
QVector<double> GLWidget::rayTracer(QVector3D ray, QVector3D camera)
{
QVector<double> result(5),intersectionResult;
double closestPolygon = pow(10,10);
QVector3D EO;
double rr,cc,v,disc;
intersectionResult = intersectionSpheres(ray,camera,closestPolygon);
if(intersectionResult[0] = 1)
{
result[1] = intersectionResult[1];
result[2] = intersectionResult[2];
result[3] = intersectionResult[3];
closestPolygon = intersectionResult[4];
}
return result;
// if(disc<=0)//ray =! intersect sphere
// {
// result.append(0.0);
// return result;
// }
// else//intersected
// {
// result.append(1.0);
// return result;
// }
}
void GLWidget::about()
{
QString vnum;
QString mess, notes;
QString title="Images in Qt and Opengl ";
vnum.setNum ( MYVERSION );
mess="Qt OpenGl image demo Release Version: ";
mess = mess+vnum;
notes = "\n\n News: Every QImage is now on stack, there is no way for memory leak. -- Lucky";
mess = mess+notes;
QMessageBox::information( this, title, mess, QMessageBox::Ok );
}
void GLWidget::help()
{
QString vnum;
QString mess, notes;
QString title="qtglimages";
vnum.setNum ( MYVERSION);
mess="Simple Image Handling in Qt/Opengl by Brian Wyvill Release Version: ";
mess = mess+vnum;
notes = "\n\n Save and Load images for display. Also Make an image such as output from a ray tracer. ";
mess = mess+notes;
QMessageBox::information( this, title, mess, QMessageBox::Ok );
}
<commit_msg>Finished Phong Shading<commit_after>//-------------------------------------------------------------------------------------------
// Painting with Flowsnakes
// fsnake program modified to use open gl vertex arrays Brian Wyvill October 2012
// added save/restore and postscript driver November 2012
// fixed memory management November 2012 delete works properly now.
// added progress bar to show memory usage.
//-------------------------------------------------------------------------------------------
#include "glwidget.h"
GLWidget::GLWidget(QWidget *parent)
: QGLWidget(parent)
{
double ambience[3] = {0.6,0.6,0.6};
double diffusal[3] = {0.6,0.6,0.6};
double spec[3] = {0.6,0.6,0.6};
double intensity[3] = {0.6,0.6,0.6};
// QVector3D circlepoint(5.0,5.0,5.0);
sceneAmbience = 0.2;
spheres.append(Sphere(QVector3D(5.0,5.0,5.0),1.0,ambience,diffusal,spec));
//spheres.append(Sphere(QVector3D(5.0,7.0,5.0),1.0,ambience,diffusal,spec));
//Spheres.append()
lightBulbs.append(LightBulb(QVector3D(4.0,2.0,7.0),0.5,intensity));
}
GLWidget::~GLWidget()
{
}
void GLWidget::clear()
{
updateGL();
}
void GLWidget::initializeGL()
{
//Background color will be white
glClearColor(1.0, 1.0, 1.0, 1.0);
glShadeModel( GL_FLAT );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glPointSize(5);
}
void GLWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
displayImage();
}
/* 2D */
void GLWidget::resizeGL( int w, int h )
{
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho(0.0,GLdouble(w),0,GLdouble(h),-10.0,10.0);
glFlush();
glMatrixMode(GL_MODELVIEW);
glViewport( 0, 0, (GLint)w, (GLint)h );
cerr << "gl new size "<< w SEP h NL;
renderWidth = w;
renderHeight = h;
}
// no mouse events in this demo
void GLWidget::mousePressEvent( QMouseEvent * )
{
}
void GLWidget::mouseReleaseEvent( QMouseEvent *)
{
}
void GLWidget::mouseMoveEvent ( QMouseEvent * )
{
}
// wheel event
void GLWidget::wheelEvent(QWheelEvent *)
{
}
void GLWidget::openImage(QString fileBuf)
{
QImage myImage;
myImage.load(fileBuf);
prepareImageDisplay(&myImage);
}
void GLWidget::prepareImageDisplay(QImage* myimage)
{
glimage = QGLWidget::convertToGLFormat( *myimage ); // flipped 32bit RGBA stored as mi
updateGL();
}
void GLWidget::displayImage()
{
if (glimage.width()==0) {
cerr << "Null Image\n";
return;
} else {
glRasterPos2i(0,0);
glDrawPixels(glimage.width(), glimage.height(), GL_RGBA, GL_UNSIGNED_BYTE, glimage.bits());
glFlush();
}
}
void GLWidget::saveImage( QString fileBuf )
{
// there is no conversion back toQImage
// hence the need to keep qtimage as well as glimage
qtimage.save ( fileBuf ); // note it is the qtimage in the right format for saving
}
void GLWidget::makeImage( )
{
QImage myimage(renderWidth, renderHeight, QImage::Format_RGB32);
qDebug() << renderWidth;
qDebug() << renderHeight;
double widthratio = 10.0;
double heightratio = renderHeight / (renderWidth/widthratio);
QVector3D camera(widthratio/2, heightratio/2, 20);
qDebug() << camera;
QVector3D pixelposition;
QVector3D ray;
QVector<double> rayTraceResult;
for(int i=0;i<renderWidth;i++)
{
for(int j=0;j<renderHeight;j++)
{
pixelposition = QVector3D(double(i)*widthratio/renderWidth,double(j)*heightratio/renderHeight,10.0);
ray = (pixelposition-camera).normalized();
//qDebug() << "ray: " << ray;
if(i == renderWidth/2 && j == renderHeight/2)
qDebug() << "ray: " << ray;
rayTraceResult = rayTracer(ray,camera);
double r = rayTraceResult[1]*255;
double g = rayTraceResult[2]*255;
double b = rayTraceResult[3]*255;
myimage.setPixel(i,renderHeight-1-j,qRgb(r,g,b));
}
}
//myimage.setPixel(i, j, qRgb(R, G, B));
qtimage=myimage.copy(0, 0, myimage.width(), myimage.height());
prepareImageDisplay(&myimage);
}
QVector<double> GLWidget::intersectionSpheres(QVector3D ray, QVector3D camera, double closestPolygon)
{
QVector<double> result;
QVector3D pointOfIntersection,sphereNormal,lightVector,lightPosition,spherePosition,EO,cameraVector,h;
result = QVector<double>(5);
double r,cc,v,disc,d, shadeR,shadeG,shadeB;
result[0] = 0;
for(int i=0;i<spheres.length();i++)//sphere index
{
r = spheres[i].radius;
spherePosition = spheres[i].position;
EO = spherePosition-camera;
cc = QVector3D::dotProduct(EO,EO);
v = QVector3D::dotProduct(EO,ray);
disc = r*r - (cc-v*v);
if(disc>0)
{
d = sqrt(disc);
if(v-d<closestPolygon)
{
closestPolygon = v-d;
result[0] = 1;
pointOfIntersection = camera + (v-d)*ray;
//Ambience
shadeR = spheres[i].ambience[0]*sceneAmbience;
shadeG = spheres[i].ambience[1]*sceneAmbience;
shadeB = spheres[i].ambience[2]*sceneAmbience;
for(int j=0;j<lightBulbs.size();j++)
{
lightPosition = lightBulbs[j].position;
//Lambertian
sphereNormal = (pointOfIntersection - spherePosition).normalized();
lightVector = (lightPosition - pointOfIntersection).normalized();
double lightmagnitude = QVector3D::dotProduct(sphereNormal,lightVector);
double l = max(0.0,(lightmagnitude));
shadeR += spheres[i].diffuse[0]*lightBulbs[j].intensity[0]*l;
shadeG += spheres[i].diffuse[1]*lightBulbs[j].intensity[1]*l;
shadeB += spheres[i].diffuse[2]*lightBulbs[j].intensity[2]*l;
//Blinn-Phong
cameraVector = (camera-pointOfIntersection).normalized();
h = (cameraVector + lightVector).normalized();
double specularmagnitude = QVector3D::dotProduct(sphereNormal,h);
double s = pow(max(0.0,specularmagnitude),100);
shadeR += spheres[i].specular[0]*lightBulbs[j].intensity[0]*s;
shadeG += spheres[i].specular[1]*lightBulbs[j].intensity[1]*s;
shadeB += spheres[i].specular[2]*lightBulbs[j].intensity[2]*s;
}
result[1] = shadeR;
result[2] = shadeG;
result[3] = shadeB;
}
}
}
result[4] = closestPolygon;
return result;
}
QVector<double> GLWidget::rayTracer(QVector3D ray, QVector3D camera)
{
QVector<double> result(5),intersectionResult;
double closestPolygon = pow(10,10);
QVector3D EO;
double rr,cc,v,disc;
intersectionResult = intersectionSpheres(ray,camera,closestPolygon);
if(intersectionResult[0] = 1)
{
result[1] = intersectionResult[1];
result[2] = intersectionResult[2];
result[3] = intersectionResult[3];
closestPolygon = intersectionResult[4];
}
return result;
// if(disc<=0)//ray =! intersect sphere
// {
// result.append(0.0);
// return result;
// }
// else//intersected
// {
// result.append(1.0);
// return result;
// }
}
void GLWidget::about()
{
QString vnum;
QString mess, notes;
QString title="Images in Qt and Opengl ";
vnum.setNum ( MYVERSION );
mess="Qt OpenGl image demo Release Version: ";
mess = mess+vnum;
notes = "\n\n News: Every QImage is now on stack, there is no way for memory leak. -- Lucky";
mess = mess+notes;
QMessageBox::information( this, title, mess, QMessageBox::Ok );
}
void GLWidget::help()
{
QString vnum;
QString mess, notes;
QString title="qtglimages";
vnum.setNum ( MYVERSION);
mess="Simple Image Handling in Qt/Opengl by Brian Wyvill Release Version: ";
mess = mess+vnum;
notes = "\n\n Save and Load images for display. Also Make an image such as output from a ray tracer. ";
mess = mess+notes;
QMessageBox::information( this, title, mess, QMessageBox::Ok );
}
<|endoftext|> |
<commit_before>/*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
//
// Created by raver119 on 29/10/17.
//
#include <system/op_boilerplate.h>
#if NOT_EXCLUDED(OP_randomuniform)
#include <ops/declarable/CustomOperations.h>
#include <helpers/RandomLauncher.h>
#include <ops/declarable/helpers/random.h>
namespace sd {
namespace ops {
///////////////////////
/**
* uniform distribution
* takes 1 ndarray
*
* T arguments map:
* TArgs[0] - min for rng
* TArgs[1] - max for rng
*/
CUSTOM_OP_IMPL(randomuniform, -1, 1, true, 0, -1) {
// uniform distribution
auto rng = block.randomGenerator();
auto dtype = DataType::FLOAT32;
if (block.getIArguments()->size())
dtype = (DataType)INT_ARG(0);
if(block.getIArguments()->size() > 1) {
auto seed = INT_ARG(1);
rng.setStates(seed,seed ^ 0xdeadbeef);
nd4j_debug("randomuniform: Setting seed %d\n",seed);
//rng.setSeed(seed);
}
auto min = block.width() > 1 ? INPUT_VARIABLE(1) : (NDArray*) nullptr;
auto max = block.width() > 2 ? INPUT_VARIABLE(2) : (NDArray*) nullptr;
bool disposable = false;
if (min == nullptr && max == nullptr && block.numT() >= 2) {
min = NDArrayFactory::create_(dtype, block.launchContext());
max = NDArrayFactory::create_(dtype, block.launchContext());
min->p(0, T_ARG(0));
max->p(0, T_ARG(1));
disposable = true;
}
auto output = OUTPUT_VARIABLE(0);
REQUIRE_TRUE(output->dataType() == dtype, 0, "RandomUniform: data type of output should be equals to given.");
helpers::fillRandomUniform(block.launchContext(), rng, min, max, output);
if (disposable) {
delete min;
delete max;
}
return Status::OK();
}
DECLARE_SHAPE_FN(randomuniform) {
auto in = INPUT_VARIABLE(0);
//auto min = INPUT_VARIABLE(1);
auto shape = in->template asVectorT<Nd4jLong>();
auto dtype = DataType::FLOAT32; //ArrayOptions::dataType(inputShape->at(1)); // output type is by given min
if (block.getIArguments()->size())
dtype = (DataType)INT_ARG(0);
if (block.width() > 1)
REQUIRE_TRUE(dtype == INPUT_VARIABLE(1)->dataType(), 0, "RandomUniform: data type of output and min/max args should be the same");
auto newShape = ConstantShapeHelper::getInstance().createShapeInfo(dtype, 'c', shape);
return SHAPELIST(newShape);
}
DECLARE_TYPES(randomuniform) {
getOpDescriptor()
->setAllowedInputTypes(0, {ALL_INTS})
->setAllowedInputTypes(1, {ALL_INTS, ALL_FLOATS})
->setAllowedInputTypes(2, {ALL_INTS, ALL_FLOATS})
->setAllowedOutputTypes({ALL_FLOATS, ALL_INTS});
}
}
}
#endif<commit_msg>uniform: change description. -2 (or values below -1 ) means unknown number of arguments or no arguments at all.<commit_after>/*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
//
// Created by raver119 on 29/10/17.
//
#include <system/op_boilerplate.h>
#if NOT_EXCLUDED(OP_randomuniform)
#include <ops/declarable/CustomOperations.h>
#include <helpers/RandomLauncher.h>
#include <ops/declarable/helpers/random.h>
namespace sd {
namespace ops {
///////////////////////
/**
* uniform distribution
* takes 1 ndarray
*
* T arguments map:
* TArgs[0] - min for rng
* TArgs[1] - max for rng
*/
CUSTOM_OP_IMPL(randomuniform, -1, 1, true, 0, -2) {
// uniform distribution
auto rng = block.randomGenerator();
auto dtype = DataType::FLOAT32;
if (block.getIArguments()->size())
dtype = (DataType)INT_ARG(0);
if(block.getIArguments()->size() > 1) {
auto seed = INT_ARG(1);
rng.setStates(seed,seed ^ 0xdeadbeef);
nd4j_debug("randomuniform: Setting seed %d\n",seed);
//rng.setSeed(seed);
}
auto min = block.width() > 1 ? INPUT_VARIABLE(1) : (NDArray*) nullptr;
auto max = block.width() > 2 ? INPUT_VARIABLE(2) : (NDArray*) nullptr;
bool disposable = false;
if (min == nullptr && max == nullptr && block.numT() >= 2) {
min = NDArrayFactory::create_(dtype, block.launchContext());
max = NDArrayFactory::create_(dtype, block.launchContext());
min->p(0, T_ARG(0));
max->p(0, T_ARG(1));
disposable = true;
}
auto output = OUTPUT_VARIABLE(0);
REQUIRE_TRUE(output->dataType() == dtype, 0, "RandomUniform: data type of output should be equals to given.");
helpers::fillRandomUniform(block.launchContext(), rng, min, max, output);
if (disposable) {
delete min;
delete max;
}
return Status::OK();
}
DECLARE_SHAPE_FN(randomuniform) {
auto in = INPUT_VARIABLE(0);
//auto min = INPUT_VARIABLE(1);
auto shape = in->template asVectorT<Nd4jLong>();
auto dtype = DataType::FLOAT32; //ArrayOptions::dataType(inputShape->at(1)); // output type is by given min
if (block.getIArguments()->size())
dtype = (DataType)INT_ARG(0);
if (block.width() > 1)
REQUIRE_TRUE(dtype == INPUT_VARIABLE(1)->dataType(), 0, "RandomUniform: data type of output and min/max args should be the same");
auto newShape = ConstantShapeHelper::getInstance().createShapeInfo(dtype, 'c', shape);
return SHAPELIST(newShape);
}
DECLARE_TYPES(randomuniform) {
getOpDescriptor()
->setAllowedInputTypes(0, {ALL_INTS})
->setAllowedInputTypes(1, {ALL_INTS, ALL_FLOATS})
->setAllowedInputTypes(2, {ALL_INTS, ALL_FLOATS})
->setAllowedOutputTypes({ALL_FLOATS, ALL_INTS});
}
}
}
#endif<|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.
*/
#include <ctype.h>
#include <assert.h>
#include <string.h>
// offsetof macro
#include <stddef.h>
#include "port_malloc.h"
#include "port_unwind.h"
#include "port_modules.h"
#include "port_crash_handler.h"
#include "port_frame_info.h"
#include "stack_dump.h"
static native_module_t* g_modules = NULL;
// Is called to fill modules list (should be called under lock)
static void sd_fill_modules()
{
if (g_modules)
return;
int count;
bool res = port_get_all_modules(&g_modules, &count);
assert(res && g_modules && count);
}
// "%s::%s (%s): %s:%d" - class::name (signature): file:line
static const char* vm_fmt_tbl[] = {
// method_class_name is present
"%s::%s (%s): %s:%d\n",
"%s::%s (%s)\n", // No sourcefile
"%s::%s: %s:%d\n", // No signature
"%s::%s\n", // No signature no sourcefile
// method_class_name is absent
"%s (%s): %s:%d\n",
"%s (%s)\n", // No sourcefile
"%s: %s:%d\n", // No signature
"%s\n", // No signature no sourcefile
};
static void sd_print_vm_line(FILE* file, int count, port_stack_frame_info* fi)
{
if (!fi->method_name)
return;
if (count >= 0)
fprintf(file, "%3d: ", count);
else
fprintf(file, " "); // additional VM info - indent
const void* args[5] = {fi->method_class_name, fi->method_name,
fi->method_signature, fi->source_file_name,
(const void*)(size_t)fi->source_line_number};
const void** pargs = args;
int fmt_num = 0;
if (!fi->method_class_name)
{
fmt_num += 4;
pargs++;
}
if (!fi->method_signature)
{
fmt_num += 2;
args[2] = args[3];
args[3] = args[4];
}
if (!fi->source_file_name)
fmt_num += 1;
fprintf(file, vm_fmt_tbl[fmt_num],
pargs[0], pargs[1], pargs[2], pargs[3], pargs[4]);
}
static void sd_print_c_line(FILE* file, int count, CFunInfo* cfi)
{
if (!cfi->name)
return;
fprintf(file, "%3d: %s (%s:%d)\n",
count, cfi->name,
cfi->filename ? cfi->filename : "??",
cfi->line);
}
static void sd_print_modules()
{
sd_fill_modules(); // Fill modules table if needed
fprintf(stderr, "\nLoaded modules:\n\n");
port_dump_modules(g_modules, stderr);
}
static void sd_print_stack(Registers* regs, port_unwind_compiled_frame unwind)
{
if (!regs)
{
fprintf(stderr, "\nNo stack trace due to registers info absence\n");
return;
}
fprintf(stderr, "\nStack trace:\n");
Registers locregs = *regs;
UnwindContext uwcontext;
bool hasnative = false;
if (port_init_unwind_context(&uwcontext, g_modules, &locregs))
hasnative = true;
port_stack_frame_info uwinfo;
int framenum = 0;
int uwresult = -1;
// Prepare VM-specific struct for stack iteration
if (unwind)
{
memset(&uwinfo, 0, sizeof(port_stack_frame_info));
uwresult = unwind(&locregs, &uwinfo);
}
if (uwresult > 0)
{
uwinfo.iteration_state = STD_ALLOCA(uwresult);
memset(uwinfo.iteration_state, 0, uwresult);
uwresult = unwind(&locregs, &uwinfo);
assert(uwresult <= 0);
}
while (true)
{
// Unwinding with VM callback
if (unwind && uwresult == 0)
{
sd_print_vm_line(stderr, framenum++, &uwinfo);
// Cleanup frame info except 'iteration_state'
memset(&uwinfo, 0, offsetof(port_stack_frame_info, iteration_state));
// Try unwinding by the callback for next iteration
uwresult = unwind(&locregs, &uwinfo);
continue;
}
// Print native frame info
CFunInfo cfi = {0};
native_module_t* module = port_find_module(g_modules, locregs.get_ip());
sd_get_c_method_info(&cfi, module, locregs.get_ip());
sd_print_c_line(stderr, framenum++, &cfi);
if (unwind && uwresult < 0 && uwinfo.method_name)
{ // VM has not unwound but has provided additional frame info
sd_print_vm_line(stderr, -1, &uwinfo); // Print as additional info
}
if (!hasnative) // Native unwinding is not initialized
break;
// Try native unwinding
bool nativeres = port_unwind_frame(&uwcontext, &locregs);
if (!nativeres)
break; // Neither VM calback nor native unwinding can unwind the frame
// Cleanup frame info except 'iteration_state'
memset(&uwinfo, 0, offsetof(port_stack_frame_info, iteration_state));
// Try unwinding by the callback for next iteration
uwresult = unwind(&locregs, &uwinfo);
}
if (hasnative)
port_clean_unwind_context(&uwcontext);
fprintf(stderr, "<end of stack trace>\n");
fflush(stderr);
}
struct sig_name_t
{
int num;
char* name;
};
static sig_name_t sig_names[] =
{
{PORT_SIGNAL_GPF, "GENERAL_PROTECTION_FAULT"},
{PORT_SIGNAL_STACK_OVERFLOW, "STACK_OVERFLOW"},
{PORT_SIGNAL_ABORT, "ABORT" },
{PORT_SIGNAL_QUIT, "QUIT"},
{PORT_SIGNAL_CTRL_C, "CTRL_C" },
{PORT_SIGNAL_CTRL_BREAK, "CTRL_BREAK" },
{PORT_SIGNAL_BREAKPOINT, "BREAKPOINT"},
{PORT_SIGNAL_ARITHMETIC, "ARITHMETIC_EXCEPTION" },
{PORT_SIGNAL_UNKNOWN, "UNKNOWN"}
};
static const char* get_sig_name(int signum)
{
for (int i = 0; i < sizeof(sig_names)/sizeof(sig_names[0]); i++)
{
if (signum == sig_names[i].num)
return sig_names[i].name;
}
return "unknown signal";
}
static void print_name_and_context(int signum, Registers* regs)
{
// Print signal name
fprintf(stderr, "\nSignal reported: %s\n", get_sig_name(signum));
// Print register state
if (regs)
print_reg_state(regs);
else
fprintf(stderr, "\nRegisters info is absent\n");
}
void sd_print_crash_info(int signum, Registers* regs, port_unwind_compiled_frame unwind)
{
// Print signal name and register info
if (port_crash_handler_get_flags() & PORT_CRASH_PRINT_REGISTERS)
print_name_and_context(signum, regs);
// Print command line and working directory
if (port_crash_handler_get_flags() & PORT_CRASH_PRINT_COMMAND_LINE)
sd_print_cmdline_cwd();
// Print program environment info
if (port_crash_handler_get_flags() & PORT_CRASH_PRINT_ENVIRONMENT)
sd_print_environment();
// Print the whole list of modules
if (port_crash_handler_get_flags() & PORT_CRASH_PRINT_MODULES)
sd_print_modules();
// Print stack of crashed module
if (port_crash_handler_get_flags() & PORT_CRASH_STACK_DUMP)
sd_print_stack(regs, unwind);
}
<commit_msg>Applied patch from HARMONY-5685 [drlvm][port][signals] Crash handler does not print stack dump when list of modules was not printed<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.
*/
#include <ctype.h>
#include <assert.h>
#include <string.h>
// offsetof macro
#include <stddef.h>
#include "port_malloc.h"
#include "port_unwind.h"
#include "port_modules.h"
#include "port_crash_handler.h"
#include "port_frame_info.h"
#include "stack_dump.h"
static native_module_t* g_modules = NULL;
// Is called to fill modules list (should be called under lock)
static void sd_fill_modules()
{
if (g_modules)
return;
int count;
bool res = port_get_all_modules(&g_modules, &count);
assert(res && g_modules && count);
}
// "%s::%s (%s): %s:%d" - class::name (signature): file:line
static const char* vm_fmt_tbl[] = {
// method_class_name is present
"%s::%s (%s): %s:%d\n",
"%s::%s (%s)\n", // No sourcefile
"%s::%s: %s:%d\n", // No signature
"%s::%s\n", // No signature no sourcefile
// method_class_name is absent
"%s (%s): %s:%d\n",
"%s (%s)\n", // No sourcefile
"%s: %s:%d\n", // No signature
"%s\n", // No signature no sourcefile
};
static void sd_print_vm_line(FILE* file, int count, port_stack_frame_info* fi)
{
if (!fi->method_name)
return;
if (count >= 0)
fprintf(file, "%3d: ", count);
else
fprintf(file, " "); // additional VM info - indent
const void* args[5] = {fi->method_class_name, fi->method_name,
fi->method_signature, fi->source_file_name,
(const void*)(size_t)fi->source_line_number};
const void** pargs = args;
int fmt_num = 0;
if (!fi->method_class_name)
{
fmt_num += 4;
pargs++;
}
if (!fi->method_signature)
{
fmt_num += 2;
args[2] = args[3];
args[3] = args[4];
}
if (!fi->source_file_name)
fmt_num += 1;
fprintf(file, vm_fmt_tbl[fmt_num],
pargs[0], pargs[1], pargs[2], pargs[3], pargs[4]);
}
static void sd_print_c_line(FILE* file, int count, CFunInfo* cfi)
{
if (!cfi->name)
return;
fprintf(file, "%3d: %s (%s:%d)\n",
count, cfi->name,
cfi->filename ? cfi->filename : "??",
cfi->line);
}
static void sd_print_modules()
{
sd_fill_modules(); // Fill modules table if needed
fprintf(stderr, "\nLoaded modules:\n\n");
port_dump_modules(g_modules, stderr);
}
static void sd_print_stack(Registers* regs, port_unwind_compiled_frame unwind)
{
if (!regs)
{
fprintf(stderr, "\nNo stack trace due to registers info absence\n");
return;
}
fprintf(stderr, "\nStack trace:\n");
Registers locregs = *regs;
UnwindContext uwcontext;
bool hasnative = false;
if (port_init_unwind_context(&uwcontext, g_modules, &locregs))
hasnative = true;
port_stack_frame_info uwinfo;
int framenum = 0;
int uwresult = -1;
// Prepare VM-specific struct for stack iteration
if (unwind)
{
memset(&uwinfo, 0, sizeof(port_stack_frame_info));
uwresult = unwind(&locregs, &uwinfo);
}
if (uwresult > 0)
{
uwinfo.iteration_state = STD_ALLOCA(uwresult);
memset(uwinfo.iteration_state, 0, uwresult);
uwresult = unwind(&locregs, &uwinfo);
assert(uwresult <= 0);
}
while (true)
{
// Unwinding with VM callback
if (unwind && uwresult == 0)
{
sd_print_vm_line(stderr, framenum++, &uwinfo);
// Cleanup frame info except 'iteration_state'
memset(&uwinfo, 0, offsetof(port_stack_frame_info, iteration_state));
// Try unwinding by the callback for next iteration
uwresult = unwind(&locregs, &uwinfo);
continue;
}
// Print native frame info
CFunInfo cfi = {0};
native_module_t* module = port_find_module(uwcontext.modules, locregs.get_ip());
sd_get_c_method_info(&cfi, module, locregs.get_ip());
sd_print_c_line(stderr, framenum++, &cfi);
if (unwind && uwresult < 0 && uwinfo.method_name)
{ // VM has not unwound but has provided additional frame info
sd_print_vm_line(stderr, -1, &uwinfo); // Print as additional info
}
if (!hasnative) // Native unwinding is not initialized
break;
// Try native unwinding
bool nativeres = port_unwind_frame(&uwcontext, &locregs);
if (!nativeres)
break; // Neither VM calback nor native unwinding can unwind the frame
// Cleanup frame info except 'iteration_state'
memset(&uwinfo, 0, offsetof(port_stack_frame_info, iteration_state));
// Try unwinding by the callback for next iteration
uwresult = unwind(&locregs, &uwinfo);
}
if (hasnative)
port_clean_unwind_context(&uwcontext);
fprintf(stderr, "<end of stack trace>\n");
fflush(stderr);
}
struct sig_name_t
{
int num;
char* name;
};
static sig_name_t sig_names[] =
{
{PORT_SIGNAL_GPF, "GENERAL_PROTECTION_FAULT"},
{PORT_SIGNAL_STACK_OVERFLOW, "STACK_OVERFLOW"},
{PORT_SIGNAL_ABORT, "ABORT" },
{PORT_SIGNAL_QUIT, "QUIT"},
{PORT_SIGNAL_CTRL_C, "CTRL_C" },
{PORT_SIGNAL_CTRL_BREAK, "CTRL_BREAK" },
{PORT_SIGNAL_BREAKPOINT, "BREAKPOINT"},
{PORT_SIGNAL_ARITHMETIC, "ARITHMETIC_EXCEPTION" },
{PORT_SIGNAL_UNKNOWN, "UNKNOWN"}
};
static const char* get_sig_name(int signum)
{
for (int i = 0; i < sizeof(sig_names)/sizeof(sig_names[0]); i++)
{
if (signum == sig_names[i].num)
return sig_names[i].name;
}
return "unknown signal";
}
static void print_name_and_context(int signum, Registers* regs)
{
// Print signal name
fprintf(stderr, "\nSignal reported: %s\n", get_sig_name(signum));
// Print register state
if (regs)
print_reg_state(regs);
else
fprintf(stderr, "\nRegisters info is absent\n");
}
void sd_print_crash_info(int signum, Registers* regs, port_unwind_compiled_frame unwind)
{
// Print signal name and register info
if (port_crash_handler_get_flags() & PORT_CRASH_PRINT_REGISTERS)
print_name_and_context(signum, regs);
// Print command line and working directory
if (port_crash_handler_get_flags() & PORT_CRASH_PRINT_COMMAND_LINE)
sd_print_cmdline_cwd();
// Print program environment info
if (port_crash_handler_get_flags() & PORT_CRASH_PRINT_ENVIRONMENT)
sd_print_environment();
// Print the whole list of modules
if (port_crash_handler_get_flags() & PORT_CRASH_PRINT_MODULES)
sd_print_modules();
// Print stack of crashed module
if (port_crash_handler_get_flags() & PORT_CRASH_STACK_DUMP)
sd_print_stack(regs, unwind);
}
<|endoftext|> |
<commit_before>/*
* NotebookQueue.cpp
*
* Copyright (C) 2009-16 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 "SessionRmdNotebook.hpp"
#include "NotebookQueue.hpp"
#include "NotebookQueueUnit.hpp"
#include "NotebookExec.hpp"
#include "NotebookDocQueue.hpp"
#include "NotebookCache.hpp"
#include "NotebookAlternateEngines.hpp"
#include "../../SessionClientEventService.hpp"
#include <boost/foreach.hpp>
#include <r/RInterface.hpp>
#include <core/Exec.hpp>
#include <core/Thread.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/SessionClientEvent.hpp>
#include <session/http/SessionRequest.hpp>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace rmarkdown {
namespace notebook {
namespace {
enum ChunkExecState
{
ChunkExecStarted = 0,
ChunkExecFinished = 1,
ChunkExecCancelled = 2
};
// represents the global queue of work
class NotebookQueue
{
public:
NotebookQueue()
{
// launch a thread to process console input
thread::safeLaunchThread(boost::bind(
&NotebookQueue::consoleThreadMain, this), &console_);
// register handler for chunk exec complete
handlers_.push_back(events().onChunkExecCompleted.connect(
boost::bind(&NotebookQueue::onChunkExecCompleted, this, _1, _2, _3)));
}
~NotebookQueue()
{
// clean up thread
console_.detach();
// unregister handlers
BOOST_FOREACH(boost::signals::connection connection, handlers_)
{
connection.disconnect();
}
}
bool complete()
{
return queue_.empty();
}
Error process()
{
// if list is empty, we're done
if (queue_.empty())
return Success();
// defer if R is currently executing code (we'll initiate processing when
// the console continues)
if (r::getGlobalContext()->nextcontext != NULL)
return Success();
// if we have a currently executing unit, execute it; otherwise, pop the
// next unit off the stack
if (execUnit_)
{
if (execContext_ && execContext_->hasErrors())
{
// when an error occurs, see what the chunk options say; if they
// have error = TRUE we can keep going, but in all other
// circumstances we should stop right away
const json::Object& options = execContext_->options();
bool error = false;
json::readObject(options, "error", &error);
if (!error)
{
clear();
return Success();
}
}
if (execUnit_->complete())
{
// unit has finished executing; remove it from the queue
popUnit(execUnit_);
// notify client
enqueueExecStateChanged(ChunkExecFinished, execContext_->options());
// clean up current exec unit
execContext_->disconnect();
execContext_.reset();
execUnit_.reset();
}
else
return executeCurrentUnit();
}
return executeNextUnit();
}
Error update(boost::shared_ptr<NotebookQueueUnit> pUnit, QueueOperation op,
const std::string& before)
{
// find the document queue corresponding to this unit
BOOST_FOREACH(const boost::shared_ptr<NotebookDocQueue> queue, queue_)
{
if (queue->docId() == pUnit->docId())
{
queue->update(pUnit, op, before);
break;
}
}
return Success();
}
void add(boost::shared_ptr<NotebookDocQueue> pQueue)
{
queue_.push_back(pQueue);
}
void clear()
{
// clean up any active execution context
if (execContext_)
execContext_->disconnect();
// remove all document queues
queue_.clear();
}
json::Value getDocQueue(const std::string& docId)
{
BOOST_FOREACH(boost::shared_ptr<NotebookDocQueue> pQueue, queue_)
{
if (pQueue->docId() == docId)
return pQueue->toJson();
}
return json::Value();
}
void onConsolePrompt(const std::string& prompt)
{
process();
}
private:
void onChunkExecCompleted(const std::string& docId,
const std::string& chunkId, const std::string& nbCtxId)
{
if (!execUnit_)
return;
// if this is the currently executing chunk but it doesn't have an R
// execution context, it must be executing with an alternate engine;
// this event signals that the alternate engine is finished, so move to
// the next document in the queue
if (execUnit_->docId() == docId && execUnit_->chunkId() == chunkId &&
!execContext_)
{
// remove from the queue
popUnit(execUnit_);
// signal client
enqueueExecStateChanged(ChunkExecFinished, json::Object());
// execute the next chunk, if any
execUnit_.reset();
process();
}
}
// execute the next line or expression in the current execution unit
Error executeCurrentUnit()
{
// ensure we have a unit to execute
if (!execUnit_)
return Success();
json::Array arr;
ExecRange range(0, 0);
arr.push_back(execUnit_->popExecRange(&range));
arr.push_back(execUnit_->chunkId());
// formulate request body
json::Object rpc;
rpc["method"] = "console_input";
rpc["params"] = arr;
rpc["clientId"] = clientEventService().clientId();
// serialize RPC body and send it to helper thread for submission
std::ostringstream oss;
json::write(rpc, oss);
input_.enque(oss.str());
// let client know the range has been sent to R
json::Object exec;
exec["doc_id"] = execUnit_->docId();
exec["chunk_id"] = execUnit_->chunkId();
exec["exec_range"] = range.toJson();
module_context::enqueClientEvent(
ClientEvent(client_events::kNotebookRangeExecuted, exec));
return Success();
}
Error executeNextUnit()
{
// no work to do if we have no documents
if (queue_.empty())
return Success();
// get the next execution unit from the current queue
boost::shared_ptr<NotebookDocQueue> docQueue = *queue_.begin();
if (docQueue->complete())
return Success();
boost::shared_ptr<NotebookQueueUnit> unit = docQueue->firstUnit();
// establish execution context for the unit
json::Object options;
Error error = unit->parseOptions(&options);
if (error)
return error;
// in batch mode, make sure unit should be evaluated -- note that
// eval=FALSE units generally do not get sent up in the first place, so
// if we're here it's because the unit has eval=<expr>
if (unit->execMode() == ExecModeBatch)
{
bool eval = true;
json::readObject(options, "eval", &eval);
if (!eval)
return skipUnit();
}
// compute context
std::string ctx = docQueue->commitMode() == ModeCommitted ?
kSavedCtx : notebookCtxId();
// compute engine
std::string engine = "r";
json::readObject(options, "engine", &engine);
if (engine == "r")
{
execContext_ = boost::make_shared<ChunkExecContext>(
unit->docId(), unit->chunkId(), ctx, unit->execScope(), options,
docQueue->pixelWidth(), docQueue->charWidth());
execContext_->connect();
}
else
{
// execute with alternate engine
std::string innerCode;
error = unit->innerCode(&innerCode);
if (error)
{
LOG_ERROR(error);
}
else
{
error = executeAlternateEngineChunk(
unit->docId(), unit->chunkId(), ctx, engine, innerCode, options);
if (error)
LOG_ERROR(error);
}
}
// if there was an error, skip the chunk
if (error)
return skipUnit();
// notify client
execUnit_ = unit;
enqueueExecStateChanged(ChunkExecStarted, options);
if (engine == "r")
executeCurrentUnit();
return Success();
}
// main function for thread which receives console input
void consoleThreadMain()
{
std::string input;
while (input_.deque(&input, boost::posix_time::not_a_date_time))
{
// loop back console input request to session -- this allows us to treat
// notebook console input exactly as user console input
core::http::Response response;
Error error = session::http::sendSessionRequest(
"/rpc/console_input", input, &response);
if (error)
LOG_ERROR(error);
}
}
void enqueueExecStateChanged(ChunkExecState state,
const json::Object& options)
{
json::Object event;
event["doc_id"] = execUnit_->docId();
event["chunk_id"] = execUnit_->chunkId();
event["exec_state"] = state;
event["options"] = options;
module_context::enqueClientEvent(ClientEvent(
client_events::kChunkExecStateChanged, event));
}
Error skipUnit()
{
if (queue_.empty())
return Success();
boost::shared_ptr<NotebookDocQueue> docQueue = *queue_.begin();
if (docQueue->complete())
return Success();
boost::shared_ptr<NotebookQueueUnit> unit = docQueue->firstUnit();
popUnit(unit);
execUnit_ = unit;
enqueueExecStateChanged(ChunkExecCancelled, json::Object());
return executeNextUnit();
}
void popUnit(boost::shared_ptr<NotebookQueueUnit> pUnit)
{
if (queue_.empty())
return;
// remove this unit from the queue
boost::shared_ptr<NotebookDocQueue> docQueue = *queue_.begin();
docQueue->update(pUnit, QueueDelete, "");
// advance if queue is complete
if (docQueue->complete())
queue_.pop_front();
}
// the documents with active queues
std::list<boost::shared_ptr<NotebookDocQueue> > queue_;
// the execution context for the currently executing chunk
boost::shared_ptr<NotebookQueueUnit> execUnit_;
boost::shared_ptr<ChunkExecContext> execContext_;
// registered signal handlers
std::vector<boost::signals::connection> handlers_;
// the thread which submits console input, and the queue which feeds it
boost::thread console_;
core::thread::ThreadsafeQueue<std::string> input_;
};
static boost::shared_ptr<NotebookQueue> s_queue;
Error updateExecQueue(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
json::Object unitJson;
int op = 0;
std::string before;
Error error = json::readParams(request.params, &unitJson, &op, &before);
if (error)
return error;
boost::shared_ptr<NotebookQueueUnit> pUnit =
boost::make_shared<NotebookQueueUnit>();
error = NotebookQueueUnit::fromJson(unitJson, &pUnit);
if (error)
return error;
if (!s_queue)
return Success();
return s_queue->update(pUnit, static_cast<QueueOperation>(op), before);
}
Error executeNotebookChunks(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
json::Object docObj;
Error error = json::readParams(request.params, &docObj);
boost::shared_ptr<NotebookDocQueue> pQueue =
boost::make_shared<NotebookDocQueue>();
error = NotebookDocQueue::fromJson(docObj, &pQueue);
if (error)
return error;
// create queue if it doesn't exist
if (!s_queue)
s_queue = boost::make_shared<NotebookQueue>();
// add the queue and process immediately
s_queue->add(pQueue);
s_queue->process();
return Success();
}
void onConsolePrompt(const std::string& prompt)
{
if (s_queue)
{
s_queue->onConsolePrompt(prompt);
}
// clean up queue if it's finished executing
if (s_queue && s_queue->complete())
{
s_queue.reset();
}
}
void onUserInterrupt()
{
if (s_queue)
{
s_queue->clear();
s_queue.reset();
}
}
} // anonymous namespace
json::Value getDocQueue(const std::string& docId)
{
if (!s_queue)
return json::Value();
return s_queue->getDocQueue(docId);
}
Error initQueue()
{
using boost::bind;
using namespace module_context;
module_context::events().onConsolePrompt.connect(onConsolePrompt);
module_context::events().onUserInterrupt.connect(onUserInterrupt);
ExecBlock initBlock;
initBlock.addFunctions()
(bind(registerRpcMethod, "update_notebook_exec_queue", updateExecQueue))
(bind(registerRpcMethod, "execute_notebook_chunks", executeNotebookChunks));
return initBlock.execute();
}
} // namespace notebook
} // namespace rmarkdown
} // namespace modules
} // namespace session
} // namespace rstudio
<commit_msg>clean up console input processing thread safely<commit_after>/*
* NotebookQueue.cpp
*
* Copyright (C) 2009-16 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 "SessionRmdNotebook.hpp"
#include "NotebookQueue.hpp"
#include "NotebookQueueUnit.hpp"
#include "NotebookExec.hpp"
#include "NotebookDocQueue.hpp"
#include "NotebookCache.hpp"
#include "NotebookAlternateEngines.hpp"
#include "../../SessionClientEventService.hpp"
#include <boost/foreach.hpp>
#include <r/RInterface.hpp>
#include <core/Exec.hpp>
#include <core/Thread.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/SessionClientEvent.hpp>
#include <session/http/SessionRequest.hpp>
#define kThreadQuitCommand "thread_quit"
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace rmarkdown {
namespace notebook {
namespace {
enum ChunkExecState
{
ChunkExecStarted = 0,
ChunkExecFinished = 1,
ChunkExecCancelled = 2
};
// represents the global queue of work
class NotebookQueue
{
public:
NotebookQueue()
{
// launch a thread to process console input
pInput_ =
boost::make_shared<core::thread::ThreadsafeQueue<std::string> >();
thread::safeLaunchThread(boost::bind(
&NotebookQueue::consoleThreadMain, this), &console_);
// register handler for chunk exec complete
handlers_.push_back(events().onChunkExecCompleted.connect(
boost::bind(&NotebookQueue::onChunkExecCompleted, this, _1, _2, _3)));
}
~NotebookQueue()
{
// let thread clean up asynchronously
pInput_->enque(kThreadQuitCommand);
// unregister handlers
BOOST_FOREACH(boost::signals::connection connection, handlers_)
{
connection.disconnect();
}
}
bool complete()
{
return queue_.empty();
}
Error process()
{
// if list is empty, we're done
if (queue_.empty())
return Success();
// defer if R is currently executing code (we'll initiate processing when
// the console continues)
if (r::getGlobalContext()->nextcontext != NULL)
return Success();
// if we have a currently executing unit, execute it; otherwise, pop the
// next unit off the stack
if (execUnit_)
{
if (execContext_ && execContext_->hasErrors())
{
// when an error occurs, see what the chunk options say; if they
// have error = TRUE we can keep going, but in all other
// circumstances we should stop right away
const json::Object& options = execContext_->options();
bool error = false;
json::readObject(options, "error", &error);
if (!error)
{
clear();
return Success();
}
}
if (execUnit_->complete())
{
// unit has finished executing; remove it from the queue
popUnit(execUnit_);
// notify client
enqueueExecStateChanged(ChunkExecFinished, execContext_->options());
// clean up current exec unit
execContext_->disconnect();
execContext_.reset();
execUnit_.reset();
}
else
return executeCurrentUnit();
}
return executeNextUnit();
}
Error update(boost::shared_ptr<NotebookQueueUnit> pUnit, QueueOperation op,
const std::string& before)
{
// find the document queue corresponding to this unit
BOOST_FOREACH(const boost::shared_ptr<NotebookDocQueue> queue, queue_)
{
if (queue->docId() == pUnit->docId())
{
queue->update(pUnit, op, before);
break;
}
}
return Success();
}
void add(boost::shared_ptr<NotebookDocQueue> pQueue)
{
queue_.push_back(pQueue);
}
void clear()
{
// clean up any active execution context
if (execContext_)
execContext_->disconnect();
// remove all document queues
queue_.clear();
}
json::Value getDocQueue(const std::string& docId)
{
BOOST_FOREACH(boost::shared_ptr<NotebookDocQueue> pQueue, queue_)
{
if (pQueue->docId() == docId)
return pQueue->toJson();
}
return json::Value();
}
void onConsolePrompt(const std::string& prompt)
{
process();
}
private:
void onChunkExecCompleted(const std::string& docId,
const std::string& chunkId, const std::string& nbCtxId)
{
if (!execUnit_)
return;
// if this is the currently executing chunk but it doesn't have an R
// execution context, it must be executing with an alternate engine;
// this event signals that the alternate engine is finished, so move to
// the next document in the queue
if (execUnit_->docId() == docId && execUnit_->chunkId() == chunkId &&
!execContext_)
{
// remove from the queue
popUnit(execUnit_);
// signal client
enqueueExecStateChanged(ChunkExecFinished, json::Object());
// execute the next chunk, if any
execUnit_.reset();
process();
}
}
// execute the next line or expression in the current execution unit
Error executeCurrentUnit()
{
// ensure we have a unit to execute
if (!execUnit_)
return Success();
json::Array arr;
ExecRange range(0, 0);
arr.push_back(execUnit_->popExecRange(&range));
arr.push_back(execUnit_->chunkId());
// formulate request body
json::Object rpc;
rpc["method"] = "console_input";
rpc["params"] = arr;
rpc["clientId"] = clientEventService().clientId();
// serialize RPC body and send it to helper thread for submission
std::ostringstream oss;
json::write(rpc, oss);
pInput_->enque(oss.str());
// let client know the range has been sent to R
json::Object exec;
exec["doc_id"] = execUnit_->docId();
exec["chunk_id"] = execUnit_->chunkId();
exec["exec_range"] = range.toJson();
module_context::enqueClientEvent(
ClientEvent(client_events::kNotebookRangeExecuted, exec));
return Success();
}
Error executeNextUnit()
{
// no work to do if we have no documents
if (queue_.empty())
return Success();
// get the next execution unit from the current queue
boost::shared_ptr<NotebookDocQueue> docQueue = *queue_.begin();
if (docQueue->complete())
return Success();
boost::shared_ptr<NotebookQueueUnit> unit = docQueue->firstUnit();
// establish execution context for the unit
json::Object options;
Error error = unit->parseOptions(&options);
if (error)
return error;
// in batch mode, make sure unit should be evaluated -- note that
// eval=FALSE units generally do not get sent up in the first place, so
// if we're here it's because the unit has eval=<expr>
if (unit->execMode() == ExecModeBatch)
{
bool eval = true;
json::readObject(options, "eval", &eval);
if (!eval)
return skipUnit();
}
// compute context
std::string ctx = docQueue->commitMode() == ModeCommitted ?
kSavedCtx : notebookCtxId();
// compute engine
std::string engine = "r";
json::readObject(options, "engine", &engine);
if (engine == "r")
{
execContext_ = boost::make_shared<ChunkExecContext>(
unit->docId(), unit->chunkId(), ctx, unit->execScope(), options,
docQueue->pixelWidth(), docQueue->charWidth());
execContext_->connect();
}
else
{
// execute with alternate engine
std::string innerCode;
error = unit->innerCode(&innerCode);
if (error)
{
LOG_ERROR(error);
}
else
{
error = executeAlternateEngineChunk(
unit->docId(), unit->chunkId(), ctx, engine, innerCode, options);
if (error)
LOG_ERROR(error);
}
}
// if there was an error, skip the chunk
if (error)
return skipUnit();
// notify client
execUnit_ = unit;
enqueueExecStateChanged(ChunkExecStarted, options);
if (engine == "r")
executeCurrentUnit();
return Success();
}
// main function for thread which receives console input
void consoleThreadMain()
{
// create our own reference to the threadsafe queue (this prevents it
// from getting cleaned up when the parent detaches)
boost::shared_ptr<core::thread::ThreadsafeQueue<std::string> > pInput =
pInput_;
std::string input;
while (pInput->deque(&input, boost::posix_time::not_a_date_time))
{
// if we were asked to quit, stop processing now
if (input == kThreadQuitCommand)
return;
// loop back console input request to session -- this allows us to treat
// notebook console input exactly as user console input
core::http::Response response;
Error error = session::http::sendSessionRequest(
"/rpc/console_input", input, &response);
if (error)
LOG_ERROR(error);
}
}
void enqueueExecStateChanged(ChunkExecState state,
const json::Object& options)
{
json::Object event;
event["doc_id"] = execUnit_->docId();
event["chunk_id"] = execUnit_->chunkId();
event["exec_state"] = state;
event["options"] = options;
module_context::enqueClientEvent(ClientEvent(
client_events::kChunkExecStateChanged, event));
}
Error skipUnit()
{
if (queue_.empty())
return Success();
boost::shared_ptr<NotebookDocQueue> docQueue = *queue_.begin();
if (docQueue->complete())
return Success();
boost::shared_ptr<NotebookQueueUnit> unit = docQueue->firstUnit();
popUnit(unit);
execUnit_ = unit;
enqueueExecStateChanged(ChunkExecCancelled, json::Object());
return executeNextUnit();
}
void popUnit(boost::shared_ptr<NotebookQueueUnit> pUnit)
{
if (queue_.empty())
return;
// remove this unit from the queue
boost::shared_ptr<NotebookDocQueue> docQueue = *queue_.begin();
docQueue->update(pUnit, QueueDelete, "");
// advance if queue is complete
if (docQueue->complete())
queue_.pop_front();
}
// the documents with active queues
std::list<boost::shared_ptr<NotebookDocQueue> > queue_;
// the execution context for the currently executing chunk
boost::shared_ptr<NotebookQueueUnit> execUnit_;
boost::shared_ptr<ChunkExecContext> execContext_;
// registered signal handlers
std::vector<boost::signals::connection> handlers_;
// the thread which submits console input, and the queue which feeds it
boost::thread console_;
boost::shared_ptr<core::thread::ThreadsafeQueue<std::string> > pInput_;
};
static boost::shared_ptr<NotebookQueue> s_queue;
Error updateExecQueue(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
json::Object unitJson;
int op = 0;
std::string before;
Error error = json::readParams(request.params, &unitJson, &op, &before);
if (error)
return error;
boost::shared_ptr<NotebookQueueUnit> pUnit =
boost::make_shared<NotebookQueueUnit>();
error = NotebookQueueUnit::fromJson(unitJson, &pUnit);
if (error)
return error;
if (!s_queue)
return Success();
return s_queue->update(pUnit, static_cast<QueueOperation>(op), before);
}
Error executeNotebookChunks(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
json::Object docObj;
Error error = json::readParams(request.params, &docObj);
boost::shared_ptr<NotebookDocQueue> pQueue =
boost::make_shared<NotebookDocQueue>();
error = NotebookDocQueue::fromJson(docObj, &pQueue);
if (error)
return error;
// create queue if it doesn't exist
if (!s_queue)
s_queue = boost::make_shared<NotebookQueue>();
// add the queue and process immediately
s_queue->add(pQueue);
s_queue->process();
return Success();
}
void onConsolePrompt(const std::string& prompt)
{
if (s_queue)
{
s_queue->onConsolePrompt(prompt);
}
// clean up queue if it's finished executing
if (s_queue && s_queue->complete())
{
s_queue.reset();
}
}
void onUserInterrupt()
{
if (s_queue)
{
s_queue->clear();
s_queue.reset();
}
}
} // anonymous namespace
json::Value getDocQueue(const std::string& docId)
{
if (!s_queue)
return json::Value();
return s_queue->getDocQueue(docId);
}
Error initQueue()
{
using boost::bind;
using namespace module_context;
module_context::events().onConsolePrompt.connect(onConsolePrompt);
module_context::events().onUserInterrupt.connect(onUserInterrupt);
ExecBlock initBlock;
initBlock.addFunctions()
(bind(registerRpcMethod, "update_notebook_exec_queue", updateExecQueue))
(bind(registerRpcMethod, "execute_notebook_chunks", executeNotebookChunks));
return initBlock.execute();
}
} // namespace notebook
} // namespace rmarkdown
} // namespace modules
} // namespace session
} // namespace rstudio
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id: */
//____________________________________________________________________
//
// T0 - T0.
//
// This class is a singleton that handles various parameters of
// the T0 detectors.
// Eventually, this class will use the Conditions DB to get the
// various parameters, which code can then request from here.
//
#include "AliLog.h"
#include "AliT0Parameters.h"
#include "AliT0CalibData.h"
#include "AliT0LookUpValue.h"
#include <AliCDBManager.h>
#include <AliCDBEntry.h>
#include <AliCDBStorage.h>
#include <TMath.h>
#include <TSystem.h>
#include <Riostream.h>
#include <TGeoManager.h>
#include <TGeoPhysicalNode.h>
#include <AliGeomManager.h>
AliT0CalibData* AliT0Parameters::fgCalibData = 0;
AliT0CalibData* AliT0Parameters::fgLookUp = 0;
AliT0CalibData* AliT0Parameters::fgSlewCorr =0;
//====================================================================
ClassImp(AliT0Parameters)
#if 0
; // This is here to keep Emacs for indenting the next line
#endif
//____________________________________________________________________
AliT0Parameters* AliT0Parameters::fgInstance = 0;
//____________________________________________________________________
AliT0Parameters* AliT0Parameters::Instance()
{
// Get static instance
if (!fgInstance) {
fgInstance = new AliT0Parameters;
}
return fgInstance;
}
//____________________________________________________________________
AliT0Parameters::AliT0Parameters()
:fIsInit(kFALSE),
fPh2Mip(0),fmV2Mip(0),
fChannelWidth(0),fmV2Channel(0),
fQTmin(0),fQTmax(0),
fAmpLEDRec(0),
fPMTeff(),
fWalk(0),
fTimeDelayDA(0),
fTimeDelayCFD(0),
fTimeDelayTVD(0),
fMeanT0(500),
fLookUp(0),
fNumberOfTRMs(2),
fCalibentry(), fLookUpentry(),fSlewCorr()
{
// Default constructor
for (Int_t ipmt=0; ipmt<24; ipmt++)
{
SetPh2Mip();
SetmV2Mip();
SetChannelWidth();
SetmV2channel();
SetQTmin();
SetQTmax();
SetPMTeff(ipmt);
}
SetTimeDelayTVD();
SetZposition();
}
//__________________________________________________________________
void
AliT0Parameters::Init()
{
// Initialize the parameters manager. We need to get stuff from the
// CDB here.
if (fIsInit) return;
AliCDBManager *stor =AliCDBManager::Instance();
//time equalizing
fCalibentry = stor->Get("T0/Calib/TimeDelay");
if (fCalibentry)
fgCalibData = (AliT0CalibData*)fCalibentry->GetObject();
else {
AliFatal(" ALARM !!!! No time delays in CDB ");
fIsInit = kFALSE;
return;
}
//slewing correction
fSlewCorr = stor->Get("T0/Calib/Slewing_Walk");
if (fSlewCorr){
fgSlewCorr = (AliT0CalibData*)fSlewCorr->GetObject();
}
else {
AliFatal(" ALARM !!!! No slewing correction in CDB ");
fIsInit = kFALSE;
return;
}
//lookup table
fLookUpentry = stor->Get("T0/Calib/LookUp_Table");
if (fLookUpentry){
fgLookUp = (AliT0CalibData*)fLookUpentry->GetObject();
}
else {
AliFatal(" ALARM !!!! No Lookup table in CDB ");
fIsInit = kFALSE;
return;
}
fIsInit = kTRUE;
}
//__________________________________________________________________
void AliT0Parameters::InitIfOnline()
{
// should be used in online
// for switching to this one should write
// AliT0RawReader myrawreader(rawReader);
// myrawreader.SetOnlineMode(kTRUE);
if (fIsInit) return;
//standart configuration (used for simulation)
//Int_t trm=0; Int_t tdc=0; Int_t chain=0; Int_t channel=0;
// configuration for test Jun07.
fgLookUp = new AliT0CalibData("T0");
fNumberOfTRMs = 1;
Int_t trm=7; Int_t tdc=0; Int_t chain=0; Int_t channel=0;
for (Int_t ik=0; ik<105; ik++)
{
AliT0LookUpKey * lookkey= new AliT0LookUpKey();
AliT0LookUpValue * lookvalue= new AliT0LookUpValue();
lookvalue->SetTRM(trm);
lookvalue->SetTDC(tdc);
lookvalue->SetChain(chain);
lookvalue->SetChannel(channel);
lookkey->SetKey(ik);
if (channel<6) channel +=2;
else {channel = 0; tdc++;}
if(ik==57) { tdc=0; channel=0; chain = 1;}
fgLookUp->GetMapLookup()->Add((TObject*)lookvalue,(TObject*)lookkey);
}
fIsInit=kTRUE;
}
//__________________________________________________________________
Float_t
AliT0Parameters::GetTimeDelayDA(Int_t ipmt)
{
// return time delay for LED channel
//
if (!fCalibentry) {
fTimeDelayDA = 500;
return fTimeDelayDA;
}
return fgCalibData ->GetTimeDelayDA(ipmt);
}
//__________________________________________________________________
Float_t
AliT0Parameters::GetTimeDelayCFD(Int_t ipmt)
{
// return time delay for CFD channel
//
if (!fCalibentry)
{
fTimeDelayCFD = 1000+ipmt*100;
return fTimeDelayCFD;
}
return fgCalibData->GetTimeDelayCFD(ipmt);
}
//__________________________________________________________________
Int_t
AliT0Parameters::GetMeanT0()
{
// return mean of T0 distrubution with vertex=0
//
if (!fCalibentry)
{
return fMeanT0;
}
return fgCalibData->GetMeanT0();
}
//__________________________________________________________________
TGraph *AliT0Parameters::GetAmpLEDRec(Int_t ipmt) const
{
if (!fSlewCorr) {
AliError("No slewing correction is available!");
return (TGraph*)fAmpLEDRec.At(ipmt);
}
return fgSlewCorr -> GetAmpLEDRec(ipmt) ;
}
//__________________________________________________________________
TGraph *AliT0Parameters::GetWalk(Int_t ipmt) const
{
if (!fSlewCorr) {
AliError("No walk correction is available!");
return (TGraph*)fWalk.At(ipmt);
}
return fgSlewCorr -> GetWalk(ipmt) ;
}
//__________________________________________________________________
Float_t AliT0Parameters::GetWalkVal(Int_t ipmt, Float_t mv) const
{
if (!fSlewCorr) {
return ((TGraph*)fWalk.At(ipmt))->Eval(mv);
}
return fgSlewCorr -> GetWalkVal(ipmt, mv) ;
}
//__________________________________________________________________
void
AliT0Parameters::SetPMTeff(Int_t ipmt)
{
Float_t lambda[50];
Float_t eff[50 ] = {0, 0, 0.23619, 0.202909, 0.177913,
0.175667, 0.17856, 0.190769, 0.206667, 0.230286,
0.252276, 0.256267,0.26, 0.27125, 0.281818,
0.288118, 0.294057,0.296222, 0.301622, 0.290421,
0.276615, 0.2666, 0.248, 0.23619, 0.227814,
0.219818, 0.206667,0.194087, 0.184681, 0.167917,
0.154367, 0.1364, 0.109412, 0.0834615,0.0725283,
0.0642963,0.05861, 0.0465, 0.0413333,0.032069,
0.0252203,0.02066, 0.016262, 0.012, 0.00590476,
0.003875, 0.00190, 0, 0, 0 } ;
for (Int_t i=0; i<50; i++) lambda[i]=200+10*i;
TGraph* gr = new TGraph(50,lambda,eff);
fPMTeff.AddAtAndExpand(gr,ipmt);
}
//________________________________________________________________
Int_t
AliT0Parameters::GetChannel(Int_t trm, Int_t tdc, Int_t chain, Int_t channel)
{
if (fgLookUp) {
AliT0LookUpValue key(trm,tdc,chain,channel);
AliT0LookUpKey *val = (AliT0LookUpKey*) fgLookUp->GetMapLookup()->GetValue((TObject*)&key);
// AliT0LookUpKey *val = (AliT0LookUpKey*) fLookUp.GetValue((TObject*)&key);
if (val )
return val->GetKey();
else {
AliWarning(Form("No such address (%d %d %d %d)!",trm,tdc,chain,channel));
return -1;
}
}
else {
AliError("No look up table has been loader!");
return -1;
}
}
//__________________________________________________________________
TMap *AliT0Parameters::GetMapLookup()
{
if (!fgLookUp){
cout<<" No look up table in OCDB";
return 0;
}
return fgLookUp->GetMapLookup();
}
//__________________________________________________________________
Int_t
AliT0Parameters::GetNumberOfTRMs()
{
// return number of trms
//
if (!fgLookUp) {
// fNumberOfTRMs = 2;
return fNumberOfTRMs;
}
return fgLookUp ->GetNumberOfTRMs();
}
/*
//________________________________________________________________________________
Double_t AliT0Parameters::GetZPosition(const char* symname){
// Get the global z coordinate of the given T0 alignable volume
//
Double_t *tr = AliGeomManager::GetMatrix(symname)->GetTranslation();
return tr[2];
}
*/
//________________________________________________________________________________
Double_t AliT0Parameters::GetZPosition(const char* symname){
// Get the global z coordinate of the given T0 alignable volume
//
Double_t *tr;
cout<<symname<<endl;
TGeoPNEntry *pne = gGeoManager->GetAlignableEntry(symname);
if (!pne) return 0;
TGeoPhysicalNode *pnode = pne->GetPhysicalNode();
if(pnode){
TGeoHMatrix* hm = pnode->GetMatrix();
tr = hm->GetTranslation();
}else{
const char* path = pne->GetTitle();
if(!gGeoManager->cd(path)){
AliErrorClass(Form("Volume path %s not valid!",path));
return 0;
}
tr = gGeoManager->GetCurrentMatrix()->GetTranslation();
}
return tr[2];
}
//________________________________________________________________________________
Double_t AliT0Parameters::GetZPositionShift(const char* symname)
{
// Get the global z coordinate of the given T0 alignable volume
//
Double_t *tr = AliGeomManager::GetMatrix(symname)->GetTranslation();
TGeoHMatrix origmat;
AliGeomManager::GetOrigGlobalMatrix(symname,origmat);
Double_t *otr = origmat.GetTranslation();
return (tr[2]-otr[2]);
}
<commit_msg>fix bug in OnlineLookup<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id: */
//____________________________________________________________________
//
// T0 - T0.
//
// This class is a singleton that handles various parameters of
// the T0 detectors.
// Eventually, this class will use the Conditions DB to get the
// various parameters, which code can then request from here.
//
#include "AliLog.h"
#include "AliT0Parameters.h"
#include "AliT0CalibData.h"
#include "AliT0LookUpValue.h"
#include <AliCDBManager.h>
#include <AliCDBEntry.h>
#include <AliCDBStorage.h>
#include <TMath.h>
#include <TSystem.h>
#include <Riostream.h>
#include <TGeoManager.h>
#include <TGeoPhysicalNode.h>
#include <AliGeomManager.h>
AliT0CalibData* AliT0Parameters::fgCalibData = 0;
AliT0CalibData* AliT0Parameters::fgLookUp = 0;
AliT0CalibData* AliT0Parameters::fgSlewCorr =0;
//====================================================================
ClassImp(AliT0Parameters)
#if 0
; // This is here to keep Emacs for indenting the next line
#endif
//____________________________________________________________________
AliT0Parameters* AliT0Parameters::fgInstance = 0;
//____________________________________________________________________
AliT0Parameters* AliT0Parameters::Instance()
{
// Get static instance
if (!fgInstance) {
fgInstance = new AliT0Parameters;
}
return fgInstance;
}
//____________________________________________________________________
AliT0Parameters::AliT0Parameters()
:fIsInit(kFALSE),
fPh2Mip(0),fmV2Mip(0),
fChannelWidth(0),fmV2Channel(0),
fQTmin(0),fQTmax(0),
fAmpLEDRec(0),
fPMTeff(),
fWalk(0),
fTimeDelayDA(0),
fTimeDelayCFD(0),
fTimeDelayTVD(0),
fMeanT0(500),
fLookUp(0),
fNumberOfTRMs(2),
fCalibentry(), fLookUpentry(),fSlewCorr()
{
// Default constructor
for (Int_t ipmt=0; ipmt<24; ipmt++)
{
SetPh2Mip();
SetmV2Mip();
SetChannelWidth();
SetmV2channel();
SetQTmin();
SetQTmax();
SetPMTeff(ipmt);
}
SetTimeDelayTVD();
SetZposition();
}
//__________________________________________________________________
void
AliT0Parameters::Init()
{
// Initialize the parameters manager. We need to get stuff from the
// CDB here.
if (fIsInit) return;
AliCDBManager *stor =AliCDBManager::Instance();
//time equalizing
fCalibentry = stor->Get("T0/Calib/TimeDelay");
if (fCalibentry)
fgCalibData = (AliT0CalibData*)fCalibentry->GetObject();
else {
AliFatal(" ALARM !!!! No time delays in CDB ");
fIsInit = kFALSE;
return;
}
//slewing correction
fSlewCorr = stor->Get("T0/Calib/Slewing_Walk");
if (fSlewCorr){
fgSlewCorr = (AliT0CalibData*)fSlewCorr->GetObject();
}
else {
AliFatal(" ALARM !!!! No slewing correction in CDB ");
fIsInit = kFALSE;
return;
}
//lookup table
fLookUpentry = stor->Get("T0/Calib/LookUp_Table");
if (fLookUpentry){
fgLookUp = (AliT0CalibData*)fLookUpentry->GetObject();
}
else {
AliFatal(" ALARM !!!! No Lookup table in CDB ");
fIsInit = kFALSE;
return;
}
fIsInit = kTRUE;
}
//__________________________________________________________________
void AliT0Parameters::InitIfOnline()
{
// should be used in online
// for switching to this one should write
// AliT0RawReader myrawreader(rawReader);
// myrawreader.SetOnlineMode(kTRUE);
if (fIsInit) return;
//standart configuration (used for simulation)
//Int_t trm=0; Int_t tdc=0; Int_t chain=0; Int_t channel=0;
// configuration for test Jun07.
fgLookUp = new AliT0CalibData("T0");
fNumberOfTRMs = 1;
fgLookUp-> SetNumberOfTRMs(fNumberOfTRMs);
Int_t trm=7; Int_t tdc=0; Int_t chain=0; Int_t channel=0;
for (Int_t ik=0; ik<105; ik++)
{
AliT0LookUpKey * lookkey= new AliT0LookUpKey();
AliT0LookUpValue * lookvalue= new AliT0LookUpValue();
lookvalue->SetTRM(trm);
lookvalue->SetTDC(tdc);
lookvalue->SetChain(chain);
lookvalue->SetChannel(channel);
lookkey->SetKey(ik);
if (channel<6) channel +=2;
else {channel = 0; tdc++;}
if(ik==57) { tdc=0; channel=0; chain = 1;}
fgLookUp->GetMapLookup()->Add((TObject*)lookvalue,(TObject*)lookkey);
}
fIsInit=kTRUE;
}
//__________________________________________________________________
Float_t
AliT0Parameters::GetTimeDelayDA(Int_t ipmt)
{
// return time delay for LED channel
//
if (!fCalibentry) {
fTimeDelayDA = 500;
return fTimeDelayDA;
}
return fgCalibData ->GetTimeDelayDA(ipmt);
}
//__________________________________________________________________
Float_t
AliT0Parameters::GetTimeDelayCFD(Int_t ipmt)
{
// return time delay for CFD channel
//
if (!fCalibentry)
{
fTimeDelayCFD = 1000+ipmt*100;
return fTimeDelayCFD;
}
return fgCalibData->GetTimeDelayCFD(ipmt);
}
//__________________________________________________________________
Int_t
AliT0Parameters::GetMeanT0()
{
// return mean of T0 distrubution with vertex=0
//
if (!fCalibentry)
{
return fMeanT0;
}
return fgCalibData->GetMeanT0();
}
//__________________________________________________________________
TGraph *AliT0Parameters::GetAmpLEDRec(Int_t ipmt) const
{
if (!fSlewCorr) {
AliError("No slewing correction is available!");
return (TGraph*)fAmpLEDRec.At(ipmt);
}
return fgSlewCorr -> GetAmpLEDRec(ipmt) ;
}
//__________________________________________________________________
TGraph *AliT0Parameters::GetWalk(Int_t ipmt) const
{
if (!fSlewCorr) {
AliError("No walk correction is available!");
return (TGraph*)fWalk.At(ipmt);
}
return fgSlewCorr -> GetWalk(ipmt) ;
}
//__________________________________________________________________
Float_t AliT0Parameters::GetWalkVal(Int_t ipmt, Float_t mv) const
{
if (!fSlewCorr) {
return ((TGraph*)fWalk.At(ipmt))->Eval(mv);
}
return fgSlewCorr -> GetWalkVal(ipmt, mv) ;
}
//__________________________________________________________________
void
AliT0Parameters::SetPMTeff(Int_t ipmt)
{
Float_t lambda[50];
Float_t eff[50 ] = {0, 0, 0.23619, 0.202909, 0.177913,
0.175667, 0.17856, 0.190769, 0.206667, 0.230286,
0.252276, 0.256267,0.26, 0.27125, 0.281818,
0.288118, 0.294057,0.296222, 0.301622, 0.290421,
0.276615, 0.2666, 0.248, 0.23619, 0.227814,
0.219818, 0.206667,0.194087, 0.184681, 0.167917,
0.154367, 0.1364, 0.109412, 0.0834615,0.0725283,
0.0642963,0.05861, 0.0465, 0.0413333,0.032069,
0.0252203,0.02066, 0.016262, 0.012, 0.00590476,
0.003875, 0.00190, 0, 0, 0 } ;
for (Int_t i=0; i<50; i++) lambda[i]=200+10*i;
TGraph* gr = new TGraph(50,lambda,eff);
fPMTeff.AddAtAndExpand(gr,ipmt);
}
//________________________________________________________________
Int_t
AliT0Parameters::GetChannel(Int_t trm, Int_t tdc, Int_t chain, Int_t channel)
{
if (fgLookUp) {
AliT0LookUpValue key(trm,tdc,chain,channel);
AliT0LookUpKey *val = (AliT0LookUpKey*) fgLookUp->GetMapLookup()->GetValue((TObject*)&key);
// AliT0LookUpKey *val = (AliT0LookUpKey*) fLookUp.GetValue((TObject*)&key);
if (val )
return val->GetKey();
else {
AliWarning(Form("No such address (%d %d %d %d)!",trm,tdc,chain,channel));
return -1;
}
}
else {
AliError("No look up table has been loader!");
return -1;
}
}
//__________________________________________________________________
TMap *AliT0Parameters::GetMapLookup()
{
if (!fgLookUp){
cout<<" No look up table in OCDB";
return 0;
}
return fgLookUp->GetMapLookup();
}
//__________________________________________________________________
Int_t
AliT0Parameters::GetNumberOfTRMs()
{
// return number of trms
//
if (!fgLookUp) {
// fNumberOfTRMs = 2;
return fNumberOfTRMs;
}
return fgLookUp ->GetNumberOfTRMs();
}
/*
//________________________________________________________________________________
Double_t AliT0Parameters::GetZPosition(const char* symname){
// Get the global z coordinate of the given T0 alignable volume
//
Double_t *tr = AliGeomManager::GetMatrix(symname)->GetTranslation();
return tr[2];
}
*/
//________________________________________________________________________________
Double_t AliT0Parameters::GetZPosition(const char* symname){
// Get the global z coordinate of the given T0 alignable volume
//
Double_t *tr;
TGeoPNEntry *pne = gGeoManager->GetAlignableEntry(symname);
if (!pne) return 0;
TGeoPhysicalNode *pnode = pne->GetPhysicalNode();
if(pnode){
TGeoHMatrix* hm = pnode->GetMatrix();
tr = hm->GetTranslation();
}else{
const char* path = pne->GetTitle();
if(!gGeoManager->cd(path)){
AliErrorClass(Form("Volume path %s not valid!",path));
return 0;
}
tr = gGeoManager->GetCurrentMatrix()->GetTranslation();
}
return tr[2];
}
//________________________________________________________________________________
Double_t AliT0Parameters::GetZPositionShift(const char* symname)
{
// Get the global z coordinate of the given T0 alignable volume
//
Double_t *tr = AliGeomManager::GetMatrix(symname)->GetTranslation();
TGeoHMatrix origmat;
AliGeomManager::GetOrigGlobalMatrix(symname,origmat);
Double_t *otr = origmat.GetTranslation();
return (tr[2]-otr[2]);
}
<|endoftext|> |
<commit_before>/* Copyright 2020 The TensorFlow 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 "tensorflow/core/common_runtime/optimization_registry.h"
#include "tensorflow/core/tpu/graph_rewrite/distributed_tpu_configuration_rewrite_pass.h"
#include "tensorflow/core/tpu/graph_rewrite/encapsulate_tpu_computations_pass.h"
#include "tensorflow/core/tpu/graph_rewrite/variable_merger_pass.h"
namespace tensorflow {
namespace {
// This pass removes the TPUEmbeddingConfiguration in ConfigureDistributedTPU.
REGISTER_OPTIMIZATION(OptimizationPassRegistry::PRE_PLACEMENT, 20,
DistributedTPUConfigurationRewritePass);
REGISTER_OPTIMIZATION(OptimizationPassRegistry::PRE_PLACEMENT, 20,
DistributedTPUShutdownRewritePass);
REGISTER_OPTIMIZATION(OptimizationPassRegistry::PRE_PLACEMENT, 34,
EncapsulateTPUComputationsPass);
REGISTER_OPTIMIZATION(OptimizationPassRegistry::PRE_PLACEMENT, 39,
ExtractOutsideCompilationPass);
} // namespace
} // namespace tensorflow
<commit_msg>Restore registration for variable merger pass.<commit_after>/* Copyright 2020 The TensorFlow 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 "tensorflow/core/common_runtime/optimization_registry.h"
#include "tensorflow/core/tpu/graph_rewrite/distributed_tpu_configuration_rewrite_pass.h"
#include "tensorflow/core/tpu/graph_rewrite/encapsulate_tpu_computations_pass.h"
#include "tensorflow/core/tpu/graph_rewrite/variable_merger_pass.h"
namespace tensorflow {
namespace {
// This pass removes the TPUEmbeddingConfiguration in ConfigureDistributedTPU.
REGISTER_OPTIMIZATION(OptimizationPassRegistry::PRE_PLACEMENT, 20,
DistributedTPUConfigurationRewritePass);
REGISTER_OPTIMIZATION(OptimizationPassRegistry::PRE_PLACEMENT, 20,
DistributedTPUShutdownRewritePass);
REGISTER_OPTIMIZATION(OptimizationPassRegistry::PRE_PLACEMENT, 34,
EncapsulateTPUComputationsPass);
REGISTER_OPTIMIZATION(OptimizationPassRegistry::PRE_PLACEMENT, 39,
ExtractOutsideCompilationPass);
REGISTER_OPTIMIZATION(OptimizationPassRegistry::POST_REWRITE_FOR_EXEC, 0,
VariableMergerPass);
} // namespace
} // namespace tensorflow
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of Qt Creator.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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 [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "maemopackagecreationstep.h"
#include "maemoconstants.h"
#include "maemopackagecreationwidget.h"
#include "maemopackagecontents.h"
#include "maemotoolchain.h"
#include <projectexplorer/projectexplorerconstants.h>
#include <qt4buildconfiguration.h>
#include <qt4project.h>
#include <qt4target.h>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QProcess>
#include <QtCore/QProcessEnvironment>
#include <QtCore/QStringBuilder>
#include <QtGui/QWidget>
namespace { const QLatin1String PackagingEnabledKey("Packaging Enabled"); }
using namespace ProjectExplorer::Constants;
using ProjectExplorer::BuildConfiguration;
using ProjectExplorer::BuildStepConfigWidget;
using ProjectExplorer::Task;
namespace Qt4ProjectManager {
namespace Internal {
MaemoPackageCreationStep::MaemoPackageCreationStep(BuildConfiguration *buildConfig)
: ProjectExplorer::BuildStep(buildConfig, CreatePackageId),
m_packageContents(new MaemoPackageContents(this)),
m_packagingEnabled(true)
{
}
MaemoPackageCreationStep::MaemoPackageCreationStep(BuildConfiguration *buildConfig,
MaemoPackageCreationStep *other)
: BuildStep(buildConfig, other),
m_packageContents(new MaemoPackageContents(this)),
m_packagingEnabled(other->m_packagingEnabled)
{
}
bool MaemoPackageCreationStep::init()
{
return true;
}
QVariantMap MaemoPackageCreationStep::toMap() const
{
QVariantMap map(ProjectExplorer::BuildStep::toMap());
map.insert(PackagingEnabledKey, m_packagingEnabled);
return map;
}
bool MaemoPackageCreationStep::fromMap(const QVariantMap &map)
{
m_packagingEnabled = map.value(PackagingEnabledKey, true).toBool();
return ProjectExplorer::BuildStep::fromMap(map);
}
void MaemoPackageCreationStep::run(QFutureInterface<bool> &fi)
{
fi.reportResult(m_packagingEnabled ? createPackage() : true);
}
BuildStepConfigWidget *MaemoPackageCreationStep::createConfigWidget()
{
return new MaemoPackageCreationWidget(this);
}
bool MaemoPackageCreationStep::createPackage()
{
if (!packagingNeeded())
return true;
QTextCharFormat textCharFormat;
emit addOutput(tr("Creating package file ..."), textCharFormat);
QFile configFile(targetRoot() % QLatin1String("/config.sh"));
if (!configFile.open(QIODevice::ReadOnly)) {
raiseError(tr("Cannot open MADDE config file '%1'.")
.arg(nativePath(configFile)));
return false;
}
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
const QString &path = QDir::toNativeSeparators(maddeRoot() + QLatin1Char('/'));
const QLatin1String key("PATH");
QString colon = QLatin1String(":");
#ifdef Q_OS_WIN
colon = QLatin1String(";");
env.insert(key, targetRoot() % "/bin" % colon % env.value(key));
env.insert(key, path % QLatin1String("bin") % colon % env.value(key));
#endif
env.insert(key, path % QLatin1String("madbin") % colon % env.value(key));
env.insert(QLatin1String("PERL5LIB"), path % QLatin1String("madlib/perl5"));
const QString buildDir = QFileInfo(localExecutableFilePath()).absolutePath();
env.insert(QLatin1String("PWD"), buildDir);
const QRegExp envPattern(QLatin1String("([^=]+)=[\"']?([^;\"']+)[\"']? ;.*"));
QByteArray line;
do {
line = configFile.readLine(200);
if (envPattern.exactMatch(line))
env.insert(envPattern.cap(1), envPattern.cap(2));
} while (!line.isEmpty());
QProcess buildProc;
buildProc.setProcessEnvironment(env);
buildProc.setWorkingDirectory(buildDir);
if (!QFileInfo(buildDir + QLatin1String("/debian")).exists()) {
const QString command = QLatin1String("dh_make -s -n -p ")
% executableFileName().toLower() % versionString();
if (!runCommand(buildProc, command))
return false;
QFile rulesFile(buildDir + QLatin1String("/debian/rules"));
if (!rulesFile.open(QIODevice::ReadWrite)) {
raiseError(tr("Packaging Error: Cannot open file '%1'.")
.arg(nativePath(rulesFile)));
return false;
}
QByteArray rulesContents = rulesFile.readAll();
rulesContents.replace("DESTDIR", "INSTALL_ROOT");
rulesFile.resize(0);
rulesFile.write(rulesContents);
if (rulesFile.error() != QFile::NoError) {
raiseError(tr("Packaging Error: Cannot write file '%1'.")
.arg(nativePath(rulesFile)));
return false;
}
}
if (!runCommand(buildProc, QLatin1String("dh_installdirs")))
return false;
const QDir debianRoot = QDir(buildDir % QLatin1String("/debian/")
% executableFileName().toLower());
for (int i = 0; i < m_packageContents->rowCount(); ++i) {
const MaemoPackageContents::Deployable &d
= m_packageContents->deployableAt(i);
const QString absTargetDir = debianRoot.path() + '/' + d.remoteDir;
const QString targetFile
= absTargetDir + '/' + QFileInfo(d.localFilePath).fileName();
const QString relTargetDir = debianRoot.relativeFilePath(absTargetDir);
if (!debianRoot.exists(relTargetDir)
&& !debianRoot.mkpath(relTargetDir)) {
raiseError(tr("Packaging Error: Could not create directory '%1'.")
.arg(QDir::toNativeSeparators(absTargetDir)));
return false;
}
if (QFile::exists(targetFile) && !QFile::remove(targetFile)) {
raiseError(tr("Packaging Error: Could not replace file '%1'.")
.arg(QDir::toNativeSeparators(targetFile)));
return false;
}
if (!QFile::copy(d.localFilePath, targetFile)) {
raiseError(tr("Packaging Error: Could not copy '%1' to '%2'.")
.arg(QDir::toNativeSeparators(d.localFilePath))
.arg(QDir::toNativeSeparators(targetFile)));
return false;
}
}
const QStringList commands = QStringList() << QLatin1String("dh_link")
<< QLatin1String("dh_fixperms") << QLatin1String("dh_installdeb")
<< QLatin1String("dh_shlibdeps") << QLatin1String("dh_gencontrol")
<< QLatin1String("dh_md5sums") << QLatin1String("dh_builddeb --destdir=.");
foreach (const QString &command, commands) {
if (!runCommand(buildProc, command))
return false;
}
emit addOutput(tr("Package created."), textCharFormat);
m_packageContents->setUnModified();
return true;
}
bool MaemoPackageCreationStep::runCommand(QProcess &proc, const QString &command)
{
QTextCharFormat textCharFormat;
emit addOutput(tr("Package Creation: Running command '%1'.").arg(command), textCharFormat);
QString perl;
#ifdef Q_OS_WIN
perl = maddeRoot() + QLatin1String("/bin/perl.exe ");
#endif
proc.start(perl + maddeRoot() % QLatin1String("/madbin/") % command);
if (!proc.waitForStarted()) {
raiseError(tr("Packaging failed."),
tr("Packaging error: Could not start command '%1'. Reason: %2")
.arg(command).arg(proc.errorString()));
return false;
}
proc.write("\n"); // For dh_make
proc.waitForFinished(-1);
if (proc.error() != QProcess::UnknownError || proc.exitCode() != 0) {
QString mainMessage = tr("Packaging Error: Command '%1' failed.")
.arg(command);
if (proc.error() != QProcess::UnknownError)
mainMessage += tr(" Reason: %1").arg(proc.errorString());
raiseError(mainMessage, mainMessage + QLatin1Char('\n')
+ tr("Output was: ") + proc.readAllStandardError()
+ QLatin1Char('\n') + proc.readAllStandardOutput());
return false;
}
return true;
}
const Qt4BuildConfiguration *MaemoPackageCreationStep::qt4BuildConfiguration() const
{
return static_cast<Qt4BuildConfiguration *>(buildConfiguration());
}
QString MaemoPackageCreationStep::localExecutableFilePath() const
{
const TargetInformation &ti = qt4BuildConfiguration()->qt4Target()
->qt4Project()->rootProjectNode()->targetInformation();
if (!ti.valid)
return QString();
return QDir::toNativeSeparators(QDir::cleanPath(ti.workingDir
+ QLatin1Char('/') + executableFileName()));
}
QString MaemoPackageCreationStep::executableFileName() const
{
const Qt4Project * const project
= qt4BuildConfiguration()->qt4Target()->qt4Project();
const TargetInformation &ti
= project->rootProjectNode()->targetInformation();
if (!ti.valid)
return QString();
return project->rootProjectNode()->projectType() == LibraryTemplate
? QLatin1String("lib") + ti.target + QLatin1String(".so")
: ti.target;
}
const MaemoToolChain *MaemoPackageCreationStep::maemoToolChain() const
{
return static_cast<MaemoToolChain *>(qt4BuildConfiguration()->toolChain());
}
QString MaemoPackageCreationStep::maddeRoot() const
{
return maemoToolChain()->maddeRoot();
}
QString MaemoPackageCreationStep::targetRoot() const
{
return maemoToolChain()->targetRoot();
}
bool MaemoPackageCreationStep::packagingNeeded() const
{
QFileInfo packageInfo(packageFilePath());
if (!packageInfo.exists() || m_packageContents->isModified())
return true;
for (int i = 0; i < m_packageContents->rowCount(); ++i) {
if (packageInfo.lastModified()
<= QFileInfo(m_packageContents->deployableAt(i).localFilePath)
.lastModified())
return true;
}
return false;
}
QString MaemoPackageCreationStep::packageFilePath() const
{
QFileInfo execInfo(localExecutableFilePath());
return execInfo.path() % QDir::separator() % execInfo.fileName().toLower()
% versionString() % QLatin1String("_armel.deb");
}
QString MaemoPackageCreationStep::versionString() const
{
return QLatin1String("_0.1");
}
QString MaemoPackageCreationStep::nativePath(const QFile &file) const
{
return QDir::toNativeSeparators(QFileInfo(file).filePath());
}
void MaemoPackageCreationStep::raiseError(const QString &shortMsg,
const QString &detailedMsg)
{
QTextCharFormat textCharFormat;
emit addOutput(detailedMsg.isNull() ? shortMsg : detailedMsg, textCharFormat);
emit addTask(Task(Task::Error, shortMsg, QString(), -1,
TASK_CATEGORY_BUILDSYSTEM));
}
const QLatin1String MaemoPackageCreationStep::CreatePackageId("Qt4ProjectManager.MaemoPackageCreationStep");
} // namespace Internal
} // namespace Qt4ProjectManager
<commit_msg>Maemo: Use generic package build command.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of Qt Creator.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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 [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "maemopackagecreationstep.h"
#include "maemoconstants.h"
#include "maemopackagecreationwidget.h"
#include "maemopackagecontents.h"
#include "maemotoolchain.h"
#include <projectexplorer/projectexplorerconstants.h>
#include <qt4buildconfiguration.h>
#include <qt4project.h>
#include <qt4target.h>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QProcess>
#include <QtCore/QProcessEnvironment>
#include <QtCore/QStringBuilder>
#include <QtGui/QWidget>
namespace { const QLatin1String PackagingEnabledKey("Packaging Enabled"); }
using namespace ProjectExplorer::Constants;
using ProjectExplorer::BuildConfiguration;
using ProjectExplorer::BuildStepConfigWidget;
using ProjectExplorer::Task;
namespace Qt4ProjectManager {
namespace Internal {
MaemoPackageCreationStep::MaemoPackageCreationStep(BuildConfiguration *buildConfig)
: ProjectExplorer::BuildStep(buildConfig, CreatePackageId),
m_packageContents(new MaemoPackageContents(this)),
m_packagingEnabled(true)
{
}
MaemoPackageCreationStep::MaemoPackageCreationStep(BuildConfiguration *buildConfig,
MaemoPackageCreationStep *other)
: BuildStep(buildConfig, other),
m_packageContents(new MaemoPackageContents(this)),
m_packagingEnabled(other->m_packagingEnabled)
{
}
bool MaemoPackageCreationStep::init()
{
return true;
}
QVariantMap MaemoPackageCreationStep::toMap() const
{
QVariantMap map(ProjectExplorer::BuildStep::toMap());
map.insert(PackagingEnabledKey, m_packagingEnabled);
return map;
}
bool MaemoPackageCreationStep::fromMap(const QVariantMap &map)
{
m_packagingEnabled = map.value(PackagingEnabledKey, true).toBool();
return ProjectExplorer::BuildStep::fromMap(map);
}
void MaemoPackageCreationStep::run(QFutureInterface<bool> &fi)
{
fi.reportResult(m_packagingEnabled ? createPackage() : true);
}
BuildStepConfigWidget *MaemoPackageCreationStep::createConfigWidget()
{
return new MaemoPackageCreationWidget(this);
}
bool MaemoPackageCreationStep::createPackage()
{
if (!packagingNeeded())
return true;
QTextCharFormat textCharFormat;
emit addOutput(tr("Creating package file ..."), textCharFormat);
QFile configFile(targetRoot() % QLatin1String("/config.sh"));
if (!configFile.open(QIODevice::ReadOnly)) {
raiseError(tr("Cannot open MADDE config file '%1'.")
.arg(nativePath(configFile)));
return false;
}
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
const QString &path = QDir::toNativeSeparators(maddeRoot() + QLatin1Char('/'));
const QLatin1String key("PATH");
QString colon = QLatin1String(":");
#ifdef Q_OS_WIN
colon = QLatin1String(";");
env.insert(key, path % QLatin1String("bin") % colon % env.value(key));
#endif
env.insert(key, targetRoot() % "/bin" % colon % env.value(key));
env.insert(key, path % QLatin1String("madbin") % colon % env.value(key));
env.insert(QLatin1String("PERL5LIB"), path % QLatin1String("madlib/perl5"));
const QString buildDir = QFileInfo(localExecutableFilePath()).absolutePath();
env.insert(QLatin1String("PWD"), buildDir);
const QRegExp envPattern(QLatin1String("([^=]+)=[\"']?([^;\"']+)[\"']? ;.*"));
QByteArray line;
do {
line = configFile.readLine(200);
if (envPattern.exactMatch(line))
env.insert(envPattern.cap(1), envPattern.cap(2));
} while (!line.isEmpty());
QProcess buildProc;
buildProc.setProcessEnvironment(env);
buildProc.setWorkingDirectory(buildDir);
buildProc.start("cd " + buildDir);
buildProc.waitForFinished();
if (!QFileInfo(buildDir + QLatin1String("/debian")).exists()) {
const QString command = QLatin1String("dh_make -s -n -p ")
% executableFileName().toLower() % versionString();
if (!runCommand(buildProc, command))
return false;
QFile rulesFile(buildDir + QLatin1String("/debian/rules"));
if (!rulesFile.open(QIODevice::ReadWrite)) {
raiseError(tr("Packaging Error: Cannot open file '%1'.")
.arg(nativePath(rulesFile)));
return false;
}
QByteArray rulesContents = rulesFile.readAll();
rulesContents.replace("DESTDIR", "INSTALL_ROOT");
// Would be the right solution, but does not work (on Windows),
// because dpkg-genchanges doesn't know about it (and can't be told).
// rulesContents.replace("dh_builddeb", "dh_builddeb --destdir=.");
rulesFile.resize(0);
rulesFile.write(rulesContents);
if (rulesFile.error() != QFile::NoError) {
raiseError(tr("Packaging Error: Cannot write file '%1'.")
.arg(nativePath(rulesFile)));
return false;
}
}
if (!runCommand(buildProc, "dpkg-buildpackage -nc -uc -us"))
return false;
// Workaround for non-working dh_builddeb --destdir=.
if (!QDir(buildDir).isRoot()) {
const QString packageFileName = QFileInfo(packageFilePath()).fileName();
const QString changesFileName = QFileInfo(packageFileName)
.completeBaseName() + QLatin1String(".changes");
const QString packageSourceDir = buildDir + QLatin1String("/../");
const QString packageSourceFilePath
= packageSourceDir + packageFileName;
const QString changesSourceFilePath
= packageSourceDir + changesFileName;
const QString changesTargetFilePath
= buildDir + QLatin1Char('/') + changesFileName;
QFile::remove(packageFilePath());
QFile::remove(changesTargetFilePath);
if (!QFile::rename(packageSourceFilePath, packageFilePath())
|| !QFile::rename(changesSourceFilePath, changesTargetFilePath)) {
raiseError(tr("Packaging failed."),
tr("Could not move package files from %1 to %2.")
.arg(packageSourceDir, buildDir));
return false;
}
}
emit addOutput(tr("Package created."), textCharFormat);
m_packageContents->setUnModified();
return true;
}
bool MaemoPackageCreationStep::runCommand(QProcess &proc, const QString &command)
{
QTextCharFormat textCharFormat;
emit addOutput(tr("Package Creation: Running command '%1'.").arg(command), textCharFormat);
QString perl;
#ifdef Q_OS_WIN
perl = maddeRoot() + QLatin1String("/bin/perl.exe ");
#endif
proc.start(perl + maddeRoot() % QLatin1String("/madbin/") % command);
if (!proc.waitForStarted()) {
raiseError(tr("Packaging failed."),
tr("Packaging error: Could not start command '%1'. Reason: %2")
.arg(command).arg(proc.errorString()));
return false;
}
proc.write("\n"); // For dh_make
proc.waitForFinished(-1);
if (proc.error() != QProcess::UnknownError || proc.exitCode() != 0) {
QString mainMessage = tr("Packaging Error: Command '%1' failed.")
.arg(command);
if (proc.error() != QProcess::UnknownError)
mainMessage += tr(" Reason: %1").arg(proc.errorString());
else
mainMessage += tr("Exit code: %1").arg(proc.exitCode());
raiseError(mainMessage, mainMessage + QLatin1Char('\n')
+ tr("Output was: ") + proc.readAllStandardError()
+ QLatin1Char('\n') + proc.readAllStandardOutput());
return false;
}
return true;
}
const Qt4BuildConfiguration *MaemoPackageCreationStep::qt4BuildConfiguration() const
{
return static_cast<Qt4BuildConfiguration *>(buildConfiguration());
}
QString MaemoPackageCreationStep::localExecutableFilePath() const
{
const TargetInformation &ti = qt4BuildConfiguration()->qt4Target()
->qt4Project()->rootProjectNode()->targetInformation();
if (!ti.valid)
return QString();
return QDir::toNativeSeparators(QDir::cleanPath(ti.workingDir
+ QLatin1Char('/') + executableFileName()));
}
QString MaemoPackageCreationStep::executableFileName() const
{
const Qt4Project * const project
= qt4BuildConfiguration()->qt4Target()->qt4Project();
const TargetInformation &ti
= project->rootProjectNode()->targetInformation();
if (!ti.valid)
return QString();
return project->rootProjectNode()->projectType() == LibraryTemplate
? QLatin1String("lib") + ti.target + QLatin1String(".so")
: ti.target;
}
const MaemoToolChain *MaemoPackageCreationStep::maemoToolChain() const
{
return static_cast<MaemoToolChain *>(qt4BuildConfiguration()->toolChain());
}
QString MaemoPackageCreationStep::maddeRoot() const
{
return maemoToolChain()->maddeRoot();
}
QString MaemoPackageCreationStep::targetRoot() const
{
return maemoToolChain()->targetRoot();
}
bool MaemoPackageCreationStep::packagingNeeded() const
{
QFileInfo packageInfo(packageFilePath());
if (!packageInfo.exists() || m_packageContents->isModified())
return true;
for (int i = 0; i < m_packageContents->rowCount(); ++i) {
if (packageInfo.lastModified()
<= QFileInfo(m_packageContents->deployableAt(i).localFilePath)
.lastModified())
return true;
}
return false;
}
QString MaemoPackageCreationStep::packageFilePath() const
{
QFileInfo execInfo(localExecutableFilePath());
return execInfo.path() % QDir::separator() % execInfo.fileName().toLower()
% versionString() % QLatin1String("_armel.deb");
}
QString MaemoPackageCreationStep::versionString() const
{
return QLatin1String("_0.1");
}
QString MaemoPackageCreationStep::nativePath(const QFile &file) const
{
return QDir::toNativeSeparators(QFileInfo(file).filePath());
}
void MaemoPackageCreationStep::raiseError(const QString &shortMsg,
const QString &detailedMsg)
{
QTextCharFormat textCharFormat;
emit addOutput(detailedMsg.isNull() ? shortMsg : detailedMsg, textCharFormat);
emit addTask(Task(Task::Error, shortMsg, QString(), -1,
TASK_CATEGORY_BUILDSYSTEM));
}
const QLatin1String MaemoPackageCreationStep::CreatePackageId("Qt4ProjectManager.MaemoPackageCreationStep");
} // namespace Internal
} // namespace Qt4ProjectManager
<|endoftext|> |
<commit_before>//=============================================================================================================
/**
* @file test_mne_forward_solution.cpp
* @author Christoph Dinh <[email protected]>;
* Matti Hamalainen <[email protected]>
* @version 1.0
* @date December, 2016
*
* @section LICENSE
*
* Copyright (C) 2016, Christoph Dinh and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief The forward solution test implementation
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include <fwd/computeFwd/compute_fwd_settings.h>
#include <fwd/computeFwd/compute_fwd.h>
#include <mne/mne.h>
//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QtTest>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace FWDLIB;
using namespace MNELIB;
//=============================================================================================================
/**
* DECLARE CLASS TestMneForwardSolution
*
* @brief The TestMneForwardSolution class provides dipole fit tests
*
*/
class TestMneForwardSolution : public QObject
{
Q_OBJECT
public:
TestMneForwardSolution();
private slots:
void initTestCase();
void computeForward();
void compareForward();
void cleanupTestCase();
private:
double epsilon;
QSharedPointer<MNEForwardSolution> m_pFwdMEGEEGRead;
QSharedPointer<MNEForwardSolution> m_pFwdMEGEEGRef;
};
//*************************************************************************************************************
TestMneForwardSolution::TestMneForwardSolution()
: epsilon(0.0001)
{
}
//*************************************************************************************************************
void TestMneForwardSolution::initTestCase()
{
}
//*************************************************************************************************************
void TestMneForwardSolution::computeForward()
{
// Compute and Write Forward Solution
printf(">>>>>>>>>>>>>>>>>>>>>>>>> Compute/Write/Read MEG/EEG Forward Solution >>>>>>>>>>>>>>>>>>>>>>>>>\n");
// Read reference forward solution
QString fwdMEGEEGFileRef("./mne-cpp-test-data/Result/ref-sample_audvis-meg-eeg-oct-6-fwd.fif");
QFile fileFwdMEGEEGRef(fwdMEGEEGFileRef);
m_pFwdMEGEEGRef = QSharedPointer<MNEForwardSolution>(new MNEForwardSolution(fileFwdMEGEEGRef));
//Following is equivalent to:
//mne_forward_solution
// --meg
// --eeg
// --accurate
// --src ./mne-cpp-test-data/subjects/sample/bem/sample-oct-6-src.fif
// --meas ./mne-cpp-test-data/MEG/sample/sample_audvis_raw_short.fif
// --mri ./mne-cpp-test-data/MEG/sample/all-trans.fif
// --bem ./mne-cpp-test-data/subjects/sample/bem/sample-1280-1280-1280-bem.fif
// --mindist 5
// --fwd ./mne-cpp-test-data/Result/sample_audvis-meg-eeg-oct-6-fwd.fif
ComputeFwdSettings settingsMEGEEG;
settingsMEGEEG.include_meg = true;
settingsMEGEEG.include_eeg = true;
settingsMEGEEG.accurate = true;
settingsMEGEEG.srcname = "./mne-cpp-test-data/subjects/sample/bem/sample-oct-6-src.fif";
settingsMEGEEG.measname = "./mne-cpp-test-data/MEG/sample/sample_audvis_raw_short.fif";
settingsMEGEEG.mriname = "./mne-cpp-test-data/MEG/sample/all-trans.fif";
settingsMEGEEG.transname.clear();
settingsMEGEEG.bemname = "./mne-cpp-test-data/subjects/sample/bem/sample-1280-1280-1280-bem.fif";
settingsMEGEEG.mindist = 5.0f/1000.0f;
settingsMEGEEG.solname = "./mne-cpp-test-data/Result/sample_audvis-meg-eeg-oct-6-fwd.fif";
settingsMEGEEG.checkIntegrity();
QSharedPointer<ComputeFwd> pFwdMEGEEGComputed = QSharedPointer<ComputeFwd>(new ComputeFwd(&settingsMEGEEG));
pFwdMEGEEGComputed->calculateFwd();
// Read newly created fwd
QFile fileFwdMEGEEGRead(settingsMEGEEG.solname);
m_pFwdMEGEEGRead = QSharedPointer<MNEForwardSolution>(new MNEForwardSolution(fileFwdMEGEEGRead));
printf("<<<<<<<<<<<<<<<<<<<<<<<<< Compute/Write/Read MEG/EEG Forward Solution Finished <<<<<<<<<<<<<<<<<<<<<<<<<\n");
}
//*************************************************************************************************************
void TestMneForwardSolution::compareForward()
{
printf(">>>>>>>>>>>>>>>>>>>>>>>>> Compare MEG/EEG Forward Solution >>>>>>>>>>>>>>>>>>>>>>>>>\n");
// Sum up the solution matrix elements to compare them with the reference
double sumComputed = 0;
for(int i = 0; i < m_pFwdMEGEEGRead->sol->nrow; ++i) {
for(int j = 0; j < m_pFwdMEGEEGRead->sol->ncol; ++j) {
sumComputed += m_pFwdMEGEEGRead->sol->data(i,j);
}
}
double sumRef = 0;
for(int i = 0; i < m_pFwdMEGEEGRef->sol->nrow; ++i) {
for(int j = 0; j < m_pFwdMEGEEGRef->sol->ncol; ++j) {
sumRef += m_pFwdMEGEEGRef->sol->data(i,j);
}
}
qDebug() << "sumComputed" << sumComputed;
qDebug() << "sumRef" << sumRef;
qDebug() << "sumComputed-sumRef" << sumComputed-sumRef;
qDebug() << "";
// Please note that the solution matrix is transposed once it is read from the data file
QVERIFY(m_pFwdMEGEEGRead->sol->ncol == m_pFwdMEGEEGRef->sol->ncol);
QVERIFY(m_pFwdMEGEEGRead->sol->nrow == m_pFwdMEGEEGRef->sol->nrow);
//Compare the actual fwd solution matrix results
QVERIFY(sumComputed-sumRef <= epsilon);
QVERIFY(m_pFwdMEGEEGRead->sol->data.isApprox(m_pFwdMEGEEGRef->sol->data, epsilon));
// This is rather hard to test since we need to combien the two forward solutions.
// This is normally done when reading the combined fwd solutions. Wait until everything is refactored.
//QVERIFY(*m_pFwdMEGEEGRead == *m_pFwdMEGEEGRef);
QVERIFY(m_pFwdMEGEEGRead->info == m_pFwdMEGEEGRef->info);
QVERIFY(m_pFwdMEGEEGRead->source_ori == m_pFwdMEGEEGRef->source_ori);
QVERIFY(m_pFwdMEGEEGRead->surf_ori == m_pFwdMEGEEGRef->surf_ori);
QVERIFY(m_pFwdMEGEEGRead->coord_frame == m_pFwdMEGEEGRef->coord_frame);
QVERIFY(m_pFwdMEGEEGRead->nsource == m_pFwdMEGEEGRef->nsource);
QVERIFY(m_pFwdMEGEEGRead->nchan == m_pFwdMEGEEGRef->nchan);
QVERIFY(*m_pFwdMEGEEGRead->sol == *m_pFwdMEGEEGRef->sol);
// QVERIFY(*m_pFwdMEGEEGRead->sol_grad == *m_pFwdMEGEEGRef->sol_grad);
// QVERIFY(m_pFwdMEGEEGRead->mri_head_t == m_pFwdMEGEEGRef->mri_head_t);
//m_pFwdMEGEEGRead->src == m_pFwdMEGEEGRef->src);
QVERIFY(m_pFwdMEGEEGRead->source_rr == m_pFwdMEGEEGRef->source_rr);
QVERIFY(m_pFwdMEGEEGRead->source_nn == m_pFwdMEGEEGRef->source_nn);
printf("<<<<<<<<<<<<<<<<<<<<<<<<< Compare MEG/EEG Forward Solution Finished <<<<<<<<<<<<<<<<<<<<<<<<<\n");
}
//*************************************************************************************************************
void TestMneForwardSolution::cleanupTestCase()
{
}
//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================
QTEST_APPLESS_MAIN(TestMneForwardSolution)
#include "test_mne_forward_solution.moc"
<commit_msg>Make use of equality operator in test_mne_forward_solution<commit_after>//=============================================================================================================
/**
* @file test_mne_forward_solution.cpp
* @author Christoph Dinh <[email protected]>;
* Matti Hamalainen <[email protected]>
* @version 1.0
* @date December, 2016
*
* @section LICENSE
*
* Copyright (C) 2016, Christoph Dinh and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief The forward solution test implementation
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include <fwd/computeFwd/compute_fwd_settings.h>
#include <fwd/computeFwd/compute_fwd.h>
#include <mne/mne.h>
//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QtTest>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace FWDLIB;
using namespace MNELIB;
//=============================================================================================================
/**
* DECLARE CLASS TestMneForwardSolution
*
* @brief The TestMneForwardSolution class provides dipole fit tests
*
*/
class TestMneForwardSolution : public QObject
{
Q_OBJECT
public:
TestMneForwardSolution();
private slots:
void initTestCase();
void computeForward();
void compareForward();
void cleanupTestCase();
private:
double epsilon;
QSharedPointer<MNEForwardSolution> m_pFwdMEGEEGRead;
QSharedPointer<MNEForwardSolution> m_pFwdMEGEEGRef;
};
//*************************************************************************************************************
TestMneForwardSolution::TestMneForwardSolution()
: epsilon(0.0001)
{
}
//*************************************************************************************************************
void TestMneForwardSolution::initTestCase()
{
}
//*************************************************************************************************************
void TestMneForwardSolution::computeForward()
{
// Compute and Write Forward Solution
printf(">>>>>>>>>>>>>>>>>>>>>>>>> Compute/Write/Read MEG/EEG Forward Solution >>>>>>>>>>>>>>>>>>>>>>>>>\n");
// Read reference forward solution
QString fwdMEGEEGFileRef("./mne-cpp-test-data/Result/ref-sample_audvis-meg-eeg-oct-6-fwd.fif");
QFile fileFwdMEGEEGRef(fwdMEGEEGFileRef);
m_pFwdMEGEEGRef = QSharedPointer<MNEForwardSolution>(new MNEForwardSolution(fileFwdMEGEEGRef));
//Following is equivalent to:
//mne_forward_solution
// --meg
// --eeg
// --accurate
// --src ./mne-cpp-test-data/subjects/sample/bem/sample-oct-6-src.fif
// --meas ./mne-cpp-test-data/MEG/sample/sample_audvis_raw_short.fif
// --mri ./mne-cpp-test-data/MEG/sample/all-trans.fif
// --bem ./mne-cpp-test-data/subjects/sample/bem/sample-1280-1280-1280-bem.fif
// --mindist 5
// --fwd ./mne-cpp-test-data/Result/sample_audvis-meg-eeg-oct-6-fwd.fif
ComputeFwdSettings settingsMEGEEG;
settingsMEGEEG.include_meg = true;
settingsMEGEEG.include_eeg = true;
settingsMEGEEG.accurate = true;
settingsMEGEEG.srcname = "./mne-cpp-test-data/subjects/sample/bem/sample-oct-6-src.fif";
settingsMEGEEG.measname = "./mne-cpp-test-data/MEG/sample/sample_audvis_raw_short.fif";
settingsMEGEEG.mriname = "./mne-cpp-test-data/MEG/sample/all-trans.fif";
settingsMEGEEG.transname.clear();
settingsMEGEEG.bemname = "./mne-cpp-test-data/subjects/sample/bem/sample-1280-1280-1280-bem.fif";
settingsMEGEEG.mindist = 5.0f/1000.0f;
settingsMEGEEG.solname = "./mne-cpp-test-data/Result/sample_audvis-meg-eeg-oct-6-fwd.fif";
settingsMEGEEG.checkIntegrity();
QSharedPointer<ComputeFwd> pFwdMEGEEGComputed = QSharedPointer<ComputeFwd>(new ComputeFwd(&settingsMEGEEG));
pFwdMEGEEGComputed->calculateFwd();
// Read newly created fwd
QFile fileFwdMEGEEGRead(settingsMEGEEG.solname);
m_pFwdMEGEEGRead = QSharedPointer<MNEForwardSolution>(new MNEForwardSolution(fileFwdMEGEEGRead));
printf("<<<<<<<<<<<<<<<<<<<<<<<<< Compute/Write/Read MEG/EEG Forward Solution Finished <<<<<<<<<<<<<<<<<<<<<<<<<\n");
}
//*************************************************************************************************************
void TestMneForwardSolution::compareForward()
{
printf(">>>>>>>>>>>>>>>>>>>>>>>>> Compare MEG/EEG Forward Solution >>>>>>>>>>>>>>>>>>>>>>>>>\n");
// The following is equal to QVERIFY(*m_pFwdMEGEEGRead == *m_pFwdMEGEEGRef);
// This just gives more inforamtion on what might be wrong if failing
QVERIFY(m_pFwdMEGEEGRead->info == m_pFwdMEGEEGRef->info);
QVERIFY(m_pFwdMEGEEGRead->source_ori == m_pFwdMEGEEGRef->source_ori);
QVERIFY(m_pFwdMEGEEGRead->surf_ori == m_pFwdMEGEEGRef->surf_ori);
QVERIFY(m_pFwdMEGEEGRead->coord_frame == m_pFwdMEGEEGRef->coord_frame);
QVERIFY(m_pFwdMEGEEGRead->nsource == m_pFwdMEGEEGRef->nsource);
QVERIFY(m_pFwdMEGEEGRead->nchan == m_pFwdMEGEEGRef->nchan);
QVERIFY(*m_pFwdMEGEEGRead->sol == *m_pFwdMEGEEGRef->sol);
QVERIFY(*m_pFwdMEGEEGRead->sol_grad == *m_pFwdMEGEEGRef->sol_grad);
QVERIFY(m_pFwdMEGEEGRead->mri_head_t == m_pFwdMEGEEGRef->mri_head_t);
//m_pFwdMEGEEGRead->src == m_pFwdMEGEEGRef->src);
QVERIFY(m_pFwdMEGEEGRead->source_rr == m_pFwdMEGEEGRef->source_rr);
QVERIFY(m_pFwdMEGEEGRead->source_nn == m_pFwdMEGEEGRef->source_nn);
printf("<<<<<<<<<<<<<<<<<<<<<<<<< Compare MEG/EEG Forward Solution Finished <<<<<<<<<<<<<<<<<<<<<<<<<\n");
}
//*************************************************************************************************************
void TestMneForwardSolution::cleanupTestCase()
{
}
//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================
QTEST_APPLESS_MAIN(TestMneForwardSolution)
#include "test_mne_forward_solution.moc"
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 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 "Xerces" 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/>.
*/
#include "XalanSourceTreeContentHandler.hpp"
#include <XalanDOM/XalanDOMException.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#include "XalanSourceTreeDocument.hpp"
#include "XalanSourceTreeElement.hpp"
#include "XalanSourceTreeHelper.hpp"
XalanSourceTreeContentHandler::XalanSourceTreeContentHandler(
XalanSourceTreeDocument* theDocument,
bool fAccumulateText) :
ContentHandler(),
DTDHandler(),
LexicalHandler(),
m_document(theDocument),
m_currentElement(0),
m_elementStack(),
m_lastChild(0),
m_lastChildStack(),
m_accumulateText(fAccumulateText),
m_textBuffer(),
m_inDTD(false)
{
}
XalanSourceTreeContentHandler::~XalanSourceTreeContentHandler()
{
}
void
XalanSourceTreeContentHandler::characters(
const XMLCh* const chars,
const unsigned int length)
{
assert(m_inDTD == false);
if (m_currentElement == 0)
{
if (isXMLWhitespace(chars) == false)
{
throw XalanDOMException(XalanDOMException::HIERARCHY_REQUEST_ERR);
}
}
else if (m_accumulateText == true)
{
append(m_textBuffer, chars, length);
}
else
{
doCharacters(chars, length);
}
}
void
XalanSourceTreeContentHandler::endDocument()
{
assert(m_inDTD == false);
// Pop off the dummy value that we pushed in
// startDocument()...
m_elementStack.pop_back();
assert(m_document->getDocumentElement() != 0);
assert(m_elementStack.empty() == true);
assert(m_lastChildStack.empty() == true);
assert(isEmpty(m_textBuffer) == true);
}
void
XalanSourceTreeContentHandler::endElement(
const XMLCh* const /* uri */,
const XMLCh* const /* localname */,
const XMLCh* const /* qname */)
{
assert(m_inDTD == false);
// Process any text that we may have accumulated...
processAccumulatedText();
assert(m_elementStack.empty() == false);
// Pop the element of the stack...
m_elementStack.pop_back();
assert(m_elementStack.empty() == false);
// Get the element from the back of the
// stack.
m_currentElement = m_elementStack.back();
assert(m_lastChildStack.empty() == false);
m_lastChild = m_lastChildStack.back();
// Pop the last child stack
m_lastChildStack.pop_back();
}
// A helper function to manage appending the new child.
template <class ParentNodeType, class ChildNodeType>
inline void
doAppendChildNode(
ParentNodeType* theParent,
XalanNode*& theLastChild,
ChildNodeType theNewChild)
{
assert(theParent != 0);
assert(theNewChild != 0);
if (theLastChild == 0)
{
theParent->appendChildNode(theNewChild);
}
else
{
XalanSourceTreeHelper::appendSibling(theLastChild, theNewChild);
}
theLastChild = theNewChild;
}
// A helper function to manage appending the new child.
template <class ChildNodeType>
inline void
doAppendChildNode(
XalanSourceTreeDocument* theDocument,
XalanSourceTreeElement* theCurrentElement,
XalanNode*& theLastChild,
ChildNodeType theNewChild)
{
assert(theDocument != 0);
assert(theNewChild != 0);
if (theCurrentElement == 0)
{
// If there is no current element. it means we haven't
// created the document element yet, so always append
// to the document, rather than the last child.
theDocument->appendChildNode(theNewChild);
}
else
{
doAppendChildNode(theCurrentElement, theLastChild, theNewChild);
}
}
void
XalanSourceTreeContentHandler::ignorableWhitespace(
const XMLCh* const chars,
const unsigned int length)
{
assert(m_inDTD == false);
// Ignore any whitespace reported before the document element has been parsed.
if (m_elementStack.empty() == false)
{
assert(m_currentElement != 0);
processAccumulatedText();
XalanSourceTreeText* theNewTextNode =
m_document->createTextIWSNode(chars, length, m_currentElement);
doAppendChildNode(m_currentElement, m_lastChild, theNewTextNode);
}
}
void
XalanSourceTreeContentHandler::processingInstruction(
const XMLCh* const target,
const XMLCh* const data)
{
assert(m_inDTD == false);
processAccumulatedText();
XalanSourceTreeProcessingInstruction* const theNewPI =
m_document->createProcessingInstructionNode(target, data, m_currentElement);
doAppendChildNode(
m_document,
m_currentElement,
m_lastChild,
theNewPI);
}
void
XalanSourceTreeContentHandler::setDocumentLocator(const Locator* const /* locator */)
{
}
void
XalanSourceTreeContentHandler::startDocument()
{
assert(m_inDTD == false);
m_currentElement = 0;
m_elementStack.clear();
m_elementStack.reserve(eDefaultStackSize);
m_lastChild = 0;
m_lastChildStack.clear();
m_lastChildStack.reserve(eDefaultStackSize);
if (m_accumulateText == true)
{
clear(m_textBuffer);
reserve(m_textBuffer, eDefaultTextBufferSize);
}
// Push a dummy value for the current element, so we
// don't have to check for an empty stack in endElement().
m_elementStack.push_back(ElementStackType::value_type(0));
}
void
XalanSourceTreeContentHandler::startElement(
const XMLCh* const uri,
const XMLCh* const localname,
const XMLCh* const qname,
const Attributes& attrs)
{
assert(m_inDTD == false);
processAccumulatedText();
XalanSourceTreeElement* const theNewElement =
createElement(uri, localname, qname, attrs, m_currentElement);
doAppendChildNode(
m_document,
m_currentElement,
m_lastChild,
theNewElement);
m_elementStack.push_back(theNewElement);
m_lastChildStack.push_back(m_lastChild);
m_currentElement = theNewElement;
m_lastChild = 0;
}
void
XalanSourceTreeContentHandler::startPrefixMapping(
const XMLCh* const /* prefix */,
const XMLCh* const /* uri */)
{
assert(m_inDTD == false);
}
void
XalanSourceTreeContentHandler::endPrefixMapping(const XMLCh* const /* prefix */)
{
assert(m_inDTD == false);
}
void
XalanSourceTreeContentHandler::skippedEntity(const XMLCh* const /* name */)
{
}
void
XalanSourceTreeContentHandler::notationDecl(
const XMLCh* const name,
const XMLCh* const publicId,
const XMLCh* const systemId)
{
}
void
XalanSourceTreeContentHandler::unparsedEntityDecl(
const XMLCh* const name,
const XMLCh* const publicId,
const XMLCh* const systemId,
const XMLCh* const notationName)
{
assert(m_document != 0);
m_document->unparsedEntityDeclaration(name, publicId, systemId, notationName);
}
void
XalanSourceTreeContentHandler::resetDocType()
{
}
void
XalanSourceTreeContentHandler::comment(
const XMLCh* const chars,
const unsigned int length)
{
assert(m_document != 0);
if (m_inDTD == false)
{
processAccumulatedText();
XalanSourceTreeComment* const theNewComment =
m_document->createCommentNode(chars, length, m_currentElement);
doAppendChildNode(
m_document,
m_currentElement,
m_lastChild,
theNewComment);
}
}
void
XalanSourceTreeContentHandler::endCDATA()
{
assert(m_inDTD == false);
}
void
XalanSourceTreeContentHandler::endDTD()
{
m_inDTD = false;
assert(m_document != 0);
}
void
XalanSourceTreeContentHandler::endEntity(const XMLCh* const name)
{
assert(m_document != 0);
}
void
XalanSourceTreeContentHandler::startCDATA()
{
assert(m_inDTD == false);
}
void
XalanSourceTreeContentHandler::startDTD(
const XMLCh* const name,
const XMLCh* const publicId,
const XMLCh* const systemId)
{
assert(m_inDTD == false);
assert(m_document != 0);
m_inDTD = true;
}
void
XalanSourceTreeContentHandler::startEntity(const XMLCh* const name)
{
assert(m_document != 0);
}
void
XalanSourceTreeContentHandler::setDocument(XalanSourceTreeDocument* theDocument)
{
m_document = theDocument;
}
XalanSourceTreeElement*
XalanSourceTreeContentHandler::createElement(
const XMLCh* const uri,
const XMLCh* const localname,
const XMLCh* const qname,
const Attributes& attrs,
XalanSourceTreeElement* theOwnerElement)
{
assert(m_inDTD == false);
// If we're creating the document element, add the special xml namespace attribute...
const bool fAddXMLNamespaceAttribute = theOwnerElement == 0 ? true : false;
if (length(uri) != 0)
{
return m_document->createElementNode(uri, localname, qname, attrs, theOwnerElement, 0, 0, fAddXMLNamespaceAttribute);
}
else
{
return m_document->createElementNode(qname, attrs, theOwnerElement, 0, 0, fAddXMLNamespaceAttribute);
}
}
void
XalanSourceTreeContentHandler::processAccumulatedText()
{
assert(m_inDTD == false);
if (isEmpty(m_textBuffer) == false)
{
assert(unsigned(length(m_textBuffer)) == length(m_textBuffer));
doCharacters(c_wstr(m_textBuffer), length(m_textBuffer));
clear(m_textBuffer);
}
}
void
XalanSourceTreeContentHandler::doCharacters(
const XMLCh* chars,
unsigned int length)
{
assert(m_inDTD == false);
assert(m_currentElement != 0);
XalanSourceTreeText* theNewTextNode =
m_document->createTextNode(chars, length, m_currentElement);
doAppendChildNode(m_currentElement, m_lastChild, theNewTextNode);
}
<commit_msg>Added assert.<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 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 "Xerces" 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/>.
*/
#include "XalanSourceTreeContentHandler.hpp"
#include <XalanDOM/XalanDOMException.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#include "XalanSourceTreeDocument.hpp"
#include "XalanSourceTreeElement.hpp"
#include "XalanSourceTreeHelper.hpp"
XalanSourceTreeContentHandler::XalanSourceTreeContentHandler(
XalanSourceTreeDocument* theDocument,
bool fAccumulateText) :
ContentHandler(),
DTDHandler(),
LexicalHandler(),
m_document(theDocument),
m_currentElement(0),
m_elementStack(),
m_lastChild(0),
m_lastChildStack(),
m_accumulateText(fAccumulateText),
m_textBuffer(),
m_inDTD(false)
{
}
XalanSourceTreeContentHandler::~XalanSourceTreeContentHandler()
{
}
void
XalanSourceTreeContentHandler::characters(
const XMLCh* const chars,
const unsigned int length)
{
assert(m_inDTD == false);
if (m_currentElement == 0)
{
if (isXMLWhitespace(chars) == false)
{
throw XalanDOMException(XalanDOMException::HIERARCHY_REQUEST_ERR);
}
}
else if (m_accumulateText == true)
{
append(m_textBuffer, chars, length);
}
else
{
doCharacters(chars, length);
}
}
void
XalanSourceTreeContentHandler::endDocument()
{
assert(m_inDTD == false);
// Pop off the dummy value that we pushed in
// startDocument()...
m_elementStack.pop_back();
assert(m_document->getDocumentElement() != 0);
assert(m_elementStack.empty() == true);
assert(m_lastChildStack.empty() == true);
assert(isEmpty(m_textBuffer) == true);
}
void
XalanSourceTreeContentHandler::endElement(
const XMLCh* const /* uri */,
const XMLCh* const /* localname */,
const XMLCh* const /* qname */)
{
assert(m_inDTD == false);
// Process any text that we may have accumulated...
processAccumulatedText();
assert(m_elementStack.empty() == false);
// Pop the element of the stack...
m_elementStack.pop_back();
assert(m_elementStack.empty() == false);
// Get the element from the back of the
// stack.
m_currentElement = m_elementStack.back();
assert(m_lastChildStack.empty() == false);
m_lastChild = m_lastChildStack.back();
// Pop the last child stack
m_lastChildStack.pop_back();
}
// A helper function to manage appending the new child.
template <class ParentNodeType, class ChildNodeType>
inline void
doAppendChildNode(
ParentNodeType* theParent,
XalanNode*& theLastChild,
ChildNodeType theNewChild)
{
assert(theParent != 0);
assert(theNewChild != 0);
if (theLastChild == 0)
{
theParent->appendChildNode(theNewChild);
}
else
{
XalanSourceTreeHelper::appendSibling(theLastChild, theNewChild);
}
theLastChild = theNewChild;
}
// A helper function to manage appending the new child.
template <class ChildNodeType>
inline void
doAppendChildNode(
XalanSourceTreeDocument* theDocument,
XalanSourceTreeElement* theCurrentElement,
XalanNode*& theLastChild,
ChildNodeType theNewChild)
{
assert(theDocument != 0);
assert(theNewChild != 0);
if (theCurrentElement == 0)
{
// If there is no current element. it means we haven't
// created the document element yet, so always append
// to the document, rather than the last child.
theDocument->appendChildNode(theNewChild);
}
else
{
doAppendChildNode(theCurrentElement, theLastChild, theNewChild);
}
}
void
XalanSourceTreeContentHandler::ignorableWhitespace(
const XMLCh* const chars,
const unsigned int length)
{
assert(m_inDTD == false);
// Ignore any whitespace reported before the document element has been parsed.
if (m_elementStack.empty() == false)
{
assert(m_currentElement != 0);
processAccumulatedText();
XalanSourceTreeText* theNewTextNode =
m_document->createTextIWSNode(chars, length, m_currentElement);
doAppendChildNode(m_currentElement, m_lastChild, theNewTextNode);
}
}
void
XalanSourceTreeContentHandler::processingInstruction(
const XMLCh* const target,
const XMLCh* const data)
{
assert(m_inDTD == false);
processAccumulatedText();
XalanSourceTreeProcessingInstruction* const theNewPI =
m_document->createProcessingInstructionNode(target, data, m_currentElement);
doAppendChildNode(
m_document,
m_currentElement,
m_lastChild,
theNewPI);
}
void
XalanSourceTreeContentHandler::setDocumentLocator(const Locator* const /* locator */)
{
}
void
XalanSourceTreeContentHandler::startDocument()
{
assert(m_inDTD == false);
m_currentElement = 0;
m_elementStack.clear();
m_elementStack.reserve(eDefaultStackSize);
m_lastChild = 0;
m_lastChildStack.clear();
m_lastChildStack.reserve(eDefaultStackSize);
if (m_accumulateText == true)
{
clear(m_textBuffer);
reserve(m_textBuffer, eDefaultTextBufferSize);
}
// Push a dummy value for the current element, so we
// don't have to check for an empty stack in endElement().
m_elementStack.push_back(ElementStackType::value_type(0));
}
void
XalanSourceTreeContentHandler::startElement(
const XMLCh* const uri,
const XMLCh* const localname,
const XMLCh* const qname,
const Attributes& attrs)
{
assert(m_inDTD == false);
processAccumulatedText();
XalanSourceTreeElement* const theNewElement =
createElement(uri, localname, qname, attrs, m_currentElement);
doAppendChildNode(
m_document,
m_currentElement,
m_lastChild,
theNewElement);
m_elementStack.push_back(theNewElement);
m_lastChildStack.push_back(m_lastChild);
m_currentElement = theNewElement;
m_lastChild = 0;
}
void
XalanSourceTreeContentHandler::startPrefixMapping(
const XMLCh* const /* prefix */,
const XMLCh* const /* uri */)
{
assert(m_inDTD == false);
}
void
XalanSourceTreeContentHandler::endPrefixMapping(const XMLCh* const /* prefix */)
{
assert(m_inDTD == false);
}
void
XalanSourceTreeContentHandler::skippedEntity(const XMLCh* const /* name */)
{
}
void
XalanSourceTreeContentHandler::notationDecl(
const XMLCh* const name,
const XMLCh* const publicId,
const XMLCh* const systemId)
{
}
void
XalanSourceTreeContentHandler::unparsedEntityDecl(
const XMLCh* const name,
const XMLCh* const publicId,
const XMLCh* const systemId,
const XMLCh* const notationName)
{
assert(m_document != 0);
m_document->unparsedEntityDeclaration(name, publicId, systemId, notationName);
}
void
XalanSourceTreeContentHandler::resetDocType()
{
}
void
XalanSourceTreeContentHandler::comment(
const XMLCh* const chars,
const unsigned int length)
{
assert(m_document != 0);
if (m_inDTD == false)
{
processAccumulatedText();
XalanSourceTreeComment* const theNewComment =
m_document->createCommentNode(chars, length, m_currentElement);
doAppendChildNode(
m_document,
m_currentElement,
m_lastChild,
theNewComment);
}
}
void
XalanSourceTreeContentHandler::endCDATA()
{
assert(m_inDTD == false);
}
void
XalanSourceTreeContentHandler::endDTD()
{
assert(m_document != 0);
assert(m_inDTD == true);
m_inDTD = false;
}
void
XalanSourceTreeContentHandler::endEntity(const XMLCh* const name)
{
assert(m_document != 0);
}
void
XalanSourceTreeContentHandler::startCDATA()
{
assert(m_inDTD == false);
}
void
XalanSourceTreeContentHandler::startDTD(
const XMLCh* const name,
const XMLCh* const publicId,
const XMLCh* const systemId)
{
assert(m_inDTD == false);
assert(m_document != 0);
m_inDTD = true;
}
void
XalanSourceTreeContentHandler::startEntity(const XMLCh* const name)
{
assert(m_document != 0);
}
void
XalanSourceTreeContentHandler::setDocument(XalanSourceTreeDocument* theDocument)
{
m_document = theDocument;
}
XalanSourceTreeElement*
XalanSourceTreeContentHandler::createElement(
const XMLCh* const uri,
const XMLCh* const localname,
const XMLCh* const qname,
const Attributes& attrs,
XalanSourceTreeElement* theOwnerElement)
{
assert(m_inDTD == false);
// If we're creating the document element, add the special xml namespace attribute...
const bool fAddXMLNamespaceAttribute = theOwnerElement == 0 ? true : false;
if (length(uri) != 0)
{
return m_document->createElementNode(uri, localname, qname, attrs, theOwnerElement, 0, 0, fAddXMLNamespaceAttribute);
}
else
{
return m_document->createElementNode(qname, attrs, theOwnerElement, 0, 0, fAddXMLNamespaceAttribute);
}
}
void
XalanSourceTreeContentHandler::processAccumulatedText()
{
assert(m_inDTD == false);
if (isEmpty(m_textBuffer) == false)
{
assert(unsigned(length(m_textBuffer)) == length(m_textBuffer));
doCharacters(c_wstr(m_textBuffer), length(m_textBuffer));
clear(m_textBuffer);
}
}
void
XalanSourceTreeContentHandler::doCharacters(
const XMLCh* chars,
unsigned int length)
{
assert(m_inDTD == false);
assert(m_currentElement != 0);
XalanSourceTreeText* theNewTextNode =
m_document->createTextNode(chars, length, m_currentElement);
doAppendChildNode(m_currentElement, m_lastChild, theNewTextNode);
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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 [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QDebug>
#include "multimedia/qlocalmediaplaylistprovider.h"
#include "multimedia/qmediaplaylistnavigator.h"
class tst_QMediaPlaylistNavigator : public QObject
{
Q_OBJECT
public slots:
void init();
void cleanup();
private slots:
void construction();
void setPlaylist();
void linearPlayback();
void loopPlayback();
void currentItemOnce();
void currentItemInLoop();
void randomPlayback();
};
void tst_QMediaPlaylistNavigator::init()
{
}
void tst_QMediaPlaylistNavigator::cleanup()
{
}
void tst_QMediaPlaylistNavigator::construction()
{
QLocalMediaPlaylistProvider playlist;
QCOMPARE(playlist.size(), 0);
QMediaPlaylistNavigator navigator(&playlist);
QVERIFY(navigator.currentItem().isNull());
QCOMPARE(navigator.currentPosition(), -1);
}
void tst_QMediaPlaylistNavigator::setPlaylist()
{
QMediaPlaylistNavigator navigator(0);
QVERIFY(navigator.playlist() != 0);
QCOMPARE(navigator.playlist()->size(), 0);
QVERIFY(navigator.playlist()->isReadOnly() );
QLocalMediaPlaylistProvider playlist;
QCOMPARE(playlist.size(), 0);
navigator.setPlaylist(&playlist);
QCOMPARE(navigator.playlist(), &playlist);
QCOMPARE(navigator.playlist()->size(), 0);
QVERIFY(!navigator.playlist()->isReadOnly() );
}
void tst_QMediaPlaylistNavigator::linearPlayback()
{
QLocalMediaPlaylistProvider playlist;
QMediaPlaylistNavigator navigator(&playlist);
navigator.setPlaybackMode(QMediaPlaylist::Linear);
QTest::ignoreMessage(QtWarningMsg, "QMediaPlaylistNavigator: Jump outside playlist range ");
navigator.jump(0);//it's ok to have warning here
QVERIFY(navigator.currentItem().isNull());
QCOMPARE(navigator.currentPosition(), -1);
QMediaContent content1(QUrl(QLatin1String("file:///1")));
playlist.appendItem(content1);
navigator.jump(0);
QVERIFY(!navigator.currentItem().isNull());
QCOMPARE(navigator.currentPosition(), 0);
QCOMPARE(navigator.currentItem(), content1);
QCOMPARE(navigator.nextItem(), QMediaContent());
QCOMPARE(navigator.nextItem(2), QMediaContent());
QCOMPARE(navigator.previousItem(), QMediaContent());
QCOMPARE(navigator.previousItem(2), QMediaContent());
QMediaContent content2(QUrl(QLatin1String("file:///2")));
playlist.appendItem(content2);
QCOMPARE(navigator.currentPosition(), 0);
QCOMPARE(navigator.currentItem(), content1);
QCOMPARE(navigator.nextItem(), content2);
QCOMPARE(navigator.nextItem(2), QMediaContent());
QCOMPARE(navigator.previousItem(), QMediaContent());
QCOMPARE(navigator.previousItem(2), QMediaContent());
navigator.jump(1);
QCOMPARE(navigator.currentPosition(), 1);
QCOMPARE(navigator.currentItem(), content2);
QCOMPARE(navigator.nextItem(), QMediaContent());
QCOMPARE(navigator.nextItem(2), QMediaContent());
QCOMPARE(navigator.previousItem(), content1);
QCOMPARE(navigator.previousItem(2), QMediaContent());
navigator.jump(0);
navigator.next();
QCOMPARE(navigator.currentPosition(), 1);
navigator.next();
QCOMPARE(navigator.currentPosition(), -1);
navigator.next();//jump to the first item
QCOMPARE(navigator.currentPosition(), 0);
navigator.previous();
QCOMPARE(navigator.currentPosition(), -1);
navigator.previous();//jump to the last item
QCOMPARE(navigator.currentPosition(), 1);
}
void tst_QMediaPlaylistNavigator::loopPlayback()
{
QLocalMediaPlaylistProvider playlist;
QMediaPlaylistNavigator navigator(&playlist);
navigator.setPlaybackMode(QMediaPlaylist::Loop);
QTest::ignoreMessage(QtWarningMsg, "QMediaPlaylistNavigator: Jump outside playlist range ");
navigator.jump(0);
QVERIFY(navigator.currentItem().isNull());
QCOMPARE(navigator.currentPosition(), -1);
QMediaContent content1(QUrl(QLatin1String("file:///1")));
playlist.appendItem(content1);
navigator.jump(0);
QVERIFY(!navigator.currentItem().isNull());
QCOMPARE(navigator.currentPosition(), 0);
QCOMPARE(navigator.currentItem(), content1);
QCOMPARE(navigator.nextItem(), content1);
QCOMPARE(navigator.nextItem(2), content1);
QCOMPARE(navigator.previousItem(), content1);
QCOMPARE(navigator.previousItem(2), content1);
QMediaContent content2(QUrl(QLatin1String("file:///2")));
playlist.appendItem(content2);
QCOMPARE(navigator.currentPosition(), 0);
QCOMPARE(navigator.currentItem(), content1);
QCOMPARE(navigator.nextItem(), content2);
QCOMPARE(navigator.nextItem(2), content1); //loop over end of the list
QCOMPARE(navigator.previousItem(), content2);
QCOMPARE(navigator.previousItem(2), content1);
navigator.jump(1);
QCOMPARE(navigator.currentPosition(), 1);
QCOMPARE(navigator.currentItem(), content2);
QCOMPARE(navigator.nextItem(), content1);
QCOMPARE(navigator.nextItem(2), content2);
QCOMPARE(navigator.previousItem(), content1);
QCOMPARE(navigator.previousItem(2), content2);
navigator.jump(0);
navigator.next();
QCOMPARE(navigator.currentPosition(), 1);
navigator.next();
QCOMPARE(navigator.currentPosition(), 0);
navigator.previous();
QCOMPARE(navigator.currentPosition(), 1);
navigator.previous();
QCOMPARE(navigator.currentPosition(), 0);
}
void tst_QMediaPlaylistNavigator::currentItemOnce()
{
QLocalMediaPlaylistProvider playlist;
QMediaPlaylistNavigator navigator(&playlist);
navigator.setPlaybackMode(QMediaPlaylist::CurrentItemOnce);
QCOMPARE(navigator.playbackMode(), QMediaPlaylist::CurrentItemOnce);
QCOMPARE(navigator.currentPosition(), -1);
playlist.appendItem(QMediaContent(QUrl(QLatin1String("file:///1"))));
playlist.appendItem(QMediaContent(QUrl(QLatin1String("file:///2"))));
playlist.appendItem(QMediaContent(QUrl(QLatin1String("file:///3"))));
QCOMPARE(navigator.currentPosition(), -1);
navigator.next();
QCOMPARE(navigator.currentPosition(), -1);
navigator.jump(1);
QCOMPARE(navigator.currentPosition(), 1);
navigator.next();
QCOMPARE(navigator.currentPosition(), -1);
navigator.next();
QCOMPARE(navigator.currentPosition(), -1);
navigator.previous();
QCOMPARE(navigator.currentPosition(), -1);
navigator.jump(1);
navigator.previous();
QCOMPARE(navigator.currentPosition(), -1);
}
void tst_QMediaPlaylistNavigator::currentItemInLoop()
{
QLocalMediaPlaylistProvider playlist;
QMediaPlaylistNavigator navigator(&playlist);
navigator.setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
QCOMPARE(navigator.playbackMode(), QMediaPlaylist::CurrentItemInLoop);
QCOMPARE(navigator.currentPosition(), -1);
playlist.appendItem(QMediaContent(QUrl(QLatin1String("file:///1"))));
playlist.appendItem(QMediaContent(QUrl(QLatin1String("file:///2"))));
playlist.appendItem(QMediaContent(QUrl(QLatin1String("file:///3"))));
QCOMPARE(navigator.currentPosition(), -1);
navigator.next();
QCOMPARE(navigator.currentPosition(), -1);
navigator.jump(1);
navigator.next();
QCOMPARE(navigator.currentPosition(), 1);
navigator.next();
QCOMPARE(navigator.currentPosition(), 1);
navigator.previous();
QCOMPARE(navigator.currentPosition(), 1);
navigator.previous();
QCOMPARE(navigator.currentPosition(), 1);
}
void tst_QMediaPlaylistNavigator::randomPlayback()
{
QLocalMediaPlaylistProvider playlist;
QMediaPlaylistNavigator navigator(&playlist);
navigator.setPlaybackMode(QMediaPlaylist::Random);
QCOMPARE(navigator.playbackMode(), QMediaPlaylist::Random);
QCOMPARE(navigator.currentPosition(), -1);
playlist.appendItem(QMediaContent(QUrl(QLatin1String("file:///1"))));
playlist.appendItem(QMediaContent(QUrl(QLatin1String("file:///2"))));
playlist.appendItem(QMediaContent(QUrl(QLatin1String("file:///3"))));
QCOMPARE(navigator.currentPosition(), -1);
navigator.next();
int pos1 = navigator.currentPosition();
navigator.next();
int pos2 = navigator.currentPosition();
navigator.next();
int pos3 = navigator.currentPosition();
QVERIFY(pos1 != -1);
QVERIFY(pos2 != -1);
QVERIFY(pos3 != -1);
navigator.previous();
QCOMPARE(navigator.currentPosition(), pos2);
navigator.next();
QCOMPARE(navigator.currentPosition(), pos3);
navigator.next();
int pos4 = navigator.currentPosition();
navigator.previous();
QCOMPARE(navigator.currentPosition(), pos3);
navigator.previous();
QCOMPARE(navigator.currentPosition(), pos2);
navigator.previous();
QCOMPARE(navigator.currentPosition(), pos1);
navigator.previous();
int pos0 = navigator.currentPosition();
QVERIFY(pos0 != -1);
navigator.next();
navigator.next();
navigator.next();
navigator.next();
QCOMPARE(navigator.currentPosition(), pos4);
}
QTEST_MAIN(tst_QMediaPlaylistNavigator)
#include "tst_qmediaplaylistnavigator.moc"
<commit_msg>Update to unit test for QLocalMediaPlaylistProvider. added shuffle() function to unit test.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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 [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QDebug>
#include "multimedia/qlocalmediaplaylistprovider.h"
#include "multimedia/qmediaplaylistnavigator.h"
class tst_QMediaPlaylistNavigator : public QObject
{
Q_OBJECT
public slots:
void init();
void cleanup();
private slots:
void construction();
void setPlaylist();
void linearPlayback();
void loopPlayback();
void currentItemOnce();
void currentItemInLoop();
void randomPlayback();
};
void tst_QMediaPlaylistNavigator::init()
{
}
void tst_QMediaPlaylistNavigator::cleanup()
{
}
void tst_QMediaPlaylistNavigator::construction()
{
QLocalMediaPlaylistProvider playlist;
QCOMPARE(playlist.size(), 0);
QMediaPlaylistNavigator navigator(&playlist);
QVERIFY(navigator.currentItem().isNull());
QCOMPARE(navigator.currentPosition(), -1);
}
void tst_QMediaPlaylistNavigator::setPlaylist()
{
QMediaPlaylistNavigator navigator(0);
QVERIFY(navigator.playlist() != 0);
QCOMPARE(navigator.playlist()->size(), 0);
QVERIFY(navigator.playlist()->isReadOnly() );
QLocalMediaPlaylistProvider playlist;
QCOMPARE(playlist.size(), 0);
navigator.setPlaylist(&playlist);
QCOMPARE(navigator.playlist(), &playlist);
QCOMPARE(navigator.playlist()->size(), 0);
QVERIFY(!navigator.playlist()->isReadOnly() );
}
void tst_QMediaPlaylistNavigator::linearPlayback()
{
QLocalMediaPlaylistProvider playlist;
QMediaPlaylistNavigator navigator(&playlist);
navigator.setPlaybackMode(QMediaPlaylist::Linear);
QTest::ignoreMessage(QtWarningMsg, "QMediaPlaylistNavigator: Jump outside playlist range ");
navigator.jump(0);//it's ok to have warning here
QVERIFY(navigator.currentItem().isNull());
QCOMPARE(navigator.currentPosition(), -1);
QMediaContent content1(QUrl(QLatin1String("file:///1")));
playlist.appendItem(content1);
navigator.jump(0);
QVERIFY(!navigator.currentItem().isNull());
QCOMPARE(navigator.currentPosition(), 0);
QCOMPARE(navigator.currentItem(), content1);
QCOMPARE(navigator.nextItem(), QMediaContent());
QCOMPARE(navigator.nextItem(2), QMediaContent());
QCOMPARE(navigator.previousItem(), QMediaContent());
QCOMPARE(navigator.previousItem(2), QMediaContent());
QMediaContent content2(QUrl(QLatin1String("file:///2")));
playlist.appendItem(content2);
QCOMPARE(navigator.currentPosition(), 0);
QCOMPARE(navigator.currentItem(), content1);
QCOMPARE(navigator.nextItem(), content2);
QCOMPARE(navigator.nextItem(2), QMediaContent());
QCOMPARE(navigator.previousItem(), QMediaContent());
QCOMPARE(navigator.previousItem(2), QMediaContent());
navigator.jump(1);
QCOMPARE(navigator.currentPosition(), 1);
QCOMPARE(navigator.currentItem(), content2);
QCOMPARE(navigator.nextItem(), QMediaContent());
QCOMPARE(navigator.nextItem(2), QMediaContent());
QCOMPARE(navigator.previousItem(), content1);
QCOMPARE(navigator.previousItem(2), QMediaContent());
navigator.jump(0);
navigator.next();
QCOMPARE(navigator.currentPosition(), 1);
navigator.next();
QCOMPARE(navigator.currentPosition(), -1);
navigator.next();//jump to the first item
QCOMPARE(navigator.currentPosition(), 0);
navigator.previous();
QCOMPARE(navigator.currentPosition(), -1);
navigator.previous();//jump to the last item
QCOMPARE(navigator.currentPosition(), 1);
}
void tst_QMediaPlaylistNavigator::loopPlayback()
{
QLocalMediaPlaylistProvider playlist;
QMediaPlaylistNavigator navigator(&playlist);
navigator.setPlaybackMode(QMediaPlaylist::Loop);
QTest::ignoreMessage(QtWarningMsg, "QMediaPlaylistNavigator: Jump outside playlist range ");
navigator.jump(0);
QVERIFY(navigator.currentItem().isNull());
QCOMPARE(navigator.currentPosition(), -1);
QMediaContent content1(QUrl(QLatin1String("file:///1")));
playlist.appendItem(content1);
navigator.jump(0);
QVERIFY(!navigator.currentItem().isNull());
QCOMPARE(navigator.currentPosition(), 0);
QCOMPARE(navigator.currentItem(), content1);
QCOMPARE(navigator.nextItem(), content1);
QCOMPARE(navigator.nextItem(2), content1);
QCOMPARE(navigator.previousItem(), content1);
QCOMPARE(navigator.previousItem(2), content1);
QMediaContent content2(QUrl(QLatin1String("file:///2")));
playlist.appendItem(content2);
QCOMPARE(navigator.currentPosition(), 0);
QCOMPARE(navigator.currentItem(), content1);
QCOMPARE(navigator.nextItem(), content2);
QCOMPARE(navigator.nextItem(2), content1); //loop over end of the list
QCOMPARE(navigator.previousItem(), content2);
QCOMPARE(navigator.previousItem(2), content1);
navigator.jump(1);
QCOMPARE(navigator.currentPosition(), 1);
QCOMPARE(navigator.currentItem(), content2);
QCOMPARE(navigator.nextItem(), content1);
QCOMPARE(navigator.nextItem(2), content2);
QCOMPARE(navigator.previousItem(), content1);
QCOMPARE(navigator.previousItem(2), content2);
navigator.jump(0);
navigator.next();
QCOMPARE(navigator.currentPosition(), 1);
navigator.next();
QCOMPARE(navigator.currentPosition(), 0);
navigator.previous();
QCOMPARE(navigator.currentPosition(), 1);
navigator.previous();
QCOMPARE(navigator.currentPosition(), 0);
}
void tst_QMediaPlaylistNavigator::currentItemOnce()
{
QLocalMediaPlaylistProvider playlist;
QMediaPlaylistNavigator navigator(&playlist);
navigator.setPlaybackMode(QMediaPlaylist::CurrentItemOnce);
QCOMPARE(navigator.playbackMode(), QMediaPlaylist::CurrentItemOnce);
QCOMPARE(navigator.currentPosition(), -1);
playlist.appendItem(QMediaContent(QUrl(QLatin1String("file:///1"))));
playlist.appendItem(QMediaContent(QUrl(QLatin1String("file:///2"))));
playlist.appendItem(QMediaContent(QUrl(QLatin1String("file:///3"))));
QCOMPARE(navigator.currentPosition(), -1);
navigator.next();
QCOMPARE(navigator.currentPosition(), -1);
navigator.jump(1);
QCOMPARE(navigator.currentPosition(), 1);
navigator.next();
QCOMPARE(navigator.currentPosition(), -1);
navigator.next();
QCOMPARE(navigator.currentPosition(), -1);
navigator.previous();
QCOMPARE(navigator.currentPosition(), -1);
navigator.jump(1);
navigator.previous();
QCOMPARE(navigator.currentPosition(), -1);
}
void tst_QMediaPlaylistNavigator::currentItemInLoop()
{
QLocalMediaPlaylistProvider playlist;
QMediaPlaylistNavigator navigator(&playlist);
navigator.setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
QCOMPARE(navigator.playbackMode(), QMediaPlaylist::CurrentItemInLoop);
QCOMPARE(navigator.currentPosition(), -1);
playlist.appendItem(QMediaContent(QUrl(QLatin1String("file:///1"))));
playlist.appendItem(QMediaContent(QUrl(QLatin1String("file:///2"))));
playlist.appendItem(QMediaContent(QUrl(QLatin1String("file:///3"))));
QCOMPARE(navigator.currentPosition(), -1);
navigator.next();
QCOMPARE(navigator.currentPosition(), -1);
navigator.jump(1);
navigator.next();
QCOMPARE(navigator.currentPosition(), 1);
navigator.next();
QCOMPARE(navigator.currentPosition(), 1);
navigator.previous();
QCOMPARE(navigator.currentPosition(), 1);
navigator.previous();
QCOMPARE(navigator.currentPosition(), 1);
}
void tst_QMediaPlaylistNavigator::randomPlayback()
{
QLocalMediaPlaylistProvider playlist;
QMediaPlaylistNavigator navigator(&playlist);
navigator.setPlaybackMode(QMediaPlaylist::Random);
QCOMPARE(navigator.playbackMode(), QMediaPlaylist::Random);
QCOMPARE(navigator.currentPosition(), -1);
playlist.appendItem(QMediaContent(QUrl(QLatin1String("file:///1"))));
playlist.appendItem(QMediaContent(QUrl(QLatin1String("file:///2"))));
playlist.appendItem(QMediaContent(QUrl(QLatin1String("file:///3"))));
playlist.shuffle();
QCOMPARE(navigator.currentPosition(), -1);
navigator.next();
int pos1 = navigator.currentPosition();
navigator.next();
int pos2 = navigator.currentPosition();
navigator.next();
int pos3 = navigator.currentPosition();
QVERIFY(pos1 != -1);
QVERIFY(pos2 != -1);
QVERIFY(pos3 != -1);
navigator.previous();
QCOMPARE(navigator.currentPosition(), pos2);
navigator.next();
QCOMPARE(navigator.currentPosition(), pos3);
navigator.next();
int pos4 = navigator.currentPosition();
navigator.previous();
QCOMPARE(navigator.currentPosition(), pos3);
navigator.previous();
QCOMPARE(navigator.currentPosition(), pos2);
navigator.previous();
QCOMPARE(navigator.currentPosition(), pos1);
navigator.previous();
int pos0 = navigator.currentPosition();
QVERIFY(pos0 != -1);
navigator.next();
navigator.next();
navigator.next();
navigator.next();
QCOMPARE(navigator.currentPosition(), pos4);
}
QTEST_MAIN(tst_QMediaPlaylistNavigator)
#include "tst_qmediaplaylistnavigator.moc"
<|endoftext|> |
<commit_before>// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <sstream>
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/compiler/plugin.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/compiler/ruby/ruby_generator.h>
using google::protobuf::internal::scoped_ptr;
namespace google {
namespace protobuf {
namespace compiler {
namespace ruby {
// Forward decls.
std::string IntToString(uint32_t value);
std::string StripDotProto(const std::string& proto_file);
std::string LabelForField(google::protobuf::FieldDescriptor* field);
std::string TypeName(google::protobuf::FieldDescriptor* field);
void GenerateMessage(const google::protobuf::Descriptor* message,
google::protobuf::io::Printer* printer);
void GenerateEnum(const google::protobuf::EnumDescriptor* en,
google::protobuf::io::Printer* printer);
void GenerateMessageAssignment(
const std::string& prefix,
const google::protobuf::Descriptor* message,
google::protobuf::io::Printer* printer);
void GenerateEnumAssignment(
const std::string& prefix,
const google::protobuf::EnumDescriptor* en,
google::protobuf::io::Printer* printer);
std::string IntToString(uint32_t value) {
std::ostringstream os;
os << value;
return os.str();
}
std::string StripDotProto(const std::string& proto_file) {
int lastindex = proto_file.find_last_of(".");
return proto_file.substr(0, lastindex);
}
std::string LabelForField(const google::protobuf::FieldDescriptor* field) {
switch (field->label()) {
case FieldDescriptor::LABEL_OPTIONAL: return "optional";
case FieldDescriptor::LABEL_REQUIRED: return "required";
case FieldDescriptor::LABEL_REPEATED: return "repeated";
default: assert(false); return "";
}
}
std::string TypeName(const google::protobuf::FieldDescriptor* field) {
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32: return "int32";
case FieldDescriptor::CPPTYPE_INT64: return "int64";
case FieldDescriptor::CPPTYPE_UINT32: return "uint32";
case FieldDescriptor::CPPTYPE_UINT64: return "uint64";
case FieldDescriptor::CPPTYPE_DOUBLE: return "double";
case FieldDescriptor::CPPTYPE_FLOAT: return "float";
case FieldDescriptor::CPPTYPE_BOOL: return "bool";
case FieldDescriptor::CPPTYPE_ENUM: return "enum";
case FieldDescriptor::CPPTYPE_STRING: return "string";
case FieldDescriptor::CPPTYPE_MESSAGE: return "message";
default: assert(false); return "";
}
}
void GenerateMessage(const google::protobuf::Descriptor* message,
google::protobuf::io::Printer* printer) {
printer->Print(
"add_message \"$name$\" do\n",
"name", message->full_name());
printer->Indent();
for (int i = 0; i < message->field_count(); i++) {
const FieldDescriptor* field = message->field(i);
printer->Print(
"$label$ :$name$, ",
"label", LabelForField(field),
"name", field->name());
printer->Print(
":$type$, $number$",
"type", TypeName(field),
"number", IntToString(field->number()));
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
printer->Print(
", \"$subtype$\"\n",
"subtype", field->message_type()->full_name());
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
printer->Print(
", \"$subtype$\"\n",
"subtype", field->enum_type()->full_name());
} else {
printer->Print("\n");
}
}
printer->Outdent();
printer->Print("end\n");
for (int i = 0; i < message->nested_type_count(); i++) {
GenerateMessage(message->nested_type(i), printer);
}
for (int i = 0; i < message->enum_type_count(); i++) {
GenerateEnum(message->enum_type(i), printer);
}
}
void GenerateEnum(const google::protobuf::EnumDescriptor* en,
google::protobuf::io::Printer* printer) {
printer->Print(
"add_enum \"$name$\" do\n",
"name", en->full_name());
printer->Indent();
for (int i = 0; i < en->value_count(); i++) {
const EnumValueDescriptor* value = en->value(i);
printer->Print(
"value :$name$, $number$\n",
"name", value->name(),
"number", IntToString(value->number()));
}
printer->Outdent();
printer->Print(
"end\n");
}
// Module names, class names, and enum value names need to be Ruby constants,
// which must start with a capital letter.
std::string RubifyConstant(const std::string& name) {
std::string ret = name;
if (!ret.empty()) {
if (ret[0] >= 'a' && ret[0] <= 'z') {
// If it starts with a lowercase letter, capitalize it.
ret[0] = ret[0] - 'a' + 'A';
} else if (ret[0] < 'A' || ret[0] > 'Z') {
// Otherwise (e.g. if it begins with an underscore), we need to come up
// with some prefix that starts with a capital letter. We could be smarter
// here, e.g. try to strip leading underscores, but this may cause other
// problems if the user really intended the name. So let's just prepend a
// well-known suffix.
ret = "PB_" + ret;
}
}
return ret;
}
void GenerateMessageAssignment(
const std::string& prefix,
const google::protobuf::Descriptor* message,
google::protobuf::io::Printer* printer) {
printer->Print(
"$prefix$$name$ = ",
"prefix", prefix,
"name", RubifyConstant(message->name()));
printer->Print(
"Google::Protobuf::DescriptorPool.generated_pool."
"lookup(\"$full_name$\").msgclass\n",
"full_name", message->full_name());
std::string nested_prefix = prefix + message->name() + "::";
for (int i = 0; i < message->nested_type_count(); i++) {
GenerateMessageAssignment(nested_prefix, message->nested_type(i), printer);
}
for (int i = 0; i < message->enum_type_count(); i++) {
GenerateEnumAssignment(nested_prefix, message->enum_type(i), printer);
}
}
void GenerateEnumAssignment(
const std::string& prefix,
const google::protobuf::EnumDescriptor* en,
google::protobuf::io::Printer* printer) {
printer->Print(
"$prefix$$name$ = ",
"prefix", prefix,
"name", RubifyConstant(en->name()));
printer->Print(
"Google::Protobuf::DescriptorPool.generated_pool."
"lookup(\"$full_name$\").enummodule\n",
"full_name", en->full_name());
}
int GeneratePackageModules(
std::string package_name,
google::protobuf::io::Printer* printer) {
int levels = 0;
while (!package_name.empty()) {
size_t dot_index = package_name.find(".");
string component;
if (dot_index == string::npos) {
component = package_name;
package_name = "";
} else {
component = package_name.substr(0, dot_index);
package_name = package_name.substr(dot_index + 1);
}
component = RubifyConstant(component);
printer->Print(
"module $name$\n",
"name", component);
printer->Indent();
levels++;
}
return levels;
}
void EndPackageModules(
int levels,
google::protobuf::io::Printer* printer) {
while (levels > 0) {
levels--;
printer->Outdent();
printer->Print(
"end\n");
}
}
void GenerateFile(const google::protobuf::FileDescriptor* file,
google::protobuf::io::Printer* printer) {
printer->Print(
"# Generated by the protocol buffer compiler. DO NOT EDIT!\n"
"# source: $filename$\n"
"\n",
"filename", file->name());
printer->Print(
"require 'google/protobuf'\n\n");
for (int i = 0; i < file->dependency_count(); i++) {
const std::string& name = file->dependency(i)->name();
printer->Print(
"require '$name$'\n", "name", StripDotProto(name));
}
printer->Print(
"Google::Protobuf::DescriptorPool.generated_pool.build do\n");
printer->Indent();
for (int i = 0; i < file->message_type_count(); i++) {
GenerateMessage(file->message_type(i), printer);
}
for (int i = 0; i < file->enum_type_count(); i++) {
GenerateEnum(file->enum_type(i), printer);
}
printer->Outdent();
printer->Print(
"end\n\n");
int levels = GeneratePackageModules(file->package(), printer);
for (int i = 0; i < file->message_type_count(); i++) {
GenerateMessageAssignment("", file->message_type(i), printer);
}
for (int i = 0; i < file->enum_type_count(); i++) {
GenerateEnumAssignment("", file->enum_type(i), printer);
}
EndPackageModules(levels, printer);
}
bool Generator::Generate(
const FileDescriptor* file,
const string& parameter,
GeneratorContext* generator_context,
string* error) const {
std::string filename =
StripDotProto(file->name()) + ".rb";
scoped_ptr<io::ZeroCopyOutputStream> output(generator_context->Open(filename));
io::Printer printer(output.get(), '$');
GenerateFile(file, &printer);
return true;
}
} // namespace ruby
} // namespace compiler
} // namespace protobuf
} // namespace google
<commit_msg>Support Ruby code generation only for proto3.<commit_after>// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <sstream>
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/compiler/plugin.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/compiler/ruby/ruby_generator.h>
using google::protobuf::internal::scoped_ptr;
namespace google {
namespace protobuf {
namespace compiler {
namespace ruby {
// Forward decls.
std::string IntToString(uint32_t value);
std::string StripDotProto(const std::string& proto_file);
std::string LabelForField(google::protobuf::FieldDescriptor* field);
std::string TypeName(google::protobuf::FieldDescriptor* field);
void GenerateMessage(const google::protobuf::Descriptor* message,
google::protobuf::io::Printer* printer);
void GenerateEnum(const google::protobuf::EnumDescriptor* en,
google::protobuf::io::Printer* printer);
void GenerateMessageAssignment(
const std::string& prefix,
const google::protobuf::Descriptor* message,
google::protobuf::io::Printer* printer);
void GenerateEnumAssignment(
const std::string& prefix,
const google::protobuf::EnumDescriptor* en,
google::protobuf::io::Printer* printer);
std::string IntToString(uint32_t value) {
std::ostringstream os;
os << value;
return os.str();
}
std::string StripDotProto(const std::string& proto_file) {
int lastindex = proto_file.find_last_of(".");
return proto_file.substr(0, lastindex);
}
std::string LabelForField(const google::protobuf::FieldDescriptor* field) {
switch (field->label()) {
case FieldDescriptor::LABEL_OPTIONAL: return "optional";
case FieldDescriptor::LABEL_REQUIRED: return "required";
case FieldDescriptor::LABEL_REPEATED: return "repeated";
default: assert(false); return "";
}
}
std::string TypeName(const google::protobuf::FieldDescriptor* field) {
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32: return "int32";
case FieldDescriptor::CPPTYPE_INT64: return "int64";
case FieldDescriptor::CPPTYPE_UINT32: return "uint32";
case FieldDescriptor::CPPTYPE_UINT64: return "uint64";
case FieldDescriptor::CPPTYPE_DOUBLE: return "double";
case FieldDescriptor::CPPTYPE_FLOAT: return "float";
case FieldDescriptor::CPPTYPE_BOOL: return "bool";
case FieldDescriptor::CPPTYPE_ENUM: return "enum";
case FieldDescriptor::CPPTYPE_STRING: return "string";
case FieldDescriptor::CPPTYPE_MESSAGE: return "message";
default: assert(false); return "";
}
}
void GenerateMessage(const google::protobuf::Descriptor* message,
google::protobuf::io::Printer* printer) {
printer->Print(
"add_message \"$name$\" do\n",
"name", message->full_name());
printer->Indent();
for (int i = 0; i < message->field_count(); i++) {
const FieldDescriptor* field = message->field(i);
printer->Print(
"$label$ :$name$, ",
"label", LabelForField(field),
"name", field->name());
printer->Print(
":$type$, $number$",
"type", TypeName(field),
"number", IntToString(field->number()));
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
printer->Print(
", \"$subtype$\"\n",
"subtype", field->message_type()->full_name());
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
printer->Print(
", \"$subtype$\"\n",
"subtype", field->enum_type()->full_name());
} else {
printer->Print("\n");
}
}
printer->Outdent();
printer->Print("end\n");
for (int i = 0; i < message->nested_type_count(); i++) {
GenerateMessage(message->nested_type(i), printer);
}
for (int i = 0; i < message->enum_type_count(); i++) {
GenerateEnum(message->enum_type(i), printer);
}
}
void GenerateEnum(const google::protobuf::EnumDescriptor* en,
google::protobuf::io::Printer* printer) {
printer->Print(
"add_enum \"$name$\" do\n",
"name", en->full_name());
printer->Indent();
for (int i = 0; i < en->value_count(); i++) {
const EnumValueDescriptor* value = en->value(i);
printer->Print(
"value :$name$, $number$\n",
"name", value->name(),
"number", IntToString(value->number()));
}
printer->Outdent();
printer->Print(
"end\n");
}
// Module names, class names, and enum value names need to be Ruby constants,
// which must start with a capital letter.
std::string RubifyConstant(const std::string& name) {
std::string ret = name;
if (!ret.empty()) {
if (ret[0] >= 'a' && ret[0] <= 'z') {
// If it starts with a lowercase letter, capitalize it.
ret[0] = ret[0] - 'a' + 'A';
} else if (ret[0] < 'A' || ret[0] > 'Z') {
// Otherwise (e.g. if it begins with an underscore), we need to come up
// with some prefix that starts with a capital letter. We could be smarter
// here, e.g. try to strip leading underscores, but this may cause other
// problems if the user really intended the name. So let's just prepend a
// well-known suffix.
ret = "PB_" + ret;
}
}
return ret;
}
void GenerateMessageAssignment(
const std::string& prefix,
const google::protobuf::Descriptor* message,
google::protobuf::io::Printer* printer) {
printer->Print(
"$prefix$$name$ = ",
"prefix", prefix,
"name", RubifyConstant(message->name()));
printer->Print(
"Google::Protobuf::DescriptorPool.generated_pool."
"lookup(\"$full_name$\").msgclass\n",
"full_name", message->full_name());
std::string nested_prefix = prefix + message->name() + "::";
for (int i = 0; i < message->nested_type_count(); i++) {
GenerateMessageAssignment(nested_prefix, message->nested_type(i), printer);
}
for (int i = 0; i < message->enum_type_count(); i++) {
GenerateEnumAssignment(nested_prefix, message->enum_type(i), printer);
}
}
void GenerateEnumAssignment(
const std::string& prefix,
const google::protobuf::EnumDescriptor* en,
google::protobuf::io::Printer* printer) {
printer->Print(
"$prefix$$name$ = ",
"prefix", prefix,
"name", RubifyConstant(en->name()));
printer->Print(
"Google::Protobuf::DescriptorPool.generated_pool."
"lookup(\"$full_name$\").enummodule\n",
"full_name", en->full_name());
}
int GeneratePackageModules(
std::string package_name,
google::protobuf::io::Printer* printer) {
int levels = 0;
while (!package_name.empty()) {
size_t dot_index = package_name.find(".");
string component;
if (dot_index == string::npos) {
component = package_name;
package_name = "";
} else {
component = package_name.substr(0, dot_index);
package_name = package_name.substr(dot_index + 1);
}
component = RubifyConstant(component);
printer->Print(
"module $name$\n",
"name", component);
printer->Indent();
levels++;
}
return levels;
}
void EndPackageModules(
int levels,
google::protobuf::io::Printer* printer) {
while (levels > 0) {
levels--;
printer->Outdent();
printer->Print(
"end\n");
}
}
void GenerateFile(const google::protobuf::FileDescriptor* file,
google::protobuf::io::Printer* printer) {
printer->Print(
"# Generated by the protocol buffer compiler. DO NOT EDIT!\n"
"# source: $filename$\n"
"\n",
"filename", file->name());
printer->Print(
"require 'google/protobuf'\n\n");
for (int i = 0; i < file->dependency_count(); i++) {
const std::string& name = file->dependency(i)->name();
printer->Print(
"require '$name$'\n", "name", StripDotProto(name));
}
printer->Print(
"Google::Protobuf::DescriptorPool.generated_pool.build do\n");
printer->Indent();
for (int i = 0; i < file->message_type_count(); i++) {
GenerateMessage(file->message_type(i), printer);
}
for (int i = 0; i < file->enum_type_count(); i++) {
GenerateEnum(file->enum_type(i), printer);
}
printer->Outdent();
printer->Print(
"end\n\n");
int levels = GeneratePackageModules(file->package(), printer);
for (int i = 0; i < file->message_type_count(); i++) {
GenerateMessageAssignment("", file->message_type(i), printer);
}
for (int i = 0; i < file->enum_type_count(); i++) {
GenerateEnumAssignment("", file->enum_type(i), printer);
}
EndPackageModules(levels, printer);
}
bool Generator::Generate(
const FileDescriptor* file,
const string& parameter,
GeneratorContext* generator_context,
string* error) const {
if (file->syntax() != FileDescriptor::SYNTAX_PROTO3) {
*error =
"Can only generate Ruby code for proto3 .proto files.\n"
"Please add 'syntax = \"proto3\";' to the top of your .proto file.\n";
return false;
}
std::string filename =
StripDotProto(file->name()) + ".rb";
scoped_ptr<io::ZeroCopyOutputStream> output(generator_context->Open(filename));
io::Printer printer(output.get(), '$');
GenerateFile(file, &printer);
return true;
}
} // namespace ruby
} // namespace compiler
} // namespace protobuf
} // namespace google
<|endoftext|> |
<commit_before>//
// File: GameController.cpp
// Class: GameController
// Author: John Barbero Unenge
// All code is my own except where credited to others.
//
// Copyright (c) 2012 Catch22. All Rights Reserved.
//
// Date: 24/9/12
//
#include "GameController.hpp"
#include "../Helper/Logger.hpp"
#include "../Helper/InputManager.hpp"
GameController::GameController(int width, int height, CLTexture* texture)
{
Log(LOG_INFO, "GameController", generateCString("GameCon: %ix%i", width, height));
InputManager::getSharedManager()->addInputListener(this);
m_renderer = CreateRendererWithOpenGL10();
m_renderer->init(width, height, texture);
m_gameModel = new GameModel();
}
GameController::~GameController()
{
Log(LOG_INFO, "GameController", "Destroyed GameController");
}
void GameController::update(float dt)
{
m_renderer->update(dt);
m_gameModel->update(dt);
m_renderer->render();
}
void GameController::onRotate(DeviceOrientation orientation)
{
m_renderer->onRotate(orientation);
}
void GameController::didRecieveInputEvent(InputType type, int locX, int locY)
{
Log(LOG_EVENT, "GameController", "DidRecieveInputEvent");
m_gameModel->playerJump();
}
<commit_msg>Added srand to initiate random. (Used by MapGenerator)<commit_after>//
// File: GameController.cpp
// Class: GameController
// Author: John Barbero Unenge
// All code is my own except where credited to others.
//
// Copyright (c) 2012 Catch22. All Rights Reserved.
//
// Date: 24/9/12
//
#include "GameController.hpp"
#include "../Helper/Logger.hpp"
#include "../Helper/InputManager.hpp"
GameController::GameController(int width, int height, CLTexture* texture)
{
srand ( time(NULL) );
Log(LOG_INFO, "GameController", generateCString("GameCon: %ix%i", width, height));
InputManager::getSharedManager()->addInputListener(this);
m_renderer = CreateRendererWithOpenGL10();
m_renderer->init(width, height, texture);
m_gameModel = new GameModel();
}
GameController::~GameController()
{
Log(LOG_INFO, "GameController", "Destroyed GameController");
}
void GameController::update(float dt)
{
m_renderer->update(dt);
m_gameModel->update(dt);
m_renderer->render();
}
void GameController::onRotate(DeviceOrientation orientation)
{
m_renderer->onRotate(orientation);
}
void GameController::didRecieveInputEvent(InputType type, int locX, int locY)
{
Log(LOG_EVENT, "GameController", "DidRecieveInputEvent");
m_gameModel->playerJump();
}
<|endoftext|> |
<commit_before>/**
* @file
* @brief Definition of Object base class
* @copyright Copyright (c) 2017 CERN and the Corryvreckan authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
/**
* @defgroup Objects Objects
* @brief Collection of objects passed around between modules
*/
#ifndef CORRYVRECKAN_OBJECT_H
#define CORRYVRECKAN_OBJECT_H
#include <string>
#include <vector>
#include "TObject.h"
#include "TTree.h"
namespace corryvreckan {
/**
* @ingroup Objects
* @brief Base class for internal objects
*
* Generic base class. Every class which inherits from Object can be placed on the clipboard and written out to file.
*/
class Object : public TObject {
public:
// Constructors and destructors
Object();
explicit Object(std::string detectorID);
explicit Object(double timestamp);
Object(std::string detectorID, double timestamp);
~Object() override;
// Methods to get member variables
std::string getDetectorID() { return m_detectorID; }
std::string detectorID() { return getDetectorID(); }
double timestamp() { return m_timestamp; }
void timestamp(double time) { m_timestamp = time; }
void setTimestamp(double time) { timestamp(time); }
// Methods to set member variables
void setDetectorID(std::string detectorID) { m_detectorID = std::move(detectorID); }
protected:
// Member variables
std::string m_detectorID;
double m_timestamp{0};
// ROOT I/O class definition - update version number when you change this class!
ClassDef(Object, 2)
};
// Vector type declaration
using Objects = std::vector<Object*>;
} // namespace corryvreckan
#endif // CORRYVRECKAN_OBJECT_H
<commit_msg>Silence warnings when building dictionary of CorryvreckanWriter: use ClassDefOverride<commit_after>/**
* @file
* @brief Definition of Object base class
* @copyright Copyright (c) 2017 CERN and the Corryvreckan authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
/**
* @defgroup Objects Objects
* @brief Collection of objects passed around between modules
*/
#ifndef CORRYVRECKAN_OBJECT_H
#define CORRYVRECKAN_OBJECT_H
#include <string>
#include <vector>
#include "TObject.h"
#include "TTree.h"
namespace corryvreckan {
/**
* @ingroup Objects
* @brief Base class for internal objects
*
* Generic base class. Every class which inherits from Object can be placed on the clipboard and written out to file.
*/
class Object : public TObject {
public:
// Constructors and destructors
Object();
explicit Object(std::string detectorID);
explicit Object(double timestamp);
Object(std::string detectorID, double timestamp);
~Object() override;
// Methods to get member variables
std::string getDetectorID() { return m_detectorID; }
std::string detectorID() { return getDetectorID(); }
double timestamp() { return m_timestamp; }
void timestamp(double time) { m_timestamp = time; }
void setTimestamp(double time) { timestamp(time); }
// Methods to set member variables
void setDetectorID(std::string detectorID) { m_detectorID = std::move(detectorID); }
protected:
// Member variables
std::string m_detectorID;
double m_timestamp{0};
// ROOT I/O class definition - update version number when you change this class!
ClassDefOverride(Object, 2)
};
// Vector type declaration
using Objects = std::vector<Object*>;
} // namespace corryvreckan
#endif // CORRYVRECKAN_OBJECT_H
<|endoftext|> |
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include <iostream>
#include <string>
#include <cstdlib>
#include <boost/program_options.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <vespa/fastos/app.h>
#include <vespa/config-zookeepers.h>
#include <vespa/fileacquirer/config-filedistributorrpc.h>
#include <vespa/filedistribution/distributor/config-filedistributor.h>
#include <vespa/filedistribution/model/config-filereferences.h>
#include <vespa/filedistribution/distributor/filedistributortrackerimpl.h>
#include <vespa/filedistribution/distributor/filedownloadermanager.h>
#include <vespa/filedistribution/distributor/filedownloader.h>
#include <vespa/filedistribution/distributor/signalhandling.h>
#include <vespa/filedistribution/distributor/state_server_impl.h>
#include <vespa/filedistribution/model/filedistributionmodelimpl.h>
#include <vespa/filedistribution/rpc/filedistributorrpc.h>
#include <vespa/filedistribution/common/exception.h>
#include <vespa/filedistribution/common/componentsdeleter.h>
namespace {
const char* programName = "filedistributor";
}
#include <vespa/log/log.h>
LOG_SETUP(programName);
using namespace std::literals;
using namespace filedistribution;
using cloud::config::ZookeepersConfig;
using cloud::config::filedistribution::FiledistributorConfig;
using cloud::config::filedistribution::FiledistributorrpcConfig;
class FileDistributor : public config::IFetcherCallback<ZookeepersConfig>,
public config::IFetcherCallback<FiledistributorConfig>,
public config::IFetcherCallback<FiledistributorrpcConfig>,
public config::IGenerationCallback
{
class Components {
ComponentsDeleter _componentsDeleter;
public:
const std::shared_ptr<ZKFacade> _zk;
const std::shared_ptr<FileDistributionModelImpl> _model;
const std::shared_ptr<FileDistributorTrackerImpl> _tracker;
const std::shared_ptr<FileDownloader> _downloader;
const FileDownloaderManager::SP _manager;
const FileDistributorRPC::SP _rpcHandler;
const std::shared_ptr<StateServerImpl> _stateServer;
private:
class GuardedThread {
public:
GuardedThread(const GuardedThread &) = delete;
GuardedThread & operator = (const GuardedThread &) = delete;
GuardedThread(const std::shared_ptr<FileDownloader> & downloader) :
_downloader(downloader),
_thread([downloader=_downloader] () { downloader->runEventLoop(); })
{ }
~GuardedThread() {
_downloader->close();
if (_thread.joinable()) {
_thread.join();
}
if ( !_downloader->drained() ) {
LOG(error, "The filedownloader did not drain fully. We will just exit quickly and let a restart repair it for us.");
std::quick_exit(67);
}
}
private:
std::shared_ptr<FileDownloader> _downloader;
std::thread _thread;
};
std::unique_ptr<GuardedThread> _downloaderEventLoopThread;
config::ConfigFetcher _configFetcher;
template <class T>
typename std::shared_ptr<T> track(T* component) {
return _componentsDeleter.track(component);
}
public:
Components(const Components &) = delete;
Components & operator = (const Components &) = delete;
Components(const config::ConfigUri & configUri,
const ZookeepersConfig& zooKeepersConfig,
const FiledistributorConfig& fileDistributorConfig,
const FiledistributorrpcConfig& rpcConfig)
:_zk(track(new ZKFacade(zooKeepersConfig.zookeeperserverlist))),
_model(track(new FileDistributionModelImpl(fileDistributorConfig.hostname, fileDistributorConfig.torrentport, _zk))),
_tracker(track(new FileDistributorTrackerImpl(_model))),
_downloader(track(new FileDownloader(_tracker, fileDistributorConfig.hostname, fileDistributorConfig.torrentport,
boost::filesystem::path(fileDistributorConfig.filedbpath)))),
_manager(track(new FileDownloaderManager(_downloader, _model))),
_rpcHandler(track(new FileDistributorRPC(rpcConfig.connectionspec, _manager))),
_stateServer(track(new StateServerImpl(fileDistributorConfig.stateport))),
_downloaderEventLoopThread(),
_configFetcher(configUri.getContext())
{
_downloaderEventLoopThread = std::make_unique<GuardedThread>(_downloader);
_manager->start();
_rpcHandler->start();
_tracker->setDownloader(_downloader);
_configFetcher.subscribe<FilereferencesConfig>(configUri.getConfigId(), _model.get());
_configFetcher.start();
updatedConfig(_configFetcher.getGeneration());
}
void updatedConfig(int64_t generation) {
vespalib::ComponentConfigProducer::Config curr("filedistributor", generation);
_stateServer->myComponents.addConfig(curr);
}
~Components() {
_configFetcher.close();
//Do not waste time retrying zookeeper operations when going down.
_zk->disableRetries();
_downloaderEventLoopThread.reset();
}
};
typedef std::lock_guard<std::mutex> LockGuard;
std::mutex _configMutex;
bool _completeReconfigurationNeeded;
std::unique_ptr<ZookeepersConfig> _zooKeepersConfig;
std::unique_ptr<FiledistributorConfig> _fileDistributorConfig;
std::unique_ptr<FiledistributorrpcConfig> _rpcConfig;
std::unique_ptr<Components> _components;
public:
FileDistributor(const FileDistributor &) = delete;
FileDistributor & operator = (const FileDistributor &) = delete;
FileDistributor()
: _configMutex(),
_completeReconfigurationNeeded(false),
_zooKeepersConfig(),
_fileDistributorConfig(),
_rpcConfig(),
_components()
{ }
void notifyGenerationChange(int64_t generation) {
if (_components && ! completeReconfigurationNeeded()) {
_components->updatedConfig(generation);
}
}
//configure overrides
void configure(std::unique_ptr<ZookeepersConfig> config) {
LockGuard guard(_configMutex);
_zooKeepersConfig = std::move(config);
_completeReconfigurationNeeded = true;
}
void configure(std::unique_ptr<FiledistributorConfig> config) {
LockGuard guard(_configMutex);
if (_fileDistributorConfig.get() != NULL &&
(config->torrentport != _fileDistributorConfig->torrentport ||
config->stateport != _fileDistributorConfig->stateport ||
config->hostname != _fileDistributorConfig->hostname ||
config->filedbpath != _fileDistributorConfig->filedbpath))
{
_completeReconfigurationNeeded = true;
} else if (_components.get()) {
configureSpeedLimits(*config);
}
_fileDistributorConfig = std::move(config);
}
void configure(std::unique_ptr<FiledistributorrpcConfig> config) {
LockGuard guard(_configMutex);
_rpcConfig = std::move(config);
_completeReconfigurationNeeded = true;
}
void run(const config::ConfigUri & configUri) {
while (!askedToShutDown()) {
clearReinitializeFlag();
runImpl(configUri);
}
}
void createComponents(const config::ConfigUri & configUri) {
LockGuard guard(_configMutex);
_components.reset(
new Components(configUri,
*_zooKeepersConfig,
*_fileDistributorConfig,
*_rpcConfig));
configureSpeedLimits(*_fileDistributorConfig);
_completeReconfigurationNeeded = false;
}
bool completeReconfigurationNeeded() {
LockGuard guard(_configMutex);
if (_completeReconfigurationNeeded) {
LOG(debug, "Complete reconfiguration needed");
}
return _completeReconfigurationNeeded;
}
void configureSpeedLimits(const FiledistributorConfig& config) {
FileDownloader& downloader = *_components->_downloader;
downloader.setMaxDownloadSpeed(config.maxdownloadspeed);
downloader.setMaxUploadSpeed(config.maxuploadspeed);
}
void runImpl(const config::ConfigUri & configUri) {
createComponents(configUri);
// We do not want back to back reinitializing as it gives zero time for serving
// some torrents.
int postPoneAskedToReinitializedSecs = 50;
while (!askedToShutDown() &&
(postPoneAskedToReinitializedSecs > 0 || !askedToReinitialize()) &&
!completeReconfigurationNeeded())
{
postPoneAskedToReinitializedSecs--;
std::this_thread::sleep_for(1s);
}
_components.reset();
}
};
class FileDistributorApplication : public FastOS_Application {
const config::ConfigUri _configUri;
public:
FileDistributorApplication(const config::ConfigUri & configUri);
//overrides
int Main();
};
namespace {
struct ProgramOptionException {
std::string _msg;
ProgramOptionException(const std::string & msg)
: _msg(msg)
{}
};
bool exists(const std::string& optionName, const boost::program_options::variables_map& map) {
return map.find(optionName) != map.end();
}
void ensureExists(const std::string& optionName, const boost::program_options::variables_map& map \
) {
if (!exists(optionName, map)) {
throw ProgramOptionException("Error: Missing option " + optionName);
}
}
} //anonymous namespace
FileDistributorApplication::FileDistributorApplication(const config::ConfigUri & configUri)
:_configUri(configUri) {
}
int
FileDistributorApplication::Main() {
try {
FileDistributor distributor;
config::ConfigFetcher configFetcher(_configUri.getContext());
configFetcher.subscribe<ZookeepersConfig>(_configUri.getConfigId(), &distributor);
configFetcher.subscribe<FiledistributorConfig>(_configUri.getConfigId(), &distributor);
configFetcher.subscribe<FiledistributorrpcConfig>(_configUri.getConfigId(), &distributor);
configFetcher.subscribeGenerationChanges(&distributor);
configFetcher.start();
distributor.run(_configUri);
EV_STOPPING(programName, "Clean exit");
return 0;
} catch(const FileDoesNotExistException & e) {
std::string s = boost::diagnostic_information(e);
EV_STOPPING(programName, s.c_str());
return 1;
} catch(const ZKNodeDoesNotExistsException & e) {
std::string s = boost::diagnostic_information(e);
EV_STOPPING(programName, s.c_str());
return 2;
} catch(const ZKSessionExpired & e) {
std::string s = boost::diagnostic_information(e);
EV_STOPPING(programName, s.c_str());
return 3;
} catch(const config::ConfigTimeoutException & e) {
std::string s = boost::diagnostic_information(e);
EV_STOPPING(programName, s.c_str());
return 4;
} catch(const vespalib::PortListenException & e) {
std::string s = boost::diagnostic_information(e);
EV_STOPPING(programName, s.c_str());
return 5;
} catch(const ZKConnectionLossException & e) {
std::string s = boost::diagnostic_information(e);
EV_STOPPING(programName, s.c_str());
return 6;
} catch(const ZKGenericException & e) {
std::string s = boost::diagnostic_information(e);
EV_STOPPING(programName, s.c_str());
return 99;
}
}
int
executeApplication(int argc, char** argv) {
const char
*configId("configid"),
*help("help");
namespace po = boost::program_options;
po::options_description description;
description.add_options()
(configId, po::value<std::string > (), "id to request config for")
(help, "help");
try {
po::variables_map values;
po::store(
po::parse_command_line(argc, argv, description),
values);
if (exists(help, values)) {
std::cout <<description;
return 0;
}
ensureExists(configId, values);
FileDistributorApplication application(
values[configId].as<std::string > ());
return application.Entry(argc, argv);
} catch(ProgramOptionException& e) {
std::cerr <<e._msg <<std::endl;
return -1;
}
}
namespace {
class InitSignals {
public:
InitSignals() { initSignals(); }
};
InitSignals _G_initSignals __attribute__ ((init_priority (101)));
}
int
main(int argc, char** argv) {
if (askedToShutDown()) { return 0; }
EV_STARTED(programName);
std::srand(std::time(0));
filedistribution::ZKLogging loggingGuard;
return executeApplication(argc, argv);
}
<commit_msg>Use existing typedef.<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include <iostream>
#include <string>
#include <cstdlib>
#include <boost/program_options.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <vespa/fastos/app.h>
#include <vespa/config-zookeepers.h>
#include <vespa/fileacquirer/config-filedistributorrpc.h>
#include <vespa/filedistribution/distributor/config-filedistributor.h>
#include <vespa/filedistribution/model/config-filereferences.h>
#include <vespa/filedistribution/distributor/filedistributortrackerimpl.h>
#include <vespa/filedistribution/distributor/filedownloadermanager.h>
#include <vespa/filedistribution/distributor/filedownloader.h>
#include <vespa/filedistribution/distributor/signalhandling.h>
#include <vespa/filedistribution/distributor/state_server_impl.h>
#include <vespa/filedistribution/model/filedistributionmodelimpl.h>
#include <vespa/filedistribution/rpc/filedistributorrpc.h>
#include <vespa/filedistribution/common/exception.h>
#include <vespa/filedistribution/common/componentsdeleter.h>
namespace {
const char* programName = "filedistributor";
}
#include <vespa/log/log.h>
LOG_SETUP(programName);
using namespace std::literals;
using namespace filedistribution;
using cloud::config::ZookeepersConfig;
using cloud::config::filedistribution::FiledistributorConfig;
using cloud::config::filedistribution::FiledistributorrpcConfig;
class FileDistributor : public config::IFetcherCallback<ZookeepersConfig>,
public config::IFetcherCallback<FiledistributorConfig>,
public config::IFetcherCallback<FiledistributorrpcConfig>,
public config::IGenerationCallback
{
class Components {
ComponentsDeleter _componentsDeleter;
public:
const std::shared_ptr<ZKFacade> _zk;
const std::shared_ptr<FileDistributionModelImpl> _model;
const std::shared_ptr<FileDistributorTrackerImpl> _tracker;
const std::shared_ptr<FileDownloader> _downloader;
const FileDownloaderManager::SP _manager;
const FileDistributorRPC::SP _rpcHandler;
const std::shared_ptr<StateServerImpl> _stateServer;
private:
class GuardedThread {
public:
GuardedThread(const GuardedThread &) = delete;
GuardedThread & operator = (const GuardedThread &) = delete;
GuardedThread(const std::shared_ptr<FileDownloader> & downloader) :
_downloader(downloader),
_thread([downloader=_downloader] () { downloader->runEventLoop(); })
{ }
~GuardedThread() {
_downloader->close();
if (_thread.joinable()) {
_thread.join();
}
if ( !_downloader->drained() ) {
LOG(error, "The filedownloader did not drain fully. We will just exit quickly and let a restart repair it for us.");
std::quick_exit(67);
}
}
private:
std::shared_ptr<FileDownloader> _downloader;
std::thread _thread;
};
std::unique_ptr<GuardedThread> _downloaderEventLoopThread;
config::ConfigFetcher _configFetcher;
template <class T>
typename std::shared_ptr<T> track(T* component) {
return _componentsDeleter.track(component);
}
public:
Components(const Components &) = delete;
Components & operator = (const Components &) = delete;
Components(const config::ConfigUri & configUri,
const ZookeepersConfig& zooKeepersConfig,
const FiledistributorConfig& fileDistributorConfig,
const FiledistributorrpcConfig& rpcConfig)
:_zk(track(new ZKFacade(zooKeepersConfig.zookeeperserverlist))),
_model(track(new FileDistributionModelImpl(fileDistributorConfig.hostname, fileDistributorConfig.torrentport, _zk))),
_tracker(track(new FileDistributorTrackerImpl(_model))),
_downloader(track(new FileDownloader(_tracker, fileDistributorConfig.hostname, fileDistributorConfig.torrentport, Path(fileDistributorConfig.filedbpath)))),
_manager(track(new FileDownloaderManager(_downloader, _model))),
_rpcHandler(track(new FileDistributorRPC(rpcConfig.connectionspec, _manager))),
_stateServer(track(new StateServerImpl(fileDistributorConfig.stateport))),
_downloaderEventLoopThread(),
_configFetcher(configUri.getContext())
{
_downloaderEventLoopThread = std::make_unique<GuardedThread>(_downloader);
_manager->start();
_rpcHandler->start();
_tracker->setDownloader(_downloader);
_configFetcher.subscribe<FilereferencesConfig>(configUri.getConfigId(), _model.get());
_configFetcher.start();
updatedConfig(_configFetcher.getGeneration());
}
void updatedConfig(int64_t generation) {
vespalib::ComponentConfigProducer::Config curr("filedistributor", generation);
_stateServer->myComponents.addConfig(curr);
}
~Components() {
_configFetcher.close();
//Do not waste time retrying zookeeper operations when going down.
_zk->disableRetries();
_downloaderEventLoopThread.reset();
}
};
typedef std::lock_guard<std::mutex> LockGuard;
std::mutex _configMutex;
bool _completeReconfigurationNeeded;
std::unique_ptr<ZookeepersConfig> _zooKeepersConfig;
std::unique_ptr<FiledistributorConfig> _fileDistributorConfig;
std::unique_ptr<FiledistributorrpcConfig> _rpcConfig;
std::unique_ptr<Components> _components;
public:
FileDistributor(const FileDistributor &) = delete;
FileDistributor & operator = (const FileDistributor &) = delete;
FileDistributor()
: _configMutex(),
_completeReconfigurationNeeded(false),
_zooKeepersConfig(),
_fileDistributorConfig(),
_rpcConfig(),
_components()
{ }
void notifyGenerationChange(int64_t generation) {
if (_components && ! completeReconfigurationNeeded()) {
_components->updatedConfig(generation);
}
}
//configure overrides
void configure(std::unique_ptr<ZookeepersConfig> config) {
LockGuard guard(_configMutex);
_zooKeepersConfig = std::move(config);
_completeReconfigurationNeeded = true;
}
void configure(std::unique_ptr<FiledistributorConfig> config) {
LockGuard guard(_configMutex);
if (_fileDistributorConfig.get() != NULL &&
(config->torrentport != _fileDistributorConfig->torrentport ||
config->stateport != _fileDistributorConfig->stateport ||
config->hostname != _fileDistributorConfig->hostname ||
config->filedbpath != _fileDistributorConfig->filedbpath))
{
_completeReconfigurationNeeded = true;
} else if (_components.get()) {
configureSpeedLimits(*config);
}
_fileDistributorConfig = std::move(config);
}
void configure(std::unique_ptr<FiledistributorrpcConfig> config) {
LockGuard guard(_configMutex);
_rpcConfig = std::move(config);
_completeReconfigurationNeeded = true;
}
void run(const config::ConfigUri & configUri) {
while (!askedToShutDown()) {
clearReinitializeFlag();
runImpl(configUri);
}
}
void createComponents(const config::ConfigUri & configUri) {
LockGuard guard(_configMutex);
_components.reset(
new Components(configUri,
*_zooKeepersConfig,
*_fileDistributorConfig,
*_rpcConfig));
configureSpeedLimits(*_fileDistributorConfig);
_completeReconfigurationNeeded = false;
}
bool completeReconfigurationNeeded() {
LockGuard guard(_configMutex);
if (_completeReconfigurationNeeded) {
LOG(debug, "Complete reconfiguration needed");
}
return _completeReconfigurationNeeded;
}
void configureSpeedLimits(const FiledistributorConfig& config) {
FileDownloader& downloader = *_components->_downloader;
downloader.setMaxDownloadSpeed(config.maxdownloadspeed);
downloader.setMaxUploadSpeed(config.maxuploadspeed);
}
void runImpl(const config::ConfigUri & configUri) {
createComponents(configUri);
// We do not want back to back reinitializing as it gives zero time for serving
// some torrents.
int postPoneAskedToReinitializedSecs = 50;
while (!askedToShutDown() &&
(postPoneAskedToReinitializedSecs > 0 || !askedToReinitialize()) &&
!completeReconfigurationNeeded())
{
postPoneAskedToReinitializedSecs--;
std::this_thread::sleep_for(1s);
}
_components.reset();
}
};
class FileDistributorApplication : public FastOS_Application {
const config::ConfigUri _configUri;
public:
FileDistributorApplication(const config::ConfigUri & configUri);
//overrides
int Main();
};
namespace {
struct ProgramOptionException {
std::string _msg;
ProgramOptionException(const std::string & msg)
: _msg(msg)
{}
};
bool exists(const std::string& optionName, const boost::program_options::variables_map& map) {
return map.find(optionName) != map.end();
}
void ensureExists(const std::string& optionName, const boost::program_options::variables_map& map \
) {
if (!exists(optionName, map)) {
throw ProgramOptionException("Error: Missing option " + optionName);
}
}
} //anonymous namespace
FileDistributorApplication::FileDistributorApplication(const config::ConfigUri & configUri)
:_configUri(configUri) {
}
int
FileDistributorApplication::Main() {
try {
FileDistributor distributor;
config::ConfigFetcher configFetcher(_configUri.getContext());
configFetcher.subscribe<ZookeepersConfig>(_configUri.getConfigId(), &distributor);
configFetcher.subscribe<FiledistributorConfig>(_configUri.getConfigId(), &distributor);
configFetcher.subscribe<FiledistributorrpcConfig>(_configUri.getConfigId(), &distributor);
configFetcher.subscribeGenerationChanges(&distributor);
configFetcher.start();
distributor.run(_configUri);
EV_STOPPING(programName, "Clean exit");
return 0;
} catch(const FileDoesNotExistException & e) {
std::string s = boost::diagnostic_information(e);
EV_STOPPING(programName, s.c_str());
return 1;
} catch(const ZKNodeDoesNotExistsException & e) {
std::string s = boost::diagnostic_information(e);
EV_STOPPING(programName, s.c_str());
return 2;
} catch(const ZKSessionExpired & e) {
std::string s = boost::diagnostic_information(e);
EV_STOPPING(programName, s.c_str());
return 3;
} catch(const config::ConfigTimeoutException & e) {
std::string s = boost::diagnostic_information(e);
EV_STOPPING(programName, s.c_str());
return 4;
} catch(const vespalib::PortListenException & e) {
std::string s = boost::diagnostic_information(e);
EV_STOPPING(programName, s.c_str());
return 5;
} catch(const ZKConnectionLossException & e) {
std::string s = boost::diagnostic_information(e);
EV_STOPPING(programName, s.c_str());
return 6;
} catch(const ZKGenericException & e) {
std::string s = boost::diagnostic_information(e);
EV_STOPPING(programName, s.c_str());
return 99;
}
}
int
executeApplication(int argc, char** argv) {
const char
*configId("configid"),
*help("help");
namespace po = boost::program_options;
po::options_description description;
description.add_options()
(configId, po::value<std::string > (), "id to request config for")
(help, "help");
try {
po::variables_map values;
po::store(
po::parse_command_line(argc, argv, description),
values);
if (exists(help, values)) {
std::cout <<description;
return 0;
}
ensureExists(configId, values);
FileDistributorApplication application(
values[configId].as<std::string > ());
return application.Entry(argc, argv);
} catch(ProgramOptionException& e) {
std::cerr <<e._msg <<std::endl;
return -1;
}
}
namespace {
class InitSignals {
public:
InitSignals() { initSignals(); }
};
InitSignals _G_initSignals __attribute__ ((init_priority (101)));
}
int
main(int argc, char** argv) {
if (askedToShutDown()) { return 0; }
EV_STARTED(programName);
std::srand(std::time(0));
filedistribution::ZKLogging loggingGuard;
return executeApplication(argc, argv);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: multisigdemo.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: vg $ $Date: 2006-04-07 11:58:21 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <stdio.h>
#include "util.hxx"
#include <rtl/ustring.hxx>
#include <cppuhelper/servicefactory.hxx>
#include <xmlsecurity/biginteger.hxx>
#include <xmlsecurity/xmlsignaturehelper.hxx>
#include "xmlsecurity/baseencoding.hxx"
#include <tools/date.hxx>
#include <tools/time.hxx>
using namespace ::com::sun::star;
long denyVerifyHandler( void *, void * )
{
return 0;
}
long startVerifyHandler( void *, void * )
{
return QueryVerifySignature();
}
int SAL_CALL main( int argc, char **argv )
{
if( argc < 5 )
{
fprintf( stderr, "Usage: %s <signature file 1> <signature file 2> <xml stream file> <binary stream file> [<cryptoken>]\n" , argv[0] ) ;
return -1 ;
}
uno::Reference< lang::XMultiServiceFactory > xMSF = CreateDemoServiceFactory();
rtl::OUString aSIGFileName = rtl::OUString::createFromAscii(argv[1]);
rtl::OUString aSIGFileName2 = rtl::OUString::createFromAscii(argv[2]);
rtl::OUString aXMLFileName = rtl::OUString::createFromAscii(argv[3]);
rtl::OUString aBINFileName = rtl::OUString::createFromAscii(argv[4]);
rtl::OUString aCryptoToken;
if ( argc >= 7 )
aCryptoToken = rtl::OUString::createFromAscii(argv[6]);
sal_Int32 nSecurityId;
uno::Reference< io::XOutputStream > xOutputStream;
uno::Reference< io::XInputStream > xInputStream;
bool bDone;
SignatureInformations signatureInformations;
uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler> xDocumentHandler;
// -------- START -------
XMLSignatureHelper aSignatureHelper( xMSF );
bool bInit = aSignatureHelper.Init( aCryptoToken );
if ( !bInit )
{
fprintf( stderr, "Error initializing security context!\n" );
return -1;
}
fprintf( stdout, "\n\nTEST MISSION 1: Create the first signature file\n");
aSignatureHelper.StartMission();
/*
* select a private key certificate
*/
uno::Reference< xml::crypto::XSecurityEnvironment > xSecurityEnvironment = aSignatureHelper.GetSecurityEnvironment();
uno::Sequence< uno::Reference< ::com::sun::star::security::XCertificate > > xPersonalCerts = xSecurityEnvironment->getPersonalCertificates() ;
fprintf( stdout, "\nPlease select two certificates:\n" );
for ( int nSig = 0; nSig < 2; nSig++ )
{
// New security ID for signature...
nSecurityId = aSignatureHelper.GetNewSecurityId();
// Select certificate...
uno::Reference< ::com::sun::star::security::XCertificate > xPersonalCert = getCertificateFromEnvironment( xSecurityEnvironment, true );
aSignatureHelper.SetX509Certificate(
nSecurityId, xPersonalCert->getIssuerName(),
bigIntegerToNumericString( xPersonalCert->getSerialNumber()),
baseEncode(xPersonalCert->getEncoded(), BASE64));
aSignatureHelper.AddForSigning( nSecurityId, aXMLFileName, aXMLFileName, sal_False );
aSignatureHelper.AddForSigning( nSecurityId, aBINFileName, aBINFileName, sal_True );
aSignatureHelper.SetDateTime( nSecurityId, Date(), Time() );
}
/*
* creates signature
*/
xOutputStream = OpenOutputStream( aSIGFileName );
bDone = aSignatureHelper.CreateAndWriteSignature( xOutputStream );
if ( !bDone )
fprintf( stderr, "\nSTATUS MISSION 1: Error creating Signature!\n" );
else
fprintf( stdout, "\nSTATUS MISSION 1: Signature successfully created!\n" );
aSignatureHelper.EndMission();
fprintf( stdout, "\n\nTEST MISSION 2: Transfer the second signature to a new signature file\n");
/*
* You can use an uninitialized SignatureHelper to perform this mission.
*/
/*
* configures the start-verify handler. Don't need to verify for transfering...
*/
aSignatureHelper.SetStartVerifySignatureHdl( Link( NULL, denyVerifyHandler ) );
aSignatureHelper.StartMission();
xInputStream = OpenInputStream( aSIGFileName );
bDone = aSignatureHelper.ReadAndVerifySignature( xInputStream );
xInputStream->closeInput();
if ( !bDone )
fprintf( stderr, "\nSTATUS MISSION 2: Error in reading Signature!\n" );
else
fprintf( stdout, "\nSTATUS MISSION 2: Signature successfully transfered!\n" );
/*
* get all signature information
*/
signatureInformations = aSignatureHelper.GetSignatureInformations();
/*
* write the first signature into the second signature file.
*/
xOutputStream = OpenOutputStream( aSIGFileName2 );
xDocumentHandler = aSignatureHelper.CreateDocumentHandlerWithHeader( xOutputStream);
aSignatureHelper.ExportSignature( xDocumentHandler, signatureInformations[1]);
aSignatureHelper.CloseDocumentHandler( xDocumentHandler);
aSignatureHelper.EndMission();
fprintf( stdout, "\n\nTEST MISSION 3: Insert a new signature to the first signature file\n");
aSignatureHelper.StartMission();
nSecurityId = aSignatureHelper.GetNewSecurityId();
// Select certificate...
uno::Reference< ::com::sun::star::security::XCertificate > xPersonalCert = getCertificateFromEnvironment( xSecurityEnvironment, true );
aSignatureHelper.SetX509Certificate(
nSecurityId, xPersonalCert->getIssuerName(),
bigIntegerToNumericString( xPersonalCert->getSerialNumber()),
baseEncode(xPersonalCert->getEncoded(), BASE64));
aSignatureHelper.AddForSigning( nSecurityId, aXMLFileName, aXMLFileName, sal_False );
aSignatureHelper.AddForSigning( nSecurityId, aBINFileName, aBINFileName, sal_True );
aSignatureHelper.SetDateTime( nSecurityId, Date(), Time() );
xOutputStream = OpenOutputStream( aSIGFileName );
xDocumentHandler = aSignatureHelper.CreateDocumentHandlerWithHeader( xOutputStream);
aSignatureHelper.ExportSignature( xDocumentHandler, signatureInformations[0]);
bDone = aSignatureHelper.CreateAndWriteSignature( xDocumentHandler );
aSignatureHelper.ExportSignature( xDocumentHandler, signatureInformations[1]);
aSignatureHelper.CloseDocumentHandler( xDocumentHandler);
if ( !bDone )
fprintf( stderr, "\nSTATUS MISSION 3: Error creating Signature!\n" );
else
fprintf( stdout, "\nSTATUS MISSION 3: Signature successfully created!\n" );
aSignatureHelper.EndMission();
fprintf( stdout, "\n\nTEST MISSION 4 : Verify the first signature file\n");
aSignatureHelper.SetStartVerifySignatureHdl( Link( NULL, startVerifyHandler ) );
aSignatureHelper.StartMission();
xInputStream = OpenInputStream( aSIGFileName );
bDone = aSignatureHelper.ReadAndVerifySignature( xInputStream );
xInputStream->closeInput();
if ( !bDone )
fprintf( stderr, "\nSTATUS MISSION 4: Error verifying Signatures!\n" );
else
fprintf( stdout, "\nSTATUS MISSION 4: All choosen Signatures veryfied successfully!\n" );
aSignatureHelper.EndMission();
QueryPrintSignatureDetails( aSignatureHelper.GetSignatureInformations(), aSignatureHelper.GetSecurityEnvironment() );
fprintf( stdout, "\n\nTEST MISSION 5: Verify the second signature file\n");
aSignatureHelper.StartMission();
xInputStream = OpenInputStream( aSIGFileName2 );
bDone = aSignatureHelper.ReadAndVerifySignature( xInputStream );
xInputStream->closeInput();
if ( !bDone )
fprintf( stderr, "\nSTATUS MISSION 5: Error verifying Signatures!\n" );
else
fprintf( stdout, "\nSTATUS MISSION 5: All choosen Signatures veryfied successfully!\n" );
aSignatureHelper.EndMission();
QueryPrintSignatureDetails( aSignatureHelper.GetSignatureInformations(), aSignatureHelper.GetSecurityEnvironment() );
return 0;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.7.38); FILE MERGED 2006/09/01 18:00:57 kaib 1.7.38.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: multisigdemo.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-09-16 14:47:33 $
*
* 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_xmlsecurity.hxx"
#include <stdio.h>
#include "util.hxx"
#include <rtl/ustring.hxx>
#include <cppuhelper/servicefactory.hxx>
#include <xmlsecurity/biginteger.hxx>
#include <xmlsecurity/xmlsignaturehelper.hxx>
#include "xmlsecurity/baseencoding.hxx"
#include <tools/date.hxx>
#include <tools/time.hxx>
using namespace ::com::sun::star;
long denyVerifyHandler( void *, void * )
{
return 0;
}
long startVerifyHandler( void *, void * )
{
return QueryVerifySignature();
}
int SAL_CALL main( int argc, char **argv )
{
if( argc < 5 )
{
fprintf( stderr, "Usage: %s <signature file 1> <signature file 2> <xml stream file> <binary stream file> [<cryptoken>]\n" , argv[0] ) ;
return -1 ;
}
uno::Reference< lang::XMultiServiceFactory > xMSF = CreateDemoServiceFactory();
rtl::OUString aSIGFileName = rtl::OUString::createFromAscii(argv[1]);
rtl::OUString aSIGFileName2 = rtl::OUString::createFromAscii(argv[2]);
rtl::OUString aXMLFileName = rtl::OUString::createFromAscii(argv[3]);
rtl::OUString aBINFileName = rtl::OUString::createFromAscii(argv[4]);
rtl::OUString aCryptoToken;
if ( argc >= 7 )
aCryptoToken = rtl::OUString::createFromAscii(argv[6]);
sal_Int32 nSecurityId;
uno::Reference< io::XOutputStream > xOutputStream;
uno::Reference< io::XInputStream > xInputStream;
bool bDone;
SignatureInformations signatureInformations;
uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler> xDocumentHandler;
// -------- START -------
XMLSignatureHelper aSignatureHelper( xMSF );
bool bInit = aSignatureHelper.Init( aCryptoToken );
if ( !bInit )
{
fprintf( stderr, "Error initializing security context!\n" );
return -1;
}
fprintf( stdout, "\n\nTEST MISSION 1: Create the first signature file\n");
aSignatureHelper.StartMission();
/*
* select a private key certificate
*/
uno::Reference< xml::crypto::XSecurityEnvironment > xSecurityEnvironment = aSignatureHelper.GetSecurityEnvironment();
uno::Sequence< uno::Reference< ::com::sun::star::security::XCertificate > > xPersonalCerts = xSecurityEnvironment->getPersonalCertificates() ;
fprintf( stdout, "\nPlease select two certificates:\n" );
for ( int nSig = 0; nSig < 2; nSig++ )
{
// New security ID for signature...
nSecurityId = aSignatureHelper.GetNewSecurityId();
// Select certificate...
uno::Reference< ::com::sun::star::security::XCertificate > xPersonalCert = getCertificateFromEnvironment( xSecurityEnvironment, true );
aSignatureHelper.SetX509Certificate(
nSecurityId, xPersonalCert->getIssuerName(),
bigIntegerToNumericString( xPersonalCert->getSerialNumber()),
baseEncode(xPersonalCert->getEncoded(), BASE64));
aSignatureHelper.AddForSigning( nSecurityId, aXMLFileName, aXMLFileName, sal_False );
aSignatureHelper.AddForSigning( nSecurityId, aBINFileName, aBINFileName, sal_True );
aSignatureHelper.SetDateTime( nSecurityId, Date(), Time() );
}
/*
* creates signature
*/
xOutputStream = OpenOutputStream( aSIGFileName );
bDone = aSignatureHelper.CreateAndWriteSignature( xOutputStream );
if ( !bDone )
fprintf( stderr, "\nSTATUS MISSION 1: Error creating Signature!\n" );
else
fprintf( stdout, "\nSTATUS MISSION 1: Signature successfully created!\n" );
aSignatureHelper.EndMission();
fprintf( stdout, "\n\nTEST MISSION 2: Transfer the second signature to a new signature file\n");
/*
* You can use an uninitialized SignatureHelper to perform this mission.
*/
/*
* configures the start-verify handler. Don't need to verify for transfering...
*/
aSignatureHelper.SetStartVerifySignatureHdl( Link( NULL, denyVerifyHandler ) );
aSignatureHelper.StartMission();
xInputStream = OpenInputStream( aSIGFileName );
bDone = aSignatureHelper.ReadAndVerifySignature( xInputStream );
xInputStream->closeInput();
if ( !bDone )
fprintf( stderr, "\nSTATUS MISSION 2: Error in reading Signature!\n" );
else
fprintf( stdout, "\nSTATUS MISSION 2: Signature successfully transfered!\n" );
/*
* get all signature information
*/
signatureInformations = aSignatureHelper.GetSignatureInformations();
/*
* write the first signature into the second signature file.
*/
xOutputStream = OpenOutputStream( aSIGFileName2 );
xDocumentHandler = aSignatureHelper.CreateDocumentHandlerWithHeader( xOutputStream);
aSignatureHelper.ExportSignature( xDocumentHandler, signatureInformations[1]);
aSignatureHelper.CloseDocumentHandler( xDocumentHandler);
aSignatureHelper.EndMission();
fprintf( stdout, "\n\nTEST MISSION 3: Insert a new signature to the first signature file\n");
aSignatureHelper.StartMission();
nSecurityId = aSignatureHelper.GetNewSecurityId();
// Select certificate...
uno::Reference< ::com::sun::star::security::XCertificate > xPersonalCert = getCertificateFromEnvironment( xSecurityEnvironment, true );
aSignatureHelper.SetX509Certificate(
nSecurityId, xPersonalCert->getIssuerName(),
bigIntegerToNumericString( xPersonalCert->getSerialNumber()),
baseEncode(xPersonalCert->getEncoded(), BASE64));
aSignatureHelper.AddForSigning( nSecurityId, aXMLFileName, aXMLFileName, sal_False );
aSignatureHelper.AddForSigning( nSecurityId, aBINFileName, aBINFileName, sal_True );
aSignatureHelper.SetDateTime( nSecurityId, Date(), Time() );
xOutputStream = OpenOutputStream( aSIGFileName );
xDocumentHandler = aSignatureHelper.CreateDocumentHandlerWithHeader( xOutputStream);
aSignatureHelper.ExportSignature( xDocumentHandler, signatureInformations[0]);
bDone = aSignatureHelper.CreateAndWriteSignature( xDocumentHandler );
aSignatureHelper.ExportSignature( xDocumentHandler, signatureInformations[1]);
aSignatureHelper.CloseDocumentHandler( xDocumentHandler);
if ( !bDone )
fprintf( stderr, "\nSTATUS MISSION 3: Error creating Signature!\n" );
else
fprintf( stdout, "\nSTATUS MISSION 3: Signature successfully created!\n" );
aSignatureHelper.EndMission();
fprintf( stdout, "\n\nTEST MISSION 4 : Verify the first signature file\n");
aSignatureHelper.SetStartVerifySignatureHdl( Link( NULL, startVerifyHandler ) );
aSignatureHelper.StartMission();
xInputStream = OpenInputStream( aSIGFileName );
bDone = aSignatureHelper.ReadAndVerifySignature( xInputStream );
xInputStream->closeInput();
if ( !bDone )
fprintf( stderr, "\nSTATUS MISSION 4: Error verifying Signatures!\n" );
else
fprintf( stdout, "\nSTATUS MISSION 4: All choosen Signatures veryfied successfully!\n" );
aSignatureHelper.EndMission();
QueryPrintSignatureDetails( aSignatureHelper.GetSignatureInformations(), aSignatureHelper.GetSecurityEnvironment() );
fprintf( stdout, "\n\nTEST MISSION 5: Verify the second signature file\n");
aSignatureHelper.StartMission();
xInputStream = OpenInputStream( aSIGFileName2 );
bDone = aSignatureHelper.ReadAndVerifySignature( xInputStream );
xInputStream->closeInput();
if ( !bDone )
fprintf( stderr, "\nSTATUS MISSION 5: Error verifying Signatures!\n" );
else
fprintf( stdout, "\nSTATUS MISSION 5: All choosen Signatures veryfied successfully!\n" );
aSignatureHelper.EndMission();
QueryPrintSignatureDetails( aSignatureHelper.GetSignatureInformations(), aSignatureHelper.GetSecurityEnvironment() );
return 0;
}
<|endoftext|> |
<commit_before>//
// CRTC6845.hpp
// Clock Signal
//
// Created by Thomas Harte on 31/07/2017.
// Copyright © 2017 Thomas Harte. All rights reserved.
//
#ifndef CRTC6845_hpp
#define CRTC6845_hpp
#include "../../ClockReceiver/ClockReceiver.hpp"
#include <cstdint>
#include <cstdio>
namespace Motorola {
namespace CRTC {
struct BusState {
bool display_enable;
bool hsync;
bool vsync;
bool cursor;
uint16_t refresh_address;
uint16_t row_address;
};
class BusHandler {
public:
/*!
Performs the first phase of a 6845 bus cycle; this is the phase in which it is intended that
systems using the 6845 respect the bus state and produce pixels, sync or whatever they require.
*/
void perform_bus_cycle_phase1(const BusState &) {}
/*!
Performs the second phase of a 6845 bus cycle. Some bus state — including sync — is updated
directly after phase 1 and hence is visible to an observer during phase 2. Handlers may therefore
implement @c perform_bus_cycle_phase2 to be notified of the availability of that state without
having to wait until the next cycle has begun.
*/
void perform_bus_cycle_phase2(const BusState &) {}
};
enum Personality {
HD6845S, //
UM6845R, //
MC6845, //
AMS40226 //
};
template <class T> class CRTC6845 {
public:
CRTC6845(Personality p, T &bus_handler) noexcept :
personality_(p), bus_handler_(bus_handler) {}
void select_register(uint8_t r) {
selected_register_ = r;
}
uint8_t get_status() const {
return 0xff;
}
uint8_t get_register() const {
if(selected_register_ < 12 || selected_register_ > 17) return 0xff;
return registers_[selected_register_];
}
void set_register(uint8_t value) {
static uint8_t masks[] = {
0xff, 0xff, 0xff, 0xff, 0x7f, 0x1f, 0x7f, 0x7f,
0xff, 0x1f, 0x7f, 0x1f, 0x3f, 0xff, 0x3f, 0xff
};
if(selected_register_ < 16) {
registers_[selected_register_] = value & masks[selected_register_];
}
}
void trigger_light_pen() {
registers_[17] = bus_state_.refresh_address & 0xff;
registers_[16] = bus_state_.refresh_address >> 8;
}
void run_for(Cycles cycles) {
int cyles_remaining = cycles.as_int();
while(cyles_remaining--) {
// check for end of visible characters
if(character_counter_ == registers_[1]) {
// TODO: consider skew in character_is_visible_. Or maybe defer until perform_bus_cycle?
character_is_visible_ = false;
end_of_line_address_ = bus_state_.refresh_address;
}
perform_bus_cycle_phase1();
bus_state_.refresh_address = (bus_state_.refresh_address + 1) & 0x3fff;
// check for end-of-line
if(character_counter_ == registers_[0]) {
character_counter_ = 0;
do_end_of_line();
character_is_visible_ = true;
} else {
// increment counter
character_counter_++;
}
// check for start of horizontal sync
if(character_counter_ == registers_[2]) {
hsync_counter_ = 0;
bus_state_.hsync = true;
}
// check for end of horizontal sync; note that a sync time of zero will result in an immediate
// cancellation of the plan to perform sync
if(bus_state_.hsync) {
bus_state_.hsync = hsync_counter_ != (registers_[3] & 15);
hsync_counter_ = (hsync_counter_ + 1) & 15;
}
perform_bus_cycle_phase2();
}
}
const BusState &get_bus_state() const {
return bus_state_;
}
private:
inline void perform_bus_cycle_phase1() {
bus_state_.display_enable = character_is_visible_ && line_is_visible_;
bus_handler_.perform_bus_cycle_phase1(bus_state_);
}
inline void perform_bus_cycle_phase2() {
bus_state_.display_enable = character_is_visible_ && line_is_visible_;
bus_handler_.perform_bus_cycle_phase2(bus_state_);
}
inline void do_end_of_line() {
// check for end of vertical sync
if(bus_state_.vsync) {
vsync_counter_ = (vsync_counter_ + 1) & 15;
if(vsync_counter_ == (registers_[3] >> 4)) {
bus_state_.vsync = false;
}
}
if(is_in_adjustment_period_) {
line_counter_++;
if(line_counter_ == registers_[5]) {
is_in_adjustment_period_ = false;
do_end_of_frame();
}
} else {
// advance vertical counter
if(bus_state_.row_address == registers_[9]) {
bus_state_.row_address = 0;
line_address_ = end_of_line_address_;
// check for entry into the overflow area
if(line_counter_ == registers_[4]) {
if(registers_[5]) {
line_counter_ = 0;
is_in_adjustment_period_ = true;
} else {
do_end_of_frame();
}
} else {
line_counter_ = (line_counter_ + 1) & 0x7f;
// check for start of vertical sync
if(line_counter_ == registers_[7]) {
bus_state_.vsync = true;
vsync_counter_ = 0;
}
// check for end of visible lines
if(line_counter_ == registers_[6]) {
line_is_visible_ = false;
}
}
} else {
bus_state_.row_address = (bus_state_.row_address + 1) & 0x1f;
}
}
bus_state_.refresh_address = line_address_;
character_counter_ = 0;
character_is_visible_ = (registers_[1] != 0);
}
inline void do_end_of_frame() {
line_counter_ = 0;
line_is_visible_ = true;
line_address_ = (uint16_t)((registers_[12] << 8) | registers_[13]);
bus_state_.refresh_address = line_address_;
}
Personality personality_;
T &bus_handler_;
BusState bus_state_;
uint8_t registers_[18];
int selected_register_;
uint8_t character_counter_;
uint8_t line_counter_;
bool character_is_visible_, line_is_visible_;
int hsync_counter_;
int vsync_counter_;
bool is_in_adjustment_period_;
uint16_t line_address_;
uint16_t end_of_line_address_;
};
}
}
#endif /* CRTC6845_hpp */
<commit_msg>Started making some formal admissions that different CRTC models exist. Plenty yet to do.<commit_after>//
// CRTC6845.hpp
// Clock Signal
//
// Created by Thomas Harte on 31/07/2017.
// Copyright © 2017 Thomas Harte. All rights reserved.
//
#ifndef CRTC6845_hpp
#define CRTC6845_hpp
#include "../../ClockReceiver/ClockReceiver.hpp"
#include <cstdint>
#include <cstdio>
namespace Motorola {
namespace CRTC {
struct BusState {
bool display_enable;
bool hsync;
bool vsync;
bool cursor;
uint16_t refresh_address;
uint16_t row_address;
};
class BusHandler {
public:
/*!
Performs the first phase of a 6845 bus cycle; this is the phase in which it is intended that
systems using the 6845 respect the bus state and produce pixels, sync or whatever they require.
*/
void perform_bus_cycle_phase1(const BusState &) {}
/*!
Performs the second phase of a 6845 bus cycle. Some bus state — including sync — is updated
directly after phase 1 and hence is visible to an observer during phase 2. Handlers may therefore
implement @c perform_bus_cycle_phase2 to be notified of the availability of that state without
having to wait until the next cycle has begun.
*/
void perform_bus_cycle_phase2(const BusState &) {}
};
enum Personality {
HD6845S, // Type 0 in CPC parlance. Zero-width HSYNC available, no status, programmable VSYNC length.
UM6845R, // Type 1 in CPC parlance. Status register, fixed-length VSYNC.
MC6845, // Type 2. No status register, fixed-length VSYNC, no zero-length HSYNC.
AMS40226 // Type 3. Status is get register, fixed-length VSYNC, no zero-length HSYNC.
};
// TODO UM6845R and R12/R13; see http://www.cpcwiki.eu/index.php/CRTC#CRTC_Differences
template <class T> class CRTC6845 {
public:
CRTC6845(Personality p, T &bus_handler) noexcept :
personality_(p), bus_handler_(bus_handler), status_(0) {}
void select_register(uint8_t r) {
selected_register_ = r;
}
uint8_t get_status() const {
switch(personality_) {
case UM6845R: return status_ | (bus_state_.vsync ? 0x20 : 0x00);
case AMS40226: return get_register();
default: return 0xff;
}
return 0xff;
}
uint8_t get_register() const {
if(selected_register_ == 31) status_ &= ~0x80;
if(selected_register_ == 16 || selected_register_ == 17) status_ &= ~0x40;
if(personality_ == UM6845R && selected_register_ == 31) return dummy_register_;
if(selected_register_ < 12 || selected_register_ > 17) return 0xff;
return registers_[selected_register_];
}
void set_register(uint8_t value) {
static uint8_t masks[] = {
0xff, 0xff, 0xff, 0xff, 0x7f, 0x1f, 0x7f, 0x7f,
0xff, 0x1f, 0x7f, 0x1f, 0x3f, 0xff, 0x3f, 0xff
};
if(selected_register_ < 16) {
registers_[selected_register_] = value & masks[selected_register_];
}
if(selected_register_ == 31 && personality_ == UM6845R) {
dummy_register_ = value;
}
}
void trigger_light_pen() {
registers_[17] = bus_state_.refresh_address & 0xff;
registers_[16] = bus_state_.refresh_address >> 8;
status_ |= 0x40;
}
void run_for(Cycles cycles) {
int cyles_remaining = cycles.as_int();
while(cyles_remaining--) {
// check for end of visible characters
if(character_counter_ == registers_[1]) {
// TODO: consider skew in character_is_visible_. Or maybe defer until perform_bus_cycle?
character_is_visible_ = false;
end_of_line_address_ = bus_state_.refresh_address;
}
perform_bus_cycle_phase1();
bus_state_.refresh_address = (bus_state_.refresh_address + 1) & 0x3fff;
// check for end-of-line
if(character_counter_ == registers_[0]) {
character_counter_ = 0;
do_end_of_line();
character_is_visible_ = true;
} else {
// increment counter
character_counter_++;
}
// check for start of horizontal sync
if(character_counter_ == registers_[2]) {
hsync_counter_ = 0;
bus_state_.hsync = true;
}
// check for end of horizontal sync; note that a sync time of zero will result in an immediate
// cancellation of the plan to perform sync
if(bus_state_.hsync) {
switch(personality_) {
case HD6845S:
case UM6845R:
bus_state_.hsync = hsync_counter_ != (registers_[3] & 15);
hsync_counter_ = (hsync_counter_ + 1) & 15;
break;
default:
hsync_counter_ = (hsync_counter_ + 1) & 15;
bus_state_.hsync = hsync_counter_ != (registers_[3] & 15);
break;
}
}
perform_bus_cycle_phase2();
}
}
const BusState &get_bus_state() const {
return bus_state_;
}
private:
inline void perform_bus_cycle_phase1() {
bus_state_.display_enable = character_is_visible_ && line_is_visible_;
bus_handler_.perform_bus_cycle_phase1(bus_state_);
}
inline void perform_bus_cycle_phase2() {
bus_state_.display_enable = character_is_visible_ && line_is_visible_;
bus_handler_.perform_bus_cycle_phase2(bus_state_);
}
inline void do_end_of_line() {
// check for end of vertical sync
if(bus_state_.vsync) {
vsync_counter_ = (vsync_counter_ + 1) & 15;
switch(personality_) {
case HD6845S:
case AMS40226:
bus_state_.vsync = vsync_counter_ != (registers_[3] >> 4);
break;
default:
bus_state_.vsync = vsync_counter_ != 0;
break;
}
}
if(is_in_adjustment_period_) {
line_counter_++;
if(line_counter_ == registers_[5]) {
is_in_adjustment_period_ = false;
do_end_of_frame();
}
} else {
// advance vertical counter
if(bus_state_.row_address == registers_[9]) {
bus_state_.row_address = 0;
line_address_ = end_of_line_address_;
// check for entry into the overflow area
if(line_counter_ == registers_[4]) {
if(registers_[5]) {
line_counter_ = 0;
is_in_adjustment_period_ = true;
} else {
do_end_of_frame();
}
} else {
line_counter_ = (line_counter_ + 1) & 0x7f;
// check for start of vertical sync
if(line_counter_ == registers_[7]) {
bus_state_.vsync = true;
vsync_counter_ = 0;
}
// check for end of visible lines
if(line_counter_ == registers_[6]) {
line_is_visible_ = false;
}
}
} else {
bus_state_.row_address = (bus_state_.row_address + 1) & 0x1f;
}
}
bus_state_.refresh_address = line_address_;
character_counter_ = 0;
character_is_visible_ = (registers_[1] != 0);
}
inline void do_end_of_frame() {
line_counter_ = 0;
line_is_visible_ = true;
line_address_ = (uint16_t)((registers_[12] << 8) | registers_[13]);
bus_state_.refresh_address = line_address_;
}
Personality personality_;
T &bus_handler_;
BusState bus_state_;
uint8_t registers_[18];
uint8_t dummy_register_;
int selected_register_;
uint8_t character_counter_;
uint8_t line_counter_;
bool character_is_visible_, line_is_visible_;
int hsync_counter_;
int vsync_counter_;
bool is_in_adjustment_period_;
uint16_t line_address_;
uint16_t end_of_line_address_;
uint8_t status_;
};
}
}
#endif /* CRTC6845_hpp */
<|endoftext|> |
<commit_before>#include "catch.hpp"
#include "scene/drawRule.h"
#include "scene/sceneLayer.h"
#include "platform.h"
#include <cstdio>
#include <algorithm>
using namespace Tangram;
// Functions to initialize DrawRule instances
const int dg1 = 0;
const int dg2 = 1;
DrawRuleData instance_a() {
std::vector<StyleParam> params = {
{ StyleParamKey::order, "value_0a" },
{ StyleParamKey::join, "value_4a" },
{ StyleParamKey::color, "value_1a" }
};
return { "dg1", dg1, std::move(params) };
}
DrawRuleData instance_b() {
std::vector<StyleParam> params = {
{ StyleParamKey::order, "value_0b" },
{ StyleParamKey::width, "value_2b" },
{ StyleParamKey::color, "value_1b" },
{ StyleParamKey::cap, "value_3b" },
{ StyleParamKey::style, "value_4b" }
};
return { "dg1", dg1, std::move(params) };
}
DrawRuleData instance_c() {
std::vector<StyleParam> params = {};
// changed from dg2 - styles will not be merged otherwise
return { "dg1", dg1, params };
}
TEST_CASE("DrawRule correctly merges with another DrawRule", "[DrawRule]") {
const SceneLayer layer_a = { "a", Filter(), { instance_a() }, {} };
const SceneLayer layer_b = { "b", Filter(), { instance_b() }, {} };
const SceneLayer layer_c = { "c", Filter(), { instance_c() }, {} };
// For parameters contained in multiple rules, the parameter from the last rule
// (by lexicographical order) should result.
{
DrawRuleMergeSet ruleSet;
ruleSet.mergeRules(layer_a);
REQUIRE(ruleSet.matchedRules().size() == 1);
auto& merged_ab = ruleSet.matchedRules()[0];
for (size_t i = 0; i < StyleParamKeySize; i++) {
auto* param = merged_ab.params[i].param;
if (!param) {
logMsg("param : none %d\n", i);
continue;
}
logMsg("param : %s\n", param->toString().c_str());
}
ruleSet.mergeRules(layer_b);
REQUIRE(ruleSet.matchedRules().size() == 1);
// printf("rule_a:\n %s", rule_a.toString().c_str());
// printf("rule_c:\n %s", rule_c.toString().c_str());
// printf("merged_ac:\n %s", merged_ac.toString().c_str());
for (size_t i = 0; i < StyleParamKeySize; i++) {
auto* param = merged_ab.params[i].param;
if (!param) {
logMsg("param : none %d\n", i);
continue;
}
logMsg("param : %s\n", param->toString().c_str());
}
REQUIRE(merged_ab.findParameter(StyleParamKey::cap).key == StyleParamKey::cap);
REQUIRE(merged_ab.findParameter(StyleParamKey::cap).value.get<std::string>() == "value_3b");
REQUIRE(merged_ab.findParameter(StyleParamKey::color).key == StyleParamKey::color);
REQUIRE(merged_ab.findParameter(StyleParamKey::color).value.get<std::string>() == "value_1b");
REQUIRE(merged_ab.findParameter(StyleParamKey::join).key == StyleParamKey::join);
REQUIRE(merged_ab.findParameter(StyleParamKey::join).value.get<std::string>() == "value_4a");
REQUIRE(merged_ab.findParameter(StyleParamKey::order).key == StyleParamKey::order);
REQUIRE(merged_ab.findParameter(StyleParamKey::order).value.get<std::string>() == "value_0b");
REQUIRE(merged_ab.findParameter(StyleParamKey::style).key == StyleParamKey::style);
REQUIRE(merged_ab.findParameter(StyleParamKey::style).value.get<std::string>() == "value_4b");
REQUIRE(merged_ab.findParameter(StyleParamKey::width).key == StyleParamKey::width);
REQUIRE(merged_ab.findParameter(StyleParamKey::width).value.get<std::string>() == "value_2b");
// explicit style wins
REQUIRE(merged_ab.getStyleName() == "value_4b");
}
{
DrawRuleMergeSet ruleSet;
ruleSet.mergeRules(layer_b);
ruleSet.mergeRules(layer_a);
REQUIRE(ruleSet.matchedRules().size() == 1);
auto& merged_ba = ruleSet.matchedRules()[0];
REQUIRE(merged_ba.findParameter(StyleParamKey::cap).key == StyleParamKey::cap);
REQUIRE(merged_ba.findParameter(StyleParamKey::cap).value.get<std::string>() == "value_3b");
REQUIRE(merged_ba.findParameter(StyleParamKey::color).key == StyleParamKey::color);
REQUIRE(merged_ba.findParameter(StyleParamKey::color).value.get<std::string>() == "value_1b");
REQUIRE(merged_ba.findParameter(StyleParamKey::join).key == StyleParamKey::join);
REQUIRE(merged_ba.findParameter(StyleParamKey::join).value.get<std::string>() == "value_4a");
REQUIRE(merged_ba.findParameter(StyleParamKey::order).key == StyleParamKey::order);
REQUIRE(merged_ba.findParameter(StyleParamKey::order).value.get<std::string>() == "value_0b");
REQUIRE(merged_ba.findParameter(StyleParamKey::style).key == StyleParamKey::style);
REQUIRE(merged_ba.findParameter(StyleParamKey::style).value.get<std::string>() == "value_4b");
REQUIRE(merged_ba.findParameter(StyleParamKey::width).key == StyleParamKey::width);
REQUIRE(merged_ba.findParameter(StyleParamKey::width).value.get<std::string>() == "value_2b");
// explicit style wins
REQUIRE(merged_ba.getStyleName() == "value_4b");
}
{
DrawRuleMergeSet ruleSet;
ruleSet.mergeRules(layer_c);
ruleSet.mergeRules(layer_b);
REQUIRE(ruleSet.matchedRules().size() == 1);
auto& merged_bc = ruleSet.matchedRules()[0];
// for (size_t i = 0; i < StyleParamKeySize; i++) {
// auto* param = merged_bc.params[i];
// if (!param) { continue; }
// REQUIRE(param->key == rule_b[0].parameters[i].key);
// REQUIRE(param->value.get<std::string>() ==
// rule_b[0].parameters[i].value.get<std::string>());
// }
// explicit style wins
REQUIRE(merged_bc.getStyleName() == "value_4b");
}
}
TEST_CASE("DrawRule locates and outputs a parameter that it contains", "[DrawRule]") {
std::string str;
const SceneLayer layer_a = { "a", Filter(), { instance_a() }, {} };
const SceneLayer layer_b = { "b", Filter(), { instance_b() }, {} };
DrawRuleMergeSet a;
a.mergeRules(layer_a);
auto& rule_a = a.matchedRules()[0];
REQUIRE(rule_a.get(StyleParamKey::order, str)); REQUIRE(str == "value_0a");
REQUIRE(rule_a.get(StyleParamKey::color, str)); REQUIRE(str == "value_1a");
REQUIRE(rule_a.get(StyleParamKey::join, str)); REQUIRE(str == "value_4a");
DrawRuleMergeSet b;
b.mergeRules(layer_b);
auto& rule_b = b.matchedRules()[0];
REQUIRE(rule_b.get(StyleParamKey::color, str)); REQUIRE(str == "value_1b");
REQUIRE(rule_b.get(StyleParamKey::width, str)); REQUIRE(str == "value_2b");
REQUIRE(rule_b.get(StyleParamKey::cap, str)); REQUIRE(str == "value_3b");
REQUIRE(rule_b.get(StyleParamKey::order, str)); REQUIRE(str == "value_0b");
}
TEST_CASE("DrawRule correctly reports that it doesn't contain a parameter", "[DrawRule]") {
std::string str;
const SceneLayer layer_a = { "a", Filter(), { instance_a() }, {} };
DrawRuleMergeSet a;
a.mergeRules(layer_a);
REQUIRE(!a.matchedRules()[0].get(StyleParamKey::width, str)); REQUIRE(str == "");
const SceneLayer layer_b = { "b", Filter(), { instance_b() }, {} };
DrawRuleMergeSet b;
b.mergeRules(layer_b);
REQUIRE(!b.matchedRules()[0].get(StyleParamKey::join, str)); REQUIRE(str == "");
const SceneLayer layer_c = { "c", Filter(), { instance_c() }, {} };
DrawRuleMergeSet c;
c.mergeRules(layer_c);
REQUIRE(!c.matchedRules()[0].get(StyleParamKey::order, str)); REQUIRE(str == "");
}
<commit_msg>Fix a probable segfault in DrawRuleTests<commit_after>#include "catch.hpp"
#include "scene/drawRule.h"
#include "scene/sceneLayer.h"
#include "platform.h"
#include <cstdio>
#include <algorithm>
using namespace Tangram;
// Functions to initialize DrawRule instances
const int dg1 = 0;
const int dg2 = 1;
DrawRuleData instance_a() {
std::vector<StyleParam> params = {
{ StyleParamKey::order, "value_0a" },
{ StyleParamKey::join, "value_4a" },
{ StyleParamKey::color, "value_1a" }
};
return { "dg1", dg1, std::move(params) };
}
DrawRuleData instance_b() {
std::vector<StyleParam> params = {
{ StyleParamKey::order, "value_0b" },
{ StyleParamKey::width, "value_2b" },
{ StyleParamKey::color, "value_1b" },
{ StyleParamKey::cap, "value_3b" },
{ StyleParamKey::style, "value_4b" }
};
return { "dg1", dg1, std::move(params) };
}
DrawRuleData instance_c() {
std::vector<StyleParam> params = {};
// changed from dg2 - styles will not be merged otherwise
return { "dg1", dg1, params };
}
TEST_CASE("DrawRule correctly merges with another DrawRule", "[DrawRule]") {
const SceneLayer layer_a = { "a", Filter(), { instance_a() }, {} };
const SceneLayer layer_b = { "b", Filter(), { instance_b() }, {} };
const SceneLayer layer_c = { "c", Filter(), { instance_c() }, {} };
// For parameters contained in multiple rules, the parameter from the last rule
// (by lexicographical order) should result.
{
DrawRuleMergeSet ruleSet;
ruleSet.mergeRules(layer_a);
REQUIRE(ruleSet.matchedRules().size() == 1);
auto& merged_ab = ruleSet.matchedRules()[0];
for (size_t i = 0; i < StyleParamKeySize; i++) {
if (!merged_ab.active[i]) {
continue;
}
auto* param = merged_ab.params[i].param;
if (!param) {
logMsg("param : none %d\n", i);
continue;
}
logMsg("param : %s\n", param->toString().c_str());
}
ruleSet.mergeRules(layer_b);
REQUIRE(ruleSet.matchedRules().size() == 1);
// printf("rule_a:\n %s", rule_a.toString().c_str());
// printf("rule_c:\n %s", rule_c.toString().c_str());
// printf("merged_ac:\n %s", merged_ac.toString().c_str());
for (size_t i = 0; i < StyleParamKeySize; i++) {
if (!merged_ab.active[i]) {
continue;
}
auto* param = merged_ab.params[i].param;
if (!param) {
logMsg("param : none %d\n", i);
continue;
}
logMsg("param : %s\n", param->toString().c_str());
}
REQUIRE(merged_ab.findParameter(StyleParamKey::cap).key == StyleParamKey::cap);
REQUIRE(merged_ab.findParameter(StyleParamKey::cap).value.get<std::string>() == "value_3b");
REQUIRE(merged_ab.findParameter(StyleParamKey::color).key == StyleParamKey::color);
REQUIRE(merged_ab.findParameter(StyleParamKey::color).value.get<std::string>() == "value_1b");
REQUIRE(merged_ab.findParameter(StyleParamKey::join).key == StyleParamKey::join);
REQUIRE(merged_ab.findParameter(StyleParamKey::join).value.get<std::string>() == "value_4a");
REQUIRE(merged_ab.findParameter(StyleParamKey::order).key == StyleParamKey::order);
REQUIRE(merged_ab.findParameter(StyleParamKey::order).value.get<std::string>() == "value_0b");
REQUIRE(merged_ab.findParameter(StyleParamKey::style).key == StyleParamKey::style);
REQUIRE(merged_ab.findParameter(StyleParamKey::style).value.get<std::string>() == "value_4b");
REQUIRE(merged_ab.findParameter(StyleParamKey::width).key == StyleParamKey::width);
REQUIRE(merged_ab.findParameter(StyleParamKey::width).value.get<std::string>() == "value_2b");
// explicit style wins
REQUIRE(merged_ab.getStyleName() == "value_4b");
}
{
DrawRuleMergeSet ruleSet;
ruleSet.mergeRules(layer_b);
ruleSet.mergeRules(layer_a);
REQUIRE(ruleSet.matchedRules().size() == 1);
auto& merged_ba = ruleSet.matchedRules()[0];
REQUIRE(merged_ba.findParameter(StyleParamKey::cap).key == StyleParamKey::cap);
REQUIRE(merged_ba.findParameter(StyleParamKey::cap).value.get<std::string>() == "value_3b");
REQUIRE(merged_ba.findParameter(StyleParamKey::color).key == StyleParamKey::color);
REQUIRE(merged_ba.findParameter(StyleParamKey::color).value.get<std::string>() == "value_1b");
REQUIRE(merged_ba.findParameter(StyleParamKey::join).key == StyleParamKey::join);
REQUIRE(merged_ba.findParameter(StyleParamKey::join).value.get<std::string>() == "value_4a");
REQUIRE(merged_ba.findParameter(StyleParamKey::order).key == StyleParamKey::order);
REQUIRE(merged_ba.findParameter(StyleParamKey::order).value.get<std::string>() == "value_0b");
REQUIRE(merged_ba.findParameter(StyleParamKey::style).key == StyleParamKey::style);
REQUIRE(merged_ba.findParameter(StyleParamKey::style).value.get<std::string>() == "value_4b");
REQUIRE(merged_ba.findParameter(StyleParamKey::width).key == StyleParamKey::width);
REQUIRE(merged_ba.findParameter(StyleParamKey::width).value.get<std::string>() == "value_2b");
// explicit style wins
REQUIRE(merged_ba.getStyleName() == "value_4b");
}
{
DrawRuleMergeSet ruleSet;
ruleSet.mergeRules(layer_c);
ruleSet.mergeRules(layer_b);
REQUIRE(ruleSet.matchedRules().size() == 1);
auto& merged_bc = ruleSet.matchedRules()[0];
// for (size_t i = 0; i < StyleParamKeySize; i++) {
// auto* param = merged_bc.params[i];
// if (!param) { continue; }
// REQUIRE(param->key == rule_b[0].parameters[i].key);
// REQUIRE(param->value.get<std::string>() ==
// rule_b[0].parameters[i].value.get<std::string>());
// }
// explicit style wins
REQUIRE(merged_bc.getStyleName() == "value_4b");
}
}
TEST_CASE("DrawRule locates and outputs a parameter that it contains", "[DrawRule]") {
std::string str;
const SceneLayer layer_a = { "a", Filter(), { instance_a() }, {} };
const SceneLayer layer_b = { "b", Filter(), { instance_b() }, {} };
DrawRuleMergeSet a;
a.mergeRules(layer_a);
auto& rule_a = a.matchedRules()[0];
REQUIRE(rule_a.get(StyleParamKey::order, str)); REQUIRE(str == "value_0a");
REQUIRE(rule_a.get(StyleParamKey::color, str)); REQUIRE(str == "value_1a");
REQUIRE(rule_a.get(StyleParamKey::join, str)); REQUIRE(str == "value_4a");
DrawRuleMergeSet b;
b.mergeRules(layer_b);
auto& rule_b = b.matchedRules()[0];
REQUIRE(rule_b.get(StyleParamKey::color, str)); REQUIRE(str == "value_1b");
REQUIRE(rule_b.get(StyleParamKey::width, str)); REQUIRE(str == "value_2b");
REQUIRE(rule_b.get(StyleParamKey::cap, str)); REQUIRE(str == "value_3b");
REQUIRE(rule_b.get(StyleParamKey::order, str)); REQUIRE(str == "value_0b");
}
TEST_CASE("DrawRule correctly reports that it doesn't contain a parameter", "[DrawRule]") {
std::string str;
const SceneLayer layer_a = { "a", Filter(), { instance_a() }, {} };
DrawRuleMergeSet a;
a.mergeRules(layer_a);
REQUIRE(!a.matchedRules()[0].get(StyleParamKey::width, str)); REQUIRE(str == "");
const SceneLayer layer_b = { "b", Filter(), { instance_b() }, {} };
DrawRuleMergeSet b;
b.mergeRules(layer_b);
REQUIRE(!b.matchedRules()[0].get(StyleParamKey::join, str)); REQUIRE(str == "");
const SceneLayer layer_c = { "c", Filter(), { instance_c() }, {} };
DrawRuleMergeSet c;
c.mergeRules(layer_c);
REQUIRE(!c.matchedRules()[0].get(StyleParamKey::order, str)); REQUIRE(str == "");
}
<|endoftext|> |
<commit_before>#include <tst/set.hpp>
#include <tst/check.hpp>
#include <utki/singleton.hpp>
namespace{
class test_singleton : public utki::singleton<test_singleton>{
public:
int a = 13;
};
}
namespace{
tst::set set("singleton", [](tst::suite& suite){
suite.add(
"only_one_singleton_instance_can_exist_at_a_time",
tst::flag::no_parallel,
[]{
test_singleton sing1;
try{
test_singleton sing2;
tst::check(false, SL) << "creating second singleton object should throw";
}catch(std::logic_error&){}
}
);
});
}
<commit_msg>fix msvc build<commit_after>#include <tst/set.hpp>
#include <tst/check.hpp>
#include <utki/config.hpp>
#include <utki/singleton.hpp>
#if M_COMPILER != M_COMPILER_MSVC
namespace{
class test_singleton : public utki::singleton<test_singleton>{
public:
int a = 13;
};
}
namespace{
tst::set set("singleton", [](tst::suite& suite){
suite.add(
"only_one_singleton_instance_can_exist_at_a_time",
tst::flag::no_parallel,
[]{
test_singleton sing1;
try{
test_singleton sing2;
tst::check(false, SL) << "creating second singleton object should throw";
}catch(std::logic_error&){}
}
);
});
}
#endif // ~msvc compiler
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "oox/ole/vbamodule.hxx"
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/script/ModuleInfo.hpp>
#include <com/sun/star/script/ModuleType.hpp>
#include <com/sun/star/script/XVBAModuleInfo.hpp>
#include "oox/helper/binaryinputstream.hxx"
#include "oox/helper/storagebase.hxx"
#include "oox/helper/textinputstream.hxx"
#include "oox/ole/vbahelper.hxx"
#include "oox/ole/vbainputstream.hxx"
using ::rtl::OUString;
using ::rtl::OUStringBuffer;
using ::com::sun::star::container::XNameAccess;
using ::com::sun::star::container::XNameContainer;
using ::com::sun::star::frame::XModel;
using ::com::sun::star::script::ModuleInfo;
using ::com::sun::star::script::XVBAModuleInfo;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::UNO_QUERY_THROW;
namespace ApiModuleType = ::com::sun::star::script::ModuleType;
namespace oox {
namespace ole {
// ============================================================================
VbaModule::VbaModule( const Reference< XModel >& rxDocModel, const OUString& rName, rtl_TextEncoding eTextEnc, bool bExecutable ) :
mxDocModel( rxDocModel ),
maName( rName ),
meTextEnc( eTextEnc ),
mnType( ApiModuleType::Unknown ),
mnOffset( SAL_MAX_UINT32 ),
mbReadOnly( false ),
mbPrivate( false ),
mbExecutable( bExecutable )
{
}
void VbaModule::importDirRecords( BinaryInputStream& rDirStrm )
{
sal_uInt16 nRecId = 0;
StreamDataSequence aRecData;
while( VbaHelper::readDirRecord( nRecId, aRecData, rDirStrm ) && (nRecId != VBA_ID_MODULEEND) )
{
SequenceInputStream aRecStrm( aRecData );
sal_Int32 nRecSize = aRecData.getLength();
switch( nRecId )
{
#define OOX_ENSURE_RECORDSIZE( cond ) OSL_ENSURE( cond, "VbaModule::importDirRecords - invalid record size" )
case VBA_ID_MODULENAME:
OSL_ENSURE( false, "VbaModule::importDirRecords - unexpected MODULENAME record" );
maName = aRecStrm.readCharArrayUC( nRecSize, meTextEnc );
break;
case VBA_ID_MODULENAMEUNICODE:
break;
case VBA_ID_MODULESTREAMNAME:
maStreamName = aRecStrm.readCharArrayUC( nRecSize, meTextEnc );
break;
case VBA_ID_MODULESTREAMNAMEUNICODE:
break;
case VBA_ID_MODULEDOCSTRING:
maDocString = aRecStrm.readCharArrayUC( nRecSize, meTextEnc );
break;
case VBA_ID_MODULEDOCSTRINGUNICODE:
break;
case VBA_ID_MODULEOFFSET:
OOX_ENSURE_RECORDSIZE( nRecSize == 4 );
aRecStrm >> mnOffset;
break;
case VBA_ID_MODULEHELPCONTEXT:
OOX_ENSURE_RECORDSIZE( nRecSize == 4 );
break;
case VBA_ID_MODULECOOKIE:
OOX_ENSURE_RECORDSIZE( nRecSize == 2 );
break;
case VBA_ID_MODULETYPEPROCEDURAL:
OOX_ENSURE_RECORDSIZE( nRecSize == 0 );
OSL_ENSURE( mnType == ApiModuleType::Unknown, "VbaModule::importDirRecords - multiple module type records" );
mnType = ApiModuleType::Normal;
break;
case VBA_ID_MODULETYPEDOCUMENT:
OOX_ENSURE_RECORDSIZE( nRecSize == 0 );
OSL_ENSURE( mnType == ApiModuleType::Unknown, "VbaModule::importDirRecords - multiple module type records" );
mnType = ApiModuleType::Document;
break;
case VBA_ID_MODULEREADONLY:
OOX_ENSURE_RECORDSIZE( nRecSize == 0 );
mbReadOnly = true;
break;
case VBA_ID_MODULEPRIVATE:
OOX_ENSURE_RECORDSIZE( nRecSize == 0 );
mbPrivate = true;
break;
default:
OSL_ENSURE( false, "VbaModule::importDirRecords - unknown module record" );
#undef OOX_ENSURE_RECORDSIZE
}
}
OSL_ENSURE( maName.getLength() > 0, "VbaModule::importDirRecords - missing module name" );
OSL_ENSURE( maStreamName.getLength() > 0, "VbaModule::importDirRecords - missing module stream name" );
OSL_ENSURE( mnType != ApiModuleType::Unknown, "VbaModule::importDirRecords - missing module type" );
OSL_ENSURE( mnOffset < SAL_MAX_UINT32, "VbaModule::importDirRecords - missing module stream offset" );
}
void VbaModule::importSourceCode( StorageBase& rVbaStrg,
const Reference< XNameContainer >& rxBasicLib, const Reference< XNameAccess >& rxDocObjectNA ) const
{
if( (maName.getLength() == 0) || (maStreamName.getLength() == 0) || (mnOffset == SAL_MAX_UINT32) )
return;
BinaryXInputStream aInStrm( rVbaStrg.openInputStream( maStreamName ), true );
OSL_ENSURE( !aInStrm.isEof(), "VbaModule::importSourceCode - cannot open module stream" );
// skip the 'performance cache' stored before the actual source code
aInStrm.seek( mnOffset );
// if stream is still valid, load the source code
if( aInStrm.isEof() )
return;
// prepare the Basic module
ModuleInfo aModuleInfo;
aModuleInfo.ModuleType = mnType;
OUStringBuffer aSourceCode;
aSourceCode.appendAscii( RTL_CONSTASCII_STRINGPARAM( "Rem Attribute VBA_ModuleType=" ) );
switch( mnType )
{
case ApiModuleType::Normal:
aSourceCode.appendAscii( RTL_CONSTASCII_STRINGPARAM( "VBAModule" ) );
break;
case ApiModuleType::Class:
aSourceCode.appendAscii( RTL_CONSTASCII_STRINGPARAM( "VBAClassModule" ) );
break;
case ApiModuleType::Form:
aSourceCode.appendAscii( RTL_CONSTASCII_STRINGPARAM( "VBAFormModule" ) );
// hack from old filter, document Basic should know the XModel, but it doesn't
aModuleInfo.ModuleObject.set( mxDocModel, UNO_QUERY );
break;
case ApiModuleType::Document:
aSourceCode.appendAscii( RTL_CONSTASCII_STRINGPARAM( "VBADocumentModule" ) );
// get the VBA object associated to the document module
if( rxDocObjectNA.is() ) try
{
aModuleInfo.ModuleObject.set( rxDocObjectNA->getByName( maName ), UNO_QUERY );
}
catch( Exception& )
{
}
break;
default:
aSourceCode.appendAscii( RTL_CONSTASCII_STRINGPARAM( "VBAUnknown" ) );
}
aSourceCode.append( sal_Unicode( '\n' ) );
if( mbExecutable )
{
aSourceCode.appendAscii( RTL_CONSTASCII_STRINGPARAM( "Option VBASupport 1\n" ) );
if( mnType == ApiModuleType::Class )
aSourceCode.appendAscii( RTL_CONSTASCII_STRINGPARAM( "Option ClassModule\n" ) );
}
else
{
// add a subroutine named after the module itself
aSourceCode.appendAscii( RTL_CONSTASCII_STRINGPARAM( "Sub " ) ).
append( maName.replace( ' ', '_' ) ).append( sal_Unicode( '\n' ) );
}
// decompression starts at current stream position of aInStrm
VbaInputStream aVbaStrm( aInStrm );
// load the source code line-by-line, with some more processing
TextInputStream aVbaTextStrm( aVbaStrm, meTextEnc );
while( !aVbaTextStrm.isEof() )
{
OUString aCodeLine = aVbaTextStrm.readLine();
// skip all 'Attribute' statements
if( !aCodeLine.matchAsciiL( RTL_CONSTASCII_STRINGPARAM( "Attribute " ) ) )
{
if( !mbExecutable )
aSourceCode.appendAscii( RTL_CONSTASCII_STRINGPARAM( "Rem " ) );
aSourceCode.append( aCodeLine ).append( sal_Unicode( '\n' ) );
}
}
// close the subroutine named after the module
if( !mbExecutable )
aSourceCode.appendAscii( RTL_CONSTASCII_STRINGPARAM( "End Sub\n" ) );
// insert the module into the passed Basic library
try
{
rxBasicLib->insertByName( maName, Any( aSourceCode.makeStringAndClear() ) );
}
catch( Exception& )
{
OSL_ENSURE( false, "VbaModule::importSourceCode - cannot insert module into library" );
}
// insert extended module info
try
{
Reference< XVBAModuleInfo > xVBAModuleInfo( rxBasicLib, UNO_QUERY_THROW );
xVBAModuleInfo->insertModuleInfo( maName, aModuleInfo );
}
catch( Exception& )
{
}
}
// ============================================================================
} // namespace ole
} // namespace oox
<commit_msg>npower13_objectmodules: fix order of XModuleInfo/Module creation order<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "oox/ole/vbamodule.hxx"
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/script/ModuleInfo.hpp>
#include <com/sun/star/script/ModuleType.hpp>
#include <com/sun/star/script/XVBAModuleInfo.hpp>
#include "oox/helper/binaryinputstream.hxx"
#include "oox/helper/storagebase.hxx"
#include "oox/helper/textinputstream.hxx"
#include "oox/ole/vbahelper.hxx"
#include "oox/ole/vbainputstream.hxx"
using ::rtl::OUString;
using ::rtl::OUStringBuffer;
using ::com::sun::star::container::XNameAccess;
using ::com::sun::star::container::XNameContainer;
using ::com::sun::star::frame::XModel;
using ::com::sun::star::script::ModuleInfo;
using ::com::sun::star::script::XVBAModuleInfo;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::UNO_QUERY_THROW;
namespace ApiModuleType = ::com::sun::star::script::ModuleType;
namespace oox {
namespace ole {
// ============================================================================
VbaModule::VbaModule( const Reference< XModel >& rxDocModel, const OUString& rName, rtl_TextEncoding eTextEnc, bool bExecutable ) :
mxDocModel( rxDocModel ),
maName( rName ),
meTextEnc( eTextEnc ),
mnType( ApiModuleType::Unknown ),
mnOffset( SAL_MAX_UINT32 ),
mbReadOnly( false ),
mbPrivate( false ),
mbExecutable( bExecutable )
{
}
void VbaModule::importDirRecords( BinaryInputStream& rDirStrm )
{
sal_uInt16 nRecId = 0;
StreamDataSequence aRecData;
while( VbaHelper::readDirRecord( nRecId, aRecData, rDirStrm ) && (nRecId != VBA_ID_MODULEEND) )
{
SequenceInputStream aRecStrm( aRecData );
sal_Int32 nRecSize = aRecData.getLength();
switch( nRecId )
{
#define OOX_ENSURE_RECORDSIZE( cond ) OSL_ENSURE( cond, "VbaModule::importDirRecords - invalid record size" )
case VBA_ID_MODULENAME:
OSL_ENSURE( false, "VbaModule::importDirRecords - unexpected MODULENAME record" );
maName = aRecStrm.readCharArrayUC( nRecSize, meTextEnc );
break;
case VBA_ID_MODULENAMEUNICODE:
break;
case VBA_ID_MODULESTREAMNAME:
maStreamName = aRecStrm.readCharArrayUC( nRecSize, meTextEnc );
break;
case VBA_ID_MODULESTREAMNAMEUNICODE:
break;
case VBA_ID_MODULEDOCSTRING:
maDocString = aRecStrm.readCharArrayUC( nRecSize, meTextEnc );
break;
case VBA_ID_MODULEDOCSTRINGUNICODE:
break;
case VBA_ID_MODULEOFFSET:
OOX_ENSURE_RECORDSIZE( nRecSize == 4 );
aRecStrm >> mnOffset;
break;
case VBA_ID_MODULEHELPCONTEXT:
OOX_ENSURE_RECORDSIZE( nRecSize == 4 );
break;
case VBA_ID_MODULECOOKIE:
OOX_ENSURE_RECORDSIZE( nRecSize == 2 );
break;
case VBA_ID_MODULETYPEPROCEDURAL:
OOX_ENSURE_RECORDSIZE( nRecSize == 0 );
OSL_ENSURE( mnType == ApiModuleType::Unknown, "VbaModule::importDirRecords - multiple module type records" );
mnType = ApiModuleType::Normal;
break;
case VBA_ID_MODULETYPEDOCUMENT:
OOX_ENSURE_RECORDSIZE( nRecSize == 0 );
OSL_ENSURE( mnType == ApiModuleType::Unknown, "VbaModule::importDirRecords - multiple module type records" );
mnType = ApiModuleType::Document;
break;
case VBA_ID_MODULEREADONLY:
OOX_ENSURE_RECORDSIZE( nRecSize == 0 );
mbReadOnly = true;
break;
case VBA_ID_MODULEPRIVATE:
OOX_ENSURE_RECORDSIZE( nRecSize == 0 );
mbPrivate = true;
break;
default:
OSL_ENSURE( false, "VbaModule::importDirRecords - unknown module record" );
#undef OOX_ENSURE_RECORDSIZE
}
}
OSL_ENSURE( maName.getLength() > 0, "VbaModule::importDirRecords - missing module name" );
OSL_ENSURE( maStreamName.getLength() > 0, "VbaModule::importDirRecords - missing module stream name" );
OSL_ENSURE( mnType != ApiModuleType::Unknown, "VbaModule::importDirRecords - missing module type" );
OSL_ENSURE( mnOffset < SAL_MAX_UINT32, "VbaModule::importDirRecords - missing module stream offset" );
}
void VbaModule::importSourceCode( StorageBase& rVbaStrg,
const Reference< XNameContainer >& rxBasicLib, const Reference< XNameAccess >& rxDocObjectNA ) const
{
if( (maName.getLength() == 0) || (maStreamName.getLength() == 0) || (mnOffset == SAL_MAX_UINT32) )
return;
BinaryXInputStream aInStrm( rVbaStrg.openInputStream( maStreamName ), true );
OSL_ENSURE( !aInStrm.isEof(), "VbaModule::importSourceCode - cannot open module stream" );
// skip the 'performance cache' stored before the actual source code
aInStrm.seek( mnOffset );
// if stream is still valid, load the source code
if( aInStrm.isEof() )
return;
// prepare the Basic module
ModuleInfo aModuleInfo;
aModuleInfo.ModuleType = mnType;
OUStringBuffer aSourceCode;
aSourceCode.appendAscii( RTL_CONSTASCII_STRINGPARAM( "Rem Attribute VBA_ModuleType=" ) );
switch( mnType )
{
case ApiModuleType::Normal:
aSourceCode.appendAscii( RTL_CONSTASCII_STRINGPARAM( "VBAModule" ) );
break;
case ApiModuleType::Class:
aSourceCode.appendAscii( RTL_CONSTASCII_STRINGPARAM( "VBAClassModule" ) );
break;
case ApiModuleType::Form:
aSourceCode.appendAscii( RTL_CONSTASCII_STRINGPARAM( "VBAFormModule" ) );
// hack from old filter, document Basic should know the XModel, but it doesn't
aModuleInfo.ModuleObject.set( mxDocModel, UNO_QUERY );
break;
case ApiModuleType::Document:
aSourceCode.appendAscii( RTL_CONSTASCII_STRINGPARAM( "VBADocumentModule" ) );
// get the VBA object associated to the document module
if( rxDocObjectNA.is() ) try
{
aModuleInfo.ModuleObject.set( rxDocObjectNA->getByName( maName ), UNO_QUERY );
}
catch( Exception& )
{
}
break;
default:
aSourceCode.appendAscii( RTL_CONSTASCII_STRINGPARAM( "VBAUnknown" ) );
}
aSourceCode.append( sal_Unicode( '\n' ) );
if( mbExecutable )
{
aSourceCode.appendAscii( RTL_CONSTASCII_STRINGPARAM( "Option VBASupport 1\n" ) );
if( mnType == ApiModuleType::Class )
aSourceCode.appendAscii( RTL_CONSTASCII_STRINGPARAM( "Option ClassModule\n" ) );
}
else
{
// add a subroutine named after the module itself
aSourceCode.appendAscii( RTL_CONSTASCII_STRINGPARAM( "Sub " ) ).
append( maName.replace( ' ', '_' ) ).append( sal_Unicode( '\n' ) );
}
// decompression starts at current stream position of aInStrm
VbaInputStream aVbaStrm( aInStrm );
// load the source code line-by-line, with some more processing
TextInputStream aVbaTextStrm( aVbaStrm, meTextEnc );
while( !aVbaTextStrm.isEof() )
{
OUString aCodeLine = aVbaTextStrm.readLine();
// skip all 'Attribute' statements
if( !aCodeLine.matchAsciiL( RTL_CONSTASCII_STRINGPARAM( "Attribute " ) ) )
{
if( !mbExecutable )
aSourceCode.appendAscii( RTL_CONSTASCII_STRINGPARAM( "Rem " ) );
aSourceCode.append( aCodeLine ).append( sal_Unicode( '\n' ) );
}
}
// close the subroutine named after the module
if( !mbExecutable )
aSourceCode.appendAscii( RTL_CONSTASCII_STRINGPARAM( "End Sub\n" ) );
// insert extended module info
try
{
Reference< XVBAModuleInfo > xVBAModuleInfo( rxBasicLib, UNO_QUERY_THROW );
xVBAModuleInfo->insertModuleInfo( maName, aModuleInfo );
}
catch( Exception& )
{
}
// insert the module into the passed Basic library
try
{
rxBasicLib->insertByName( maName, Any( aSourceCode.makeStringAndClear() ) );
}
catch( Exception& )
{
OSL_ENSURE( false, "VbaModule::importSourceCode - cannot insert module into library" );
}
}
// ============================================================================
} // namespace ole
} // namespace oox
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2011-2012, John Haddon. All rights reserved.
// Copyright (c) 2011-2015, Image Engine Design 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 John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "ActionBinding.h"
#include "AnimationBinding.h"
#include "ApplicationRootBinding.h"
#include "ArrayPlugBinding.h"
#include "BoxPlugBinding.h"
#include "CompoundDataPlugBinding.h"
#include "CompoundNumericPlugBinding.h"
#include "ContextBinding.h"
#include "ContextProcessorBinding.h"
#include "DirtyPropagationScopeBinding.h"
#include "DotBinding.h"
#include "ExpressionBinding.h"
#include "GraphComponentBinding.h"
#include "ProcessMessageHandlerBinding.h"
#include "MetadataAlgoBinding.h"
#include "MetadataBinding.h"
#include "MonitorBinding.h"
#include "NodeAlgoBinding.h"
#include "NodeBinding.h"
#include "NumericPlugBinding.h"
#include "ParallelAlgoBinding.h"
#include "PathBinding.h"
#include "PathFilterBinding.h"
#include "PlugAlgoBinding.h"
#include "PlugBinding.h"
#include "ProcessBinding.h"
#include "RandomBinding.h"
#include "ScriptNodeBinding.h"
#include "SerialisationBinding.h"
#include "SetBinding.h"
#include "SignalsBinding.h"
#include "SplinePlugBinding.h"
#include "SpreadsheetBinding.h"
#include "StringPlugBinding.h"
#include "SubGraphBinding.h"
#include "SwitchBinding.h"
#include "Transform2DPlugBinding.h"
#include "TransformPlugBinding.h"
#include "TypedObjectPlugBinding.h"
#include "TypedPlugBinding.h"
#include "UndoScopeBinding.h"
#include "ValuePlugBinding.h"
#include "NameValuePlugBinding.h"
#include "ShufflesBinding.h"
#include "MessagesBinding.h"
#include "GafferBindings/DependencyNodeBinding.h"
#include "Gaffer/Backdrop.h"
#ifdef __linux__
#include <sys/prctl.h>
#endif
using namespace boost::python;
using namespace Gaffer;
using namespace GafferModule;
using namespace GafferBindings;
namespace
{
bool isDebug()
{
#ifdef NDEBUG
return false;
#else
return true;
#endif
}
int g_argc = 0;
char **g_argv = nullptr;
int storeArgcArgv( int argc, char **argv, char **env )
{
g_argc = argc;
g_argv = argv;
return 0;
}
void clobberArgv()
{
if( g_argc < 2 )
{
return;
}
// A typical command line looks like this :
//
// `gaffer arg1 arg2 arg3`
//
// But will look like this once the wrapper
// has launched Gaffer via Python :
//
// `python gaffer.py arg1 arg2 arg3`
//
// Replace the `python` bit with `gaffer` and
// shuffle all the arguments around so that
// the `gaffer.py` argument disappears and we
// get back to the original.
char *end = g_argv[g_argc-1] + strlen( g_argv[g_argc-1] );
strncpy( g_argv[0], "gaffer", strlen( g_argv[0] ) );
strncpy( g_argv[1], "", strlen( g_argv[1] ) );
char *emptyString = g_argv[1];
for( int i = 1; i < g_argc - 1; ++i )
{
g_argv[i] = g_argv[i+1];
}
g_argv[g_argc-1] = emptyString;
// We've just shuffled the pointers so far, but
// in practice the original strings were contiguous
// in the same chunk of memory, and `ps` uses that fact
// rather than actually use the argv pointers. See
// https://stackoverflow.com/a/23400588.
//
// Pack everything back down so `ps` sees what it
// expects.
char *c = g_argv[0];
for( int i = 0; i < g_argc - 1; ++i )
{
const size_t l = strlen( g_argv[i] ) + 1;
memmove( c, g_argv[i], l );
g_argv[i] = c;
c += l;
}
g_argv[g_argc-1] = c;
memset( c, 0, end - c );
}
void nameProcess()
{
// Some things (for instance, `ps` in default mode) look at `argv` to get
// the name.
clobberArgv();
// Others (for instance, `top` in default mode) use other methods.
// Cater to everyone as best we can.
#ifdef __linux__
prctl( PR_SET_NAME, "gaffer", 0, 0, 0 );
#endif
}
} // namespace
// Arrange for `storeArgcArgv()` to be called when our module loads,
// so we can stash the original values for `argc` and `argv`.
// In Python 2 we could simply use `Py_GetArgcArgv()` instead, but
// in Python 3 that gives us a mangled copy which is of no use.
#if defined( __APPLE__ )
__attribute__( ( section( "__DATA,__mod_init_func" ) ) ) decltype( storeArgcArgv ) *g_initArgcArgv = storeArgcArgv;
#elif defined( __linux__ )
__attribute__( ( section( ".init_array" ) ) ) decltype( storeArgcArgv ) *g_initArgcArgv = storeArgcArgv;
#endif
BOOST_PYTHON_MODULE( _Gaffer )
{
bindSignals();
bindGraphComponent();
bindContext();
bindSerialisation();
bindNode();
bindPlug();
bindValuePlug();
bindNumericPlug();
bindTypedPlug();
bindStringPlug();
bindTypedObjectPlug();
bindScriptNode();
bindApplicationRoot();
bindSet();
bindDirtyPropagationScope();
bindUndoScope();
bindCompoundNumericPlug();
bindSplinePlug();
bindBoxPlug();
bindExpression();
bindTransformPlug();
bindTransform2DPlug();
bindCompoundDataPlug();
bindRandom();
bindSubGraph();
bindAction();
bindArrayPlug();
bindMetadata();
bindDot();
bindPath();
bindPathFilter();
bindAnimation();
bindMonitor();
bindMetadataAlgo();
bindSwitch();
bindPlugAlgo();
bindParallelAlgo();
bindContextProcessor();
bindProcessMessageHandler();
bindNameValuePlug();
bindProcess();
bindSpreadsheet();
bindNodeAlgo();
bindShuffles();
bindMessages();
NodeClass<Backdrop>();
def( "isDebug", &isDebug );
def( "_nameProcess", &nameProcess );
// Various parts of gaffer create new threads from C++, and those
// threads may call back into Python via wrapped classes at any time.
// We must prepare Python for this by calling PyEval_InitThreads().
PyEval_InitThreads();
}
<commit_msg>GafferModule : Restrict process naming to Linux and Mac<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2011-2012, John Haddon. All rights reserved.
// Copyright (c) 2011-2015, Image Engine Design 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 John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "ActionBinding.h"
#include "AnimationBinding.h"
#include "ApplicationRootBinding.h"
#include "ArrayPlugBinding.h"
#include "BoxPlugBinding.h"
#include "CompoundDataPlugBinding.h"
#include "CompoundNumericPlugBinding.h"
#include "ContextBinding.h"
#include "ContextProcessorBinding.h"
#include "DirtyPropagationScopeBinding.h"
#include "DotBinding.h"
#include "ExpressionBinding.h"
#include "GraphComponentBinding.h"
#include "ProcessMessageHandlerBinding.h"
#include "MetadataAlgoBinding.h"
#include "MetadataBinding.h"
#include "MonitorBinding.h"
#include "NodeAlgoBinding.h"
#include "NodeBinding.h"
#include "NumericPlugBinding.h"
#include "ParallelAlgoBinding.h"
#include "PathBinding.h"
#include "PathFilterBinding.h"
#include "PlugAlgoBinding.h"
#include "PlugBinding.h"
#include "ProcessBinding.h"
#include "RandomBinding.h"
#include "ScriptNodeBinding.h"
#include "SerialisationBinding.h"
#include "SetBinding.h"
#include "SignalsBinding.h"
#include "SplinePlugBinding.h"
#include "SpreadsheetBinding.h"
#include "StringPlugBinding.h"
#include "SubGraphBinding.h"
#include "SwitchBinding.h"
#include "Transform2DPlugBinding.h"
#include "TransformPlugBinding.h"
#include "TypedObjectPlugBinding.h"
#include "TypedPlugBinding.h"
#include "UndoScopeBinding.h"
#include "ValuePlugBinding.h"
#include "NameValuePlugBinding.h"
#include "ShufflesBinding.h"
#include "MessagesBinding.h"
#include "GafferBindings/DependencyNodeBinding.h"
#include "Gaffer/Backdrop.h"
#ifdef __linux__
#include <sys/prctl.h>
#endif
using namespace boost::python;
using namespace Gaffer;
using namespace GafferModule;
using namespace GafferBindings;
namespace
{
bool isDebug()
{
#ifdef NDEBUG
return false;
#else
return true;
#endif
}
#ifndef _MSC_VER
int g_argc = 0;
char **g_argv = nullptr;
int storeArgcArgv( int argc, char **argv, char **env )
{
g_argc = argc;
g_argv = argv;
return 0;
}
void clobberArgv()
{
if( g_argc < 2 )
{
return;
}
// A typical command line looks like this :
//
// `gaffer arg1 arg2 arg3`
//
// But will look like this once the wrapper
// has launched Gaffer via Python :
//
// `python gaffer.py arg1 arg2 arg3`
//
// Replace the `python` bit with `gaffer` and
// shuffle all the arguments around so that
// the `gaffer.py` argument disappears and we
// get back to the original.
char *end = g_argv[g_argc-1] + strlen( g_argv[g_argc-1] );
strncpy( g_argv[0], "gaffer", strlen( g_argv[0] ) );
strncpy( g_argv[1], "", strlen( g_argv[1] ) );
char *emptyString = g_argv[1];
for( int i = 1; i < g_argc - 1; ++i )
{
g_argv[i] = g_argv[i+1];
}
g_argv[g_argc-1] = emptyString;
// We've just shuffled the pointers so far, but
// in practice the original strings were contiguous
// in the same chunk of memory, and `ps` uses that fact
// rather than actually use the argv pointers. See
// https://stackoverflow.com/a/23400588.
//
// Pack everything back down so `ps` sees what it
// expects.
char *c = g_argv[0];
for( int i = 0; i < g_argc - 1; ++i )
{
const size_t l = strlen( g_argv[i] ) + 1;
memmove( c, g_argv[i], l );
g_argv[i] = c;
c += l;
}
g_argv[g_argc-1] = c;
memset( c, 0, end - c );
}
#endif
void nameProcess()
{
// Some things (for instance, `ps` in default mode) look at `argv` to get
// the name.
#ifndef _MSC_VER
clobberArgv();
#endif
// Others (for instance, `top` in default mode) use other methods.
// Cater to everyone as best we can.
#ifdef __linux__
prctl( PR_SET_NAME, "gaffer", 0, 0, 0 );
#endif
}
} // namespace
// Arrange for `storeArgcArgv()` to be called when our module loads,
// so we can stash the original values for `argc` and `argv`.
// In Python 2 we could simply use `Py_GetArgcArgv()` instead, but
// in Python 3 that gives us a mangled copy which is of no use.
#if defined( __APPLE__ )
__attribute__( ( section( "__DATA,__mod_init_func" ) ) ) decltype( storeArgcArgv ) *g_initArgcArgv = storeArgcArgv;
#elif defined( __linux__ )
__attribute__( ( section( ".init_array" ) ) ) decltype( storeArgcArgv ) *g_initArgcArgv = storeArgcArgv;
#endif
BOOST_PYTHON_MODULE( _Gaffer )
{
bindSignals();
bindGraphComponent();
bindContext();
bindSerialisation();
bindNode();
bindPlug();
bindValuePlug();
bindNumericPlug();
bindTypedPlug();
bindStringPlug();
bindTypedObjectPlug();
bindScriptNode();
bindApplicationRoot();
bindSet();
bindDirtyPropagationScope();
bindUndoScope();
bindCompoundNumericPlug();
bindSplinePlug();
bindBoxPlug();
bindExpression();
bindTransformPlug();
bindTransform2DPlug();
bindCompoundDataPlug();
bindRandom();
bindSubGraph();
bindAction();
bindArrayPlug();
bindMetadata();
bindDot();
bindPath();
bindPathFilter();
bindAnimation();
bindMonitor();
bindMetadataAlgo();
bindSwitch();
bindPlugAlgo();
bindParallelAlgo();
bindContextProcessor();
bindProcessMessageHandler();
bindNameValuePlug();
bindProcess();
bindSpreadsheet();
bindNodeAlgo();
bindShuffles();
bindMessages();
NodeClass<Backdrop>();
def( "isDebug", &isDebug );
def( "_nameProcess", &nameProcess );
// Various parts of gaffer create new threads from C++, and those
// threads may call back into Python via wrapped classes at any time.
// We must prepare Python for this by calling PyEval_InitThreads().
PyEval_InitThreads();
}
<|endoftext|> |
<commit_before>#include <set>
#include "Game/Physics/MergeBuilder.h"
#ifdef DEBUG
//#define DEBUG_MAPSPEW
#endif
#ifdef DEBUG_MAPSPEW
#include <iostream>
#include <sstream>
#endif
using namespace Wulf;
using namespace Wulf::Physics;
bool notMergable(TileType type)
{
return type == TileType::Door || type == TileType::Pickup;
}
MergeNode::MergeNode(Map::Node const& node)
: topLeft(node.x, node.y), type(NodeToTile(node))
, width(0), height(0)
, done(false)
, mTileData(nullptr)
{
}
bool MergeNode::compatible(MergeNode const* other) const
{
if (other == nullptr || other->done || other->type != type || notMergable(other->type))
return false;
return true;
}
// This returns the tiledata for the merged mass.
// It is safe to call multiple times as it only returns one TileData.
TileData* MergeNode::toTile()
{
if (mTileData != nullptr)
return mTileData;
coords topLeft = this->topLeft;
int tlx = topLeft.x;
topLeft.x -= width;
coords bottomRight = coords(tlx, topLeft.y + height);
mTileData = new TileData(topLeft, bottomRight, type);
return mTileData;
}
std::tuple<std::string, std::string, std::string> MergeNode::toString(coords tile) const
{
#ifdef DEBUG_MAPSPEW
std::string contents;
if (type == TileType::Empty) {
contents = ".";
} else if (type == TileType::Pickup) {
contents = "x";
} else if (type == TileType::Sprite) {
contents = "~";
} else if (type == TileType::Door) {
contents = "D";
} else {
contents = "#";
}
std::stringstream a, b, c;
coords bottomRight(topLeft.x - width, topLeft.y + height);
if (tile == topLeft) {
a << "/-";
b << "|";
} else if (tile.x == topLeft.x) {
a << "|" << contents;
b << "|";
} else if (tile.y == topLeft.y) {
a << "--";
b << contents;
} else {
a << contents << contents;
b << contents;
}
b << contents;
if (tile.y == topLeft.y) {
if (tile.x == bottomRight.x) {
a << "\\";
b << "|";
} else {
a << "-";
b << contents;
}
} else if (tile.x == bottomRight.x) {
a << "|";
b << "|";
} else {
a << contents;
b << contents;
}
if (tile.x == topLeft.x) {
if (tile.y == bottomRight.y) {
c << "\\-";
} else {
c << "|" << contents;
}
} else if (tile.y == bottomRight.y) {
c << "--";
} else {
c << contents << contents;
}
if (tile == bottomRight) {
c << "/";
} else if (tile.x == bottomRight.x) {
c << "|";
} else if (tile.y == bottomRight.y) {
c << "-";
} else {
c << contents;
}
return std::make_tuple(a.str(), b.str(), c.str());
#else
return std::make_tuple("", "", "");
#endif
}
MergeBuilder::MergeBuilder(Map::Map const& map)
{
for (auto& xnodes : nodes)
std::fill(xnodes.begin(), xnodes.end(), nullptr);
loadMap(map);
performMerges();
}
MergeBuilder::~MergeBuilder()
{
// Use a set because we have duplicate pointers
std::set<MergeNode*> pointrs;
for (auto& xnodes : nodes) {
pointrs.insert(xnodes.begin(), xnodes.end());
}
for (MergeNode* node : pointrs) {
delete node;
}
}
inline
void MergeBuilder::loadMap(Map::Map const& map)
{
const auto& mapNodes = map.nodes;
for (int x = 0; x < xsize; x++) {
const auto& xnodes = mapNodes[x];
for (int y = 0; y < ysize; y++) {
const auto& node = xnodes[y];
// Filter out walls the player can never hit
if (node.wall && !node.visibleWall) {
// Make sure corners are included
byte i = 0;
for (Map::Node *neighbour : node.neighbours) {
if (neighbour != nullptr && neighbour->visibleWall) {
i++;
}
}
if (i < 2)
continue;
}
nodes[x][y] = new MergeNode(node);
}
}
}
inline
int MergeBuilder::verticalMerge(int x, int y)
{
MergeNode *node = nodes[x][y];
int i = 1;
while (y + i < ysize) { // Ensure we stay within bounds
MergeNode *other = nodes[x][y + i];
// Check if the node is the same kind as us. (includes a nullptr check)
if (!node->compatible(other))
break;
// Eat the node
node->height++;
delete other;
nodes[x][y + i] = node;
i++;
}
return i - 1;
}
inline
void MergeBuilder::horizontalMerge(int x, int y)
{
MergeNode *node = nodes[x][y];
int i = 1;
// Consume horizontally
while (x + i < xsize) {
// Make sure that we can consume all x tiles for our height
for (int j = 0; j <= node->height; j++) {
MergeNode *other = nodes[x + i][y + j];
if (!node->compatible(other)) {
return;
}
}
node->width++;
// Eat all nodes for our height
for (int j = 0; j <= node->height; j++) {
delete nodes[x + i][y + j];
nodes[x + i][y + j] = node;
}
i++;
}
}
inline
void MergeBuilder::performMerges()
{
for (int x = 0; x < xsize; x++) {
for (int y = 0; y < ysize; y++) {
MergeNode *node = nodes[x][y];
if (node == nullptr || node->done || notMergable(node->type))
continue;
// Merge vertically first due to how the loop is layed out.
int yadd = verticalMerge(x, y);
horizontalMerge(x, y);
node->done = true;
// yadd lets us skip consumed nodes for the next iteration of y.
y += yadd;
}
}
}
std::vector<std::pair<coords, TileData*>> MergeBuilder::getTileData() const
{
std::vector<std::pair<coords, TileData*>> ret;
ret.reserve(xsize * ysize);
const coord xhalf = Map::Map::halfwidth;
const coord yhalf = Map::Map::halfheight;
// SPAM
#ifdef DEBUG_MAPSPEW
DebugOutput();
#endif
for (coord x = 0; x < xsize; x++) {
for (coord y = 0; y < ysize; y++) {
MergeNode* node = nodes[x][y];
if (node == nullptr)
continue;
coord nodeX = -(x - xhalf); // I don't know why this is negative, but it is.
coord nodeY = y - yhalf;
ret.emplace_back(coords(nodeX, nodeY), node->toTile());
}
}
return ret;
}
void MergeBuilder::DebugOutput() const
{
#ifdef DEBUG_MAPSPEW
const coord xhalf = Map::Map::halfwidth;
const coord yhalf = Map::Map::halfheight;
coord xcoord, ycoord;
std::cout << " vim: nowrap listchars=" << std::endl;
std::cout.setf(std::ios_base::right);
std::cout.fill(' ');
std::cout.width(3);
std::cout << " ";
std::ostringstream bluh;
bluh << " ";
for (byte x = 0; x < xsize; ++x) {
std::cout.width(3);
std::cout << -(x - xhalf);
bluh << "***";
}
std::cout << std::endl;
std::cout << bluh.str() << std::endl;
for (byte y = 0; y < ysize; ++y) {
ycoord = (y - yhalf);
std::stringstream a, b, c;
a << " *";
b.width(3);
b << ycoord << '*';
c << " *";
for (byte x = 0; x < xsize; ++x) {
xcoord = -(x - xhalf);
MergeNode *node = nodes[x][y];
if (node == nullptr) {
a << " ";
b << " ";
c << " ";
continue;
}
auto lines = node->toString(coords(xcoord, ycoord));
a << std::get<0>(lines);
b << std::get<1>(lines);
c << std::get<2>(lines);
}
std::cout << a.str() << std::endl;
std::cout << b.str() << std::endl;
std::cout << c.str() << std::endl;
}
#endif
}
<commit_msg>Remove pickups from the collision map<commit_after>#include <set>
#include "Game/Physics/MergeBuilder.h"
#ifdef DEBUG
//#define DEBUG_MAPSPEW
#endif
#ifdef DEBUG_MAPSPEW
#include <iostream>
#include <sstream>
#endif
using namespace Wulf;
using namespace Wulf::Physics;
bool notMergable(TileType type)
{
return type == TileType::Door || type == TileType::Pickup;
}
MergeNode::MergeNode(Map::Node const& node)
: topLeft(node.x, node.y), type(NodeToTile(node))
, width(0), height(0)
, done(false)
, mTileData(nullptr)
{
// For us, pickups don't exist
if (type == TileType::Pickup)
type = TileType::Empty;
}
bool MergeNode::compatible(MergeNode const* other) const
{
if (other == nullptr || other->done || other->type != type || notMergable(other->type))
return false;
return true;
}
// This returns the tiledata for the merged mass.
// It is safe to call multiple times as it only returns one TileData.
TileData* MergeNode::toTile()
{
if (mTileData != nullptr)
return mTileData;
coords topLeft = this->topLeft;
int tlx = topLeft.x;
topLeft.x -= width;
coords bottomRight = coords(tlx, topLeft.y + height);
mTileData = new TileData(topLeft, bottomRight, type);
return mTileData;
}
std::tuple<std::string, std::string, std::string> MergeNode::toString(coords tile) const
{
#ifdef DEBUG_MAPSPEW
std::string contents;
if (type == TileType::Empty) {
contents = ".";
} else if (type == TileType::Pickup) {
contents = "x";
} else if (type == TileType::Sprite) {
contents = "~";
} else if (type == TileType::Door) {
contents = "D";
} else {
contents = "#";
}
std::stringstream a, b, c;
coords bottomRight(topLeft.x - width, topLeft.y + height);
if (tile == topLeft) {
a << "/-";
b << "|";
} else if (tile.x == topLeft.x) {
a << "|" << contents;
b << "|";
} else if (tile.y == topLeft.y) {
a << "--";
b << contents;
} else {
a << contents << contents;
b << contents;
}
b << contents;
if (tile.y == topLeft.y) {
if (tile.x == bottomRight.x) {
a << "\\";
b << "|";
} else {
a << "-";
b << contents;
}
} else if (tile.x == bottomRight.x) {
a << "|";
b << "|";
} else {
a << contents;
b << contents;
}
if (tile.x == topLeft.x) {
if (tile.y == bottomRight.y) {
c << "\\-";
} else {
c << "|" << contents;
}
} else if (tile.y == bottomRight.y) {
c << "--";
} else {
c << contents << contents;
}
if (tile == bottomRight) {
c << "/";
} else if (tile.x == bottomRight.x) {
c << "|";
} else if (tile.y == bottomRight.y) {
c << "-";
} else {
c << contents;
}
return std::make_tuple(a.str(), b.str(), c.str());
#else
return std::make_tuple("", "", "");
#endif
}
MergeBuilder::MergeBuilder(Map::Map const& map)
{
for (auto& xnodes : nodes)
std::fill(xnodes.begin(), xnodes.end(), nullptr);
loadMap(map);
performMerges();
}
MergeBuilder::~MergeBuilder()
{
// Use a set because we have duplicate pointers
std::set<MergeNode*> pointrs;
for (auto& xnodes : nodes) {
pointrs.insert(xnodes.begin(), xnodes.end());
}
for (MergeNode* node : pointrs) {
delete node;
}
}
inline
void MergeBuilder::loadMap(Map::Map const& map)
{
const auto& mapNodes = map.nodes;
for (int x = 0; x < xsize; x++) {
const auto& xnodes = mapNodes[x];
for (int y = 0; y < ysize; y++) {
const auto& node = xnodes[y];
// Filter out walls the player can never hit
if (node.wall && !node.visibleWall) {
// Make sure corners are included
byte i = 0;
for (Map::Node *neighbour : node.neighbours) {
if (neighbour != nullptr && neighbour->visibleWall) {
i++;
}
}
if (i < 2)
continue;
}
nodes[x][y] = new MergeNode(node);
}
}
}
inline
int MergeBuilder::verticalMerge(int x, int y)
{
MergeNode *node = nodes[x][y];
int i = 1;
while (y + i < ysize) { // Ensure we stay within bounds
MergeNode *other = nodes[x][y + i];
// Check if the node is the same kind as us. (includes a nullptr check)
if (!node->compatible(other))
break;
// Eat the node
node->height++;
delete other;
nodes[x][y + i] = node;
i++;
}
return i - 1;
}
inline
void MergeBuilder::horizontalMerge(int x, int y)
{
MergeNode *node = nodes[x][y];
int i = 1;
// Consume horizontally
while (x + i < xsize) {
// Make sure that we can consume all x tiles for our height
for (int j = 0; j <= node->height; j++) {
MergeNode *other = nodes[x + i][y + j];
if (!node->compatible(other)) {
return;
}
}
node->width++;
// Eat all nodes for our height
for (int j = 0; j <= node->height; j++) {
delete nodes[x + i][y + j];
nodes[x + i][y + j] = node;
}
i++;
}
}
inline
void MergeBuilder::performMerges()
{
for (int x = 0; x < xsize; x++) {
for (int y = 0; y < ysize; y++) {
MergeNode *node = nodes[x][y];
if (node == nullptr || node->done || notMergable(node->type))
continue;
// Merge vertically first due to how the loop is layed out.
int yadd = verticalMerge(x, y);
horizontalMerge(x, y);
node->done = true;
// yadd lets us skip consumed nodes for the next iteration of y.
y += yadd;
}
}
}
std::vector<std::pair<coords, TileData*>> MergeBuilder::getTileData() const
{
std::vector<std::pair<coords, TileData*>> ret;
ret.reserve(xsize * ysize);
const coord xhalf = Map::Map::halfwidth;
const coord yhalf = Map::Map::halfheight;
// SPAM
#ifdef DEBUG_MAPSPEW
DebugOutput();
#endif
for (coord x = 0; x < xsize; x++) {
for (coord y = 0; y < ysize; y++) {
MergeNode* node = nodes[x][y];
if (node == nullptr)
continue;
coord nodeX = -(x - xhalf); // I don't know why this is negative, but it is.
coord nodeY = y - yhalf;
ret.emplace_back(coords(nodeX, nodeY), node->toTile());
}
}
return ret;
}
void MergeBuilder::DebugOutput() const
{
#ifdef DEBUG_MAPSPEW
const coord xhalf = Map::Map::halfwidth;
const coord yhalf = Map::Map::halfheight;
coord xcoord, ycoord;
std::cout << " vim: nowrap listchars=" << std::endl;
std::cout.setf(std::ios_base::right);
std::cout.fill(' ');
std::cout.width(3);
std::cout << " ";
std::ostringstream bluh;
bluh << " ";
for (byte x = 0; x < xsize; ++x) {
std::cout.width(3);
std::cout << -(x - xhalf);
bluh << "***";
}
std::cout << std::endl;
std::cout << bluh.str() << std::endl;
for (byte y = 0; y < ysize; ++y) {
ycoord = (y - yhalf);
std::stringstream a, b, c;
a << " *";
b.width(3);
b << ycoord << '*';
c << " *";
for (byte x = 0; x < xsize; ++x) {
xcoord = -(x - xhalf);
MergeNode *node = nodes[x][y];
if (node == nullptr) {
a << " ";
b << " ";
c << " ";
continue;
}
auto lines = node->toString(coords(xcoord, ycoord));
a << std::get<0>(lines);
b << std::get<1>(lines);
c << std::get<2>(lines);
}
std::cout << a.str() << std::endl;
std::cout << b.str() << std::endl;
std::cout << c.str() << std::endl;
}
#endif
}
<|endoftext|> |
<commit_before>#include <stdint.h>
#include <iostream>
#include <stdexcept>
#include "allowedtypes.hpp"
#include "bin_file.hpp"
#include "renderer.hpp"
#include "statistics.hpp"
#include "string_util.hpp"
using allowed::AllowedTypes;
using std::cout;
using std::endl;
using std::runtime_error;
using std::size_t;
using std::string;
using std::stringstream;
using std::vector;
namespace render {
namespace { // anonymous namespace
static const string EOL("\n");
AllowedTypes getTypes()
{
AllowedTypes types;
types.append("char");
types.append("uint8");
types.append("uint16");
types.append("uint32");
types.append("uint64");
types.append("int8");
types.append("int16");
types.append("int32");
types.append("int64");
types.append("float32");
types.append("float64");
return types;
}
} // anonymous namespace
Renderer::Renderer(): m_showLines(false), m_quiet(false), m_numItemsPerLine(1)
{
this->m_dataDescr = new vector<string>();
this->types = getTypes();
}
Renderer::~Renderer()
{
if (this->m_dataDescr != NULL)
delete this->m_dataDescr;
this->m_dataDescr = NULL;
}
void Renderer::setDataDescr(const std::string & descr)
{
if (! this->types.has(descr)) {
stringstream msg;
msg << "Encountered unknown type \"" << descr << "\". Allowed types are: "
<< this->types;
throw runtime_error(msg.str());
}
this->m_dataDescr->clear();
this->m_dataDescr->push_back(descr);
}
void Renderer::showLines(const bool showLines)
{
this->m_showLines = showLines;
}
bool Renderer::showLines() const
{
return this->m_showLines;
}
void Renderer::numItemsPerLine(const std::size_t numItems)
{
if (numItems > 0)
m_numItemsPerLine = numItems;
else
throw std::runtime_error("Tried to set number of items per line to less than 1");
}
std::size_t Renderer::numItemsPerLine()
{
return m_numItemsPerLine;
}
void Renderer::quiet(const bool value)
{
m_quiet = value;
}
bool Renderer::quiet()
{
return m_quiet;
}
template <typename NumT>
void Renderer::innerShowData(BinFile &file, size_t offset, size_t length)
{
// this is used for printing line numbers
size_t myOffset = 0;
if ((offset % sizeof(NumT)) == 0)
myOffset = offset / sizeof(NumT);
Statistics<NumT> stats; // object for generating statistics
vector<NumT> data;
size_t totalItems = this->numItemsPerLine() - 1;
size_t items = 0;
file.read(data, length);
if (!(data.empty())) {
stats.parseData(data);
if (!m_quiet)
{
for (size_t i = 0; i < data.size(); i++) {
if (this->m_showLines)
cout << (myOffset + i + 1) << " "; // start counting with one
cout << toStr(data[i]);
if (items < totalItems)
{
cout << "\t";
items += 1;
}
else
{
cout << EOL;
items = 0;
}
}
}
}
cout << stats << endl;
}
/// Special version for strings
template <>
void Renderer::innerShowData<char>(BinFile &file, size_t offset, size_t length)
{
StringStatistics stats;
stringstream data;
file.read(data, length);
if (!m_quiet)
cout << data.str();
stats.parseData(data);
cout << stats << endl;
}
void Renderer::showData(BinFile &file, size_t offset, size_t length)
{
// TODO have debug mode for this print statement
// cout << "Renderer.showData(file, " << offset << ", " << length << ")" << endl;
file.seek(offset);
if (this->m_dataDescr->size() != 1)
throw runtime_error("Do not know how to deal with multi-type data");
string descr = this->m_dataDescr->at(0);
// TODO calculate information on the fly rather than reading in the whole file
// TODO there was the ability to show integrated values
// TODO ? there was the ability to filter out tof error events
if (descr == "char")
innerShowData<char>(file, offset, length);
else if (descr == "uint8")
innerShowData<uint8_t>(file, offset, length);
else if (descr == "int8")
innerShowData<int8_t>(file, offset, length);
else if (descr == "uint16")
innerShowData<uint16_t>(file, offset, length);
else if (descr == "int16")
innerShowData<int16_t>(file, offset, length);
else if (descr == "uint32")
innerShowData<uint32_t>(file, offset, length);
else if (descr == "int32")
innerShowData<int32_t>(file, offset, length);
else if (descr == "uint64")
innerShowData<uint64_t>(file, offset, length);
else if (descr == "int64")
innerShowData<int64_t>(file, offset, length);
else if (descr == "float32" || descr == "float")
innerShowData<float>(file, offset, length);
else if (descr == "float64" || descr == "double")
innerShowData<double>(file, offset, length);
else
throw runtime_error("The code should have never gotten to this place");
}
const std::string getKnownDataDescr()
{
stringstream msg;
msg << getTypes();
return msg.str();
}
} // namespace render
<commit_msg>Refs #15. Pointing out unused variable.<commit_after>#include <stdint.h>
#include <iostream>
#include <stdexcept>
#include "allowedtypes.hpp"
#include "bin_file.hpp"
#include "renderer.hpp"
#include "statistics.hpp"
#include "string_util.hpp"
using allowed::AllowedTypes;
using std::cout;
using std::endl;
using std::runtime_error;
using std::size_t;
using std::string;
using std::stringstream;
using std::vector;
namespace render {
namespace { // anonymous namespace
static const string EOL("\n");
AllowedTypes getTypes()
{
AllowedTypes types;
types.append("char");
types.append("uint8");
types.append("uint16");
types.append("uint32");
types.append("uint64");
types.append("int8");
types.append("int16");
types.append("int32");
types.append("int64");
types.append("float32");
types.append("float64");
return types;
}
} // anonymous namespace
Renderer::Renderer(): m_showLines(false), m_quiet(false), m_numItemsPerLine(1)
{
this->m_dataDescr = new vector<string>();
this->types = getTypes();
}
Renderer::~Renderer()
{
if (this->m_dataDescr != NULL)
delete this->m_dataDescr;
this->m_dataDescr = NULL;
}
void Renderer::setDataDescr(const std::string & descr)
{
if (! this->types.has(descr)) {
stringstream msg;
msg << "Encountered unknown type \"" << descr << "\". Allowed types are: "
<< this->types;
throw runtime_error(msg.str());
}
this->m_dataDescr->clear();
this->m_dataDescr->push_back(descr);
}
void Renderer::showLines(const bool showLines)
{
this->m_showLines = showLines;
}
bool Renderer::showLines() const
{
return this->m_showLines;
}
void Renderer::numItemsPerLine(const std::size_t numItems)
{
if (numItems > 0)
m_numItemsPerLine = numItems;
else
throw std::runtime_error("Tried to set number of items per line to less than 1");
}
std::size_t Renderer::numItemsPerLine()
{
return m_numItemsPerLine;
}
void Renderer::quiet(const bool value)
{
m_quiet = value;
}
bool Renderer::quiet()
{
return m_quiet;
}
template <typename NumT>
void Renderer::innerShowData(BinFile &file, size_t offset, size_t length)
{
// this is used for printing line numbers
size_t myOffset = 0;
if ((offset % sizeof(NumT)) == 0)
myOffset = offset / sizeof(NumT);
Statistics<NumT> stats; // object for generating statistics
vector<NumT> data;
size_t totalItems = this->numItemsPerLine() - 1;
size_t items = 0;
file.read(data, length);
if (!(data.empty())) {
stats.parseData(data);
if (!m_quiet)
{
for (size_t i = 0; i < data.size(); i++) {
if (this->m_showLines)
cout << (myOffset + i + 1) << " "; // start counting with one
cout << toStr(data[i]);
if (items < totalItems)
{
cout << "\t";
items += 1;
}
else
{
cout << EOL;
items = 0;
}
}
}
}
cout << stats << endl;
}
/// Special version for strings
template <>
void Renderer::innerShowData<char>(BinFile &file, size_t offset, size_t length)
{
//offset is required by interface but not needed
(void)offset;
StringStatistics stats;
stringstream data;
file.read(data, length);
if (!m_quiet)
cout << data.str();
stats.parseData(data);
cout << stats << endl;
}
void Renderer::showData(BinFile &file, size_t offset, size_t length)
{
// TODO have debug mode for this print statement
// cout << "Renderer.showData(file, " << offset << ", " << length << ")" << endl;
file.seek(offset);
if (this->m_dataDescr->size() != 1)
throw runtime_error("Do not know how to deal with multi-type data");
string descr = this->m_dataDescr->at(0);
// TODO calculate information on the fly rather than reading in the whole file
// TODO there was the ability to show integrated values
// TODO ? there was the ability to filter out tof error events
if (descr == "char")
innerShowData<char>(file, offset, length);
else if (descr == "uint8")
innerShowData<uint8_t>(file, offset, length);
else if (descr == "int8")
innerShowData<int8_t>(file, offset, length);
else if (descr == "uint16")
innerShowData<uint16_t>(file, offset, length);
else if (descr == "int16")
innerShowData<int16_t>(file, offset, length);
else if (descr == "uint32")
innerShowData<uint32_t>(file, offset, length);
else if (descr == "int32")
innerShowData<int32_t>(file, offset, length);
else if (descr == "uint64")
innerShowData<uint64_t>(file, offset, length);
else if (descr == "int64")
innerShowData<int64_t>(file, offset, length);
else if (descr == "float32" || descr == "float")
innerShowData<float>(file, offset, length);
else if (descr == "float64" || descr == "double")
innerShowData<double>(file, offset, length);
else
throw runtime_error("The code should have never gotten to this place");
}
const std::string getKnownDataDescr()
{
stringstream msg;
msg << getTypes();
return msg.str();
}
} // namespace render
<|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.
*/
/*
* Modified by Cloudius Systems
* Copyright 2015 Cloudius Systems
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <memory>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <boost/range/adaptor/map.hpp>
#include <core/future.hh>
#include <core/sharded.hh>
#include "commitlog.hh"
#include "commitlog_replayer.hh"
#include "database.hh"
#include "sstables/sstables.hh"
#include "db/system_keyspace.hh"
#include "db/serializer.hh"
#include "cql3/query_processor.hh"
#include "log.hh"
#include "converting_mutation_partition_applier.hh"
#include "schema_registry.hh"
#include "commitlog_entry.hh"
static logging::logger logger("commitlog_replayer");
class db::commitlog_replayer::impl {
std::unordered_map<table_schema_version, column_mapping> _column_mappings;
public:
impl(seastar::sharded<cql3::query_processor>& db);
future<> init();
struct stats {
uint64_t invalid_mutations = 0;
uint64_t skipped_mutations = 0;
uint64_t applied_mutations = 0;
uint64_t corrupt_bytes = 0;
stats& operator+=(const stats& s) {
invalid_mutations += s.invalid_mutations;
skipped_mutations += s.skipped_mutations;
applied_mutations += s.applied_mutations;
corrupt_bytes += s.corrupt_bytes;
return *this;
}
stats operator+(const stats& s) const {
stats tmp = *this;
tmp += s;
return tmp;
}
};
future<> process(stats*, temporary_buffer<char> buf, replay_position rp);
future<stats> recover(sstring file);
typedef std::unordered_map<utils::UUID, replay_position> rp_map;
typedef std::unordered_map<unsigned, rp_map> shard_rpm_map;
typedef std::unordered_map<unsigned, replay_position> shard_rp_map;
seastar::sharded<cql3::query_processor>&
_qp;
shard_rpm_map
_rpm;
shard_rp_map
_min_pos;
};
db::commitlog_replayer::impl::impl(seastar::sharded<cql3::query_processor>& qp)
: _qp(qp)
{}
future<> db::commitlog_replayer::impl::init() {
return _qp.map_reduce([this](shard_rpm_map map) {
for (auto& p1 : map) {
for (auto& p2 : p1.second) {
auto& pp = _rpm[p1.first][p2.first];
pp = std::max(pp, p2.second);
auto& min = _min_pos[p1.first];
min = (min == replay_position()) ? p2.second : std::min(p2.second, min);
}
}
}, [this](cql3::query_processor& qp) {
return do_with(shard_rpm_map{}, [this, &qp](shard_rpm_map& map) {
return parallel_for_each(qp.db().local().get_column_families(), [&map, &qp](auto& cfp) {
auto uuid = cfp.first;
for (auto& sst : *cfp.second->get_sstables() | boost::adaptors::map_values) {
try {
auto p = sst->get_stats_metadata().position;
logger.trace("sstable {} -> rp {}", sst->get_filename(), p);
if (p != replay_position()) {
auto& pp = map[p.shard_id()][uuid];
pp = std::max(pp, p);
}
} catch (...) {
logger.warn("Could not read sstable metadata {}", std::current_exception());
}
}
// We do this on each cpu, for each CF, which technically is a little wasteful, but the values are
// cached, this is only startup, and it makes the code easier.
// Get all truncation records for the CF and initialize max rps if
// present. Cannot do this on demand, as there may be no sstables to
// mark the CF as "needed".
return db::system_keyspace::get_truncated_position(uuid).then([&map, &uuid](std::vector<db::replay_position> tpps) {
for (auto& p : tpps) {
logger.trace("CF {} truncated at {}", uuid, p);
auto& pp = map[p.shard_id()][uuid];
pp = std::max(pp, p);
}
});
}).then([&map] {
return make_ready_future<shard_rpm_map>(map);
});
});
}).finally([this] {
for (auto&p : _min_pos) {
logger.debug("minimum position for shard {}: {}", p.first, p.second);
}
for (auto&p1 : _rpm) {
for (auto& p2 : p1.second) {
logger.debug("replay position for shard/uuid {}/{}: {}", p1.first, p2.first, p2.second);
}
}
});
}
future<db::commitlog_replayer::impl::stats>
db::commitlog_replayer::impl::recover(sstring file) {
replay_position rp{commitlog::descriptor(file)};
auto gp = _min_pos[rp.shard_id()];
if (rp.id < gp.id) {
logger.debug("skipping replay of fully-flushed {}", file);
return make_ready_future<stats>();
}
position_type p = 0;
if (rp.id == gp.id) {
p = gp.pos;
}
auto s = make_lw_shared<stats>();
return db::commitlog::read_log_file(file,
std::bind(&impl::process, this, s.get(), std::placeholders::_1,
std::placeholders::_2), p).then([](auto s) {
auto f = s->done();
return f.finally([s = std::move(s)] {});
}).then_wrapped([s](future<> f) {
try {
f.get();
} catch (commitlog::segment_data_corruption_error& e) {
s->corrupt_bytes += e.bytes();
} catch (...) {
throw;
}
return make_ready_future<stats>(*s);
});
}
future<> db::commitlog_replayer::impl::process(stats* s, temporary_buffer<char> buf, replay_position rp) {
try {
commitlog_entry_reader cer(buf);
auto& fm = cer.mutation();
auto cm_it = _column_mappings.find(fm.schema_version());
if (cm_it == _column_mappings.end()) {
if (!cer.get_column_mapping()) {
throw std::runtime_error(sprint("unknown schema version {}", fm.schema_version()));
}
logger.debug("new schema version {} in entry {}", fm.schema_version(), rp);
cm_it = _column_mappings.emplace(fm.schema_version(), *cer.get_column_mapping()).first;
}
auto shard_id = rp.shard_id();
if (rp < _min_pos[shard_id]) {
logger.trace("entry {} is less than global min position. skipping", rp);
s->skipped_mutations++;
return make_ready_future<>();
}
auto uuid = fm.column_family_id();
auto& map = _rpm[shard_id];
auto i = map.find(uuid);
if (i != map.end() && rp <= i->second) {
logger.trace("entry {} at {} is younger than recorded replay position {}. skipping", fm.column_family_id(), rp, i->second);
s->skipped_mutations++;
return make_ready_future<>();
}
auto shard = _qp.local().db().local().shard_of(fm);
return _qp.local().db().invoke_on(shard, [this, cer = std::move(cer), cm_it, rp, shard, s] (database& db) -> future<> {
auto& fm = cer.mutation();
// TODO: might need better verification that the deserialized mutation
// is schema compatible. My guess is that just applying the mutation
// will not do this.
auto& cf = db.find_column_family(fm.column_family_id());
if (logger.is_enabled(logging::log_level::debug)) {
logger.debug("replaying at {} v={} {}:{} at {}", fm.column_family_id(), fm.schema_version(),
cf.schema()->ks_name(), cf.schema()->cf_name(), rp);
}
// Removed forwarding "new" RP. Instead give none/empty.
// This is what origin does, and it should be fine.
// The end result should be that once sstables are flushed out
// their "replay_position" attribute will be empty, which is
// lower than anything the new session will produce.
if (cf.schema()->version() != fm.schema_version()) {
const column_mapping& cm = cm_it->second;
mutation m(fm.decorated_key(*cf.schema()), cf.schema());
converting_mutation_partition_applier v(cm, *cf.schema(), m.partition());
fm.partition().accept(cm, v);
cf.apply(std::move(m));
} else {
cf.apply(fm, cf.schema());
}
s->applied_mutations++;
return make_ready_future<>();
}).handle_exception([s](auto ep) {
s->invalid_mutations++;
// TODO: write mutation to file like origin.
logger.warn("error replaying: {}", ep);
});
} catch (no_such_column_family&) {
// No such CF now? Origin just ignores this.
} catch (...) {
s->invalid_mutations++;
// TODO: write mutation to file like origin.
logger.warn("error replaying: {}", std::current_exception());
}
return make_ready_future<>();
}
db::commitlog_replayer::commitlog_replayer(seastar::sharded<cql3::query_processor>& qp)
: _impl(std::make_unique<impl>(qp))
{}
db::commitlog_replayer::commitlog_replayer(commitlog_replayer&& r) noexcept
: _impl(std::move(r._impl))
{}
db::commitlog_replayer::~commitlog_replayer()
{}
future<db::commitlog_replayer> db::commitlog_replayer::create_replayer(seastar::sharded<cql3::query_processor>& qp) {
return do_with(commitlog_replayer(qp), [](auto&& rp) {
auto f = rp._impl->init();
return f.then([rp = std::move(rp)]() mutable {
return make_ready_future<commitlog_replayer>(std::move(rp));
});
});
}
future<> db::commitlog_replayer::recover(std::vector<sstring> files) {
logger.info("Replaying {}", join(", ", files));
return map_reduce(files, [this](auto f) {
logger.debug("Replaying {}", f);
return _impl->recover(f).then([f](impl::stats stats) {
if (stats.corrupt_bytes != 0) {
logger.warn("Corrupted file: {}. {} bytes skipped.", f, stats.corrupt_bytes);
}
logger.debug("Log replay of {} complete, {} replayed mutations ({} invalid, {} skipped)"
, f
, stats.applied_mutations
, stats.invalid_mutations
, stats.skipped_mutations
);
return make_ready_future<impl::stats>(stats);
}).handle_exception([f](auto ep) -> future<impl::stats> {
logger.error("Error recovering {}: {}", f, ep);
try {
std::rethrow_exception(ep);
} catch (std::invalid_argument&) {
logger.error("Scylla cannot process {}. Make sure to fully flush all Cassandra commit log files to sstable before migrating.");
throw;
} catch (...) {
throw;
}
});
}, impl::stats(), std::plus<impl::stats>()).then([](impl::stats totals) {
logger.info("Log replay complete, {} replayed mutations ({} invalid, {} skipped)"
, totals.applied_mutations
, totals.invalid_mutations
, totals.skipped_mutations
);
});
}
future<> db::commitlog_replayer::recover(sstring f) {
return recover(std::vector<sstring>{ f });
}
<commit_msg>db/commitlog: Fix debug log format string in commitlog_replayer::recover()<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.
*/
/*
* Modified by Cloudius Systems
* Copyright 2015 Cloudius Systems
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <memory>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <boost/range/adaptor/map.hpp>
#include <core/future.hh>
#include <core/sharded.hh>
#include "commitlog.hh"
#include "commitlog_replayer.hh"
#include "database.hh"
#include "sstables/sstables.hh"
#include "db/system_keyspace.hh"
#include "db/serializer.hh"
#include "cql3/query_processor.hh"
#include "log.hh"
#include "converting_mutation_partition_applier.hh"
#include "schema_registry.hh"
#include "commitlog_entry.hh"
static logging::logger logger("commitlog_replayer");
class db::commitlog_replayer::impl {
std::unordered_map<table_schema_version, column_mapping> _column_mappings;
public:
impl(seastar::sharded<cql3::query_processor>& db);
future<> init();
struct stats {
uint64_t invalid_mutations = 0;
uint64_t skipped_mutations = 0;
uint64_t applied_mutations = 0;
uint64_t corrupt_bytes = 0;
stats& operator+=(const stats& s) {
invalid_mutations += s.invalid_mutations;
skipped_mutations += s.skipped_mutations;
applied_mutations += s.applied_mutations;
corrupt_bytes += s.corrupt_bytes;
return *this;
}
stats operator+(const stats& s) const {
stats tmp = *this;
tmp += s;
return tmp;
}
};
future<> process(stats*, temporary_buffer<char> buf, replay_position rp);
future<stats> recover(sstring file);
typedef std::unordered_map<utils::UUID, replay_position> rp_map;
typedef std::unordered_map<unsigned, rp_map> shard_rpm_map;
typedef std::unordered_map<unsigned, replay_position> shard_rp_map;
seastar::sharded<cql3::query_processor>&
_qp;
shard_rpm_map
_rpm;
shard_rp_map
_min_pos;
};
db::commitlog_replayer::impl::impl(seastar::sharded<cql3::query_processor>& qp)
: _qp(qp)
{}
future<> db::commitlog_replayer::impl::init() {
return _qp.map_reduce([this](shard_rpm_map map) {
for (auto& p1 : map) {
for (auto& p2 : p1.second) {
auto& pp = _rpm[p1.first][p2.first];
pp = std::max(pp, p2.second);
auto& min = _min_pos[p1.first];
min = (min == replay_position()) ? p2.second : std::min(p2.second, min);
}
}
}, [this](cql3::query_processor& qp) {
return do_with(shard_rpm_map{}, [this, &qp](shard_rpm_map& map) {
return parallel_for_each(qp.db().local().get_column_families(), [&map, &qp](auto& cfp) {
auto uuid = cfp.first;
for (auto& sst : *cfp.second->get_sstables() | boost::adaptors::map_values) {
try {
auto p = sst->get_stats_metadata().position;
logger.trace("sstable {} -> rp {}", sst->get_filename(), p);
if (p != replay_position()) {
auto& pp = map[p.shard_id()][uuid];
pp = std::max(pp, p);
}
} catch (...) {
logger.warn("Could not read sstable metadata {}", std::current_exception());
}
}
// We do this on each cpu, for each CF, which technically is a little wasteful, but the values are
// cached, this is only startup, and it makes the code easier.
// Get all truncation records for the CF and initialize max rps if
// present. Cannot do this on demand, as there may be no sstables to
// mark the CF as "needed".
return db::system_keyspace::get_truncated_position(uuid).then([&map, &uuid](std::vector<db::replay_position> tpps) {
for (auto& p : tpps) {
logger.trace("CF {} truncated at {}", uuid, p);
auto& pp = map[p.shard_id()][uuid];
pp = std::max(pp, p);
}
});
}).then([&map] {
return make_ready_future<shard_rpm_map>(map);
});
});
}).finally([this] {
for (auto&p : _min_pos) {
logger.debug("minimum position for shard {}: {}", p.first, p.second);
}
for (auto&p1 : _rpm) {
for (auto& p2 : p1.second) {
logger.debug("replay position for shard/uuid {}/{}: {}", p1.first, p2.first, p2.second);
}
}
});
}
future<db::commitlog_replayer::impl::stats>
db::commitlog_replayer::impl::recover(sstring file) {
replay_position rp{commitlog::descriptor(file)};
auto gp = _min_pos[rp.shard_id()];
if (rp.id < gp.id) {
logger.debug("skipping replay of fully-flushed {}", file);
return make_ready_future<stats>();
}
position_type p = 0;
if (rp.id == gp.id) {
p = gp.pos;
}
auto s = make_lw_shared<stats>();
return db::commitlog::read_log_file(file,
std::bind(&impl::process, this, s.get(), std::placeholders::_1,
std::placeholders::_2), p).then([](auto s) {
auto f = s->done();
return f.finally([s = std::move(s)] {});
}).then_wrapped([s](future<> f) {
try {
f.get();
} catch (commitlog::segment_data_corruption_error& e) {
s->corrupt_bytes += e.bytes();
} catch (...) {
throw;
}
return make_ready_future<stats>(*s);
});
}
future<> db::commitlog_replayer::impl::process(stats* s, temporary_buffer<char> buf, replay_position rp) {
try {
commitlog_entry_reader cer(buf);
auto& fm = cer.mutation();
auto cm_it = _column_mappings.find(fm.schema_version());
if (cm_it == _column_mappings.end()) {
if (!cer.get_column_mapping()) {
throw std::runtime_error(sprint("unknown schema version {}", fm.schema_version()));
}
logger.debug("new schema version {} in entry {}", fm.schema_version(), rp);
cm_it = _column_mappings.emplace(fm.schema_version(), *cer.get_column_mapping()).first;
}
auto shard_id = rp.shard_id();
if (rp < _min_pos[shard_id]) {
logger.trace("entry {} is less than global min position. skipping", rp);
s->skipped_mutations++;
return make_ready_future<>();
}
auto uuid = fm.column_family_id();
auto& map = _rpm[shard_id];
auto i = map.find(uuid);
if (i != map.end() && rp <= i->second) {
logger.trace("entry {} at {} is younger than recorded replay position {}. skipping", fm.column_family_id(), rp, i->second);
s->skipped_mutations++;
return make_ready_future<>();
}
auto shard = _qp.local().db().local().shard_of(fm);
return _qp.local().db().invoke_on(shard, [this, cer = std::move(cer), cm_it, rp, shard, s] (database& db) -> future<> {
auto& fm = cer.mutation();
// TODO: might need better verification that the deserialized mutation
// is schema compatible. My guess is that just applying the mutation
// will not do this.
auto& cf = db.find_column_family(fm.column_family_id());
if (logger.is_enabled(logging::log_level::debug)) {
logger.debug("replaying at {} v={} {}:{} at {}", fm.column_family_id(), fm.schema_version(),
cf.schema()->ks_name(), cf.schema()->cf_name(), rp);
}
// Removed forwarding "new" RP. Instead give none/empty.
// This is what origin does, and it should be fine.
// The end result should be that once sstables are flushed out
// their "replay_position" attribute will be empty, which is
// lower than anything the new session will produce.
if (cf.schema()->version() != fm.schema_version()) {
const column_mapping& cm = cm_it->second;
mutation m(fm.decorated_key(*cf.schema()), cf.schema());
converting_mutation_partition_applier v(cm, *cf.schema(), m.partition());
fm.partition().accept(cm, v);
cf.apply(std::move(m));
} else {
cf.apply(fm, cf.schema());
}
s->applied_mutations++;
return make_ready_future<>();
}).handle_exception([s](auto ep) {
s->invalid_mutations++;
// TODO: write mutation to file like origin.
logger.warn("error replaying: {}", ep);
});
} catch (no_such_column_family&) {
// No such CF now? Origin just ignores this.
} catch (...) {
s->invalid_mutations++;
// TODO: write mutation to file like origin.
logger.warn("error replaying: {}", std::current_exception());
}
return make_ready_future<>();
}
db::commitlog_replayer::commitlog_replayer(seastar::sharded<cql3::query_processor>& qp)
: _impl(std::make_unique<impl>(qp))
{}
db::commitlog_replayer::commitlog_replayer(commitlog_replayer&& r) noexcept
: _impl(std::move(r._impl))
{}
db::commitlog_replayer::~commitlog_replayer()
{}
future<db::commitlog_replayer> db::commitlog_replayer::create_replayer(seastar::sharded<cql3::query_processor>& qp) {
return do_with(commitlog_replayer(qp), [](auto&& rp) {
auto f = rp._impl->init();
return f.then([rp = std::move(rp)]() mutable {
return make_ready_future<commitlog_replayer>(std::move(rp));
});
});
}
future<> db::commitlog_replayer::recover(std::vector<sstring> files) {
logger.info("Replaying {}", join(", ", files));
return map_reduce(files, [this](auto f) {
logger.debug("Replaying {}", f);
return _impl->recover(f).then([f](impl::stats stats) {
if (stats.corrupt_bytes != 0) {
logger.warn("Corrupted file: {}. {} bytes skipped.", f, stats.corrupt_bytes);
}
logger.debug("Log replay of {} complete, {} replayed mutations ({} invalid, {} skipped)"
, f
, stats.applied_mutations
, stats.invalid_mutations
, stats.skipped_mutations
);
return make_ready_future<impl::stats>(stats);
}).handle_exception([f](auto ep) -> future<impl::stats> {
logger.error("Error recovering {}: {}", f, ep);
try {
std::rethrow_exception(ep);
} catch (std::invalid_argument&) {
logger.error("Scylla cannot process {}. Make sure to fully flush all Cassandra commit log files to sstable before migrating.", f);
throw;
} catch (...) {
throw;
}
});
}, impl::stats(), std::plus<impl::stats>()).then([](impl::stats totals) {
logger.info("Log replay complete, {} replayed mutations ({} invalid, {} skipped)"
, totals.applied_mutations
, totals.invalid_mutations
, totals.skipped_mutations
);
});
}
future<> db::commitlog_replayer::recover(sstring f) {
return recover(std::vector<sstring>{ f });
}
<|endoftext|> |
<commit_before>//===--- OwnershipModelEliminator.cpp - Eliminate SILOwnership Instr. -----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// This file contains a small pass that lowers SIL ownership instructions to
/// their constituent operations. This will enable us to separate
/// implementation
/// of Semantic ARC in SIL and SILGen from ensuring that all of the optimizer
/// passes respect Semantic ARC. This is done by running this pass right after
/// SILGen and as the pass pipeline is updated, moving this pass further and
/// further back in the pipeline.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-ownership-model-eliminator"
#include "swift/SIL/Projection.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SILOptimizer/Analysis/SimplifyInstruction.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/Local.h"
#include "llvm/Support/CommandLine.h"
using namespace swift;
// Utility command line argument to dump the module before we eliminate
// ownership from it.
static llvm::cl::opt<std::string>
DumpBefore("sil-dump-before-ome-to-path", llvm::cl::Hidden);
//===----------------------------------------------------------------------===//
// Implementation
//===----------------------------------------------------------------------===//
namespace {
struct OwnershipModelEliminatorVisitor
: SILInstructionVisitor<OwnershipModelEliminatorVisitor, bool> {
SILBuilder &B;
SILOpenedArchetypesTracker OpenedArchetypesTracker;
OwnershipModelEliminatorVisitor(SILBuilder &B)
: B(B), OpenedArchetypesTracker(&B.getFunction()) {
B.setOpenedArchetypesTracker(&OpenedArchetypesTracker);
}
void beforeVisit(SILInstruction *I) {
B.setInsertionPoint(I);
B.setCurrentDebugScope(I->getDebugScope());
}
bool visitSILInstruction(SILInstruction *I) { return false; }
bool visitLoadInst(LoadInst *LI);
bool visitStoreInst(StoreInst *SI);
bool visitStoreBorrowInst(StoreBorrowInst *SI);
bool visitCopyValueInst(CopyValueInst *CVI);
bool visitDestroyValueInst(DestroyValueInst *DVI);
bool visitLoadBorrowInst(LoadBorrowInst *LBI);
bool visitBeginBorrowInst(BeginBorrowInst *BBI) {
BBI->replaceAllUsesWith(BBI->getOperand());
BBI->eraseFromParent();
return true;
}
bool visitEndBorrowInst(EndBorrowInst *EBI) {
EBI->eraseFromParent();
return true;
}
bool visitEndLifetimeInst(EndLifetimeInst *ELI) {
ELI->eraseFromParent();
return true;
}
bool visitUncheckedOwnershipConversionInst(
UncheckedOwnershipConversionInst *UOCI) {
UOCI->replaceAllUsesWith(UOCI->getOperand());
UOCI->eraseFromParent();
return true;
}
bool visitUnmanagedRetainValueInst(UnmanagedRetainValueInst *URVI);
bool visitUnmanagedReleaseValueInst(UnmanagedReleaseValueInst *URVI);
bool visitUnmanagedAutoreleaseValueInst(UnmanagedAutoreleaseValueInst *UAVI);
bool visitCheckedCastBranchInst(CheckedCastBranchInst *CBI);
bool visitSwitchEnumInst(SwitchEnumInst *SWI);
bool visitDestructureStructInst(DestructureStructInst *DSI);
bool visitDestructureTupleInst(DestructureTupleInst *DTI);
};
} // end anonymous namespace
bool OwnershipModelEliminatorVisitor::visitLoadInst(LoadInst *LI) {
auto Qualifier = LI->getOwnershipQualifier();
// If the qualifier is unqualified, there is nothing further to do
// here. Just return.
if (Qualifier == LoadOwnershipQualifier::Unqualified)
return false;
SILValue Result = B.emitLoadValueOperation(LI->getLoc(), LI->getOperand(),
LI->getOwnershipQualifier());
// Then remove the qualified load and use the unqualified load as the def of
// all of LI's uses.
LI->replaceAllUsesWith(Result);
LI->eraseFromParent();
return true;
}
bool OwnershipModelEliminatorVisitor::visitStoreInst(StoreInst *SI) {
auto Qualifier = SI->getOwnershipQualifier();
// If the qualifier is unqualified, there is nothing further to do
// here. Just return.
if (Qualifier == StoreOwnershipQualifier::Unqualified)
return false;
B.emitStoreValueOperation(SI->getLoc(), SI->getSrc(), SI->getDest(),
SI->getOwnershipQualifier());
// Then remove the qualified store.
SI->eraseFromParent();
return true;
}
bool OwnershipModelEliminatorVisitor::visitStoreBorrowInst(
StoreBorrowInst *SI) {
B.emitStoreValueOperation(SI->getLoc(), SI->getSrc(), SI->getDest(),
StoreOwnershipQualifier::Init);
// Then remove the qualified store.
SI->eraseFromParent();
return true;
}
bool
OwnershipModelEliminatorVisitor::visitLoadBorrowInst(LoadBorrowInst *LBI) {
// Break down the load borrow into an unqualified load.
auto *UnqualifiedLoad = B.createLoad(LBI->getLoc(), LBI->getOperand(),
LoadOwnershipQualifier::Unqualified);
// Then remove the qualified load and use the unqualified load as the def of
// all of LI's uses.
LBI->replaceAllUsesWith(UnqualifiedLoad);
LBI->eraseFromParent();
return true;
}
bool OwnershipModelEliminatorVisitor::visitCopyValueInst(CopyValueInst *CVI) {
// A copy_value of an address-only type cannot be replaced.
if (CVI->getType().isAddressOnly(B.getFunction()))
return false;
// Now that we have set the unqualified ownership flag, destroy value
// operation will delegate to the appropriate strong_release, etc.
B.emitCopyValueOperation(CVI->getLoc(), CVI->getOperand());
CVI->replaceAllUsesWith(CVI->getOperand());
CVI->eraseFromParent();
return true;
}
bool OwnershipModelEliminatorVisitor::visitUnmanagedRetainValueInst(
UnmanagedRetainValueInst *URVI) {
// Now that we have set the unqualified ownership flag, destroy value
// operation will delegate to the appropriate strong_release, etc.
B.emitCopyValueOperation(URVI->getLoc(), URVI->getOperand());
URVI->eraseFromParent();
return true;
}
bool OwnershipModelEliminatorVisitor::visitUnmanagedReleaseValueInst(
UnmanagedReleaseValueInst *URVI) {
// Now that we have set the unqualified ownership flag, destroy value
// operation will delegate to the appropriate strong_release, etc.
B.emitDestroyValueOperation(URVI->getLoc(), URVI->getOperand());
URVI->eraseFromParent();
return true;
}
bool OwnershipModelEliminatorVisitor::visitUnmanagedAutoreleaseValueInst(
UnmanagedAutoreleaseValueInst *UAVI) {
// Now that we have set the unqualified ownership flag, destroy value
// operation will delegate to the appropriate strong_release, etc.
B.createAutoreleaseValue(UAVI->getLoc(), UAVI->getOperand(),
UAVI->getAtomicity());
UAVI->eraseFromParent();
return true;
}
bool OwnershipModelEliminatorVisitor::visitDestroyValueInst(DestroyValueInst *DVI) {
// A destroy_value of an address-only type cannot be replaced.
if (DVI->getOperand()->getType().isAddressOnly(B.getFunction()))
return false;
// Now that we have set the unqualified ownership flag, destroy value
// operation will delegate to the appropriate strong_release, etc.
B.emitDestroyValueOperation(DVI->getLoc(), DVI->getOperand());
DVI->eraseFromParent();
return true;
}
bool OwnershipModelEliminatorVisitor::visitCheckedCastBranchInst(
CheckedCastBranchInst *CBI) {
// In ownership qualified SIL, checked_cast_br must pass its argument to the
// fail case so we can clean it up. In non-ownership qualified SIL, we expect
// no argument from the checked_cast_br in the default case. The way that we
// handle this transformation is that:
//
// 1. We replace all uses of the argument to the false block with a use of the
// checked cast branch's operand.
// 2. We delete the argument from the false block.
SILBasicBlock *FailureBlock = CBI->getFailureBB();
if (FailureBlock->getNumArguments() == 0)
return false;
FailureBlock->getArgument(0)->replaceAllUsesWith(CBI->getOperand());
FailureBlock->eraseArgument(0);
return true;
}
bool OwnershipModelEliminatorVisitor::visitSwitchEnumInst(
SwitchEnumInst *SWEI) {
// In ownership qualified SIL, switch_enum must pass its argument to the fail
// case so we can clean it up. In non-ownership qualified SIL, we expect no
// argument from the switch_enum in the default case. The way that we handle
// this transformation is that:
//
// 1. We replace all uses of the argument to the false block with a use of the
// checked cast branch's operand.
// 2. We delete the argument from the false block.
if (!SWEI->hasDefault())
return false;
SILBasicBlock *DefaultBlock = SWEI->getDefaultBB();
if (DefaultBlock->getNumArguments() == 0)
return false;
DefaultBlock->getArgument(0)->replaceAllUsesWith(SWEI->getOperand());
DefaultBlock->eraseArgument(0);
return true;
}
static void splitDestructure(SILBuilder &B, SILInstruction *I, SILValue Op) {
assert((isa<DestructureStructInst>(I) || isa<DestructureTupleInst>(I)) &&
"Only destructure operations can be passed to splitDestructure");
// First before we destructure anything, see if we can simplify any of our
// instruction operands.
SILModule &M = I->getModule();
SILLocation Loc = I->getLoc();
SILType OpType = Op->getType();
llvm::SmallVector<Projection, 8> Projections;
Projection::getFirstLevelProjections(OpType, M, Projections);
assert(Projections.size() == I->getNumResults());
auto Results = I->getResults();
for (unsigned Index : indices(Results)) {
SILValue Result = Results[Index];
// If our result doesnt have any uses, do not emit instructions, just skip
// it.
if (Result->use_empty())
continue;
// Otherwise, create a projection.
const auto &Proj = Projections[Index];
SingleValueInstruction *ProjInst =
Proj.createObjectProjection(B, Loc, Op).get();
// If we can simplify, do so.
if (SILValue NewV = simplifyInstruction(ProjInst)) {
Result->replaceAllUsesWith(NewV);
ProjInst->eraseFromParent();
continue;
}
Result->replaceAllUsesWith(ProjInst);
}
// We may have exposed trivially dead instructions due to
// simplifyInstruction... delete I and any such instructions!
recursivelyDeleteTriviallyDeadInstructions(I, true);
}
bool OwnershipModelEliminatorVisitor::visitDestructureStructInst(
DestructureStructInst *DSI) {
splitDestructure(B, DSI, DSI->getOperand());
return true;
}
bool OwnershipModelEliminatorVisitor::visitDestructureTupleInst(
DestructureTupleInst *DTI) {
splitDestructure(B, DTI, DTI->getOperand());
return true;
}
//===----------------------------------------------------------------------===//
// Top Level Entry Point
//===----------------------------------------------------------------------===//
static bool stripOwnership(SILFunction &F) {
// If F is an external declaration, do not process it.
if (F.isExternalDeclaration())
return false;
// Set F to have unqualified ownership.
F.setOwnershipEliminated();
bool MadeChange = false;
SILBuilder B(F);
OwnershipModelEliminatorVisitor Visitor(B);
for (auto &BB : F) {
// Change all arguments to have ValueOwnershipKind::Any.
for (auto *Arg : BB.getArguments()) {
Arg->setOwnershipKind(ValueOwnershipKind::Any);
}
for (auto II = BB.begin(), IE = BB.end(); II != IE;) {
// Since we are going to be potentially removing instructions, we need
// to make sure to increment our iterator before we perform any
// visits.
SILInstruction *I = &*II;
++II;
MadeChange |= Visitor.visit(I);
}
}
return MadeChange;
}
static void prepareNonTransparentSILFunctionForOptimization(ModuleDecl *,
SILFunction *F) {
if (!F->hasOwnership() || F->isTransparent())
return;
LLVM_DEBUG(llvm::dbgs() << "After deserialization, stripping ownership in:"
<< F->getName() << "\n");
stripOwnership(*F);
}
static void prepareSILFunctionForOptimization(ModuleDecl *, SILFunction *F) {
if (!F->hasOwnership())
return;
LLVM_DEBUG(llvm::dbgs() << "After deserialization, stripping ownership in:"
<< F->getName() << "\n");
stripOwnership(*F);
}
namespace {
struct OwnershipModelEliminator : SILModuleTransform {
bool SkipTransparent;
OwnershipModelEliminator(bool SkipTransparent)
: SkipTransparent(SkipTransparent) {}
void run() override {
if (DumpBefore.size()) {
getModule()->dump(DumpBefore.c_str());
}
auto &Mod = *getModule();
for (auto &F : Mod) {
// If F does not have ownership, skip it. We have no further work to do.
if (!F.hasOwnership())
continue;
// If we were asked to not strip ownership from transparent functions in
// /our/ module, continue.
if (SkipTransparent && F.isTransparent())
continue;
// Verify here to make sure ownership is correct before we strip.
F.verify();
if (stripOwnership(F)) {
auto InvalidKind =
SILAnalysis::InvalidationKind::BranchesAndInstructions;
invalidateAnalysis(&F, InvalidKind);
}
}
// If we were asked to strip transparent, we are at the beginning of the
// performance pipeline. In such a case, we register a handler so that all
// future things we deserialize have ownership stripped.
using NotificationHandlerTy =
FunctionBodyDeserializationNotificationHandler;
std::unique_ptr<DeserializationNotificationHandler> ptr;
if (SkipTransparent) {
ptr.reset(new NotificationHandlerTy(
prepareNonTransparentSILFunctionForOptimization));
} else {
ptr.reset(new NotificationHandlerTy(prepareSILFunctionForOptimization));
}
Mod.registerDeserializationNotificationHandler(std::move(ptr));
}
};
} // end anonymous namespace
SILTransform *swift::createOwnershipModelEliminator() {
return new OwnershipModelEliminator(false /*skip transparent*/);
}
SILTransform *swift::createNonTransparentFunctionOwnershipModelEliminator() {
return new OwnershipModelEliminator(true /*skip transparent*/);
}
<commit_msg>Revert "[ownership] Verify functions before we strip ownership."<commit_after>//===--- OwnershipModelEliminator.cpp - Eliminate SILOwnership Instr. -----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// This file contains a small pass that lowers SIL ownership instructions to
/// their constituent operations. This will enable us to separate
/// implementation
/// of Semantic ARC in SIL and SILGen from ensuring that all of the optimizer
/// passes respect Semantic ARC. This is done by running this pass right after
/// SILGen and as the pass pipeline is updated, moving this pass further and
/// further back in the pipeline.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-ownership-model-eliminator"
#include "swift/SIL/Projection.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SILOptimizer/Analysis/SimplifyInstruction.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/Local.h"
#include "llvm/Support/CommandLine.h"
using namespace swift;
// Utility command line argument to dump the module before we eliminate
// ownership from it.
static llvm::cl::opt<std::string>
DumpBefore("sil-dump-before-ome-to-path", llvm::cl::Hidden);
//===----------------------------------------------------------------------===//
// Implementation
//===----------------------------------------------------------------------===//
namespace {
struct OwnershipModelEliminatorVisitor
: SILInstructionVisitor<OwnershipModelEliminatorVisitor, bool> {
SILBuilder &B;
SILOpenedArchetypesTracker OpenedArchetypesTracker;
OwnershipModelEliminatorVisitor(SILBuilder &B)
: B(B), OpenedArchetypesTracker(&B.getFunction()) {
B.setOpenedArchetypesTracker(&OpenedArchetypesTracker);
}
void beforeVisit(SILInstruction *I) {
B.setInsertionPoint(I);
B.setCurrentDebugScope(I->getDebugScope());
}
bool visitSILInstruction(SILInstruction *I) { return false; }
bool visitLoadInst(LoadInst *LI);
bool visitStoreInst(StoreInst *SI);
bool visitStoreBorrowInst(StoreBorrowInst *SI);
bool visitCopyValueInst(CopyValueInst *CVI);
bool visitDestroyValueInst(DestroyValueInst *DVI);
bool visitLoadBorrowInst(LoadBorrowInst *LBI);
bool visitBeginBorrowInst(BeginBorrowInst *BBI) {
BBI->replaceAllUsesWith(BBI->getOperand());
BBI->eraseFromParent();
return true;
}
bool visitEndBorrowInst(EndBorrowInst *EBI) {
EBI->eraseFromParent();
return true;
}
bool visitEndLifetimeInst(EndLifetimeInst *ELI) {
ELI->eraseFromParent();
return true;
}
bool visitUncheckedOwnershipConversionInst(
UncheckedOwnershipConversionInst *UOCI) {
UOCI->replaceAllUsesWith(UOCI->getOperand());
UOCI->eraseFromParent();
return true;
}
bool visitUnmanagedRetainValueInst(UnmanagedRetainValueInst *URVI);
bool visitUnmanagedReleaseValueInst(UnmanagedReleaseValueInst *URVI);
bool visitUnmanagedAutoreleaseValueInst(UnmanagedAutoreleaseValueInst *UAVI);
bool visitCheckedCastBranchInst(CheckedCastBranchInst *CBI);
bool visitSwitchEnumInst(SwitchEnumInst *SWI);
bool visitDestructureStructInst(DestructureStructInst *DSI);
bool visitDestructureTupleInst(DestructureTupleInst *DTI);
};
} // end anonymous namespace
bool OwnershipModelEliminatorVisitor::visitLoadInst(LoadInst *LI) {
auto Qualifier = LI->getOwnershipQualifier();
// If the qualifier is unqualified, there is nothing further to do
// here. Just return.
if (Qualifier == LoadOwnershipQualifier::Unqualified)
return false;
SILValue Result = B.emitLoadValueOperation(LI->getLoc(), LI->getOperand(),
LI->getOwnershipQualifier());
// Then remove the qualified load and use the unqualified load as the def of
// all of LI's uses.
LI->replaceAllUsesWith(Result);
LI->eraseFromParent();
return true;
}
bool OwnershipModelEliminatorVisitor::visitStoreInst(StoreInst *SI) {
auto Qualifier = SI->getOwnershipQualifier();
// If the qualifier is unqualified, there is nothing further to do
// here. Just return.
if (Qualifier == StoreOwnershipQualifier::Unqualified)
return false;
B.emitStoreValueOperation(SI->getLoc(), SI->getSrc(), SI->getDest(),
SI->getOwnershipQualifier());
// Then remove the qualified store.
SI->eraseFromParent();
return true;
}
bool OwnershipModelEliminatorVisitor::visitStoreBorrowInst(
StoreBorrowInst *SI) {
B.emitStoreValueOperation(SI->getLoc(), SI->getSrc(), SI->getDest(),
StoreOwnershipQualifier::Init);
// Then remove the qualified store.
SI->eraseFromParent();
return true;
}
bool
OwnershipModelEliminatorVisitor::visitLoadBorrowInst(LoadBorrowInst *LBI) {
// Break down the load borrow into an unqualified load.
auto *UnqualifiedLoad = B.createLoad(LBI->getLoc(), LBI->getOperand(),
LoadOwnershipQualifier::Unqualified);
// Then remove the qualified load and use the unqualified load as the def of
// all of LI's uses.
LBI->replaceAllUsesWith(UnqualifiedLoad);
LBI->eraseFromParent();
return true;
}
bool OwnershipModelEliminatorVisitor::visitCopyValueInst(CopyValueInst *CVI) {
// A copy_value of an address-only type cannot be replaced.
if (CVI->getType().isAddressOnly(B.getFunction()))
return false;
// Now that we have set the unqualified ownership flag, destroy value
// operation will delegate to the appropriate strong_release, etc.
B.emitCopyValueOperation(CVI->getLoc(), CVI->getOperand());
CVI->replaceAllUsesWith(CVI->getOperand());
CVI->eraseFromParent();
return true;
}
bool OwnershipModelEliminatorVisitor::visitUnmanagedRetainValueInst(
UnmanagedRetainValueInst *URVI) {
// Now that we have set the unqualified ownership flag, destroy value
// operation will delegate to the appropriate strong_release, etc.
B.emitCopyValueOperation(URVI->getLoc(), URVI->getOperand());
URVI->eraseFromParent();
return true;
}
bool OwnershipModelEliminatorVisitor::visitUnmanagedReleaseValueInst(
UnmanagedReleaseValueInst *URVI) {
// Now that we have set the unqualified ownership flag, destroy value
// operation will delegate to the appropriate strong_release, etc.
B.emitDestroyValueOperation(URVI->getLoc(), URVI->getOperand());
URVI->eraseFromParent();
return true;
}
bool OwnershipModelEliminatorVisitor::visitUnmanagedAutoreleaseValueInst(
UnmanagedAutoreleaseValueInst *UAVI) {
// Now that we have set the unqualified ownership flag, destroy value
// operation will delegate to the appropriate strong_release, etc.
B.createAutoreleaseValue(UAVI->getLoc(), UAVI->getOperand(),
UAVI->getAtomicity());
UAVI->eraseFromParent();
return true;
}
bool OwnershipModelEliminatorVisitor::visitDestroyValueInst(DestroyValueInst *DVI) {
// A destroy_value of an address-only type cannot be replaced.
if (DVI->getOperand()->getType().isAddressOnly(B.getFunction()))
return false;
// Now that we have set the unqualified ownership flag, destroy value
// operation will delegate to the appropriate strong_release, etc.
B.emitDestroyValueOperation(DVI->getLoc(), DVI->getOperand());
DVI->eraseFromParent();
return true;
}
bool OwnershipModelEliminatorVisitor::visitCheckedCastBranchInst(
CheckedCastBranchInst *CBI) {
// In ownership qualified SIL, checked_cast_br must pass its argument to the
// fail case so we can clean it up. In non-ownership qualified SIL, we expect
// no argument from the checked_cast_br in the default case. The way that we
// handle this transformation is that:
//
// 1. We replace all uses of the argument to the false block with a use of the
// checked cast branch's operand.
// 2. We delete the argument from the false block.
SILBasicBlock *FailureBlock = CBI->getFailureBB();
if (FailureBlock->getNumArguments() == 0)
return false;
FailureBlock->getArgument(0)->replaceAllUsesWith(CBI->getOperand());
FailureBlock->eraseArgument(0);
return true;
}
bool OwnershipModelEliminatorVisitor::visitSwitchEnumInst(
SwitchEnumInst *SWEI) {
// In ownership qualified SIL, switch_enum must pass its argument to the fail
// case so we can clean it up. In non-ownership qualified SIL, we expect no
// argument from the switch_enum in the default case. The way that we handle
// this transformation is that:
//
// 1. We replace all uses of the argument to the false block with a use of the
// checked cast branch's operand.
// 2. We delete the argument from the false block.
if (!SWEI->hasDefault())
return false;
SILBasicBlock *DefaultBlock = SWEI->getDefaultBB();
if (DefaultBlock->getNumArguments() == 0)
return false;
DefaultBlock->getArgument(0)->replaceAllUsesWith(SWEI->getOperand());
DefaultBlock->eraseArgument(0);
return true;
}
static void splitDestructure(SILBuilder &B, SILInstruction *I, SILValue Op) {
assert((isa<DestructureStructInst>(I) || isa<DestructureTupleInst>(I)) &&
"Only destructure operations can be passed to splitDestructure");
// First before we destructure anything, see if we can simplify any of our
// instruction operands.
SILModule &M = I->getModule();
SILLocation Loc = I->getLoc();
SILType OpType = Op->getType();
llvm::SmallVector<Projection, 8> Projections;
Projection::getFirstLevelProjections(OpType, M, Projections);
assert(Projections.size() == I->getNumResults());
auto Results = I->getResults();
for (unsigned Index : indices(Results)) {
SILValue Result = Results[Index];
// If our result doesnt have any uses, do not emit instructions, just skip
// it.
if (Result->use_empty())
continue;
// Otherwise, create a projection.
const auto &Proj = Projections[Index];
SingleValueInstruction *ProjInst =
Proj.createObjectProjection(B, Loc, Op).get();
// If we can simplify, do so.
if (SILValue NewV = simplifyInstruction(ProjInst)) {
Result->replaceAllUsesWith(NewV);
ProjInst->eraseFromParent();
continue;
}
Result->replaceAllUsesWith(ProjInst);
}
// We may have exposed trivially dead instructions due to
// simplifyInstruction... delete I and any such instructions!
recursivelyDeleteTriviallyDeadInstructions(I, true);
}
bool OwnershipModelEliminatorVisitor::visitDestructureStructInst(
DestructureStructInst *DSI) {
splitDestructure(B, DSI, DSI->getOperand());
return true;
}
bool OwnershipModelEliminatorVisitor::visitDestructureTupleInst(
DestructureTupleInst *DTI) {
splitDestructure(B, DTI, DTI->getOperand());
return true;
}
//===----------------------------------------------------------------------===//
// Top Level Entry Point
//===----------------------------------------------------------------------===//
static bool stripOwnership(SILFunction &F) {
// If F is an external declaration, do not process it.
if (F.isExternalDeclaration())
return false;
// Set F to have unqualified ownership.
F.setOwnershipEliminated();
bool MadeChange = false;
SILBuilder B(F);
OwnershipModelEliminatorVisitor Visitor(B);
for (auto &BB : F) {
// Change all arguments to have ValueOwnershipKind::Any.
for (auto *Arg : BB.getArguments()) {
Arg->setOwnershipKind(ValueOwnershipKind::Any);
}
for (auto II = BB.begin(), IE = BB.end(); II != IE;) {
// Since we are going to be potentially removing instructions, we need
// to make sure to increment our iterator before we perform any
// visits.
SILInstruction *I = &*II;
++II;
MadeChange |= Visitor.visit(I);
}
}
return MadeChange;
}
static void prepareNonTransparentSILFunctionForOptimization(ModuleDecl *,
SILFunction *F) {
if (!F->hasOwnership() || F->isTransparent())
return;
LLVM_DEBUG(llvm::dbgs() << "After deserialization, stripping ownership in:"
<< F->getName() << "\n");
stripOwnership(*F);
}
static void prepareSILFunctionForOptimization(ModuleDecl *, SILFunction *F) {
if (!F->hasOwnership())
return;
LLVM_DEBUG(llvm::dbgs() << "After deserialization, stripping ownership in:"
<< F->getName() << "\n");
stripOwnership(*F);
}
namespace {
struct OwnershipModelEliminator : SILModuleTransform {
bool SkipTransparent;
OwnershipModelEliminator(bool SkipTransparent)
: SkipTransparent(SkipTransparent) {}
void run() override {
if (DumpBefore.size()) {
getModule()->dump(DumpBefore.c_str());
}
auto &Mod = *getModule();
for (auto &F : Mod) {
// If F does not have ownership, skip it. We have no further work to do.
if (!F.hasOwnership())
continue;
// If we were asked to not strip ownership from transparent functions in
// /our/ module, continue.
if (SkipTransparent && F.isTransparent())
continue;
if (stripOwnership(F)) {
auto InvalidKind =
SILAnalysis::InvalidationKind::BranchesAndInstructions;
invalidateAnalysis(&F, InvalidKind);
}
}
// If we were asked to strip transparent, we are at the beginning of the
// performance pipeline. In such a case, we register a handler so that all
// future things we deserialize have ownership stripped.
using NotificationHandlerTy =
FunctionBodyDeserializationNotificationHandler;
std::unique_ptr<DeserializationNotificationHandler> ptr;
if (SkipTransparent) {
ptr.reset(new NotificationHandlerTy(
prepareNonTransparentSILFunctionForOptimization));
} else {
ptr.reset(new NotificationHandlerTy(prepareSILFunctionForOptimization));
}
Mod.registerDeserializationNotificationHandler(std::move(ptr));
}
};
} // end anonymous namespace
SILTransform *swift::createOwnershipModelEliminator() {
return new OwnershipModelEliminator(false /*skip transparent*/);
}
SILTransform *swift::createNonTransparentFunctionOwnershipModelEliminator() {
return new OwnershipModelEliminator(true /*skip transparent*/);
}
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
/**
\file TransferFunction1D.cpp
\author Jens Krueger
SCI Institute
University of Utah
\version 1.0
\date September 2008
*/
#include <cstdlib>
#include <fstream>
#include <iterator>
#include <memory.h>
#include <sstream>
#include "TransferFunction1D.h"
#include "Controller/Controller.h"
using namespace std;
TransferFunction1D::TransferFunction1D(size_t iSize) :
m_vValueBBox(0,0)
{
Resize(iSize);
}
TransferFunction1D::TransferFunction1D(const std::string& filename) {
Load(filename);
}
TransferFunction1D::~TransferFunction1D(void)
{
}
void TransferFunction1D::Resize(size_t iSize) {
vColorData.resize(iSize);
}
float TransferFunction1D::Smoothstep(float x) const {
return 3*x*x-2*x*x*x;
}
void TransferFunction1D::SetStdFunction(float fCenterPoint, float fInvGradient) {
SetStdFunction(fCenterPoint, fInvGradient,0, false);
SetStdFunction(fCenterPoint, fInvGradient,1, false);
SetStdFunction(fCenterPoint, fInvGradient,2, false);
SetStdFunction(fCenterPoint, fInvGradient,3, false);
}
void TransferFunction1D::SetStdFunction(float fCenterPoint, float fInvGradient, int iComponent, bool bInvertedStep) {
size_t iCenterPoint = size_t((vColorData.size()-1) * float(std::min<float>(std::max<float>(0,fCenterPoint),1)));
size_t iInvGradient = size_t((vColorData.size()-1) * float(std::min<float>(std::max<float>(0,fInvGradient),1)));
size_t iRampStartPoint = (iInvGradient/2 > iCenterPoint) ? 0 : iCenterPoint-(iInvGradient/2);
size_t iRampEndPoint = (iInvGradient/2 + iCenterPoint > vColorData.size()) ? vColorData.size() : iCenterPoint+(iInvGradient/2);
if (bInvertedStep) {
for (size_t i = 0;i<iRampStartPoint;i++)
vColorData[i][iComponent] = 1;
for (size_t i = iRampStartPoint;i<iRampEndPoint;i++) {
float fValue = Smoothstep(float(i-iCenterPoint+(iInvGradient/2))/float(iInvGradient));
vColorData[i][iComponent] = 1.0f-fValue;
}
for (size_t i = iRampEndPoint;i<vColorData.size();i++)
vColorData[i][iComponent] = 0;
} else {
for (size_t i = 0;i<iRampStartPoint;i++)
vColorData[i][iComponent] = 0;
for (size_t i = iRampStartPoint;i<iRampEndPoint;i++) {
float fValue = Smoothstep(float(i-iCenterPoint+(iInvGradient/2))/float(iInvGradient));
vColorData[i][iComponent] = fValue;
}
for (size_t i = iRampEndPoint;i<vColorData.size();i++)
vColorData[i][iComponent] = 1;
}
ComputeNonZeroLimits();
}
template<typename T>
static bool is_nan(T) { std::abort(); } // Rely on specialization.
template<>
bool is_nan(float v) {
// This is only valid for ieee754.
return (v != v);
}
template<typename T>
static bool is_infinite(T) { abort(); } // Rely on specialization.
template<>
bool is_infinite(float v) {
return (v == std::numeric_limits<float>::infinity() ||
v == -std::numeric_limits<float>::infinity());
}
template<typename in, typename out>
static inline out
lerp(in value, in imin, in imax, out omin, out omax)
{
out ret = out(omin + (value-imin) * (static_cast<double>(omax-omin) /
(imax-imin)));
#if 0
// Very useful while debugging.
if(is_nan(ret) || is_infinite(ret)) { return 0; }
#endif
return ret;
}
/// Finds the minimum and maximum per-channel of a 4-component packed vector.
template<typename ForwardIter, typename Out>
void minmax_component4(ForwardIter first, ForwardIter last,
Out c_min[4], Out c_max[4])
{
c_min[0] = c_min[1] = c_min[2] = c_min[3] = *first;
c_max[0] = c_max[1] = c_max[2] = c_max[3] = *first;
if(first == last) { return; }
while(first < last) {
if(*(first+0) < c_min[0]) { c_min[0] = *(first+0); }
if(*(first+1) < c_min[1]) { c_min[1] = *(first+1); }
if(*(first+2) < c_min[2]) { c_min[2] = *(first+2); }
if(*(first+3) < c_min[3]) { c_min[3] = *(first+3); }
if(*(first+0) > c_max[0]) { c_max[0] = *(first+0); }
if(*(first+1) > c_max[1]) { c_max[1] = *(first+1); }
if(*(first+2) > c_max[2]) { c_max[2] = *(first+2); }
if(*(first+3) > c_max[3]) { c_max[3] = *(first+3); }
// Ugh. Bail out if incrementing the iterator would go beyond the end.
// We'd never actually deref the iterator in that case (because of the
// while conditional), but we hit internal libstdc++ asserts anyway.
if(static_cast<size_t>(std::distance(first, last)) < 4) {
break;
}
std::advance(first, 4);
}
}
/// Set the transfer function from an external source. Assumes the vector
/// has 4-components per element, in RGBA order.
void TransferFunction1D::Set(const std::vector<unsigned char>& tf)
{
assert(!tf.empty());
vColorData.resize(tf.size()/4);
unsigned char tfmin[4];
unsigned char tfmax[4];
// A bit tricky. We need the min/max of our vector so that we know how to
// interpolate, but it needs to be a per-channel min/max.
minmax_component4(tf.begin(),tf.end(), tfmin,tfmax);
// Similarly, we need the min/max of our output format.
const float fmin = 0.0;
const float fmax = 1.0;
assert(tfmin[0] <= tfmax[0]);
assert(tfmin[1] <= tfmax[1]);
assert(tfmin[2] <= tfmax[2]);
assert(tfmin[3] <= tfmax[3]);
for(size_t i=0; i < vColorData.size(); ++i) {
vColorData[i] = FLOATVECTOR4(
lerp(tf[4*i+0], tfmin[0],tfmax[0], fmin,fmax),
lerp(tf[4*i+1], tfmin[1],tfmax[1], fmin,fmax),
lerp(tf[4*i+2], tfmin[2],tfmax[2], fmin,fmax),
lerp(tf[4*i+3], static_cast<unsigned char>(0),
static_cast<unsigned char>(255), fmin,fmax)
);
}
ComputeNonZeroLimits();
}
void TransferFunction1D::Clear() {
for (size_t i = 0;i<vColorData.size();i++)
vColorData[i] = FLOATVECTOR4(0,0,0,0);
m_vValueBBox = UINT64VECTOR2(0,0);
}
void TransferFunction1D::Resample(size_t iTargetSize) {
size_t iSourceSize = vColorData.size();
if (iTargetSize == iSourceSize) return;
vector< FLOATVECTOR4 > vTmpColorData(iTargetSize);
if (iTargetSize < iSourceSize) {
// downsample
size_t iFrom = 0;
for (size_t i = 0;i<vTmpColorData.size();i++) {
size_t iTo = iFrom + iSourceSize/iTargetSize;
vTmpColorData[i] = 0;
for (size_t j = iFrom;j<iTo;j++) {
vTmpColorData[i] += vColorData[j];
}
vTmpColorData[i] /= float(iTo-iFrom);
iTargetSize -= 1;
iSourceSize -= iTo-iFrom;
iFrom = iTo;
}
} else {
// upsample
for (size_t i = 0;i<vTmpColorData.size();i++) {
float fPos = float(i) * float(iSourceSize-1)/float(iTargetSize);
size_t iFloor = size_t(floor(fPos));
size_t iCeil = std::min(iFloor+1, vColorData.size()-1);
float fInterp = fPos - float(iFloor);
vTmpColorData[i] = vColorData[iFloor] * (1-fInterp) + vColorData[iCeil] * fInterp;
}
}
vColorData = vTmpColorData;
ComputeNonZeroLimits();
}
bool TransferFunction1D::Load(const std::string& filename, size_t iTargetSize) {
if (!Load(filename)) {
return false;
} else {
Resample(iTargetSize);
return true;
}
}
bool TransferFunction1D::Load(const std::string& filename) {
ifstream file(filename.c_str());
if (!Load(file)) return false;
file.close();
ComputeNonZeroLimits();
return true;
}
bool TransferFunction1D::Load(std::istream& tf, size_t iTargetSize) {
if (!Load(tf)) {
return false;
} else {
Resample(iTargetSize);
return true;
}
}
bool TransferFunction1D::Save(const std::string& filename) const {
ofstream file(filename.c_str());
if (!Save(file)) return false;
file.close();
return true;
}
bool TransferFunction1D::Load(std::istream& tf) {
UINT32 iSize;
tf >> iSize;
vColorData.resize(iSize);
for(size_t i=0;i<vColorData.size();++i){
for(size_t j=0;j<4;++j){
tf >> vColorData[i][j];
}
}
return true;
}
bool TransferFunction1D::Save(std::ostream& file) const {
file << vColorData.size() << endl;
for(size_t i=0;i<vColorData.size();++i){
for(size_t j=0;j<4;++j){
file << vColorData[i][j] << " ";
}
file << endl;
}
return true;
}
void TransferFunction1D::GetByteArray(std::vector<unsigned char>& vData,
unsigned char cUsedRange) const {
// bail out immediately if we've got no data
if(vColorData.empty()) { return; }
vData.resize(vColorData.size() * 4);
unsigned char *pcDataIterator = &vData.at(0);
for (size_t i = 0;i<vColorData.size();i++) {
*pcDataIterator++ = (unsigned char)(vColorData[i][0]*cUsedRange);
*pcDataIterator++ = (unsigned char)(vColorData[i][1]*cUsedRange);
*pcDataIterator++ = (unsigned char)(vColorData[i][2]*cUsedRange);
*pcDataIterator++ = (unsigned char)(vColorData[i][3]*cUsedRange);
}
}
void TransferFunction1D::GetShortArray(unsigned short** psData,
unsigned short sUsedRange) const {
// bail out immediately if we've got no data
if(vColorData.empty()) { return; }
if (*psData == NULL) *psData = new unsigned short[vColorData.size()*4];
unsigned short *psDataIterator = *psData;
for (size_t i = 0;i<vColorData.size();i++) {
*psDataIterator++ = (unsigned short)(vColorData[i][0]*sUsedRange);
*psDataIterator++ = (unsigned short)(vColorData[i][1]*sUsedRange);
*psDataIterator++ = (unsigned short)(vColorData[i][2]*sUsedRange);
*psDataIterator++ = (unsigned short)(vColorData[i][3]*sUsedRange);
}
}
void TransferFunction1D::GetFloatArray(float** pfData) const {
// bail out immediately if we've got no data
if(vColorData.empty()) { return; }
if (*pfData == NULL) *pfData = new float[4*vColorData.size()];
memcpy(*pfData, &pfData[0], sizeof(float)*4*vColorData.size());
}
void TransferFunction1D::ComputeNonZeroLimits() {
m_vValueBBox = UINT64VECTOR2(UINT64(vColorData.size()),0);
for (size_t i = 0;i<vColorData.size();i++) {
if (vColorData[i][3] != 0) {
m_vValueBBox.x = MIN(m_vValueBBox.x, i);
m_vValueBBox.y = i;
}
}
}
<commit_msg>Use the `lerp' from MathTools.<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
/**
\file TransferFunction1D.cpp
\author Jens Krueger
SCI Institute
University of Utah
\version 1.0
\date September 2008
*/
#include <cstdlib>
#include <fstream>
#include <iterator>
#include <memory.h>
#include <sstream>
#include "Basics/MathTools.h"
#include "Controller/Controller.h"
#include "TransferFunction1D.h"
using namespace std;
TransferFunction1D::TransferFunction1D(size_t iSize) :
m_vValueBBox(0,0)
{
Resize(iSize);
}
TransferFunction1D::TransferFunction1D(const std::string& filename) {
Load(filename);
}
TransferFunction1D::~TransferFunction1D(void)
{
}
void TransferFunction1D::Resize(size_t iSize) {
vColorData.resize(iSize);
}
float TransferFunction1D::Smoothstep(float x) const {
return 3*x*x-2*x*x*x;
}
void TransferFunction1D::SetStdFunction(float fCenterPoint, float fInvGradient) {
SetStdFunction(fCenterPoint, fInvGradient,0, false);
SetStdFunction(fCenterPoint, fInvGradient,1, false);
SetStdFunction(fCenterPoint, fInvGradient,2, false);
SetStdFunction(fCenterPoint, fInvGradient,3, false);
}
void TransferFunction1D::SetStdFunction(float fCenterPoint, float fInvGradient, int iComponent, bool bInvertedStep) {
size_t iCenterPoint = size_t((vColorData.size()-1) * float(std::min<float>(std::max<float>(0,fCenterPoint),1)));
size_t iInvGradient = size_t((vColorData.size()-1) * float(std::min<float>(std::max<float>(0,fInvGradient),1)));
size_t iRampStartPoint = (iInvGradient/2 > iCenterPoint) ? 0 : iCenterPoint-(iInvGradient/2);
size_t iRampEndPoint = (iInvGradient/2 + iCenterPoint > vColorData.size()) ? vColorData.size() : iCenterPoint+(iInvGradient/2);
if (bInvertedStep) {
for (size_t i = 0;i<iRampStartPoint;i++)
vColorData[i][iComponent] = 1;
for (size_t i = iRampStartPoint;i<iRampEndPoint;i++) {
float fValue = Smoothstep(float(i-iCenterPoint+(iInvGradient/2))/float(iInvGradient));
vColorData[i][iComponent] = 1.0f-fValue;
}
for (size_t i = iRampEndPoint;i<vColorData.size();i++)
vColorData[i][iComponent] = 0;
} else {
for (size_t i = 0;i<iRampStartPoint;i++)
vColorData[i][iComponent] = 0;
for (size_t i = iRampStartPoint;i<iRampEndPoint;i++) {
float fValue = Smoothstep(float(i-iCenterPoint+(iInvGradient/2))/float(iInvGradient));
vColorData[i][iComponent] = fValue;
}
for (size_t i = iRampEndPoint;i<vColorData.size();i++)
vColorData[i][iComponent] = 1;
}
ComputeNonZeroLimits();
}
/// Finds the minimum and maximum per-channel of a 4-component packed vector.
template<typename ForwardIter, typename Out>
void minmax_component4(ForwardIter first, ForwardIter last,
Out c_min[4], Out c_max[4])
{
c_min[0] = c_min[1] = c_min[2] = c_min[3] = *first;
c_max[0] = c_max[1] = c_max[2] = c_max[3] = *first;
if(first == last) { return; }
while(first < last) {
if(*(first+0) < c_min[0]) { c_min[0] = *(first+0); }
if(*(first+1) < c_min[1]) { c_min[1] = *(first+1); }
if(*(first+2) < c_min[2]) { c_min[2] = *(first+2); }
if(*(first+3) < c_min[3]) { c_min[3] = *(first+3); }
if(*(first+0) > c_max[0]) { c_max[0] = *(first+0); }
if(*(first+1) > c_max[1]) { c_max[1] = *(first+1); }
if(*(first+2) > c_max[2]) { c_max[2] = *(first+2); }
if(*(first+3) > c_max[3]) { c_max[3] = *(first+3); }
// Ugh. Bail out if incrementing the iterator would go beyond the end.
// We'd never actually deref the iterator in that case (because of the
// while conditional), but we hit internal libstdc++ asserts anyway.
if(static_cast<size_t>(std::distance(first, last)) < 4) {
break;
}
std::advance(first, 4);
}
}
/// Set the transfer function from an external source. Assumes the vector
/// has 4-components per element, in RGBA order.
void TransferFunction1D::Set(const std::vector<unsigned char>& tf)
{
assert(!tf.empty());
vColorData.resize(tf.size()/4);
unsigned char tfmin[4];
unsigned char tfmax[4];
// A bit tricky. We need the min/max of our vector so that we know how to
// interpolate, but it needs to be a per-channel min/max.
minmax_component4(tf.begin(),tf.end(), tfmin,tfmax);
// Similarly, we need the min/max of our output format.
const float fmin = 0.0;
const float fmax = 1.0;
assert(tfmin[0] <= tfmax[0]);
assert(tfmin[1] <= tfmax[1]);
assert(tfmin[2] <= tfmax[2]);
assert(tfmin[3] <= tfmax[3]);
for(size_t i=0; i < vColorData.size(); ++i) {
vColorData[i] = FLOATVECTOR4(
MathTools::lerp(tf[4*i+0], tfmin[0],tfmax[0], fmin,fmax),
MathTools::lerp(tf[4*i+1], tfmin[1],tfmax[1], fmin,fmax),
MathTools::lerp(tf[4*i+2], tfmin[2],tfmax[2], fmin,fmax),
MathTools::lerp(tf[4*i+3], static_cast<unsigned char>(0),
static_cast<unsigned char>(255), fmin,fmax)
);
}
ComputeNonZeroLimits();
}
void TransferFunction1D::Clear() {
for (size_t i = 0;i<vColorData.size();i++)
vColorData[i] = FLOATVECTOR4(0,0,0,0);
m_vValueBBox = UINT64VECTOR2(0,0);
}
void TransferFunction1D::Resample(size_t iTargetSize) {
size_t iSourceSize = vColorData.size();
if (iTargetSize == iSourceSize) return;
vector< FLOATVECTOR4 > vTmpColorData(iTargetSize);
if (iTargetSize < iSourceSize) {
// downsample
size_t iFrom = 0;
for (size_t i = 0;i<vTmpColorData.size();i++) {
size_t iTo = iFrom + iSourceSize/iTargetSize;
vTmpColorData[i] = 0;
for (size_t j = iFrom;j<iTo;j++) {
vTmpColorData[i] += vColorData[j];
}
vTmpColorData[i] /= float(iTo-iFrom);
iTargetSize -= 1;
iSourceSize -= iTo-iFrom;
iFrom = iTo;
}
} else {
// upsample
for (size_t i = 0;i<vTmpColorData.size();i++) {
float fPos = float(i) * float(iSourceSize-1)/float(iTargetSize);
size_t iFloor = size_t(floor(fPos));
size_t iCeil = std::min(iFloor+1, vColorData.size()-1);
float fInterp = fPos - float(iFloor);
vTmpColorData[i] = vColorData[iFloor] * (1-fInterp) + vColorData[iCeil] * fInterp;
}
}
vColorData = vTmpColorData;
ComputeNonZeroLimits();
}
bool TransferFunction1D::Load(const std::string& filename, size_t iTargetSize) {
if (!Load(filename)) {
return false;
} else {
Resample(iTargetSize);
return true;
}
}
bool TransferFunction1D::Load(const std::string& filename) {
ifstream file(filename.c_str());
if (!Load(file)) return false;
file.close();
ComputeNonZeroLimits();
return true;
}
bool TransferFunction1D::Load(std::istream& tf, size_t iTargetSize) {
if (!Load(tf)) {
return false;
} else {
Resample(iTargetSize);
return true;
}
}
bool TransferFunction1D::Save(const std::string& filename) const {
ofstream file(filename.c_str());
if (!Save(file)) return false;
file.close();
return true;
}
bool TransferFunction1D::Load(std::istream& tf) {
UINT32 iSize;
tf >> iSize;
vColorData.resize(iSize);
for(size_t i=0;i<vColorData.size();++i){
for(size_t j=0;j<4;++j){
tf >> vColorData[i][j];
}
}
return true;
}
bool TransferFunction1D::Save(std::ostream& file) const {
file << vColorData.size() << endl;
for(size_t i=0;i<vColorData.size();++i){
for(size_t j=0;j<4;++j){
file << vColorData[i][j] << " ";
}
file << endl;
}
return true;
}
void TransferFunction1D::GetByteArray(std::vector<unsigned char>& vData,
unsigned char cUsedRange) const {
// bail out immediately if we've got no data
if(vColorData.empty()) { return; }
vData.resize(vColorData.size() * 4);
unsigned char *pcDataIterator = &vData.at(0);
for (size_t i = 0;i<vColorData.size();i++) {
*pcDataIterator++ = (unsigned char)(vColorData[i][0]*cUsedRange);
*pcDataIterator++ = (unsigned char)(vColorData[i][1]*cUsedRange);
*pcDataIterator++ = (unsigned char)(vColorData[i][2]*cUsedRange);
*pcDataIterator++ = (unsigned char)(vColorData[i][3]*cUsedRange);
}
}
void TransferFunction1D::GetShortArray(unsigned short** psData,
unsigned short sUsedRange) const {
// bail out immediately if we've got no data
if(vColorData.empty()) { return; }
if (*psData == NULL) *psData = new unsigned short[vColorData.size()*4];
unsigned short *psDataIterator = *psData;
for (size_t i = 0;i<vColorData.size();i++) {
*psDataIterator++ = (unsigned short)(vColorData[i][0]*sUsedRange);
*psDataIterator++ = (unsigned short)(vColorData[i][1]*sUsedRange);
*psDataIterator++ = (unsigned short)(vColorData[i][2]*sUsedRange);
*psDataIterator++ = (unsigned short)(vColorData[i][3]*sUsedRange);
}
}
void TransferFunction1D::GetFloatArray(float** pfData) const {
// bail out immediately if we've got no data
if(vColorData.empty()) { return; }
if (*pfData == NULL) *pfData = new float[4*vColorData.size()];
memcpy(*pfData, &pfData[0], sizeof(float)*4*vColorData.size());
}
void TransferFunction1D::ComputeNonZeroLimits() {
m_vValueBBox = UINT64VECTOR2(UINT64(vColorData.size()),0);
for (size_t i = 0;i<vColorData.size();i++) {
if (vColorData[i][3] != 0) {
m_vValueBBox.x = MIN(m_vValueBBox.x, i);
m_vValueBBox.y = i;
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: query.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: oj $ $Date: 2000-10-25 07:30:24 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _DBA_COREAPI_QUERY_HXX_
#include "query.hxx"
#endif
#ifndef DBACCESS_SHARED_DBASTRINGS_HRC
#include "dbastrings.hrc"
#endif
#include "registryhelper.hxx"
#ifndef _CPPUHELPER_QUERYINTERFACE_HXX_
#include <cppuhelper/queryinterface.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_AGGREGATION_HXX_
#include <comphelper/propagg.hxx>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
using namespace dbaccess;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::registry;
using namespace ::comphelper;
using namespace ::osl;
using namespace ::cppu;
#define AGG_PROPERTY(handle, propname_out) \
static_cast< ::comphelper::OPropertyArrayAggregationHelper* >(const_cast< OQuery_LINUX* >(this)->getArrayHelper())->fillAggregatePropertyInfoByHandle(&propname_out, NULL, handle)
//........................................................................
namespace dbaccess
{
//........................................................................
//==========================================================================
//= OQuery_LINUX
//==========================================================================
DBG_NAME(OQuery_LINUX)
//--------------------------------------------------------------------------
OQuery_LINUX::OQuery_LINUX(const Reference< XPropertySet >& _rxCommandDefinition, const Reference< XConnection >& _rxConn)
:OConfigurationFlushable(m_aMutex)
,m_bColumnsOutOfDate(sal_True)
,m_bCaseSensitiv(sal_True)
,m_xCommandDefinition(_rxCommandDefinition)
,m_eDoingCurrently(NONE)
,m_xConnection(_rxConn)
{
DBG_CTOR(OQuery_LINUX, NULL);
DBG_ASSERT(m_xCommandDefinition.is(), "OQuery_LINUX::OQuery_LINUX : invalid CommandDefinition object !");
if (m_xCommandDefinition.is())
{
m_xCommandDefinition->addPropertyChangeListener(::rtl::OUString(), this);
// TODO : be a listener on the configuration node which is responsible for my properties not belonging
// to the CommandDefinition
}
DBG_ASSERT(m_xConnection.is(), "OQuery_LINUX::OQuery_LINUX : invalid connection !");
}
//--------------------------------------------------------------------------
OQuery_LINUX::~OQuery_LINUX()
{
DBG_DTOR(OQuery_LINUX, NULL);
}
// XTypeProvider
//--------------------------------------------------------------------------
Sequence< Type > SAL_CALL OQuery_LINUX::getTypes() throw (RuntimeException)
{
return ::comphelper::concatSequences(OQueryDescriptor::getTypes(), OQuery_Base::getTypes(), OConfigurationFlushable::getTypes());
}
// XInterface
//--------------------------------------------------------------------------
Any SAL_CALL OQuery_LINUX::queryInterface( const Type& _rType ) throw(RuntimeException)
{
Any aReturn = OQuery_Base::queryInterface(_rType);
if (!aReturn.hasValue())
aReturn = OQueryDescriptor::queryInterface(_rType);
if (!aReturn.hasValue())
aReturn = OConfigurationFlushable::queryInterface(_rType);
return aReturn;
}
// XColumnsSupplier
//--------------------------------------------------------------------------
Reference< XNameAccess > SAL_CALL OQuery_LINUX::getColumns( ) throw(RuntimeException)
{
MutexGuard aGuard(m_aMutex);
if (m_bColumnsOutOfDate)
{
m_aColumns.clearColumns();
// TODO
m_bColumnsOutOfDate = sal_False;
}
return &m_aColumns;
}
// XServiceInfo
//--------------------------------------------------------------------------
IMPLEMENT_SERVICE_INFO3(OQuery_LINUX, "com.sun.star.sdb.dbaccess.OQuery", SERVICE_SDB_DATASETTINGS, SERVICE_SDB_QUERY, SERVICE_SDB_QUERYDEFINITION)
// ::com::sun::star::beans::XPropertyChangeListener
//--------------------------------------------------------------------------
void SAL_CALL OQuery_LINUX::propertyChange( const PropertyChangeEvent& _rSource ) throw(RuntimeException)
{
sal_Int32 nOwnHandle = -1;
{
MutexGuard aGuard(m_aMutex);
DBG_ASSERT(_rSource.Source.get() == Reference< XInterface >(m_xCommandDefinition, UNO_QUERY).get(),
"OQuery_LINUX::propertyChange : where did this call come from ?");
if (m_eDoingCurrently == SETTING_PROPERTIES)
// we're setting the property ourself, so we will do the neccessary notifications later
return;
// forward this to our own member holding a copy of the property value
if (getArrayHelper()->hasPropertyByName(_rSource.PropertyName))
{
Property aOwnProp = getArrayHelper()->getPropertyByName(_rSource.PropertyName);
nOwnHandle = aOwnProp.Handle;
OQueryDescriptor::setFastPropertyValue_NoBroadcast(nOwnHandle, _rSource.NewValue);
// don't use our own setFastPropertyValue_NoBroadcast, this would forward it to the CommandSettings,
// again
// and don't use the "real" setPropertyValue, this is to expensive and not sure to succeed
}
else
{
DBG_ERROR("OQuery_LINUX::propertyChange : my CommandDefinition has more properties than I do !");
}
}
fire(&nOwnHandle, &_rSource.NewValue, &_rSource.OldValue, 1, sal_False);
}
//--------------------------------------------------------------------------
void SAL_CALL OQuery_LINUX::disposing( const EventObject& _rSource )
{
MutexGuard aGuard(m_aMutex);
DBG_ASSERT(_rSource.Source.get() == Reference< XInterface >(m_xCommandDefinition, UNO_QUERY).get(),
"OQuery_LINUX::disposing : where did this call come from ?");
m_xCommandDefinition->removePropertyChangeListener(::rtl::OUString(), this);
m_xCommandDefinition = NULL;
}
// XDataDescriptorFactory
//--------------------------------------------------------------------------
Reference< XPropertySet > SAL_CALL OQuery_LINUX::createDataDescriptor( ) throw(RuntimeException)
{
return new OQueryDescriptor(*this);
}
// OQueryDescriptor
//--------------------------------------------------------------------------
void OQuery_LINUX::initializeFrom(const OConfigurationNode& _rConfigLocation)
{
OQueryDescriptor::initializeFrom(_rConfigLocation);
m_aConfigurationNode = _rConfigLocation.cloneAsRoot();
}
// OConfigurationFlushable
//--------------------------------------------------------------------------
void OQuery_LINUX::flush_NoBroadcast_NoCommit()
{
if (!m_aConfigurationNode.isValid())
throw DisposedException();
OQueryDescriptor::storeTo(m_aConfigurationNode);
}
// pseudo-XComponent
//--------------------------------------------------------------------------
void SAL_CALL OQuery_LINUX::dispose()
{
MutexGuard aGuard(m_aMutex);
if (m_xCommandDefinition.is())
{
m_xCommandDefinition->removePropertyChangeListener(::rtl::OUString(), this);
m_xCommandDefinition = NULL;
}
m_aConfigurationNode.clear();
OQueryDescriptor::dispose();
}
//--------------------------------------------------------------------------
void OQuery_LINUX::setFastPropertyValue_NoBroadcast( sal_Int32 _nHandle, const Any& _rValue ) throw (Exception)
{
ODataSettings::setFastPropertyValue_NoBroadcast(_nHandle, _rValue);
::rtl::OUString sAggPropName;
if (AGG_PROPERTY(_nHandle, sAggPropName))
{ // the base class holds the property values itself, but we have to forward this to our CommandDefinition
m_eDoingCurrently = SETTING_PROPERTIES;
OAutoActionReset(this);
m_xCommandDefinition->setPropertyValue(sAggPropName, _rValue);
}
}
//--------------------------------------------------------------------------
Reference< XPropertySetInfo > SAL_CALL OQuery_LINUX::getPropertySetInfo( ) throw(RuntimeException)
{
return createPropertySetInfo( getInfoHelper() ) ;
}
//------------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& OQuery_LINUX::getInfoHelper()
{
return *getArrayHelper();
}
//--------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OQuery::createArrayHelper( ) const
{
Sequence< Property > aProps;
// our own props
describeProperties(aProps);
return new ::cppu::OPropertyArrayHelper(aProps);
}
//........................................................................
} // namespace dbaccess
//........................................................................
<commit_msg>fill query with live, like columns<commit_after>/*************************************************************************
*
* $RCSfile: query.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: oj $ $Date: 2001-01-04 14:26:47 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _DBA_COREAPI_QUERY_HXX_
#include "query.hxx"
#endif
#ifndef DBACCESS_SHARED_DBASTRINGS_HRC
#include "dbastrings.hrc"
#endif
#include "registryhelper.hxx"
#ifndef _CPPUHELPER_QUERYINTERFACE_HXX_
#include <cppuhelper/queryinterface.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_AGGREGATION_HXX_
#include <comphelper/propagg.hxx>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_HXX_
#include <comphelper/property.hxx>
#endif
using namespace dbaccess;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::registry;
using namespace ::comphelper;
using namespace ::osl;
using namespace ::cppu;
#define AGG_PROPERTY(handle, propname_out) \
static_cast< ::comphelper::OPropertyArrayAggregationHelper* >(const_cast< OQuery_LINUX* >(this)->getArrayHelper())->fillAggregatePropertyInfoByHandle(&propname_out, NULL, handle)
//........................................................................
namespace dbaccess
{
//........................................................................
//==========================================================================
//= OQuery_LINUX
//==========================================================================
DBG_NAME(OQuery_LINUX)
//--------------------------------------------------------------------------
OQuery_LINUX::OQuery_LINUX(const Reference< XPropertySet >& _rxCommandDefinition, const Reference< XConnection >& _rxConn)
:OConfigurationFlushable(m_aMutex)
,OQueryDescriptor(_rxCommandDefinition)
,m_bColumnsOutOfDate(sal_True)
,m_bCaseSensitiv(sal_True)
,m_xCommandDefinition(_rxCommandDefinition)
,m_eDoingCurrently(NONE)
,m_xConnection(_rxConn)
{
DBG_CTOR(OQuery_LINUX, NULL);
DBG_ASSERT(m_xCommandDefinition.is(), "OQuery_LINUX::OQuery_LINUX : invalid CommandDefinition object !");
if (m_xCommandDefinition.is())
{
m_xCommandDefinition->addPropertyChangeListener(::rtl::OUString(), this);
// TODO : be a listener on the configuration node which is responsible for my properties not belonging
// to the CommandDefinition
}
DBG_ASSERT(m_xConnection.is(), "OQuery_LINUX::OQuery_LINUX : invalid connection !");
}
//--------------------------------------------------------------------------
OQuery_LINUX::~OQuery_LINUX()
{
DBG_DTOR(OQuery_LINUX, NULL);
}
// XTypeProvider
//--------------------------------------------------------------------------
Sequence< Type > SAL_CALL OQuery_LINUX::getTypes() throw (RuntimeException)
{
return ::comphelper::concatSequences(OQueryDescriptor::getTypes(), OQuery_Base::getTypes(), OConfigurationFlushable::getTypes());
}
// XInterface
//--------------------------------------------------------------------------
Any SAL_CALL OQuery_LINUX::queryInterface( const Type& _rType ) throw(RuntimeException)
{
Any aReturn = OQuery_Base::queryInterface(_rType);
if (!aReturn.hasValue())
aReturn = OQueryDescriptor::queryInterface(_rType);
if (!aReturn.hasValue())
aReturn = OConfigurationFlushable::queryInterface(_rType);
return aReturn;
}
// XColumnsSupplier
//--------------------------------------------------------------------------
Reference< XNameAccess > SAL_CALL OQuery_LINUX::getColumns( ) throw(RuntimeException)
{
MutexGuard aGuard(m_aMutex);
if (m_bColumnsOutOfDate)
{
m_aColumns.clearColumns();
// fill the columns with columns from teh statement
try
{
Reference< XStatement > xStmt = m_xConnection->createStatement();
OSL_ENSURE(xStmt.is(),"No Statement created!");
if(xStmt.is())
{
Reference< XColumnsSupplier > xRs(xStmt->executeQuery(m_sCommand),UNO_QUERY);
OSL_ENSURE(xRs.is(),"No Resultset created!");
if(xRs.is())
{
Reference< XNameAccess > xColumns = xRs->getColumns();
if(xColumns.is())
{
Sequence< ::rtl::OUString> aNames = xColumns->getElementNames();
const ::rtl::OUString* pBegin = aNames.getConstArray();
const ::rtl::OUString* pEnd = pBegin + aNames.getLength();
for(;pBegin != pEnd;++pBegin)
{
ODescriptorColumn* pColumn = new ODescriptorColumn(*pBegin);
Reference<XPropertySet> xSet = pColumn;
Reference<XPropertySet> xSource;
xColumns->getByName(*pBegin) >>= xSource;
::comphelper::copyProperties(xSource,xSet);
m_aColumns.append(*pBegin,pColumn);
}
}
::comphelper::disposeComponent(xRs);
}
::comphelper::disposeComponent(xStmt);
}
m_bColumnsOutOfDate = sal_False;
m_aColumns.setInitialized();
}
catch(SQLException&)
{
}
}
return &m_aColumns;
}
// XServiceInfo
//--------------------------------------------------------------------------
IMPLEMENT_SERVICE_INFO3(OQuery_LINUX, "com.sun.star.sdb.dbaccess.OQuery", SERVICE_SDB_DATASETTINGS, SERVICE_SDB_QUERY, SERVICE_SDB_QUERYDEFINITION)
// ::com::sun::star::beans::XPropertyChangeListener
//--------------------------------------------------------------------------
void SAL_CALL OQuery_LINUX::propertyChange( const PropertyChangeEvent& _rSource ) throw(RuntimeException)
{
sal_Int32 nOwnHandle = -1;
{
MutexGuard aGuard(m_aMutex);
DBG_ASSERT(_rSource.Source.get() == Reference< XInterface >(m_xCommandDefinition, UNO_QUERY).get(),
"OQuery_LINUX::propertyChange : where did this call come from ?");
if (m_eDoingCurrently == SETTING_PROPERTIES)
// we're setting the property ourself, so we will do the neccessary notifications later
return;
// forward this to our own member holding a copy of the property value
if (getArrayHelper()->hasPropertyByName(_rSource.PropertyName))
{
Property aOwnProp = getArrayHelper()->getPropertyByName(_rSource.PropertyName);
nOwnHandle = aOwnProp.Handle;
OQueryDescriptor::setFastPropertyValue_NoBroadcast(nOwnHandle, _rSource.NewValue);
// don't use our own setFastPropertyValue_NoBroadcast, this would forward it to the CommandSettings,
// again
// and don't use the "real" setPropertyValue, this is to expensive and not sure to succeed
}
else
{
DBG_ERROR("OQuery_LINUX::propertyChange : my CommandDefinition has more properties than I do !");
}
}
fire(&nOwnHandle, &_rSource.NewValue, &_rSource.OldValue, 1, sal_False);
}
//--------------------------------------------------------------------------
void SAL_CALL OQuery_LINUX::disposing( const EventObject& _rSource )
{
MutexGuard aGuard(m_aMutex);
DBG_ASSERT(_rSource.Source.get() == Reference< XInterface >(m_xCommandDefinition, UNO_QUERY).get(),
"OQuery_LINUX::disposing : where did this call come from ?");
m_xCommandDefinition->removePropertyChangeListener(::rtl::OUString(), this);
m_xCommandDefinition = NULL;
}
// XDataDescriptorFactory
//--------------------------------------------------------------------------
Reference< XPropertySet > SAL_CALL OQuery_LINUX::createDataDescriptor( ) throw(RuntimeException)
{
return new OQueryDescriptor(*this);
}
// OQueryDescriptor
//--------------------------------------------------------------------------
void OQuery_LINUX::initializeFrom(const OConfigurationNode& _rConfigLocation)
{
OQueryDescriptor::initializeFrom(_rConfigLocation);
m_aConfigurationNode = _rConfigLocation.cloneAsRoot();
}
// OConfigurationFlushable
//--------------------------------------------------------------------------
void OQuery_LINUX::flush_NoBroadcast_NoCommit()
{
if (!m_aConfigurationNode.isValid())
throw DisposedException();
OQueryDescriptor::storeTo(m_aConfigurationNode);
}
// pseudo-XComponent
//--------------------------------------------------------------------------
void SAL_CALL OQuery_LINUX::dispose()
{
MutexGuard aGuard(m_aMutex);
if (m_xCommandDefinition.is())
{
m_xCommandDefinition->removePropertyChangeListener(::rtl::OUString(), this);
m_xCommandDefinition = NULL;
}
m_aConfigurationNode.clear();
OQueryDescriptor::dispose();
}
//--------------------------------------------------------------------------
void OQuery_LINUX::setFastPropertyValue_NoBroadcast( sal_Int32 _nHandle, const Any& _rValue ) throw (Exception)
{
OQueryDescriptor::setFastPropertyValue_NoBroadcast(_nHandle, _rValue);
::rtl::OUString sAggPropName;
sal_Int16 nAttr = 0;
if (getInfoHelper().fillPropertyMembersByHandle(&sAggPropName,&nAttr,_nHandle))
{ // the base class holds the property values itself, but we have to forward this to our CommandDefinition
m_eDoingCurrently = SETTING_PROPERTIES;
OAutoActionReset(this);
m_xCommandDefinition->setPropertyValue(sAggPropName, _rValue);
}
}
//--------------------------------------------------------------------------
Reference< XPropertySetInfo > SAL_CALL OQuery_LINUX::getPropertySetInfo( ) throw(RuntimeException)
{
return createPropertySetInfo( getInfoHelper() ) ;
}
//------------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& OQuery_LINUX::getInfoHelper()
{
return *getArrayHelper();
}
//--------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OQuery::createArrayHelper( ) const
{
Sequence< Property > aProps;
// our own props
describeProperties(aProps);
return new ::cppu::OPropertyArrayHelper(aProps);
}
//........................................................................
} // namespace dbaccess
//........................................................................
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: JAccess.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2007-06-27 12:25:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef DBACCESS_JACCESS_HXX
#define DBACCESS_JACCESS_HXX
#ifndef _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_
#include <toolkit/awt/vclxaccessiblecomponent.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
namespace dbaui
{
class OJoinTableView;
typedef ::cppu::ImplHelper1< ::com::sun::star::accessibility::XAccessible
> OJoinDesignViewAccess_BASE;
/** the class OJoinDesignViewAccess represents the accessible object for join views
like the QueryDesign and the RelationDesign
*/
class OJoinDesignViewAccess : public VCLXAccessibleComponent, public OJoinDesignViewAccess_BASE
{
OJoinTableView* m_pTableView; // the window which I should give accessibility to
protected:
/** isEditable returns the current editable state
@return true if the controller is not readonly otherwise false
*/
virtual sal_Bool isEditable() const;
public:
/** OJoinDesignViewAccess needs a valid view
*/
OJoinDesignViewAccess( OJoinTableView* _pTableView);
// XInterface
DECLARE_XINTERFACE( )
DECLARE_XTYPEPROVIDER( )
// XServiceInfo - static methods
static ::rtl::OUString getImplementationName_Static(void) throw( com::sun::star::uno::RuntimeException );
virtual ::rtl::OUString SAL_CALL getImplementationName() throw(com::sun::star::uno::RuntimeException);
// XAccessible
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext( ) throw (::com::sun::star::uno::RuntimeException);
// XAccessibleContext
virtual sal_Int32 SAL_CALL getAccessibleChildCount( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException,::com::sun::star::uno::RuntimeException);
virtual sal_Int16 SAL_CALL getAccessibleRole( ) throw (::com::sun::star::uno::RuntimeException);
OJoinTableView* getTableView() const { return m_pTableView; }
void notifyAccessibleEvent(
const sal_Int16 _nEventId,
const ::com::sun::star::uno::Any& _rOldValue,
const ::com::sun::star::uno::Any& _rNewValue
)
{
NotifyAccessibleEvent(_nEventId,_rOldValue,_rNewValue);
}
void clearTableView();
};
}
#endif // DBACCESS_JACCESS_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.7.162); FILE MERGED 2008/03/31 13:27:43 rt 1.7.162.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: JAccess.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 DBACCESS_JACCESS_HXX
#define DBACCESS_JACCESS_HXX
#ifndef _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_
#include <toolkit/awt/vclxaccessiblecomponent.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
namespace dbaui
{
class OJoinTableView;
typedef ::cppu::ImplHelper1< ::com::sun::star::accessibility::XAccessible
> OJoinDesignViewAccess_BASE;
/** the class OJoinDesignViewAccess represents the accessible object for join views
like the QueryDesign and the RelationDesign
*/
class OJoinDesignViewAccess : public VCLXAccessibleComponent, public OJoinDesignViewAccess_BASE
{
OJoinTableView* m_pTableView; // the window which I should give accessibility to
protected:
/** isEditable returns the current editable state
@return true if the controller is not readonly otherwise false
*/
virtual sal_Bool isEditable() const;
public:
/** OJoinDesignViewAccess needs a valid view
*/
OJoinDesignViewAccess( OJoinTableView* _pTableView);
// XInterface
DECLARE_XINTERFACE( )
DECLARE_XTYPEPROVIDER( )
// XServiceInfo - static methods
static ::rtl::OUString getImplementationName_Static(void) throw( com::sun::star::uno::RuntimeException );
virtual ::rtl::OUString SAL_CALL getImplementationName() throw(com::sun::star::uno::RuntimeException);
// XAccessible
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext( ) throw (::com::sun::star::uno::RuntimeException);
// XAccessibleContext
virtual sal_Int32 SAL_CALL getAccessibleChildCount( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException,::com::sun::star::uno::RuntimeException);
virtual sal_Int16 SAL_CALL getAccessibleRole( ) throw (::com::sun::star::uno::RuntimeException);
OJoinTableView* getTableView() const { return m_pTableView; }
void notifyAccessibleEvent(
const sal_Int16 _nEventId,
const ::com::sun::star::uno::Any& _rOldValue,
const ::com::sun::star::uno::Any& _rNewValue
)
{
NotifyAccessibleEvent(_nEventId,_rOldValue,_rNewValue);
}
void clearTableView();
};
}
#endif // DBACCESS_JACCESS_HXX
<|endoftext|> |
<commit_before>/*===========================================================================*\
* *
* OpenMesh *
* Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
* *
* OpenMesh 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 3 of *
* the License, or (at your option) any later version with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenMesh 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 LesserGeneral Public *
* License along with OpenMesh. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision$ *
* $Date$ *
* *
\*===========================================================================*/
#ifndef DOXY_IGNORE_THIS
// ----------------------------------------------------------------------------
#include <OpenMesh/Core/System/config.h>
#if defined(OM_CC_MIPS)
# include <math.h>
# include <stdio.h>
#else
# include <cmath>
# include <cstdio>
#endif
#include "Timer.hh"
// ----------------------------------------------------------------------------
// ------------------------------------------------------------- namespace ----
namespace OpenMesh {
namespace Utils {
// ----------------------------------------------------------------------------
using namespace std;
// -------------------------------------------------------------- TimerImpl ----
};
// compiler and os dependent implementation
// ------------------------------------------------------------- posix time ----
#if defined(__GNUC__) && defined(__POSIX__)
#ifndef DOXY_IGNORE_THIS
# include <time.h>
#endif
template <clockid_t N>
class TimerImplPosix : public TimerImpl
{
public:
TimerImplPosix() : id_(N), seconds_(0.0)
{ }
~TimerImplPosix()
{ }
virtual void reset(void) { seconds_ = 0.0; }
virtual void start(void) { seconds_ = 0.0; clock_gettime( id_, &start_ ); }
virtual void stop(void)
{
timespec stop;
clock_gettime( id_, &stop );
seconds_ += ( stop.tv_sec - start_.tv_sec );
seconds_ += ( (double(stop.tv_nsec-start_.tv_nsec)*1e-9) );
}
virtual void cont(void) { clock_gettime( id_, &start_ ); }
virtual double seconds() const { return seconds_; }
protected:
clockid_t id_;
double seconds_;
timespec start_;
};
// ----------------------------------------------------------- gettimeofday ----
#elif (defined(__GNUC__) || (defined(__INTEL_COMPILER) && !defined(WIN32))) && !defined(__MINGW32__)
# include <sys/time.h>
# include <sys/resource.h>
# include <unistd.h>
class TimerImplGToD: public TimerImpl
{
public:
TimerImplGToD() : seconds_(0.0)
{ }
~TimerImplGToD()
{ }
virtual void reset(void) { seconds_ = 0.0; }
virtual void start(void) { seconds_ = 0.0; gettimeofday( &start_, &tz_ ); }
virtual void stop(void)
{
gettimeofday( &stop_, &tz_ );
seconds_ += (double)(stop_.tv_sec - start_.tv_sec);
seconds_ += (double)(stop_.tv_usec- start_.tv_usec)*1e-6;
}
virtual void cont(void) { gettimeofday( &start_, &tz_); }
virtual double seconds() const { return seconds_; }
private:
struct timeval start_, stop_;
struct timezone tz_;
double seconds_;
};
#else // ---------------------------------------- standard implementation ----
#include <time.h>
static const unsigned long clockticks = CLOCKS_PER_SEC;
class TimerImplStd : public TimerImpl
{
public:
TimerImplStd() : freq_(clockticks),count_(0),start_(0) { reset(); }
~TimerImplStd() { ; }
virtual void reset(void) { count_ = 0; }
virtual void start(void) { count_ = 0; start_ = clock(); }
virtual void stop(void);
virtual void cont(void) { start_ = clock(); }
virtual double seconds(void) const { return (double)count_/(double)freq_; }
protected:
unsigned long freq_;
unsigned long count_;
unsigned long start_;
};
void TimerImplStd::stop(void)
{
unsigned long stop_ = clock();
count_ += stop_-start_;
}
#endif
// ----------------------------------------------------------------- Timer ----
Timer::Timer(void)
{
#if defined(__GNUC__) && defined(__POSIX__)
// CLOCK_REALTIME
// CLOCK_MONOTONIC - ?
// CLOCK_REALTIME_HR - RTlinux
// CLOCK_MONOTONIC_HR - ?
# if defined(CLOCK_REALTIME_HR)
impl_ = new TimerImplPosix<CLOCK_REALTIME_HR>;
# else
impl_ = new TimerImplPosix<CLOCK_REALTIME>;
# endif
#elif (defined(__GNUC__) || (defined(__INTEL_COMPILER) && !defined(WIN32)) ) && !defined(__MINGW32__)
impl_ = new TimerImplGToD;
#else
impl_ = new TimerImplStd;
#endif
state_ = Stopped;
}
Timer::~Timer(void)
{
delete impl_;
state_ = Stopped;
}
void Timer::reset(void)
{
state_ = Stopped;
impl_->reset();
}
void Timer::start(void)
{
state_ = Running;
impl_->start();
}
void Timer::stop(void)
{
impl_->stop();
state_ = Stopped;
}
void Timer::cont(void)
{
impl_->cont();
state_ = Running;
}
double Timer::seconds(void) const
{
return state_==Stopped ? impl_->seconds() : 0.0;
}
std::string Timer::as_string(Timer::Format format)
{
if (state_ == Running)
return "Running";
return as_string(impl_->seconds(),format);
}
std::string Timer::as_string(double seconds, Timer::Format format)
{
char string[32];
double fraction;
double integer;
unsigned long t;
// double rest;
short hour,min,sec;
bool negative = false;
if ( seconds < 0 )
{
negative = true;
seconds *= -1;
}
fraction = modf(seconds,&integer);
t = (unsigned long)integer;
hour = short( t / 3600L );
t %= 3600L;
min = short( t / 60L );
t %= 60L;
sec = short( t );
// rest = (double)t + fraction;
char *ptr = string;
if (negative)
*ptr++ = '-';
switch(format)
{
case Timer::Automatic:
if (hour)
ptr += sprintf(ptr,"%02dh:",hour);
if (min)
ptr += sprintf(ptr,"%02dm:",min);
else if (ptr>string && hour)
ptr += sprintf(ptr,"00m:");
if (sec)
ptr += sprintf(ptr,"%02d",sec);
else if (ptr>string && min)
ptr += sprintf(ptr,"00");
if (!hour && !min) // higher resolution necessary
{
if (ptr > string && sec)
{
sprintf(ptr,".%.3fs",fraction);
ptr++;
while(*(ptr+2))
{
*ptr = *(ptr+2);
ptr++;
}
*ptr = '\0';
}
else if ( fraction * 1e2 > 0.1)
sprintf(ptr,"%.3fcs",fraction*1.e2);
else if ( fraction * 1e3 > 0.1)
sprintf(ptr,"%.3fms",fraction*1.e3);
else if ( fraction * 1e6 > 0.1)
sprintf(ptr,"%.1f\xb5s",fraction*1.e6);
else if ( fraction * 1e9 > 0.1)
sprintf(ptr,"%.1fns",fraction*1.e9);
else
sprintf(ptr,"%.1fps",fraction*1.e12);
} else // append a 's' for seconds!
{
ptr[0] = 's';
ptr[1] = '\0';
}
break;
case Timer::Long:
ptr += sprintf(ptr,"%02dh:%02dm:%02d",hour,min,sec);
sprintf(ptr,".%.12fs",fraction);
ptr++;
while(*(ptr+2))
{
*ptr = *(ptr+2);
ptr++;
}
*ptr = '\0';
break;
case Timer::Hours:
sprintf(ptr,"%02dh:%02dm:%02ds",hour,min,sec); break;
case Timer::Minutes:
ptr += sprintf(ptr,"%02dm:%02d", min, sec);
sprintf(ptr,".%.2fs",fraction);
ptr++;
while(*(ptr+2))
{
*ptr = *(ptr+2);
ptr++;
}
*ptr = '\0';
break;
case Timer::Seconds: sprintf(ptr,"%.3fs",seconds); break;
case Timer::HSeconds: sprintf(ptr,"%.3fcs",seconds*1e2); break;
case Timer::MSeconds: sprintf(ptr,"%.3fms",seconds*1e3); break;
case Timer::MicroSeconds: sprintf(ptr,"%.1f\xb5s",seconds*1e6); break;
case Timer::NanoSeconds: sprintf(ptr,"%.1fns",seconds*1e9); break;
}
return string;
}
// ============================================================================
} // END_NS_UTILS
} // END_NS_OPENMESH
// ----------------------------------------------------------------------------
#endif // DOXY_IGNORE_THIS
// ============================================================================
// end of file Timer.cc
// ============================================================================
<commit_msg>Typo<commit_after>/*===========================================================================*\
* *
* OpenMesh *
* Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
* *
* OpenMesh 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 3 of *
* the License, or (at your option) any later version with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenMesh 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 LesserGeneral Public *
* License along with OpenMesh. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision$ *
* $Date$ *
* *
\*===========================================================================*/
#ifndef DOXY_IGNORE_THIS
// ----------------------------------------------------------------------------
#include <OpenMesh/Core/System/config.h>
#if defined(OM_CC_MIPS)
# include <math.h>
# include <stdio.h>
#else
# include <cmath>
# include <cstdio>
#endif
#include "Timer.hh"
// ----------------------------------------------------------------------------
// ------------------------------------------------------------- namespace ----
namespace OpenMesh {
namespace Utils {
// ----------------------------------------------------------------------------
using namespace std;
// -------------------------------------------------------------- TimerImpl ----
// compiler and os dependent implementation
// ------------------------------------------------------------- posix time ----
#if defined(__GNUC__) && defined(__POSIX__)
#ifndef DOXY_IGNORE_THIS
# include <time.h>
#endif
template <clockid_t N>
class TimerImplPosix : public TimerImpl
{
public:
TimerImplPosix() : id_(N), seconds_(0.0)
{ }
~TimerImplPosix()
{ }
virtual void reset(void) { seconds_ = 0.0; }
virtual void start(void) { seconds_ = 0.0; clock_gettime( id_, &start_ ); }
virtual void stop(void)
{
timespec stop;
clock_gettime( id_, &stop );
seconds_ += ( stop.tv_sec - start_.tv_sec );
seconds_ += ( (double(stop.tv_nsec-start_.tv_nsec)*1e-9) );
}
virtual void cont(void) { clock_gettime( id_, &start_ ); }
virtual double seconds() const { return seconds_; }
protected:
clockid_t id_;
double seconds_;
timespec start_;
};
// ----------------------------------------------------------- gettimeofday ----
#elif (defined(__GNUC__) || (defined(__INTEL_COMPILER) && !defined(WIN32))) && !defined(__MINGW32__)
# include <sys/time.h>
# include <sys/resource.h>
# include <unistd.h>
class TimerImplGToD: public TimerImpl
{
public:
TimerImplGToD() : seconds_(0.0)
{ }
~TimerImplGToD()
{ }
virtual void reset(void) { seconds_ = 0.0; }
virtual void start(void) { seconds_ = 0.0; gettimeofday( &start_, &tz_ ); }
virtual void stop(void)
{
gettimeofday( &stop_, &tz_ );
seconds_ += (double)(stop_.tv_sec - start_.tv_sec);
seconds_ += (double)(stop_.tv_usec- start_.tv_usec)*1e-6;
}
virtual void cont(void) { gettimeofday( &start_, &tz_); }
virtual double seconds() const { return seconds_; }
private:
struct timeval start_, stop_;
struct timezone tz_;
double seconds_;
};
#else // ---------------------------------------- standard implementation ----
#include <time.h>
static const unsigned long clockticks = CLOCKS_PER_SEC;
class TimerImplStd : public TimerImpl
{
public:
TimerImplStd() : freq_(clockticks),count_(0),start_(0) { reset(); }
~TimerImplStd() { ; }
virtual void reset(void) { count_ = 0; }
virtual void start(void) { count_ = 0; start_ = clock(); }
virtual void stop(void);
virtual void cont(void) { start_ = clock(); }
virtual double seconds(void) const { return (double)count_/(double)freq_; }
protected:
unsigned long freq_;
unsigned long count_;
unsigned long start_;
};
void TimerImplStd::stop(void)
{
unsigned long stop_ = clock();
count_ += stop_-start_;
}
#endif
// ----------------------------------------------------------------- Timer ----
Timer::Timer(void)
{
#if defined(__GNUC__) && defined(__POSIX__)
// CLOCK_REALTIME
// CLOCK_MONOTONIC - ?
// CLOCK_REALTIME_HR - RTlinux
// CLOCK_MONOTONIC_HR - ?
# if defined(CLOCK_REALTIME_HR)
impl_ = new TimerImplPosix<CLOCK_REALTIME_HR>;
# else
impl_ = new TimerImplPosix<CLOCK_REALTIME>;
# endif
#elif (defined(__GNUC__) || (defined(__INTEL_COMPILER) && !defined(WIN32)) ) && !defined(__MINGW32__)
impl_ = new TimerImplGToD;
#else
impl_ = new TimerImplStd;
#endif
state_ = Stopped;
}
Timer::~Timer(void)
{
delete impl_;
state_ = Stopped;
}
void Timer::reset(void)
{
state_ = Stopped;
impl_->reset();
}
void Timer::start(void)
{
state_ = Running;
impl_->start();
}
void Timer::stop(void)
{
impl_->stop();
state_ = Stopped;
}
void Timer::cont(void)
{
impl_->cont();
state_ = Running;
}
double Timer::seconds(void) const
{
return state_==Stopped ? impl_->seconds() : 0.0;
}
std::string Timer::as_string(Timer::Format format)
{
if (state_ == Running)
return "Running";
return as_string(impl_->seconds(),format);
}
std::string Timer::as_string(double seconds, Timer::Format format)
{
char string[32];
double fraction;
double integer;
unsigned long t;
// double rest;
short hour,min,sec;
bool negative = false;
if ( seconds < 0 )
{
negative = true;
seconds *= -1;
}
fraction = modf(seconds,&integer);
t = (unsigned long)integer;
hour = short( t / 3600L );
t %= 3600L;
min = short( t / 60L );
t %= 60L;
sec = short( t );
// rest = (double)t + fraction;
char *ptr = string;
if (negative)
*ptr++ = '-';
switch(format)
{
case Timer::Automatic:
if (hour)
ptr += sprintf(ptr,"%02dh:",hour);
if (min)
ptr += sprintf(ptr,"%02dm:",min);
else if (ptr>string && hour)
ptr += sprintf(ptr,"00m:");
if (sec)
ptr += sprintf(ptr,"%02d",sec);
else if (ptr>string && min)
ptr += sprintf(ptr,"00");
if (!hour && !min) // higher resolution necessary
{
if (ptr > string && sec)
{
sprintf(ptr,".%.3fs",fraction);
ptr++;
while(*(ptr+2))
{
*ptr = *(ptr+2);
ptr++;
}
*ptr = '\0';
}
else if ( fraction * 1e2 > 0.1)
sprintf(ptr,"%.3fcs",fraction*1.e2);
else if ( fraction * 1e3 > 0.1)
sprintf(ptr,"%.3fms",fraction*1.e3);
else if ( fraction * 1e6 > 0.1)
sprintf(ptr,"%.1f\xb5s",fraction*1.e6);
else if ( fraction * 1e9 > 0.1)
sprintf(ptr,"%.1fns",fraction*1.e9);
else
sprintf(ptr,"%.1fps",fraction*1.e12);
} else // append a 's' for seconds!
{
ptr[0] = 's';
ptr[1] = '\0';
}
break;
case Timer::Long:
ptr += sprintf(ptr,"%02dh:%02dm:%02d",hour,min,sec);
sprintf(ptr,".%.12fs",fraction);
ptr++;
while(*(ptr+2))
{
*ptr = *(ptr+2);
ptr++;
}
*ptr = '\0';
break;
case Timer::Hours:
sprintf(ptr,"%02dh:%02dm:%02ds",hour,min,sec); break;
case Timer::Minutes:
ptr += sprintf(ptr,"%02dm:%02d", min, sec);
sprintf(ptr,".%.2fs",fraction);
ptr++;
while(*(ptr+2))
{
*ptr = *(ptr+2);
ptr++;
}
*ptr = '\0';
break;
case Timer::Seconds: sprintf(ptr,"%.3fs",seconds); break;
case Timer::HSeconds: sprintf(ptr,"%.3fcs",seconds*1e2); break;
case Timer::MSeconds: sprintf(ptr,"%.3fms",seconds*1e3); break;
case Timer::MicroSeconds: sprintf(ptr,"%.1f\xb5s",seconds*1e6); break;
case Timer::NanoSeconds: sprintf(ptr,"%.1fns",seconds*1e9); break;
}
return string;
}
// ============================================================================
} // END_NS_UTILS
} // END_NS_OPENMESH
// ----------------------------------------------------------------------------
#endif // DOXY_IGNORE_THIS
// ============================================================================
// end of file Timer.cc
// ============================================================================
<|endoftext|> |
<commit_before>#include "SDBPShardConnection.h"
#include "SDBPClient.h"
#include "Application/Common/ClientResponse.h"
#include "Application/SDBP/SDBPRequestMessage.h"
#include "Application/SDBP/SDBPResponseMessage.h"
#define CONN_BUFSIZE 4096
#define CLIENT_MUTEX_GUARD_DECLARE() MutexGuard mutexGuard(client->mutex)
#define CLIENT_MUTEX_LOCK() mutexGuard.Lock()
#define CLIENT_MUTEX_UNLOCK() mutexGuard.Unlock()
using namespace SDBPClient;
static bool LessThan(uint64_t a, uint64_t b)
{
return a < b;
}
ShardConnection::ShardConnection(Client* client_, uint64_t nodeID_, Endpoint& endpoint_)
{
client = client_;
nodeID = nodeID_;
endpoint = endpoint_;
autoFlush = false;
// submitRequest.Init();
Connect();
}
void ShardConnection::Connect()
{
// Log_Debug("Connecting to %s", endpoint.ToString());
MessageConnection::Connect(endpoint);
}
bool ShardConnection::SendRequest(Request* request)
{
SDBPRequestMessage msg;
sentRequests.Append(request);
msg.request = request;
Write(msg);
request->numTry++;
request->requestTime = EventLoop::Now();
//request->requestTime = NowClock();
// if (request->numTry > 1)
// Log_Debug("Resending, commandID: %U, conn: %s", request->commandID, endpoint.ToString());
Log_Debug("Sending conn: %s, writeBuffer = %B", endpoint.ToString(), writeBuffer);
// buffer is saturated
if (writeBuffer->GetLength() >= MESSAGING_BUFFER_THRESHOLD)
return false;
return true;
}
void ShardConnection::SendSubmit(uint64_t /*quorumID*/)
{
// Log_Debug("Flushing, conn: %s", endpoint.ToString());
// SDBPRequestMessage msg;
//
// // TODO: optimize away submitRequest and msg by writing the buffer in constructor
// submitRequest.Submit(quorumID);
// msg.request = &submitRequest;
// Write(msg);
Flush();
}
void ShardConnection::Flush()
{
FlushWriteBuffer();
}
uint64_t ShardConnection::GetNodeID()
{
return nodeID;
}
Endpoint& ShardConnection::GetEndpoint()
{
return endpoint;
}
bool ShardConnection::IsWritePending()
{
return tcpwrite.active;
}
void ShardConnection::SetQuorumMembership(uint64_t quorumID)
{
// SortedList takes care of unique IDs
quorums.Add(quorumID, true);
}
void ShardConnection::ClearQuorumMembership(uint64_t quorumID)
{
quorums.Remove(quorumID);
}
void ShardConnection::ClearQuorumMemberships()
{
quorums.Clear();
}
SortedList<uint64_t>& ShardConnection::GetQuorumList()
{
return quorums;
}
bool ShardConnection::OnMessage(ReadBuffer& rbuf)
{
SDBPResponseMessage msg;
Request* it;
uint64_t quorumID;
CLIENT_MUTEX_GUARD_DECLARE();
Log_Debug("Shard conn: %s, message: %R", endpoint.ToString(), &rbuf);
response.Init();
msg.response = &response;
if (!msg.Read(rbuf))
return false;
// find the request in sent requests by commandID
FOREACH (it, sentRequests)
{
if (it->commandID == response.commandID)
{
// TODO: what to do when the first in the queue returns NOSERVICE
// but the others return OK ?!?
// TODO: invalidate quorum state on NOSERVICE response
if (response.type == CLIENTRESPONSE_NOSERVICE)
{
quorumID = it->quorumID;
InvalidateQuorum(quorumID);
return false;
}
sentRequests.Remove(it);
break;
}
}
client->result->AppendRequestResponse(&response);
response.Init();
return false;
}
void ShardConnection::OnWrite()
{
CLIENT_MUTEX_GUARD_DECLARE();
MessageConnection::OnWrite();
SendQuorumRequests();
}
void ShardConnection::OnConnect()
{
Log_Trace();
Log_Debug("Shard connection connected, endpoint: %s", endpoint.ToString());
CLIENT_MUTEX_GUARD_DECLARE();
MessageConnection::OnConnect();
SendQuorumRequests();
}
void ShardConnection::OnClose()
{
// Log_Debug("Shard connection closing: %s", endpoint.ToString());
Request* it;
Request* prev;
uint64_t* itQuorum;
uint64_t* itNext;
CLIENT_MUTEX_GUARD_DECLARE();
// close the socket and try reconnecting
MessageConnection::OnClose();
// invalidate quorums
for (itQuorum = quorums.First(); itQuorum != NULL; itQuorum = itNext)
{
itNext = quorums.Next(itQuorum);
InvalidateQuorum(*itQuorum);
}
// put back requests that have no response to the client's quorum queue
for (it = sentRequests.Last(); it != NULL; it = prev)
{
prev = sentRequests.Prev(it);
sentRequests.Remove(it);
client->AddRequestToQuorum(it, false);
}
}
void ShardConnection::InvalidateQuorum(uint64_t quorumID)
{
Request* it;
Request* prev;
for (it = sentRequests.Last(); it != NULL; it = prev)
{
prev = sentRequests.Prev(it);
if (it->quorumID == quorumID)
{
sentRequests.Remove(it);
client->AddRequestToQuorum(it, false);
}
}
client->InvalidateQuorum(quorumID, nodeID);
}
void ShardConnection::SendQuorumRequests()
{
uint64_t* qit;
// notify the client so that it can assign the requests to the connection
FOREACH (qit, quorums)
client->SendQuorumRequest(this, *qit);
}
<commit_msg>Removed Log_Debug from client.<commit_after>#include "SDBPShardConnection.h"
#include "SDBPClient.h"
#include "Application/Common/ClientResponse.h"
#include "Application/SDBP/SDBPRequestMessage.h"
#include "Application/SDBP/SDBPResponseMessage.h"
#define CONN_BUFSIZE 4096
#define CLIENT_MUTEX_GUARD_DECLARE() MutexGuard mutexGuard(client->mutex)
#define CLIENT_MUTEX_LOCK() mutexGuard.Lock()
#define CLIENT_MUTEX_UNLOCK() mutexGuard.Unlock()
using namespace SDBPClient;
static bool LessThan(uint64_t a, uint64_t b)
{
return a < b;
}
ShardConnection::ShardConnection(Client* client_, uint64_t nodeID_, Endpoint& endpoint_)
{
client = client_;
nodeID = nodeID_;
endpoint = endpoint_;
autoFlush = false;
// submitRequest.Init();
Connect();
}
void ShardConnection::Connect()
{
// Log_Debug("Connecting to %s", endpoint.ToString());
MessageConnection::Connect(endpoint);
}
bool ShardConnection::SendRequest(Request* request)
{
SDBPRequestMessage msg;
sentRequests.Append(request);
msg.request = request;
Write(msg);
request->numTry++;
request->requestTime = EventLoop::Now();
//request->requestTime = NowClock();
// if (request->numTry > 1)
// Log_Debug("Resending, commandID: %U, conn: %s", request->commandID, endpoint.ToString());
//Log_Debug("Sending conn: %s, writeBuffer = %B", endpoint.ToString(), writeBuffer);
// buffer is saturated
if (writeBuffer->GetLength() >= MESSAGING_BUFFER_THRESHOLD)
return false;
return true;
}
void ShardConnection::SendSubmit(uint64_t /*quorumID*/)
{
// Log_Debug("Flushing, conn: %s", endpoint.ToString());
// SDBPRequestMessage msg;
//
// // TODO: optimize away submitRequest and msg by writing the buffer in constructor
// submitRequest.Submit(quorumID);
// msg.request = &submitRequest;
// Write(msg);
Flush();
}
void ShardConnection::Flush()
{
FlushWriteBuffer();
}
uint64_t ShardConnection::GetNodeID()
{
return nodeID;
}
Endpoint& ShardConnection::GetEndpoint()
{
return endpoint;
}
bool ShardConnection::IsWritePending()
{
return tcpwrite.active;
}
void ShardConnection::SetQuorumMembership(uint64_t quorumID)
{
// SortedList takes care of unique IDs
quorums.Add(quorumID, true);
}
void ShardConnection::ClearQuorumMembership(uint64_t quorumID)
{
quorums.Remove(quorumID);
}
void ShardConnection::ClearQuorumMemberships()
{
quorums.Clear();
}
SortedList<uint64_t>& ShardConnection::GetQuorumList()
{
return quorums;
}
bool ShardConnection::OnMessage(ReadBuffer& rbuf)
{
SDBPResponseMessage msg;
Request* it;
uint64_t quorumID;
CLIENT_MUTEX_GUARD_DECLARE();
//Log_Debug("Shard conn: %s, message: %R", endpoint.ToString(), &rbuf);
response.Init();
msg.response = &response;
if (!msg.Read(rbuf))
return false;
// find the request in sent requests by commandID
FOREACH (it, sentRequests)
{
if (it->commandID == response.commandID)
{
// TODO: what to do when the first in the queue returns NOSERVICE
// but the others return OK ?!?
// TODO: invalidate quorum state on NOSERVICE response
if (response.type == CLIENTRESPONSE_NOSERVICE)
{
quorumID = it->quorumID;
InvalidateQuorum(quorumID);
return false;
}
sentRequests.Remove(it);
break;
}
}
client->result->AppendRequestResponse(&response);
response.Init();
return false;
}
void ShardConnection::OnWrite()
{
CLIENT_MUTEX_GUARD_DECLARE();
MessageConnection::OnWrite();
SendQuorumRequests();
}
void ShardConnection::OnConnect()
{
Log_Trace();
//Log_Debug("Shard connection connected, endpoint: %s", endpoint.ToString());
CLIENT_MUTEX_GUARD_DECLARE();
MessageConnection::OnConnect();
SendQuorumRequests();
}
void ShardConnection::OnClose()
{
// Log_Debug("Shard connection closing: %s", endpoint.ToString());
Request* it;
Request* prev;
uint64_t* itQuorum;
uint64_t* itNext;
CLIENT_MUTEX_GUARD_DECLARE();
// close the socket and try reconnecting
MessageConnection::OnClose();
// invalidate quorums
for (itQuorum = quorums.First(); itQuorum != NULL; itQuorum = itNext)
{
itNext = quorums.Next(itQuorum);
InvalidateQuorum(*itQuorum);
}
// put back requests that have no response to the client's quorum queue
for (it = sentRequests.Last(); it != NULL; it = prev)
{
prev = sentRequests.Prev(it);
sentRequests.Remove(it);
client->AddRequestToQuorum(it, false);
}
}
void ShardConnection::InvalidateQuorum(uint64_t quorumID)
{
Request* it;
Request* prev;
for (it = sentRequests.Last(); it != NULL; it = prev)
{
prev = sentRequests.Prev(it);
if (it->quorumID == quorumID)
{
sentRequests.Remove(it);
client->AddRequestToQuorum(it, false);
}
}
client->InvalidateQuorum(quorumID, nodeID);
}
void ShardConnection::SendQuorumRequests()
{
uint64_t* qit;
// notify the client so that it can assign the requests to the connection
FOREACH (qit, quorums)
client->SendQuorumRequest(this, *qit);
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.