text
stringlengths 54
60.6k
|
|---|
<commit_before>#include "ValidSudoku.hpp"
bool ValidSudoku::isValidSudoku(vector<vector<char>>& board)
{
bool used1[9][9] = {false}, used2[9][9] = {false}, used3[9][9] = {false};
for(int i = 0; i < board.size(); i++)
for(int j = 0; j < board[i].size(); j++)
if (board[i][j] != '.') {
int num = board[i][j] - '0' - 1;
int k = i / 3 * 3 + j / 3;
if (used1[i][num] || used2[j][num] || used3[k][num])
return false;
used1[i][num] = used2[j][num] = used3[k][num] = true;
}
return true;
}
<commit_msg>Refine Problem 36. Valid Sudoku<commit_after>#include "ValidSudoku.hpp"
bool ValidSudoku::isValidSudoku(vector<vector<char>>& board)
{
bool used1[9][9] = {false}, used2[9][9] = {false}, used3[9][9] = {false};
for (int i = 0; i < board.size(); i++)
for (int j = 0; j < board[i].size(); j++)
if (board[i][j] != '.') {
int num = board[i][j] - '0' - 1;
int k = i / 3 * 3 + j / 3;
if (used1[i][num] || used2[j][num] || used3[k][num])
return false;
used1[i][num] = used2[j][num] = used3[k][num] = true;
}
return true;
}
<|endoftext|>
|
<commit_before>/*
* A wrapper for an async_operation which unrefs the pool on abort.
*
* This solves a problem of many libraries which reference a pool, but
* pass the async_ref object to another library. When the caller
* aborts the operation, the "middle" library never gets a chance to
* unref the pool; plugging this wrapper solves this problem.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "abort_unref.hxx"
#include "async.hxx"
#include "pool.hxx"
#include "util/Cast.hxx"
struct UnrefOnAbort {
struct pool &pool;
struct async_operation operation;
struct async_operation_ref ref;
#ifdef TRACE
const char *const file;
unsigned line;
#endif
UnrefOnAbort(struct pool &_pool,
struct async_operation_ref &async_ref
TRACE_ARGS_DECL_)
:pool(_pool)
TRACE_ARGS_INIT {
operation.Init2<UnrefOnAbort>();
async_ref.Set(operation);
}
void Abort() {
ref.Abort();
pool_unref_fwd(&pool);
}
};
/*
* constructor
*
*/
struct async_operation_ref &
async_unref_on_abort_impl(struct pool &pool,
struct async_operation_ref &async_ref
TRACE_ARGS_DECL)
{
auto uoa = NewFromPool<UnrefOnAbort>(pool, pool, async_ref
TRACE_ARGS_FWD);
return uoa->ref;
}
<commit_msg>abort_unref: migrate to class Cancellable<commit_after>/*
* A wrapper for an async_operation which unrefs the pool on abort.
*
* This solves a problem of many libraries which reference a pool, but
* pass the async_ref object to another library. When the caller
* aborts the operation, the "middle" library never gets a chance to
* unref the pool; plugging this wrapper solves this problem.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "abort_unref.hxx"
#include "async.hxx"
#include "pool.hxx"
#include "util/Cast.hxx"
struct UnrefOnAbort final : Cancellable {
struct pool &pool;
struct async_operation_ref ref;
#ifdef TRACE
const char *const file;
unsigned line;
#endif
UnrefOnAbort(struct pool &_pool,
struct async_operation_ref &async_ref
TRACE_ARGS_DECL_)
:pool(_pool)
TRACE_ARGS_INIT {
async_ref = *this;
}
/* virtual methods from class Cancellable */
void Cancel() override {
ref.Abort();
pool_unref_fwd(&pool);
}
};
/*
* constructor
*
*/
struct async_operation_ref &
async_unref_on_abort_impl(struct pool &pool,
struct async_operation_ref &async_ref
TRACE_ARGS_DECL)
{
auto uoa = NewFromPool<UnrefOnAbort>(pool, pool, async_ref
TRACE_ARGS_FWD);
return uoa->ref;
}
<|endoftext|>
|
<commit_before>#include "accumulator.h"
#include "thread/loopi.h"
using namespace nano;
accumulator_t::accumulator_t(const model_t& model, const loss_t& loss) :
m_type(type::value), m_loss(loss)
{
const auto size = thread_pool_t::instance().workers();
for (size_t i = 0; i < size; ++ i)
{
m_tcaches.emplace_back(model);
}
}
void accumulator_t::clear()
{
for (auto& tcache : m_tcaches)
{
tcache.m_vstats.clear();
tcache.m_estats.clear();
if (m_type == type::vgrad)
{
tcache.m_vgrad.setZero();
}
}
}
void accumulator_t::random()
{
origin().m_model->random();
params(origin().m_model->params());
}
void accumulator_t::params(const vector_t& params)
{
for (auto& tcache : m_tcaches)
{
tcache.m_model->params(params);
}
clear();
}
void accumulator_t::mode(const accumulator_t::type t)
{
m_type = t;
clear();
}
void accumulator_t::lambda(const scalar_t lambda)
{
m_lambda = lambda;
clear();
}
void accumulator_t::minibatch(const size_t minibatch_size)
{
m_batch = minibatch_size;
}
void accumulator_t::update(const task_t& task, const fold_t& fold)
{
update(task, fold, 0, task.size(fold));
}
void accumulator_t::update(const task_t& task, const fold_t& fold, const size_t begin, const size_t end)
{
assert(begin <= end);
const auto old_count = vstats().count();
loopit(end - begin, m_batch, [&] (const size_t ibegin, const size_t iend, const size_t thread)
{
assert(thread < m_tcaches.size());
assert(ibegin < iend && iend + begin <= end);
update(m_tcaches[thread], task.get(fold, begin + ibegin, begin + iend));
});
NANO_UNUSED1_RELEASE(old_count);
assert(old_count + end == begin + vstats().count());
}
void accumulator_t::update(tcache_t& tcache, const minibatch_t& minibatch)
{
update(tcache, minibatch.odata(), minibatch.idata());
}
void accumulator_t::update(tcache_t& tcache, const tensor4d_t& targets, const tensor4d_t& inputs)
{
const auto& outputs = tcache.m_model->output(inputs);
const auto values = m_loss.value(targets, outputs);
const auto errors = m_loss.error(targets, outputs);
assert(outputs.size<0>() == values.size<0>());
assert(outputs.size<0>() == errors.size<0>());
tcache.m_vstats(values.data(), values.data() + values.size());
tcache.m_estats(errors.data(), errors.data() + errors.size());
if (m_type == type::vgrad)
{
tcache.m_vgrad += tcache.m_model->gparam(m_loss.vgrad(targets, outputs));
}
}
void accumulator_t::accumulate()
{
auto& origin = this->origin();
for (const auto& tcache : m_tcaches)
{
if (&tcache != &origin)
{
origin.m_vstats(tcache.m_vstats);
origin.m_estats(tcache.m_estats);
if (m_type == type::vgrad)
{
origin.m_vgrad += tcache.m_vgrad;
}
}
}
}
accumulator_t::tcache_t& accumulator_t::origin()
{
return *m_tcaches.begin();
}
const accumulator_t::tcache_t& accumulator_t::origin() const
{
return *m_tcaches.cbegin();
}
const stats_t<scalar_t>& accumulator_t::vstats() const
{
return origin().m_vstats;
}
const stats_t<scalar_t>& accumulator_t::estats() const
{
return origin().m_estats;
}
scalar_t accumulator_t::value() const
{
assert(vstats().count() > 0);
return vstats().avg() + (m_lambda / 2) * params().squaredNorm();
}
vector_t accumulator_t::vgrad() const
{
assert(vstats().count() > 0);
assert(m_type == type::vgrad);
return origin().m_vgrad / vstats().count() + m_lambda * params();
}
tensor_size_t accumulator_t::psize() const
{
return origin().m_model->psize();
}
const vector_t& accumulator_t::params() const
{
return origin().m_model->params();
}
probes_t accumulator_t::probes() const
{
return origin().m_model->probes();
}
<commit_msg>fix accumulator<commit_after>#include "accumulator.h"
#include "thread/loopi.h"
using namespace nano;
accumulator_t::accumulator_t(const model_t& model, const loss_t& loss) :
m_type(type::value), m_loss(loss)
{
const auto size = thread_pool_t::instance().workers();
for (size_t i = 0; i < size; ++ i)
{
m_tcaches.emplace_back(model);
}
}
void accumulator_t::clear()
{
for (auto& tcache : m_tcaches)
{
tcache.m_vstats.clear();
tcache.m_estats.clear();
if (m_type == type::vgrad)
{
tcache.m_vgrad.setZero();
}
}
}
void accumulator_t::random()
{
origin().m_model->random();
params(origin().m_model->params());
}
void accumulator_t::params(const vector_t& params)
{
for (auto& tcache : m_tcaches)
{
tcache.m_model->params(params);
}
clear();
}
void accumulator_t::mode(const accumulator_t::type t)
{
m_type = t;
clear();
}
void accumulator_t::lambda(const scalar_t lambda)
{
m_lambda = lambda;
clear();
}
void accumulator_t::minibatch(const size_t minibatch_size)
{
m_batch = minibatch_size;
}
void accumulator_t::update(const task_t& task, const fold_t& fold)
{
update(task, fold, 0, task.size(fold));
}
void accumulator_t::update(const task_t& task, const fold_t& fold, const size_t begin, const size_t end)
{
assert(begin <= end);
const auto old_count = vstats().count();
loopit(end - begin, m_batch, [&] (const size_t ibegin, const size_t iend, const size_t thread)
{
assert(thread < m_tcaches.size());
assert(ibegin < iend && iend + begin <= end);
update(m_tcaches[thread], task.get(fold, begin + ibegin, begin + iend));
});
accumulate();
NANO_UNUSED1_RELEASE(old_count);
assert(old_count + end == begin + vstats().count());
}
void accumulator_t::update(tcache_t& tcache, const minibatch_t& minibatch)
{
update(tcache, minibatch.odata(), minibatch.idata());
}
void accumulator_t::update(tcache_t& tcache, const tensor4d_t& targets, const tensor4d_t& inputs)
{
const auto& outputs = tcache.m_model->output(inputs);
const auto values = m_loss.value(targets, outputs);
const auto errors = m_loss.error(targets, outputs);
assert(outputs.size<0>() == values.size<0>());
assert(outputs.size<0>() == errors.size<0>());
tcache.m_vstats(values.data(), values.data() + values.size());
tcache.m_estats(errors.data(), errors.data() + errors.size());
if (m_type == type::vgrad)
{
tcache.m_vgrad += tcache.m_model->gparam(m_loss.vgrad(targets, outputs));
}
}
void accumulator_t::accumulate()
{
auto& origin = this->origin();
for (const auto& tcache : m_tcaches)
{
if (&tcache != &origin)
{
origin.m_vstats(tcache.m_vstats);
origin.m_estats(tcache.m_estats);
if (m_type == type::vgrad)
{
origin.m_vgrad += tcache.m_vgrad;
}
}
}
}
accumulator_t::tcache_t& accumulator_t::origin()
{
return *m_tcaches.begin();
}
const accumulator_t::tcache_t& accumulator_t::origin() const
{
return *m_tcaches.cbegin();
}
const stats_t<scalar_t>& accumulator_t::vstats() const
{
return origin().m_vstats;
}
const stats_t<scalar_t>& accumulator_t::estats() const
{
return origin().m_estats;
}
scalar_t accumulator_t::value() const
{
assert(vstats().count() > 0);
return vstats().avg() + (m_lambda / 2) * params().squaredNorm();
}
vector_t accumulator_t::vgrad() const
{
assert(vstats().count() > 0);
assert(m_type == type::vgrad);
return origin().m_vgrad / vstats().count() + m_lambda * params();
}
tensor_size_t accumulator_t::psize() const
{
return origin().m_model->psize();
}
const vector_t& accumulator_t::params() const
{
return origin().m_model->params();
}
probes_t accumulator_t::probes() const
{
return origin().m_model->probes();
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014-2022 Patrizio Bekerle -- <patrizio@bekerle.com>
*
* 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; version 2 of the License.
*
* 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.
*
*/
#include "qplaintexteditsearchwidget.h"
#include <QDebug>
#include <QEvent>
#include <QKeyEvent>
#include "ui_qplaintexteditsearchwidget.h"
QPlainTextEditSearchWidget::QPlainTextEditSearchWidget(QPlainTextEdit *parent)
: QWidget(parent),
ui(new Ui::QPlainTextEditSearchWidget),
selectionColor(0, 180, 0, 100) {
ui->setupUi(this);
_textEdit = parent;
_darkMode = false;
hide();
ui->searchCountLabel->setStyleSheet(QStringLiteral("* {color: grey}"));
// hiding will leave a open space in the horizontal layout
ui->searchCountLabel->setEnabled(false);
_currentSearchResult = 0;
_searchResultCount = 0;
connect(ui->closeButton, &QPushButton::clicked, this,
&QPlainTextEditSearchWidget::deactivate);
connect(ui->searchLineEdit, &QLineEdit::textChanged, this,
&QPlainTextEditSearchWidget::searchLineEditTextChanged);
connect(ui->searchDownButton, &QPushButton::clicked, this,
&QPlainTextEditSearchWidget::doSearchDown);
connect(ui->searchUpButton, &QPushButton::clicked, this,
&QPlainTextEditSearchWidget::doSearchUp);
connect(ui->replaceToggleButton, &QPushButton::toggled, this,
&QPlainTextEditSearchWidget::setReplaceMode);
connect(ui->replaceButton, &QPushButton::clicked, this,
&QPlainTextEditSearchWidget::doReplace);
connect(ui->replaceAllButton, &QPushButton::clicked, this,
&QPlainTextEditSearchWidget::doReplaceAll);
connect(&_debounceTimer, &QTimer::timeout,
this, &QPlainTextEditSearchWidget::performSearch);
installEventFilter(this);
ui->searchLineEdit->installEventFilter(this);
ui->replaceLineEdit->installEventFilter(this);
#ifdef Q_OS_MAC
// set the spacing to 8 for OS X
layout()->setSpacing(8);
ui->buttonFrame->layout()->setSpacing(9);
// set the margin to 0 for the top buttons for OS X
QString buttonStyle = "QPushButton {margin: 0}";
ui->closeButton->setStyleSheet(buttonStyle);
ui->searchDownButton->setStyleSheet(buttonStyle);
ui->searchUpButton->setStyleSheet(buttonStyle);
ui->replaceToggleButton->setStyleSheet(buttonStyle);
ui->matchCaseSensitiveButton->setStyleSheet(buttonStyle);
#endif
}
QPlainTextEditSearchWidget::~QPlainTextEditSearchWidget() { delete ui; }
void QPlainTextEditSearchWidget::activate() { activate(true); }
void QPlainTextEditSearchWidget::activateReplace() {
// replacing is prohibited if the text edit is readonly
if (_textEdit->isReadOnly()) {
return;
}
ui->searchLineEdit->setText(_textEdit->textCursor().selectedText());
ui->searchLineEdit->selectAll();
activate();
setReplaceMode(true);
}
void QPlainTextEditSearchWidget::deactivate() {
stopDebounce();
hide();
// Clear the search extra selections when closing the search bar
clearSearchExtraSelections();
_textEdit->setFocus();
}
void QPlainTextEditSearchWidget::setReplaceMode(bool enabled) {
ui->replaceToggleButton->setChecked(enabled);
ui->replaceLabel->setVisible(enabled);
ui->replaceLineEdit->setVisible(enabled);
ui->modeLabel->setVisible(enabled);
ui->buttonFrame->setVisible(enabled);
ui->matchCaseSensitiveButton->setVisible(enabled);
}
bool QPlainTextEditSearchWidget::eventFilter(QObject *obj, QEvent *event) {
if (event->type() == QEvent::KeyPress) {
auto *keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->key() == Qt::Key_Escape) {
deactivate();
return true;
} else if ((!_debounceTimer.isActive() &&
keyEvent->modifiers().testFlag(Qt::ShiftModifier) &&
(keyEvent->key() == Qt::Key_Return)) ||
(keyEvent->key() == Qt::Key_Up)) {
doSearchUp();
return true;
} else if (!_debounceTimer.isActive() &&
((keyEvent->key() == Qt::Key_Return) ||
(keyEvent->key() == Qt::Key_Down))) {
doSearchDown();
return true;
} else if (!_debounceTimer.isActive() && keyEvent->key() == Qt::Key_F3) {
doSearch(!keyEvent->modifiers().testFlag(Qt::ShiftModifier));
return true;
}
// if ((obj == ui->replaceLineEdit) && (keyEvent->key() ==
// Qt::Key_Tab)
// && ui->replaceToggleButton->isChecked()) {
// ui->replaceLineEdit->setFocus();
// }
return false;
}
return QWidget::eventFilter(obj, event);
}
void QPlainTextEditSearchWidget::searchLineEditTextChanged(
const QString &arg1) {
_searchTerm = arg1;
if (_debounceTimer.interval() != 0 && !_searchTerm.isEmpty()) {
_debounceTimer.start();
ui->searchDownButton->setEnabled(false);
ui->searchUpButton->setEnabled(false);
} else {
performSearch();
}
}
void QPlainTextEditSearchWidget::performSearch()
{
const int searchMode = ui->modeComboBox->currentIndex();
if (searchMode == RegularExpressionMode) {
// Prevent stuck application when the user enters just start or end markers
static const QRegularExpression regExp(R"(^[\^\$]+$)");
if (regExp.match(_searchTerm).hasMatch()) {
clearSearchExtraSelections();
if (_debounceTimer.isActive()) {
stopDebounce();
}
return;
}
}
doSearchCount();
updateSearchExtraSelections();
doSearchDown();
}
void QPlainTextEditSearchWidget::clearSearchExtraSelections() {
_searchExtraSelections.clear();
setSearchExtraSelections();
}
void QPlainTextEditSearchWidget::updateSearchExtraSelections() {
_searchExtraSelections.clear();
const auto textCursor = _textEdit->textCursor();
_textEdit->moveCursor(QTextCursor::Start);
const QColor color = selectionColor;
QTextCharFormat extraFmt;
extraFmt.setBackground(color);
while (doSearch(true, false, false)) {
QTextEdit::ExtraSelection extra = QTextEdit::ExtraSelection();
extra.format = extraFmt;
extra.cursor = _textEdit->textCursor();
_searchExtraSelections.append(extra);
}
_textEdit->setTextCursor(textCursor);
this->setSearchExtraSelections();
}
void QPlainTextEditSearchWidget::setSearchExtraSelections() const {
this->_textEdit->setExtraSelections(this->_searchExtraSelections);
}
void QPlainTextEditSearchWidget::stopDebounce()
{
_debounceTimer.stop();
ui->searchDownButton->setEnabled(true);
ui->searchUpButton->setEnabled(true);
}
void QPlainTextEditSearchWidget::doSearchUp() { doSearch(false); }
void QPlainTextEditSearchWidget::doSearchDown() { doSearch(true); }
bool QPlainTextEditSearchWidget::doReplace(bool forAll) {
if (_textEdit->isReadOnly()) {
return false;
}
QTextCursor cursor = _textEdit->textCursor();
if (!forAll && cursor.selectedText().isEmpty()) {
return false;
}
const int searchMode = ui->modeComboBox->currentIndex();
if (searchMode == RegularExpressionMode) {
QString text = cursor.selectedText();
text.replace(QRegularExpression(ui->searchLineEdit->text()),
ui->replaceLineEdit->text());
cursor.insertText(text);
} else {
cursor.insertText(ui->replaceLineEdit->text());
}
if (!forAll) {
const int position = cursor.position();
if (!doSearch(true)) {
// restore the last cursor position if text wasn't found any more
cursor.setPosition(position);
_textEdit->setTextCursor(cursor);
}
}
return true;
}
void QPlainTextEditSearchWidget::doReplaceAll() {
if (_textEdit->isReadOnly()) {
return;
}
// start at the top
_textEdit->moveCursor(QTextCursor::Start);
// replace until everything to the bottom is replaced
while (doSearch(true, false) && doReplace(true)) {
}
}
/**
* @brief Searches for text in the text edit
* @returns true if found
*/
bool QPlainTextEditSearchWidget::doSearch(bool searchDown,
bool allowRestartAtTop,
bool updateUI) {
if (_debounceTimer.isActive()) {
stopDebounce();
}
const QString text = ui->searchLineEdit->text();
if (text.isEmpty()) {
if (updateUI) {
ui->searchLineEdit->setStyleSheet(QLatin1String(""));
}
return false;
}
const int searchMode = ui->modeComboBox->currentIndex();
const bool caseSensitive = ui->matchCaseSensitiveButton->isChecked();
QFlags<QTextDocument::FindFlag> options =
searchDown ? QTextDocument::FindFlag(0) : QTextDocument::FindBackward;
if (searchMode == WholeWordsMode) {
options |= QTextDocument::FindWholeWords;
}
if (caseSensitive) {
options |= QTextDocument::FindCaseSensitively;
}
// block signal to reduce too many signals being fired and too many updates
_textEdit->blockSignals(true);
bool found =
searchMode == RegularExpressionMode
?
#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))
_textEdit->find(
QRegularExpression(
text, caseSensitive
? QRegularExpression::NoPatternOption
: QRegularExpression::CaseInsensitiveOption),
options)
:
#else
_textEdit->find(QRegExp(text, caseSensitive ? Qt::CaseSensitive
: Qt::CaseInsensitive),
options)
:
#endif
_textEdit->find(text, options);
_textEdit->blockSignals(false);
if (found) {
const int result =
searchDown ? ++_currentSearchResult : --_currentSearchResult;
_currentSearchResult = std::min(result, _searchResultCount);
updateSearchCountLabelText();
}
// start at the top (or bottom) if not found
if (!found && allowRestartAtTop) {
_textEdit->moveCursor(searchDown ? QTextCursor::Start
: QTextCursor::End);
found =
searchMode == RegularExpressionMode
?
#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))
_textEdit->find(
QRegularExpression(
text, caseSensitive
? QRegularExpression::NoPatternOption
: QRegularExpression::CaseInsensitiveOption),
options)
:
#else
_textEdit->find(
QRegExp(text, caseSensitive ? Qt::CaseSensitive
: Qt::CaseInsensitive),
options)
:
#endif
_textEdit->find(text, options);
if (found && updateUI) {
_currentSearchResult = searchDown ? 1 : _searchResultCount;
updateSearchCountLabelText();
}
}
if (updateUI) {
const QRect rect = _textEdit->cursorRect();
QMargins margins = _textEdit->layout()->contentsMargins();
const int searchWidgetHotArea = _textEdit->height() - this->height();
const int marginBottom =
(rect.y() > searchWidgetHotArea) ? (this->height() + 10) : 0;
// move the search box a bit up if we would block the search result
if (margins.bottom() != marginBottom) {
margins.setBottom(marginBottom);
_textEdit->layout()->setContentsMargins(margins);
}
// add a background color according if we found the text or not
const QString bgColorCode =
_darkMode
? (found ? QStringLiteral("#135a13")
: QStringLiteral("#8d2b36"))
: found ? QStringLiteral("#D5FAE2") : QStringLiteral("#FAE9EB");
const QString fgColorCode =
_darkMode ? QStringLiteral("#cccccc") : QStringLiteral("#404040");
ui->searchLineEdit->setStyleSheet(
QStringLiteral("* { background: ") + bgColorCode +
QStringLiteral("; color: ") + fgColorCode + QStringLiteral("; }"));
// restore the search extra selections after the find command
this->setSearchExtraSelections();
}
return found;
}
/**
* @brief Counts the search results
*/
void QPlainTextEditSearchWidget::doSearchCount() {
// Note that we are moving the anchor, so the search will start from the top
// again! Alternative: Restore cursor position afterwards, but then we will
// not know
// at what _currentSearchResult we currently are
_textEdit->moveCursor(QTextCursor::Start, QTextCursor::MoveAnchor);
bool found;
_searchResultCount = 0;
_currentSearchResult = 0;
do {
found = doSearch(true, false, false);
if (found) {
_searchResultCount++;
}
} while (found);
updateSearchCountLabelText();
}
void QPlainTextEditSearchWidget::setDarkMode(bool enabled) {
_darkMode = enabled;
}
void QPlainTextEditSearchWidget::setSearchText(const QString &searchText) {
ui->searchLineEdit->setText(searchText);
}
void QPlainTextEditSearchWidget::setSearchMode(SearchMode searchMode) {
ui->modeComboBox->setCurrentIndex(searchMode);
}
void QPlainTextEditSearchWidget::setDebounceDelay(uint debounceDelay)
{
_debounceTimer.setInterval(static_cast<int>(debounceDelay));
}
void QPlainTextEditSearchWidget::activate(bool focus) {
setReplaceMode(ui->modeComboBox->currentIndex() !=
SearchMode::PlainTextMode);
show();
// preset the selected text as search text if there is any and there is no
// other search text
const QString selectedText = _textEdit->textCursor().selectedText();
if (!selectedText.isEmpty() && ui->searchLineEdit->text().isEmpty()) {
ui->searchLineEdit->setText(selectedText);
}
if (focus) {
ui->searchLineEdit->setFocus();
}
ui->searchLineEdit->selectAll();
updateSearchExtraSelections();
doSearchDown();
}
void QPlainTextEditSearchWidget::reset() {
ui->searchLineEdit->clear();
setSearchMode(SearchMode::PlainTextMode);
setReplaceMode(false);
ui->searchCountLabel->setEnabled(false);
}
void QPlainTextEditSearchWidget::updateSearchCountLabelText() {
ui->searchCountLabel->setEnabled(true);
ui->searchCountLabel->setText(QString("%1/%2").arg(
_currentSearchResult == 0 ? QChar('-')
: QString::number(_currentSearchResult),
_searchResultCount == 0 ? QChar('-')
: QString::number(_searchResultCount)));
}
void QPlainTextEditSearchWidget::setSearchSelectionColor(const QColor &color) {
selectionColor = color;
}
void QPlainTextEditSearchWidget::on_modeComboBox_currentIndexChanged(
int index) {
Q_UNUSED(index)
doSearchCount();
doSearchDown();
}
void QPlainTextEditSearchWidget::on_matchCaseSensitiveButton_toggled(
bool checked) {
Q_UNUSED(checked)
doSearchCount();
doSearchDown();
}
<commit_msg>Improve stuck regular expression detection while searching (pbek/QOwnNotes#2302)<commit_after>/*
* Copyright (c) 2014-2022 Patrizio Bekerle -- <patrizio@bekerle.com>
*
* 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; version 2 of the License.
*
* 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.
*
*/
#include "qplaintexteditsearchwidget.h"
#include <QDebug>
#include <QEvent>
#include <QKeyEvent>
#include "ui_qplaintexteditsearchwidget.h"
QPlainTextEditSearchWidget::QPlainTextEditSearchWidget(QPlainTextEdit *parent)
: QWidget(parent),
ui(new Ui::QPlainTextEditSearchWidget),
selectionColor(0, 180, 0, 100) {
ui->setupUi(this);
_textEdit = parent;
_darkMode = false;
hide();
ui->searchCountLabel->setStyleSheet(QStringLiteral("* {color: grey}"));
// hiding will leave a open space in the horizontal layout
ui->searchCountLabel->setEnabled(false);
_currentSearchResult = 0;
_searchResultCount = 0;
connect(ui->closeButton, &QPushButton::clicked, this,
&QPlainTextEditSearchWidget::deactivate);
connect(ui->searchLineEdit, &QLineEdit::textChanged, this,
&QPlainTextEditSearchWidget::searchLineEditTextChanged);
connect(ui->searchDownButton, &QPushButton::clicked, this,
&QPlainTextEditSearchWidget::doSearchDown);
connect(ui->searchUpButton, &QPushButton::clicked, this,
&QPlainTextEditSearchWidget::doSearchUp);
connect(ui->replaceToggleButton, &QPushButton::toggled, this,
&QPlainTextEditSearchWidget::setReplaceMode);
connect(ui->replaceButton, &QPushButton::clicked, this,
&QPlainTextEditSearchWidget::doReplace);
connect(ui->replaceAllButton, &QPushButton::clicked, this,
&QPlainTextEditSearchWidget::doReplaceAll);
connect(&_debounceTimer, &QTimer::timeout,
this, &QPlainTextEditSearchWidget::performSearch);
installEventFilter(this);
ui->searchLineEdit->installEventFilter(this);
ui->replaceLineEdit->installEventFilter(this);
#ifdef Q_OS_MAC
// set the spacing to 8 for OS X
layout()->setSpacing(8);
ui->buttonFrame->layout()->setSpacing(9);
// set the margin to 0 for the top buttons for OS X
QString buttonStyle = "QPushButton {margin: 0}";
ui->closeButton->setStyleSheet(buttonStyle);
ui->searchDownButton->setStyleSheet(buttonStyle);
ui->searchUpButton->setStyleSheet(buttonStyle);
ui->replaceToggleButton->setStyleSheet(buttonStyle);
ui->matchCaseSensitiveButton->setStyleSheet(buttonStyle);
#endif
}
QPlainTextEditSearchWidget::~QPlainTextEditSearchWidget() { delete ui; }
void QPlainTextEditSearchWidget::activate() { activate(true); }
void QPlainTextEditSearchWidget::activateReplace() {
// replacing is prohibited if the text edit is readonly
if (_textEdit->isReadOnly()) {
return;
}
ui->searchLineEdit->setText(_textEdit->textCursor().selectedText());
ui->searchLineEdit->selectAll();
activate();
setReplaceMode(true);
}
void QPlainTextEditSearchWidget::deactivate() {
stopDebounce();
hide();
// Clear the search extra selections when closing the search bar
clearSearchExtraSelections();
_textEdit->setFocus();
}
void QPlainTextEditSearchWidget::setReplaceMode(bool enabled) {
ui->replaceToggleButton->setChecked(enabled);
ui->replaceLabel->setVisible(enabled);
ui->replaceLineEdit->setVisible(enabled);
ui->modeLabel->setVisible(enabled);
ui->buttonFrame->setVisible(enabled);
ui->matchCaseSensitiveButton->setVisible(enabled);
}
bool QPlainTextEditSearchWidget::eventFilter(QObject *obj, QEvent *event) {
if (event->type() == QEvent::KeyPress) {
auto *keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->key() == Qt::Key_Escape) {
deactivate();
return true;
} else if ((!_debounceTimer.isActive() &&
keyEvent->modifiers().testFlag(Qt::ShiftModifier) &&
(keyEvent->key() == Qt::Key_Return)) ||
(keyEvent->key() == Qt::Key_Up)) {
doSearchUp();
return true;
} else if (!_debounceTimer.isActive() &&
((keyEvent->key() == Qt::Key_Return) ||
(keyEvent->key() == Qt::Key_Down))) {
doSearchDown();
return true;
} else if (!_debounceTimer.isActive() && keyEvent->key() == Qt::Key_F3) {
doSearch(!keyEvent->modifiers().testFlag(Qt::ShiftModifier));
return true;
}
// if ((obj == ui->replaceLineEdit) && (keyEvent->key() ==
// Qt::Key_Tab)
// && ui->replaceToggleButton->isChecked()) {
// ui->replaceLineEdit->setFocus();
// }
return false;
}
return QWidget::eventFilter(obj, event);
}
void QPlainTextEditSearchWidget::searchLineEditTextChanged(
const QString &arg1) {
_searchTerm = arg1;
if (_debounceTimer.interval() != 0 && !_searchTerm.isEmpty()) {
_debounceTimer.start();
ui->searchDownButton->setEnabled(false);
ui->searchUpButton->setEnabled(false);
} else {
performSearch();
}
}
void QPlainTextEditSearchWidget::performSearch()
{
doSearchCount();
updateSearchExtraSelections();
doSearchDown();
}
void QPlainTextEditSearchWidget::clearSearchExtraSelections() {
_searchExtraSelections.clear();
setSearchExtraSelections();
}
void QPlainTextEditSearchWidget::updateSearchExtraSelections() {
_searchExtraSelections.clear();
const auto textCursor = _textEdit->textCursor();
_textEdit->moveCursor(QTextCursor::Start);
const QColor color = selectionColor;
QTextCharFormat extraFmt;
extraFmt.setBackground(color);
while (doSearch(true, false, false)) {
QTextEdit::ExtraSelection extra = QTextEdit::ExtraSelection();
extra.format = extraFmt;
extra.cursor = _textEdit->textCursor();
_searchExtraSelections.append(extra);
}
_textEdit->setTextCursor(textCursor);
this->setSearchExtraSelections();
}
void QPlainTextEditSearchWidget::setSearchExtraSelections() const {
this->_textEdit->setExtraSelections(this->_searchExtraSelections);
}
void QPlainTextEditSearchWidget::stopDebounce()
{
_debounceTimer.stop();
ui->searchDownButton->setEnabled(true);
ui->searchUpButton->setEnabled(true);
}
void QPlainTextEditSearchWidget::doSearchUp() { doSearch(false); }
void QPlainTextEditSearchWidget::doSearchDown() { doSearch(true); }
bool QPlainTextEditSearchWidget::doReplace(bool forAll) {
if (_textEdit->isReadOnly()) {
return false;
}
QTextCursor cursor = _textEdit->textCursor();
if (!forAll && cursor.selectedText().isEmpty()) {
return false;
}
const int searchMode = ui->modeComboBox->currentIndex();
if (searchMode == RegularExpressionMode) {
QString text = cursor.selectedText();
text.replace(QRegularExpression(ui->searchLineEdit->text()),
ui->replaceLineEdit->text());
cursor.insertText(text);
} else {
cursor.insertText(ui->replaceLineEdit->text());
}
if (!forAll) {
const int position = cursor.position();
if (!doSearch(true)) {
// restore the last cursor position if text wasn't found any more
cursor.setPosition(position);
_textEdit->setTextCursor(cursor);
}
}
return true;
}
void QPlainTextEditSearchWidget::doReplaceAll() {
if (_textEdit->isReadOnly()) {
return;
}
// start at the top
_textEdit->moveCursor(QTextCursor::Start);
// replace until everything to the bottom is replaced
while (doSearch(true, false) && doReplace(true)) {
}
}
/**
* @brief Searches for text in the text edit
* @returns true if found
*/
bool QPlainTextEditSearchWidget::doSearch(bool searchDown,
bool allowRestartAtTop,
bool updateUI) {
if (_debounceTimer.isActive()) {
stopDebounce();
}
const QString text = ui->searchLineEdit->text();
if (text.isEmpty()) {
if (updateUI) {
ui->searchLineEdit->setStyleSheet(QLatin1String(""));
}
return false;
}
const int searchMode = ui->modeComboBox->currentIndex();
if (searchMode == RegularExpressionMode) {
// Prevent stuck application when the user enters just start or end markers
static const QRegularExpression regExp(R"(^[\^\$]+$)");
if (regExp.match(text).hasMatch()) {
clearSearchExtraSelections();
if (_debounceTimer.isActive()) {
stopDebounce();
}
return false;
}
}
const bool caseSensitive = ui->matchCaseSensitiveButton->isChecked();
QFlags<QTextDocument::FindFlag> options =
searchDown ? QTextDocument::FindFlag(0) : QTextDocument::FindBackward;
if (searchMode == WholeWordsMode) {
options |= QTextDocument::FindWholeWords;
}
if (caseSensitive) {
options |= QTextDocument::FindCaseSensitively;
}
// block signal to reduce too many signals being fired and too many updates
_textEdit->blockSignals(true);
bool found =
searchMode == RegularExpressionMode
?
#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))
_textEdit->find(
QRegularExpression(
text, caseSensitive
? QRegularExpression::NoPatternOption
: QRegularExpression::CaseInsensitiveOption),
options)
:
#else
_textEdit->find(QRegExp(text, caseSensitive ? Qt::CaseSensitive
: Qt::CaseInsensitive),
options)
:
#endif
_textEdit->find(text, options);
_textEdit->blockSignals(false);
if (found) {
const int result =
searchDown ? ++_currentSearchResult : --_currentSearchResult;
_currentSearchResult = std::min(result, _searchResultCount);
updateSearchCountLabelText();
}
// start at the top (or bottom) if not found
if (!found && allowRestartAtTop) {
_textEdit->moveCursor(searchDown ? QTextCursor::Start
: QTextCursor::End);
found =
searchMode == RegularExpressionMode
?
#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))
_textEdit->find(
QRegularExpression(
text, caseSensitive
? QRegularExpression::NoPatternOption
: QRegularExpression::CaseInsensitiveOption),
options)
:
#else
_textEdit->find(
QRegExp(text, caseSensitive ? Qt::CaseSensitive
: Qt::CaseInsensitive),
options)
:
#endif
_textEdit->find(text, options);
if (found && updateUI) {
_currentSearchResult = searchDown ? 1 : _searchResultCount;
updateSearchCountLabelText();
}
}
if (updateUI) {
const QRect rect = _textEdit->cursorRect();
QMargins margins = _textEdit->layout()->contentsMargins();
const int searchWidgetHotArea = _textEdit->height() - this->height();
const int marginBottom =
(rect.y() > searchWidgetHotArea) ? (this->height() + 10) : 0;
// move the search box a bit up if we would block the search result
if (margins.bottom() != marginBottom) {
margins.setBottom(marginBottom);
_textEdit->layout()->setContentsMargins(margins);
}
// add a background color according if we found the text or not
const QString bgColorCode =
_darkMode
? (found ? QStringLiteral("#135a13")
: QStringLiteral("#8d2b36"))
: found ? QStringLiteral("#D5FAE2") : QStringLiteral("#FAE9EB");
const QString fgColorCode =
_darkMode ? QStringLiteral("#cccccc") : QStringLiteral("#404040");
ui->searchLineEdit->setStyleSheet(
QStringLiteral("* { background: ") + bgColorCode +
QStringLiteral("; color: ") + fgColorCode + QStringLiteral("; }"));
// restore the search extra selections after the find command
this->setSearchExtraSelections();
}
return found;
}
/**
* @brief Counts the search results
*/
void QPlainTextEditSearchWidget::doSearchCount() {
// Note that we are moving the anchor, so the search will start from the top
// again! Alternative: Restore cursor position afterwards, but then we will
// not know
// at what _currentSearchResult we currently are
_textEdit->moveCursor(QTextCursor::Start, QTextCursor::MoveAnchor);
bool found;
_searchResultCount = 0;
_currentSearchResult = 0;
do {
found = doSearch(true, false, false);
if (found) {
_searchResultCount++;
}
} while (found);
updateSearchCountLabelText();
}
void QPlainTextEditSearchWidget::setDarkMode(bool enabled) {
_darkMode = enabled;
}
void QPlainTextEditSearchWidget::setSearchText(const QString &searchText) {
ui->searchLineEdit->setText(searchText);
}
void QPlainTextEditSearchWidget::setSearchMode(SearchMode searchMode) {
ui->modeComboBox->setCurrentIndex(searchMode);
}
void QPlainTextEditSearchWidget::setDebounceDelay(uint debounceDelay)
{
_debounceTimer.setInterval(static_cast<int>(debounceDelay));
}
void QPlainTextEditSearchWidget::activate(bool focus) {
setReplaceMode(ui->modeComboBox->currentIndex() !=
SearchMode::PlainTextMode);
show();
// preset the selected text as search text if there is any and there is no
// other search text
const QString selectedText = _textEdit->textCursor().selectedText();
if (!selectedText.isEmpty() && ui->searchLineEdit->text().isEmpty()) {
ui->searchLineEdit->setText(selectedText);
}
if (focus) {
ui->searchLineEdit->setFocus();
}
ui->searchLineEdit->selectAll();
updateSearchExtraSelections();
doSearchDown();
}
void QPlainTextEditSearchWidget::reset() {
ui->searchLineEdit->clear();
setSearchMode(SearchMode::PlainTextMode);
setReplaceMode(false);
ui->searchCountLabel->setEnabled(false);
}
void QPlainTextEditSearchWidget::updateSearchCountLabelText() {
ui->searchCountLabel->setEnabled(true);
ui->searchCountLabel->setText(QString("%1/%2").arg(
_currentSearchResult == 0 ? QChar('-')
: QString::number(_currentSearchResult),
_searchResultCount == 0 ? QChar('-')
: QString::number(_searchResultCount)));
}
void QPlainTextEditSearchWidget::setSearchSelectionColor(const QColor &color) {
selectionColor = color;
}
void QPlainTextEditSearchWidget::on_modeComboBox_currentIndexChanged(
int index) {
Q_UNUSED(index)
doSearchCount();
doSearchDown();
}
void QPlainTextEditSearchWidget::on_matchCaseSensitiveButton_toggled(
bool checked) {
Q_UNUSED(checked)
doSearchCount();
doSearchDown();
}
<|endoftext|>
|
<commit_before>// Copyright 2021 The CFU-Playground 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 "tflite.h"
#include <cstdint>
#include "perf.h"
#include "playground_util/random.h"
#include "proj_tflite.h"
#include "tensorflow/lite/micro/all_ops_resolver.h"
#include "tensorflow/lite/micro/micro_error_reporter.h"
#include "tensorflow/lite/micro/micro_interpreter.h"
#include "tensorflow/lite/micro/micro_mutable_op_resolver.h"
#include "tensorflow/lite/micro/micro_profiler.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "tflite_unit_tests.h"
#ifdef TF_LITE_SHOW_MEMORY_USE
#include "tensorflow/lite/micro/recording_micro_interpreter.h"
#define INTERPRETER_TYPE RecordingMicroInterpreter
#else
#define INTERPRETER_TYPE MicroInterpreter
#endif
// For C++ exceptions
void* __dso_handle = &__dso_handle;
//
// TfLM global objects
namespace {
// A profiler that prints a "." for each profile event begun
class ProgressProfiler : public tflite::MicroProfiler {
public:
virtual uint32_t BeginEvent(const char* tag) {
printf(".");
return tflite::MicroProfiler::BeginEvent(tag);
}
private:
TF_LITE_REMOVE_VIRTUAL_DELETE;
};
tflite::ErrorReporter* error_reporter = nullptr;
tflite::MicroOpResolver* op_resolver = nullptr;
tflite::MicroProfiler* profiler = nullptr;
const tflite::Model* model = nullptr;
tflite::INTERPRETER_TYPE* interpreter = nullptr;
// C++ 11 does not have a constexpr std::max.
// For this reason, a small implementation is written.
template <typename T>
constexpr T const& const_max(const T& x) {
return x;
}
template <typename T, typename... Args>
constexpr T const& const_max(const T& x, const T& y, const Args&... rest) {
return const_max(x > y ? x : y, rest...);
}
// Get the smallest kTensorArenaSize possible.
constexpr int kTensorArenaSize = const_max<int>(
#ifdef INCLUDE_MODEL_PDTI8
81 * 1024,
#endif
#ifdef INCLUDE_MODEL_MICRO_SPEECH
7 * 1024,
#endif
#ifdef INCLUDE_MODEL_MAGIC_WAND
5 * 1024,
#endif
#ifdef INCLUDE_MODEL_MNV2
800 * 1024,
#endif
#ifdef INCLUDE_MODEL_HPS
1024 * 1024,
#endif
#ifdef INLCUDE_MODEL_MLCOMMONS_TINY_V01_ANOMD
3 * 1024,
#endif
#ifdef INLCUDE_MODEL_MLCOMMONS_TINY_V01_IMGC
53 * 1024,
#endif
#ifdef INLCUDE_MODEL_MLCOMMONS_TINY_V01_KWS
23 * 1024,
#endif
#ifdef INLCUDE_MODEL_MLCOMMONS_TINY_V01_VWW
99 * 1024,
#endif
0 /* When no models defined, we don't need a tensor arena. */
);
static uint8_t tensor_arena[kTensorArenaSize];
} // anonymous namespace
static void tflite_init() {
static bool initialized = false;
if (initialized) {
return;
}
initialized = true;
// Sets up error reporting etc
static tflite::MicroErrorReporter micro_error_reporter;
error_reporter = µ_error_reporter;
TF_LITE_REPORT_ERROR(error_reporter, "Error_reporter OK!");
// Pull in only the operation implementations we need.
// This relies on a complete list of all the ops needed by this graph.
// An easier approach is to just use the AllOpsResolver, but this will
// incur some penalty in code space for op implementations that are not
// needed by this graph.
//
static tflite::AllOpsResolver resolver;
op_resolver = &resolver;
// // NOLINTNEXTLINE(runtime-global-variables)
// static tflite::MicroMutableOpResolver<8> micro_op_resolver;
// micro_op_resolver.AddAveragePool2D();
// micro_op_resolver.AddConv2D();
// micro_op_resolver.AddDepthwiseConv2D();
// micro_op_resolver.AddReshape();
// micro_op_resolver.AddSoftmax();
// // needed for jon's model conv2d/relu, maxpool2d, reshape, fullyconnected,
// logistic micro_op_resolver.AddMaxPool2D();
// micro_op_resolver.AddFullyConnected();
// micro_op_resolver.AddLogistic();
// // needed for MODEL=magic_wand_full_i8
// // micro_op_resolver.AddQuantize();
// op_resolver = µ_op_resolver;
// profiler
static ProgressProfiler micro_profiler;
profiler = µ_profiler;
}
void tflite_load_model(const unsigned char* model_data,
unsigned int model_length) {
tflite_init();
tflite_preload(model_data, model_length);
if (interpreter) {
interpreter->~INTERPRETER_TYPE();
interpreter = nullptr;
}
// Map the model into a usable data structure. This doesn't involve any
// copying or parsing, it's a very lightweight operation.
model = tflite::GetModel(model_data);
// Build an interpreter to run the model with.
// NOLINTNEXTLINE(runtime-global-variables)
alignas(tflite::INTERPRETER_TYPE) static unsigned char
buf[sizeof(tflite::INTERPRETER_TYPE)];
interpreter = new (buf)
tflite::INTERPRETER_TYPE(model, *op_resolver, tensor_arena,
kTensorArenaSize, error_reporter, profiler);
// Allocate memory from the tensor_arena for the model's tensors.
TfLiteStatus allocate_status = interpreter->AllocateTensors();
if (allocate_status != kTfLiteOk) {
TF_LITE_REPORT_ERROR(error_reporter, "AllocateTensors() failed");
return;
}
#ifdef TF_LITE_SHOW_MEMORY_USE
interpreter->GetMicroAllocator().PrintAllocations();
#endif
// Get information about the memory area to use for the model's input.
auto input = interpreter->input(0);
auto dims = input->dims;
printf("Input: %d bytes, %d dims:", input->bytes, dims->size);
for (int ii = 0; ii < dims->size; ++ii) {
printf(" %d", dims->data[ii]);
}
puts("\n");
tflite_postload();
}
void tflite_set_input_zeros(void) {
auto input = interpreter->input(0);
memset(input->data.int8, 0, input->bytes);
printf("Zeroed %d bytes at %p\n", input->bytes, input->data.int8);
}
void tflite_set_input_zeros_float() {
auto input = interpreter->input(0);
memset(input->data.f, 0, input->bytes);
printf("Zeroed %d bytes at %p\n", input->bytes, input->data.f);
}
void tflite_set_input(const void* data) {
auto input = interpreter->input(0);
memcpy(input->data.int8, data, input->bytes);
printf("Copied %d bytes at %p\n", input->bytes, input->data.int8);
}
void tflite_set_input_unsigned(const unsigned char* data) {
auto input = interpreter->input(0);
for (size_t i = 0; i < input->bytes; i++) {
input->data.int8[i] = static_cast<int>(data[i]) - 128;
}
printf("Set %d bytes at %p\n", input->bytes, input->data.int8);
}
void tflite_set_input_float(const float* data) {
auto input = interpreter->input(0);
memcpy(input->data.f, data, input->bytes);
printf("Copied %d bytes at %p\n", input->bytes, input->data.f);
}
void tflite_randomize_input(int64_t seed) {
int64_t r = seed;
auto input = interpreter->input(0);
for (size_t i = 0; i < input->bytes; i++) {
input->data.int8[i] = static_cast<int8_t>(next_pseudo_random(&r));
}
printf("Set %d bytes at %p\n", input->bytes, input->data.int8);
}
void tflite_set_grid_input(void) {
auto input = interpreter->input(0);
size_t height = input->dims->data[1];
size_t width = input->dims->data[2];
for (size_t y = 0; y < height; y++) {
for (size_t x = 0; x < width; x++) {
int8_t val = (y & 0x20) & (x & 0x20) ? -128 : 127;
input->data.int8[x + y * width] = val;
}
}
printf("Set %d bytes at %p\n", input->bytes, input->data.int8);
}
int8_t* tflite_get_output() { return interpreter->output(0)->data.int8; }
float* tflite_get_output_float() { return interpreter->output(0)->data.f; }
void tflite_classify() {
// Run the model on this input and make sure it succeeds.
profiler->ClearEvents();
perf_reset_all_counters();
// perf_set_mcycle is a no-op for some boards, start and end used instead.
uint32_t start = perf_get_mcycle();
if (kTfLiteOk != interpreter->Invoke()) {
puts("Invoke failed.");
}
uint32_t end = perf_get_mcycle();
#ifndef NPROFILE
profiler->LogCsv();
perf_print_all_counters();
#endif
perf_print_value(end - start); // Possible overflow is intentional here.
printf(" cycles total\n");
}
int8_t* get_input() { return interpreter->input(0)->data.int8; }
<commit_msg>tflite.cc: fix LogCsv format<commit_after>// Copyright 2021 The CFU-Playground 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 "tflite.h"
#include <cstdint>
#include "perf.h"
#include "playground_util/random.h"
#include "proj_tflite.h"
#include "tensorflow/lite/micro/all_ops_resolver.h"
#include "tensorflow/lite/micro/micro_error_reporter.h"
#include "tensorflow/lite/micro/micro_interpreter.h"
#include "tensorflow/lite/micro/micro_mutable_op_resolver.h"
#include "tensorflow/lite/micro/micro_profiler.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "tflite_unit_tests.h"
#ifdef TF_LITE_SHOW_MEMORY_USE
#include "tensorflow/lite/micro/recording_micro_interpreter.h"
#define INTERPRETER_TYPE RecordingMicroInterpreter
#else
#define INTERPRETER_TYPE MicroInterpreter
#endif
// For C++ exceptions
void* __dso_handle = &__dso_handle;
//
// TfLM global objects
namespace {
// A profiler that prints a "." for each profile event begun
class ProgressProfiler : public tflite::MicroProfiler {
public:
virtual uint32_t BeginEvent(const char* tag) {
printf(".");
return tflite::MicroProfiler::BeginEvent(tag);
}
private:
TF_LITE_REMOVE_VIRTUAL_DELETE;
};
tflite::ErrorReporter* error_reporter = nullptr;
tflite::MicroOpResolver* op_resolver = nullptr;
tflite::MicroProfiler* profiler = nullptr;
const tflite::Model* model = nullptr;
tflite::INTERPRETER_TYPE* interpreter = nullptr;
// C++ 11 does not have a constexpr std::max.
// For this reason, a small implementation is written.
template <typename T>
constexpr T const& const_max(const T& x) {
return x;
}
template <typename T, typename... Args>
constexpr T const& const_max(const T& x, const T& y, const Args&... rest) {
return const_max(x > y ? x : y, rest...);
}
// Get the smallest kTensorArenaSize possible.
constexpr int kTensorArenaSize = const_max<int>(
#ifdef INCLUDE_MODEL_PDTI8
81 * 1024,
#endif
#ifdef INCLUDE_MODEL_MICRO_SPEECH
7 * 1024,
#endif
#ifdef INCLUDE_MODEL_MAGIC_WAND
5 * 1024,
#endif
#ifdef INCLUDE_MODEL_MNV2
800 * 1024,
#endif
#ifdef INCLUDE_MODEL_HPS
1024 * 1024,
#endif
#ifdef INLCUDE_MODEL_MLCOMMONS_TINY_V01_ANOMD
3 * 1024,
#endif
#ifdef INLCUDE_MODEL_MLCOMMONS_TINY_V01_IMGC
53 * 1024,
#endif
#ifdef INLCUDE_MODEL_MLCOMMONS_TINY_V01_KWS
23 * 1024,
#endif
#ifdef INLCUDE_MODEL_MLCOMMONS_TINY_V01_VWW
99 * 1024,
#endif
0 /* When no models defined, we don't need a tensor arena. */
);
static uint8_t tensor_arena[kTensorArenaSize];
} // anonymous namespace
static void tflite_init() {
static bool initialized = false;
if (initialized) {
return;
}
initialized = true;
// Sets up error reporting etc
static tflite::MicroErrorReporter micro_error_reporter;
error_reporter = µ_error_reporter;
TF_LITE_REPORT_ERROR(error_reporter, "Error_reporter OK!");
// Pull in only the operation implementations we need.
// This relies on a complete list of all the ops needed by this graph.
// An easier approach is to just use the AllOpsResolver, but this will
// incur some penalty in code space for op implementations that are not
// needed by this graph.
//
static tflite::AllOpsResolver resolver;
op_resolver = &resolver;
// // NOLINTNEXTLINE(runtime-global-variables)
// static tflite::MicroMutableOpResolver<8> micro_op_resolver;
// micro_op_resolver.AddAveragePool2D();
// micro_op_resolver.AddConv2D();
// micro_op_resolver.AddDepthwiseConv2D();
// micro_op_resolver.AddReshape();
// micro_op_resolver.AddSoftmax();
// // needed for jon's model conv2d/relu, maxpool2d, reshape, fullyconnected,
// logistic micro_op_resolver.AddMaxPool2D();
// micro_op_resolver.AddFullyConnected();
// micro_op_resolver.AddLogistic();
// // needed for MODEL=magic_wand_full_i8
// // micro_op_resolver.AddQuantize();
// op_resolver = µ_op_resolver;
// profiler
static ProgressProfiler micro_profiler;
profiler = µ_profiler;
}
void tflite_load_model(const unsigned char* model_data,
unsigned int model_length) {
tflite_init();
tflite_preload(model_data, model_length);
if (interpreter) {
interpreter->~INTERPRETER_TYPE();
interpreter = nullptr;
}
// Map the model into a usable data structure. This doesn't involve any
// copying or parsing, it's a very lightweight operation.
model = tflite::GetModel(model_data);
// Build an interpreter to run the model with.
// NOLINTNEXTLINE(runtime-global-variables)
alignas(tflite::INTERPRETER_TYPE) static unsigned char
buf[sizeof(tflite::INTERPRETER_TYPE)];
interpreter = new (buf)
tflite::INTERPRETER_TYPE(model, *op_resolver, tensor_arena,
kTensorArenaSize, error_reporter, profiler);
// Allocate memory from the tensor_arena for the model's tensors.
TfLiteStatus allocate_status = interpreter->AllocateTensors();
if (allocate_status != kTfLiteOk) {
TF_LITE_REPORT_ERROR(error_reporter, "AllocateTensors() failed");
return;
}
#ifdef TF_LITE_SHOW_MEMORY_USE
interpreter->GetMicroAllocator().PrintAllocations();
#endif
// Get information about the memory area to use for the model's input.
auto input = interpreter->input(0);
auto dims = input->dims;
printf("Input: %d bytes, %d dims:", input->bytes, dims->size);
for (int ii = 0; ii < dims->size; ++ii) {
printf(" %d", dims->data[ii]);
}
puts("\n");
tflite_postload();
}
void tflite_set_input_zeros(void) {
auto input = interpreter->input(0);
memset(input->data.int8, 0, input->bytes);
printf("Zeroed %d bytes at %p\n", input->bytes, input->data.int8);
}
void tflite_set_input_zeros_float() {
auto input = interpreter->input(0);
memset(input->data.f, 0, input->bytes);
printf("Zeroed %d bytes at %p\n", input->bytes, input->data.f);
}
void tflite_set_input(const void* data) {
auto input = interpreter->input(0);
memcpy(input->data.int8, data, input->bytes);
printf("Copied %d bytes at %p\n", input->bytes, input->data.int8);
}
void tflite_set_input_unsigned(const unsigned char* data) {
auto input = interpreter->input(0);
for (size_t i = 0; i < input->bytes; i++) {
input->data.int8[i] = static_cast<int>(data[i]) - 128;
}
printf("Set %d bytes at %p\n", input->bytes, input->data.int8);
}
void tflite_set_input_float(const float* data) {
auto input = interpreter->input(0);
memcpy(input->data.f, data, input->bytes);
printf("Copied %d bytes at %p\n", input->bytes, input->data.f);
}
void tflite_randomize_input(int64_t seed) {
int64_t r = seed;
auto input = interpreter->input(0);
for (size_t i = 0; i < input->bytes; i++) {
input->data.int8[i] = static_cast<int8_t>(next_pseudo_random(&r));
}
printf("Set %d bytes at %p\n", input->bytes, input->data.int8);
}
void tflite_set_grid_input(void) {
auto input = interpreter->input(0);
size_t height = input->dims->data[1];
size_t width = input->dims->data[2];
for (size_t y = 0; y < height; y++) {
for (size_t x = 0; x < width; x++) {
int8_t val = (y & 0x20) & (x & 0x20) ? -128 : 127;
input->data.int8[x + y * width] = val;
}
}
printf("Set %d bytes at %p\n", input->bytes, input->data.int8);
}
int8_t* tflite_get_output() { return interpreter->output(0)->data.int8; }
float* tflite_get_output_float() { return interpreter->output(0)->data.f; }
void tflite_classify() {
// Run the model on this input and make sure it succeeds.
profiler->ClearEvents();
perf_reset_all_counters();
// perf_set_mcycle is a no-op for some boards, start and end used instead.
uint32_t start = perf_get_mcycle();
if (kTfLiteOk != interpreter->Invoke()) {
puts("Invoke failed.");
}
uint32_t end = perf_get_mcycle();
#ifndef NPROFILE
printf("\n");
profiler->LogCsv();
perf_print_all_counters();
#endif
perf_print_value(end - start); // Possible overflow is intentional here.
printf(" cycles total\n");
}
int8_t* get_input() { return interpreter->input(0)->data.int8; }
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkIdList.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "vtkIdList.h"
#include "vtkObjectFactory.h"
vtkIdList* vtkIdList::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkIdList");
if(ret)
{
return (vtkIdList*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkIdList;
}
vtkIdList::vtkIdList()
{
this->NumberOfIds = 0;
this->Size = 0;
this->Ids = NULL;
}
vtkIdList::~vtkIdList()
{
if ( this->Ids != NULL )
{
delete [] this->Ids;
}
}
void vtkIdList::Initialize()
{
if ( this->Ids != NULL )
{
delete [] this->Ids;
this->Ids = NULL;
}
this->NumberOfIds = 0;
this->Size = 0;
}
int vtkIdList::Allocate(const int sz, const int vtkNotUsed(strategy))
{
if ( sz > this->Size)
{
this->Initialize();
this->Size = ( sz > 0 ? sz : 1);
if ( (this->Ids = new int[this->Size]) == NULL )
{
return 0;
}
}
this->NumberOfIds = 0;
return 1;
}
void vtkIdList::SetNumberOfIds(const int number)
{
this->Allocate(number,0);
this->NumberOfIds = number;
}
void vtkIdList::InsertId(const int i, const int id)
{
if ( i >= this->Size )
{
this->Resize(i+1);
}
this->Ids[i] = id;
if ( i >= this->NumberOfIds )
{
this->NumberOfIds = i + 1;
}
}
int vtkIdList::InsertNextId(const int id)
{
if ( this->NumberOfIds >= this->Size )
{
this->Resize(this->NumberOfIds+1);
}
this->Ids[this->NumberOfIds++] = id;
return this->NumberOfIds-1;
}
int vtkIdList::InsertUniqueId(const int id)
{
for (int i=0; i < this->NumberOfIds; i++)
{
if ( id == this->Ids[i] )
{
return i;
}
}
return this->InsertNextId(id);
}
int *vtkIdList::WritePointer(const int i, const int number)
{
int newSize=i+number;
if ( newSize > this->Size )
{
this->Resize(newSize);
}
if ( newSize > this->NumberOfIds )
{
this->NumberOfIds = newSize;
}
return this->Ids + i;
}
void vtkIdList::DeleteId(int id)
{
int i=0;
// while loop is necessary to delete all occurences of id
while ( i < this->NumberOfIds )
{
for ( ; i < this->NumberOfIds; i++)
{
if ( this->Ids[i] == id )
{
break;
}
}
// if found; replace current id with last
if ( i < this->NumberOfIds )
{
this->SetId(i,this->Ids[this->NumberOfIds-1]);
this->NumberOfIds--;
}
}
}
void vtkIdList::DeepCopy(vtkIdList *ids)
{
ids->Initialize();
ids->NumberOfIds = this->NumberOfIds;
ids->Size = this->Size;
ids->Ids = new int [this->Size];
for (int i=0; i < this->NumberOfIds; i++)
{
ids->Ids[i] = this->Ids[i];
}
}
int *vtkIdList::Resize(const int sz)
{
int *newIds;
int newSize;
if ( sz > this->Size )
{
newSize = this->Size + sz;
}
else if (sz == this->Size)
{
return this->Ids;
}
else
{
newSize = sz;
}
if (newSize <= 0)
{
this->Initialize();
return 0;
}
if ( (newIds = new int[newSize]) == NULL )
{
vtkErrorMacro(<< "Cannot allocate memory\n");
return 0;
}
if (this->Ids)
{
memcpy(newIds, this->Ids,
(sz < this->Size ? sz : this->Size) * sizeof(int));
delete [] this->Ids;
}
this->Size = newSize;
this->Ids = newIds;
return this->Ids;
}
#define VTK_TMP_ARRAY_SIZE 500
// Intersect this list with another vtkIdList. Updates current list according
// to result of intersection operation.
void vtkIdList::IntersectWith(vtkIdList& otherIds)
{
// Fast method due to Dr. Andreas Mueller of ISE Integrated Systems
// Engineering (CH).
int thisNumIds = this->GetNumberOfIds();
if (thisNumIds <= VTK_TMP_ARRAY_SIZE)
{//Use fast method if we can fit in temporary storage
int thisIds[VTK_TMP_ARRAY_SIZE];
int i, id;
for (i=0; i < thisNumIds; i++)
{
thisIds[i] = this->GetId(i);
}
for (this->Reset(), i=0; i < thisNumIds; i++)
{
id = thisIds[i];
if ( otherIds.IsId(id) != (-1) )
{
this->InsertNextId(id);
}
}
}
else
{//use slower method for extreme cases
int *thisIds = new int [thisNumIds];
int i, id;
for (i=0; i < thisNumIds; i++)
{
*(thisIds + i) = this->GetId(i);
}
for (this->Reset(), i=0; i < thisNumIds; i++)
{
id = *(thisIds + i);
if ( otherIds.IsId(id) != (-1) )
{
this->InsertNextId(id);
}
}
delete [] thisIds;
}
}
#undef VTK_TMP_ARRAY_SIZE
void vtkIdList::PrintSelf(ostream& os, vtkIndent indent)
{
vtkObject::PrintSelf(os,indent);
os << indent << "Number of Ids: " << this->NumberOfIds << "\n";
}
<commit_msg>ERR: DeepCopy had from and to reversed.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkIdList.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "vtkIdList.h"
#include "vtkObjectFactory.h"
vtkIdList* vtkIdList::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkIdList");
if(ret)
{
return (vtkIdList*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkIdList;
}
vtkIdList::vtkIdList()
{
this->NumberOfIds = 0;
this->Size = 0;
this->Ids = NULL;
}
vtkIdList::~vtkIdList()
{
if ( this->Ids != NULL )
{
delete [] this->Ids;
}
}
void vtkIdList::Initialize()
{
if ( this->Ids != NULL )
{
delete [] this->Ids;
this->Ids = NULL;
}
this->NumberOfIds = 0;
this->Size = 0;
}
int vtkIdList::Allocate(const int sz, const int vtkNotUsed(strategy))
{
if ( sz > this->Size)
{
this->Initialize();
this->Size = ( sz > 0 ? sz : 1);
if ( (this->Ids = new int[this->Size]) == NULL )
{
return 0;
}
}
this->NumberOfIds = 0;
return 1;
}
void vtkIdList::SetNumberOfIds(const int number)
{
this->Allocate(number,0);
this->NumberOfIds = number;
}
void vtkIdList::InsertId(const int i, const int id)
{
if ( i >= this->Size )
{
this->Resize(i+1);
}
this->Ids[i] = id;
if ( i >= this->NumberOfIds )
{
this->NumberOfIds = i + 1;
}
}
int vtkIdList::InsertNextId(const int id)
{
if ( this->NumberOfIds >= this->Size )
{
this->Resize(this->NumberOfIds+1);
}
this->Ids[this->NumberOfIds++] = id;
return this->NumberOfIds-1;
}
int vtkIdList::InsertUniqueId(const int id)
{
for (int i=0; i < this->NumberOfIds; i++)
{
if ( id == this->Ids[i] )
{
return i;
}
}
return this->InsertNextId(id);
}
int *vtkIdList::WritePointer(const int i, const int number)
{
int newSize=i+number;
if ( newSize > this->Size )
{
this->Resize(newSize);
}
if ( newSize > this->NumberOfIds )
{
this->NumberOfIds = newSize;
}
return this->Ids + i;
}
void vtkIdList::DeleteId(int id)
{
int i=0;
// while loop is necessary to delete all occurences of id
while ( i < this->NumberOfIds )
{
for ( ; i < this->NumberOfIds; i++)
{
if ( this->Ids[i] == id )
{
break;
}
}
// if found; replace current id with last
if ( i < this->NumberOfIds )
{
this->SetId(i,this->Ids[this->NumberOfIds-1]);
this->NumberOfIds--;
}
}
}
void vtkIdList::DeepCopy(vtkIdList *ids)
{
this->Initialize();
this->NumberOfIds = ids->NumberOfIds;
this->Size = ids->Size;
this->Ids = new int [ids->Size];
for (int i=0; i < ids->NumberOfIds; i++)
{
this->Ids[i] = ids->Ids[i];
}
}
int *vtkIdList::Resize(const int sz)
{
int *newIds;
int newSize;
if ( sz > this->Size )
{
newSize = this->Size + sz;
}
else if (sz == this->Size)
{
return this->Ids;
}
else
{
newSize = sz;
}
if (newSize <= 0)
{
this->Initialize();
return 0;
}
if ( (newIds = new int[newSize]) == NULL )
{
vtkErrorMacro(<< "Cannot allocate memory\n");
return 0;
}
if (this->Ids)
{
memcpy(newIds, this->Ids,
(sz < this->Size ? sz : this->Size) * sizeof(int));
delete [] this->Ids;
}
this->Size = newSize;
this->Ids = newIds;
return this->Ids;
}
#define VTK_TMP_ARRAY_SIZE 500
// Intersect this list with another vtkIdList. Updates current list according
// to result of intersection operation.
void vtkIdList::IntersectWith(vtkIdList& otherIds)
{
// Fast method due to Dr. Andreas Mueller of ISE Integrated Systems
// Engineering (CH).
int thisNumIds = this->GetNumberOfIds();
if (thisNumIds <= VTK_TMP_ARRAY_SIZE)
{//Use fast method if we can fit in temporary storage
int thisIds[VTK_TMP_ARRAY_SIZE];
int i, id;
for (i=0; i < thisNumIds; i++)
{
thisIds[i] = this->GetId(i);
}
for (this->Reset(), i=0; i < thisNumIds; i++)
{
id = thisIds[i];
if ( otherIds.IsId(id) != (-1) )
{
this->InsertNextId(id);
}
}
}
else
{//use slower method for extreme cases
int *thisIds = new int [thisNumIds];
int i, id;
for (i=0; i < thisNumIds; i++)
{
*(thisIds + i) = this->GetId(i);
}
for (this->Reset(), i=0; i < thisNumIds; i++)
{
id = *(thisIds + i);
if ( otherIds.IsId(id) != (-1) )
{
this->InsertNextId(id);
}
}
delete [] thisIds;
}
}
#undef VTK_TMP_ARRAY_SIZE
void vtkIdList::PrintSelf(ostream& os, vtkIndent indent)
{
vtkObject::PrintSelf(os,indent);
os << indent << "Number of Ids: " << this->NumberOfIds << "\n";
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkWindow.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "vtkWindow.h"
// Construct an instance of vtkRenderWindow with its screen size
// set to 300x300, borders turned on, positioned at (0,0), double
// buffering turned on.
vtkWindow::vtkWindow()
{
this->OffScreenRendering = 0;
this->Size[0] = this->Size[1] = 0;
this->Position[0] = this->Position[1] = 0;
this->Mapped = 0;
this->WindowName = new char[strlen("Visualization Toolkit")+1];
strcpy( this->WindowName, "Visualization Toolkit" );
this->Erase = 1;
this->DoubleBuffer = 0;
this->DPI = 120;
}
// Destructor for the vtkWindow object.
vtkWindow::~vtkWindow()
{
if( this->WindowName )
{
delete [] this->WindowName;
this->WindowName = NULL;
}
}
void vtkWindow::SetWindowName( char * _arg )
{
vtkDebugMacro("Debug: In " __FILE__ << ", line " << __LINE__ << "\n"
<< this->GetClassName() << " (" << this << "): setting "
<< this->WindowName << " to " << _arg << "\n\n");
if ( this->WindowName && _arg && (!strcmp(this->WindowName,_arg)))
{
return;
}
if (this->WindowName)
{
delete [] this->WindowName;
}
if( _arg )
{
this->WindowName = new char[strlen(_arg)+1];
strcpy(this->WindowName,_arg);
}
else
{
this->WindowName = NULL;
}
this->Modified();
}
int *vtkWindow::GetSize()
{
return this->Size;
}
void vtkWindow::SetSize(int a[2])
{
this->SetSize(a[0],a[1]);
}
void vtkWindow::SetSize(int x, int y)
{
if ((this->Size[0] != x)||(this->Size[1] != y))
{
this->Modified();
this->Size[0] = x;
this->Size[1] = y;
}
}
int *vtkWindow::GetPosition()
{
return this->Position;
}
void vtkWindow::SetPosition(int a[2])
{
this->SetPosition(a[0],a[1]);
}
void vtkWindow::SetPosition(int x, int y)
{
if ((this->Position[0] != x)||(this->Position[1] != y))
{
this->Modified();
this->Position[0] = x;
this->Position[1] = y;
}
}
void vtkWindow::PrintSelf(ostream& os, vtkIndent indent)
{
int *temp;
vtkObject::PrintSelf(os,indent);
os << indent << "Erase: " << (this->Erase ? "On\n" : "Off\n");
if ( this->WindowName )
{
os << indent << "Window Name: " << this->WindowName << "\n";
}
else
{
os << indent << "Window Name: (none)\n";
}
temp = this->GetPosition();
os << indent << "Position: (" << temp[0] << ", " << temp[1] << ")\n";
temp = this->GetSize();
os << indent << "Size: (" << temp[0] << ", " << temp[1] << ")\n";
os << indent << "Mapped: " << this->Mapped << "\n";
os << indent << "OffScreenRendering: " << this->OffScreenRendering << "\n";
os << indent << "Double Buffered: " << this->DoubleBuffer << "\n";
os << indent << "DPI: " << this->DPI << "\n";
}
<commit_msg>BUG: Fixed segfault when calling this->GetPosition before window creation in XWindows<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkWindow.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "vtkWindow.h"
// Construct an instance of vtkRenderWindow with its screen size
// set to 300x300, borders turned on, positioned at (0,0), double
// buffering turned on.
vtkWindow::vtkWindow()
{
this->OffScreenRendering = 0;
this->Size[0] = this->Size[1] = 0;
this->Position[0] = this->Position[1] = 0;
this->Mapped = 0;
this->WindowName = new char[strlen("Visualization Toolkit")+1];
strcpy( this->WindowName, "Visualization Toolkit" );
this->Erase = 1;
this->DoubleBuffer = 0;
this->DPI = 120;
}
// Destructor for the vtkWindow object.
vtkWindow::~vtkWindow()
{
if( this->WindowName )
{
delete [] this->WindowName;
this->WindowName = NULL;
}
}
void vtkWindow::SetWindowName( char * _arg )
{
vtkDebugMacro("Debug: In " __FILE__ << ", line " << __LINE__ << "\n"
<< this->GetClassName() << " (" << this << "): setting "
<< this->WindowName << " to " << _arg << "\n\n");
if ( this->WindowName && _arg && (!strcmp(this->WindowName,_arg)))
{
return;
}
if (this->WindowName)
{
delete [] this->WindowName;
}
if( _arg )
{
this->WindowName = new char[strlen(_arg)+1];
strcpy(this->WindowName,_arg);
}
else
{
this->WindowName = NULL;
}
this->Modified();
}
int *vtkWindow::GetSize()
{
return this->Size;
}
void vtkWindow::SetSize(int a[2])
{
this->SetSize(a[0],a[1]);
}
void vtkWindow::SetSize(int x, int y)
{
if ((this->Size[0] != x)||(this->Size[1] != y))
{
this->Modified();
this->Size[0] = x;
this->Size[1] = y;
}
}
int *vtkWindow::GetPosition()
{
return this->Position;
}
void vtkWindow::SetPosition(int a[2])
{
this->SetPosition(a[0],a[1]);
}
void vtkWindow::SetPosition(int x, int y)
{
if ((this->Position[0] != x)||(this->Position[1] != y))
{
this->Modified();
this->Position[0] = x;
this->Position[1] = y;
}
}
void vtkWindow::PrintSelf(ostream& os, vtkIndent indent)
{
int *temp;
vtkObject::PrintSelf(os,indent);
os << indent << "Erase: " << (this->Erase ? "On\n" : "Off\n");
if ( this->WindowName )
{
os << indent << "Window Name: " << this->WindowName << "\n";
}
else
{
os << indent << "Window Name: (none)\n";
}
// Can only print out the ivars because the window may not have been
// created yet.
// temp = this->GetPosition();
os << indent << "Position: (" << Position[0] << ", " << Position[1] << ")\n";
// temp = this->GetSize();
os << indent << "Size: (" << Size[0] << ", " << Size[1] << ")\n";
os << indent << "Mapped: " << this->Mapped << "\n";
os << indent << "OffScreenRendering: " << this->OffScreenRendering << "\n";
os << indent << "Double Buffered: " << this->DoubleBuffer << "\n";
os << indent << "DPI: " << this->DPI << "\n";
}
<|endoftext|>
|
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "CAVEView.h"
#include "ExternalRenderWindow.h"
#include "Renderer.h"
#include "OgreWorld.h"
#include <QDesktopWidget>
#include <QResizeEvent>
#include <QKeyEvent>
#include <QDebug>
#include <QApplication>
#include "Framework.h"
#include "UiAPI.h"
#include "UiMainWindow.h"
#include "MemoryLeakCheck.h"
namespace CAVEStereo
{
CAVEView::CAVEView(const OgreRenderer::RendererPtr &renderer) :
renderer_(renderer),
camera_(0),
render_window_(0)
{
}
CAVEView::~CAVEView()
{
if (!renderer_.expired() && camera_)
{
Ogre::Root::getSingleton().detachRenderTarget(render_window_->getRenderWindow()->getName());
renderer_.lock()->GetActiveOgreWorld()->GetSceneManager()->destroyCamera(camera_);
}
SAFE_DELETE(render_window_);
}
void CAVEView::Initialize(const QString& name, Ogre::Vector3 &top_left, Ogre::Vector3 &bottom_left, Ogre::Vector3 &bottom_right, Ogre::Vector3 &eye_pos)
{
assert(!renderer_.expired());
Initialize(name, renderer_.lock()->GetWindowWidth(), renderer_.lock()->GetWindowHeight(),top_left, bottom_left, bottom_right, eye_pos);
}
void CAVEView::InitializePanorama(const QString& name, Ogre::Vector3 &top_left, Ogre::Vector3 &bottom_left, Ogre::Vector3 &bottom_right, Ogre::Vector3 &eye_pos,int n)
{
assert(!renderer_.expired());
InitializePanorama(name, renderer_.lock()->GetWindowWidth(), renderer_.lock()->GetWindowHeight(),top_left, bottom_left, bottom_right, eye_pos, n);
}
void CAVEView::GetProjectionParameters( Ogre::Vector3 &top_left, Ogre::Vector3 &bottom_left, Ogre::Vector3 &bottom_right, Ogre::Vector3 &eye_pos)
{
top_left = tl;
bottom_left = lb;
bottom_right = rb;
eye_pos = ep;
}
void CAVEView::ReCalculateProjection(Ogre::Vector3 &top_left, Ogre::Vector3 &bottom_left, Ogre::Vector3 &bottom_right, Ogre::Vector3 &eye_pos)
{
lb = bottom_left;
rb = bottom_right;
tl = top_left;
ep = eye_pos;
assert(renderer_.lock());
assert(camera_);
assert(render_window_);
bool openGL = false;
if (renderer_.lock()->GetRoot()->getRenderSystem()->getName() == "OpenGL Rendering Subsystem")
openGL = true;
//Projection magic be happening here.
double n = camera_->getNearClipDistance();
double f = camera_->getFarClipDistance();
double l, r, b, t;
//screenspace axes
Ogre::Vector3 sr, su, sn;
//from eye to screenpoints
Ogre::Vector3 ebl,etl,ebr;
Ogre::Matrix4 proj_mat, transl, change_base;
sr=bottom_right-bottom_left;
sr.normalise();
su=top_left-bottom_left;
su.normalise();
sn=su.crossProduct(sr);
sn.normalise();
ebl = bottom_left-eye_pos;
etl = top_left-eye_pos;
ebr = bottom_right-eye_pos;
qreal distance_to_plane;
if(openGL)
{
sn = -sn;
distance_to_plane = -sn.dotProduct(ebl);
}
else
{
distance_to_plane = sn.dotProduct(ebl);
}
l = sr.dotProduct(ebl)*n/distance_to_plane;
r = sr.dotProduct(ebr)*n/distance_to_plane;
b = su.dotProduct(ebl)*n/distance_to_plane;
t = su.dotProduct(etl)*n/distance_to_plane;
renderer_.lock()->GetRoot()->getRenderSystem()->_makeProjectionMatrix(l,r,b,t,n,f,proj_mat);
change_base=Ogre::Matrix4(sr.x,sr.y,sr.z,0,
su.x,su.y,su.z,0,
sn.x,sn.y,sn.z,0,
0,0,0,1);
transl.makeTrans(-eye_pos);
proj_mat = proj_mat*change_base*transl;
camera_->setCustomProjectionMatrix(true, proj_mat);
}
void CAVEView::Initialize(const QString& name, qreal window_width, qreal window_height, Ogre::Vector3 &top_left, Ogre::Vector3 &bottom_left, Ogre::Vector3 &bottom_right, Ogre::Vector3 &eye_pos)
{
assert(renderer_.lock().get());
Ogre::Camera* original_cam = renderer_.lock()->GetActiveOgreCamera();
std::string std_name = name.toStdString();
render_window_ = new ExternalRenderWindow();
render_window_->CreateRenderWindow(std_name, window_width, window_height,0,0,false);
render_window_->setGeometry(20,20,window_width,window_height);
camera_ = renderer_.lock()->GetActiveOgreWorld()->GetSceneManager()->createCamera(std_name + "_camera");
render_window_->getRenderWindow()->addViewport(camera_);
camera_->getViewport()->setOverlaysEnabled(false);
camera_->getViewport()->setShadowsEnabled(true);
//setup the camera
camera_->setCustomProjectionMatrix(false);
camera_->setNearClipDistance(original_cam->getNearClipDistance());
camera_->setFarClipDistance(original_cam->getFarClipDistance());
camera_->setVisibilityFlags(original_cam->getVisibilityFlags());
Ogre::SceneNode* node = dynamic_cast<Ogre::SceneNode*>(original_cam->getParentNode());
if(node)
node->attachObject(camera_);
ReCalculateProjection(top_left, bottom_left, bottom_right, eye_pos);
}
void CAVEView::InitializePanorama(const QString& name, qreal window_width, qreal window_height, Ogre::Vector3 &top_left, Ogre::Vector3 &bottom_left, Ogre::Vector3 &bottom_right, Ogre::Vector3 &eye_pos, int window_number)
{
assert(renderer_.lock().get());
Ogre::Camera* original_cam = renderer_.lock()->GetActiveOgreCamera();
std::string std_name = name.toStdString();
render_window_ = new ExternalRenderWindow();
QRect rect = QApplication::desktop()->screenGeometry();
int new_render_width = rect.width();
int new_render_height = rect.height();
int new_render_x = ((new_render_width/2) - ((new_render_width*0.2)/2) );
switch(window_number)
{
case 1:
render_window_->CreateRenderWindow(std_name, new_render_width*0.2, new_render_height*0.2,0,0,false);
render_window_->setGeometry(new_render_x + 2*(new_render_width*0.2),0.77*new_render_height,new_render_width*0.2, new_render_height*0.2);
break;
case 2:
render_window_->CreateRenderWindow(std_name, new_render_width*0.2, new_render_height*0.2,0,0,false);
render_window_->setGeometry(new_render_x + (new_render_width*0.2),0.77*new_render_height,new_render_width*0.2, new_render_height*0.2);
break;
case 3:
render_window_->CreateRenderWindow(std_name, new_render_width*0.2, new_render_height*0.2,0,0,false);
render_window_->setGeometry(new_render_x ,0.77*new_render_height,new_render_width*0.2, new_render_height*0.2);
break;
case 4:
render_window_->CreateRenderWindow(std_name, new_render_width*0.2, new_render_height*0.2,0,0,false);
render_window_->setGeometry(new_render_x - (new_render_width*0.2),0.77*new_render_height,new_render_width*0.2, new_render_height*0.2);
break;
case 5:
render_window_->CreateRenderWindow(std_name, new_render_width*0.2, new_render_height*0.2,0,0,false);
render_window_->setGeometry(new_render_x - 2*(new_render_width*0.2),0.77*new_render_height,new_render_width*0.2, new_render_height*0.2);
break;
}
camera_ = renderer_.lock()->GetActiveOgreWorld()->GetSceneManager()->createCamera(std_name + "_camera");
render_window_->getRenderWindow()->addViewport(camera_);
camera_->getViewport()->setOverlaysEnabled(false);
camera_->getViewport()->setShadowsEnabled(true);
camera_->setCustomProjectionMatrix(false);
camera_->setNearClipDistance(original_cam->getNearClipDistance());
camera_->setFarClipDistance(original_cam->getFarClipDistance());
camera_->setVisibilityFlags(original_cam->getVisibilityFlags());
Ogre::SceneNode* node = dynamic_cast<Ogre::SceneNode*>(original_cam->getParentNode());
if(node)
node->attachObject(camera_);
ReCalculateProjection(top_left, bottom_left, bottom_right, eye_pos);
}
}
<commit_msg>CAVE & Stereo module build fix, after default/main cam renames in Renderer. Thanks to the friendly anonymous reporter on IRC :)<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "CAVEView.h"
#include "ExternalRenderWindow.h"
#include "Renderer.h"
#include "OgreWorld.h"
#include <QDesktopWidget>
#include <QResizeEvent>
#include <QKeyEvent>
#include <QDebug>
#include <QApplication>
#include "Framework.h"
#include "UiAPI.h"
#include "UiMainWindow.h"
#include "MemoryLeakCheck.h"
namespace CAVEStereo
{
CAVEView::CAVEView(const OgreRenderer::RendererPtr &renderer) :
renderer_(renderer),
camera_(0),
render_window_(0)
{
}
CAVEView::~CAVEView()
{
if (!renderer_.expired() && camera_)
{
Ogre::Root::getSingleton().detachRenderTarget(render_window_->getRenderWindow()->getName());
renderer_.lock()->GetActiveOgreWorld()->GetSceneManager()->destroyCamera(camera_);
}
SAFE_DELETE(render_window_);
}
void CAVEView::Initialize(const QString& name, Ogre::Vector3 &top_left, Ogre::Vector3 &bottom_left, Ogre::Vector3 &bottom_right, Ogre::Vector3 &eye_pos)
{
assert(!renderer_.expired());
Initialize(name, renderer_.lock()->GetWindowWidth(), renderer_.lock()->GetWindowHeight(),top_left, bottom_left, bottom_right, eye_pos);
}
void CAVEView::InitializePanorama(const QString& name, Ogre::Vector3 &top_left, Ogre::Vector3 &bottom_left, Ogre::Vector3 &bottom_right, Ogre::Vector3 &eye_pos,int n)
{
assert(!renderer_.expired());
InitializePanorama(name, renderer_.lock()->GetWindowWidth(), renderer_.lock()->GetWindowHeight(),top_left, bottom_left, bottom_right, eye_pos, n);
}
void CAVEView::GetProjectionParameters( Ogre::Vector3 &top_left, Ogre::Vector3 &bottom_left, Ogre::Vector3 &bottom_right, Ogre::Vector3 &eye_pos)
{
top_left = tl;
bottom_left = lb;
bottom_right = rb;
eye_pos = ep;
}
void CAVEView::ReCalculateProjection(Ogre::Vector3 &top_left, Ogre::Vector3 &bottom_left, Ogre::Vector3 &bottom_right, Ogre::Vector3 &eye_pos)
{
lb = bottom_left;
rb = bottom_right;
tl = top_left;
ep = eye_pos;
assert(renderer_.lock());
assert(camera_);
assert(render_window_);
bool openGL = false;
if (renderer_.lock()->GetRoot()->getRenderSystem()->getName() == "OpenGL Rendering Subsystem")
openGL = true;
//Projection magic be happening here.
double n = camera_->getNearClipDistance();
double f = camera_->getFarClipDistance();
double l, r, b, t;
//screenspace axes
Ogre::Vector3 sr, su, sn;
//from eye to screenpoints
Ogre::Vector3 ebl,etl,ebr;
Ogre::Matrix4 proj_mat, transl, change_base;
sr=bottom_right-bottom_left;
sr.normalise();
su=top_left-bottom_left;
su.normalise();
sn=su.crossProduct(sr);
sn.normalise();
ebl = bottom_left-eye_pos;
etl = top_left-eye_pos;
ebr = bottom_right-eye_pos;
qreal distance_to_plane;
if(openGL)
{
sn = -sn;
distance_to_plane = -sn.dotProduct(ebl);
}
else
{
distance_to_plane = sn.dotProduct(ebl);
}
l = sr.dotProduct(ebl)*n/distance_to_plane;
r = sr.dotProduct(ebr)*n/distance_to_plane;
b = su.dotProduct(ebl)*n/distance_to_plane;
t = su.dotProduct(etl)*n/distance_to_plane;
renderer_.lock()->GetRoot()->getRenderSystem()->_makeProjectionMatrix(l,r,b,t,n,f,proj_mat);
change_base=Ogre::Matrix4(sr.x,sr.y,sr.z,0,
su.x,su.y,su.z,0,
sn.x,sn.y,sn.z,0,
0,0,0,1);
transl.makeTrans(-eye_pos);
proj_mat = proj_mat*change_base*transl;
camera_->setCustomProjectionMatrix(true, proj_mat);
}
void CAVEView::Initialize(const QString& name, qreal window_width, qreal window_height, Ogre::Vector3 &top_left, Ogre::Vector3 &bottom_left, Ogre::Vector3 &bottom_right, Ogre::Vector3 &eye_pos)
{
assert(renderer_.lock().get());
Ogre::Camera* original_cam = renderer_.lock()->MainOgreCamera();
std::string std_name = name.toStdString();
render_window_ = new ExternalRenderWindow();
render_window_->CreateRenderWindow(std_name, window_width, window_height,0,0,false);
render_window_->setGeometry(20,20,window_width,window_height);
camera_ = renderer_.lock()->GetActiveOgreWorld()->GetSceneManager()->createCamera(std_name + "_camera");
render_window_->getRenderWindow()->addViewport(camera_);
camera_->getViewport()->setOverlaysEnabled(false);
camera_->getViewport()->setShadowsEnabled(true);
//setup the camera
camera_->setCustomProjectionMatrix(false);
camera_->setNearClipDistance(original_cam->getNearClipDistance());
camera_->setFarClipDistance(original_cam->getFarClipDistance());
camera_->setVisibilityFlags(original_cam->getVisibilityFlags());
Ogre::SceneNode* node = dynamic_cast<Ogre::SceneNode*>(original_cam->getParentNode());
if(node)
node->attachObject(camera_);
ReCalculateProjection(top_left, bottom_left, bottom_right, eye_pos);
}
void CAVEView::InitializePanorama(const QString& name, qreal window_width, qreal window_height, Ogre::Vector3 &top_left, Ogre::Vector3 &bottom_left, Ogre::Vector3 &bottom_right, Ogre::Vector3 &eye_pos, int window_number)
{
assert(renderer_.lock().get());
Ogre::Camera* original_cam = renderer_.lock()->MainOgreCamera();
std::string std_name = name.toStdString();
render_window_ = new ExternalRenderWindow();
QRect rect = QApplication::desktop()->screenGeometry();
int new_render_width = rect.width();
int new_render_height = rect.height();
int new_render_x = ((new_render_width/2) - ((new_render_width*0.2)/2) );
switch(window_number)
{
case 1:
render_window_->CreateRenderWindow(std_name, new_render_width*0.2, new_render_height*0.2,0,0,false);
render_window_->setGeometry(new_render_x + 2*(new_render_width*0.2),0.77*new_render_height,new_render_width*0.2, new_render_height*0.2);
break;
case 2:
render_window_->CreateRenderWindow(std_name, new_render_width*0.2, new_render_height*0.2,0,0,false);
render_window_->setGeometry(new_render_x + (new_render_width*0.2),0.77*new_render_height,new_render_width*0.2, new_render_height*0.2);
break;
case 3:
render_window_->CreateRenderWindow(std_name, new_render_width*0.2, new_render_height*0.2,0,0,false);
render_window_->setGeometry(new_render_x ,0.77*new_render_height,new_render_width*0.2, new_render_height*0.2);
break;
case 4:
render_window_->CreateRenderWindow(std_name, new_render_width*0.2, new_render_height*0.2,0,0,false);
render_window_->setGeometry(new_render_x - (new_render_width*0.2),0.77*new_render_height,new_render_width*0.2, new_render_height*0.2);
break;
case 5:
render_window_->CreateRenderWindow(std_name, new_render_width*0.2, new_render_height*0.2,0,0,false);
render_window_->setGeometry(new_render_x - 2*(new_render_width*0.2),0.77*new_render_height,new_render_width*0.2, new_render_height*0.2);
break;
}
camera_ = renderer_.lock()->GetActiveOgreWorld()->GetSceneManager()->createCamera(std_name + "_camera");
render_window_->getRenderWindow()->addViewport(camera_);
camera_->getViewport()->setOverlaysEnabled(false);
camera_->getViewport()->setShadowsEnabled(true);
camera_->setCustomProjectionMatrix(false);
camera_->setNearClipDistance(original_cam->getNearClipDistance());
camera_->setFarClipDistance(original_cam->getFarClipDistance());
camera_->setVisibilityFlags(original_cam->getVisibilityFlags());
Ogre::SceneNode* node = dynamic_cast<Ogre::SceneNode*>(original_cam->getParentNode());
if(node)
node->attachObject(camera_);
ReCalculateProjection(top_left, bottom_left, bottom_right, eye_pos);
}
}
<|endoftext|>
|
<commit_before>// For conditions of distribution and use, see copyright notice in LICENSE
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "MemoryLeakCheck.h"
#include "OggVorbisLoader.h"
#include "LoggingFunctions.h"
#include <sstream>
#ifndef TUNDRA_NO_AUDIO
#include <vorbis/vorbisfile.h>
#endif
#ifndef TUNDRA_NO_AUDIO
namespace
{
class OggMemDataSource
{
public:
OggMemDataSource(const u8* data, size_t size) :
data_(data),
size_(size),
position_(0)
{
}
size_t Read(void* ptr, size_t size)
{
size_t max_read = size_ - position_;
if (size > max_read)
size = max_read;
if (size)
{
memcpy(ptr, &data_[position_], size);
position_ += size;
}
return size;
}
int Seek(ogg_int64_t offset, int whence)
{
ogg_int64_t new_pos = position_;
switch (whence)
{
case SEEK_SET:
new_pos = offset;
break;
case SEEK_CUR:
new_pos += offset;
break;
case SEEK_END:
new_pos = size_ + offset;
break;
}
if ((new_pos < 0) || (new_pos > size_))
return -1;
position_ = (uint)new_pos;
return 0;
}
long Tell() const
{
return (long)position_;
}
private:
const u8* data_;
size_t size_;
size_t position_;
};
size_t OggReadCallback(void* ptr, size_t size, size_t nmemb, void* datasource)
{
OggMemDataSource* source = (OggMemDataSource*)datasource;
return source->Read(ptr, size * nmemb);
}
int OggSeekCallback(void* datasource, ogg_int64_t offset, int whence)
{
OggMemDataSource* source = (OggMemDataSource*)datasource;
return source->Seek(offset, whence);
}
long OggTellCallback(void* datasource)
{
OggMemDataSource* source = (OggMemDataSource*)datasource;
return source->Tell();
}
} // ~unnamed namespace
#endif
namespace OggVorbisLoader
{
bool LoadOggVorbisFromFileInMemory(const u8 *fileData, size_t numBytes, std::vector<u8> &dst, bool *isStereo, bool *is16Bit, int *frequency)
{
if (!fileData || numBytes == 0)
{
LogError("Null input data passed in");
return false;
}
if (!isStereo || !is16Bit || !frequency)
{
LogError("Outputs not set");
return false;
}
#ifndef TUNDRA_NO_AUDIO
OggVorbis_File vf;
OggMemDataSource src(fileData, numBytes);
ov_callbacks cb;
cb.read_func = &OggReadCallback;
cb.seek_func = &OggSeekCallback;
cb.tell_func = &OggTellCallback;
cb.close_func = 0;
int ret = ov_open_callbacks(&src, &vf, 0, 0, cb);
if (ret < 0)
{
LogError("Not ogg vorbis format");
ov_clear(&vf);
return false;
}
vorbis_info* vi = ov_info(&vf, -1);
if (!vi)
{
LogError("No ogg vorbis stream info");
ov_clear(&vf);
return false;
}
std::ostringstream msg;
msg << "Decoding ogg vorbis stream with " << vi->channels << " channels, frequency " << vi->rate;
// LogDebug(msg.str());
*frequency = vi->rate;
*isStereo = (vi->channels > 1);
if (vi->channels != 1 && vi->channels != 2)
LogWarning("Warning: Loaded Ogg Vorbis data contains an unsupported number of channels: " + QString::number(vi->channels));
uint decoded_bytes = 0;
dst.clear();
for(;;)
{
static const int MAX_DECODE_SIZE = 16384;
dst.resize(decoded_bytes + MAX_DECODE_SIZE);
int bitstream;
long ret = ov_read(&vf, (char*)&dst[decoded_bytes], MAX_DECODE_SIZE, 0, 2, 1, &bitstream);
if (ret <= 0)
break;
decoded_bytes += ret;
}
dst.resize(decoded_bytes);
{
std::ostringstream msg;
msg << "Decoded " << decoded_bytes << " bytes of ogg vorbis sound data";
// LogDebug(msg.str());
}
ov_clear(&vf);
return true;
#else
return false;
#endif
}
} // ~OggVorbisLoader
<commit_msg>Singed<->unsigned int conversion warning fix.<commit_after>// For conditions of distribution and use, see copyright notice in LICENSE
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "MemoryLeakCheck.h"
#include "OggVorbisLoader.h"
#include "LoggingFunctions.h"
#include <sstream>
#ifndef TUNDRA_NO_AUDIO
#include <vorbis/vorbisfile.h>
#endif
#ifndef TUNDRA_NO_AUDIO
namespace
{
class OggMemDataSource
{
public:
OggMemDataSource(const u8* data, size_t size) :
data_(data),
size_(size),
position_(0)
{
}
size_t Read(void* ptr, size_t size)
{
size_t max_read = size_ - position_;
if (size > max_read)
size = max_read;
if (size)
{
memcpy(ptr, &data_[position_], size);
position_ += size;
}
return size;
}
int Seek(ogg_int64_t offset, int whence)
{
size_t new_pos = position_;
switch (whence)
{
case SEEK_SET:
new_pos = offset;
break;
case SEEK_CUR:
new_pos += offset;
break;
case SEEK_END:
new_pos = size_ + offset;
break;
}
if (new_pos < 0 || new_pos > size_)
return -1;
position_ = new_pos;
return 0;
}
long Tell() const
{
return (long)position_;
}
private:
const u8* data_;
size_t size_;
size_t position_;
};
size_t OggReadCallback(void* ptr, size_t size, size_t nmemb, void* datasource)
{
OggMemDataSource* source = (OggMemDataSource*)datasource;
return source->Read(ptr, size * nmemb);
}
int OggSeekCallback(void* datasource, ogg_int64_t offset, int whence)
{
OggMemDataSource* source = (OggMemDataSource*)datasource;
return source->Seek(offset, whence);
}
long OggTellCallback(void* datasource)
{
OggMemDataSource* source = (OggMemDataSource*)datasource;
return source->Tell();
}
} // ~unnamed namespace
#endif
namespace OggVorbisLoader
{
bool LoadOggVorbisFromFileInMemory(const u8 *fileData, size_t numBytes, std::vector<u8> &dst, bool *isStereo, bool *is16Bit, int *frequency)
{
if (!fileData || numBytes == 0)
{
LogError("Null input data passed in");
return false;
}
if (!isStereo || !is16Bit || !frequency)
{
LogError("Outputs not set");
return false;
}
#ifndef TUNDRA_NO_AUDIO
OggVorbis_File vf;
OggMemDataSource src(fileData, numBytes);
ov_callbacks cb;
cb.read_func = &OggReadCallback;
cb.seek_func = &OggSeekCallback;
cb.tell_func = &OggTellCallback;
cb.close_func = 0;
int ret = ov_open_callbacks(&src, &vf, 0, 0, cb);
if (ret < 0)
{
LogError("Not ogg vorbis format");
ov_clear(&vf);
return false;
}
vorbis_info* vi = ov_info(&vf, -1);
if (!vi)
{
LogError("No ogg vorbis stream info");
ov_clear(&vf);
return false;
}
std::ostringstream msg;
msg << "Decoding ogg vorbis stream with " << vi->channels << " channels, frequency " << vi->rate;
// LogDebug(msg.str());
*frequency = vi->rate;
*isStereo = (vi->channels > 1);
if (vi->channels != 1 && vi->channels != 2)
LogWarning("Warning: Loaded Ogg Vorbis data contains an unsupported number of channels: " + QString::number(vi->channels));
uint decoded_bytes = 0;
dst.clear();
for(;;)
{
static const int MAX_DECODE_SIZE = 16384;
dst.resize(decoded_bytes + MAX_DECODE_SIZE);
int bitstream;
long ret = ov_read(&vf, (char*)&dst[decoded_bytes], MAX_DECODE_SIZE, 0, 2, 1, &bitstream);
if (ret <= 0)
break;
decoded_bytes += ret;
}
dst.resize(decoded_bytes);
{
std::ostringstream msg;
msg << "Decoded " << decoded_bytes << " bytes of ogg vorbis sound data";
// LogDebug(msg.str());
}
ov_clear(&vf);
return true;
#else
return false;
#endif
}
} // ~OggVorbisLoader
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2008, 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 Image Engine Design 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 "IECore/DPXImageWriter.h"
#include "IECore/MessageHandler.h"
#include "IECore/VectorTypedData.h"
#include "IECore/ByteOrder.h"
#include "IECore/ImagePrimitive.h"
#include "IECore/FileNameParameter.h"
#include "IECore/DataConvert.h"
#include "IECore/ScaledDataConversion.h"
#include "IECore/CompoundDataConversion.h"
#include "IECore/LinearToCineonDataConversion.h"
#include "IECore/DespatchTypedData.h"
#include "IECore/private/dpx.h"
#include "boost/format.hpp"
#include <fstream>
#include <time.h>
using namespace IECore;
using namespace std;
using namespace boost;
using namespace Imath;
const Writer::WriterDescription<DPXImageWriter> DPXImageWriter::m_writerDescription("dpx");
DPXImageWriter::DPXImageWriter() :
ImageWriter("DPXImageWriter", "Serializes images to Digital Picture eXchange 10-bit log image format")
{
}
DPXImageWriter::DPXImageWriter( ObjectPtr image, const string &fileName ) :
ImageWriter("DPXImageWriter", "Serializes images to Digital Picture eXchange 10-bit log image format")
{
m_objectParameter->setValue( image );
m_fileNameParameter->setTypedValue( fileName );
}
DPXImageWriter::~DPXImageWriter()
{
}
struct DPXImageWriter::ChannelConverter
{
typedef void ReturnType;
std::string m_channelName;
Box2i m_displayWindow;
Box2i m_dataWindow;
unsigned int m_bitShift;
std::vector<unsigned int> &m_imageBuffer;
ChannelConverter( const std::string &channelName, const Box2i &displayWindow, const Box2i &dataWindow, unsigned int bitShift, std::vector<unsigned int> &imageBuffer )
: m_channelName( channelName ), m_displayWindow( displayWindow ), m_dataWindow( dataWindow ), m_bitShift( bitShift ), m_imageBuffer( imageBuffer )
{
}
template<typename T>
ReturnType operator()( typename T::Ptr dataContainer )
{
assert( dataContainer );
const typename T::ValueType &data = dataContainer->readable();
CompoundDataConversion<
ScaledDataConversion<typename T::ValueType::value_type, float>,
LinearToCineonDataConversion<float, unsigned int>
> converter;
int displayWidth = m_displayWindow.size().x + 1;
int dataWidth = m_dataWindow.size().x + 1;
int dataY = 0;
for ( int y = m_dataWindow.min.y; y <= m_dataWindow.max.y; y++, dataY++ )
{
int dataOffset = dataY * dataWidth;
assert( dataOffset >= 0 );
for ( int x = m_dataWindow.min.x; x <= m_dataWindow.max.x; x++, dataOffset++ )
{
int pixelIdx = ( y - m_displayWindow.min.y ) * displayWidth + ( x - m_displayWindow.min.x );
assert( pixelIdx >= 0 );
assert( pixelIdx < (int)m_imageBuffer.size() );
assert( dataOffset < (int)data.size() );
/// Perform the conversion, and set the appropriate bits in the "cell"
m_imageBuffer[ pixelIdx ] |= converter( data[dataOffset] ) << m_bitShift;
}
}
};
struct ErrorHandler
{
template<typename T, typename F>
void operator()( typename T::ConstPtr data, const F& functor )
{
assert( data );
throw InvalidArgumentException( ( boost::format( "DPXImageWriter: Invalid data type \"%s\" for channel \"%s\"." ) % Object::typeNameFromTypeId( data->typeId() ) % functor.m_channelName ).str() );
}
};
};
void DPXImageWriter::writeImage( const vector<string> &names, ConstImagePrimitivePtr image, const Box2i &dataWindow ) const
{
// write the dpx in the standard 10bit log format
ofstream out;
out.open(fileName().c_str());
if ( !out.is_open() )
{
throw IOException( "DPXImageWriter: Error writing to " + fileName() );
}
/// We'd like RGB to be at the front, in that order, because it seems that not all readers support the channel identifiers!
vector<string> desiredChannelOrder;
desiredChannelOrder.push_back( "R" );
desiredChannelOrder.push_back( "G" );
desiredChannelOrder.push_back( "B" );
vector<string> namesCopy = names;
vector<string> filteredNames;
for ( vector<string>::const_iterator it = desiredChannelOrder.begin(); it != desiredChannelOrder.end(); ++it )
{
vector<string>::iterator res = find( namesCopy.begin(), namesCopy.end(), *it );
if ( res != namesCopy.end() )
{
namesCopy.erase( res );
filteredNames.push_back( *it );
}
}
for ( vector<string>::const_iterator it = namesCopy.begin(); it != namesCopy.end(); ++it )
{
filteredNames.push_back( *it );
}
assert( names.size() == filteredNames.size() );
Box2i displayWindow = image->getDisplayWindow();
int displayWidth = 1 + displayWindow.size().x;
int displayHeight = 1 + displayWindow.size().y;
// build the header
DPXFileInformation fi;
memset(&fi, 0, sizeof(fi));
DPXImageInformation ii;
memset(&ii, 0, sizeof(ii));
DPXImageOrientation ioi;
memset(&ioi, 0, sizeof(ioi));
DPXMotionPictureFilm mpf;
memset(&mpf, 0, sizeof(mpf));
DPXTelevisionHeader th;
memset(&th, 0, sizeof(th));
fi.magic = asBigEndian<>( 0x53445058 );
// compute data offsets
fi.gen_hdr_size = sizeof(fi) + sizeof(ii) + sizeof(ioi);
fi.gen_hdr_size = asBigEndian<>(fi.gen_hdr_size);
fi.ind_hdr_size = sizeof(mpf) + sizeof(th);
fi.ind_hdr_size = asBigEndian<>(fi.ind_hdr_size);
int header_size = sizeof(fi) + sizeof(ii) + sizeof(ioi) + sizeof(mpf) + sizeof(th);
fi.image_data_offset = header_size;
fi.image_data_offset = asBigEndian<>(fi.image_data_offset);
strcpy((char *) fi.vers, "V2.0");
strncpy( (char *) fi.file_name, fileName().c_str(), sizeof( fi.file_name ) );
// compute the current date and time
time_t t;
time(&t);
struct tm gmt;
localtime_r(&t, &gmt);
snprintf((char *) fi.create_time, sizeof( fi.create_time ), "%04d:%02d:%02d:%02d:%02d:%02d:%s",
1900 + gmt.tm_year, gmt.tm_mon, gmt.tm_mday,
gmt.tm_hour, gmt.tm_min, gmt.tm_sec, gmt.tm_zone );
snprintf((char *) fi.creator, sizeof( fi.creator ), "cortex");
snprintf((char *) fi.project, sizeof( fi.project ), "cortex");
snprintf((char *) fi.copyright, sizeof( fi.copyright ), "Unknown");
ii.orientation = 0; // left-to-right, top-to-bottom
ii.element_number = 1;
ii.pixels_per_line = displayWidth;
ii.lines_per_image_ele = displayHeight;
ii.element_number = asBigEndian<>(ii.element_number);
ii.pixels_per_line = asBigEndian<>(ii.pixels_per_line);
ii.lines_per_image_ele = asBigEndian<>(ii.lines_per_image_ele);
for (int c = 0; c < 8; ++c)
{
DPXImageInformation::_image_element &ie = ii.image_element[c];
ie.data_sign = 0;
/// \todo Dcoument these constants
ie.ref_low_data = 0;
ie.ref_low_quantity = 0.0;
ie.ref_high_data = 1023;
ie.ref_high_quantity = 2.046;
ie.ref_low_data = asBigEndian<>(ie.ref_low_data);
ie.ref_low_quantity = asBigEndian<>(ie.ref_low_quantity);
ie.ref_high_data = asBigEndian<>(ie.ref_high_data);
ie.ref_high_quantity = asBigEndian<>(ie.ref_high_quantity);
/// \todo Dcoument these constants
ie.transfer = 1;
ie.packing = 256;
ie.bit_size = 10;
ie.descriptor = 50;
ie.data_offset = fi.image_data_offset;
}
ioi.x_offset = 0;
ioi.y_offset = 0;
// Write the header
int image_data_size = sizeof( unsigned int ) * displayWidth * displayHeight;
fi.file_size = header_size + image_data_size;
fi.file_size = asBigEndian<>(fi.file_size);
out.write(reinterpret_cast<char *>(&fi), sizeof(fi));
if ( out.fail() )
{
throw IOException( "DPXImageWriter: Error writing to " + fileName() );
}
out.write(reinterpret_cast<char *>(&ii), sizeof(ii));
if ( out.fail() )
{
throw IOException( "DPXImageWriter: Error writing to " + fileName() );
}
out.write(reinterpret_cast<char *>(&ioi), sizeof(ioi));
if ( out.fail() )
{
throw IOException( "DPXImageWriter: Error writing to " + fileName() );
}
out.write(reinterpret_cast<char *>(&mpf), sizeof(mpf));
if ( out.fail() )
{
throw IOException( "DPXImageWriter: Error writing to " + fileName() );
}
out.write(reinterpret_cast<char *>(&th), sizeof(th));
if ( out.fail() )
{
throw IOException( "DPXImageWriter: Error writing to " + fileName() );
}
// write the data
vector<unsigned int> imageBuffer( displayWidth*displayHeight, 0 );
int offset = 0;
vector<string>::const_iterator i = filteredNames.begin();
while (i != filteredNames.end())
{
if (!(*i == "R" || *i == "G" || *i == "B"))
{
msg( Msg::Warning, "DPXImageWriter::write", format( "Channel \"%s\" was not encoded." ) % *i );
++i;
continue;
}
int bpp = 10;
unsigned int shift = (32 - bpp) - (offset*bpp);
assert( image->variables.find( *i ) != image->variables.end() );
DataPtr dataContainer = image->variables.find( *i )->second.data;
assert( dataContainer );
ChannelConverter converter( *i, image->getDisplayWindow(), dataWindow, shift, imageBuffer );
despatchTypedData<
ChannelConverter,
TypeTraits::IsNumericVectorTypedData,
ChannelConverter::ErrorHandler
>( dataContainer, converter );
++i;
++offset;
}
// write the buffer
for (int i = 0; i < displayWidth * displayHeight; ++i)
{
imageBuffer[i] = asBigEndian<>(imageBuffer[i]);
out.write( (const char *) (&imageBuffer[i]), sizeof(unsigned int) );
if ( out.fail() )
{
throw IOException( "DPXImageWriter: Error writing to " + fileName() );
}
}
}
<commit_msg>Fixed constant to make consistent with DPXImageReader<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2008, 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 Image Engine Design 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 "IECore/DPXImageWriter.h"
#include "IECore/MessageHandler.h"
#include "IECore/VectorTypedData.h"
#include "IECore/ByteOrder.h"
#include "IECore/ImagePrimitive.h"
#include "IECore/FileNameParameter.h"
#include "IECore/DataConvert.h"
#include "IECore/ScaledDataConversion.h"
#include "IECore/CompoundDataConversion.h"
#include "IECore/LinearToCineonDataConversion.h"
#include "IECore/DespatchTypedData.h"
#include "IECore/private/dpx.h"
#include "boost/format.hpp"
#include <fstream>
#include <time.h>
using namespace IECore;
using namespace std;
using namespace boost;
using namespace Imath;
const Writer::WriterDescription<DPXImageWriter> DPXImageWriter::m_writerDescription("dpx");
DPXImageWriter::DPXImageWriter() :
ImageWriter("DPXImageWriter", "Serializes images to Digital Picture eXchange 10-bit log image format")
{
}
DPXImageWriter::DPXImageWriter( ObjectPtr image, const string &fileName ) :
ImageWriter("DPXImageWriter", "Serializes images to Digital Picture eXchange 10-bit log image format")
{
m_objectParameter->setValue( image );
m_fileNameParameter->setTypedValue( fileName );
}
DPXImageWriter::~DPXImageWriter()
{
}
struct DPXImageWriter::ChannelConverter
{
typedef void ReturnType;
std::string m_channelName;
Box2i m_displayWindow;
Box2i m_dataWindow;
unsigned int m_bitShift;
std::vector<unsigned int> &m_imageBuffer;
ChannelConverter( const std::string &channelName, const Box2i &displayWindow, const Box2i &dataWindow, unsigned int bitShift, std::vector<unsigned int> &imageBuffer )
: m_channelName( channelName ), m_displayWindow( displayWindow ), m_dataWindow( dataWindow ), m_bitShift( bitShift ), m_imageBuffer( imageBuffer )
{
}
template<typename T>
ReturnType operator()( typename T::Ptr dataContainer )
{
assert( dataContainer );
const typename T::ValueType &data = dataContainer->readable();
CompoundDataConversion<
ScaledDataConversion<typename T::ValueType::value_type, float>,
LinearToCineonDataConversion<float, unsigned int>
> converter;
int displayWidth = m_displayWindow.size().x + 1;
int dataWidth = m_dataWindow.size().x + 1;
int dataY = 0;
for ( int y = m_dataWindow.min.y; y <= m_dataWindow.max.y; y++, dataY++ )
{
int dataOffset = dataY * dataWidth;
assert( dataOffset >= 0 );
for ( int x = m_dataWindow.min.x; x <= m_dataWindow.max.x; x++, dataOffset++ )
{
int pixelIdx = ( y - m_displayWindow.min.y ) * displayWidth + ( x - m_displayWindow.min.x );
assert( pixelIdx >= 0 );
assert( pixelIdx < (int)m_imageBuffer.size() );
assert( dataOffset < (int)data.size() );
/// Perform the conversion, and set the appropriate bits in the "cell"
m_imageBuffer[ pixelIdx ] |= converter( data[dataOffset] ) << m_bitShift;
}
}
};
struct ErrorHandler
{
template<typename T, typename F>
void operator()( typename T::ConstPtr data, const F& functor )
{
assert( data );
throw InvalidArgumentException( ( boost::format( "DPXImageWriter: Invalid data type \"%s\" for channel \"%s\"." ) % Object::typeNameFromTypeId( data->typeId() ) % functor.m_channelName ).str() );
}
};
};
void DPXImageWriter::writeImage( const vector<string> &names, ConstImagePrimitivePtr image, const Box2i &dataWindow ) const
{
// write the dpx in the standard 10bit log format
ofstream out;
out.open(fileName().c_str());
if ( !out.is_open() )
{
throw IOException( "DPXImageWriter: Error writing to " + fileName() );
}
/// We'd like RGB to be at the front, in that order, because it seems that not all readers support the channel identifiers!
vector<string> desiredChannelOrder;
desiredChannelOrder.push_back( "R" );
desiredChannelOrder.push_back( "G" );
desiredChannelOrder.push_back( "B" );
vector<string> namesCopy = names;
vector<string> filteredNames;
for ( vector<string>::const_iterator it = desiredChannelOrder.begin(); it != desiredChannelOrder.end(); ++it )
{
vector<string>::iterator res = find( namesCopy.begin(), namesCopy.end(), *it );
if ( res != namesCopy.end() )
{
namesCopy.erase( res );
filteredNames.push_back( *it );
}
}
for ( vector<string>::const_iterator it = namesCopy.begin(); it != namesCopy.end(); ++it )
{
filteredNames.push_back( *it );
}
assert( names.size() == filteredNames.size() );
Box2i displayWindow = image->getDisplayWindow();
int displayWidth = 1 + displayWindow.size().x;
int displayHeight = 1 + displayWindow.size().y;
// build the header
DPXFileInformation fi;
memset(&fi, 0, sizeof(fi));
DPXImageInformation ii;
memset(&ii, 0, sizeof(ii));
DPXImageOrientation ioi;
memset(&ioi, 0, sizeof(ioi));
DPXMotionPictureFilm mpf;
memset(&mpf, 0, sizeof(mpf));
DPXTelevisionHeader th;
memset(&th, 0, sizeof(th));
fi.magic = asBigEndian<>( 0x53445058 );
// compute data offsets
fi.gen_hdr_size = sizeof(fi) + sizeof(ii) + sizeof(ioi);
fi.gen_hdr_size = asBigEndian<>(fi.gen_hdr_size);
fi.ind_hdr_size = sizeof(mpf) + sizeof(th);
fi.ind_hdr_size = asBigEndian<>(fi.ind_hdr_size);
int header_size = sizeof(fi) + sizeof(ii) + sizeof(ioi) + sizeof(mpf) + sizeof(th);
fi.image_data_offset = header_size;
fi.image_data_offset = asBigEndian<>(fi.image_data_offset);
strcpy((char *) fi.vers, "V2.0");
strncpy( (char *) fi.file_name, fileName().c_str(), sizeof( fi.file_name ) );
// compute the current date and time
time_t t;
time(&t);
struct tm gmt;
localtime_r(&t, &gmt);
snprintf((char *) fi.create_time, sizeof( fi.create_time ), "%04d:%02d:%02d:%02d:%02d:%02d:%s",
1900 + gmt.tm_year, gmt.tm_mon, gmt.tm_mday,
gmt.tm_hour, gmt.tm_min, gmt.tm_sec, gmt.tm_zone );
snprintf((char *) fi.creator, sizeof( fi.creator ), "cortex");
snprintf((char *) fi.project, sizeof( fi.project ), "cortex");
snprintf((char *) fi.copyright, sizeof( fi.copyright ), "Unknown");
ii.orientation = 0; // left-to-right, top-to-bottom
ii.element_number = 1;
ii.pixels_per_line = displayWidth;
ii.lines_per_image_ele = displayHeight;
ii.element_number = asBigEndian<>(ii.element_number);
ii.pixels_per_line = asBigEndian<>(ii.pixels_per_line);
ii.lines_per_image_ele = asBigEndian<>(ii.lines_per_image_ele);
for (int c = 0; c < 8; ++c)
{
DPXImageInformation::_image_element &ie = ii.image_element[c];
ie.data_sign = 0;
/// \todo Dcoument these constants
ie.ref_low_data = 0;
ie.ref_low_quantity = 0.0;
ie.ref_high_data = 1023;
ie.ref_high_quantity = 2.046;
ie.ref_low_data = asBigEndian<>(ie.ref_low_data);
ie.ref_low_quantity = asBigEndian<>(ie.ref_low_quantity);
ie.ref_high_data = asBigEndian<>(ie.ref_high_data);
ie.ref_high_quantity = asBigEndian<>(ie.ref_high_quantity);
/// \todo Dcoument these constants
ie.transfer = 1;
ie.packing = asBigEndian<short>( 1 );
ie.bit_size = 10;
ie.descriptor = 50;
ie.data_offset = fi.image_data_offset;
}
ioi.x_offset = 0;
ioi.y_offset = 0;
// Write the header
int image_data_size = sizeof( unsigned int ) * displayWidth * displayHeight;
fi.file_size = header_size + image_data_size;
fi.file_size = asBigEndian<>(fi.file_size);
out.write(reinterpret_cast<char *>(&fi), sizeof(fi));
if ( out.fail() )
{
throw IOException( "DPXImageWriter: Error writing to " + fileName() );
}
out.write(reinterpret_cast<char *>(&ii), sizeof(ii));
if ( out.fail() )
{
throw IOException( "DPXImageWriter: Error writing to " + fileName() );
}
out.write(reinterpret_cast<char *>(&ioi), sizeof(ioi));
if ( out.fail() )
{
throw IOException( "DPXImageWriter: Error writing to " + fileName() );
}
out.write(reinterpret_cast<char *>(&mpf), sizeof(mpf));
if ( out.fail() )
{
throw IOException( "DPXImageWriter: Error writing to " + fileName() );
}
out.write(reinterpret_cast<char *>(&th), sizeof(th));
if ( out.fail() )
{
throw IOException( "DPXImageWriter: Error writing to " + fileName() );
}
// write the data
vector<unsigned int> imageBuffer( displayWidth*displayHeight, 0 );
int offset = 0;
vector<string>::const_iterator i = filteredNames.begin();
while (i != filteredNames.end())
{
if (!(*i == "R" || *i == "G" || *i == "B"))
{
msg( Msg::Warning, "DPXImageWriter::write", format( "Channel \"%s\" was not encoded." ) % *i );
++i;
continue;
}
int bpp = 10;
unsigned int shift = (32 - bpp) - (offset*bpp);
assert( image->variables.find( *i ) != image->variables.end() );
DataPtr dataContainer = image->variables.find( *i )->second.data;
assert( dataContainer );
ChannelConverter converter( *i, image->getDisplayWindow(), dataWindow, shift, imageBuffer );
despatchTypedData<
ChannelConverter,
TypeTraits::IsNumericVectorTypedData,
ChannelConverter::ErrorHandler
>( dataContainer, converter );
++i;
++offset;
}
// write the buffer
for (int i = 0; i < displayWidth * displayHeight; ++i)
{
imageBuffer[i] = asBigEndian<>(imageBuffer[i]);
out.write( (const char *) (&imageBuffer[i]), sizeof(unsigned int) );
if ( out.fail() )
{
throw IOException( "DPXImageWriter: Error writing to " + fileName() );
}
}
}
<|endoftext|>
|
<commit_before>#include <list>
#include <map>
#include <stdexcept>
#include <string>
#include <utility>
#include <boost/tr1/unordered_map.hpp>
#include <boost/filesystem.hpp>
#include <AlpinoCorpus/CorpusReader.hh>
#include <AlpinoCorpus/CorpusReaderFactory.hh>
#include <AlpinoCorpus/Entry.hh>
#include <AlpinoCorpus/Error.hh>
#include <AlpinoCorpus/IterImpl.hh>
#include <AlpinoCorpus/RecursiveCorpusReader.hh>
#include "util/NameCompare.hh"
namespace bf = boost::filesystem;
namespace alpinocorpus {
struct ReaderIter
{
ReaderIter(std::string newName, CorpusReader *newReader,
CorpusReader::EntryIterator newIter) :
name(newName), reader(newReader), iter(newIter) {}
std::string name;
CorpusReader *reader;
CorpusReader::EntryIterator iter;
};
/*
bool operator==(ReaderIter const &left, ReaderIter const &right)
{
return left.name == right.name && left.reader == right.reader &&
left.iter == right.iter;
}
*/
class RecursiveCorpusReaderPrivate : public CorpusReader
{
typedef std::map<std::string, CorpusReader *, NameCompare> CorpusReaders;
class RecursiveIter : public IterImpl
{
public:
RecursiveIter(CorpusReaders const &readers);
RecursiveIter(CorpusReaders const &readers,
std::string const &query);
~RecursiveIter();
IterImpl *copy() const;
void nextIterator();
bool hasNext();
Entry next(CorpusReader const &rdr);
private:
std::list<ReaderIter> d_iters;
};
public:
RecursiveCorpusReaderPrivate(std::string const &directory);
virtual ~RecursiveCorpusReaderPrivate();
EntryIterator getEntries() const;
std::string getName() const;
size_t getSize() const;
void push_back(std::string const &name, CorpusReader *reader);
std::string readEntry(std::string const &) const;
std::string readEntryMarkQueries(std::string const &entry, std::list<MarkerQuery> const &queries) const;
EntryIterator runXPath(std::string const &query) const;
bool validQuery(QueryDialect d, bool variables, std::string const &query) const;
private:
CorpusReader const *corpusReaderFromPath(std::string const &path) const;
std::string entryFromPath(std::string const &path) const;
bf::path d_directory;
std::list<CorpusReader *> d_corpusReaders;
CorpusReaders d_corpusReaderMap;
};
// Implementation of the public interface.
RecursiveCorpusReader::RecursiveCorpusReader(std::string const &directory) :
d_private(new RecursiveCorpusReaderPrivate(directory))
{
}
RecursiveCorpusReader::~RecursiveCorpusReader()
{
delete d_private;
}
CorpusReader::EntryIterator RecursiveCorpusReader::getEntries() const
{
return d_private->getEntries();
}
std::string RecursiveCorpusReader::getName() const
{
return d_private->getName();
}
size_t RecursiveCorpusReader::getSize() const
{
return d_private->getSize();
}
bool RecursiveCorpusReader::validQuery(QueryDialect d, bool variables, std::string const &query) const
{
return d_private->isValidQuery(d, variables, query);
}
std::string RecursiveCorpusReader::readEntry(std::string const &entry) const
{
return d_private->readEntry(entry);
}
std::string RecursiveCorpusReader::readEntryMarkQueries(std::string const &entry,
std::list<MarkerQuery> const &queries) const
{
return d_private->readEntryMarkQueries(entry, queries);
}
CorpusReader::EntryIterator RecursiveCorpusReader::runXPath(std::string const &query) const
{
return d_private->query(XPATH, query);
}
// Implementation of the private interface
RecursiveCorpusReaderPrivate::RecursiveCorpusReaderPrivate(std::string const &directory)
{
if (directory[directory.size() - 1] == '/')
d_directory = bf::path(directory).parent_path();
else
d_directory = bf::path(directory);
if (!bf::exists(d_directory) ||
!bf::is_directory(d_directory))
throw OpenError(directory, "non-existent or not a directory");
for (bf::recursive_directory_iterator iter(d_directory, bf::symlink_option::recurse);
iter != bf::recursive_directory_iterator();
++iter)
{
if (iter->path().extension() != ".dact" &&
iter->path().extension() != ".index")
continue;
CorpusReader *reader(CorpusReaderFactory::open(iter->path().string()));
bf::path namePath = iter->path();
namePath.replace_extension("");
std::string name = namePath.string();
name.erase(0, d_directory.string().size() + 1);
push_back(name, reader);
}
}
RecursiveCorpusReaderPrivate::~RecursiveCorpusReaderPrivate()
{
for (std::list<CorpusReader *>::iterator iter = d_corpusReaders.begin();
iter != d_corpusReaders.end(); ++iter)
delete *iter;
}
CorpusReader::EntryIterator RecursiveCorpusReaderPrivate::getEntries() const
{
return EntryIterator(new RecursiveIter(d_corpusReaderMap));
}
std::string RecursiveCorpusReaderPrivate::getName() const
{
return "<multi>";
}
size_t RecursiveCorpusReaderPrivate::getSize() const
{
size_t size = 0;
for (std::list<CorpusReader *>::const_iterator iter =
d_corpusReaders.begin(); iter != d_corpusReaders.end(); ++iter)
size += (*iter)->size();
return size;
}
void RecursiveCorpusReaderPrivate::push_back(std::string const &name,
CorpusReader *reader)
{
// Ignore empty corpus readers, simplifies assumptions.
if (reader->size() == 0) {
delete reader;
return;
}
d_corpusReaders.push_back(reader);
d_corpusReaderMap[name] = reader; // XXX - exists check?
}
CorpusReader const *RecursiveCorpusReaderPrivate::corpusReaderFromPath(
std::string const &path) const
{
for (CorpusReaders::const_iterator iter =
d_corpusReaderMap.begin(); iter != d_corpusReaderMap.end(); ++iter)
if (path.find(iter->first) == 0)
return iter->second;
throw std::runtime_error(std::string("Unknown corpus: " + path));
}
std::string RecursiveCorpusReaderPrivate::entryFromPath(
std::string const &path) const
{
for (CorpusReaders::const_iterator iter =
d_corpusReaderMap.begin(); iter != d_corpusReaderMap.end(); ++iter)
if (path.find(iter->first) == 0)
return path.substr(iter->first.size() + 1);
throw std::runtime_error(std::string("Could not find entry: " + path));
}
std::string RecursiveCorpusReaderPrivate::readEntry(std::string const &path) const
{
CorpusReader const *reader = corpusReaderFromPath(path);
return reader->read(entryFromPath(path));
}
std::string RecursiveCorpusReaderPrivate::readEntryMarkQueries(
std::string const &path, std::list<MarkerQuery> const &queries) const
{
CorpusReader const *reader = corpusReaderFromPath(path);
return reader->read(entryFromPath(path), queries);
}
CorpusReader::EntryIterator RecursiveCorpusReaderPrivate::runXPath(
std::string const &query) const
{
return EntryIterator(new RecursiveIter(d_corpusReaderMap, query));
}
bool RecursiveCorpusReaderPrivate::validQuery(QueryDialect d, bool variables, std::string const &query) const
{
if (d_corpusReaders.size() == 0)
return false;
for (std::list<CorpusReader *>::const_iterator iter = d_corpusReaders.begin();
iter != d_corpusReaders.end(); ++iter)
if (!(*iter)->isValidQuery(d, variables, query))
return false;
// Correct according to all corpus readers.
return true;
}
// Iteration over RecursiveCorpusReaders
RecursiveCorpusReaderPrivate::RecursiveIter::RecursiveIter(
CorpusReaders const &readers)
{
for (CorpusReaders::const_iterator
iter = readers.begin();
iter != readers.end(); ++iter)
d_iters.push_back(ReaderIter(iter->first, iter->second,
(iter->second->entries())));
// If we have a query for which none of the corpora has a matching result,
// then the iterator is in fact an end-iterator. We just don't know it yet,
// unless we attempt to move the iterator.
nextIterator();
}
RecursiveCorpusReaderPrivate::RecursiveIter::RecursiveIter(
CorpusReaders const &readers,
std::string const &query)
{
for (CorpusReaders::const_iterator
iter = readers.begin();
iter != readers.end(); ++iter)
d_iters.push_back(ReaderIter(iter->first, iter->second,
(iter->second->query(XPATH, query))));
// If we have a query for which none of the corpora has a matching result,
// then the iterator is in fact an end-iterator. We just don't know it yet,
// unless we attempt to move the iterator.
nextIterator();
}
RecursiveCorpusReaderPrivate::RecursiveIter::~RecursiveIter() {}
IterImpl *RecursiveCorpusReaderPrivate::RecursiveIter::copy() const
{
// No pointer members, pointer member of ReaderIter is not managed by
// ReaderIter.
return new RecursiveIter(*this);
}
bool RecursiveCorpusReaderPrivate::RecursiveIter::hasNext()
{
return d_iters.size() != 0;
}
Entry RecursiveCorpusReaderPrivate::RecursiveIter::next(CorpusReader const &rdr)
{
if (d_iters.size() == 0)
throw std::runtime_error("Called next() on a finished iterator!");
Entry e = d_iters.front().iter.next(rdr);
e.name = d_iters.front().name + "/" + e.name;
nextIterator();
return e;
}
void RecursiveCorpusReaderPrivate::RecursiveIter::nextIterator()
{
while (d_iters.size() != 0 &&
!d_iters.front().iter.hasNext())
d_iters.pop_front();
}
}
<commit_msg>Make RecursiveCorpusReader lazy.<commit_after>#include <list>
#include <map>
#include <stdexcept>
#include <string>
#include <utility>
#include <boost/tr1/memory.hpp>
#include <boost/tr1/unordered_map.hpp>
#include <boost/filesystem.hpp>
#include <AlpinoCorpus/CorpusReader.hh>
#include <AlpinoCorpus/CorpusReaderFactory.hh>
#include <AlpinoCorpus/Entry.hh>
#include <AlpinoCorpus/Error.hh>
#include <AlpinoCorpus/IterImpl.hh>
#include <AlpinoCorpus/RecursiveCorpusReader.hh>
#include "util/NameCompare.hh"
namespace bf = boost::filesystem;
namespace alpinocorpus {
struct ReaderIter
{
ReaderIter(std::string newName, std::string newFilename) :
name(newName), filename(newFilename) {}
std::string name;
std::string filename;
};
/*
bool operator==(ReaderIter const &left, ReaderIter const &right)
{
return left.name == right.name && left.reader == right.reader &&
left.iter == right.iter;
}
*/
class RecursiveCorpusReaderPrivate : public CorpusReader
{
typedef std::map<std::string, std::string, NameCompare> Corpora;
class RecursiveIter : public IterImpl
{
public:
RecursiveIter(Corpora const &readers);
RecursiveIter(Corpora const &readers,
std::string const &query);
~RecursiveIter();
IterImpl *copy() const;
void nextIterator();
bool hasNext();
Entry next(CorpusReader const &rdr);
private:
void openTip();
std::list<ReaderIter> d_iters;
std::tr1::shared_ptr<CorpusReader> d_currentReader;
std::tr1::shared_ptr<CorpusReader::EntryIterator> d_currentIter;
std::string d_currentName;
bool d_hasQuery;
std::string d_query;
};
public:
RecursiveCorpusReaderPrivate(std::string const &directory);
virtual ~RecursiveCorpusReaderPrivate();
EntryIterator getEntries() const;
std::string getName() const;
size_t getSize() const;
void push_back(std::string const &name, std::string const &filename);
std::string readEntry(std::string const &) const;
std::string readEntryMarkQueries(std::string const &entry, std::list<MarkerQuery> const &queries) const;
EntryIterator runXPath(std::string const &query) const;
bool validQuery(QueryDialect d, bool variables, std::string const &query) const;
private:
std::string corpusFromPath(std::string const &path) const;
std::string entryFromPath(std::string const &path) const;
bf::path d_directory;
std::list<std::string> d_corpora;
Corpora d_corporaMap;
};
// Implementation of the public interface.
RecursiveCorpusReader::RecursiveCorpusReader(std::string const &directory) :
d_private(new RecursiveCorpusReaderPrivate(directory))
{
}
RecursiveCorpusReader::~RecursiveCorpusReader()
{
delete d_private;
}
CorpusReader::EntryIterator RecursiveCorpusReader::getEntries() const
{
return d_private->getEntries();
}
std::string RecursiveCorpusReader::getName() const
{
return d_private->getName();
}
size_t RecursiveCorpusReader::getSize() const
{
return d_private->getSize();
}
bool RecursiveCorpusReader::validQuery(QueryDialect d, bool variables, std::string const &query) const
{
return d_private->isValidQuery(d, variables, query);
}
std::string RecursiveCorpusReader::readEntry(std::string const &entry) const
{
return d_private->readEntry(entry);
}
std::string RecursiveCorpusReader::readEntryMarkQueries(std::string const &entry,
std::list<MarkerQuery> const &queries) const
{
return d_private->readEntryMarkQueries(entry, queries);
}
CorpusReader::EntryIterator RecursiveCorpusReader::runXPath(std::string const &query) const
{
return d_private->query(XPATH, query);
}
// Implementation of the private interface
RecursiveCorpusReaderPrivate::RecursiveCorpusReaderPrivate(std::string const &directory)
{
if (directory[directory.size() - 1] == '/')
d_directory = bf::path(directory).parent_path();
else
d_directory = bf::path(directory);
if (!bf::exists(d_directory) ||
!bf::is_directory(d_directory))
throw OpenError(directory, "non-existent or not a directory");
for (bf::recursive_directory_iterator iter(d_directory, bf::symlink_option::recurse);
iter != bf::recursive_directory_iterator();
++iter)
{
if (iter->path().extension() != ".dact" &&
iter->path().extension() != ".index")
continue;
bf::path namePath = iter->path();
namePath.replace_extension("");
std::string name = namePath.string();
name.erase(0, d_directory.string().size() + 1);
push_back(name, iter->path().string());
}
}
RecursiveCorpusReaderPrivate::~RecursiveCorpusReaderPrivate()
{
}
CorpusReader::EntryIterator RecursiveCorpusReaderPrivate::getEntries() const
{
return EntryIterator(new RecursiveIter(d_corporaMap));
}
std::string RecursiveCorpusReaderPrivate::getName() const
{
return "<multi>";
}
size_t RecursiveCorpusReaderPrivate::getSize() const
{
size_t size = 0;
for (std::list<std::string>::const_iterator iter =
d_corpora.begin(); iter != d_corpora.end(); ++iter)
{
CorpusReader *reader;
try {
reader = CorpusReaderFactory::open(*iter);
} catch (OpenError const &)
{
// XXX - Print a warning?
continue;
}
size += reader->size();
delete reader;
}
return size;
}
void RecursiveCorpusReaderPrivate::push_back(std::string const &name,
std::string const &filename)
{
// Ignore empty corpus readers, simplifies assumptions.
/*if (reader->size() == 0) {
delete reader;
return;
}
*/
d_corpora.push_back(filename);
d_corporaMap[name] = filename; // XXX - exists check?
}
std::string RecursiveCorpusReaderPrivate::corpusFromPath(
std::string const &path) const
{
for (Corpora::const_iterator iter =
d_corporaMap.begin(); iter != d_corporaMap.end(); ++iter)
if (path.find(iter->first) == 0)
return iter->second;
throw std::runtime_error(std::string("Unknown corpus: " + path));
}
std::string RecursiveCorpusReaderPrivate::entryFromPath(
std::string const &path) const
{
for (Corpora::const_iterator iter =
d_corporaMap.begin(); iter != d_corporaMap.end(); ++iter)
if (path.find(iter->first) == 0)
return path.substr(iter->first.size() + 1);
throw std::runtime_error(std::string("Could not find entry: " + path));
}
std::string RecursiveCorpusReaderPrivate::readEntry(std::string const &path) const
{
std::string fn = corpusFromPath(path);
CorpusReader *reader = CorpusReaderFactory::open(fn);
std::string data = reader->read(entryFromPath(path));
delete reader;
return data;
}
std::string RecursiveCorpusReaderPrivate::readEntryMarkQueries(
std::string const &path, std::list<MarkerQuery> const &queries) const
{
std::string fn = corpusFromPath(path);
CorpusReader *reader = CorpusReaderFactory::open(fn);
std::string data = reader->read(entryFromPath(path), queries);
delete reader;
return data;
}
CorpusReader::EntryIterator RecursiveCorpusReaderPrivate::runXPath(
std::string const &query) const
{
return EntryIterator(new RecursiveIter(d_corporaMap, query));
}
bool RecursiveCorpusReaderPrivate::validQuery(QueryDialect d, bool variables, std::string const &query) const
{
if (d_corpora.size() == 0)
return false;
// Only check using the first reader, otherwise, this is too expensive.
std::string fn = d_corpora.front();
CorpusReader *reader = CorpusReaderFactory::open(fn);
bool valid = reader->isValidQuery(d, variables, query);
delete reader;
return valid;
}
// Iteration over RecursiveCorpusReaders
RecursiveCorpusReaderPrivate::RecursiveIter::RecursiveIter(
Corpora const &corpora) : d_hasQuery(false)
{
for (Corpora::const_iterator
iter = corpora.begin();
iter != corpora.end(); ++iter)
d_iters.push_back(ReaderIter(iter->first, iter->second));
}
RecursiveCorpusReaderPrivate::RecursiveIter::RecursiveIter(
Corpora const &readers,
std::string const &query) : d_hasQuery(true)
{
for (Corpora::const_iterator
iter = readers.begin();
iter != readers.end(); ++iter)
d_iters.push_back(ReaderIter(iter->first, iter->second));
d_query = query;
}
RecursiveCorpusReaderPrivate::RecursiveIter::~RecursiveIter() {}
IterImpl *RecursiveCorpusReaderPrivate::RecursiveIter::copy() const
{
// No pointer members, pointer member of ReaderIter is not managed by
// ReaderIter.
return new RecursiveIter(*this);
}
bool RecursiveCorpusReaderPrivate::RecursiveIter::hasNext()
{
nextIterator();
return d_currentIter && d_currentIter->hasNext();
}
Entry RecursiveCorpusReaderPrivate::RecursiveIter::next(CorpusReader const &rdr)
{
Entry e = d_currentIter->next(rdr);
e.name = d_currentName + "/" + e.name;
return e;
}
void RecursiveCorpusReaderPrivate::RecursiveIter::nextIterator()
{
while (d_iters.size() != 0 &&
(!d_currentIter || !d_currentIter->hasNext()))
{
d_currentIter.reset();
d_currentReader.reset();
openTip();
d_iters.pop_front();
}
}
void RecursiveCorpusReaderPrivate::RecursiveIter::openTip()
{
CorpusReader *reader;
try {
reader = CorpusReaderFactory::open(d_iters.front().filename);
} catch (OpenError const &e)
{
// XXX - print warning?
return;
}
try {
if (d_hasQuery)
d_currentIter.reset(new EntryIterator(reader->query(CorpusReader::XPATH, d_query)));
else
d_currentIter.reset(new EntryIterator(reader->entries()));
} catch (std::runtime_error &e)
{
delete reader;
return;
}
d_currentReader.reset(reader);
d_currentName = d_iters.front().name;
}
}
<|endoftext|>
|
<commit_before>#include "util/funcs.h"
#include "util/bitmap.h"
#include "fog_atmosphere.h"
#include <math.h>
static int screenX(){
return 320;
}
static int screenY(){
return 240;
}
FogAtmosphere::FogAtmosphere():
Atmosphere(){
fog = new Bitmap( 50, 50 );
fog->fill( Bitmap::MaskColor );
fog->circleFill( 25, 25, 20, Bitmap::makeColor( 0xbb, 0xbb, 0xcc ) );
for ( int i = 0; i < screenX(); i += 20 ){
for ( int q = 0; q < 3; q++ ){
fogs.push_back( new Fog( i + Util::rnd( 9 ) - 4, screenY() - Util::rnd( 30 ) - 40, Util::rnd( 360 ) ) );
}
}
}
FogAtmosphere::~FogAtmosphere(){
delete fog;
}
void FogAtmosphere::draw( Bitmap * work ){
Bitmap::transBlender( 0, 0, 0, 64 );
for ( vector< Fog * >::iterator it = fogs.begin(); it != fogs.end(); it++ ){
Fog * f = *it;
int y = (int)(f->y + sin( f->ang * 3.14159 / 180.0 ) * 4);
fog->drawTrans( f->x, y, *work );
}
/*
screenX();
for ( int i = -10; i < screenX() + 10; i += 15 ){
fog->drawTrans( i, screenY() - 50, *work );
}
*/
}
void FogAtmosphere::act(){
for ( vector< Fog * >::iterator it = fogs.begin(); it != fogs.end(); it++ ){
Fog * f = *it;
f->ang += 1;
}
}
<commit_msg>delete fog<commit_after>#include "util/funcs.h"
#include "util/bitmap.h"
#include "fog_atmosphere.h"
#include <math.h>
static int screenX(){
return 320;
}
static int screenY(){
return 240;
}
FogAtmosphere::FogAtmosphere():
Atmosphere(){
fog = new Bitmap( 50, 50 );
fog->fill( Bitmap::MaskColor );
fog->circleFill( 25, 25, 20, Bitmap::makeColor( 0xbb, 0xbb, 0xcc ) );
for ( int i = 0; i < screenX(); i += 20 ){
for ( int q = 0; q < 3; q++ ){
fogs.push_back( new Fog( i + Util::rnd( 9 ) - 4, screenY() - Util::rnd( 30 ) - 40, Util::rnd( 360 ) ) );
}
}
}
FogAtmosphere::~FogAtmosphere(){
delete fog;
for ( vector< Fog * >::iterator it = fogs.begin(); it != fogs.end(); it++ ){
delete *it;
}
}
void FogAtmosphere::draw( Bitmap * work ){
Bitmap::transBlender( 0, 0, 0, 64 );
for ( vector< Fog * >::iterator it = fogs.begin(); it != fogs.end(); it++ ){
Fog * f = *it;
int y = (int)(f->y + sin( f->ang * 3.14159 / 180.0 ) * 4);
fog->drawTrans( f->x, y, *work );
}
/*
screenX();
for ( int i = -10; i < screenX() + 10; i += 15 ){
fog->drawTrans( i, screenY() - 50, *work );
}
*/
}
void FogAtmosphere::act(){
for ( vector< Fog * >::iterator it = fogs.begin(); it != fogs.end(); it++ ){
Fog * f = *it;
f->ang += 1;
}
}
<|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 <glog/logging.h>
#include <iostream>
#include <string>
#include <vector>
#include <mesos/resources.hpp>
#include <mesos/scheduler.hpp>
#include <process/clock.hpp>
#include <process/dispatch.hpp>
#include <process/process.hpp>
#include <process/time.hpp>
#include <stout/bytes.hpp>
#include <stout/flags.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/path.hpp>
#include <stout/stringify.hpp>
using namespace mesos;
using namespace mesos::internal;
using std::string;
using process::Clock;
const double CPUS_PER_TASK = 0.1;
const double CPUS_PER_EXECUTOR = 0.1;
const int32_t MEM_PER_EXECUTOR = 64;
class Flags : public flags::FlagsBase
{
public:
Flags()
{
add(&master,
"master",
"Master to connect to.");
add(&task_memory_usage_limit,
"task_memory_usage_limit",
None(),
"Maximum size, in bytes, of the task's memory usage.\n"
"The task will attempt to occupy memory up until this limit.",
static_cast<const Bytes*>(nullptr),
[](const Bytes& value) -> Option<Error> {
if (value.megabytes() < MEM_PER_EXECUTOR) {
return Error(
"Please use a --task_memory_usage_limit greater than " +
stringify(MEM_PER_EXECUTOR) + " MB");
}
return None();
});
add(&task_memory,
"task_memory",
"How much memory the framework will require per task.\n"
"If not specified, the task(s) will use all available memory in\n"
"applicable offers.");
add(&build_dir,
"build_dir",
"The build directory of Mesos. If set, the framework will assume\n"
"that the executor, framework, and agent(s) all live on the same\n"
"machine.");
add(&executor_uri,
"executor_uri",
"URI the fetcher should use to get the executor.");
add(&executor_command,
"executor_command",
"The command that should be used to start the executor.\n"
"This will override the value set by `--build_dir`.");
add(&checkpoint,
"checkpoint",
"Whether this framework should be checkpointed.\n",
false);
add(&long_running,
"long_running",
"Whether this framework should launch tasks repeatedly\n"
"or exit after finishing a single task.",
false);
}
string master;
Bytes task_memory_usage_limit;
Bytes task_memory;
// Flags for specifying the executor binary.
Option<string> build_dir;
Option<string> executor_uri;
Option<string> executor_command;
bool checkpoint;
bool long_running;
};
// Actor holding the business logic and metrics for the `BalloonScheduler`.
// See `BalloonScheduler` below for the intended behavior.
class BalloonSchedulerProcess : public process::Process<BalloonSchedulerProcess>
{
public:
BalloonSchedulerProcess(
const ExecutorInfo& _executor,
const Flags& _flags)
: executor(_executor),
flags(_flags),
taskActive(false),
tasksLaunched(0),
isRegistered(false)
{
start_time = Clock::now();
}
void registered()
{
isRegistered = true;
}
void disconnected()
{
isRegistered = false;
}
void resourceOffers(
SchedulerDriver* driver,
const std::vector<Offer>& offers)
{
static const Resources TASK_RESOURCES = Resources::parse(
"cpus:" + stringify(CPUS_PER_TASK) +
";mem:" + stringify(flags.task_memory.megabytes())).get();
static const Resources EXECUTOR_RESOURCES = Resources(executor.resources());
foreach (const Offer& offer, offers) {
Resources resources(offer.resources());
// If there is an active task, or if the offer is not
// big enough, reject the offer.
if (taskActive || !resources.flatten().contains(
TASK_RESOURCES + EXECUTOR_RESOURCES)) {
Filters filters;
filters.set_refuse_seconds(600);
driver->declineOffer(offer.id(), filters);
continue;
}
int taskId = tasksLaunched++;
LOG(INFO) << "Starting task " << taskId;
TaskInfo task;
task.set_name("Balloon Task");
task.mutable_task_id()->set_value(stringify(taskId));
task.mutable_slave_id()->MergeFrom(offer.slave_id());
task.mutable_resources()->CopyFrom(TASK_RESOURCES);
task.set_data(stringify(flags.task_memory_usage_limit));
task.mutable_executor()->CopyFrom(executor);
task.mutable_executor()->mutable_executor_id()
->set_value(stringify(taskId));
driver->launchTasks(offer.id(), {task});
taskActive = true;
}
}
void statusUpdate(SchedulerDriver* driver, const TaskStatus& status)
{
if (!flags.long_running) {
if (status.state() == TASK_FAILED &&
status.reason() == TaskStatus::REASON_CONTAINER_LIMITATION_MEMORY) {
// NOTE: We expect TASK_FAILED when this scheduler is launched by the
// balloon_framework_test.sh shell script. The abort here ensures the
// script considers the test result as "PASS".
driver->abort();
} else if (status.state() == TASK_FAILED ||
status.state() == TASK_FINISHED ||
status.state() == TASK_KILLED ||
status.state() == TASK_LOST ||
status.state() == TASK_ERROR) {
driver->stop();
}
}
// TODO(josephw): Add some metrics for some cases below.
switch (status.state()) {
case TASK_FINISHED:
case TASK_FAILED:
case TASK_KILLED:
case TASK_LOST:
case TASK_ERROR:
taskActive = false;
break;
default:
break;
}
}
private:
const ExecutorInfo executor;
const Flags flags;
bool taskActive;
int tasksLaunched;
process::Time start_time;
double _uptime_secs()
{
return (Clock::now() - start_time).secs();
}
bool isRegistered;
double _registered()
{
return isRegistered ? 1 : 0;
}
// TODO(josephw): Add some metrics here.
};
// This scheduler starts a single executor and task which gradually
// increases its memory footprint up to a limit. Depending on the
// resource limits set for the container, the framework expects the
// executor to either finish successfully or be OOM-killed.
class BalloonScheduler : public Scheduler
{
public:
BalloonScheduler(
const ExecutorInfo& _executor,
const Flags& _flags)
: process(_executor, _flags)
{
process::spawn(process);
}
virtual ~BalloonScheduler()
{
process::terminate(process);
process::wait(process);
}
virtual void registered(
SchedulerDriver*,
const FrameworkID& frameworkId,
const MasterInfo&)
{
LOG(INFO) << "Registered with framework ID: " << frameworkId;
process::dispatch(
&process,
&BalloonSchedulerProcess::registered);
}
virtual void reregistered(SchedulerDriver*, const MasterInfo& masterInfo)
{
LOG(INFO) << "Reregistered";
process::dispatch(
&process,
&BalloonSchedulerProcess::registered);
}
virtual void disconnected(SchedulerDriver* driver)
{
LOG(INFO) << "Disconnected";
process::dispatch(
&process,
&BalloonSchedulerProcess::disconnected);
}
virtual void resourceOffers(
SchedulerDriver* driver,
const std::vector<Offer>& offers)
{
LOG(INFO) << "Resource offers received";
process::dispatch(
&process,
&BalloonSchedulerProcess::resourceOffers,
driver,
offers);
}
virtual void offerRescinded(
SchedulerDriver* driver,
const OfferID& offerId)
{
LOG(INFO) << "Offer rescinded";
}
virtual void statusUpdate(SchedulerDriver* driver, const TaskStatus& status)
{
LOG(INFO)
<< "Task " << status.task_id() << " in state "
<< TaskState_Name(status.state())
<< ", Source: " << status.source()
<< ", Reason: " << status.reason()
<< (status.has_message() ? ", Message: " + status.message() : "");
process::dispatch(
&process,
&BalloonSchedulerProcess::statusUpdate,
driver,
status);
}
virtual void frameworkMessage(
SchedulerDriver* driver,
const ExecutorID& executorId,
const SlaveID& slaveId,
const string& data)
{
LOG(INFO) << "Framework message: " << data;
}
virtual void slaveLost(SchedulerDriver* driver, const SlaveID& slaveId)
{
LOG(INFO) << "Agent lost: " << slaveId;
}
virtual void executorLost(
SchedulerDriver* driver,
const ExecutorID& executorId,
const SlaveID& slaveId,
int status)
{
LOG(INFO) << "Executor '" << executorId << "' lost on agent: " << slaveId;
}
virtual void error(SchedulerDriver* driver, const string& message)
{
LOG(INFO) << "Error message: " << message;
}
private:
BalloonSchedulerProcess process;
};
int main(int argc, char** argv)
{
Flags flags;
Try<flags::Warnings> load = flags.load("MESOS_", argc, argv);
if (load.isError()) {
EXIT(EXIT_FAILURE) << flags.usage(load.error());
}
const Resources resources = Resources::parse(
"cpus:" + stringify(CPUS_PER_EXECUTOR) +
";mem:" + stringify(MEM_PER_EXECUTOR)).get();
ExecutorInfo executor;
executor.mutable_resources()->CopyFrom(resources);
executor.set_name("Balloon Executor");
executor.set_source("balloon_test");
// Determine the command to run the executor based on three possibilities:
// 1) `--executor_command` was set, which overrides the below cases.
// 2) We are in the Mesos build directory, so the targeted executable
// is actually a libtool wrapper script.
// 3) We have not detected the Mesos build directory, so assume the
// executor is in the same directory as the framework.
string command;
// Find this executable's directory to locate executor.
if (flags.executor_command.isSome()) {
command = flags.executor_command.get();
} else if (flags.build_dir.isSome()) {
command = path::join(
flags.build_dir.get(), "src", "balloon-executor");
} else {
command = path::join(
os::realpath(Path(argv[0]).dirname()).get(),
"balloon-executor");
}
executor.mutable_command()->set_value(command);
// Copy `--executor_uri` into the command.
if (flags.executor_uri.isSome()) {
mesos::CommandInfo::URI* uri = executor.mutable_command()->add_uris();
uri->set_value(flags.executor_uri.get());
uri->set_executable(true);
}
BalloonScheduler scheduler(executor, flags);
// Log any flag warnings (after logging is initialized by the scheduler).
foreach (const flags::Warning& warning, load->warnings) {
LOG(WARNING) << warning.message;
}
FrameworkInfo framework;
framework.set_user(os::user().get());
framework.set_name("Balloon Framework (C++)");
framework.set_checkpoint(flags.checkpoint);
MesosSchedulerDriver* driver;
// TODO(josephw): Refactor these into a common set of flags.
Option<string> value = os::getenv("MESOS_AUTHENTICATE_FRAMEWORKS");
if (value.isSome()) {
LOG(INFO) << "Enabling authentication for the framework";
value = os::getenv("DEFAULT_PRINCIPAL");
if (value.isNone()) {
EXIT(EXIT_FAILURE)
<< "Expecting authentication principal in the environment";
}
Credential credential;
credential.set_principal(value.get());
framework.set_principal(value.get());
value = os::getenv("DEFAULT_SECRET");
if (value.isNone()) {
EXIT(EXIT_FAILURE)
<< "Expecting authentication secret in the environment";
}
credential.set_secret(value.get());
driver = new MesosSchedulerDriver(
&scheduler, framework, flags.master, credential);
} else {
framework.set_principal("balloon-framework-cpp");
driver = new MesosSchedulerDriver(
&scheduler, framework, flags.master);
}
int status = driver->run() == DRIVER_STOPPED ? 0 : 1;
// Ensure that the driver process terminates.
driver->stop();
delete driver;
return status;
}
<commit_msg>Added metrics to the balloon framework.<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 <glog/logging.h>
#include <iostream>
#include <string>
#include <vector>
#include <mesos/resources.hpp>
#include <mesos/scheduler.hpp>
#include <process/clock.hpp>
#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/http.hpp>
#include <process/process.hpp>
#include <process/protobuf.hpp>
#include <process/time.hpp>
#include <process/metrics/counter.hpp>
#include <process/metrics/gauge.hpp>
#include <process/metrics/metrics.hpp>
#include <stout/bytes.hpp>
#include <stout/flags.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/path.hpp>
#include <stout/stringify.hpp>
using namespace mesos;
using namespace mesos::internal;
using std::string;
using process::Clock;
using process::defer;
using process::metrics::Gauge;
using process::metrics::Counter;
const double CPUS_PER_TASK = 0.1;
const double CPUS_PER_EXECUTOR = 0.1;
const int32_t MEM_PER_EXECUTOR = 64;
class Flags : public flags::FlagsBase
{
public:
Flags()
{
add(&master,
"master",
"Master to connect to.");
add(&task_memory_usage_limit,
"task_memory_usage_limit",
None(),
"Maximum size, in bytes, of the task's memory usage.\n"
"The task will attempt to occupy memory up until this limit.",
static_cast<const Bytes*>(nullptr),
[](const Bytes& value) -> Option<Error> {
if (value.megabytes() < MEM_PER_EXECUTOR) {
return Error(
"Please use a --task_memory_usage_limit greater than " +
stringify(MEM_PER_EXECUTOR) + " MB");
}
return None();
});
add(&task_memory,
"task_memory",
"How much memory the framework will require per task.\n"
"If not specified, the task(s) will use all available memory in\n"
"applicable offers.");
add(&build_dir,
"build_dir",
"The build directory of Mesos. If set, the framework will assume\n"
"that the executor, framework, and agent(s) all live on the same\n"
"machine.");
add(&executor_uri,
"executor_uri",
"URI the fetcher should use to get the executor.");
add(&executor_command,
"executor_command",
"The command that should be used to start the executor.\n"
"This will override the value set by `--build_dir`.");
add(&checkpoint,
"checkpoint",
"Whether this framework should be checkpointed.\n",
false);
add(&long_running,
"long_running",
"Whether this framework should launch tasks repeatedly\n"
"or exit after finishing a single task.",
false);
}
string master;
Bytes task_memory_usage_limit;
Bytes task_memory;
// Flags for specifying the executor binary.
Option<string> build_dir;
Option<string> executor_uri;
Option<string> executor_command;
bool checkpoint;
bool long_running;
};
// Actor holding the business logic and metrics for the `BalloonScheduler`.
// See `BalloonScheduler` below for the intended behavior.
class BalloonSchedulerProcess : public process::Process<BalloonSchedulerProcess>
{
public:
BalloonSchedulerProcess(
const ExecutorInfo& _executor,
const Flags& _flags)
: executor(_executor),
flags(_flags),
taskActive(false),
tasksLaunched(0),
isRegistered(false),
metrics(*this)
{
start_time = Clock::now();
}
void registered()
{
isRegistered = true;
}
void disconnected()
{
isRegistered = false;
}
void resourceOffers(
SchedulerDriver* driver,
const std::vector<Offer>& offers)
{
static const Resources TASK_RESOURCES = Resources::parse(
"cpus:" + stringify(CPUS_PER_TASK) +
";mem:" + stringify(flags.task_memory.megabytes())).get();
static const Resources EXECUTOR_RESOURCES = Resources(executor.resources());
foreach (const Offer& offer, offers) {
Resources resources(offer.resources());
// If there is an active task, or if the offer is not
// big enough, reject the offer.
if (taskActive || !resources.flatten().contains(
TASK_RESOURCES + EXECUTOR_RESOURCES)) {
Filters filters;
filters.set_refuse_seconds(600);
driver->declineOffer(offer.id(), filters);
continue;
}
int taskId = tasksLaunched++;
LOG(INFO) << "Starting task " << taskId;
TaskInfo task;
task.set_name("Balloon Task");
task.mutable_task_id()->set_value(stringify(taskId));
task.mutable_slave_id()->MergeFrom(offer.slave_id());
task.mutable_resources()->CopyFrom(TASK_RESOURCES);
task.set_data(stringify(flags.task_memory_usage_limit));
task.mutable_executor()->CopyFrom(executor);
task.mutable_executor()->mutable_executor_id()
->set_value(stringify(taskId));
driver->launchTasks(offer.id(), {task});
taskActive = true;
}
}
void statusUpdate(SchedulerDriver* driver, const TaskStatus& status)
{
if (!flags.long_running) {
if (status.state() == TASK_FAILED &&
status.reason() == TaskStatus::REASON_CONTAINER_LIMITATION_MEMORY) {
// NOTE: We expect TASK_FAILED when this scheduler is launched by the
// balloon_framework_test.sh shell script. The abort here ensures the
// script considers the test result as "PASS".
driver->abort();
} else if (status.state() == TASK_FAILED ||
status.state() == TASK_FINISHED ||
status.state() == TASK_KILLED ||
status.state() == TASK_LOST ||
status.state() == TASK_ERROR) {
driver->stop();
}
}
if (stringify(tasksLaunched - 1) != status.task_id().value()) {
// We might receive messages from older tasks. Ignore them.
LOG(INFO) << "Ignoring status update from older task "
<< status.task_id();
return;
}
switch (status.state()) {
case TASK_FINISHED:
taskActive = false;
++metrics.tasks_finished;
break;
case TASK_FAILED:
taskActive = false;
if (status.reason() == TaskStatus::REASON_CONTAINER_LIMITATION_MEMORY) {
++metrics.tasks_oomed;
break;
}
// NOTE: Fetching the executor (e.g. `--executor_uri`) may fail
// occasionally if the URI is rate limited. This case is common
// enough that it makes sense to track this failure metric separately.
if (status.reason() == TaskStatus::REASON_CONTAINER_LAUNCH_FAILED) {
++metrics.launch_failures;
break;
}
case TASK_KILLED:
case TASK_LOST:
case TASK_ERROR:
taskActive = false;
++metrics.abnormal_terminations;
break;
default:
break;
}
}
private:
const ExecutorInfo executor;
const Flags flags;
bool taskActive;
int tasksLaunched;
process::Time start_time;
double _uptime_secs()
{
return (Clock::now() - start_time).secs();
}
bool isRegistered;
double _registered()
{
return isRegistered ? 1 : 0;
}
struct Metrics
{
Metrics(const BalloonSchedulerProcess& _scheduler)
: uptime_secs(
"balloon_framework/uptime_secs",
defer(_scheduler, &BalloonSchedulerProcess::_uptime_secs)),
registered(
"balloon_framework/registered",
defer(_scheduler, &BalloonSchedulerProcess::_registered)),
tasks_finished("balloon_framework/tasks_finished"),
tasks_oomed("balloon_framework/tasks_oomed"),
launch_failures("balloon_framework/launch_failures"),
abnormal_terminations("balloon_framework/abnormal_terminations")
{
process::metrics::add(uptime_secs);
process::metrics::add(registered);
process::metrics::add(tasks_finished);
process::metrics::add(tasks_oomed);
process::metrics::add(launch_failures);
process::metrics::add(abnormal_terminations);
}
~Metrics()
{
process::metrics::remove(uptime_secs);
process::metrics::remove(registered);
process::metrics::remove(tasks_finished);
process::metrics::remove(tasks_oomed);
process::metrics::remove(launch_failures);
process::metrics::remove(abnormal_terminations);
}
process::metrics::Gauge uptime_secs;
process::metrics::Gauge registered;
process::metrics::Counter tasks_finished;
process::metrics::Counter tasks_oomed;
process::metrics::Counter launch_failures;
process::metrics::Counter abnormal_terminations;
} metrics;
};
// This scheduler starts a single executor and task which gradually
// increases its memory footprint up to a limit. Depending on the
// resource limits set for the container, the framework expects the
// executor to either finish successfully or be OOM-killed.
class BalloonScheduler : public Scheduler
{
public:
BalloonScheduler(
const ExecutorInfo& _executor,
const Flags& _flags)
: process(_executor, _flags)
{
process::spawn(process);
}
virtual ~BalloonScheduler()
{
process::terminate(process);
process::wait(process);
}
virtual void registered(
SchedulerDriver*,
const FrameworkID& frameworkId,
const MasterInfo&)
{
LOG(INFO) << "Registered with framework ID: " << frameworkId;
process::dispatch(
&process,
&BalloonSchedulerProcess::registered);
}
virtual void reregistered(SchedulerDriver*, const MasterInfo& masterInfo)
{
LOG(INFO) << "Reregistered";
process::dispatch(
&process,
&BalloonSchedulerProcess::registered);
}
virtual void disconnected(SchedulerDriver* driver)
{
LOG(INFO) << "Disconnected";
process::dispatch(
&process,
&BalloonSchedulerProcess::disconnected);
}
virtual void resourceOffers(
SchedulerDriver* driver,
const std::vector<Offer>& offers)
{
LOG(INFO) << "Resource offers received";
process::dispatch(
&process,
&BalloonSchedulerProcess::resourceOffers,
driver,
offers);
}
virtual void offerRescinded(
SchedulerDriver* driver,
const OfferID& offerId)
{
LOG(INFO) << "Offer rescinded";
}
virtual void statusUpdate(SchedulerDriver* driver, const TaskStatus& status)
{
LOG(INFO)
<< "Task " << status.task_id() << " in state "
<< TaskState_Name(status.state())
<< ", Source: " << status.source()
<< ", Reason: " << status.reason()
<< (status.has_message() ? ", Message: " + status.message() : "");
process::dispatch(
&process,
&BalloonSchedulerProcess::statusUpdate,
driver,
status);
}
virtual void frameworkMessage(
SchedulerDriver* driver,
const ExecutorID& executorId,
const SlaveID& slaveId,
const string& data)
{
LOG(INFO) << "Framework message: " << data;
}
virtual void slaveLost(SchedulerDriver* driver, const SlaveID& slaveId)
{
LOG(INFO) << "Agent lost: " << slaveId;
}
virtual void executorLost(
SchedulerDriver* driver,
const ExecutorID& executorId,
const SlaveID& slaveId,
int status)
{
LOG(INFO) << "Executor '" << executorId << "' lost on agent: " << slaveId;
}
virtual void error(SchedulerDriver* driver, const string& message)
{
LOG(INFO) << "Error message: " << message;
}
private:
BalloonSchedulerProcess process;
};
int main(int argc, char** argv)
{
Flags flags;
Try<flags::Warnings> load = flags.load("MESOS_", argc, argv);
if (load.isError()) {
EXIT(EXIT_FAILURE) << flags.usage(load.error());
}
const Resources resources = Resources::parse(
"cpus:" + stringify(CPUS_PER_EXECUTOR) +
";mem:" + stringify(MEM_PER_EXECUTOR)).get();
ExecutorInfo executor;
executor.mutable_resources()->CopyFrom(resources);
executor.set_name("Balloon Executor");
executor.set_source("balloon_test");
// Determine the command to run the executor based on three possibilities:
// 1) `--executor_command` was set, which overrides the below cases.
// 2) We are in the Mesos build directory, so the targeted executable
// is actually a libtool wrapper script.
// 3) We have not detected the Mesos build directory, so assume the
// executor is in the same directory as the framework.
string command;
// Find this executable's directory to locate executor.
if (flags.executor_command.isSome()) {
command = flags.executor_command.get();
} else if (flags.build_dir.isSome()) {
command = path::join(
flags.build_dir.get(), "src", "balloon-executor");
} else {
command = path::join(
os::realpath(Path(argv[0]).dirname()).get(),
"balloon-executor");
}
executor.mutable_command()->set_value(command);
// Copy `--executor_uri` into the command.
if (flags.executor_uri.isSome()) {
mesos::CommandInfo::URI* uri = executor.mutable_command()->add_uris();
uri->set_value(flags.executor_uri.get());
uri->set_executable(true);
}
BalloonScheduler scheduler(executor, flags);
// Log any flag warnings (after logging is initialized by the scheduler).
foreach (const flags::Warning& warning, load->warnings) {
LOG(WARNING) << warning.message;
}
FrameworkInfo framework;
framework.set_user(os::user().get());
framework.set_name("Balloon Framework (C++)");
framework.set_checkpoint(flags.checkpoint);
MesosSchedulerDriver* driver;
// TODO(josephw): Refactor these into a common set of flags.
Option<string> value = os::getenv("MESOS_AUTHENTICATE_FRAMEWORKS");
if (value.isSome()) {
LOG(INFO) << "Enabling authentication for the framework";
value = os::getenv("DEFAULT_PRINCIPAL");
if (value.isNone()) {
EXIT(EXIT_FAILURE)
<< "Expecting authentication principal in the environment";
}
Credential credential;
credential.set_principal(value.get());
framework.set_principal(value.get());
value = os::getenv("DEFAULT_SECRET");
if (value.isNone()) {
EXIT(EXIT_FAILURE)
<< "Expecting authentication secret in the environment";
}
credential.set_secret(value.get());
driver = new MesosSchedulerDriver(
&scheduler, framework, flags.master, credential);
} else {
framework.set_principal("balloon-framework-cpp");
driver = new MesosSchedulerDriver(
&scheduler, framework, flags.master);
}
int status = driver->run() == DRIVER_STOPPED ? 0 : 1;
// Ensure that the driver process terminates.
driver->stop();
delete driver;
return status;
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "Directory.h"
#include "utils/Charsets.h"
#include "utils/Filename.h"
#include "utils/Url.h"
#include "factory/IFileSystem.h"
#include "File.h"
#include "logging/Logger.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <windows.h>
#include <winapifamily.h>
namespace medialibrary
{
namespace fs
{
Directory::Directory( const std::string& mrl , factory::IFileSystem& fsFactory )
: CommonDirectory( fsFactory )
{
m_path = utils::file::toFolderPath( toAbsolute( utils::file::toLocalPath( mrl ) ) );
assert( *m_path.crbegin() == '/' );
m_mrl = utils::file::toMrl( m_path );
}
const std::string& Directory::mrl() const
{
return m_mrl;
}
void Directory::read() const
{
#if WINAPI_FAMILY_PARTITION (WINAPI_PARTITION_DESKTOP)
WIN32_FIND_DATA f;
auto pattern = m_path + '*';
auto wpattern = charset::ToWide( pattern.c_str() );
auto h = FindFirstFile( wpattern.get(), &f );
if ( h == INVALID_HANDLE_VALUE )
{
LOG_ERROR( "Failed to browse ", m_path );
throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" );
}
do
{
auto file = charset::FromWide( f.cFileName );
if ( file[0] == '.' && strcasecmp( file.get(), ".nomedia" ) )
continue;
if ( ( f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
m_dirs.emplace_back( m_fsFactory.createDirectory( m_path +
utils::url::encode( fullpath ) ) );
else
{
m_files.emplace_back( std::make_shared<File>( m_path + file.get() ) );
}
} while ( FindNextFile( h, &f ) != 0 );
FindClose( h );
#else
// We must remove the trailing /
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
// «Do not use a trailing backslash (\), which indicates the root directory of a drive»
auto tmpPath = path.substr( 0, m_path.length() - 1 );
auto wpath = charset::ToWide( tmpPath.c_str() );
CREATEFILE2_EXTENDED_PARAMETERS params{};
params.dwFileFlags = FILE_FLAG_BACKUP_SEMANTICS;
auto handle = CreateFile2( wpath.get(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, ¶ms );
if ( handle == INVALID_HANDLE_VALUE )
{
LOG_ERROR( "Failed to open directory ", m_path );
throw std::system_error( GetLastError(), std::generic_category(), "Failed to open directory" );
}
std::unique_ptr<typename std::remove_pointer<HANDLE>::type,
decltype(&CloseHandle)> handlePtr( handle, &CloseHandle );
// Allocating a 32 bytes buffer to contain the file name. If more is required, we'll allocate
size_t buffSize = sizeof( FILE_FULL_DIR_INFO ) + 32;
std::unique_ptr<FILE_FULL_DIR_INFO, void(*)(FILE_FULL_DIR_INFO*)> dirInfo(
reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ),
[](FILE_FULL_DIR_INFO* ptr) { free( ptr ); } );
if ( dirInfo == nullptr )
throw std::bad_alloc();
while ( true )
{
auto h = GetFileInformationByHandleEx( handle, FileFullDirectoryInfo, dirInfo.get(), buffSize );
if ( h == 0 )
{
auto error = GetLastError();
if ( error == ERROR_FILE_NOT_FOUND )
break;
else if ( error == ERROR_MORE_DATA )
{
buffSize *= 2;
dirInfo.reset( reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ) );
if ( dirInfo == nullptr )
throw std::bad_alloc();
continue;
}
LOG_ERROR( "Failed to browse ", m_path, ". GetLastError(): ", GetLastError() );
throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" );
}
auto file = charset::FromWide( dirInfo->FileName );
if ( file[0] == '.' && strcasecmp( file.get(), ".nomedia" ) )
continue;
if ( ( dirInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
m_dirs.emplace_back( m_fsFactory.createDirectory( m_mrl + utils::url::encode( file.get() ) ) );
else
m_files.emplace_back( std::make_shared<File>( m_path + file.get()) );
}
#endif
}
std::string Directory::toAbsolute( const std::string& path )
{
TCHAR buff[MAX_PATH];
auto wpath = charset::ToWide( path.c_str() );
if ( GetFullPathName( wpath.get(), MAX_PATH, buff, nullptr ) == 0 )
{
LOG_ERROR( "Failed to convert ", path, " to absolute path" );
throw std::system_error( GetLastError(), std::generic_category(), "Failed to convert to absolute path" );
}
auto upath = charset::FromWide( buff );
return std::string( upath.get() );
}
}
}
<commit_msg>win32: Directory: Fix build<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "Directory.h"
#include "utils/Charsets.h"
#include "utils/Filename.h"
#include "utils/Url.h"
#include "factory/IFileSystem.h"
#include "File.h"
#include "logging/Logger.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <windows.h>
#include <winapifamily.h>
namespace medialibrary
{
namespace fs
{
Directory::Directory( const std::string& mrl , factory::IFileSystem& fsFactory )
: CommonDirectory( fsFactory )
{
m_path = utils::file::toFolderPath( toAbsolute( utils::file::toLocalPath( mrl ) ) );
assert( *m_path.crbegin() == '/' );
m_mrl = utils::file::toMrl( m_path );
}
const std::string& Directory::mrl() const
{
return m_mrl;
}
void Directory::read() const
{
#if WINAPI_FAMILY_PARTITION (WINAPI_PARTITION_DESKTOP)
WIN32_FIND_DATA f;
auto pattern = m_path + '*';
auto wpattern = charset::ToWide( pattern.c_str() );
auto h = FindFirstFile( wpattern.get(), &f );
if ( h == INVALID_HANDLE_VALUE )
{
LOG_ERROR( "Failed to browse ", m_path );
throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" );
}
do
{
auto file = charset::FromWide( f.cFileName );
if ( file[0] == '.' && strcasecmp( file.get(), ".nomedia" ) )
continue;
auto fullpath = m_path + file.get();
if ( ( f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
m_dirs.emplace_back( m_fsFactory.createDirectory( m_path +
utils::url::encode( fullpath ) ) );
else
m_files.emplace_back( std::make_shared<File>( fullpath ) );
} while ( FindNextFile( h, &f ) != 0 );
FindClose( h );
#else
// We must remove the trailing /
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
// «Do not use a trailing backslash (\), which indicates the root directory of a drive»
auto tmpPath = path.substr( 0, m_path.length() - 1 );
auto wpath = charset::ToWide( tmpPath.c_str() );
CREATEFILE2_EXTENDED_PARAMETERS params{};
params.dwFileFlags = FILE_FLAG_BACKUP_SEMANTICS;
auto handle = CreateFile2( wpath.get(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, ¶ms );
if ( handle == INVALID_HANDLE_VALUE )
{
LOG_ERROR( "Failed to open directory ", m_path );
throw std::system_error( GetLastError(), std::generic_category(), "Failed to open directory" );
}
std::unique_ptr<typename std::remove_pointer<HANDLE>::type,
decltype(&CloseHandle)> handlePtr( handle, &CloseHandle );
// Allocating a 32 bytes buffer to contain the file name. If more is required, we'll allocate
size_t buffSize = sizeof( FILE_FULL_DIR_INFO ) + 32;
std::unique_ptr<FILE_FULL_DIR_INFO, void(*)(FILE_FULL_DIR_INFO*)> dirInfo(
reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ),
[](FILE_FULL_DIR_INFO* ptr) { free( ptr ); } );
if ( dirInfo == nullptr )
throw std::bad_alloc();
while ( true )
{
auto h = GetFileInformationByHandleEx( handle, FileFullDirectoryInfo, dirInfo.get(), buffSize );
if ( h == 0 )
{
auto error = GetLastError();
if ( error == ERROR_FILE_NOT_FOUND )
break;
else if ( error == ERROR_MORE_DATA )
{
buffSize *= 2;
dirInfo.reset( reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ) );
if ( dirInfo == nullptr )
throw std::bad_alloc();
continue;
}
LOG_ERROR( "Failed to browse ", m_path, ". GetLastError(): ", GetLastError() );
throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" );
}
auto file = charset::FromWide( dirInfo->FileName );
if ( file[0] == '.' && strcasecmp( file.get(), ".nomedia" ) )
continue;
if ( ( dirInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
m_dirs.emplace_back( m_fsFactory.createDirectory( m_mrl + utils::url::encode( file.get() ) ) );
else
m_files.emplace_back( std::make_shared<File>( m_path + file.get()) );
}
#endif
}
std::string Directory::toAbsolute( const std::string& path )
{
TCHAR buff[MAX_PATH];
auto wpath = charset::ToWide( path.c_str() );
if ( GetFullPathName( wpath.get(), MAX_PATH, buff, nullptr ) == 0 )
{
LOG_ERROR( "Failed to convert ", path, " to absolute path" );
throw std::system_error( GetLastError(), std::generic_category(), "Failed to convert to absolute path" );
}
auto upath = charset::FromWide( buff );
return std::string( upath.get() );
}
}
}
<|endoftext|>
|
<commit_before>#include "graph/expression_operators.h"
#include "layers/constructors.h"
#include "graph/node_operators.h"
#include "graph/node_operators_binary.h"
#include "graph/node_operators_unary.h"
namespace marian {
Expr debug(Expr a, const std::string& message) {
a->debug(message);
return a;
}
Expr logit(Expr a) {
return Expression<LogitNodeOp>(a);
}
Expr relu(Expr a) {
return Expression<ReLUNodeOp>(a);
}
Expr leakyrelu(Expr a) {
return Expression<PReLUNodeOp>(0.01f, a);
}
Expr prelu(Expr a, float alpha) {
return Expression<PReLUNodeOp>(alpha, a);
}
Expr log(Expr a) {
return Expression<LogNodeOp>(a);
};
Expr exp(Expr a) {
return Expression<ExpNodeOp>(a);
};
Expr swish(Expr a) {
return Expression<SwishNodeOp>(a);
}
Expr operator-(Expr a) {
return Expression<NegNodeOp>(a);
};
Expr softmax(Expr a, Expr mask) {
return Expression<SoftmaxNodeOp>(a, mask);
}
Expr logsoftmax(Expr a) {
return Expression<LogSoftmaxNodeOp>(a);
}
/*********************************************************/
Expr operator+(Expr a, Expr b) {
return Expression<PlusNodeOp>(a, b);
}
Expr operator-(Expr a, Expr b) {
return Expression<MinusNodeOp>(a, b);
}
Expr operator*(Expr a, Expr b) {
return Expression<MultNodeOp>(a, b);
}
Expr operator/(Expr a, Expr b) {
return Expression<DivNodeOp>(a, b);
}
/*********************************************************/
Expr operator+(Expr a, float b) {
return Expression<ScalarAddNodeOp>(a, b);
}
Expr operator+(float a, Expr b) {
return Expression<ScalarAddNodeOp>(b, a);
}
Expr operator-(Expr a, float b) {
return Expression<ScalarAddNodeOp>(a, -b);
}
Expr operator-(float a, Expr b) {
return Expression<ScalarAddNodeOp>(-b, a);
}
Expr operator*(float a, Expr b) {
return Expression<ScalarMultNodeOp>(b, a);
}
Expr operator*(Expr a, float b) {
return Expression<ScalarMultNodeOp>(a, b);
}
Expr operator/(Expr a, float b) {
return Expression<ScalarMultNodeOp>(a, 1.f / b);
}
// Expr pow(float a, Expr b) {
// return Expression<Scalar1PowNodeOp>(a, b);
//
//}
//
// Expr pow(Expr a, float b) {
// return Expression<Scalar2PowNodeOp>(a, b);
//
//}
//
// Expr pow(Expr a, Expr b) {
// return Expression<PowNodeOp>(a, b);
//}
/*********************************************************/
Expr concatenate(const std::vector<Expr>& concats, keywords::axis_k ax) {
return Expression<ConcatenateNodeOp>(concats, ax);
}
Expr repeat(Expr a, size_t repeats, keywords::axis_k ax) {
if(repeats == 1)
return a;
return concatenate(std::vector<Expr>(repeats, a), ax);
}
Expr reshape(Expr a, Shape shape) {
return Expression<ReshapeNodeOp>(a, shape);
}
Expr atleast_1d(Expr a) {
return atleast_nd(a, 1);
}
Expr atleast_2d(Expr a) {
return atleast_nd(a, 2);
}
Expr atleast_3d(Expr a) {
return atleast_nd(a, 3);
}
Expr atleast_4d(Expr a) {
return atleast_nd(a, 4);
}
Expr atleast_nd(Expr a, size_t dims) {
if(a->shape().size() >= dims)
return a;
Shape nShape;
nShape.resize(dims);
for(int i = 1; i <= a->shape().size(); ++i)
nShape.set(-i, a->shape()[-i]);
return reshape(a, nShape);
}
Expr flatten(Expr a) {
Shape shape = {a->shape().elements()};
return Expression<ReshapeNodeOp>(a, shape);
}
Expr flatten_2d(Expr a) {
Shape shape = {a->shape().elements() / a->shape()[-1], a->shape()[-1]};
return Expression<ReshapeNodeOp>(a, shape);
}
Expr rows(Expr a, const std::vector<size_t>& indices) {
return Expression<RowsNodeOp>(a, indices);
}
Expr cols(Expr a, const std::vector<size_t>& indices) {
return Expression<ColsNodeOp>(a, indices);
}
Expr select(Expr a, int axis, const std::vector<size_t>& indices) {
return Expression<SelectNodeOp>(a, axis, indices);
}
Expr sum(Expr a, keywords::axis_k ax) {
return Expression<SumNodeOp>(a, ax);
}
Expr mean(Expr a, keywords::axis_k ax) {
return Expression<MeanNodeOp>(a, ax);
}
Expr scalar_product(Expr a, Expr b, keywords::axis_k ax) {
return Expression<ScalarProductNodeOp>(a, b, ax);
}
Expr weighted_average(Expr in, Expr weights, keywords::axis_k ax) {
auto p = scalar_product(in, weights, ax);
auto s = sum(weights, ax);
return p / s;
}
Expr dot(Expr a, Expr b, bool transA, bool transB, float scalar) {
return Expression<DotNodeOp>(a, b, transA, transB, scalar);
}
Expr bdot(Expr a, Expr b, bool transA, bool transB, float scalar) {
return Expression<DotBatchedNodeOp>(a, b, transA, transB, scalar);
}
Expr transpose(Expr a) {
std::vector<int> axes(a->shape().size());
for(int i = 0; i < axes.size(); ++i) {
axes[i] = i;
}
if(axes.size() > 1) {
axes[axes.size() - 1] = axes.size() - 2;
axes[axes.size() - 2] = axes.size() - 1;
}
return Expression<TransposeNodeOp>(a, axes);
}
Expr transpose(Expr a, const std::vector<int>& axes) {
return Expression<TransposeNodeOp>(a, axes);
}
Expr step(Expr a, int step, int axis) {
return Expression<StepNodeOp>(a, step, axis);
}
Expr cross_entropy(Expr a, Expr b) {
// auto sOrig = a->shape();
// auto sOut = a->shape();
// Shape sTemp({sOrig[0] * sOrig[2] * sOrig[3], sOrig[1], 1, 1});
// sOut.set(1, 1);
// return reshape(Expression<CrossEntropyNodeOp>(reshape(a, sTemp), b), sOut);
return Expression<CrossEntropyNodeOp>(a, b);
}
Expr affine(Expr a, Expr b, Expr c, bool transA, bool transB, float scalar) {
std::vector<Expr> nodes = {a, b, c};
return debug(Expression<AffineNodeOp>(nodes, transA, transB, scalar), "test");
}
Expr plus(const std::vector<Expr>&) {
ABORT("Not implemented");
}
Expr swish(const std::vector<Expr>&) {
ABORT("Not implemented");
}
Expr tanh(const std::vector<Expr>& nodes) {
return Expression<TanhNodeOp>(nodes);
}
Expr logit(const std::vector<Expr>&) {
ABORT("Not implemented");
}
Expr relu(const std::vector<Expr>&) {
ABORT("Not implemented");
}
Expr leakyrelu(const std::vector<Expr>&) {
ABORT("Not implemented");
}
Expr prelu(const std::vector<Expr>&, float alpha) {
ABORT("Not implemented");
}
Expr sqrt(Expr a, float eps) {
return Expression<SqrtNodeOp>(a, eps);
}
Expr square(Expr a) {
return Expression<SquareNodeOp>(a);
}
Expr layer_norm(Expr x,
Expr gamma,
Expr beta /*= nullptr*/,
float eps /*= 1e-9*/) {
std::vector<Expr> nodes = {x, gamma};
if(beta)
nodes.push_back(beta);
return Expression<LayerNormalizationOp>(nodes, eps);
}
Expr highway(Expr y, Expr x, Expr t) {
std::vector<Expr> nodes = {y, x, t};
return Expression<HighwayNodeOp>(nodes);
}
Expr highway(const std::string prefix, Expr x) {
// clang-format off
size_t outDim = x->shape()[-1];
auto g = mlp::dense(x->graph())
("prefix", prefix + "_highway_d1")
("dim", outDim)
("activation", mlp::act::logit)
.construct()->apply(x);
auto relued = mlp::dense(x->graph())
("prefix", prefix + "_highway_d2")
("dim", outDim)
("activation", mlp::act::ReLU)
.construct()->apply(x);
return (g * relued) + ((1 - g) * x);
// clang-format on
}
// Expr batch_norm(Expr x, Expr gamma, Expr beta) {
// auto mju = mean(x, keywords::axis=0);
// auto xmmju = x - mju;
// auto std = sqrt(mean(square(xmmju), keywords::axis=0), 1e-9);
//
// if(beta)
// return gamma * (xmmju / std) + beta;
// else
// return gamma * (xmmju / std);
//}
Expr shift(Expr a, Shape shift) {
return Expression<ShiftNodeOp>(a, shift);
}
// Expr lexical_bias(Expr logits, Expr att, float eps, Ptr<sparse::CSR> lf) {
// return Expression<LexicalProbNodeOp>(logits, att, eps, lf);
//}
#ifdef CUDA_FOUND
Expr avg_pooling(Expr x,
int height,
int width,
int padHeight,
int padWidth,
int strideHeight,
int strideWidth) {
return Expression<PoolingOp>(
x, height, width, padHeight, padWidth, strideHeight, strideWidth, "avg");
}
Expr max_pooling(Expr x,
int height,
int width,
int padHeight,
int padWidth,
int strideHeight,
int strideWidth) {
return Expression<PoolingOp>(
x, height, width, padHeight, padWidth, strideHeight, strideWidth, "max");
}
Expr convert2cudnnFormat(Expr x) {
int numWords = x->shape()[0];
int numExamples = x->shape()[1];
int embSize = x->shape()[2];
std::vector<size_t> newIndeces;
for(int b = 0; b < numExamples; ++b) {
for(int t = 0; t < numWords; ++t) {
newIndeces.push_back((t * numExamples) + b);
}
}
auto xRows = reshape(x, {x->shape()[0] * x->shape()[1], x->shape()[2]});
Shape outShape({numExamples, 1, numWords, embSize});
return reshape(rows(xRows, newIndeces), outShape);
}
Expr convertFromcudnnFormat(Expr x) {
int batchDim = x->shape()[0];
int sentenceDim = x->shape()[2];
int embSize = x->shape()[3];
auto reshapedX = reshape(x, {batchDim * sentenceDim, embSize});
std::vector<size_t> newIndeces;
for(int t = 0; t < sentenceDim; ++t) {
for(int b = 0; b < batchDim; ++b) {
newIndeces.push_back(b * sentenceDim + t);
}
}
Shape shape({batchDim, sentenceDim, embSize});
return reshape(rows(reshapedX, newIndeces), shape);
}
Expr pooling_with_masking(Expr x, Expr mask, int width, bool isEven) {
return Expression<PoolingWithMaskingOp>(x, mask, width, isEven);
}
#endif
}
<commit_msg>remove debug message<commit_after>#include "graph/expression_operators.h"
#include "layers/constructors.h"
#include "graph/node_operators.h"
#include "graph/node_operators_binary.h"
#include "graph/node_operators_unary.h"
namespace marian {
Expr debug(Expr a, const std::string& message) {
a->debug(message);
return a;
}
Expr logit(Expr a) {
return Expression<LogitNodeOp>(a);
}
Expr relu(Expr a) {
return Expression<ReLUNodeOp>(a);
}
Expr leakyrelu(Expr a) {
return Expression<PReLUNodeOp>(0.01f, a);
}
Expr prelu(Expr a, float alpha) {
return Expression<PReLUNodeOp>(alpha, a);
}
Expr log(Expr a) {
return Expression<LogNodeOp>(a);
};
Expr exp(Expr a) {
return Expression<ExpNodeOp>(a);
};
Expr swish(Expr a) {
return Expression<SwishNodeOp>(a);
}
Expr operator-(Expr a) {
return Expression<NegNodeOp>(a);
};
Expr softmax(Expr a, Expr mask) {
return Expression<SoftmaxNodeOp>(a, mask);
}
Expr logsoftmax(Expr a) {
return Expression<LogSoftmaxNodeOp>(a);
}
/*********************************************************/
Expr operator+(Expr a, Expr b) {
return Expression<PlusNodeOp>(a, b);
}
Expr operator-(Expr a, Expr b) {
return Expression<MinusNodeOp>(a, b);
}
Expr operator*(Expr a, Expr b) {
return Expression<MultNodeOp>(a, b);
}
Expr operator/(Expr a, Expr b) {
return Expression<DivNodeOp>(a, b);
}
/*********************************************************/
Expr operator+(Expr a, float b) {
return Expression<ScalarAddNodeOp>(a, b);
}
Expr operator+(float a, Expr b) {
return Expression<ScalarAddNodeOp>(b, a);
}
Expr operator-(Expr a, float b) {
return Expression<ScalarAddNodeOp>(a, -b);
}
Expr operator-(float a, Expr b) {
return Expression<ScalarAddNodeOp>(-b, a);
}
Expr operator*(float a, Expr b) {
return Expression<ScalarMultNodeOp>(b, a);
}
Expr operator*(Expr a, float b) {
return Expression<ScalarMultNodeOp>(a, b);
}
Expr operator/(Expr a, float b) {
return Expression<ScalarMultNodeOp>(a, 1.f / b);
}
// Expr pow(float a, Expr b) {
// return Expression<Scalar1PowNodeOp>(a, b);
//
//}
//
// Expr pow(Expr a, float b) {
// return Expression<Scalar2PowNodeOp>(a, b);
//
//}
//
// Expr pow(Expr a, Expr b) {
// return Expression<PowNodeOp>(a, b);
//}
/*********************************************************/
Expr concatenate(const std::vector<Expr>& concats, keywords::axis_k ax) {
return Expression<ConcatenateNodeOp>(concats, ax);
}
Expr repeat(Expr a, size_t repeats, keywords::axis_k ax) {
if(repeats == 1)
return a;
return concatenate(std::vector<Expr>(repeats, a), ax);
}
Expr reshape(Expr a, Shape shape) {
return Expression<ReshapeNodeOp>(a, shape);
}
Expr atleast_1d(Expr a) {
return atleast_nd(a, 1);
}
Expr atleast_2d(Expr a) {
return atleast_nd(a, 2);
}
Expr atleast_3d(Expr a) {
return atleast_nd(a, 3);
}
Expr atleast_4d(Expr a) {
return atleast_nd(a, 4);
}
Expr atleast_nd(Expr a, size_t dims) {
if(a->shape().size() >= dims)
return a;
Shape nShape;
nShape.resize(dims);
for(int i = 1; i <= a->shape().size(); ++i)
nShape.set(-i, a->shape()[-i]);
return reshape(a, nShape);
}
Expr flatten(Expr a) {
Shape shape = {a->shape().elements()};
return Expression<ReshapeNodeOp>(a, shape);
}
Expr flatten_2d(Expr a) {
Shape shape = {a->shape().elements() / a->shape()[-1], a->shape()[-1]};
return Expression<ReshapeNodeOp>(a, shape);
}
Expr rows(Expr a, const std::vector<size_t>& indices) {
return Expression<RowsNodeOp>(a, indices);
}
Expr cols(Expr a, const std::vector<size_t>& indices) {
return Expression<ColsNodeOp>(a, indices);
}
Expr select(Expr a, int axis, const std::vector<size_t>& indices) {
return Expression<SelectNodeOp>(a, axis, indices);
}
Expr sum(Expr a, keywords::axis_k ax) {
return Expression<SumNodeOp>(a, ax);
}
Expr mean(Expr a, keywords::axis_k ax) {
return Expression<MeanNodeOp>(a, ax);
}
Expr scalar_product(Expr a, Expr b, keywords::axis_k ax) {
return Expression<ScalarProductNodeOp>(a, b, ax);
}
Expr weighted_average(Expr in, Expr weights, keywords::axis_k ax) {
auto p = scalar_product(in, weights, ax);
auto s = sum(weights, ax);
return p / s;
}
Expr dot(Expr a, Expr b, bool transA, bool transB, float scalar) {
return Expression<DotNodeOp>(a, b, transA, transB, scalar);
}
Expr bdot(Expr a, Expr b, bool transA, bool transB, float scalar) {
return Expression<DotBatchedNodeOp>(a, b, transA, transB, scalar);
}
Expr transpose(Expr a) {
std::vector<int> axes(a->shape().size());
for(int i = 0; i < axes.size(); ++i) {
axes[i] = i;
}
if(axes.size() > 1) {
axes[axes.size() - 1] = axes.size() - 2;
axes[axes.size() - 2] = axes.size() - 1;
}
return Expression<TransposeNodeOp>(a, axes);
}
Expr transpose(Expr a, const std::vector<int>& axes) {
return Expression<TransposeNodeOp>(a, axes);
}
Expr step(Expr a, int step, int axis) {
return Expression<StepNodeOp>(a, step, axis);
}
Expr cross_entropy(Expr a, Expr b) {
// auto sOrig = a->shape();
// auto sOut = a->shape();
// Shape sTemp({sOrig[0] * sOrig[2] * sOrig[3], sOrig[1], 1, 1});
// sOut.set(1, 1);
// return reshape(Expression<CrossEntropyNodeOp>(reshape(a, sTemp), b), sOut);
return Expression<CrossEntropyNodeOp>(a, b);
}
Expr affine(Expr a, Expr b, Expr c, bool transA, bool transB, float scalar) {
std::vector<Expr> nodes = {a, b, c};
return Expression<AffineNodeOp>(nodes, transA, transB, scalar);
}
Expr plus(const std::vector<Expr>&) {
ABORT("Not implemented");
}
Expr swish(const std::vector<Expr>&) {
ABORT("Not implemented");
}
Expr tanh(const std::vector<Expr>& nodes) {
return Expression<TanhNodeOp>(nodes);
}
Expr logit(const std::vector<Expr>&) {
ABORT("Not implemented");
}
Expr relu(const std::vector<Expr>&) {
ABORT("Not implemented");
}
Expr leakyrelu(const std::vector<Expr>&) {
ABORT("Not implemented");
}
Expr prelu(const std::vector<Expr>&, float alpha) {
ABORT("Not implemented");
}
Expr sqrt(Expr a, float eps) {
return Expression<SqrtNodeOp>(a, eps);
}
Expr square(Expr a) {
return Expression<SquareNodeOp>(a);
}
Expr layer_norm(Expr x,
Expr gamma,
Expr beta /*= nullptr*/,
float eps /*= 1e-9*/) {
std::vector<Expr> nodes = {x, gamma};
if(beta)
nodes.push_back(beta);
return Expression<LayerNormalizationOp>(nodes, eps);
}
Expr highway(Expr y, Expr x, Expr t) {
std::vector<Expr> nodes = {y, x, t};
return Expression<HighwayNodeOp>(nodes);
}
Expr highway(const std::string prefix, Expr x) {
// clang-format off
size_t outDim = x->shape()[-1];
auto g = mlp::dense(x->graph())
("prefix", prefix + "_highway_d1")
("dim", outDim)
("activation", mlp::act::logit)
.construct()->apply(x);
auto relued = mlp::dense(x->graph())
("prefix", prefix + "_highway_d2")
("dim", outDim)
("activation", mlp::act::ReLU)
.construct()->apply(x);
return (g * relued) + ((1 - g) * x);
// clang-format on
}
// Expr batch_norm(Expr x, Expr gamma, Expr beta) {
// auto mju = mean(x, keywords::axis=0);
// auto xmmju = x - mju;
// auto std = sqrt(mean(square(xmmju), keywords::axis=0), 1e-9);
//
// if(beta)
// return gamma * (xmmju / std) + beta;
// else
// return gamma * (xmmju / std);
//}
Expr shift(Expr a, Shape shift) {
return Expression<ShiftNodeOp>(a, shift);
}
// Expr lexical_bias(Expr logits, Expr att, float eps, Ptr<sparse::CSR> lf) {
// return Expression<LexicalProbNodeOp>(logits, att, eps, lf);
//}
#ifdef CUDA_FOUND
Expr avg_pooling(Expr x,
int height,
int width,
int padHeight,
int padWidth,
int strideHeight,
int strideWidth) {
return Expression<PoolingOp>(
x, height, width, padHeight, padWidth, strideHeight, strideWidth, "avg");
}
Expr max_pooling(Expr x,
int height,
int width,
int padHeight,
int padWidth,
int strideHeight,
int strideWidth) {
return Expression<PoolingOp>(
x, height, width, padHeight, padWidth, strideHeight, strideWidth, "max");
}
Expr convert2cudnnFormat(Expr x) {
int numWords = x->shape()[0];
int numExamples = x->shape()[1];
int embSize = x->shape()[2];
std::vector<size_t> newIndeces;
for(int b = 0; b < numExamples; ++b) {
for(int t = 0; t < numWords; ++t) {
newIndeces.push_back((t * numExamples) + b);
}
}
auto xRows = reshape(x, {x->shape()[0] * x->shape()[1], x->shape()[2]});
Shape outShape({numExamples, 1, numWords, embSize});
return reshape(rows(xRows, newIndeces), outShape);
}
Expr convertFromcudnnFormat(Expr x) {
int batchDim = x->shape()[0];
int sentenceDim = x->shape()[2];
int embSize = x->shape()[3];
auto reshapedX = reshape(x, {batchDim * sentenceDim, embSize});
std::vector<size_t> newIndeces;
for(int t = 0; t < sentenceDim; ++t) {
for(int b = 0; b < batchDim; ++b) {
newIndeces.push_back(b * sentenceDim + t);
}
}
Shape shape({batchDim, sentenceDim, embSize});
return reshape(rows(reshapedX, newIndeces), shape);
}
Expr pooling_with_masking(Expr x, Expr mask, int width, bool isEven) {
return Expression<PoolingWithMaskingOp>(x, mask, width, isEven);
}
#endif
}
<|endoftext|>
|
<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2014, 2015
Raffaello D. Di Napoli
This file is part of Abaclade.
Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Abaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
Public License for more details.
You should have received a copy of the GNU General Public License along with Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#include <abaclade.hxx>
#include <abaclade/bitmanip.hxx>
#if ABC_HOST_API_POSIX
#include <pthread.h>
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////
namespace abc { namespace detail {
#if ABC_HOST_API_POSIX
//! One-time initializer for g_pthkey.
static pthread_once_t g_pthonce = PTHREAD_ONCE_INIT;
//! TLS key.
static pthread_key_t g_pthkey;
#elif ABC_HOST_API_WIN32
//! TLS index.
static DWORD g_iTls = TLS_OUT_OF_INDEXES;
#endif
ABC_COLLECTIONS_STATIC_LIST_DEFINE_SUBCLASS_STATIC_MEMBERS(thread_local_storage)
std::size_t thread_local_storage::sm_cb = 0;
std::size_t thread_local_storage::sm_cbFrozen = 0;
thread_local_storage::thread_local_storage() :
m_pb(new std::int8_t[sm_cb]) {
if (sm_cbFrozen == 0) {
// Track the size of this first block.
sm_cbFrozen = sm_cb;
}
/* Assign the TLS slot immediately, so that if any of the construct()s calls get() we won’t end
up with an infinitely-recursive call. */
#if ABC_HOST_API_POSIX
pthread_setspecific(g_pthkey, this);
#elif ABC_HOST_API_WIN32
::TlsSetValue(g_iTls, this);
#endif
// Iterate over the list to construct TLS for this thread.
for (auto it(begin()), itEnd(end()); it != itEnd; ++it) {
it->construct(get_storage(it->m_ibStorageOffset));
}
}
thread_local_storage::~thread_local_storage() {
// Iterate backwards over the list to destruct TLS for this thread.
for (auto it(rbegin()), itEnd(rend()); it != itEnd; ++it) {
it->destruct(get_storage(it->m_ibStorageOffset));
}
}
/*static*/ void thread_local_storage::add_var(thread_local_var_impl * ptlvi, std::size_t cb) {
// Calculate the offset for *ptlvi’s storage and increase sm_cb accordingly.
ptlvi->m_ibStorageOffset = sm_cb;
sm_cb += bitmanip::ceiling_to_pow2_multiple(cb, sizeof(abc::max_align_t));
if (sm_cbFrozen && sm_cb > sm_cbFrozen) {
// TODO: can’t log/report anything since no thread locals are available! Fix me!
std::abort();
}
}
/*static*/ void thread_local_storage::alloc_slot() {
#if ABC_HOST_API_POSIX
if (int iErr = pthread_key_create(&g_pthkey, &destruct)) {
ABC_UNUSED_ARG(iErr);
// throw an exception (iErr).
}
#elif ABC_HOST_API_WIN32
g_iTls = ::TlsAlloc();
if (g_iTls == TLS_OUT_OF_INDEXES) {
// throw an exception (::GetLastError()).
}
#endif
}
#if ABC_HOST_API_POSIX
/*static*/ void thread_local_storage::destruct(void * pThis /*= get()*/) {
delete static_cast<thread_local_storage *>(pThis);
}
#endif
#if ABC_HOST_API_WIN32
/*static*/ bool thread_local_storage::dllmain_hook(unsigned iReason) {
if (iReason == DLL_PROCESS_ATTACH || iReason == DLL_THREAD_ATTACH) {
if (iReason == DLL_PROCESS_ATTACH) {
alloc_slot();
}
// Not calling construct() since initialization of TLS is lazy.
} else if (iReason == DLL_THREAD_DETACH || iReason == DLL_PROCESS_DETACH) {
/* Allow get() to return nullptr if the TLS slot was not initialized for this thread, in which
case nothing will happen. */
delete get(false);
if (iReason == DLL_PROCESS_DETACH) {
free_slot();
}
}
// TODO: handle errors and return false in case.
return true;
}
#endif //if ABC_HOST_API_WIN32
/*static*/ void thread_local_storage::free_slot() {
#if ABC_HOST_API_POSIX
pthread_key_delete(g_pthkey);
#elif ABC_HOST_API_WIN32
::TlsFree(g_iTls);
#endif
}
/*static*/ thread_local_storage * thread_local_storage::get(bool bCreateNewIfNull /*= true*/) {
void * pThis;
#if ABC_HOST_API_POSIX
// With POSIX Threads we need a one-time call to alloc_slot().
pthread_once(&g_pthonce, &alloc_slot);
pThis = pthread_getspecific(g_pthkey);
#elif ABC_HOST_API_WIN32
// Under Win32, alloc_slot() has already been called by dllmain_hook().
pThis = ::TlsGetValue(g_iTls);
#endif
if (pThis || !bCreateNewIfNull) {
return static_cast<thread_local_storage *>(pThis);
} else {
// First call for this thread: initialize the TLS slot.
return new thread_local_storage;
}
}
}} //namespace abc::detail
////////////////////////////////////////////////////////////////////////////////////////////////////
namespace abc { namespace detail {
thread_local_var_impl::thread_local_var_impl(std::size_t cbObject) {
// Initializes m_ibStorageOffset.
thread_local_storage::add_var(this, cbObject);
}
}} //namespace abc::detail
<commit_msg>Add missing #include<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2014, 2015
Raffaello D. Di Napoli
This file is part of Abaclade.
Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Abaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
Public License for more details.
You should have received a copy of the GNU General Public License along with Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#include <abaclade.hxx>
#include <abaclade/bitmanip.hxx>
#include <cstdlib> // std::abort()
#if ABC_HOST_API_POSIX
#include <pthread.h>
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////
namespace abc { namespace detail {
#if ABC_HOST_API_POSIX
//! One-time initializer for g_pthkey.
static pthread_once_t g_pthonce = PTHREAD_ONCE_INIT;
//! TLS key.
static pthread_key_t g_pthkey;
#elif ABC_HOST_API_WIN32
//! TLS index.
static DWORD g_iTls = TLS_OUT_OF_INDEXES;
#endif
ABC_COLLECTIONS_STATIC_LIST_DEFINE_SUBCLASS_STATIC_MEMBERS(thread_local_storage)
std::size_t thread_local_storage::sm_cb = 0;
std::size_t thread_local_storage::sm_cbFrozen = 0;
thread_local_storage::thread_local_storage() :
m_pb(new std::int8_t[sm_cb]) {
if (sm_cbFrozen == 0) {
// Track the size of this first block.
sm_cbFrozen = sm_cb;
}
/* Assign the TLS slot immediately, so that if any of the construct()s calls get() we won’t end
up with an infinitely-recursive call. */
#if ABC_HOST_API_POSIX
pthread_setspecific(g_pthkey, this);
#elif ABC_HOST_API_WIN32
::TlsSetValue(g_iTls, this);
#endif
// Iterate over the list to construct TLS for this thread.
for (auto it(begin()), itEnd(end()); it != itEnd; ++it) {
it->construct(get_storage(it->m_ibStorageOffset));
}
}
thread_local_storage::~thread_local_storage() {
// Iterate backwards over the list to destruct TLS for this thread.
for (auto it(rbegin()), itEnd(rend()); it != itEnd; ++it) {
it->destruct(get_storage(it->m_ibStorageOffset));
}
}
/*static*/ void thread_local_storage::add_var(thread_local_var_impl * ptlvi, std::size_t cb) {
// Calculate the offset for *ptlvi’s storage and increase sm_cb accordingly.
ptlvi->m_ibStorageOffset = sm_cb;
sm_cb += bitmanip::ceiling_to_pow2_multiple(cb, sizeof(abc::max_align_t));
if (sm_cbFrozen && sm_cb > sm_cbFrozen) {
// TODO: can’t log/report anything since no thread locals are available! Fix me!
std::abort();
}
}
/*static*/ void thread_local_storage::alloc_slot() {
#if ABC_HOST_API_POSIX
if (int iErr = pthread_key_create(&g_pthkey, &destruct)) {
ABC_UNUSED_ARG(iErr);
// throw an exception (iErr).
}
#elif ABC_HOST_API_WIN32
g_iTls = ::TlsAlloc();
if (g_iTls == TLS_OUT_OF_INDEXES) {
// throw an exception (::GetLastError()).
}
#endif
}
#if ABC_HOST_API_POSIX
/*static*/ void thread_local_storage::destruct(void * pThis /*= get()*/) {
delete static_cast<thread_local_storage *>(pThis);
}
#endif
#if ABC_HOST_API_WIN32
/*static*/ bool thread_local_storage::dllmain_hook(unsigned iReason) {
if (iReason == DLL_PROCESS_ATTACH || iReason == DLL_THREAD_ATTACH) {
if (iReason == DLL_PROCESS_ATTACH) {
alloc_slot();
}
// Not calling construct() since initialization of TLS is lazy.
} else if (iReason == DLL_THREAD_DETACH || iReason == DLL_PROCESS_DETACH) {
/* Allow get() to return nullptr if the TLS slot was not initialized for this thread, in which
case nothing will happen. */
delete get(false);
if (iReason == DLL_PROCESS_DETACH) {
free_slot();
}
}
// TODO: handle errors and return false in case.
return true;
}
#endif //if ABC_HOST_API_WIN32
/*static*/ void thread_local_storage::free_slot() {
#if ABC_HOST_API_POSIX
pthread_key_delete(g_pthkey);
#elif ABC_HOST_API_WIN32
::TlsFree(g_iTls);
#endif
}
/*static*/ thread_local_storage * thread_local_storage::get(bool bCreateNewIfNull /*= true*/) {
void * pThis;
#if ABC_HOST_API_POSIX
// With POSIX Threads we need a one-time call to alloc_slot().
pthread_once(&g_pthonce, &alloc_slot);
pThis = pthread_getspecific(g_pthkey);
#elif ABC_HOST_API_WIN32
// Under Win32, alloc_slot() has already been called by dllmain_hook().
pThis = ::TlsGetValue(g_iTls);
#endif
if (pThis || !bCreateNewIfNull) {
return static_cast<thread_local_storage *>(pThis);
} else {
// First call for this thread: initialize the TLS slot.
return new thread_local_storage;
}
}
}} //namespace abc::detail
////////////////////////////////////////////////////////////////////////////////////////////////////
namespace abc { namespace detail {
thread_local_var_impl::thread_local_var_impl(std::size_t cbObject) {
// Initializes m_ibStorageOffset.
thread_local_storage::add_var(this, cbObject);
}
}} //namespace abc::detail
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (C) 2006 by FThauer FHammer *
* f.thauer@web.de *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "chattools.h"
#include "session.h"
#include "configfile.h"
#include "gametablestylereader.h"
#include "gamelobbydialogimpl.h"
#include <iostream>
using namespace std;
ChatTools::ChatTools(QLineEdit* l, ConfigFile *c, ChatType ct, QTextBrowser *b, QStandardItemModel *m, gameLobbyDialogImpl *lo) : nickAutoCompletitionCounter(0), myLineEdit(l), myNickListModel(m), myNickStringList(NULL), myTextBrowser(b), myChatType(ct), myConfig(c), myNick(""), myLobby(lo)
{
myNick = QString::fromUtf8(myConfig->readConfigString("MyName").c_str());
ignoreList = myConfig->readConfigStringList("PlayerIgnoreList");
}
ChatTools::~ChatTools()
{
}
void ChatTools::sendMessage() {
if(myLineEdit->text().size() && mySession) {
fillChatLinesHistory(myLineEdit->text());
if(myChatType == INGAME_CHAT) {
mySession->sendGameChatMessage(myLineEdit->text().toUtf8().constData());
}
else {
mySession->sendLobbyChatMessage(myLineEdit->text().toUtf8().constData());
}
myLineEdit->setText("");
}
}
void ChatTools::receiveMessage(QString playerName, QString message) {
if(myTextBrowser) {
message = message.replace("<","<");
message = message.replace(">",">");
//refresh myNick if it was changed during runtime
myNick = QString::fromUtf8(myConfig->readConfigString("MyName").c_str());
QString tempMsg;
if(INET_LOBBY_CHAT && playerName == "(chat bot)" && message.startsWith(myNick)) {
tempMsg = QString("<span style=\"font-weight:bold; color:red;\">"+message+"</span>");
//play beep sound only in INET-lobby-chat
if(myLobby->isVisible() && myConfig->readConfigInt("PlayLobbyChatNotification")) {
myLobby->getMyW()->getMySDLPlayer()->playSound("lobbychatnotify",0);
}
}
else if(message.contains(myNick, Qt::CaseInsensitive)) {
switch (myChatType) {
case INET_LOBBY_CHAT: {
tempMsg = QString("<span style=\"font-weight:bold; color:"+myLobby->palette().link().color().name()+";\">"+message+"</span>");
//play beep sound only in INET-lobby-chat
// TODO dont play when message is from yourself
if(myLobby->isVisible() && myConfig->readConfigInt("PlayLobbyChatNotification")) {
myLobby->getMyW()->getMySDLPlayer()->playSound("lobbychatnotify",0);
}
}
break;
case LAN_LOBBY_CHAT: tempMsg = QString("<span style=\"font-weight:bold;\">"+message+"</span>");
break;
case INGAME_CHAT: tempMsg = QString("<span style=\"color:#"+myStyle->getChatTextNickNotifyColor()+";\">"+message+"</span>");
break;
default: tempMsg = message;
}
}
else if(playerName == myNick) {
switch (myChatType) {
case INET_LOBBY_CHAT: tempMsg = QString("<span style=\"font-weight:normal; color:"+myLobby->palette().link().color().name()+";\">"+message+"</span>");
break;
case LAN_LOBBY_CHAT: tempMsg = QString("<span style=\"font-weight:normal;\">"+message+"</span>");
break;
case INGAME_CHAT: tempMsg = QString("<span style=\"color:#"+myStyle->getChatLogTextColor()+";\">"+message+"</span>");
break;
default: tempMsg = message;
}
}
else {
switch (myChatType) {
case INET_LOBBY_CHAT: tempMsg = QString("<span style=\"font-weight:normal; color:"+myLobby->palette().text().color().name()+";\">"+message+"</span>");
break;
case LAN_LOBBY_CHAT: tempMsg = QString("<span style=\"font-weight:normal;\">"+message+"</span>");
break;
case INGAME_CHAT: tempMsg = QString("<span style=\"color:#"+myStyle->getChatLogTextColor()+";\">"+message+"</span>");
break;
default: tempMsg = message;
}
}
bool nickFoundOnIgnoreList = false;
list<std::string>::iterator it1;
for(it1=ignoreList.begin(); it1 != ignoreList.end(); it1++) {
if(playerName == QString::fromUtf8(it1->c_str())) {
nickFoundOnIgnoreList = true;
}
}
if(!nickFoundOnIgnoreList) {
myTextBrowser->append(playerName + ": " + tempMsg);
}
}
}
void ChatTools::clearChat() {
if(myTextBrowser)
myTextBrowser->clear();
}
void ChatTools::checkInputLength(QString string) {
if(string.toUtf8().length() > 120) myLineEdit->setMaxLength(string.length());
}
void ChatTools::fillChatLinesHistory(QString fillString) {
chatLinesHistory << fillString;
if(chatLinesHistory.size() > 50) chatLinesHistory.removeFirst();
}
void ChatTools::showChatHistoryIndex(int index) {
if(index <= chatLinesHistory.size()) {
// cout << chatLinesHistory.size() << " : " << index << endl;
if(index > 0)
myLineEdit->setText(chatLinesHistory.at(chatLinesHistory.size()-(index)));
else
myLineEdit->setText("");
}
}
void ChatTools::nickAutoCompletition() {
QString myChatString = myLineEdit->text();
QStringList myChatStringList = myChatString.split(" ");
QStringList matchStringList;
if(nickAutoCompletitionCounter == 0) {
if(myNickListModel) {
int it = 0;
while (myNickListModel->item(it)) {
QString text = myNickListModel->item(it, 0)->data(Qt::DisplayRole).toString();
if(text.startsWith(myChatStringList.last(), Qt::CaseInsensitive) && myChatStringList.last() != "") {
matchStringList << text;
}
++it;
}
}
if(!myNickStringList.isEmpty()) {
QStringListIterator it(myNickStringList);
while (it.hasNext()) {
QString next = it.next();
if (next.startsWith(myChatStringList.last(), Qt::CaseInsensitive) && myChatStringList.last() != "")
matchStringList << next;
}
}
}
if(!matchStringList.isEmpty() || nickAutoCompletitionCounter > 0) {
myChatStringList.removeLast();
// cout << nickAutoCompletitionCounter << endl;
if(nickAutoCompletitionCounter == 0) {
//first one
lastChatString = myChatStringList.join(" ");
lastMatchStringList = matchStringList;
}
if(nickAutoCompletitionCounter == lastMatchStringList.size()) nickAutoCompletitionCounter = 0;
// cout << nickAutoCompletitionCounter << "\n";
if(lastChatString == "")
myLineEdit->setText(lastMatchStringList.at(nickAutoCompletitionCounter)+": ");
else
myLineEdit->setText(lastChatString+" "+lastMatchStringList.at(nickAutoCompletitionCounter)+" ");
nickAutoCompletitionCounter++;
}
}
void ChatTools::setChatTextEdited() {
nickAutoCompletitionCounter = 0;
}
void ChatTools::refreshIgnoreList()
{
ignoreList = myConfig->readConfigStringList("PlayerIgnoreList");
}
<commit_msg>fixes<commit_after>/***************************************************************************
* Copyright (C) 2006 by FThauer FHammer *
* f.thauer@web.de *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "chattools.h"
#include "session.h"
#include "configfile.h"
#include "gametablestylereader.h"
#include "gamelobbydialogimpl.h"
#include <iostream>
using namespace std;
ChatTools::ChatTools(QLineEdit* l, ConfigFile *c, ChatType ct, QTextBrowser *b, QStandardItemModel *m, gameLobbyDialogImpl *lo) : nickAutoCompletitionCounter(0), myLineEdit(l), myNickListModel(m), myNickStringList(NULL), myTextBrowser(b), myChatType(ct), myConfig(c), myNick(""), myLobby(lo)
{
myNick = QString::fromUtf8(myConfig->readConfigString("MyName").c_str());
ignoreList = myConfig->readConfigStringList("PlayerIgnoreList");
}
ChatTools::~ChatTools()
{
}
void ChatTools::sendMessage() {
if(myLineEdit->text().size() && mySession) {
fillChatLinesHistory(myLineEdit->text());
if(myChatType == INGAME_CHAT) {
mySession->sendGameChatMessage(myLineEdit->text().toUtf8().constData());
}
else {
mySession->sendLobbyChatMessage(myLineEdit->text().toUtf8().constData());
}
myLineEdit->setText("");
}
}
void ChatTools::receiveMessage(QString playerName, QString message) {
if(myTextBrowser) {
message = message.replace("<","<");
message = message.replace(">",">");
//refresh myNick if it was changed during runtime
myNick = QString::fromUtf8(myConfig->readConfigString("MyName").c_str());
QString tempMsg;
if(myChatType == INET_LOBBY_CHAT && playerName == "(chat bot)" && message.startsWith(myNick)) {
tempMsg = QString("<span style=\"font-weight:bold; color:red;\">"+message+"</span>");
//play beep sound only in INET-lobby-chat
if(myLobby->isVisible() && myConfig->readConfigInt("PlayLobbyChatNotification")) {
myLobby->getMyW()->getMySDLPlayer()->playSound("lobbychatnotify",0);
}
}
else if(message.contains(myNick, Qt::CaseInsensitive)) {
switch (myChatType) {
case INET_LOBBY_CHAT: {
tempMsg = QString("<span style=\"font-weight:bold; color:"+myLobby->palette().link().color().name()+";\">"+message+"</span>");
//play beep sound only in INET-lobby-chat
// TODO dont play when message is from yourself
if(myLobby->isVisible() && myConfig->readConfigInt("PlayLobbyChatNotification")) {
myLobby->getMyW()->getMySDLPlayer()->playSound("lobbychatnotify",0);
}
}
break;
case LAN_LOBBY_CHAT: tempMsg = QString("<span style=\"font-weight:bold;\">"+message+"</span>");
break;
case INGAME_CHAT: tempMsg = QString("<span style=\"color:#"+myStyle->getChatTextNickNotifyColor()+";\">"+message+"</span>");
break;
default: tempMsg = message;
}
}
else if(playerName == myNick) {
switch (myChatType) {
case INET_LOBBY_CHAT: tempMsg = QString("<span style=\"font-weight:normal; color:"+myLobby->palette().link().color().name()+";\">"+message+"</span>");
break;
case LAN_LOBBY_CHAT: tempMsg = QString("<span style=\"font-weight:normal;\">"+message+"</span>");
break;
case INGAME_CHAT: tempMsg = QString("<span style=\"color:#"+myStyle->getChatLogTextColor()+";\">"+message+"</span>");
break;
default: tempMsg = message;
}
}
else {
switch (myChatType) {
case INET_LOBBY_CHAT: tempMsg = QString("<span style=\"font-weight:normal; color:"+myLobby->palette().text().color().name()+";\">"+message+"</span>");
break;
case LAN_LOBBY_CHAT: tempMsg = QString("<span style=\"font-weight:normal;\">"+message+"</span>");
break;
case INGAME_CHAT: tempMsg = QString("<span style=\"color:#"+myStyle->getChatLogTextColor()+";\">"+message+"</span>");
break;
default: tempMsg = message;
}
}
bool nickFoundOnIgnoreList = false;
list<std::string>::iterator it1;
for(it1=ignoreList.begin(); it1 != ignoreList.end(); it1++) {
if(playerName == QString::fromUtf8(it1->c_str())) {
nickFoundOnIgnoreList = true;
}
}
if(!nickFoundOnIgnoreList) {
myTextBrowser->append(playerName + ": " + tempMsg);
}
}
}
void ChatTools::clearChat() {
if(myTextBrowser)
myTextBrowser->clear();
}
void ChatTools::checkInputLength(QString string) {
if(string.toUtf8().length() > 120) myLineEdit->setMaxLength(string.length());
}
void ChatTools::fillChatLinesHistory(QString fillString) {
chatLinesHistory << fillString;
if(chatLinesHistory.size() > 50) chatLinesHistory.removeFirst();
}
void ChatTools::showChatHistoryIndex(int index) {
if(index <= chatLinesHistory.size()) {
// cout << chatLinesHistory.size() << " : " << index << endl;
if(index > 0)
myLineEdit->setText(chatLinesHistory.at(chatLinesHistory.size()-(index)));
else
myLineEdit->setText("");
}
}
void ChatTools::nickAutoCompletition() {
QString myChatString = myLineEdit->text();
QStringList myChatStringList = myChatString.split(" ");
QStringList matchStringList;
if(nickAutoCompletitionCounter == 0) {
if(myNickListModel) {
int it = 0;
while (myNickListModel->item(it)) {
QString text = myNickListModel->item(it, 0)->data(Qt::DisplayRole).toString();
if(text.startsWith(myChatStringList.last(), Qt::CaseInsensitive) && myChatStringList.last() != "") {
matchStringList << text;
}
++it;
}
}
if(!myNickStringList.isEmpty()) {
QStringListIterator it(myNickStringList);
while (it.hasNext()) {
QString next = it.next();
if (next.startsWith(myChatStringList.last(), Qt::CaseInsensitive) && myChatStringList.last() != "")
matchStringList << next;
}
}
}
if(!matchStringList.isEmpty() || nickAutoCompletitionCounter > 0) {
myChatStringList.removeLast();
// cout << nickAutoCompletitionCounter << endl;
if(nickAutoCompletitionCounter == 0) {
//first one
lastChatString = myChatStringList.join(" ");
lastMatchStringList = matchStringList;
}
if(nickAutoCompletitionCounter == lastMatchStringList.size()) nickAutoCompletitionCounter = 0;
// cout << nickAutoCompletitionCounter << "\n";
if(lastChatString == "")
myLineEdit->setText(lastMatchStringList.at(nickAutoCompletitionCounter)+": ");
else
myLineEdit->setText(lastChatString+" "+lastMatchStringList.at(nickAutoCompletitionCounter)+" ");
nickAutoCompletitionCounter++;
}
}
void ChatTools::setChatTextEdited() {
nickAutoCompletitionCounter = 0;
}
void ChatTools::refreshIgnoreList()
{
ignoreList = myConfig->readConfigStringList("PlayerIgnoreList");
}
<|endoftext|>
|
<commit_before>#ifndef BASE_OBSTACLE_DETECTOR_H_
#define BASE_OBSTACLE_DETECTOR_H_
#include <vector>
#include <algorithm>
#include <pcl/visualization/cloud_viewer.h>
#include "lepp2/VideoObserver.hpp"
#include "lepp2/BaseSegmenter.hpp"
#include "lepp2/NoopSegmenter.hpp"
#include "lepp2/EuclideanPlaneSegmenter.hpp"
#include "lepp2/ObstacleAggregator.hpp"
#include "lepp2/ObjectApproximator.hpp"
#include "lepp2/MomentOfInertiaApproximator.hpp"
using namespace lepp;
#include "lepp2/debug/timer.hpp"
template<class PointT>
class BaseObstacleDetector : public lepp::VideoObserver<PointT> {
public:
BaseObstacleDetector();
virtual ~BaseObstacleDetector() {}
/**
* VideoObserver interface method implementation.
*/
virtual void notifyNewFrame(
int idx,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud);
/**
* Attaches a new ObstacleAggregator, which will be notified of newly detected
* obstacles by this detector.
*/
void attachObstacleAggregator(
boost::shared_ptr<ObstacleAggregator> aggregator);
/**
* Returns the point cloud that the detector is currently working with.
*
* NOTE: Needed only for the legacy code that relies of pulling the point
* cloud from the detector, instead of getting it as a parameter.
*/
virtual typename pcl::PointCloud<PointT>::ConstPtr getPointCloud() const {
return cloud_;
}
protected:
/// Some convenience typedefs
typedef pcl::PointCloud<PointT> PointCloud;
typedef typename pcl::PointCloud<PointT>::ConstPtr PointCloudConstPtr;
/**
* Notifies any observers about newly detected obstacles.
*/
void notifyObstacles(std::vector<ObjectModelPtr> const& models);
private:
typename pcl::PointCloud<PointT>::ConstPtr cloud_;
/**
* Tracks all attached ObstacleAggregators that wish to be notified of newly
* detected obstacles.
*/
std::vector<boost::shared_ptr<ObstacleAggregator> > aggregators;
boost::shared_ptr<BaseSegmenter<PointT> > segmenter_;
boost::shared_ptr<ObjectApproximator<PointT> > approximator_;
/**
* Performs a new update of the obstacle approximations.
* Triggered when the detector is notified of a new frame (i.e. point cloud).
*/
void update();
};
template<class PointT>
BaseObstacleDetector<PointT>::BaseObstacleDetector()
: approximator_(new MomentOfInertiaObjectApproximator<PointT>()),
segmenter_(new EuclideanPlaneSegmenter<PointT>()) {
// TODO Allow for dependency injection.
}
template<class PointT>
void BaseObstacleDetector<PointT>::notifyNewFrame(
int id,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) {
cloud_ = point_cloud;
update();
}
template<class PointT>
void BaseObstacleDetector<PointT>::update() {
Timer t;
t.start();
std::vector<PointCloudConstPtr> segments(segmenter_->segment(cloud_));
// Iteratively approximate the segments
size_t segment_count = segments.size();
std::vector<ObjectModelPtr> models;
for (size_t i = 0; i < segment_count; ++i) {
std::vector<ObjectModelPtr> approximations =
approximator_->approximate(segments[i]);
// Add all approximations to the final return value.
// For now the fact that multiple approximations were a part of one group
// is ignored to keep compatibility with the old iterfaces.
std::copy(approximations.begin(), approximations.end(),
std::back_inserter(models));
}
t.stop();
std::cerr << "Obstacle detection took " << t.duration() << std::endl;
notifyObstacles(models);
}
template<class PointT>
void BaseObstacleDetector<PointT>::attachObstacleAggregator(
boost::shared_ptr<ObstacleAggregator> aggregator) {
aggregators.push_back(aggregator);
}
template<class PointT>
void BaseObstacleDetector<PointT>::notifyObstacles(
std::vector<ObjectModelPtr> const& models) {
size_t sz = aggregators.size();
for (size_t i = 0; i < sz; ++i) {
aggregators[i]->updateObstacles(models);
}
}
#endif
<commit_msg>Wrap obstacle detection in a try-catch block<commit_after>#ifndef BASE_OBSTACLE_DETECTOR_H_
#define BASE_OBSTACLE_DETECTOR_H_
#include <vector>
#include <algorithm>
#include <pcl/visualization/cloud_viewer.h>
#include "lepp2/VideoObserver.hpp"
#include "lepp2/BaseSegmenter.hpp"
#include "lepp2/NoopSegmenter.hpp"
#include "lepp2/EuclideanPlaneSegmenter.hpp"
#include "lepp2/ObstacleAggregator.hpp"
#include "lepp2/ObjectApproximator.hpp"
#include "lepp2/MomentOfInertiaApproximator.hpp"
using namespace lepp;
#include "lepp2/debug/timer.hpp"
template<class PointT>
class BaseObstacleDetector : public lepp::VideoObserver<PointT> {
public:
BaseObstacleDetector();
virtual ~BaseObstacleDetector() {}
/**
* VideoObserver interface method implementation.
*/
virtual void notifyNewFrame(
int idx,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud);
/**
* Attaches a new ObstacleAggregator, which will be notified of newly detected
* obstacles by this detector.
*/
void attachObstacleAggregator(
boost::shared_ptr<ObstacleAggregator> aggregator);
/**
* Returns the point cloud that the detector is currently working with.
*
* NOTE: Needed only for the legacy code that relies of pulling the point
* cloud from the detector, instead of getting it as a parameter.
*/
virtual typename pcl::PointCloud<PointT>::ConstPtr getPointCloud() const {
return cloud_;
}
protected:
/// Some convenience typedefs
typedef pcl::PointCloud<PointT> PointCloud;
typedef typename pcl::PointCloud<PointT>::ConstPtr PointCloudConstPtr;
/**
* Notifies any observers about newly detected obstacles.
*/
void notifyObstacles(std::vector<ObjectModelPtr> const& models);
private:
typename pcl::PointCloud<PointT>::ConstPtr cloud_;
/**
* Tracks all attached ObstacleAggregators that wish to be notified of newly
* detected obstacles.
*/
std::vector<boost::shared_ptr<ObstacleAggregator> > aggregators;
boost::shared_ptr<BaseSegmenter<PointT> > segmenter_;
boost::shared_ptr<ObjectApproximator<PointT> > approximator_;
/**
* Performs a new update of the obstacle approximations.
* Triggered when the detector is notified of a new frame (i.e. point cloud).
*/
void update();
};
template<class PointT>
BaseObstacleDetector<PointT>::BaseObstacleDetector()
: approximator_(new MomentOfInertiaObjectApproximator<PointT>()),
segmenter_(new EuclideanPlaneSegmenter<PointT>()) {
// TODO Allow for dependency injection.
}
template<class PointT>
void BaseObstacleDetector<PointT>::notifyNewFrame(
int id,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) {
cloud_ = point_cloud;
try {
update();
} catch (...) {
std::cerr << "ObstacleDetector: Obstacle detection failed ..." << std::endl;
}
}
template<class PointT>
void BaseObstacleDetector<PointT>::update() {
Timer t;
t.start();
std::vector<PointCloudConstPtr> segments(segmenter_->segment(cloud_));
// Iteratively approximate the segments
size_t segment_count = segments.size();
std::vector<ObjectModelPtr> models;
for (size_t i = 0; i < segment_count; ++i) {
std::vector<ObjectModelPtr> approximations =
approximator_->approximate(segments[i]);
// Add all approximations to the final return value.
// For now the fact that multiple approximations were a part of one group
// is ignored to keep compatibility with the old iterfaces.
std::copy(approximations.begin(), approximations.end(),
std::back_inserter(models));
}
t.stop();
std::cerr << "Obstacle detection took " << t.duration() << std::endl;
notifyObstacles(models);
}
template<class PointT>
void BaseObstacleDetector<PointT>::attachObstacleAggregator(
boost::shared_ptr<ObstacleAggregator> aggregator) {
aggregators.push_back(aggregator);
}
template<class PointT>
void BaseObstacleDetector<PointT>::notifyObstacles(
std::vector<ObjectModelPtr> const& models) {
size_t sz = aggregators.size();
for (size_t i = 0; i < sz; ++i) {
aggregators[i]->updateObstacles(models);
}
}
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2015 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 "net/third_party/quiche/src/quic/tools/quic_client_base.h"
#include "net/third_party/quiche/src/quic/core/crypto/quic_random.h"
#include "net/third_party/quiche/src/quic/core/http/spdy_utils.h"
#include "net/third_party/quiche/src/quic/core/quic_server_id.h"
#include "net/third_party/quiche/src/quic/core/quic_utils.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
namespace quic {
QuicClientBase::NetworkHelper::~NetworkHelper() = default;
QuicClientBase::QuicClientBase(
const QuicServerId& server_id,
const ParsedQuicVersionVector& supported_versions,
const QuicConfig& config,
QuicConnectionHelperInterface* helper,
QuicAlarmFactory* alarm_factory,
std::unique_ptr<NetworkHelper> network_helper,
std::unique_ptr<ProofVerifier> proof_verifier,
std::unique_ptr<SessionCache> session_cache)
: server_id_(server_id),
initialized_(false),
local_port_(0),
config_(config),
crypto_config_(std::move(proof_verifier), std::move(session_cache)),
helper_(helper),
alarm_factory_(alarm_factory),
supported_versions_(supported_versions),
initial_max_packet_length_(0),
num_sent_client_hellos_(0),
connection_error_(QUIC_NO_ERROR),
connected_or_attempting_connect_(false),
network_helper_(std::move(network_helper)),
connection_debug_visitor_(nullptr),
server_connection_id_length_(kQuicDefaultConnectionIdLength),
client_connection_id_length_(0) {}
QuicClientBase::~QuicClientBase() = default;
bool QuicClientBase::Initialize() {
num_sent_client_hellos_ = 0;
connection_error_ = QUIC_NO_ERROR;
connected_or_attempting_connect_ = false;
// If an initial flow control window has not explicitly been set, then use the
// same values that Chrome uses.
const uint32_t kSessionMaxRecvWindowSize = 15 * 1024 * 1024; // 15 MB
const uint32_t kStreamMaxRecvWindowSize = 6 * 1024 * 1024; // 6 MB
if (config()->GetInitialStreamFlowControlWindowToSend() ==
kDefaultFlowControlSendWindow) {
config()->SetInitialStreamFlowControlWindowToSend(kStreamMaxRecvWindowSize);
}
if (config()->GetInitialSessionFlowControlWindowToSend() ==
kDefaultFlowControlSendWindow) {
config()->SetInitialSessionFlowControlWindowToSend(
kSessionMaxRecvWindowSize);
}
if (!network_helper_->CreateUDPSocketAndBind(server_address_,
bind_to_address_, local_port_)) {
return false;
}
initialized_ = true;
return true;
}
bool QuicClientBase::Connect() {
// Attempt multiple connects until the maximum number of client hellos have
// been sent.
int num_attempts = 0;
while (!connected() &&
num_attempts <= QuicCryptoClientStream::kMaxClientHellos) {
StartConnect();
while (EncryptionBeingEstablished()) {
WaitForEvents();
}
ParsedQuicVersion version = UnsupportedQuicVersion();
if (session() != nullptr && !CanReconnectWithDifferentVersion(&version)) {
// We've successfully created a session but we're not connected, and we
// cannot reconnect with a different version. Give up trying.
break;
}
num_attempts++;
}
if (session() == nullptr) {
QUIC_BUG << "Missing session after Connect";
return false;
}
return session()->connection()->connected();
}
void QuicClientBase::StartConnect() {
DCHECK(initialized_);
DCHECK(!connected());
QuicPacketWriter* writer = network_helper_->CreateQuicPacketWriter();
ParsedQuicVersion mutual_version = UnsupportedQuicVersion();
const bool can_reconnect_with_different_version =
CanReconnectWithDifferentVersion(&mutual_version);
if (connected_or_attempting_connect()) {
// Clear queued up data if client can not try to connect with a different
// version.
if (!can_reconnect_with_different_version) {
ClearDataToResend();
}
// Before we destroy the last session and create a new one, gather its stats
// and update the stats for the overall connection.
UpdateStats();
}
session_ = CreateQuicClientSession(
supported_versions(),
new QuicConnection(GetNextConnectionId(), server_address(), helper(),
alarm_factory(), writer,
/* owns_writer= */ false, Perspective::IS_CLIENT,
can_reconnect_with_different_version
? ParsedQuicVersionVector{mutual_version}
: supported_versions()));
if (connection_debug_visitor_ != nullptr) {
session()->connection()->set_debug_visitor(connection_debug_visitor_);
}
session()->connection()->set_client_connection_id(GetClientConnectionId());
if (initial_max_packet_length_ != 0) {
session()->connection()->SetMaxPacketLength(initial_max_packet_length_);
}
// Reset |writer()| after |session()| so that the old writer outlives the old
// session.
set_writer(writer);
InitializeSession();
if (can_reconnect_with_different_version) {
// This is a reconnect using server supported |mutual_version|.
session()->connection()->SetVersionNegotiated();
}
set_connected_or_attempting_connect(true);
}
void QuicClientBase::InitializeSession() {
session()->Initialize();
}
void QuicClientBase::Disconnect() {
DCHECK(initialized_);
initialized_ = false;
if (connected()) {
session()->connection()->CloseConnection(
QUIC_PEER_GOING_AWAY, "Client disconnecting",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
}
ClearDataToResend();
network_helper_->CleanUpAllUDPSockets();
}
ProofVerifier* QuicClientBase::proof_verifier() const {
return crypto_config_.proof_verifier();
}
bool QuicClientBase::EncryptionBeingEstablished() {
return !session_->IsEncryptionEstablished() &&
session_->connection()->connected();
}
bool QuicClientBase::WaitForEvents() {
if (!connected()) {
QUIC_BUG << "Cannot call WaitForEvents on non-connected client";
return false;
}
network_helper_->RunEventLoop();
DCHECK(session() != nullptr);
ParsedQuicVersion version = UnsupportedQuicVersion();
if (!connected() && CanReconnectWithDifferentVersion(&version)) {
QUIC_DLOG(INFO) << "Can reconnect with version: " << version
<< ", attempting to reconnect.";
Connect();
}
return HasActiveRequests();
}
bool QuicClientBase::MigrateSocket(const QuicIpAddress& new_host) {
return MigrateSocketWithSpecifiedPort(new_host, local_port_);
}
bool QuicClientBase::MigrateSocketWithSpecifiedPort(
const QuicIpAddress& new_host,
int port) {
if (!connected()) {
return false;
}
network_helper_->CleanUpAllUDPSockets();
set_bind_to_address(new_host);
if (!network_helper_->CreateUDPSocketAndBind(server_address_,
bind_to_address_, port)) {
return false;
}
session()->connection()->SetSelfAddress(
network_helper_->GetLatestClientAddress());
QuicPacketWriter* writer = network_helper_->CreateQuicPacketWriter();
set_writer(writer);
session()->connection()->SetQuicPacketWriter(writer, false);
return true;
}
bool QuicClientBase::ChangeEphemeralPort() {
auto current_host = network_helper_->GetLatestClientAddress().host();
return MigrateSocketWithSpecifiedPort(current_host, 0 /*any ephemeral port*/);
}
QuicSession* QuicClientBase::session() {
return session_.get();
}
const QuicSession* QuicClientBase::session() const {
return session_.get();
}
QuicClientBase::NetworkHelper* QuicClientBase::network_helper() {
return network_helper_.get();
}
const QuicClientBase::NetworkHelper* QuicClientBase::network_helper() const {
return network_helper_.get();
}
void QuicClientBase::WaitForStreamToClose(QuicStreamId id) {
if (!connected()) {
QUIC_BUG << "Cannot WaitForStreamToClose on non-connected client";
return;
}
while (connected() && !session_->IsClosedStream(id)) {
WaitForEvents();
}
}
bool QuicClientBase::WaitForOneRttKeysAvailable() {
if (!connected()) {
QUIC_BUG << "Cannot WaitForOneRttKeysAvailable on non-connected client";
return false;
}
while (connected() && !session_->OneRttKeysAvailable()) {
WaitForEvents();
}
// If the handshake fails due to a timeout, the connection will be closed.
QUIC_LOG_IF(ERROR, !connected()) << "Handshake with server failed.";
return connected();
}
bool QuicClientBase::WaitForHandshakeConfirmed() {
if (!session_->connection()->version().HasHandshakeDone()) {
return WaitForOneRttKeysAvailable();
}
while (connected() && session_->GetHandshakeState() < HANDSHAKE_CONFIRMED) {
WaitForEvents();
}
// If the handshake fails due to a timeout, the connection will be closed.
QUIC_LOG_IF(ERROR, !connected()) << "Handshake with server failed.";
return connected();
}
bool QuicClientBase::connected() const {
return session_.get() && session_->connection() &&
session_->connection()->connected();
}
bool QuicClientBase::goaway_received() const {
return session_ != nullptr && session_->goaway_received();
}
int QuicClientBase::GetNumSentClientHellos() {
// If we are not actively attempting to connect, the session object
// corresponds to the previous connection and should not be used.
const int current_session_hellos = !connected_or_attempting_connect_
? 0
: GetNumSentClientHellosFromSession();
return num_sent_client_hellos_ + current_session_hellos;
}
void QuicClientBase::UpdateStats() {
num_sent_client_hellos_ += GetNumSentClientHellosFromSession();
}
int QuicClientBase::GetNumReceivedServerConfigUpdates() {
// If we are not actively attempting to connect, the session object
// corresponds to the previous connection and should not be used.
return !connected_or_attempting_connect_
? 0
: GetNumReceivedServerConfigUpdatesFromSession();
}
QuicErrorCode QuicClientBase::connection_error() const {
// Return the high-level error if there was one. Otherwise, return the
// connection error from the last session.
if (connection_error_ != QUIC_NO_ERROR) {
return connection_error_;
}
if (session_ == nullptr) {
return QUIC_NO_ERROR;
}
return session_->error();
}
QuicConnectionId QuicClientBase::GetNextConnectionId() {
return GenerateNewConnectionId();
}
QuicConnectionId QuicClientBase::GenerateNewConnectionId() {
return QuicUtils::CreateRandomConnectionId(server_connection_id_length_);
}
QuicConnectionId QuicClientBase::GetClientConnectionId() {
return QuicUtils::CreateRandomConnectionId(client_connection_id_length_);
}
bool QuicClientBase::CanReconnectWithDifferentVersion(
ParsedQuicVersion* version) const {
if (session_ == nullptr || session_->connection() == nullptr ||
session_->error() != QUIC_INVALID_VERSION ||
session_->connection()->server_supported_versions().empty()) {
return false;
}
for (const auto& client_version : supported_versions_) {
if (QuicContainsValue(session_->connection()->server_supported_versions(),
client_version)) {
*version = client_version;
return true;
}
}
return false;
}
} // namespace quic
<commit_msg>Fix client supported versions when quic_client reconnects. Client code only, not protected.<commit_after>// Copyright (c) 2015 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 "net/third_party/quiche/src/quic/tools/quic_client_base.h"
#include "net/third_party/quiche/src/quic/core/crypto/quic_random.h"
#include "net/third_party/quiche/src/quic/core/http/spdy_utils.h"
#include "net/third_party/quiche/src/quic/core/quic_server_id.h"
#include "net/third_party/quiche/src/quic/core/quic_utils.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
namespace quic {
QuicClientBase::NetworkHelper::~NetworkHelper() = default;
QuicClientBase::QuicClientBase(
const QuicServerId& server_id,
const ParsedQuicVersionVector& supported_versions,
const QuicConfig& config,
QuicConnectionHelperInterface* helper,
QuicAlarmFactory* alarm_factory,
std::unique_ptr<NetworkHelper> network_helper,
std::unique_ptr<ProofVerifier> proof_verifier,
std::unique_ptr<SessionCache> session_cache)
: server_id_(server_id),
initialized_(false),
local_port_(0),
config_(config),
crypto_config_(std::move(proof_verifier), std::move(session_cache)),
helper_(helper),
alarm_factory_(alarm_factory),
supported_versions_(supported_versions),
initial_max_packet_length_(0),
num_sent_client_hellos_(0),
connection_error_(QUIC_NO_ERROR),
connected_or_attempting_connect_(false),
network_helper_(std::move(network_helper)),
connection_debug_visitor_(nullptr),
server_connection_id_length_(kQuicDefaultConnectionIdLength),
client_connection_id_length_(0) {}
QuicClientBase::~QuicClientBase() = default;
bool QuicClientBase::Initialize() {
num_sent_client_hellos_ = 0;
connection_error_ = QUIC_NO_ERROR;
connected_or_attempting_connect_ = false;
// If an initial flow control window has not explicitly been set, then use the
// same values that Chrome uses.
const uint32_t kSessionMaxRecvWindowSize = 15 * 1024 * 1024; // 15 MB
const uint32_t kStreamMaxRecvWindowSize = 6 * 1024 * 1024; // 6 MB
if (config()->GetInitialStreamFlowControlWindowToSend() ==
kDefaultFlowControlSendWindow) {
config()->SetInitialStreamFlowControlWindowToSend(kStreamMaxRecvWindowSize);
}
if (config()->GetInitialSessionFlowControlWindowToSend() ==
kDefaultFlowControlSendWindow) {
config()->SetInitialSessionFlowControlWindowToSend(
kSessionMaxRecvWindowSize);
}
if (!network_helper_->CreateUDPSocketAndBind(server_address_,
bind_to_address_, local_port_)) {
return false;
}
initialized_ = true;
return true;
}
bool QuicClientBase::Connect() {
// Attempt multiple connects until the maximum number of client hellos have
// been sent.
int num_attempts = 0;
while (!connected() &&
num_attempts <= QuicCryptoClientStream::kMaxClientHellos) {
StartConnect();
while (EncryptionBeingEstablished()) {
WaitForEvents();
}
ParsedQuicVersion version = UnsupportedQuicVersion();
if (session() != nullptr && !CanReconnectWithDifferentVersion(&version)) {
// We've successfully created a session but we're not connected, and we
// cannot reconnect with a different version. Give up trying.
break;
}
num_attempts++;
}
if (session() == nullptr) {
QUIC_BUG << "Missing session after Connect";
return false;
}
return session()->connection()->connected();
}
void QuicClientBase::StartConnect() {
DCHECK(initialized_);
DCHECK(!connected());
QuicPacketWriter* writer = network_helper_->CreateQuicPacketWriter();
ParsedQuicVersion mutual_version = UnsupportedQuicVersion();
const bool can_reconnect_with_different_version =
CanReconnectWithDifferentVersion(&mutual_version);
if (connected_or_attempting_connect()) {
// Clear queued up data if client can not try to connect with a different
// version.
if (!can_reconnect_with_different_version) {
ClearDataToResend();
}
// Before we destroy the last session and create a new one, gather its stats
// and update the stats for the overall connection.
UpdateStats();
}
const quic::ParsedQuicVersionVector client_supported_versions =
can_reconnect_with_different_version
? ParsedQuicVersionVector{mutual_version}
: supported_versions();
session_ = CreateQuicClientSession(
client_supported_versions,
new QuicConnection(GetNextConnectionId(), server_address(), helper(),
alarm_factory(), writer,
/* owns_writer= */ false, Perspective::IS_CLIENT,
client_supported_versions));
if (connection_debug_visitor_ != nullptr) {
session()->connection()->set_debug_visitor(connection_debug_visitor_);
}
session()->connection()->set_client_connection_id(GetClientConnectionId());
if (initial_max_packet_length_ != 0) {
session()->connection()->SetMaxPacketLength(initial_max_packet_length_);
}
// Reset |writer()| after |session()| so that the old writer outlives the old
// session.
set_writer(writer);
InitializeSession();
if (can_reconnect_with_different_version) {
// This is a reconnect using server supported |mutual_version|.
session()->connection()->SetVersionNegotiated();
}
set_connected_or_attempting_connect(true);
}
void QuicClientBase::InitializeSession() {
session()->Initialize();
}
void QuicClientBase::Disconnect() {
DCHECK(initialized_);
initialized_ = false;
if (connected()) {
session()->connection()->CloseConnection(
QUIC_PEER_GOING_AWAY, "Client disconnecting",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
}
ClearDataToResend();
network_helper_->CleanUpAllUDPSockets();
}
ProofVerifier* QuicClientBase::proof_verifier() const {
return crypto_config_.proof_verifier();
}
bool QuicClientBase::EncryptionBeingEstablished() {
return !session_->IsEncryptionEstablished() &&
session_->connection()->connected();
}
bool QuicClientBase::WaitForEvents() {
if (!connected()) {
QUIC_BUG << "Cannot call WaitForEvents on non-connected client";
return false;
}
network_helper_->RunEventLoop();
DCHECK(session() != nullptr);
ParsedQuicVersion version = UnsupportedQuicVersion();
if (!connected() && CanReconnectWithDifferentVersion(&version)) {
QUIC_DLOG(INFO) << "Can reconnect with version: " << version
<< ", attempting to reconnect.";
Connect();
}
return HasActiveRequests();
}
bool QuicClientBase::MigrateSocket(const QuicIpAddress& new_host) {
return MigrateSocketWithSpecifiedPort(new_host, local_port_);
}
bool QuicClientBase::MigrateSocketWithSpecifiedPort(
const QuicIpAddress& new_host,
int port) {
if (!connected()) {
return false;
}
network_helper_->CleanUpAllUDPSockets();
set_bind_to_address(new_host);
if (!network_helper_->CreateUDPSocketAndBind(server_address_,
bind_to_address_, port)) {
return false;
}
session()->connection()->SetSelfAddress(
network_helper_->GetLatestClientAddress());
QuicPacketWriter* writer = network_helper_->CreateQuicPacketWriter();
set_writer(writer);
session()->connection()->SetQuicPacketWriter(writer, false);
return true;
}
bool QuicClientBase::ChangeEphemeralPort() {
auto current_host = network_helper_->GetLatestClientAddress().host();
return MigrateSocketWithSpecifiedPort(current_host, 0 /*any ephemeral port*/);
}
QuicSession* QuicClientBase::session() {
return session_.get();
}
const QuicSession* QuicClientBase::session() const {
return session_.get();
}
QuicClientBase::NetworkHelper* QuicClientBase::network_helper() {
return network_helper_.get();
}
const QuicClientBase::NetworkHelper* QuicClientBase::network_helper() const {
return network_helper_.get();
}
void QuicClientBase::WaitForStreamToClose(QuicStreamId id) {
if (!connected()) {
QUIC_BUG << "Cannot WaitForStreamToClose on non-connected client";
return;
}
while (connected() && !session_->IsClosedStream(id)) {
WaitForEvents();
}
}
bool QuicClientBase::WaitForOneRttKeysAvailable() {
if (!connected()) {
QUIC_BUG << "Cannot WaitForOneRttKeysAvailable on non-connected client";
return false;
}
while (connected() && !session_->OneRttKeysAvailable()) {
WaitForEvents();
}
// If the handshake fails due to a timeout, the connection will be closed.
QUIC_LOG_IF(ERROR, !connected()) << "Handshake with server failed.";
return connected();
}
bool QuicClientBase::WaitForHandshakeConfirmed() {
if (!session_->connection()->version().HasHandshakeDone()) {
return WaitForOneRttKeysAvailable();
}
while (connected() && session_->GetHandshakeState() < HANDSHAKE_CONFIRMED) {
WaitForEvents();
}
// If the handshake fails due to a timeout, the connection will be closed.
QUIC_LOG_IF(ERROR, !connected()) << "Handshake with server failed.";
return connected();
}
bool QuicClientBase::connected() const {
return session_.get() && session_->connection() &&
session_->connection()->connected();
}
bool QuicClientBase::goaway_received() const {
return session_ != nullptr && session_->goaway_received();
}
int QuicClientBase::GetNumSentClientHellos() {
// If we are not actively attempting to connect, the session object
// corresponds to the previous connection and should not be used.
const int current_session_hellos = !connected_or_attempting_connect_
? 0
: GetNumSentClientHellosFromSession();
return num_sent_client_hellos_ + current_session_hellos;
}
void QuicClientBase::UpdateStats() {
num_sent_client_hellos_ += GetNumSentClientHellosFromSession();
}
int QuicClientBase::GetNumReceivedServerConfigUpdates() {
// If we are not actively attempting to connect, the session object
// corresponds to the previous connection and should not be used.
return !connected_or_attempting_connect_
? 0
: GetNumReceivedServerConfigUpdatesFromSession();
}
QuicErrorCode QuicClientBase::connection_error() const {
// Return the high-level error if there was one. Otherwise, return the
// connection error from the last session.
if (connection_error_ != QUIC_NO_ERROR) {
return connection_error_;
}
if (session_ == nullptr) {
return QUIC_NO_ERROR;
}
return session_->error();
}
QuicConnectionId QuicClientBase::GetNextConnectionId() {
return GenerateNewConnectionId();
}
QuicConnectionId QuicClientBase::GenerateNewConnectionId() {
return QuicUtils::CreateRandomConnectionId(server_connection_id_length_);
}
QuicConnectionId QuicClientBase::GetClientConnectionId() {
return QuicUtils::CreateRandomConnectionId(client_connection_id_length_);
}
bool QuicClientBase::CanReconnectWithDifferentVersion(
ParsedQuicVersion* version) const {
if (session_ == nullptr || session_->connection() == nullptr ||
session_->error() != QUIC_INVALID_VERSION ||
session_->connection()->server_supported_versions().empty()) {
return false;
}
for (const auto& client_version : supported_versions_) {
if (QuicContainsValue(session_->connection()->server_supported_versions(),
client_version)) {
*version = client_version;
return true;
}
}
return false;
}
} // namespace quic
<|endoftext|>
|
<commit_before>// Copyright 2021 Amazon.com, Inc. or its affiliates. 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 <rcl/error_handling.h>
#include <rcl/event.h>
#include <rcl/types.h>
#include <rcpputils/scope_exit.hpp>
#include <rmw/incompatible_qos_events_statuses.h>
#include <memory>
#include <utility>
#include "rclpy_common/common.h"
#include "rclpy_common/handle.h"
#include "rclpy_common/exceptions.hpp"
#include "qos_events.hpp"
namespace rclpy
{
namespace
{
#define PYMODULE_NAME "rclpy.qos_event"
typedef union qos_event_callback_data {
// Subscription events
rmw_requested_deadline_missed_status_t requested_deadline_missed;
rmw_liveliness_changed_status_t liveliness_changed;
rmw_message_lost_status_t message_lost;
rmw_requested_qos_incompatible_event_status_t requested_incompatible_qos;
// Publisher events
rmw_offered_deadline_missed_status_t offered_deadline_missed;
rmw_liveliness_lost_status_t liveliness_lost;
rmw_offered_qos_incompatible_event_status_t offered_incompatible_qos;
} qos_event_callback_data_t;
typedef py::object qos_event_data_filler_function (const qos_event_callback_data_t *);
template<typename T>
using unique_cstruct_ptr = std::unique_ptr<T, void (*)(T *)>;
unique_cstruct_ptr<rcl_event_t>
create_zero_initialized_event()
{
unique_cstruct_ptr<rcl_event_t> event(
static_cast<rcl_event_t *>(PyMem_Malloc(sizeof(rcl_event_t))),
[](rcl_event_t * event) {
if (!event) {
PyErr_Clear();
int stack_level = 1;
PyErr_WarnFormat(
PyExc_RuntimeWarning, stack_level,
"no rcl_event_t to delete");
}
rcl_ret_t ret = rcl_event_fini(event);
if (RCL_RET_OK != ret) {
int stack_level = 1;
PyErr_WarnFormat(
PyExc_RuntimeWarning, stack_level,
"failed to fini event: %s",
rcl_get_error_string().str);
rcl_reset_error();
}
PyMem_Free(event);
});
if (!event) {
throw std::bad_alloc();
}
*event = rcl_get_zero_initialized_event();
return event;
}
py::object
_requested_deadline_missed_to_py_object(const qos_event_callback_data_t * data)
{
py::module qos_events = py::module::import(PYMODULE_NAME);
py::object pyclass = qos_events.attr("QoSRequestedDeadlineMissedInfo");
return pyclass(
data->requested_deadline_missed.total_count,
data->requested_deadline_missed.total_count_change);
}
py::object
_liveliness_changed_to_py_object(const qos_event_callback_data_t * data)
{
py::module qos_events = py::module::import(PYMODULE_NAME);
py::object pyclass = qos_events.attr("QoSLivelinessChangedInfo");
return pyclass(
data->liveliness_changed.alive_count,
data->liveliness_changed.not_alive_count,
data->liveliness_changed.alive_count_change,
data->liveliness_changed.not_alive_count_change);
}
py::object
_message_lost_to_py_object(const qos_event_callback_data_t * data)
{
py::module qos_events = py::module::import(PYMODULE_NAME);
py::object pyclass = qos_events.attr("QoSMessageLostInfo");
return pyclass(
data->message_lost.total_count,
data->message_lost.total_count_change);
}
py::object
_requested_incompatible_qos_to_py_object(const qos_event_callback_data_t * data)
{
py::module qos_events = py::module::import(PYMODULE_NAME);
py::object pyclass = qos_events.attr("QoSRequestedIncompatibleQoSInfo");
return pyclass(
data->requested_incompatible_qos.total_count,
data->requested_incompatible_qos.total_count_change,
// enum does not specify underlying data type, need intermediate cast
static_cast<int>(data->requested_incompatible_qos.last_policy_kind));
}
py::object
_offered_deadline_missed_to_py_object(const qos_event_callback_data_t * data)
{
py::module qos_events = py::module::import(PYMODULE_NAME);
py::object pyclass = qos_events.attr("QoSOfferedDeadlineMissedInfo");
return pyclass(
data->offered_deadline_missed.total_count,
data->offered_deadline_missed.total_count_change);
}
py::object
_liveliness_lost_to_py_object(const qos_event_callback_data_t * data)
{
py::module qos_events = py::module::import(PYMODULE_NAME);
py::object pyclass = qos_events.attr("QoSLivelinessLostInfo");
return pyclass(
data->liveliness_lost.total_count,
data->liveliness_lost.total_count_change);
}
py::object
_offered_incompatible_qos_to_py_object(const qos_event_callback_data_t * data)
{
py::module qos_events = py::module::import(PYMODULE_NAME);
py::object pyclass = qos_events.attr("QoSOfferedIncompatibleQoSInfo");
return pyclass(
data->offered_incompatible_qos.total_count,
data->offered_incompatible_qos.total_count_change,
// enum does not specify underlying data type, need intermediate cast
static_cast<int>(data->offered_incompatible_qos.last_policy_kind));
}
qos_event_data_filler_function *
qos_event_data_filler_function_for(py::capsule pyparent, py::object pyevent_type)
{
if (strcmp(pyparent.name(), "rclpy_subscription_t") == 0) {
switch (pyevent_type.cast<rcl_subscription_event_type_t>()) {
case RCL_SUBSCRIPTION_REQUESTED_DEADLINE_MISSED:
return &_requested_deadline_missed_to_py_object;
case RCL_SUBSCRIPTION_LIVELINESS_CHANGED:
return &_liveliness_changed_to_py_object;
case RCL_SUBSCRIPTION_MESSAGE_LOST:
return &_message_lost_to_py_object;
case RCL_SUBSCRIPTION_REQUESTED_INCOMPATIBLE_QOS:
return &_requested_incompatible_qos_to_py_object;
default:
throw py::value_error("event type for subscriptions not understood");
// although this suggests a misalignment between C and Python interfaces
}
}
if (strcmp(pyparent.name(), "rclpy_publisher_t") == 0) {
switch (pyevent_type.cast<rcl_publisher_event_type_t>()) {
case RCL_PUBLISHER_OFFERED_DEADLINE_MISSED:
return &_offered_deadline_missed_to_py_object;
case RCL_PUBLISHER_LIVELINESS_LOST:
return &_liveliness_lost_to_py_object;
case RCL_PUBLISHER_OFFERED_INCOMPATIBLE_QOS:
return &_offered_incompatible_qos_to_py_object;
default:
throw py::value_error("event type for publishers not understood");
// although this suggests a misalignment between C and Python interfaces
}
}
throw py::type_error("event parent is neither a publisher nor a subscription");
}
py::capsule
event_wrap_in_capsule(unique_cstruct_ptr<rcl_event_t> event, py::capsule pyparent)
{
rclpy_handle_destructor_t destructor =
reinterpret_cast<rclpy_handle_destructor_t>(event.get_deleter());
PyObject * pyevent_c =
rclpy_create_handle_capsule(event.get(), "rcl_event_t", destructor);
if (!pyevent_c) {
throw py::error_already_set();
}
auto pyevent = py::reinterpret_steal<py::capsule>(pyevent_c);
event.release(); // pyevent now owns rcl_event_t
rclpy_handle_t * event_handle = static_cast<rclpy_handle_t *>(pyevent);
rclpy_handle_t * parent_handle = static_cast<rclpy_handle_t *>(pyparent);
_rclpy_handle_add_dependency(event_handle, parent_handle);
if (PyErr_Occurred()) {
throw py::error_already_set();
}
return pyevent;
}
py::object
publisher_event_create(rcl_publisher_event_type_t event_type, py::capsule pypublisher)
{
auto wrapper = static_cast<rclpy_publisher_t *>(
rclpy_handle_get_pointer_from_capsule(pypublisher.ptr(), "rclpy_publisher_t"));
if (!wrapper) {
throw py::error_already_set();
}
unique_cstruct_ptr<rcl_event_t> event = create_zero_initialized_event();
rcl_ret_t ret = rcl_publisher_event_init(
event.get(), &(wrapper->publisher), event_type);
if (RCL_RET_OK != ret) {
if (RCL_RET_BAD_ALLOC == ret) {
rcl_reset_error();
throw std::bad_alloc();
}
if (RCL_RET_UNSUPPORTED == ret) {
throw UnsupportedEventTypeError("publisher event is unsupported");
}
throw RCLError("failed to create publisher event");
}
return event_wrap_in_capsule(std::move(event), pypublisher);
}
py::object
subscription_event_create(rcl_subscription_event_type_t event_type, py::capsule pysubscription)
{
auto wrapper = static_cast<rclpy_subscription_t *>(
rclpy_handle_get_pointer_from_capsule(pysubscription.ptr(), "rclpy_subscription_t"));
if (!wrapper) {
throw py::error_already_set();
}
unique_cstruct_ptr<rcl_event_t> event = create_zero_initialized_event();
rcl_ret_t ret = rcl_subscription_event_init(
event.get(), &(wrapper->subscription), event_type);
if (RCL_RET_OK != ret) {
if (RCL_RET_BAD_ALLOC == ret) {
rcl_reset_error();
throw std::bad_alloc();
}
if (RCL_RET_UNSUPPORTED == ret) {
throw UnsupportedEventTypeError("subscription event is unsupported");
}
throw RCLError("failed to create subscription event");
}
return event_wrap_in_capsule(std::move(event), pysubscription);
}
} // namespace
py::object
create_event(py::object pyevent_type, py::capsule pyparent)
{
if (strcmp(pyparent.name(), "rclpy_subscription_t") == 0) {
auto event_type = pyevent_type.cast<rcl_subscription_event_type_t>();
return subscription_event_create(event_type, pyparent);
}
if (strcmp(pyparent.name(), "rclpy_publisher_t") == 0) {
auto event_type = pyevent_type.cast<rcl_publisher_event_type_t>();
return publisher_event_create(event_type, pyparent);
}
throw py::type_error("event parent is neither a publisher nor a subscription");
}
py::object
take_event(py::capsule pyevent, py::capsule pyparent, py::object pyevent_type)
{
auto event = static_cast<rcl_event_t *>(
rclpy_handle_get_pointer_from_capsule(pyevent.ptr(), "rcl_event_t"));
if (!event) {
throw py::error_already_set();
}
qos_event_data_filler_function * event_filler =
qos_event_data_filler_function_for(pyparent, pyevent_type);
qos_event_callback_data_t event_data;
rcl_ret_t ret = rcl_take_event(event, &event_data);
if (RCL_RET_OK != ret) {
if (RCL_RET_BAD_ALLOC == ret) {
rcl_reset_error();
throw std::bad_alloc();
}
if (RCL_RET_EVENT_TAKE_FAILED == ret) {
return py::none();
}
throw RCLError("failed to take event");
}
return event_filler(&event_data);
}
} // namespace rclpy
<commit_msg>Include pybind11 first to fix windows debug warning (#731)<commit_after>// Copyright 2021 Amazon.com, Inc. or its affiliates. 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 pybind11 before rclpy_common/handle.h includes Python.h
#include <pybind11/pybind11.h>
#include <rcl/error_handling.h>
#include <rcl/event.h>
#include <rcl/types.h>
#include <rcpputils/scope_exit.hpp>
#include <rmw/incompatible_qos_events_statuses.h>
#include <memory>
#include <utility>
#include "rclpy_common/common.h"
#include "rclpy_common/handle.h"
#include "rclpy_common/exceptions.hpp"
#include "qos_events.hpp"
namespace rclpy
{
namespace
{
#define PYMODULE_NAME "rclpy.qos_event"
typedef union qos_event_callback_data {
// Subscription events
rmw_requested_deadline_missed_status_t requested_deadline_missed;
rmw_liveliness_changed_status_t liveliness_changed;
rmw_message_lost_status_t message_lost;
rmw_requested_qos_incompatible_event_status_t requested_incompatible_qos;
// Publisher events
rmw_offered_deadline_missed_status_t offered_deadline_missed;
rmw_liveliness_lost_status_t liveliness_lost;
rmw_offered_qos_incompatible_event_status_t offered_incompatible_qos;
} qos_event_callback_data_t;
typedef py::object qos_event_data_filler_function (const qos_event_callback_data_t *);
template<typename T>
using unique_cstruct_ptr = std::unique_ptr<T, void (*)(T *)>;
unique_cstruct_ptr<rcl_event_t>
create_zero_initialized_event()
{
unique_cstruct_ptr<rcl_event_t> event(
static_cast<rcl_event_t *>(PyMem_Malloc(sizeof(rcl_event_t))),
[](rcl_event_t * event) {
if (!event) {
PyErr_Clear();
int stack_level = 1;
PyErr_WarnFormat(
PyExc_RuntimeWarning, stack_level,
"no rcl_event_t to delete");
}
rcl_ret_t ret = rcl_event_fini(event);
if (RCL_RET_OK != ret) {
int stack_level = 1;
PyErr_WarnFormat(
PyExc_RuntimeWarning, stack_level,
"failed to fini event: %s",
rcl_get_error_string().str);
rcl_reset_error();
}
PyMem_Free(event);
});
if (!event) {
throw std::bad_alloc();
}
*event = rcl_get_zero_initialized_event();
return event;
}
py::object
_requested_deadline_missed_to_py_object(const qos_event_callback_data_t * data)
{
py::module qos_events = py::module::import(PYMODULE_NAME);
py::object pyclass = qos_events.attr("QoSRequestedDeadlineMissedInfo");
return pyclass(
data->requested_deadline_missed.total_count,
data->requested_deadline_missed.total_count_change);
}
py::object
_liveliness_changed_to_py_object(const qos_event_callback_data_t * data)
{
py::module qos_events = py::module::import(PYMODULE_NAME);
py::object pyclass = qos_events.attr("QoSLivelinessChangedInfo");
return pyclass(
data->liveliness_changed.alive_count,
data->liveliness_changed.not_alive_count,
data->liveliness_changed.alive_count_change,
data->liveliness_changed.not_alive_count_change);
}
py::object
_message_lost_to_py_object(const qos_event_callback_data_t * data)
{
py::module qos_events = py::module::import(PYMODULE_NAME);
py::object pyclass = qos_events.attr("QoSMessageLostInfo");
return pyclass(
data->message_lost.total_count,
data->message_lost.total_count_change);
}
py::object
_requested_incompatible_qos_to_py_object(const qos_event_callback_data_t * data)
{
py::module qos_events = py::module::import(PYMODULE_NAME);
py::object pyclass = qos_events.attr("QoSRequestedIncompatibleQoSInfo");
return pyclass(
data->requested_incompatible_qos.total_count,
data->requested_incompatible_qos.total_count_change,
// enum does not specify underlying data type, need intermediate cast
static_cast<int>(data->requested_incompatible_qos.last_policy_kind));
}
py::object
_offered_deadline_missed_to_py_object(const qos_event_callback_data_t * data)
{
py::module qos_events = py::module::import(PYMODULE_NAME);
py::object pyclass = qos_events.attr("QoSOfferedDeadlineMissedInfo");
return pyclass(
data->offered_deadline_missed.total_count,
data->offered_deadline_missed.total_count_change);
}
py::object
_liveliness_lost_to_py_object(const qos_event_callback_data_t * data)
{
py::module qos_events = py::module::import(PYMODULE_NAME);
py::object pyclass = qos_events.attr("QoSLivelinessLostInfo");
return pyclass(
data->liveliness_lost.total_count,
data->liveliness_lost.total_count_change);
}
py::object
_offered_incompatible_qos_to_py_object(const qos_event_callback_data_t * data)
{
py::module qos_events = py::module::import(PYMODULE_NAME);
py::object pyclass = qos_events.attr("QoSOfferedIncompatibleQoSInfo");
return pyclass(
data->offered_incompatible_qos.total_count,
data->offered_incompatible_qos.total_count_change,
// enum does not specify underlying data type, need intermediate cast
static_cast<int>(data->offered_incompatible_qos.last_policy_kind));
}
qos_event_data_filler_function *
qos_event_data_filler_function_for(py::capsule pyparent, py::object pyevent_type)
{
if (strcmp(pyparent.name(), "rclpy_subscription_t") == 0) {
switch (pyevent_type.cast<rcl_subscription_event_type_t>()) {
case RCL_SUBSCRIPTION_REQUESTED_DEADLINE_MISSED:
return &_requested_deadline_missed_to_py_object;
case RCL_SUBSCRIPTION_LIVELINESS_CHANGED:
return &_liveliness_changed_to_py_object;
case RCL_SUBSCRIPTION_MESSAGE_LOST:
return &_message_lost_to_py_object;
case RCL_SUBSCRIPTION_REQUESTED_INCOMPATIBLE_QOS:
return &_requested_incompatible_qos_to_py_object;
default:
throw py::value_error("event type for subscriptions not understood");
// although this suggests a misalignment between C and Python interfaces
}
}
if (strcmp(pyparent.name(), "rclpy_publisher_t") == 0) {
switch (pyevent_type.cast<rcl_publisher_event_type_t>()) {
case RCL_PUBLISHER_OFFERED_DEADLINE_MISSED:
return &_offered_deadline_missed_to_py_object;
case RCL_PUBLISHER_LIVELINESS_LOST:
return &_liveliness_lost_to_py_object;
case RCL_PUBLISHER_OFFERED_INCOMPATIBLE_QOS:
return &_offered_incompatible_qos_to_py_object;
default:
throw py::value_error("event type for publishers not understood");
// although this suggests a misalignment between C and Python interfaces
}
}
throw py::type_error("event parent is neither a publisher nor a subscription");
}
py::capsule
event_wrap_in_capsule(unique_cstruct_ptr<rcl_event_t> event, py::capsule pyparent)
{
rclpy_handle_destructor_t destructor =
reinterpret_cast<rclpy_handle_destructor_t>(event.get_deleter());
PyObject * pyevent_c =
rclpy_create_handle_capsule(event.get(), "rcl_event_t", destructor);
if (!pyevent_c) {
throw py::error_already_set();
}
auto pyevent = py::reinterpret_steal<py::capsule>(pyevent_c);
event.release(); // pyevent now owns rcl_event_t
rclpy_handle_t * event_handle = static_cast<rclpy_handle_t *>(pyevent);
rclpy_handle_t * parent_handle = static_cast<rclpy_handle_t *>(pyparent);
_rclpy_handle_add_dependency(event_handle, parent_handle);
if (PyErr_Occurred()) {
throw py::error_already_set();
}
return pyevent;
}
py::object
publisher_event_create(rcl_publisher_event_type_t event_type, py::capsule pypublisher)
{
auto wrapper = static_cast<rclpy_publisher_t *>(
rclpy_handle_get_pointer_from_capsule(pypublisher.ptr(), "rclpy_publisher_t"));
if (!wrapper) {
throw py::error_already_set();
}
unique_cstruct_ptr<rcl_event_t> event = create_zero_initialized_event();
rcl_ret_t ret = rcl_publisher_event_init(
event.get(), &(wrapper->publisher), event_type);
if (RCL_RET_OK != ret) {
if (RCL_RET_BAD_ALLOC == ret) {
rcl_reset_error();
throw std::bad_alloc();
}
if (RCL_RET_UNSUPPORTED == ret) {
throw UnsupportedEventTypeError("publisher event is unsupported");
}
throw RCLError("failed to create publisher event");
}
return event_wrap_in_capsule(std::move(event), pypublisher);
}
py::object
subscription_event_create(rcl_subscription_event_type_t event_type, py::capsule pysubscription)
{
auto wrapper = static_cast<rclpy_subscription_t *>(
rclpy_handle_get_pointer_from_capsule(pysubscription.ptr(), "rclpy_subscription_t"));
if (!wrapper) {
throw py::error_already_set();
}
unique_cstruct_ptr<rcl_event_t> event = create_zero_initialized_event();
rcl_ret_t ret = rcl_subscription_event_init(
event.get(), &(wrapper->subscription), event_type);
if (RCL_RET_OK != ret) {
if (RCL_RET_BAD_ALLOC == ret) {
rcl_reset_error();
throw std::bad_alloc();
}
if (RCL_RET_UNSUPPORTED == ret) {
throw UnsupportedEventTypeError("subscription event is unsupported");
}
throw RCLError("failed to create subscription event");
}
return event_wrap_in_capsule(std::move(event), pysubscription);
}
} // namespace
py::object
create_event(py::object pyevent_type, py::capsule pyparent)
{
if (strcmp(pyparent.name(), "rclpy_subscription_t") == 0) {
auto event_type = pyevent_type.cast<rcl_subscription_event_type_t>();
return subscription_event_create(event_type, pyparent);
}
if (strcmp(pyparent.name(), "rclpy_publisher_t") == 0) {
auto event_type = pyevent_type.cast<rcl_publisher_event_type_t>();
return publisher_event_create(event_type, pyparent);
}
throw py::type_error("event parent is neither a publisher nor a subscription");
}
py::object
take_event(py::capsule pyevent, py::capsule pyparent, py::object pyevent_type)
{
auto event = static_cast<rcl_event_t *>(
rclpy_handle_get_pointer_from_capsule(pyevent.ptr(), "rcl_event_t"));
if (!event) {
throw py::error_already_set();
}
qos_event_data_filler_function * event_filler =
qos_event_data_filler_function_for(pyparent, pyevent_type);
qos_event_callback_data_t event_data;
rcl_ret_t ret = rcl_take_event(event, &event_data);
if (RCL_RET_OK != ret) {
if (RCL_RET_BAD_ALLOC == ret) {
rcl_reset_error();
throw std::bad_alloc();
}
if (RCL_RET_EVENT_TAKE_FAILED == ret) {
return py::none();
}
throw RCLError("failed to take event");
}
return event_filler(&event_data);
}
} // namespace rclpy
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "filetime.h"
#include <QtCore/qstring.h>
#ifdef Q_OS_WIN
#include <QtCore/qt_windows.h>
#else
#include <QtCore/qdatetime.h>
#endif
namespace qbs {
namespace Internal {
#ifdef Q_OS_WIN
template<bool> struct CompileTimeAssert;
template<> struct CompileTimeAssert<true> {};
#endif
#ifdef APPLE_CUSTOM_CLOCK_GETTIME
#include <sys/time.h>
// clk_id isn't used, only the CLOCK_REALTIME case is implemented.
int clock_gettime(int /*clk_id*/, struct timespec *t)
{
struct timeval tv;
// Resolution of gettimeofday is 1000nsecs = 1 microsecond.
int ret = gettimeofday(&tv, NULL);
t->tv_sec = tv.tv_sec;
t->tv_nsec = tv.tv_usec * 1000;
return ret;
}
#endif
FileTime::FileTime()
{
#ifdef Q_OS_WIN
static CompileTimeAssert<sizeof(FileTime::InternalType) == sizeof(FILETIME)> internal_type_has_wrong_size;
Q_UNUSED(internal_type_has_wrong_size);
m_fileTime = 0;
#elif HAS_CLOCK_GETTIME
m_fileTime = {0, 0};
#else
m_fileTime = 0;
#endif
}
FileTime::FileTime(const FileTime::InternalType &ft) : m_fileTime(ft)
{
#if HAS_CLOCK_GETTIME
if (m_fileTime.tv_sec == 0)
m_fileTime.tv_nsec = 0; // stat() sets only the first member to 0 for non-existing files.
#endif
}
int FileTime::compare(const FileTime &other) const
{
#ifdef Q_OS_WIN
const FILETIME *const t1 = reinterpret_cast<const FILETIME *>(&m_fileTime);
const FILETIME *const t2 = reinterpret_cast<const FILETIME *>(&other.m_fileTime);
return CompareFileTime(t1, t2);
#elif HAS_CLOCK_GETTIME
if (m_fileTime.tv_sec < other.m_fileTime.tv_sec)
return -1;
if (m_fileTime.tv_sec > other.m_fileTime.tv_sec)
return 1;
if (m_fileTime.tv_nsec < other.m_fileTime.tv_nsec)
return -1;
if (m_fileTime.tv_nsec > other.m_fileTime.tv_nsec)
return 1;
return 0;
#else
if (m_fileTime < other.m_fileTime)
return -1;
if (m_fileTime > other.m_fileTime)
return 1;
return 0;
#endif
}
void FileTime::clear()
{
#if HAS_CLOCK_GETTIME
m_fileTime = { 0, 0 };
#else
m_fileTime = 0;
#endif
}
bool FileTime::isValid() const
{
return *this != FileTime();
}
FileTime FileTime::currentTime()
{
#ifdef Q_OS_WIN
FileTime result;
SYSTEMTIME st;
GetSystemTime(&st);
FILETIME *const ft = reinterpret_cast<FILETIME *>(&result.m_fileTime);
SystemTimeToFileTime(&st, ft);
return result;
#elif defined APPLE_CUSTOM_CLOCK_GETTIME
InternalType t;
// Explicitly use our custom version, so that we don't get an additional unresolved symbol on a
// system that actually provides one, but isn't used due to the minimium deployment target
// being lower.
qbs::Internal::clock_gettime(CLOCK_REALTIME, &t);
return t;
#elif HAS_CLOCK_GETTIME
InternalType t;
clock_gettime(CLOCK_REALTIME, &t);
return t;
#else
return time(nullptr);
#endif
}
FileTime FileTime::oldestTime()
{
#ifdef Q_OS_WIN
SYSTEMTIME st = {
1601,
1,
5,
2,
0,
0,
0,
0
};
FileTime result;
FILETIME *const ft = reinterpret_cast<FILETIME *>(&result.m_fileTime);
SystemTimeToFileTime(&st, ft);
return result;
#elif HAS_CLOCK_GETTIME
return FileTime({1, 0});
#else
return 1;
#endif
}
double FileTime::asDouble() const
{
#if HAS_CLOCK_GETTIME
return static_cast<double>(m_fileTime.tv_sec);
#else
return static_cast<double>(m_fileTime);
#endif
}
QString FileTime::toString() const
{
#ifdef Q_OS_WIN
const FILETIME *const ft = reinterpret_cast<const FILETIME *>(&m_fileTime);
SYSTEMTIME stUTC, stLocal;
FileTimeToSystemTime(ft, &stUTC);
SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
const QString result = QString::fromLatin1("%1.%2.%3 %4:%5:%6")
.arg(stLocal.wDay, 2, 10, QLatin1Char('0')).arg(stLocal.wMonth, 2, 10, QLatin1Char('0')).arg(stLocal.wYear)
.arg(stLocal.wHour, 2, 10, QLatin1Char('0')).arg(stLocal.wMinute, 2, 10, QLatin1Char('0')).arg(stLocal.wSecond, 2, 10, QLatin1Char('0'));
return result;
#else
QDateTime dt;
#if HAS_CLOCK_GETTIME
dt.setMSecsSinceEpoch(m_fileTime.tv_sec * 1000 + m_fileTime.tv_nsec / 1000000);
#else
dt.setTime_t(m_fileTime);
#endif
return dt.toString(Qt::ISODateWithMs);
#endif
}
} // namespace Internal
} // namespace qbs
<commit_msg>Fix CLOCK_REALTIME not being available on macOS SDK < 10.11<commit_after>/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "filetime.h"
#include <QtCore/qstring.h>
#ifdef Q_OS_WIN
#include <QtCore/qt_windows.h>
#else
#include <QtCore/qdatetime.h>
#endif
namespace qbs {
namespace Internal {
#ifdef Q_OS_WIN
template<bool> struct CompileTimeAssert;
template<> struct CompileTimeAssert<true> {};
#endif
#ifdef APPLE_CUSTOM_CLOCK_GETTIME
#include <sys/time.h>
#ifndef CLOCK_REALTIME
#define CLOCK_REALTIME 0
#endif
// clk_id isn't used, only the CLOCK_REALTIME case is implemented.
int clock_gettime(int /*clk_id*/, struct timespec *t)
{
struct timeval tv;
// Resolution of gettimeofday is 1000nsecs = 1 microsecond.
int ret = gettimeofday(&tv, NULL);
t->tv_sec = tv.tv_sec;
t->tv_nsec = tv.tv_usec * 1000;
return ret;
}
#endif
FileTime::FileTime()
{
#ifdef Q_OS_WIN
static CompileTimeAssert<sizeof(FileTime::InternalType) == sizeof(FILETIME)> internal_type_has_wrong_size;
Q_UNUSED(internal_type_has_wrong_size);
m_fileTime = 0;
#elif HAS_CLOCK_GETTIME
m_fileTime = {0, 0};
#else
m_fileTime = 0;
#endif
}
FileTime::FileTime(const FileTime::InternalType &ft) : m_fileTime(ft)
{
#if HAS_CLOCK_GETTIME
if (m_fileTime.tv_sec == 0)
m_fileTime.tv_nsec = 0; // stat() sets only the first member to 0 for non-existing files.
#endif
}
int FileTime::compare(const FileTime &other) const
{
#ifdef Q_OS_WIN
const FILETIME *const t1 = reinterpret_cast<const FILETIME *>(&m_fileTime);
const FILETIME *const t2 = reinterpret_cast<const FILETIME *>(&other.m_fileTime);
return CompareFileTime(t1, t2);
#elif HAS_CLOCK_GETTIME
if (m_fileTime.tv_sec < other.m_fileTime.tv_sec)
return -1;
if (m_fileTime.tv_sec > other.m_fileTime.tv_sec)
return 1;
if (m_fileTime.tv_nsec < other.m_fileTime.tv_nsec)
return -1;
if (m_fileTime.tv_nsec > other.m_fileTime.tv_nsec)
return 1;
return 0;
#else
if (m_fileTime < other.m_fileTime)
return -1;
if (m_fileTime > other.m_fileTime)
return 1;
return 0;
#endif
}
void FileTime::clear()
{
#if HAS_CLOCK_GETTIME
m_fileTime = { 0, 0 };
#else
m_fileTime = 0;
#endif
}
bool FileTime::isValid() const
{
return *this != FileTime();
}
FileTime FileTime::currentTime()
{
#ifdef Q_OS_WIN
FileTime result;
SYSTEMTIME st;
GetSystemTime(&st);
FILETIME *const ft = reinterpret_cast<FILETIME *>(&result.m_fileTime);
SystemTimeToFileTime(&st, ft);
return result;
#elif defined APPLE_CUSTOM_CLOCK_GETTIME
InternalType t;
// Explicitly use our custom version, so that we don't get an additional unresolved symbol on a
// system that actually provides one, but isn't used due to the minimium deployment target
// being lower.
qbs::Internal::clock_gettime(CLOCK_REALTIME, &t);
return t;
#elif HAS_CLOCK_GETTIME
InternalType t;
clock_gettime(CLOCK_REALTIME, &t);
return t;
#else
return time(nullptr);
#endif
}
FileTime FileTime::oldestTime()
{
#ifdef Q_OS_WIN
SYSTEMTIME st = {
1601,
1,
5,
2,
0,
0,
0,
0
};
FileTime result;
FILETIME *const ft = reinterpret_cast<FILETIME *>(&result.m_fileTime);
SystemTimeToFileTime(&st, ft);
return result;
#elif HAS_CLOCK_GETTIME
return FileTime({1, 0});
#else
return 1;
#endif
}
double FileTime::asDouble() const
{
#if HAS_CLOCK_GETTIME
return static_cast<double>(m_fileTime.tv_sec);
#else
return static_cast<double>(m_fileTime);
#endif
}
QString FileTime::toString() const
{
#ifdef Q_OS_WIN
const FILETIME *const ft = reinterpret_cast<const FILETIME *>(&m_fileTime);
SYSTEMTIME stUTC, stLocal;
FileTimeToSystemTime(ft, &stUTC);
SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
const QString result = QString::fromLatin1("%1.%2.%3 %4:%5:%6")
.arg(stLocal.wDay, 2, 10, QLatin1Char('0')).arg(stLocal.wMonth, 2, 10, QLatin1Char('0')).arg(stLocal.wYear)
.arg(stLocal.wHour, 2, 10, QLatin1Char('0')).arg(stLocal.wMinute, 2, 10, QLatin1Char('0')).arg(stLocal.wSecond, 2, 10, QLatin1Char('0'));
return result;
#else
QDateTime dt;
#if HAS_CLOCK_GETTIME
dt.setMSecsSinceEpoch(m_fileTime.tv_sec * 1000 + m_fileTime.tv_nsec / 1000000);
#else
dt.setTime_t(m_fileTime);
#endif
return dt.toString(Qt::ISODateWithMs);
#endif
}
} // namespace Internal
} // namespace qbs
<|endoftext|>
|
<commit_before>/* $Id$ */
/*
* Copyright (c) 2010 SURFnet bv
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*****************************************************************************
Directory.cpp
Helper functions for accessing directories.
*****************************************************************************/
#include "config.h"
#include "Directory.h"
#include "OSPathSep.h"
#include "log.h"
#include <string>
#include <vector>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
// Constructor
Directory::Directory(std::string path)
{
this->path = path;
valid = refresh();
}
// Check if the directory is valid
bool Directory::isValid()
{
return valid;
}
// Return a list of all files in a directory
std::vector<std::string> Directory::getFiles()
{
return files;
}
// Return a list of all subdirectories in a directory
std::vector<std::string> Directory::getSubDirs()
{
return subDirs;
}
// Refresh the directory listing
bool Directory::refresh()
{
// Reset the state
valid = false;
subDirs.clear();
files.clear();
// Enumerate the directory
DIR* dir = opendir(path.c_str());
if (dir == NULL)
{
DEBUG_MSG("Failed to open directory %s", path.c_str());
return false;
}
// Enumerate the directory
struct dirent* entry = NULL;
while ((entry = readdir(dir)) != NULL)
{
// Check if this is the . or .. entry
if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
{
continue;
}
// Convert the name of the entry to a C++ string
std::string name(entry->d_name);
#if defined(_DIRENT_HAVE_D_TYPE) && defined(_BSD_SOURCE)
// Determine the type of the entry
switch(entry->d_type)
{
case DT_DIR:
// This is a directory
subDirs.push_back(name);
break;
case DT_REG:
// This is a regular file
files.push_back(name);
break;
default:
DEBUG_MSG("File not used %s", name.c_str());
break;
}
#else
// The entry type has to be determined using lstat
struct stat entryStatus;
std::string fullPath = path + OS_PATHSEP + name;
if (!lstat(fullPath.c_str(), &entryStatus))
{
if (S_ISDIR(entryStatus->st_mode))
{
subDirs.push_back(name);
}
else if (S_ISREG(entryStatus->st_mode))
{
files.push_back(name);
}
else
{
DEBUG_MSG("File not used %s", name.c_str());
}
}
#endif
}
// Close the directory
closedir(dir);
valid = true;
return true;
}
// Create a new subdirectory
bool Directory::mkdir(std::string name)
{
std::string fullPath = path + OS_PATHSEP + name;
return (!::mkdir(fullPath.c_str(), S_IFDIR | S_IRWXU) && refresh());
}
// Delete a file or subdirectory in the directory
bool Directory::remove(std::string name)
{
std::string fullPath = path + OS_PATHSEP + name;
return (!::remove(fullPath.c_str()) && refresh());
}
<commit_msg>Non-pointer<commit_after>/* $Id$ */
/*
* Copyright (c) 2010 SURFnet bv
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*****************************************************************************
Directory.cpp
Helper functions for accessing directories.
*****************************************************************************/
#include "config.h"
#include "Directory.h"
#include "OSPathSep.h"
#include "log.h"
#include <string>
#include <vector>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
// Constructor
Directory::Directory(std::string path)
{
this->path = path;
valid = refresh();
}
// Check if the directory is valid
bool Directory::isValid()
{
return valid;
}
// Return a list of all files in a directory
std::vector<std::string> Directory::getFiles()
{
return files;
}
// Return a list of all subdirectories in a directory
std::vector<std::string> Directory::getSubDirs()
{
return subDirs;
}
// Refresh the directory listing
bool Directory::refresh()
{
// Reset the state
valid = false;
subDirs.clear();
files.clear();
// Enumerate the directory
DIR* dir = opendir(path.c_str());
if (dir == NULL)
{
DEBUG_MSG("Failed to open directory %s", path.c_str());
return false;
}
// Enumerate the directory
struct dirent* entry = NULL;
while ((entry = readdir(dir)) != NULL)
{
// Check if this is the . or .. entry
if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
{
continue;
}
// Convert the name of the entry to a C++ string
std::string name(entry->d_name);
#if defined(_DIRENT_HAVE_D_TYPE) && defined(_BSD_SOURCE)
// Determine the type of the entry
switch(entry->d_type)
{
case DT_DIR:
// This is a directory
subDirs.push_back(name);
break;
case DT_REG:
// This is a regular file
files.push_back(name);
break;
default:
DEBUG_MSG("File not used %s", name.c_str());
break;
}
#else
// The entry type has to be determined using lstat
struct stat entryStatus;
std::string fullPath = path + OS_PATHSEP + name;
if (!lstat(fullPath.c_str(), &entryStatus))
{
if (S_ISDIR(entryStatus.st_mode))
{
subDirs.push_back(name);
}
else if (S_ISREG(entryStatus.st_mode))
{
files.push_back(name);
}
else
{
DEBUG_MSG("File not used %s", name.c_str());
}
}
#endif
}
// Close the directory
closedir(dir);
valid = true;
return true;
}
// Create a new subdirectory
bool Directory::mkdir(std::string name)
{
std::string fullPath = path + OS_PATHSEP + name;
return (!::mkdir(fullPath.c_str(), S_IFDIR | S_IRWXU) && refresh());
}
// Delete a file or subdirectory in the directory
bool Directory::remove(std::string name)
{
std::string fullPath = path + OS_PATHSEP + name;
return (!::remove(fullPath.c_str()) && refresh());
}
<|endoftext|>
|
<commit_before>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2014 Pedro Côrte-Real
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "tiff/CiffEntry.h"
#include "common/Common.h" // for uchar8, uint32, ushort16
#include "io/Buffer.h" // for Buffer
#include "io/Endianness.h" // for getU32LE, getU16LE
#include "parsers/CiffParserException.h" // for ThrowCPE
#include <cstdio> // for sprintf
#include <cstring> // for memcpy, strlen
#include <limits> // for numeric_limits
#include <string> // for string, allocator
#include <vector> // for vector
using std::numeric_limits;
using std::string;
using std::vector;
namespace rawspeed {
CiffEntry::CiffEntry(Buffer* f, uint32 value_data, uint32 offset) {
own_data = nullptr;
ushort16 p = getU16LE(f->getData(offset, 2));
tag = static_cast<CiffTag>(p & 0x3fff);
ushort16 datalocation = (p & 0xc000);
type = static_cast<CiffDataType>(p & 0x3800);
if (datalocation == 0x0000) { // Data is offset in value_data
bytesize = getU32LE(f->getData(offset + 2, 4));
data_offset = getU32LE(f->getData(offset + 6, 4));
if (data_offset >= numeric_limits<uint32>::max() - value_data)
ThrowCPE("Corrupt data offset.");
data_offset += value_data;
data = f->getData(data_offset, bytesize);
} else if (datalocation == 0x4000) { // Data is stored directly in entry
data_offset = offset + 2;
bytesize = 8; // Maximum of 8 bytes of data (the size and offset fields)
data = f->getData(data_offset, bytesize);
} else
ThrowCPE("Don't understand data location 0x%x", datalocation);
// Set the number of items using the shift
count = bytesize >> getElementShift();
}
CiffEntry::~CiffEntry() { delete[] own_data; }
uint32 __attribute__((pure)) CiffEntry::getElementShift() {
switch (type) {
case CIFF_SHORT:
return 1;
case CIFF_LONG:
case CIFF_MIX:
case CIFF_SUB1:
case CIFF_SUB2:
return 2;
case CIFF_BYTE:
case CIFF_ASCII:
default:
return 0;
}
}
uint32 __attribute__((pure)) CiffEntry::getElementSize() {
switch (type) {
case CIFF_BYTE:
case CIFF_ASCII:
return 1;
case CIFF_SHORT:
return 2;
case CIFF_LONG:
case CIFF_MIX:
case CIFF_SUB1:
case CIFF_SUB2:
return 4;
default:
return 0;
}
}
bool __attribute__((pure)) CiffEntry::isInt() {
return (type == CIFF_LONG || type == CIFF_SHORT || type == CIFF_BYTE);
}
uint32 CiffEntry::getU32(uint32 num) {
if (!isInt()) {
ThrowCPE(
"Wrong type 0x%x encountered. Expected Long, Short or Byte at 0x%x",
type, tag);
}
if (type == CIFF_BYTE)
return getByte(num);
if (type == CIFF_SHORT)
return getU16(num);
if (num*4+3 >= bytesize)
ThrowCPE("Trying to read out of bounds");
return getU32LE(data + num * 4);
}
ushort16 CiffEntry::getU16(uint32 num) {
if (type != CIFF_SHORT && type != CIFF_BYTE)
ThrowCPE("Wrong type 0x%x encountered. Expected Short at 0x%x", type, tag);
if (num*2+1 >= bytesize)
ThrowCPE("Trying to read out of bounds");
return getU16LE(data + num * 2);
}
uchar8 CiffEntry::getByte(uint32 num) {
if (type != CIFF_BYTE)
ThrowCPE("Wrong type 0x%x encountered. Expected Byte at 0x%x", type, tag);
if (num >= bytesize)
ThrowCPE("Trying to read out of bounds");
return data[num];
}
string CiffEntry::getString() {
if (type != CIFF_ASCII)
ThrowCPE("Wrong type 0x%x encountered. Expected Ascii", type);
if (count == 0)
return string("");
if (!own_data) {
own_data = new uchar8[count];
memcpy(own_data, data, count);
own_data[count-1] = 0; // Ensure string is not larger than count defines
}
return string(reinterpret_cast<const char*>(&own_data[0]));
}
vector<string> CiffEntry::getStrings() {
vector<string> strs;
if (type != CIFF_ASCII)
ThrowCPE("Wrong type 0x%x encountered. Expected Ascii", type);
if (!own_data) {
own_data = new uchar8[count];
memcpy(own_data, data, count);
own_data[count-1] = 0; // Ensure string is not larger than count defines
}
uint32 start = 0;
for (uint32 i=0; i< count; i++) {
if (own_data[i] == 0) {
strs.emplace_back(reinterpret_cast<const char*>(&own_data[start]));
start = i+1;
}
}
return strs;
}
bool __attribute__((pure)) CiffEntry::isString() {
return (type == CIFF_ASCII);
}
void CiffEntry::setData( const void *in_data, uint32 byte_count )
{
if (byte_count > bytesize)
ThrowCPE("data set larger than entry size given");
if (!own_data) {
own_data = new uchar8[bytesize];
memcpy(own_data, data, bytesize);
}
memcpy(own_data, in_data, byte_count);
}
#ifdef _MSC_VER
#pragma warning(disable: 4996) // this function or variable may be unsafe
#endif
std::string CiffEntry::getValueAsString()
{
if (type == CIFF_ASCII)
return string(reinterpret_cast<const char*>(&data[0]));
auto *temp_string = new char[4096];
if (count == 1) {
switch (type) {
case CIFF_LONG:
sprintf(temp_string, "Long: %u (0x%x)", getU32(), getU32());
break;
case CIFF_SHORT:
sprintf(temp_string, "Short: %u (0x%x)", getU32(), getU32());
break;
case CIFF_BYTE:
sprintf(temp_string, "Byte: %u (0x%x)", getU32(), getU32());
break;
default:
sprintf(temp_string, "Type: %x: ", type);
for (uint32 i = 0; i < getElementSize(); i++) {
sprintf(&temp_string[strlen(temp_string-1)], "%x", data[i]);
}
}
}
string ret(temp_string);
delete [] temp_string;
return ret;
}
} // namespace rawspeed
<commit_msg>CiffEntry::getElementShift(): remove redundant case<commit_after>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2014 Pedro Côrte-Real
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "tiff/CiffEntry.h"
#include "common/Common.h" // for uchar8, uint32, ushort16
#include "io/Buffer.h" // for Buffer
#include "io/Endianness.h" // for getU32LE, getU16LE
#include "parsers/CiffParserException.h" // for ThrowCPE
#include <cstdio> // for sprintf
#include <cstring> // for memcpy, strlen
#include <limits> // for numeric_limits
#include <string> // for string, allocator
#include <vector> // for vector
using std::numeric_limits;
using std::string;
using std::vector;
namespace rawspeed {
CiffEntry::CiffEntry(Buffer* f, uint32 value_data, uint32 offset) {
own_data = nullptr;
ushort16 p = getU16LE(f->getData(offset, 2));
tag = static_cast<CiffTag>(p & 0x3fff);
ushort16 datalocation = (p & 0xc000);
type = static_cast<CiffDataType>(p & 0x3800);
if (datalocation == 0x0000) { // Data is offset in value_data
bytesize = getU32LE(f->getData(offset + 2, 4));
data_offset = getU32LE(f->getData(offset + 6, 4));
if (data_offset >= numeric_limits<uint32>::max() - value_data)
ThrowCPE("Corrupt data offset.");
data_offset += value_data;
data = f->getData(data_offset, bytesize);
} else if (datalocation == 0x4000) { // Data is stored directly in entry
data_offset = offset + 2;
bytesize = 8; // Maximum of 8 bytes of data (the size and offset fields)
data = f->getData(data_offset, bytesize);
} else
ThrowCPE("Don't understand data location 0x%x", datalocation);
// Set the number of items using the shift
count = bytesize >> getElementShift();
}
CiffEntry::~CiffEntry() { delete[] own_data; }
uint32 __attribute__((pure)) CiffEntry::getElementShift() {
switch (type) {
case CIFF_SHORT:
return 1;
case CIFF_LONG:
case CIFF_MIX:
case CIFF_SUB1:
case CIFF_SUB2:
return 2;
default:
// e.g. CIFF_BYTE or CIFF_ASCII
return 0;
}
}
uint32 __attribute__((pure)) CiffEntry::getElementSize() {
switch (type) {
case CIFF_BYTE:
case CIFF_ASCII:
return 1;
case CIFF_SHORT:
return 2;
case CIFF_LONG:
case CIFF_MIX:
case CIFF_SUB1:
case CIFF_SUB2:
return 4;
default:
return 0;
}
}
bool __attribute__((pure)) CiffEntry::isInt() {
return (type == CIFF_LONG || type == CIFF_SHORT || type == CIFF_BYTE);
}
uint32 CiffEntry::getU32(uint32 num) {
if (!isInt()) {
ThrowCPE(
"Wrong type 0x%x encountered. Expected Long, Short or Byte at 0x%x",
type, tag);
}
if (type == CIFF_BYTE)
return getByte(num);
if (type == CIFF_SHORT)
return getU16(num);
if (num*4+3 >= bytesize)
ThrowCPE("Trying to read out of bounds");
return getU32LE(data + num * 4);
}
ushort16 CiffEntry::getU16(uint32 num) {
if (type != CIFF_SHORT && type != CIFF_BYTE)
ThrowCPE("Wrong type 0x%x encountered. Expected Short at 0x%x", type, tag);
if (num*2+1 >= bytesize)
ThrowCPE("Trying to read out of bounds");
return getU16LE(data + num * 2);
}
uchar8 CiffEntry::getByte(uint32 num) {
if (type != CIFF_BYTE)
ThrowCPE("Wrong type 0x%x encountered. Expected Byte at 0x%x", type, tag);
if (num >= bytesize)
ThrowCPE("Trying to read out of bounds");
return data[num];
}
string CiffEntry::getString() {
if (type != CIFF_ASCII)
ThrowCPE("Wrong type 0x%x encountered. Expected Ascii", type);
if (count == 0)
return string("");
if (!own_data) {
own_data = new uchar8[count];
memcpy(own_data, data, count);
own_data[count-1] = 0; // Ensure string is not larger than count defines
}
return string(reinterpret_cast<const char*>(&own_data[0]));
}
vector<string> CiffEntry::getStrings() {
vector<string> strs;
if (type != CIFF_ASCII)
ThrowCPE("Wrong type 0x%x encountered. Expected Ascii", type);
if (!own_data) {
own_data = new uchar8[count];
memcpy(own_data, data, count);
own_data[count-1] = 0; // Ensure string is not larger than count defines
}
uint32 start = 0;
for (uint32 i=0; i< count; i++) {
if (own_data[i] == 0) {
strs.emplace_back(reinterpret_cast<const char*>(&own_data[start]));
start = i+1;
}
}
return strs;
}
bool __attribute__((pure)) CiffEntry::isString() {
return (type == CIFF_ASCII);
}
void CiffEntry::setData( const void *in_data, uint32 byte_count )
{
if (byte_count > bytesize)
ThrowCPE("data set larger than entry size given");
if (!own_data) {
own_data = new uchar8[bytesize];
memcpy(own_data, data, bytesize);
}
memcpy(own_data, in_data, byte_count);
}
#ifdef _MSC_VER
#pragma warning(disable: 4996) // this function or variable may be unsafe
#endif
std::string CiffEntry::getValueAsString()
{
if (type == CIFF_ASCII)
return string(reinterpret_cast<const char*>(&data[0]));
auto *temp_string = new char[4096];
if (count == 1) {
switch (type) {
case CIFF_LONG:
sprintf(temp_string, "Long: %u (0x%x)", getU32(), getU32());
break;
case CIFF_SHORT:
sprintf(temp_string, "Short: %u (0x%x)", getU32(), getU32());
break;
case CIFF_BYTE:
sprintf(temp_string, "Byte: %u (0x%x)", getU32(), getU32());
break;
default:
sprintf(temp_string, "Type: %x: ", type);
for (uint32 i = 0; i < getElementSize(); i++) {
sprintf(&temp_string[strlen(temp_string-1)], "%x", data[i]);
}
}
}
string ret(temp_string);
delete [] temp_string;
return ret;
}
} // namespace rawspeed
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2015 Sergii Pylypenko
*
* 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 <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include "gfx.h"
#include "gui.h"
#include "input.h"
#include "scancodes.h"
#include "flash_kernel.h"
static struct supportedDevices_t
{
const char * device;
const char * download;
const char * checksum;
const char * flash;
const char * clear_tmp;
}
supportedDevices[] =
{
{
"$APPDIR/busybox [ \"`getprop ro.product.device`\" = grouper -a \"`getprop ro.build.version.release`\" = 5.0.2 ] && echo Matched || $APPDIR/busybox [ \"`getprop ro.product.device`\" = nakasi -a \"`getprop ro.build.version.release`\" = 5.0.2 ] && echo Matched",
"$APPDIR/wget --no-check-certificate -O boot.img 'https://github.com/pelya/android-keyboard-gadget/blob/e44670bdcbc8d6a6939e083fcefec067f11094a8/nexus7-2012-wifi-grouper/boot.img?raw=true' && echo Successful",
"echo 'bb164ba3a76a6d2921414414a26c0498b7ce29de boot.img' | $APPDIR/busybox sha1sum -c",
"echo \"$APPDIR/busybox dd if=boot.img of=/dev/block/platform/sdhci-tegra.3/by-name/LNX && echo Successful\" | su",
"rm boot.img"
},
{
"$APPDIR/busybox [ \"`getprop ro.product.device`\" = grouper -a \"`getprop ro.build.version.release`\" = 4.4.4 ] && echo Matched || $APPDIR/busybox [ \"`getprop ro.product.device`\" = nakasi -a \"`getprop ro.build.version.release`\" = 4.4.4 ] && echo Matched",
"$APPDIR/wget --no-check-certificate -O boot.img 'https://github.com/pelya/android-keyboard-gadget/blob/bfcefabcd60829866c23ad03ea43fd3166462468/nexus7-2012-wifi-grouper/boot.img?raw=true' && echo Successful",
"echo '1b57049e0823f632f8c69bbde8f9dd632cad7e7b boot.img' | $APPDIR/busybox sha1sum -c",
"echo \"$APPDIR/busybox dd if=boot.img of=/dev/block/platform/sdhci-tegra.3/by-name/LNX && echo Successful\" | su",
"rm boot.img"
},
{ NULL, NULL, NULL, NULL, NULL }
};
static int executeCommand(const char * cmd, const char *search)
{
int success = 0;
printf("executeCommand > %s", cmd);
char buf[512] = "";
FILE *ff = popen(cmd, "r");
while( fgets(buf, sizeof(buf), ff) )
{
printf("executeCommand >> %s", buf);
addDialogText(buf);
mainLoop(true);
if (strstr(buf, search) != NULL)
success = 1;
}
pclose(ff);
return success;
}
static int flashCustomKernelDialog(struct supportedDevices_t & dev)
{
createDialog();
addDialogText("You will need custom kernel to use this app.");
addDialogText("Do you wish to download and flash custom kernel?");
addDialogText("You will need root on your device.");
addDialogText("If you don't have root, please follow this link:");
addDialogText("");
addDialogText("");
addDialogUrlButton("https://github.com/pelya/android-keyboard-gadget");
addDialogYesNoButtons();
int result = 0;
while( !getDialogResult(&result) )
mainLoop(true);
if( result == 0 )
exit(0);
createDialog();
addDialogText("Downloading package...");
mainLoop(true);
if( !executeCommand(dev.download, "Successful") )
showErrorMessage("Cannot download kernel, please check your network connectivity");
addDialogText("Validating package...");
mainLoop(true);
if( !executeCommand(dev.checksum, "boot.img: OK") )
showErrorMessage("Downloaded package was corrupted, please re-download it");
createDialog();
addDialogText("Custom kernel will be flashed to your device.");
addDialogText("This kernel is EXPERIMENTAL, and comes WTIH NO WARRANTY.");
addDialogText("Your device may become unstable, and reboot at random.");
addDialogText("You will lose root, please root your device again.");
addDialogText("");
addDialogText("Do you wish to flash custom kernel to your device?");
addDialogYesNoButtons();
while( !getDialogResult(&result) )
mainLoop(true);
if( result == 0 )
exit(0);
result = executeCommand(dev.flash, "Successful");
executeCommand(dev.clear_tmp, "-");
if( result )
showErrorMessage("Flashing kernel succeeded.\nPlease restart your device now.");
else
showErrorMessage("Flashing kernel failed.\nDo you have root installed on your device?");
return 1;
}
int flashCustomKernel()
{
int d;
for( d = 0; supportedDevices[d].device; d++ )
if( executeCommand(supportedDevices[d].device, "Matched") )
return flashCustomKernelDialog(supportedDevices[d]);
createDialog();
addDialogText("You will need a custom kernel to use this app.");
addDialogText("Prebuilt kernel is available only for Nexus 7 2012 WiFi");
addDialogText("with Android 4.4.4 or 5.0.2.");
addDialogText("You will need to compile and install the kernel yourself for other devices.");
addDialogText("Compilation instructions are available here:");
addDialogText("");
addDialogUrlButton("https://github.com/pelya/android-keyboard-gadget");
while( true )
mainLoop(true);
return 0;
}
<commit_msg>Updated dialog to flash boot image<commit_after>/*
* Copyright (C) 2015 Sergii Pylypenko
*
* 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 <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include "gfx.h"
#include "gui.h"
#include "input.h"
#include "scancodes.h"
#include "flash_kernel.h"
static struct supportedDevices_t
{
const char * device;
const char * download;
const char * checksum;
const char * flash;
const char * clear_tmp;
}
supportedDevices[] =
{
{
"$APPDIR/busybox [ \"`getprop ro.product.device`\" = grouper -a \"`getprop ro.build.version.release`\" = 5.1.1 ] && echo Matched || $APPDIR/busybox [ \"`getprop ro.product.device`\" = nakasi -a \"`getprop ro.build.version.release`\" = 5.1.1 ] && echo Matched",
"$APPDIR/wget --no-check-certificate -O boot.img 'https://github.com/pelya/android-keyboard-gadget/blob/8017463df1fc106852d2d4e2f04a0f26b6008bbe/nexus7-2012-wifi-grouper/boot.img?raw=true' && echo Successful",
"echo '556b568734cc4c29b046a6b6b9a992ca31e09a96 boot.img' | $APPDIR/busybox sha1sum -c",
"echo \"$APPDIR/busybox dd if=boot.img of=/dev/block/platform/sdhci-tegra.3/by-name/LNX && echo Successful\" | su",
"rm boot.img"
},
{
"$APPDIR/busybox [ \"`getprop ro.product.device`\" = grouper -a \"`getprop ro.build.version.release`\" = 5.0.2 ] && echo Matched || $APPDIR/busybox [ \"`getprop ro.product.device`\" = nakasi -a \"`getprop ro.build.version.release`\" = 5.0.2 ] && echo Matched",
"$APPDIR/wget --no-check-certificate -O boot.img 'https://github.com/pelya/android-keyboard-gadget/blob/e44670bdcbc8d6a6939e083fcefec067f11094a8/nexus7-2012-wifi-grouper/boot.img?raw=true' && echo Successful",
"echo 'bb164ba3a76a6d2921414414a26c0498b7ce29de boot.img' | $APPDIR/busybox sha1sum -c",
"echo \"$APPDIR/busybox dd if=boot.img of=/dev/block/platform/sdhci-tegra.3/by-name/LNX && echo Successful\" | su",
"rm boot.img"
},
{
"$APPDIR/busybox [ \"`getprop ro.product.device`\" = grouper -a \"`getprop ro.build.version.release`\" = 4.4.4 ] && echo Matched || $APPDIR/busybox [ \"`getprop ro.product.device`\" = nakasi -a \"`getprop ro.build.version.release`\" = 4.4.4 ] && echo Matched",
"$APPDIR/wget --no-check-certificate -O boot.img 'https://github.com/pelya/android-keyboard-gadget/blob/bfcefabcd60829866c23ad03ea43fd3166462468/nexus7-2012-wifi-grouper/boot.img?raw=true' && echo Successful",
"echo '1b57049e0823f632f8c69bbde8f9dd632cad7e7b boot.img' | $APPDIR/busybox sha1sum -c",
"echo \"$APPDIR/busybox dd if=boot.img of=/dev/block/platform/sdhci-tegra.3/by-name/LNX && echo Successful\" | su",
"rm boot.img"
},
{ NULL, NULL, NULL, NULL, NULL }
};
static int executeCommand(const char * cmd, const char *search)
{
int success = 0;
printf("executeCommand > %s", cmd);
char buf[512] = "";
FILE *ff = popen(cmd, "r");
while( fgets(buf, sizeof(buf), ff) )
{
printf("executeCommand >> %s", buf);
addDialogText(buf);
mainLoop(true);
if (strstr(buf, search) != NULL)
success = 1;
}
pclose(ff);
return success;
}
static int flashCustomKernelDialog(struct supportedDevices_t & dev)
{
createDialog();
addDialogText("You will need custom kernel to use this app.");
addDialogText("Do you wish to download and flash custom kernel?");
addDialogText("You will need root on your device.");
addDialogText("If you don't have root, please follow this link:");
addDialogText("");
addDialogText("");
addDialogUrlButton("https://github.com/pelya/android-keyboard-gadget");
addDialogYesNoButtons();
int result = 0;
while( !getDialogResult(&result) )
mainLoop(true);
if( result == 0 )
exit(0);
createDialog();
addDialogText("Downloading package...");
mainLoop(true);
if( !executeCommand(dev.download, "Successful") )
showErrorMessage("Cannot download kernel, please check your network connectivity");
addDialogText("Validating package...");
mainLoop(true);
if( !executeCommand(dev.checksum, "boot.img: OK") )
showErrorMessage("Downloaded package was corrupted, please re-download it");
createDialog();
addDialogText("Custom kernel will be flashed to your device.");
addDialogText("This kernel is EXPERIMENTAL, and comes WTIH NO WARRANTY.");
addDialogText("Your device may become unstable, and reboot at random.");
addDialogText("You will lose root, please root your device again.");
addDialogText("");
addDialogText("Do you wish to flash custom kernel to your device?");
addDialogYesNoButtons();
while( !getDialogResult(&result) )
mainLoop(true);
if( result == 0 )
exit(0);
result = executeCommand(dev.flash, "Successful");
executeCommand(dev.clear_tmp, "-");
if( result )
showErrorMessage("Flashing kernel succeeded.\nPlease restart your device now.");
else
showErrorMessage("Flashing kernel failed.\nDo you have root installed on your device?");
return 1;
}
int flashCustomKernel()
{
int d;
for( d = 0; supportedDevices[d].device; d++ )
if( executeCommand(supportedDevices[d].device, "Matched") )
return flashCustomKernelDialog(supportedDevices[d]);
createDialog();
addDialogText("You will need a custom kernel to use this app.");
addDialogText("Prebuilt kernel is available only for Nexus 7 2012 WiFi");
addDialogText("with Android 4.4.4 or 5.0.2.");
addDialogText("You will need to compile and install the kernel yourself for other devices.");
addDialogText("Compilation instructions are available here:");
addDialogText("");
addDialogUrlButton("https://github.com/pelya/android-keyboard-gadget");
while( true )
mainLoop(true);
return 0;
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name: managedframe.cpp
// Purpose: Implementation of wxExManagedFrame class.
// Author: Anton van Wezenbeek
// Created: 2010-04-11
// RCS-ID: $Id$
// Copyright: (c) 2010 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/extension/managedframe.h>
#include <wx/extension/stcfile.h>
#include <wx/extension/toolbar.h>
#if wxUSE_GUI
#if wxUSE_AUI
BEGIN_EVENT_TABLE(wxExManagedFrame, wxExFrame)
EVT_MENU(wxID_PREFERENCES, wxExManagedFrame::OnCommand)
EVT_MENU_RANGE(ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnCommand)
EVT_UPDATE_UI_RANGE(ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnUpdateUI)
END_EVENT_TABLE()
wxExManagedFrame::wxExManagedFrame(wxWindow* parent,
wxWindowID id,
const wxString& title,
long style,
const wxString& name)
: wxExFrame(parent, id, title, style, name)
{
m_Manager.SetManagedWindow(this);
CreateToolBar();
CreateFindBar();
}
wxExManagedFrame::~wxExManagedFrame()
{
m_Manager.UnInit();
}
void wxExManagedFrame::CreateFindBar(long style, wxWindowID id)
{
wxExFindToolBar* findBar = new wxExFindToolBar(this,
id,
wxDefaultPosition,
wxDefaultSize,
style);
GetManager().AddPane(findBar,
wxAuiPaneInfo().Bottom().ToolbarPane().Name("FINDBAR").Caption(_("Find Bar")));
}
void wxExManagedFrame::CreateToolBar(long style, wxWindowID id)
{
wxExToolBar* toolBar = new wxExToolBar(this,
id,
wxDefaultPosition,
wxDefaultSize,
style);
toolBar->AddControls();
DoAddControl(toolBar);
GetManager().AddPane(toolBar,
wxAuiPaneInfo().Top().ToolbarPane().Name("TOOLBAR").Caption(_("Tool Bar")));
}
void wxExManagedFrame::OnCommand(wxCommandEvent& event)
{
switch (event.GetId())
{
case wxID_PREFERENCES:
wxExSTCFile::ConfigDialog(this,
_("Editor Options"),
wxExSTCFile::STC_CONFIG_MODELESS |
wxExSTCFile::STC_CONFIG_SIMPLE |
wxExSTCFile::STC_CONFIG_WITH_APPLY,
event.GetId());
break;
case ID_VIEW_FINDBAR: TogglePane("FINDBAR"); break;
case ID_VIEW_TOOLBAR: TogglePane("TOOLBAR"); break;
case ID_VIEW_MENUBAR:
if (GetMenuBar()->IsShown())
{
SetMenuBar(NULL);
}
break;
case ID_VIEW_STATUSBAR:
GetStatusBar()->Show(!GetStatusBar()->IsShown());
SendSizeEvent();
break;
default:
wxFAIL;
}
}
void wxExManagedFrame::OnUpdateUI(wxUpdateUIEvent& event)
{
switch (event.GetId())
{
case ID_VIEW_FINDBAR:
event.Check(GetManager().GetPane("FINDBAR").IsShown());
break;
case ID_VIEW_TOOLBAR:
event.Check(GetManager().GetPane("TOOLBAR").IsShown());
break;
case ID_VIEW_MENUBAR:
wxASSERT(GetMenuBar() != NULL);
event.Check(GetMenuBar()->IsShown());
break;
case ID_VIEW_STATUSBAR:
wxASSERT(GetStatusBar() != NULL);
event.Check(GetStatusBar()->IsShown());
break;
default:
wxFAIL;
}
}
void wxExManagedFrame::TogglePane(const wxString& pane)
{
wxAuiPaneInfo& info = m_Manager.GetPane(pane);
wxASSERT(info.IsOk());
info.IsShown() ? info.Hide(): info.Show();
m_Manager.Update();
}
#endif // wxUSE_AUI
#endif // wxUSE_GUI
<commit_msg>fix for menubar NULL<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name: managedframe.cpp
// Purpose: Implementation of wxExManagedFrame class.
// Author: Anton van Wezenbeek
// Created: 2010-04-11
// RCS-ID: $Id$
// Copyright: (c) 2010 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/extension/managedframe.h>
#include <wx/extension/stcfile.h>
#include <wx/extension/toolbar.h>
#if wxUSE_GUI
#if wxUSE_AUI
BEGIN_EVENT_TABLE(wxExManagedFrame, wxExFrame)
EVT_MENU(wxID_PREFERENCES, wxExManagedFrame::OnCommand)
EVT_MENU_RANGE(ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnCommand)
EVT_UPDATE_UI_RANGE(ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnUpdateUI)
END_EVENT_TABLE()
wxExManagedFrame::wxExManagedFrame(wxWindow* parent,
wxWindowID id,
const wxString& title,
long style,
const wxString& name)
: wxExFrame(parent, id, title, style, name)
{
m_Manager.SetManagedWindow(this);
CreateToolBar();
CreateFindBar();
}
wxExManagedFrame::~wxExManagedFrame()
{
m_Manager.UnInit();
}
void wxExManagedFrame::CreateFindBar(long style, wxWindowID id)
{
wxExFindToolBar* findBar = new wxExFindToolBar(this,
id,
wxDefaultPosition,
wxDefaultSize,
style);
GetManager().AddPane(findBar,
wxAuiPaneInfo().Bottom().ToolbarPane().Name("FINDBAR").Caption(_("Find Bar")));
}
void wxExManagedFrame::CreateToolBar(long style, wxWindowID id)
{
wxExToolBar* toolBar = new wxExToolBar(this,
id,
wxDefaultPosition,
wxDefaultSize,
style);
toolBar->AddControls();
DoAddControl(toolBar);
GetManager().AddPane(toolBar,
wxAuiPaneInfo().Top().ToolbarPane().Name("TOOLBAR").Caption(_("Tool Bar")));
}
void wxExManagedFrame::OnCommand(wxCommandEvent& event)
{
switch (event.GetId())
{
case wxID_PREFERENCES:
wxExSTCFile::ConfigDialog(this,
_("Editor Options"),
wxExSTCFile::STC_CONFIG_MODELESS |
wxExSTCFile::STC_CONFIG_SIMPLE |
wxExSTCFile::STC_CONFIG_WITH_APPLY,
event.GetId());
break;
case ID_VIEW_FINDBAR: TogglePane("FINDBAR"); break;
case ID_VIEW_TOOLBAR: TogglePane("TOOLBAR"); break;
case ID_VIEW_MENUBAR:
if (GetMenuBar()->IsShown())
{
SetMenuBar(NULL);
}
break;
case ID_VIEW_STATUSBAR:
GetStatusBar()->Show(!GetStatusBar()->IsShown());
SendSizeEvent();
break;
default:
wxFAIL;
}
}
void wxExManagedFrame::OnUpdateUI(wxUpdateUIEvent& event)
{
switch (event.GetId())
{
case ID_VIEW_FINDBAR:
event.Check(GetManager().GetPane("FINDBAR").IsShown());
break;
case ID_VIEW_TOOLBAR:
event.Check(GetManager().GetPane("TOOLBAR").IsShown());
break;
case ID_VIEW_MENUBAR:
if (GetMenuBar() != NULL)
{
event.Check(GetMenuBar()->IsShown());
}
else
{
event.Check(false);
}
break;
case ID_VIEW_STATUSBAR:
wxASSERT(GetStatusBar() != NULL);
event.Check(GetStatusBar()->IsShown());
break;
default:
wxFAIL;
}
}
void wxExManagedFrame::TogglePane(const wxString& pane)
{
wxAuiPaneInfo& info = m_Manager.GetPane(pane);
wxASSERT(info.IsOk());
info.IsShown() ? info.Hide(): info.Show();
m_Manager.Update();
}
#endif // wxUSE_AUI
#endif // wxUSE_GUI
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include "STRTK/strtk.hpp"
#include "SFML/System.hpp"
#include "SFML/Graphics/Sprite.hpp"
#include "SFML/Graphics/Text.hpp"
#include "SFML/Graphics.hpp"
#include "painter.h"
#define WINDOW_WIDTH 1024
#define WINDOW_HEIGHT 768
Painter::Painter(RenderNode *node)
{
sf::RenderWindow window(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, 32), "OpenWeb");
paintNode(node, &window);
}
//SFML does not automatically wrap text to fit the window. This is a hurriedly
//implemented, temporary solution, and will receive more attention in the future.
//Right now, I am considering adopting SFGUI as an additional graphics library
//to address this (and other) issues I have found with SFML.
std::string Painter::parseTextToLines(std::string textToParse, int windowBoundary)
{
std::vector<std::string> wordVector;
strtk::parse(textToParse, " ", wordVector);
std::string parsedString;
std::string temporaryString;
sf::Text tempString;
for (int i = 0; i < wordVector.size(); i++)
{
temporaryString = temporaryString + wordVector.at(i) + " ";
tempString.setString(temporaryString);
if (tempString.getLocalBounds().width < windowBoundary)
{
parsedString = parsedString + wordVector.at(i) + " ";
}
else
{
parsedString = parsedString + "\n" + wordVector.at(i) + " ";
tempString.setString("");
temporaryString.clear();
}
}
return parsedString;
}
void Painter::paintNode(RenderNode *node, sf::RenderWindow *window)
{
try
{
sf::Text text;
text.setString(parseTextToLines(node->getText(), 2048));
text.setCharacterSize(15);
sf::Font font;
if (!font.loadFromFile("fonts/LinLibertine_R.ttf"))
{
throw "Error: Could not load the font.";
}
text.setFont(font);
while (window->isOpen())
{
window->clear();
window->draw(text);
window->display();
sf::Event event;
while (window->pollEvent(event))
{
if (sf::Event::Closed == event.type)
{
window->close();
}
}
}
}
catch (std::string error)
{
std::cout << error << std::endl;
}
}
<commit_msg>Commit to merge changes.<commit_after>#include <iostream>
#include <string>
#include "STRTK/strtk.hpp"
#include "SFML/System.hpp"
#include "SFML/Graphics/Sprite.hpp"
#include "SFML/Graphics/Text.hpp"
#include "SFML/Graphics.hpp"
#include "painter.h"
#define WINDOW_WIDTH 1024
#define WINDOW_HEIGHT 768
Painter::Painter(RenderNode *node)
{
sf::RenderWindow window(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, 32), "OpenWeb");
paintNode(node, &window);
}
//SFML does not automatically wrap text to fit the window. This is a hurriedly
//implemented, temporary solution, and will receive more attention in the future.
//Right now, I am considering adopting SFGUI as an additional graphics library
//to address this (and other) issues I have found with SFML.
std::string Painter::parseTextToLines(std::string textToParse, int windowBoundary)
{
std::vector<std::string> wordVector;
strtk::parse(textToParse, " ", wordVector);
std::string parsedString;
std::string temporaryString;
sf::Text tempString;
for (int i = 0; i < wordVector.size(); i++)
{
temporaryString = temporaryString + wordVector.at(i) + " ";
tempString.setString(temporaryString);
if (tempString.getLocalBounds().width < windowBoundary)
{
parsedString = parsedString + wordVector.at(i) + " ";
}
else
{
parsedString = parsedString + "\n" + wordVector.at(i) + " ";
tempString.setString("");
temporaryString.clear();
}
}
return parsedString;
}
void Painter::paintNode(RenderNode *node, sf::RenderWindow *window)
{
try
{
sf::Text text;
text.setString(parseTextToLines(node->getText(), WINDOW_WIDTH));
text.setCharacterSize(15);
sf::Font font;
if (!font.loadFromFile("fonts/LinLibertine_R.ttf"))
{
throw "Error: Could not load the font.";
}
text.setFont(font);
while (window->isOpen())
{
window->clear();
window->draw(text);
window->display();
sf::Event event;
while (window->pollEvent(event))
{
if (sf::Event::Closed == event.type)
{
window->close();
}
}
}
}
catch (std::string error)
{
std::cout << error << std::endl;
}
}
<|endoftext|>
|
<commit_before>#include "application.hpp"
#include <boost/log/attributes.hpp>
#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <iostream>
#include <cstdlib>
#include "log.hpp"
namespace asio = boost::asio;
namespace logging = boost::log;
namespace simplicity
{
xcb_atom_t xcbAtomDeleteWindow;
xcb_atom_t xcbAtomProtocols;
bool check_xcb_connection(xcb_connection_t *pConnection);
const string SimplicityApplication::ENV_VAR_DISPLAY_NAME = "DISPLAY";
SimplicityApplication &SimplicityApplication::get_instance(void)
{
static SimplicityApplication singleton;
return singleton;
}
SimplicityApplication::SimplicityApplication(void) :
m_bRunning(true),
m_pXConnection(nullptr),
m_GlobalLogger(),
m_IOService(),
m_Signals(m_IOService, SIGINT, SIGTERM, SIGHUP),
m_sDisplayName("")
{
m_Signals.async_wait(boost::bind(&SimplicityApplication::handler_sig, this, _1, _2));
m_ServiceThread = boost::thread(boost::bind(&asio::io_service::run, &m_IOService));
}
SimplicityApplication::~SimplicityApplication(void)
{
global_log_trace << "Destroying application singleton";
}
logging::sources::severity_logger<logging::trivial::severity_level> &SimplicityApplication::get_global_logger(void)
{
return m_GlobalLogger;
}
bool SimplicityApplication::run(void)
{
if (!m_bRunning)
return true;
global_log_trace << "Starting main application loop";
xcbAtomDeleteWindow = get_atom("WM_DELETE_WINDOW");
xcbAtomProtocols = get_atom("WM_PROTOCOLS");
m_bRunning = true;
while (m_bRunning)
{
xcb_generic_event_t *pEvent = xcb_poll_for_event(m_pXConnection);
if (pEvent == nullptr)
continue;
// TODO: do something with the event
delete pEvent; // TODO: necessary?
}
xcb_disconnect(m_pXConnection);
m_IOService.stop();
return false;
}
void SimplicityApplication::quit(void)
{
global_log_trace << "Ending main application loop";
xcb_client_message_event_t xcbEvent = {
.response_type = XCB_CLIENT_MESSAGE,
.format = 32,
.sequence = 0,
.window = m_pRootScreen->root,
.type = xcbAtomProtocols,
.data = {
(uint8_t)xcbAtomDeleteWindow,
XCB_CURRENT_TIME
}
};
xcb_send_event(
m_pXConnection,
false,
m_pRootScreen->root,
XCB_EVENT_MASK_NO_EVENT,
(char *)&xcbEvent
);
xcb_flush(m_pXConnection);
m_bRunning = false;
}
string SimplicityApplication::get_display_name(void) const
{
return m_sDisplayName;
}
void SimplicityApplication::set_display_name(string sDisplay)
{
if (sDisplay.empty())
{
char *pEnvVar = std::getenv(SimplicityApplication::ENV_VAR_DISPLAY_NAME.c_str());
if (pEnvVar)
m_sDisplayName = pEnvVar;
else
m_sDisplayName = ":0.0";
global_log_trace << "No display set. Defaulting to " << m_sDisplayName;
}
else
{
m_sDisplayName = sDisplay;
global_log_trace << "Display set to " << sDisplay;
}
putenv((char *)(SimplicityApplication::ENV_VAR_DISPLAY_NAME + "=" + m_sDisplayName).c_str());
}
void SimplicityApplication::handler_sig(const boost::system::error_code &error, int nSignal)
{
global_log_trace << "Received OS signal: " << nSignal;
switch (nSignal)
{
case SIGHUP:
global_log_trace << "Received OS SIGHUP";
handler_sig_hup(error, nSignal);
break;
case SIGINT:
global_log_trace << "Received OS SIGINT";
handler_sig_int(error, nSignal);
return;
case SIGTERM:
global_log_trace << "Received OS SIGTERM";
handler_sig_term(error, nSignal);
return;
default:
global_log_debug << "Unhandled signal: " << nSignal;
}
m_Signals.async_wait(boost::bind(&SimplicityApplication::handler_sig, this, _1, _2));
}
xcb_atom_t SimplicityApplication::get_atom(string sAtomName)
{
xcb_intern_atom_cookie_t xcbCookie = xcb_intern_atom(
m_pXConnection,
0,
sAtomName.length(),
sAtomName.c_str()
);
xcb_intern_atom_reply_t *pxcbReply = xcb_intern_atom_reply(
m_pXConnection,
xcbCookie,
NULL
);
if (pxcbReply == nullptr)
return 0;
xcb_atom_t xcbAtom = pxcbReply->atom;
delete pxcbReply;
return xcbAtom;
}
void SimplicityApplication::initialize(string sDisplay)
{
set_display_name(sDisplay);
initialize_logging();
initialize_x_connection();
}
void SimplicityApplication::initialize_logging(void)
{
logging::add_common_attributes();
logging::add_console_log(
std::cerr,
logging::keywords::format = (
logging::expressions::stream
<< "(" << logging::expressions::format_date_time<boost::posix_time::ptime>("TimeStamp", "%Y-%m-%d %H:%M%S") << ") "
<< "[" << logging::trivial::severity << "]: "
<< logging::expressions::smessage
),
logging::keywords::auto_flush = true
);
}
void SimplicityApplication::initialize_x_connection(void)
{
int nScreenNum = 0;
m_pXConnection = xcb_connect(m_sDisplayName.c_str(), &nScreenNum);
if (check_xcb_connection(m_pXConnection))
{
xcb_disconnect(m_pXConnection);
m_bRunning = false;
return;
}
xcb_screen_iterator_t iter = xcb_setup_roots_iterator(xcb_get_setup(m_pXConnection));
for (int i = 0; i != nScreenNum; i++)
xcb_screen_next(&iter);
m_pRootScreen = iter.data;
if (m_pRootScreen == nullptr)
{
global_log_error << "Could not get the current screen. Exiting";
xcb_disconnect(m_pXConnection);
m_bRunning = false;
}
global_log_debug << "Root screen dimensions: "
<< m_pRootScreen->width_in_pixels
<< "x"
<< m_pRootScreen->height_in_pixels
<< "Root window: "
<< m_pRootScreen->root;
}
void SimplicityApplication::handler_sig_hup(const boost::system::error_code &error, int nSignal)
{
// TODO: reload config
global_log_debug << "SIGHUP received";
}
void SimplicityApplication::handler_sig_int(const boost::system::error_code &error, int nSignal)
{
quit();
}
void SimplicityApplication::handler_sig_term(const boost::system::error_code &error, int nSignal)
{
quit();
}
bool check_xcb_connection(xcb_connection_t *pConnection)
{
switch (xcb_connection_has_error(pConnection))
{
case XCB_CONN_ERROR:
global_log_error << "Socket, pipe, or stream error prevented connetion to X server";
return true;
case XCB_CONN_CLOSED_EXT_NOTSUPPORTED:
global_log_error << "Extension not supported. Could not connect to X server";
return true;
case XCB_CONN_CLOSED_MEM_INSUFFICIENT:
global_log_error << "Not enough memory. Could not connect to X server";
return true;
case XCB_CONN_CLOSED_REQ_LEN_EXCEED:
global_log_error << "Exceeded request length. Could not connect to X server";
return true;
case XCB_CONN_CLOSED_PARSE_ERR:
global_log_error << "Could not parse display string. Could not connect to X server";
return true;
case XCB_CONN_CLOSED_INVALID_SCREEN:
global_log_error << "Could not connect to X server because an invalid screen was selected";
return true;
default:
return false;
}
}
}
<commit_msg>Do not allow calling of quit if not running<commit_after>#include "application.hpp"
#include <boost/log/attributes.hpp>
#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <iostream>
#include <cstdlib>
#include "log.hpp"
namespace asio = boost::asio;
namespace logging = boost::log;
namespace simplicity
{
xcb_atom_t xcbAtomDeleteWindow;
xcb_atom_t xcbAtomProtocols;
bool check_xcb_connection(xcb_connection_t *pConnection);
const string SimplicityApplication::ENV_VAR_DISPLAY_NAME = "DISPLAY";
SimplicityApplication &SimplicityApplication::get_instance(void)
{
static SimplicityApplication singleton;
return singleton;
}
SimplicityApplication::SimplicityApplication(void) :
m_bRunning(true),
m_pXConnection(nullptr),
m_GlobalLogger(),
m_IOService(),
m_Signals(m_IOService, SIGINT, SIGTERM, SIGHUP),
m_sDisplayName("")
{
m_Signals.async_wait(boost::bind(&SimplicityApplication::handler_sig, this, _1, _2));
m_ServiceThread = boost::thread(boost::bind(&asio::io_service::run, &m_IOService));
}
SimplicityApplication::~SimplicityApplication(void)
{
global_log_trace << "Destroying application singleton";
}
logging::sources::severity_logger<logging::trivial::severity_level> &SimplicityApplication::get_global_logger(void)
{
return m_GlobalLogger;
}
bool SimplicityApplication::run(void)
{
if (!m_bRunning)
return true;
global_log_trace << "Starting main application loop";
xcbAtomDeleteWindow = get_atom("WM_DELETE_WINDOW");
xcbAtomProtocols = get_atom("WM_PROTOCOLS");
m_bRunning = true;
while (m_bRunning)
{
xcb_generic_event_t *pEvent = xcb_poll_for_event(m_pXConnection);
if (pEvent == nullptr)
continue;
// TODO: do something with the event
delete pEvent; // TODO: necessary?
}
xcb_disconnect(m_pXConnection);
m_IOService.stop();
return false;
}
void SimplicityApplication::quit(void)
{
if (!m_bRunning)
{
global_log_error << "Quit called but the application is not running";
return;
}
global_log_trace << "Ending main application loop";
xcb_client_message_event_t xcbEvent = {
.response_type = XCB_CLIENT_MESSAGE,
.format = 32,
.sequence = 0,
.window = m_pRootScreen->root,
.type = xcbAtomProtocols,
.data = {
(uint8_t)xcbAtomDeleteWindow,
XCB_CURRENT_TIME
}
};
xcb_send_event(
m_pXConnection,
false,
m_pRootScreen->root,
XCB_EVENT_MASK_NO_EVENT,
(char *)&xcbEvent
);
xcb_flush(m_pXConnection);
m_bRunning = false;
}
string SimplicityApplication::get_display_name(void) const
{
return m_sDisplayName;
}
void SimplicityApplication::set_display_name(string sDisplay)
{
if (sDisplay.empty())
{
char *pEnvVar = std::getenv(SimplicityApplication::ENV_VAR_DISPLAY_NAME.c_str());
if (pEnvVar)
m_sDisplayName = pEnvVar;
else
m_sDisplayName = ":0.0";
global_log_trace << "No display set. Defaulting to " << m_sDisplayName;
}
else
{
m_sDisplayName = sDisplay;
global_log_trace << "Display set to " << sDisplay;
}
putenv((char *)(SimplicityApplication::ENV_VAR_DISPLAY_NAME + "=" + m_sDisplayName).c_str());
}
void SimplicityApplication::handler_sig(const boost::system::error_code &error, int nSignal)
{
global_log_trace << "Received OS signal: " << nSignal;
switch (nSignal)
{
case SIGHUP:
global_log_trace << "Received OS SIGHUP";
handler_sig_hup(error, nSignal);
break;
case SIGINT:
global_log_trace << "Received OS SIGINT";
handler_sig_int(error, nSignal);
return;
case SIGTERM:
global_log_trace << "Received OS SIGTERM";
handler_sig_term(error, nSignal);
return;
default:
global_log_debug << "Unhandled signal: " << nSignal;
}
m_Signals.async_wait(boost::bind(&SimplicityApplication::handler_sig, this, _1, _2));
}
xcb_atom_t SimplicityApplication::get_atom(string sAtomName)
{
xcb_intern_atom_cookie_t xcbCookie = xcb_intern_atom(
m_pXConnection,
0,
sAtomName.length(),
sAtomName.c_str()
);
xcb_intern_atom_reply_t *pxcbReply = xcb_intern_atom_reply(
m_pXConnection,
xcbCookie,
NULL
);
if (pxcbReply == nullptr)
return 0;
xcb_atom_t xcbAtom = pxcbReply->atom;
delete pxcbReply;
return xcbAtom;
}
void SimplicityApplication::initialize(string sDisplay)
{
set_display_name(sDisplay);
initialize_logging();
initialize_x_connection();
}
void SimplicityApplication::initialize_logging(void)
{
logging::add_common_attributes();
logging::add_console_log(
std::cerr,
logging::keywords::format = (
logging::expressions::stream
<< "(" << logging::expressions::format_date_time<boost::posix_time::ptime>("TimeStamp", "%Y-%m-%d %H:%M%S") << ") "
<< "[" << logging::trivial::severity << "]: "
<< logging::expressions::smessage
),
logging::keywords::auto_flush = true
);
}
void SimplicityApplication::initialize_x_connection(void)
{
int nScreenNum = 0;
m_pXConnection = xcb_connect(m_sDisplayName.c_str(), &nScreenNum);
if (check_xcb_connection(m_pXConnection))
{
xcb_disconnect(m_pXConnection);
m_bRunning = false;
return;
}
xcb_screen_iterator_t iter = xcb_setup_roots_iterator(xcb_get_setup(m_pXConnection));
for (int i = 0; i != nScreenNum; i++)
xcb_screen_next(&iter);
m_pRootScreen = iter.data;
if (m_pRootScreen == nullptr)
{
global_log_error << "Could not get the current screen. Exiting";
xcb_disconnect(m_pXConnection);
m_bRunning = false;
}
global_log_debug << "Root screen dimensions: "
<< m_pRootScreen->width_in_pixels
<< "x"
<< m_pRootScreen->height_in_pixels
<< "Root window: "
<< m_pRootScreen->root;
}
void SimplicityApplication::handler_sig_hup(const boost::system::error_code &error, int nSignal)
{
// TODO: reload config
global_log_debug << "SIGHUP received";
}
void SimplicityApplication::handler_sig_int(const boost::system::error_code &error, int nSignal)
{
quit();
}
void SimplicityApplication::handler_sig_term(const boost::system::error_code &error, int nSignal)
{
quit();
}
bool check_xcb_connection(xcb_connection_t *pConnection)
{
switch (xcb_connection_has_error(pConnection))
{
case XCB_CONN_ERROR:
global_log_error << "Socket, pipe, or stream error prevented connetion to X server";
return true;
case XCB_CONN_CLOSED_EXT_NOTSUPPORTED:
global_log_error << "Extension not supported. Could not connect to X server";
return true;
case XCB_CONN_CLOSED_MEM_INSUFFICIENT:
global_log_error << "Not enough memory. Could not connect to X server";
return true;
case XCB_CONN_CLOSED_REQ_LEN_EXCEED:
global_log_error << "Exceeded request length. Could not connect to X server";
return true;
case XCB_CONN_CLOSED_PARSE_ERR:
global_log_error << "Could not parse display string. Could not connect to X server";
return true;
case XCB_CONN_CLOSED_INVALID_SCREEN:
global_log_error << "Could not connect to X server because an invalid screen was selected";
return true;
default:
return false;
}
}
}
<|endoftext|>
|
<commit_before>//
// pfilter.cpp
// EpiGenMCMC
//
// Created by Lucy Li on 05/05/2016.
// Copyright (c) 2016 Lucy Li, Imperial College London. All rights reserved.
//
#include "pfilter.h"
#include <iostream>
namespace EpiGenPfilter {
double pfilter(Model & sim_model, Parameter & model_params, MCMCoptions & options, Particle &particles, Trajectory & output_traj, TimeSeriesData &epi_data, TreeData &tree_data, MultiTreeData &multitree_data) {
double loglik = 0.0;
int num_groups = options.num_groups;
int num_particles = options.particles;
int init_seed = options.seed;
int total_dt = options.total_dt;
double sim_dt = options.sim_dt;
int total_steps = ceil((double)total_dt/(double)options.pfilter_every);
int add_dt = 0;
double ESS_threshold = options.pfilter_threshold*(double)num_particles;
Likelihood likelihood_calc;
// std::vector <Parameter> values;// (options.num_threads, model_params);
// for (int i=0; i!=options.num_threads; ++i) values.push_back(model_params);
// for (int i=0; i!=model_params.get_total_params(); ++i) values.push_back(model_params.get(i));
std::vector <std::vector<double> > values(options.num_threads, std::vector<double>(model_params.get_total_params(), 0.0));
for (int i=0; i!=options.num_threads; ++i) {
for (int j=0; j!=model_params.get_total_params(); ++j) {
values[i][j] = model_params.get(j);
}
}
// printf("Size of values = %d\n",values.size());
double reporting_rate = 1.0;
if (model_params.param_exists("reporting")) {
reporting_rate = model_params.get("reporting");
}
std::vector <std::string> param_names = model_params.get_names_vector();
if (model_params.param_exists("time_before_data")) {
add_dt = model_params.get("time_before_data");
}
if (options.save_traj) {
if (add_dt > 0) {
particles.start_particle_tracing(add_dt+total_dt, num_groups);
}
else if (add_dt < 0) {
particles.start_particle_tracing(add_dt+total_dt, num_groups);
total_steps = ceil((double)(total_dt+add_dt)/(double)options.pfilter_every);
}
else {
particles.start_particle_tracing(total_dt, num_groups);
}
}
std::vector <Model> models;
for (int i=0; i<options.num_threads; ++i) {
models.push_back(sim_model);
}
// Simulate model and calculate likelihood assuming no observed data
if (model_params.param_exists("time_before_data")) {
if (add_dt > 0) {
omp_set_num_threads(options.num_threads);
// std::vector <Trajectory *> curr_trajs;
// for (int i=0; i!=num_particles; ++i) {
// curr_trajs.push_back(particles.get_traj(i));
// }
#pragma omp parallel for shared(particles, values) schedule(static, 1)
for (int tn=0; tn<options.num_threads; tn++) {
for (int i=tn; i<num_particles; i+=options.num_threads) {
// Adjust length of trajectory
particles.get_traj(i)->resize(add_dt, num_groups);
models[tn].simulate(values[tn], param_names, particles.get_traj(i), 0, add_dt, sim_dt, total_dt, options.rng[tn]);
if (options.which_likelihood<2) {
double w = likelihood_calc.binomial_lik(reporting_rate, particles.get_traj(i)->get_total_traj(), add_dt+total_dt, 0, add_dt, num_groups, false);
particles.set_weight(w, i, false);
}
if (options.save_traj) {
particles.save_traj_to_matrix(i, 0, add_dt);
particles.save_ancestry(i, 0, add_dt);
}
}
}
}
}
init_seed += num_particles;
int t=0;
int start_dt;
int end_dt;
for (t=0; t!=total_steps; ++t) {
// std::vector<double> we(options.particles, 0.0), wg(options.particles, 0.0);
start_dt = t*options.pfilter_every;
end_dt = std::min(total_dt, (t+1)*options.pfilter_every);
omp_set_num_threads(options.num_threads);
#pragma omp parallel for shared (particles, values) schedule(static,1)
for (int tn=0; tn<options.num_threads; tn++) {
for (int i=tn; i<num_particles; i+=options.num_threads) {
// Adjust length of trajectory
particles.get_traj(i)->resize(end_dt-start_dt, options.num_groups);
models[tn].simulate(values[tn], param_names, particles.get_traj(i), start_dt, end_dt, sim_dt, total_dt, options.rng[tn]);
double w = 1.0;
double temp = 0.0;
if (options.which_likelihood<2) {
double A = particles.get_traj(i)->get_total_traj();
temp = likelihood_calc.binomial_lik(reporting_rate, A, epi_data.get_data_ptr(0), add_dt+total_dt, start_dt, end_dt, add_dt, options.num_groups, false);
w *= temp;
// we[i] = log(temp);
}
if (options.which_likelihood != 1) {
temp = likelihood_calc.coalescent_lik(particles.get_traj(i)->get_traj_ptr(1, 0), particles.get_traj(i)->get_traj_ptr(2, 0),
tree_data.get_binomial_ptr(0), tree_data.get_interval_ptr(0), tree_data.get_ends_ptr(0),
start_dt, end_dt, add_dt, false);
w *= temp;
// wg[i] = log(temp);
}
particles.set_weight(w, i, true);
if (options.save_traj) {
particles.save_traj_to_matrix(i, start_dt+add_dt, end_dt+add_dt);
particles.save_ancestry(i, start_dt+add_dt, end_dt+add_dt);
}
}
}
// std::cout << "Epi Weight: " << std::accumulate(we.begin(), we.end(), 0.0) << " Gen Weight: " << std::accumulate(wg.begin(), wg.end(), 0.0) << " Total: " << particles.get_total_weight() << std::endl;
double curr_ESS = particles.get_ESS();
if (curr_ESS < ESS_threshold) {
double total_weight = particles.get_total_weight();
if (total_weight == 0.0) {
loglik += -0.1*std::numeric_limits<double>::max();
// std::cout << std::accumulate(epi_data.get_data_ptr(0)+start_dt, epi_data.get_data_ptr(0)+end_dt, 0.0) << " : " << particles.get_traj(0)->get_traj(0) << std::endl;
std::cout << "stop time: " << end_dt << std::endl;
break;
} else {
loglik += log(total_weight) - log(num_particles);
}
particles.resample(options.rng[0]);
}
else {
particles.reset_parents();
}
}
if (options.save_traj) {
output_traj.resize((total_dt+add_dt), num_groups);
//if (loglik > -0.1*std::numeric_limits<double>::max()) {
particles.retrace_traj(output_traj, options.rng[0]);
//}
}
for (int i=0; i!=num_particles; ++i) {
particles.get_traj(i)->reset();
}
std::vector < std::vector<double> >().swap(values);
return (loglik);
}
}
<commit_msg>latest working version<commit_after>//
// pfilter.cpp
// EpiGenMCMC
//
// Created by Lucy Li on 05/05/2016.
// Copyright (c) 2016 Lucy Li, Imperial College London. All rights reserved.
//
#include "pfilter.h"
#include <iostream>
namespace EpiGenPfilter {
double pfilter(Model & sim_model, Parameter & model_params, MCMCoptions & options, Particle &particles, Trajectory & output_traj, TimeSeriesData &epi_data, TreeData &tree_data, MultiTreeData &multitree_data) {
double loglik = 0.0;
int num_groups = options.num_groups;
int num_particles = options.particles;
int init_seed = options.seed;
int total_dt = options.total_dt;
double sim_dt = options.sim_dt;
int total_steps = ceil((double)total_dt/(double)options.pfilter_every);
int add_dt = 0;
double ESS_threshold = options.pfilter_threshold*(double)num_particles;
Likelihood likelihood_calc;
// std::vector <Parameter> values;// (options.num_threads, model_params);
// for (int i=0; i!=options.num_threads; ++i) values.push_back(model_params);
// for (int i=0; i!=model_params.get_total_params(); ++i) values.push_back(model_params.get(i));
std::vector <std::vector<double> > values(options.num_threads, std::vector<double>(model_params.get_total_params(), 0.0));
for (int i=0; i!=options.num_threads; ++i) {
for (int j=0; j!=model_params.get_total_params(); ++j) {
values[i][j] = model_params.get(j);
}
}
// printf("Size of values = %d\n",values.size());
double reporting_rate = 1.0;
if (model_params.param_exists("reporting")) {
reporting_rate = model_params.get("reporting");
}
std::vector <std::string> param_names = model_params.get_names_vector();
if (model_params.param_exists("time_before_data")) {
add_dt = model_params.get("time_before_data");
}
if (options.save_traj) {
if (add_dt > 0) {
particles.start_particle_tracing(add_dt+total_dt, num_groups);
}
else if (add_dt < 0) {
particles.start_particle_tracing(add_dt+total_dt, num_groups);
total_steps = ceil((double)(total_dt+add_dt)/(double)options.pfilter_every);
}
else {
particles.start_particle_tracing(total_dt, num_groups);
}
}
std::vector <Model> models;
for (int i=0; i<options.num_threads; ++i) {
models.push_back(sim_model);
}
// Simulate model and calculate likelihood assuming no observed data
if (model_params.param_exists("time_before_data")) {
if (add_dt > 0) {
omp_set_num_threads(options.num_threads);
// std::vector <Trajectory *> curr_trajs;
// for (int i=0; i!=num_particles; ++i) {
// curr_trajs.push_back(particles.get_traj(i));
// }
#pragma omp parallel for shared(particles, values) schedule(static, 1)
for (int tn=0; tn<options.num_threads; tn++) {
for (int i=tn; i<num_particles; i+=options.num_threads) {
// Adjust length of trajectory
particles.get_traj(i)->resize(add_dt, num_groups);
models[tn].simulate(values[tn], param_names, particles.get_traj(i), 0, add_dt, sim_dt, total_dt, options.rng[tn]);
if (options.which_likelihood<2) {
double w = likelihood_calc.binomial_lik(reporting_rate, particles.get_traj(i)->get_total_traj(), add_dt+total_dt, 0, add_dt, num_groups, false);
particles.set_weight(w, i, false);
}
if (options.save_traj) {
particles.save_traj_to_matrix(i, 0, add_dt);
particles.save_ancestry(i, 0, add_dt);
}
}
}
}
}
init_seed += num_particles;
int t=0;
int start_dt;
int end_dt;
for (t=0; t!=total_steps; ++t) {
// std::vector<double> we(options.particles, 0.0), wg(options.particles, 0.0);
start_dt = t*options.pfilter_every;
end_dt = std::min(total_dt, (t+1)*options.pfilter_every);
omp_set_num_threads(options.num_threads);
#pragma omp parallel for shared (particles, values) schedule(static,1)
for (int tn=0; tn<options.num_threads; tn++) {
for (int i=tn; i<num_particles; i+=options.num_threads) {
// Adjust length of trajectory
// if (tn==0) std::cout << i << ' ' << std::endl;
particles.get_traj(i)->resize(end_dt-start_dt, options.num_groups);
models[tn].simulate(values[tn], param_names, particles.get_traj(i), start_dt, end_dt, sim_dt, total_dt, options.rng[tn]);
double w = 1.0;
double temp = 0.0;
if (options.which_likelihood<2) {
double A = particles.get_traj(i)->get_total_traj();
temp = likelihood_calc.binomial_lik(reporting_rate, A, epi_data.get_data_ptr(0), add_dt+total_dt, start_dt, end_dt, add_dt, options.num_groups, false);
w *= temp;
// we[i] = log(temp);
}
if (options.which_likelihood != 1) {
temp = likelihood_calc.coalescent_lik(particles.get_traj(i)->get_traj_ptr(1, 0), particles.get_traj(i)->get_traj_ptr(2, 0),
tree_data.get_binomial_ptr(0), tree_data.get_interval_ptr(0), tree_data.get_ends_ptr(0),
start_dt, end_dt, add_dt, false);
w *= temp;
// wg[i] = log(temp);
}
particles.set_weight(w, i, true);
if (options.save_traj) {
particles.save_traj_to_matrix(i, start_dt+add_dt, end_dt+add_dt);
particles.save_ancestry(i, start_dt+add_dt, end_dt+add_dt);
}
}
}
// std::cout << "Epi Weight: " << std::accumulate(we.begin(), we.end(), 0.0) << " Gen Weight: " << std::accumulate(wg.begin(), wg.end(), 0.0) << " Total: " << particles.get_total_weight() << std::endl;
double curr_ESS = particles.get_ESS();
if (curr_ESS < ESS_threshold) {
double total_weight = particles.get_total_weight();
if (total_weight == 0.0) {
loglik += -0.1*std::numeric_limits<double>::max();
// std::cout << std::accumulate(epi_data.get_data_ptr(0)+start_dt, epi_data.get_data_ptr(0)+end_dt, 0.0) << " : " << particles.get_traj(0)->get_traj(0) << std::endl;
std::cout << "stop time: " << end_dt << std::endl;
break;
} else {
loglik += log(total_weight) - log(num_particles);
}
particles.resample(options.rng[0]);
}
else {
particles.reset_parents();
}
}
if (options.save_traj) {
output_traj.resize((total_dt+add_dt), num_groups);
//if (loglik > -0.1*std::numeric_limits<double>::max()) {
particles.retrace_traj(output_traj, options.rng[0]);
//}
}
for (int i=0; i!=num_particles; ++i) {
particles.get_traj(i)->reset();
}
std::vector < std::vector<double> >().swap(values);
return (loglik);
}
}
<|endoftext|>
|
<commit_before>/* This file exists to provide some stat monitors for process statistics and the like. */
#include <vector>
#include <string.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sstream>
#include <iomanip>
#include <stdarg.h>
#include "arch/io/io_utils.hpp"
#include "perfmon.hpp"
#include "logger.hpp"
#include "utils.hpp"
#include "thread_local.hpp"
/* Class to represent and parse the contents of /proc/[pid]/stat */
struct proc_pid_stat_exc_t : public std::exception {
explicit proc_pid_stat_exc_t(const char *format, ...) __attribute__ ((format (printf, 2, 3))) {
char buffer[2000];
va_list l;
va_start(l, format);
vsnprintf(buffer, sizeof(buffer), format, l);
va_end(l);
msg = buffer;
}
std::string msg;
const char *what() const throw () {
return msg.c_str();
}
~proc_pid_stat_exc_t() throw () { }
};
struct proc_pid_stat_t {
int pid;
char name[500];
char state;
int ppid, pgrp, session, tty_nr, tpgid;
unsigned int flags;
unsigned long int minflt, cminflt, majflt, cmajflt, utime, stime;
long int cutime, cstime, priority, nice, num_threads, itrealvalue;
long long unsigned int starttime;
long unsigned int vsize;
long int rss;
long unsigned int rsslim, startcode, endcode, startstack, kstkesp, kstkeip, signal, blocked,
sigignore, sigcatch, wchan, nswap, cnswap;
int exit_signal, processor;
unsigned int rt_priority, policy;
long long unsigned int delayacct_blkio_ticks;
long unsigned int guest_time;
long int cguest_time;
static proc_pid_stat_t for_pid(pid_t pid) {
char path[100];
snprintf(path, sizeof(path), "/proc/%d/stat", pid);
proc_pid_stat_t stat;
stat.read_from_file(path);
return stat;
}
static proc_pid_stat_t for_pid_and_tid(pid_t pid, pid_t tid) {
char path[100];
snprintf(path, sizeof(path), "/proc/%d/task/%d/stat", pid, tid);
proc_pid_stat_t stat;
stat.read_from_file(path);
return stat;
}
private:
void read_from_file(char * path) {
scoped_fd_t stat_file(open(path, O_RDONLY));
if (stat_file.get() == INVALID_FD) {
throw proc_pid_stat_exc_t("Could not open '%s': %s (errno = %d)", path, strerror(errno), errno);
}
char buffer[1000];
int res = ::read(stat_file.get(), buffer, sizeof(buffer));
if (res <= 0) {
throw proc_pid_stat_exc_t("Could not read '%s': %s (errno = %d)", path, strerror(errno), errno);
}
buffer[res] = '\0';
// TODO rewrite this mess to use something more safe and sane, e.g. iostreams
const int items_to_parse = 44;
int res2 = sscanf(buffer, "%d %s %c %d %d %d %d %d %u %lu %lu %lu %lu %lu %lu %ld %ld "
"%ld %ld %ld %ld %llu %lu %ld %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %d "
"%d %u %u %u %u %llu %lu %ld",
&pid, name, &state, &ppid, &pgrp, &session, &tty_nr, &tpgid,
&flags, &minflt, &cminflt, &majflt, &cmajflt, &utime, &stime,
&cutime, &cstime, &priority, &nice, &num_threads, &itrealvalue,
&starttime, &vsize, &rss, &rsslim, &startcode, &endcode, &startstack,
&kstkesp, &kstkeip, &signal, &blocked, &sigignore, &sigcatch, &wchan,
&nswap, &cnswap, &exit_signal, &processor, &rt_priority, &processor,
&rt_priority, &policy, &delayacct_blkio_ticks, &guest_time, &cguest_time);
if (res2 != items_to_parse) {
throw proc_pid_stat_exc_t("Could not parse '%s': expected to parse %d items, parsed "
"%d. Buffer contents: %s", path, items_to_parse, res2, buffer);
}
}
};
/* perfmon_system_t is used to monitor system stats that do not need to be polled. */
struct perfmon_system_t :
public perfmon_t
{
bool have_reported_error;
perfmon_system_t() : perfmon_t(false), have_reported_error(false) { }
void *begin_stats() {
return NULL;
}
void visit_stats(void *) {
}
void end_stats(void *, perfmon_stats_t *dest) {
put_timestamp(dest);
(*dest)["version"] = std::string(RETHINKDB_VERSION);
(*dest)["pid"] = strprintf("%d", getpid());
proc_pid_stat_t pid_stat;
try {
pid_stat = proc_pid_stat_t::for_pid(getpid());
} catch (proc_pid_stat_exc_t e) {
if (!have_reported_error) {
logWRN("Error in reporting system stats: %s (Further errors like this will "
"be suppressed.)\n", e.what());
have_reported_error = true;
}
return;
}
(*dest)["memory_virtual[bytes]"] = strprintf("%lu", pid_stat.vsize);
(*dest)["memory_real[bytes]"] = strprintf("%ld", pid_stat.rss * sysconf(_SC_PAGESIZE));
}
void put_timestamp(perfmon_stats_t *dest) {
timespec uptime = get_uptime();
std::stringstream uptime_str;
uptime_str << uptime.tv_sec << '.' << std::setfill('0') << std::setw(6) << uptime.tv_nsec / 1000;
(*dest)["uptime"] = uptime_str.str();
(*dest)["timestamp"] = format_precise_time(get_absolute_time(uptime));
}
} pm_system;
/* Some of the stats need to be polled periodically. Call this function periodically on each
thread to ensure that stats are up to date. It takes a void* so that it can be called as a timer
callback. */
perfmon_sampler_t
pm_cpu_user("cpu_user", secs_to_ticks(5)),
pm_cpu_system("cpu_system", secs_to_ticks(5)),
pm_cpu_combined("cpu_combined", secs_to_ticks(5)),
pm_memory_faults("memory_faults", secs_to_ticks(5));
TLS(proc_pid_stat_t, last_stats);
TLS_with_init(ticks_t, last_ticks, 0);
TLS_with_init(bool, have_reported_stats_error, false);
void poll_system_stats(void *) {
proc_pid_stat_t current_stats;
try {
current_stats = proc_pid_stat_t::for_pid_and_tid(getpid(), syscall(SYS_gettid));
} catch (proc_pid_stat_exc_t e) {
if (!TLS_get_have_reported_stats_error()) {
logWRN("Error in reporting per-thread stats: %s (Further errors like this will "
"be suppressed.)\n", e.what());
TLS_set_have_reported_stats_error(true);
}
}
ticks_t current_ticks = get_ticks();
if (TLS_get_last_ticks() == 0) {
TLS_set_last_stats(current_stats);
TLS_set_last_ticks(current_ticks);
} else if (current_ticks > TLS_get_last_ticks() + secs_to_ticks(1)) {
double realtime_elapsed = ticks_to_secs(current_ticks - TLS_get_last_ticks()) * sysconf(_SC_CLK_TCK);
pm_cpu_user.record((current_stats.utime - TLS_get_last_stats().utime) / realtime_elapsed);
pm_cpu_system.record((current_stats.stime - TLS_get_last_stats().stime) / realtime_elapsed);
pm_cpu_combined.record(
(current_stats.utime - TLS_get_last_stats().utime +
current_stats.stime - TLS_get_last_stats().stime) /
realtime_elapsed);
pm_memory_faults.record((current_stats.majflt - TLS_get_last_stats().majflt) / realtime_elapsed);
TLS_set_last_stats(current_stats);
TLS_set_last_ticks(current_ticks);
}
}
<commit_msg>Fixed a bug in perfmon_system /proc/stat parsing, we had duplicated the processor and rt_policy arguments by accident.<commit_after>/* This file exists to provide some stat monitors for process statistics and the like. */
#include <vector>
#include <string.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sstream>
#include <iomanip>
#include <stdarg.h>
#include "arch/io/io_utils.hpp"
#include "perfmon.hpp"
#include "logger.hpp"
#include "utils.hpp"
#include "thread_local.hpp"
/* Class to represent and parse the contents of /proc/[pid]/stat */
struct proc_pid_stat_exc_t : public std::exception {
explicit proc_pid_stat_exc_t(const char *format, ...) __attribute__ ((format (printf, 2, 3))) {
char buffer[2000];
va_list l;
va_start(l, format);
vsnprintf(buffer, sizeof(buffer), format, l);
va_end(l);
msg = buffer;
}
std::string msg;
const char *what() const throw () {
return msg.c_str();
}
~proc_pid_stat_exc_t() throw () { }
};
struct proc_pid_stat_t {
int pid;
char name[500];
char state;
int ppid, pgrp, session, tty_nr, tpgid;
unsigned int flags;
unsigned long int minflt, cminflt, majflt, cmajflt, utime, stime;
long int cutime, cstime, priority, nice, num_threads, itrealvalue;
long long unsigned int starttime;
long unsigned int vsize;
long int rss;
long unsigned int rsslim, startcode, endcode, startstack, kstkesp, kstkeip, signal, blocked,
sigignore, sigcatch, wchan, nswap, cnswap;
int exit_signal, processor;
unsigned int rt_priority, policy;
long long unsigned int delayacct_blkio_ticks;
long unsigned int guest_time;
long int cguest_time;
static proc_pid_stat_t for_pid(pid_t pid) {
char path[100];
snprintf(path, sizeof(path), "/proc/%d/stat", pid);
proc_pid_stat_t stat;
stat.read_from_file(path);
return stat;
}
static proc_pid_stat_t for_pid_and_tid(pid_t pid, pid_t tid) {
char path[100];
snprintf(path, sizeof(path), "/proc/%d/task/%d/stat", pid, tid);
proc_pid_stat_t stat;
stat.read_from_file(path);
return stat;
}
private:
void read_from_file(char * path) {
scoped_fd_t stat_file(open(path, O_RDONLY));
if (stat_file.get() == INVALID_FD) {
throw proc_pid_stat_exc_t("Could not open '%s': %s (errno = %d)", path, strerror(errno), errno);
}
char buffer[1000];
int res = ::read(stat_file.get(), buffer, sizeof(buffer));
if (res <= 0) {
throw proc_pid_stat_exc_t("Could not read '%s': %s (errno = %d)", path, strerror(errno), errno);
}
buffer[res] = '\0';
// TODO rewrite this mess to use something more safe and sane, e.g. iostreams
const int items_to_parse = 44;
int res2 = sscanf(buffer, "%d %s %c %d %d %d %d %d %u %lu %lu %lu %lu %lu %lu %ld %ld "
"%ld %ld %ld %ld %llu %lu %ld %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %d "
"%d %u %u %llu %lu %ld",
&pid, name, &state, &ppid, &pgrp, &session, &tty_nr, &tpgid,
&flags, &minflt, &cminflt, &majflt, &cmajflt, &utime, &stime,
&cutime, &cstime, &priority, &nice, &num_threads, &itrealvalue,
&starttime, &vsize, &rss, &rsslim, &startcode, &endcode, &startstack,
&kstkesp, &kstkeip, &signal, &blocked, &sigignore, &sigcatch, &wchan,
&nswap, &cnswap, &exit_signal, &processor, &rt_priority, &policy,
&delayacct_blkio_ticks, &guest_time, &cguest_time);
if (res2 != items_to_parse) {
throw proc_pid_stat_exc_t("Could not parse '%s': expected to parse %d items, parsed "
"%d. Buffer contents: %s", path, items_to_parse, res2, buffer);
}
}
};
/* perfmon_system_t is used to monitor system stats that do not need to be polled. */
struct perfmon_system_t :
public perfmon_t
{
bool have_reported_error;
perfmon_system_t() : perfmon_t(false), have_reported_error(false) { }
void *begin_stats() {
return NULL;
}
void visit_stats(void *) {
}
void end_stats(void *, perfmon_stats_t *dest) {
put_timestamp(dest);
(*dest)["version"] = std::string(RETHINKDB_VERSION);
(*dest)["pid"] = strprintf("%d", getpid());
proc_pid_stat_t pid_stat;
try {
pid_stat = proc_pid_stat_t::for_pid(getpid());
} catch (proc_pid_stat_exc_t e) {
if (!have_reported_error) {
logWRN("Error in reporting system stats: %s (Further errors like this will "
"be suppressed.)\n", e.what());
have_reported_error = true;
}
return;
}
(*dest)["memory_virtual[bytes]"] = strprintf("%lu", pid_stat.vsize);
(*dest)["memory_real[bytes]"] = strprintf("%ld", pid_stat.rss * sysconf(_SC_PAGESIZE));
}
void put_timestamp(perfmon_stats_t *dest) {
timespec uptime = get_uptime();
std::stringstream uptime_str;
uptime_str << uptime.tv_sec << '.' << std::setfill('0') << std::setw(6) << uptime.tv_nsec / 1000;
(*dest)["uptime"] = uptime_str.str();
(*dest)["timestamp"] = format_precise_time(get_absolute_time(uptime));
}
} pm_system;
/* Some of the stats need to be polled periodically. Call this function periodically on each
thread to ensure that stats are up to date. It takes a void* so that it can be called as a timer
callback. */
perfmon_sampler_t
pm_cpu_user("cpu_user", secs_to_ticks(5)),
pm_cpu_system("cpu_system", secs_to_ticks(5)),
pm_cpu_combined("cpu_combined", secs_to_ticks(5)),
pm_memory_faults("memory_faults", secs_to_ticks(5));
TLS(proc_pid_stat_t, last_stats);
TLS_with_init(ticks_t, last_ticks, 0);
TLS_with_init(bool, have_reported_stats_error, false);
void poll_system_stats(void *) {
proc_pid_stat_t current_stats;
try {
current_stats = proc_pid_stat_t::for_pid_and_tid(getpid(), syscall(SYS_gettid));
} catch (proc_pid_stat_exc_t e) {
if (!TLS_get_have_reported_stats_error()) {
logWRN("Error in reporting per-thread stats: %s (Further errors like this will "
"be suppressed.)\n", e.what());
TLS_set_have_reported_stats_error(true);
}
}
ticks_t current_ticks = get_ticks();
if (TLS_get_last_ticks() == 0) {
TLS_set_last_stats(current_stats);
TLS_set_last_ticks(current_ticks);
} else if (current_ticks > TLS_get_last_ticks() + secs_to_ticks(1)) {
double realtime_elapsed = ticks_to_secs(current_ticks - TLS_get_last_ticks()) * sysconf(_SC_CLK_TCK);
pm_cpu_user.record((current_stats.utime - TLS_get_last_stats().utime) / realtime_elapsed);
pm_cpu_system.record((current_stats.stime - TLS_get_last_stats().stime) / realtime_elapsed);
pm_cpu_combined.record(
(current_stats.utime - TLS_get_last_stats().utime +
current_stats.stime - TLS_get_last_stats().stime) /
realtime_elapsed);
pm_memory_faults.record((current_stats.majflt - TLS_get_last_stats().majflt) / realtime_elapsed);
TLS_set_last_stats(current_stats);
TLS_set_last_ticks(current_ticks);
}
}
<|endoftext|>
|
<commit_before>#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <GL/glew.h>
#include <SDL2/SDL.h>
#include "FileUtil.h"
#define WINDOW_SIZE 640
#define ARRAY_COUNT(array) (sizeof(array) / sizeof(array[0]))
struct ShaderProgramSource {
GLenum shaderType;
const char* sourceFilename;
};
void printShaderInfoLog(GLuint shaderHandle, const char* name) {
GLint logLength;
glGetShaderiv(shaderHandle, GL_INFO_LOG_LENGTH, &logLength);
if (logLength > 0) {
char* logBuffer = new char[logLength];
GLsizei bytesCopied;
glGetShaderInfoLog(shaderHandle, logLength, &bytesCopied, logBuffer);
(void)fprintf(stderr, "Shader '%s' info log:\n%s\n", name, logBuffer);
delete [] logBuffer;
}
}
GLuint compileShader(GLenum shaderType, const char* filename) {
GLuint shaderHandle = glCreateShader(shaderType);
if (shaderHandle != 0) {
const GLchar* shaderCode = FileUtil::loadFileAsString(filename);
glShaderSource(shaderHandle, 1, &shaderCode, NULL);
delete [] shaderCode;
glCompileShader(shaderHandle);
GLint result;
glGetShaderiv(shaderHandle, GL_COMPILE_STATUS, &result);
if (result == GL_TRUE) {
(void)printf("Shader '%s' compilation was successful!\n", filename);
// Print warnings, if available
printShaderInfoLog(shaderHandle, filename);
} else {
(void)fprintf(stderr, "Shader compilation failed for '%s'!\n", filename);
printShaderInfoLog(shaderHandle, filename);
glDeleteShader(shaderHandle);
shaderHandle = 0;
}
} else {
(void)fprintf(stderr, "Error creating shader for '%s'.\n", filename);
}
return shaderHandle;
}
void printProgramInfoLog(GLuint programHandle) {
GLint logLength;
glGetProgramiv(programHandle, GL_INFO_LOG_LENGTH, &logLength);
if (logLength > 0) {
char* logBuffer = new char[logLength];
GLsizei bytesCopied;
glGetProgramInfoLog(programHandle, logLength, &bytesCopied, logBuffer);
(void)fprintf(stderr, "Program info log:\n%s\n", logBuffer);
delete [] logBuffer;
}
}
GLuint linkShaderProgram(const ShaderProgramSource* sources, size_t numSources) {
assert(numSources != 0);
GLuint programHandle = glCreateProgram();
if (programHandle != 0) {
for (int i = 0; i < numSources; ++i) {
GLuint shaderHandle = compileShader(sources[i].shaderType, sources[i].sourceFilename);
if (shaderHandle != 0) {
glAttachShader(programHandle, shaderHandle);
glDeleteShader(shaderHandle);
}
}
glLinkProgram(programHandle);
GLint linkStatus;
glGetProgramiv(programHandle, GL_LINK_STATUS, &linkStatus);
if (linkStatus == GL_TRUE) {
(void)printf("Shader link was successful!\n");
printProgramInfoLog(programHandle);
} else {
(void)fprintf(stderr, "Shader link failed!\n");
printProgramInfoLog(programHandle);
glDeleteProgram(programHandle);
programHandle = 0;
}
} else {
(void)fprintf(stderr, "Error creating shader program handle.\n");
exit(EXIT_FAILURE);
}
return programHandle;
}
int
main(int argc, char** argv) {
(void)argc;
(void)argv;
int retval = SDL_Init(SDL_INIT_VIDEO);
if (retval != 0) {
(void)fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
exit(EXIT_FAILURE);
}
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_ClearError();
SDL_Window* mainWindow = SDL_CreateWindow("Compiling a Shader",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
WINDOW_SIZE,
WINDOW_SIZE,
SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN);
if (mainWindow == NULL) {
(void)fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
exit(EXIT_FAILURE);
}
SDL_GLContext mainContext = SDL_GL_CreateContext(mainWindow);
if (mainContext == NULL) {
(void)fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
exit(EXIT_FAILURE);
}
GLenum err = glewInit();
if (err != GLEW_OK) {
(void)fprintf(stderr, "Error Initializing GLEW: %s\n", glewGetErrorString(err));
exit(EXIT_FAILURE);
}
ShaderProgramSource programSources[] = {{GL_VERTEX_SHADER, "basic.vert"},
{GL_FRAGMENT_SHADER, "basic.frag"}};
GLuint programHandle = linkShaderProgram(programSources, ARRAY_COUNT(programSources));
if (programHandle != 0) {
glUseProgram(programHandle);
}
SDL_GL_DeleteContext(mainContext);
SDL_DestroyWindow(mainWindow);
SDL_Quit();
return 0;
}
<commit_msg>Typo.<commit_after>#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <GL/glew.h>
#include <SDL2/SDL.h>
#include "FileUtil.h"
#define WINDOW_SIZE 640
#define ARRAY_COUNT(array) (sizeof(array) / sizeof(array[0]))
struct ShaderProgramSource {
GLenum shaderType;
const char* sourceFilename;
};
void printShaderInfoLog(GLuint shaderHandle, const char* name) {
GLint logLength;
glGetShaderiv(shaderHandle, GL_INFO_LOG_LENGTH, &logLength);
if (logLength > 0) {
char* logBuffer = new char[logLength];
GLsizei bytesCopied;
glGetShaderInfoLog(shaderHandle, logLength, &bytesCopied, logBuffer);
(void)fprintf(stderr, "Shader '%s' info log:\n%s\n", name, logBuffer);
delete [] logBuffer;
}
}
GLuint compileShader(GLenum shaderType, const char* filename) {
GLuint shaderHandle = glCreateShader(shaderType);
if (shaderHandle != 0) {
const GLchar* shaderCode = FileUtil::loadFileAsString(filename);
glShaderSource(shaderHandle, 1, &shaderCode, NULL);
delete [] shaderCode;
glCompileShader(shaderHandle);
GLint result;
glGetShaderiv(shaderHandle, GL_COMPILE_STATUS, &result);
if (result == GL_TRUE) {
(void)printf("Shader '%s' compilation was successful!\n", filename);
// Print warnings, if available
printShaderInfoLog(shaderHandle, filename);
} else {
(void)fprintf(stderr, "Shader compilation failed for '%s'!\n", filename);
printShaderInfoLog(shaderHandle, filename);
glDeleteShader(shaderHandle);
shaderHandle = 0;
}
} else {
(void)fprintf(stderr, "Error creating shader for '%s'.\n", filename);
}
return shaderHandle;
}
void printProgramInfoLog(GLuint programHandle) {
GLint logLength;
glGetProgramiv(programHandle, GL_INFO_LOG_LENGTH, &logLength);
if (logLength > 0) {
char* logBuffer = new char[logLength];
GLsizei bytesCopied;
glGetProgramInfoLog(programHandle, logLength, &bytesCopied, logBuffer);
(void)fprintf(stderr, "Program info log:\n%s\n", logBuffer);
delete [] logBuffer;
}
}
GLuint linkShaderProgram(const ShaderProgramSource* sources, size_t numSources) {
assert(numSources != 0);
GLuint programHandle = glCreateProgram();
if (programHandle != 0) {
for (int i = 0; i < numSources; ++i) {
GLuint shaderHandle = compileShader(sources[i].shaderType, sources[i].sourceFilename);
if (shaderHandle != 0) {
glAttachShader(programHandle, shaderHandle);
glDeleteShader(shaderHandle);
}
}
glLinkProgram(programHandle);
GLint linkStatus;
glGetProgramiv(programHandle, GL_LINK_STATUS, &linkStatus);
if (linkStatus == GL_TRUE) {
(void)printf("Shader link was successful!\n");
printProgramInfoLog(programHandle);
} else {
(void)fprintf(stderr, "Shader link failed!\n");
printProgramInfoLog(programHandle);
glDeleteProgram(programHandle);
programHandle = 0;
}
} else {
(void)fprintf(stderr, "Error creating shader program handle.\n");
exit(EXIT_FAILURE);
}
return programHandle;
}
int
main(int argc, char** argv) {
(void)argc;
(void)argv;
int retval = SDL_Init(SDL_INIT_VIDEO);
if (retval != 0) {
(void)fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
exit(EXIT_FAILURE);
}
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_ClearError();
SDL_Window* mainWindow = SDL_CreateWindow("Linking a Shader",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
WINDOW_SIZE,
WINDOW_SIZE,
SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN);
if (mainWindow == NULL) {
(void)fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
exit(EXIT_FAILURE);
}
SDL_GLContext mainContext = SDL_GL_CreateContext(mainWindow);
if (mainContext == NULL) {
(void)fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
exit(EXIT_FAILURE);
}
GLenum err = glewInit();
if (err != GLEW_OK) {
(void)fprintf(stderr, "Error Initializing GLEW: %s\n", glewGetErrorString(err));
exit(EXIT_FAILURE);
}
ShaderProgramSource programSources[] = {{GL_VERTEX_SHADER, "basic.vert"},
{GL_FRAGMENT_SHADER, "basic.frag"}};
GLuint programHandle = linkShaderProgram(programSources, ARRAY_COUNT(programSources));
if (programHandle != 0) {
glUseProgram(programHandle);
}
SDL_GL_DeleteContext(mainContext);
SDL_DestroyWindow(mainWindow);
SDL_Quit();
return 0;
}
<|endoftext|>
|
<commit_before>// __BEGIN_LICENSE__
// Copyright (c) 2009-2013, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NGT platform is 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.
// __END_LICENSE__
#include <asp/Core/Nvm.h>
#include <vw/Core/Exception.h>
#include <vw/Core/Log.h>
#include <vw/FileIO/FileUtils.h>
#include <fstream>
#include <iostream>
namespace asp {
// A wrapper to carry fewer things around
void ReadNVM(std::string const& input_filename, nvmData & nvm) {
ReadNVM(input_filename,
&nvm.cid_to_keypoint_map,
&nvm.cid_to_filename,
&nvm.pid_to_cid_fid,
&nvm.pid_to_xyz,
&nvm.cid_to_cam_t_global);
}
// Reads the NVM control network format.
void ReadNVM(std::string const& input_filename,
std::vector<Eigen::Matrix2Xd> * cid_to_keypoint_map,
std::vector<std::string> * cid_to_filename,
std::vector<std::map<int, int>> * pid_to_cid_fid,
std::vector<Eigen::Vector3d> * pid_to_xyz,
std::vector<Eigen::Affine3d> * cid_to_cam_t_global) {
std::ifstream f(input_filename, std::ios::in);
std::string token;
std::getline(f, token);
// Assert that we start with our NVM token
if (token.compare(0, 6, "NVM_V3") != 0) {
vw::vw_throw(vw::ArgumentErr() << "File doesn't start with NVM token.");
}
// Read the number of cameras
ptrdiff_t number_of_cid;
f >> number_of_cid;
if (number_of_cid < 1) {
vw::vw_throw(vw::ArgumentErr() << "NVM file is missing cameras.");
}
// Resize all our structures to support the number of cameras we now expect
cid_to_keypoint_map->resize(number_of_cid);
cid_to_filename->resize(number_of_cid);
cid_to_cam_t_global->resize(number_of_cid);
for (ptrdiff_t cid = 0; cid < number_of_cid; cid++) {
// Clear keypoints from map. We'll read these in shortly
cid_to_keypoint_map->at(cid).resize(Eigen::NoChange_t(), 2);
// Read the line that contains camera information
double focal, dist1, dist2;
Eigen::Quaterniond q;
Eigen::Vector3d c;
f >> token >> focal;
f >> q.w() >> q.x() >> q.y() >> q.z();
f >> c[0] >> c[1] >> c[2] >> dist1 >> dist2;
cid_to_filename->at(cid) = token;
// Solve for t, which is part of the affine transform
Eigen::Matrix3d r = q.matrix();
cid_to_cam_t_global->at(cid).linear() = r;
cid_to_cam_t_global->at(cid).translation() = -r * c;
}
// Read the number of points
ptrdiff_t number_of_pid;
f >> number_of_pid;
if (number_of_pid < 1)
vw::vw_throw(vw::ArgumentErr() << "The NVM file has no triangulated points.");
// Read the point
pid_to_cid_fid->resize(number_of_pid);
pid_to_xyz->resize(number_of_pid);
Eigen::Vector3d xyz;
Eigen::Vector3i color;
Eigen::Vector2d pt;
ptrdiff_t cid, fid;
for (ptrdiff_t pid = 0; pid < number_of_pid; pid++) {
pid_to_cid_fid->at(pid).clear();
ptrdiff_t number_of_measures;
f >> xyz[0] >> xyz[1] >> xyz[2] >>
color[0] >> color[1] >> color[2] >> number_of_measures;
pid_to_xyz->at(pid) = xyz;
for (ptrdiff_t m = 0; m < number_of_measures; m++) {
f >> cid >> fid >> pt[0] >> pt[1];
pid_to_cid_fid->at(pid)[cid] = fid;
if (cid_to_keypoint_map->at(cid).cols() <= fid) {
cid_to_keypoint_map->at(cid).conservativeResize(Eigen::NoChange_t(), fid + 1);
}
cid_to_keypoint_map->at(cid).col(fid) = pt;
}
if (!f.good())
vw::vw_throw(vw::ArgumentErr() << "Unable to correctly read PID: " << pid);
}
}
// Write an nvm file. Note that a single focal length is assumed and no distortion.
// Those are ignored, and only camera poses, matches, and keypoints are used.
void WriteNVM(std::vector<Eigen::Matrix2Xd> const& cid_to_keypoint_map,
std::vector<std::string> const& cid_to_filename,
std::vector<double> const& focal_lengths,
std::vector<std::map<int, int>> const& pid_to_cid_fid,
std::vector<Eigen::Vector3d> const& pid_to_xyz,
std::vector<Eigen::Affine3d> const& cid_to_cam_t_global,
std::string const& output_filename) {
// Ensure that the output directory having this file exists
vw::create_out_dir(output_filename);
vw::vw_out() << "Writing: " << output_filename << std::endl;
std::fstream f(output_filename, std::ios::out);
f.precision(17); // double precision
f << "NVM_V3\n";
if (cid_to_filename.size() != cid_to_keypoint_map.size())
vw::vw_throw(vw::ArgumentErr() << "Unequal number of filenames and keypoints.");
if (pid_to_cid_fid.size() != pid_to_xyz.size())
vw::vw_throw(vw::ArgumentErr() << "Unequal number of pid_to_cid_fid and xyz measurements.");
if (cid_to_filename.size() != cid_to_cam_t_global.size())
vw::vw_throw(vw::ArgumentErr() << "Unequal number of filename and camera transforms.");
// Write camera information
f << cid_to_filename.size() << std::endl;
for (size_t cid = 0; cid < cid_to_filename.size(); cid++) {
// World-to-camera rotation quaternion
Eigen::Quaterniond q(cid_to_cam_t_global[cid].rotation());
// Camera center in world coordinates
Eigen::Vector3d t(cid_to_cam_t_global[cid].translation());
Eigen::Vector3d camera_center =
- cid_to_cam_t_global[cid].rotation().inverse() * t;
f << cid_to_filename[cid] << " " << focal_lengths[cid]
<< " " << q.w() << " " << q.x() << " " << q.y() << " " << q.z() << " "
<< camera_center[0] << " " << camera_center[1] << " "
<< camera_center[2] << " " << "0 0\n"; // zero distortion, not used
}
// Write the number of points
f << pid_to_cid_fid.size() << std::endl;
for (size_t pid = 0; pid < pid_to_cid_fid.size(); pid++) {
f << pid_to_xyz[pid][0] << " " << pid_to_xyz[pid][1] << " "
<< pid_to_xyz[pid][2] << " 0 0 0 "
<< pid_to_cid_fid[pid].size();
if (pid_to_cid_fid[pid].size() <= 1)
vw::vw_throw(vw::ArgumentErr() << "PID " << pid << " has "
<< pid_to_cid_fid[pid].size() << " measurements.");
for (std::map<int, int>::const_iterator it = pid_to_cid_fid[pid].begin();
it != pid_to_cid_fid[pid].end(); it++) {
f << " " << it->first << " " << it->second << " "
<< cid_to_keypoint_map[it->first].col(it->second)[0] << " "
<< cid_to_keypoint_map[it->first].col(it->second)[1];
}
f << std::endl;
}
// Close the file
f.flush();
f.close();
}
} // end namespace asp
<commit_msg>Minor tuning of loading pairwise matches<commit_after>// __BEGIN_LICENSE__
// Copyright (c) 2009-2013, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NGT platform is 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.
// __END_LICENSE__
#include <asp/Core/Nvm.h>
#include <vw/Core/Exception.h>
#include <vw/Core/Log.h>
#include <vw/FileIO/FileUtils.h>
#include <fstream>
#include <iostream>
namespace asp {
// A wrapper to carry fewer things around
void ReadNVM(std::string const& input_filename, nvmData & nvm) {
ReadNVM(input_filename,
&nvm.cid_to_keypoint_map,
&nvm.cid_to_filename,
&nvm.pid_to_cid_fid,
&nvm.pid_to_xyz,
&nvm.cid_to_cam_t_global);
}
// Reads the NVM control network format. The interest points may or may not
// be shifted relative to optical center. The user is responsible for knowing that.
void ReadNVM(std::string const& input_filename,
std::vector<Eigen::Matrix2Xd> * cid_to_keypoint_map,
std::vector<std::string> * cid_to_filename,
std::vector<std::map<int, int>> * pid_to_cid_fid,
std::vector<Eigen::Vector3d> * pid_to_xyz,
std::vector<Eigen::Affine3d> * cid_to_cam_t_global) {
std::ifstream f(input_filename, std::ios::in);
std::string token;
std::getline(f, token);
// Assert that we start with our NVM token
if (token.compare(0, 6, "NVM_V3") != 0) {
vw::vw_throw(vw::ArgumentErr() << "File doesn't start with NVM token.");
}
// Read the number of cameras
ptrdiff_t number_of_cid;
f >> number_of_cid;
if (number_of_cid < 1) {
vw::vw_throw(vw::ArgumentErr() << "NVM file is missing cameras.");
}
// Resize all our structures to support the number of cameras we now expect
cid_to_keypoint_map->resize(number_of_cid);
cid_to_filename->resize(number_of_cid);
cid_to_cam_t_global->resize(number_of_cid);
for (ptrdiff_t cid = 0; cid < number_of_cid; cid++) {
// Clear keypoints from map. We'll read these in shortly
cid_to_keypoint_map->at(cid).resize(Eigen::NoChange_t(), 2);
// Read the line that contains camera information
double focal, dist1, dist2;
Eigen::Quaterniond q;
Eigen::Vector3d c;
f >> token >> focal;
f >> q.w() >> q.x() >> q.y() >> q.z();
f >> c[0] >> c[1] >> c[2] >> dist1 >> dist2;
cid_to_filename->at(cid) = token;
// Solve for t, which is part of the affine transform
Eigen::Matrix3d r = q.matrix();
cid_to_cam_t_global->at(cid).linear() = r;
cid_to_cam_t_global->at(cid).translation() = -r * c;
}
// Read the number of points
ptrdiff_t number_of_pid;
f >> number_of_pid;
if (number_of_pid < 1)
vw::vw_throw(vw::ArgumentErr() << "The NVM file has no triangulated points.");
// Read the point
pid_to_cid_fid->resize(number_of_pid);
pid_to_xyz->resize(number_of_pid);
Eigen::Vector3d xyz;
Eigen::Vector3i color;
Eigen::Vector2d pt;
ptrdiff_t cid, fid;
for (ptrdiff_t pid = 0; pid < number_of_pid; pid++) {
pid_to_cid_fid->at(pid).clear();
ptrdiff_t number_of_measures;
f >> xyz[0] >> xyz[1] >> xyz[2] >>
color[0] >> color[1] >> color[2] >> number_of_measures;
pid_to_xyz->at(pid) = xyz;
for (ptrdiff_t m = 0; m < number_of_measures; m++) {
f >> cid >> fid >> pt[0] >> pt[1];
pid_to_cid_fid->at(pid)[cid] = fid;
if (cid_to_keypoint_map->at(cid).cols() <= fid) {
cid_to_keypoint_map->at(cid).conservativeResize(Eigen::NoChange_t(), fid + 1);
}
cid_to_keypoint_map->at(cid).col(fid) = pt;
}
if (!f.good())
vw::vw_throw(vw::ArgumentErr() << "Unable to correctly read PID: " << pid);
}
}
// Write an nvm file. Note that a single focal length is assumed and no distortion.
// Those are ignored, and only camera poses, matches, and keypoints are used.
void WriteNVM(std::vector<Eigen::Matrix2Xd> const& cid_to_keypoint_map,
std::vector<std::string> const& cid_to_filename,
std::vector<double> const& focal_lengths,
std::vector<std::map<int, int>> const& pid_to_cid_fid,
std::vector<Eigen::Vector3d> const& pid_to_xyz,
std::vector<Eigen::Affine3d> const& cid_to_cam_t_global,
std::string const& output_filename) {
// Ensure that the output directory having this file exists
vw::create_out_dir(output_filename);
vw::vw_out() << "Writing: " << output_filename << std::endl;
std::fstream f(output_filename, std::ios::out);
f.precision(17); // double precision
f << "NVM_V3\n";
if (cid_to_filename.size() != cid_to_keypoint_map.size())
vw::vw_throw(vw::ArgumentErr() << "Unequal number of filenames and keypoints.");
if (pid_to_cid_fid.size() != pid_to_xyz.size())
vw::vw_throw(vw::ArgumentErr() << "Unequal number of pid_to_cid_fid and xyz measurements.");
if (cid_to_filename.size() != cid_to_cam_t_global.size())
vw::vw_throw(vw::ArgumentErr() << "Unequal number of filename and camera transforms.");
// Write camera information
f << cid_to_filename.size() << std::endl;
for (size_t cid = 0; cid < cid_to_filename.size(); cid++) {
// World-to-camera rotation quaternion
Eigen::Quaterniond q(cid_to_cam_t_global[cid].rotation());
// Camera center in world coordinates
Eigen::Vector3d t(cid_to_cam_t_global[cid].translation());
Eigen::Vector3d camera_center =
- cid_to_cam_t_global[cid].rotation().inverse() * t;
f << cid_to_filename[cid] << " " << focal_lengths[cid]
<< " " << q.w() << " " << q.x() << " " << q.y() << " " << q.z() << " "
<< camera_center[0] << " " << camera_center[1] << " "
<< camera_center[2] << " " << "0 0\n"; // zero distortion, not used
}
// Write the number of points
f << pid_to_cid_fid.size() << std::endl;
for (size_t pid = 0; pid < pid_to_cid_fid.size(); pid++) {
f << pid_to_xyz[pid][0] << " " << pid_to_xyz[pid][1] << " "
<< pid_to_xyz[pid][2] << " 0 0 0 "
<< pid_to_cid_fid[pid].size();
if (pid_to_cid_fid[pid].size() <= 1)
vw::vw_throw(vw::ArgumentErr() << "PID " << pid << " has "
<< pid_to_cid_fid[pid].size() << " measurements.");
for (std::map<int, int>::const_iterator it = pid_to_cid_fid[pid].begin();
it != pid_to_cid_fid[pid].end(); it++) {
f << " " << it->first << " " << it->second << " "
<< cid_to_keypoint_map[it->first].col(it->second)[0] << " "
<< cid_to_keypoint_map[it->first].col(it->second)[1];
}
f << std::endl;
}
// Close the file
f.flush();
f.close();
}
} // end namespace asp
<|endoftext|>
|
<commit_before>#ifndef __Data_student__
#define __Data_student__
#include "data-general.hpp"
#include "data-major.hpp"
#include "data-course.hpp"
using namespace std;
class Semester {
private:
int period;
public:
Semester() {
period = 0;
}
Semester(int p) {
period = p;
}
vector<Course> courses;
};
class Student {
private:
void init(string n, int s, int g, string m) {
name = n;
startingYear = s;
gradutationYear = g;
// parseMajors(m);
year1.push_back(Semester(1));
year1.push_back(Semester(2));
year1.push_back(Semester(3));
year2.push_back(Semester(1));
year2.push_back(Semester(2));
year2.push_back(Semester(3));
year3.push_back(Semester(1));
year3.push_back(Semester(2));
year3.push_back(Semester(3));
year4.push_back(Semester(1));
year4.push_back(Semester(2));
year4.push_back(Semester(3));
}
public:
string name;
int startingYear, gradutationYear;
vector<Major> majors;
vector<Semester> year1;//(3);
vector<Semester> year2;//(3);
vector<Semester> year3;//(3);
vector<Semester> year4;//(3);
Student() {
init("", 2000, 2004, "");
}
Student(string fn) {
ifstream infile;
infile.open(fn.c_str());
}
bool hasTakenCourse() {
return false;
}
ostream& getData(ostream &os) {
os << name << " ";
return os;
}
void display();
};
#endif
<commit_msg>Initial attempt at addCourse()<commit_after>#ifndef __Data_student__
#define __Data_student__
#include "data-general.hpp"
#include "data-major.hpp"
#include "data-course.hpp"
using namespace std;
class Semester {
private:
int period;
public:
Semester() {
period = 0;
}
Semester(int p) {
period = p;
}
vector<Course> courses;
};
class Student {
private:
void init(string n, int s, int g, string m) {
name = n;
startingYear = s;
gradutationYear = g;
// parseMajors(m);
year1.push_back(Semester(1));
year1.push_back(Semester(2));
year1.push_back(Semester(3));
year2.push_back(Semester(1));
year2.push_back(Semester(2));
year2.push_back(Semester(3));
year3.push_back(Semester(1));
year3.push_back(Semester(2));
year3.push_back(Semester(3));
year4.push_back(Semester(1));
year4.push_back(Semester(2));
year4.push_back(Semester(3));
}
public:
string name;
int startingYear, gradutationYear;
vector<Major> majors;
vector<Semester> year1;//(3);
vector<Semester> year2;//(3);
vector<Semester> year3;//(3);
vector<Semester> year4;//(3);
Student() {
init("", 2000, 2004, "");
}
Student(string fn) {
ifstream infile;
infile.open(fn.c_str());
}
bool hasTakenCourse() {
return false;
}
void addCourse(const Course& c, const Semester& s) {
// s.push_back();
}
ostream& getData(ostream &os) {
os << name << " ";
return os;
}
void display();
};
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: configmgr.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: mba $ $Date: 2000-11-30 09:11:37 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _UTL_CONFIGMGR_HXX_
#include "unotools/configmgr.hxx"
#endif
#ifndef _UTL_CONFIGITEM_HXX_
#include "unotools/configitem.hxx"
#endif
#ifndef _UNOTOOLS_PROCESSFACTORY_HXX_
#include <unotools/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALNAMEACCESS_HPP_
#include <com/sun/star/container/XHierarchicalNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#include <list>
//-----------------------------------------------------------------------------
using namespace utl;
using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::container;
#define C2U(cChar) OUString::createFromAscii(cChar)
//-----------------------------------------------------------------------------
const char* cConfigBaseURL = "/org.openoffice.";
//const char* cConfigBaseURL = "/com.sun.star.";
const char* cAccessSrvc = "com.sun.star.configuration.ConfigurationUpdateAccess";
//-----------------------------------------------------------------------------
struct ConfigItemListEntry_Impl
{
ConfigItem* pConfigItem;
ConfigItemListEntry_Impl(ConfigItem* pItem ) :
pConfigItem(pItem){}
};
typedef std::list<ConfigItemListEntry_Impl> ConfigItemList;
struct utl::ConfigMgr_Impl
{
ConfigItemList aItemList;
};
/* -----------------------------28.08.00 15:35--------------------------------
---------------------------------------------------------------------------*/
ConfigManager::ConfigManager() :
pMgrImpl(new utl::ConfigMgr_Impl)
{
}
/* -----------------------------17.11.00 13:51--------------------------------
---------------------------------------------------------------------------*/
ConfigManager::ConfigManager(Reference< XMultiServiceFactory > xConfigProv) :
pMgrImpl(new utl::ConfigMgr_Impl),
xConfigurationProvider(xConfigProv)
{
}
/* -----------------------------28.08.00 15:35--------------------------------
---------------------------------------------------------------------------*/
ConfigManager::~ConfigManager()
{
//check list content -> should be empty!
OSL_ENSHURE(pMgrImpl->aItemList.empty(), "some ConfigItems are still alive");
if(!pMgrImpl->aItemList.empty())
{
ConfigItemList::iterator aListIter;
for(aListIter = pMgrImpl->aItemList.begin(); aListIter != pMgrImpl->aItemList.end(); ++aListIter)
{
ConfigItemListEntry_Impl& rEntry = *aListIter;
rEntry.pConfigItem->ReleaseConfigMgr();
}
pMgrImpl->aItemList.erase(pMgrImpl->aItemList.begin(), pMgrImpl->aItemList.end());
}
delete pMgrImpl;
}
/* -----------------------------28.08.00 16:17--------------------------------
---------------------------------------------------------------------------*/
Reference< XMultiServiceFactory > ConfigManager::GetConfigurationProvider()
{
if(!xConfigurationProvider.is())
{
Reference< XMultiServiceFactory > xMSF = ::utl::getProcessServiceFactory();
Sequence <Any> aArgs(1);
Any* pValues = aArgs.getArray();
PropertyValue aPValue;
aPValue.Name = C2U("servertype");
aPValue.Value <<= C2U("plugin");
pValues[0] <<= aPValue;
xConfigurationProvider = Reference< XMultiServiceFactory >
(xMSF->createInstanceWithArguments(
C2U("com.sun.star.configuration.ConfigurationProvider"), aArgs),
UNO_QUERY);
}
return xConfigurationProvider;
}
/* -----------------------------29.08.00 12:35--------------------------------
---------------------------------------------------------------------------*/
Reference< XHierarchicalNameAccess > ConfigManager::AddConfigItem(utl::ConfigItem& rCfgItem)
{
ConfigItemList::iterator aListIter = pMgrImpl->aItemList.begin();
#ifdef DBG_UTIL
for(aListIter = pMgrImpl->aItemList.begin(); aListIter != pMgrImpl->aItemList.end(); ++aListIter)
{
ConfigItemListEntry_Impl& rEntry = *aListIter;
if(rEntry.pConfigItem == &rCfgItem)
OSL_DEBUG_ONLY("AddConfigItem: already inserted!");
}
#endif
OUString sPath = C2U(cConfigBaseURL);
sPath += rCfgItem.GetSubTreeName();
Sequence< Any > aArgs(1);
aArgs[0] <<= sPath;
Reference< XMultiServiceFactory > xCfgProvider = GetConfigurationProvider();
Reference< XInterface > xIFace;
try
{
xIFace = xCfgProvider->createInstanceWithArguments(
C2U(cAccessSrvc),
aArgs);
pMgrImpl->aItemList.insert(aListIter, ConfigItemListEntry_Impl(&rCfgItem));
#ifdef DEBUG
Reference<XNameAccess> xNA(xIFace, UNO_QUERY);
Sequence<OUString> aNames = xNA->getElementNames();
const OUString* pNames = aNames.getConstArray();
#endif
}
#ifdef DBG_UTIL
catch(Exception& rEx)
{
OString sMsg("CreateInstance exception: ");
sMsg += OString(rEx.Message.getStr(),
rEx.Message.getLength(),
RTL_TEXTENCODING_ASCII_US);
OSL_DEBUG_ONLY(sMsg.getStr());
}
#else
catch(Exception&){}
#endif
return Reference<XHierarchicalNameAccess>(xIFace, UNO_QUERY);
}
/* -----------------------------29.08.00 12:35--------------------------------
---------------------------------------------------------------------------*/
void ConfigManager::RemoveConfigItem(utl::ConfigItem& rCfgItem)
{
OSL_ENSHURE(!pMgrImpl->aItemList.empty(), "no ConfigItems available");
ConfigItemList::iterator aListIter = pMgrImpl->aItemList.begin();
for(aListIter = pMgrImpl->aItemList.begin(); aListIter != pMgrImpl->aItemList.end(); ++aListIter)
{
ConfigItemListEntry_Impl& rEntry = *aListIter;
if(rEntry.pConfigItem == &rCfgItem)
{
pMgrImpl->aItemList.erase(aListIter);
break;
}
}
}
/* -----------------------------30.08.00 15:04--------------------------------
---------------------------------------------------------------------------*/
void ConfigManager::StoreConfigItems()
{
if(!pMgrImpl->aItemList.empty())
{
ConfigItemList::iterator aListIter = pMgrImpl->aItemList.begin();
for(aListIter = pMgrImpl->aItemList.begin(); aListIter != pMgrImpl->aItemList.end(); ++aListIter)
{
ConfigItemListEntry_Impl& rEntry = *aListIter;
if(rEntry.pConfigItem->IsModified())
rEntry.pConfigItem->Commit();
}
}
}
ConfigManager* ConfigManager::pConfigManager = 0;
/* -----------------------------07.09.00 11:06--------------------------------
---------------------------------------------------------------------------*/
ConfigManager* ConfigManager::GetConfigManager()
{
if(!pConfigManager)
{
pConfigManager = new ConfigManager();
}
return pConfigManager;
}
/* -----------------------------07.09.00 11:06--------------------------------
---------------------------------------------------------------------------*/
void ConfigManager::RemoveConfigManager()
{
if(pConfigManager)
{
delete pConfigManager;
pConfigManager = 0;
}
}
/* -----------------------------08.09.00 13:22--------------------------------
---------------------------------------------------------------------------*/
rtl::OUString ConfigManager::GetConfigBaseURL()
{
return C2U(cConfigBaseURL);
}
/* -----------------------------25.09.00 16:34--------------------------------
---------------------------------------------------------------------------*/
Any ConfigManager::GetDirectConfigProperty(ConfigProperty eProp)
{
Any aRet;
OUString sPath = C2U(cConfigBaseURL);
switch(eProp)
{
case INSTALLPATH:
case USERINSTALLURL:
sPath += C2U("UserProfile/Office"); break;
case LOCALE: sPath += C2U("UserProfile/International"); break;
case PRODUCTNAME: sPath += C2U("Setup/Product"); break;
case OFFICEINSTALL:
case OFFICEINSTALLURL:
sPath += C2U("Office.Common/Path/Current"); break;
}
Sequence< Any > aArgs(1);
aArgs[0] <<= sPath;
Reference< XMultiServiceFactory > xCfgProvider = GetConfigManager()->GetConfigurationProvider();
Reference< XInterface > xIFace;
try
{
xIFace = xCfgProvider->createInstanceWithArguments(
C2U(cAccessSrvc),
aArgs);
}
catch(Exception&){}
Reference<XHierarchicalNameAccess> xHierarchyAccess(xIFace, UNO_QUERY);
if(xHierarchyAccess.is())
{
OUString sProperty;
switch(eProp)
{
case INSTALLPATH: sProperty = C2U("InstallPath"); break;
case LOCALE: sProperty = C2U("Locale"); break;
case PRODUCTNAME: sProperty = C2U("Name"); break;
case OFFICEINSTALL: sProperty = C2U("OfficeInstall"); break;
case USERINSTALLURL: sProperty = C2U("InstallURL"); break;
case OFFICEINSTALLURL: sProperty = C2U("OfficeInstallURL"); break;
}
try
{
aRet = xHierarchyAccess->getByHierarchicalName(sProperty);
}
catch(Exception&)
{
}
}
return aRet;
}
<commit_msg>#79541#: exchangeable product name cached<commit_after>/*************************************************************************
*
* $RCSfile: configmgr.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: mba $ $Date: 2000-12-08 08:56:14 $
*
* 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 _UTL_CONFIGMGR_HXX_
#include "unotools/configmgr.hxx"
#endif
#ifndef _UTL_CONFIGITEM_HXX_
#include "unotools/configitem.hxx"
#endif
#ifndef _UNOTOOLS_PROCESSFACTORY_HXX_
#include <unotools/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALNAMEACCESS_HPP_
#include <com/sun/star/container/XHierarchicalNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#include <list>
//-----------------------------------------------------------------------------
using namespace utl;
using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::container;
#define C2U(cChar) OUString::createFromAscii(cChar)
//-----------------------------------------------------------------------------
const char* cConfigBaseURL = "/org.openoffice.";
//const char* cConfigBaseURL = "/com.sun.star.";
const char* cAccessSrvc = "com.sun.star.configuration.ConfigurationUpdateAccess";
static ::rtl::OUString aBrandName;
//-----------------------------------------------------------------------------
struct ConfigItemListEntry_Impl
{
ConfigItem* pConfigItem;
ConfigItemListEntry_Impl(ConfigItem* pItem ) :
pConfigItem(pItem){}
};
typedef std::list<ConfigItemListEntry_Impl> ConfigItemList;
struct utl::ConfigMgr_Impl
{
ConfigItemList aItemList;
};
/* -----------------------------28.08.00 15:35--------------------------------
---------------------------------------------------------------------------*/
ConfigManager::ConfigManager() :
pMgrImpl(new utl::ConfigMgr_Impl)
{
}
/* -----------------------------17.11.00 13:51--------------------------------
---------------------------------------------------------------------------*/
ConfigManager::ConfigManager(Reference< XMultiServiceFactory > xConfigProv) :
pMgrImpl(new utl::ConfigMgr_Impl),
xConfigurationProvider(xConfigProv)
{
}
/* -----------------------------28.08.00 15:35--------------------------------
---------------------------------------------------------------------------*/
ConfigManager::~ConfigManager()
{
//check list content -> should be empty!
OSL_ENSHURE(pMgrImpl->aItemList.empty(), "some ConfigItems are still alive");
if(!pMgrImpl->aItemList.empty())
{
ConfigItemList::iterator aListIter;
for(aListIter = pMgrImpl->aItemList.begin(); aListIter != pMgrImpl->aItemList.end(); ++aListIter)
{
ConfigItemListEntry_Impl& rEntry = *aListIter;
rEntry.pConfigItem->ReleaseConfigMgr();
}
pMgrImpl->aItemList.erase(pMgrImpl->aItemList.begin(), pMgrImpl->aItemList.end());
}
delete pMgrImpl;
}
/* -----------------------------28.08.00 16:17--------------------------------
---------------------------------------------------------------------------*/
Reference< XMultiServiceFactory > ConfigManager::GetConfigurationProvider()
{
if(!xConfigurationProvider.is())
{
Reference< XMultiServiceFactory > xMSF = ::utl::getProcessServiceFactory();
Sequence <Any> aArgs(1);
Any* pValues = aArgs.getArray();
PropertyValue aPValue;
aPValue.Name = C2U("servertype");
aPValue.Value <<= C2U("plugin");
pValues[0] <<= aPValue;
xConfigurationProvider = Reference< XMultiServiceFactory >
(xMSF->createInstanceWithArguments(
C2U("com.sun.star.configuration.ConfigurationProvider"), aArgs),
UNO_QUERY);
}
return xConfigurationProvider;
}
/* -----------------------------29.08.00 12:35--------------------------------
---------------------------------------------------------------------------*/
Reference< XHierarchicalNameAccess > ConfigManager::AddConfigItem(utl::ConfigItem& rCfgItem)
{
ConfigItemList::iterator aListIter = pMgrImpl->aItemList.begin();
#ifdef DBG_UTIL
for(aListIter = pMgrImpl->aItemList.begin(); aListIter != pMgrImpl->aItemList.end(); ++aListIter)
{
ConfigItemListEntry_Impl& rEntry = *aListIter;
if(rEntry.pConfigItem == &rCfgItem)
OSL_DEBUG_ONLY("AddConfigItem: already inserted!");
}
#endif
OUString sPath = C2U(cConfigBaseURL);
sPath += rCfgItem.GetSubTreeName();
Sequence< Any > aArgs(1);
aArgs[0] <<= sPath;
Reference< XMultiServiceFactory > xCfgProvider = GetConfigurationProvider();
Reference< XInterface > xIFace;
try
{
xIFace = xCfgProvider->createInstanceWithArguments(
C2U(cAccessSrvc),
aArgs);
pMgrImpl->aItemList.insert(aListIter, ConfigItemListEntry_Impl(&rCfgItem));
#ifdef DEBUG
Reference<XNameAccess> xNA(xIFace, UNO_QUERY);
Sequence<OUString> aNames = xNA->getElementNames();
const OUString* pNames = aNames.getConstArray();
#endif
}
#ifdef DBG_UTIL
catch(Exception& rEx)
{
OString sMsg("CreateInstance exception: ");
sMsg += OString(rEx.Message.getStr(),
rEx.Message.getLength(),
RTL_TEXTENCODING_ASCII_US);
OSL_DEBUG_ONLY(sMsg.getStr());
}
#else
catch(Exception&){}
#endif
return Reference<XHierarchicalNameAccess>(xIFace, UNO_QUERY);
}
/* -----------------------------29.08.00 12:35--------------------------------
---------------------------------------------------------------------------*/
void ConfigManager::RemoveConfigItem(utl::ConfigItem& rCfgItem)
{
OSL_ENSHURE(!pMgrImpl->aItemList.empty(), "no ConfigItems available");
ConfigItemList::iterator aListIter = pMgrImpl->aItemList.begin();
for(aListIter = pMgrImpl->aItemList.begin(); aListIter != pMgrImpl->aItemList.end(); ++aListIter)
{
ConfigItemListEntry_Impl& rEntry = *aListIter;
if(rEntry.pConfigItem == &rCfgItem)
{
pMgrImpl->aItemList.erase(aListIter);
break;
}
}
}
/* -----------------------------30.08.00 15:04--------------------------------
---------------------------------------------------------------------------*/
void ConfigManager::StoreConfigItems()
{
if(!pMgrImpl->aItemList.empty())
{
ConfigItemList::iterator aListIter = pMgrImpl->aItemList.begin();
for(aListIter = pMgrImpl->aItemList.begin(); aListIter != pMgrImpl->aItemList.end(); ++aListIter)
{
ConfigItemListEntry_Impl& rEntry = *aListIter;
if(rEntry.pConfigItem->IsModified())
rEntry.pConfigItem->Commit();
}
}
}
ConfigManager* ConfigManager::pConfigManager = 0;
/* -----------------------------07.09.00 11:06--------------------------------
---------------------------------------------------------------------------*/
ConfigManager* ConfigManager::GetConfigManager()
{
if(!pConfigManager)
{
pConfigManager = new ConfigManager();
}
return pConfigManager;
}
/* -----------------------------07.09.00 11:06--------------------------------
---------------------------------------------------------------------------*/
void ConfigManager::RemoveConfigManager()
{
if(pConfigManager)
{
delete pConfigManager;
pConfigManager = 0;
}
}
/* -----------------------------08.09.00 13:22--------------------------------
---------------------------------------------------------------------------*/
rtl::OUString ConfigManager::GetConfigBaseURL()
{
return C2U(cConfigBaseURL);
}
/* -----------------------------25.09.00 16:34--------------------------------
---------------------------------------------------------------------------*/
Any ConfigManager::GetDirectConfigProperty(ConfigProperty eProp)
{
Any aRet;
if ( eProp == PRODUCTNAME && aBrandName.getLength() )
{
aRet <<= aBrandName;
return aRet;
}
OUString sPath = C2U(cConfigBaseURL);
switch(eProp)
{
case INSTALLPATH:
case USERINSTALLURL:
sPath += C2U("UserProfile/Office"); break;
case LOCALE: sPath += C2U("UserProfile/International"); break;
case PRODUCTNAME: sPath += C2U("Setup/Product"); break;
case OFFICEINSTALL:
case OFFICEINSTALLURL:
sPath += C2U("Office.Common/Path/Current"); break;
}
Sequence< Any > aArgs(1);
aArgs[0] <<= sPath;
Reference< XMultiServiceFactory > xCfgProvider = GetConfigManager()->GetConfigurationProvider();
Reference< XInterface > xIFace;
try
{
xIFace = xCfgProvider->createInstanceWithArguments(
C2U(cAccessSrvc),
aArgs);
}
catch(Exception&){}
Reference<XHierarchicalNameAccess> xHierarchyAccess(xIFace, UNO_QUERY);
if(xHierarchyAccess.is())
{
OUString sProperty;
switch(eProp)
{
case INSTALLPATH: sProperty = C2U("InstallPath"); break;
case LOCALE: sProperty = C2U("Locale"); break;
case PRODUCTNAME: sProperty = C2U("Name"); break;
case OFFICEINSTALL: sProperty = C2U("OfficeInstall"); break;
case USERINSTALLURL: sProperty = C2U("InstallURL"); break;
case OFFICEINSTALLURL: sProperty = C2U("OfficeInstallURL"); break;
}
try
{
aRet = xHierarchyAccess->getByHierarchicalName(sProperty);
}
catch(Exception&)
{
}
}
if ( eProp == PRODUCTNAME )
aRet >>= aBrandName;
return aRet;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
* Copyright (C) 2012-2015 by Savoir-Faire Linux *
* Author : Emmanuel Lepage Vallee <emmanuel.lepage@savoirfairelinux.com> *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#include "availableaccountmodel.h"
//Qt
#include <QtCore/QItemSelectionModel>
#include <QtCore/QCoreApplication>
//DRing
#include <account_const.h>
//Ring
#include "private/accountmodel_p.h"
#include "contactmethod.h"
#include "uri.h"
class AvailableAccountModelPrivate : public QObject
{
Q_OBJECT
public:
AvailableAccountModelPrivate(AvailableAccountModel* parent);
QItemSelectionModel* m_pSelectionModel;
static Account* m_spPriorAccount ;
static AvailableAccountModel* m_spInstance ;
static void setPriorAccount ( const Account* account );
static Account* firstRegisteredAccount( URI::SchemeType type = URI::SchemeType::NONE );
AvailableAccountModel* q_ptr;
public Q_SLOTS:
void checkRemovedAccount(Account* a);
void checkStateChanges(Account* account, const Account::RegistrationState state);
void selectionChanged(const QModelIndex& idx, const QModelIndex& previous);
};
Account* AvailableAccountModelPrivate::m_spPriorAccount = nullptr;
AvailableAccountModel* AvailableAccountModelPrivate::m_spInstance = nullptr;
AvailableAccountModelPrivate::AvailableAccountModelPrivate(AvailableAccountModel* parent) :m_pSelectionModel(nullptr),q_ptr(parent)
{
connect(AccountModel::instance(), &AccountModel::accountRemoved , this, &AvailableAccountModelPrivate::checkRemovedAccount );
connect(AccountModel::instance(), &AccountModel::accountStateChanged, this, &AvailableAccountModelPrivate::checkStateChanges );
}
AvailableAccountModel::AvailableAccountModel(QObject* parent) : QSortFilterProxyModel(parent),
d_ptr(new AvailableAccountModelPrivate(this))
{
setSourceModel(AccountModel::instance());
}
AvailableAccountModel* AvailableAccountModel::instance()
{
if (!AvailableAccountModelPrivate::m_spInstance)
AvailableAccountModelPrivate::m_spInstance = new AvailableAccountModel(QCoreApplication::instance());
return AvailableAccountModelPrivate::m_spInstance;
}
//Do not show the checkbox
QVariant AvailableAccountModel::data(const QModelIndex& idx,int role ) const
{
return (role == Qt::CheckStateRole) ? QVariant() : mapToSource(idx).data(role);
}
///Disable the unavailable accounts
Qt::ItemFlags AvailableAccountModel::flags (const QModelIndex& idx) const
{
const QModelIndex& src = mapToSource(idx);
if (qvariant_cast<Account::RegistrationState>(src.data(static_cast<int>(Account::Role::RegistrationState))) != Account::RegistrationState::READY)
return Qt::NoItemFlags;
return sourceModel()->flags(idx);
}
//Do not display disabled account
bool AvailableAccountModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
{
return sourceModel()->index(source_row,0,source_parent).data(Qt::CheckStateRole) == Qt::Checked;
}
///Return the current account
Account* AvailableAccountModel::currentDefaultAccount(ContactMethod* method)
{
Account* priorAccount = AvailableAccountModelPrivate::m_spPriorAccount;
URI::SchemeType type = (!method) ? URI::SchemeType::NONE : method->uri().schemeType();
/* if the scheme type could not be strictly determinded, try using the
* protocol hint
*/
if (type == URI::SchemeType::NONE && method) {
switch (method->protocolHint()) {
case URI::ProtocolHint::SIP_OTHER:
case URI::ProtocolHint::SIP_HOST:
type = URI::SchemeType::SIP;
break;
case URI::ProtocolHint::IAX:
type = URI::SchemeType::IAX;
break;
case URI::ProtocolHint::IP:
break;
case URI::ProtocolHint::RING:
type = URI::SchemeType::RING;
break;
}
}
if(priorAccount
&& priorAccount->registrationState() == Account::RegistrationState::READY
&& priorAccount->isEnabled()
&& (priorAccount->supportScheme(type))
) {
return priorAccount;
}
else {
Account* a = AvailableAccountModelPrivate::firstRegisteredAccount(type);
if (!a)
a = AccountModel::instance()->getById(DRing::Account::ProtocolNames::IP2IP);
AvailableAccountModelPrivate::setPriorAccount(a);
return a;
}
} //getCurrentAccount
Account* AvailableAccountModel::currentDefaultAccount(URI::SchemeType schemeType)
{
return AvailableAccountModelPrivate::firstRegisteredAccount(schemeType);
}
///Set the previous account used
void AvailableAccountModelPrivate::setPriorAccount(const Account* account) {
const bool changed = (account && m_spPriorAccount != account) || (!account && m_spPriorAccount);
m_spPriorAccount = const_cast<Account*>(account);
if (changed) {
AvailableAccountModel* self = AvailableAccountModel::instance();
Account* a = self->currentDefaultAccount();
emit self->currentDefaultAccountChanged(a);
if (self->d_ptr->m_pSelectionModel) {
self->d_ptr->m_pSelectionModel->setCurrentIndex(self->mapFromSource(a->index()), QItemSelectionModel::ClearAndSelect);
}
}
}
///Get the first registerred account (default account)
Account* AvailableAccountModelPrivate::firstRegisteredAccount(URI::SchemeType type)
{
for (Account* current : AccountModel::instance()->d_ptr->m_lAccounts) {
if(current
&& current->registrationState() == Account::RegistrationState::READY
&& current->isEnabled()
&& current->supportScheme(type)
)
return current;
}
return nullptr;
}
QItemSelectionModel* AvailableAccountModel::selectionModel() const
{
if (!d_ptr->m_pSelectionModel) {
d_ptr->m_pSelectionModel = new QItemSelectionModel(const_cast<AvailableAccountModel*>(this));
connect(d_ptr->m_pSelectionModel, &QItemSelectionModel::currentChanged,d_ptr,&AvailableAccountModelPrivate::selectionChanged);
Account* a = d_ptr->firstRegisteredAccount();
if (a)
d_ptr->m_pSelectionModel->setCurrentIndex(mapFromSource(a->index()), QItemSelectionModel::ClearAndSelect);
}
return d_ptr->m_pSelectionModel;
}
void AvailableAccountModelPrivate::selectionChanged(const QModelIndex& idx, const QModelIndex& previous)
{
Q_UNUSED(previous)
Account* a = qvariant_cast<Account*>(idx.data(static_cast<int>(Account::Role::Object)));
setPriorAccount(a);
}
void AvailableAccountModelPrivate::checkRemovedAccount(Account* a)
{
if (a == m_spPriorAccount) {
Account* a = firstRegisteredAccount();
qDebug() << "The current default account has been removed, now defaulting to" << a;
setPriorAccount(a);
}
}
void AvailableAccountModelPrivate::checkStateChanges(Account* account, const Account::RegistrationState state)
{
Q_UNUSED(account)
Q_UNUSED(state)
Account* a = firstRegisteredAccount();
if ( m_spPriorAccount != a ) {
qDebug() << "The current default account changed to" << a;
setPriorAccount(a);
}
}
#include <availableaccountmodel.moc>
<commit_msg>account: Avoid IP2IP when guessing the best account<commit_after>/****************************************************************************
* Copyright (C) 2012-2015 by Savoir-Faire Linux *
* Author : Emmanuel Lepage Vallee <emmanuel.lepage@savoirfairelinux.com> *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#include "availableaccountmodel.h"
//Qt
#include <QtCore/QItemSelectionModel>
#include <QtCore/QCoreApplication>
//DRing
#include <account_const.h>
//Ring
#include "private/accountmodel_p.h"
#include "contactmethod.h"
#include "uri.h"
class AvailableAccountModelPrivate : public QObject
{
Q_OBJECT
public:
AvailableAccountModelPrivate(AvailableAccountModel* parent);
QItemSelectionModel* m_pSelectionModel;
static Account* m_spPriorAccount ;
static AvailableAccountModel* m_spInstance ;
static void setPriorAccount ( const Account* account );
static Account* firstRegisteredAccount( URI::SchemeType type = URI::SchemeType::NONE );
AvailableAccountModel* q_ptr;
public Q_SLOTS:
void checkRemovedAccount(Account* a);
void checkStateChanges(Account* account, const Account::RegistrationState state);
void selectionChanged(const QModelIndex& idx, const QModelIndex& previous);
};
Account* AvailableAccountModelPrivate::m_spPriorAccount = nullptr;
AvailableAccountModel* AvailableAccountModelPrivate::m_spInstance = nullptr;
AvailableAccountModelPrivate::AvailableAccountModelPrivate(AvailableAccountModel* parent) :m_pSelectionModel(nullptr),q_ptr(parent)
{
connect(AccountModel::instance(), &AccountModel::accountRemoved , this, &AvailableAccountModelPrivate::checkRemovedAccount );
connect(AccountModel::instance(), &AccountModel::accountStateChanged, this, &AvailableAccountModelPrivate::checkStateChanges );
}
AvailableAccountModel::AvailableAccountModel(QObject* parent) : QSortFilterProxyModel(parent),
d_ptr(new AvailableAccountModelPrivate(this))
{
setSourceModel(AccountModel::instance());
}
AvailableAccountModel* AvailableAccountModel::instance()
{
if (!AvailableAccountModelPrivate::m_spInstance)
AvailableAccountModelPrivate::m_spInstance = new AvailableAccountModel(QCoreApplication::instance());
return AvailableAccountModelPrivate::m_spInstance;
}
//Do not show the checkbox
QVariant AvailableAccountModel::data(const QModelIndex& idx,int role ) const
{
return (role == Qt::CheckStateRole) ? QVariant() : mapToSource(idx).data(role);
}
///Disable the unavailable accounts
Qt::ItemFlags AvailableAccountModel::flags (const QModelIndex& idx) const
{
const QModelIndex& src = mapToSource(idx);
if (qvariant_cast<Account::RegistrationState>(src.data(static_cast<int>(Account::Role::RegistrationState))) != Account::RegistrationState::READY)
return Qt::NoItemFlags;
return sourceModel()->flags(idx);
}
//Do not display disabled account
bool AvailableAccountModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
{
return sourceModel()->index(source_row,0,source_parent).data(Qt::CheckStateRole) == Qt::Checked;
}
///Return the current account
Account* AvailableAccountModel::currentDefaultAccount(ContactMethod* method)
{
static Account* ip2ip = AccountModel::instance()->getById(DRing::Account::ProtocolNames::IP2IP);
Account* priorAccount = AvailableAccountModelPrivate::m_spPriorAccount;
//Ip2Ip is a bad prior account, using it cause issues down in this code
if (priorAccount && priorAccount == ip2ip)
priorAccount = nullptr;
URI::SchemeType type = (!method) ? URI::SchemeType::NONE : method->uri().schemeType();
/* if the scheme type could not be strictly determined, try using the
* protocol hint
*/
if (type == URI::SchemeType::NONE && method) {
switch (method->protocolHint()) {
case URI::ProtocolHint::SIP_OTHER:
case URI::ProtocolHint::SIP_HOST:
type = URI::SchemeType::SIP;
break;
case URI::ProtocolHint::IAX:
type = URI::SchemeType::IAX;
break;
case URI::ProtocolHint::IP:
break;
case URI::ProtocolHint::RING:
type = URI::SchemeType::RING;
break;
}
}
if(priorAccount
&& priorAccount->registrationState() == Account::RegistrationState::READY
&& priorAccount->isEnabled()
&& (priorAccount->supportScheme(type))
) {
return priorAccount;
}
else {
Account* a = AvailableAccountModelPrivate::firstRegisteredAccount(type);
if (!a)
a = ip2ip;
AvailableAccountModelPrivate::setPriorAccount(a);
return a;
}
} //getCurrentAccount
Account* AvailableAccountModel::currentDefaultAccount(URI::SchemeType schemeType)
{
return AvailableAccountModelPrivate::firstRegisteredAccount(schemeType);
}
///Set the previous account used
void AvailableAccountModelPrivate::setPriorAccount(const Account* account) {
const bool changed = (account && m_spPriorAccount != account) || (!account && m_spPriorAccount);
m_spPriorAccount = const_cast<Account*>(account);
if (changed) {
AvailableAccountModel* self = AvailableAccountModel::instance();
Account* a = self->currentDefaultAccount();
emit self->currentDefaultAccountChanged(a);
if (self->d_ptr->m_pSelectionModel) {
self->d_ptr->m_pSelectionModel->setCurrentIndex(self->mapFromSource(a->index()), QItemSelectionModel::ClearAndSelect);
}
}
}
///Get the first registerred account (default account)
Account* AvailableAccountModelPrivate::firstRegisteredAccount(URI::SchemeType type)
{
for (Account* current : AccountModel::instance()->d_ptr->m_lAccounts) {
if(current
&& current->registrationState() == Account::RegistrationState::READY
&& current->isEnabled()
&& current->supportScheme(type)
)
return current;
}
return nullptr;
}
QItemSelectionModel* AvailableAccountModel::selectionModel() const
{
if (!d_ptr->m_pSelectionModel) {
d_ptr->m_pSelectionModel = new QItemSelectionModel(const_cast<AvailableAccountModel*>(this));
connect(d_ptr->m_pSelectionModel, &QItemSelectionModel::currentChanged,d_ptr,&AvailableAccountModelPrivate::selectionChanged);
Account* a = d_ptr->firstRegisteredAccount();
if (a)
d_ptr->m_pSelectionModel->setCurrentIndex(mapFromSource(a->index()), QItemSelectionModel::ClearAndSelect);
}
return d_ptr->m_pSelectionModel;
}
void AvailableAccountModelPrivate::selectionChanged(const QModelIndex& idx, const QModelIndex& previous)
{
Q_UNUSED(previous)
Account* a = qvariant_cast<Account*>(idx.data(static_cast<int>(Account::Role::Object)));
setPriorAccount(a);
}
void AvailableAccountModelPrivate::checkRemovedAccount(Account* a)
{
if (a == m_spPriorAccount) {
Account* a = firstRegisteredAccount();
qDebug() << "The current default account has been removed, now defaulting to" << a;
setPriorAccount(a);
}
}
void AvailableAccountModelPrivate::checkStateChanges(Account* account, const Account::RegistrationState state)
{
Q_UNUSED(account)
Q_UNUSED(state)
Account* a = firstRegisteredAccount();
if ( m_spPriorAccount != a ) {
qDebug() << "The current default account changed to" << a;
setPriorAccount(a);
}
}
#include <availableaccountmodel.moc>
<|endoftext|>
|
<commit_before>/////////////////////////////////////////////////////////////////////////
// $Id: fpu_const.cc,v 1.15 2009/03/10 21:43:11 sshwarts Exp $
/////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2003 Stanislav Shwartsman
// Written by Stanislav Shwartsman [sshwarts at sourceforge net]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
/////////////////////////////////////////////////////////////////////////
#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#include "cpu/cpu.h"
#define LOG_THIS BX_CPU_THIS_PTR
#if BX_SUPPORT_FPU
#include "softfloatx80.h"
const floatx80 Const_QNaN = packFloatx80(0, floatx80_default_nan_exp, floatx80_default_nan_fraction);
const floatx80 Const_Z = packFloatx80(0, 0x0000, 0);
const floatx80 Const_1 = packFloatx80(0, 0x3fff, BX_CONST64(0x8000000000000000));
const floatx80 Const_L2T = packFloatx80(0, 0x4000, BX_CONST64(0xd49a784bcd1b8afe));
const floatx80 Const_L2E = packFloatx80(0, 0x3fff, BX_CONST64(0xb8aa3b295c17f0bc));
const floatx80 Const_PI = packFloatx80(0, 0x4000, BX_CONST64(0xc90fdaa22168c235));
const floatx80 Const_LG2 = packFloatx80(0, 0x3ffd, BX_CONST64(0x9a209a84fbcff799));
const floatx80 Const_LN2 = packFloatx80(0, 0x3ffe, BX_CONST64(0xb17217f7d1cf79ac));
const floatx80 Const_INF = packFloatx80(0, 0x7fff, BX_CONST64(0x8000000000000000));
/* A fast way to find out whether x is one of RC_DOWN or RC_CHOP
(and not one of RC_RND or RC_UP).
*/
#define DOWN_OR_CHOP() (FPU_CONTROL_WORD & FPU_CW_RC & FPU_RC_DOWN)
BX_CPP_INLINE floatx80 FPU_round_const(const floatx80 &a, int adj)
{
floatx80 result = a;
result.fraction += adj;
return result;
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::FLDL2T(bxInstruction_c *i)
{
#if BX_SUPPORT_FPU
BX_CPU_THIS_PTR prepareFPU(i);
clear_C1();
if (! IS_TAG_EMPTY(-1))
{
BX_CPU_THIS_PTR FPU_stack_overflow();
}
else {
BX_CPU_THIS_PTR the_i387.FPU_push();
BX_WRITE_FPU_REG(FPU_round_const(Const_L2T, (FPU_CONTROL_WORD == FPU_RC_UP) ? 1 : 0), 0);
}
#else
BX_INFO(("FLDL2T: required FPU, configure --enable-fpu"));
#endif
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::FLDL2E(bxInstruction_c *i)
{
#if BX_SUPPORT_FPU
BX_CPU_THIS_PTR prepareFPU(i);
clear_C1();
if (! IS_TAG_EMPTY(-1))
{
BX_CPU_THIS_PTR FPU_stack_overflow();
}
else {
BX_CPU_THIS_PTR the_i387.FPU_push();
BX_WRITE_FPU_REG(FPU_round_const(Const_L2E, DOWN_OR_CHOP() ? -1 : 0), 0);
}
#else
BX_INFO(("FLDL2E: required FPU, configure --enable-fpu"));
#endif
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::FLDPI(bxInstruction_c *i)
{
#if BX_SUPPORT_FPU
BX_CPU_THIS_PTR prepareFPU(i);
clear_C1();
if (! IS_TAG_EMPTY(-1))
{
BX_CPU_THIS_PTR FPU_stack_overflow();
}
else {
BX_CPU_THIS_PTR the_i387.FPU_push();
BX_WRITE_FPU_REG(FPU_round_const(Const_PI, DOWN_OR_CHOP() ? -1 : 0), 0);
}
#else
BX_INFO(("FLDPI: required FPU, configure --enable-fpu"));
#endif
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::FLDLG2(bxInstruction_c *i)
{
#if BX_SUPPORT_FPU
BX_CPU_THIS_PTR prepareFPU(i);
clear_C1();
if (! IS_TAG_EMPTY(-1))
{
BX_CPU_THIS_PTR FPU_stack_overflow();
}
else {
BX_CPU_THIS_PTR the_i387.FPU_push();
BX_WRITE_FPU_REG(FPU_round_const(Const_LG2, DOWN_OR_CHOP() ? -1 : 0), 0);
}
#else
BX_INFO(("FLDLG2: required FPU, configure --enable-fpu"));
#endif
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::FLDLN2(bxInstruction_c *i)
{
#if BX_SUPPORT_FPU
BX_CPU_THIS_PTR prepareFPU(i);
clear_C1();
if (! IS_TAG_EMPTY(-1))
{
BX_CPU_THIS_PTR FPU_stack_overflow();
}
else {
BX_CPU_THIS_PTR the_i387.FPU_push();
BX_WRITE_FPU_REG(FPU_round_const(Const_LN2, DOWN_OR_CHOP() ? -1 : 0), 0);
}
#else
BX_INFO(("FLDLN2: required FPU, configure --enable-fpu"));
#endif
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::FLD1(bxInstruction_c *i)
{
#if BX_SUPPORT_FPU
BX_CPU_THIS_PTR prepareFPU(i);
clear_C1();
if (! IS_TAG_EMPTY(-1))
{
BX_CPU_THIS_PTR FPU_stack_overflow();
}
else {
BX_CPU_THIS_PTR the_i387.FPU_push();
BX_WRITE_FPU_REG(Const_1, 0);
}
#else
BX_INFO(("FLD1: required FPU, configure --enable-fpu"));
#endif
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::FLDZ(bxInstruction_c *i)
{
#if BX_SUPPORT_FPU
BX_CPU_THIS_PTR prepareFPU(i);
clear_C1();
if (! IS_TAG_EMPTY(-1))
{
BX_CPU_THIS_PTR FPU_stack_overflow();
}
else {
BX_CPU_THIS_PTR the_i387.FPU_push();
BX_WRITE_FPU_REG(Const_Z, 0);
}
#else
BX_INFO(("FLDZ: required FPU, configure --enable-fpu"));
#endif
}
#endif
<commit_msg>Fixed FLDL2T instruction<commit_after>/////////////////////////////////////////////////////////////////////////
// $Id: fpu_const.cc,v 1.16 2009/04/13 08:37:49 sshwarts Exp $
/////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2003 Stanislav Shwartsman
// Written by Stanislav Shwartsman [sshwarts at sourceforge net]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
/////////////////////////////////////////////////////////////////////////
#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#include "cpu/cpu.h"
#define LOG_THIS BX_CPU_THIS_PTR
#if BX_SUPPORT_FPU
#include "softfloatx80.h"
const floatx80 Const_QNaN = packFloatx80(0, floatx80_default_nan_exp, floatx80_default_nan_fraction);
const floatx80 Const_Z = packFloatx80(0, 0x0000, 0);
const floatx80 Const_1 = packFloatx80(0, 0x3fff, BX_CONST64(0x8000000000000000));
const floatx80 Const_L2T = packFloatx80(0, 0x4000, BX_CONST64(0xd49a784bcd1b8afe));
const floatx80 Const_L2E = packFloatx80(0, 0x3fff, BX_CONST64(0xb8aa3b295c17f0bc));
const floatx80 Const_PI = packFloatx80(0, 0x4000, BX_CONST64(0xc90fdaa22168c235));
const floatx80 Const_LG2 = packFloatx80(0, 0x3ffd, BX_CONST64(0x9a209a84fbcff799));
const floatx80 Const_LN2 = packFloatx80(0, 0x3ffe, BX_CONST64(0xb17217f7d1cf79ac));
const floatx80 Const_INF = packFloatx80(0, 0x7fff, BX_CONST64(0x8000000000000000));
/* A fast way to find out whether x is one of RC_DOWN or RC_CHOP
(and not one of RC_RND or RC_UP).
*/
#define DOWN_OR_CHOP() (FPU_CONTROL_WORD & FPU_CW_RC & FPU_RC_DOWN)
BX_CPP_INLINE floatx80 FPU_round_const(const floatx80 &a, int adj)
{
floatx80 result = a;
result.fraction += adj;
return result;
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::FLDL2T(bxInstruction_c *i)
{
#if BX_SUPPORT_FPU
BX_CPU_THIS_PTR prepareFPU(i);
clear_C1();
if (! IS_TAG_EMPTY(-1))
{
BX_CPU_THIS_PTR FPU_stack_overflow();
}
else {
BX_CPU_THIS_PTR the_i387.FPU_push();
BX_WRITE_FPU_REG(FPU_round_const(Const_L2T, (FPU_CONTROL_WORD & FPU_CW_RC) == FPU_RC_UP), 0);
}
#else
BX_INFO(("FLDL2T: required FPU, configure --enable-fpu"));
#endif
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::FLDL2E(bxInstruction_c *i)
{
#if BX_SUPPORT_FPU
BX_CPU_THIS_PTR prepareFPU(i);
clear_C1();
if (! IS_TAG_EMPTY(-1))
{
BX_CPU_THIS_PTR FPU_stack_overflow();
}
else {
BX_CPU_THIS_PTR the_i387.FPU_push();
BX_WRITE_FPU_REG(FPU_round_const(Const_L2E, DOWN_OR_CHOP() ? -1 : 0), 0);
}
#else
BX_INFO(("FLDL2E: required FPU, configure --enable-fpu"));
#endif
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::FLDPI(bxInstruction_c *i)
{
#if BX_SUPPORT_FPU
BX_CPU_THIS_PTR prepareFPU(i);
clear_C1();
if (! IS_TAG_EMPTY(-1))
{
BX_CPU_THIS_PTR FPU_stack_overflow();
}
else {
BX_CPU_THIS_PTR the_i387.FPU_push();
BX_WRITE_FPU_REG(FPU_round_const(Const_PI, DOWN_OR_CHOP() ? -1 : 0), 0);
}
#else
BX_INFO(("FLDPI: required FPU, configure --enable-fpu"));
#endif
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::FLDLG2(bxInstruction_c *i)
{
#if BX_SUPPORT_FPU
BX_CPU_THIS_PTR prepareFPU(i);
clear_C1();
if (! IS_TAG_EMPTY(-1))
{
BX_CPU_THIS_PTR FPU_stack_overflow();
}
else {
BX_CPU_THIS_PTR the_i387.FPU_push();
BX_WRITE_FPU_REG(FPU_round_const(Const_LG2, DOWN_OR_CHOP() ? -1 : 0), 0);
}
#else
BX_INFO(("FLDLG2: required FPU, configure --enable-fpu"));
#endif
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::FLDLN2(bxInstruction_c *i)
{
#if BX_SUPPORT_FPU
BX_CPU_THIS_PTR prepareFPU(i);
clear_C1();
if (! IS_TAG_EMPTY(-1))
{
BX_CPU_THIS_PTR FPU_stack_overflow();
}
else {
BX_CPU_THIS_PTR the_i387.FPU_push();
BX_WRITE_FPU_REG(FPU_round_const(Const_LN2, DOWN_OR_CHOP() ? -1 : 0), 0);
}
#else
BX_INFO(("FLDLN2: required FPU, configure --enable-fpu"));
#endif
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::FLD1(bxInstruction_c *i)
{
#if BX_SUPPORT_FPU
BX_CPU_THIS_PTR prepareFPU(i);
clear_C1();
if (! IS_TAG_EMPTY(-1))
{
BX_CPU_THIS_PTR FPU_stack_overflow();
}
else {
BX_CPU_THIS_PTR the_i387.FPU_push();
BX_WRITE_FPU_REG(Const_1, 0);
}
#else
BX_INFO(("FLD1: required FPU, configure --enable-fpu"));
#endif
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::FLDZ(bxInstruction_c *i)
{
#if BX_SUPPORT_FPU
BX_CPU_THIS_PTR prepareFPU(i);
clear_C1();
if (! IS_TAG_EMPTY(-1))
{
BX_CPU_THIS_PTR FPU_stack_overflow();
}
else {
BX_CPU_THIS_PTR the_i387.FPU_push();
BX_WRITE_FPU_REG(Const_Z, 0);
}
#else
BX_INFO(("FLDZ: required FPU, configure --enable-fpu"));
#endif
}
#endif
<|endoftext|>
|
<commit_before>/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include <boost/make_shared.hpp>
#include <qitype/genericobject.hpp>
#include "boundobject.hpp"
#include "serverresult.hpp"
qiLogCategory("qimessaging.boundobject");
static const int gObjectOffset = 100;
namespace qi {
static GenericValuePtr forwardEvent(const GenericFunctionParameters& params,
unsigned int service, unsigned int object,
unsigned int event, TransportSocketPtr client,
ObjectHost* context)
{
qi::Message msg;
msg.setValues(params, context);
msg.setService(service);
msg.setFunction(event);
msg.setType(Message::Type_Event);
msg.setObject(object);
client->send(msg);
return GenericValuePtr();
}
ServiceBoundObject::ServiceBoundObject(unsigned int serviceId, unsigned int objectId,
qi::ObjectPtr object,
qi::MetaCallType mct,
bool bindTerminate,
ObjectHost* owner)
: ObjectHost(serviceId)
, _links()
, _serviceId(serviceId)
, _objectId(objectId)
, _object(object)
, _callType(mct)
, _owner(owner)
{
onDestroy.setCallType(MetaCallType_Direct);
_self = createServiceBoundObjectType(this, bindTerminate);
}
ServiceBoundObject::~ServiceBoundObject()
{
ObjectHost::clear();
if (_owner)
_owner->removeObject(_objectId);
onDestroy(this);
}
qi::ObjectPtr ServiceBoundObject::createServiceBoundObjectType(ServiceBoundObject *self, bool bindTerminate) {
static qi::ObjectTypeBuilder<ServiceBoundObject>* ob = 0;
if (!ob)
{
ob = new qi::ObjectTypeBuilder<ServiceBoundObject>();
/* Network-related stuff.
*/
ob->advertiseMethod("registerEvent" , &ServiceBoundObject::registerEvent, MetaCallType_Auto, qi::Message::BoundObjectFunction_RegisterEvent);
ob->advertiseMethod("unregisterEvent", &ServiceBoundObject::unregisterEvent, MetaCallType_Auto, qi::Message::BoundObjectFunction_UnregisterEvent);
ob->advertiseMethod("terminate", &ServiceBoundObject::terminate, MetaCallType_Auto, qi::Message::BoundObjectFunction_Terminate);
/* GenericObject-related stuff.
* Those methods could be advertised and implemented by GenericObject itself.
* But since we already have a wrapper system in place in BoundObject, us it.
* There is no use-case that requires the methods below without a BoundObject present.
*/
ob->advertiseMethod("metaObject" , &ServiceBoundObject::metaObject, MetaCallType_Auto, qi::Message::BoundObjectFunction_MetaObject);
ob->advertiseMethod("getProperty", &ServiceBoundObject::getProperty, MetaCallType_Auto, qi::Message::BoundObjectFunction_GetProperty);
ob->advertiseMethod("setProperty", &ServiceBoundObject::setProperty, MetaCallType_Auto, qi::Message::BoundObjectFunction_SetProperty);
ob->advertiseMethod("properties", &ServiceBoundObject::properties, MetaCallType_Auto, qi::Message::BoundObjectFunction_Properties);
// Manageable-level stuff, above comment applies.
ob->advertiseMethod("isStatsEnabled", &ServiceBoundObject::isStatsEnabled, MetaCallType_Auto, qi::Message::BoundObjectFunction_Properties + 1);
ob->advertiseMethod("enableStats", &ServiceBoundObject::enableStats, MetaCallType_Auto, qi::Message::BoundObjectFunction_Properties + 2);
ob->advertiseMethod("stats", &ServiceBoundObject::stats, MetaCallType_Auto, qi::Message::BoundObjectFunction_Properties + 3);
ob->advertiseMethod("clearStats", &ServiceBoundObject::clearStats, MetaCallType_Auto, qi::Message::BoundObjectFunction_Properties + 4);
//global currentSocket: we are not multithread or async capable ob->setThreadingModel(ObjectThreadingModel_MultiThread);
}
ObjectPtr result = ob->object(self);
return result;
}
bool ServiceBoundObject::isStatsEnabled()
{
return _object->isStatsEnabled();
}
void ServiceBoundObject::enableStats(bool enable)
{
_object->enableStats(enable);
}
ObjectStatistics ServiceBoundObject::stats()
{
return _object->stats();
}
void ServiceBoundObject::clearStats()
{
_object->clearStats();
}
//Bound Method
Link ServiceBoundObject::registerEvent(unsigned int objectId, unsigned int eventId, Link remoteLinkId) {
GenericFunction mc = makeDynamicGenericFunction(boost::bind(&forwardEvent, _1, _serviceId, _objectId, eventId, _currentSocket, this));
Link linkId = _object->connect(eventId, mc);
qiLogDebug() << "SBO rl " << remoteLinkId <<" ll " << linkId;
_links[_currentSocket][remoteLinkId] = RemoteLink(linkId, eventId);
return linkId;
}
//Bound Method
void ServiceBoundObject::unregisterEvent(unsigned int objectId, unsigned int QI_UNUSED(event), Link remoteLinkId) {
ServiceLinks& sl = _links[_currentSocket];
ServiceLinks::iterator it = sl.find(remoteLinkId);
if (it == sl.end())
{
std::stringstream ss;
ss << "Unregister request failed for " << remoteLinkId <<" " << objectId;
qiLogError() << ss.str();
throw std::runtime_error(ss.str());
}
_object->disconnect(it->second.localLinkId);
}
//Bound Method
qi::MetaObject ServiceBoundObject::metaObject(unsigned int objectId) {
//we inject specials methods here
return qi::MetaObject::merge(_self->metaObject(), _object->metaObject());
}
void ServiceBoundObject::terminate(unsigned int)
{
qiLogDebug() << "terminate() received";
if (_owner)
_owner->removeObject(_objectId);
else
qiLogWarning() << "terminate() received on object without owner";
}
void ServiceBoundObject::onMessage(const qi::Message &msg, TransportSocketPtr socket) {
if (msg.object() > _objectId)
{
qiLogDebug() << "onChildMessage " << msg.address();
ObjectHost::onMessage(msg, socket);
return;
}
qiLogDebug() << "onMessage " << msg.address();
qi::ObjectPtr obj;
unsigned int funcId;
//choose between special function (on BoundObject) or normal calls
if (msg.function() < static_cast<unsigned int>(gObjectOffset)) {
obj = _self;
} else {
obj = _object;
}
funcId = msg.function();
std::string sigparam;
GenericFunctionParameters mfp;
if (msg.type() == qi::Message::Type_Call) {
const qi::MetaMethod *mm = obj->metaObject().method(funcId);
if (!mm) {
std::stringstream ss;
ss << "No such method " << msg.address();
qiLogError() << ss.str();
qi::Promise<GenericValuePtr> prom;
prom.setError(ss.str());
serverResultAdapter(prom.future(), this, socket, msg.address());
return;
}
sigparam = mm->parametersSignature();
}
else if (msg.type() == qi::Message::Type_Post) {
const qi::MetaSignal *ms = obj->metaObject().signal(funcId);
if (ms)
sigparam = ms->parametersSignature();
else {
const qi::MetaMethod *mm = obj->metaObject().method(funcId);
if (mm)
sigparam = mm->parametersSignature();
else {
qiLogError() << "No such signal/method on event message " << msg.address();
return;
}
}
}
else
{
qiLogError() << "Unexpected message type " << msg.type();
return;
}
GenericValuePtr value = msg.value(sigparam, socket);
mfp = value.asTupleValuePtr();
/* Because of 'global' _currentSocket, we cannot support parallel
* executions at this point.
* Both on self, and on obj which can use currentSocket() too.
*
* So put a lock, and rely on metaCall we invoke being asynchronous for// execution
* This is decided by _callType, set from BoundObject ctor argument, passed by Server, which
* uses its internal _defaultCallType, passed to its constructor, default
* to queued. When Server is instanciated by ObjectHost, it uses the default
* value.
*
* As a consequence, users of currentSocket() must set _callType to Direct.
*/
switch (msg.type())
{
case Message::Type_Call: {
boost::mutex::scoped_lock lock(_mutex);
_currentSocket = socket;
qi::Future<GenericValuePtr> fut = obj->metaCall(funcId, mfp,
obj==_self ? MetaCallType_Direct: _callType);
_currentSocket.reset();
fut.connect(boost::bind<void>(&serverResultAdapter, _1, (ObjectHost*)this, socket, msg.address()));
}
break;
case Message::Type_Post: {
obj->metaPost(funcId, mfp);
}
break;
default:
qiLogError() << "unknown request of type " << (int)msg.type() << " on service: " << msg.address();
}
//########################
value.destroy();
}
void ServiceBoundObject::onSocketDisconnected(TransportSocketPtr client, int error)
{
// Disconnect event links set for this client.
BySocketServiceLinks::iterator it = _links.find(client);
if (it != _links.end())
{
for (ServiceLinks::iterator jt = it->second.begin(); jt != it->second.end(); ++jt)
{
try
{
_object->disconnect(jt->second.localLinkId);
}
catch (const std::runtime_error& e)
{
qiLogError() << e.what();
}
}
_links.erase(it);
}
}
qi::BoundObjectPtr makeServiceBoundObjectPtr(unsigned int serviceId, qi::ObjectPtr object, qi::MetaCallType mct) {
boost::shared_ptr<ServiceBoundObject> ret = boost::make_shared<ServiceBoundObject>(serviceId, Message::GenericObject_Main, object, mct);
return ret;
}
GenericValue ServiceBoundObject::getProperty(const GenericValue& prop)
{
if (prop.kind() == Type::String)
return _object->getProperty<GenericValue>(prop.toString());
else if (prop.kind() == Type::Int)
return _object->type->getProperty(_object->value, prop.toUInt());
else
throw std::runtime_error("Expected int or string for property index");
}
void ServiceBoundObject::setProperty(const GenericValue& prop, GenericValue val)
{
qi::Future<void> result;
if (prop.kind() == Type::String)
result = _object->setProperty(prop.toString(), val);
else if (prop.kind() == Type::Int)
result = _object->type->setProperty(_object->value, prop.toUInt(), val);
else
throw std::runtime_error("Expected int or string for property index");
if (!result.isFinished())
qiLogWarning() << "Assertion failed, setProperty() call not finished";
// Throw the future error
result.value();
}
std::vector<std::string> ServiceBoundObject::properties()
{
// FIXME implement
std::vector<std::string> res;
const MetaObject& mo = _object->metaObject();
MetaObject::PropertyMap map = mo.propertyMap();
for (MetaObject::PropertyMap::iterator it = map.begin(); it != map.end(); ++it)
res.push_back(it->second.name());
return res;
}
}
<commit_msg>Object passing: Do not create Boundobject trees, it does not work.<commit_after>/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include <boost/make_shared.hpp>
#include <qitype/genericobject.hpp>
#include "boundobject.hpp"
#include "serverresult.hpp"
qiLogCategory("qimessaging.boundobject");
static const int gObjectOffset = 100;
namespace qi {
static GenericValuePtr forwardEvent(const GenericFunctionParameters& params,
unsigned int service, unsigned int object,
unsigned int event, TransportSocketPtr client,
ObjectHost* context)
{
qi::Message msg;
msg.setValues(params, context);
msg.setService(service);
msg.setFunction(event);
msg.setType(Message::Type_Event);
msg.setObject(object);
client->send(msg);
return GenericValuePtr();
}
ServiceBoundObject::ServiceBoundObject(unsigned int serviceId, unsigned int objectId,
qi::ObjectPtr object,
qi::MetaCallType mct,
bool bindTerminate,
ObjectHost* owner)
: ObjectHost(serviceId)
, _links()
, _serviceId(serviceId)
, _objectId(objectId)
, _object(object)
, _callType(mct)
, _owner(owner)
{
onDestroy.setCallType(MetaCallType_Direct);
_self = createServiceBoundObjectType(this, bindTerminate);
}
ServiceBoundObject::~ServiceBoundObject()
{
ObjectHost::clear();
if (_owner)
_owner->removeObject(_objectId);
onDestroy(this);
}
qi::ObjectPtr ServiceBoundObject::createServiceBoundObjectType(ServiceBoundObject *self, bool bindTerminate) {
static qi::ObjectTypeBuilder<ServiceBoundObject>* ob = 0;
if (!ob)
{
ob = new qi::ObjectTypeBuilder<ServiceBoundObject>();
/* Network-related stuff.
*/
ob->advertiseMethod("registerEvent" , &ServiceBoundObject::registerEvent, MetaCallType_Auto, qi::Message::BoundObjectFunction_RegisterEvent);
ob->advertiseMethod("unregisterEvent", &ServiceBoundObject::unregisterEvent, MetaCallType_Auto, qi::Message::BoundObjectFunction_UnregisterEvent);
ob->advertiseMethod("terminate", &ServiceBoundObject::terminate, MetaCallType_Auto, qi::Message::BoundObjectFunction_Terminate);
/* GenericObject-related stuff.
* Those methods could be advertised and implemented by GenericObject itself.
* But since we already have a wrapper system in place in BoundObject, us it.
* There is no use-case that requires the methods below without a BoundObject present.
*/
ob->advertiseMethod("metaObject" , &ServiceBoundObject::metaObject, MetaCallType_Auto, qi::Message::BoundObjectFunction_MetaObject);
ob->advertiseMethod("getProperty", &ServiceBoundObject::getProperty, MetaCallType_Auto, qi::Message::BoundObjectFunction_GetProperty);
ob->advertiseMethod("setProperty", &ServiceBoundObject::setProperty, MetaCallType_Auto, qi::Message::BoundObjectFunction_SetProperty);
ob->advertiseMethod("properties", &ServiceBoundObject::properties, MetaCallType_Auto, qi::Message::BoundObjectFunction_Properties);
// Manageable-level stuff, above comment applies.
ob->advertiseMethod("isStatsEnabled", &ServiceBoundObject::isStatsEnabled, MetaCallType_Auto, qi::Message::BoundObjectFunction_Properties + 1);
ob->advertiseMethod("enableStats", &ServiceBoundObject::enableStats, MetaCallType_Auto, qi::Message::BoundObjectFunction_Properties + 2);
ob->advertiseMethod("stats", &ServiceBoundObject::stats, MetaCallType_Auto, qi::Message::BoundObjectFunction_Properties + 3);
ob->advertiseMethod("clearStats", &ServiceBoundObject::clearStats, MetaCallType_Auto, qi::Message::BoundObjectFunction_Properties + 4);
//global currentSocket: we are not multithread or async capable ob->setThreadingModel(ObjectThreadingModel_MultiThread);
}
ObjectPtr result = ob->object(self);
return result;
}
bool ServiceBoundObject::isStatsEnabled()
{
return _object->isStatsEnabled();
}
void ServiceBoundObject::enableStats(bool enable)
{
_object->enableStats(enable);
}
ObjectStatistics ServiceBoundObject::stats()
{
return _object->stats();
}
void ServiceBoundObject::clearStats()
{
_object->clearStats();
}
//Bound Method
Link ServiceBoundObject::registerEvent(unsigned int objectId, unsigned int eventId, Link remoteLinkId) {
GenericFunction mc = makeDynamicGenericFunction(boost::bind(&forwardEvent, _1, _serviceId, _objectId, eventId, _currentSocket, this));
Link linkId = _object->connect(eventId, mc);
qiLogDebug() << "SBO rl " << remoteLinkId <<" ll " << linkId;
_links[_currentSocket][remoteLinkId] = RemoteLink(linkId, eventId);
return linkId;
}
//Bound Method
void ServiceBoundObject::unregisterEvent(unsigned int objectId, unsigned int QI_UNUSED(event), Link remoteLinkId) {
ServiceLinks& sl = _links[_currentSocket];
ServiceLinks::iterator it = sl.find(remoteLinkId);
if (it == sl.end())
{
std::stringstream ss;
ss << "Unregister request failed for " << remoteLinkId <<" " << objectId;
qiLogError() << ss.str();
throw std::runtime_error(ss.str());
}
_object->disconnect(it->second.localLinkId);
}
//Bound Method
qi::MetaObject ServiceBoundObject::metaObject(unsigned int objectId) {
//we inject specials methods here
return qi::MetaObject::merge(_self->metaObject(), _object->metaObject());
}
void ServiceBoundObject::terminate(unsigned int)
{
qiLogDebug() << "terminate() received";
if (_owner)
_owner->removeObject(_objectId);
else
qiLogWarning() << "terminate() received on object without owner";
}
void ServiceBoundObject::onMessage(const qi::Message &msg, TransportSocketPtr socket) {
if (msg.object() > _objectId)
{
qiLogDebug() << "onChildMessage " << msg.address();
ObjectHost::onMessage(msg, socket);
return;
}
qiLogDebug() << "onMessage " << msg.address();
qi::ObjectPtr obj;
unsigned int funcId;
//choose between special function (on BoundObject) or normal calls
if (msg.function() < static_cast<unsigned int>(gObjectOffset)) {
obj = _self;
} else {
obj = _object;
}
funcId = msg.function();
std::string sigparam;
GenericFunctionParameters mfp;
if (msg.type() == qi::Message::Type_Call) {
const qi::MetaMethod *mm = obj->metaObject().method(funcId);
if (!mm) {
std::stringstream ss;
ss << "No such method " << msg.address();
qiLogError() << ss.str();
qi::Promise<GenericValuePtr> prom;
prom.setError(ss.str());
serverResultAdapter(prom.future(), _owner?_owner:this, socket, msg.address());
return;
}
sigparam = mm->parametersSignature();
}
else if (msg.type() == qi::Message::Type_Post) {
const qi::MetaSignal *ms = obj->metaObject().signal(funcId);
if (ms)
sigparam = ms->parametersSignature();
else {
const qi::MetaMethod *mm = obj->metaObject().method(funcId);
if (mm)
sigparam = mm->parametersSignature();
else {
qiLogError() << "No such signal/method on event message " << msg.address();
return;
}
}
}
else
{
qiLogError() << "Unexpected message type " << msg.type();
return;
}
GenericValuePtr value = msg.value(sigparam, socket);
mfp = value.asTupleValuePtr();
/* Because of 'global' _currentSocket, we cannot support parallel
* executions at this point.
* Both on self, and on obj which can use currentSocket() too.
*
* So put a lock, and rely on metaCall we invoke being asynchronous for// execution
* This is decided by _callType, set from BoundObject ctor argument, passed by Server, which
* uses its internal _defaultCallType, passed to its constructor, default
* to queued. When Server is instanciated by ObjectHost, it uses the default
* value.
*
* As a consequence, users of currentSocket() must set _callType to Direct.
*/
switch (msg.type())
{
case Message::Type_Call: {
boost::mutex::scoped_lock lock(_mutex);
_currentSocket = socket;
qi::Future<GenericValuePtr> fut = obj->metaCall(funcId, mfp,
obj==_self ? MetaCallType_Direct: _callType);
_currentSocket.reset();
fut.connect(boost::bind<void>(&serverResultAdapter, _1, _owner?_owner:(ObjectHost*)this, socket, msg.address()));
}
break;
case Message::Type_Post: {
obj->metaPost(funcId, mfp);
}
break;
default:
qiLogError() << "unknown request of type " << (int)msg.type() << " on service: " << msg.address();
}
//########################
value.destroy();
}
void ServiceBoundObject::onSocketDisconnected(TransportSocketPtr client, int error)
{
// Disconnect event links set for this client.
BySocketServiceLinks::iterator it = _links.find(client);
if (it != _links.end())
{
for (ServiceLinks::iterator jt = it->second.begin(); jt != it->second.end(); ++jt)
{
try
{
_object->disconnect(jt->second.localLinkId);
}
catch (const std::runtime_error& e)
{
qiLogError() << e.what();
}
}
_links.erase(it);
}
}
qi::BoundObjectPtr makeServiceBoundObjectPtr(unsigned int serviceId, qi::ObjectPtr object, qi::MetaCallType mct) {
boost::shared_ptr<ServiceBoundObject> ret = boost::make_shared<ServiceBoundObject>(serviceId, Message::GenericObject_Main, object, mct);
return ret;
}
GenericValue ServiceBoundObject::getProperty(const GenericValue& prop)
{
if (prop.kind() == Type::String)
return _object->getProperty<GenericValue>(prop.toString());
else if (prop.kind() == Type::Int)
return _object->type->getProperty(_object->value, prop.toUInt());
else
throw std::runtime_error("Expected int or string for property index");
}
void ServiceBoundObject::setProperty(const GenericValue& prop, GenericValue val)
{
qi::Future<void> result;
if (prop.kind() == Type::String)
result = _object->setProperty(prop.toString(), val);
else if (prop.kind() == Type::Int)
result = _object->type->setProperty(_object->value, prop.toUInt(), val);
else
throw std::runtime_error("Expected int or string for property index");
if (!result.isFinished())
qiLogWarning() << "Assertion failed, setProperty() call not finished";
// Throw the future error
result.value();
}
std::vector<std::string> ServiceBoundObject::properties()
{
// FIXME implement
std::vector<std::string> res;
const MetaObject& mo = _object->metaObject();
MetaObject::PropertyMap map = mo.propertyMap();
for (MetaObject::PropertyMap::iterator it = map.begin(); it != map.end(); ++it)
res.push_back(it->second.name());
return res;
}
}
<|endoftext|>
|
<commit_before>#include "definitions.hpp"
// position of u in a reverse toposort
static int pos(int u) {
static int next = 1, dp[MAXN] = {};
int& ans = dp[u];
if (ans) return ans;
for (int v : G[u].down) pos(v);
return ans = next++;
}
// p(phi(u))
static int p(int u) {
static int dp[MAXN] = {};
int& ans = dp[u];
if (ans) return ans;
switch (G[u].type) {
case CONJ: ans = 0; for (int v : G[u].down) ans = clip(ans+p(v)); break;
case DISJ: ans = 1; for (int v : G[u].down) ans = clip(ans*p(v)); break;
default: ans = 1; break;
}
return ans;
}
// Boy de la Tour's top-down renaming
static void R_rec(int u, int a) {
auto& phi = G[u];
if (phi.p == 1) return;
// check renaming condition
bool renamed = false;
if (a > 1) { // ap >= a+p. to check if ap > a+p, add && (a!=2 || p!=2)
a = 1;
renamed = true;
}
// search children
if (phi.type == CONJ) {
for (int v : phi.down) R_rec(v,a);
phi.p = 0; for (int v : phi.down) phi.p = clip(phi.p+G[v].p);
}
else { // phi.type == DISJ
int n = phi.down.size();
vector<int> dp(n,1); // dp[i] = prod(phi_j.p), i < j < n
for (int i = n-2; 0 <= i; i--) dp[i] = clip(G[phi.down[i+1]].p*dp[i+1]);
int ai = a; // ai = a*prod(phi_j.p), 0 <= j < i
for (int i = 0; i < n; i++) {
R_rec(phi.down[i],clip(ai*dp[i]));
ai = clip(ai*G[phi.down[i]].p);
}
phi.p = 1; for (int v : phi.down) phi.p = clip(phi.p*G[v].p);
}
if (renamed) {
R.push_back(u);
phi.p = 1;
}
}
void boydelatour() {
// necessary preprocessing for Boy de la Tour's algorithm
auto toposortless = [](int u, int v) { return pos(u) < pos(v); };
for (int u = 0; u < G.size(); u++) {
auto& phi = G[u];
sort(phi.down.begin(),phi.down.end(),toposortless);
phi.p = p(u);
}
R_rec(0,1); // recursive algorithm
}
<commit_msg>Improving Boy de la Tour condition<commit_after>#include "definitions.hpp"
// position of u in a reverse toposort
static int pos(int u) {
static int next = 1, dp[MAXN] = {};
int& ans = dp[u];
if (ans) return ans;
for (int v : G[u].down) pos(v);
return ans = next++;
}
// p(phi(u))
static int p(int u) {
static int dp[MAXN] = {};
int& ans = dp[u];
if (ans) return ans;
switch (G[u].type) {
case CONJ: ans = 0; for (int v : G[u].down) ans = clip(ans+p(v)); break;
case DISJ: ans = 1; for (int v : G[u].down) ans = clip(ans*p(v)); break;
default: ans = 1; break;
}
return ans;
}
// Boy de la Tour's top-down renaming
static void R_rec(int u, int a) {
auto& phi = G[u];
if (phi.p == 1) return;
// check renaming condition
bool renamed = false;
if (a >= 2 && (a != 2 || phi.p != 2)) { // ap > a+p
a = 1;
renamed = true;
}
// search children
if (phi.type == CONJ) {
for (int v : phi.down) R_rec(v,a);
phi.p = 0; for (int v : phi.down) phi.p = clip(phi.p+G[v].p);
}
else { // phi.type == DISJ
int n = phi.down.size();
vector<int> dp(n,1); // dp[i] = prod(phi_j.p), i < j < n
for (int i = n-2; 0 <= i; i--) dp[i] = clip(G[phi.down[i+1]].p*dp[i+1]);
int ai = a; // ai = a*prod(phi_j.p), 0 <= j < i
for (int i = 0; i < n; i++) {
R_rec(phi.down[i],clip(ai*dp[i]));
ai = clip(ai*G[phi.down[i]].p);
}
phi.p = 1; for (int v : phi.down) phi.p = clip(phi.p*G[v].p);
}
if (renamed) {
R.push_back(u);
phi.p = 1;
}
}
void boydelatour() {
// necessary preprocessing for Boy de la Tour's algorithm
auto toposortless = [](int u, int v) { return pos(u) < pos(v); };
for (int u = 0; u < G.size(); u++) {
auto& phi = G[u];
sort(phi.down.begin(),phi.down.end(),toposortless);
phi.p = p(u);
}
R_rec(0,1); // recursive algorithm
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <map>
#include <Ice/Ice.h>
#include "server.h"
// TODO: remove this global variable
Ice::CommunicatorPtr ic;
class MetaServer : public Player::IMetaServer
{
public:
MetaServer();
virtual void add(const std::string& endpointStr, const Player::Song& s, const Ice::Current& c);
virtual void remove(const Player::MediaInfo& media, const Ice::Current& c);
virtual Player::MediaInfoSeq find(const std::string& s, const Ice::Current& c);
virtual Player::StreamToken setupStreaming(const Player::MediaInfo& media, const Ice::Current& c);
virtual void play(const Player::StreamToken& token, const Ice::Current& c);
virtual void stop(const Player::StreamToken& token, const Ice::Current& c);
private:
/* std::map<std::string, Player::IMusicServerPrx> serverList; */
std::vector<std::pair<std::string, std::string>> serverList;
};
MetaServer::MetaServer()
{
serverList.push_back(std::make_pair("onche.ovh", "10001"));
}
void MetaServer::add(const std::string& endpointStr, const Player::Song& s, const Ice::Current& c)
{
std::cout << "Adding to " << endpointStr << " : " << s.artist << " - " << s.title << " - " << s.path << '\n';
Ice::ObjectPrx base = ic->stringToProxy(endpointStr);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv)
srv->add(s);
}
void MetaServer::remove(const Player::MediaInfo& media, const Ice::Current& c)
{
std::cout << "Removing on " << media.endpointStr << " : " << media.media.path << '\n';
Ice::ObjectPrx base = ic->stringToProxy(media.endpointStr);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv)
srv->remove(media.media.path);
}
Player::MediaInfoSeq MetaServer::find(const std::string& s, const Ice::Current& c)
{
std::cout << "Searching for: " << s << '\n';
Player::MediaInfoSeq medias;
for (const auto& it : serverList) {
std::string endpointStr = "MusicServer:default -h " + it.first + " -p " + it.second;
Ice::ObjectPrx base = ic->stringToProxy(endpointStr);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv) {
auto results = srv->find(s);
for (const auto& r : results) {
Player::MediaInfo m;
m.endpointStr = endpointStr;
m.media = r;
medias.push_back(m);
}
}
}
return medias;
}
Player::StreamToken MetaServer::setupStreaming(const Player::MediaInfo& media, const Ice::Current& c)
{
Player::StreamToken token;
Ice::ObjectPrx base = ic->stringToProxy(media.endpointStr);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv) {
Ice::IPConnectionInfo* ipConInfo = dynamic_cast<Ice::IPConnectionInfo*>(c.con->getInfo().get());
token = srv->setupStreaming(media.media.path, ipConInfo->remoteAddress, std::to_string(ipConInfo->remotePort));
token.endpointStr = media.endpointStr;
}
return token;
}
void MetaServer::play(const Player::StreamToken& token, const Ice::Current& c)
{
Ice::ObjectPrx base = ic->stringToProxy(token.endpointStr);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv)
srv->play(token);
}
void MetaServer::stop(const Player::StreamToken& token, const Ice::Current& c)
{
Ice::ObjectPrx base = ic->stringToProxy(token.endpointStr);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv)
srv->stop(token);
}
int main(int argc, char **argv)
{
int status = 0;
try {
ic = Ice::initialize(argc, argv);
Ice::ObjectAdapterPtr adapter = ic->createObjectAdapterWithEndpoints("MetaServerAdapter", "default -p 10000");
Ice::ObjectPtr object = new MetaServer;
adapter->add(object, ic->stringToIdentity("MetaServer"));
adapter->activate();
ic->waitForShutdown();
}
catch (const Ice::Exception& e) {
std::cerr << e << std::endl;
status = 1;
}
catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
status = 1;
}
catch (...) {
status = 1;
}
if (ic) {
try {
ic->destroy();
}
catch (const Ice::Exception& e) {
std::cerr << e << std::endl;
status = 1;
}
}
return status;
}
<commit_msg>fix serverlist and streamingURL<commit_after>#include <iostream>
#include <map>
#include <Ice/Ice.h>
#include "server.h"
// TODO: remove this global variable
Ice::CommunicatorPtr ic;
class MetaServer : public Player::IMetaServer
{
public:
MetaServer();
virtual void add(const std::string& endpointStr, const Player::Song& s, const Ice::Current& c);
virtual void remove(const Player::MediaInfo& media, const Ice::Current& c);
virtual Player::MediaInfoSeq find(const std::string& s, const Ice::Current& c);
virtual Player::StreamToken setupStreaming(const Player::MediaInfo& media, const Ice::Current& c);
virtual void play(const Player::StreamToken& token, const Ice::Current& c);
virtual void stop(const Player::StreamToken& token, const Ice::Current& c);
private:
/* std::map<std::string, Player::IMusicServerPrx> serverList; */
std::map<std::string, std::string> serverList;
};
MetaServer::MetaServer()
{
serverList.emplace("MusicServer:default -h onche.ovh -p 10001", "onche.ovh");
}
void MetaServer::add(const std::string& endpointStr, const Player::Song& s, const Ice::Current& c)
{
std::cout << "Adding to " << endpointStr << " : " << s.artist << " - " << s.title << " - " << s.path << '\n';
Ice::ObjectPrx base = ic->stringToProxy(endpointStr);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv)
srv->add(s);
}
void MetaServer::remove(const Player::MediaInfo& media, const Ice::Current& c)
{
std::cout << "Removing on " << media.endpointStr << " : " << media.media.path << '\n';
Ice::ObjectPrx base = ic->stringToProxy(media.endpointStr);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv)
srv->remove(media.media.path);
}
Player::MediaInfoSeq MetaServer::find(const std::string& s, const Ice::Current& c)
{
std::cout << "Searching for: " << s << '\n';
Player::MediaInfoSeq medias;
for (const auto& it : serverList) {
Ice::ObjectPrx base = ic->stringToProxy(it.first);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv) {
auto results = srv->find(s);
for (const auto& r : results) {
Player::MediaInfo m;
m.endpointStr = it.first;
m.media = r;
medias.push_back(m);
}
}
}
return medias;
}
Player::StreamToken MetaServer::setupStreaming(const Player::MediaInfo& media, const Ice::Current& c)
{
std::cout << "Setup stream on " << media.endpointStr << ", " << media.media.path << '\n';
Player::StreamToken token;
Ice::ObjectPrx base = ic->stringToProxy(media.endpointStr);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv) {
Ice::IPConnectionInfo* ipConInfo = dynamic_cast<Ice::IPConnectionInfo*>(c.con->getInfo().get());
token = srv->setupStreaming(media.media.path, ipConInfo->remoteAddress, std::to_string(ipConInfo->remotePort));
token.endpointStr = media.endpointStr;
try {
token.streamingURL = "http://" + serverList.at(media.endpointStr) + ":8090" + '/' + token.streamingURL; // prepend http://hostname:8090
}
catch (const std::exception& e) {
return Player::StreamToken();
}
}
return token;
}
void MetaServer::play(const Player::StreamToken& token, const Ice::Current& c)
{
Ice::ObjectPrx base = ic->stringToProxy(token.endpointStr);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv)
srv->play(token);
}
void MetaServer::stop(const Player::StreamToken& token, const Ice::Current& c)
{
Ice::ObjectPrx base = ic->stringToProxy(token.endpointStr);
Player::IMusicServerPrx srv = Player::IMusicServerPrx::checkedCast(base);
if (srv)
srv->stop(token);
}
int main(int argc, char **argv)
{
int status = 0;
try {
ic = Ice::initialize(argc, argv);
Ice::ObjectAdapterPtr adapter = ic->createObjectAdapterWithEndpoints("MetaServerAdapter", "default -p 10000");
Ice::ObjectPtr object = new MetaServer;
adapter->add(object, ic->stringToIdentity("MetaServer"));
adapter->activate();
ic->waitForShutdown();
}
catch (const Ice::Exception& e) {
std::cerr << e << std::endl;
status = 1;
}
catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
status = 1;
}
catch (...) {
status = 1;
}
if (ic) {
try {
ic->destroy();
}
catch (const Ice::Exception& e) {
std::cerr << e << std::endl;
status = 1;
}
}
return status;
}
<|endoftext|>
|
<commit_before><commit_msg>sc tiled editing: Set the 100% zoom in the selection-related methods too.<commit_after><|endoftext|>
|
<commit_before>#include "CQuery.hpp"
#include "CHandle.hpp"
#include "CConnection.hpp"
#include "COptions.hpp"
#include "misc.hpp"
#include <fstream>
#include <boost/spirit/include/qi.hpp>
using namespace boost::spirit;
#include "mysql.hpp"
CHandle::~CHandle()
{
if (m_MainConnection != nullptr)
delete m_MainConnection;
if (m_ThreadedConnection != nullptr)
delete m_ThreadedConnection;
if (m_ConnectionPool != nullptr)
delete m_ConnectionPool;
}
bool CHandle::Execute(ExecutionType type, Query_t query)
{
bool return_val = false;
if (query)
{
switch (type)
{
case ExecutionType::THREADED:
if (m_ThreadedConnection != nullptr)
return_val = m_ThreadedConnection->Queue(query);
break;
case ExecutionType::PARALLEL:
if (m_ConnectionPool != nullptr)
return_val = m_ConnectionPool->Queue(query);
break;
case ExecutionType::UNTHREADED:
if (m_MainConnection != nullptr)
return_val = m_MainConnection->Execute(query);
break;
default:
; //TODO: log error
}
}
return return_val;
}
bool CHandle::GetErrorId(unsigned int &errorid)
{
if (m_MainConnection == nullptr)
return false;
string unused_errormsg;
return m_MainConnection->GetError(errorid, unused_errormsg);
}
bool CHandle::EscapeString(const string &src, string &dest)
{
if (m_MainConnection == nullptr)
return false;
return m_MainConnection->EscapeString(src.c_str(), dest);
}
bool CHandle::SetCharacterSet(string charset)
{
if (m_MainConnection == nullptr)
return false;
return
m_MainConnection->SetCharset(charset)
&& m_ThreadedConnection->SetCharset(charset)
&& m_ConnectionPool != nullptr ? m_ConnectionPool->SetCharset(charset) : true;
}
bool CHandle::GetCharacterSet(string &charset)
{
if (m_MainConnection == nullptr)
return false;
return m_MainConnection->GetCharset(charset);
}
bool CHandle::GetStatus(string &stat)
{
if (m_MainConnection == nullptr)
return false;
return m_MainConnection->GetStatus(stat);
}
CHandle *CHandleManager::Create(string host, string user, string pass, string db,
const COptions *options, CHandle::Error &error)
{
error = CHandle::Error::NONE;
if (host.empty())
{
error = CHandle::Error::EMPTY_HOST;
return nullptr;
}
if (user.empty())
{
error = CHandle::Error::EMPTY_USER;
return nullptr;
}
if (pass.empty())
;//TODO: warning
if (db.empty())
{
error = CHandle::Error::EMPTY_DATABASE;
return nullptr;
}
if (options == nullptr)
{
error = CHandle::Error::INVALID_OPTIONS;
return nullptr;
}
HandleId_t id = 1;
while (m_Handles.find(id) != m_Handles.end())
id++;
CHandle *handle = new CHandle(id);
handle->m_MainConnection = new CConnection(host, user, pass, db, options);
handle->m_ThreadedConnection = new CThreadedConnection(host, user, pass, db, options);
auto pool_size = options->GetOption<unsigned int>(COptions::Type::POOL_SIZE);
if (pool_size != 0)
handle->m_ConnectionPool = new CConnectionPool(pool_size, host, user, pass, db, options);
m_Handles.emplace(id, handle);
return handle;
}
CHandle *CHandleManager::CreateFromFile(string file_path, CHandle::Error &error)
{
error = CHandle::Error::NONE;
std::ifstream file(file_path);
if (file.fail())
{
error = CHandle::Error::INVALID_FILE;
return nullptr;
}
string hostname, username, password, database;
auto options_id = COptionManager::Get()->Create();
COptions *options = COptionManager::Get()->GetOptionHandle(options_id);
const std::unordered_map<string, function<void(string &)>> assign_map{
{ "hostname", [&](string &val_str) { hostname = val_str; } },
{ "username", [&](string &val_str) { username = val_str; } },
{ "password", [&](string &val_str) { password = val_str; } },
{ "database", [&](string &val_str) { database = val_str; } },
{ "auto_reconnect", [&](string &val_str)
{
bool val;
if (ConvertStrToData(val_str, val))
options->SetOption(COptions::Type::AUTO_RECONNECT, val);
}
},
{ "multi_statements", [&](string &val_str)
{
bool val;
if (ConvertStrToData(val_str, val))
options->SetOption(COptions::Type::MULTI_STATEMENTS, val);
}
},
{ "pool_size", [&](string &val_str)
{
unsigned int val = 0;
if (ConvertStrToData(val_str, val))
options->SetOption(COptions::Type::POOL_SIZE, val);
}
},
{ "server_port", [&](string &val_str)
{
unsigned int val = 0;
if (ConvertStrToData(val_str, val))
options->SetOption(COptions::Type::SERVER_PORT, val);
}
}
};
while (file.good())
{
string line;
std::getline(file, line);
if (line.empty())
continue;
//erase comment from line
size_t comment_pos = line.find_first_of("#;");
if (comment_pos != string::npos)
line.erase(comment_pos);
std::string field, data;
if (qi::parse(line.begin(), line.end(),
qi::skip(qi::space)[
qi::as_string[+qi::char_("a-z_")] >> qi::lit('=') >> qi::as_string[+qi::graph]
],
field, data))
{
auto field_it = assign_map.find(field);
if (field_it != assign_map.end() && data.empty() == false)
{
field_it->second(data);
}
else
{
error = CHandle::Error::INVALID_FIELD;
return nullptr;
}
}
else
{
error = CHandle::Error::SYNTAX_ERROR;
return nullptr;
}
}
return Create(hostname, username, password, database, options, error);
}
bool CHandleManager::Destroy(CHandle *handle)
{
if (handle == nullptr)
return false;
if (m_Handles.erase(handle->GetId()) == 0)
return false;
delete handle;
return true;
}
<commit_msg>fix connection file comment parsing<commit_after>#include "CQuery.hpp"
#include "CHandle.hpp"
#include "CConnection.hpp"
#include "COptions.hpp"
#include "misc.hpp"
#include <fstream>
#include <boost/spirit/include/qi.hpp>
using namespace boost::spirit;
#include "mysql.hpp"
CHandle::~CHandle()
{
if (m_MainConnection != nullptr)
delete m_MainConnection;
if (m_ThreadedConnection != nullptr)
delete m_ThreadedConnection;
if (m_ConnectionPool != nullptr)
delete m_ConnectionPool;
}
bool CHandle::Execute(ExecutionType type, Query_t query)
{
bool return_val = false;
if (query)
{
switch (type)
{
case ExecutionType::THREADED:
if (m_ThreadedConnection != nullptr)
return_val = m_ThreadedConnection->Queue(query);
break;
case ExecutionType::PARALLEL:
if (m_ConnectionPool != nullptr)
return_val = m_ConnectionPool->Queue(query);
break;
case ExecutionType::UNTHREADED:
if (m_MainConnection != nullptr)
return_val = m_MainConnection->Execute(query);
break;
default:
; //TODO: log error
}
}
return return_val;
}
bool CHandle::GetErrorId(unsigned int &errorid)
{
if (m_MainConnection == nullptr)
return false;
string unused_errormsg;
return m_MainConnection->GetError(errorid, unused_errormsg);
}
bool CHandle::EscapeString(const string &src, string &dest)
{
if (m_MainConnection == nullptr)
return false;
return m_MainConnection->EscapeString(src.c_str(), dest);
}
bool CHandle::SetCharacterSet(string charset)
{
if (m_MainConnection == nullptr)
return false;
return
m_MainConnection->SetCharset(charset)
&& m_ThreadedConnection->SetCharset(charset)
&& m_ConnectionPool != nullptr ? m_ConnectionPool->SetCharset(charset) : true;
}
bool CHandle::GetCharacterSet(string &charset)
{
if (m_MainConnection == nullptr)
return false;
return m_MainConnection->GetCharset(charset);
}
bool CHandle::GetStatus(string &stat)
{
if (m_MainConnection == nullptr)
return false;
return m_MainConnection->GetStatus(stat);
}
CHandle *CHandleManager::Create(string host, string user, string pass, string db,
const COptions *options, CHandle::Error &error)
{
error = CHandle::Error::NONE;
if (host.empty())
{
error = CHandle::Error::EMPTY_HOST;
return nullptr;
}
if (user.empty())
{
error = CHandle::Error::EMPTY_USER;
return nullptr;
}
if (pass.empty())
;//TODO: warning
if (db.empty())
{
error = CHandle::Error::EMPTY_DATABASE;
return nullptr;
}
if (options == nullptr)
{
error = CHandle::Error::INVALID_OPTIONS;
return nullptr;
}
HandleId_t id = 1;
while (m_Handles.find(id) != m_Handles.end())
id++;
CHandle *handle = new CHandle(id);
handle->m_MainConnection = new CConnection(host, user, pass, db, options);
handle->m_ThreadedConnection = new CThreadedConnection(host, user, pass, db, options);
auto pool_size = options->GetOption<unsigned int>(COptions::Type::POOL_SIZE);
if (pool_size != 0)
handle->m_ConnectionPool = new CConnectionPool(pool_size, host, user, pass, db, options);
m_Handles.emplace(id, handle);
return handle;
}
CHandle *CHandleManager::CreateFromFile(string file_path, CHandle::Error &error)
{
error = CHandle::Error::NONE;
std::ifstream file(file_path);
if (file.fail())
{
error = CHandle::Error::INVALID_FILE;
return nullptr;
}
string hostname, username, password, database;
auto options_id = COptionManager::Get()->Create();
COptions *options = COptionManager::Get()->GetOptionHandle(options_id);
const std::unordered_map<string, function<void(string &)>> assign_map{
{ "hostname", [&](string &val_str) { hostname = val_str; } },
{ "username", [&](string &val_str) { username = val_str; } },
{ "password", [&](string &val_str) { password = val_str; } },
{ "database", [&](string &val_str) { database = val_str; } },
{ "auto_reconnect", [&](string &val_str)
{
bool val;
if (ConvertStrToData(val_str, val))
options->SetOption(COptions::Type::AUTO_RECONNECT, val);
}
},
{ "multi_statements", [&](string &val_str)
{
bool val;
if (ConvertStrToData(val_str, val))
options->SetOption(COptions::Type::MULTI_STATEMENTS, val);
}
},
{ "pool_size", [&](string &val_str)
{
unsigned int val = 0;
if (ConvertStrToData(val_str, val))
options->SetOption(COptions::Type::POOL_SIZE, val);
}
},
{ "server_port", [&](string &val_str)
{
unsigned int val = 0;
if (ConvertStrToData(val_str, val))
options->SetOption(COptions::Type::SERVER_PORT, val);
}
}
};
while (file.good())
{
string line;
std::getline(file, line);
//erase prepending whitespace
size_t first_char_pos = line.find_first_not_of(" \t");
if (first_char_pos != string::npos)
line.erase(0, first_char_pos);
//erase comment from line
size_t comment_pos = line.find_first_of("#;");
if (comment_pos != string::npos)
line.erase(comment_pos);
if (line.empty())
continue;
std::string field, data;
if (qi::parse(line.begin(), line.end(),
qi::skip(qi::space)[
qi::as_string[+qi::char_("a-z_")] >> qi::lit('=') >> qi::as_string[+qi::graph]
],
field, data))
{
auto field_it = assign_map.find(field);
if (field_it != assign_map.end() && data.empty() == false)
{
field_it->second(data);
}
else
{
error = CHandle::Error::INVALID_FIELD;
return nullptr;
}
}
else
{
error = CHandle::Error::SYNTAX_ERROR;
return nullptr;
}
}
return Create(hostname, username, password, database, options, error);
}
bool CHandleManager::Destroy(CHandle *handle)
{
if (handle == nullptr)
return false;
if (m_Handles.erase(handle->GetId()) == 0)
return false;
delete handle;
return true;
}
<|endoftext|>
|
<commit_before>// Scintilla source code edit control
/** @file CallTip.cxx
** Code for displaying call tips.
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include "Platform.h"
#include "Scintilla.h"
#include "CallTip.h"
CallTip::CallTip() {
wCallTip = 0;
inCallTipMode = false;
posStartCallTip = 0;
val = 0;
xUp = -100;
xDown = -100;
lineHeight = 1;
startHighlight = 0;
endHighlight = 0;
colourBG.desired = ColourDesired(0xff, 0xff, 0xff);
colourUnSel.desired = ColourDesired(0x80, 0x80, 0x80);
colourSel.desired = ColourDesired(0, 0, 0x80);
colourShade.desired = ColourDesired(0, 0, 0);
colourLight.desired = ColourDesired(0xc0, 0xc0, 0xc0);
}
CallTip::~CallTip() {
font.Release();
wCallTip.Destroy();
delete []val;
val = 0;
}
const int widthArrow = 14;
void CallTip::RefreshColourPalette(Palette &pal, bool want) {
pal.WantFind(colourBG, want);
pal.WantFind(colourUnSel, want);
pal.WantFind(colourSel, want);
pal.WantFind(colourShade, want);
pal.WantFind(colourLight, want);
}
void CallTip::DrawChunk(Surface *surface, int &x, const char *s,
int posStart, int posEnd, int ytext, PRectangle rcClient,
bool highlight, bool draw) {
s += posStart;
int len = posEnd - posStart;
int maxEnd = 0;
int ends[10];
for (int i=0;i<len;i++) {
if (s[i] <= '\002') {
if (i > 0)
ends[maxEnd++] = i;
ends[maxEnd++] = i+1;
}
}
ends[maxEnd++] = len;
int startSeg = 0;
int xEnd;
for (int seg = 0; seg<maxEnd; seg++) {
int endSeg = ends[seg];
if (endSeg > startSeg) {
if (s[startSeg] <= '\002') {
xEnd = x + widthArrow;
offsetMain = xEnd;
if (draw) {
const int halfWidth = widthArrow / 2 - 3;
const int centreX = x + widthArrow / 2 - 1;
const int centreY = ytext - halfWidth - 1;
rcClient.left = x;
rcClient.right = xEnd;
surface->FillRectangle(rcClient, colourBG.allocated);
PRectangle rcClientInner(rcClient.left+1, rcClient.top+1, rcClient.right-2, rcClient.bottom-1);
surface->FillRectangle(rcClientInner, colourUnSel.allocated);
if (s[startSeg] == '\001') {
// Up arrow
Point pts[] = {
Point(centreX - halfWidth, centreY + halfWidth / 2),
Point(centreX + halfWidth, centreY + halfWidth / 2),
Point(centreX, centreY - halfWidth + halfWidth / 2),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
colourBG.allocated, colourBG.allocated);
} else {
// Down arrow
Point pts[] = {
Point(centreX - halfWidth, centreY - halfWidth / 2 + 2),
Point(centreX + halfWidth, centreY - halfWidth / 2 + 2),
Point(centreX, centreY + halfWidth - halfWidth / 2 + 2),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
colourBG.allocated, colourBG.allocated);
}
} else {
if (s[startSeg] == '\001') {
xUp = x+1;
} else {
xDown = x+1;
}
}
} else {
xEnd = x + surface->WidthText(font, s+startSeg, endSeg - startSeg);
if (draw) {
rcClient.left = x;
rcClient.right = xEnd;
surface->DrawTextNoClip(rcClient, font, ytext,
s+startSeg, endSeg - startSeg,
highlight ? colourSel.allocated : colourUnSel.allocated,
colourBG.allocated);
}
}
x = xEnd;
startSeg = endSeg;
}
}
}
int CallTip::PaintContents(Surface *surfaceWindow, bool draw) {
PRectangle rcClientPos = wCallTip.GetClientPosition();
PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left,
rcClientPos.bottom - rcClientPos.top);
PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1);
// To make a nice small call tip window, it is only sized to fit most normal characters without accents
int ascent = surfaceWindow->Ascent(font) - surfaceWindow->InternalLeading(font);
// For each line...
// Draw the definition in three parts: before highlight, highlighted, after highlight
int ytext = rcClient.top + ascent + 1;
rcClient.bottom = ytext + surfaceWindow->Descent(font) + 1;
char *chunkVal = val;
bool moreChunks = true;
int maxWidth = 0;
while (moreChunks) {
char *chunkEnd = strchr(chunkVal, '\n');
if (chunkEnd == NULL) {
chunkEnd = chunkVal + strlen(chunkVal);
moreChunks = false;
}
int chunkOffset = chunkVal - val;
int chunkLength = chunkEnd - chunkVal;
int chunkEndOffset = chunkOffset + chunkLength;
int thisStartHighlight = Platform::Maximum(startHighlight, chunkOffset);
thisStartHighlight = Platform::Minimum(thisStartHighlight, chunkEndOffset);
thisStartHighlight -= chunkOffset;
int thisEndHighlight = Platform::Maximum(endHighlight, chunkOffset);
thisEndHighlight = Platform::Minimum(thisEndHighlight, chunkEndOffset);
thisEndHighlight -= chunkOffset;
rcClient.top = ytext - ascent - 1;
int x = 5;
DrawChunk(surfaceWindow, x, chunkVal, 0, thisStartHighlight,
ytext, rcClient, false, draw);
DrawChunk(surfaceWindow, x, chunkVal, thisStartHighlight, thisEndHighlight,
ytext, rcClient, true, draw);
DrawChunk(surfaceWindow, x, chunkVal, thisEndHighlight, chunkLength,
ytext, rcClient, false, draw);
chunkVal = chunkEnd + 1;
ytext += lineHeight;
rcClient.bottom += lineHeight;
maxWidth = Platform::Maximum(maxWidth, x);
}
return maxWidth;
}
void CallTip::PaintCT(Surface *surfaceWindow) {
if (!val)
return;
PRectangle rcClientPos = wCallTip.GetClientPosition();
PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left,
rcClientPos.bottom - rcClientPos.top);
PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1);
surfaceWindow->FillRectangle(rcClient, colourBG.allocated);
offsetMain = 5;
PaintContents(surfaceWindow, true);
// Draw a raised border around the edges of the window
surfaceWindow->MoveTo(0, rcClientSize.bottom - 1);
surfaceWindow->PenColour(colourShade.allocated);
surfaceWindow->LineTo(rcClientSize.right - 1, rcClientSize.bottom - 1);
surfaceWindow->LineTo(rcClientSize.right - 1, 0);
surfaceWindow->PenColour(colourLight.allocated);
surfaceWindow->LineTo(0, 0);
surfaceWindow->LineTo(0, rcClientSize.bottom - 1);
}
void CallTip::MouseClick(Point pt) {
clickPlace = 0;
if (pt.y < lineHeight) {
if ((pt.x > xUp) && (pt.x < xUp + widthArrow - 2)) {
clickPlace = 1;
} else if ((pt.x > xDown) && (pt.x < xDown + widthArrow - 2)) {
clickPlace = 2;
}
}
}
PRectangle CallTip::CallTipStart(int pos, Point pt, const char *defn,
const char *faceName, int size,
int codePage_, Window &wParent) {
clickPlace = 0;
if (val)
delete []val;
val = new char[strlen(defn) + 1];
if (!val)
return PRectangle();
strcpy(val, defn);
codePage = codePage_;
Surface *surfaceMeasure = Surface::Allocate();
if (!surfaceMeasure)
return PRectangle();
surfaceMeasure->Init(wParent.GetID());
surfaceMeasure->SetUnicodeMode(SC_CP_UTF8 == codePage);
surfaceMeasure->SetDBCSMode(codePage);
startHighlight = 0;
endHighlight = 0;
inCallTipMode = true;
posStartCallTip = pos;
int deviceHeight = surfaceMeasure->DeviceHeightFont(size);
font.Create(faceName, SC_CHARSET_DEFAULT, deviceHeight, false, false);
// Look for multiple lines in the text
// Only support \n here - simply means container must avoid \r!
int numLines = 1;
const char *newline;
const char *look = val;
xUp = -100;
xDown = -100;
offsetMain = 5;
int width = PaintContents(surfaceMeasure, false) + 5;
while ((newline = strchr(look, '\n')) != NULL) {
look = newline + 1;
numLines++;
}
lineHeight = surfaceMeasure->Height(font);
// Extra line for border and an empty line at top and bottom
int height = lineHeight * numLines - surfaceMeasure->InternalLeading(font) + 2 + 2;
delete surfaceMeasure;
return PRectangle(pt.x - offsetMain, pt.y + 1, pt.x + width - offsetMain, pt.y + 1 + height);
}
void CallTip::CallTipCancel() {
inCallTipMode = false;
if (wCallTip.Created()) {
wCallTip.Destroy();
}
}
void CallTip::SetHighlight(int start, int end) {
// Avoid flashing by checking something has really changed
if ((start != startHighlight) || (end != endHighlight)) {
startHighlight = start;
endHighlight = end;
if (wCallTip.Created()) {
wCallTip.InvalidateAll();
}
}
}
<commit_msg>Tweaked arrow position slightly.<commit_after>// Scintilla source code edit control
/** @file CallTip.cxx
** Code for displaying call tips.
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include "Platform.h"
#include "Scintilla.h"
#include "CallTip.h"
CallTip::CallTip() {
wCallTip = 0;
inCallTipMode = false;
posStartCallTip = 0;
val = 0;
xUp = -100;
xDown = -100;
lineHeight = 1;
startHighlight = 0;
endHighlight = 0;
colourBG.desired = ColourDesired(0xff, 0xff, 0xff);
colourUnSel.desired = ColourDesired(0x80, 0x80, 0x80);
colourSel.desired = ColourDesired(0, 0, 0x80);
colourShade.desired = ColourDesired(0, 0, 0);
colourLight.desired = ColourDesired(0xc0, 0xc0, 0xc0);
}
CallTip::~CallTip() {
font.Release();
wCallTip.Destroy();
delete []val;
val = 0;
}
const int widthArrow = 14;
void CallTip::RefreshColourPalette(Palette &pal, bool want) {
pal.WantFind(colourBG, want);
pal.WantFind(colourUnSel, want);
pal.WantFind(colourSel, want);
pal.WantFind(colourShade, want);
pal.WantFind(colourLight, want);
}
void CallTip::DrawChunk(Surface *surface, int &x, const char *s,
int posStart, int posEnd, int ytext, PRectangle rcClient,
bool highlight, bool draw) {
s += posStart;
int len = posEnd - posStart;
int maxEnd = 0;
int ends[10];
for (int i=0;i<len;i++) {
if (s[i] <= '\002') {
if (i > 0)
ends[maxEnd++] = i;
ends[maxEnd++] = i+1;
}
}
ends[maxEnd++] = len;
int startSeg = 0;
int xEnd;
for (int seg = 0; seg<maxEnd; seg++) {
int endSeg = ends[seg];
if (endSeg > startSeg) {
if (s[startSeg] <= '\002') {
xEnd = x + widthArrow;
offsetMain = xEnd;
if (draw) {
const int halfWidth = widthArrow / 2 - 3;
const int centreX = x + widthArrow / 2 - 1;
const int centreY = (rcClient.top + rcClient.bottom) / 2;
rcClient.left = x;
rcClient.right = xEnd;
surface->FillRectangle(rcClient, colourBG.allocated);
PRectangle rcClientInner(rcClient.left+1, rcClient.top+1, rcClient.right-2, rcClient.bottom-1);
surface->FillRectangle(rcClientInner, colourUnSel.allocated);
if (s[startSeg] == '\001') {
// Up arrow
Point pts[] = {
Point(centreX - halfWidth, centreY + halfWidth / 2),
Point(centreX + halfWidth, centreY + halfWidth / 2),
Point(centreX, centreY - halfWidth + halfWidth / 2),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
colourBG.allocated, colourBG.allocated);
} else {
// Down arrow
Point pts[] = {
Point(centreX - halfWidth, centreY - halfWidth / 2),
Point(centreX + halfWidth, centreY - halfWidth / 2),
Point(centreX, centreY + halfWidth - halfWidth / 2),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
colourBG.allocated, colourBG.allocated);
}
} else {
if (s[startSeg] == '\001') {
xUp = x+1;
} else {
xDown = x+1;
}
}
} else {
xEnd = x + surface->WidthText(font, s+startSeg, endSeg - startSeg);
if (draw) {
rcClient.left = x;
rcClient.right = xEnd;
surface->DrawTextNoClip(rcClient, font, ytext,
s+startSeg, endSeg - startSeg,
highlight ? colourSel.allocated : colourUnSel.allocated,
colourBG.allocated);
}
}
x = xEnd;
startSeg = endSeg;
}
}
}
int CallTip::PaintContents(Surface *surfaceWindow, bool draw) {
PRectangle rcClientPos = wCallTip.GetClientPosition();
PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left,
rcClientPos.bottom - rcClientPos.top);
PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1);
// To make a nice small call tip window, it is only sized to fit most normal characters without accents
int ascent = surfaceWindow->Ascent(font) - surfaceWindow->InternalLeading(font);
// For each line...
// Draw the definition in three parts: before highlight, highlighted, after highlight
int ytext = rcClient.top + ascent + 1;
rcClient.bottom = ytext + surfaceWindow->Descent(font) + 1;
char *chunkVal = val;
bool moreChunks = true;
int maxWidth = 0;
while (moreChunks) {
char *chunkEnd = strchr(chunkVal, '\n');
if (chunkEnd == NULL) {
chunkEnd = chunkVal + strlen(chunkVal);
moreChunks = false;
}
int chunkOffset = chunkVal - val;
int chunkLength = chunkEnd - chunkVal;
int chunkEndOffset = chunkOffset + chunkLength;
int thisStartHighlight = Platform::Maximum(startHighlight, chunkOffset);
thisStartHighlight = Platform::Minimum(thisStartHighlight, chunkEndOffset);
thisStartHighlight -= chunkOffset;
int thisEndHighlight = Platform::Maximum(endHighlight, chunkOffset);
thisEndHighlight = Platform::Minimum(thisEndHighlight, chunkEndOffset);
thisEndHighlight -= chunkOffset;
rcClient.top = ytext - ascent - 1;
int x = 5;
DrawChunk(surfaceWindow, x, chunkVal, 0, thisStartHighlight,
ytext, rcClient, false, draw);
DrawChunk(surfaceWindow, x, chunkVal, thisStartHighlight, thisEndHighlight,
ytext, rcClient, true, draw);
DrawChunk(surfaceWindow, x, chunkVal, thisEndHighlight, chunkLength,
ytext, rcClient, false, draw);
chunkVal = chunkEnd + 1;
ytext += lineHeight;
rcClient.bottom += lineHeight;
maxWidth = Platform::Maximum(maxWidth, x);
}
return maxWidth;
}
void CallTip::PaintCT(Surface *surfaceWindow) {
if (!val)
return;
PRectangle rcClientPos = wCallTip.GetClientPosition();
PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left,
rcClientPos.bottom - rcClientPos.top);
PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1);
surfaceWindow->FillRectangle(rcClient, colourBG.allocated);
offsetMain = 5;
PaintContents(surfaceWindow, true);
// Draw a raised border around the edges of the window
surfaceWindow->MoveTo(0, rcClientSize.bottom - 1);
surfaceWindow->PenColour(colourShade.allocated);
surfaceWindow->LineTo(rcClientSize.right - 1, rcClientSize.bottom - 1);
surfaceWindow->LineTo(rcClientSize.right - 1, 0);
surfaceWindow->PenColour(colourLight.allocated);
surfaceWindow->LineTo(0, 0);
surfaceWindow->LineTo(0, rcClientSize.bottom - 1);
}
void CallTip::MouseClick(Point pt) {
clickPlace = 0;
if (pt.y < lineHeight) {
if ((pt.x > xUp) && (pt.x < xUp + widthArrow - 2)) {
clickPlace = 1;
} else if ((pt.x > xDown) && (pt.x < xDown + widthArrow - 2)) {
clickPlace = 2;
}
}
}
PRectangle CallTip::CallTipStart(int pos, Point pt, const char *defn,
const char *faceName, int size,
int codePage_, Window &wParent) {
clickPlace = 0;
if (val)
delete []val;
val = new char[strlen(defn) + 1];
if (!val)
return PRectangle();
strcpy(val, defn);
codePage = codePage_;
Surface *surfaceMeasure = Surface::Allocate();
if (!surfaceMeasure)
return PRectangle();
surfaceMeasure->Init(wParent.GetID());
surfaceMeasure->SetUnicodeMode(SC_CP_UTF8 == codePage);
surfaceMeasure->SetDBCSMode(codePage);
startHighlight = 0;
endHighlight = 0;
inCallTipMode = true;
posStartCallTip = pos;
int deviceHeight = surfaceMeasure->DeviceHeightFont(size);
font.Create(faceName, SC_CHARSET_DEFAULT, deviceHeight, false, false);
// Look for multiple lines in the text
// Only support \n here - simply means container must avoid \r!
int numLines = 1;
const char *newline;
const char *look = val;
xUp = -100;
xDown = -100;
offsetMain = 5;
int width = PaintContents(surfaceMeasure, false) + 5;
while ((newline = strchr(look, '\n')) != NULL) {
look = newline + 1;
numLines++;
}
lineHeight = surfaceMeasure->Height(font);
// Extra line for border and an empty line at top and bottom
int height = lineHeight * numLines - surfaceMeasure->InternalLeading(font) + 2 + 2;
delete surfaceMeasure;
return PRectangle(pt.x - offsetMain, pt.y + 1, pt.x + width - offsetMain, pt.y + 1 + height);
}
void CallTip::CallTipCancel() {
inCallTipMode = false;
if (wCallTip.Created()) {
wCallTip.Destroy();
}
}
void CallTip::SetHighlight(int start, int end) {
// Avoid flashing by checking something has really changed
if ((start != startHighlight) || (end != endHighlight)) {
startHighlight = start;
endHighlight = end;
if (wCallTip.Created()) {
wCallTip.InvalidateAll();
}
}
}
<|endoftext|>
|
<commit_before>#include <cstdlib>
#include <ctime>
#include <sys/wait.h>
#include <fstream>
#include <set>
#include <string>
#include <iostream>
#include <deque>
#include <vector>
#include "Crawler.h"
#include "Downloader.h"
std::string Crawler::GenerateFileName()
{
return data_directory_ +
std::to_string(time(NULL)) + " " + std::to_string(rand());
}
// Return value:
// 0 - success
// 1 - failed to download
// 2 - received interruption signal
// 3 - download queue is empty
int Crawler::FetchNextPage()
{
if (download_queue_.container.empty())
{
return 3;
}
std::string link = download_queue_.container.front();
if (link.compare(0, root_path_.length(), root_path_) != 0)
{
link = root_path_ + link;
}
std::string filename = GenerateFileName();
std::cout << "Downloading " << link << std::endl;
int result = Downloader::DownloadPage(link, filename);
// check if program got signal to quit
if (WIFSIGNALED(result) &&
(WTERMSIG(result) == SIGINT || WTERMSIG(result) == SIGQUIT))
{
return 2;
}
// decode value that was returned by system() call
result = WEXITSTATUS(result);
if (result != 0)
{
std::cerr << "\033[1;31mFailed to fetch page " <<
link << "\033[0m" << std::endl;
}
if (result != 0)
{
return 1;
}
download_queue_.container.pop_front();
GetLinks(filename);
return 0;
}
void Crawler::GetLinks(const std::string& filename)
{
std::ifstream file(filename);
char ch;
while (file.get(ch))
{
int current = 0;
while (current < link_prefix_.length() &&
ch == link_prefix_[current])
{
current++;
if (!file.get(ch))
{
break;
}
}
if (current != link_prefix_.length())
{
continue;
}
std::string link;
bool flag = true;
do
{
if (ch != '"')
{
link.append(1, ch);
}
if (!file.get(ch))
{
flag = false;
break;
}
for (char banned_symbol : banned_symbols_)
{
if (ch == banned_symbol)
{
flag = false;
}
}
} while (ch != '"');
if (!flag ||
link.compare(0,
required_link_prefix_.length(),
required_link_prefix_) != 0)
{
continue;
}
if (visited_links_.container.count(link) == 0)
{
visited_links_.container.insert(link);
download_queue_.container.push_back(link);
}
}
}
Crawler::Crawler(const std::string& data_directory,
const std::string& root_path,
const std::string& required_link_prefix,
const std::vector<char>& banned_symbols) :
data_directory_(data_directory),
root_path_(root_path),
required_link_prefix_(required_link_prefix),
banned_symbols_(banned_symbols)
{
download_queue_ =
SaveableStringContainer<std::deque<std::string>>
(data_directory_ + queue_filename_);
visited_links_ =
SaveableStringContainer<std::unordered_set<std::string>>
(data_directory_ + visited_filename_);
}
void Crawler::Crawl(const std::string& start_page)
{
if (download_queue_.container.empty())
{
download_queue_.container.push_back(start_page);
visited_links_.container.insert(start_page);
}
while (FetchNextPage() <= 1)
{ }
}
<commit_msg>Fix bug with 404 pages.<commit_after>#include <cstdlib>
#include <ctime>
#include <sys/wait.h>
#include <fstream>
#include <set>
#include <string>
#include <iostream>
#include <deque>
#include <vector>
#include "Crawler.h"
#include "Downloader.h"
std::string Crawler::GenerateFileName()
{
return data_directory_ +
std::to_string(time(NULL)) + " " + std::to_string(rand());
}
// Return value:
// 0 - success
// 1 - failed to download
// 2 - received interruption signal
// 3 - download queue is empty
int Crawler::FetchNextPage()
{
if (download_queue_.container.empty())
{
return 3;
}
std::string link = download_queue_.container.front();
if (link.compare(0, root_path_.length(), root_path_) != 0)
{
link = root_path_ + link;
}
std::string filename = GenerateFileName();
std::cout << "Downloading " << link << std::endl;
int result = Downloader::DownloadPage(link, filename);
// check if program got signal to quit
if (WIFSIGNALED(result) &&
(WTERMSIG(result) == SIGINT || WTERMSIG(result) == SIGQUIT))
{
return 2;
}
// decode value that was returned by system() call
result = WEXITSTATUS(result);
if (result != 0)
{
std::cerr << "\033[1;31mFailed to fetch page " <<
link << "\033[0m" << std::endl;
}
if (result != 0 && result != 8)
// 8 means server issued an error response (like 404) and we should
// probably just ignore it
{
return 1;
}
download_queue_.container.pop_front();
GetLinks(filename);
return 0;
}
void Crawler::GetLinks(const std::string& filename)
{
std::ifstream file(filename);
char ch;
while (file.get(ch))
{
int current = 0;
while (current < link_prefix_.length() &&
ch == link_prefix_[current])
{
current++;
if (!file.get(ch))
{
break;
}
}
if (current != link_prefix_.length())
{
continue;
}
std::string link;
bool flag = true;
do
{
if (ch != '"')
{
link.append(1, ch);
}
if (!file.get(ch))
{
flag = false;
break;
}
for (char banned_symbol : banned_symbols_)
{
if (ch == banned_symbol)
{
flag = false;
}
}
} while (ch != '"');
if (!flag ||
link.compare(0,
required_link_prefix_.length(),
required_link_prefix_) != 0)
{
continue;
}
if (visited_links_.container.count(link) == 0)
{
visited_links_.container.insert(link);
download_queue_.container.push_back(link);
}
}
}
Crawler::Crawler(const std::string& data_directory,
const std::string& root_path,
const std::string& required_link_prefix,
const std::vector<char>& banned_symbols) :
data_directory_(data_directory),
root_path_(root_path),
required_link_prefix_(required_link_prefix),
banned_symbols_(banned_symbols)
{
download_queue_ =
SaveableStringContainer<std::deque<std::string>>
(data_directory_ + queue_filename_);
visited_links_ =
SaveableStringContainer<std::unordered_set<std::string>>
(data_directory_ + visited_filename_);
}
void Crawler::Crawl(const std::string& start_page)
{
if (download_queue_.container.empty())
{
download_queue_.container.push_back(start_page);
visited_links_.container.insert(start_page);
}
while (FetchNextPage() <= 1)
{ }
}
<|endoftext|>
|
<commit_before>/**
* @file Decoder.cpp
* @copyright (c) 2014 by Petr Zemek (s3rvac@gmail.com) and contributors
* @license BSD, see the @c LICENSE file for more details
* @brief Implementation of the Decoder class.
*/
#include "Decoder.h"
#include <cassert>
#include <regex>
#include <sstream>
#include "BInteger.h"
#include "Utils.h"
namespace bencoding {
/**
* @brief Constructs a new exception with the given message.
*/
DecodingError::DecodingError(const std::string &what):
std::runtime_error(what) {}
/**
* @brief Constructs a decoder.
*/
Decoder::Decoder() {}
/**
* @brief Creates a new decoder.
*/
std::unique_ptr<Decoder> Decoder::create() {
return std::unique_ptr<Decoder>(new Decoder());
}
/**
* @brief Decodes the given bencoded data and returns them.
*/
std::unique_ptr<BItem> Decoder::decode(const std::string &data) {
std::istringstream input(data);
return decode(input);
}
/**
* @brief Reads all the data from the given @a input, decodes them and returns
* them.
*/
std::unique_ptr<BItem> Decoder::decode(std::istream &input) {
switch (input.peek()) {
case 'i':
return decodeInteger(input);
default:
throw DecodingError("unexpected character: '" +
std::to_string(input.peek()) + "'");
}
assert(false && "should never happen");
return std::unique_ptr<BItem>();
}
/**
* @brief Decodes an integer from @a input.
*
* @par Format
* @code
* i<integer encoded in base ten ASCII>e
* @endcode
*
* @par Example
* @code
* i3e represents the integer 3
* @endcode
*
* Moreover, only the significant digits should be used, one cannot pad the
* integer with zeroes, such as @c i04e (see the <a
* href="https://wiki.theory.org/BitTorrentSpecification#Bencoding">
* specification</a>).
*/
std::unique_ptr<BInteger> Decoder::decodeInteger(std::istream &input) const {
return decodeEncodedInteger(readEncodedInteger(input));
}
/**
* @brief Reads an encoded integer from @a input.
*/
std::string Decoder::readEncodedInteger(std::istream &input) const {
// See the description of decodeInteger() for the format and example.
std::string encodedInteger;
bool encodedIntegerReadCorrectly = readUntil(input, encodedInteger, 'e');
if (!encodedIntegerReadCorrectly) {
throw DecodingError("error during the decoding of an integer near '" +
encodedInteger + "'");
}
return encodedInteger;
}
/**
* @brief Decodes the given encoded integer.
*/
std::unique_ptr<BInteger> Decoder::decodeEncodedInteger(
const std::string &encodedInteger) const {
// See the description of decodeInteger() for the format and example.
std::regex integerRegex("i([-+]?(0|[1-9][0-9]*))e");
std::smatch match;
bool valid = std::regex_match(encodedInteger, match, integerRegex);
if (!valid) {
throw DecodingError("encountered an encoded integer of invalid format: '" +
encodedInteger + "'");
}
BInteger::ValueType integerValue;
strToNum(match[1].str(), integerValue);
return BInteger::create(integerValue);
}
} // namespace bencoding
<commit_msg>Decoder: Fix the message of DecodingError with input.peek().<commit_after>/**
* @file Decoder.cpp
* @copyright (c) 2014 by Petr Zemek (s3rvac@gmail.com) and contributors
* @license BSD, see the @c LICENSE file for more details
* @brief Implementation of the Decoder class.
*/
#include "Decoder.h"
#include <cassert>
#include <regex>
#include <sstream>
#include "BInteger.h"
#include "Utils.h"
namespace bencoding {
/**
* @brief Constructs a new exception with the given message.
*/
DecodingError::DecodingError(const std::string &what):
std::runtime_error(what) {}
/**
* @brief Constructs a decoder.
*/
Decoder::Decoder() {}
/**
* @brief Creates a new decoder.
*/
std::unique_ptr<Decoder> Decoder::create() {
return std::unique_ptr<Decoder>(new Decoder());
}
/**
* @brief Decodes the given bencoded data and returns them.
*/
std::unique_ptr<BItem> Decoder::decode(const std::string &data) {
std::istringstream input(data);
return decode(input);
}
/**
* @brief Reads all the data from the given @a input, decodes them and returns
* them.
*/
std::unique_ptr<BItem> Decoder::decode(std::istream &input) {
switch (input.peek()) {
case 'i':
return decodeInteger(input);
default:
throw DecodingError(std::string("unexpected character: '") +
static_cast<char>(input.peek()) + "'");
}
assert(false && "should never happen");
return std::unique_ptr<BItem>();
}
/**
* @brief Decodes an integer from @a input.
*
* @par Format
* @code
* i<integer encoded in base ten ASCII>e
* @endcode
*
* @par Example
* @code
* i3e represents the integer 3
* @endcode
*
* Moreover, only the significant digits should be used, one cannot pad the
* integer with zeroes, such as @c i04e (see the <a
* href="https://wiki.theory.org/BitTorrentSpecification#Bencoding">
* specification</a>).
*/
std::unique_ptr<BInteger> Decoder::decodeInteger(std::istream &input) const {
return decodeEncodedInteger(readEncodedInteger(input));
}
/**
* @brief Reads an encoded integer from @a input.
*/
std::string Decoder::readEncodedInteger(std::istream &input) const {
// See the description of decodeInteger() for the format and example.
std::string encodedInteger;
bool encodedIntegerReadCorrectly = readUntil(input, encodedInteger, 'e');
if (!encodedIntegerReadCorrectly) {
throw DecodingError("error during the decoding of an integer near '" +
encodedInteger + "'");
}
return encodedInteger;
}
/**
* @brief Decodes the given encoded integer.
*/
std::unique_ptr<BInteger> Decoder::decodeEncodedInteger(
const std::string &encodedInteger) const {
// See the description of decodeInteger() for the format and example.
std::regex integerRegex("i([-+]?(0|[1-9][0-9]*))e");
std::smatch match;
bool valid = std::regex_match(encodedInteger, match, integerRegex);
if (!valid) {
throw DecodingError("encountered an encoded integer of invalid format: '" +
encodedInteger + "'");
}
BInteger::ValueType integerValue;
strToNum(match[1].str(), integerValue);
return BInteger::create(integerValue);
}
} // namespace bencoding
<|endoftext|>
|
<commit_before>#include <cmath>
#include <limits>
#include "Lander/Geometry.h"
namespace {
const Lander::Point INVALID_POINT(
std::numeric_limits<double>::quiet_NaN(),
std::numeric_limits<double>::quiet_NaN()
);
/**
* Based on a:
* public domain function by Darel Rex Finley, 2006
* Determines the intersection point of the line segment defined by points A and B
* with the line segment defined by points C and D.
*
* @return a Point if the intersection point was found.
* Returns an invalid Point if there is no determinable intersection point.
*/
bool lineSegmentIntersection(
double Ax, double Ay,
double Bx, double By,
double Cx, double Cy,
double Dx, double Dy,
double *X, double *Y
) {
double distAB, theCos, theSin, newX, ABpos ;
// Fail if the segments share an end-point.
if ((Ax==Cx && Ay==Cy) || (Bx==Cx && By==Cy)
|| (Ax==Dx && Ay==Dy) || (Bx==Dx && By==Dy)) {
return false; }
// (1) Translate the system so that point A is on the origin.
Bx-=Ax; By-=Ay;
Cx-=Ax; Cy-=Ay;
Dx-=Ax; Dy-=Ay;
// Discover the length of segment A-B.
distAB = sqrt(Bx * Bx + By * By);
// (2) Rotate the system so that point B is on the positive X axis.
theCos = Bx / distAB;
theSin = By / distAB;
newX = Cx * theCos + Cy * theSin;
Cy = Cy * theCos - Cx * theSin;
Cx = newX;
newX = Dx * theCos + Dy * theSin;
Dy = Dy * theCos - Dx * theSin;
Dx = newX;
// Fail if segment C-D doesn't cross line A-B.
if ((Cy < 0.0 && Dy < 0.0) || (Cy >= 0.0 && Dy >= 0.0))
return false;
// (3) Discover the position of the intersection point along line A-B.
ABpos=Dx+(Cx-Dx)*Dy/(Dy-Cy);
// Fail if segment C-D crosses line A-B outside of segment A-B.
if ((ABpos < 0.0) || (ABpos > distAB)) return false;
// (4) Apply the discovered position to line A-B in the original coordinate system.
*X=Ax+ABpos*theCos;
*Y=Ay+ABpos*theSin;
// Success.
return true;
}
}
namespace Lander {
/* Point utilities! */
Point::operator bool() const
{
return !(isnan(x) || isnan(y));
}
Point Point::operator-() const
{
return Point(-x, -y);
}
Point Point::operator+(const Point& other) const
{
return Point(x + other.x, y + other.y);
}
Point Point::operator-(const Point& other) const
{
return *this + -other;
}
bool Point::operator==(const Point& other) const
{
return x == other.x && y == other.y;
}
/*
* Line utilities!
*/
Line Line::translate(const Point& origin) const
{
return Line(start + origin, end + origin);
}
Point Line::intersection(const Line& other) const
{
double x, y;
// Fail if either line segment is zero-length.
if (isZeroLength() || other.isZeroLength()) return INVALID_POINT;
bool didIntersect = lineSegmentIntersection(
this->start.x, this->start.y,
this->end.x, this->end.y,
other.start.x, other.start.y,
other.end.x, other.end.y,
&x, &y
);
if (didIntersect) {
return Point(x, y);
} else {
return INVALID_POINT;
}
}
bool Line::isZeroLength() const
{
return start == end;
}
}
<commit_msg>Use line translation.<commit_after>#include <cmath>
#include <limits>
#include "Lander/Geometry.h"
//#include <iostream>
namespace {
const Lander::Point INVALID_POINT(
std::numeric_limits<double>::quiet_NaN(),
std::numeric_limits<double>::quiet_NaN()
);
/**
* Based on a:
* public domain function by Darel Rex Finley, 2006
* Determines the intersection point of the line segment defined by points A and B
* with the line segment defined by points C and D.
*
* @return a Point if the intersection point was found.
* Returns an invalid Point if there is no determinable intersection point.
*/
bool lineSegmentIntersection(
double Ax, double Ay,
double Bx, double By,
double Cx, double Cy,
double Dx, double Dy,
double *X, double *Y
) {
double distAB, theCos, theSin, newX, ABpos ;
// Discover the length of segment A-B.
distAB = sqrt(Bx * Bx + By * By);
//std::cerr << Ax << ',' << Ay << "=>" << Bx << ',' << By << std::endl;
//std::cerr << Cx << ',' << Cy << "=>" << Dx << ',' << Dy << std::endl;
// (2) Rotate the system so that point B is on the positive X axis.
theCos = Bx / distAB;
theSin = By / distAB;
newX = Cx * theCos + Cy * theSin;
Cy = Cy * theCos - Cx * theSin;
Cx = newX;
newX = Dx * theCos + Dy * theSin;
Dy = Dy * theCos - Dx * theSin;
Dx = newX;
// Fail if segment C-D doesn't cross line A-B.
if ((Cy < 0.0 && Dy < 0.0) || (Cy >= 0.0 && Dy >= 0.0))
return false;
// (3) Discover the position of the intersection point along line A-B.
ABpos=Dx+(Cx-Dx)*Dy/(Dy-Cy);
// Fail if segment C-D crosses line A-B outside of segment A-B.
if ((ABpos < 0.0) || (ABpos > distAB)) return false;
// (4) Apply the discovered position to line A-B in the original coordinate system.
*X=Ax+ABpos*theCos;
*Y=Ay+ABpos*theSin;
// Success.
return true;
}
}
namespace Lander {
/* Point utilities! */
Point::operator bool() const
{
return !(isnan(x) || isnan(y));
}
Point Point::operator-() const
{
return Point(-x, -y);
}
Point Point::operator+(const Point& other) const
{
return Point(x + other.x, y + other.y);
}
Point Point::operator-(const Point& other) const
{
return *this + -other;
}
bool Point::operator==(const Point& other) const
{
return x == other.x && y == other.y;
}
/*
* Line utilities!
*/
Line Line::translate(const Point& origin) const
{
return Line(start + origin, end + origin);
}
Point Line::intersection(const Line& other) const
{
double x, y;
// Fail if either line segment is zero-length.
if (isZeroLength() || other.isZeroLength()) return INVALID_POINT;
// SKIPPED: Fail if the segments share an end-point.
// (1) Translate the system so that point A is on the origin.
Line a = this->translate(-start);
Line b = other.translate(-start);
bool didIntersect = lineSegmentIntersection(
a.start.x, a.start.y,
a.end.x, a.end.y,
b.start.x, b.start.y,
b.end.x, b.end.y,
&x, &y
);
if (didIntersect) {
return Point(x, y);
} else {
return INVALID_POINT;
}
}
bool Line::isZeroLength() const
{
return start == end;
}
}
<|endoftext|>
|
<commit_before>#include "JWModules.hpp"
#include "dsp/digital.hpp"
struct GridSeq : Module {
enum ParamIds {
RUN_PARAM,
CLOCK_PARAM,
RESET_PARAM,
CELL_PARAM,
GATE_PARAM = CELL_PARAM + 16,
NUM_PARAMS = GATE_PARAM + 16,
};
enum InputIds {
CLOCK_INPUT,
EXT_CLOCK_INPUT,
RESET_INPUT,
RIGHT_INPUT, LEFT_INPUT, DOWN_INPUT, UP_INPUT,
NUM_INPUTS
};
enum OutputIds {
GATES_OUTPUT,
CELL_OUTPUT,
NUM_OUTPUTS
};
SchmittTrigger rightTrigger;
SchmittTrigger leftTrigger;
SchmittTrigger downTrigger;
SchmittTrigger upTrigger;
SchmittTrigger runningTrigger;
SchmittTrigger resetTrigger;
SchmittTrigger gateTriggers[16];
int index = 0;
int posX = 0;
int posY = 0;
float phase = 0.0;
bool gateState[16] = {};
bool running = true;
enum GateMode { TRIGGER, RETRIGGER, CONTINUOUS };
GateMode gateMode = TRIGGER;
PulseGenerator gatePulse;
// Lights
float resetLight = 0.0;
float runningLight = 0.0;
float stepLights[16] = {};
float gateLights[16] = {};
GridSeq() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS) {}
void step();
json_t *toJson() {
json_t *rootJ = json_object();
// running
json_object_set_new(rootJ, "running", json_boolean(running));
// gates
json_t *gatesJ = json_array();
for (int i = 0; i < 16; i++) {
json_t *gateJ = json_integer((int) gateState[i]);
json_array_append_new(gatesJ, gateJ);
}
json_object_set_new(rootJ, "gates", gatesJ);
// gateMode
json_t *gateModeJ = json_integer((int) gateMode);
json_object_set_new(rootJ, "gateMode", gateModeJ);
return rootJ;
}
void fromJson(json_t *rootJ) {
// running
json_t *runningJ = json_object_get(rootJ, "running");
if (runningJ)
running = json_is_true(runningJ);
// gates
json_t *gatesJ = json_object_get(rootJ, "gates");
if (gatesJ) {
for (int i = 0; i < 16; i++) {
json_t *gateJ = json_array_get(gatesJ, i);
if (gateJ)
gateState[i] = !!json_integer_value(gateJ);
}
}
// gateMode
json_t *gateModeJ = json_object_get(rootJ, "gateMode");
if (gateModeJ)
gateMode = (GateMode)json_integer_value(gateModeJ);
}
void initialize() {
for (int i = 0; i < 8; i++) {
gateState[i] = true;
}
}
void randomize() {
for (int i = 0; i < 8; i++) {
gateState[i] = (randomf() > 0.5);
}
}
};
void GridSeq::step() {
const float lightLambda = 0.075;
// Run
if (runningTrigger.process(params[RUN_PARAM].value)) {
running = !running;
}
runningLight = running ? 1.0 : 0.0;
bool nextStep = false;
// Reset
if (resetTrigger.process(params[RESET_PARAM].value + inputs[RESET_INPUT].value)) {
phase = 0.0;
posX = 0;
posY = 0;
nextStep = true;
resetLight = 1.0;
}
if(running){
if (rightTrigger.process(inputs[RIGHT_INPUT].value)) {
nextStep = true;
posX = posX == 3 ? 0 : posX + 1;
}
if (leftTrigger.process(inputs[LEFT_INPUT].value)) {
nextStep = true;
posX = posX == 0 ? 3 : posX - 1;
}
if (downTrigger.process(inputs[DOWN_INPUT].value)) {
nextStep = true;
posY = posY == 3 ? 0 : posY + 1;
}
if (upTrigger.process(inputs[UP_INPUT].value)) {
nextStep = true;
posY = posY == 0 ? 3 : posY - 1;
}
}
if (nextStep) {
index = posX + (posY * 4);
stepLights[index] = 1.0;
gatePulse.trigger(1e-3);
}
resetLight -= resetLight / lightLambda / gSampleRate;
bool pulse = gatePulse.process(1.0 / gSampleRate);
// Gate buttons
for (int i = 0; i < 16; i++) {
if (gateTriggers[i].process(params[GATE_PARAM + i].value)) {
gateState[i] = !gateState[i];
}
bool gateOn = (running && i == index && gateState[i]);
if (gateMode == TRIGGER)
gateOn = gateOn && pulse;
else if (gateMode == RETRIGGER)
gateOn = gateOn && !pulse;
stepLights[i] -= stepLights[i] / lightLambda / gSampleRate;
gateLights[i] = gateState[i] ? 1.0 - stepLights[i] : stepLights[i];
}
// Cells
bool gatesOn = (running && gateState[index]);
if (gateMode == TRIGGER)
gatesOn = gatesOn && pulse;
else if (gateMode == RETRIGGER)
gatesOn = gatesOn && !pulse;
// Outputs
float cellVal = params[CELL_PARAM + index].value;
outputs[CELL_OUTPUT].value = cellVal;
outputs[GATES_OUTPUT].value = gatesOn ? 10.0 : 0.0;
}
GridSeqWidget::GridSeqWidget() {
GridSeq *module = new GridSeq();
setModule(module);
box.size = Vec(15*20, 380);
{
SVGPanel *panel = new SVGPanel();
panel->box.size = box.size;
panel->setBackground(SVG::load(assetPlugin(plugin, "res/GridSeq.svg")));
addChild(panel);
}
addChild(createScrew<ScrewSilver>(Vec(15, 0)));
addChild(createScrew<ScrewSilver>(Vec(box.size.x-30, 0)));
addChild(createScrew<ScrewSilver>(Vec(15, 365)));
addChild(createScrew<ScrewSilver>(Vec(box.size.x-30, 365)));
addParam(createParam<LEDButton>(Vec(23, 90), module, GridSeq::RUN_PARAM, 0.0, 1.0, 0.0));
addChild(createValueLight<SmallLight<MyBlueValueLight>>(Vec(23+5, 90+5), &module->runningLight));
addInput(createInput<PJ301MPort>(Vec(20, 160), module, GridSeq::RESET_INPUT));
addParam(createParam<LEDButton>(Vec(23, 130), module, GridSeq::RESET_PARAM, 0.0, 1.0, 0.0));
addChild(createValueLight<SmallLight<GreenValueLight>>(Vec(23+5, 130+5), &module->resetLight));
addOutput(createOutput<PJ301MPort>(Vec(20, 238), module, GridSeq::GATES_OUTPUT));
addOutput(createOutput<PJ301MPort>(Vec(20, 299), module, GridSeq::CELL_OUTPUT));
addInput(createInput<PJ301MPort>(Vec(83, 90), module, GridSeq::RIGHT_INPUT));
addInput(createInput<PJ301MPort>(Vec(138, 90), module, GridSeq::LEFT_INPUT));
addInput(createInput<PJ301MPort>(Vec(193, 90), module, GridSeq::DOWN_INPUT));
addInput(createInput<PJ301MPort>(Vec(248, 90), module, GridSeq::UP_INPUT));
int boxSize = 55;
for (int x = 0; x < 4; x++) {
for (int y = 0; y < 4; y++) {
int knobX = x * boxSize + 76;
int knobY = y * boxSize + 149;
int idx = (x+(y*4));
addParam(createParam<SmallWhiteKnob>(Vec(knobX, knobY), module, GridSeq::CELL_PARAM + idx, 0.0, 6.0, 0.0));
addParam(createParam<LEDButton>(Vec(knobX+22, knobY-15), module, GridSeq::GATE_PARAM + idx, 0.0, 1.0, 0.0));
addChild(createValueLight<SmallLight<MyBlueValueLight>>(Vec(knobX+27, knobY-10), &module->gateLights[idx]));
}
}
}
struct GridSeqGateModeItem : MenuItem {
GridSeq *gridSeq;
GridSeq::GateMode gateMode;
void onAction() {
gridSeq->gateMode = gateMode;
}
void step() {
rightText = (gridSeq->gateMode == gateMode) ? "✔" : "";
}
};
Menu *GridSeqWidget::createContextMenu() {
Menu *menu = ModuleWidget::createContextMenu();
MenuLabel *spacerLabel = new MenuLabel();
menu->pushChild(spacerLabel);
GridSeq *gridSeq = dynamic_cast<GridSeq*>(module);
assert(gridSeq);
MenuLabel *modeLabel = new MenuLabel();
modeLabel->text = "Gate Mode";
menu->pushChild(modeLabel);
GridSeqGateModeItem *triggerItem = new GridSeqGateModeItem();
triggerItem->text = "Trigger";
triggerItem->gridSeq = gridSeq;
triggerItem->gateMode = GridSeq::TRIGGER;
menu->pushChild(triggerItem);
GridSeqGateModeItem *retriggerItem = new GridSeqGateModeItem();
retriggerItem->text = "Retrigger";
retriggerItem->gridSeq = gridSeq;
retriggerItem->gateMode = GridSeq::RETRIGGER;
menu->pushChild(retriggerItem);
GridSeqGateModeItem *continuousItem = new GridSeqGateModeItem();
continuousItem->text = "Continuous";
continuousItem->gridSeq = gridSeq;
continuousItem->gateMode = GridSeq::CONTINUOUS;
menu->pushChild(continuousItem);
return menu;
}
<commit_msg>fixed init<commit_after>#include "JWModules.hpp"
#include "dsp/digital.hpp"
struct GridSeq : Module {
enum ParamIds {
RUN_PARAM,
CLOCK_PARAM,
RESET_PARAM,
CELL_PARAM,
GATE_PARAM = CELL_PARAM + 16,
NUM_PARAMS = GATE_PARAM + 16,
};
enum InputIds {
CLOCK_INPUT,
EXT_CLOCK_INPUT,
RESET_INPUT,
RIGHT_INPUT, LEFT_INPUT, DOWN_INPUT, UP_INPUT,
NUM_INPUTS
};
enum OutputIds {
GATES_OUTPUT,
CELL_OUTPUT,
NUM_OUTPUTS
};
SchmittTrigger rightTrigger;
SchmittTrigger leftTrigger;
SchmittTrigger downTrigger;
SchmittTrigger upTrigger;
SchmittTrigger runningTrigger;
SchmittTrigger resetTrigger;
SchmittTrigger gateTriggers[16];
int index = 0;
int posX = 0;
int posY = 0;
float phase = 0.0;
bool gateState[16] = {};
bool running = true;
enum GateMode { TRIGGER, RETRIGGER, CONTINUOUS };
GateMode gateMode = TRIGGER;
PulseGenerator gatePulse;
// Lights
float resetLight = 0.0;
float runningLight = 0.0;
float stepLights[16] = {};
float gateLights[16] = {};
GridSeq() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS) {}
void step();
json_t *toJson() {
json_t *rootJ = json_object();
// running
json_object_set_new(rootJ, "running", json_boolean(running));
// gates
json_t *gatesJ = json_array();
for (int i = 0; i < 16; i++) {
json_t *gateJ = json_integer((int) gateState[i]);
json_array_append_new(gatesJ, gateJ);
}
json_object_set_new(rootJ, "gates", gatesJ);
// gateMode
json_t *gateModeJ = json_integer((int) gateMode);
json_object_set_new(rootJ, "gateMode", gateModeJ);
return rootJ;
}
void fromJson(json_t *rootJ) {
// running
json_t *runningJ = json_object_get(rootJ, "running");
if (runningJ)
running = json_is_true(runningJ);
// gates
json_t *gatesJ = json_object_get(rootJ, "gates");
if (gatesJ) {
for (int i = 0; i < 16; i++) {
json_t *gateJ = json_array_get(gatesJ, i);
if (gateJ)
gateState[i] = !!json_integer_value(gateJ);
}
}
// gateMode
json_t *gateModeJ = json_object_get(rootJ, "gateMode");
if (gateModeJ)
gateMode = (GateMode)json_integer_value(gateModeJ);
}
void initialize() {
for (int i = 0; i < 16; i++) {
gateState[i] = true;
}
}
void randomize() {
for (int i = 0; i < 16; i++) {
gateState[i] = (randomf() > 0.5);
}
}
};
void GridSeq::step() {
const float lightLambda = 0.075;
// Run
if (runningTrigger.process(params[RUN_PARAM].value)) {
running = !running;
}
runningLight = running ? 1.0 : 0.0;
bool nextStep = false;
// Reset
if (resetTrigger.process(params[RESET_PARAM].value + inputs[RESET_INPUT].value)) {
phase = 0.0;
posX = 0;
posY = 0;
nextStep = true;
resetLight = 1.0;
}
if(running){
if (rightTrigger.process(inputs[RIGHT_INPUT].value)) {
nextStep = true;
posX = posX == 3 ? 0 : posX + 1;
}
if (leftTrigger.process(inputs[LEFT_INPUT].value)) {
nextStep = true;
posX = posX == 0 ? 3 : posX - 1;
}
if (downTrigger.process(inputs[DOWN_INPUT].value)) {
nextStep = true;
posY = posY == 3 ? 0 : posY + 1;
}
if (upTrigger.process(inputs[UP_INPUT].value)) {
nextStep = true;
posY = posY == 0 ? 3 : posY - 1;
}
}
if (nextStep) {
index = posX + (posY * 4);
stepLights[index] = 1.0;
gatePulse.trigger(1e-3);
}
resetLight -= resetLight / lightLambda / gSampleRate;
bool pulse = gatePulse.process(1.0 / gSampleRate);
// Gate buttons
for (int i = 0; i < 16; i++) {
if (gateTriggers[i].process(params[GATE_PARAM + i].value)) {
gateState[i] = !gateState[i];
}
bool gateOn = (running && i == index && gateState[i]);
if (gateMode == TRIGGER)
gateOn = gateOn && pulse;
else if (gateMode == RETRIGGER)
gateOn = gateOn && !pulse;
stepLights[i] -= stepLights[i] / lightLambda / gSampleRate;
gateLights[i] = gateState[i] ? 1.0 - stepLights[i] : stepLights[i];
}
// Cells
bool gatesOn = (running && gateState[index]);
if (gateMode == TRIGGER)
gatesOn = gatesOn && pulse;
else if (gateMode == RETRIGGER)
gatesOn = gatesOn && !pulse;
// Outputs
float cellVal = params[CELL_PARAM + index].value;
outputs[CELL_OUTPUT].value = cellVal;
outputs[GATES_OUTPUT].value = gatesOn ? 10.0 : 0.0;
}
GridSeqWidget::GridSeqWidget() {
GridSeq *module = new GridSeq();
setModule(module);
box.size = Vec(15*20, 380);
{
SVGPanel *panel = new SVGPanel();
panel->box.size = box.size;
panel->setBackground(SVG::load(assetPlugin(plugin, "res/GridSeq.svg")));
addChild(panel);
}
addChild(createScrew<ScrewSilver>(Vec(15, 0)));
addChild(createScrew<ScrewSilver>(Vec(box.size.x-30, 0)));
addChild(createScrew<ScrewSilver>(Vec(15, 365)));
addChild(createScrew<ScrewSilver>(Vec(box.size.x-30, 365)));
addParam(createParam<LEDButton>(Vec(23, 90), module, GridSeq::RUN_PARAM, 0.0, 1.0, 0.0));
addChild(createValueLight<SmallLight<MyBlueValueLight>>(Vec(23+5, 90+5), &module->runningLight));
addInput(createInput<PJ301MPort>(Vec(20, 160), module, GridSeq::RESET_INPUT));
addParam(createParam<LEDButton>(Vec(23, 130), module, GridSeq::RESET_PARAM, 0.0, 1.0, 0.0));
addChild(createValueLight<SmallLight<GreenValueLight>>(Vec(23+5, 130+5), &module->resetLight));
addOutput(createOutput<PJ301MPort>(Vec(20, 238), module, GridSeq::GATES_OUTPUT));
addOutput(createOutput<PJ301MPort>(Vec(20, 299), module, GridSeq::CELL_OUTPUT));
addInput(createInput<PJ301MPort>(Vec(83, 90), module, GridSeq::RIGHT_INPUT));
addInput(createInput<PJ301MPort>(Vec(138, 90), module, GridSeq::LEFT_INPUT));
addInput(createInput<PJ301MPort>(Vec(193, 90), module, GridSeq::DOWN_INPUT));
addInput(createInput<PJ301MPort>(Vec(248, 90), module, GridSeq::UP_INPUT));
int boxSize = 55;
for (int x = 0; x < 4; x++) {
for (int y = 0; y < 4; y++) {
int knobX = x * boxSize + 76;
int knobY = y * boxSize + 149;
int idx = (x+(y*4));
addParam(createParam<SmallWhiteKnob>(Vec(knobX, knobY), module, GridSeq::CELL_PARAM + idx, 0.0, 6.0, 0.0));
addParam(createParam<LEDButton>(Vec(knobX+22, knobY-15), module, GridSeq::GATE_PARAM + idx, 0.0, 1.0, 0.0));
addChild(createValueLight<SmallLight<MyBlueValueLight>>(Vec(knobX+27, knobY-10), &module->gateLights[idx]));
}
}
}
struct GridSeqGateModeItem : MenuItem {
GridSeq *gridSeq;
GridSeq::GateMode gateMode;
void onAction() {
gridSeq->gateMode = gateMode;
}
void step() {
rightText = (gridSeq->gateMode == gateMode) ? "✔" : "";
}
};
Menu *GridSeqWidget::createContextMenu() {
Menu *menu = ModuleWidget::createContextMenu();
MenuLabel *spacerLabel = new MenuLabel();
menu->pushChild(spacerLabel);
GridSeq *gridSeq = dynamic_cast<GridSeq*>(module);
assert(gridSeq);
MenuLabel *modeLabel = new MenuLabel();
modeLabel->text = "Gate Mode";
menu->pushChild(modeLabel);
GridSeqGateModeItem *triggerItem = new GridSeqGateModeItem();
triggerItem->text = "Trigger";
triggerItem->gridSeq = gridSeq;
triggerItem->gateMode = GridSeq::TRIGGER;
menu->pushChild(triggerItem);
GridSeqGateModeItem *retriggerItem = new GridSeqGateModeItem();
retriggerItem->text = "Retrigger";
retriggerItem->gridSeq = gridSeq;
retriggerItem->gateMode = GridSeq::RETRIGGER;
menu->pushChild(retriggerItem);
GridSeqGateModeItem *continuousItem = new GridSeqGateModeItem();
continuousItem->text = "Continuous";
continuousItem->gridSeq = gridSeq;
continuousItem->gateMode = GridSeq::CONTINUOUS;
menu->pushChild(continuousItem);
return menu;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <cassert>
#include "HelpCmd.h"
#include "CommandSet.h"
// ---------------------------------------------------------------------------
cigma::HelpCmd::HelpCmd()
{
name = "help";
commands = 0;
}
cigma::HelpCmd::~HelpCmd()
{
}
void cigma::HelpCmd::setCmdMap(CommandSet::CmdMap *cmds)
{
/* pointer to set of commands */
this->commands = cmds;
/* prepare usage list from current set of commands */
usageList.clear();
std::string prefix = " ";
CommandSet::CmdMap::iterator it;
for (it = commands->begin(); it != commands->end(); ++it)
{
Command *cmd = it->second;
usageList.push_back(prefix + (cmd->name));
}
}
// ---------------------------------------------------------------------------
void cigma::HelpCmd::setupOptions(AnyOption *opt)
{
//std::cout << "Calling cigma::HelpCmd::setupOptions()" << std::endl;
assert(opt != 0);
/* prepare preamble */
opt->addUsage("Usage: cigma <subcommand> [options] [args]");
opt->addUsage("Type 'cigma help <subcommand>' for help on a specific subcommand.");
opt->addUsage("");
opt->addUsage("Available subcommands");
/* pass contents of usage list to opt object */
std::vector<std::string>::iterator it;
for (it = usageList.begin(); it != usageList.end(); ++it)
{
opt->addUsage(it->c_str());
}
// XXX: need to set at least one flag or option (bug in AnyOption)
opt->setFlag("help",'h');
}
void cigma::HelpCmd::configure(AnyOption *opt)
{
//std::cout << "Calling cigma::HelpCmd::configure()" << std::endl;
assert(opt != 0);
int argc = opt->getArgc();
subcommand = "";
if (argc == 0)
{
subcommand = "help";
}
else
{
subcommand = opt->getArgv(0);
if (argc >= 2)
{
// XXX: too many args!
std::cerr << "Too many arguments! "
<< "Taking only '"
<< subcommand
<< "'" << std::endl;
}
}
}
int cigma::HelpCmd::run()
{
//std::cout << "Calling cigma::HelpCmd::run()" << std::endl;
CommandSet::CmdMap::iterator it = commands->find(subcommand);
if (it != commands->end())
{
AnyOption opt;
Command *cmd = it->second;
cmd->setupOptions(&opt);
opt.printUsage();
return 0;
}
else
{
std::cerr << "Unknown command: '"
<< subcommand
<< "'" << std::endl;
}
return 1;
}
<commit_msg>Added 'using namespace cigma' to HelpCmd.cpp<commit_after>#include <iostream>
#include <cassert>
#include "HelpCmd.h"
#include "CommandSet.h"
using namespace cigma;
// ---------------------------------------------------------------------------
HelpCmd::HelpCmd()
{
name = "help";
commands = 0;
}
HelpCmd::~HelpCmd()
{
}
void HelpCmd::setCmdMap(CommandSet::CmdMap *cmds)
{
/* pointer to set of commands */
this->commands = cmds;
/* prepare usage list from current set of commands */
usageList.clear();
std::string prefix = " ";
CommandSet::CmdMap::iterator it;
for (it = commands->begin(); it != commands->end(); ++it)
{
Command *cmd = it->second;
usageList.push_back(prefix + (cmd->name));
}
}
// ---------------------------------------------------------------------------
void HelpCmd::setupOptions(AnyOption *opt)
{
//std::cout << "Calling cigma::HelpCmd::setupOptions()" << std::endl;
assert(opt != 0);
/* prepare preamble */
opt->addUsage("Usage: cigma <subcommand> [options] [args]");
opt->addUsage("Type 'cigma help <subcommand>' for help on a specific subcommand.");
opt->addUsage("");
opt->addUsage("Available subcommands");
/* pass contents of usage list to opt object */
std::vector<std::string>::iterator it;
for (it = usageList.begin(); it != usageList.end(); ++it)
{
opt->addUsage(it->c_str());
}
// XXX: need to set at least one flag or option (bug in AnyOption)
opt->setFlag("help",'h');
}
void HelpCmd::configure(AnyOption *opt)
{
//std::cout << "Calling cigma::HelpCmd::configure()" << std::endl;
assert(opt != 0);
int argc = opt->getArgc();
subcommand = "";
if (argc == 0)
{
subcommand = "help";
}
else
{
subcommand = opt->getArgv(0);
if (argc >= 2)
{
// XXX: too many args!
std::cerr << "Too many arguments! "
<< "Taking only '"
<< subcommand
<< "'" << std::endl;
}
}
}
int HelpCmd::run()
{
//std::cout << "Calling cigma::HelpCmd::run()" << std::endl;
CommandSet::CmdMap::iterator it = commands->find(subcommand);
if (it != commands->end())
{
AnyOption opt;
Command *cmd = it->second;
cmd->setupOptions(&opt);
opt.printUsage();
return 0;
}
else
{
std::cerr << "Unknown command: '"
<< subcommand
<< "'" << std::endl;
}
return 1;
}
<|endoftext|>
|
<commit_before>
#include "Internal.hpp"
#include <LuminoEngine/Tilemap/TilemapLayer.hpp>
#include <LuminoEngine/Tilemap/TilemapModel.hpp>
#include <LuminoEngine/Tilemap/Tileset.hpp>
namespace ln {
//==============================================================================
// AbstractTilemapLayer
AbstractTilemapLayer::AbstractTilemapLayer()
: m_tileSize(1, 1)
, m_orientation(TilemapOrientation::UpFlow)
{
}
AbstractTilemapLayer::~AbstractTilemapLayer()
{
}
void AbstractTilemapLayer::init()
{
Object::init();
}
//void AbstractTilemapLayer::resize(int width, int height)
//{
// m_size.set(width, height);
// m_data.resize(width * height);
//}
//
//void AbstractTilemapLayer::setTileId(int x, int y, int id)
//{
// m_data[y * m_size.width + x] = id;
//}
//
//int AbstractTilemapLayer::getTileId(int x, int y) const
//{
// // TODO: round
// // clamp
// if (x < 0 || m_size.width <= x) return 0;
// if (y < 0 || m_size.height <= y) return 0;
//
// return m_data[y * m_size.width + x];
//}
void AbstractTilemapLayer::setTileSize(const Size& size)
{
m_tileSize = size;
}
// bounds: Y+ を上方向とした、ローカル空間上の描画範囲
void AbstractTilemapLayer::render(TilemapModel* model, RenderingContext* context, const Matrix& transform, const detail::TilemapBounds& bounds)
{
//int l, t, r, b; // 2D array としてどの範囲を描画するか
float wL, wT, wR, wB; // world としてどの範囲を描画するか
//Vector3 offset;
int l, t, r, b;
{
wL = l = static_cast<int>(bounds.l / m_tileSize.width);
wT = t = static_cast<int>(bounds.t / m_tileSize.height);
wR = r = static_cast<int>(bounds.r / m_tileSize.width);
wB = b = static_cast<int>(bounds.b / m_tileSize.height);
//wL *= m_tileSize.width;
//wT *= m_tileSize.height;
//wR *= m_tileSize.width;
//wB *= m_tileSize.height;
//t = -t;
//b = -b;
//if (m_orientation == TilemapOrientation::UpFlow)
//{
// offset.y = m_tileSize.height * m_size.height;
// // Y=0 から↑へ向かって配置する。(0, 0) = [0, m_size.height-1]
// //t = m_size.height - t;
// //b = m_size.height - b;
//}
//else if (m_orientation == TilemapOrientation::DownFlow)
//{
// // Y=0 から↓へ向かって配置する。(0, 0) = [0, 0]
// //t = -t;
// //b = -b;
//}
//else
//{
// LN_UNREACHABLE();
//}
}
int width = getWidth();
int height = getHeight();
//float tw = m_tileSize.width;
//float th = m_tileSize.height;
for (int y = t; y >= b; y--)
{
// clamp
//if (y < 0 || m_size.height <= y) continue;
for (int x = l; x < r; x++)
{
// clamp
//if (x < 0 || m_size.width <= x) continue;
int tileId = 0;
if (m_orientation == TilemapOrientation::UpFlow)
{
tileId = getTileId(x, height - y - 1);
}
else if (m_orientation == TilemapOrientation::DownFlow) {
tileId = getTileId(x, -y);
}
else {
LN_UNREACHABLE();
}
if (tileId > 0)
{
Vector3 pos(x * m_tileSize.width, y * m_tileSize.height, 0);
Tileset* tileset;
int localId;
if (model->fetchTileset(tileId, &tileset, &localId)) {
tileset->drawTile(context, localId, pos, m_tileSize);
}
}
}
}
//for (int y = t; y < renderRange.bottom; ++y)
//{
// Vector3 pos = offset + (stepY * y) + (stepX * renderRange.left);
// for (int x = renderRange.left; x < renderRange.right; ++x)
// {
// }
//}
}
//==============================================================================
// TilemapLayer
Ref<TilemapLayer> TilemapLayer::create()
{
return newObject<TilemapLayer>();
}
TilemapLayer::TilemapLayer()
{
}
TilemapLayer::~TilemapLayer()
{
}
void TilemapLayer::init()
{
AbstractTilemapLayer::init();
}
void TilemapLayer::resize(int width, int height)
{
m_size.set(width, height);
m_data.resize(width * height);
}
void TilemapLayer::setTileId(int x, int y, int id)
{
m_data[y * m_size.width + x] = id;
}
int TilemapLayer::getTileId(int x, int y) const
{
// TODO: round
// clamp
if (x < 0 || m_size.width <= x) return 0;
if (y < 0 || m_size.height <= y) return 0;
return m_data[y * m_size.width + x];
}
} // namespace ln
<commit_msg>border<commit_after>
#include "Internal.hpp"
#include <LuminoEngine/Tilemap/TilemapLayer.hpp>
#include <LuminoEngine/Tilemap/TilemapModel.hpp>
#include <LuminoEngine/Tilemap/Tileset.hpp>
namespace ln {
//==============================================================================
// AbstractTilemapLayer
AbstractTilemapLayer::AbstractTilemapLayer()
: m_tileSize(1, 1)
, m_orientation(TilemapOrientation::UpFlow)
{
}
AbstractTilemapLayer::~AbstractTilemapLayer()
{
}
void AbstractTilemapLayer::init()
{
Object::init();
}
//void AbstractTilemapLayer::resize(int width, int height)
//{
// m_size.set(width, height);
// m_data.resize(width * height);
//}
//
//void AbstractTilemapLayer::setTileId(int x, int y, int id)
//{
// m_data[y * m_size.width + x] = id;
//}
//
//int AbstractTilemapLayer::getTileId(int x, int y) const
//{
// // TODO: round
// // clamp
// if (x < 0 || m_size.width <= x) return 0;
// if (y < 0 || m_size.height <= y) return 0;
//
// return m_data[y * m_size.width + x];
//}
void AbstractTilemapLayer::setTileSize(const Size& size)
{
m_tileSize = size;
}
// bounds: Y+ を上方向とした、ローカル空間上の描画範囲
void AbstractTilemapLayer::render(TilemapModel* model, RenderingContext* context, const Matrix& transform, const detail::TilemapBounds& bounds)
{
//int l, t, r, b; // 2D array としてどの範囲を描画するか
float wL, wT, wR, wB; // world としてどの範囲を描画するか
//Vector3 offset;
int l, t, r, b;
{
wL = l = static_cast<int>(bounds.l / m_tileSize.width);
wT = t = static_cast<int>(bounds.t / m_tileSize.height);
wR = r = static_cast<int>(bounds.r / m_tileSize.width);
wB = b = static_cast<int>(bounds.b / m_tileSize.height);
//wL *= m_tileSize.width;
//wT *= m_tileSize.height;
//wR *= m_tileSize.width;
//wB *= m_tileSize.height;
//t = -t;
//b = -b;
//if (m_orientation == TilemapOrientation::UpFlow)
//{
// offset.y = m_tileSize.height * m_size.height;
// // Y=0 から↑へ向かって配置する。(0, 0) = [0, m_size.height-1]
// //t = m_size.height - t;
// //b = m_size.height - b;
//}
//else if (m_orientation == TilemapOrientation::DownFlow)
//{
// // Y=0 から↓へ向かって配置する。(0, 0) = [0, 0]
// //t = -t;
// //b = -b;
//}
//else
//{
// LN_UNREACHABLE();
//}
r += 1;
b -= 1;
}
int width = getWidth();
int height = getHeight();
//float tw = m_tileSize.width;
//float th = m_tileSize.height;
for (int y = t; y >= b; y--)
{
// clamp
//if (y < 0 || m_size.height <= y) continue;
for (int x = l; x < r; x++)
{
// clamp
//if (x < 0 || m_size.width <= x) continue;
int tileId = 0;
if (m_orientation == TilemapOrientation::UpFlow)
{
tileId = getTileId(x, height - y - 1);
}
else if (m_orientation == TilemapOrientation::DownFlow) {
tileId = getTileId(x, -y);
}
else {
LN_UNREACHABLE();
}
if (tileId > 0)
{
Vector3 pos(x * m_tileSize.width, y * m_tileSize.height, 0);
Tileset* tileset;
int localId;
if (model->fetchTileset(tileId, &tileset, &localId)) {
tileset->drawTile(context, localId, pos, m_tileSize);
}
}
}
}
//for (int y = t; y < renderRange.bottom; ++y)
//{
// Vector3 pos = offset + (stepY * y) + (stepX * renderRange.left);
// for (int x = renderRange.left; x < renderRange.right; ++x)
// {
// }
//}
}
//==============================================================================
// TilemapLayer
Ref<TilemapLayer> TilemapLayer::create()
{
return newObject<TilemapLayer>();
}
TilemapLayer::TilemapLayer()
{
}
TilemapLayer::~TilemapLayer()
{
}
void TilemapLayer::init()
{
AbstractTilemapLayer::init();
}
void TilemapLayer::resize(int width, int height)
{
m_size.set(width, height);
m_data.resize(width * height);
}
void TilemapLayer::setTileId(int x, int y, int id)
{
m_data[y * m_size.width + x] = id;
}
int TilemapLayer::getTileId(int x, int y) const
{
// TODO: round
// clamp
if (x < 0 || m_size.width <= x) return 0;
if (y < 0 || m_size.height <= y) return 0;
return m_data[y * m_size.width + x];
}
} // namespace ln
<|endoftext|>
|
<commit_before>//template provided by SurgicalSteel a.k.a Yuwono Bangun Nagoro for competitive programming purposes
#include <bits/stdc++.h>
#define Mas_Bangun using
#define cinta namespace
#define Mbak_IsyanaSarasvati std
#define PI 3.1415926535897932384626433832795
#define MOD 1000000007
#define PB push_back
#define MP make_pair
Mas_Bangun cinta Mbak_IsyanaSarasvati;
struct point{int x,y;};
int toInt(string x)
{
istringstream ss(x);
int a;
ss>>a;
return a;
}
string tostr(int x)
{
ostringstream ss;
ss<<x;
return ss.str();
}
vector<int> sieve(int n)
{
vector <int> res;
int temp=1;
for(int i=2;i<=n;i++)
{
for(int a=2;a<=i;a++)
{if(i%a==0){temp++;}}
if(temp==2){res.PB(i);}
temp=1;
}
return res;
}
string eliminateAt(string x, int num)//eliminates a single substring of a string in a given position
{
if(num==0){return x.substr(1,x.length()-1);}
else if(num==x.length()-1){return x.substr(0,x.length()-1);}
else{return x.substr(0,num)+x.substr(num+1,x.length()-1);}
}
long long factorial(int num) //finds factorial of given integer
{
if(num==0){return 1;}
else{return num*factorial(num-1);}
}
long long pangkatp(int base,int exp) //powers base by exponen
{
if(exp==0){return 1;}
else{return base*pangkatp(base,exp-1);}
}
int sumdigit(string a) //sums all digit on given string (if the string only contains digits)
{
int sum=0;
for(int x=0;x<a.length();x++){sum+=toInt(a.substr(x,1));}
return sum;
}
int absolutey(int a) //returns absolute value of an integer
{if(a<0){return a*-1;}else{return a;}}
bool contains(string a,string b) //Checks if string a contains string b, where a.length()>=b.length()
{
bool valid=false;
int x=0;
while(x<a.length()-b.length()&&!valid)
{
if(a.substr(x,b.length())==b){valid=true;}
else{x++;}
}
return valid;
}
char toCharSingle(string x)//single substring as input. Converts single substring to single char
{
char a[1];
strncpy(a,x.c_str(),sizeof(a));
return a[0];
}
string toStringSingle(char x) //converts single char to single substring
{
string c;
stringstream ss;
ss<<x;
ss>>c;
return c;
}
string reverse(string a) //reverses a given string
{
string x;
for(int y=a.length()-1;y>=0;y--)
{x+=a.substr(y,1);}
return x;
}
string tobase(int num,int base) //translates bitmask from decimal number to base n. 2<=n<=9
{
string a;
while(num>0)
{
a+=tostr(num%base);
num=(num-(num%base))/base;
}
return reverse(a);
}
int main()
{
//MAIN SECTION GOES HERE
/* //In case you need, use them like cin and cout
fstream fin("input.txt");
fstream fout("output.txt");
*/
return 0;
}
<commit_msg>edit sieve on template<commit_after>//template provided by SurgicalSteel a.k.a Yuwono Bangun Nagoro for competitive programming purposes
#include <bits/stdc++.h>
#define Mas_Bangun using
#define cinta namespace
#define Mbak_IsyanaSarasvati std
#define PI 3.1415926535897932384626433832795
#define MOD 1000000007
#define PB push_back
#define MP make_pair
Mas_Bangun cinta Mbak_IsyanaSarasvati;
struct point{int x,y;};
int toInt(string x)
{
istringstream ss(x);
int a;
ss>>a;
return a;
}
string tostr(int x)
{
ostringstream ss;
ss<<x;
return ss.str();
}
vector<int> sieve(int n)
{
vector <int> res;
int temp=1;
for(int i=2;i<=n;i++)
{
for(int a=2;a<=i;a++)
{if(i%a==0){temp++;}}
if(temp==2){res.PB(i);}
temp=1;
}
return res;
}
string eliminateAt(string x, int num)//eliminates a single substring of a string in a given position
{
if(num==0){return x.substr(1,x.length()-1);}
else if(num==x.length()-1){return x.substr(0,x.length()-1);}
else{return x.substr(0,num)+x.substr(num+1,x.length()-1);}
}
long long factorial(int num) //finds factorial of given integer
{
if(num==0){return 1;}
else{return num*factorial(num-1);}
}
long long pangkatp(int base,int exp) //powers base by exponen
{
if(exp==0){return 1;}
else{return base*pangkatp(base,exp-1);}
}
int sumdigit(string a) //sums all digit on given string (if the string only contains digits)
{
int sum=0;
for(int x=0;x<a.length();x++){sum+=toInt(a.substr(x,1));}
return sum;
}
int absolutey(int a) //returns absolute value of an integer
{if(a<0){return a*-1;}else{return a;}}
bool contains(string a,string b) //Checks if string a contains string b, where a.length()>=b.length()
{
bool valid=false;
int x=0;
while(x<a.length()-b.length()&&!valid)
{
if(a.substr(x,b.length())==b){valid=true;}
else{x++;}
}
return valid;
}
char toCharSingle(string x)//single substring as input. Converts single substring to single char
{
char a[1];
strncpy(a,x.c_str(),sizeof(a));
return a[0];
}
string toStringSingle(char x) //converts single char to single substring
{
string c;
stringstream ss;
ss<<x;
ss>>c;
return c;
}
string reverse(string a) //reverses a given string
{
string x;
for(int y=a.length()-1;y>=0;y--)
{x+=a.substr(y,1);}
return x;
}
string tobase(int num,int base) //translates bitmask from decimal number to base n. 2<=n<=9
{
string a;
while(num>0)
{
a+=tostr(num%base);
num=(num-(num%base))/base;
}
return reverse(a);
}
int main()
{
//MAIN SECTION GOES HERE
/* //In case you need, use them like cin and cout
fstream fin("input.txt");
fstream fout("output.txt");
*/
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2017 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include <dali/internal/graphics/gles20/egl-implementation.h>
// EXTERNAL INCLUDES
#include <dali/integration-api/debug.h>
#include <dali/public-api/common/dali-common.h>
#include <dali/public-api/common/dali-vector.h>
// INTERNAL INCLUDES
#include <dali/internal/graphics/gles20/gl-implementation.h>
#include <dali/internal/graphics/gles20/egl-debug.h>
// EGL constants use C style casts
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
#define TEST_EGL_ERROR(lastCommand) \
{ \
EGLint err = eglGetError(); \
if (err != EGL_SUCCESS) \
{ \
DALI_LOG_ERROR("EGL error after %s\n", lastCommand); \
Egl::PrintError(err); \
DALI_ASSERT_ALWAYS(0 && "EGL error"); \
} \
}
EglImplementation::EglImplementation( int multiSamplingLevel,
Integration::DepthBufferAvailable depthBufferRequired,
Integration::StencilBufferAvailable stencilBufferRequired )
: mContextAttribs(),
mEglNativeDisplay( 0 ),
mEglNativeWindow( 0 ),
mCurrentEglNativePixmap( 0 ),
mEglDisplay( 0 ),
mEglConfig( 0 ),
mEglContext( 0 ),
mCurrentEglSurface( 0 ),
mMultiSamplingLevel( multiSamplingLevel ),
mColorDepth( COLOR_DEPTH_24 ),
mGlesInitialized( false ),
mIsOwnSurface( true ),
mContextCurrent( false ),
mIsWindow( true ),
mDepthBufferRequired( depthBufferRequired == Integration::DepthBufferAvailable::TRUE ),
mStencilBufferRequired( stencilBufferRequired == Integration::StencilBufferAvailable::TRUE )
{
}
EglImplementation::~EglImplementation()
{
TerminateGles();
}
bool EglImplementation::InitializeGles( EGLNativeDisplayType display, bool isOwnSurface )
{
if ( !mGlesInitialized )
{
mEglNativeDisplay = display;
//@todo see if we can just EGL_DEFAULT_DISPLAY instead
mEglDisplay = eglGetDisplay(mEglNativeDisplay);
EGLint error = eglGetError();
if( mEglDisplay == NULL && error != EGL_SUCCESS )
{
throw Dali::DaliException( "", "OpenGL ES is not supported");
}
EGLint majorVersion = 0;
EGLint minorVersion = 0;
if ( !eglInitialize( mEglDisplay, &majorVersion, &minorVersion ) )
{
return false;
}
eglBindAPI(EGL_OPENGL_ES_API);
mContextAttribs.Clear();
#if DALI_GLES_VERSION >= 30
mContextAttribs.Reserve(5);
mContextAttribs.PushBack( EGL_CONTEXT_MAJOR_VERSION_KHR );
mContextAttribs.PushBack( DALI_GLES_VERSION / 10 );
mContextAttribs.PushBack( EGL_CONTEXT_MINOR_VERSION_KHR );
mContextAttribs.PushBack( DALI_GLES_VERSION % 10 );
#else // DALI_GLES_VERSION >= 30
mContextAttribs.Reserve(3);
mContextAttribs.PushBack( EGL_CONTEXT_CLIENT_VERSION );
mContextAttribs.PushBack( 2 );
#endif // DALI_GLES_VERSION >= 30
mContextAttribs.PushBack( EGL_NONE );
mGlesInitialized = true;
mIsOwnSurface = isOwnSurface;
}
return mGlesInitialized;
}
bool EglImplementation::CreateContext()
{
// make sure a context isn't created twice
DALI_ASSERT_ALWAYS( (mEglContext == 0) && "EGL context recreated" );
mEglContext = eglCreateContext(mEglDisplay, mEglConfig, NULL, &(mContextAttribs[0]));
TEST_EGL_ERROR("eglCreateContext render thread");
DALI_ASSERT_ALWAYS( EGL_NO_CONTEXT != mEglContext && "EGL context not created" );
DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_VENDOR : %s ***\n", glGetString(GL_VENDOR));
DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_RENDERER : %s ***\n", glGetString(GL_RENDERER));
DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_VERSION : %s ***\n", glGetString(GL_VERSION));
DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_SHADING_LANGUAGE_VERSION : %s***\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** Supported Extensions ***\n%s\n\n", glGetString(GL_EXTENSIONS));
return true;
}
void EglImplementation::DestroyContext()
{
DALI_ASSERT_ALWAYS( mEglContext && "no EGL context" );
eglDestroyContext( mEglDisplay, mEglContext );
mEglContext = 0;
}
void EglImplementation::DestroySurface()
{
if(mIsOwnSurface && mCurrentEglSurface)
{
// Make context null to prevent crash in driver side
MakeContextNull();
eglDestroySurface( mEglDisplay, mCurrentEglSurface );
mCurrentEglSurface = 0;
}
}
void EglImplementation::MakeContextCurrent()
{
mContextCurrent = true;
if(mIsOwnSurface)
{
eglMakeCurrent( mEglDisplay, mCurrentEglSurface, mCurrentEglSurface, mEglContext );
}
EGLint error = eglGetError();
if ( error != EGL_SUCCESS )
{
Egl::PrintError(error);
DALI_ASSERT_ALWAYS(false && "MakeContextCurrent failed!");
}
// We want to display this information all the time, so use the LogMessage directly
Integration::Log::LogMessage(Integration::Log::DebugInfo, "EGL Information\n"
" Vendor: %s\n"
" Version: %s\n"
" Client APIs: %s\n"
" Extensions: %s\n",
eglQueryString(mEglDisplay, EGL_VENDOR),
eglQueryString(mEglDisplay, EGL_VERSION),
eglQueryString(mEglDisplay, EGL_CLIENT_APIS),
eglQueryString(mEglDisplay, EGL_EXTENSIONS));
}
void EglImplementation::MakeCurrent( EGLNativePixmapType pixmap, EGLSurface eglSurface )
{
mCurrentEglNativePixmap = pixmap;
mCurrentEglSurface = eglSurface;
if(mIsOwnSurface)
{
eglMakeCurrent( mEglDisplay, mCurrentEglSurface, mCurrentEglSurface, mEglContext );
}
EGLint error = eglGetError();
if ( error != EGL_SUCCESS )
{
Egl::PrintError(error);
DALI_ASSERT_ALWAYS(false && "MakeCurrent failed!");
}
}
void EglImplementation::MakeContextNull()
{
mContextCurrent = false;
// clear the current context
eglMakeCurrent( mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT );
}
void EglImplementation::TerminateGles()
{
if ( mGlesInitialized )
{
// Make context null to prevent crash in driver side
MakeContextNull();
if(mIsOwnSurface && mCurrentEglSurface)
{
eglDestroySurface(mEglDisplay, mCurrentEglSurface);
}
eglDestroyContext(mEglDisplay, mEglContext);
eglTerminate(mEglDisplay);
mEglDisplay = NULL;
mEglConfig = NULL;
mEglContext = NULL;
mCurrentEglSurface = NULL;
mGlesInitialized = false;
}
}
bool EglImplementation::IsGlesInitialized() const
{
return mGlesInitialized;
}
void EglImplementation::SwapBuffers()
{
eglSwapBuffers( mEglDisplay, mCurrentEglSurface );
}
void EglImplementation::CopyBuffers()
{
eglCopyBuffers( mEglDisplay, mCurrentEglSurface, mCurrentEglNativePixmap );
}
void EglImplementation::WaitGL()
{
eglWaitGL();
}
void EglImplementation::ChooseConfig( bool isWindowType, ColorDepth depth )
{
if(mEglConfig && isWindowType == mIsWindow && mColorDepth == depth)
{
return;
}
mIsWindow = isWindowType;
EGLint numConfigs;
Vector<EGLint> configAttribs;
configAttribs.Reserve(31);
if(isWindowType)
{
configAttribs.PushBack( EGL_SURFACE_TYPE );
configAttribs.PushBack( EGL_WINDOW_BIT );
}
else
{
configAttribs.PushBack( EGL_SURFACE_TYPE );
configAttribs.PushBack( EGL_PIXMAP_BIT );
}
configAttribs.PushBack( EGL_RENDERABLE_TYPE );
#if DALI_GLES_VERSION >= 30
#ifdef _ARCH_ARM_
configAttribs.PushBack( EGL_OPENGL_ES3_BIT_KHR );
#else
// There is a bug in the desktop emulator
// Requesting for ES3 causes eglCreateContext even though it allows to ask
// for a configuration that supports GLES 3.0
configAttribs.PushBack( EGL_OPENGL_ES2_BIT );
#endif // _ARCH_ARM_
#else // DALI_GLES_VERSION >= 30
Integration::Log::LogMessage( Integration::Log::DebugInfo, "Using OpenGL ES 2 \n" );
configAttribs.PushBack( EGL_OPENGL_ES2_BIT );
#endif //DALI_GLES_VERSION >= 30
#if DALI_GLES_VERSION >= 30
// TODO: enable this flag when it becomes supported
// configAttribs.PushBack( EGL_CONTEXT_FLAGS_KHR );
// configAttribs.PushBack( EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE_BIT_KHR );
#endif //DALI_GLES_VERSION >= 30
configAttribs.PushBack( EGL_RED_SIZE );
configAttribs.PushBack( 8 );
configAttribs.PushBack( EGL_GREEN_SIZE );
configAttribs.PushBack( 8 );
configAttribs.PushBack( EGL_BLUE_SIZE );
configAttribs.PushBack( 8 );
configAttribs.PushBack( EGL_ALPHA_SIZE );
#ifdef _ARCH_ARM_
configAttribs.PushBack( (depth == COLOR_DEPTH_32) ? 8 : 0 );
#else
// There is a bug in the desktop emulator
// setting EGL_ALPHA_SIZE to 8 results in eglChooseConfig failing
configAttribs.PushBack( 0 );
#endif // _ARCH_ARM_
configAttribs.PushBack( EGL_DEPTH_SIZE );
configAttribs.PushBack( mDepthBufferRequired ? 24 : 0 );
configAttribs.PushBack( EGL_STENCIL_SIZE );
configAttribs.PushBack( mStencilBufferRequired ? 8 : 0 );
#ifndef DALI_PROFILE_UBUNTU
if( mMultiSamplingLevel != EGL_DONT_CARE )
{
configAttribs.PushBack( EGL_SAMPLES );
configAttribs.PushBack( mMultiSamplingLevel );
configAttribs.PushBack( EGL_SAMPLE_BUFFERS );
configAttribs.PushBack( 1 );
}
#endif // DALI_PROFILE_UBUNTU
configAttribs.PushBack( EGL_NONE );
if ( eglChooseConfig( mEglDisplay, &(configAttribs[0]), &mEglConfig, 1, &numConfigs ) != EGL_TRUE )
{
EGLint error = eglGetError();
switch (error)
{
case EGL_BAD_DISPLAY:
{
DALI_LOG_ERROR("Display is not an EGL display connection\n");
break;
}
case EGL_BAD_ATTRIBUTE:
{
DALI_LOG_ERROR("The parameter configAttribs contains an invalid frame buffer configuration attribute or an attribute value that is unrecognized or out of range\n");
break;
}
case EGL_NOT_INITIALIZED:
{
DALI_LOG_ERROR("Display has not been initialized\n");
break;
}
case EGL_BAD_PARAMETER:
{
DALI_LOG_ERROR("The parameter numConfig is NULL\n");
break;
}
default:
{
DALI_LOG_ERROR("Unknown error.\n");
}
}
DALI_ASSERT_ALWAYS(false && "eglChooseConfig failed!");
}
if ( numConfigs != 1 )
{
DALI_LOG_ERROR("No configurations found.\n");
TEST_EGL_ERROR("eglChooseConfig");
}
}
void EglImplementation::CreateSurfaceWindow( EGLNativeWindowType window, ColorDepth depth )
{
DALI_ASSERT_ALWAYS( ( mCurrentEglSurface == 0 ) && "EGL surface already exists" );
mEglNativeWindow = window;
mColorDepth = depth;
mIsWindow = true;
// egl choose config
ChooseConfig(mIsWindow, mColorDepth);
mCurrentEglSurface = eglCreateWindowSurface( mEglDisplay, mEglConfig, mEglNativeWindow, NULL );
TEST_EGL_ERROR("eglCreateWindowSurface");
DALI_ASSERT_ALWAYS( mCurrentEglSurface && "Create window surface failed" );
}
EGLSurface EglImplementation::CreateSurfacePixmap( EGLNativePixmapType pixmap, ColorDepth depth )
{
mCurrentEglNativePixmap = pixmap;
mColorDepth = depth;
mIsWindow = false;
// egl choose config
ChooseConfig(mIsWindow, mColorDepth);
mCurrentEglSurface = eglCreatePixmapSurface( mEglDisplay, mEglConfig, mCurrentEglNativePixmap, NULL );
TEST_EGL_ERROR("eglCreatePixmapSurface");
DALI_ASSERT_ALWAYS( mCurrentEglSurface && "Create pixmap surface failed" );
return mCurrentEglSurface;
}
bool EglImplementation::ReplaceSurfaceWindow( EGLNativeWindowType window )
{
bool contextLost = false;
// display connection has not changed, then we can just create a new surface
// the surface is bound to the context, so set the context to null
MakeContextNull();
// destroy the surface
DestroySurface();
// create the EGL surface
CreateSurfaceWindow( window, mColorDepth );
// set the context to be current with the new surface
MakeContextCurrent();
return contextLost;
}
bool EglImplementation::ReplaceSurfacePixmap( EGLNativePixmapType pixmap, EGLSurface& eglSurface )
{
bool contextLost = false;
// display connection has not changed, then we can just create a new surface
// create the EGL surface
eglSurface = CreateSurfacePixmap( pixmap, mColorDepth );
// set the eglSurface to be current
MakeCurrent( pixmap, eglSurface );
return contextLost;
}
EGLDisplay EglImplementation::GetDisplay() const
{
return mEglDisplay;
}
EGLDisplay EglImplementation::GetContext() const
{
return mEglContext;
}
} // namespace Adaptor
} // namespace Internal
} // namespace Dali
#pragma GCC diagnostic pop
<commit_msg>For underlay video playback, we also need to set the alpha value of the 24/32bit window.<commit_after>/*
* Copyright (c) 2017 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include <dali/internal/graphics/gles20/egl-implementation.h>
// EXTERNAL INCLUDES
#include <dali/integration-api/debug.h>
#include <dali/public-api/common/dali-common.h>
#include <dali/public-api/common/dali-vector.h>
// INTERNAL INCLUDES
#include <dali/internal/graphics/gles20/gl-implementation.h>
#include <dali/internal/graphics/gles20/egl-debug.h>
// EGL constants use C style casts
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
#define TEST_EGL_ERROR(lastCommand) \
{ \
EGLint err = eglGetError(); \
if (err != EGL_SUCCESS) \
{ \
DALI_LOG_ERROR("EGL error after %s\n", lastCommand); \
Egl::PrintError(err); \
DALI_ASSERT_ALWAYS(0 && "EGL error"); \
} \
}
EglImplementation::EglImplementation( int multiSamplingLevel,
Integration::DepthBufferAvailable depthBufferRequired,
Integration::StencilBufferAvailable stencilBufferRequired )
: mContextAttribs(),
mEglNativeDisplay( 0 ),
mEglNativeWindow( 0 ),
mCurrentEglNativePixmap( 0 ),
mEglDisplay( 0 ),
mEglConfig( 0 ),
mEglContext( 0 ),
mCurrentEglSurface( 0 ),
mMultiSamplingLevel( multiSamplingLevel ),
mColorDepth( COLOR_DEPTH_24 ),
mGlesInitialized( false ),
mIsOwnSurface( true ),
mContextCurrent( false ),
mIsWindow( true ),
mDepthBufferRequired( depthBufferRequired == Integration::DepthBufferAvailable::TRUE ),
mStencilBufferRequired( stencilBufferRequired == Integration::StencilBufferAvailable::TRUE )
{
}
EglImplementation::~EglImplementation()
{
TerminateGles();
}
bool EglImplementation::InitializeGles( EGLNativeDisplayType display, bool isOwnSurface )
{
if ( !mGlesInitialized )
{
mEglNativeDisplay = display;
//@todo see if we can just EGL_DEFAULT_DISPLAY instead
mEglDisplay = eglGetDisplay(mEglNativeDisplay);
EGLint error = eglGetError();
if( mEglDisplay == NULL && error != EGL_SUCCESS )
{
throw Dali::DaliException( "", "OpenGL ES is not supported");
}
EGLint majorVersion = 0;
EGLint minorVersion = 0;
if ( !eglInitialize( mEglDisplay, &majorVersion, &minorVersion ) )
{
return false;
}
eglBindAPI(EGL_OPENGL_ES_API);
mContextAttribs.Clear();
#if DALI_GLES_VERSION >= 30
mContextAttribs.Reserve(5);
mContextAttribs.PushBack( EGL_CONTEXT_MAJOR_VERSION_KHR );
mContextAttribs.PushBack( DALI_GLES_VERSION / 10 );
mContextAttribs.PushBack( EGL_CONTEXT_MINOR_VERSION_KHR );
mContextAttribs.PushBack( DALI_GLES_VERSION % 10 );
#else // DALI_GLES_VERSION >= 30
mContextAttribs.Reserve(3);
mContextAttribs.PushBack( EGL_CONTEXT_CLIENT_VERSION );
mContextAttribs.PushBack( 2 );
#endif // DALI_GLES_VERSION >= 30
mContextAttribs.PushBack( EGL_NONE );
mGlesInitialized = true;
mIsOwnSurface = isOwnSurface;
}
return mGlesInitialized;
}
bool EglImplementation::CreateContext()
{
// make sure a context isn't created twice
DALI_ASSERT_ALWAYS( (mEglContext == 0) && "EGL context recreated" );
mEglContext = eglCreateContext(mEglDisplay, mEglConfig, NULL, &(mContextAttribs[0]));
TEST_EGL_ERROR("eglCreateContext render thread");
DALI_ASSERT_ALWAYS( EGL_NO_CONTEXT != mEglContext && "EGL context not created" );
DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_VENDOR : %s ***\n", glGetString(GL_VENDOR));
DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_RENDERER : %s ***\n", glGetString(GL_RENDERER));
DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_VERSION : %s ***\n", glGetString(GL_VERSION));
DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_SHADING_LANGUAGE_VERSION : %s***\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** Supported Extensions ***\n%s\n\n", glGetString(GL_EXTENSIONS));
return true;
}
void EglImplementation::DestroyContext()
{
DALI_ASSERT_ALWAYS( mEglContext && "no EGL context" );
eglDestroyContext( mEglDisplay, mEglContext );
mEglContext = 0;
}
void EglImplementation::DestroySurface()
{
if(mIsOwnSurface && mCurrentEglSurface)
{
// Make context null to prevent crash in driver side
MakeContextNull();
eglDestroySurface( mEglDisplay, mCurrentEglSurface );
mCurrentEglSurface = 0;
}
}
void EglImplementation::MakeContextCurrent()
{
mContextCurrent = true;
if(mIsOwnSurface)
{
eglMakeCurrent( mEglDisplay, mCurrentEglSurface, mCurrentEglSurface, mEglContext );
}
EGLint error = eglGetError();
if ( error != EGL_SUCCESS )
{
Egl::PrintError(error);
DALI_ASSERT_ALWAYS(false && "MakeContextCurrent failed!");
}
// We want to display this information all the time, so use the LogMessage directly
Integration::Log::LogMessage(Integration::Log::DebugInfo, "EGL Information\n"
" Vendor: %s\n"
" Version: %s\n"
" Client APIs: %s\n"
" Extensions: %s\n",
eglQueryString(mEglDisplay, EGL_VENDOR),
eglQueryString(mEglDisplay, EGL_VERSION),
eglQueryString(mEglDisplay, EGL_CLIENT_APIS),
eglQueryString(mEglDisplay, EGL_EXTENSIONS));
}
void EglImplementation::MakeCurrent( EGLNativePixmapType pixmap, EGLSurface eglSurface )
{
mCurrentEglNativePixmap = pixmap;
mCurrentEglSurface = eglSurface;
if(mIsOwnSurface)
{
eglMakeCurrent( mEglDisplay, mCurrentEglSurface, mCurrentEglSurface, mEglContext );
}
EGLint error = eglGetError();
if ( error != EGL_SUCCESS )
{
Egl::PrintError(error);
DALI_ASSERT_ALWAYS(false && "MakeCurrent failed!");
}
}
void EglImplementation::MakeContextNull()
{
mContextCurrent = false;
// clear the current context
eglMakeCurrent( mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT );
}
void EglImplementation::TerminateGles()
{
if ( mGlesInitialized )
{
// Make context null to prevent crash in driver side
MakeContextNull();
if(mIsOwnSurface && mCurrentEglSurface)
{
eglDestroySurface(mEglDisplay, mCurrentEglSurface);
}
eglDestroyContext(mEglDisplay, mEglContext);
eglTerminate(mEglDisplay);
mEglDisplay = NULL;
mEglConfig = NULL;
mEglContext = NULL;
mCurrentEglSurface = NULL;
mGlesInitialized = false;
}
}
bool EglImplementation::IsGlesInitialized() const
{
return mGlesInitialized;
}
void EglImplementation::SwapBuffers()
{
eglSwapBuffers( mEglDisplay, mCurrentEglSurface );
}
void EglImplementation::CopyBuffers()
{
eglCopyBuffers( mEglDisplay, mCurrentEglSurface, mCurrentEglNativePixmap );
}
void EglImplementation::WaitGL()
{
eglWaitGL();
}
void EglImplementation::ChooseConfig( bool isWindowType, ColorDepth depth )
{
if(mEglConfig && isWindowType == mIsWindow && mColorDepth == depth)
{
return;
}
mIsWindow = isWindowType;
EGLint numConfigs;
Vector<EGLint> configAttribs;
configAttribs.Reserve(31);
if(isWindowType)
{
configAttribs.PushBack( EGL_SURFACE_TYPE );
configAttribs.PushBack( EGL_WINDOW_BIT );
}
else
{
configAttribs.PushBack( EGL_SURFACE_TYPE );
configAttribs.PushBack( EGL_PIXMAP_BIT );
}
configAttribs.PushBack( EGL_RENDERABLE_TYPE );
#if DALI_GLES_VERSION >= 30
#ifdef _ARCH_ARM_
configAttribs.PushBack( EGL_OPENGL_ES3_BIT_KHR );
#else
// There is a bug in the desktop emulator
// Requesting for ES3 causes eglCreateContext even though it allows to ask
// for a configuration that supports GLES 3.0
configAttribs.PushBack( EGL_OPENGL_ES2_BIT );
#endif // _ARCH_ARM_
#else // DALI_GLES_VERSION >= 30
Integration::Log::LogMessage( Integration::Log::DebugInfo, "Using OpenGL ES 2 \n" );
configAttribs.PushBack( EGL_OPENGL_ES2_BIT );
#endif //DALI_GLES_VERSION >= 30
#if DALI_GLES_VERSION >= 30
// TODO: enable this flag when it becomes supported
// configAttribs.PushBack( EGL_CONTEXT_FLAGS_KHR );
// configAttribs.PushBack( EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE_BIT_KHR );
#endif //DALI_GLES_VERSION >= 30
configAttribs.PushBack( EGL_RED_SIZE );
configAttribs.PushBack( 8 );
configAttribs.PushBack( EGL_GREEN_SIZE );
configAttribs.PushBack( 8 );
configAttribs.PushBack( EGL_BLUE_SIZE );
configAttribs.PushBack( 8 );
configAttribs.PushBack( EGL_ALPHA_SIZE );
#ifdef _ARCH_ARM_
// For underlay video playback, we also need to set the alpha value of the 24/32bit window.
configAttribs.PushBack( 8 );
#else
// There is a bug in the desktop emulator
// setting EGL_ALPHA_SIZE to 8 results in eglChooseConfig failing
configAttribs.PushBack( 0 );
#endif // _ARCH_ARM_
configAttribs.PushBack( EGL_DEPTH_SIZE );
configAttribs.PushBack( mDepthBufferRequired ? 24 : 0 );
configAttribs.PushBack( EGL_STENCIL_SIZE );
configAttribs.PushBack( mStencilBufferRequired ? 8 : 0 );
#ifndef DALI_PROFILE_UBUNTU
if( mMultiSamplingLevel != EGL_DONT_CARE )
{
configAttribs.PushBack( EGL_SAMPLES );
configAttribs.PushBack( mMultiSamplingLevel );
configAttribs.PushBack( EGL_SAMPLE_BUFFERS );
configAttribs.PushBack( 1 );
}
#endif // DALI_PROFILE_UBUNTU
configAttribs.PushBack( EGL_NONE );
if ( eglChooseConfig( mEglDisplay, &(configAttribs[0]), &mEglConfig, 1, &numConfigs ) != EGL_TRUE )
{
EGLint error = eglGetError();
switch (error)
{
case EGL_BAD_DISPLAY:
{
DALI_LOG_ERROR("Display is not an EGL display connection\n");
break;
}
case EGL_BAD_ATTRIBUTE:
{
DALI_LOG_ERROR("The parameter configAttribs contains an invalid frame buffer configuration attribute or an attribute value that is unrecognized or out of range\n");
break;
}
case EGL_NOT_INITIALIZED:
{
DALI_LOG_ERROR("Display has not been initialized\n");
break;
}
case EGL_BAD_PARAMETER:
{
DALI_LOG_ERROR("The parameter numConfig is NULL\n");
break;
}
default:
{
DALI_LOG_ERROR("Unknown error.\n");
}
}
DALI_ASSERT_ALWAYS(false && "eglChooseConfig failed!");
}
if ( numConfigs != 1 )
{
DALI_LOG_ERROR("No configurations found.\n");
TEST_EGL_ERROR("eglChooseConfig");
}
}
void EglImplementation::CreateSurfaceWindow( EGLNativeWindowType window, ColorDepth depth )
{
DALI_ASSERT_ALWAYS( ( mCurrentEglSurface == 0 ) && "EGL surface already exists" );
mEglNativeWindow = window;
mColorDepth = depth;
mIsWindow = true;
// egl choose config
ChooseConfig(mIsWindow, mColorDepth);
mCurrentEglSurface = eglCreateWindowSurface( mEglDisplay, mEglConfig, mEglNativeWindow, NULL );
TEST_EGL_ERROR("eglCreateWindowSurface");
DALI_ASSERT_ALWAYS( mCurrentEglSurface && "Create window surface failed" );
}
EGLSurface EglImplementation::CreateSurfacePixmap( EGLNativePixmapType pixmap, ColorDepth depth )
{
mCurrentEglNativePixmap = pixmap;
mColorDepth = depth;
mIsWindow = false;
// egl choose config
ChooseConfig(mIsWindow, mColorDepth);
mCurrentEglSurface = eglCreatePixmapSurface( mEglDisplay, mEglConfig, mCurrentEglNativePixmap, NULL );
TEST_EGL_ERROR("eglCreatePixmapSurface");
DALI_ASSERT_ALWAYS( mCurrentEglSurface && "Create pixmap surface failed" );
return mCurrentEglSurface;
}
bool EglImplementation::ReplaceSurfaceWindow( EGLNativeWindowType window )
{
bool contextLost = false;
// display connection has not changed, then we can just create a new surface
// the surface is bound to the context, so set the context to null
MakeContextNull();
// destroy the surface
DestroySurface();
// create the EGL surface
CreateSurfaceWindow( window, mColorDepth );
// set the context to be current with the new surface
MakeContextCurrent();
return contextLost;
}
bool EglImplementation::ReplaceSurfacePixmap( EGLNativePixmapType pixmap, EGLSurface& eglSurface )
{
bool contextLost = false;
// display connection has not changed, then we can just create a new surface
// create the EGL surface
eglSurface = CreateSurfacePixmap( pixmap, mColorDepth );
// set the eglSurface to be current
MakeCurrent( pixmap, eglSurface );
return contextLost;
}
EGLDisplay EglImplementation::GetDisplay() const
{
return mEglDisplay;
}
EGLDisplay EglImplementation::GetContext() const
{
return mEglContext;
}
} // namespace Adaptor
} // namespace Internal
} // namespace Dali
#pragma GCC diagnostic pop
<|endoftext|>
|
<commit_before>// Copyright 2008-present Contributors to the OpenImageIO project.
// SPDX-License-Identifier: BSD-3-Clause
// https://github.com/OpenImageIO/oiio
#include <cstdio>
#include <OpenImageIO/filesystem.h>
#include <OpenImageIO/imageio.h>
#include <OpenImageIO/strutil.h>
#include "bmp_pvt.h"
OIIO_PLUGIN_NAMESPACE_BEGIN
using namespace bmp_pvt;
class BmpOutput final : public ImageOutput {
public:
BmpOutput() { init(); }
~BmpOutput() override { close(); }
const char* format_name(void) const override { return "bmp"; }
int supports(string_view feature) const override;
bool open(const std::string& name, const ImageSpec& spec,
OpenMode mode) override;
bool close(void) override;
bool write_scanline(int y, int z, TypeDesc format, const void* data,
stride_t xstride) override;
bool write_tile(int x, int y, int z, TypeDesc format, const void* data,
stride_t xstride, stride_t ystride,
stride_t zstride) override;
private:
int64_t m_padded_scanline_size;
std::string m_filename;
bmp_pvt::BmpFileHeader m_bmp_header;
bmp_pvt::DibInformationHeader m_dib_header;
int64_t m_image_start;
unsigned int m_dither;
std::vector<unsigned char> m_tilebuffer;
std::vector<unsigned char> m_scratch;
std::vector<unsigned char> m_buf; // more tmp space for write_scanline
void init(void)
{
m_padded_scanline_size = 0;
m_filename.clear();
ioproxy_clear();
}
void create_and_write_file_header(void);
void create_and_write_bitmap_header(void);
};
// Obligatory material to make this a recognizable imageio plugin
OIIO_PLUGIN_EXPORTS_BEGIN
OIIO_EXPORT ImageOutput*
bmp_output_imageio_create()
{
return new BmpOutput;
}
OIIO_EXPORT const char* bmp_output_extensions[] = { "bmp", nullptr };
OIIO_PLUGIN_EXPORTS_END
int
BmpOutput::supports(string_view feature) const
{
return (feature == "alpha" || feature == "ioproxy");
}
bool
BmpOutput::open(const std::string& name, const ImageSpec& spec, OpenMode mode)
{
if (mode != Create) {
errorfmt("{} does not support subimages or MIP levels", format_name());
return false;
}
// saving 'name' and 'spec' for later use
m_filename = name;
m_spec = spec;
if (m_spec.nchannels != 1 && m_spec.nchannels != 3
&& m_spec.nchannels != 4) {
errorfmt("{} does not support {}-channel images\n", format_name(),
m_spec.nchannels);
return false;
}
// Only support 8 bit channels for now.
m_spec.set_format(TypeDesc::UINT8);
m_dither = m_spec.get_int_attribute("oiio:dither", 0);
int64_t file_size = m_spec.image_bytes() + BMP_HEADER_SIZE + WINDOWS_V3;
if (file_size >= int64_t(1) << 32) {
errorfmt("{} does not support files over 4GB in size\n", format_name());
return false;
}
ioproxy_retrieve_from_config(m_spec);
if (!ioproxy_use_or_open(name))
return false;
// Scanline size is rounded up to align to 4-byte boundary
m_padded_scanline_size = round_to_multiple(m_spec.scanline_bytes(), 4);
create_and_write_file_header();
create_and_write_bitmap_header();
m_image_start = iotell();
// If user asked for tiles -- which this format doesn't support, emulate
// it by buffering the whole image.
if (m_spec.tile_width && m_spec.tile_height)
m_tilebuffer.resize(m_spec.image_bytes());
return true;
}
bool
BmpOutput::write_scanline(int y, int z, TypeDesc format, const void* data,
stride_t xstride)
{
if (y > m_spec.height) {
errorfmt("Attempt to write too many scanlines to {}", m_filename);
close();
return false;
}
if (m_spec.width >= 0)
y = (m_spec.height - y - 1);
int64_t scanline_off = y * m_padded_scanline_size;
ioseek(m_image_start + scanline_off);
m_scratch.clear();
data = to_native_scanline(format, data, xstride, m_scratch, m_dither, y, z);
m_buf.assign((const unsigned char*)data,
(const unsigned char*)data + m_spec.scanline_bytes());
m_buf.resize(m_padded_scanline_size, 0); // pad with zeroes if needed
// Swap RGB pixels into BGR format
if (m_spec.nchannels >= 3)
for (int i = 0, iend = m_buf.size() - 2; i < iend;
i += m_spec.nchannels)
std::swap(m_buf[i], m_buf[i + 2]);
return iowrite(&m_buf[0], m_buf.size());
}
bool
BmpOutput::write_tile(int x, int y, int z, TypeDesc format, const void* data,
stride_t xstride, stride_t ystride, stride_t zstride)
{
// Emulate tiles by buffering the whole image
return copy_tile_to_image_buffer(x, y, z, format, data, xstride, ystride,
zstride, &m_tilebuffer[0]);
}
bool
BmpOutput::close(void)
{
if (!ioproxy_opened()) { // already closed
init();
return true;
}
bool ok = true;
if (m_spec.tile_width) {
// Handle tile emulation -- output the buffered pixels
OIIO_DASSERT(m_tilebuffer.size());
ok &= write_scanlines(m_spec.y, m_spec.y + m_spec.height, 0,
m_spec.format, &m_tilebuffer[0]);
std::vector<unsigned char>().swap(m_tilebuffer);
}
init();
return ok;
}
void
BmpOutput::create_and_write_file_header(void)
{
m_bmp_header.magic = MAGIC_BM;
int64_t data_size = m_padded_scanline_size * m_spec.height;
int palettesize = (m_spec.nchannels == 1) ? 4 * 256 : 0;
int64_t file_size = data_size + BMP_HEADER_SIZE + WINDOWS_V3 + palettesize;
m_bmp_header.fsize = file_size;
m_bmp_header.res1 = 0;
m_bmp_header.res2 = 0;
m_bmp_header.offset = BMP_HEADER_SIZE + WINDOWS_V3 + palettesize;
m_bmp_header.write_header(ioproxy());
}
void
BmpOutput::create_and_write_bitmap_header(void)
{
m_dib_header.size = WINDOWS_V3;
m_dib_header.width = m_spec.width;
m_dib_header.height = m_spec.height;
m_dib_header.cplanes = 1;
m_dib_header.compression = NO_COMPRESSION;
if (m_spec.nchannels == 1) {
// Special case -- write a 1-channel image as a gray palette
m_dib_header.bpp = 8;
m_dib_header.cpalete = 256;
m_dib_header.important = 256;
} else {
m_dib_header.bpp = m_spec.nchannels * 8;
m_dib_header.cpalete = 0;
m_dib_header.important = 0;
}
m_dib_header.isize = int32_t(m_spec.image_pixels());
m_dib_header.hres = 0;
m_dib_header.vres = 0;
string_view res_units = m_spec.get_string_attribute("ResolutionUnit");
if (Strutil::iequals(res_units, "m")
|| Strutil::iequals(res_units, "pixel per meter")) {
m_dib_header.hres = m_spec.get_int_attribute("XResolution");
m_dib_header.vres = m_spec.get_int_attribute("YResolution");
}
m_dib_header.write_header(ioproxy());
// Write palette, if there is one. This is only used for grayscale
// images, and the palette is just the 256 possible gray values.
for (int i = 0; i < m_dib_header.cpalete; ++i) {
unsigned char val[4] = { uint8_t(i), uint8_t(i), uint8_t(i), 255 };
iowrite(&val, 4);
}
}
OIIO_PLUGIN_NAMESPACE_END
<commit_msg>BMP output safety (#3673)<commit_after>// Copyright 2008-present Contributors to the OpenImageIO project.
// SPDX-License-Identifier: BSD-3-Clause
// https://github.com/OpenImageIO/oiio
#include <cstdio>
#include <OpenImageIO/filesystem.h>
#include <OpenImageIO/imageio.h>
#include <OpenImageIO/strutil.h>
#include "bmp_pvt.h"
OIIO_PLUGIN_NAMESPACE_BEGIN
using namespace bmp_pvt;
class BmpOutput final : public ImageOutput {
public:
BmpOutput() { init(); }
~BmpOutput() override { close(); }
const char* format_name(void) const override { return "bmp"; }
int supports(string_view feature) const override;
bool open(const std::string& name, const ImageSpec& spec,
OpenMode mode) override;
bool close(void) override;
bool write_scanline(int y, int z, TypeDesc format, const void* data,
stride_t xstride) override;
bool write_tile(int x, int y, int z, TypeDesc format, const void* data,
stride_t xstride, stride_t ystride,
stride_t zstride) override;
private:
int64_t m_padded_scanline_size;
std::string m_filename;
bmp_pvt::BmpFileHeader m_bmp_header;
bmp_pvt::DibInformationHeader m_dib_header;
int64_t m_image_start;
unsigned int m_dither;
std::vector<unsigned char> m_tilebuffer;
std::vector<unsigned char> m_scratch;
std::vector<unsigned char> m_buf; // more tmp space for write_scanline
void init(void)
{
m_padded_scanline_size = 0;
m_filename.clear();
ioproxy_clear();
}
void create_and_write_file_header(void);
void create_and_write_bitmap_header(void);
};
// Obligatory material to make this a recognizable imageio plugin
OIIO_PLUGIN_EXPORTS_BEGIN
OIIO_EXPORT ImageOutput*
bmp_output_imageio_create()
{
return new BmpOutput;
}
OIIO_EXPORT const char* bmp_output_extensions[] = { "bmp", nullptr };
OIIO_PLUGIN_EXPORTS_END
int
BmpOutput::supports(string_view feature) const
{
return (feature == "alpha" || feature == "ioproxy");
}
bool
BmpOutput::open(const std::string& name, const ImageSpec& spec, OpenMode mode)
{
if (mode != Create) {
errorfmt("{} does not support subimages or MIP levels", format_name());
return false;
}
// saving 'name' and 'spec' for later use
m_filename = name;
m_spec = spec;
if (m_spec.nchannels != 1 && m_spec.nchannels != 3
&& m_spec.nchannels != 4) {
errorfmt("{} does not support {}-channel images\n", format_name(),
m_spec.nchannels);
return false;
}
if (m_spec.x || m_spec.y || m_spec.z) {
errorfmt("{} does not support images with non-zero image origin offset",
format_name());
return false;
}
// Only support 8 bit channels for now.
m_spec.set_format(TypeDesc::UINT8);
m_dither = m_spec.get_int_attribute("oiio:dither", 0);
int64_t file_size = m_spec.image_bytes() + BMP_HEADER_SIZE + WINDOWS_V3;
if (file_size >= int64_t(1) << 32) {
errorfmt("{} does not support files over 4GB in size\n", format_name());
return false;
}
ioproxy_retrieve_from_config(m_spec);
if (!ioproxy_use_or_open(name))
return false;
// Scanline size is rounded up to align to 4-byte boundary
m_padded_scanline_size = round_to_multiple(m_spec.scanline_bytes(), 4);
create_and_write_file_header();
create_and_write_bitmap_header();
m_image_start = iotell();
// If user asked for tiles -- which this format doesn't support, emulate
// it by buffering the whole image.
if (m_spec.tile_width && m_spec.tile_height)
m_tilebuffer.resize(m_spec.image_bytes());
return true;
}
bool
BmpOutput::write_scanline(int y, int z, TypeDesc format, const void* data,
stride_t xstride)
{
if (!ioproxy_opened()) {
errorfmt("write_scanline called but file is not open.");
return false;
}
if (y > m_spec.y + m_spec.height) {
errorfmt("Attempt to write too many scanlines to {}", m_filename);
close();
return false;
}
y -= m_spec.y;
if (m_spec.width >= 0)
y = (m_spec.height - y - 1);
int64_t scanline_off = y * m_padded_scanline_size;
ioseek(m_image_start + scanline_off);
m_scratch.clear();
data = to_native_scanline(format, data, xstride, m_scratch, m_dither, y, z);
m_buf.assign((const unsigned char*)data,
(const unsigned char*)data + m_spec.scanline_bytes());
m_buf.resize(m_padded_scanline_size, 0); // pad with zeroes if needed
// Swap RGB pixels into BGR format
if (m_spec.nchannels >= 3)
for (int i = 0, iend = m_buf.size() - 2; i < iend;
i += m_spec.nchannels)
std::swap(m_buf[i], m_buf[i + 2]);
return iowrite(&m_buf[0], m_buf.size());
}
bool
BmpOutput::write_tile(int x, int y, int z, TypeDesc format, const void* data,
stride_t xstride, stride_t ystride, stride_t zstride)
{
if (!ioproxy_opened()) {
errorfmt("write_tile called but file is not open.");
return false;
}
// Emulate tiles by buffering the whole image
return copy_tile_to_image_buffer(x, y, z, format, data, xstride, ystride,
zstride, m_tilebuffer.data());
}
bool
BmpOutput::close(void)
{
if (!ioproxy_opened()) { // already closed
init();
return true;
}
bool ok = true;
if (m_spec.tile_width && m_tilebuffer.size()) {
// Handle tile emulation -- output the buffered pixels
OIIO_DASSERT(m_tilebuffer.size());
ok &= write_scanlines(m_spec.y, m_spec.y + m_spec.height, 0,
m_spec.format, m_tilebuffer.data());
std::vector<unsigned char>().swap(m_tilebuffer);
}
init();
return ok;
}
void
BmpOutput::create_and_write_file_header(void)
{
m_bmp_header.magic = MAGIC_BM;
int64_t data_size = m_padded_scanline_size * m_spec.height;
int palettesize = (m_spec.nchannels == 1) ? 4 * 256 : 0;
int64_t file_size = data_size + BMP_HEADER_SIZE + WINDOWS_V3 + palettesize;
m_bmp_header.fsize = file_size;
m_bmp_header.res1 = 0;
m_bmp_header.res2 = 0;
m_bmp_header.offset = BMP_HEADER_SIZE + WINDOWS_V3 + palettesize;
m_bmp_header.write_header(ioproxy());
}
void
BmpOutput::create_and_write_bitmap_header(void)
{
m_dib_header.size = WINDOWS_V3;
m_dib_header.width = m_spec.width;
m_dib_header.height = m_spec.height;
m_dib_header.cplanes = 1;
m_dib_header.compression = NO_COMPRESSION;
if (m_spec.nchannels == 1) {
// Special case -- write a 1-channel image as a gray palette
m_dib_header.bpp = 8;
m_dib_header.cpalete = 256;
m_dib_header.important = 256;
} else {
m_dib_header.bpp = m_spec.nchannels * 8;
m_dib_header.cpalete = 0;
m_dib_header.important = 0;
}
m_dib_header.isize = int32_t(m_spec.image_pixels());
m_dib_header.hres = 0;
m_dib_header.vres = 0;
string_view res_units = m_spec.get_string_attribute("ResolutionUnit");
if (Strutil::iequals(res_units, "m")
|| Strutil::iequals(res_units, "pixel per meter")) {
m_dib_header.hres = m_spec.get_int_attribute("XResolution");
m_dib_header.vres = m_spec.get_int_attribute("YResolution");
}
m_dib_header.write_header(ioproxy());
// Write palette, if there is one. This is only used for grayscale
// images, and the palette is just the 256 possible gray values.
for (int i = 0; i < m_dib_header.cpalete; ++i) {
unsigned char val[4] = { uint8_t(i), uint8_t(i), uint8_t(i), 255 };
iowrite(&val, 4);
}
}
OIIO_PLUGIN_NAMESPACE_END
<|endoftext|>
|
<commit_before>/**
* Copyright (C) 2014 3D Repo Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//-----------------------------------------------------------------------------
// Qt
#include <QMessageBox>
//------------------------------------------------------------------------------
// Repo
#include "repogui.h"
#include "ui_repogui.h"
#include "widgets/repo_widgetrepository.h"
//------------------------------------------------------------------------------
repo::gui::RepoGUI::RepoGUI(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::RepoGUI)
{
ui->setupUi(this);
this->setWindowIcon(
RepoFontAwesome::getInstance().getIcon(
RepoFontAwesome::fa_database,
QColor(246, 101, 60)));
//--------------------------------------------------------------------------
// For docks and windows not to update as they are slow to repaint.
this->setAnimated(false);
//--------------------------------------------------------------------------
// Force opengl format settings by default.
QGLFormat format(QGL::SampleBuffers);
format.setSwapInterval(1); // vsync
format.setSamples(16); // Antialiasing (multisample)
QGLFormat::setDefaultFormat(format);
//--------------------------------------------------------------------------
// Connect
QObject::connect(ui->actionConnect, SIGNAL(triggered()), this, SLOT(connect()));
ui->actionConnect->setIcon(RepoDialogConnect::getIcon());
//--------------------------------------------------------------------------
// Refresh
QObject::connect(ui->actionRefresh, SIGNAL(triggered()), this, SLOT(refresh()));
ui->actionRefresh->setIcon(RepoFontAwesome::getInstance().getIcon(RepoFontAwesome::fa_refresh));
//--------------------------------------------------------------------------
// Drop
QObject::connect(ui->actionDrop, SIGNAL(triggered()), this, SLOT(dropDatabase()));
ui->actionDrop->setIcon(RepoFontAwesome::getInstance().getIcon(RepoFontAwesome::fa_trash_o));
//--------------------------------------------------------------------------
// Exit
QObject::connect(ui->actionExit, SIGNAL(triggered()),
QApplication::instance(), SLOT(quit()));
ui->actionExit->setIcon(
RepoFontAwesome::getInstance().getIcon(
RepoFontAwesome::fa_sign_out, QColor(Qt::darkRed)));
}
repo::gui::RepoGUI::~RepoGUI()
{
delete ui;
}
void repo::gui::RepoGUI::connect()
{
RepoDialogConnect connectionDialog(this);
if(!connectionDialog.exec()) // if not clicked "Connect"
{
std::cout<< "Connection dialog cancelled by user" << std::endl;
}
else
{
// TODO move mongo creation outside of this main GUI to repository widget
// or similar
core::MongoClientWrapper mongo;
//----------------------------------------------------------------------
// if not successfully connected
if (!mongo.connect(
connectionDialog.getHost().toStdString(),
connectionDialog.getPort()))
{
std::cerr << "Connection error" << std::endl;
}
else
{
if (!connectionDialog.getUsername().isEmpty())
{
mongo.authenticate(
connectionDialog.getUsername().toStdString(),
connectionDialog.getPassword().toStdString());
}
ui->widgetRepository->fetchDatabases(mongo);
//-----------------------------------------------------------------
// enable buttons
ui->actionRefresh->setEnabled(true);
ui->actionHead->setEnabled(true);
ui->actionHistory->setEnabled(true);
ui->actionCommit->setEnabled(true);
ui->actionDrop->setEnabled(true);
}
}
}
void repo::gui::RepoGUI::refresh()
{
ui->widgetRepository->refresh();
}
void repo::gui::RepoGUI::dropDatabase()
{
QString dbName = ui->widgetRepository->getSelectedDatabase();
if (!dbName.isNull() &&
!dbName.isEmpty() &&
dbName != "local" &&
dbName != "admin")
{
switch (QMessageBox::warning(this,
"Drop Database?",
"Are you sure you want to drop '" + dbName + "' repository?",
"&Yes",
"&No",
QString::null, 1, 1))
{
case 0:
// yes
if (ui->widgetRepository->getSelectedConnection().deleteDatabase(dbName.toStdString()))
{
std::cout << dbName.toStdString() << " deleted successfully."
<< std::endl;
}
else
std::cout << "Delete unsuccessful" << std::endl;
refresh();
break;
}
}
else
{
std::cout << "You are not allowed to delete 'local' and 'admin' databases." << std::endl;
}
}
<commit_msg>Added delete<commit_after>/**
* Copyright (C) 2014 3D Repo Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//-----------------------------------------------------------------------------
// Qt
#include <QMessageBox>
//------------------------------------------------------------------------------
// Repo
#include "repogui.h"
#include "ui_repogui.h"
#include "widgets/repo_widgetrepository.h"
//------------------------------------------------------------------------------
repo::gui::RepoGUI::RepoGUI(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::RepoGUI)
{
ui->setupUi(this);
this->setWindowIcon(
RepoFontAwesome::getInstance().getIcon(
RepoFontAwesome::fa_database,
QColor(246, 101, 60)));
//--------------------------------------------------------------------------
// For docks and windows not to update as they are slow to repaint.
this->setAnimated(false);
//--------------------------------------------------------------------------
// Force opengl format settings by default.
QGLFormat format(QGL::SampleBuffers);
format.setSwapInterval(1); // vsync
format.setSamples(16); // Antialiasing (multisample)
QGLFormat::setDefaultFormat(format);
//--------------------------------------------------------------------------
// Connect
QObject::connect(ui->actionConnect, SIGNAL(triggered()), this, SLOT(connect()));
ui->actionConnect->setIcon(RepoDialogConnect::getIcon());
//--------------------------------------------------------------------------
// Refresh
QObject::connect(ui->actionRefresh, SIGNAL(triggered()), this, SLOT(refresh()));
ui->actionRefresh->setIcon(RepoFontAwesome::getInstance().getIcon(RepoFontAwesome::fa_refresh));
//--------------------------------------------------------------------------
// Drop
QObject::connect(ui->actionDrop, SIGNAL(triggered()), this, SLOT(dropDatabase()));
ui->actionDrop->setIcon(RepoFontAwesome::getInstance().getIcon(RepoFontAwesome::fa_trash_o));
//--------------------------------------------------------------------------
// Exit
QObject::connect(ui->actionExit, SIGNAL(triggered()),
QApplication::instance(), SLOT(quit()));
ui->actionExit->setIcon(
RepoFontAwesome::getInstance().getIcon(
RepoFontAwesome::fa_sign_out, QColor(Qt::darkRed)));
}
repo::gui::RepoGUI::~RepoGUI()
{
delete ui;
}
void repo::gui::RepoGUI::connect()
{
RepoDialogConnect connectionDialog(this);
if(!connectionDialog.exec()) // if not clicked "Connect"
{
std::cout<< "Connection dialog cancelled by user" << std::endl;
}
else
{
// TODO move mongo creation outside of this main GUI to repository widget
// or similar
core::MongoClientWrapper mongo;
//----------------------------------------------------------------------
// if not successfully connected
if (!mongo.connect(
connectionDialog.getHost().toStdString(),
connectionDialog.getPort()))
{
std::cerr << "Connection error" << std::endl;
}
else
{
if (!connectionDialog.getUsername().isEmpty())
{
mongo.authenticate(
connectionDialog.getUsername().toStdString(),
connectionDialog.getPassword().toStdString());
}
ui->widgetRepository->fetchDatabases(mongo);
//-----------------------------------------------------------------
// enable buttons
ui->actionRefresh->setEnabled(true);
ui->actionHead->setEnabled(true);
ui->actionHistory->setEnabled(true);
ui->actionCommit->setEnabled(true);
ui->actionDrop->setEnabled(true);
}
}
}
void repo::gui::RepoGUI::refresh()
{
ui->widgetRepository->refresh();
}
void repo::gui::RepoGUI::dropDatabase()
{
QString dbName = ui->widgetRepository->getSelectedDatabase();
if (!dbName.isNull() &&
!dbName.isEmpty() &&
dbName != "local" &&
dbName != "admin")
{
switch (QMessageBox::warning(this,
"Drop Database?",
"Are you sure you want to drop '" + dbName + "' repository?",
"&Yes",
"&No",
QString::null, 1, 1))
{
case 0:
// yes
core::MongoClientWrapper mongo = ui->widgetRepository->getSelectedConnection();
mongo.reconnectAndReauthenticate();
if (mongo.dropDatabase(dbName.toStdString()))
{
std::cout << dbName.toStdString() << " deleted successfully."
<< std::endl;
}
else
std::cout << "Delete unsuccessful" << std::endl;
refresh();
break;
}
}
else
{
std::cout << "You are not allowed to delete 'local' and 'admin' databases." << std::endl;
}
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2014, 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 <cmake.h>
#include <sstream>
#include <stdlib.h>
#include <Context.h>
#include <ViewText.h>
#include <Date.h>
#include <main.h>
#include <i18n.h>
#include <text.h>
#include <CmdTimesheet.h>
extern Context context;
////////////////////////////////////////////////////////////////////////////////
CmdTimesheet::CmdTimesheet ()
{
_keyword = "timesheet";
_usage = "task timesheet [weeks]";
_description = STRING_CMD_TIMESHEET_USAGE;
_read_only = true;
_displays_id = false;
}
////////////////////////////////////////////////////////////////////////////////
int CmdTimesheet::execute (std::string& output)
{
int rc = 0;
// Scan the pending tasks.
handleRecurrence ();
std::vector <Task> all = context.tdb2.all_tasks ();
context.tdb2.commit ();
// What day of the week does the user consider the first?
int weekStart = Date::dayOfWeek (context.config.get ("weekstart"));
if (weekStart != 0 && weekStart != 1)
throw std::string (STRING_DATE_BAD_WEEKSTART);
// Determine the date of the first day of the most recent report.
Date today;
Date start;
start -= (((today.dayOfWeek () - weekStart) + 7) % 7) * 86400;
// Roll back to midnight.
start = Date (start.month (), start.day (), start.year ());
Date end = start + (7 * 86400);
// Determine how many reports to run.
int quantity = 1;
std::vector <std::string> words = context.parser.getWords ();
if (words.size () == 1)
quantity = strtol (words[0].c_str (), NULL, 10);;
std::stringstream out;
for (int week = 0; week < quantity; ++week)
{
Date endString (end);
endString -= 86400;
std::string title = start.toString (context.config.get ("dateformat"))
+ " - "
+ endString.toString (context.config.get ("dateformat"));
Color bold (Color::nocolor, Color::nocolor, false, true, false);
out << "\n"
<< (context.color () ? bold.colorize (title) : title)
<< "\n";
// Render the completed table.
ViewText completed;
completed.width (context.getWidth ());
completed.add (Column::factory ("string", " "));
completed.add (Column::factory ("string", STRING_COLUMN_LABEL_PROJECT));
completed.add (Column::factory ("string.right", STRING_COLUMN_LABEL_DUE));
completed.add (Column::factory ("string", STRING_COLUMN_LABEL_DESC));
std::vector <Task>::iterator task;
for (task = all.begin (); task != all.end (); ++task)
{
// If task completed within range.
if (task->getStatus () == Task::completed)
{
Date compDate (task->get_date ("end"));
if (compDate >= start && compDate < end)
{
Color c;
if (context.color ())
autoColorize (*task, c);
int row = completed.addRow ();
std::string format = context.config.get ("dateformat.report");
if (format == "")
format = context.config.get ("dateformat");
completed.set (row, 1, task->get ("project"), c);
if(task->has ("due"))
{
Date dt (task->get_date ("due"));
completed.set (row, 2, dt.toString (format));
}
std::string description = task->get ("description");
int indent = context.config.getInteger ("indent.annotation");
std::map <std::string, std::string> annotations;
task->getAnnotations (annotations);
std::map <std::string, std::string>::iterator ann;
for (ann = annotations.begin (); ann != annotations.end (); ++ann)
description += "\n"
+ std::string (indent, ' ')
+ Date (ann->first.substr (11)).toString (context.config.get ("dateformat"))
+ " "
+ ann->second;
completed.set (row, 3, description, c);
}
}
}
out << " " << format (STRING_CMD_TIMESHEET_DONE, completed.rows ()) << "\n";
if (completed.rows ())
out << completed.render ()
<< "\n";
// Now render the started table.
ViewText started;
started.width (context.getWidth ());
started.add (Column::factory ("string", " "));
started.add (Column::factory ("string", STRING_COLUMN_LABEL_PROJECT));
started.add (Column::factory ("string.right", STRING_COLUMN_LABEL_DUE));
started.add (Column::factory ("string", STRING_COLUMN_LABEL_DESC));
for (task = all.begin (); task != all.end (); ++task)
{
// If task started within range, but not completed withing range.
if (task->getStatus () == Task::pending &&
task->has ("start"))
{
Date startDate (task->get_date ("start"));
if (startDate >= start && startDate < end)
{
Color c;
if (context.color ())
autoColorize (*task, c);
int row = started.addRow ();
std::string format = context.config.get ("dateformat.report");
if (format == "")
format = context.config.get ("dateformat");
started.set (row, 1, task->get ("project"), c);
if(task->has ("due"))
{
Date dt (task->get_date ("due"));
started.set (row, 2, dt.toString (format));
}
std::string description = task->get ("description");
int indent = context.config.getInteger ("indent.annotation");
std::map <std::string, std::string> annotations;
task->getAnnotations (annotations);
std::map <std::string, std::string>::iterator ann;
for (ann = annotations.begin (); ann != annotations.end (); ++ann)
description += "\n"
+ std::string (indent, ' ')
+ Date (ann->first.substr (11)).toString (context.config.get ("dateformat"))
+ " "
+ ann->second;
started.set (row, 3, description, c);
}
}
}
out << " " << format (STRING_CMD_TIMESHEET_STARTED, started.rows ()) << "\n";
if (started.rows ())
out << started.render ()
<< "\n\n";
// Prior week.
start -= 7 * 86400;
end -= 7 * 86400;
}
output = out.str ();
return rc;
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>CmdTimesheet<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2014, 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 <cmake.h>
#include <sstream>
#include <stdlib.h>
#include <Context.h>
#include <ViewText.h>
#include <Date.h>
#include <main.h>
#include <i18n.h>
#include <text.h>
#include <CmdTimesheet.h>
extern Context context;
////////////////////////////////////////////////////////////////////////////////
CmdTimesheet::CmdTimesheet ()
{
_keyword = "timesheet";
_usage = "task timesheet [weeks]";
_description = STRING_CMD_TIMESHEET_USAGE;
_read_only = true;
_displays_id = false;
}
////////////////////////////////////////////////////////////////////////////////
int CmdTimesheet::execute (std::string& output)
{
int rc = 0;
// Scan the pending tasks.
handleRecurrence ();
std::vector <Task> all = context.tdb2.all_tasks ();
// What day of the week does the user consider the first?
int weekStart = Date::dayOfWeek (context.config.get ("weekstart"));
if (weekStart != 0 && weekStart != 1)
throw std::string (STRING_DATE_BAD_WEEKSTART);
// Determine the date of the first day of the most recent report.
Date today;
Date start;
start -= (((today.dayOfWeek () - weekStart) + 7) % 7) * 86400;
// Roll back to midnight.
start = Date (start.month (), start.day (), start.year ());
Date end = start + (7 * 86400);
// Determine how many reports to run.
int quantity = 1;
std::vector <std::string> words = context.parser.getWords ();
if (words.size () == 1)
quantity = strtol (words[0].c_str (), NULL, 10);;
std::stringstream out;
for (int week = 0; week < quantity; ++week)
{
Date endString (end);
endString -= 86400;
std::string title = start.toString (context.config.get ("dateformat"))
+ " - "
+ endString.toString (context.config.get ("dateformat"));
Color bold (Color::nocolor, Color::nocolor, false, true, false);
out << "\n"
<< (context.color () ? bold.colorize (title) : title)
<< "\n";
// Render the completed table.
ViewText completed;
completed.width (context.getWidth ());
completed.add (Column::factory ("string", " "));
completed.add (Column::factory ("string", STRING_COLUMN_LABEL_PROJECT));
completed.add (Column::factory ("string.right", STRING_COLUMN_LABEL_DUE));
completed.add (Column::factory ("string", STRING_COLUMN_LABEL_DESC));
std::vector <Task>::iterator task;
for (task = all.begin (); task != all.end (); ++task)
{
// If task completed within range.
if (task->getStatus () == Task::completed)
{
Date compDate (task->get_date ("end"));
if (compDate >= start && compDate < end)
{
Color c;
if (context.color ())
autoColorize (*task, c);
int row = completed.addRow ();
std::string format = context.config.get ("dateformat.report");
if (format == "")
format = context.config.get ("dateformat");
completed.set (row, 1, task->get ("project"), c);
if(task->has ("due"))
{
Date dt (task->get_date ("due"));
completed.set (row, 2, dt.toString (format));
}
std::string description = task->get ("description");
int indent = context.config.getInteger ("indent.annotation");
std::map <std::string, std::string> annotations;
task->getAnnotations (annotations);
std::map <std::string, std::string>::iterator ann;
for (ann = annotations.begin (); ann != annotations.end (); ++ann)
description += "\n"
+ std::string (indent, ' ')
+ Date (ann->first.substr (11)).toString (context.config.get ("dateformat"))
+ " "
+ ann->second;
completed.set (row, 3, description, c);
}
}
}
out << " " << format (STRING_CMD_TIMESHEET_DONE, completed.rows ()) << "\n";
if (completed.rows ())
out << completed.render ()
<< "\n";
// Now render the started table.
ViewText started;
started.width (context.getWidth ());
started.add (Column::factory ("string", " "));
started.add (Column::factory ("string", STRING_COLUMN_LABEL_PROJECT));
started.add (Column::factory ("string.right", STRING_COLUMN_LABEL_DUE));
started.add (Column::factory ("string", STRING_COLUMN_LABEL_DESC));
for (task = all.begin (); task != all.end (); ++task)
{
// If task started within range, but not completed withing range.
if (task->getStatus () == Task::pending &&
task->has ("start"))
{
Date startDate (task->get_date ("start"));
if (startDate >= start && startDate < end)
{
Color c;
if (context.color ())
autoColorize (*task, c);
int row = started.addRow ();
std::string format = context.config.get ("dateformat.report");
if (format == "")
format = context.config.get ("dateformat");
started.set (row, 1, task->get ("project"), c);
if(task->has ("due"))
{
Date dt (task->get_date ("due"));
started.set (row, 2, dt.toString (format));
}
std::string description = task->get ("description");
int indent = context.config.getInteger ("indent.annotation");
std::map <std::string, std::string> annotations;
task->getAnnotations (annotations);
std::map <std::string, std::string>::iterator ann;
for (ann = annotations.begin (); ann != annotations.end (); ++ann)
description += "\n"
+ std::string (indent, ' ')
+ Date (ann->first.substr (11)).toString (context.config.get ("dateformat"))
+ " "
+ ann->second;
started.set (row, 3, description, c);
}
}
}
out << " " << format (STRING_CMD_TIMESHEET_STARTED, started.rows ()) << "\n";
if (started.rows ())
out << started.render ()
<< "\n\n";
// Prior week.
start -= 7 * 86400;
end -= 7 * 86400;
}
output = out.str ();
return rc;
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|>
|
<commit_before>#include "sensors.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "SparkFunBME280.h"
#include "esp_log.h"
static float readings[SENS_MAX-1];
static QueueHandle_t *subscriptions;
static size_t num_subscriptions;
static SemaphoreHandle_t sensor_mutex;
static const char *TAG = "sensors";
static void sensor_task(void *arg);
void sensors_initialize()
{
xTaskCreate(sensor_task, "sensor_task", 4096, NULL, 1, NULL);
}
/* Internal function to update a cached sensor reading */
static void sensor_set(tuz_sensor_t sensor, float value)
{
if (sensor >= SENS_MAX) {
return;
}
/* Update our cache copy of the reading */
xSemaphoreTake(sensor_mutex, portMAX_DELAY);
readings[sensor] = value;
xSemaphoreGive(sensor_mutex);
/* Try to push a reading to all subscribed tasks */
sensor_reading_t reading = {
.sensor = sensor,
.value = value,
};
for (int i = 0; i < num_subscriptions; i++) {
/* TODO: we assume that queueing the reading succeeds.
if queue is full, we may want to pop from the front
of the queue and then push again so the stale values
are always recent.
*/
xQueueSendToBack(subscriptions[i], &reading, 0);
}
}
float sensor_get(tuz_sensor_t sensor)
{
float result;
if (sensor >= SENS_MAX) {
return 0.0;
}
/* note: using 32-bit floats, mutex is not strictly
necessary here as reading is atomic. */
xSemaphoreTake(sensor_mutex, portMAX_DELAY);
result = readings[sensor];
xSemaphoreGive(sensor_mutex);
return result;
}
bool sensors_subscribe(QueueHandle_t queue)
{
void *new_subscriptions = realloc(subscriptions, (num_subscriptions + 1) * sizeof(QueueHandle_t));
if (!new_subscriptions) {
ESP_LOGE(TAG, "Failed to allocate new subscription #%d", (num_subscriptions+1));
return false;
}
num_subscriptions++;
subscriptions = (QueueHandle_t *)new_subscriptions;
subscriptions[num_subscriptions-1] = queue;
return true;
}
int loops;
static void sensor_task(void *arg)
{
ESP_LOGI(TAG, "sensor task running");
TwoWire i2cWire(1);
i2cWire.begin(GPIO_NUM_21, GPIO_NUM_22);
i2cWire.setClock(100000L);
BME280 bme280(0x77, &i2cWire);
sensor_mutex = xSemaphoreCreateMutex();
ESP_LOGI(TAG, "BME280 0x%02x", bme280.begin());
ESP_LOGI(TAG, "ID(0xD0) 0x%02x", bme280.readRegister(BME280_CHIP_ID_REG));
ESP_LOGI(TAG, "Displaying ID, reset and ctrl regs\n");
ESP_LOGI(TAG, "ID(0xD0): 0x%02x", bme280.readRegister(BME280_CHIP_ID_REG));
ESP_LOGI(TAG, "Reset register(0xE0): 0x%02x", bme280.readRegister(BME280_RST_REG));
ESP_LOGI(TAG, "ctrl_meas(0xF4): 0x%02x", bme280.readRegister(BME280_CTRL_MEAS_REG));
ESP_LOGI(TAG, "ctrl_hum(0xF2): 0x%02x", bme280.readRegister(BME280_CTRL_HUMIDITY_REG));
bme280.settings.runMode = 3; //Normal mode
bme280.settings.tStandby = 0;
bme280.settings.filter = 2;
bme280.settings.tempOverSample = 1;
bme280.settings.pressOverSample = 1;
bme280.settings.humidOverSample = 1;
loops = 0;
while (1) {
vTaskDelay(100 / portTICK_PERIOD_MS);
if (loops < 100) {
loops++;
continue;
}
for (int i = 0; i < SENS_MAX; i++) {
float value;
/* TODO: actually take readings here */
switch((tuz_sensor_t)i) {
case SENS_TEMPERATURE:
value = bme280.readTempC();
break;
case SENS_HUMIDITY:
value = bme280.readFloatHumidity();
break;
case SENS_ALTITUDE:
value = bme280.readFloatAltitudeMeters();
break;
case SENS_BAROMETRIC:
value = bme280.readFloatPressure();
break;
default:
ESP_LOGE(TAG, "invalid tuz_sensor_t value %d", i);
continue;
}
sensor_set((tuz_sensor_t)i, value);
loops = 0;
}
}
}
const char *sensor_name(tuz_sensor_t sensor) {
switch(sensor) {
case SENS_TEMPERATURE:
return "temperature";
case SENS_HUMIDITY:
return "humidity";
case SENS_ALTITUDE:
return "altitude";
case SENS_BAROMETRIC:
return "barometric";
default:
return "unknownsensor";
}
}
<commit_msg>sensors: Make readings array large enough<commit_after>#include "sensors.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "SparkFunBME280.h"
#include "esp_log.h"
static float readings[SENS_MAX];
static QueueHandle_t *subscriptions;
static size_t num_subscriptions;
static SemaphoreHandle_t sensor_mutex;
static const char *TAG = "sensors";
static void sensor_task(void *arg);
void sensors_initialize()
{
xTaskCreate(sensor_task, "sensor_task", 4096, NULL, 1, NULL);
}
/* Internal function to update a cached sensor reading */
static void sensor_set(tuz_sensor_t sensor, float value)
{
if (sensor >= SENS_MAX) {
return;
}
/* Update our cache copy of the reading */
xSemaphoreTake(sensor_mutex, portMAX_DELAY);
readings[sensor] = value;
xSemaphoreGive(sensor_mutex);
/* Try to push a reading to all subscribed tasks */
sensor_reading_t reading = {
.sensor = sensor,
.value = value,
};
for (int i = 0; i < num_subscriptions; i++) {
/* TODO: we assume that queueing the reading succeeds.
if queue is full, we may want to pop from the front
of the queue and then push again so the stale values
are always recent.
*/
xQueueSendToBack(subscriptions[i], &reading, 0);
}
}
float sensor_get(tuz_sensor_t sensor)
{
float result;
if (sensor >= SENS_MAX) {
return 0.0;
}
/* note: using 32-bit floats, mutex is not strictly
necessary here as reading is atomic. */
xSemaphoreTake(sensor_mutex, portMAX_DELAY);
result = readings[sensor];
xSemaphoreGive(sensor_mutex);
return result;
}
bool sensors_subscribe(QueueHandle_t queue)
{
void *new_subscriptions = realloc(subscriptions, (num_subscriptions + 1) * sizeof(QueueHandle_t));
if (!new_subscriptions) {
ESP_LOGE(TAG, "Failed to allocate new subscription #%d", (num_subscriptions+1));
return false;
}
num_subscriptions++;
subscriptions = (QueueHandle_t *)new_subscriptions;
subscriptions[num_subscriptions-1] = queue;
return true;
}
int loops;
static void sensor_task(void *arg)
{
ESP_LOGI(TAG, "sensor task running");
TwoWire i2cWire(1);
i2cWire.begin(GPIO_NUM_21, GPIO_NUM_22);
i2cWire.setClock(100000L);
BME280 bme280(0x77, &i2cWire);
sensor_mutex = xSemaphoreCreateMutex();
ESP_LOGI(TAG, "BME280 0x%02x", bme280.begin());
ESP_LOGI(TAG, "ID(0xD0) 0x%02x", bme280.readRegister(BME280_CHIP_ID_REG));
ESP_LOGI(TAG, "Displaying ID, reset and ctrl regs\n");
ESP_LOGI(TAG, "ID(0xD0): 0x%02x", bme280.readRegister(BME280_CHIP_ID_REG));
ESP_LOGI(TAG, "Reset register(0xE0): 0x%02x", bme280.readRegister(BME280_RST_REG));
ESP_LOGI(TAG, "ctrl_meas(0xF4): 0x%02x", bme280.readRegister(BME280_CTRL_MEAS_REG));
ESP_LOGI(TAG, "ctrl_hum(0xF2): 0x%02x", bme280.readRegister(BME280_CTRL_HUMIDITY_REG));
bme280.settings.runMode = 3; //Normal mode
bme280.settings.tStandby = 0;
bme280.settings.filter = 2;
bme280.settings.tempOverSample = 1;
bme280.settings.pressOverSample = 1;
bme280.settings.humidOverSample = 1;
loops = 0;
while (1) {
vTaskDelay(100 / portTICK_PERIOD_MS);
if (loops < 100) {
loops++;
continue;
}
for (int i = 0; i < SENS_MAX; i++) {
float value;
/* TODO: actually take readings here */
switch((tuz_sensor_t)i) {
case SENS_TEMPERATURE:
value = bme280.readTempC();
break;
case SENS_HUMIDITY:
value = bme280.readFloatHumidity();
break;
case SENS_ALTITUDE:
value = bme280.readFloatAltitudeMeters();
break;
case SENS_BAROMETRIC:
value = bme280.readFloatPressure();
break;
default:
ESP_LOGE(TAG, "invalid tuz_sensor_t value %d", i);
continue;
}
sensor_set((tuz_sensor_t)i, value);
loops = 0;
}
}
}
const char *sensor_name(tuz_sensor_t sensor) {
switch(sensor) {
case SENS_TEMPERATURE:
return "temperature";
case SENS_HUMIDITY:
return "humidity";
case SENS_ALTITUDE:
return "altitude";
case SENS_BAROMETRIC:
return "barometric";
default:
return "unknownsensor";
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include "kernel/type_checker.h"
#include "kernel/abstract.h"
#include "kernel/instantiate.h"
#include "kernel/inductive/inductive.h"
#include "library/replace_visitor.h"
#include "library/constants.h"
#include "library/util.h"
#include "compiler/util.h"
namespace lean {
class simp_pr1_rec_fn : public replace_visitor {
environment m_env;
name_generator m_ngen;
type_checker m_tc;
struct failed {};
struct elim_nested_pr1_fn : public replace_visitor {
buffer<bool> const & minor_is_rec_arg;
buffer<expr> const & minor_ctx;
elim_nested_pr1_fn(buffer<bool> const & b1, buffer<expr> const & b2):
minor_is_rec_arg(b1), minor_ctx(b2) {
lean_assert(minor_is_rec_arg.size() == minor_ctx.size());
}
bool is_rec_arg(expr const & e) {
if (!is_local(e))
return false;
for (unsigned i = 0; i < minor_ctx.size(); i++) {
if (minor_is_rec_arg[i] && mlocal_name(minor_ctx[i]) == mlocal_name(e))
return true;
}
return false;
}
virtual expr visit_app(expr const & e) {
expr const & f = get_app_fn(e);
if (is_constant(f) && const_name(f) == get_prod_pr1_name()) {
buffer<expr> args;
get_app_args(e, args);
if (args.size() >= 3 && is_rec_arg(args[2])) {
for (unsigned i = 3; i < args.size(); i++)
args[i] = visit(args[i]);
return mk_app(args[2], args.size() - 3, args.data() + 3);
}
}
return replace_visitor::visit_app(e);
}
virtual expr visit_local(expr const & e) {
if (is_rec_arg(e))
throw failed();
return replace_visitor::visit_local(e);
}
};
optional<expr> simplify(expr const & e) {
expr const & f = get_app_fn(e);
if (!is_constant(f) || const_name(f) != get_prod_pr1_name())
return none_expr();
buffer<expr> args;
get_app_args(e, args);
if (args.size() < 3)
return none_expr();
for (unsigned i = 3; i < args.size(); i++)
args[i] = visit(args[i]);
expr const & rec = args[2];
buffer<expr> rec_args;
expr const & rec_fn = get_app_args(rec, rec_args);
if (!is_constant(rec_fn))
return none_expr();
auto I_name = inductive::is_elim_rule(m_env, const_name(rec_fn));
if (!I_name)
return none_expr();
buffer<buffer<bool>> is_rec_arg;
get_rec_args(m_env, *I_name, is_rec_arg);
unsigned nparams = *inductive::get_num_params(m_env, *I_name);
unsigned ntypeformers = *inductive::get_num_type_formers(m_env, *I_name);
unsigned nminors = *inductive::get_num_minor_premises(m_env, *I_name);
if (rec_args.size() < nparams + ntypeformers + nminors)
return none_expr();
// update type formers
for (unsigned i = nparams; i < nparams + ntypeformers; i++) {
// Check whether each type former is of the form
// (lambda ctx, prod c1 c2), and replace it with (lambda ctx, c1)
expr typeformer = rec_args[i];
buffer<expr> typeformer_ctx;
expr typeformer_body = fun_to_telescope(m_ngen, typeformer, typeformer_ctx, optional<binder_info>());
buffer<expr> typeformer_body_args;
expr typeformer_body_fn = get_app_args(typeformer_body, typeformer_body_args);
if (!is_constant(typeformer_body_fn) || const_name(typeformer_body_fn) != get_prod_name() || typeformer_body_args.size() != 2) {
return none_expr();
}
typeformer_body = typeformer_body_args[0];
rec_args[i] = Fun(typeformer_ctx, typeformer_body);
}
// update minor premises
for (unsigned i = nparams + ntypeformers, j = 0; i < nparams + ntypeformers + nminors; i++, j++) {
buffer<bool> const & minor_is_rec_arg = is_rec_arg[j];
expr minor = rec_args[i];
buffer<expr> minor_ctx;
expr minor_body = fun_to_telescope(m_ngen, minor, minor_ctx, optional<binder_info>());
if (minor_is_rec_arg.size() != minor_ctx.size()) {
return none_expr();
}
// We have to check:
// 1- For each local r in the context minor_ctx s.t. r is marked as recursive in minor_is_rec_arg,
// its type is of the form (prod A B). The new type will be just A.
// 2- minor body is of the form (prod.mk A B c1 c2)
// 3- In c1, all occurrences of recursive arguments r are of the form (prod.pr1 A B r)
// Step 1.
for (unsigned i = 0; i < minor_ctx.size(); i++) {
if (minor_is_rec_arg[i]) {
expr type = m_tc.whnf(mlocal_type(minor_ctx[i])).first;
buffer<expr> type_args;
expr type_fn = get_app_args(type, type_args);
if (!is_constant(type_fn) || const_name(type_fn) != get_prod_name() || type_args.size() != 2)
return none_expr();
minor_ctx[i] = update_mlocal(minor_ctx[i], type_args[0]);
}
}
// Step 2
buffer<expr> minor_body_args;
expr minor_body_fn = get_app_args(minor_body, minor_body_args);
if (!is_constant(minor_body_fn) || const_name(minor_body_fn) != get_prod_mk_name() || minor_body_args.size() != 4)
return none_expr();
minor_body = minor_body_args[2];
// Step 3
try {
elim_nested_pr1_fn elim(minor_is_rec_arg, minor_ctx);
minor_body = elim(minor_body);
} catch (failed &) {
return none_expr();
}
// Update minor premise
rec_args[i] = Fun(minor_ctx, minor_body);
}
expr new_rec = mk_app(rec_fn, rec_args.size(), rec_args.data());
return some_expr(mk_app(new_rec, args.size() - 3, args.data() + 3));
}
virtual expr visit_app(expr const & e) {
if (auto r = simplify(e))
return *r;
else
return replace_visitor::visit_app(e);
}
virtual expr visit_binding(expr const & b) {
expr new_domain = visit(binding_domain(b));
expr l = mk_local(m_ngen.next(), new_domain);
expr new_body = abstract_local(visit(instantiate(binding_body(b), l)), l);
return update_binding(b, new_domain, new_body);
}
public:
simp_pr1_rec_fn(environment const & env):m_env(env), m_tc(env, m_ngen.mk_child()) {}
};
expr simp_pr1_rec(environment const & env, expr const & e) {
return simp_pr1_rec_fn(env)(e);
}
}
<commit_msg>fix(compiler/simp_pr1_rec): missing recursor nested inside recursor<commit_after>/*
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include "kernel/type_checker.h"
#include "kernel/abstract.h"
#include "kernel/instantiate.h"
#include "kernel/inductive/inductive.h"
#include "library/replace_visitor.h"
#include "library/constants.h"
#include "library/util.h"
#include "compiler/util.h"
namespace lean {
class simp_pr1_rec_fn : public replace_visitor {
environment m_env;
name_generator m_ngen;
type_checker m_tc;
struct failed {};
struct elim_nested_pr1_fn : public replace_visitor {
buffer<bool> const & minor_is_rec_arg;
buffer<expr> const & minor_ctx;
elim_nested_pr1_fn(buffer<bool> const & b1, buffer<expr> const & b2):
minor_is_rec_arg(b1), minor_ctx(b2) {
lean_assert(minor_is_rec_arg.size() == minor_ctx.size());
}
bool is_rec_arg(expr const & e) {
if (!is_local(e))
return false;
for (unsigned i = 0; i < minor_ctx.size(); i++) {
if (minor_is_rec_arg[i] && mlocal_name(minor_ctx[i]) == mlocal_name(e))
return true;
}
return false;
}
virtual expr visit_app(expr const & e) {
expr const & f = get_app_fn(e);
if (is_constant(f) && const_name(f) == get_prod_pr1_name()) {
buffer<expr> args;
get_app_args(e, args);
if (args.size() >= 3 && is_rec_arg(args[2])) {
for (unsigned i = 3; i < args.size(); i++)
args[i] = visit(args[i]);
return mk_app(args[2], args.size() - 3, args.data() + 3);
}
}
return replace_visitor::visit_app(e);
}
virtual expr visit_local(expr const & e) {
if (is_rec_arg(e))
throw failed();
return replace_visitor::visit_local(e);
}
};
optional<expr> simplify(expr const & e) {
expr const & f = get_app_fn(e);
if (!is_constant(f) || const_name(f) != get_prod_pr1_name())
return none_expr();
buffer<expr> args;
get_app_args(e, args);
if (args.size() < 3)
return none_expr();
for (unsigned i = 3; i < args.size(); i++)
args[i] = visit(args[i]);
expr const & rec = args[2];
buffer<expr> rec_args;
expr const & rec_fn = get_app_args(rec, rec_args);
if (!is_constant(rec_fn))
return none_expr();
auto I_name = inductive::is_elim_rule(m_env, const_name(rec_fn));
if (!I_name)
return none_expr();
buffer<buffer<bool>> is_rec_arg;
get_rec_args(m_env, *I_name, is_rec_arg);
unsigned nparams = *inductive::get_num_params(m_env, *I_name);
unsigned ntypeformers = *inductive::get_num_type_formers(m_env, *I_name);
unsigned nminors = *inductive::get_num_minor_premises(m_env, *I_name);
if (rec_args.size() < nparams + ntypeformers + nminors)
return none_expr();
// update type formers
for (unsigned i = nparams; i < nparams + ntypeformers; i++) {
// Check whether each type former is of the form
// (lambda ctx, prod c1 c2), and replace it with (lambda ctx, c1)
expr typeformer = rec_args[i];
buffer<expr> typeformer_ctx;
expr typeformer_body = fun_to_telescope(m_ngen, typeformer, typeformer_ctx, optional<binder_info>());
buffer<expr> typeformer_body_args;
expr typeformer_body_fn = get_app_args(typeformer_body, typeformer_body_args);
if (!is_constant(typeformer_body_fn) || const_name(typeformer_body_fn) != get_prod_name() || typeformer_body_args.size() != 2) {
return none_expr();
}
typeformer_body = typeformer_body_args[0];
rec_args[i] = Fun(typeformer_ctx, typeformer_body);
}
// update minor premises
for (unsigned i = nparams + ntypeformers, j = 0; i < nparams + ntypeformers + nminors; i++, j++) {
buffer<bool> const & minor_is_rec_arg = is_rec_arg[j];
expr minor = rec_args[i];
buffer<expr> minor_ctx;
expr minor_body = fun_to_telescope(m_ngen, minor, minor_ctx, optional<binder_info>());
if (minor_is_rec_arg.size() != minor_ctx.size()) {
return none_expr();
}
// We have to check:
// 1- For each local r in the context minor_ctx s.t. r is marked as recursive in minor_is_rec_arg,
// its type is of the form (prod A B). The new type will be just A.
// 2- minor body is of the form (prod.mk A B c1 c2)
// 3- In c1, all occurrences of recursive arguments r are of the form (prod.pr1 A B r)
// Step 1.
for (unsigned i = 0; i < minor_ctx.size(); i++) {
if (minor_is_rec_arg[i]) {
expr type = m_tc.whnf(mlocal_type(minor_ctx[i])).first;
buffer<expr> type_args;
expr type_fn = get_app_args(type, type_args);
if (!is_constant(type_fn) || const_name(type_fn) != get_prod_name() || type_args.size() != 2)
return none_expr();
minor_ctx[i] = update_mlocal(minor_ctx[i], type_args[0]);
}
}
// Step 2
buffer<expr> minor_body_args;
expr minor_body_fn = get_app_args(minor_body, minor_body_args);
if (!is_constant(minor_body_fn) || const_name(minor_body_fn) != get_prod_mk_name() || minor_body_args.size() != 4)
return none_expr();
minor_body = minor_body_args[2];
// Step 3
try {
elim_nested_pr1_fn elim(minor_is_rec_arg, minor_ctx);
minor_body = elim(minor_body);
} catch (failed &) {
return none_expr();
}
// Update minor premise
rec_args[i] = Fun(minor_ctx, minor_body);
}
expr new_rec = mk_app(rec_fn, rec_args.size(), rec_args.data());
return some_expr(visit(mk_app(new_rec, args.size() - 3, args.data() + 3)));
}
virtual expr visit_app(expr const & e) {
if (auto r = simplify(e))
return *r;
else
return replace_visitor::visit_app(e);
}
virtual expr visit_binding(expr const & b) {
expr new_domain = visit(binding_domain(b));
expr l = mk_local(m_ngen.next(), new_domain);
expr new_body = abstract_local(visit(instantiate(binding_body(b), l)), l);
return update_binding(b, new_domain, new_body);
}
public:
simp_pr1_rec_fn(environment const & env):m_env(env), m_tc(env, m_ngen.mk_child()) {}
};
expr simp_pr1_rec(environment const & env, expr const & e) {
return simp_pr1_rec_fn(env)(e);
}
}
<|endoftext|>
|
<commit_before>// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "components/rendermesh.h"
#include "components/transform.h"
#include "components_generated.h"
#include "fplbase/mesh.h"
using mathfu::vec3;
using mathfu::mat4;
namespace fpl {
namespace fpl_project {
// Offset the frustrum by this many world-units. As long as no objects are
// larger than this number, they should still all draw, even if their
// registration points technically fall outside our frustrum.
static const float kFrustrumOffset = 50.0f;
void RenderMeshComponent::Initialize(mathfu::vec3 light_position,
MaterialManager* material_manager) {
light_position_ = light_position;
material_manager_ = material_manager;
}
// Rendermesh depends on transform:
void RenderMeshComponent::InitEntity(entity::EntityRef& entity) {
entity_manager_->AddEntityToComponent<TransformComponent>(entity);
}
void RenderMeshComponent::RenderEntity(entity::EntityRef& entity,
Renderer& renderer,
const Camera& camera) {
TransformData* transform_data = Data<TransformData>(entity);
RenderMeshData* rendermesh_data = Data<RenderMeshData>(entity);
// Check to make sure objects are inside the frustrum of our view-cone:
float max_cos = cos(camera.viewport_angle());
vec3 camera_facing = camera.facing();
vec3 entity_position = transform_data->world_transform.TranslationVector3D();
vec3 pos_relative_to_camera = (entity_position - camera.position()) +
camera_facing * kFrustrumOffset;
if (vec3::DotProduct(pos_relative_to_camera.Normalized(),
camera_facing.Normalized()) < max_cos) {
// The origin point for this mesh is not in our field of view. Cut out
// early, and don't bother rendering it.
return;
}
mat4 world_transform = transform_data->world_transform;
const mat4 mvp = camera.GetTransformMatrix() * world_transform;
const mat4 world_matrix_inverse = world_transform.Inverse();
renderer.camera_pos() = world_matrix_inverse * camera.position();
renderer.light_pos() = world_matrix_inverse * light_position_;
renderer.model_view_projection() = mvp;
if (rendermesh_data->shader) {
rendermesh_data->shader->Set(renderer);
}
rendermesh_data->mesh->Render(renderer);
}
void RenderMeshComponent::RenderAllEntities(Renderer& renderer,
const Camera& camera) {
// todo(ccornell) - instead of iterating like this, sort by
// z depth and alpha blend mode.
for (auto iter = component_data_.begin();
iter != component_data_.end(); ++iter) {
RenderEntity(iter->entity, renderer, camera);
}
}
void RenderMeshComponent::AddFromRawData(entity::EntityRef& entity,
const void* raw_data) {
auto component_data = static_cast<const ComponentDefInstance*>(raw_data);
assert(component_data->data_type() == ComponentDataUnion_RenderMeshDef);
auto rendermesh_def =
static_cast<const RenderMeshDef*>(component_data->data());
// You need to call set_material_manager before you can add from raw data,
// otherwise it can't load up new meshes!
assert(material_manager_ != nullptr);
assert(rendermesh_def->source_file() != nullptr);
assert(rendermesh_def->shader() != nullptr);
RenderMeshData* rendermesh_data = AddEntity(entity);
rendermesh_data->mesh =
material_manager_->LoadMesh(rendermesh_def->source_file()->c_str());
rendermesh_data->shader =
material_manager_->LoadShader(rendermesh_def->shader()->c_str());
// TODO: Load this from a flatbuffer file instead of setting it.
rendermesh_data->tint = mathfu::kOnes4f;
}
} // fpl_project
} // fpl
<commit_msg>Added support for tinting rendermeshes<commit_after>// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "components/rendermesh.h"
#include "components/transform.h"
#include "components_generated.h"
#include "fplbase/mesh.h"
using mathfu::vec3;
using mathfu::mat4;
namespace fpl {
namespace fpl_project {
// Offset the frustrum by this many world-units. As long as no objects are
// larger than this number, they should still all draw, even if their
// registration points technically fall outside our frustrum.
static const float kFrustrumOffset = 50.0f;
void RenderMeshComponent::Initialize(mathfu::vec3 light_position,
MaterialManager* material_manager) {
light_position_ = light_position;
material_manager_ = material_manager;
}
// Rendermesh depends on transform:
void RenderMeshComponent::InitEntity(entity::EntityRef& entity) {
entity_manager_->AddEntityToComponent<TransformComponent>(entity);
}
void RenderMeshComponent::RenderEntity(entity::EntityRef& entity,
Renderer& renderer,
const Camera& camera) {
TransformData* transform_data = Data<TransformData>(entity);
RenderMeshData* rendermesh_data = Data<RenderMeshData>(entity);
// Check to make sure objects are inside the frustrum of our view-cone:
float max_cos = cos(camera.viewport_angle());
vec3 camera_facing = camera.facing();
vec3 entity_position = transform_data->world_transform.TranslationVector3D();
vec3 pos_relative_to_camera = (entity_position - camera.position()) +
camera_facing * kFrustrumOffset;
if (vec3::DotProduct(pos_relative_to_camera.Normalized(),
camera_facing.Normalized()) < max_cos) {
// The origin point for this mesh is not in our field of view. Cut out
// early, and don't bother rendering it.
return;
}
mat4 world_transform = transform_data->world_transform;
const mat4 mvp = camera.GetTransformMatrix() * world_transform;
const mat4 world_matrix_inverse = world_transform.Inverse();
renderer.camera_pos() = world_matrix_inverse * camera.position();
renderer.light_pos() = world_matrix_inverse * light_position_;
renderer.model_view_projection() = mvp;
renderer.color() = rendermesh_data->tint;
if (rendermesh_data->shader) {
rendermesh_data->shader->Set(renderer);
}
rendermesh_data->mesh->Render(renderer);
}
void RenderMeshComponent::RenderAllEntities(Renderer& renderer,
const Camera& camera) {
// todo(ccornell) - instead of iterating like this, sort by
// z depth and alpha blend mode.
for (auto iter = component_data_.begin();
iter != component_data_.end(); ++iter) {
RenderEntity(iter->entity, renderer, camera);
}
}
void RenderMeshComponent::AddFromRawData(entity::EntityRef& entity,
const void* raw_data) {
auto component_data = static_cast<const ComponentDefInstance*>(raw_data);
assert(component_data->data_type() == ComponentDataUnion_RenderMeshDef);
auto rendermesh_def =
static_cast<const RenderMeshDef*>(component_data->data());
// You need to call set_material_manager before you can add from raw data,
// otherwise it can't load up new meshes!
assert(material_manager_ != nullptr);
assert(rendermesh_def->source_file() != nullptr);
assert(rendermesh_def->shader() != nullptr);
RenderMeshData* rendermesh_data = AddEntity(entity);
rendermesh_data->mesh =
material_manager_->LoadMesh(rendermesh_def->source_file()->c_str());
rendermesh_data->shader =
material_manager_->LoadShader(rendermesh_def->shader()->c_str());
// TODO: Load this from a flatbuffer file instead of setting it.
rendermesh_data->tint = mathfu::kOnes4f;
}
} // fpl_project
} // fpl
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
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.
*/
#include "Extractor.h"
#include "ExtractionContainers.h"
#include "ExtractionNode.h"
#include "ExtractionWay.h"
#include "ExtractorCallbacks.h"
#include "RestrictionParser.h"
#include "ScriptingEnvironment.h"
#include "../Util/GitDescription.h"
#include "../Util/IniFileUtil.h"
#include "../Util/OSRMException.h"
#include "../Util/simple_logger.hpp"
#include "../Util/TimingUtil.h"
#include "../Util/make_unique.hpp"
#include "../typedefs.h"
#include <boost/program_options.hpp>
#include <luabind/luabind.hpp>
#include <tbb/task_scheduler_init.h>
#include <osmium/io/any_input.hpp>
#include <cstdlib>
#include <chrono>
#include <fstream>
#include <iostream>
#include <thread>
#include <unordered_map>
Extractor::Extractor() : requested_num_threads(0), file_has_pbf_format(false)
{
}
int lua_error_callback(lua_State *L) // This is so I can use my own function as an
// exception handler, pcall_log()
{
luabind::object error_msg(luabind::from_stack(L, -1));
std::ostringstream error_stream;
error_stream << error_msg;
throw OSRMException("ERROR occured in profile script:\n" + error_stream.str());
}
bool Extractor::ParseArguments(int argc, char *argv[])
{
// declare a group of options that will be allowed only on command line
boost::program_options::options_description generic_options("Options");
generic_options.add_options()("version,v", "Show version")("help,h", "Show this help message")(
"config,c",
boost::program_options::value<boost::filesystem::path>(&config_file_path)
->default_value("extractor.ini"),
"Path to a configuration file.");
// declare a group of options that will be allowed both on command line and in config file
boost::program_options::options_description config_options("Configuration");
config_options.add_options()("profile,p",
boost::program_options::value<boost::filesystem::path>(
&profile_path)->default_value("profile.lua"),
"Path to LUA routing profile")(
"threads,t",
boost::program_options::value<unsigned int>(&requested_num_threads)
->default_value(tbb::task_scheduler_init::default_num_threads()),
"Number of threads to use");
// hidden options, will be allowed both on command line and in config file, but will not be
// shown to the user
boost::program_options::options_description hidden_options("Hidden options");
hidden_options.add_options()(
"input,i",
boost::program_options::value<boost::filesystem::path>(&input_path),
"Input file in .osm, .osm.bz2 or .osm.pbf format");
// positional option
boost::program_options::positional_options_description positional_options;
positional_options.add("input", 1);
// combine above options for parsing
boost::program_options::options_description cmdline_options;
cmdline_options.add(generic_options).add(config_options).add(hidden_options);
boost::program_options::options_description config_file_options;
config_file_options.add(config_options).add(hidden_options);
boost::program_options::options_description visible_options(
boost::filesystem::basename(argv[0]) + " <input.osm/.osm.bz2/.osm.pbf> [options]");
visible_options.add(generic_options).add(config_options);
// parse command line options
boost::program_options::variables_map option_variables;
boost::program_options::store(boost::program_options::command_line_parser(argc, argv)
.options(cmdline_options)
.positional(positional_options)
.run(),
option_variables);
if (option_variables.count("version"))
{
SimpleLogger().Write() << g_GIT_DESCRIPTION;
return false;
}
if (option_variables.count("help"))
{
SimpleLogger().Write() << visible_options;
return false;
}
boost::program_options::notify(option_variables);
// parse config file
if (boost::filesystem::is_regular_file(config_file_path))
{
SimpleLogger().Write() << "Reading options from: " << config_file_path.string();
std::string ini_file_contents = ReadIniFileAndLowerContents(config_file_path);
std::stringstream config_stream(ini_file_contents);
boost::program_options::store(parse_config_file(config_stream, config_file_options),
option_variables);
boost::program_options::notify(option_variables);
}
if (!option_variables.count("input"))
{
SimpleLogger().Write() << visible_options;
return false;
}
return true;
}
void Extractor::GenerateOutputFilesNames()
{
output_file_name = input_path.string();
restriction_file_name = input_path.string();
std::string::size_type pos = output_file_name.find(".osm.bz2");
if (pos == std::string::npos)
{
pos = output_file_name.find(".osm.pbf");
if (pos != std::string::npos)
{
file_has_pbf_format = true;
}
else
{
pos = output_file_name.find(".osm.xml");
}
}
if (pos == std::string::npos)
{
pos = output_file_name.find(".pbf");
if (pos != std::string::npos)
{
file_has_pbf_format = true;
}
}
if (pos == std::string::npos)
{
pos = output_file_name.find(".osm");
if (pos == std::string::npos)
{
output_file_name.append(".osrm");
restriction_file_name.append(".osrm.restrictions");
timestamp_file_name.append(".osrm.timestamp");
}
else
{
output_file_name.replace(pos, 5, ".osrm");
restriction_file_name.replace(pos, 5, ".osrm.restrictions");
timestamp_file_name.replace(pos, 5, ".osrm.timestamp");
}
}
else
{
output_file_name.replace(pos, 8, ".osrm");
restriction_file_name.replace(pos, 8, ".osrm.restrictions");
timestamp_file_name.replace(pos, 8, ".osrm.timestamp");
}
}
int Extractor::Run(int argc, char *argv[])
{
try
{
LogPolicy::GetInstance().Unmute();
TIMER_START(extracting);
if (!ParseArguments(argc, argv))
return 0;
if (1 > requested_num_threads)
{
SimpleLogger().Write(logWARNING) << "Number of threads must be 1 or larger";
return 1;
}
if (!boost::filesystem::is_regular_file(input_path))
{
SimpleLogger().Write(logWARNING) << "Input file " << input_path.string()
<< " not found!";
return 1;
}
if (!boost::filesystem::is_regular_file(profile_path))
{
SimpleLogger().Write(logWARNING) << "Profile " << profile_path.string()
<< " not found!";
return 1;
}
const unsigned recommended_num_threads = tbb::task_scheduler_init::default_num_threads();
SimpleLogger().Write() << "Input file: " << input_path.filename().string();
SimpleLogger().Write() << "Profile: " << profile_path.filename().string();
SimpleLogger().Write() << "Threads: " << requested_num_threads;
if (recommended_num_threads != requested_num_threads)
{
SimpleLogger().Write(logWARNING) << "The recommended number of threads is "
<< recommended_num_threads
<< "! This setting may have performance side-effects.";
}
tbb::task_scheduler_init init(requested_num_threads);
/*** Setup Scripting Environment ***/
ScriptingEnvironment scripting_environment(profile_path.string().c_str());
GenerateOutputFilesNames();
std::unordered_map<std::string, NodeID> string_map;
ExtractionContainers extraction_containers;
string_map[""] = 0;
auto extractor_callbacks = osrm::make_unique<ExtractorCallbacks>(extraction_containers, string_map);
osmium::io::File infile(input_path.string());
osmium::io::Reader reader(infile);
osmium::io::Header header = reader.header();
unsigned number_of_nodes = 0;
unsigned number_of_ways = 0;
unsigned number_of_relations = 0;
unsigned number_of_others = 0;
SimpleLogger().Write() << "Parsing in progress..";
TIMER_START(parsing);
std::string generator = header.get("generator");
if (generator.empty())
{
generator = "unknown tool";
}
SimpleLogger().Write() << "input file generated by " << generator;
// TODO: write timestamp if non-empty
std::string timestamp = header.get("osmosis_replication_timestamp");
if (timestamp.empty())
{
timestamp = "n/a";
}
SimpleLogger().Write() << "timestamp: " << timestamp;
boost::filesystem::ofstream timestamp_out(timestamp_file_name);
timestamp_out.write(timestamp.c_str(), timestamp.length());
timestamp_out.close();
lua_State *lua_state = scripting_environment.getLuaState();
luabind::set_pcall_callback(&lua_error_callback);
RestrictionParser restriction_parser(scripting_environment);
ExtractionNode result_node;
ExtractionWay result_way;
while (osmium::memory::Buffer buffer = reader.read()) {
for (osmium::OSMEntity &entity : buffer)
{
switch (entity.type())
{
case osmium::item_type::node:
++number_of_nodes;
result_node.Clear();
luabind::call_function<void>(
lua_state,
"node_function",
boost::cref(static_cast<osmium::Node &>(entity)),
boost::ref(result_node));
extractor_callbacks->ProcessNode(static_cast<osmium::Node &>(entity),
result_node);
break;
case osmium::item_type::way:
++number_of_ways;
result_way.Clear();
luabind::call_function<void>(
lua_state,
"way_function",
boost::cref(static_cast<osmium::Way &>(entity)),
boost::ref(result_way));
extractor_callbacks->ProcessWay(static_cast<osmium::Way &>(entity),
result_way);
break;
case osmium::item_type::relation:
++number_of_relations;
extractor_callbacks->ProcessRestriction(
restriction_parser.TryParse(static_cast<osmium::Relation &>(entity)));
break;
default:
++number_of_others;
break;
}
}
}
TIMER_STOP(parsing);
SimpleLogger().Write() << "Parsing finished after " << TIMER_SEC(parsing) << " seconds";
extractor_callbacks.reset();
if (extraction_containers.all_edges_list.empty())
{
SimpleLogger().Write(logWARNING) << "The input data is empty, exiting.";
return 1;
}
extraction_containers.PrepareData(output_file_name, restriction_file_name);
TIMER_STOP(extracting);
SimpleLogger().Write() << "extraction finished after " << TIMER_SEC(extracting) << "s";
SimpleLogger().Write() << "To prepare the data for routing, run: "
<< "./osrm-prepare " << output_file_name << std::endl;
}
catch (boost::program_options::too_many_positional_options_error &)
{
SimpleLogger().Write(logWARNING) << "Only one input file can be specified";
return 1;
}
catch (std::exception &e)
{
SimpleLogger().Write(logWARNING) << e.what();
return 1;
}
return 0;
}
<commit_msg>fix generation of file names<commit_after>/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
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.
*/
#include "Extractor.h"
#include "ExtractionContainers.h"
#include "ExtractionNode.h"
#include "ExtractionWay.h"
#include "ExtractorCallbacks.h"
#include "RestrictionParser.h"
#include "ScriptingEnvironment.h"
#include "../Util/GitDescription.h"
#include "../Util/IniFileUtil.h"
#include "../Util/OSRMException.h"
#include "../Util/simple_logger.hpp"
#include "../Util/TimingUtil.h"
#include "../Util/make_unique.hpp"
#include "../typedefs.h"
#include <boost/program_options.hpp>
#include <luabind/luabind.hpp>
#include <tbb/task_scheduler_init.h>
#include <osmium/io/any_input.hpp>
#include <cstdlib>
#include <chrono>
#include <fstream>
#include <iostream>
#include <thread>
#include <unordered_map>
Extractor::Extractor() : requested_num_threads(0), file_has_pbf_format(false)
{
}
int lua_error_callback(lua_State *L) // This is so I can use my own function as an
// exception handler, pcall_log()
{
luabind::object error_msg(luabind::from_stack(L, -1));
std::ostringstream error_stream;
error_stream << error_msg;
throw OSRMException("ERROR occured in profile script:\n" + error_stream.str());
}
bool Extractor::ParseArguments(int argc, char *argv[])
{
// declare a group of options that will be allowed only on command line
boost::program_options::options_description generic_options("Options");
generic_options.add_options()("version,v", "Show version")("help,h", "Show this help message")(
"config,c",
boost::program_options::value<boost::filesystem::path>(&config_file_path)
->default_value("extractor.ini"),
"Path to a configuration file.");
// declare a group of options that will be allowed both on command line and in config file
boost::program_options::options_description config_options("Configuration");
config_options.add_options()("profile,p",
boost::program_options::value<boost::filesystem::path>(
&profile_path)->default_value("profile.lua"),
"Path to LUA routing profile")(
"threads,t",
boost::program_options::value<unsigned int>(&requested_num_threads)
->default_value(tbb::task_scheduler_init::default_num_threads()),
"Number of threads to use");
// hidden options, will be allowed both on command line and in config file, but will not be
// shown to the user
boost::program_options::options_description hidden_options("Hidden options");
hidden_options.add_options()(
"input,i",
boost::program_options::value<boost::filesystem::path>(&input_path),
"Input file in .osm, .osm.bz2 or .osm.pbf format");
// positional option
boost::program_options::positional_options_description positional_options;
positional_options.add("input", 1);
// combine above options for parsing
boost::program_options::options_description cmdline_options;
cmdline_options.add(generic_options).add(config_options).add(hidden_options);
boost::program_options::options_description config_file_options;
config_file_options.add(config_options).add(hidden_options);
boost::program_options::options_description visible_options(
boost::filesystem::basename(argv[0]) + " <input.osm/.osm.bz2/.osm.pbf> [options]");
visible_options.add(generic_options).add(config_options);
// parse command line options
boost::program_options::variables_map option_variables;
boost::program_options::store(boost::program_options::command_line_parser(argc, argv)
.options(cmdline_options)
.positional(positional_options)
.run(),
option_variables);
if (option_variables.count("version"))
{
SimpleLogger().Write() << g_GIT_DESCRIPTION;
return false;
}
if (option_variables.count("help"))
{
SimpleLogger().Write() << visible_options;
return false;
}
boost::program_options::notify(option_variables);
// parse config file
if (boost::filesystem::is_regular_file(config_file_path))
{
SimpleLogger().Write() << "Reading options from: " << config_file_path.string();
std::string ini_file_contents = ReadIniFileAndLowerContents(config_file_path);
std::stringstream config_stream(ini_file_contents);
boost::program_options::store(parse_config_file(config_stream, config_file_options),
option_variables);
boost::program_options::notify(option_variables);
}
if (!option_variables.count("input"))
{
SimpleLogger().Write() << visible_options;
return false;
}
return true;
}
void Extractor::GenerateOutputFilesNames()
{
output_file_name = input_path.string();
restriction_file_name = input_path.string();
timestamp_file_name = input_path.string();
std::string::size_type pos = output_file_name.find(".osm.bz2");
if (pos == std::string::npos)
{
pos = output_file_name.find(".osm.pbf");
if (pos != std::string::npos)
{
file_has_pbf_format = true;
}
else
{
pos = output_file_name.find(".osm.xml");
}
}
if (pos == std::string::npos)
{
pos = output_file_name.find(".pbf");
if (pos != std::string::npos)
{
file_has_pbf_format = true;
}
}
if (pos == std::string::npos)
{
pos = output_file_name.find(".osm");
if (pos == std::string::npos)
{
output_file_name.append(".osrm");
restriction_file_name.append(".osrm.restrictions");
timestamp_file_name.append(".osrm.timestamp");
}
else
{
output_file_name.replace(pos, 5, ".osrm");
restriction_file_name.replace(pos, 5, ".osrm.restrictions");
timestamp_file_name.replace(pos, 5, ".osrm.timestamp");
}
}
else
{
output_file_name.replace(pos, 8, ".osrm");
restriction_file_name.replace(pos, 8, ".osrm.restrictions");
timestamp_file_name.replace(pos, 8, ".osrm.timestamp");
}
}
int Extractor::Run(int argc, char *argv[])
{
try
{
LogPolicy::GetInstance().Unmute();
TIMER_START(extracting);
if (!ParseArguments(argc, argv))
return 0;
if (1 > requested_num_threads)
{
SimpleLogger().Write(logWARNING) << "Number of threads must be 1 or larger";
return 1;
}
if (!boost::filesystem::is_regular_file(input_path))
{
SimpleLogger().Write(logWARNING) << "Input file " << input_path.string()
<< " not found!";
return 1;
}
if (!boost::filesystem::is_regular_file(profile_path))
{
SimpleLogger().Write(logWARNING) << "Profile " << profile_path.string()
<< " not found!";
return 1;
}
const unsigned recommended_num_threads = tbb::task_scheduler_init::default_num_threads();
SimpleLogger().Write() << "Input file: " << input_path.filename().string();
SimpleLogger().Write() << "Profile: " << profile_path.filename().string();
SimpleLogger().Write() << "Threads: " << requested_num_threads;
if (recommended_num_threads != requested_num_threads)
{
SimpleLogger().Write(logWARNING) << "The recommended number of threads is "
<< recommended_num_threads
<< "! This setting may have performance side-effects.";
}
tbb::task_scheduler_init init(requested_num_threads);
/*** Setup Scripting Environment ***/
ScriptingEnvironment scripting_environment(profile_path.string().c_str());
GenerateOutputFilesNames();
std::unordered_map<std::string, NodeID> string_map;
ExtractionContainers extraction_containers;
string_map[""] = 0;
auto extractor_callbacks = osrm::make_unique<ExtractorCallbacks>(extraction_containers, string_map);
osmium::io::File infile(input_path.string());
osmium::io::Reader reader(infile);
osmium::io::Header header = reader.header();
unsigned number_of_nodes = 0;
unsigned number_of_ways = 0;
unsigned number_of_relations = 0;
unsigned number_of_others = 0;
SimpleLogger().Write() << "Parsing in progress..";
TIMER_START(parsing);
std::string generator = header.get("generator");
if (generator.empty())
{
generator = "unknown tool";
}
SimpleLogger().Write() << "input file generated by " << generator;
// TODO: write timestamp if non-empty
std::string timestamp = header.get("osmosis_replication_timestamp");
if (timestamp.empty())
{
timestamp = "n/a";
}
SimpleLogger().Write() << "timestamp: " << timestamp;
boost::filesystem::ofstream timestamp_out(timestamp_file_name);
timestamp_out.write(timestamp.c_str(), timestamp.length());
timestamp_out.close();
lua_State *lua_state = scripting_environment.getLuaState();
luabind::set_pcall_callback(&lua_error_callback);
RestrictionParser restriction_parser(scripting_environment);
ExtractionNode result_node;
ExtractionWay result_way;
while (osmium::memory::Buffer buffer = reader.read()) {
for (osmium::OSMEntity &entity : buffer)
{
switch (entity.type())
{
case osmium::item_type::node:
++number_of_nodes;
result_node.Clear();
// luabind::call_function<void>(
// lua_state,
// "node_function",
// boost::cref(static_cast<osmium::Node &>(entity)),
// boost::ref(result_node));
// extractor_callbacks->ProcessNode(static_cast<osmium::Node &>(entity),
// result_node);
break;
case osmium::item_type::way:
++number_of_ways;
result_way.Clear();
// luabind::call_function<void>(
// lua_state,
// "way_function",
// boost::cref(static_cast<osmium::Way &>(entity)),
// boost::ref(result_way));
// extractor_callbacks->ProcessWay(static_cast<osmium::Way &>(entity),
// result_way);
break;
case osmium::item_type::relation:
++number_of_relations;
extractor_callbacks->ProcessRestriction(
restriction_parser.TryParse(static_cast<osmium::Relation &>(entity)));
break;
default:
++number_of_others;
break;
}
}
}
TIMER_STOP(parsing);
SimpleLogger().Write() << "Parsing finished after " << TIMER_SEC(parsing) << " seconds";
SimpleLogger().Write() << "Raw input contains " << number_of_nodes << " nodes, " << number_of_ways << " ways, and " << number_of_relations << " relations";
extractor_callbacks.reset();
if (extraction_containers.all_edges_list.empty())
{
SimpleLogger().Write(logWARNING) << "The input data is empty, exiting.";
return 1;
}
extraction_containers.PrepareData(output_file_name, restriction_file_name);
TIMER_STOP(extracting);
SimpleLogger().Write() << "extraction finished after " << TIMER_SEC(extracting) << "s";
SimpleLogger().Write() << "To prepare the data for routing, run: "
<< "./osrm-prepare " << output_file_name << std::endl;
}
catch (boost::program_options::too_many_positional_options_error &)
{
SimpleLogger().Write(logWARNING) << "Only one input file can be specified";
return 1;
}
catch (std::exception &e)
{
SimpleLogger().Write(logWARNING) << e.what();
return 1;
}
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>AliFITv8: Remove old containing volumes and some of the screws, rods, which cause overlaps<commit_after><|endoftext|>
|
<commit_before>/*
* File: Network.cpp
* Author: janvojt
*
* Created on May 30, 2014, 12:17 AM
*/
#include "Network.h"
#include <cstring>
#include <string>
Network::Network(NetworkConfiguration *conf) {
this->conf = conf;
this->noLayers = conf->getLayers();
this->bias = 0;
initWeights();
initInputs();
}
Network::Network(const Network& orig) {
}
Network::~Network() {
delete weights;
delete inputs;
}
NetworkConfiguration* Network::getConfiguration() {
return conf;
}
void Network::initWeights() {
int noWeights = 0;
int pLayer = 1; // neurons in previous layer
for (int i = 0; i<noLayers; i++) {
int tLayer = this->conf->getNeurons(i);
noWeights += pLayer * tLayer;
pLayer = tLayer;
}
weights = new float[noWeights];
// initialize weights for input layer to 1
for (int i = 0; i<getInputNeurons(); i++) {
weights[i] = 1;
}
}
void Network::initInputs() {
int noNeurons = 0;
for (int i = 0; i<noLayers; i++) {
noNeurons += conf->getNeurons(i);
}
this->noNeurons = noNeurons;
inputs = new float[noNeurons];
}
void Network::setInput(float* input) {
std::memcpy(inputs, input, sizeof(float) * getInputNeurons());
}
void Network::run() {
// number of neurons in so far processed layers
int nPrevLayers = 0;
// for every layer
for (int l = 0; l<noLayers; l++) {
int nThisLayer = conf->getNeurons(l);
int nNextLayer = conf->getNeurons(l+1);
clearLayer(inputs + nPrevLayers + nThisLayer, nNextLayer);
// for every neuron in (l)th layer
for (int i = 0; i<nThisLayer; i++) {
// for every neuron in (l+1)th layer
for (int j = 0; j<nNextLayer; j++) {
int indexFrom = nPrevLayers + i;
int indexTo = nPrevLayers + nThisLayer + j;
inputs[indexTo] += inputs[indexFrom];
}
}
nPrevLayers += nThisLayer;
}
}
void Network::clearLayer(float *inputPtr, int layerSize) {
std::fill_n(inputPtr, layerSize, 0);
}
float* Network::getOutput() {
return inputs + noNeurons - getOutputNeurons();
}
int Network::getInputNeurons() {
return conf->getNeurons(0);
}
int Network::getOutputNeurons() {
return conf->getNeurons(noLayers-1);
}
<commit_msg>Using weights when computing output.<commit_after>/*
* File: Network.cpp
* Author: janvojt
*
* Created on May 30, 2014, 12:17 AM
*/
#include "Network.h"
#include <cstring>
#include <string>
Network::Network(NetworkConfiguration *conf) {
this->conf = conf;
this->noLayers = conf->getLayers();
this->bias = 0;
initWeights();
initInputs();
}
Network::Network(const Network& orig) {
}
Network::~Network() {
delete weights;
delete inputs;
}
NetworkConfiguration* Network::getConfiguration() {
return conf;
}
void Network::initWeights() {
int noWeights = 0;
int pLayer = 1; // neurons in previous layer
for (int i = 0; i<noLayers; i++) {
int tLayer = this->conf->getNeurons(i);
noWeights += pLayer * tLayer;
pLayer = tLayer;
}
weights = new float[noWeights];
// initialize weights for input layer to 1
for (int i = 0; i<getInputNeurons(); i++) {
weights[i] = 1;
}
}
void Network::initInputs() {
int noNeurons = 0;
for (int i = 0; i<noLayers; i++) {
noNeurons += conf->getNeurons(i);
}
this->noNeurons = noNeurons;
inputs = new float[noNeurons];
}
void Network::setInput(float* input) {
std::memcpy(inputs, input, sizeof(float) * getInputNeurons());
}
void Network::run() {
// number of neurons in so far processed layers
int nPrevLayers = 0;
float *weighPtr = weights + getInputNeurons();
// for every layer
for (int l = 0; l<noLayers; l++) {
int nThisLayer = conf->getNeurons(l);
int nNextLayer = conf->getNeurons(l+1);
clearLayer(inputs + nPrevLayers + nThisLayer, nNextLayer);
// for every neuron in (l)th layer
for (int i = 0; i<nThisLayer; i++) {
// for every neuron in (l+1)th layer
for (int j = 0; j<nNextLayer; j++) {
int indexFrom = nPrevLayers + i;
int indexTo = nPrevLayers + nThisLayer + j;
inputs[indexTo] += *weighPtr * inputs[indexFrom];
weighPtr++;
}
}
nPrevLayers += nThisLayer;
}
}
void Network::clearLayer(float *inputPtr, int layerSize) {
std::fill_n(inputPtr, layerSize, 0);
}
float* Network::getOutput() {
return inputs + noNeurons - getOutputNeurons();
}
int Network::getInputNeurons() {
return conf->getNeurons(0);
}
int Network::getOutputNeurons() {
return conf->getNeurons(noLayers-1);
}
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2019 The nanoFramework project contributors
// See LICENSE file in the project root for full license information.
//
#include "sys_dev_dac_native.h"
static const CLR_RT_MethodHandler method_lookup[] =
{
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
Library_sys_dev_dac_native_System_Devices_Dac_DacChannel::NativeWriteValue___VOID__U2,
Library_sys_dev_dac_native_System_Devices_Dac_DacChannel::NativeDispose___VOID__BOOLEAN,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
Library_sys_dev_dac_native_System_Devices_Dac_DacController::NativeOpenChannel___VOID__I4,
Library_sys_dev_dac_native_System_Devices_Dac_DacController::NativeGetChannelCount___I4,
Library_sys_dev_dac_native_System_Devices_Dac_DacController::NativeGetResolutionInBits___I4,
Library_sys_dev_dac_native_System_Devices_Dac_DacController::NativeInit___VOID,
NULL,
Library_sys_dev_dac_native_System_Devices_Dac_DacController::GetDeviceSelector___STATIC__STRING,
NULL,
NULL,
NULL,
};
const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_System_Devices_Dac =
{
"System.Devices.Dac",
0x12640AF3,
method_lookup,
{ 100, 0, 0, 4 }
};
<commit_msg>Update declaration of Devices.Dac (#1479)<commit_after>//
// Copyright (c) 2019 The nanoFramework project contributors
// See LICENSE file in the project root for full license information.
//
#include "sys_dev_dac_native.h"
static const CLR_RT_MethodHandler method_lookup[] =
{
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
Library_sys_dev_dac_native_System_Devices_Dac_DacChannel::NativeWriteValue___VOID__U2,
Library_sys_dev_dac_native_System_Devices_Dac_DacChannel::NativeDispose___VOID__BOOLEAN,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
Library_sys_dev_dac_native_System_Devices_Dac_DacController::NativeOpenChannel___VOID__I4,
Library_sys_dev_dac_native_System_Devices_Dac_DacController::NativeGetChannelCount___I4,
Library_sys_dev_dac_native_System_Devices_Dac_DacController::NativeGetResolutionInBits___I4,
Library_sys_dev_dac_native_System_Devices_Dac_DacController::NativeInit___VOID,
NULL,
NULL,
Library_sys_dev_dac_native_System_Devices_Dac_DacController::GetDeviceSelector___STATIC__STRING,
NULL,
NULL,
NULL,
};
const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_System_Devices_Dac =
{
"System.Devices.Dac",
0x9B932004,
method_lookup,
{ 100, 0, 0, 5 }
};
<|endoftext|>
|
<commit_before>#include "IHMD.hpp"
#include <bx/fpumath.h>
#include <SDL.h>
#include "Registry.hpp"
namespace xveearr
{
namespace
{
const unsigned int gViewportWidth = 1280 / 2;
const unsigned int gViewportHeight = 720;
const float gLeftEye[] = { -50.0f, 0.0f, 0.f };
const float gRightEye[] = { 50.0f, 0.0f, 0.f };
float gLookAt[] = { 0.f, 0.0f, -10.f };
}
class NullHMD: public IHMD
{
public:
NullHMD()
{
mRenderData[Eye::Left].mFrameBuffer = BGFX_INVALID_HANDLE;
mRenderData[Eye::Right].mFrameBuffer = BGFX_INVALID_HANDLE;
}
bool init(const ApplicationContext&)
{
bx::mtxSRT(mHeadTransform,
1.f, 1.f, 1.f,
0.f, 0.f, 0.f,
0.f, 0.f, 600.f);
return true;
}
void shutdown()
{
}
void initRenderer()
{
}
void shutdownRenderer()
{
}
void beginRender()
{
}
void endRender()
{
}
void prepareResources()
{
mRenderData[Eye::Left].mFrameBuffer = createEyeFB();
mRenderData[Eye::Right].mFrameBuffer = createEyeFB();
}
void releaseResources()
{
if(bgfx::isValid(mRenderData[Eye::Left].mFrameBuffer))
{
bgfx::destroyFrameBuffer(mRenderData[Eye::Left].mFrameBuffer);
}
if(bgfx::isValid(mRenderData[Eye::Right].mFrameBuffer))
{
bgfx::destroyFrameBuffer(mRenderData[Eye::Right].mFrameBuffer);
}
}
void getViewportSize(unsigned int& width, unsigned int& height)
{
width = gViewportWidth;
height = gViewportHeight;
}
const char* getName() const
{
return "null";
}
void update()
{
const Uint8* keyStates = SDL_GetKeyboardState(NULL);
float translation[3] = {};
float rotation[3] = {};
if(keyStates[SDL_SCANCODE_A]) { translation[0] = -4.f; }
if(keyStates[SDL_SCANCODE_D]) { translation[0] = 4.f; }
if(keyStates[SDL_SCANCODE_W]) { translation[2] = -4.f; }
if(keyStates[SDL_SCANCODE_S]) { translation[2] = 4.f; }
if(keyStates[SDL_SCANCODE_Q]) { rotation[1] = -0.01f; }
if(keyStates[SDL_SCANCODE_E]) { rotation[1] = 0.01f; }
if(keyStates[SDL_SCANCODE_R]) { rotation[0] = -0.01f; }
if(keyStates[SDL_SCANCODE_F]) { rotation[0] = 0.01f; }
float move[16];
bx::mtxSRT(move,
1.f, 1.f, 1.f,
rotation[0], rotation[1], rotation[2],
translation[0], translation[1], translation[2]
);
float tmp[16];
memcpy(tmp, mHeadTransform, sizeof(tmp));
bx::mtxMul(mHeadTransform, move, tmp);
float leftEye[3];
float leftLookAt[3];
float leftRelLookat[3];
bx::vec3MulMtx(leftEye, gLeftEye, mHeadTransform);
bx::vec3Add(leftRelLookat, gLeftEye, gLookAt);
bx::vec3MulMtx(leftLookAt, leftRelLookat, mHeadTransform);
bx::mtxLookAtRh(
mRenderData[Eye::Left].mViewTransform, leftEye, leftLookAt
);
bx::mtxProjRh(mRenderData[Eye::Left].mViewProjection,
50.0f,
(float)gViewportWidth / (float)gViewportHeight,
1.f, 100000.f
);
float rightEye[3];
float rightLookAt[3];
float rightRelLookat[3];
bx::vec3MulMtx(rightEye, gRightEye, mHeadTransform);
bx::vec3Add(rightRelLookat, gRightEye, gLookAt);
bx::vec3MulMtx(rightLookAt, rightRelLookat, mHeadTransform);
bx::mtxLookAtRh(
mRenderData[Eye::Right].mViewTransform, rightEye, rightLookAt
);
bx::mtxProjRh(mRenderData[Eye::Right].mViewProjection,
50.0f,
(float)gViewportWidth / (float)gViewportHeight,
1.f, 100000.f
);
}
const RenderData& getRenderData(Eye::Enum eye)
{
return mRenderData[eye];
}
private:
bgfx::FrameBufferHandle createEyeFB()
{
bgfx::TextureHandle textures[] = {
bgfx::createTexture2D(
gViewportWidth, gViewportHeight, 1,
bgfx::TextureFormat::BGRA8,
BGFX_TEXTURE_RT|BGFX_TEXTURE_U_CLAMP|BGFX_TEXTURE_V_CLAMP
),
bgfx::createTexture2D(
gViewportWidth, gViewportHeight, 1,
bgfx::TextureFormat::D16,
BGFX_TEXTURE_RT_WRITE_ONLY
)
};
return bgfx::createFrameBuffer(BX_COUNTOF(textures), textures, true);
}
float mHeadTransform[16];
RenderData mRenderData[Eye::Count];
};
NullHMD gNullHMDInstance;
Registry<IHMD>::Entry gFakeHMDEntry(&gNullHMDInstance);
}
<commit_msg>Use floating point format for eye framebuffer's depth texture<commit_after>#include "IHMD.hpp"
#include <bx/fpumath.h>
#include <SDL.h>
#include "Registry.hpp"
namespace xveearr
{
namespace
{
const unsigned int gViewportWidth = 1280 / 2;
const unsigned int gViewportHeight = 720;
const float gLeftEye[] = { -50.0f, 0.0f, 0.f };
const float gRightEye[] = { 50.0f, 0.0f, 0.f };
float gLookAt[] = { 0.f, 0.0f, -10.f };
}
class NullHMD: public IHMD
{
public:
NullHMD()
{
mRenderData[Eye::Left].mFrameBuffer = BGFX_INVALID_HANDLE;
mRenderData[Eye::Right].mFrameBuffer = BGFX_INVALID_HANDLE;
}
bool init(const ApplicationContext&)
{
bx::mtxSRT(mHeadTransform,
1.f, 1.f, 1.f,
0.f, 0.f, 0.f,
0.f, 0.f, 600.f);
return true;
}
void shutdown()
{
}
void initRenderer()
{
}
void shutdownRenderer()
{
}
void beginRender()
{
}
void endRender()
{
}
void prepareResources()
{
mRenderData[Eye::Left].mFrameBuffer = createEyeFB();
mRenderData[Eye::Right].mFrameBuffer = createEyeFB();
}
void releaseResources()
{
if(bgfx::isValid(mRenderData[Eye::Left].mFrameBuffer))
{
bgfx::destroyFrameBuffer(mRenderData[Eye::Left].mFrameBuffer);
}
if(bgfx::isValid(mRenderData[Eye::Right].mFrameBuffer))
{
bgfx::destroyFrameBuffer(mRenderData[Eye::Right].mFrameBuffer);
}
}
void getViewportSize(unsigned int& width, unsigned int& height)
{
width = gViewportWidth;
height = gViewportHeight;
}
const char* getName() const
{
return "null";
}
void update()
{
const Uint8* keyStates = SDL_GetKeyboardState(NULL);
float translation[3] = {};
float rotation[3] = {};
if(keyStates[SDL_SCANCODE_A]) { translation[0] = -4.f; }
if(keyStates[SDL_SCANCODE_D]) { translation[0] = 4.f; }
if(keyStates[SDL_SCANCODE_W]) { translation[2] = -4.f; }
if(keyStates[SDL_SCANCODE_S]) { translation[2] = 4.f; }
if(keyStates[SDL_SCANCODE_Q]) { rotation[1] = -0.01f; }
if(keyStates[SDL_SCANCODE_E]) { rotation[1] = 0.01f; }
if(keyStates[SDL_SCANCODE_R]) { rotation[0] = -0.01f; }
if(keyStates[SDL_SCANCODE_F]) { rotation[0] = 0.01f; }
float move[16];
bx::mtxSRT(move,
1.f, 1.f, 1.f,
rotation[0], rotation[1], rotation[2],
translation[0], translation[1], translation[2]
);
float tmp[16];
memcpy(tmp, mHeadTransform, sizeof(tmp));
bx::mtxMul(mHeadTransform, move, tmp);
float leftEye[3];
float leftLookAt[3];
float leftRelLookat[3];
bx::vec3MulMtx(leftEye, gLeftEye, mHeadTransform);
bx::vec3Add(leftRelLookat, gLeftEye, gLookAt);
bx::vec3MulMtx(leftLookAt, leftRelLookat, mHeadTransform);
bx::mtxLookAtRh(
mRenderData[Eye::Left].mViewTransform, leftEye, leftLookAt
);
bx::mtxProjRh(mRenderData[Eye::Left].mViewProjection,
50.0f,
(float)gViewportWidth / (float)gViewportHeight,
1.f, 100000.f
);
float rightEye[3];
float rightLookAt[3];
float rightRelLookat[3];
bx::vec3MulMtx(rightEye, gRightEye, mHeadTransform);
bx::vec3Add(rightRelLookat, gRightEye, gLookAt);
bx::vec3MulMtx(rightLookAt, rightRelLookat, mHeadTransform);
bx::mtxLookAtRh(
mRenderData[Eye::Right].mViewTransform, rightEye, rightLookAt
);
bx::mtxProjRh(mRenderData[Eye::Right].mViewProjection,
50.0f,
(float)gViewportWidth / (float)gViewportHeight,
1.f, 100000.f
);
}
const RenderData& getRenderData(Eye::Enum eye)
{
return mRenderData[eye];
}
private:
bgfx::FrameBufferHandle createEyeFB()
{
bgfx::TextureHandle textures[] = {
bgfx::createTexture2D(
gViewportWidth, gViewportHeight, 1,
bgfx::TextureFormat::BGRA8,
BGFX_TEXTURE_RT|BGFX_TEXTURE_U_CLAMP|BGFX_TEXTURE_V_CLAMP
),
bgfx::createTexture2D(
gViewportWidth, gViewportHeight, 1,
bgfx::TextureFormat::D16F,
BGFX_TEXTURE_RT_WRITE_ONLY
)
};
return bgfx::createFrameBuffer(BX_COUNTOF(textures), textures, true);
}
float mHeadTransform[16];
RenderData mRenderData[Eye::Count];
};
NullHMD gNullHMDInstance;
Registry<IHMD>::Entry gFakeHMDEntry(&gNullHMDInstance);
}
<|endoftext|>
|
<commit_before>#include <Process.h>
#include <boost/interprocess/sync/named_semaphore.hpp>
#include <unistd.h>
namespace Interprocess
{
using Semaphore = boost::interprocess::named_semaphore;
boost::interprocess::open_or_create_t OpenCreate = boost::interprocess::open_or_create;
using namespace std;
Process::Process(Process&& otherProcess)
: _processId(otherProcess._processId), _mainFunction(otherProcess._mainFunction)
{
otherProcess._processId = -1;
}
Process& Process::operator=(Process&& otherProcess)
{
_processId = otherProcess._processId;
_mainFunction = otherProcess._mainFunction;
return *this;
}
void Process::startProcess() const
{
auto pIDString = to_string(_processId);
Semaphore semaphore(OpenCreate, pIDString.c_str(), 0);
semaphore.post();
}
void Process::childProcessRunner()
{
_processId = fork();
if( ! _processId)
{
auto pIDString = to_string(getpid());
Semaphore semaphore(OpenCreate, pIDString.c_str(), 0);
semaphore.wait();
_mainFunction();
exit(0);
}
}
}
<commit_msg>Removed global open or create variable, fixed move constructor.<commit_after>#include <Process.h>
#include <boost/interprocess/sync/named_semaphore.hpp>
#include <unistd.h>
namespace Interprocess
{
using Semaphore = boost::interprocess::named_semaphore;
using namespace boost::interprocess;
using namespace std;
Process::Process(Process&& otherProcess)
: _processId(otherProcess._processId), _mainFunction(otherProcess._mainFunction)
{
otherProcess._processId = -1;
}
Process& Process::operator=(Process&& otherProcess)
{
_processId = otherProcess._processId;
_mainFunction = otherProcess._mainFunction;
otherProcess._processId = -1;
return *this;
}
void Process::startProcess() const
{
auto pIDString = to_string(_processId);
Semaphore semaphore(open_or_create, pIDString.c_str(), 0);
semaphore.post();
}
void Process::childProcessRunner()
{
_processId = fork();
if( ! _processId)
{
auto pIDString = to_string(getpid());
Semaphore semaphore(open_or_create, pIDString.c_str(), 0);
semaphore.wait();
_mainFunction();
exit(0);
}
}
}
<|endoftext|>
|
<commit_before>// Program.cpp
#include "stdafx.h"
#include "Program.h"
#include "PythonStuff.h"
#include "../../tinyxml/tinyxml.h"
#include "ProgramCanvas.h"
#include "NCCode.h"
#include "../../interface/MarkedObject.h"
#include "../../interface/PropertyString.h"
#include "Profile.h"
#include "Pocket.h"
#include "ZigZag.h"
bool COperations::CanAdd(HeeksObj* object)
{
return object->GetType() == ProfileType || object->GetType() == PocketType || object->GetType() == ZigZagType;
}
void COperations::WriteXML(TiXmlNode *root)
{
TiXmlElement * element;
element = new TiXmlElement( "Operations" );
root->LinkEndChild( element );
WriteBaseXML(element);
}
//static
HeeksObj* COperations::ReadFromXMLElement(TiXmlElement* pElem)
{
COperations* new_object = new COperations;
new_object->ReadBaseXML(pElem);
return new_object;
}
CProgram::CProgram():m_machine(_T("nc.iso")), m_output_file(_T("test.tap")), m_nc_code(NULL), m_operations(NULL), m_script_edited(false)
{
}
HeeksObj *CProgram::MakeACopy(void)const
{
return new CProgram(*this);
}
void CProgram::CopyFrom(const HeeksObj* object)
{
operator=(*((CProgram*)object));
}
static void on_set_machine(const wxChar* value, HeeksObj* object){((CProgram*)object)->m_machine = value;}
static void on_set_output_file(const wxChar* value, HeeksObj* object){((CProgram*)object)->m_output_file = value;}
void CProgram::GetProperties(std::list<Property *> *list)
{
list->push_back(new PropertyString(_("machine"), m_machine, this, on_set_machine));
list->push_back(new PropertyString(_("output file"), m_output_file, this, on_set_output_file));
HeeksObj::GetProperties(list);
}
bool CProgram::CanAdd(HeeksObj* object)
{
return object->GetType() == NCCodeType || object->GetType() == OperationsType;
}
bool CProgram::CanAddTo(HeeksObj* owner)
{
return owner->GetType() == DocumentType;
}
void CProgram::SetClickMarkPoint(MarkedObject* marked_object, const double* ray_start, const double* ray_direction)
{
if(marked_object->m_map.size() > 0)
{
MarkedObject* sub_marked_object = marked_object->m_map.begin()->second;
if(sub_marked_object)
{
HeeksObj* object = sub_marked_object->m_map.begin()->first;
if(object && object->GetType() == NCCodeType)
{
((CNCCode*)object)->SetClickMarkPoint(sub_marked_object, ray_start, ray_direction);
}
}
}
}
void CProgram::WriteXML(TiXmlNode *root)
{
TiXmlElement * element;
element = new TiXmlElement( "Program" );
root->LinkEndChild( element );
element->SetAttribute("machine", Ttc(m_machine.c_str()));
element->SetAttribute("output_file", Ttc(m_output_file.c_str()));
element->SetAttribute("program", Ttc(theApp.m_program_canvas->m_textCtrl->GetValue()));
WriteBaseXML(element);
}
bool CProgram::Add(HeeksObj* object, HeeksObj* prev_object)
{
if(object->GetType() == NCCodeType)m_nc_code = (CNCCode*)object;
if(object->GetType() == OperationsType)m_operations = (COperations*)object;
return ObjList::Add(object, prev_object);
}
void CProgram::Remove(HeeksObj* object)
{
// these shouldn't happen, though
if(object == m_nc_code)m_nc_code = NULL;
else if(object == m_operations)m_operations = NULL;
ObjList::Remove(object);
}
// static member function
HeeksObj* CProgram::ReadFromXMLElement(TiXmlElement* pElem)
{
CProgram* new_object = new CProgram;
// get the attributes
for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())
{
std::string name(a->Name());
if(name == "machine"){new_object->m_machine.assign(Ctt(a->Value()));}
else if(name == "output_file"){new_object->m_output_file.assign(Ctt(a->Value()));}
else if(name == "program"){theApp.m_program_canvas->m_textCtrl->SetValue(Ctt(a->Value()));}
}
new_object->ReadBaseXML(pElem);
theApp.m_program = new_object;
return new_object;
}
void CProgram::RewritePythonProgram()
{
theApp.m_program_canvas->m_textCtrl->Clear();
CZigZag::number_for_stl_file = 1;
bool profile_op_exists = false;
bool pocket_op_exists = false;
bool zigzag_op_exists = false;
for(HeeksObj* object = m_operations->GetFirstChild(); object; object = m_operations->GetNextChild())
{
if(object->GetType() == ProfileType)
{
profile_op_exists = true;
}
else if(object->GetType() == PocketType)
{
pocket_op_exists = true;
}
else if(object->GetType() == ZigZagType)
{
zigzag_op_exists = true;
}
}
// add standard stuff at the top
// kurve related things
if(profile_op_exists)
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import kurve\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import kurve_funcs\n"));
}
// area related things
if(pocket_op_exists)
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import area\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import area_funcs\n"));
}
// pycam stuff
if(zigzag_op_exists)
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import sys\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("sys.path.insert(0,'PyCam/trunk')\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Geometry import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.SphericalCutter import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.CylindricalCutter import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Importers.STLImporter import ImportModel\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.PathGenerators.DropCutter import DropCutter\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from PyCamToHeeks import HeeksCNCExporter\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
}
// machine general stuff
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from nc.nc import *\n"));
// specific machine
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import ") + m_machine + _T("\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
// output file
theApp.m_program_canvas->m_textCtrl->AppendText(_T("output('") + m_output_file + _T("')\n"));
// begin program
theApp.m_program_canvas->m_textCtrl->AppendText(_T("program_begin(123, 'Test program')\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("absolute()\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("metric()\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("set_plane(0)\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
// write the operations
for(HeeksObj* object = m_operations->GetFirstChild(); object; object = m_operations->GetNextChild())
{
switch(object->GetType())
{
case ProfileType:
((CProfile*)object)->AppendTextToProgram();
break;
case PocketType:
((CPocket*)object)->AppendTextToProgram();
break;
case ZigZagType:
((CZigZag*)object)->AppendTextToProgram();
break;
}
}
}
ProgramUserType CProgram::GetUserType()
{
if(m_nc_code->m_user_edited)return ProgramUserTypeNC;
if(m_script_edited)return ProgramUserTypeScript;
if(m_operations->GetFirstChild())return ProgramUserTypeTree;
return ProgramUserTypeUnkown;
}
void CProgram::UpdateFromUserType()
{
#if 0
switch(GetUserType())
{
case ProgramUserTypeUnkown:
case tree:
Enable "Operations" icon in tree
editing the tree, recreates the python script
Read only "Program" window
pressing "Post-process" creates the NC code ( and backplots it )
Read only "Output" window
Disable all buttons on "Output" window
}
#endif
}<commit_msg>import pycam.Cutters.ToroidalCutter<commit_after>// Program.cpp
#include "stdafx.h"
#include "Program.h"
#include "PythonStuff.h"
#include "../../tinyxml/tinyxml.h"
#include "ProgramCanvas.h"
#include "NCCode.h"
#include "../../interface/MarkedObject.h"
#include "../../interface/PropertyString.h"
#include "Profile.h"
#include "Pocket.h"
#include "ZigZag.h"
bool COperations::CanAdd(HeeksObj* object)
{
return object->GetType() == ProfileType || object->GetType() == PocketType || object->GetType() == ZigZagType;
}
void COperations::WriteXML(TiXmlNode *root)
{
TiXmlElement * element;
element = new TiXmlElement( "Operations" );
root->LinkEndChild( element );
WriteBaseXML(element);
}
//static
HeeksObj* COperations::ReadFromXMLElement(TiXmlElement* pElem)
{
COperations* new_object = new COperations;
new_object->ReadBaseXML(pElem);
return new_object;
}
CProgram::CProgram():m_machine(_T("nc.iso")), m_output_file(_T("test.tap")), m_nc_code(NULL), m_operations(NULL), m_script_edited(false)
{
}
HeeksObj *CProgram::MakeACopy(void)const
{
return new CProgram(*this);
}
void CProgram::CopyFrom(const HeeksObj* object)
{
operator=(*((CProgram*)object));
}
static void on_set_machine(const wxChar* value, HeeksObj* object){((CProgram*)object)->m_machine = value;}
static void on_set_output_file(const wxChar* value, HeeksObj* object){((CProgram*)object)->m_output_file = value;}
void CProgram::GetProperties(std::list<Property *> *list)
{
list->push_back(new PropertyString(_("machine"), m_machine, this, on_set_machine));
list->push_back(new PropertyString(_("output file"), m_output_file, this, on_set_output_file));
HeeksObj::GetProperties(list);
}
bool CProgram::CanAdd(HeeksObj* object)
{
return object->GetType() == NCCodeType || object->GetType() == OperationsType;
}
bool CProgram::CanAddTo(HeeksObj* owner)
{
return owner->GetType() == DocumentType;
}
void CProgram::SetClickMarkPoint(MarkedObject* marked_object, const double* ray_start, const double* ray_direction)
{
if(marked_object->m_map.size() > 0)
{
MarkedObject* sub_marked_object = marked_object->m_map.begin()->second;
if(sub_marked_object)
{
HeeksObj* object = sub_marked_object->m_map.begin()->first;
if(object && object->GetType() == NCCodeType)
{
((CNCCode*)object)->SetClickMarkPoint(sub_marked_object, ray_start, ray_direction);
}
}
}
}
void CProgram::WriteXML(TiXmlNode *root)
{
TiXmlElement * element;
element = new TiXmlElement( "Program" );
root->LinkEndChild( element );
element->SetAttribute("machine", Ttc(m_machine.c_str()));
element->SetAttribute("output_file", Ttc(m_output_file.c_str()));
element->SetAttribute("program", Ttc(theApp.m_program_canvas->m_textCtrl->GetValue()));
WriteBaseXML(element);
}
bool CProgram::Add(HeeksObj* object, HeeksObj* prev_object)
{
if(object->GetType() == NCCodeType)m_nc_code = (CNCCode*)object;
if(object->GetType() == OperationsType)m_operations = (COperations*)object;
return ObjList::Add(object, prev_object);
}
void CProgram::Remove(HeeksObj* object)
{
// these shouldn't happen, though
if(object == m_nc_code)m_nc_code = NULL;
else if(object == m_operations)m_operations = NULL;
ObjList::Remove(object);
}
// static member function
HeeksObj* CProgram::ReadFromXMLElement(TiXmlElement* pElem)
{
CProgram* new_object = new CProgram;
// get the attributes
for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())
{
std::string name(a->Name());
if(name == "machine"){new_object->m_machine.assign(Ctt(a->Value()));}
else if(name == "output_file"){new_object->m_output_file.assign(Ctt(a->Value()));}
else if(name == "program"){theApp.m_program_canvas->m_textCtrl->SetValue(Ctt(a->Value()));}
}
new_object->ReadBaseXML(pElem);
theApp.m_program = new_object;
return new_object;
}
void CProgram::RewritePythonProgram()
{
theApp.m_program_canvas->m_textCtrl->Clear();
CZigZag::number_for_stl_file = 1;
bool profile_op_exists = false;
bool pocket_op_exists = false;
bool zigzag_op_exists = false;
for(HeeksObj* object = m_operations->GetFirstChild(); object; object = m_operations->GetNextChild())
{
if(object->GetType() == ProfileType)
{
profile_op_exists = true;
}
else if(object->GetType() == PocketType)
{
pocket_op_exists = true;
}
else if(object->GetType() == ZigZagType)
{
zigzag_op_exists = true;
}
}
// add standard stuff at the top
// kurve related things
if(profile_op_exists)
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import kurve\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import kurve_funcs\n"));
}
// area related things
if(pocket_op_exists)
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import area\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import area_funcs\n"));
}
// pycam stuff
if(zigzag_op_exists)
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import sys\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("sys.path.insert(0,'PyCam/trunk')\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Geometry import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.SphericalCutter import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.CylindricalCutter import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.ToroidalCutter import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Importers.STLImporter import ImportModel\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.PathGenerators.DropCutter import DropCutter\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from PyCamToHeeks import HeeksCNCExporter\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
}
// machine general stuff
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from nc.nc import *\n"));
// specific machine
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import ") + m_machine + _T("\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
// output file
theApp.m_program_canvas->m_textCtrl->AppendText(_T("output('") + m_output_file + _T("')\n"));
// begin program
theApp.m_program_canvas->m_textCtrl->AppendText(_T("program_begin(123, 'Test program')\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("absolute()\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("metric()\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("set_plane(0)\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
// write the operations
for(HeeksObj* object = m_operations->GetFirstChild(); object; object = m_operations->GetNextChild())
{
switch(object->GetType())
{
case ProfileType:
((CProfile*)object)->AppendTextToProgram();
break;
case PocketType:
((CPocket*)object)->AppendTextToProgram();
break;
case ZigZagType:
((CZigZag*)object)->AppendTextToProgram();
break;
}
}
}
ProgramUserType CProgram::GetUserType()
{
if(m_nc_code->m_user_edited)return ProgramUserTypeNC;
if(m_script_edited)return ProgramUserTypeScript;
if(m_operations->GetFirstChild())return ProgramUserTypeTree;
return ProgramUserTypeUnkown;
}
void CProgram::UpdateFromUserType()
{
#if 0
switch(GetUserType())
{
case ProgramUserTypeUnkown:
case tree:
Enable "Operations" icon in tree
editing the tree, recreates the python script
Read only "Program" window
pressing "Post-process" creates the NC code ( and backplots it )
Read only "Output" window
Disable all buttons on "Output" window
}
#endif
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Jolla Ltd.
** Contact: Chris Adams <chris.adams@jollamobile.com>
**
****************************************************************************/
#include "facebooknotificationsyncadaptor.h"
#include "trace.h"
#include <QUrlQuery>
#include <QDebug>
static const int OLD_NOTIFICATION_LIMIT_IN_DAYS = 21;
FacebookNotificationSyncAdaptor::FacebookNotificationSyncAdaptor(QObject *parent)
: FacebookDataTypeSyncAdaptor(SocialNetworkSyncAdaptor::Notifications, parent)
{
setInitialActive(true);
}
FacebookNotificationSyncAdaptor::~FacebookNotificationSyncAdaptor()
{
}
QString FacebookNotificationSyncAdaptor::syncServiceName() const
{
return QStringLiteral("facebook-microblog");
}
void FacebookNotificationSyncAdaptor::purgeDataForOldAccounts(const QList<int> &purgeIds)
{
if (purgeIds.size()) {
foreach (int accountIdentifier, purgeIds) {
m_db.removeNotifications(accountIdentifier);
}
m_db.sync();
m_db.wait();
}
}
void FacebookNotificationSyncAdaptor::beginSync(int accountId, const QString &accessToken)
{
requestNotifications(accountId, accessToken);
}
void FacebookNotificationSyncAdaptor::finalize(int accountId)
{
Q_UNUSED(accountId)
m_db.purgeOldNotifications(OLD_NOTIFICATION_LIMIT_IN_DAYS);
m_db.sync();
m_db.wait();
}
void FacebookNotificationSyncAdaptor::requestNotifications(int accountId, const QString &accessToken, const QString &until, const QString &pagingToken)
{
// TODO: continuation requests need these two. if exists, also set limit = 5000.
// if not set, set "since" to the timestamp value.
Q_UNUSED(until);
Q_UNUSED(pagingToken);
QList<QPair<QString, QString> > queryItems;
queryItems.append(QPair<QString, QString>(QString(QLatin1String("include_read")), QString(QLatin1String("true"))));
queryItems.append(QPair<QString, QString>(QString(QLatin1String("access_token")), accessToken));
queryItems.append(QPair<QString, QString>(QString(QLatin1String("locale")), QLocale::system().name()));
QUrl url(QLatin1String("https://graph.facebook.com/me/notifications"));
QUrlQuery query(url);
query.setQueryItems(queryItems);
url.setQuery(query);
QNetworkReply *reply = networkAccessManager->get(QNetworkRequest(url));
if (reply) {
reply->setProperty("accountId", accountId);
reply->setProperty("accessToken", accessToken);
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(errorHandler(QNetworkReply::NetworkError)));
connect(reply, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslErrorsHandler(QList<QSslError>)));
connect(reply, SIGNAL(finished()), this, SLOT(finishedHandler()));
// we're requesting data. Increment the semaphore so that we know we're still busy.
incrementSemaphore(accountId);
setupReplyTimeout(accountId, reply);
} else {
TRACE(SOCIALD_ERROR,
QString(QLatin1String("error: unable to request notifications from Facebook account with id %1"))
.arg(accountId));
}
}
void FacebookNotificationSyncAdaptor::finishedHandler()
{
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
bool isError = reply->property("isError").toBool();
int accountId = reply->property("accountId").toInt();
QByteArray replyData = reply->readAll();
disconnect(reply);
reply->deleteLater();
removeReplyTimeout(accountId, reply);
bool ok = false;
int sinceSpan = m_accountSyncProfile
? m_accountSyncProfile->key(Buteo::KEY_SYNC_SINCE_DAYS_PAST, QStringLiteral("7")).toInt()
: 7;
QJsonObject parsed = parseJsonObjectReplyData(replyData, &ok);
if (!isError && ok && parsed.contains(QLatin1String("summary"))) {
QJsonArray data = parsed.value(QLatin1String("data")).toArray();
foreach (const QJsonValue &entry, data) {
QJsonObject object = entry.toObject();
QDateTime createdTime = QDateTime::fromString(object.value(QLatin1String("created_time")).toString(), Qt::ISODate);
createdTime.setTimeSpec(Qt::UTC);
QDateTime updatedTime = QDateTime::fromString(object.value(QLatin1String("updated_time")).toString(), Qt::ISODate);
updatedTime.setTimeSpec(Qt::UTC);
if (createdTime.daysTo(QDateTime::currentDateTime()) > sinceSpan
&& updatedTime.daysTo(QDateTime::currentDateTime()) > sinceSpan) {
TRACE(SOCIALD_DEBUG,
QString(QLatin1String("notification for account %1 is more than %2 days old:\n %3 - %4 - %5"))
.arg(accountId)
.arg(sinceSpan)
.arg(createdTime.toString(Qt::ISODate))
.arg(updatedTime.toString(Qt::ISODate))
.arg(object.value(QLatin1String("title")).toString()));
continue;
}
QJsonObject sender = object.value(QLatin1String("from")).toObject();
QJsonObject receiver = object.value(QLatin1String("to")).toObject();
QJsonObject application = object.value(QLatin1String("application")).toObject();
QJsonObject notificationObject = object.value(QLatin1String("object")).toObject();
m_db.addFacebookNotification(object.value(QLatin1String("id")).toString(),
sender.value(QLatin1String("id")).toString(),
receiver.value(QLatin1String("id")).toString(),
createdTime,
updatedTime,
object.value(QLatin1String("title")).toString(),
object.value(QLatin1String("link")).toString(),
application.value(QLatin1String("id")).toString(),
notificationObject.value(QLatin1String("id")).toString(),
object.value(QLatin1String("unread")).toDouble() != 0,
accountId,
clientId());
}
} else {
// error occurred during request.
TRACE(SOCIALD_ERROR,
QString(QLatin1String("error: unable to parse notification data from request with account %1; got: %2"))
.arg(accountId).arg(QString::fromLatin1(replyData.constData())));
}
// we're finished this request. Decrement our busy semaphore.
decrementSemaphore(accountId);
}
<commit_msg>[sociald] Ignore result pagination in FB Notif sync.<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Jolla Ltd.
** Contact: Chris Adams <chris.adams@jollamobile.com>
**
****************************************************************************/
#include "facebooknotificationsyncadaptor.h"
#include "trace.h"
#include <QUrlQuery>
#include <QDebug>
static const int OLD_NOTIFICATION_LIMIT_IN_DAYS = 21;
static const int NOTIFICATIONS_LIMIT = 30;
FacebookNotificationSyncAdaptor::FacebookNotificationSyncAdaptor(QObject *parent)
: FacebookDataTypeSyncAdaptor(SocialNetworkSyncAdaptor::Notifications, parent)
{
setInitialActive(true);
}
FacebookNotificationSyncAdaptor::~FacebookNotificationSyncAdaptor()
{
}
QString FacebookNotificationSyncAdaptor::syncServiceName() const
{
return QStringLiteral("facebook-microblog");
}
void FacebookNotificationSyncAdaptor::purgeDataForOldAccounts(const QList<int> &purgeIds)
{
if (purgeIds.size()) {
foreach (int accountIdentifier, purgeIds) {
m_db.removeNotifications(accountIdentifier);
}
m_db.sync();
m_db.wait();
}
}
void FacebookNotificationSyncAdaptor::beginSync(int accountId, const QString &accessToken)
{
requestNotifications(accountId, accessToken);
}
void FacebookNotificationSyncAdaptor::finalize(int accountId)
{
Q_UNUSED(accountId)
m_db.purgeOldNotifications(OLD_NOTIFICATION_LIMIT_IN_DAYS);
m_db.sync();
m_db.wait();
}
void FacebookNotificationSyncAdaptor::requestNotifications(int accountId, const QString &accessToken, const QString &until, const QString &pagingToken)
{
// continuation requests require until+paging token.
// if not set, set "since" to the timestamp value.
QList<QPair<QString, QString> > queryItems;
queryItems.append(QPair<QString, QString>(QString(QLatin1String("include_read")), QString(QLatin1String("true"))));
queryItems.append(QPair<QString, QString>(QString(QLatin1String("access_token")), accessToken));
queryItems.append(QPair<QString, QString>(QString(QLatin1String("locale")), QLocale::system().name()));
QUrl url(QLatin1String("https://graph.facebook.com/me/notifications"));
if (pagingToken.isEmpty()) {
int sinceSpan = m_accountSyncProfile
? m_accountSyncProfile->key(Buteo::KEY_SYNC_SINCE_DAYS_PAST, QStringLiteral("7")).toInt()
: 7;
queryItems.append(QPair<QString, QString>(QString(QLatin1String("since")),
QString::number(QDateTime::currentDateTime().addDays(-1 * sinceSpan).toTime_t())));
queryItems.append(QPair<QString, QString>(QString(QLatin1String("limit")), QString::number(NOTIFICATIONS_LIMIT)));
} else {
queryItems.append(QPair<QString, QString>(QString(QLatin1String("limit")), QString::number(NOTIFICATIONS_LIMIT)));
queryItems.append(QPair<QString, QString>(QString(QLatin1String("until")), until));
queryItems.append(QPair<QString, QString>(QString(QLatin1String("__paging_token")), pagingToken));
}
QUrlQuery query(url);
query.setQueryItems(queryItems);
url.setQuery(query);
QNetworkReply *reply = networkAccessManager->get(QNetworkRequest(url));
if (reply) {
reply->setProperty("accountId", accountId);
reply->setProperty("accessToken", accessToken);
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(errorHandler(QNetworkReply::NetworkError)));
connect(reply, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslErrorsHandler(QList<QSslError>)));
connect(reply, SIGNAL(finished()), this, SLOT(finishedHandler()));
// we're requesting data. Increment the semaphore so that we know we're still busy.
incrementSemaphore(accountId);
setupReplyTimeout(accountId, reply);
} else {
TRACE(SOCIALD_ERROR,
QString(QLatin1String("error: unable to request notifications from Facebook account with id %1"))
.arg(accountId));
}
}
void FacebookNotificationSyncAdaptor::finishedHandler()
{
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
bool isError = reply->property("isError").toBool();
int accountId = reply->property("accountId").toInt();
QString accessToken = reply->property("accessToken").toString();
QByteArray replyData = reply->readAll();
disconnect(reply);
reply->deleteLater();
removeReplyTimeout(accountId, reply);
bool ok = false;
int sinceSpan = m_accountSyncProfile
? m_accountSyncProfile->key(Buteo::KEY_SYNC_SINCE_DAYS_PAST, QStringLiteral("7")).toInt()
: 7;
QJsonObject parsed = parseJsonObjectReplyData(replyData, &ok);
if (!isError && ok && parsed.contains(QLatin1String("summary"))) {
QJsonArray data = parsed.value(QLatin1String("data")).toArray();
bool needNextPage = false;
bool seenOldNotification = false;
foreach (const QJsonValue &entry, data) {
QJsonObject object = entry.toObject();
QDateTime createdTime = QDateTime::fromString(object.value(QLatin1String("created_time")).toString(), Qt::ISODate);
createdTime.setTimeSpec(Qt::UTC);
QDateTime updatedTime = QDateTime::fromString(object.value(QLatin1String("updated_time")).toString(), Qt::ISODate);
updatedTime.setTimeSpec(Qt::UTC);
if (createdTime.daysTo(QDateTime::currentDateTime()) > sinceSpan
&& updatedTime.daysTo(QDateTime::currentDateTime()) > sinceSpan) {
TRACE(SOCIALD_DEBUG,
QString(QLatin1String("notification for account %1 is more than %2 days old:\n %3 - %4 - %5"))
.arg(accountId)
.arg(sinceSpan)
.arg(createdTime.toString(Qt::ISODate))
.arg(updatedTime.toString(Qt::ISODate))
.arg(object.value(QLatin1String("title")).toString()));
seenOldNotification = true;
needNextPage = false;
continue;
}
QJsonObject sender = object.value(QLatin1String("from")).toObject();
QJsonObject receiver = object.value(QLatin1String("to")).toObject();
QJsonObject application = object.value(QLatin1String("application")).toObject();
QJsonObject notificationObject = object.value(QLatin1String("object")).toObject();
m_db.addFacebookNotification(object.value(QLatin1String("id")).toString(),
sender.value(QLatin1String("id")).toString(),
receiver.value(QLatin1String("id")).toString(),
createdTime,
updatedTime,
object.value(QLatin1String("title")).toString(),
object.value(QLatin1String("link")).toString(),
application.value(QLatin1String("id")).toString(),
notificationObject.value(QLatin1String("id")).toString(),
object.value(QLatin1String("unread")).toDouble() != 0,
accountId,
clientId());
if (!seenOldNotification) {
needNextPage = true;
}
}
if (needNextPage && parsed.contains(QLatin1String("paging"))) {
// we don't actually request the next page of results
// since the sync schedule has such a small interval,
// 30 notifications at a time should be plenty,
// and we want to avoid performing spurious network activity.
Q_UNUSED(accessToken)
/*
QString nextPage = parsed.value(QLatin1String("paging")).toObject().value(QLatin1String("next")).toString();
QUrl nextPageUrl(nextPage);
// instead of doing this, we could just pass the nextPageUrl directly to the requestNotifications function
QUrlQuery npuQuery(nextPageUrl.query());
QString until = npuQuery.queryItemValue(QStringLiteral("until"));
QString pagingToken = npuQuery.queryItemValue(QStringLiteral("__paging_token"));
if (!nextPage.isEmpty() && !until.isEmpty() && !pagingToken.isEmpty()) {
TRACE(SOCIALD_DEBUG,
QString(QLatin1String("another page of notifications exists for account %1: %2"))
.arg(accountId).arg(nextPage));
requestNotifications(accountId, accessToken, until, pagingToken);
}
*/
}
} else {
// error occurred during request.
TRACE(SOCIALD_ERROR,
QString(QLatin1String("error: unable to parse notification data from request with account %1; got: %2"))
.arg(accountId).arg(QString::fromLatin1(replyData.constData())));
}
// we're finished this request. Decrement our busy semaphore.
decrementSemaphore(accountId);
}
<|endoftext|>
|
<commit_before>#ifndef SAPLIST_HPP
#define SAPLIST_HPP 1
#include <functional>
#include <map>
#include <typeinfo>
#include <climits>
#include <iostream>
#include "CollisionManager.hpp"
class ActionManager;
class Collisionable;
class SAPList;
class Collisionable {
protected:
/* (void *) because AABB type is hidden */
void * boundingBox;
public:
/**
* @return a pointer to Collisionable's bouding box (it needs cast).
*/
void * getBoundingBox() { return boundingBox; }
/**
* Change the boundingBox of a Collisionable
* @param b new bounding box
*/
void setBoundingBox(void * b) { boundingBox = b; }
/** @return the smallest value of a Collisionable on X axis */
virtual int getXMin() = 0;
/** @return the smallest value of a Collisionable on Y axis */
virtual int getYMin() = 0;
/** @return the greatest value of a Collisionable on X axis */
virtual int getXMax() = 0;
/** @return the greatest value of a Collisionable on Y axis */
virtual int getYMax() = 0;
virtual ~Collisionable() {};
};
class ActionManager {
public:
/**
* Function to call on collision
* @param o1 first object which collide
* @param o2 second object which collide
*/
virtual void onCollision(Collisionable * o1, Collisionable * o2) = 0;
/**
* @param o1 first object which do not collide
* @param o2 second object which do not collide
*/
virtual void onSeparation(Collisionable * o1, Collisionable * o2) = 0;
virtual ~ActionManager() {};
};
class SAPList : virtual public CollisionManager<Collisionable> {
private:
/* BEGIN: private classes for SAPList collision manager */
class AABB;
class EndPoint {
/**
* TODO:
* - Optimize merging isMin boolean into another member
* (as a flag)
* - Using doubly-linked list could waste memory but is easier to
* implement than arrays.
*/
public:
AABB * owner;
/** Value used to sort EndPoint list */
int value;
/** Flag to indicate if this EndPoint is minimum of a AABB or not */
bool isMin;
/** Previous EndPoint in the list */
EndPoint * prev;
/** Next EndPoint in the list */
EndPoint * next;
EndPoint (AABB* o,int v,bool m,EndPoint* p=NULL,EndPoint* n=NULL) :
owner(o), value(v), isMin(m), prev(p), next(n) {}
/** When and EndPoint is destroyed, it updates prev and next */
~EndPoint () {
if (this->prev != NULL) {
this->prev->next = this->next;
}
if (this->next != NULL)
this->next->prev = this->prev;
}
};
class AABB {
public:
/** First minimum EndPoint is on x axis, second one is on y */
EndPoint * min[2];
/** Second minimum EndPoint is on x axis, second one is on y */
EndPoint * max[2];
/** Object the box is attached to */
Collisionable * owner;
/**
* Create the AABB corresponding to a collisionable object
* @param c the object used to create the corresponding AABB
*/
AABB(Collisionable * c) : owner(c) {
min[0] = new EndPoint(this, c->getXMin(), true);
min[1] = new EndPoint(this, c->getYMin(), true);
max[0] = new EndPoint(this, c->getXMax(), false);
max[1] = new EndPoint(this, c->getYMax(), false);
c->setBoundingBox(this);
}
~AABB ()
{ delete min[0]; delete min[1]; delete max[0]; delete max[1]; }
/**
* Update EndPoints values according to information provided by
* owner and Collisionable API
*/
void updateEPValues() {
min[0]->value = owner->getXMin();
min[1]->value = owner->getYMin();
max[0]->value = owner->getXMax();
max[1]->value = owner->getYMax();
}
};
/* END: private classes for SAPList collision manager */
private:
/** First EndPoint on xAxis (not a real point, but a sentinel)*/
EndPoint * xAxis;
/** Second EndPoint on xAxis (not a real point, but a sentinel)*/
EndPoint * yAxis;
/** Action manager used on collision/separation */
ActionManager * actionManager;
/** Swap two EndPoint.
* **p2 has to be the direct next EndPoint after p1**
* @param p1 first EndPoint
* @param p2 second EndPoint
*/
void swap(EndPoint * p1, EndPoint * p2) {
if (p2->next != NULL) p2->next->prev = p1;
if (p1->prev != NULL) p1->prev->next = p2;
p1->next = p2->next;
p2->next = p1;
p2->prev = p1->prev;
p1->prev = p2;
}
/**
* A collision between two AABB on one axis
* no collision on equality (>/<)
*/
inline bool partialCollisionCheck(const AABB & a,
const AABB & b,
int dim) {
return !(a.min[dim]->value > b.max[dim]->value
|| a.max[dim]->value < b.min[dim]->value);
}
/**
* Check if two AABB collide using 2 axises
* @see partialCollisionCheck
*/
bool collisionCheck(const AABB & b1, const AABB & b2) {
return partialCollisionCheck (b1, b2, 0)
&& partialCollisionCheck (b1, b2, 1);
}
/** Update EndPoint place and call the appropriate function in case
* of collision/separation. Does not affect the EndPoint.value, which must
* be updated before calling updateEndPoint.
* @param pt the EndPoint to update
*/
void updateAxis(EndPoint * min, EndPoint * max) {
auto update =
[this]
(EndPoint * pt,
std::function<EndPoint*(EndPoint*)>succ,
std::function<bool(EndPoint*pt,EndPoint*succ)>loop_cond,
std::function<void(EndPoint*pt,EndPoint*succ)>swap_fun,
std::function<bool(EndPoint*pt,EndPoint*succ)>doCollide,
std::function<bool(EndPoint*pt,EndPoint*succ)>doSeparate) {
EndPoint * tmp = succ(pt);
if (!loop_cond(pt, tmp))
{ return false; }
do {
swap_fun(pt, tmp);
if (doCollide(pt, tmp)) {
if (this->collisionCheck(*(pt->owner), *(tmp->owner))) {
this->actionManager->onCollision(pt->owner->owner,
tmp->owner->owner);
}
} else if (doSeparate(pt, tmp)) {
this->actionManager->onSeparation(pt->owner->owner,
tmp->owner->owner);
}
tmp = succ(pt);
} while (loop_cond(pt, tmp));
return true;
};
/* No collision detected on equality (<=/>=). */
auto prev = [](EndPoint *p)
{ return p->prev;};
auto prev_cond = [](EndPoint * pt, EndPoint * succ)
{ return pt->value < succ->value; };
auto prev_swap = [this](EndPoint * pt, EndPoint * succ)
{ swap(succ, pt); };
auto prev_col = [](EndPoint *pt, EndPoint *succ)
{ return pt->isMin && !succ->isMin; };
auto prev_sep = [](EndPoint *pt, EndPoint *succ)
{ return !pt->isMin && succ->isMin; };
auto next = [](EndPoint *p)
{ return p->next; };
auto next_cond = [](EndPoint * pt, EndPoint * succ)
{ return pt->value > succ->value; };
auto next_swap = [this](EndPoint * pt, EndPoint * succ)
{ swap(pt, succ); };
auto next_col = [](EndPoint *pt, EndPoint *succ)
{ return !pt->isMin && succ->isMin; };
auto next_sep = [](EndPoint *pt, EndPoint *succ)
{ return pt->isMin && !succ->isMin; };
/* BINOR force update and allow to use a boolean test */
if(!(update(max, next, next_cond, next_swap, next_col, next_sep) |
update(min, next, next_cond, next_swap, next_col, next_sep))) {
update(min, prev, prev_cond, prev_swap, prev_col, prev_sep);
update(max, prev, prev_cond, prev_swap, prev_col, prev_sep);
}
}
public:
SAPList (ActionManager * am) {
this->actionManager = am;
/* not sure about the true/false values */
xAxis = new EndPoint(NULL, INT_MIN, true, NULL, NULL);
xAxis->next = new EndPoint(NULL, INT_MAX, false, xAxis, NULL);
yAxis = new EndPoint(NULL, INT_MIN, true, NULL, NULL);
yAxis->next = new EndPoint(NULL, INT_MAX, false, yAxis, NULL);
}
~SAPList () {
/* delete all AABB will delete EndPoints */
while (xAxis->next != NULL && xAxis->next->owner != NULL) {
delete xAxis->next->owner;
}
/* delete all sentinels */
delete xAxis->next;
delete xAxis;
delete yAxis->next;
delete yAxis;
}
/**
* Create a bounding box attached to a Collisionable and insert its
* points in xAxis and yAxis (keep it sorted)
* @param c Object (Collisionable) attached to the new bounding box
* to insert in the list
*/
void addObject(Collisionable * c) {
AABB * aabb = new AABB(c);
aabb->min[0]->next = aabb->max[0];
aabb->max[0]->prev = aabb->min[0];
aabb->min[0]->prev = xAxis;
aabb->max[0]->next = xAxis->next;
xAxis->next->prev = aabb->max[0];
xAxis->next = aabb->min[0];
aabb->min[1]->next = aabb->max[1];
aabb->max[1]->prev = aabb->min[1];
aabb->min[1]->prev = yAxis;
aabb->max[1]->next = yAxis->next;
yAxis->next->prev = aabb->max[1];
yAxis->next = aabb->min[1];
updateObject(c);
}
/**
* Update Collisionable's EndPoints position in CollisionManger. Detect
* collisions and separation and act according to actionManager. Should
* be called as soon as an object moves.
* @param c Object to update
*/
void updateObject(Collisionable * c) {
AABB * aabb = static_cast<AABB *>(c->getBoundingBox());
updateAxis(aabb->min[0], aabb->max[0]);
updateAxis(aabb->min[1], aabb->max[1]);
}
void removeObject(Collisionable * c) {
delete static_cast<AABB *>(c->getBoundingBox());
}
};
#endif
<commit_msg>AABB's owner **SHOULD** be set to NULL when AABB is destroyed. doc++<commit_after>#ifndef SAPLIST_HPP
#define SAPLIST_HPP 1
#include <functional>
#include <map>
#include <typeinfo>
#include <climits>
#include <iostream>
#include "CollisionManager.hpp"
class ActionManager;
class Collisionable;
class SAPList;
class Collisionable {
protected:
/* (void *) because AABB type is hidden */
void * boundingBox;
public:
/**
* @return a pointer to Collisionable's bouding box (it needs cast).
*/
void * getBoundingBox() { return boundingBox; }
/**
* Change the boundingBox of a Collisionable
* @param b new bounding box
*/
void setBoundingBox(void * b) { boundingBox = b; }
/** @return the smallest value of a Collisionable on X axis */
virtual int getXMin() = 0;
/** @return the smallest value of a Collisionable on Y axis */
virtual int getYMin() = 0;
/** @return the greatest value of a Collisionable on X axis */
virtual int getXMax() = 0;
/** @return the greatest value of a Collisionable on Y axis */
virtual int getYMax() = 0;
virtual ~Collisionable() {};
};
class ActionManager {
public:
/**
* Function to call on collision
* @param o1 first object which collide
* @param o2 second object which collide
*/
virtual void onCollision(Collisionable * o1, Collisionable * o2) = 0;
/**
* @param o1 first object which do not collide
* @param o2 second object which do not collide
*/
virtual void onSeparation(Collisionable * o1, Collisionable * o2) = 0;
virtual ~ActionManager() {};
};
class SAPList : virtual public CollisionManager<Collisionable> {
private:
/* BEGIN: private classes for SAPList collision manager */
class AABB;
class EndPoint {
/**
* TODO:
* - Optimize merging isMin boolean into another member
* (as a flag)
* - Using doubly-linked list could waste memory but is easier to
* implement than arrays.
*/
public:
AABB * owner;
/** Value used to sort EndPoint list */
int value;
/** Flag to indicate if this EndPoint is minimum of a AABB or not */
bool isMin;
/** Previous EndPoint in the list */
EndPoint * prev;
/** Next EndPoint in the list */
EndPoint * next;
EndPoint (AABB* o,int v,bool m,EndPoint* p=NULL,EndPoint* n=NULL) :
owner(o), value(v), isMin(m), prev(p), next(n) {}
/** When and EndPoint is destroyed, it updates prev and next */
~EndPoint () {
if (this->prev != NULL) {
this->prev->next = this->next;
}
if (this->next != NULL) {
this->next->prev = this->prev;
}
}
};
class AABB {
public:
/** First minimum EndPoint is on x axis, second one is on y */
EndPoint * min[2];
/** Second minimum EndPoint is on x axis, second one is on y */
EndPoint * max[2];
/** Object the box is attached to */
Collisionable * owner;
/**
* Create the AABB corresponding to a collisionable object
* @param c the object used to create the corresponding AABB
*/
AABB(Collisionable * c) : owner(c) {
min[0] = new EndPoint(this, c->getXMin(), true);
min[1] = new EndPoint(this, c->getYMin(), true);
max[0] = new EndPoint(this, c->getXMax(), false);
max[1] = new EndPoint(this, c->getYMax(), false);
c->setBoundingBox(this);
}
/**
* When a AABB is destroyed, its owner bounding box is set to NULL
*/
~AABB () {
delete min[0];
delete min[1];
delete max[0];
delete max[1];
if (owner) {
// owner->setBoundingBox(NULL); <- segfault in unit tests.
}
}
/**
* Update EndPoints values according to information provided by
* owner and Collisionable API
*/
void updateEPValues() {
min[0]->value = owner->getXMin();
min[1]->value = owner->getYMin();
max[0]->value = owner->getXMax();
max[1]->value = owner->getYMax();
}
};
/* END: private classes for SAPList collision manager */
private:
/** First EndPoint on xAxis (not a real point, but a sentinel)*/
EndPoint * xAxis;
/** Second EndPoint on xAxis (not a real point, but a sentinel)*/
EndPoint * yAxis;
/** Action manager used on collision/separation */
ActionManager * actionManager;
/** Swap two EndPoint.
* **p2 has to be the direct next EndPoint after p1**
* @param p1 first EndPoint
* @param p2 second EndPoint
*/
void swap(EndPoint * p1, EndPoint * p2) {
if (p2->next != NULL) p2->next->prev = p1;
if (p1->prev != NULL) p1->prev->next = p2;
p1->next = p2->next;
p2->next = p1;
p2->prev = p1->prev;
p1->prev = p2;
}
/**
* A collision between two AABB on one axis
* no collision on equality (>/<)
*/
inline bool partialCollisionCheck(const AABB & a,
const AABB & b,
int dim) {
return !(a.min[dim]->value > b.max[dim]->value
|| a.max[dim]->value < b.min[dim]->value);
}
/**
* Check if two AABB collide using 2 axises
* @see partialCollisionCheck
*/
bool collisionCheck(const AABB & b1, const AABB & b2) {
return partialCollisionCheck (b1, b2, 0)
&& partialCollisionCheck (b1, b2, 1);
}
/** Update EndPoint place and call the appropriate function in case
* of collision/separation. Does not affect the EndPoint.value, which must
* be updated before calling updateEndPoint.
* @param pt the EndPoint to update
*/
void updateAxis(EndPoint * min, EndPoint * max) {
auto update =
[this]
(EndPoint * pt,
std::function<EndPoint*(EndPoint*)>succ,
std::function<bool(EndPoint*pt,EndPoint*succ)>loop_cond,
std::function<void(EndPoint*pt,EndPoint*succ)>swap_fun,
std::function<bool(EndPoint*pt,EndPoint*succ)>doCollide,
std::function<bool(EndPoint*pt,EndPoint*succ)>doSeparate) {
EndPoint * tmp = succ(pt);
if (!loop_cond(pt, tmp))
{ return false; }
do {
swap_fun(pt, tmp);
if (doCollide(pt, tmp)) {
if (this->collisionCheck(*(pt->owner), *(tmp->owner))) {
this->actionManager->onCollision(pt->owner->owner,
tmp->owner->owner);
}
} else if (doSeparate(pt, tmp)) {
this->actionManager->onSeparation(pt->owner->owner,
tmp->owner->owner);
}
tmp = succ(pt);
} while (loop_cond(pt, tmp));
return true;
};
/* No collision detected on equality (<=/>=). */
auto prev = [](EndPoint *p)
{ return p->prev;};
auto prev_cond = [](EndPoint * pt, EndPoint * succ)
{ return pt->value < succ->value; };
auto prev_swap = [this](EndPoint * pt, EndPoint * succ)
{ swap(succ, pt); };
auto prev_col = [](EndPoint *pt, EndPoint *succ)
{ return pt->isMin && !succ->isMin; };
auto prev_sep = [](EndPoint *pt, EndPoint *succ)
{ return !pt->isMin && succ->isMin; };
auto next = [](EndPoint *p)
{ return p->next; };
auto next_cond = [](EndPoint * pt, EndPoint * succ)
{ return pt->value > succ->value; };
auto next_swap = [this](EndPoint * pt, EndPoint * succ)
{ swap(pt, succ); };
auto next_col = [](EndPoint *pt, EndPoint *succ)
{ return !pt->isMin && succ->isMin; };
auto next_sep = [](EndPoint *pt, EndPoint *succ)
{ return pt->isMin && !succ->isMin; };
/* BINOR force update and allow to use a boolean test */
if(!(update(max, next, next_cond, next_swap, next_col, next_sep) |
update(min, next, next_cond, next_swap, next_col, next_sep))) {
update(min, prev, prev_cond, prev_swap, prev_col, prev_sep);
update(max, prev, prev_cond, prev_swap, prev_col, prev_sep);
}
}
public:
SAPList (ActionManager * am) {
this->actionManager = am;
/* not sure about the true/false values */
xAxis = new EndPoint(NULL, INT_MIN, true, NULL, NULL);
xAxis->next = new EndPoint(NULL, INT_MAX, false, xAxis, NULL);
yAxis = new EndPoint(NULL, INT_MIN, true, NULL, NULL);
yAxis->next = new EndPoint(NULL, INT_MAX, false, yAxis, NULL);
}
~SAPList () {
/* delete all AABB will delete EndPoints */
while (xAxis->next != NULL && xAxis->next->owner != NULL) {
delete xAxis->next->owner;
}
/* delete all sentinels */
delete xAxis->next;
delete xAxis;
delete yAxis->next;
delete yAxis;
}
/**
* Create a bounding box attached to a Collisionable and insert its
* points in xAxis and yAxis (keep it sorted)
* @param c Object (Collisionable) attached to the new bounding box
* to insert in the list
*/
void addObject(Collisionable * c) {
AABB * aabb = new AABB(c);
aabb->min[0]->next = aabb->max[0];
aabb->max[0]->prev = aabb->min[0];
aabb->min[0]->prev = xAxis;
aabb->max[0]->next = xAxis->next;
xAxis->next->prev = aabb->max[0];
xAxis->next = aabb->min[0];
aabb->min[1]->next = aabb->max[1];
aabb->max[1]->prev = aabb->min[1];
aabb->min[1]->prev = yAxis;
aabb->max[1]->next = yAxis->next;
yAxis->next->prev = aabb->max[1];
yAxis->next = aabb->min[1];
updateObject(c);
}
/**
* Update Collisionable's EndPoints position in CollisionManger. Detect
* collisions and separation and act according to actionManager. Should
* be called as soon as an object moves.
* @param c Object to update
*/
void updateObject(Collisionable * c) {
AABB * aabb = static_cast<AABB *>(c->getBoundingBox());
updateAxis(aabb->min[0], aabb->max[0]);
updateAxis(aabb->min[1], aabb->max[1]);
}
/**
* Remove a bounding box attached to a Collisionable
* @param c Object attached to the bounding box to remove
*/
void removeObject(Collisionable * c) {
delete static_cast<AABB *>(c->getBoundingBox());
}
};
#endif
<|endoftext|>
|
<commit_before>#pragma ident "$Id$"
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// any later version.
//
// The GPSTk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
/**
* @file SP3Data.cpp
* Encapsulate SP3 file data, including I/O
*/
#include "SP3Stream.hpp"
#include "SP3Header.hpp"
#include "SP3Data.hpp"
#include "StringUtils.hpp"
#include "DayTime.hpp"
using namespace gpstk::StringUtils;
using namespace std;
namespace gpstk
{
void SP3Data::reallyPutRecord(FFStream& ffs) const
throw(std::exception, FFStreamError, StringException)
{
SP3Stream& strm = dynamic_cast<SP3Stream&>(ffs);
string line;
if(flag == '*') {// output Epoch Header Record
line = "* ";
line += time.printf(" %4Y %2m %2d %2H %2M");
line += " " + rightJustify(time.printf("%.8f"),11);
}
else { // output Position and Clock OR Velocity and Clock Rate Record
line = flag;
if(version == 'c')
line += SP3SatID(sat).toString();
else
line += rightJustify(asString(sat.id),3);
line += rightJustify(asString(x[0],6),14);
line += rightJustify(asString(x[1],6),14);
line += rightJustify(asString(x[2],6),14);
line += rightJustify(asString(clk,6),14);
if(version == 'c') {
line += rightJustify(asString(sig[0]),3);
line += rightJustify(asString(sig[1]),3);
line += rightJustify(asString(sig[2]),3);
line += rightJustify(asString(sig[3]),4);
if(flag == 'P') {
line += string(" ");
line += (clockEventFlag ? string("E") : string(" "));
line += (clockPredFlag ? string("P") : string(" "));
line += string(" ");
line += (orbitManeuverFlag ? string("M") : string(" "));
line += (orbitPredFlag ? string("P") : string(" "));
}
//else {
// line += string(" ");
//}
}
// if version is 'c' and correlation flag is set,
// output P|V Correlation Record
if(version == 'c' && correlationFlag) {
// first output the P|V record
strm << line << endl;
// now output the correlation record
if(flag == 'P') line = "EP ";
else line = "EV ";
line += rightJustify(asString(sdev[0]),5);
line += rightJustify(asString(sdev[1]),5);
line += rightJustify(asString(sdev[2]),5);
line += rightJustify(asString(sdev[3]),8);
for(int i=0; i<6; i++)
line += rightJustify(asString(correlation[i]),9);
}
}
// write the line
strm << line << endl;
}
void SP3Data::dump(ostream& s) const
{
s << flag << " " << sat
<< " " << time.printf("%Y/%02m/%02d %2H:%02M:%06.3f = %F/%10.3g");
if(flag != '*') {
s << fixed << setprecision(6)
<< " X=" << setw(14) << x[0]
<< " Y=" << setw(14) << x[1]
<< " Z=" << setw(14) << x[2]
<< " C=" << setw(14) << clk;
if(version == 'c') {
s << " sX=" << setw(2) << sig[0]
<< " sY=" << setw(2) << sig[1]
<< " sZ=" << setw(2) << sig[2]
<< " sC=" << setw(3) << sig[3];
if(flag == 'P')
s << " " << (clockEventFlag ? "clockEvent" : "-")
<< " " << (clockPredFlag ? "clockPrediction" : "-")
<< " " << (orbitManeuverFlag ? "orbitManeuver" : "-")
<< " " << (orbitPredFlag ? "orbitPrediction" : "-");
if(correlationFlag)
s << endl
<< 'E' << flag
<< " cXX=" << setw(4) << sdev[0]
<< " cYY=" << setw(4) << sdev[1]
<< " cZZ=" << setw(4) << sdev[2]
<< " cCC=" << setw(7) << sdev[3]
<< " cXY=" << setw(8) << correlation[0]
<< " cXZ=" << setw(8) << correlation[1]
<< " cXC=" << setw(8) << correlation[2]
<< " cYZ=" << setw(8) << correlation[3]
<< " cYC=" << setw(8) << correlation[4]
<< " cZC=" << setw(8) << correlation[5];
}
}
s << endl;
};
void SP3Data::reallyGetRecord(FFStream& ffs)
throw(std::exception, FFStreamError, StringException)
{
SP3Stream& strm = dynamic_cast<SP3Stream&>(ffs);
correlationFlag = false;
int status = 0; // initial status = 0
while(1) {
// set the time in the record
time = strm.currentEpoch;
// ---------------------------------------------------------
// process the buffer containing the last line read
if(strm.buffer.size() < 3) {
// nothing in buffer - do nothing here, get another line
;
}
else if(strm.buffer.substr(0,3) == string("EOF")) { // 'EOF' record
// if a data record has been processed during this call, then
// return and let the next call process this EOF.
//if(status == 1) throw - found EOF right after an epoch record
if(status > 1) break;
// this next read had better fail - if it does, an exception will
// be thrown, and the FFStreamError created next won't get thrown
strm.formattedGetLine(strm.buffer, true);
FFStreamError err("EOF text found but file didn't end");
GPSTK_THROW(err);
}
else if(strm.buffer[0] == '*') { // Epoch record
// if another record has been process during this call, quit now
if(status > 0) break;
status = 1; // epoch status = 1
// throw if the line is short
if(strm.buffer.size() <= 30) {
FFStreamError err("Invalid line length "+asString(strm.buffer.size()));
GPSTK_THROW(err);
}
// parse the epoch line
int year = asInt(strm.buffer.substr(3,4));
int month = asInt(strm.buffer.substr(8,2));
int dom = asInt(strm.buffer.substr(11,2));
int hour = asInt(strm.buffer.substr(14,2));
int minute = asInt(strm.buffer.substr(17,2));
double second = asInt(strm.buffer.substr(20,10));
DayTime t(year, month, dom, hour, minute, second);
time = strm.currentEpoch = t;
}
else if(strm.buffer[0] == 'P' || strm.buffer[0] == 'V') {// P|V record
// if nothing, or epoch record, was processed during this call,
// process this P|V, otherwise (P|V or EP|V were processed), quit now
if(status > 1) break;
status = 2; // P|V status = 2
flag = strm.buffer[0]; // P or V
// throw if the line is short
if ((version == 'a' && strm.buffer.size() < 60) ||
(version == 'c' && strm.buffer.size() < 73) ) {
FFStreamError err("Invalid line length "+asString(strm.buffer.size()));
GPSTK_THROW(err);
}
// parse the line
if(version == 'a')
sat = SatID(asInt(strm.buffer.substr(1, 3)), SP3SatID::systemGPS);
else
sat = SP3SatID(strm.buffer.substr(1,3));
x[0] = asDouble(strm.buffer.substr(5,14));
x[1] = asDouble(strm.buffer.substr(19,14));
x[2] = asDouble(strm.buffer.substr(33,14));
clk = asDouble(strm.buffer.substr(47,14));
if(version == 'c') {
// get sigmas from P|V record
sig[0] = asInt(strm.buffer.substr(61,2));
sig[1] = asInt(strm.buffer.substr(64,2));
sig[2] = asInt(strm.buffer.substr(67,2));
sig[3] = asInt(strm.buffer.substr(70,3));
// get flags
if(flag == 'P') {
clockEventFlag = clockPredFlag
= orbitManeuverFlag = orbitPredFlag = false;
if(strm.buffer.size() >= 75 && strm.buffer[74] == 'E')
clockEventFlag = true;
if(strm.buffer.size() >= 76 && strm.buffer[75] == 'P')
clockPredFlag = true;
if(strm.buffer.size() >= 79 && strm.buffer[78] == 'M')
orbitManeuverFlag = true;
if(strm.buffer.size() >= 80 && strm.buffer[79] == 'P')
orbitPredFlag = true;
}
}
}
else if(strm.buffer[0] == 'E' && // EP|EV record
(strm.buffer[1] == 'P' || strm.buffer[1] == 'V')) {
// always process an EP|V immediately, since it must follow P|V
status = 3; // EP|V status = 3
// throw if correlation record did not follow corresponding P|V record
if(strm.buffer[1] != flag) {
Exception e("SP3c correlation record mismatched with previous P|V");
GPSTK_THROW(e);
}
// throw if line is short
if(strm.buffer.size()<80) {
FFStreamError err("Invalid SP3c correlation line length "
+ asString(strm.buffer.size()));
GPSTK_THROW(err);
}
sdev[0] = abs(asInt(strm.buffer.substr(4,4)));
sdev[1] = abs(asInt(strm.buffer.substr(9,4)));
sdev[2] = abs(asInt(strm.buffer.substr(14,4)));
sdev[3] = abs(asInt(strm.buffer.substr(19,7)));
correlation[0] = asInt(strm.buffer.substr(27,8));
correlation[1] = asInt(strm.buffer.substr(36,8));
correlation[2] = asInt(strm.buffer.substr(45,8));
correlation[3] = asInt(strm.buffer.substr(54,8));
correlation[4] = asInt(strm.buffer.substr(63,8));
correlation[5] = asInt(strm.buffer.substr(72,8));
// tell the caller that correlation data is now present
correlationFlag = true;
}
else { // Unknown record
FFStreamError err("Unknown line label " + strm.buffer.substr(0,2));
GPSTK_THROW(err);
}
// ---------------------------------------------------------
// read next line into the buffer
strm.formattedGetLine(strm.buffer);
// ---------------------------------------------------------
// quit if EP|EV was processed
if(status == 3) break;
// go back if buffer was empty (0)
// go back if epoch was processed (1)
// go back if P|V was processed (2)
}
} // end reallyGetRecord()
} // namespace
<commit_msg>Bug fix in reallyGetRecord, thanks Dagoberto<commit_after>#pragma ident "$Id$"
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// any later version.
//
// The GPSTk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
/**
* @file SP3Data.cpp
* Encapsulate SP3 file data, including I/O
*/
#include "SP3Stream.hpp"
#include "SP3Header.hpp"
#include "SP3Data.hpp"
#include "StringUtils.hpp"
#include "DayTime.hpp"
using namespace gpstk::StringUtils;
using namespace std;
namespace gpstk
{
void SP3Data::reallyPutRecord(FFStream& ffs) const
throw(std::exception, FFStreamError, StringException)
{
SP3Stream& strm = dynamic_cast<SP3Stream&>(ffs);
string line;
if(flag == '*') {// output Epoch Header Record
line = "* ";
line += time.printf(" %4Y %2m %2d %2H %2M");
line += " " + rightJustify(time.printf("%.8f"),11);
}
else { // output Position and Clock OR Velocity and Clock Rate Record
line = flag;
if(version == 'c')
line += SP3SatID(sat).toString();
else
line += rightJustify(asString(sat.id),3);
line += rightJustify(asString(x[0],6),14);
line += rightJustify(asString(x[1],6),14);
line += rightJustify(asString(x[2],6),14);
line += rightJustify(asString(clk,6),14);
if(version == 'c') {
line += rightJustify(asString(sig[0]),3);
line += rightJustify(asString(sig[1]),3);
line += rightJustify(asString(sig[2]),3);
line += rightJustify(asString(sig[3]),4);
if(flag == 'P') {
line += string(" ");
line += (clockEventFlag ? string("E") : string(" "));
line += (clockPredFlag ? string("P") : string(" "));
line += string(" ");
line += (orbitManeuverFlag ? string("M") : string(" "));
line += (orbitPredFlag ? string("P") : string(" "));
}
//else {
// line += string(" ");
//}
}
// if version is 'c' and correlation flag is set,
// output P|V Correlation Record
if(version == 'c' && correlationFlag) {
// first output the P|V record
strm << line << endl;
// now output the correlation record
if(flag == 'P') line = "EP ";
else line = "EV ";
line += rightJustify(asString(sdev[0]),5);
line += rightJustify(asString(sdev[1]),5);
line += rightJustify(asString(sdev[2]),5);
line += rightJustify(asString(sdev[3]),8);
for(int i=0; i<6; i++)
line += rightJustify(asString(correlation[i]),9);
}
}
// write the line
strm << line << endl;
}
void SP3Data::dump(ostream& s) const
{
s << flag << " " << sat
<< " " << time.printf("%Y/%02m/%02d %2H:%02M:%06.3f = %F/%10.3g");
if(flag != '*') {
s << fixed << setprecision(6)
<< " X=" << setw(14) << x[0]
<< " Y=" << setw(14) << x[1]
<< " Z=" << setw(14) << x[2]
<< " C=" << setw(14) << clk;
if(version == 'c') {
s << " sX=" << setw(2) << sig[0]
<< " sY=" << setw(2) << sig[1]
<< " sZ=" << setw(2) << sig[2]
<< " sC=" << setw(3) << sig[3];
if(flag == 'P')
s << " " << (clockEventFlag ? "clockEvent" : "-")
<< " " << (clockPredFlag ? "clockPrediction" : "-")
<< " " << (orbitManeuverFlag ? "orbitManeuver" : "-")
<< " " << (orbitPredFlag ? "orbitPrediction" : "-");
if(correlationFlag)
s << endl
<< 'E' << flag
<< " cXX=" << setw(4) << sdev[0]
<< " cYY=" << setw(4) << sdev[1]
<< " cZZ=" << setw(4) << sdev[2]
<< " cCC=" << setw(7) << sdev[3]
<< " cXY=" << setw(8) << correlation[0]
<< " cXZ=" << setw(8) << correlation[1]
<< " cXC=" << setw(8) << correlation[2]
<< " cYZ=" << setw(8) << correlation[3]
<< " cYC=" << setw(8) << correlation[4]
<< " cZC=" << setw(8) << correlation[5];
}
}
s << endl;
};
void SP3Data::reallyGetRecord(FFStream& ffs)
throw(std::exception, FFStreamError, StringException)
{
SP3Stream& strm = dynamic_cast<SP3Stream&>(ffs);
correlationFlag = false;
int status = 0; // initial status = 0
while(1) {
// set the time in the record
time = strm.currentEpoch;
// ---------------------------------------------------------
// process the buffer containing the last line read
if(strm.buffer.size() < 3) {
// nothing in buffer - do nothing here, get another line
;
}
else if(strm.buffer.substr(0,3) == string("EOF")) { // 'EOF' record
// if a data record has been processed during this call, then
// return and let the next call process this EOF.
//if(status == 1) throw - found EOF right after an epoch record
if(status > 1) break;
// this next read had better fail - if it does, an exception will
// be thrown, and the FFStreamError created next won't get thrown
strm.formattedGetLine(strm.buffer, true);
FFStreamError err("EOF text found but file didn't end");
GPSTK_THROW(err);
}
else if(strm.buffer[0] == '*') { // Epoch record
// if another record has been process during this call, quit now
if(status > 0) break;
status = 1; // epoch status = 1
// throw if the line is short
if(strm.buffer.size() <= 30) {
FFStreamError err("Invalid line length "+asString(strm.buffer.size()));
GPSTK_THROW(err);
}
// parse the epoch line
int year = asInt(strm.buffer.substr(3,4));
int month = asInt(strm.buffer.substr(8,2));
int dom = asInt(strm.buffer.substr(11,2));
int hour = asInt(strm.buffer.substr(14,2));
int minute = asInt(strm.buffer.substr(17,2));
double second = asInt(strm.buffer.substr(20,10));
DayTime t(year, month, dom, hour, minute, second);
time = strm.currentEpoch = t;
}
else if(strm.buffer[0] == 'P' || strm.buffer[0] == 'V') {// P|V record
// if nothing, or epoch record, was processed during this call,
// process this P|V, otherwise (P|V or EP|V were processed), quit now
if(status > 1) break;
status = 2; // P|V status = 2
flag = strm.buffer[0]; // P or V
// throw if the line is short
if ((version == 'a' && strm.buffer.size() < 60) ||
(version == 'c' && strm.buffer.size() < 73) ) {
FFStreamError err("Invalid line length "+asString(strm.buffer.size()));
GPSTK_THROW(err);
}
// parse the line
if(version == 'a')
sat = SatID(asInt(strm.buffer.substr(1, 3)), SP3SatID::systemGPS);
else
sat = SP3SatID(strm.buffer.substr(1,3));
x[0] = asDouble(strm.buffer.substr(4,14));
x[1] = asDouble(strm.buffer.substr(18,14));
x[2] = asDouble(strm.buffer.substr(32,14));
clk = asDouble(strm.buffer.substr(46,14));
if(version == 'c') {
// get sigmas from P|V record
sig[0] = asInt(strm.buffer.substr(61,2));
sig[1] = asInt(strm.buffer.substr(64,2));
sig[2] = asInt(strm.buffer.substr(67,2));
sig[3] = asInt(strm.buffer.substr(70,3));
// get flags
if(flag == 'P') {
clockEventFlag = clockPredFlag
= orbitManeuverFlag = orbitPredFlag = false;
if(strm.buffer.size() >= 75 && strm.buffer[74] == 'E')
clockEventFlag = true;
if(strm.buffer.size() >= 76 && strm.buffer[75] == 'P')
clockPredFlag = true;
if(strm.buffer.size() >= 79 && strm.buffer[78] == 'M')
orbitManeuverFlag = true;
if(strm.buffer.size() >= 80 && strm.buffer[79] == 'P')
orbitPredFlag = true;
}
}
}
else if(strm.buffer[0] == 'E' && // EP|EV record
(strm.buffer[1] == 'P' || strm.buffer[1] == 'V')) {
// always process an EP|V immediately, since it must follow P|V
status = 3; // EP|V status = 3
// throw if correlation record did not follow corresponding P|V record
if(strm.buffer[1] != flag) {
Exception e("SP3c correlation record mismatched with previous P|V");
GPSTK_THROW(e);
}
// throw if line is short
if(strm.buffer.size()<80) {
FFStreamError err("Invalid SP3c correlation line length "
+ asString(strm.buffer.size()));
GPSTK_THROW(err);
}
sdev[0] = abs(asInt(strm.buffer.substr(4,4)));
sdev[1] = abs(asInt(strm.buffer.substr(9,4)));
sdev[2] = abs(asInt(strm.buffer.substr(14,4)));
sdev[3] = abs(asInt(strm.buffer.substr(19,7)));
correlation[0] = asInt(strm.buffer.substr(27,8));
correlation[1] = asInt(strm.buffer.substr(36,8));
correlation[2] = asInt(strm.buffer.substr(45,8));
correlation[3] = asInt(strm.buffer.substr(54,8));
correlation[4] = asInt(strm.buffer.substr(63,8));
correlation[5] = asInt(strm.buffer.substr(72,8));
// tell the caller that correlation data is now present
correlationFlag = true;
}
else { // Unknown record
FFStreamError err("Unknown line label " + strm.buffer.substr(0,2));
GPSTK_THROW(err);
}
// ---------------------------------------------------------
// read next line into the buffer
strm.formattedGetLine(strm.buffer);
// ---------------------------------------------------------
// quit if EP|EV was processed
if(status == 3) break;
// go back if buffer was empty (0)
// go back if epoch was processed (1)
// go back if P|V was processed (2)
}
} // end reallyGetRecord()
} // namespace
<|endoftext|>
|
<commit_before>
#pragma once
#include <deque>
#include <optional>
#include "quantities/named_quantities.hpp"
#include "quantities/quantities.hpp"
namespace principia {
namespace numerics {
namespace internal_pid {
using quantities::Inverse;
using quantities::Time;
template<typename Value, int horizon, int finite_difference_order>
class PID {
public:
static_assert(finite_difference_order <= horizon);
PID(double kp, Inverse<Time> const& ki, Time const& kd);
// Clears the state of the PID.
void Clear();
// Adds the error between the process variable and the set-point to the state
// of the PID and returns an updated process variable derived from the
// set-point and the control variable.
Value ComputeValue(Value const& process_variable,
Value const& set_point,
Time const& Δt);
private:
double const kp_;
Inverse<Time> const ki_;
Time const kd_;
// The PID is not prepared to receive inputs that are not equally spaced.
std::optional<Time> previous_Δt_;
// The front element is the oldest.
std::deque<Value> errors_;
};
} // namespace internal_pid
using internal_pid::PID;
} // namespace numerics
} // namespace principia
#include "numerics/pid_body.hpp"
<commit_msg>Lint.<commit_after>
#pragma once
#include <deque>
#include <optional>
#include "quantities/named_quantities.hpp"
#include "quantities/quantities.hpp"
namespace principia {
namespace numerics {
namespace internal_pid {
using quantities::Inverse;
using quantities::Time;
template<typename Value, int horizon, int finite_difference_order>
class PID {
public:
static_assert(finite_difference_order <= horizon);
PID(double kp, Inverse<Time> const& ki, Time const& kd);
// Clears the state of the PID.
void Clear();
// Adds the error between the process variable and the set-point to the state
// of the PID and returns an updated process variable derived from the
// set-point and the control variable.
Value ComputeValue(Value const& process_variable,
Value const& set_point,
Time const& Δt);
private:
double const kp_;
Inverse<Time> const ki_;
Time const kd_;
// The PID is not prepared to receive inputs that are not equally spaced.
std::optional<Time> previous_Δt_;
// The front element is the oldest.
std::deque<Value> errors_;
};
} // namespace internal_pid
using internal_pid::PID;
} // namespace numerics
} // namespace principia
#include "numerics/pid_body.hpp"
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string.h>
#include <istream>
#include <cstring>
#include <unistd.h>
using namespace std;
#include <cstdio>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <errno.h>
#include <cstdlib>
int main()
{
string input;
//taking input as a c++ string; will convert to c_str later
cout << "$ "; //command prompt
getline (cin,input);
cout << endl << "outputting input: " << endl << input << endl;
//these will be the arguments to my shell after parsing
int argc = 0; // no arguments (yet)
char* argv[99999];
argv[0] = new char[9999];
char * tmp; //cstring to not deal with memory management for now
char delims[] = " "; // connectors we are looking out for.
//FIXME: may not be exactly what we want since may have
//to be arguments too
char input2[9999]; //will take copy of input from std::string input
strcpy(input2, input.c_str() );
cout << "about to run strtok 1st time" << endl;
tmp = strtok(input2,delims) ;
strcpy( argv[argc] , tmp ); //copying first token
cout << "about to run strtok In while loop." << endl;
while (tmp != NULL)
{
argc +=1; // argument count increases.
printf ("%s\n",tmp) ;
tmp = strtok (NULL,delims);
argv[argc] = tmp; // copying tokens into argv one at a time
}
/* cerr << "copying tmp into argv..." << endl;
strcpy(*argv,tmp );
cout << "strcpy successful!! (maybe LOL)" << endl;
*/
//checking everything was read in
cout << "argc: " << argc << " " << endl;
cout << " argv:" << endl;
for(unsigned i = 0; argv[i]!='\0'; ++i){
cout << i << ": " << argv[i] << endl;
}
//need to figure out a way to read in commands with ';' in between
//and white space in between
//checking how execvp works (dummy variables)
char * aargv[4];
aargv[0] = new char[4];
aargv[1] = new char[4];
aargv[2] = new char[4];
strcpy( aargv[0] , "pwd"); //copying first token
cout << "first copy. \n" << endl;
strcpy( aargv[1] , " ; " );
cout << "about tho start third..." << endl;
strcpy( aargv[2] , "ls");
cout << "done copying... " << endl;
//beginning fork, execpv processes
//may need to creat multiple forks to run input with connectors
int pid=fork();
if(pid == -1)
{
perror("There was an error with fork(). " );
exit(1);
}
//child process
if (pid==0) {
cout << "i'm a child" << endl;
cout <<" before" << endl;
if(-1 == execvp(argv[0], argv))
{
perror("Error: execvp didn't run as expected. Commands may not exist.");
}
exit(1); //avoid zombies
}
//pid now > 0 so we are in parent process.
else{
if( wait(NULL) == -1 ){
perror("Error: wait() did not wait!! :o ");
}
cout << "I'm a parent." << endl;
exit(1);
}
return 0;
}
<commit_msg>created at vector <char**> argv to handle different argumentsgit add rschell.cpp and sorta got the loop to get these arguments working. MUCH MORE WORK LEFTgit add rschell.cpp<commit_after>#include <iostream>
#include <string.h>
#include <istream>
#include <cstring>
#include <unistd.h>
using namespace std;
#include <cstdio>
#include <cstring>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <errno.h>
#include <cstdlib>
#include <vector>
//Counts number of arguments
int count_args( const string & input ) {
if (input.size() == 0 )
{
return 0;
}
int count = 1;
for(unsigned i = 0; i < input.size(); ++i)
{
if ( input.at(i) == '&' || input.at(i) == '|' )
{
i+=1; // first '&' or '|' will be followed by another
count +=1;
}
if ( input.at(i) == ';' && i+1 != input.size() )//can have command: pwd;
{
count +=1;
//BUG: will give greater size than should be when have input: "ls ; pwd; "
//will count white space unfortunately.....
//will say extra argument than there is..
}
}
return count;
}
int main()
{
string input;
//taking input as a c++ string; will convert to c_str later
cout << "$ "; //command prompt
getline (cin,input);
cout << endl << "outputting input: " << endl << input << endl;
cout << "input.size() (raw): " << input.size() << endl; // trying to see if space adds size
//these will be the arguments to my shell after parsing
unsigned arg_count = count_args(input);
vector <char**> argv;
argv.resize( arg_count );
char * tmp; //cstring to not deal with memory management for now
char delims[] = " "; // connectors we are looking out for.
//FIXME: may not be exactly what we want since may have
//to be arguments too
int inp_sz = input.size()+1;
char* input2 = new char[inp_sz]; //will take copy of input from std::string input
strcpy(input2, input.c_str() );
cout << "input2 done. no seg fault here. " << endl;
for(unsigned i = 0; i < arg_count; ++i)
{
int argc = 0 ; // no arguments (yet)
tmp = strtok(input2,delims) ;
cout << "strtok, i = " << i << endl;
argv.at(i) = new char* [999];
argv.at(i)[argc] = new char[strlen(tmp) +1];
strcpy( (argv.at(i)[argc] ) , tmp ); //copying first token
cout << "strcpy, i = " << i << endl;
while (tmp != NULL)
{
argc +=1; // argument count increases.
printf ("%s\n",tmp) ;
tmp = strtok (NULL,delims);
argv.at(i)[argc] = tmp; // copying tokens into argv one at a time
}
cout << "first while, i = " << i << endl;
}
/* cerr << "copying tmp into argv..." << endl;
strcpy(*argv,tmp );
cout << "strcpy successful!! (maybe LOL)" << endl;
*/
//checking everything was read in
//cout << "argc: " << argc << " " << endl;
//cout << " argv:" << endl;
for(unsigned i = 0; argv[i]!='\0'; ++i){
cout << i << ": " << argv[i] << endl;
}
//need to figure out a way to read in commands with ';' in between
//and white space in between
//checking how execvp works (dummy variables)
char * aargv[4];
aargv[0] = new char[4];
aargv[1] = new char[4];
aargv[2] = new char[4];
strcpy( aargv[0] , "pwd"); //copying first token
cout << "first copy. \n" << endl;
strcpy( aargv[1] , " ; " );
cout << "about tho start third..." << endl;
strcpy( aargv[2] , "ls");
cout << "done copying... " << endl;
//beginning fork, execpv processes
//may need to creat multiple forks to run input with connectors
//will now make major changes
//execute multiple commands through for loop (similar to lab02)
int pid=fork();
if(pid == -1)
{
perror("There was an error with fork(). " );
exit(1);
}
//child process
if (pid==0) {
cout << "i'm a child" << endl;
/*
if(-1 == execvp(*argv.at(0)[0] , *argv.at(0) )
{
perror("Error: execvp didn't run as expected. Commands may not exist.");
exit(1); //avoid zombies
}*/
}
//pid now > 0 so we are in parent process.
else{
if( wait(NULL) == -1 ){
perror("Error: wait() did not wait!! :o ");
}
cout << "I'm a parent." << endl;
exit(1);
}
return 0;
}
<|endoftext|>
|
<commit_before>#pragma once
#include "h5file.hpp"
namespace mocc {
/**
* This simply specifies an interface for outputing "stuff" to and HDF5
* file. Any class extending it must implement the output() method, which
* adds its data to the H5File instance passed to it.
*/
class HasOutput {
public:
// Perform final output to a data file. Most output is probably
// delegated to supbordinate objects.
virtual void output( H5Node &file ) const = 0;
};
}
<commit_msg>Improve HasOutput docs<commit_after>#pragma once
#include "h5file.hpp"
namespace mocc {
/**
* This simply specifies an interface for outputing "stuff" to and HDF5
* file. Any class extending it must implement the output() method, which
* adds its data to the H5File instance passed to it.
*/
class HasOutput {
public:
/**
* \brief Output relevant data to an HDF5 file node.
*/
virtual void output( H5Node &file ) const = 0;
};
}
<|endoftext|>
|
<commit_before>/*
* Texture.h
*
* Created on: 16 Jun 2014
* Author: rick
*/
#ifndef TEXTURE_H_
#define TEXTURE_H_
#include "Vec3D.hpp"
typedef Vec3Df Texture;
#endif /* TEXTURE_H_ */
<commit_msg>Really fixed refactor.<commit_after>/*
* Texture.hpp
*
* Created on: 16 Jun 2014
* Author: rick
*/
#ifndef TEXTURE_H_
#define TEXTURE_H_
#include "Vec3D.hpp"
typedef Vec3Df Texture;
#endif /* TEXTURE_H_ */
<|endoftext|>
|
<commit_before>// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "pal.h"
#include "utils.h"
#include "trace.h"
#include <dlfcn.h>
#include <dirent.h>
#include <sys/stat.h>
#if defined(__APPLE__)
#include <mach-o/dyld.h>
#endif
#if defined(__LINUX__)
#define symlinkEntrypointExecutable "/proc/self/exe"
#elif !defined(__APPLE__)
#define symlinkEntrypointExecutable "/proc/curproc/exe"
#endif
bool pal::find_coreclr(pal::string_t& recv)
{
pal::string_t candidate;
pal::string_t test;
// Try /usr/share/dotnet and /usr/local/share/dotnet
candidate.assign("/usr/share/dotnet/runtime/coreclr");
if (coreclr_exists_in_dir(candidate)) {
recv.assign(candidate);
return true;
}
candidate.assign("/usr/local/share/dotnet/runtime/coreclr");
if (coreclr_exists_in_dir(candidate)) {
recv.assign(candidate);
return true;
}
return false;
}
bool pal::load_library(const char_t* path, dll_t& dll)
{
dll = dlopen(path, RTLD_LAZY);
if (dll == nullptr)
{
trace::error(_X("failed to load %s, error: %s"), path, dlerror());
return false;
}
return true;
}
pal::proc_t pal::get_symbol(dll_t library, const char* name)
{
auto result = dlsym(library, name);
if (result == nullptr)
{
trace::error(_X("failed to resolve library symbol %s, error: %s"), name, dlerror());
}
return result;
}
void pal::unload_library(dll_t library)
{
if (dlclose(library) != 0)
{
trace::warning(_X("failed to unload library, error: %s"), dlerror());
}
}
int pal::xtoi(const char_t* input)
{
return atoi(input);
}
bool pal::is_path_rooted(const pal::string_t& path)
{
return path.front() == '/';
}
bool pal::get_default_packages_directory(pal::string_t& recv)
{
if (!pal::getenv("HOME", recv))
{
return false;
}
append_path(recv, _X(".dnx"));
append_path(recv, _X("packages"));
return true;
}
#if defined(__APPLE__)
bool pal::get_own_executable_path(pal::string_t& recv)
{
uint32_t path_length = 0;
if (_NSGetExecutablePath(nullptr, &path_length) == -1)
{
char path_buf[path_length];
if (_NSGetExecutablePath(path_buf, &path_length) == 0)
{
recv.assign(path_buf);
return true;
}
}
return false;
}
#else
bool pal::get_own_executable_path(pal::string_t& recv)
{
// Just return the symlink to the exe from /proc
// We'll call realpath on it later
recv.assign(symlinkEntrypointExecutable);
return true;
}
#endif
bool pal::getenv(const pal::char_t* name, pal::string_t& recv)
{
auto result = ::getenv(name);
if (result != nullptr)
{
recv.assign(result);
}
// We don't return false. Windows does have a concept of an error reading the variable,
// but Unix just returns null, which we treat as the variable not existing.
return true;
}
bool pal::realpath(pal::string_t& path)
{
pal::char_t buf[PATH_MAX];
auto resolved = ::realpath(path.c_str(), buf);
if (resolved == nullptr)
{
if (errno == ENOENT)
{
return false;
}
perror("realpath()");
return false;
}
path.assign(resolved);
return true;
}
bool pal::file_exists(const pal::string_t& path)
{
struct stat buffer;
return (::stat(path.c_str(), &buffer) == 0);
}
std::vector<pal::string_t> pal::readdir(const pal::string_t& path)
{
std::vector<pal::string_t> files;
auto dir = opendir(path.c_str());
if (dir != nullptr)
{
struct dirent* entry = nullptr;
while((entry = readdir(dir)) != nullptr)
{
// We are interested in files only
switch (entry->d_type)
{
case DT_REG:
break;
// Handle symlinks and file systems that do not support d_type
case DT_LNK:
case DT_UNKNOWN:
{
std::string fullFilename;
fullFilename.append(path);
fullFilename.push_back(DIR_SEPARATOR);
fullFilename.append(entry->d_name);
struct stat sb;
if (stat(fullFilename.c_str(), &sb) == -1)
{
continue;
}
if (!S_ISREG(sb.st_mode))
{
continue;
}
}
break;
default:
continue;
}
files.push_back(pal::string_t(entry->d_name));
}
}
return files;
}
<commit_msg>Changes for corehost default path resolution on mac<commit_after>// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "pal.h"
#include "utils.h"
#include "trace.h"
#include <dlfcn.h>
#include <dirent.h>
#include <sys/stat.h>
#if defined(__APPLE__)
#include <mach-o/dyld.h>
#endif
#if defined(__LINUX__)
#define symlinkEntrypointExecutable "/proc/self/exe"
#elif !defined(__APPLE__)
#define symlinkEntrypointExecutable "/proc/curproc/exe"
#endif
bool pal::find_coreclr(pal::string_t& recv)
{
pal::string_t candidate;
pal::string_t test;
// Try /usr/share/dotnet and /usr/local/share/dotnet/cli
// TODO: These paths should be consistent
candidate.assign("/usr/share/dotnet/runtime/coreclr");
if (coreclr_exists_in_dir(candidate)) {
recv.assign(candidate);
return true;
}
candidate.assign("/usr/local/share/dotnet/cli/runtime/coreclr");
if (coreclr_exists_in_dir(candidate)) {
recv.assign(candidate);
return true;
}
return false;
}
bool pal::load_library(const char_t* path, dll_t& dll)
{
dll = dlopen(path, RTLD_LAZY);
if (dll == nullptr)
{
trace::error(_X("failed to load %s, error: %s"), path, dlerror());
return false;
}
return true;
}
pal::proc_t pal::get_symbol(dll_t library, const char* name)
{
auto result = dlsym(library, name);
if (result == nullptr)
{
trace::error(_X("failed to resolve library symbol %s, error: %s"), name, dlerror());
}
return result;
}
void pal::unload_library(dll_t library)
{
if (dlclose(library) != 0)
{
trace::warning(_X("failed to unload library, error: %s"), dlerror());
}
}
int pal::xtoi(const char_t* input)
{
return atoi(input);
}
bool pal::is_path_rooted(const pal::string_t& path)
{
return path.front() == '/';
}
bool pal::get_default_packages_directory(pal::string_t& recv)
{
if (!pal::getenv("HOME", recv))
{
return false;
}
append_path(recv, _X(".dnx"));
append_path(recv, _X("packages"));
return true;
}
#if defined(__APPLE__)
bool pal::get_own_executable_path(pal::string_t& recv)
{
uint32_t path_length = 0;
if (_NSGetExecutablePath(nullptr, &path_length) == -1)
{
char path_buf[path_length];
if (_NSGetExecutablePath(path_buf, &path_length) == 0)
{
recv.assign(path_buf);
return true;
}
}
return false;
}
#else
bool pal::get_own_executable_path(pal::string_t& recv)
{
// Just return the symlink to the exe from /proc
// We'll call realpath on it later
recv.assign(symlinkEntrypointExecutable);
return true;
}
#endif
bool pal::getenv(const pal::char_t* name, pal::string_t& recv)
{
auto result = ::getenv(name);
if (result != nullptr)
{
recv.assign(result);
}
// We don't return false. Windows does have a concept of an error reading the variable,
// but Unix just returns null, which we treat as the variable not existing.
return true;
}
bool pal::realpath(pal::string_t& path)
{
pal::char_t buf[PATH_MAX];
auto resolved = ::realpath(path.c_str(), buf);
if (resolved == nullptr)
{
if (errno == ENOENT)
{
return false;
}
perror("realpath()");
return false;
}
path.assign(resolved);
return true;
}
bool pal::file_exists(const pal::string_t& path)
{
struct stat buffer;
return (::stat(path.c_str(), &buffer) == 0);
}
std::vector<pal::string_t> pal::readdir(const pal::string_t& path)
{
std::vector<pal::string_t> files;
auto dir = opendir(path.c_str());
if (dir != nullptr)
{
struct dirent* entry = nullptr;
while((entry = readdir(dir)) != nullptr)
{
// We are interested in files only
switch (entry->d_type)
{
case DT_REG:
break;
// Handle symlinks and file systems that do not support d_type
case DT_LNK:
case DT_UNKNOWN:
{
std::string fullFilename;
fullFilename.append(path);
fullFilename.push_back(DIR_SEPARATOR);
fullFilename.append(entry->d_name);
struct stat sb;
if (stat(fullFilename.c_str(), &sb) == -1)
{
continue;
}
if (!S_ISREG(sb.st_mode))
{
continue;
}
}
break;
default:
continue;
}
files.push_back(pal::string_t(entry->d_name));
}
}
return files;
}
<|endoftext|>
|
<commit_before>/*
* Message.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/http/Message.hpp>
#include <algorithm>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/function.hpp>
#include <boost/asio/buffer.hpp>
#include <core/SafeConvert.hpp>
namespace rstudio {
namespace core {
namespace http {
// encodings
const char * const kGzipEncoding = "gzip";
void Message::setHttpVersion(int httpVersionMajor, int httpVersionMinor)
{
httpVersionMajor_ = httpVersionMajor ;
httpVersionMinor_ = httpVersionMinor ;
}
void Message::setContentType(const std::string& contentType)
{
setHeader("Content-Type", contentType) ;
}
std::string Message::contentType() const
{
return headerValue("Content-Type") ;
}
std::size_t Message::contentLength() const
{
return safe_convert::stringTo<std::size_t>(headerValue("Content-Length"), 0);
}
void Message::setContentLength(int contentLength)
{
setHeader("Content-Length", contentLength);
}
void Message::addHeader(const std::string& name, const std::string& value)
{
Header header ;
header.name = name ;
header.value = value ;
addHeader(header);
}
void Message::addHeader(const Header& header)
{
headers_.push_back(header);
}
void Message::addHeaders(const std::vector<Header>& headers)
{
std::copy(headers.begin(), headers.end(), std::back_inserter(headers_));
}
std::string Message::headerValue(const std::string& name) const
{
return http::headerValue(headers_, name);
}
bool Message::containsHeader(const std::string& name) const
{
return http::containsHeader(headers_, name);
}
void Message::setHeaderLine(const std::string& line)
{
Header header;
if (http::parseHeader(line, &header))
setHeader(header);
}
void Message::setHeader(const Header& header)
{
setHeader(header.name, header.value);
}
void Message::setHeader(const std::string& name, const std::string& value)
{
Headers::iterator it = std::find_if(headers_.begin(),
headers_.end(),
HeaderNamePredicate(name));
if ( it != headers_.end() )
{
Header hdr ;
hdr.name = name ;
hdr.value = value ;
*it = hdr ;
}
else
{
addHeader(name, value) ;
}
}
void Message::setHeader(const std::string& name, int value)
{
setHeader(name, safe_convert::numberToString(value));
}
void Message::replaceHeader(const std::string& name, const std::string& value)
{
Header hdr ;
hdr.name = name ;
hdr.value = value ;
std::replace_if(headers_.begin(),
headers_.end(),
HeaderNamePredicate(name),
hdr) ;
}
void Message::removeHeader(const std::string& name)
{
headers_.erase(std::remove_if(headers_.begin(),
headers_.end(),
HeaderNamePredicate(name)),
headers_.end()) ;
}
void Message::reset()
{
setHttpVersion(1,1) ;
httpVersion_.clear() ;
headers_.clear() ;
body_.clear() ;
// allow additional reseting by subclasses
resetMembers() ;
}
namespace {
const char Space[] = { ' ' } ;
const char HeaderSeparator[] = { ':', ' ' } ;
const char CrLf[] = { '\r', '\n' } ;
void appendHeader(const Header& header,
std::vector<boost::asio::const_buffer>* pBuffers)
{
pBuffers->push_back(boost::asio::buffer(header.name)) ;
pBuffers->push_back(boost::asio::buffer(HeaderSeparator)) ;
pBuffers->push_back(boost::asio::buffer(header.value)) ;
pBuffers->push_back(boost::asio::buffer(CrLf)) ;
}
}
std::vector<boost::asio::const_buffer> Message::toBuffers(
const Header& overrideHeader) const
{
// buffers to return
std::vector<boost::asio::const_buffer> buffers ;
// call subclass to append first line
appendFirstLineBuffers(buffers) ;
buffers.push_back(boost::asio::buffer(CrLf)) ;
// copy override header (for stable storage)
overrideHeader_ = overrideHeader;
// headers
for (Headers::const_iterator
it = headers_.begin(); it != headers_.end(); ++it)
{
// add the header if it isn't being overriden
if (it->name != overrideHeader_.name)
appendHeader(*it, &buffers);
}
// add override header
if (!overrideHeader_.empty())
appendHeader(overrideHeader_, &buffers);
// empty line
buffers.push_back(boost::asio::buffer(CrLf)) ;
// body
buffers.push_back(boost::asio::buffer(body_)) ;
// return the buffers
return buffers ;
}
void Message::appendSpaceBuffer(
std::vector<boost::asio::const_buffer>& buffers) const
{
buffers.push_back(boost::asio::buffer(Space)) ;
}
void Message::appendHttpVersionBuffers(
std::vector<boost::asio::const_buffer>& buffers) const
{
std::ostringstream httpVersionStream;
httpVersionStream << "HTTP/" << httpVersionMajor_ << "." << httpVersionMinor_ ;
httpVersion_ = httpVersionStream.str() ;
buffers.push_back(boost::asio::buffer(httpVersion_)) ;
}
std::ostream& operator << (std::ostream& stream, const Message& m)
{
// headers
for (Headers::const_iterator it =
m.headers().begin(); it != m.headers().end(); ++ it)
{
stream << it->name << ": " << it->value << std::endl ;
}
// empty line
stream << std::endl ;
// body
stream << m.body() << std::endl ;
return stream ;
}
} // namespace http
} // namespace core
} // namespace rstudio
<commit_msg>work around RStudio crash (toolchain issue?)<commit_after>/*
* Message.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/http/Message.hpp>
#include <algorithm>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/function.hpp>
#include <boost/asio/buffer.hpp>
#include <core/SafeConvert.hpp>
namespace rstudio {
namespace core {
namespace http {
// encodings
const char * const kGzipEncoding = "gzip";
void Message::setHttpVersion(int httpVersionMajor, int httpVersionMinor)
{
httpVersionMajor_ = httpVersionMajor ;
httpVersionMinor_ = httpVersionMinor ;
}
void Message::setContentType(const std::string& contentType)
{
setHeader("Content-Type", contentType) ;
}
std::string Message::contentType() const
{
return headerValue("Content-Type") ;
}
std::size_t Message::contentLength() const
{
std::string value = headerValue("Content-Length");
if (value.empty())
return 0;
return safe_convert::stringTo<std::size_t>(value, 0);
}
void Message::setContentLength(int contentLength)
{
setHeader("Content-Length", contentLength);
}
void Message::addHeader(const std::string& name, const std::string& value)
{
Header header ;
header.name = name ;
header.value = value ;
addHeader(header);
}
void Message::addHeader(const Header& header)
{
headers_.push_back(header);
}
void Message::addHeaders(const std::vector<Header>& headers)
{
std::copy(headers.begin(), headers.end(), std::back_inserter(headers_));
}
std::string Message::headerValue(const std::string& name) const
{
return http::headerValue(headers_, name);
}
bool Message::containsHeader(const std::string& name) const
{
return http::containsHeader(headers_, name);
}
void Message::setHeaderLine(const std::string& line)
{
Header header;
if (http::parseHeader(line, &header))
setHeader(header);
}
void Message::setHeader(const Header& header)
{
setHeader(header.name, header.value);
}
void Message::setHeader(const std::string& name, const std::string& value)
{
Headers::iterator it = std::find_if(headers_.begin(),
headers_.end(),
HeaderNamePredicate(name));
if ( it != headers_.end() )
{
Header hdr ;
hdr.name = name ;
hdr.value = value ;
*it = hdr ;
}
else
{
addHeader(name, value) ;
}
}
void Message::setHeader(const std::string& name, int value)
{
setHeader(name, safe_convert::numberToString(value));
}
void Message::replaceHeader(const std::string& name, const std::string& value)
{
Header hdr ;
hdr.name = name ;
hdr.value = value ;
std::replace_if(headers_.begin(),
headers_.end(),
HeaderNamePredicate(name),
hdr) ;
}
void Message::removeHeader(const std::string& name)
{
headers_.erase(std::remove_if(headers_.begin(),
headers_.end(),
HeaderNamePredicate(name)),
headers_.end()) ;
}
void Message::reset()
{
setHttpVersion(1,1) ;
httpVersion_.clear() ;
headers_.clear() ;
body_.clear() ;
// allow additional reseting by subclasses
resetMembers() ;
}
namespace {
const char Space[] = { ' ' } ;
const char HeaderSeparator[] = { ':', ' ' } ;
const char CrLf[] = { '\r', '\n' } ;
void appendHeader(const Header& header,
std::vector<boost::asio::const_buffer>* pBuffers)
{
pBuffers->push_back(boost::asio::buffer(header.name)) ;
pBuffers->push_back(boost::asio::buffer(HeaderSeparator)) ;
pBuffers->push_back(boost::asio::buffer(header.value)) ;
pBuffers->push_back(boost::asio::buffer(CrLf)) ;
}
}
std::vector<boost::asio::const_buffer> Message::toBuffers(
const Header& overrideHeader) const
{
// buffers to return
std::vector<boost::asio::const_buffer> buffers ;
// call subclass to append first line
appendFirstLineBuffers(buffers) ;
buffers.push_back(boost::asio::buffer(CrLf)) ;
// copy override header (for stable storage)
overrideHeader_ = overrideHeader;
// headers
for (Headers::const_iterator
it = headers_.begin(); it != headers_.end(); ++it)
{
// add the header if it isn't being overriden
if (it->name != overrideHeader_.name)
appendHeader(*it, &buffers);
}
// add override header
if (!overrideHeader_.empty())
appendHeader(overrideHeader_, &buffers);
// empty line
buffers.push_back(boost::asio::buffer(CrLf)) ;
// body
buffers.push_back(boost::asio::buffer(body_)) ;
// return the buffers
return buffers ;
}
void Message::appendSpaceBuffer(
std::vector<boost::asio::const_buffer>& buffers) const
{
buffers.push_back(boost::asio::buffer(Space)) ;
}
void Message::appendHttpVersionBuffers(
std::vector<boost::asio::const_buffer>& buffers) const
{
std::ostringstream httpVersionStream;
httpVersionStream << "HTTP/" << httpVersionMajor_ << "." << httpVersionMinor_ ;
httpVersion_ = httpVersionStream.str() ;
buffers.push_back(boost::asio::buffer(httpVersion_)) ;
}
std::ostream& operator << (std::ostream& stream, const Message& m)
{
// headers
for (Headers::const_iterator it =
m.headers().begin(); it != m.headers().end(); ++ it)
{
stream << it->name << ": " << it->value << std::endl ;
}
// empty line
stream << std::endl ;
// body
stream << m.body() << std::endl ;
return stream ;
}
} // namespace http
} // namespace core
} // namespace rstudio
<|endoftext|>
|
<commit_before>#include "alara.h"
#include "Matrix.h"
/* this is used to determine how many terms are needed in the expansion */
#define MAXEXPTOL 1e-15
/* This is the maximum number of terms allowed for the expansion method
* If more are needed, the inversion method is used */
#define MAXNUMEXPTERMS 15
/* This is used to determine if poles are degenerate. Loops should
* generate poles which are exactly the same, but poles with small
* relative differences may act as degeneracies anyway */
#define SMALL_REL_DIFF 1e-8
/* routine for to calculate factorial */
double fact(int i)
{
double result=1;
while (i>1) result *= i--;
return result;
}
double bateman(int row, int col, double* P, double* d, double t)
{
if (row == col)
/* if this is on the diagonal,
* simple exponential decay */
return exp(-d[col]*t);
if (d[col] == 0)
/* if the isotope at this rank=col has no destruction,
* the whole column is empty ! (except the diagonal)
* Note: this is only possible when calling from a decay matrix sol'n
*/
return 0;
double result, sum, sumInc, den;
int term, denTerm;
result = 1;
sum = 0;
sumInc = 0;
for (term=col;term<row;term++)
{
/* multiplicative increment of normalization */
result *= P[term+1];
if (result == 0)
/* if there is no production path between the isotopes at
* row and col, this element is empty
* Note: this is only possible when calling from a decay matrix sol'n
*/
return 0;
/* set denominator element based on Laplace root: d[term]
* (traditional analytic inverse Laplace transform) */
den = 1;
for (denTerm=col;denTerm<term;denTerm++)
den *= (d[denTerm]-d[term]);
for (denTerm++;denTerm<=row;denTerm++)
den *= (d[denTerm]-d[term]);
/* set numerator element based on Laplace root: d[term] */
sumInc = expm1(-d[term]*t)-expm1(-d[row]*t);
/* add element based on Laplace root: d[term] */
sum += sumInc/den;
}
/* multiply normalization by sum of Laplace inverse terms */
result *= sum;
return result;
};
double dGn(int idx, double *pole, int *mult, int numPoles, int termNum)
{
int pNum, pwr;
double invPwrSum,result = 0;
if (termNum==0) /* End Condition - 0th derivative */
/* return inverse product of pole-otherPoles */
{
result = 1;
/* all poles before the current pole */
for (pNum=0; pNum<idx; pNum++)
result /= pow( pole[pNum] - pole[idx] , mult[pNum] );
/* all poles after the current pole */
for (pNum++; pNum<numPoles; pNum++)
result /= pow( pole[pNum] - pole[idx] , mult[pNum] );
}
else
for (pwr=termNum;pwr>0;pwr--)
{
invPwrSum = 0;
/* all poles before the current pole */
for (pNum=0; pNum<idx; pNum++)
invPwrSum += mult[pNum] * pow( pole[pNum]-pole[idx] , -pwr );
/* all poles after the current pole */
for (pNum++; pNum<numPoles; pNum++)
invPwrSum += mult[pNum] * pow( pole[pNum]-pole[idx] , -pwr );
/* recursively add terms */
result += -2*(pwr%2 -.5) * (fact(termNum-1)/fact(termNum-pwr))
* invPwrSum * dGn(idx,pole,mult,numPoles,termNum-pwr);
}
return result;
}
double laplaceInverse(int row, int col, double *d, double t)
{
int idx, checkIdx, multCnt;
int numPoles = 0;
int *mult = new int[row-col+1];
double *pole = new double[row-col+1];
double poleResult, result;
if (row == col)
/* if this is on the diagonal,
* simple exponential decay */
return exp(-d[col]*t);
/* index all the poles with the multiplicities */
for (idx = col;idx<=row;idx++)
{
for (checkIdx=0;checkIdx<numPoles;checkIdx++)
if ( fabs((d[idx]-pole[checkIdx]))<SMALL_REL_DIFF*d[idx] )
{
mult[checkIdx]++;
break;
}
if (checkIdx == numPoles)
{
pole[checkIdx] = d[idx];
mult[checkIdx] = 1;
numPoles++;
}
}
/* perform recursive analytic Laplace inversion */
for (idx=0;idx<numPoles;idx++)
{
poleResult = 0;
for (multCnt=mult[idx];multCnt>0;multCnt--)
poleResult += dGn(idx, pole, mult, numPoles, mult[idx] - multCnt)
* pow(t,multCnt-1)
/ fact(multCnt-1)
/ fact(mult[idx]-multCnt) ;
result += poleResult * exp(-pole[idx]*t);
}
return result;
}
double laplaceExpansion(int row, int col, double *d, double t, int numTerms)
{
int sz = row-col;
double result;
if (row == col)
/* if this is on the diagonal,
* simple exponential decay */
return exp(-d[col]*t);
/* initialize matrix with destruction rates */
Matrix poleMat = Matrix::Triangle(d,sz+1);
Matrix powPoleMat = Matrix::Identity(sz+1);
/* zeroth term is simply the correct power of t/n! */
result = pow(t,sz)/fact(sz);
/* for each successive term */
for (int termNum=1;termNum<numTerms;termNum++)
{
/* multiply the power matrix by the non-power matrix */
powPoleMat *= poleMat;
/* power of t/n! times coefficient, with alternating sign!! */
result += powPoleMat.rowSum(sz) * ( 1-2*(termNum%2) )
* pow(t,termNum+sz)/fact(termNum+sz);
}
return result;
}
int small(double *d, double t, int rank)
{
double max=0;
/* for each pole in the problem */
for (int poleNum=0;poleNum<rank;poleNum++)
/* determine the larges pole */
max = d[poleNum]>max?d[poleNum]:max;
int n=MAXNUMEXPTERMS;
/* using a defined maximum number of terms, if the last term results
* in a correction which is too large */
if (pow(rank*max*t,n)*fact(rank-1)/(n*fact(n+rank-1)) > MAXEXPTOL)
/* return the maximum number of terms + 1
* to be used to indicate that a series expansion will not work */
return MAXNUMEXPTERMS+1;
/* arrive at a VERY rough approximation for number of terms by splitting
* guess in half */
/* for each guess at the number of terms */
for (;n>0;n/=2)
{
/* if the correction is too large */
if (pow(rank*max*t,n)*fact(rank-1)/(n*fact(n+rank-1))>MAXEXPTOL)
/* return the previous guess */
return 2*n;
}
/* return the last guess (must be 1 ... VERY unlikely ) */
return n;
}
double loopSoln(int row, int col, double *P, double *d, double t)
{
double result = 1;
int idx;
for (idx=col;idx<row;idx++)
result *= P[idx+1];
int numExpansionTerms = small(d,t,row-col+1);
if (numExpansionTerms>MAXNUMEXPTERMS)
result *= laplaceInverse(row, col, d, t);
else
result *= laplaceExpansion(row, col, d, t, numExpansionTerms);
return result;
}
<commit_msg>Make sure that small() compares correct poles [col..row] rather than first (row-col+1) poles.<commit_after>#include "alara.h"
#include "Matrix.h"
/* this is used to determine how many terms are needed in the expansion */
#define MAXEXPTOL 1e-15
/* This is the maximum number of terms allowed for the expansion method
* If more are needed, the inversion method is used */
#define MAXNUMEXPTERMS 15
/* This is used to determine if poles are degenerate. Loops should
* generate poles which are exactly the same, but poles with small
* relative differences may act as degeneracies anyway */
#define SMALL_REL_DIFF 1e-8
/* routine for to calculate factorial */
double fact(int i)
{
double result=1;
while (i>1) result *= i--;
return result;
}
double bateman(int row, int col, double* P, double* d, double t)
{
if (row == col)
/* if this is on the diagonal,
* simple exponential decay */
return exp(-d[col]*t);
if (d[col] == 0)
/* if the isotope at this rank=col has no destruction,
* the whole column is empty ! (except the diagonal)
* Note: this is only possible when calling from a decay matrix sol'n
*/
return 0;
double result, sum, sumInc, den;
int term, denTerm;
result = 1;
sum = 0;
sumInc = 0;
for (term=col;term<row;term++)
{
/* multiplicative increment of normalization */
result *= P[term+1];
if (result == 0)
/* if there is no production path between the isotopes at
* row and col, this element is empty
* Note: this is only possible when calling from a decay matrix sol'n
*/
return 0;
/* set denominator element based on Laplace root: d[term]
* (traditional analytic inverse Laplace transform) */
den = 1;
for (denTerm=col;denTerm<term;denTerm++)
den *= (d[denTerm]-d[term]);
for (denTerm++;denTerm<=row;denTerm++)
den *= (d[denTerm]-d[term]);
/* set numerator element based on Laplace root: d[term] */
sumInc = expm1(-d[term]*t)-expm1(-d[row]*t);
/* add element based on Laplace root: d[term] */
sum += sumInc/den;
}
/* multiply normalization by sum of Laplace inverse terms */
result *= sum;
return result;
};
double dGn(int idx, double *pole, int *mult, int numPoles, int termNum)
{
int pNum, pwr;
double invPwrSum,result = 0;
if (termNum==0) /* End Condition - 0th derivative */
/* return inverse product of pole-otherPoles */
{
result = 1;
/* all poles before the current pole */
for (pNum=0; pNum<idx; pNum++)
result /= pow( pole[pNum] - pole[idx] , mult[pNum] );
/* all poles after the current pole */
for (pNum++; pNum<numPoles; pNum++)
result /= pow( pole[pNum] - pole[idx] , mult[pNum] );
}
else
for (pwr=termNum;pwr>0;pwr--)
{
invPwrSum = 0;
/* all poles before the current pole */
for (pNum=0; pNum<idx; pNum++)
invPwrSum += mult[pNum] * pow( pole[pNum]-pole[idx] , -pwr );
/* all poles after the current pole */
for (pNum++; pNum<numPoles; pNum++)
invPwrSum += mult[pNum] * pow( pole[pNum]-pole[idx] , -pwr );
/* recursively add terms */
result += -2*(pwr%2 -.5) * (fact(termNum-1)/fact(termNum-pwr))
* invPwrSum * dGn(idx,pole,mult,numPoles,termNum-pwr);
}
return result;
}
double laplaceInverse(int row, int col, double *d, double t)
{
int idx, checkIdx, multCnt;
int numPoles = 0;
int *mult = new int[row-col+1];
double *pole = new double[row-col+1];
double poleResult, result;
if (row == col)
/* if this is on the diagonal,
* simple exponential decay */
return exp(-d[col]*t);
/* index all the poles with the multiplicities */
for (idx = col;idx<=row;idx++)
{
for (checkIdx=0;checkIdx<numPoles;checkIdx++)
if ( fabs((d[idx]-pole[checkIdx]))<SMALL_REL_DIFF*d[idx] )
{
mult[checkIdx]++;
break;
}
if (checkIdx == numPoles)
{
pole[checkIdx] = d[idx];
mult[checkIdx] = 1;
numPoles++;
}
}
/* perform recursive analytic Laplace inversion */
for (idx=0;idx<numPoles;idx++)
{
poleResult = 0;
for (multCnt=mult[idx];multCnt>0;multCnt--)
poleResult += dGn(idx, pole, mult, numPoles, mult[idx] - multCnt)
* pow(t,multCnt-1)
/ fact(multCnt-1)
/ fact(mult[idx]-multCnt) ;
result += poleResult * exp(-pole[idx]*t);
}
return result;
}
double laplaceExpansion(int row, int col, double *d, double t, int numTerms)
{
int sz = row-col;
double result;
if (row == col)
/* if this is on the diagonal,
* simple exponential decay */
return exp(-d[col]*t);
/* initialize matrix with destruction rates */
Matrix poleMat = Matrix::Triangle(d,sz+1);
Matrix powPoleMat = Matrix::Identity(sz+1);
/* zeroth term is simply the correct power of t/n! */
result = pow(t,sz)/fact(sz);
/* for each successive term */
for (int termNum=1;termNum<numTerms;termNum++)
{
/* multiply the power matrix by the non-power matrix */
powPoleMat *= poleMat;
/* power of t/n! times coefficient, with alternating sign!! */
result += powPoleMat.rowSum(sz) * ( 1-2*(termNum%2) )
* pow(t,termNum+sz)/fact(termNum+sz);
}
return result;
}
int small(double *d, double t, int col, int row)
{
int rank = row-col+1;
double max=0;
/* for each pole in the problem */
for (int poleNum=col;poleNum<=row;poleNum++)
/* determine the larges pole */
max = d[poleNum]>max?d[poleNum]:max;
int n=MAXNUMEXPTERMS;
/* using a defined maximum number of terms, if the last term results
* in a correction which is too large */
if (pow(rank*max*t,n)*fact(rank-1)/(n*fact(n+rank-1)) > MAXEXPTOL)
/* return the maximum number of terms + 1
* to be used to indicate that a series expansion will not work */
return MAXNUMEXPTERMS+1;
/* arrive at a VERY rough approximation for number of terms by splitting
* guess in half */
/* for each guess at the number of terms */
for (;n>0;n/=2)
{
/* if the correction is too large */
if (pow(rank*max*t,n)*fact(rank-1)/(n*fact(n+rank-1))>MAXEXPTOL)
/* return the previous guess */
return 2*n;
}
/* return the last guess (must be 1 ... VERY unlikely ) */
return n;
}
double loopSoln(int row, int col, double *P, double *d, double t)
{
double result = 1;
int idx;
for (idx=col;idx<row;idx++)
result *= P[idx+1];
int numExpansionTerms = small(d,t,col,row);
if (numExpansionTerms>MAXNUMEXPTERMS)
result *= laplaceInverse(row, col, d, t);
else
result *= laplaceExpansion(row, col, d, t, numExpansionTerms);
return result;
}
<|endoftext|>
|
<commit_before>#include "Utility.h"
#include <vector>
#include <random>
#include <chrono>
#include <fstream>
#include <algorithm>
#include <string>
#include <cctype>
#include <iostream>
namespace String
{
namespace
{
const auto whitespace = " \t\n";
}
}
std::vector<std::string> String::split(const std::string& s, const std::string& delim, size_t count)
{
std::vector<std::string> result;
size_t start_index = 0;
size_t end_index = 0;
size_t split_count = 0;
while(end_index < s.size() && split_count < count)
{
end_index = (delim.empty() ?
s.find_first_of(" \t\n", start_index) :
s.find(delim, start_index));
result.push_back(s.substr(start_index, end_index-start_index));
if(end_index == std::string::npos)
{
start_index = std::string::npos;
}
else
{
start_index = end_index + (delim.empty() ? 1 : delim.size());
}
++split_count;
}
if(start_index < s.size())
{
result.push_back(s.substr(start_index));
}
if(delim.empty())
{
auto it = result.begin();
while(it != result.end())
{
if((*it).empty())
{
it = result.erase(it);
}
else
{
(*it) = String::trim_outer_whitespace(*it);
++it;
}
}
}
return result;
}
bool String::starts_with(const std::string& s, const std::string& beginning)
{
if(beginning.size() > s.size())
{
return false;
}
return std::equal(beginning.begin(), beginning.end(), s.begin());
}
bool String::starts_with(const std::string& s, char beginning)
{
return s[0] == beginning;
}
std::string String::consolidate_inner_whitespace(const std::string& s)
{
size_t start = s.find_first_not_of(whitespace);
auto initial_whitespace = s.substr(0, start);
size_t last_non_whitespace = s.find_last_not_of(whitespace);
std::string final_whitespace;
if(last_non_whitespace != std::string::npos)
{
final_whitespace = s.substr(last_non_whitespace + 1);
}
std::string result;
while(true)
{
auto end = s.find_first_of(whitespace, start);
// [start, end) is all non-whitespace
if( ! result.empty())
{
result += " ";
}
result += s.substr(start, end - start);
start = s.find_first_not_of(whitespace, end);
if(start == std::string::npos)
{
start = end; // only whitespace left
break;
}
}
return initial_whitespace + result + final_whitespace;
}
std::string String::trim_outer_whitespace(const std::string& s)
{
auto text_start = s.find_first_not_of(whitespace);
if(text_start == std::string::npos)
{
return std::string{};
}
auto text_end = s.find_last_not_of(whitespace);
if(text_end == std::string::npos)
{
return s.substr(text_start);
}
return s.substr(text_start, text_end - text_start + 1);
}
std::string String::remove_extra_whitespace(const std::string& s)
{
return trim_outer_whitespace(consolidate_inner_whitespace(s));
}
std::string String::strip_comments(const std::string& str, char comment)
{
return trim_outer_whitespace(str.substr(0, str.find(comment)));
}
std::string String::strip_block_comment(const std::string& str, char start, char end)
{
auto start_comment_index = str.find(start);
auto end_comment_index = str.find(end);
if(start_comment_index == std::string::npos || end_comment_index == std::string::npos)
{
return consolidate_inner_whitespace(trim_outer_whitespace(str));
}
auto first_part = str.substr(0, start_comment_index);
auto last_part = str.substr(end_comment_index + 1);
return strip_block_comment(first_part + " " + last_part, start, end);
}
std::string String::lowercase(std::string s)
{
std::transform(s.begin(), s.end(), s.begin(), [](char c) -> char { return std::tolower(c); });
return s;
}
int Random::random_integer(int min, int max)
{
thread_local static std::mt19937_64 generator(std::random_device{}());
using uid = std::uniform_int_distribution<int>;
thread_local static auto dist = uid{};
return dist(generator, uid::param_type{min, max});
}
double Random::random_normal(double standard_deviation)
{
thread_local static std::mt19937_64 generator(std::random_device{}());
using nd = std::normal_distribution<double>;
thread_local static auto dist = nd{};
return dist(generator, nd::param_type{0.0, standard_deviation});
}
double Random::random_real(double min, double max)
{
thread_local static std::mt19937_64 generator(std::random_device{}());
using urd = std::uniform_real_distribution<double>;
thread_local static auto dist = urd{};
return dist(generator, urd::param_type{min, max});
}
bool Random::coin_flip()
{
return success_probability(0.5);
}
bool Random::success_probability(double probability)
{
return random_real(0.0, 1.0) < probability;
}
// Mean moves left in game given that a number of moves have been made already.
double Math::average_moves_left(double mean_moves, double width, size_t moves_so_far)
{
// Assumes the number of moves in a game has a log-normal distribution.
//
// A = Sum(x = moves_so_far + 1 to infinity) P(x)*x = average number of moves
// given game has already progressed
// moves_so_far
//
// B = Sum(x = moves_so_far + 1 to infinity) P(x) = renormalization of P(x) for a
// truncated range
auto M = std::log(mean_moves);
auto S = width;
auto S2 = std::pow(S, 2);
auto Sr2 = S*std::sqrt(2);
auto ln_x = std::log(moves_so_far);
auto A = std::exp(M + S2/2)*(1 + std::erf((M + S2 - ln_x)/Sr2));
auto B = 1 + std::erf((M-ln_x)/Sr2);
auto expected_mean = A/B;
return expected_mean - moves_so_far;
}
Configuration_File::Configuration_File(const std::string& file_name)
{
std::ifstream ifs(file_name);
std::string line;
while(std::getline(ifs, line))
{
line = String::strip_comments(line, '#');
if(line.empty())
{
continue;
}
if( ! String::contains(line, '='))
{
throw std::runtime_error("Configuration file lines must be of form \"Name = Value\"\n" + line);
}
auto line_split = String::split(line, "=", 1);
auto parameter = String::lowercase(String::remove_extra_whitespace(line_split[0]));
parameters[parameter] = String::trim_outer_whitespace(line_split[1]);
}
}
std::string Configuration_File::get_text(const std::string& parameter) const
{
try
{
return parameters.at(parameter);
}
catch(const std::out_of_range&)
{
for(const auto& key_value : parameters)
{
std::cerr << "\"" << key_value.first << "\" --> \"" << key_value.second << "\"" << std::endl;
}
throw std::runtime_error("Configuration parameter not found: " + parameter);
}
}
double Configuration_File::get_number(const std::string& parameter) const
{
try
{
return std::stod(get_text(parameter));
}
catch(const std::invalid_argument&)
{
throw std::runtime_error("Invalid number for \"" + parameter + "\" : " + get_text(parameter));
}
}
std::ofstream Scoped_Stopwatch::out_file;
std::mutex Scoped_Stopwatch::write_lock;
Scoped_Stopwatch::Scoped_Stopwatch(const std::string& name) :
place_name(name),
start_time(std::chrono::steady_clock::now()),
stopped(false)
{
}
Scoped_Stopwatch::~Scoped_Stopwatch()
{
stop();
}
void Scoped_Stopwatch::stop()
{
auto end_time = std::chrono::steady_clock::now();
if(stopped)
{
return;
}
std::lock_guard<std::mutex> write_lock_guard(write_lock);
if( ! out_file.is_open())
{
out_file.open("timings.txt");
}
out_file << place_name << "|"
<< std::chrono::duration_cast<std::chrono::duration<double>>
(end_time - start_time).count()
<< '\n';
stopped = true;
}
void Scoped_Stopwatch::add_info(const std::string& info)
{
place_name += info;
}
<commit_msg>Minor fixes to Utility.cpp<commit_after>#include "Utility.h"
#include <vector>
#include <random>
#include <chrono>
#include <fstream>
#include <algorithm>
#include <string>
#include <cctype>
#include <iostream>
#include <cmath>
namespace String
{
namespace
{
const auto whitespace = " \t\n";
}
}
std::vector<std::string> String::split(const std::string& s, const std::string& delim, size_t count)
{
std::vector<std::string> result;
size_t start_index = 0;
size_t end_index = 0;
size_t split_count = 0;
while(end_index < s.size() && split_count < count)
{
end_index = (delim.empty() ?
s.find_first_of(" \t\n", start_index) :
s.find(delim, start_index));
result.push_back(s.substr(start_index, end_index-start_index));
if(end_index == std::string::npos)
{
start_index = std::string::npos;
}
else
{
start_index = end_index + (delim.empty() ? 1 : delim.size());
}
++split_count;
}
if(start_index < s.size())
{
result.push_back(s.substr(start_index));
}
if(delim.empty())
{
auto it = result.begin();
while(it != result.end())
{
if((*it).empty())
{
it = result.erase(it);
}
else
{
(*it) = String::trim_outer_whitespace(*it);
++it;
}
}
}
return result;
}
bool String::starts_with(const std::string& s, const std::string& beginning)
{
if(beginning.size() > s.size())
{
return false;
}
return std::equal(beginning.begin(), beginning.end(), s.begin());
}
bool String::starts_with(const std::string& s, char beginning)
{
return s[0] == beginning;
}
std::string String::consolidate_inner_whitespace(const std::string& s)
{
size_t start = s.find_first_not_of(whitespace);
auto initial_whitespace = s.substr(0, start);
size_t last_non_whitespace = s.find_last_not_of(whitespace);
std::string final_whitespace;
if(last_non_whitespace != std::string::npos)
{
final_whitespace = s.substr(last_non_whitespace + 1);
}
std::string result;
while(true)
{
auto end = s.find_first_of(whitespace, start);
// [start, end) is all non-whitespace
if( ! result.empty())
{
result += " ";
}
result += s.substr(start, end - start);
start = s.find_first_not_of(whitespace, end);
if(start == std::string::npos)
{
start = end; // only whitespace left
break;
}
}
return initial_whitespace + result + final_whitespace;
}
std::string String::trim_outer_whitespace(const std::string& s)
{
auto text_start = s.find_first_not_of(whitespace);
if(text_start == std::string::npos)
{
return std::string{};
}
auto text_end = s.find_last_not_of(whitespace);
if(text_end == std::string::npos)
{
return s.substr(text_start);
}
return s.substr(text_start, text_end - text_start + 1);
}
std::string String::remove_extra_whitespace(const std::string& s)
{
return trim_outer_whitespace(consolidate_inner_whitespace(s));
}
std::string String::strip_comments(const std::string& str, char comment)
{
return trim_outer_whitespace(str.substr(0, str.find(comment)));
}
std::string String::strip_block_comment(const std::string& str, char start, char end)
{
auto start_comment_index = str.find(start);
auto end_comment_index = str.find(end);
if(start_comment_index == std::string::npos || end_comment_index == std::string::npos)
{
return consolidate_inner_whitespace(trim_outer_whitespace(str));
}
auto first_part = str.substr(0, start_comment_index);
auto last_part = str.substr(end_comment_index + 1);
return strip_block_comment(first_part + " " + last_part, start, end);
}
std::string String::lowercase(std::string s)
{
std::transform(s.begin(), s.end(), s.begin(), [](char c) -> char { return std::tolower(c); });
return s;
}
int Random::random_integer(int min, int max)
{
thread_local static std::mt19937_64 generator(std::random_device{}());
using uid = std::uniform_int_distribution<int>;
thread_local static auto dist = uid{};
return dist(generator, uid::param_type{min, max});
}
double Random::random_normal(double standard_deviation)
{
thread_local static std::mt19937_64 generator(std::random_device{}());
using nd = std::normal_distribution<double>;
thread_local static auto dist = nd{};
return dist(generator, nd::param_type{0.0, standard_deviation});
}
double Random::random_real(double min, double max)
{
thread_local static std::mt19937_64 generator(std::random_device{}());
using urd = std::uniform_real_distribution<double>;
thread_local static auto dist = urd{};
return dist(generator, urd::param_type{min, max});
}
bool Random::coin_flip()
{
return success_probability(0.5);
}
bool Random::success_probability(double probability)
{
return random_real(0.0, 1.0) < probability;
}
// Mean moves left in game given that a number of moves have been made already.
double Math::average_moves_left(double mean_moves, double width, size_t moves_so_far)
{
// Assumes the number of moves in a game has a log-normal distribution.
//
// A = Sum(x = moves_so_far + 1 to infinity) P(x)*x = average number of moves
// given game has already progressed
// moves_so_far
//
// B = Sum(x = moves_so_far + 1 to infinity) P(x) = renormalization of P(x) for a
// truncated range
//
// The calculations below for A and B use integrals on continuous functions as a
// faster approximation.
auto M = std::log(mean_moves);
auto S = width;
auto S2 = std::pow(S, 2);
auto Sr2 = S*std::sqrt(2);
auto ln_x = std::log(moves_so_far);
auto A = std::exp(M + S2/2)*(1 + std::erf((M + S2 - ln_x)/Sr2));
auto B = 1 + std::erf((M-ln_x)/Sr2);
auto expected_mean = A/B;
return expected_mean - moves_so_far;
}
Configuration_File::Configuration_File(const std::string& file_name)
{
std::ifstream ifs(file_name);
std::string line;
while(std::getline(ifs, line))
{
line = String::strip_comments(line, '#');
if(line.empty())
{
continue;
}
if( ! String::contains(line, '='))
{
throw std::runtime_error("Configuration file lines must be of form \"Name = Value\"\n" + line);
}
auto line_split = String::split(line, "=", 1);
auto parameter = String::lowercase(String::remove_extra_whitespace(line_split[0]));
parameters[parameter] = String::trim_outer_whitespace(line_split[1]);
}
}
std::string Configuration_File::get_text(const std::string& parameter) const
{
try
{
return parameters.at(parameter);
}
catch(const std::out_of_range&)
{
for(const auto& key_value : parameters)
{
std::cerr << "\"" << key_value.first << "\" --> \"" << key_value.second << "\"" << std::endl;
}
throw std::runtime_error("Configuration parameter not found: " + parameter);
}
}
double Configuration_File::get_number(const std::string& parameter) const
{
try
{
return std::stod(get_text(parameter));
}
catch(const std::invalid_argument&)
{
throw std::runtime_error("Invalid number for \"" + parameter + "\" : " + get_text(parameter));
}
}
std::ofstream Scoped_Stopwatch::out_file;
std::mutex Scoped_Stopwatch::write_lock;
Scoped_Stopwatch::Scoped_Stopwatch(const std::string& name) :
place_name(name),
start_time(std::chrono::steady_clock::now()),
stopped(false)
{
}
Scoped_Stopwatch::~Scoped_Stopwatch()
{
stop();
}
void Scoped_Stopwatch::stop()
{
auto end_time = std::chrono::steady_clock::now();
if(stopped)
{
return;
}
std::lock_guard<std::mutex> write_lock_guard(write_lock);
if( ! out_file.is_open())
{
out_file.open("timings.txt");
}
out_file << place_name << "|"
<< std::chrono::duration_cast<std::chrono::duration<double>>
(end_time - start_time).count()
<< '\n';
stopped = true;
}
void Scoped_Stopwatch::add_info(const std::string& info)
{
place_name += info;
}
<|endoftext|>
|
<commit_before>// For faster build
#include "marisa/trie.cc"
#include "marisa/agent.cc"
#include "marisa/grimoire/io/reader.cc"
#include "marisa/grimoire/io/writer.cc"
#include "marisa/grimoire/io/mapper.cc"
#include "marisa/grimoire/trie/louds-trie.cc"
#include "marisa/grimoire/trie/tail.cc"
#include "marisa/grimoire/vector/bit-vector.cc"
#include "marisa/keyset.cc"
<commit_msg>Add comments to marisa.cc for node.<commit_after>// For faster build
// Keep include order for VS compatibility.
#include "marisa/trie.cc"
// 1
#include "marisa/agent.cc"
// 2
#include "marisa/grimoire/io/reader.cc"
#include "marisa/grimoire/io/writer.cc"
// 3
#include "marisa/grimoire/io/mapper.cc"
#include "marisa/grimoire/trie/louds-trie.cc"
#include "marisa/grimoire/trie/tail.cc"
#include "marisa/grimoire/vector/bit-vector.cc"
#include "marisa/keyset.cc"
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014, Julien Bernard
*
* 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 "Rules.h"
#include <cassert>
#include <cstdio>
Rules::Rules(const Racket& lft, const Racket& rgt, Ball& ball)
: l(&lft), r(&rgt), b(&ball)
, m_l_points(0), m_r_points(0) {
assert(lft.isOnLeft() && rgt.isOnRight());
}
int Rules::priority() const {
return 1;
}
static bool isTouchingX(const Ball& ball, const Racket& racket) {
float dx = std::abs(ball.getPosition().x - racket.getPosition().x);
return dx < Ball::RADIUS + Racket::WIDTH / 2;
}
static bool isTouchingY(const Ball& ball, const Racket& racket) {
float dy = std::abs(ball.getPosition().y - racket.getPosition().y);
return dy < Racket::HEIGHT / 2;
}
static constexpr float PI = 3.14159265358979323846f;
static float computeNewAngle(const Ball& ball, const Racket& racket) {
float dy = ball.getPosition().y - racket.getPosition().y;
return 0.7 * dy / Racket::HEIGHT * PI;
}
void Rules::update(float dt) {
static constexpr float X_LIMIT = Ground::WIDTH / 2 - Ball::RADIUS;
sf::Vector2f velocity = b->getVelocity();
auto position = b->getPosition();
if (velocity.x > 0) {
if (position.x < r->getPosition().x && isTouchingX(*b, *r) && isTouchingY(*b, *r)) {
float angle = computeNewAngle(*b, *r);
velocity.x = std::cos(PI - angle) * Ball::VELOCITY;
velocity.y = std::sin(PI - angle) * Ball::VELOCITY;
// velocity.x = -velocity.x;
}
if (position.x > X_LIMIT) {
m_l_points++;
velocity.x = -velocity.x;
b->resetPosition();
}
} else {
if (position.x > l->getPosition().x && isTouchingX(*b, *l) && isTouchingY(*b, *l)) {
float angle = computeNewAngle(*b, *l);
velocity.x = std::cos(angle) * Ball::VELOCITY;
velocity.y = std::sin(angle) * Ball::VELOCITY;
// velocity.x = -velocity.x;
}
if (position.x < - X_LIMIT) {
m_r_points++;
velocity.x = -velocity.x;
b->resetPosition();
}
}
b->setVelocity(velocity);
}
static const char digits[10][5][4] = {
{
" ##",
"# #",
"# #",
"# #",
"## ",
},
{
" # ",
" # ",
" # ",
" # ",
" # ",
},
{
"## ",
" #",
" # ",
"# ",
"###",
},
{
"###",
" #",
" ##",
" #",
"###",
},
{
"# ",
"# ",
"# #",
"###",
" #",
},
{
"###",
"# ",
"###",
" #",
"## ",
},
{
"# ",
"# ",
"###",
"# #",
"###",
},
{
"###",
" #",
" #",
" #",
" #",
},
{
"###",
"# #",
"###",
"# #",
"###",
},
{
"###",
"# #",
"###",
" #",
" #",
},
};
static void displayDigit(unsigned d, const sf::Vector2f& position, sf::RenderWindow& window) {
assert(0 <= d && d <= 9);
static constexpr float WIDTH = 1.3f;
static constexpr float HEIGHT = 2.0f;
sf::RectangleShape shape({ WIDTH, HEIGHT });
shape.setOrigin(WIDTH / 2, HEIGHT / 2);
shape.setFillColor(sf::Color::White);
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 3; ++j) {
if (digits[d][i][j] == '#') {
shape.setPosition(position.x + (j - 1) * WIDTH, position.y + (i - 2) * HEIGHT);
window.draw(shape);
}
}
}
}
void Rules::render(sf::RenderWindow& window) {
static constexpr float HI_X = 85.0f;
static constexpr float LO_X = 90.0f;
static constexpr float Y = 40.0f;
displayDigit((m_r_points / 10) % 10, { HI_X, -Y }, window);
displayDigit(m_r_points % 10, { LO_X, -Y }, window);
displayDigit((m_l_points / 10) % 10, { -LO_X, -Y }, window);
displayDigit(m_l_points % 10, { - HI_X, -Y }, window);
}
<commit_msg>remove unnecessary header<commit_after>/*
* Copyright (c) 2014, Julien Bernard
*
* 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 "Rules.h"
#include <cassert>
Rules::Rules(const Racket& lft, const Racket& rgt, Ball& ball)
: l(&lft), r(&rgt), b(&ball)
, m_l_points(0), m_r_points(0) {
assert(lft.isOnLeft() && rgt.isOnRight());
}
int Rules::priority() const {
return 1;
}
static bool isTouchingX(const Ball& ball, const Racket& racket) {
float dx = std::abs(ball.getPosition().x - racket.getPosition().x);
return dx < Ball::RADIUS + Racket::WIDTH / 2;
}
static bool isTouchingY(const Ball& ball, const Racket& racket) {
float dy = std::abs(ball.getPosition().y - racket.getPosition().y);
return dy < Racket::HEIGHT / 2;
}
static constexpr float PI = 3.14159265358979323846f;
static float computeNewAngle(const Ball& ball, const Racket& racket) {
float dy = ball.getPosition().y - racket.getPosition().y;
return 0.7 * dy / Racket::HEIGHT * PI;
}
void Rules::update(float dt) {
static constexpr float X_LIMIT = Ground::WIDTH / 2 - Ball::RADIUS;
sf::Vector2f velocity = b->getVelocity();
auto position = b->getPosition();
if (velocity.x > 0) {
if (position.x < r->getPosition().x && isTouchingX(*b, *r) && isTouchingY(*b, *r)) {
float angle = computeNewAngle(*b, *r);
velocity.x = std::cos(PI - angle) * Ball::VELOCITY;
velocity.y = std::sin(PI - angle) * Ball::VELOCITY;
// velocity.x = -velocity.x;
}
if (position.x > X_LIMIT) {
m_l_points++;
velocity.x = -velocity.x;
b->resetPosition();
}
} else {
if (position.x > l->getPosition().x && isTouchingX(*b, *l) && isTouchingY(*b, *l)) {
float angle = computeNewAngle(*b, *l);
velocity.x = std::cos(angle) * Ball::VELOCITY;
velocity.y = std::sin(angle) * Ball::VELOCITY;
// velocity.x = -velocity.x;
}
if (position.x < - X_LIMIT) {
m_r_points++;
velocity.x = -velocity.x;
b->resetPosition();
}
}
b->setVelocity(velocity);
}
static const char digits[10][5][4] = {
{
" ##",
"# #",
"# #",
"# #",
"## ",
},
{
" # ",
" # ",
" # ",
" # ",
" # ",
},
{
"## ",
" #",
" # ",
"# ",
"###",
},
{
"###",
" #",
" ##",
" #",
"###",
},
{
"# ",
"# ",
"# #",
"###",
" #",
},
{
"###",
"# ",
"###",
" #",
"## ",
},
{
"# ",
"# ",
"###",
"# #",
"###",
},
{
"###",
" #",
" #",
" #",
" #",
},
{
"###",
"# #",
"###",
"# #",
"###",
},
{
"###",
"# #",
"###",
" #",
" #",
},
};
static void displayDigit(unsigned d, const sf::Vector2f& position, sf::RenderWindow& window) {
assert(0 <= d && d <= 9);
static constexpr float WIDTH = 1.3f;
static constexpr float HEIGHT = 2.0f;
sf::RectangleShape shape({ WIDTH, HEIGHT });
shape.setOrigin(WIDTH / 2, HEIGHT / 2);
shape.setFillColor(sf::Color::White);
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 3; ++j) {
if (digits[d][i][j] == '#') {
shape.setPosition(position.x + (j - 1) * WIDTH, position.y + (i - 2) * HEIGHT);
window.draw(shape);
}
}
}
}
void Rules::render(sf::RenderWindow& window) {
static constexpr float HI_X = 85.0f;
static constexpr float LO_X = 90.0f;
static constexpr float Y = 40.0f;
displayDigit((m_r_points / 10) % 10, { HI_X, -Y }, window);
displayDigit(m_r_points % 10, { LO_X, -Y }, window);
displayDigit((m_l_points / 10) % 10, { -LO_X, -Y }, window);
displayDigit(m_l_points % 10, { - HI_X, -Y }, window);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: TableFieldControl.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2005-09-08 16:41:26 $
*
* 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 DBAUI_TABLEFIELDCONTROL_HXX
#include "TableFieldControl.hxx"
#endif
#ifndef DBUI_TABLECONTROLLER_HXX
#include "TableController.hxx"
#endif
#ifndef DBAUI_TABLEDESIGNVIEW_HXX
#include "TableDesignView.hxx"
#endif
#ifndef DBAUI_TABLEEDITORCONTROL_HXX
#include "TEditControl.hxx"
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef DBAUI_TYPEINFO_HXX
#include "TypeInfo.hxx"
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::sdbc;
using namespace dbaui;
OTableFieldControl::OTableFieldControl( Window* pParent, OTableDesignHelpBar* pHelpBar) :OFieldDescControl(pParent,pHelpBar)
{
}
//------------------------------------------------------------------
void OTableFieldControl::CellModified(long nRow, sal_uInt16 nColId )
{
GetCtrl()->CellModified(nRow,nColId);
}
//------------------------------------------------------------------
OTableEditorCtrl* OTableFieldControl::GetCtrl() const
{
OTableDesignView* pDesignWin = static_cast<OTableDesignView*>(GetParent()->GetParent()->GetParent()->GetParent());
OSL_ENSURE(pDesignWin,"no view!");
return pDesignWin->GetEditorCtrl();
}
//------------------------------------------------------------------
sal_Bool OTableFieldControl::IsReadOnly()
{
sal_Bool bRead(GetCtrl()->IsReadOnly());
if( !bRead )
{
// Die Spalten einer ::com::sun::star::sdbcx::View knnen nicht verndert werden
Reference<XPropertySet> xTable = GetCtrl()->GetView()->getController()->getTable();
if(xTable.is() && ::comphelper::getString(xTable->getPropertyValue(PROPERTY_TYPE)) == ::rtl::OUString::createFromAscii("VIEW"))
bRead = sal_True;
else
{
OTableRow* pCurRow = GetCtrl()->GetActRow();
if( pCurRow )
bRead = pCurRow->IsReadOnly();
}
}
return bRead;
}
//------------------------------------------------------------------
void OTableFieldControl::ActivateAggregate( EControlType eType )
{
switch(eType)
{
case tpColumnName:
case tpType:
break;
default:
OFieldDescControl::ActivateAggregate(eType);
}
}
//------------------------------------------------------------------
void OTableFieldControl::DeactivateAggregate( EControlType eType )
{
switch(eType)
{
case tpColumnName:
case tpType:
break;
default:
OFieldDescControl::DeactivateAggregate(eType);
}
}
// -----------------------------------------------------------------------------
void OTableFieldControl::SetModified(BOOL bModified)
{
GetCtrl()->GetView()->getController()->setModified(bModified);
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> OTableFieldControl::getConnection()
{
return GetCtrl()->GetView()->getController()->getConnection();
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData> OTableFieldControl::getMetaData()
{
Reference<XConnection> xCon = GetCtrl()->GetView()->getController()->getConnection();
if(!xCon.is())
return NULL;
return xCon->getMetaData();
}
// -----------------------------------------------------------------------------
Reference< XNumberFormatter > OTableFieldControl::GetFormatter() const
{
return GetCtrl()->GetView()->getController()->getNumberFormatter();
}
// -----------------------------------------------------------------------------
TOTypeInfoSP OTableFieldControl::getTypeInfo(sal_Int32 _nPos)
{
return GetCtrl()->GetView()->getController()->getTypeInfo(_nPos);
}
// -----------------------------------------------------------------------------
const OTypeInfoMap* OTableFieldControl::getTypeInfo() const
{
return const_cast<OTableFieldControl*>(this)->GetCtrl()->GetView()->getController()->getTypeInfo();
}
// -----------------------------------------------------------------------------
Locale OTableFieldControl::GetLocale() const
{
return const_cast<OTableFieldControl*>(this)->GetCtrl()->GetView()->getLocale();
}
// -----------------------------------------------------------------------------
sal_Bool OTableFieldControl::isAutoIncrementValueEnabled() const
{
return const_cast<OTableFieldControl*>(this)->GetCtrl()->GetView()->getController()->isAutoIncrementValueEnabled();
}
// -----------------------------------------------------------------------------
::rtl::OUString OTableFieldControl::getAutoIncrementValue() const
{
return const_cast<OTableFieldControl*>(this)->GetCtrl()->GetView()->getController()->getAutoIncrementValue();
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS dba203c (1.9.110); FILE MERGED 2006/04/13 13:57:19 oj 1.9.110.1: hold TableRow now with a shared_ptr<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: TableFieldControl.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2006-05-04 08:51:01 $
*
* 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 DBAUI_TABLEFIELDCONTROL_HXX
#include "TableFieldControl.hxx"
#endif
#ifndef DBUI_TABLECONTROLLER_HXX
#include "TableController.hxx"
#endif
#ifndef DBAUI_TABLEDESIGNVIEW_HXX
#include "TableDesignView.hxx"
#endif
#ifndef DBAUI_TABLEEDITORCONTROL_HXX
#include "TEditControl.hxx"
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef DBAUI_TYPEINFO_HXX
#include "TypeInfo.hxx"
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::sdbc;
using namespace dbaui;
OTableFieldControl::OTableFieldControl( Window* pParent, OTableDesignHelpBar* pHelpBar) :OFieldDescControl(pParent,pHelpBar)
{
}
//------------------------------------------------------------------
void OTableFieldControl::CellModified(long nRow, sal_uInt16 nColId )
{
GetCtrl()->CellModified(nRow,nColId);
}
//------------------------------------------------------------------
OTableEditorCtrl* OTableFieldControl::GetCtrl() const
{
OTableDesignView* pDesignWin = static_cast<OTableDesignView*>(GetParent()->GetParent()->GetParent()->GetParent());
OSL_ENSURE(pDesignWin,"no view!");
return pDesignWin->GetEditorCtrl();
}
//------------------------------------------------------------------
sal_Bool OTableFieldControl::IsReadOnly()
{
sal_Bool bRead(GetCtrl()->IsReadOnly());
if( !bRead )
{
// Die Spalten einer ::com::sun::star::sdbcx::View knnen nicht verndert werden
Reference<XPropertySet> xTable = GetCtrl()->GetView()->getController()->getTable();
if(xTable.is() && ::comphelper::getString(xTable->getPropertyValue(PROPERTY_TYPE)) == ::rtl::OUString::createFromAscii("VIEW"))
bRead = sal_True;
else
{
::boost::shared_ptr<OTableRow> pCurRow = GetCtrl()->GetActRow();
if( pCurRow )
bRead = pCurRow->IsReadOnly();
}
}
return bRead;
}
//------------------------------------------------------------------
void OTableFieldControl::ActivateAggregate( EControlType eType )
{
switch(eType)
{
case tpColumnName:
case tpType:
break;
default:
OFieldDescControl::ActivateAggregate(eType);
}
}
//------------------------------------------------------------------
void OTableFieldControl::DeactivateAggregate( EControlType eType )
{
switch(eType)
{
case tpColumnName:
case tpType:
break;
default:
OFieldDescControl::DeactivateAggregate(eType);
}
}
// -----------------------------------------------------------------------------
void OTableFieldControl::SetModified(BOOL bModified)
{
GetCtrl()->GetView()->getController()->setModified(bModified);
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> OTableFieldControl::getConnection()
{
return GetCtrl()->GetView()->getController()->getConnection();
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData> OTableFieldControl::getMetaData()
{
Reference<XConnection> xCon = GetCtrl()->GetView()->getController()->getConnection();
if(!xCon.is())
return NULL;
return xCon->getMetaData();
}
// -----------------------------------------------------------------------------
Reference< XNumberFormatter > OTableFieldControl::GetFormatter() const
{
return GetCtrl()->GetView()->getController()->getNumberFormatter();
}
// -----------------------------------------------------------------------------
TOTypeInfoSP OTableFieldControl::getTypeInfo(sal_Int32 _nPos)
{
return GetCtrl()->GetView()->getController()->getTypeInfo(_nPos);
}
// -----------------------------------------------------------------------------
const OTypeInfoMap* OTableFieldControl::getTypeInfo() const
{
return const_cast<OTableFieldControl*>(this)->GetCtrl()->GetView()->getController()->getTypeInfo();
}
// -----------------------------------------------------------------------------
Locale OTableFieldControl::GetLocale() const
{
return const_cast<OTableFieldControl*>(this)->GetCtrl()->GetView()->getLocale();
}
// -----------------------------------------------------------------------------
sal_Bool OTableFieldControl::isAutoIncrementValueEnabled() const
{
return const_cast<OTableFieldControl*>(this)->GetCtrl()->GetView()->getController()->isAutoIncrementValueEnabled();
}
// -----------------------------------------------------------------------------
::rtl::OUString OTableFieldControl::getAutoIncrementValue() const
{
return const_cast<OTableFieldControl*>(this)->GetCtrl()->GetView()->getController()->getAutoIncrementValue();
}
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>#include "testApp.h"
#include <iostream.h>
//--------------------------------------------------------------
void testApp::setup(){
ofSetVerticalSync(true);
video.loadMovie( "GoodHair_JFleurantin/Resources/GoodHair_JFleurantin.mov" );
sound.loadSound( "GoodHair_short.mp3" );
// BlurOne.allocate(ofGetWidth(), ofGetHeight());
// BlurTwo.allocate(ofGetWidth(), ofGetHeight());
shader1.load("shaders/pixelate");
// shaderX.load("shaders/blur");
// shaderY.load("shaders/blur2");
kinect.init(false, false); // disable video image (faster fps)
kinect.open();
sound.play();
sound.setVolume(0.8f);
sound.setLoop(true);
video.play();
video.setVolume(0.0f);
point.set(20, 20);
angle = 0;
kinect.setCameraTiltAngle(angle);
}
//--------------------------------------------------------------
void testApp::update(){
ofSoundUpdate;
kinect.update();
video.update();
int currentDepthPixel = 0;
closestValue = 50;
farthestValue = 1000;
unsigned char* depthPixels = kinect.getDepthPixels();
// int sumX = 0;
// int sumY = 0;
// int counter = 0;
//I don't know if the bounds should be the Kinect, Video, or App Window
for(int x = 0; x < kinect.getWidth(); x++){
for(int y = 0; y < kinect.getHeight(); y++){
int i = x + y * kinect.getWidth();
int currentDepthPixel = depthPixels[i];
// int currentDepthPixel = depthPixels[x + y * ofGetWindowWidth()]
if(currentDepthPixel > closestValue && currentDepthPixel < farthestValue){
// save its value
closestValue = currentDepthPixel;
// and save its position (both X and Y coordinates)
// closestX = x;
// closestY = y;
closePixel.x = x;
closePixel.y = y;
}
}
}
cout<<"closestX: "<<closePixel.x<<"\tclosestY: "<<closePixel.y<<"\tclosestZ: "<<closestValue<<endl;
kinectValue(closePixel.x, closePixel.y);
// if(upLeftQuad || lowRightQuad){
// BlurOne.begin();
// video.draw(0, 0, ofGetWindowWidth(), ofGetWindowHeight());
//
// ofSetColor(255);
// for(int y = 0; y<ofGetWindowHeight(); y+=10)
// for(int x=0; x<ofGetWindowWidth(); x+=10) {
// ofRect(x, y, 5, 5);
// }
//
// BlurOne.end();
// }
// if(upLeftQuad || lowRightQuad){
// int iterations = 5;
// for (int i=0; i<iterations; i++){
//
// BlurTwo.begin();
// shaderX.begin();
// shaderX.setUniform1f("amount", point.x);
// BlurOne.draw(0, 0);
// shaderX.end();
// BlurTwo.end();
//
// BlurOne.begin();
// shaderY.begin();
// shaderY.setUniform1f("amount", point.y);
// BlurTwo.draw(0, 0);
// shaderY.end();
// BlurOne.end();
// }
// }
}
//--------------------------------------------------------------
void testApp::draw(){
// if(upLeftQuad || lowRightQuad){
//
// BlurOne.draw(0, 0, ofGetWindowWidth(), ofGetWindowHeight());
// }
//
// if((upRightQuad || lowLeftQuad)){
shader1.begin();
shader1.setUniform2f("sampleDivisor", point.x, point.y);
shader1.setUniform2f("depthPoint", closePixel.x, closePixel.y);
video.draw(0, 0, ofGetWindowWidth(), ofGetWindowHeight());
shader1.end();
// }
//
// if(upLeftQuad || lowRightQuad){
// BlurTwo.draw(0, 0, ofGetWindowWidth(), ofGetWindowHeight());
// }
// ofSetColor(20);
// ofCircle( closePixel.x, closePixel.y, point.x );
}
//--------------------------------------------------------------
void testApp::kinectValue(int cx, int cy){
float dist = ofDist(0, 0, cx, cy);
float max = ofDist(0, 0, ofGetWindowWidth(), ofGetWindowHeight());
float pixelSize = ofMap(dist, 0, max, 1, 50);
point.x = pixelSize;
point.y = pixelSize;
float positionX = ofMap(dist, closePixel.x, 1000, 0, ofGetWindowWidth());
float positionY = ofMap(dist, closePixel.y, 500, 0, ofGetWindowHeight());
// float mapPlayback = (closestValue - 200) * 0.01;
// float playback = ofMap(mapPlayback, 0, .55, 0, 1, true);
//// if(video.getPosition() == 1.0){
//// playback = 0;
//// }
// video.setPosition(playback);
// int counter = 0;
// for (counter; counter < 5; counter++) {
// int playheadAvg += mapPlayback;
//
// } (mapPlayback) {
// <#statements#>
// }
// cout<<"playhead\t"<<mapPlayback<<endl;
quad1 = (positionX/2)-4;
quad2 = (positionX/2)+4;
quad3 = (positionY/2)-4;
quad4 = (positionY/2)+4;
if((cx % 5 == 0) && (cx % 3 != 0)) {
if((closePixel.x > 0 && closePixel.x < quad1) && (closePixel.y > 0 && closePixel.y < quad3)){
upLeftQuad = true;
upRightQuad = false;
lowLeftQuad = false;
lowRightQuad = false;
} else if((closePixel.x > quad2 && closePixel.x < ofGetWindowWidth()) && (closePixel.y > quad4 && closePixel.y < ofGetWindowHeight())){
upLeftQuad = false;
upRightQuad = false;
lowLeftQuad = false;
lowRightQuad = true;
} else if((closePixel.x > 0 && closePixel.x < quad1) && (closePixel.y > quad4 && closePixel.y < ofGetWindowHeight())){
upLeftQuad = false;
upRightQuad = false;
lowLeftQuad = true;
lowRightQuad = false;
}else if((closePixel.x > quad2 && closePixel.x < ofGetWindowWidth()) && (closePixel.y > 0 && closePixel.y < quad3)){
upLeftQuad = false;
upRightQuad = true;
lowLeftQuad = false;
lowRightQuad = false;
}
}
if((cx % 3 == 0) || (cx % 5 != 0)){
if((closePixel.x > 0 && closePixel.x < 510) && (closePixel.y > 0 && closePixel.y < 362)){
upLeftQuad = false;
upRightQuad = true;
lowLeftQuad = false;
lowRightQuad = false;
} else if((closePixel.x > quad2 && closePixel.x < ofGetWindowWidth()) && (closePixel.y > quad4 && closePixel.y < ofGetWindowHeight())){
upLeftQuad = false;
upRightQuad = false;
lowLeftQuad = true;
lowRightQuad = false;
} else if((closePixel.x > 0 && closePixel.x < quad1) && (closePixel.y > quad4 && closePixel.y < ofGetWindowHeight())){
upLeftQuad = false;
upRightQuad = false;
lowLeftQuad = false;
lowRightQuad = true;
}else if((closePixel.x > quad2 && closePixel.x < ofGetWindowWidth()) && (closePixel.y > 0 && closePixel.y < quad3)){
upLeftQuad = true;
upRightQuad = true;
lowLeftQuad = false;
lowRightQuad = false;
}
}
}
//--------------------------------------------------------------
void testApp::exit() {
kinect.setCameraTiltAngle(0); // zero the tilt on exit
kinect.close();
}
//--------------------------------------------------------------
void testApp::keyPressed(int key){
}
//--------------------------------------------------------------
void testApp::keyReleased(int key){
}
//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void testApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void testApp::dragEvent(ofDragInfo dragInfo){
}
<commit_msg>Update testApp.cpp<commit_after>#include "testApp.h"
#include <iostream.h>
//--------------------------------------------------------------
void testApp::setup(){
ofSetVerticalSync(true);
video.loadMovie( "MOVIE.mov" );
sound.loadSound( "SOUND.mp3" );
shader1.load("shaders/pixelate");
kinect.init(false, false);
kinect.open();
sound.play();
sound.setVolume(0.8f);
sound.setLoop(true);
video.play();
video.setVolume(0.0f);
point.set(20, 20);
angle = 0;
kinect.setCameraTiltAngle(angle);
}
//--------------------------------------------------------------
void testApp::update(){
ofSoundUpdate;
kinect.update();
video.update();
int currentDepthPixel = 0;
closestValue = 50;
farthestValue = 1000;
unsigned char* depthPixels = kinect.getDepthPixels();
for(int x = 0; x < kinect.getWidth(); x++){
for(int y = 0; y < kinect.getHeight(); y++){
int i = x + y * kinect.getWidth();
int currentDepthPixel = depthPixels[i];
if(currentDepthPixel > closestValue && currentDepthPixel < farthestValue){
closestValue = currentDepthPixel;
closePixel.x = x;
closePixel.y = y;
}
}
}
kinectValue(closePixel.x, closePixel.y);
}
//--------------------------------------------------------------
void testApp::draw(){
shader1.begin();
shader1.setUniform2f("sampleDivisor", point.x, point.y);
shader1.setUniform2f("depthPoint", closePixel.x, closePixel.y);
video.draw(0, 0, ofGetWindowWidth(), ofGetWindowHeight());
shader1.end();
}
//--------------------------------------------------------------
void testApp::kinectValue(int cx, int cy){
float dist = ofDist(0, 0, cx, cy);
float max = ofDist(0, 0, ofGetWindowWidth(), ofGetWindowHeight());
float pixelSize = ofMap(dist, 0, max, 1, 50);
point.x = pixelSize;
point.y = pixelSize;
float positionX = ofMap(dist, closePixel.x, 1000, 0, ofGetWindowWidth());
float positionY = ofMap(dist, closePixel.y, 500, 0, ofGetWindowHeight());
/*
Mapping playback position
float mapPlayback = (closestValue - 200) * 0.01;
float playback = ofMap(mapPlayback, 0, .55, 0, 1, true);
if(video.getPosition() == 1.0){
playback = 0;
}
video.setPosition(playback);
*/
/*
If swapping between shaders
quad1 = (positionX/2)-4;
quad2 = (positionX/2)+4;
quad3 = (positionY/2)-4;
quad4 = (positionY/2)+4;
if((cx % 5 == 0) && (cx % 3 != 0)) {
if((closePixel.x > 0 && closePixel.x < quad1) && (closePixel.y > 0 && closePixel.y < quad3)){
upLeftQuad = true;
upRightQuad = false;
lowLeftQuad = false;
lowRightQuad = false;
} else if((closePixel.x > quad2 && closePixel.x < ofGetWindowWidth()) && (closePixel.y > quad4 && closePixel.y < ofGetWindowHeight())){
upLeftQuad = false;
upRightQuad = false;
lowLeftQuad = false;
lowRightQuad = true;
} else if((closePixel.x > 0 && closePixel.x < quad1) && (closePixel.y > quad4 && closePixel.y < ofGetWindowHeight())){
upLeftQuad = false;
upRightQuad = false;
lowLeftQuad = true;
lowRightQuad = false;
}else if((closePixel.x > quad2 && closePixel.x < ofGetWindowWidth()) && (closePixel.y > 0 && closePixel.y < quad3)){
upLeftQuad = false;
upRightQuad = true;
lowLeftQuad = false;
lowRightQuad = false;
}
}
if((cx % 3 == 0) || (cx % 5 != 0)){
if((closePixel.x > 0 && closePixel.x < 510) && (closePixel.y > 0 && closePixel.y < 362)){
upLeftQuad = false;
upRightQuad = true;
lowLeftQuad = false;
lowRightQuad = false;
} else if((closePixel.x > quad2 && closePixel.x < ofGetWindowWidth()) && (closePixel.y > quad4 && closePixel.y < ofGetWindowHeight())){
upLeftQuad = false;
upRightQuad = false;
lowLeftQuad = true;
lowRightQuad = false;
} else if((closePixel.x > 0 && closePixel.x < quad1) && (closePixel.y > quad4 && closePixel.y < ofGetWindowHeight())){
upLeftQuad = false;
upRightQuad = false;
lowLeftQuad = false;
lowRightQuad = true;
}else if((closePixel.x > quad2 && closePixel.x < ofGetWindowWidth()) && (closePixel.y > 0 && closePixel.y < quad3)){
upLeftQuad = true;
upRightQuad = true;
lowLeftQuad = false;
lowRightQuad = false;
}
}
*/
}
//--------------------------------------------------------------
void testApp::exit() {
kinect.setCameraTiltAngle(0);
kinect.close();
}
//--------------------------------------------------------------
void testApp::keyPressed(int key){
}
//--------------------------------------------------------------
void testApp::keyReleased(int key){
}
//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void testApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void testApp::dragEvent(ofDragInfo dragInfo){
}
<|endoftext|>
|
<commit_before>#include <cstring>
#include <string>
#include <boost/assign/list_of.hpp>
#include "constants.h"
#include "testnet.h"
static uint8_t TESTNET_PROTOCOL_MAGIC_BYTES[sizeof(PROTOCOL_MAGIC_BYTES)] = { 0xe5, 0xcf, 0x81, 0xdf };
static char const * TESTNET_AUTO_DNS_SEEDS[][2] = { { "t-seed-a", "t-seed-a.neucoin.org" }, { 0, 0 } };
static uint32_t TESTNET_AUTO_IP_SEEDS[] = { 0 };
void ApplyTestnetParameters(void)
{
COIN_PORT = 8742;
RPC_PORT = 8743;
std::memcpy(PROTOCOL_MAGIC_BYTES, &TESTNET_PROTOCOL_MAGIC_BYTES, sizeof(PROTOCOL_MAGIC_BYTES));
AUTO_DNS_SEEDS = TESTNET_AUTO_DNS_SEEDS;
AUTO_IP_SEEDS = TESTNET_AUTO_IP_SEEDS;
PUBKEY_ADDRESS_PREFIX = 65; // 'T'
PRVKEY_ADDRESS_PREFIX = 68; // 'U'
SCRIPT_ADDRESS_PREFIX = 127; // 't'
GENESIS_MERKLE_HASH = hash_t("0xa7fc40033828e0b0aa5f829ad35233efe8a15e5820d31e53d8e865a1c29cf024");
GENESIS_HASH = hash_t("0x000002f38bfabee423e760cbbbd2147984be70a531928b89e64d59531b136944");
GENESIS_IDENT = "06-15-15 :: LFG 887 :: We can still take them out for an overpriced dinner";
GENESIS_TX_TIME = 1345083810;
GENESIS_BLOCK_TIME = 1345084287;
GENESIS_BLOCK_NONCE = 2179980296;
GENESIS_BLOCK_VERSION = 1;
BLOCK_CHECKPOINTS = boost::assign::map_list_of(0, GENESIS_HASH)((8 * WEEK) / (10 * MINUTE) + (8 * WEEK) / (1 * MINUTE), hash_t("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"));
STAKE_MODIFIER_CHECKPOINTS = boost::assign::map_list_of(0, 0xfd11f4e7);
POW_MAX_BLOCK = std::numeric_limits< blockheight_t >::max();
COIN_PREMINE = 0 * COIN;
POW_INITIAL_TARGET = target_t(~uint256(0) >> 20);
POS_INITIAL_TARGET = target_t(~uint256(0) >> 20);
POW_MAX_TARGET = target_t(~uint256(0) >> 20);
POS_MAX_TARGET = target_t(~uint256(0) >> 20);
POW_TARGET_SPACING = 10 * MINUTE / 10;
POS_TARGET_SPACING = 1 * MINUTE / 2;
POW_BLOCK_REWARD = 1141 * COIN;
STAKE_MIN_AGE = 138240 * SECOND / 2;
STAKE_MAX_AGE = 138240 * SECOND / 2;
MODIFIER_INTERVAL_BASE = 200 * MINUTE / 2;
MODIFIER_INTERVAL_RATIO = 18;
STAKE_COIN_STEP = 1 * COIN;
STAKE_AGE_STEP = 1 * DAY / 2;
TARGET_TIMESPAN = 2 * HOUR / 2;
}
<commit_msg>Pushing back end of testnet network<commit_after>#include <cstring>
#include <string>
#include <boost/assign/list_of.hpp>
#include "constants.h"
#include "testnet.h"
static uint8_t TESTNET_PROTOCOL_MAGIC_BYTES[sizeof(PROTOCOL_MAGIC_BYTES)] = { 0xe5, 0xcf, 0x81, 0xdf };
static char const * TESTNET_AUTO_DNS_SEEDS[][2] = { { "t-seed-a", "t-seed-a.neucoin.org" }, { 0, 0 } };
static uint32_t TESTNET_AUTO_IP_SEEDS[] = { 0 };
void ApplyTestnetParameters(void)
{
COIN_PORT = 8742;
RPC_PORT = 8743;
std::memcpy(PROTOCOL_MAGIC_BYTES, &TESTNET_PROTOCOL_MAGIC_BYTES, sizeof(PROTOCOL_MAGIC_BYTES));
AUTO_DNS_SEEDS = TESTNET_AUTO_DNS_SEEDS;
AUTO_IP_SEEDS = TESTNET_AUTO_IP_SEEDS;
PUBKEY_ADDRESS_PREFIX = 65; // 'T'
PRVKEY_ADDRESS_PREFIX = 68; // 'U'
SCRIPT_ADDRESS_PREFIX = 127; // 't'
GENESIS_MERKLE_HASH = hash_t("0xa7fc40033828e0b0aa5f829ad35233efe8a15e5820d31e53d8e865a1c29cf024");
GENESIS_HASH = hash_t("0x000002f38bfabee423e760cbbbd2147984be70a531928b89e64d59531b136944");
GENESIS_IDENT = "06-15-15 :: LFG 887 :: We can still take them out for an overpriced dinner";
GENESIS_TX_TIME = 1345083810;
GENESIS_BLOCK_TIME = 1345084287;
GENESIS_BLOCK_NONCE = 2179980296;
GENESIS_BLOCK_VERSION = 1;
STAKE_MODIFIER_CHECKPOINTS = boost::assign::map_list_of(0, 0xfd11f4e7);
POW_MAX_BLOCK = std::numeric_limits< blockheight_t >::max();
COIN_PREMINE = 0 * COIN;
POW_INITIAL_TARGET = target_t(~uint256(0) >> 20);
POS_INITIAL_TARGET = target_t(~uint256(0) >> 20);
POW_MAX_TARGET = target_t(~uint256(0) >> 20);
POS_MAX_TARGET = target_t(~uint256(0) >> 20);
POW_TARGET_SPACING = 10 * MINUTE / 10;
POS_TARGET_SPACING = 1 * MINUTE / 2;
POW_BLOCK_REWARD = 1141 * COIN;
STAKE_MIN_AGE = 138240 * SECOND / 2;
STAKE_MAX_AGE = 138240 * SECOND / 2;
MODIFIER_INTERVAL_BASE = 200 * MINUTE / 2;
MODIFIER_INTERVAL_RATIO = 18;
STAKE_COIN_STEP = 1 * COIN;
STAKE_AGE_STEP = 1 * DAY / 2;
TARGET_TIMESPAN = 2 * HOUR / 2;
BLOCK_CHECKPOINTS = boost::assign::map_list_of(0, GENESIS_HASH)((8 * WEEK) / POW_TARGET_SPACING + (8 * WEEK) / POS_TARGET_SPACING, hash_t("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"));
}
<|endoftext|>
|
<commit_before>/*
* Transform a TSV format factor graph file and output corresponding binary
* format used in DeepDive
*/
#include "text2bin.h"
#include "binary_format.h"
#include <assert.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdint.h>
#include <stdlib.h>
#include <vector>
namespace dd {
constexpr char field_delim = '\t'; // tsv file delimiter
// read variables and convert to binary format
void load_var(std::string input_filename, std::string output_filename) {
std::ifstream fin(input_filename);
std::ofstream fout(output_filename, std::ios::binary | std::ios::out);
num_variables_t count = 0;
int is_evidence;
uint16_t var_type;
variable_id_t vid;
variable_value_t initial_value;
num_variable_values_t cardinality;
while (fin >> vid >> is_evidence >> initial_value >> var_type >>
cardinality) {
write_be(fout, vid);
write_be<uint8_t>(fout, is_evidence);
write_be(fout, initial_value);
write_be(fout, var_type);
write_be(fout, cardinality);
++count;
}
std::cout << count << std::endl;
}
// convert weights
void load_weight(std::string input_filename, std::string output_filename) {
std::ifstream fin(input_filename);
std::ofstream fout(output_filename, std::ios::binary | std::ios::out);
long count = 0;
int isfixed;
weight_id_t wid;
weight_value_t initial_value;
while (fin >> wid >> isfixed >> initial_value) {
write_be(fout, wid);
write_be<uint8_t>(fout, isfixed);
write_be(fout, initial_value);
++count;
}
std::cout << count << std::endl;
}
static inline long parse_pgarray(
std::istream &input, std::function<void(const std::string &)> parse_element,
long expected_count = -1) {
if (input.peek() == '{') {
input.get();
std::string element;
bool ended = false;
long count = 0;
while (getline(input, element, ',')) {
if (element.at(element.length() - 1) == '}') {
ended = true;
element = element.substr(0, element.length() - 1);
}
parse_element(element);
count++;
if (ended) break;
}
assert(expected_count < 0 || count == expected_count);
return count;
} else {
return -1;
}
}
static inline long parse_pgarray_or_die(
std::istream &input, std::function<void(const std::string &)> parse_element,
long expected_count = -1) {
long count = parse_pgarray(input, parse_element, expected_count);
if (count >= 0) {
return count;
} else {
std::cerr << "Expected an array '{' but found: " << input.get()
<< std::endl;
std::abort();
}
}
// load factors
// wid, vids
void load_factor(std::string input_filename, std::string output_filename,
factor_function_type_t funcid, factor_arity_t arity_expected,
const std::vector<bool> &positives_vec) {
std::ifstream fin(input_filename);
std::ofstream fout(output_filename, std::ios::binary | std::ios::out);
num_edges_t total_edges = 0;
std::vector<variable_id_t> vids;
std::vector<weight_id_t> vals_and_weights; // FIXME separate the two
std::string line;
std::string array_piece;
while (getline(fin, line)) {
std::string field;
istringstream ss(line);
vids.clear();
// factor type
write_be<uint16_t>(fout, funcid);
// variable ids
factor_arity_t arity = 0;
auto parse_variableid = [&vids, &arity,
&total_edges](const std::string &element) {
vids.push_back(atol(element.c_str()));
++total_edges;
++arity;
};
for (factor_arity_t i = 0; i < arity_expected; ++i) {
getline(ss, field, field_delim);
// try parsing as an array first
// FIXME remove this? parsing vid arrays is probably broken since this
// doesn't create a cross product of factors but simply widens the arity
istringstream fieldinput(field);
if (parse_pgarray(fieldinput, parse_variableid) < 0) {
// otherwise, parse it as a single variable
parse_variableid(field);
}
}
write_be(fout, arity);
for (factor_arity_t i = 0; i < vids.size(); ++i) {
write_be(fout, vids[i]);
variable_value_t should_equal_to = positives_vec.at(i) ? 1 : 0;
write_be(fout, should_equal_to);
}
// weight ids
switch (funcid) {
case FUNC_AND_CATEGORICAL: {
vals_and_weights.clear();
// IN Format: NUM_WEIGHTS [VAR1 VAL ID] [VAR2 VAL ID] ... [WEIGHT ID]
// OUT Format: NUM_WEIGHTS [[VAR1_VALi, VAR2_VALi, ..., WEIGHTi]]
// first, the run-length
getline(ss, field, field_delim);
factor_weight_key_t num_weightids = atol(field.c_str());
write_be<uint32_t /*FIXME factor_weight_key_t*/>(fout, num_weightids);
// second, parse var vals for each var
// TODO: hard coding cid length (4) for now
for (factor_arity_t i = 0; i < arity; ++i) {
getline(ss, array_piece, field_delim);
istringstream ass(array_piece);
parse_pgarray_or_die(
ass, [&vals_and_weights](const std::string &element) {
variable_value_t cid = atoi(element.c_str());
vals_and_weights.push_back(cid);
}, num_weightids);
}
// third, parse weights
parse_pgarray_or_die(
ss, [&vals_and_weights](const std::string &element) {
weight_id_t weightid = atol(element.c_str());
vals_and_weights.push_back(weightid);
}, num_weightids);
// fourth, transpose into output format
for (factor_weight_key_t i = 0; i < num_weightids; ++i) {
for (factor_arity_t j = 0; j < arity; ++j) {
variable_value_t cid =
(variable_value_t)vals_and_weights[j * num_weightids + i];
write_be(fout, cid);
}
weight_id_t weightid = vals_and_weights[arity * num_weightids + i];
write_be(fout, weightid);
}
break;
}
default:
// a single weight id
getline(ss, field, field_delim);
weight_id_t weightid = atol(field.c_str());
write_be(fout, weightid);
}
}
std::cout << total_edges << std::endl;
}
// read categorical variable domains and convert to binary format
void load_domain(std::string input_filename, std::string output_filename) {
std::ifstream fin(input_filename);
std::ofstream fout(output_filename, std::ios::binary | std::ios::out);
std::string line;
while (getline(fin, line)) {
istringstream line_input(line);
variable_id_t vid;
num_variable_values_t cardinality;
std::string domain;
assert(line_input >> vid >> cardinality >> domain);
write_be(fout, vid);
write_be(fout, cardinality);
// an array of domain values
istringstream domain_input(domain);
parse_pgarray_or_die(domain_input, [&fout](const std::string &subfield) {
variable_value_t value = atoi(subfield.c_str());
write_be(fout, value);
}, cardinality);
}
}
int text2bin(const CmdParser &args) {
// common arguments
if (args.text2bin_mode == "variable") {
load_var(args.text2bin_input, args.text2bin_output);
} else if (args.text2bin_mode == "weight") {
load_weight(args.text2bin_input, args.text2bin_output);
} else if (args.text2bin_mode == "factor") {
load_factor(args.text2bin_input, args.text2bin_output,
args.text2bin_factor_func_id, args.text2bin_factor_arity,
args.text2bin_factor_positives_or_not);
} else if (args.text2bin_mode == "domain") {
load_domain(args.text2bin_input, args.text2bin_output);
} else {
std::cerr << "Unsupported type" << std::endl;
return 1;
}
return 0;
}
} // namespace dd
<commit_msg>Scrubs some types in text2bin<commit_after>/*
* Transform a TSV format factor graph file and output corresponding binary
* format used in DeepDive
*/
#include "text2bin.h"
#include "binary_format.h"
#include <assert.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdint.h>
#include <stdlib.h>
#include <vector>
namespace dd {
constexpr char field_delim = '\t'; // tsv file delimiter
// read variables and convert to binary format
void load_var(std::string input_filename, std::string output_filename) {
std::ifstream fin(input_filename);
std::ofstream fout(output_filename, std::ios::binary | std::ios::out);
num_variables_t count = 0;
int is_evidence;
uint16_t var_type;
variable_id_t vid;
variable_value_t initial_value;
num_variable_values_t cardinality;
while (fin >> vid >> is_evidence >> initial_value >> var_type >>
cardinality) {
write_be(fout, vid);
write_be<uint8_t>(fout, is_evidence);
write_be(fout, initial_value);
write_be(fout, var_type);
write_be(fout, cardinality);
++count;
}
std::cout << count << std::endl;
}
// convert weights
void load_weight(std::string input_filename, std::string output_filename) {
std::ifstream fin(input_filename);
std::ofstream fout(output_filename, std::ios::binary | std::ios::out);
num_weights_t count = 0;
int isfixed;
weight_id_t wid;
weight_value_t initial_value;
while (fin >> wid >> isfixed >> initial_value) {
write_be(fout, wid);
write_be<uint8_t>(fout, isfixed);
write_be(fout, initial_value);
++count;
}
std::cout << count << std::endl;
}
static inline size_t parse_pgarray(
std::istream &input, std::function<void(const std::string &)> parse_element,
size_t expected_count = -1) {
if (input.peek() == '{') {
input.get();
std::string element;
bool ended = false;
size_t count = 0;
while (getline(input, element, ',')) {
if (element.at(element.length() - 1) == '}') {
ended = true;
element = element.substr(0, element.length() - 1);
}
parse_element(element);
count++;
if (ended) break;
}
assert(expected_count == -1 || count == expected_count);
return count;
} else {
return -1;
}
}
static inline size_t parse_pgarray_or_die(
std::istream &input, std::function<void(const std::string &)> parse_element,
size_t expected_count = -1) {
size_t count = parse_pgarray(input, parse_element, expected_count);
if (count != -1) {
return count;
} else {
std::cerr << "Expected an array '{' but found: " << input.get()
<< std::endl;
std::abort();
}
}
// load factors
// wid, vids
void load_factor(std::string input_filename, std::string output_filename,
factor_function_type_t funcid, factor_arity_t arity_expected,
const std::vector<bool> &positives_vec) {
std::ifstream fin(input_filename);
std::ofstream fout(output_filename, std::ios::binary | std::ios::out);
num_edges_t total_edges = 0;
std::vector<variable_id_t> vids;
std::vector<weight_id_t> vals_and_weights; // FIXME separate the two
std::string line;
std::string array_piece;
while (getline(fin, line)) {
std::string field;
istringstream ss(line);
vids.clear();
// factor type
write_be<uint16_t>(fout, funcid);
// variable ids
factor_arity_t arity = 0;
auto parse_variableid = [&vids, &arity,
&total_edges](const std::string &element) {
vids.push_back(atol(element.c_str()));
++total_edges;
++arity;
};
for (factor_arity_t i = 0; i < arity_expected; ++i) {
getline(ss, field, field_delim);
// try parsing as an array first
// FIXME remove this? parsing vid arrays is probably broken since this
// doesn't create a cross product of factors but simply widens the arity
istringstream fieldinput(field);
if (parse_pgarray(fieldinput, parse_variableid) == -1) {
// otherwise, parse it as a single variable
parse_variableid(field);
}
}
write_be(fout, arity);
for (factor_arity_t i = 0; i < vids.size(); ++i) {
write_be(fout, vids[i]);
variable_value_t should_equal_to = positives_vec.at(i) ? 1 : 0;
write_be(fout, should_equal_to);
}
// weight ids
switch (funcid) {
case FUNC_AND_CATEGORICAL: {
vals_and_weights.clear();
// IN Format: NUM_WEIGHTS [VAR1 VAL ID] [VAR2 VAL ID] ... [WEIGHT ID]
// OUT Format: NUM_WEIGHTS [[VAR1_VALi, VAR2_VALi, ..., WEIGHTi]]
// first, the run-length
getline(ss, field, field_delim);
factor_weight_key_t num_weightids = atol(field.c_str());
write_be<uint32_t /*FIXME factor_weight_key_t*/>(fout, num_weightids);
// second, parse var vals for each var
// TODO: hard coding cid length (4) for now
for (factor_arity_t i = 0; i < arity; ++i) {
getline(ss, array_piece, field_delim);
istringstream ass(array_piece);
parse_pgarray_or_die(
ass, [&vals_and_weights](const std::string &element) {
variable_value_t cid = atoi(element.c_str());
vals_and_weights.push_back(cid);
}, num_weightids);
}
// third, parse weights
parse_pgarray_or_die(
ss, [&vals_and_weights](const std::string &element) {
weight_id_t weightid = atol(element.c_str());
vals_and_weights.push_back(weightid);
}, num_weightids);
// fourth, transpose into output format
for (factor_weight_key_t i = 0; i < num_weightids; ++i) {
for (factor_arity_t j = 0; j < arity; ++j) {
variable_value_t cid =
(variable_value_t)vals_and_weights[j * num_weightids + i];
write_be(fout, cid);
}
weight_id_t weightid = vals_and_weights[arity * num_weightids + i];
write_be(fout, weightid);
}
break;
}
default:
// a single weight id
getline(ss, field, field_delim);
weight_id_t weightid = atol(field.c_str());
write_be(fout, weightid);
}
}
std::cout << total_edges << std::endl;
}
// read categorical variable domains and convert to binary format
void load_domain(std::string input_filename, std::string output_filename) {
std::ifstream fin(input_filename);
std::ofstream fout(output_filename, std::ios::binary | std::ios::out);
std::string line;
while (getline(fin, line)) {
istringstream line_input(line);
variable_id_t vid;
num_variable_values_t cardinality;
std::string domain;
assert(line_input >> vid >> cardinality >> domain);
write_be(fout, vid);
write_be(fout, cardinality);
// an array of domain values
istringstream domain_input(domain);
parse_pgarray_or_die(domain_input, [&fout](const std::string &subfield) {
variable_value_t value = atoi(subfield.c_str());
write_be(fout, value);
}, cardinality);
}
}
int text2bin(const CmdParser &args) {
// common arguments
if (args.text2bin_mode == "variable") {
load_var(args.text2bin_input, args.text2bin_output);
} else if (args.text2bin_mode == "weight") {
load_weight(args.text2bin_input, args.text2bin_output);
} else if (args.text2bin_mode == "factor") {
load_factor(args.text2bin_input, args.text2bin_output,
args.text2bin_factor_func_id, args.text2bin_factor_arity,
args.text2bin_factor_positives_or_not);
} else if (args.text2bin_mode == "domain") {
load_domain(args.text2bin_input, args.text2bin_output);
} else {
std::cerr << "Unsupported type" << std::endl;
return 1;
}
return 0;
}
} // namespace dd
<|endoftext|>
|
<commit_before>#include "internal.h"
/// Group of functions dedicated to handling of shaders
namespace ShaderHandler {
static const char* readShader(char* path);
static std::vector<Shader> shaders;
static std::vector<GLuint> programs;
static unsigned int currentProgram;
///
/// Adds shader to the shader vector.
///
/// @param type shaderType enum which represents the type of the shader
/// @param filePath Filepath of the shader
///
/// @return ID of the shader
unsigned int addShader(shaderType type, char* filePath)
{
//Adds a new shader to the vector and returns it's id
shaders.push_back(*(new Shader(type, readShader(filePath))));
return shaders.capacity() - 1;
}
///
/// Adds program to the program vector and sets itself as the current program.
///
/// @return ID of the program
///
unsigned int addProgram()
{
//Adds a new program to the Programs Vertex and returns it's id
GLuint i = glCreateProgram();
programs.push_back(i);
currentProgram = programs.size() - 1;
return programs.size() - 1;
}
///
/// Attaches shaders to the current program and links it
///
/// @param vertexShader ID of the vertex shader
/// @param fragmentShader ID of the fragment shader
///
void bindProgram(unsigned int vertexShader, unsigned int fragmentShader)
{
//Attaches vertex and fragment shaders to program
glAttachShader(programs[currentProgram], shaders[vertexShader].id);
glAttachShader(programs[currentProgram], shaders[fragmentShader].id);
//Links the program
glLinkProgram(programs[currentProgram]);
}
///
/// Attaches shaders to a program and links it.
///
/// @param program Program ID
/// @param vertexShader ID of the vertex shader
/// @param fragmentShader ID of the fragment shader
///
void bindProgram(unsigned int program, unsigned int vertexShader, unsigned int fragmentShader)
{
//Attaches vertex and fragment shaders to program
glAttachShader(programs[program], shaders[vertexShader].id);
glAttachShader(programs[program], shaders[fragmentShader].id);
//Links the program
glLinkProgram(programs[program]);
}
///
/// Sets program that is in use to the current program
///
void useProgram(){
glUseProgram(programs[currentProgram]);
}
///
/// Sets program that is in use
///
/// @param program Program ID
///
void useProgram(unsigned int program){
glUseProgram(programs[program]);
}
///
/// Gets current program
///
unsigned int getProgram()
{
return programs[currentProgram];
}
///
/// Gets a program
///
/// @param program Program ID
///
unsigned int getProgram(unsigned int program)
{
return programs[program];
}
Shader::Shader(shaderType type, const char* shader)
{
//Creates a new shader binds it to it's source and compiles it
id = glCreateShader(type);
glShaderSource(id, 1, &shader, NULL);
glCompileShader(id);
GLint b;
GLint length;
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);
GLchar* log = (GLchar*)malloc(length);
glGetShaderInfoLog(id, 200, &length, log);
printf("Log file: ");
if (length>1){
printf("%s\n", log);
}
}
// Private functions which reads shader from file
const char * readShader(char* path)
{
// Reads the shader into a string
std::ifstream shader;
shader.open(path, std::ios::in);
std::string contents((std::istreambuf_iterator<char>(shader)),
std::istreambuf_iterator<char>());
shader.close();
//Creates a new string from contents since returning contents will result in a Null pointer after it's deletion
char* ptr = new char[contents.length() + 1];
std::strcpy(ptr, contents.c_str());
//#ifdef _DEBUG
// std::cout << std::endl << ptr;
//#endif
return ptr;
}
}<commit_msg>Removed unused variable<commit_after>#include "internal.h"
/// Group of functions dedicated to handling of shaders
namespace ShaderHandler {
static const char* readShader(char* path);
static std::vector<Shader> shaders;
static std::vector<GLuint> programs;
static unsigned int currentProgram;
///
/// Adds shader to the shader vector.
///
/// @param type shaderType enum which represents the type of the shader
/// @param filePath Filepath of the shader
///
/// @return ID of the shader
unsigned int addShader(shaderType type, char* filePath)
{
//Adds a new shader to the vector and returns it's id
shaders.push_back(*(new Shader(type, readShader(filePath))));
return shaders.capacity() - 1;
}
///
/// Adds program to the program vector and sets itself as the current program.
///
/// @return ID of the program
///
unsigned int addProgram()
{
//Adds a new program to the Programs Vertex and returns it's id
GLuint i = glCreateProgram();
programs.push_back(i);
currentProgram = programs.size() - 1;
return programs.size() - 1;
}
///
/// Attaches shaders to the current program and links it
///
/// @param vertexShader ID of the vertex shader
/// @param fragmentShader ID of the fragment shader
///
void bindProgram(unsigned int vertexShader, unsigned int fragmentShader)
{
//Attaches vertex and fragment shaders to program
glAttachShader(programs[currentProgram], shaders[vertexShader].id);
glAttachShader(programs[currentProgram], shaders[fragmentShader].id);
//Links the program
glLinkProgram(programs[currentProgram]);
}
///
/// Attaches shaders to a program and links it.
///
/// @param program Program ID
/// @param vertexShader ID of the vertex shader
/// @param fragmentShader ID of the fragment shader
///
void bindProgram(unsigned int program, unsigned int vertexShader, unsigned int fragmentShader)
{
//Attaches vertex and fragment shaders to program
glAttachShader(programs[program], shaders[vertexShader].id);
glAttachShader(programs[program], shaders[fragmentShader].id);
//Links the program
glLinkProgram(programs[program]);
}
///
/// Sets program that is in use to the current program
///
void useProgram(){
glUseProgram(programs[currentProgram]);
}
///
/// Sets program that is in use
///
/// @param program Program ID
///
void useProgram(unsigned int program){
glUseProgram(programs[program]);
}
///
/// Gets current program
///
unsigned int getProgram()
{
return programs[currentProgram];
}
///
/// Gets a program
///
/// @param program Program ID
///
unsigned int getProgram(unsigned int program)
{
return programs[program];
}
Shader::Shader(shaderType type, const char* shader)
{
//Creates a new shader binds it to it's source and compiles it
id = glCreateShader(type);
glShaderSource(id, 1, &shader, NULL);
glCompileShader(id);
GLint length;
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);
GLchar* log = (GLchar*)malloc(length);
glGetShaderInfoLog(id, 200, &length, log);
printf("Log file: ");
if (length>1){
printf("%s\n", log);
}
}
// Private functions which reads shader from file
const char * readShader(char* path)
{
// Reads the shader into a string
std::ifstream shader;
shader.open(path, std::ios::in);
std::string contents((std::istreambuf_iterator<char>(shader)),
std::istreambuf_iterator<char>());
shader.close();
//Creates a new string from contents since returning contents will result in a Null pointer after it's deletion
char* ptr = new char[contents.length() + 1];
std::strcpy(ptr, contents.c_str());
//#ifdef _DEBUG
// std::cout << std::endl << ptr;
//#endif
return ptr;
}
}<|endoftext|>
|
<commit_before>/*************************************************************************
*
* TIGHTDB CONFIDENTIAL
* __________________
*
* [2011] - [2012] TightDB Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of TightDB Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to TightDB Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from TightDB Incorporated.
*
**************************************************************************/
#ifndef TIGHTDB_HPP
#define TIGHTDB_HPP
#include <tightdb/group_shared.hpp>
#include <tightdb/table_macros.hpp>
#include <tightdb/descriptor.hpp>
#include <tightdb/link_view.hpp>
#endif // TIGHTDB_HPP
<commit_msg>lr_sharedptr: Dummy commit to make jenkins re-test (edited a 2012 year to 2014)<commit_after>/*************************************************************************
*
* TIGHTDB CONFIDENTIAL
* __________________
*
* [2011] - [2014] TightDB Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of TightDB Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to TightDB Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from TightDB Incorporated.
*
**************************************************************************/
#ifndef TIGHTDB_HPP
#define TIGHTDB_HPP
#include <tightdb/group_shared.hpp>
#include <tightdb/table_macros.hpp>
#include <tightdb/descriptor.hpp>
#include <tightdb/link_view.hpp>
#endif // TIGHTDB_HPP
<|endoftext|>
|
<commit_before><commit_msg>vcl wmf test: null terminate stream<commit_after><|endoftext|>
|
<commit_before>#include "BoundaryFlux3EqnGhostDensityVelocity.h"
#include "SinglePhaseFluidProperties.h"
#include "Numerics.h"
#include "THMIndices3Eqn.h"
registerMooseObject("THMApp", BoundaryFlux3EqnGhostDensityVelocity);
template <>
InputParameters
validParams<BoundaryFlux3EqnGhostDensityVelocity>()
{
InputParameters params = validParams<BoundaryFlux3EqnGhostBase>();
params.addClassDescription("Computes boundary flux from density and velocity for the 3-equation "
"model using a ghost cell approach.");
params.addRequiredParam<Real>("rho", "Density");
params.addRequiredParam<Real>("vel", "Velocity");
params.addRequiredParam<UserObjectName>("fluid_properties",
"1-phase fluid properties user object name");
params.declareControllable("rho vel");
return params;
}
BoundaryFlux3EqnGhostDensityVelocity::BoundaryFlux3EqnGhostDensityVelocity(
const InputParameters & parameters)
: BoundaryFlux3EqnGhostBase(parameters),
_rho(getParam<Real>("rho")),
_vel(getParam<Real>("vel")),
_fp(getUserObjectByName<SinglePhaseFluidProperties>(
getParam<UserObjectName>("fluid_properties")))
{
}
std::vector<Real>
BoundaryFlux3EqnGhostDensityVelocity::getGhostCellSolution(
const std::vector<Real> & U_interior) const
{
const Real rhoA = U_interior[THM3Eqn::CONS_VAR_RHOA];
const Real rhouA = U_interior[THM3Eqn::CONS_VAR_RHOUA];
const Real rhoEA = U_interior[THM3Eqn::CONS_VAR_RHOEA];
const Real A = U_interior[THM3Eqn::CONS_VAR_AREA];
// Get the pressure from the interior solution
const Real rho = rhoA / A;
const Real vel = rhouA / rhoA;
const Real E = rhoEA / rhoA;
const Real e = E - 0.5 * vel * vel;
const Real p = _fp.p_from_v_e(1.0 / rho, e);
// Compute remaining boundary quantities
const Real e_b = _fp.e_from_p_rho(p, _rho);
const Real E_b = e_b + 0.5 * _vel * _vel;
// compute ghost solution
std::vector<Real> U_ghost(THM3Eqn::N_CONS_VAR);
U_ghost[THM3Eqn::CONS_VAR_RHOA] = _rho * A;
U_ghost[THM3Eqn::CONS_VAR_RHOUA] = _rho * _vel * A;
U_ghost[THM3Eqn::CONS_VAR_RHOEA] = _rho * E_b * A;
U_ghost[THM3Eqn::CONS_VAR_AREA] = A;
return U_ghost;
}
DenseMatrix<Real>
BoundaryFlux3EqnGhostDensityVelocity::getGhostCellSolutionJacobian(
const std::vector<Real> & U_interior) const
{
const Real rhoA = U_interior[THM3Eqn::CONS_VAR_RHOA];
const Real rhouA = U_interior[THM3Eqn::CONS_VAR_RHOUA];
const Real rhoEA = U_interior[THM3Eqn::CONS_VAR_RHOEA];
const Real A = U_interior[THM3Eqn::CONS_VAR_AREA];
// Get the pressures from the interior solution
Real rho = rhoA / A;
Real drho_drhoA = 1.0 / A;
Real v, dv_drho;
THM::v_from_rho(rho, v, dv_drho);
const Real dv_drhoA = dv_drho * drho_drhoA;
const Real vel = rhouA / rhoA;
const Real E = rhoEA / rhoA;
const Real e = E - 0.5 * vel * vel;
const Real de_drhoA = THM::de_darhoA(rhoA, rhouA, rhoEA);
const Real de_drhouA = THM::de_darhouA(rhoA, rhouA);
const Real de_drhoEA = THM::de_darhoEA(rhoA);
Real p, dp_dv, dp_de;
_fp.p_from_v_e(v, e, p, dp_dv, dp_de);
const Real dp_drhoA = dp_dv * dv_drhoA + dp_de * de_drhoA;
const Real dp_drhouA = dp_de * de_drhouA;
const Real dp_drhoEA = dp_de * de_drhoEA;
// Compute remaining boundary quantities
const Real rhoA_b = _rho * A;
Real e_b, de_b_dp, de_b_drho_b;
_fp.e_from_p_rho(p, _rho, e_b, de_b_dp, de_b_drho_b);
const Real de_b_drhoA = de_b_dp * dp_drhoA;
const Real de_b_drhouA = de_b_dp * dp_drhouA;
const Real de_b_drhoEA = de_b_dp * dp_drhoEA;
Real E_b, dE_b_de_b, dE_b_dvel_b;
THM::E_from_e_vel(e_b, _vel, E_b, dE_b_de_b, dE_b_dvel_b);
const Real dE_b_drhoA = dE_b_de_b * de_b_drhoA;
const Real dE_b_drhouA = dE_b_de_b * de_b_drhouA;
const Real dE_b_drhoEA = dE_b_de_b * de_b_drhoEA;
const Real drhoEA_b_drhoA = rhoA_b * dE_b_drhoA;
const Real drhoEA_b_drhouA = rhoA_b * dE_b_drhouA;
const Real drhoEA_b_drhoEA = rhoA_b * dE_b_drhoEA;
// compute ghost solution
std::vector<Real> U_ghost(THM3Eqn::N_CONS_VAR);
U_ghost[THM3Eqn::CONS_VAR_RHOA] = _rho * A;
U_ghost[THM3Eqn::CONS_VAR_RHOUA] = _rho * _vel * A;
U_ghost[THM3Eqn::CONS_VAR_RHOEA] = _rho * E_b * A;
U_ghost[THM3Eqn::CONS_VAR_AREA] = A;
// compute ghost solution Jacobian
DenseMatrix<Real> J(THM3Eqn::N_EQ, THM3Eqn::N_EQ);
J(THM3Eqn::EQ_ENERGY, THM3Eqn::EQ_MASS) = drhoEA_b_drhoA;
J(THM3Eqn::EQ_ENERGY, THM3Eqn::EQ_MOMENTUM) = drhoEA_b_drhouA;
J(THM3Eqn::EQ_ENERGY, THM3Eqn::EQ_ENERGY) = drhoEA_b_drhoEA;
return J;
}
<commit_msg>Removing useless code<commit_after>#include "BoundaryFlux3EqnGhostDensityVelocity.h"
#include "SinglePhaseFluidProperties.h"
#include "Numerics.h"
#include "THMIndices3Eqn.h"
registerMooseObject("THMApp", BoundaryFlux3EqnGhostDensityVelocity);
template <>
InputParameters
validParams<BoundaryFlux3EqnGhostDensityVelocity>()
{
InputParameters params = validParams<BoundaryFlux3EqnGhostBase>();
params.addClassDescription("Computes boundary flux from density and velocity for the 3-equation "
"model using a ghost cell approach.");
params.addRequiredParam<Real>("rho", "Density");
params.addRequiredParam<Real>("vel", "Velocity");
params.addRequiredParam<UserObjectName>("fluid_properties",
"1-phase fluid properties user object name");
params.declareControllable("rho vel");
return params;
}
BoundaryFlux3EqnGhostDensityVelocity::BoundaryFlux3EqnGhostDensityVelocity(
const InputParameters & parameters)
: BoundaryFlux3EqnGhostBase(parameters),
_rho(getParam<Real>("rho")),
_vel(getParam<Real>("vel")),
_fp(getUserObjectByName<SinglePhaseFluidProperties>(
getParam<UserObjectName>("fluid_properties")))
{
}
std::vector<Real>
BoundaryFlux3EqnGhostDensityVelocity::getGhostCellSolution(
const std::vector<Real> & U_interior) const
{
const Real rhoA = U_interior[THM3Eqn::CONS_VAR_RHOA];
const Real rhouA = U_interior[THM3Eqn::CONS_VAR_RHOUA];
const Real rhoEA = U_interior[THM3Eqn::CONS_VAR_RHOEA];
const Real A = U_interior[THM3Eqn::CONS_VAR_AREA];
// Get the pressure from the interior solution
const Real rho = rhoA / A;
const Real vel = rhouA / rhoA;
const Real E = rhoEA / rhoA;
const Real e = E - 0.5 * vel * vel;
const Real p = _fp.p_from_v_e(1.0 / rho, e);
// Compute remaining boundary quantities
const Real e_b = _fp.e_from_p_rho(p, _rho);
const Real E_b = e_b + 0.5 * _vel * _vel;
// compute ghost solution
std::vector<Real> U_ghost(THM3Eqn::N_CONS_VAR);
U_ghost[THM3Eqn::CONS_VAR_RHOA] = _rho * A;
U_ghost[THM3Eqn::CONS_VAR_RHOUA] = _rho * _vel * A;
U_ghost[THM3Eqn::CONS_VAR_RHOEA] = _rho * E_b * A;
U_ghost[THM3Eqn::CONS_VAR_AREA] = A;
return U_ghost;
}
DenseMatrix<Real>
BoundaryFlux3EqnGhostDensityVelocity::getGhostCellSolutionJacobian(
const std::vector<Real> & U_interior) const
{
const Real rhoA = U_interior[THM3Eqn::CONS_VAR_RHOA];
const Real rhouA = U_interior[THM3Eqn::CONS_VAR_RHOUA];
const Real rhoEA = U_interior[THM3Eqn::CONS_VAR_RHOEA];
const Real A = U_interior[THM3Eqn::CONS_VAR_AREA];
// Get the pressures from the interior solution
Real rho = rhoA / A;
Real drho_drhoA = 1.0 / A;
Real v, dv_drho;
THM::v_from_rho(rho, v, dv_drho);
const Real dv_drhoA = dv_drho * drho_drhoA;
const Real vel = rhouA / rhoA;
const Real E = rhoEA / rhoA;
const Real e = E - 0.5 * vel * vel;
const Real de_drhoA = THM::de_darhoA(rhoA, rhouA, rhoEA);
const Real de_drhouA = THM::de_darhouA(rhoA, rhouA);
const Real de_drhoEA = THM::de_darhoEA(rhoA);
Real p, dp_dv, dp_de;
_fp.p_from_v_e(v, e, p, dp_dv, dp_de);
const Real dp_drhoA = dp_dv * dv_drhoA + dp_de * de_drhoA;
const Real dp_drhouA = dp_de * de_drhouA;
const Real dp_drhoEA = dp_de * de_drhoEA;
// Compute remaining boundary quantities
const Real rhoA_b = _rho * A;
Real e_b, de_b_dp, de_b_drho_b;
_fp.e_from_p_rho(p, _rho, e_b, de_b_dp, de_b_drho_b);
const Real de_b_drhoA = de_b_dp * dp_drhoA;
const Real de_b_drhouA = de_b_dp * dp_drhouA;
const Real de_b_drhoEA = de_b_dp * dp_drhoEA;
Real E_b, dE_b_de_b, dE_b_dvel_b;
THM::E_from_e_vel(e_b, _vel, E_b, dE_b_de_b, dE_b_dvel_b);
const Real dE_b_drhoA = dE_b_de_b * de_b_drhoA;
const Real dE_b_drhouA = dE_b_de_b * de_b_drhouA;
const Real dE_b_drhoEA = dE_b_de_b * de_b_drhoEA;
const Real drhoEA_b_drhoA = rhoA_b * dE_b_drhoA;
const Real drhoEA_b_drhouA = rhoA_b * dE_b_drhouA;
const Real drhoEA_b_drhoEA = rhoA_b * dE_b_drhoEA;
// compute ghost solution Jacobian
DenseMatrix<Real> J(THM3Eqn::N_EQ, THM3Eqn::N_EQ);
J(THM3Eqn::EQ_ENERGY, THM3Eqn::EQ_MASS) = drhoEA_b_drhoA;
J(THM3Eqn::EQ_ENERGY, THM3Eqn::EQ_MOMENTUM) = drhoEA_b_drhouA;
J(THM3Eqn::EQ_ENERGY, THM3Eqn::EQ_ENERGY) = drhoEA_b_drhoEA;
return J;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <sstream>
#include "mcc/main.h"
#include "mcc/tac/tac.h"
using namespace mcc::tac;
int main(int argc, char** argv) {
if(argc!=2) {
std::cout << "usage: mC [file]" << std::endl;
return -1;
}
std::ifstream input{argv[1]};
std::stringstream buffer;
buffer << input.rdbuf();
auto source = buffer.str();
auto tree = parser::parse(source);
formatted_ostream out(std::cout);
out << "Parsed:\n" << tree << "\n";
// three adress code
Tac tac;
tac.convertAst(tree);
std::cout << "Three-Adress Code:" << std::endl;
std::cout << tac.toString() << std::endl;
}
<commit_msg>Added tac print after LVN<commit_after>#include <iostream>
#include <fstream>
#include <sstream>
#include "mcc/main.h"
#include "mcc/tac/tac.h"
#include "mcc/lvn/lvn.h"
using namespace mcc::tac;
int main(int argc, char** argv) {
if(argc!=2) {
std::cout << "usage: mC [file]" << std::endl;
return -1;
}
std::ifstream input{argv[1]};
std::stringstream buffer;
buffer << input.rdbuf();
auto source = buffer.str();
auto tree = parser::parse(source);
formatted_ostream out(std::cout);
out << "Parsed:\n" << tree << "\n";
// three adress code
Tac tac;
tac.convertAst(tree);
std::cout << "Three-Adress Code:" << std::endl;
std::cout << tac.toString() << std::endl;
mcc::lvn::LVN::transform(tac);
std::cout << std::endl << "Three-Adress Code after LVN:" << std::endl;
std::cout << tac.toString() << std::endl;
}
<|endoftext|>
|
<commit_before>#include "clause.hpp"
#include "internal.hpp"
#include "iterator.hpp"
#include "macros.hpp"
#include "message.hpp"
#include "proof.hpp"
#include <algorithm>
#include <cmath>
namespace CaDiCaL {
// Code for conflict analysis, e.g., to generate the first UIP clause. The
// main function is 'analyze' below. It further uses 'minimize' to minimize
// the first UIP clause, which is in 'minimize.cpp'. An important side
// effect of conflict analysis is to update the decision queue by bumping
// variables. Similarly resolved clauses are bumped to mark them as active.
/*------------------------------------------------------------------------*/
void Internal::learn_empty_clause () {
assert (!unsat);
LOG ("learned empty clause");
if (proof) proof->trace_empty_clause ();
unsat = true;
}
void Internal::learn_unit_clause (int lit) {
LOG ("learned unit clause %d", lit);
if (proof) proof->trace_unit_clause (lit);
iterating = true;
stats.fixed++;
}
/*------------------------------------------------------------------------*/
// Important variables recently used in conflict analysis are 'bumped',
// which means to move them to the front of the VMTF decision queue. The
// 'bumped' time stamp is updated accordingly. It is used to determine
// whether the 'queue.assigned' pointer has to be moved in 'unassign'.
void Internal::bump_variable (int lit) {
const int idx = vidx (lit);
Link * l = ltab + idx;
if (!l->next) return;
queue.dequeue (ltab, l);
queue.enqueue (ltab, l);
btab[idx] = ++stats.bumped;
if (var (idx).level == level) stats.bumplast++;
LOG ("moved to front %d and bumped %ld", idx, btab[idx]);
if (!vals[idx]) update_queue_unassigned (idx);
}
struct bumped_earlier {
Internal * internal;
bumped_earlier (Internal * i) : internal (i) { }
bool operator () (int a, int b) {
return internal->bumped (a) < internal->bumped (b);
}
};
#if 0
struct bumped_plus_trail_earlier {
Internal * internal;
bumped_plus_trail_earlier (Internal * i) : internal (i) { }
bool operator () (int a, int b) {
long s = internal->bumped (a) + internal->var (a).trail;
long t = internal->bumped (b) + internal->var (b).trail;
return s < t;
}
};
#endif
void Internal::bump_variables () {
START (bump);
if (percent (stats.bumplast, stats.bumped) > opts.bumprevlim &&
propconf > opts.reverselim) {
// There are some instances (for instance the 'newton...' instances),
// which have a very high number of propagations per decision if we try
// to maintain previous bump order as much as possible. They go through
// easily if more recent propagated variables are bumped last, which
// also reduces propagations per decision by two orders of magnitude.
// It seems that this is related to the high percentage of bumped
// variables on the highest decision level. So if this percentage is
// hight we take the assignment order into account too by comparing with
// respect to the sum of bumped and trail order. For the instances
// mentioned above just comparing with respect to assignment order
// (e.g., trail height when assigned) would work too, but is in general
// less robust and thus we use the sum instead.
reverse (analyzed.begin (), analyzed.end ());
#if 0
stable_sort (analyzed.begin (),
analyzed.end (),
bumped_plus_trail_earlier (this));
#endif
stats.reverse++;
} else {
// Otherwise the default is to bump the variable in the order they are
// in the current decision queue. This maintains relative order between
// bumped variables in the queue and seems to work best for those
// instance with smaller number of bumped variables on the last decision
// level.
sort (analyzed.begin (), analyzed.end (), bumped_earlier (this));
}
for (const_int_iterator i = analyzed.begin (); i != analyzed.end (); i++)
bump_variable (*i);
STOP (bump);
}
/*------------------------------------------------------------------------*/
// Clause activity is replaced by a move-to-front scheme as well with
// 'resolved' as time stamp. Only long and high glue clauses are stamped
// since small or low glue clauses are kept anyhow (and do not actually have
// a 'resolved' field). We keep the relative order of bumped clauses by
// sorting them first.
void Internal::bump_resolved_clauses () {
if (!opts.resolve) { assert (resolved.empty ()); return; }
START (bump);
sort (resolved.begin (), resolved.end (), resolved_earlier ());
for (const_clause_iterator i = resolved.begin (); i != resolved.end (); i++)
(*i)->resolved () = ++stats.resolved;
STOP (bump);
resolved.clear ();
}
inline void Internal::resolve_clause (Clause * c) {
if (!c->redundant) return;
if (c->size <= opts.keepsize) return;
if (c->glue <= opts.keepglue) return;
assert (c->extended);
resolved.push_back (c);
}
/*------------------------------------------------------------------------*/
// During conflict analysis literals not seen yet either become part of the
// first UIP clause (if on lower decision level), are dropped (if fixed),
// or are resolved away (if on the current decision level and different from
// the first UIP). At the same time we update the number of seen literals on
// a decision level. This helps conflict clause minimization. The number
// of seen levels is the glucose level (also called glue, or LBD).
inline void Internal::analyze_literal (int lit, int & open) {
assert (lit);
Flags & f = flags (lit);
if (f.seen ()) return;
Var & v = var (lit);
if (!v.level) return;
assert (val (lit) < 0);
if (v.level < level) clause.push_back (lit);
Level & l = control[v.level];
if (!l.seen++) {
LOG ("found new level %d contributing to conflict", v.level);
levels.push_back (v.level);
}
//if (v.trail < l.trail) l.trail = v.trail;
f.set (SEEN);
analyzed.push_back (lit);
LOG ("analyzed literal %d assigned at level %d", lit, v.level);
if (v.level == level) open++;
}
inline void
Internal::analyze_reason (int lit, Clause * reason, int & open) {
assert (reason);
if (opts.resolve) resolve_clause (reason);
const const_literal_iterator end = reason->end ();
const_literal_iterator j = reason->begin ();
int other;
while (j != end)
if ((other = *j++) != lit)
analyze_literal (other, open);
}
/*------------------------------------------------------------------------*/
void Internal::clear_seen () {
for (const_int_iterator i = analyzed.begin (); i != analyzed.end (); i++)
flags (*i).reset ();
analyzed.clear ();
}
void Internal::clear_levels () {
for (const_int_iterator i = levels.begin (); i != levels.end (); i++)
control[*i].reset ();
levels.clear ();
}
/*------------------------------------------------------------------------*/
struct level_greater {
Internal * internal;
level_greater (Internal * s) : internal (s) { }
bool operator () (int a, int b) {
return internal->var (a).level > internal->var (b).level;
}
};
void Internal::analyze () {
assert (conflict);
if (!level) { learn_empty_clause (); conflict = 0; return; }
START (analyze);
// First derive the first UIP clause.
//
Clause * reason = conflict;
LOG (reason, "analyzing conflict");
int open = 0, uip = 0, other = 0;
const_int_iterator i = trail.end ();
for (;;) {
if (reason) analyze_reason (uip, reason, open);
else analyze_literal (other, open);
while (!seen (uip = *--i))
;
if (!--open) break;
Var & v = var (uip);
if (!(reason = v.reason)) other = v.other;
#ifdef LOGGING
if (reason) LOG (reason, "analyzing %d reason", uip);
else LOG ("analyzing %d binary reason %d %d", uip, uip, other);
#endif
}
LOG ("first UIP %d", uip);
clause.push_back (-uip);
reverse (clause.begin (), clause.end ());
check_clause ();
// Update glue statistics.
//
bump_resolved_clauses ();
const int glue = (int) levels.size ();
LOG ("1st UIP clause of size %ld and glue %d",
(long) clause.size (), glue);
UPDATE_AVG (fast_glue_avg, glue);
UPDATE_AVG (slow_glue_avg, glue);
if (lim.decision_level_at_last_restart) {
double x = relative (level, lim.decision_level_at_last_restart);
LOG ("last restart effectiveness %.2f", x);
UPDATE_AVG (restarteff, x);
lim.decision_level_at_last_restart = 0;
}
if (opts.minimize) minimize_clause (); // minimize clause
if (opts.shrink &&
clause.size () <= (size_t) opts.shrinksize &&
glue <= opts.shrinkglue)
shrink_clause ();
int size = (int) clause.size ();
stats.units += (size == 1);
stats.binaries += (size == 2);
UPDATE_AVG (size_avg, size);
if (size > 1 && opts.sublast) eagerly_subsume_last_learned ();
bump_variables (); // Update decision heuristics.
// Determine back jump level, backtrack and assign flipped literal.
//
Clause * driving_clause = 0;
int jump = 0;
if (size > 1) {
stable_sort (clause.begin (), clause.end (), level_greater (this));
driving_clause = new_learned_clause (glue);
jump = var (clause[1]).level;
}
UPDATE_AVG (jump_avg, jump);
backtrack (jump);
assign (-uip, driving_clause);
// Clean up.
//
clear_seen ();
clause.clear ();
clear_levels ();
conflict = 0;
STOP (analyze);
}
// We wait reporting a learned unit until propagation of that unit is
// completed. Otherwise the 'i' report line might prematurely give the
// number of remaining variables.
void Internal::iterate () { iterating = false; report ('i'); }
};
<commit_msg>Revert "fixed"<commit_after>#include "clause.hpp"
#include "internal.hpp"
#include "iterator.hpp"
#include "macros.hpp"
#include "message.hpp"
#include "proof.hpp"
#include <algorithm>
#include <cmath>
namespace CaDiCaL {
// Code for conflict analysis, e.g., to generate the first UIP clause. The
// main function is 'analyze' below. It further uses 'minimize' to minimize
// the first UIP clause, which is in 'minimize.cpp'. An important side
// effect of conflict analysis is to update the decision queue by bumping
// variables. Similarly resolved clauses are bumped to mark them as active.
/*------------------------------------------------------------------------*/
void Internal::learn_empty_clause () {
assert (!unsat);
LOG ("learned empty clause");
if (proof) proof->trace_empty_clause ();
unsat = true;
}
void Internal::learn_unit_clause (int lit) {
LOG ("learned unit clause %d", lit);
if (proof) proof->trace_unit_clause (lit);
iterating = true;
stats.fixed++;
}
/*------------------------------------------------------------------------*/
// Important variables recently used in conflict analysis are 'bumped',
// which means to move them to the front of the VMTF decision queue. The
// 'bumped' time stamp is updated accordingly. It is used to determine
// whether the 'queue.assigned' pointer has to be moved in 'unassign'.
void Internal::bump_variable (int lit) {
const int idx = vidx (lit);
Link * l = ltab + idx;
if (!l->next) return;
queue.dequeue (ltab, l);
queue.enqueue (ltab, l);
btab[idx] = ++stats.bumped;
if (var (idx).level == level) stats.bumplast++;
LOG ("moved to front %d and bumped %ld", idx, btab[idx]);
if (!vals[idx]) update_queue_unassigned (idx);
}
struct bumped_earlier {
Internal * internal;
bumped_earlier (Internal * i) : internal (i) { }
bool operator () (int a, int b) {
return internal->bumped (a) < internal->bumped (b);
}
};
#if 0
struct bumped_plus_trail_earlier {
Internal * internal;
bumped_plus_trail_earlier (Internal * i) : internal (i) { }
bool operator () (int a, int b) {
long s = internal->bumped (a) + internal->var (a).trail;
long t = internal->bumped (b) + internal->var (b).trail;
return s < t;
}
};
#endif
void Internal::bump_variables () {
START (bump);
if (percent (stats.bumplast, stats.bumped) > opts.bumprevlim &&
propconf > opts.reverselim) {
// There are some instances (for instance the 'newton...' instances),
// which have a very high number of propagations per decision if we try
// to maintain previous bump order as much as possible. They go through
// easily if more recent propagated variables are bumped last, which
// also reduces propagations per decision by two orders of magnitude.
// It seems that this is related to the high percentage of bumped
// variables on the highest decision level. So if this percentage is
// hight we take the assignment order into account too by comparing with
// respect to the sum of bumped and trail order. For the instances
// mentioned above just comparing with respect to assignment order
// (e.g., trail height when assigned) would work too, but is in general
// less robust and thus we use the sum instead.
#if 0
reverse (analyzed.begin (), analyzed.end ());
stable_sort (analyzed.begin (),
analyzed.end (),
bumped_plus_trail_earlier (this));
#endif
stats.reverse++;
} else {
// Otherwise the default is to bump the variable in the order they are
// in the current decision queue. This maintains relative order between
// bumped variables in the queue and seems to work best for those
// instance with smaller number of bumped variables on the last decision
// level.
sort (analyzed.begin (), analyzed.end (), bumped_earlier (this));
}
for (const_int_iterator i = analyzed.begin (); i != analyzed.end (); i++)
bump_variable (*i);
STOP (bump);
}
/*------------------------------------------------------------------------*/
// Clause activity is replaced by a move-to-front scheme as well with
// 'resolved' as time stamp. Only long and high glue clauses are stamped
// since small or low glue clauses are kept anyhow (and do not actually have
// a 'resolved' field). We keep the relative order of bumped clauses by
// sorting them first.
void Internal::bump_resolved_clauses () {
if (!opts.resolve) { assert (resolved.empty ()); return; }
START (bump);
sort (resolved.begin (), resolved.end (), resolved_earlier ());
for (const_clause_iterator i = resolved.begin (); i != resolved.end (); i++)
(*i)->resolved () = ++stats.resolved;
STOP (bump);
resolved.clear ();
}
inline void Internal::resolve_clause (Clause * c) {
if (!c->redundant) return;
if (c->size <= opts.keepsize) return;
if (c->glue <= opts.keepglue) return;
assert (c->extended);
resolved.push_back (c);
}
/*------------------------------------------------------------------------*/
// During conflict analysis literals not seen yet either become part of the
// first UIP clause (if on lower decision level), are dropped (if fixed),
// or are resolved away (if on the current decision level and different from
// the first UIP). At the same time we update the number of seen literals on
// a decision level. This helps conflict clause minimization. The number
// of seen levels is the glucose level (also called glue, or LBD).
inline void Internal::analyze_literal (int lit, int & open) {
assert (lit);
Flags & f = flags (lit);
if (f.seen ()) return;
Var & v = var (lit);
if (!v.level) return;
assert (val (lit) < 0);
if (v.level < level) clause.push_back (lit);
Level & l = control[v.level];
if (!l.seen++) {
LOG ("found new level %d contributing to conflict", v.level);
levels.push_back (v.level);
}
//if (v.trail < l.trail) l.trail = v.trail;
f.set (SEEN);
analyzed.push_back (lit);
LOG ("analyzed literal %d assigned at level %d", lit, v.level);
if (v.level == level) open++;
}
inline void
Internal::analyze_reason (int lit, Clause * reason, int & open) {
assert (reason);
if (opts.resolve) resolve_clause (reason);
const const_literal_iterator end = reason->end ();
const_literal_iterator j = reason->begin ();
int other;
while (j != end)
if ((other = *j++) != lit)
analyze_literal (other, open);
}
/*------------------------------------------------------------------------*/
void Internal::clear_seen () {
for (const_int_iterator i = analyzed.begin (); i != analyzed.end (); i++)
flags (*i).reset ();
analyzed.clear ();
}
void Internal::clear_levels () {
for (const_int_iterator i = levels.begin (); i != levels.end (); i++)
control[*i].reset ();
levels.clear ();
}
/*------------------------------------------------------------------------*/
struct level_greater {
Internal * internal;
level_greater (Internal * s) : internal (s) { }
bool operator () (int a, int b) {
return internal->var (a).level > internal->var (b).level;
}
};
void Internal::analyze () {
assert (conflict);
if (!level) { learn_empty_clause (); conflict = 0; return; }
START (analyze);
// First derive the first UIP clause.
//
Clause * reason = conflict;
LOG (reason, "analyzing conflict");
int open = 0, uip = 0, other = 0;
const_int_iterator i = trail.end ();
for (;;) {
if (reason) analyze_reason (uip, reason, open);
else analyze_literal (other, open);
while (!seen (uip = *--i))
;
if (!--open) break;
Var & v = var (uip);
if (!(reason = v.reason)) other = v.other;
#ifdef LOGGING
if (reason) LOG (reason, "analyzing %d reason", uip);
else LOG ("analyzing %d binary reason %d %d", uip, uip, other);
#endif
}
LOG ("first UIP %d", uip);
clause.push_back (-uip);
reverse (clause.begin (), clause.end ());
check_clause ();
// Update glue statistics.
//
bump_resolved_clauses ();
const int glue = (int) levels.size ();
LOG ("1st UIP clause of size %ld and glue %d",
(long) clause.size (), glue);
UPDATE_AVG (fast_glue_avg, glue);
UPDATE_AVG (slow_glue_avg, glue);
if (lim.decision_level_at_last_restart) {
double x = relative (level, lim.decision_level_at_last_restart);
LOG ("last restart effectiveness %.2f", x);
UPDATE_AVG (restarteff, x);
lim.decision_level_at_last_restart = 0;
}
if (opts.minimize) minimize_clause (); // minimize clause
if (opts.shrink &&
clause.size () <= (size_t) opts.shrinksize &&
glue <= opts.shrinkglue)
shrink_clause ();
int size = (int) clause.size ();
stats.units += (size == 1);
stats.binaries += (size == 2);
UPDATE_AVG (size_avg, size);
if (size > 1 && opts.sublast) eagerly_subsume_last_learned ();
bump_variables (); // Update decision heuristics.
// Determine back jump level, backtrack and assign flipped literal.
//
Clause * driving_clause = 0;
int jump = 0;
if (size > 1) {
stable_sort (clause.begin (), clause.end (), level_greater (this));
driving_clause = new_learned_clause (glue);
jump = var (clause[1]).level;
}
UPDATE_AVG (jump_avg, jump);
backtrack (jump);
assign (-uip, driving_clause);
// Clean up.
//
clear_seen ();
clause.clear ();
clear_levels ();
conflict = 0;
STOP (analyze);
}
// We wait reporting a learned unit until propagation of that unit is
// completed. Otherwise the 'i' report line might prematurely give the
// number of remaining variables.
void Internal::iterate () { iterating = false; report ('i'); }
};
<|endoftext|>
|
<commit_before>#include "app.h"
#include <chrono>
#include <thread>
#include <algorithm>
#include <numeric>
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
App::App(
Settings settings,
std::unique_ptr<FileManagerInterface> fileManager,
std::unique_ptr<P2PNetworkInterface> networkManager) :
settings(settings),
fileManager(std::move(fileManager)),
networkManager(std::move(networkManager)) {
this->networkManager->setPorts(
settings.ms_port,
settings.server_port,
settings.file_mgr_port);
}
void App::run() {
running = true;
networkManager->start(settings.main_server);
fileMgrThread = new std::thread(&FileManagerInterface::run, &*fileManager);
appThread = new std::thread(&App::listener, this);
}
void App::stop() {
running = false;
fileMgrThread->join();
delete fileMgrThread;
appThread->join();
delete appThread;
fileManager->stop();
networkManager->stop();
}
App::~App() {
stop();
}
void App::listener() {
// bind, listen on settings.app_port and return fileManager->myIds();
// stop when this->running == false
}
App::host_id_map App::getPeersIds() {
// connect to all networkManager->get_peers():settings.app_port and get their ids
return host_id_map();
}
namespace {
vector<string> split(const string & str, const string & delimiter) {
std::remove_const<decltype(string::npos)>::type start = 0, end = 0;
vector<string> output;
while ((end = str.find(delimiter, start)) != string::npos) {
output.push_back(str.substr(start, end - start));
start = end + 1;
}
output.push_back(str.substr(start));
return output;
}
vector<string> fixPeers(const vector<PeerInfo> & inputPeers) {
vector<string> fixedPeers;
for (const auto & peer : inputPeers) {
const auto parts = split(peer.address, "/");
fixedPeers.push_back(parts[0] + ":" + parts.back());
}
return fixedPeers;
}
//TODO: make cleaner impl, maybe move to fileManager?
std::vector<App::FileInfo> chunkifyFile(const std::string & filePath) {
std::ifstream file(filePath, std::ios::in | std::ios::binary);
if (!file) {
return {};
}
file.seekg(0, std::ios::end);
uint64_t size = file.tellg();
file.close();
std::vector<App::FileInfo> chunks;
uint64_t c = 0;
// push chunks with size App::fileChunkSize
for (; size >= App::fileChunkSize; c += App::fileChunkSize) {
chunks.push_back({ c, App::fileChunkSize, {} });
size -= App::fileChunkSize;
}
// if there is more of the file, make it last chunk
if (size > 0) {
chunks.push_back({ c, size, {} });
}
return chunks;
}
}
bool App::importFile(const std::string & filePath) {
cout << "Imporintg file " << filePath << endl;
if (storage.find(filePath) != storage.end()) {
cout << "File already in storage" << endl;
return false;
}
auto peers = fixPeers(networkManager->get_peers());
if (!peers.size()) {
cout << "No peers connected" << endl;
return false;
}
std::vector<FileInfo> fileChunks = chunkifyFile(filePath);
auto peerIter = peers.cbegin();
// circular iterator over std::vector
auto next = [](decltype(peerIter) & iter, decltype(peers) & container) {
if (++iter == container.end()) {
iter = container.begin();
}
};
for (auto & chunk : fileChunks) {
for (int c = 0; c < static_cast<int>(FileAvailability::High); ++c) {
cout << "Sending chunk to " << *peerIter << endl;
uint64_t sentChunkId = fileManager->send(*peerIter, filePath, chunk.start, chunk.start + chunk.size);
if (sentChunkId == 0) {
cout << "Failed to transfer chunk to host " << *peerIter << " chunk start " << chunk.start << endl;
break;
} else {
cout << "Imorted chunk with ID " << sentChunkId << " to host " << *peerIter << endl;
chunk.hosts.push_back(make_pair(*peerIter, sentChunkId));
}
}
next(peerIter, peers);
}
storage[filePath] = fileChunks;
return true;
}
App::FileAvailability App::isFileInStorage(const std::string & filePath) {
auto file = storage.find(filePath);
if (file == storage.end()) {
cout << "File not in storage" << endl;
return FileAvailability::None;
}
const auto & peers = networkManager->get_peers();
if (!peers.size()){
cout << "No peers connected" << endl;
return FileAvailability::None;
}
FileAvailability fileStatus = FileAvailability::High;
// Go trough all of the chunks and check which of them has least connected hosts
for (auto & chunk : file->second) {
int currentChunk = 0;
for (auto & host : chunk.hosts) {
cout << "Checking chunk with ID: " << host.second << " with host " << host.first << endl;
currentChunk +=
std::any_of(peers.begin(), peers.end(), [&host](const PeerInfo & info) {
const auto & parts = split(info.address, "/");
const auto & peerAddress = parts[0] + ":" + parts.back();
return peerAddress == host.first && info.connected;
});
}
if (!currentChunk) {
cout << "Chunk not found - " << chunk.start << endl;
}
fileStatus = static_cast<FileAvailability>(
std::min<int>(currentChunk, static_cast<int>(fileStatus)));
}
return fileStatus;
}
bool App::exportFile(const std::string & storageFile, const std::string & outputFilePath) {
auto file = storage.find(storageFile);
if (file == storage.end()) {
cout << "File not in storage" << endl;
return false;
}
ofstream outputFile(outputFilePath, ios::trunc | ios::binary);
if (!outputFile) {
cout << "Failed to open export file " << outputFilePath << endl;
return false;
}
for (const auto & chunk : file->second) {
bool gotChunk = false;
for (const auto & chunkLocation : chunk.hosts) {
auto data = fileManager->getFile(chunkLocation.first, chunkLocation.second);
if (data) {
gotChunk = true;
if (!outputFile.write(data.get(), chunk.size)) {
return false;
}
break; // all good chink written to file
} else {
cout << "Failed to receive chunk with ID: " << chunkLocation.second << " with host " << chunkLocation.first << endl;
}
}
if (!gotChunk) {
cout << "Chunk failed to export" << endl;
return false;
}
}
return true;
}
<commit_msg>Add more debug info<commit_after>#include "app.h"
#include <chrono>
#include <thread>
#include <algorithm>
#include <numeric>
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
App::App(
Settings settings,
std::unique_ptr<FileManagerInterface> fileManager,
std::unique_ptr<P2PNetworkInterface> networkManager) :
settings(settings),
fileManager(std::move(fileManager)),
networkManager(std::move(networkManager)) {
this->networkManager->setPorts(
settings.ms_port,
settings.server_port,
settings.file_mgr_port);
}
void App::run() {
running = true;
networkManager->start(settings.main_server);
fileMgrThread = new std::thread(&FileManagerInterface::run, &*fileManager);
appThread = new std::thread(&App::listener, this);
}
void App::stop() {
running = false;
fileMgrThread->join();
delete fileMgrThread;
appThread->join();
delete appThread;
fileManager->stop();
networkManager->stop();
}
App::~App() {
stop();
}
void App::listener() {
// bind, listen on settings.app_port and return fileManager->myIds();
// stop when this->running == false
}
App::host_id_map App::getPeersIds() {
// connect to all networkManager->get_peers():settings.app_port and get their ids
return host_id_map();
}
namespace {
vector<string> split(const string & str, const string & delimiter) {
std::remove_const<decltype(string::npos)>::type start = 0, end = 0;
vector<string> output;
while ((end = str.find(delimiter, start)) != string::npos) {
output.push_back(str.substr(start, end - start));
start = end + 1;
}
output.push_back(str.substr(start));
return output;
}
vector<string> fixPeers(const vector<PeerInfo> & inputPeers) {
vector<string> fixedPeers;
for (const auto & peer : inputPeers) {
const auto parts = split(peer.address, "/");
fixedPeers.push_back(parts[0] + ":" + parts.back());
}
return fixedPeers;
}
//TODO: make cleaner impl, maybe move to fileManager?
std::vector<App::FileInfo> chunkifyFile(const std::string & filePath) {
std::ifstream file(filePath, std::ios::in | std::ios::binary);
if (!file) {
return {};
}
file.seekg(0, std::ios::end);
uint64_t size = file.tellg();
file.close();
std::vector<App::FileInfo> chunks;
uint64_t c = 0;
// push chunks with size App::fileChunkSize
for (; size >= App::fileChunkSize; c += App::fileChunkSize) {
chunks.push_back({ c, App::fileChunkSize, {} });
size -= App::fileChunkSize;
}
// if there is more of the file, make it last chunk
if (size > 0) {
chunks.push_back({ c, size, {} });
}
return chunks;
}
}
bool App::importFile(const std::string & filePath) {
cout << "Imporintg file " << filePath << endl;
if (storage.find(filePath) != storage.end()) {
cout << "File already in storage" << endl;
return false;
}
auto peers = fixPeers(networkManager->get_peers());
if (!peers.size()) {
cout << "No peers connected" << endl;
return false;
}
std::vector<FileInfo> fileChunks = chunkifyFile(filePath);
auto peerIter = peers.cbegin();
// circular iterator over std::vector
auto next = [](decltype(peerIter) & iter, decltype(peers) & container) {
if (++iter == container.end()) {
iter = container.begin();
}
};
for (auto & chunk : fileChunks) {
for (int c = 0; c < static_cast<int>(FileAvailability::High); ++c) {
cout << "Sending chunk to " << *peerIter << endl;
uint64_t sentChunkId = fileManager->send(*peerIter, filePath, chunk.start, chunk.start + chunk.size);
if (sentChunkId == 0) {
cout << "Failed to transfer chunk to host " << *peerIter << " chunk start " << chunk.start << endl;
break;
} else {
cout << "Imorted chunk with ID " << sentChunkId << " to host " << *peerIter << endl;
chunk.hosts.push_back(make_pair(*peerIter, sentChunkId));
}
}
next(peerIter, peers);
}
storage[filePath] = fileChunks;
return true;
}
App::FileAvailability App::isFileInStorage(const std::string & filePath) {
cout << "Checking for file " << filePath << " in storage " << endl;
auto file = storage.find(filePath);
if (file == storage.end()) {
cout << "File not in storage" << endl;
return FileAvailability::None;
}
const auto & peers = networkManager->get_peers();
if (!peers.size()){
cout << "No peers connected" << endl;
return FileAvailability::None;
}
FileAvailability fileStatus = FileAvailability::High;
// Go trough all of the chunks and check which of them has least connected hosts
for (auto & chunk : file->second) {
int currentChunk = 0;
for (auto & host : chunk.hosts) {
cout << "Checking chunk with ID: " << host.second << " with host " << host.first << endl;
currentChunk +=
std::any_of(peers.begin(), peers.end(), [&host](const PeerInfo & info) {
const auto & parts = split(info.address, "/");
const auto & peerAddress = parts[0] + ":" + parts.back();
return peerAddress == host.first && info.connected;
});
}
if (!currentChunk) {
cout << "Chunk not found - " << chunk.start << endl;
}
fileStatus = static_cast<FileAvailability>(
std::min<int>(currentChunk, static_cast<int>(fileStatus)));
}
return fileStatus;
}
bool App::exportFile(const std::string & storageFile, const std::string & outputFilePath) {
cout << "Exporting file " << storageFile << " to " << outputFilePath << endl;
auto file = storage.find(storageFile);
if (file == storage.end()) {
cout << "File not in storage" << endl;
return false;
}
ofstream outputFile(outputFilePath, ios::trunc | ios::binary);
if (!outputFile) {
cout << "Failed to open export file " << outputFilePath << endl;
return false;
}
for (const auto & chunk : file->second) {
bool gotChunk = false;
for (const auto & chunkLocation : chunk.hosts) {
cout << "Getting chunk ID: " << chunkLocation.second << " from host " << chunkLocation.first << " ... ";
auto data = fileManager->getFile(chunkLocation.first, chunkLocation.second);
if (data) {
cout << " Success!" << endl;
gotChunk = true;
if (!outputFile.write(data.get(), chunk.size)) {
return false;
}
break; // all good chink written to file
} else {
cout << " Failed!"<< endl;
}
}
if (!gotChunk) {
cout << "Chunk failed to export" << endl;
return false;
}
}
return true;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014 The Darkcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "assert.h"
#include "core.h"
#include "protocol.h"
#include "util.h"
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
//
// Main network
//
unsigned int pnSeed[] =
{
0x3210ce66, 0x3213747b, 0x1717ba83, 0x3210ce66, 0x3213747b,
0x1715cc22, 0xbc8e2769, 0x36f8e397, 0x2a793a5b, 0x3251c027,
0x05fe6003, 0xaf73c92c, 0xd035bf02, 0xc06f4182, 0xa2f32110,
};
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0xbf;
pchMessageStart[1] = 0x0c;
pchMessageStart[2] = 0x6b;
pchMessageStart[3] = 0xbd;
vAlertPubKey = ParseHex("048240a8748a80a286b270ba126705ced4f2ce5a7847b3610ea3c06513150dade2a8512ed5ea86320824683fc0818f0ac019214973e677acd1244f6d0571fc5103");
nDefaultPort = 9999;
nRPCPort = 9998;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); // Darkcoin starting difficulty is 1 / 2^12
nSubsidyHalvingInterval = 210000;
// Genesis block
const char* pszTimestamp = "Wired 09/Jan/2014 The Grand Experiment Goes Live: Overstock.com Is Now Accepting Bitcoins";
CTransaction txNew;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].nValue = 50 * COIN;
txNew.vout[0].scriptPubKey = CScript() << ParseHex("040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9") << OP_CHECKSIG;
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1390095618;
genesis.nBits = 0x1e0ffff0;
genesis.nNonce = 28917698;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x00000ffd590b1485b3caadc19b22e6379c733355108f107a430458cdf3407ab6"));
assert(genesis.hashMerkleRoot == uint256("0xe0028eb9648db56b1ac77cf090b99048a8007e2bb64b68f092c03c7f56a662c7"));
vSeeds.push_back(CDNSSeedData("darkcoin.io", "dnsseed.darkcoin.io"));
vSeeds.push_back(CDNSSeedData("darkcoin.qa", "dnsseed.darkcoin.qa"));
base58Prefixes[PUBKEY_ADDRESS] = list_of(76); // Darkcoin addresses start with X
base58Prefixes[SCRIPT_ADDRESS] = list_of(5);
base58Prefixes[SECRET_KEY] = list_of(204);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E);
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4);
// Convert the pnSeeds array into usable address objects.
for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
struct in_addr ip;
memcpy(&ip, &pnSeed[i], sizeof(ip));
CAddress addr(CService(ip, GetDefaultPort()));
addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
vFixedSeeds.push_back(addr);
}
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet (v3)
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0xce;
pchMessageStart[1] = 0xe2;
pchMessageStart[2] = 0xca;
pchMessageStart[3] = 0xff;
vAlertPubKey = ParseHex("04517d8a699cb43d3938d7b24faaff7cda448ca4ea267723ba614784de661949bf632d6304316b244646dea079735b9a6fc4af804efb4752075b9fe2245e14e412");
nDefaultPort = 19999;
nRPCPort = 19998;
strDataDir = "testnet3";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nTime = 1390666206;
genesis.nNonce = 3861367235;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x00000bafbc94add76cb75e2ec92894837288a481e5c005f6563d91623bf8bc2c"));
vFixedSeeds.clear();
vSeeds.clear();
vSeeds.push_back(CDNSSeedData("darkcoin.io", "testnet-seed.darkcoin.io"));
vSeeds.push_back(CDNSSeedData("darkcoin.qa", "testnet-seed.darkcoin.qa"));
base58Prefixes[PUBKEY_ADDRESS] = list_of(111); // Testnet v3 addresses
base58Prefixes[SCRIPT_ADDRESS] = list_of(196);
base58Prefixes[SECRET_KEY] = list_of(239);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF);
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94);
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
//
// Regression test
//
class CRegTestParams : public CTestNetParams {
public:
CRegTestParams() {
pchMessageStart[0] = 0xfc;
pchMessageStart[1] = 0xc1;
pchMessageStart[2] = 0xb7;
pchMessageStart[3] = 0xdc;
nSubsidyHalvingInterval = 150;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1);
genesis.nTime = 1417713337;
genesis.nBits = 0x207fffff;
genesis.nNonce = 1096447;
nDefaultPort = 19994;
strDataDir = "regtest";
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x000008ca1832a4baf228eb1553c03d3a2c8e02399550dd6ea8d65cec3ef23d2e"));
vSeeds.clear(); // Regtest mode doesn't have any DNS seeds.
}
virtual bool RequireRPCPassword() const { return false; }
virtual Network NetworkID() const { return CChainParams::REGTEST; }
};
static CRegTestParams regTestParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
case CChainParams::REGTEST:
pCurrentParams = ®TestParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fRegTest = GetBoolArg("-regtest", false);
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet && fRegTest) {
return false;
}
if (fRegTest) {
SelectParams(CChainParams::REGTEST);
} else if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
<commit_msg>Add masternode.io dnsseed operated by @coingun<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014 The Darkcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "assert.h"
#include "core.h"
#include "protocol.h"
#include "util.h"
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
//
// Main network
//
unsigned int pnSeed[] =
{
0x3210ce66, 0x3213747b, 0x1717ba83, 0x3210ce66, 0x3213747b,
0x1715cc22, 0xbc8e2769, 0x36f8e397, 0x2a793a5b, 0x3251c027,
0x05fe6003, 0xaf73c92c, 0xd035bf02, 0xc06f4182, 0xa2f32110,
};
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0xbf;
pchMessageStart[1] = 0x0c;
pchMessageStart[2] = 0x6b;
pchMessageStart[3] = 0xbd;
vAlertPubKey = ParseHex("048240a8748a80a286b270ba126705ced4f2ce5a7847b3610ea3c06513150dade2a8512ed5ea86320824683fc0818f0ac019214973e677acd1244f6d0571fc5103");
nDefaultPort = 9999;
nRPCPort = 9998;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); // Darkcoin starting difficulty is 1 / 2^12
nSubsidyHalvingInterval = 210000;
// Genesis block
const char* pszTimestamp = "Wired 09/Jan/2014 The Grand Experiment Goes Live: Overstock.com Is Now Accepting Bitcoins";
CTransaction txNew;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].nValue = 50 * COIN;
txNew.vout[0].scriptPubKey = CScript() << ParseHex("040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9") << OP_CHECKSIG;
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1390095618;
genesis.nBits = 0x1e0ffff0;
genesis.nNonce = 28917698;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x00000ffd590b1485b3caadc19b22e6379c733355108f107a430458cdf3407ab6"));
assert(genesis.hashMerkleRoot == uint256("0xe0028eb9648db56b1ac77cf090b99048a8007e2bb64b68f092c03c7f56a662c7"));
vSeeds.push_back(CDNSSeedData("darkcoin.io", "dnsseed.darkcoin.io"));
vSeeds.push_back(CDNSSeedData("darkcoin.qa", "dnsseed.darkcoin.qa"));
vSeeds.push_back(CDNSSeedData("masternode.io", "dnsseed.masternode.io"));
base58Prefixes[PUBKEY_ADDRESS] = list_of(76); // Darkcoin addresses start with X
base58Prefixes[SCRIPT_ADDRESS] = list_of(5);
base58Prefixes[SECRET_KEY] = list_of(204);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E);
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4);
// Convert the pnSeeds array into usable address objects.
for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
struct in_addr ip;
memcpy(&ip, &pnSeed[i], sizeof(ip));
CAddress addr(CService(ip, GetDefaultPort()));
addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
vFixedSeeds.push_back(addr);
}
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet (v3)
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0xce;
pchMessageStart[1] = 0xe2;
pchMessageStart[2] = 0xca;
pchMessageStart[3] = 0xff;
vAlertPubKey = ParseHex("04517d8a699cb43d3938d7b24faaff7cda448ca4ea267723ba614784de661949bf632d6304316b244646dea079735b9a6fc4af804efb4752075b9fe2245e14e412");
nDefaultPort = 19999;
nRPCPort = 19998;
strDataDir = "testnet3";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nTime = 1390666206;
genesis.nNonce = 3861367235;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x00000bafbc94add76cb75e2ec92894837288a481e5c005f6563d91623bf8bc2c"));
vFixedSeeds.clear();
vSeeds.clear();
vSeeds.push_back(CDNSSeedData("darkcoin.io", "testnet-seed.darkcoin.io"));
vSeeds.push_back(CDNSSeedData("darkcoin.qa", "testnet-seed.darkcoin.qa"));
vSeeds.push_back(CDNSSeedData("masternode.io", "test.dnsseed.masternode.io"));
base58Prefixes[PUBKEY_ADDRESS] = list_of(111); // Testnet v3 addresses
base58Prefixes[SCRIPT_ADDRESS] = list_of(196);
base58Prefixes[SECRET_KEY] = list_of(239);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF);
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94);
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
//
// Regression test
//
class CRegTestParams : public CTestNetParams {
public:
CRegTestParams() {
pchMessageStart[0] = 0xfc;
pchMessageStart[1] = 0xc1;
pchMessageStart[2] = 0xb7;
pchMessageStart[3] = 0xdc;
nSubsidyHalvingInterval = 150;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1);
genesis.nTime = 1417713337;
genesis.nBits = 0x207fffff;
genesis.nNonce = 1096447;
nDefaultPort = 19994;
strDataDir = "regtest";
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x000008ca1832a4baf228eb1553c03d3a2c8e02399550dd6ea8d65cec3ef23d2e"));
vSeeds.clear(); // Regtest mode doesn't have any DNS seeds.
}
virtual bool RequireRPCPassword() const { return false; }
virtual Network NetworkID() const { return CChainParams::REGTEST; }
};
static CRegTestParams regTestParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
case CChainParams::REGTEST:
pCurrentParams = ®TestParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fRegTest = GetBoolArg("-regtest", false);
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet && fRegTest) {
return false;
}
if (fRegTest) {
SelectParams(CChainParams::REGTEST);
} else if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
<|endoftext|>
|
<commit_before>// Copyright 2012 Philip Puryear
//
// 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 "memrev.h"
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <cstdlib>
#define UNREACHABLE() __builtin_unreachable()
using namespace std;
namespace {
#ifdef USE_VECTOR
#include "__vector.h"
/// Returns a pointer whose integer value is the largest multiple of
/// \a boundary less than or equal to \a ptr.
template<typename T>
inline T* AlignBack(const void* ptr, size_t boundary) {
return (T*) (((uintptr_t) ptr / boundary) * boundary);
}
/// Returns a pointer whose integer value is the smallest multiple of
/// \a boundary greater than or equal to \a ptr.
template<typename T>
inline T* AlignFront(const void* ptr, size_t boundary) {
return (T*) ((((uintptr_t) ptr + boundary - 1) / boundary) * boundary);
}
/// Returns a copy of \a vec with the units reversed.
template<typename Unit, typename Vector>
inline Vector ReverseVector(const Vector& vec) {
switch (sizeof(Unit)) {
case 1:
return ReverseVector8(vec);
case 2:
return ReverseVector16(vec);
case 4:
return ReverseVector32(vec);
case 8:
return ReverseVector64(vec);
}
UNREACHABLE();
}
/// The intermediate stage of the vector reversal algorithm.
/// (See MemrevImpl)
void ShiftMiddleAndSwapSides(char* data, size_t data_length,
size_t start_length, size_t end_length) {
char* data_end = data + data_length;
char* sides_temp;
size_t sides_length = start_length + end_length;
// Save the sides.
if (sides_length > 0) {
sides_temp = new char[sides_length];
memcpy(sides_temp, data, start_length);
memcpy(sides_temp + start_length, data_end - end_length, end_length);
}
// Shift the middle.
if (start_length != end_length) {
memmove(data + end_length, data + start_length,
data_length - sides_length);
}
// Restore the sides, swapped.
if (sides_length > 0) {
memcpy(data, sides_temp + start_length, end_length);
memcpy(data_end - start_length, sides_temp, start_length);
delete [] sides_temp;
}
}
#endif // USE_VECTOR
/// Reverses the order of the first \a count units of \a data using a simple
/// swap algorithm.
template<typename T>
void Reverse(T* data, size_t count) {
T* data_end = data + count;
for (size_t i = 0; i < count / 2; i++) {
T e = data[i];
data[i] = data_end[-1 - i];
data_end[-1 - i] = e;
}
}
#ifdef USE_VECTOR
template<typename Vector, typename T>
#else
template<typename T>
#endif
T* MemrevImpl(T* data, size_t count) {
size_t remaining_units = count;
#ifdef USE_VECTOR
const size_t kMinVectorBytes = 0;
// First, we need to find a subset of the array with 16-byte-aligned bounds
// and a length that is a multiple of 32 bytes.
Vector* vector_start = AlignFront<Vector>(data, SIMD_WIDTH);
Vector* vector_end = AlignBack<Vector>(&data[count], SIMD_WIDTH);
ptrdiff_t total_vector_bytes =
(uintptr_t) vector_end - (uintptr_t) vector_start;
if (total_vector_bytes % (2 * SIMD_WIDTH) != 0) {
total_vector_bytes -= SIMD_WIDTH;
vector_end = (Vector*) (((char*) vector_end) - SIMD_WIDTH);
}
if (total_vector_bytes > kMinVectorBytes) {
// We've found a suitable and sufficiently large subset.
// Do the actual swapping.
for (size_t i = 0; i < total_vector_bytes / (2 * SIMD_WIDTH); i++) {
Vector v = ReverseVector<T>(vector_start[i]);
vector_start[i] = ReverseVector<T>(vector_end[-1 - i]);
vector_end[-1 - i] = v;
}
// Our subset of the array is now reversed. But:
// (a) There may be unreversed bytes at the beginning and/or end.
// (b) The reversed subset may need shifting to its final position.
// Take care of both of these at once.
// Note: |remaining_end_length| refers to the number of unreversed
// bytes that will *end up* at the end of the array, not the ones that
// are currently at the end (likewise for |remaining_start_length|).
size_t total_bytes = count * sizeof(T);
size_t remaining_end_length =
(uintptr_t) vector_start - (uintptr_t) data;
size_t remaining_start_length =
total_bytes - total_vector_bytes - remaining_end_length;
ShiftMiddleAndSwapSides((char*) data, total_bytes,
remaining_end_length, remaining_start_length);
// Reverse the end.
size_t remaining_end_count = remaining_end_length / sizeof(T);
if (remaining_end_count > 0)
Reverse(&data[count - remaining_end_count], remaining_end_count);
remaining_units = remaining_start_length / sizeof(T);
}
#endif
// Reverse the remaining units.
if (remaining_units > 0)
Reverse(data, remaining_units);
return data;
}
} // namespace
char* strrev(char* str) {
return (char*) memrev(str, 1, strlen(str));
}
void* memrev(void* data, int size, size_t count) {
const static int kMaxUnitSize = 8;
if (size <= 0 || size > kMaxUnitSize || size & (size - 1))
return NULL;
#ifdef USE_VECTOR
#define CALL_MEMREV_IMPL(WIDTH) \
MemrevImpl<Vector ## WIDTH>((uint ## WIDTH ##_t*) data, count);
#else
#define CALL_MEMREV_IMPL(WIDTH) \
MemrevImpl((uint ## WIDTH ##_t*) data, count);
#endif
switch (size) {
case 1:
return CALL_MEMREV_IMPL(8);
case 2:
return CALL_MEMREV_IMPL(16);
case 4:
return CALL_MEMREV_IMPL(32);
case 8:
return CALL_MEMREV_IMPL(64);
}
UNREACHABLE();
}
<commit_msg>Tweak include to unbreak Mac build.<commit_after>// Copyright 2012 Philip Puryear
//
// 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 "memrev.h"
#include <cstddef>
#include <cstring>
#include <cstdlib>
#include <stdint.h>
#define UNREACHABLE() __builtin_unreachable()
using namespace std;
namespace {
#ifdef USE_VECTOR
#include "__vector.h"
/// Returns a pointer whose integer value is the largest multiple of
/// \a boundary less than or equal to \a ptr.
template<typename T>
inline T* AlignBack(const void* ptr, size_t boundary) {
return (T*) (((uintptr_t) ptr / boundary) * boundary);
}
/// Returns a pointer whose integer value is the smallest multiple of
/// \a boundary greater than or equal to \a ptr.
template<typename T>
inline T* AlignFront(const void* ptr, size_t boundary) {
return (T*) ((((uintptr_t) ptr + boundary - 1) / boundary) * boundary);
}
/// Returns a copy of \a vec with the units reversed.
template<typename Unit, typename Vector>
inline Vector ReverseVector(const Vector& vec) {
switch (sizeof(Unit)) {
case 1:
return ReverseVector8(vec);
case 2:
return ReverseVector16(vec);
case 4:
return ReverseVector32(vec);
case 8:
return ReverseVector64(vec);
}
UNREACHABLE();
}
/// The intermediate stage of the vector reversal algorithm.
/// (See MemrevImpl)
void ShiftMiddleAndSwapSides(char* data, size_t data_length,
size_t start_length, size_t end_length) {
char* data_end = data + data_length;
char* sides_temp;
size_t sides_length = start_length + end_length;
// Save the sides.
if (sides_length > 0) {
sides_temp = new char[sides_length];
memcpy(sides_temp, data, start_length);
memcpy(sides_temp + start_length, data_end - end_length, end_length);
}
// Shift the middle.
if (start_length != end_length) {
memmove(data + end_length, data + start_length,
data_length - sides_length);
}
// Restore the sides, swapped.
if (sides_length > 0) {
memcpy(data, sides_temp + start_length, end_length);
memcpy(data_end - start_length, sides_temp, start_length);
delete [] sides_temp;
}
}
#endif // USE_VECTOR
/// Reverses the order of the first \a count units of \a data using a simple
/// swap algorithm.
template<typename T>
void Reverse(T* data, size_t count) {
T* data_end = data + count;
for (size_t i = 0; i < count / 2; i++) {
T e = data[i];
data[i] = data_end[-1 - i];
data_end[-1 - i] = e;
}
}
#ifdef USE_VECTOR
template<typename Vector, typename T>
#else
template<typename T>
#endif
T* MemrevImpl(T* data, size_t count) {
size_t remaining_units = count;
#ifdef USE_VECTOR
const size_t kMinVectorBytes = 0;
// First, we need to find a subset of the array with 16-byte-aligned bounds
// and a length that is a multiple of 32 bytes.
Vector* vector_start = AlignFront<Vector>(data, SIMD_WIDTH);
Vector* vector_end = AlignBack<Vector>(&data[count], SIMD_WIDTH);
ptrdiff_t total_vector_bytes =
(uintptr_t) vector_end - (uintptr_t) vector_start;
if (total_vector_bytes % (2 * SIMD_WIDTH) != 0) {
total_vector_bytes -= SIMD_WIDTH;
vector_end = (Vector*) (((char*) vector_end) - SIMD_WIDTH);
}
if (total_vector_bytes > kMinVectorBytes) {
// We've found a suitable and sufficiently large subset.
// Do the actual swapping.
for (size_t i = 0; i < total_vector_bytes / (2 * SIMD_WIDTH); i++) {
Vector v = ReverseVector<T>(vector_start[i]);
vector_start[i] = ReverseVector<T>(vector_end[-1 - i]);
vector_end[-1 - i] = v;
}
// Our subset of the array is now reversed. But:
// (a) There may be unreversed bytes at the beginning and/or end.
// (b) The reversed subset may need shifting to its final position.
// Take care of both of these at once.
// Note: |remaining_end_length| refers to the number of unreversed
// bytes that will *end up* at the end of the array, not the ones that
// are currently at the end (likewise for |remaining_start_length|).
size_t total_bytes = count * sizeof(T);
size_t remaining_end_length =
(uintptr_t) vector_start - (uintptr_t) data;
size_t remaining_start_length =
total_bytes - total_vector_bytes - remaining_end_length;
ShiftMiddleAndSwapSides((char*) data, total_bytes,
remaining_end_length, remaining_start_length);
// Reverse the end.
size_t remaining_end_count = remaining_end_length / sizeof(T);
if (remaining_end_count > 0)
Reverse(&data[count - remaining_end_count], remaining_end_count);
remaining_units = remaining_start_length / sizeof(T);
}
#endif
// Reverse the remaining units.
if (remaining_units > 0)
Reverse(data, remaining_units);
return data;
}
} // namespace
char* strrev(char* str) {
return (char*) memrev(str, 1, strlen(str));
}
void* memrev(void* data, int size, size_t count) {
const static int kMaxUnitSize = 8;
if (size <= 0 || size > kMaxUnitSize || size & (size - 1))
return NULL;
#ifdef USE_VECTOR
#define CALL_MEMREV_IMPL(WIDTH) \
MemrevImpl<Vector ## WIDTH>((uint ## WIDTH ##_t*) data, count);
#else
#define CALL_MEMREV_IMPL(WIDTH) \
MemrevImpl((uint ## WIDTH ##_t*) data, count);
#endif
switch (size) {
case 1:
return CALL_MEMREV_IMPL(8);
case 2:
return CALL_MEMREV_IMPL(16);
case 4:
return CALL_MEMREV_IMPL(32);
case 8:
return CALL_MEMREV_IMPL(64);
}
UNREACHABLE();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "assert.h"
#include "chainparams.h"
#include "main.h"
#include "util.h"
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
#include "chainparamsseeds.h"
//
// Main network
//
// Convert the pnSeeds6 array into usable address objects.
static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
for (unsigned int i = 0; i < count; i++)
{
struct in6_addr ip;
memcpy(&ip, data[i].addr, sizeof(ip));
CAddress addr(CService(ip, data[i].port));
addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
vSeedsOut.push_back(addr);
}
}
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x18;
pchMessageStart[1] = 0x2d;
pchMessageStart[2] = 0x43;
pchMessageStart[3] = 0xf3;
vAlertPubKey = ParseHex("04bf1c0874e989ca090e7eb5d5dd8a04224f2db5cc80d28a256ee676a33396f21622aacb06a9159eaf02ada44238f935f12dd35dad2f6f9075e325ee1219c88533");
nDefaultPort = 15814;
nRPCPort = 15815;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);
// Build the genesis block. Note that the output of the genesis coinbase cannot
// be spent as it did not originally exist in the database.
// Genesis info:
//Found Genesis, Nonce: 45707, Hash: 000007d69ba0f79b4823effb06b08663e2e4c51ed03aaeb547e2e0b83fd37b73
//Gensis Hash Merkle: 73513debc549137a47f2afb73173a2d2b4b0c13f57a57387ae3849a928e1e08d
const char* pszTimestamp = "12 Feb 2017 Whitecoin switches to POSv3";
std::vector<CTxIn> vin;
vin.resize(1);
vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
std::vector<CTxOut> vout;
vout.resize(1);
vout[0].SetEmpty();
CTransaction txNew(1, 1486939650, vin, vout, 0);
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1486939650;
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 45707;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x000007d69ba0f79b4823effb06b08663e2e4c51ed03aaeb547e2e0b83fd37b73"));
assert(genesis.hashMerkleRoot == uint256("0x73513debc549137a47f2afb73173a2d2b4b0c13f57a57387ae3849a928e1e08d"));
vSeeds.push_back(CDNSSeedData("oizopower.nl", "dnsseed.oizopower.nl"));
vSeeds.push_back(CDNSSeedData("dnsseed-cn", "dnsseed-cn.whitecoin.info"));
vSeeds.push_back(CDNSSeedData("seed1", "seed1.oizopower.nl"));
vSeeds.push_back(CDNSSeedData("seed2", "seed2.oizopower.nl"));
vSeeds.push_back(CDNSSeedData("seed3", "seed3.oizopower.nl"));
vSeeds.push_back(CDNSSeedData("xwcseeder", "xwcseeder.ftc-c.com"));
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 73);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 87);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 73+128);
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x88)(0x7F)(0x1E).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x88)(0x94)(0xED).convert_to_container<std::vector<unsigned char> >();
convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));
nLastPOWBlock = 10000;
//Registered Message PubKey
mapBroadcastMessPubKey.insert(pair<std::string,vector<unsigned char>>("Ray", ParseHex("04bf1c0874e989ca090e7eb5d5dd8a04224f2db5cc80d28a256ee676a33396f21622aacb06a9159eaf02ada44238f935f12dd35dad2f6f9075e325ee1219c88533")));
mapBroadcastMessPubKey.insert(pair<std::string,vector<unsigned char>>("Lizhi", ParseHex("04cd377cb31be7b1b4484f8b42e9ca3b748fa9fb3ab1f877ecb9907bfd8623cdaba04c15db1ac897bc384a355e3e099bd78696b3ff03e7955ab43bf3c30bb6e7ec")));
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x31;
pchMessageStart[1] = 0x56;
pchMessageStart[2] = 0x9c;
pchMessageStart[3] = 0xe7;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
vAlertPubKey = ParseHex("046cf758b2a6cb1bf1a144beea816fe63ddc8def9315e697f278225f49ab868d1ec3151e1edc2badcb3090b9eb1f71ba0c5b07b8d4a9bb13d52b5c08b577deddcd");
nDefaultPort = 24070;
nRPCPort = 24071;
strDataDir = "testnet";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 216178;
hashGenesisBlock = genesis.GetHash();
//assert(hashGenesisBlock == uint256("0x0000724595fb3b9609d441cbfb9577615c292abf07d996d3edabc48de843642d"));
vFixedSeeds.clear();
vSeeds.clear();
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 111);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 196);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 239);
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >();
convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));
nLastPOWBlock = 0x7fffffff;
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
//
// Regression test
//
class CRegTestParams : public CTestNetParams {
public:
CRegTestParams() {
pchMessageStart[0] = 0x7b;
pchMessageStart[1] = 0x92;
pchMessageStart[2] = 0xb3;
pchMessageStart[3] = 0xee;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1);
genesis.nTime = 1411111111;
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 2;
hashGenesisBlock = genesis.GetHash();
nDefaultPort = 18444;
strDataDir = "regtest";
//assert(hashGenesisBlock == uint256("0x523dda6d336047722cbaf1c5dce622298af791bac21b33bf6e2d5048b2a13e3d"));
vSeeds.clear(); // Regtest mode doesn't have any DNS seeds.
}
virtual bool RequireRPCPassword() const { return false; }
virtual Network NetworkID() const { return CChainParams::REGTEST; }
};
static CRegTestParams regTestParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
case CChainParams::REGTEST:
pCurrentParams = ®TestParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fRegTest = GetBoolArg("-regtest", false);
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet && fRegTest) {
return false;
}
if (fRegTest) {
SelectParams(CChainParams::REGTEST);
} else if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
<commit_msg>Update chainparams.cpp<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "assert.h"
#include "chainparams.h"
#include "main.h"
#include "util.h"
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
#include "chainparamsseeds.h"
//
// Main network
//
// Convert the pnSeeds6 array into usable address objects.
static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
for (unsigned int i = 0; i < count; i++)
{
struct in6_addr ip;
memcpy(&ip, data[i].addr, sizeof(ip));
CAddress addr(CService(ip, data[i].port));
addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
vSeedsOut.push_back(addr);
}
}
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x18;
pchMessageStart[1] = 0x2d;
pchMessageStart[2] = 0x43;
pchMessageStart[3] = 0xf3;
vAlertPubKey = ParseHex("04bf1c0874e989ca090e7eb5d5dd8a04224f2db5cc80d28a256ee676a33396f21622aacb06a9159eaf02ada44238f935f12dd35dad2f6f9075e325ee1219c88533");
nDefaultPort = 15814;
nRPCPort = 15815;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);
// Build the genesis block. Note that the output of the genesis coinbase cannot
// be spent as it did not originally exist in the database.
// Genesis info:
//Found Genesis, Nonce: 45707, Hash: 000007d69ba0f79b4823effb06b08663e2e4c51ed03aaeb547e2e0b83fd37b73
//Gensis Hash Merkle: 73513debc549137a47f2afb73173a2d2b4b0c13f57a57387ae3849a928e1e08d
const char* pszTimestamp = "12 Feb 2017 Whitecoin switches to POSv3";
std::vector<CTxIn> vin;
vin.resize(1);
vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
std::vector<CTxOut> vout;
vout.resize(1);
vout[0].SetEmpty();
CTransaction txNew(1, 1486939650, vin, vout, 0);
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1486939650;
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 45707;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x000007d69ba0f79b4823effb06b08663e2e4c51ed03aaeb547e2e0b83fd37b73"));
assert(genesis.hashMerkleRoot == uint256("0x73513debc549137a47f2afb73173a2d2b4b0c13f57a57387ae3849a928e1e08d"));
vSeeds.push_back(CDNSSeedData("oizopower.nl", "dnsseed.oizopower.nl"));
vSeeds.push_back(CDNSSeedData("dnsseed-cn", "dnsseed-cn.whitecoin.info"));
vSeeds.push_back(CDNSSeedData("seed1", "seed1.oizopower.nl"));
vSeeds.push_back(CDNSSeedData("seed2", "seed2.oizopower.nl"));
vSeeds.push_back(CDNSSeedData("seed3", "seed3.oizopower.nl"));
vSeeds.push_back(CDNSSeedData("xwcseeder", "xwcseeder.ftc-c.com"));
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 73);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 87);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 73+128);
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x88)(0x7F)(0x1E).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x88)(0x94)(0xED).convert_to_container<std::vector<unsigned char> >();
convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));
nLastPOWBlock = 10000;
//Registered Message PubKey
mapBroadcastMessPubKey.insert(pair<std::string,vector<unsigned char> >("Ray", ParseHex("04bf1c0874e989ca090e7eb5d5dd8a04224f2db5cc80d28a256ee676a33396f21622aacb06a9159eaf02ada44238f935f12dd35dad2f6f9075e325ee1219c88533")));
mapBroadcastMessPubKey.insert(pair<std::string,vector<unsigned char> >("Lizhi", ParseHex("04cd377cb31be7b1b4484f8b42e9ca3b748fa9fb3ab1f877ecb9907bfd8623cdaba04c15db1ac897bc384a355e3e099bd78696b3ff03e7955ab43bf3c30bb6e7ec")));
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x31;
pchMessageStart[1] = 0x56;
pchMessageStart[2] = 0x9c;
pchMessageStart[3] = 0xe7;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
vAlertPubKey = ParseHex("046cf758b2a6cb1bf1a144beea816fe63ddc8def9315e697f278225f49ab868d1ec3151e1edc2badcb3090b9eb1f71ba0c5b07b8d4a9bb13d52b5c08b577deddcd");
nDefaultPort = 24070;
nRPCPort = 24071;
strDataDir = "testnet";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 216178;
hashGenesisBlock = genesis.GetHash();
//assert(hashGenesisBlock == uint256("0x0000724595fb3b9609d441cbfb9577615c292abf07d996d3edabc48de843642d"));
vFixedSeeds.clear();
vSeeds.clear();
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 111);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 196);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 239);
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >();
convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));
nLastPOWBlock = 0x7fffffff;
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
//
// Regression test
//
class CRegTestParams : public CTestNetParams {
public:
CRegTestParams() {
pchMessageStart[0] = 0x7b;
pchMessageStart[1] = 0x92;
pchMessageStart[2] = 0xb3;
pchMessageStart[3] = 0xee;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1);
genesis.nTime = 1411111111;
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 2;
hashGenesisBlock = genesis.GetHash();
nDefaultPort = 18444;
strDataDir = "regtest";
//assert(hashGenesisBlock == uint256("0x523dda6d336047722cbaf1c5dce622298af791bac21b33bf6e2d5048b2a13e3d"));
vSeeds.clear(); // Regtest mode doesn't have any DNS seeds.
}
virtual bool RequireRPCPassword() const { return false; }
virtual Network NetworkID() const { return CChainParams::REGTEST; }
};
static CRegTestParams regTestParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
case CChainParams::REGTEST:
pCurrentParams = ®TestParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fRegTest = GetBoolArg("-regtest", false);
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet && fRegTest) {
return false;
}
if (fRegTest) {
SelectParams(CChainParams::REGTEST);
} else if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
<|endoftext|>
|
<commit_before>
#include <io/Socket.hpp>
#include <io/ServerSocket.hpp>
#include <io/StringWriter.hpp>
#include <io/Inet4Address.hpp>
#include <io/binary/StreamGetter.hpp>
#include <cstdio>
#include <log/LogManager.hpp>
#include <proc/ProcessManager.hpp>
#include <unistd.h>
using namespace logger ;
using namespace std ;
using namespace proc ;
using namespace io ;
using namespace os ;
class MyProcess2: public Process {
public:
MyProcess2() : Process("MyProcess2") {
}
void run() {
LogContext& log = LogManager::instance().getLogContext("MyProcess2", "run");
log.printfln(INFO, "MyProcess2 starting.");
log.printfln(INFO, "Attempting to get a process and send a message");
ProcessProxy* proxy = ProcessManager::instance().getProcessByName("MyProcess");
if( ! proxy ) {
log.printfln(ERROR, "Unable to find process.");
return ;
}
const char* str = "Hello, World";
Message msg;
msg.message = Buffer<byte>((byte*)str, strlen(str));
proxy->sendMessage(msg);
sleep(50000000);
}
protected:
virtual void messageReceivedCallback( const Message& msg ) {
LogContext& log =
LogManager::instance().getLogContext("MyProcess2", "MyProcess2");
log.printfln(INFO, "Message received");
log.printHex(INFO, msg.message.rawPointer(), msg.message.length());
}
};
class MyProcess: public Process {
public:
MyProcess() : Process("MyProcess") {
}
void run() {
LogContext& log = LogManager::instance().getLogContext("MyProcess", "run");
log.printfln(INFO, "MyProcess starting.");
sleep(50000000);
}
protected:
virtual void messageReceivedCallback( const Message& msg ) {
LogContext& log =
LogManager::instance().getLogContext("MyProcess", "MyProcess");
log.printfln(INFO, "Message received");
log.printHex(INFO, msg.message.rawPointer(), msg.message.length());
}
};
int main( int argc, char** argv ) {
(void) argc; (void) argv;
LogManager::instance().setEnableByDefault(true);
LogContext& log = LogManager::instance().getLogContext("Main", "Main");
log.printfln(TRACE, "simulating debug");
log.printfln(DEBUG, "simulating debug");
log.printfln(INFO, "logging has started");
log.printfln(SUCCESS, "simulating success");
log.printfln(WARN, "simulating a warning");
log.printfln(ERROR, "This is simulating an error");
ProcessManager& man = ProcessManager::instance();
log.printfln(INFO, "man: %p", &man);
MyProcess process;
Thread* m_thread = process.start();
sleep(1);
MyProcess2 process2;
process2.run();
return 0;
}
<commit_msg>editing main<commit_after>
#include <io/Socket.hpp>
#include <io/ServerSocket.hpp>
#include <io/StringWriter.hpp>
#include <io/Inet4Address.hpp>
#include <io/binary/StreamGetter.hpp>
#include <cstdio>
#include <log/LogManager.hpp>
#include <proc/ProcessManager.hpp>
#include <unistd.h>
using namespace logger ;
using namespace std ;
using namespace proc ;
using namespace io ;
using namespace os ;
class MyProcess2: public Process {
public:
MyProcess2() : Process("MyProcess2") {
}
void run() {
LogContext& log = LogManager::instance().getLogContext("MyProcess2", "run");
log.printfln(INFO, "MyProcess2 starting.");
log.printfln(INFO, "Attempting to get a process and send a message");
ProcessProxy* proxy = ProcessManager::instance().getProcessByName("MyProcess");
if( ! proxy ) {
log.printfln(ERROR, "Unable to find process.");
return ;
}
const char* str = "ping";
proxy->sendMessage(getAddress(), (byte*)str, strlen(str));
sleep(50000000);
}
protected:
virtual void messageReceivedCallback( ProcessProxy& from, const byte* bytes, size_t len ) {
LogContext& log =
LogManager::instance().getLogContext("MyProcess2", "MyProcess2");
log.printfln(INFO, "Message received");
log.printHex(INFO, bytes, len);
from.sendMessage( getAddress(), (byte*)"ping", strlen("ping") );
}
};
class MyProcess: public Process {
public:
MyProcess() : Process("MyProcess") {
}
void run() {
LogContext& log = LogManager::instance().getLogContext("MyProcess", "run");
log.printfln(INFO, "MyProcess starting.");
sleep(50000000);
}
protected:
virtual void messageReceivedCallback( ProcessProxy& from, const byte* bytes, size_t len ) {
LogContext& log =
LogManager::instance().getLogContext("MyProcess", "MyProcess");
log.printfln(INFO, "Message received");
log.printHex(INFO, bytes, len);
from.sendMessage( getAddress(), (byte*)"pong", strlen("pong") );
}
};
int main( int argc, char** argv ) {
(void) argc; (void) argv;
LogManager::instance().setEnableByDefault(true);
LogContext& log = LogManager::instance().getLogContext("Main", "Main");
log.printfln(TRACE, "simulating debug");
log.printfln(DEBUG, "simulating debug");
log.printfln(INFO, "logging has started");
log.printfln(SUCCESS, "simulating success");
log.printfln(WARN, "simulating a warning");
log.printfln(ERROR, "This is simulating an error");
ProcessManager& man = ProcessManager::instance();
log.printfln(INFO, "man: %p", &man);
MyProcess process;
Thread* m_thread = process.start();
sleep(1);
MyProcess2 process2;
process2.run();
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2016 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Developers
// Copyright (c) 2015-2016 The Silk Network Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "main.h"
#include "util.h"
#include "chainparamsseeds.h"
#include "assert.h"
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
//
// Main network
//
// Convert the pnSeeds array into usable address objects.
static void convertSeeds(std::vector<CAddress> &vSeedsOut, const unsigned int *data, unsigned int count, int port)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
for (unsigned int k = 0; k < count; ++k)
{
struct in_addr ip;
unsigned int i = data[k], t;
// -- convert to big endian
t = (i & 0x000000ff) << 24u
| (i & 0x0000ff00) << 8u
| (i & 0x00ff0000) >> 8u
| (i & 0xff000000) >> 24u;
memcpy(&ip, &t, sizeof(ip));
CAddress addr(CService(ip, port));
addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
vSeedsOut.push_back(addr);
}
}
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x1f;
pchMessageStart[1] = 0x22;
pchMessageStart[2] = 0x05;
pchMessageStart[3] = 0x31;
vAlertPubKey = ParseHex("0450e0acc669231cfe2d0a8f0d164c341547487adff89f09e1e78a5299d204bd1c9f05897cb916365c56a31377d872abddb551a12d8d8163149abfc851be7f88ba");
nDefaultPort = 31000;
nRPCPort = 31500;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); // PoW starting difficulty = 0.0002441
// Build the genesis block. Note that the output of the genesis coinbase cannot
// be spent as it did not originally exist in the database.
const char* pszTimestamp = "2015 DarkSilk is Born";
std::vector<CTxIn> vin;
vin.resize(1);
vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
std::vector<CTxOut> vout;
vout.resize(1);
vout[0].SetEmpty();
CMutableTransaction txNew(1, 1444948732, vin, vout, 0);
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1444948732; //Change to current UNIX Time of generated genesis
genesis.nBits = 0x1e0ffff0;
genesis.nNonce = 763220;
hashGenesisBlock = genesis.GetHash();
//// debug print
/*
printf("Gensis Hash: %s\n", genesis.GetHash().ToString().c_str());
printf("Gensis Hash Merkle: %s\n", genesis.hashMerkleRoot.ToString().c_str());
printf("Gensis nTime: %u\n", genesis.nTime);
printf("Gensis nBits: %08x\n", genesis.nBits);
printf("Gensis Nonce: %u\n\n\n", genesis.nNonce);
*/
assert(hashGenesisBlock == uint256("0xdcc5e22e275eff273799a4c06493f8364316d032813c22845602f05ff13d7ec7"));
assert(genesis.hashMerkleRoot == uint256("0xfed7550a453e532c460fac58d438740235c380f9908cae2d602b705ca2c2f0a6"));
vSeeds.push_back(CDNSSeedData("darksilk.org", "ds1.darksilk.org"));
vSeeds.push_back(CDNSSeedData("", ""));
base58Prefixes[PUBKEY_ADDRESS] = list_of(30); //DarkSilk addresses start with 'D'
base58Prefixes[SCRIPT_ADDRESS] = list_of(10); //DarkSilk script addresses start with '5'
base58Prefixes[SECRET_KEY] = list_of(140); //DarkSilk private keys start with 'y'
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x02)(0xFE)(0x52)(0x7D); //DarkSilk BIP32 pubkeys start with 'drks'
base58Prefixes[EXT_SECRET_KEY] = list_of(0x02)(0xFE)(0x52)(0x8C); //DarkSilk BIP32 prvkeys start with 'drky'
convertSeeds(vFixedSeeds, pnSeed, ARRAYLEN(pnSeed), nDefaultPort);
//TODO(AA)
nPoolMaxTransactions = 3;
strSandstormPoolDummyAddress = "DDCxTmWLPytjnEAMd3TCGaryJStEx5caSm"; //private key = MpBeYuuA7c47bqa6ubmBnP8P7hkpmJTSUgwejC8AehSPwsXmkZHD
strStormnodePaymentsPubKey = "";
nLastPOWBlock = 100;
nFirstPOSBlock = 101;
nStartStormnodePayments = 1446335999; //Wed, 31 Oct 2015 23:59:59 GMT
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x1f;
pchMessageStart[1] = 0x22;
pchMessageStart[2] = 0x05;
pchMessageStart[3] = 0x30;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); // PoW starting difficulty = 0.0002441
vAlertPubKey = ParseHex("");
nDefaultPort = 31750;
nRPCPort = 31800;
strDataDir = "testnet";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nTime = 1438578972;
genesis.nBits = 0;
genesis.nNonce = 0;
hashGenesisBlock = genesis.GetHash();
//printf("Test Genesis Hash: %s\n", genesis.GetHash().ToString().c_str());
assert(hashGenesisBlock == uint256("0xf788ac4ae46429468897b4b9758651cb8a642a6e01f16968134a75078905e24d"));
vFixedSeeds.clear();
vSeeds.clear();
base58Prefixes[PUBKEY_ADDRESS] = list_of(30); //DarkSilk addresses start with 'D'
base58Prefixes[SCRIPT_ADDRESS] = list_of(10); //DarkSilk script addresses start with '5'
base58Prefixes[SECRET_KEY] = list_of(140); //DarkSilk private keys start with 'y'
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x02)(0xFE)(0x52)(0x7D); //DarkSilk BIP32 pubkeys start with 'drks'
base58Prefixes[EXT_SECRET_KEY] = list_of(0x02)(0xFE)(0x52)(0x8C); //DarkSilk BIP32 prvkeys start with 'drky'
convertSeeds(vFixedSeeds, pnTestnetSeed, ARRAYLEN(pnTestnetSeed), nDefaultPort);
//TODO(Amir): Change pub key and dummy address
nPoolMaxTransactions = 3;
strStormnodePaymentsPubKey = "";
strSandstormPoolDummyAddress = "DDCxTmWLPytjnEAMd3TCGaryJStEx5caSm"; //private key = MpBeYuuA7c47bqa6ubmBnP8P7hkpmJTSUgwejC8AehSPwsXmkZHD
nLastPOWBlock = 100;
nFirstPOSBlock = 101;
nStartStormnodePayments = 1446335999; //Wed, 31 Oct 2015 23:59:59 GMT
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
<commit_msg>PoW/PoS Start/End Change<commit_after>// Copyright (c) 2009-2016 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Developers
// Copyright (c) 2015-2016 The Silk Network Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "main.h"
#include "util.h"
#include "chainparamsseeds.h"
#include "assert.h"
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
//
// Main network
//
// Convert the pnSeeds array into usable address objects.
static void convertSeeds(std::vector<CAddress> &vSeedsOut, const unsigned int *data, unsigned int count, int port)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
for (unsigned int k = 0; k < count; ++k)
{
struct in_addr ip;
unsigned int i = data[k], t;
// -- convert to big endian
t = (i & 0x000000ff) << 24u
| (i & 0x0000ff00) << 8u
| (i & 0x00ff0000) >> 8u
| (i & 0xff000000) >> 24u;
memcpy(&ip, &t, sizeof(ip));
CAddress addr(CService(ip, port));
addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
vSeedsOut.push_back(addr);
}
}
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x1f;
pchMessageStart[1] = 0x22;
pchMessageStart[2] = 0x05;
pchMessageStart[3] = 0x31;
vAlertPubKey = ParseHex("0450e0acc669231cfe2d0a8f0d164c341547487adff89f09e1e78a5299d204bd1c9f05897cb916365c56a31377d872abddb551a12d8d8163149abfc851be7f88ba");
nDefaultPort = 31000;
nRPCPort = 31500;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); // PoW starting difficulty = 0.0002441
// Build the genesis block. Note that the output of the genesis coinbase cannot
// be spent as it did not originally exist in the database.
const char* pszTimestamp = "2015 DarkSilk is Born";
std::vector<CTxIn> vin;
vin.resize(1);
vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
std::vector<CTxOut> vout;
vout.resize(1);
vout[0].SetEmpty();
CMutableTransaction txNew(1, 1444948732, vin, vout, 0);
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1444948732; //Change to current UNIX Time of generated genesis
genesis.nBits = 0x1e0ffff0;
genesis.nNonce = 763220;
hashGenesisBlock = genesis.GetHash();
//// debug print
/*
printf("Gensis Hash: %s\n", genesis.GetHash().ToString().c_str());
printf("Gensis Hash Merkle: %s\n", genesis.hashMerkleRoot.ToString().c_str());
printf("Gensis nTime: %u\n", genesis.nTime);
printf("Gensis nBits: %08x\n", genesis.nBits);
printf("Gensis Nonce: %u\n\n\n", genesis.nNonce);
*/
assert(hashGenesisBlock == uint256("0xdcc5e22e275eff273799a4c06493f8364316d032813c22845602f05ff13d7ec7"));
assert(genesis.hashMerkleRoot == uint256("0xfed7550a453e532c460fac58d438740235c380f9908cae2d602b705ca2c2f0a6"));
vSeeds.push_back(CDNSSeedData("darksilk.org", "ds1.darksilk.org"));
vSeeds.push_back(CDNSSeedData("", ""));
base58Prefixes[PUBKEY_ADDRESS] = list_of(30); //DarkSilk addresses start with 'D'
base58Prefixes[SCRIPT_ADDRESS] = list_of(10); //DarkSilk script addresses start with '5'
base58Prefixes[SECRET_KEY] = list_of(140); //DarkSilk private keys start with 'y'
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x02)(0xFE)(0x52)(0x7D); //DarkSilk BIP32 pubkeys start with 'drks'
base58Prefixes[EXT_SECRET_KEY] = list_of(0x02)(0xFE)(0x52)(0x8C); //DarkSilk BIP32 prvkeys start with 'drky'
convertSeeds(vFixedSeeds, pnSeed, ARRAYLEN(pnSeed), nDefaultPort);
//TODO(AA)
nPoolMaxTransactions = 3;
strSandstormPoolDummyAddress = "DDCxTmWLPytjnEAMd3TCGaryJStEx5caSm"; //private key = MpBeYuuA7c47bqa6ubmBnP8P7hkpmJTSUgwejC8AehSPwsXmkZHD
strStormnodePaymentsPubKey = "";
nLastPOWBlock = -1;
nFirstPOSBlock = 101;
nStartStormnodePayments = 1446335999; //Wed, 31 Oct 2015 23:59:59 GMT
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x1f;
pchMessageStart[1] = 0x22;
pchMessageStart[2] = 0x05;
pchMessageStart[3] = 0x30;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); // PoW starting difficulty = 0.0002441
vAlertPubKey = ParseHex("");
nDefaultPort = 31750;
nRPCPort = 31800;
strDataDir = "testnet";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nTime = 1438578972;
genesis.nBits = 0;
genesis.nNonce = 0;
hashGenesisBlock = genesis.GetHash();
//printf("Test Genesis Hash: %s\n", genesis.GetHash().ToString().c_str());
assert(hashGenesisBlock == uint256("0xf788ac4ae46429468897b4b9758651cb8a642a6e01f16968134a75078905e24d"));
vFixedSeeds.clear();
vSeeds.clear();
base58Prefixes[PUBKEY_ADDRESS] = list_of(30); //DarkSilk addresses start with 'D'
base58Prefixes[SCRIPT_ADDRESS] = list_of(10); //DarkSilk script addresses start with '5'
base58Prefixes[SECRET_KEY] = list_of(140); //DarkSilk private keys start with 'y'
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x02)(0xFE)(0x52)(0x7D); //DarkSilk BIP32 pubkeys start with 'drks'
base58Prefixes[EXT_SECRET_KEY] = list_of(0x02)(0xFE)(0x52)(0x8C); //DarkSilk BIP32 prvkeys start with 'drky'
convertSeeds(vFixedSeeds, pnTestnetSeed, ARRAYLEN(pnTestnetSeed), nDefaultPort);
//TODO(Amir): Change pub key and dummy address
nPoolMaxTransactions = 3;
strStormnodePaymentsPubKey = "";
strSandstormPoolDummyAddress = "DDCxTmWLPytjnEAMd3TCGaryJStEx5caSm"; //private key = MpBeYuuA7c47bqa6ubmBnP8P7hkpmJTSUgwejC8AehSPwsXmkZHD
nLastPOWBlock = -1;
nFirstPOSBlock = 101;
nStartStormnodePayments = 1446335999; //Wed, 31 Oct 2015 23:59:59 GMT
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
<|endoftext|>
|
<commit_before>/* indivudal.cpp - CS 472 Project #2: Genetic Programming
* Copyright 2014 Andrew Schwartzmeyer
*
* Source file for individual namespace
*/
#include <algorithm>
#include <cassert>
#include <cmath>
#include <iostream>
#include <memory>
#include <tuple>
#include <vector>
#include "individual.hpp"
#include "../options/options.hpp"
#include "../random_generator/random_generator.hpp"
namespace individual
{
using std::vector;
using std::string;
using namespace random_generator;
// Default Size struct constructor.
Size::Size(): internals{0}, leaves{0} {}
// Available methods for tree creation.
enum class Method {grow, full};
// List of valid functions for an expression.
enum class Function {nil, constant, input, sqrt, sin, cos, log, exp,
add, subtract, divide, multiply, pow, lesser, greater};
using F = Function;
// Vectors of same-arity function enums.
vector <F> nullaries {F::constant, F::input};
vector <F> unaries {F::sqrt, F::sin, F::cos, F::log, F::exp};
vector <F> binaries {F::add, F::subtract, F::multiply, F::divide, F::pow};
vector <F> quadnaries {F::lesser, F::greater};
/* Vectors of available function enums. Should be moved into
Options struct. */
vector <F> leaves {F::constant, F::input};
vector <F> internals {F::sin, F::cos, F::add, F::subtract,
F::multiply, F::divide, F::lesser, F::greater};
// Returns a random function from a given set of functions.
Function
get_function(const vector <Function>& functions)
{
int_dist dist{0, (int) functions.size() - 1}; // closed interval
return functions[dist(rg.engine)];
}
// Returns a random double between min and max.
double
get_constant(const double& min, const double& max)
{
real_dist dist{min, max};
return dist(rg.engine);
}
// Returns bool of whether or not the item is in the set.
template<typename I, typename S> bool
contains(const I& item, const S& set)
{
return std::find(set.begin(), set.end(), item) != set.end();
}
// Returns the appropriate arity for a given function.
unsigned int
get_arity(const Function& function)
{
if (contains(function, nullaries))
return 0;
else if (contains(function, unaries))
return 1;
else if (contains(function, binaries))
return 2;
else if (contains(function, quadnaries))
return 4;
assert(false);
}
// Default constructor for "empty" node
Node::Node(): function{Function::nil}, arity{0}, value{0} {}
/* Recursively constructs a parse tree using the given method
(either GROW or FULL). */
Node::Node(const Method& method, const unsigned int& max_depth,
const double& constant_min, const double& constant_max)
{
// Create terminal node if at the max depth or randomly (if growing).
real_dist dist{0, 1};
double grow_chance = (double) leaves.size() / leaves.size() + leaves.size();
if (max_depth == 0
or (method == Method::grow and dist(rg.engine) < grow_chance))
{
function = get_function(leaves);
arity = get_arity(function);
// Setup constant function; input is provided on evaluation.
if (function == Function::constant)
value = get_constant(constant_min, constant_max);
}
// Otherwise choose a non-terminal node.
else
{
function = get_function(internals);
// Determine node's arity.
arity = get_arity(function);
// Recursively create subtrees.
for (unsigned int i = 0; i < arity; ++i)
children.emplace_back(Node{
method, max_depth - 1, constant_min, constant_max});
}
assert(function != Function::nil); // do not create null types
assert(children.size() == arity); // ensure arity
}
// Returns a string visually representing a particular node.
string
Node::represent() const
{
switch (function)
{
case F::nil:
assert(false); // Never represent empty node.
case F::constant:
return std::to_string(value);
case F::input:
return "x";
case F::sqrt:
return "sqrt";
case F::sin:
return "sin";
case F::cos:
return "cos";
case F::log:
return "log";
case F::exp:
return "exp";
case F::add:
return "+";
case F::subtract:
return "-";
case F::multiply:
return "*";
case F::divide:
return "%";
case F::pow:
return "^";
case F::lesser:
return "<";
case F::greater:
return ">";
}
assert(false); // Every node should have been matched.
}
/* Returns string representation of expression in Polish/prefix
notation using a pre-order traversal. */
string
Node::print() const
{
if (children.size() == 0)
return represent();
string formula = "(" + represent();
for (const Node& child : children)
formula += " " + child.print();
return formula + ")";
}
/* Returns a double as the result of a depth-first post-order
recursive evaluation of a parse tree. */
double
Node::evaluate(const double& x) const
{
double a, b;
// Evaluate children a and possibly b.
if (arity == 1)
a = children[0].evaluate(x);
else if (arity == 2 or arity == 4)
{
a = children[0].evaluate(x);
b = children[1].evaluate(x);
// Children c and d are evaluated conditionally.
}
// Calculate the result for the given function.
switch (function)
{
case F::nil:
assert(false); // Never calculate empty node.
case F::constant:
assert(arity == 0);
return value;
case F::input:
assert(arity == 0);
return x;
case F::sqrt:
assert(arity == 1);
return std::sqrt(std::abs(a)); // Protected via abs.
case F::sin:
assert(arity == 1);
return std::sin(a);
case F::cos:
assert(arity == 1);
return std::cos(a);
case F::log:
assert(arity == 1);
return (a == 0) ? 0 : std::log(std::abs(a)); // Protected via abs.
case F::exp:
assert(arity == 1);
return std::exp(a);
case F::add:
assert(arity == 2);
return a + b;
case F::subtract:
assert(arity == 2);
return a - b;
case F::multiply:
assert(arity == 2);
return a * b;
case F::divide:
assert(arity == 2);
return (b == 0) ? 1 : a / b; // Protected divide by zero: return 1.
case F::pow:
assert(arity == 2);
return std::pow(std::abs(a), std::abs(b)); // Protected via abs.
case F::lesser:
assert(arity == 4);
return (a < b) ? children[2].evaluate(x) : children[3].evaluate(x);
case F::greater:
assert(arity == 4);
return (a > b) ? children[2].evaluate(x) : children[3].evaluate(x);
}
assert(false);
}
/* Recursively count children via post-order traversal. Keep track
of internals and leaves via Size struct */
const Size
Node::size() const
{
Size size;
for (const Node& child : children)
{
Size temp = child.size();
size.internals += temp.internals;
size.leaves += temp.leaves;
}
if (children.size() == 0)
++size.leaves;
else
++size.internals;
return size;
}
// Used to represent "not-found" (similar to a NULL pointer).
Node empty;
/* Depth-first search for taget node. Must be seeking either
internal or leaf, cannot be both. */
Node&
Node::visit(const Size& i, Size& visiting)
{
for (Node& child : children) {
// Increase relevant count.
if (child.children.size() == 0)
++visiting.leaves;
else
++visiting.internals;
// Return node reference if found.
if (visiting.internals == i.internals or visiting.leaves == i.leaves)
return child;
else
{
Node& temp = child.visit(i, visiting); // Recursive search.
if (temp.function != Function::nil)
return temp;
}
}
return empty;
}
// Single node mutation to different function of same arity.
void
Node::mutate_self()
{
/* Mutate constant to a value in its neighborhood. Here we do
not switch functions (between CONSTANT and INPUT), as it
introduces too much volatility into the terminals. TODO:
review the above and possibly change. */
if (arity == 0)
{
if (function == Function::constant)
{
normal_dist dist{0, 1};
value *= 1 + dist(rg.engine);
}
}
/* Otherwise mutate to internal function of same arity. We do
this by saving the old function and arity, then repeatedly
drawing a new random function until the arity matches and it is
not the original function. */
else
{
Function old_function = function;
unsigned int old_arity = arity;
while (function == old_function or arity != old_arity)
{
function = get_function(internals);
arity = get_arity(function);
}
assert(function != old_function and arity == old_arity);
}
assert(function != Function::nil);
}
// Recursively mutate nodes with given probability.
void
Node::mutate_tree(const double& chance)
{
real_dist dist{0, 1};
for (Node& child : children)
{
if (dist(rg.engine) < chance)
child.mutate_self();
child.mutate_tree(chance);
}
}
// Default constructor for Individual
Individual::Individual() {}
/* Create an Individual tree by having a root node (to which the
actual construction is delegated). The depth is passed by value
as its creation elsewhere is temporary. */
Individual::Individual(const unsigned int depth, const double& chance,
const double& min, const double& max,
const options::pairs& values): fitness{0}, adjusted{0}
{
real_dist dist{0, 1};
Method method = (dist(rg.engine) < chance) ? Method::grow : Method::full;
root = Node{method, depth, min, max};
/*The evaluate method updates the size and both raw and adjusted
fitnesses. */
evaluate(values);
}
// Return string representation of a tree's size and fitness.
string
Individual::print() const
{
using std::to_string;
string info = "# Size " + to_string(get_total())
+ ", with " + to_string(get_internals())
+ " internals, and " + to_string(get_leaves()) + " leaves.\n"
+ "# Raw fitness: " + to_string(get_fitness())
+ ", and adjusted: " + to_string(get_adjusted()) + ".\n";
return info;
}
// Return string represenation of tree's expression (delegated).
string
Individual::print_formula() const
{
return "# Formula: " + root.print() + "\n";
}
// Read-only "getters" for private data
unsigned int
Individual::get_internals() const
{
return size.internals;
}
unsigned int
Individual::get_leaves() const
{
return size.leaves;
}
unsigned int
Individual::get_total() const
{
return size.internals + size.leaves;
}
double
Individual::get_fitness() const
{
return fitness;
}
double
Individual::get_adjusted() const
{
return adjusted;
}
/* Evaluate Individual for given values and calculate size. Update
Individual's size and fitness accordingly. Return non-empty
string if printing. */
string
Individual::evaluate(const options::pairs& values, const double& penalty,
const bool& print)
{
using std::to_string;
using std::get;
string calculation = "# x - y - expected - error\n";
// Update size on evaluation because it's incredibly convenient.
size = root.size();
// Reset fitness and apply scaled size penalty.
fitness = penalty * get_total();
// Evalute for given values.
for (auto pair : values)
{
double x = std::get<0>(pair);
double y = root.evaluate(x);
assert(not std::isnan(y) and not std::isinf(y));
double expected = std::get<1>(pair);
double error = std::pow(y - expected, 2);
fitness += error;
if (print) // Concatenate information if printing.
{
calculation += to_string(x) + "\t"
+ to_string(y) + "\t"
+ to_string(expected) + "\t"
+ to_string(error) + "\n";
}
}
adjusted = (double) 1 / (1 + fitness - penalty * get_total());
return calculation;
}
// Mutate each node with given probability.
void
Individual::mutate(const double& chance)
{
root.mutate_tree(chance);
}
// Safely return reference to desired node.
Node&
Individual::operator[](const Size& i)
{
assert(i.internals <= get_internals());
assert(i.leaves <= get_leaves());
Size visiting;
// Return root node if that's what we're seeking.
if (i.internals == 0 and i.leaves == 0)
return root;
else
return root.visit(i, visiting);
}
/* Swap two random subtrees between Individuals "a" and "b",
selecting an internal node with chance probability. TODO: DRY */
void
crossover(const double& chance, Individual& a, Individual& b)
{
real_dist probability{0, 1};
Size target_a, target_b;
// Guaranteed to have at least 1 leaf, but may have 0 internals.
if (a.get_internals() != 0 and probability(rg.engine) < chance)
{
// Choose an internal node.
int_dist dist{0, (int) a.get_internals() - 1};
target_a.internals = dist(rg.engine);
}
else
{
// Otherwise choose a leaf node.
int_dist dist{0, (int) a.get_leaves() - 1};
target_a.leaves = dist(rg.engine);
}
// Totally repeating myself here for "b".
if (b.get_internals() != 0 and probability(rg.engine) < chance)
{
int_dist dist{0, (int) b.get_internals() - 1};
target_b.internals = dist(rg.engine);
}
else
{
int_dist dist{0, (int) b.get_leaves() - 1};
target_b.leaves = dist(rg.engine);
}
std::swap(a[target_a], b[target_b]);
}
}
<commit_msg>Fixing node constructor for grow method<commit_after>/* indivudal.cpp - CS 472 Project #2: Genetic Programming
* Copyright 2014 Andrew Schwartzmeyer
*
* Source file for individual namespace
*/
#include <algorithm>
#include <cassert>
#include <cmath>
#include <iostream>
#include <memory>
#include <tuple>
#include <vector>
#include "individual.hpp"
#include "../options/options.hpp"
#include "../random_generator/random_generator.hpp"
namespace individual
{
using std::vector;
using std::string;
using namespace random_generator;
// Default Size struct constructor.
Size::Size(): internals{0}, leaves{0} {}
// Available methods for tree creation.
enum class Method {grow, full};
// List of valid functions for an expression.
enum class Function {nil, constant, input, sqrt, sin, cos, log, exp,
add, subtract, divide, multiply, pow, lesser, greater};
using F = Function;
// Vectors of same-arity function enums.
vector <F> nullaries {F::constant, F::input};
vector <F> unaries {F::sqrt, F::sin, F::cos, F::log, F::exp};
vector <F> binaries {F::add, F::subtract, F::multiply, F::divide, F::pow};
vector <F> quadnaries {F::lesser, F::greater};
/* Vectors of available function enums. Should be moved into
Options struct. */
vector <F> leaves {F::constant, F::input};
vector <F> internals {F::sin, F::cos, F::add, F::subtract,
F::multiply, F::divide, F::lesser, F::greater};
// Returns a random function from a given set of functions.
Function
get_function(const vector <Function>& functions)
{
int_dist dist{0, (int) functions.size() - 1}; // closed interval
return functions[dist(rg.engine)];
}
// Returns a random double between min and max.
double
get_constant(const double& min, const double& max)
{
real_dist dist{min, max};
return dist(rg.engine);
}
// Returns bool of whether or not the item is in the set.
template<typename I, typename S> bool
contains(const I& item, const S& set)
{
return std::find(set.begin(), set.end(), item) != set.end();
}
// Returns the appropriate arity for a given function.
unsigned int
get_arity(const Function& function)
{
if (contains(function, nullaries))
return 0;
else if (contains(function, unaries))
return 1;
else if (contains(function, binaries))
return 2;
else if (contains(function, quadnaries))
return 4;
assert(false);
}
// Default constructor for "empty" node
Node::Node(): function{Function::nil}, arity{0}, value{0} {}
/* Recursively constructs a parse tree using the given method
(either GROW or FULL). */
Node::Node(const Method& method, const unsigned int& max_depth,
const double& constant_min, const double& constant_max)
{
// Create terminal node if at the max depth or randomly (if growing).
real_dist dist{0, 1};
double grow_chance =
static_cast<double>(leaves.size()) / (leaves.size() + internals.size());
if (max_depth == 0
or (method == Method::grow and dist(rg.engine) < grow_chance))
{
function = get_function(leaves);
arity = get_arity(function);
// Setup constant function; input is provided on evaluation.
if (function == Function::constant)
value = get_constant(constant_min, constant_max);
}
// Otherwise choose a non-terminal node.
else
{
function = get_function(internals);
// Determine node's arity.
arity = get_arity(function);
// Recursively create subtrees.
for (unsigned int i = 0; i < arity; ++i)
children.emplace_back(Node{
method, max_depth - 1, constant_min, constant_max});
}
assert(function != Function::nil); // do not create null types
assert(children.size() == arity); // ensure arity
}
// Returns a string visually representing a particular node.
string
Node::represent() const
{
switch (function)
{
case F::nil:
assert(false); // Never represent empty node.
case F::constant:
return std::to_string(value);
case F::input:
return "x";
case F::sqrt:
return "sqrt";
case F::sin:
return "sin";
case F::cos:
return "cos";
case F::log:
return "log";
case F::exp:
return "exp";
case F::add:
return "+";
case F::subtract:
return "-";
case F::multiply:
return "*";
case F::divide:
return "%";
case F::pow:
return "^";
case F::lesser:
return "<";
case F::greater:
return ">";
}
assert(false); // Every node should have been matched.
}
/* Returns string representation of expression in Polish/prefix
notation using a pre-order traversal. */
string
Node::print() const
{
if (children.size() == 0)
return represent();
string formula = "(" + represent();
for (const Node& child : children)
formula += " " + child.print();
return formula + ")";
}
/* Returns a double as the result of a depth-first post-order
recursive evaluation of a parse tree. */
double
Node::evaluate(const double& x) const
{
double a, b;
// Evaluate children a and possibly b.
if (arity == 1)
a = children[0].evaluate(x);
else if (arity == 2 or arity == 4)
{
a = children[0].evaluate(x);
b = children[1].evaluate(x);
// Children c and d are evaluated conditionally.
}
// Calculate the result for the given function.
switch (function)
{
case F::nil:
assert(false); // Never calculate empty node.
case F::constant:
assert(arity == 0);
return value;
case F::input:
assert(arity == 0);
return x;
case F::sqrt:
assert(arity == 1);
return std::sqrt(std::abs(a)); // Protected via abs.
case F::sin:
assert(arity == 1);
return std::sin(a);
case F::cos:
assert(arity == 1);
return std::cos(a);
case F::log:
assert(arity == 1);
return (a == 0) ? 0 : std::log(std::abs(a)); // Protected via abs.
case F::exp:
assert(arity == 1);
return std::exp(a);
case F::add:
assert(arity == 2);
return a + b;
case F::subtract:
assert(arity == 2);
return a - b;
case F::multiply:
assert(arity == 2);
return a * b;
case F::divide:
assert(arity == 2);
return (b == 0) ? 1 : a / b; // Protected divide by zero: return 1.
case F::pow:
assert(arity == 2);
return std::pow(std::abs(a), std::abs(b)); // Protected via abs.
case F::lesser:
assert(arity == 4);
return (a < b) ? children[2].evaluate(x) : children[3].evaluate(x);
case F::greater:
assert(arity == 4);
return (a > b) ? children[2].evaluate(x) : children[3].evaluate(x);
}
assert(false);
}
/* Recursively count children via post-order traversal. Keep track
of internals and leaves via Size struct */
const Size
Node::size() const
{
Size size;
for (const Node& child : children)
{
Size temp = child.size();
size.internals += temp.internals;
size.leaves += temp.leaves;
}
if (children.size() == 0)
++size.leaves;
else
++size.internals;
return size;
}
// Used to represent "not-found" (similar to a NULL pointer).
Node empty;
/* Depth-first search for taget node. Must be seeking either
internal or leaf, cannot be both. */
Node&
Node::visit(const Size& i, Size& visiting)
{
for (Node& child : children) {
// Increase relevant count.
if (child.children.size() == 0)
++visiting.leaves;
else
++visiting.internals;
// Return node reference if found.
if (visiting.internals == i.internals or visiting.leaves == i.leaves)
return child;
else
{
Node& temp = child.visit(i, visiting); // Recursive search.
if (temp.function != Function::nil)
return temp;
}
}
return empty;
}
// Single node mutation to different function of same arity.
void
Node::mutate_self()
{
/* Mutate constant to a value in its neighborhood. Here we do
not switch functions (between CONSTANT and INPUT), as it
introduces too much volatility into the terminals. TODO:
review the above and possibly change. */
if (arity == 0)
{
if (function == Function::constant)
{
normal_dist dist{0, 1};
value *= 1 + dist(rg.engine);
}
}
/* Otherwise mutate to internal function of same arity. We do
this by saving the old function and arity, then repeatedly
drawing a new random function until the arity matches and it is
not the original function. */
else
{
Function old_function = function;
unsigned int old_arity = arity;
while (function == old_function or arity != old_arity)
{
function = get_function(internals);
arity = get_arity(function);
}
assert(function != old_function and arity == old_arity);
}
assert(function != Function::nil);
}
// Recursively mutate nodes with given probability.
void
Node::mutate_tree(const double& chance)
{
real_dist dist{0, 1};
for (Node& child : children)
{
if (dist(rg.engine) < chance)
child.mutate_self();
child.mutate_tree(chance);
}
}
// Default constructor for Individual
Individual::Individual() {}
/* Create an Individual tree by having a root node (to which the
actual construction is delegated). The depth is passed by value
as its creation elsewhere is temporary. */
Individual::Individual(const unsigned int depth, const double& chance,
const double& min, const double& max,
const options::pairs& values): fitness{0}, adjusted{0}
{
real_dist dist{0, 1};
Method method = (dist(rg.engine) < chance) ? Method::grow : Method::full;
root = Node{method, depth, min, max};
/*The evaluate method updates the size and both raw and adjusted
fitnesses. */
evaluate(values);
}
// Return string representation of a tree's size and fitness.
string
Individual::print() const
{
using std::to_string;
string info = "# Size " + to_string(get_total())
+ ", with " + to_string(get_internals())
+ " internals, and " + to_string(get_leaves()) + " leaves.\n"
+ "# Raw fitness: " + to_string(get_fitness())
+ ", and adjusted: " + to_string(get_adjusted()) + ".\n";
return info;
}
// Return string represenation of tree's expression (delegated).
string
Individual::print_formula() const
{
return "# Formula: " + root.print() + "\n";
}
// Read-only "getters" for private data
unsigned int
Individual::get_internals() const
{
return size.internals;
}
unsigned int
Individual::get_leaves() const
{
return size.leaves;
}
unsigned int
Individual::get_total() const
{
return size.internals + size.leaves;
}
double
Individual::get_fitness() const
{
return fitness;
}
double
Individual::get_adjusted() const
{
return adjusted;
}
/* Evaluate Individual for given values and calculate size. Update
Individual's size and fitness accordingly. Return non-empty
string if printing. */
string
Individual::evaluate(const options::pairs& values, const double& penalty,
const bool& print)
{
using std::to_string;
using std::get;
string calculation = "# x - y - expected - error\n";
// Update size on evaluation because it's incredibly convenient.
size = root.size();
// Reset fitness and apply scaled size penalty.
fitness = penalty * get_total();
// Evalute for given values.
for (auto pair : values)
{
double x = std::get<0>(pair);
double y = root.evaluate(x);
assert(not std::isnan(y) and not std::isinf(y));
double expected = std::get<1>(pair);
double error = std::pow(y - expected, 2);
fitness += error;
if (print) // Concatenate information if printing.
{
calculation += to_string(x) + "\t"
+ to_string(y) + "\t"
+ to_string(expected) + "\t"
+ to_string(error) + "\n";
}
}
adjusted = (double) 1 / (1 + fitness - penalty * get_total());
return calculation;
}
// Mutate each node with given probability.
void
Individual::mutate(const double& chance)
{
root.mutate_tree(chance);
}
// Safely return reference to desired node.
Node&
Individual::operator[](const Size& i)
{
assert(i.internals <= get_internals());
assert(i.leaves <= get_leaves());
Size visiting;
// Return root node if that's what we're seeking.
if (i.internals == 0 and i.leaves == 0)
return root;
else
return root.visit(i, visiting);
}
/* Swap two random subtrees between Individuals "a" and "b",
selecting an internal node with chance probability. TODO: DRY */
void
crossover(const double& chance, Individual& a, Individual& b)
{
real_dist probability{0, 1};
Size target_a, target_b;
// Guaranteed to have at least 1 leaf, but may have 0 internals.
if (a.get_internals() != 0 and probability(rg.engine) < chance)
{
// Choose an internal node.
int_dist dist{0, (int) a.get_internals() - 1};
target_a.internals = dist(rg.engine);
}
else
{
// Otherwise choose a leaf node.
int_dist dist{0, (int) a.get_leaves() - 1};
target_a.leaves = dist(rg.engine);
}
// Totally repeating myself here for "b".
if (b.get_internals() != 0 and probability(rg.engine) < chance)
{
int_dist dist{0, (int) b.get_internals() - 1};
target_b.internals = dist(rg.engine);
}
else
{
int_dist dist{0, (int) b.get_leaves() - 1};
target_b.leaves = dist(rg.engine);
}
std::swap(a[target_a], b[target_b]);
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014 The Mini-Blockchain Project
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "assert.h"
#include "core.h"
#include "protocol.h"
#include "util.h"
#include "trie.h"
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
//
// Main network
//
unsigned int pnSeed[] =
{
0x0ce5bb25, 0x0ee5bb25, 0xe4540905
};
void MineGenesis(CBlock genesis){
// This will figure out a valid hash and Nonce if you're creating a different genesis block:
uint256 hashTarget = CBigNum().SetCompact(Params().ProofOfWorkLimit().GetCompact()).getuint256();
printf("Target: %s\n", hashTarget.GetHex().c_str());
uint256 newhash = genesis.GetHash();
uint256 besthash;
memset(&besthash,0xFF,32);
while (newhash > hashTarget) {
++genesis.nNonce;
if (genesis.nNonce == 0){
printf("NONCE WRAPPED, incrementing time");
++genesis.nTime;
}
newhash = genesis.GetHash();
if(newhash < besthash){
besthash=newhash;
printf("New best: %s\n", newhash.GetHex().c_str());
}
}
printf("Found Genesis, Nonce: %ld, Hash: %s\n", genesis.nNonce, genesis.GetHash().GetHex().c_str());
exit(0);
}
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0xf9;
pchMessageStart[1] = 0xbe;
pchMessageStart[2] = 0xb4;
pchMessageStart[3] = 0xd9;
vAlertPubKey = ParseHex("02bcd71fb5844bb64b486c8645d0c9ed500c9b854e721f924c017f6fbb61fd156a");
nDefaultPort = 8253;
nRPCPort = 8252;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);
nSubsidyHalvingInterval = 210000;
//printf("Target: %s\n", GetTargetWork(4096.0).GetHex().c_str()); exit(0);
// Build the genesis block. Note that the output of the genesis coinbase cannot
// be spent as it did not originally exist in the database.
//
// CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
// CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
// CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
// CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
// vMerkleTree: 4a5e1e
CTransaction txNew;
txNew.vin.resize(0);
txNew.vout.resize(1);
txNew.vout[0].nValue = MAX_MONEY; //All coins created in genesis
txNew.vout[0].pubKey = 0; //Genesis target is coinbase
txNew.nLockHeight=0;
string msg = "2014/07/27 - Epoch Times - How Bitcoin Compares...";
txNew.msg = vector<char>(msg.begin(),msg.end());
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
//Build a single trienode to find the hash of the coinbase only trie
TrieNode *coinbase = new TrieNode(NODE_LEAF);
coinbase->SetKey(0);
coinbase->SetBalance(txNew.vout[0].nValue);
genesis.hashAccountRoot = coinbase->Hash(); //TODO: get the trie hash
delete coinbase;
genesis.nVersion = 1;
genesis.nHeight = 0;
genesis.nTime = 1406509200;
genesis.nNonce = 1041215929;
hashGenesisBlock = genesis.GetHash();
//printf("%s\n", genesis.GetHash().ToString().c_str());
//printf("%s\n", genesis.hashMerkleRoot.ToString().c_str());
assert(genesis.hashMerkleRoot == uint256("0x9dabd47e692ed615eae95da0c95f195a7dea9428bb9f9e0cd4c7d12533bf3667"));
if(hashGenesisBlock != uint256("0x000009a460ccc429ac6e53c91c6ed2d96697884b8b656a903042faff8971c5aa"))
MineGenesis(genesis);
vSeeds.push_back(CDNSSeedData("gpile.it", "gpile.it"));
//sa ToDO: Review. The convert_to_container stuff was added as a quick fix to get it building in c++11. it should work
// but not 100% certain and haven't tested
base58Prefixes[PUBKEY_ADDRESS] = (list_of(28)).convert_to_container<vector<unsigned char> >();
base58Prefixes[SCRIPT_ADDRESS] = (list_of(5)).convert_to_container<vector<unsigned char> >();
base58Prefixes[SECRET_KEY] = (list_of(128)).convert_to_container<vector<unsigned char> >();
base58Prefixes[EXT_PUBLIC_KEY] = (list_of(0x04)(0x88)(0xB2)(0x1E)).convert_to_container<vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = (list_of(0x04)(0x88)(0xAD)(0xE4)).convert_to_container<vector<unsigned char> >();
// Convert the pnSeeds array into usable address objects.
for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
struct in_addr ip;
memcpy(&ip, &pnSeed[i], sizeof(ip));
CAddress addr(CService(ip, GetDefaultPort()));
addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
vFixedSeeds.push_back(addr);
}
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet (v3)
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x0c;
pchMessageStart[1] = 0x12;
pchMessageStart[2] = 0x09;
pchMessageStart[3] = 0x07;
vAlertPubKey = ParseHex("02bcd71fb5844bb64b486c8645d0c9ed500c9b854e721f924c017f6fbb61fd156a");
nDefaultPort = 18253;
nRPCPort = 18252;
strDataDir = "testnet3";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nTime = 1406495892;
genesis.nNonce = 9337333;
string msg = "foo";
genesis.vtx[0].msg = vector<char>(msg.begin(),msg.end());
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
hashGenesisBlock = genesis.GetHash();
//printf("%s\n", genesis.GetHash().ToString().c_str());
// assert(hashGenesisBlock == uint256("0xcc9c9f3b61e8422bc54b86925238262a2994f265aea14b5e10e3d2fd4cb413a8"));
if(hashGenesisBlock!= uint256("0000069d96f7f6135475139bc49f268997cb14850aae8feedf70047cfd89291a")){
MineGenesis(genesis);
}
vFixedSeeds.clear();
vSeeds.push_back(CDNSSeedData("seed.cryptonite.info", "seed.cryptonite.info"));
//sa ToDO: Review. The convert_to_container stuff was added as a quick fix to get it building in c++11. it should work
// but not 100% certain and haven't tested
base58Prefixes[PUBKEY_ADDRESS] = (list_of(87)).convert_to_container<vector<unsigned char> >();
base58Prefixes[SCRIPT_ADDRESS] = (list_of(196)).convert_to_container<vector<unsigned char> >();
base58Prefixes[SECRET_KEY] = (list_of(239)).convert_to_container<vector<unsigned char> >();
base58Prefixes[EXT_PUBLIC_KEY] = (list_of(0x04)(0x35)(0x87)(0xCF)).convert_to_container<vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = (list_of(0x04)(0x35)(0x83)(0x94)).convert_to_container<vector<unsigned char> >();
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
<commit_msg>Change alert key<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014 The Mini-Blockchain Project
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "assert.h"
#include "core.h"
#include "protocol.h"
#include "util.h"
#include "trie.h"
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
//
// Main network
//
unsigned int pnSeed[] =
{
0x0ce5bb25, 0x0ee5bb25, 0xe4540905
};
void MineGenesis(CBlock genesis){
// This will figure out a valid hash and Nonce if you're creating a different genesis block:
uint256 hashTarget = CBigNum().SetCompact(Params().ProofOfWorkLimit().GetCompact()).getuint256();
printf("Target: %s\n", hashTarget.GetHex().c_str());
uint256 newhash = genesis.GetHash();
uint256 besthash;
memset(&besthash,0xFF,32);
while (newhash > hashTarget) {
++genesis.nNonce;
if (genesis.nNonce == 0){
printf("NONCE WRAPPED, incrementing time");
++genesis.nTime;
}
newhash = genesis.GetHash();
if(newhash < besthash){
besthash=newhash;
printf("New best: %s\n", newhash.GetHex().c_str());
}
}
printf("Found Genesis, Nonce: %ld, Hash: %s\n", genesis.nNonce, genesis.GetHash().GetHex().c_str());
exit(0);
}
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0xf9;
pchMessageStart[1] = 0xbe;
pchMessageStart[2] = 0xb4;
pchMessageStart[3] = 0xd9;
vAlertPubKey = ParseHex("038b1e94fa4d647bb8ea50b1540b2a04846181fd10d87e35b609311054ab02cba3");
nDefaultPort = 8253;
nRPCPort = 8252;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);
nSubsidyHalvingInterval = 210000;
//printf("Target: %s\n", GetTargetWork(4096.0).GetHex().c_str()); exit(0);
// Build the genesis block. Note that the output of the genesis coinbase cannot
// be spent as it did not originally exist in the database.
//
// CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
// CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
// CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
// CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
// vMerkleTree: 4a5e1e
CTransaction txNew;
txNew.vin.resize(0);
txNew.vout.resize(1);
txNew.vout[0].nValue = MAX_MONEY; //All coins created in genesis
txNew.vout[0].pubKey = 0; //Genesis target is coinbase
txNew.nLockHeight=0;
string msg = "2014/07/27 - Epoch Times - How Bitcoin Compares...";
txNew.msg = vector<char>(msg.begin(),msg.end());
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
//Build a single trienode to find the hash of the coinbase only trie
TrieNode *coinbase = new TrieNode(NODE_LEAF);
coinbase->SetKey(0);
coinbase->SetBalance(txNew.vout[0].nValue);
genesis.hashAccountRoot = coinbase->Hash(); //TODO: get the trie hash
delete coinbase;
genesis.nVersion = 1;
genesis.nHeight = 0;
genesis.nTime = 1406509200;
genesis.nNonce = 1041215929;
hashGenesisBlock = genesis.GetHash();
//printf("%s\n", genesis.GetHash().ToString().c_str());
//printf("%s\n", genesis.hashMerkleRoot.ToString().c_str());
assert(genesis.hashMerkleRoot == uint256("0x9dabd47e692ed615eae95da0c95f195a7dea9428bb9f9e0cd4c7d12533bf3667"));
if(hashGenesisBlock != uint256("0x000009a460ccc429ac6e53c91c6ed2d96697884b8b656a903042faff8971c5aa"))
MineGenesis(genesis);
vSeeds.push_back(CDNSSeedData("gpile.it", "gpile.it"));
//sa ToDO: Review. The convert_to_container stuff was added as a quick fix to get it building in c++11. it should work
// but not 100% certain and haven't tested
base58Prefixes[PUBKEY_ADDRESS] = (list_of(28)).convert_to_container<vector<unsigned char> >();
base58Prefixes[SCRIPT_ADDRESS] = (list_of(5)).convert_to_container<vector<unsigned char> >();
base58Prefixes[SECRET_KEY] = (list_of(128)).convert_to_container<vector<unsigned char> >();
base58Prefixes[EXT_PUBLIC_KEY] = (list_of(0x04)(0x88)(0xB2)(0x1E)).convert_to_container<vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = (list_of(0x04)(0x88)(0xAD)(0xE4)).convert_to_container<vector<unsigned char> >();
// Convert the pnSeeds array into usable address objects.
for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
struct in_addr ip;
memcpy(&ip, &pnSeed[i], sizeof(ip));
CAddress addr(CService(ip, GetDefaultPort()));
addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
vFixedSeeds.push_back(addr);
}
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet (v3)
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x0c;
pchMessageStart[1] = 0x12;
pchMessageStart[2] = 0x09;
pchMessageStart[3] = 0x07;
vAlertPubKey = ParseHex("038b1e94fa4d647bb8ea50b1540b2a04846181fd10d87e35b609311054ab02cba3");
nDefaultPort = 18253;
nRPCPort = 18252;
strDataDir = "testnet3";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nTime = 1406495892;
genesis.nNonce = 9337333;
string msg = "foo";
genesis.vtx[0].msg = vector<char>(msg.begin(),msg.end());
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
hashGenesisBlock = genesis.GetHash();
//printf("%s\n", genesis.GetHash().ToString().c_str());
// assert(hashGenesisBlock == uint256("0xcc9c9f3b61e8422bc54b86925238262a2994f265aea14b5e10e3d2fd4cb413a8"));
if(hashGenesisBlock!= uint256("0000069d96f7f6135475139bc49f268997cb14850aae8feedf70047cfd89291a")){
MineGenesis(genesis);
}
vFixedSeeds.clear();
vSeeds.push_back(CDNSSeedData("seed.cryptonite.info", "seed.cryptonite.info"));
//sa ToDO: Review. The convert_to_container stuff was added as a quick fix to get it building in c++11. it should work
// but not 100% certain and haven't tested
base58Prefixes[PUBKEY_ADDRESS] = (list_of(87)).convert_to_container<vector<unsigned char> >();
base58Prefixes[SCRIPT_ADDRESS] = (list_of(196)).convert_to_container<vector<unsigned char> >();
base58Prefixes[SECRET_KEY] = (list_of(239)).convert_to_container<vector<unsigned char> >();
base58Prefixes[EXT_PUBLIC_KEY] = (list_of(0x04)(0x35)(0x87)(0xCF)).convert_to_container<vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = (list_of(0x04)(0x35)(0x83)(0x94)).convert_to_container<vector<unsigned char> >();
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014 Kryptohash developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
#include <stdint.h>
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
namespace Checkpoints
{
typedef std::map<int64_t, uint320> MapCheckpoints;
// How many times we expect transactions after the last checkpoint to
// be slower. This number is a compromise, as it can't be accurate for
// every system. When reindexing from a fast disk with a slow CPU, it
// can be up to 20, while when downloading from a slow network with a
// fast multicore CPU, it won't be much higher than 1.
static const double SIGCHECK_VERIFICATION_FACTOR = 5.0;
struct CCheckpointData {
const MapCheckpoints *mapCheckpoints;
int64_t nTimeLastCheckpoint;
int64_t nTransactionsLastCheckpoint;
double fTransactionsPerDay;
};
bool fEnabled = true;
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
(0, uint320(0))
;
static const CCheckpointData data = {
&mapCheckpoints,
0x1488DDBA3EE, // * UNIX timestamp of last checkpoint block
0, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
60000.0 // * estimated number of transactions per day after checkpoint
};
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 0, uint320(0))
;
static const CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
0x1488DDBA3EE,
0,
300.0
};
static MapCheckpoints mapCheckpointsRegtest =
boost::assign::map_list_of
( 0, uint320(0))
;
static const CCheckpointData dataRegtest = {
&mapCheckpointsRegtest,
0,
0,
0
};
const CCheckpointData &Checkpoints() {
if (Params().NetworkID() == CChainParams::TESTNET) {
return dataTestnet;
}
else if (Params().NetworkID() == CChainParams::MAIN) {
return data;
}
else {
return dataRegtest;
}
}
bool CheckBlock(int64_t nHeight, const uint320& hash)
{
if (!fEnabled) {
return true;
}
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) {
return true;
}
return hash == i->second;
}
// Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(CBlockIndex *pindex, bool fSigchecks) {
if (pindex == NULL) {
return 0.0;
}
int64_t nNow = time(NULL);
double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0;
double fWorkBefore = 0.0; // Amount of work done before pindex
double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
// Work is defined as: 1.0 per transaction before the last checkpoint, and
// fSigcheckVerificationFactor per transaction after.
const CCheckpointData &data = Checkpoints();
if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
double nCheapBefore = pindex->nChainTx;
double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore;
fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
} else {
double nCheapBefore = data.nTransactionsLastCheckpoint;
double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
}
return fWorkBefore / (fWorkBefore + fWorkAfter);
}
int64_t GetTotalBlocksEstimate()
{
if (!fEnabled) {
return 0;
}
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint320, CBlockIndex*>& mapBlockIndex)
{
if (!fEnabled) {
return NULL;
}
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint320& hash = i.second;
std::map<uint320, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end()) {
return t->second;
}
}
return NULL;
}
}
namespace PIDCheckpoints
{
typedef std::map<int64_t, CPID> MapPIDCheckpoints;
struct CPIDCheckpointData {
const MapPIDCheckpoints *mapPIDCheckpoints;
int64_t nTimeLastCheckpoint;
};
bool fEnabled = true;
static MapPIDCheckpoints mapPIDCheckpoints =
boost::assign::map_list_of
(0, CPID(180.0f, 1.0f, 0.05f, 0.1f))
;
static const CPIDCheckpointData data = {
&mapPIDCheckpoints,
0x148d455b42a // * timestamp of last PID checkpoint
};
static MapPIDCheckpoints mapPIDCheckpointsTestnet =
boost::assign::map_list_of
(0, CPID(180.0f, 1.0f, 0.05f, 0.1f))
;
static const CPIDCheckpointData dataTestnet = {
&mapPIDCheckpointsTestnet,
0x148d455b42a
};
static MapPIDCheckpoints mapPIDCheckpointsRegtest =
boost::assign::map_list_of
(0, CPID(180.0f, 1.0f, 0.05f, 0.1f))
;
static const CPIDCheckpointData dataRegtest = {
&mapPIDCheckpointsRegtest,
0
};
const CPIDCheckpointData &PIDCheckpoints() {
if (Params().NetworkID() == CChainParams::TESTNET) {
return dataTestnet;
}
else if (Params().NetworkID() == CChainParams::MAIN) {
return data;
}
else {
return dataRegtest;
}
}
int64_t PIDGetHeightLastCheckpoint()
{
if (!fEnabled) {
return 0;
}
const MapPIDCheckpoints& PIDcheckpoints = *PIDCheckpoints().mapPIDCheckpoints;
return PIDcheckpoints.rbegin()->first;
}
int64_t PIDGetTimeLastCheckpoint()
{
if (!fEnabled) {
return 0;
}
const int64_t PIDcheckpointTime = PIDCheckpoints().nTimeLastCheckpoint;
return PIDcheckpointTime;
}
const CPID* GetPIDCheckpoint(int64_t height)
{
if (!fEnabled) {
return NULL;
}
const MapPIDCheckpoints& PIDcheckpoints = *PIDCheckpoints().mapPIDCheckpoints;
BOOST_REVERSE_FOREACH(const MapPIDCheckpoints::value_type& i, PIDcheckpoints)
{
if (i.first <= height) {
const CPID& PIDChkpoint = i.second;
return &PIDChkpoint;
}
}
return NULL;
}
}
<commit_msg>Added first checkpoint at block #99<commit_after>// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014 Kryptohash developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
#include <stdint.h>
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
namespace Checkpoints
{
typedef std::map<int64_t, uint320> MapCheckpoints;
// How many times we expect transactions after the last checkpoint to
// be slower. This number is a compromise, as it can't be accurate for
// every system. When reindexing from a fast disk with a slow CPU, it
// can be up to 20, while when downloading from a slow network with a
// fast multicore CPU, it won't be much higher than 1.
static const double SIGCHECK_VERIFICATION_FACTOR = 5.0;
struct CCheckpointData {
const MapCheckpoints *mapCheckpoints;
int64_t nTimeLastCheckpoint;
int64_t nTransactionsLastCheckpoint;
double fTransactionsPerDay;
};
bool fEnabled = true;
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
(99, uint320("00000018CE97B434F8396CB989C61190BB72B8CD2A7352C48C91AEDB2E0F8AFCE8CDB7A59334E95B"))
;
static const CCheckpointData data = {
&mapCheckpoints,
0x14a0e8193b3, // * UNIX timestamp of last checkpoint block
218, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
60000.0 // * estimated number of transactions per day after checkpoint
};
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 0, uint320(0))
;
static const CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
0x1488DDBA3EE,
0,
300.0
};
static MapCheckpoints mapCheckpointsRegtest =
boost::assign::map_list_of
( 0, uint320(0))
;
static const CCheckpointData dataRegtest = {
&mapCheckpointsRegtest,
0,
0,
0
};
const CCheckpointData &Checkpoints() {
if (Params().NetworkID() == CChainParams::TESTNET) {
return dataTestnet;
}
else if (Params().NetworkID() == CChainParams::MAIN) {
return data;
}
else {
return dataRegtest;
}
}
bool CheckBlock(int64_t nHeight, const uint320& hash)
{
if (!fEnabled) {
return true;
}
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) {
return true;
}
return hash == i->second;
}
// Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(CBlockIndex *pindex, bool fSigchecks) {
if (pindex == NULL) {
return 0.0;
}
int64_t nNow = time(NULL);
double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0;
double fWorkBefore = 0.0; // Amount of work done before pindex
double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
// Work is defined as: 1.0 per transaction before the last checkpoint, and
// fSigcheckVerificationFactor per transaction after.
const CCheckpointData &data = Checkpoints();
if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
double nCheapBefore = pindex->nChainTx;
double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore;
fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
} else {
double nCheapBefore = data.nTransactionsLastCheckpoint;
double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
}
return fWorkBefore / (fWorkBefore + fWorkAfter);
}
int64_t GetTotalBlocksEstimate()
{
if (!fEnabled) {
return 0;
}
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint320, CBlockIndex*>& mapBlockIndex)
{
if (!fEnabled) {
return NULL;
}
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint320& hash = i.second;
std::map<uint320, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end()) {
return t->second;
}
}
return NULL;
}
}
namespace PIDCheckpoints
{
typedef std::map<int64_t, CPID> MapPIDCheckpoints;
struct CPIDCheckpointData {
const MapPIDCheckpoints *mapPIDCheckpoints;
int64_t nTimeLastCheckpoint;
};
bool fEnabled = true;
static MapPIDCheckpoints mapPIDCheckpoints =
boost::assign::map_list_of
(0, CPID(180.0f, 1.0f, 0.05f, 0.1f))
;
static const CPIDCheckpointData data = {
&mapPIDCheckpoints,
0x148d455b42a // * timestamp of last PID checkpoint
};
static MapPIDCheckpoints mapPIDCheckpointsTestnet =
boost::assign::map_list_of
(0, CPID(180.0f, 1.0f, 0.05f, 0.1f))
;
static const CPIDCheckpointData dataTestnet = {
&mapPIDCheckpointsTestnet,
0x148d455b42a
};
static MapPIDCheckpoints mapPIDCheckpointsRegtest =
boost::assign::map_list_of
(0, CPID(180.0f, 1.0f, 0.05f, 0.1f))
;
static const CPIDCheckpointData dataRegtest = {
&mapPIDCheckpointsRegtest,
0
};
const CPIDCheckpointData &PIDCheckpoints() {
if (Params().NetworkID() == CChainParams::TESTNET) {
return dataTestnet;
}
else if (Params().NetworkID() == CChainParams::MAIN) {
return data;
}
else {
return dataRegtest;
}
}
int64_t PIDGetHeightLastCheckpoint()
{
if (!fEnabled) {
return 0;
}
const MapPIDCheckpoints& PIDcheckpoints = *PIDCheckpoints().mapPIDCheckpoints;
return PIDcheckpoints.rbegin()->first;
}
int64_t PIDGetTimeLastCheckpoint()
{
if (!fEnabled) {
return 0;
}
const int64_t PIDcheckpointTime = PIDCheckpoints().nTimeLastCheckpoint;
return PIDcheckpointTime;
}
const CPID* GetPIDCheckpoint(int64_t height)
{
if (!fEnabled) {
return NULL;
}
const MapPIDCheckpoints& PIDcheckpoints = *PIDCheckpoints().mapPIDCheckpoints;
BOOST_REVERSE_FOREACH(const MapPIDCheckpoints::value_type& i, PIDcheckpoints)
{
if (i.first <= height) {
const CPID& PIDChkpoint = i.second;
return &PIDChkpoint;
}
}
return NULL;
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
// How many times we expect transactions after the last checkpoint to
// be slower. This number is a compromise, as it can't be accurate for
// every system. When reindexing from a fast disk with a slow CPU, it
// can be up to 20, while when downloading from a slow network with a
// fast multicore CPU, it won't be much higher than 1.
static const double fSigcheckVerificationFactor = 5.0;
struct CCheckpointData {
const MapCheckpoints *mapCheckpoints;
int64 nTimeLastCheckpoint;
int64 nTransactionsLastCheckpoint;
double fTransactionsPerDay;
};
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("0x19225ae90d538561217b5949e98ca4964ac91af39090d1a4407c892293e4f44f"))
( 10, uint256("0xb98fe58aa04ca9a5a216c0bd01d952e0fff16e702d0fb512f748f201b9be26fb"))
( 100, uint256("0x56b00c7d17fd10680dfafa0617f26af75f6c2b0c11aafa9cf1b6704de2766f72"))
( 1000, uint256("0x076d62aef68a8330e5f927cdbc23d58ac1e2838877936512aa16487f098d35ca"))
( 5000, uint256("0x5b7fc427fa913510186e034e1415bdf987d37f4674c2f2fd0b492836fc58de0d"))
( 10000, uint256("0xd4bf99505611f97b6cf6f273a79c21c1b21b03238b06396e2e9a02f83c13d01c"))
( 27000, uint256("0x397e50d20f9a21f274b8787fa66ca1ebc208a1b7e5bc3a9a0e352350bd42e125"))
( 27650, uint256("0xb2a25b57648bf10a81dcc3b23fb758bceb6f652d121bd44b2f3c7da3fd0f0cef"))
( 29040, uint256("0x34b4dbe94b3e1bc0f6b199ee722a9fbbb52315ae53dd37cbc949fbc84aa3c6fe"))
( 48080, uint256("0x08f789323bf5d116575c5749fa617696f88d0179faac534647abb5065abbaddf"))
( 60000, uint256("0x046ca133f715de3f8d83965487002c9cc1cebe4bb0fc10a1155fc9a6d2767293b"))
( 70000, uint256("0x01ad0aa03e8888cef8381aeea5ca679602bbb32e8245e9cd36abce77cda936bfb"))
( 80000, uint256("0x03a508431391d8203d4dd8fde8ffc529c26923cc8da9f2e64342441bb7afa940c"))
( 90000, uint256("0x08571865fb72beddf95872cbe3490aeb2b7558c7810b0a4aef9d581e249ef9d98"))
( 216802, uint256("0x0c946c4bdb51a240a103059f69112f301995e3a293044d3a4eff8d4c95cb0a5e1"))
( 219638, uint256("0x035fcdaff88c5b989895047f2be66948618feec9ceefaa947341c4f58c55d9362"))
( 323288, uint256("0x089a2340f2715a4bede40ce7f095a8d841df7a18c46f76c21c312b31cee2c7a8d"))
;
static const CCheckpointData data = {
&mapCheckpoints,
1387205035, // * UNIX timestamp of last checkpoint block
353519, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
10000.0 // * estimated number of transactions per day after checkpoint
};
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70"))
;
static const CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
1369685559,
37581,
300
};
const CCheckpointData &Checkpoints() {
if (fTestNet)
return dataTestnet;
else
return data;
}
bool CheckBlock(int nHeight, const uint256& hash)
{
if (fTestNet) return true; // Testnet has no checkpoints
if (!GetBoolArg("-checkpoints", true))
return true;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
// Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(CBlockIndex *pindex) {
if (pindex==NULL)
return 0.0;
int64 nNow = time(NULL);
double fWorkBefore = 0.0; // Amount of work done before pindex
double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
// Work is defined as: 1.0 per transaction before the last checkoint, and
// fSigcheckVerificationFactor per transaction after.
const CCheckpointData &data = Checkpoints();
if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
double nCheapBefore = pindex->nChainTx;
double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore;
fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
} else {
double nCheapBefore = data.nTransactionsLastCheckpoint;
double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
}
return fWorkBefore / (fWorkBefore + fWorkAfter);
}
int GetTotalBlocksEstimate()
{
if (fTestNet) return 0; // Testnet has no checkpoints
if (!GetBoolArg("-checkpoints", true))
return 0;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (fTestNet) return NULL; // Testnet has no checkpoints
if (!GetBoolArg("-checkpoints", true))
return NULL;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<commit_msg>Adding checkpoints since the update<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
// How many times we expect transactions after the last checkpoint to
// be slower. This number is a compromise, as it can't be accurate for
// every system. When reindexing from a fast disk with a slow CPU, it
// can be up to 20, while when downloading from a slow network with a
// fast multicore CPU, it won't be much higher than 1.
static const double fSigcheckVerificationFactor = 5.0;
struct CCheckpointData {
const MapCheckpoints *mapCheckpoints;
int64 nTimeLastCheckpoint;
int64 nTransactionsLastCheckpoint;
double fTransactionsPerDay;
};
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("0x19225ae90d538561217b5949e98ca4964ac91af39090d1a4407c892293e4f44f"))
( 10, uint256("0xb98fe58aa04ca9a5a216c0bd01d952e0fff16e702d0fb512f748f201b9be26fb"))
( 100, uint256("0x56b00c7d17fd10680dfafa0617f26af75f6c2b0c11aafa9cf1b6704de2766f72"))
( 1000, uint256("0x076d62aef68a8330e5f927cdbc23d58ac1e2838877936512aa16487f098d35ca"))
( 5000, uint256("0x5b7fc427fa913510186e034e1415bdf987d37f4674c2f2fd0b492836fc58de0d"))
( 10000, uint256("0xd4bf99505611f97b6cf6f273a79c21c1b21b03238b06396e2e9a02f83c13d01c"))
( 27000, uint256("0x397e50d20f9a21f274b8787fa66ca1ebc208a1b7e5bc3a9a0e352350bd42e125"))
( 27650, uint256("0xb2a25b57648bf10a81dcc3b23fb758bceb6f652d121bd44b2f3c7da3fd0f0cef"))
( 29040, uint256("0x34b4dbe94b3e1bc0f6b199ee722a9fbbb52315ae53dd37cbc949fbc84aa3c6fe"))
( 48080, uint256("0x08f789323bf5d116575c5749fa617696f88d0179faac534647abb5065abbaddf"))
( 60000, uint256("0x046ca133f715de3f8d83965487002c9cc1cebe4bb0fc10a1155fc9a6d2767293b"))
( 70000, uint256("0x01ad0aa03e8888cef8381aeea5ca679602bbb32e8245e9cd36abce77cda936bfb"))
( 80000, uint256("0x03a508431391d8203d4dd8fde8ffc529c26923cc8da9f2e64342441bb7afa940c"))
( 90000, uint256("0x08571865fb72beddf95872cbe3490aeb2b7558c7810b0a4aef9d581e249ef9d98"))
( 216802, uint256("0x0c946c4bdb51a240a103059f69112f301995e3a293044d3a4eff8d4c95cb0a5e1"))
( 219638, uint256("0x035fcdaff88c5b989895047f2be66948618feec9ceefaa947341c4f58c55d9362"))
( 323288, uint256("0x089a2340f2715a4bede40ce7f095a8d841df7a18c46f76c21c312b31cee2c7a8d"))
( 402360, uint256("0x014a96abb528216321b91ac3f29918b60e9292d5cada7a047fcaeb6177c93fbe6"))
( 402376, uint256("0x041f33e89e8369d88e1a516a4860fb0c1b4b8b5037f28388a9fd062e4966258f6"))
;
static const CCheckpointData data = {
&mapCheckpoints,
1390784732, // * UNIX timestamp of last checkpoint block
450658, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
10000.0 // * estimated number of transactions per day after checkpoint
};
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70"))
;
static const CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
1369685559,
37581,
300
};
const CCheckpointData &Checkpoints() {
if (fTestNet)
return dataTestnet;
else
return data;
}
bool CheckBlock(int nHeight, const uint256& hash)
{
if (fTestNet) return true; // Testnet has no checkpoints
if (!GetBoolArg("-checkpoints", true))
return true;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
// Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(CBlockIndex *pindex) {
if (pindex==NULL)
return 0.0;
int64 nNow = time(NULL);
double fWorkBefore = 0.0; // Amount of work done before pindex
double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
// Work is defined as: 1.0 per transaction before the last checkoint, and
// fSigcheckVerificationFactor per transaction after.
const CCheckpointData &data = Checkpoints();
if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
double nCheapBefore = pindex->nChainTx;
double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore;
fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
} else {
double nCheapBefore = data.nTransactionsLastCheckpoint;
double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
}
return fWorkBefore / (fWorkBefore + fWorkAfter);
}
int GetTotalBlocksEstimate()
{
if (fTestNet) return 0; // Testnet has no checkpoints
if (!GetBoolArg("-checkpoints", true))
return 0;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (fTestNet) return NULL; // Testnet has no checkpoints
if (!GetBoolArg("-checkpoints", true))
return NULL;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<|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 <arpa/inet.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <algorithm>
#include <boost/functional/hash.hpp>
#include <gflags/gflags.h>
#include <unordered_set>
#include <utility>
#include <vector>
#include "kudu/gutil/endian.h"
#include "kudu/gutil/gscoped_ptr.h"
#include "kudu/gutil/map-util.h"
#include "kudu/gutil/strings/join.h"
#include "kudu/gutil/strings/numbers.h"
#include "kudu/gutil/strings/split.h"
#include "kudu/gutil/strings/strip.h"
#include "kudu/gutil/strings/substitute.h"
#include "kudu/gutil/strings/util.h"
#include "kudu/util/debug/trace_event.h"
#include "kudu/util/errno.h"
#include "kudu/util/faststring.h"
#include "kudu/util/flag_tags.h"
#include "kudu/util/net/net_util.h"
#include "kudu/util/net/sockaddr.h"
#include "kudu/util/scoped_cleanup.h"
#include "kudu/util/stopwatch.h"
#include "kudu/util/subprocess.h"
#include "kudu/util/trace.h"
// Mac OS 10.9 does not appear to define HOST_NAME_MAX in unistd.h
#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX 64
#endif
DEFINE_bool(fail_dns_resolution, false, "Whether to fail all dns resolution, for tests.");
TAG_FLAG(fail_dns_resolution, hidden);
using std::unordered_set;
using std::vector;
using strings::Substitute;
namespace kudu {
namespace {
struct AddrinfoDeleter {
void operator()(struct addrinfo* info) {
freeaddrinfo(info);
}
};
}
HostPort::HostPort()
: host_(""),
port_(0) {
}
HostPort::HostPort(std::string host, uint16_t port)
: host_(std::move(host)), port_(port) {}
HostPort::HostPort(const Sockaddr& addr)
: host_(addr.host()),
port_(addr.port()) {
}
bool operator==(const HostPort& hp1, const HostPort& hp2) {
return hp1.port() == hp2.port() && hp1.host() == hp2.host();
}
size_t HostPort::HashCode() const {
size_t seed = 0;
boost::hash_combine(seed, host_);
boost::hash_combine(seed, port_);
return seed;
}
Status HostPort::ParseString(const string& str, uint16_t default_port) {
std::pair<string, string> p = strings::Split(str, strings::delimiter::Limit(":", 1));
// Strip any whitespace from the host.
StripWhiteSpace(&p.first);
// Parse the port.
uint32_t port;
if (p.second.empty() && strcount(str, ':') == 0) {
// No port specified.
port = default_port;
} else if (!SimpleAtoi(p.second, &port) ||
port > 65535) {
return Status::InvalidArgument("Invalid port", str);
}
host_.swap(p.first);
port_ = port;
return Status::OK();
}
Status HostPort::ResolveAddresses(vector<Sockaddr>* addresses) const {
TRACE_EVENT1("net", "HostPort::ResolveAddresses",
"host", host_);
TRACE_COUNTER_SCOPE_LATENCY_US("dns_us");
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
struct addrinfo* res = nullptr;
int rc;
LOG_SLOW_EXECUTION(WARNING, 200,
Substitute("resolving address for $0", host_)) {
rc = getaddrinfo(host_.c_str(), nullptr, &hints, &res);
}
if (rc != 0) {
return Status::NetworkError(
StringPrintf("Unable to resolve address '%s'", host_.c_str()),
gai_strerror(rc));
}
gscoped_ptr<addrinfo, AddrinfoDeleter> scoped_res(res);
for (; res != nullptr; res = res->ai_next) {
CHECK_EQ(res->ai_family, AF_INET);
struct sockaddr_in* addr = reinterpret_cast<struct sockaddr_in*>(res->ai_addr);
addr->sin_port = htons(port_);
Sockaddr sockaddr(*addr);
if (addresses) {
addresses->push_back(sockaddr);
}
VLOG(2) << "Resolved address " << sockaddr.ToString()
<< " for host/port " << ToString();
}
if (PREDICT_FALSE(FLAGS_fail_dns_resolution)) {
return Status::NetworkError("injected DNS resolution failure");
}
return Status::OK();
}
Status HostPort::ParseStrings(const string& comma_sep_addrs,
uint16_t default_port,
vector<HostPort>* res) {
vector<string> addr_strings = strings::Split(comma_sep_addrs, ",", strings::SkipEmpty());
for (const string& addr_string : addr_strings) {
HostPort host_port;
RETURN_NOT_OK(host_port.ParseString(addr_string, default_port));
res->push_back(host_port);
}
return Status::OK();
}
string HostPort::ToString() const {
return Substitute("$0:$1", host_, port_);
}
string HostPort::ToCommaSeparatedString(const vector<HostPort>& hostports) {
vector<string> hostport_strs;
for (const HostPort& hostport : hostports) {
hostport_strs.push_back(hostport.ToString());
}
return JoinStrings(hostport_strs, ",");
}
Network::Network()
: addr_(0),
netmask_(0) {
}
Network::Network(uint32_t addr, uint32_t netmask)
: addr_(addr), netmask_(netmask) {}
bool Network::WithinNetwork(const Sockaddr& addr) const {
return ((addr.addr().sin_addr.s_addr & netmask_) ==
(addr_ & netmask_));
}
Status Network::ParseCIDRString(const string& addr) {
std::pair<string, string> p = strings::Split(addr, strings::delimiter::Limit("/", 1));
kudu::Sockaddr sockaddr;
Status s = sockaddr.ParseString(p.first, 0);
uint32_t bits;
bool success = SimpleAtoi(p.second, &bits);
if (!s.ok() || !success || bits > 32) {
return Status::NetworkError("Unable to parse CIDR address", addr);
}
// Netmask in network byte order
uint32_t netmask = NetworkByteOrder::FromHost32(~(0xffffffff >> bits));
addr_ = sockaddr.addr().sin_addr.s_addr;
netmask_ = netmask;
return Status::OK();
}
Status Network::ParseCIDRStrings(const string& comma_sep_addrs,
vector<Network>* res) {
vector<string> addr_strings = strings::Split(comma_sep_addrs, ",", strings::SkipEmpty());
for (const string& addr_string : addr_strings) {
Network network;
RETURN_NOT_OK(network.ParseCIDRString(addr_string));
res->push_back(network);
}
return Status::OK();
}
bool IsPrivilegedPort(uint16_t port) {
return port <= 1024 && port != 0;
}
Status ParseAddressList(const std::string& addr_list,
uint16_t default_port,
std::vector<Sockaddr>* addresses) {
vector<HostPort> host_ports;
RETURN_NOT_OK(HostPort::ParseStrings(addr_list, default_port, &host_ports));
if (host_ports.empty()) return Status::InvalidArgument("No address specified");
unordered_set<Sockaddr> uniqued;
for (const HostPort& host_port : host_ports) {
vector<Sockaddr> this_addresses;
RETURN_NOT_OK(host_port.ResolveAddresses(&this_addresses));
// Only add the unique ones -- the user may have specified
// some IP addresses in multiple ways
for (const Sockaddr& addr : this_addresses) {
if (InsertIfNotPresent(&uniqued, addr)) {
addresses->push_back(addr);
} else {
LOG(INFO) << "Address " << addr.ToString() << " for " << host_port.ToString()
<< " duplicates an earlier resolved entry.";
}
}
}
return Status::OK();
}
Status GetHostname(string* hostname) {
TRACE_EVENT0("net", "GetHostname");
char name[HOST_NAME_MAX];
int ret = gethostname(name, HOST_NAME_MAX);
if (ret != 0) {
return Status::NetworkError("Unable to determine local hostname",
ErrnoToString(errno),
errno);
}
*hostname = name;
return Status::OK();
}
Status GetLocalNetworks(std::vector<Network>* net) {
struct ifaddrs *ifap = nullptr;
int ret = getifaddrs(&ifap);
auto cleanup = MakeScopedCleanup([&]() {
if (ifap) freeifaddrs(ifap);
});
if (ret != 0) {
return Status::NetworkError("Unable to determine local network addresses",
ErrnoToString(errno),
errno);
}
net->clear();
for (struct ifaddrs *ifa = ifap; ifa; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == nullptr || ifa->ifa_netmask == nullptr) continue;
if (ifa->ifa_addr->sa_family == AF_INET) {
Sockaddr addr(*reinterpret_cast<struct sockaddr_in*>(ifa->ifa_addr));
Sockaddr netmask(*reinterpret_cast<struct sockaddr_in*>(ifa->ifa_netmask));
Network network(addr.addr().sin_addr.s_addr, netmask.addr().sin_addr.s_addr);
net->push_back(network);
}
}
return Status::OK();
}
Status GetFQDN(string* hostname) {
TRACE_EVENT0("net", "GetFQDN");
// Start with the non-qualified hostname
RETURN_NOT_OK(GetHostname(hostname));
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_CANONNAME;
struct addrinfo* result;
LOG_SLOW_EXECUTION(WARNING, 200,
Substitute("looking up canonical hostname for localhost "
"(eventual result was $0)", *hostname)) {
TRACE_EVENT0("net", "getaddrinfo");
int rc = getaddrinfo(hostname->c_str(), nullptr, &hints, &result);
if (rc != 0) {
return Status::NetworkError("Unable to lookup FQDN", ErrnoToString(errno), errno);
}
}
*hostname = result->ai_canonname;
freeaddrinfo(result);
return Status::OK();
}
Status SockaddrFromHostPort(const HostPort& host_port, Sockaddr* addr) {
vector<Sockaddr> addrs;
RETURN_NOT_OK(host_port.ResolveAddresses(&addrs));
if (addrs.empty()) {
return Status::NetworkError("Unable to resolve address", host_port.ToString());
}
*addr = addrs[0];
if (addrs.size() > 1) {
VLOG(1) << "Hostname " << host_port.host() << " resolved to more than one address. "
<< "Using address: " << addr->ToString();
}
return Status::OK();
}
Status HostPortFromSockaddrReplaceWildcard(const Sockaddr& addr, HostPort* hp) {
string host;
if (addr.IsWildcard()) {
RETURN_NOT_OK(GetFQDN(&host));
} else {
host = addr.host();
}
hp->set_host(host);
hp->set_port(addr.port());
return Status::OK();
}
void TryRunLsof(const Sockaddr& addr, vector<string>* log) {
#if defined(__APPLE__)
string cmd = strings::Substitute(
"lsof -n -i 'TCP:$0' -sTCP:LISTEN ; "
"for pid in $$(lsof -F p -n -i 'TCP:$0' -sTCP:LISTEN | cut -f 2 -dp) ; do"
" pstree $$pid || ps h -p $$pid;"
"done",
addr.port());
#else
// Little inline bash script prints the full ancestry of any pid listening
// on the same port as 'addr'. We could use 'pstree -s', but that option
// doesn't exist on el6.
string cmd = strings::Substitute(
"export PATH=$$PATH:/usr/sbin ; "
"lsof -n -i 'TCP:$0' -sTCP:LISTEN ; "
"for pid in $$(lsof -F p -n -i 'TCP:$0' -sTCP:LISTEN | grep p | cut -f 2 -dp) ; do"
" while [ $$pid -gt 1 ] ; do"
" ps h -fp $$pid ;"
" stat=($$(</proc/$$pid/stat)) ;"
" pid=$${stat[3]} ;"
" done ; "
"done",
addr.port());
#endif // defined(__APPLE__)
LOG_STRING(WARNING, log)
<< "Trying to use lsof to find any processes listening on "
<< addr.ToString();
LOG_STRING(INFO, log) << "$ " << cmd;
vector<string> argv = { "bash", "-c", cmd };
string results;
Status s = Subprocess::Call(argv, "", &results);
if (PREDICT_FALSE(!s.ok())) {
LOG_STRING(WARNING, log) << s.ToString();
}
LOG_STRING(WARNING, log) << results;
}
} // namespace kudu
<commit_msg>[net_util] fix reporting getaddrinfo() error<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 <arpa/inet.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <algorithm>
#include <functional>
#include <memory>
#include <unordered_set>
#include <utility>
#include <vector>
#include <boost/functional/hash.hpp>
#include <gflags/gflags.h>
#include "kudu/gutil/endian.h"
#include "kudu/gutil/map-util.h"
#include "kudu/gutil/strings/join.h"
#include "kudu/gutil/strings/numbers.h"
#include "kudu/gutil/strings/split.h"
#include "kudu/gutil/strings/strip.h"
#include "kudu/gutil/strings/substitute.h"
#include "kudu/gutil/strings/util.h"
#include "kudu/util/debug/trace_event.h"
#include "kudu/util/errno.h"
#include "kudu/util/faststring.h"
#include "kudu/util/flag_tags.h"
#include "kudu/util/net/net_util.h"
#include "kudu/util/net/sockaddr.h"
#include "kudu/util/scoped_cleanup.h"
#include "kudu/util/stopwatch.h"
#include "kudu/util/subprocess.h"
#include "kudu/util/trace.h"
// Mac OS 10.9 does not appear to define HOST_NAME_MAX in unistd.h
#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX 64
#endif
DEFINE_bool(fail_dns_resolution, false, "Whether to fail all dns resolution, for tests.");
TAG_FLAG(fail_dns_resolution, hidden);
using std::function;
using std::unordered_set;
using std::unique_ptr;
using std::vector;
using strings::Substitute;
namespace kudu {
namespace {
using AddrInfo = unique_ptr<addrinfo, function<void(addrinfo*)>>;
// An utility wrapper around getaddrinfo() call to convert the return code
// of the libc library function into Status.
Status GetAddrInfo(const string& hostname,
const addrinfo& hints,
const string& op_description,
AddrInfo* info) {
addrinfo* res = nullptr;
const int rc = getaddrinfo(hostname.c_str(), nullptr, &hints, &res);
const int err = errno; // preserving the errno from the getaddrinfo() call
AddrInfo result(res, ::freeaddrinfo);
if (rc == 0) {
if (info != nullptr) {
info->swap(result);
}
return Status::OK();
}
const string err_msg = Substitute("unable to $0", op_description);
if (rc == EAI_SYSTEM) {
return Status::NetworkError(err_msg, ErrnoToString(err), err);
}
return Status::NetworkError(err_msg, gai_strerror(rc));
}
} // anonymous namespace
HostPort::HostPort()
: host_(""),
port_(0) {
}
HostPort::HostPort(std::string host, uint16_t port)
: host_(std::move(host)), port_(port) {}
HostPort::HostPort(const Sockaddr& addr)
: host_(addr.host()),
port_(addr.port()) {
}
bool operator==(const HostPort& hp1, const HostPort& hp2) {
return hp1.port() == hp2.port() && hp1.host() == hp2.host();
}
size_t HostPort::HashCode() const {
size_t seed = 0;
boost::hash_combine(seed, host_);
boost::hash_combine(seed, port_);
return seed;
}
Status HostPort::ParseString(const string& str, uint16_t default_port) {
std::pair<string, string> p = strings::Split(str, strings::delimiter::Limit(":", 1));
// Strip any whitespace from the host.
StripWhiteSpace(&p.first);
// Parse the port.
uint32_t port;
if (p.second.empty() && strcount(str, ':') == 0) {
// No port specified.
port = default_port;
} else if (!SimpleAtoi(p.second, &port) ||
port > 65535) {
return Status::InvalidArgument("Invalid port", str);
}
host_.swap(p.first);
port_ = port;
return Status::OK();
}
Status HostPort::ResolveAddresses(vector<Sockaddr>* addresses) const {
TRACE_EVENT1("net", "HostPort::ResolveAddresses",
"host", host_);
TRACE_COUNTER_SCOPE_LATENCY_US("dns_us");
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
AddrInfo result;
const string op_description = Substitute("resolve address for $0", host_);
LOG_SLOW_EXECUTION(WARNING, 200, op_description) {
RETURN_NOT_OK(GetAddrInfo(host_, hints, op_description, &result));
}
for (const addrinfo* ai = result.get(); ai != nullptr; ai = ai->ai_next) {
CHECK_EQ(ai->ai_family, AF_INET);
struct sockaddr_in* addr = reinterpret_cast<struct sockaddr_in*>(ai->ai_addr);
addr->sin_port = htons(port_);
Sockaddr sockaddr(*addr);
if (addresses) {
addresses->push_back(sockaddr);
}
VLOG(2) << "Resolved address " << sockaddr.ToString()
<< " for host/port " << ToString();
}
if (PREDICT_FALSE(FLAGS_fail_dns_resolution)) {
return Status::NetworkError("injected DNS resolution failure");
}
return Status::OK();
}
Status HostPort::ParseStrings(const string& comma_sep_addrs,
uint16_t default_port,
vector<HostPort>* res) {
vector<string> addr_strings = strings::Split(comma_sep_addrs, ",", strings::SkipEmpty());
for (const string& addr_string : addr_strings) {
HostPort host_port;
RETURN_NOT_OK(host_port.ParseString(addr_string, default_port));
res->push_back(host_port);
}
return Status::OK();
}
string HostPort::ToString() const {
return Substitute("$0:$1", host_, port_);
}
string HostPort::ToCommaSeparatedString(const vector<HostPort>& hostports) {
vector<string> hostport_strs;
for (const HostPort& hostport : hostports) {
hostport_strs.push_back(hostport.ToString());
}
return JoinStrings(hostport_strs, ",");
}
Network::Network()
: addr_(0),
netmask_(0) {
}
Network::Network(uint32_t addr, uint32_t netmask)
: addr_(addr), netmask_(netmask) {}
bool Network::WithinNetwork(const Sockaddr& addr) const {
return ((addr.addr().sin_addr.s_addr & netmask_) ==
(addr_ & netmask_));
}
Status Network::ParseCIDRString(const string& addr) {
std::pair<string, string> p = strings::Split(addr, strings::delimiter::Limit("/", 1));
kudu::Sockaddr sockaddr;
Status s = sockaddr.ParseString(p.first, 0);
uint32_t bits;
bool success = SimpleAtoi(p.second, &bits);
if (!s.ok() || !success || bits > 32) {
return Status::NetworkError("Unable to parse CIDR address", addr);
}
// Netmask in network byte order
uint32_t netmask = NetworkByteOrder::FromHost32(~(0xffffffff >> bits));
addr_ = sockaddr.addr().sin_addr.s_addr;
netmask_ = netmask;
return Status::OK();
}
Status Network::ParseCIDRStrings(const string& comma_sep_addrs,
vector<Network>* res) {
vector<string> addr_strings = strings::Split(comma_sep_addrs, ",", strings::SkipEmpty());
for (const string& addr_string : addr_strings) {
Network network;
RETURN_NOT_OK(network.ParseCIDRString(addr_string));
res->push_back(network);
}
return Status::OK();
}
bool IsPrivilegedPort(uint16_t port) {
return port <= 1024 && port != 0;
}
Status ParseAddressList(const std::string& addr_list,
uint16_t default_port,
std::vector<Sockaddr>* addresses) {
vector<HostPort> host_ports;
RETURN_NOT_OK(HostPort::ParseStrings(addr_list, default_port, &host_ports));
if (host_ports.empty()) return Status::InvalidArgument("No address specified");
unordered_set<Sockaddr> uniqued;
for (const HostPort& host_port : host_ports) {
vector<Sockaddr> this_addresses;
RETURN_NOT_OK(host_port.ResolveAddresses(&this_addresses));
// Only add the unique ones -- the user may have specified
// some IP addresses in multiple ways
for (const Sockaddr& addr : this_addresses) {
if (InsertIfNotPresent(&uniqued, addr)) {
addresses->push_back(addr);
} else {
LOG(INFO) << "Address " << addr.ToString() << " for " << host_port.ToString()
<< " duplicates an earlier resolved entry.";
}
}
}
return Status::OK();
}
Status GetHostname(string* hostname) {
TRACE_EVENT0("net", "GetHostname");
char name[HOST_NAME_MAX];
int ret = gethostname(name, HOST_NAME_MAX);
if (ret != 0) {
return Status::NetworkError("Unable to determine local hostname",
ErrnoToString(errno),
errno);
}
*hostname = name;
return Status::OK();
}
Status GetLocalNetworks(std::vector<Network>* net) {
struct ifaddrs *ifap = nullptr;
int ret = getifaddrs(&ifap);
auto cleanup = MakeScopedCleanup([&]() {
if (ifap) freeifaddrs(ifap);
});
if (ret != 0) {
return Status::NetworkError("Unable to determine local network addresses",
ErrnoToString(errno),
errno);
}
net->clear();
for (struct ifaddrs *ifa = ifap; ifa; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == nullptr || ifa->ifa_netmask == nullptr) continue;
if (ifa->ifa_addr->sa_family == AF_INET) {
Sockaddr addr(*reinterpret_cast<struct sockaddr_in*>(ifa->ifa_addr));
Sockaddr netmask(*reinterpret_cast<struct sockaddr_in*>(ifa->ifa_netmask));
Network network(addr.addr().sin_addr.s_addr, netmask.addr().sin_addr.s_addr);
net->push_back(network);
}
}
return Status::OK();
}
Status GetFQDN(string* hostname) {
TRACE_EVENT0("net", "GetFQDN");
// Start with the non-qualified hostname
RETURN_NOT_OK(GetHostname(hostname));
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_CANONNAME;
AddrInfo result;
const string op_description =
Substitute("look up canonical hostname for localhost '$0'", *hostname);
LOG_SLOW_EXECUTION(WARNING, 200, op_description) {
TRACE_EVENT0("net", "getaddrinfo");
RETURN_NOT_OK(GetAddrInfo(*hostname, hints, op_description, &result));
}
*hostname = result->ai_canonname;
return Status::OK();
}
Status SockaddrFromHostPort(const HostPort& host_port, Sockaddr* addr) {
vector<Sockaddr> addrs;
RETURN_NOT_OK(host_port.ResolveAddresses(&addrs));
if (addrs.empty()) {
return Status::NetworkError("Unable to resolve address", host_port.ToString());
}
*addr = addrs[0];
if (addrs.size() > 1) {
VLOG(1) << "Hostname " << host_port.host() << " resolved to more than one address. "
<< "Using address: " << addr->ToString();
}
return Status::OK();
}
Status HostPortFromSockaddrReplaceWildcard(const Sockaddr& addr, HostPort* hp) {
string host;
if (addr.IsWildcard()) {
RETURN_NOT_OK(GetFQDN(&host));
} else {
host = addr.host();
}
hp->set_host(host);
hp->set_port(addr.port());
return Status::OK();
}
void TryRunLsof(const Sockaddr& addr, vector<string>* log) {
#if defined(__APPLE__)
string cmd = strings::Substitute(
"lsof -n -i 'TCP:$0' -sTCP:LISTEN ; "
"for pid in $$(lsof -F p -n -i 'TCP:$0' -sTCP:LISTEN | cut -f 2 -dp) ; do"
" pstree $$pid || ps h -p $$pid;"
"done",
addr.port());
#else
// Little inline bash script prints the full ancestry of any pid listening
// on the same port as 'addr'. We could use 'pstree -s', but that option
// doesn't exist on el6.
string cmd = strings::Substitute(
"export PATH=$$PATH:/usr/sbin ; "
"lsof -n -i 'TCP:$0' -sTCP:LISTEN ; "
"for pid in $$(lsof -F p -n -i 'TCP:$0' -sTCP:LISTEN | grep p | cut -f 2 -dp) ; do"
" while [ $$pid -gt 1 ] ; do"
" ps h -fp $$pid ;"
" stat=($$(</proc/$$pid/stat)) ;"
" pid=$${stat[3]} ;"
" done ; "
"done",
addr.port());
#endif // defined(__APPLE__)
LOG_STRING(WARNING, log)
<< "Trying to use lsof to find any processes listening on "
<< addr.ToString();
LOG_STRING(INFO, log) << "$ " << cmd;
vector<string> argv = { "bash", "-c", cmd };
string results;
Status s = Subprocess::Call(argv, "", &results);
if (PREDICT_FALSE(!s.ok())) {
LOG_STRING(WARNING, log) << s.ToString();
}
LOG_STRING(WARNING, log) << results;
}
} // namespace kudu
<|endoftext|>
|
<commit_before>/*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "ForwardHttpRequest.hxx"
#include "lb_instance.hxx"
#include "lb_connection.hxx"
#include "lb_config.hxx"
#include "lb_session.hxx"
#include "lb_cookie.hxx"
#include "lb_jvm_route.hxx"
#include "lb_headers.hxx"
#include "lb_log.hxx"
#include "ssl/ssl_filter.hxx"
#include "address_sticky.hxx"
#include "http_server/http_server.hxx"
#include "http_server/Request.hxx"
#include "http_server/Handler.hxx"
#include "http_client.hxx"
#include "tcp_stock.hxx"
#include "tcp_balancer.hxx"
#include "http_response.hxx"
#include "http_headers.hxx"
#include "stock/GetHandler.hxx"
#include "stock/Item.hxx"
#include "stock/Lease.hxx"
#include "strmap.hxx"
#include "failure.hxx"
#include "bulldog.hxx"
#include "pool.hxx"
#include "net/SocketAddress.hxx"
#include "net/SocketDescriptor.hxx"
#include "istream/istream.hxx"
#include "istream/UnusedHoldPtr.hxx"
#include "util/Cancellable.hxx"
struct LbRequest final
: Cancellable, StockGetHandler, HttpResponseHandler {
LbConnection &connection;
const LbClusterConfig &cluster_config;
TcpBalancer &balancer;
HttpServerRequest &request;
/**
* The request body.
*/
UnusedHoldIstreamPtr body;
CancellablePointer cancel_ptr;
StockItem *stock_item;
unsigned new_cookie = 0;
LbRequest(LbConnection &_connection, const LbClusterConfig &_cluster_config,
TcpBalancer &_balancer,
HttpServerRequest &_request,
CancellablePointer &_cancel_ptr)
:connection(_connection), cluster_config(_cluster_config),
balancer(_balancer),
request(_request),
body(request.pool, request.body) {
_cancel_ptr = *this;
}
void Destroy() {
DeleteFromPool(request.pool, this);
}
sticky_hash_t GetStickyHash();
sticky_hash_t MakeCookieHash();
/* virtual methods from class Cancellable */
void Cancel() override {
body.Clear();
CancellablePointer c(std::move(cancel_ptr));
Destroy();
c.Cancel();
}
/* virtual methods from class StockGetHandler */
void OnStockItemReady(StockItem &item) override;
void OnStockItemError(GError *error) override;
/* virtual methods from class HttpResponseHandler */
void OnHttpResponse(http_status_t status, StringMap &&headers,
Istream *body) override;
void OnHttpError(GError *error) override;
};
static void
SendResponse(HttpServerRequest &request,
const LbSimpleHttpResponse &response)
{
assert(response.IsDefined());
http_server_simple_response(request, response.status,
response.location.empty() ? nullptr : response.location.c_str(),
response.message.empty() ? nullptr : response.message.c_str());
}
static bool
send_fallback(HttpServerRequest &request,
const LbSimpleHttpResponse &fallback)
{
if (!fallback.IsDefined())
return false;
SendResponse(request, fallback);
return true;
}
/**
* Generate a cookie for sticky worker selection. Return only worker
* numbers that are not known to be failing. Returns 0 on total
* failure.
*/
static unsigned
generate_cookie(const AddressList *list)
{
assert(list->GetSize() >= 2);
const unsigned first = lb_cookie_generate(list->GetSize());
unsigned i = first;
do {
assert(i >= 1 && i <= list->GetSize());
const SocketAddress address = list->addresses[i % list->GetSize()];
if (failure_get_status(address) == FAILURE_OK &&
bulldog_check(address) && !bulldog_is_fading(address))
return i;
i = lb_cookie_next(list->GetSize(), i);
} while (i != first);
/* all nodes have failed */
return first;
}
sticky_hash_t
LbRequest::MakeCookieHash()
{
unsigned hash = lb_cookie_get(request.headers);
if (hash == 0)
new_cookie = hash = generate_cookie(&cluster_config.address_list);
return hash;
}
sticky_hash_t
LbRequest::GetStickyHash()
{
switch (cluster_config.sticky_mode) {
case StickyMode::NONE:
case StickyMode::FAILOVER:
/* these modes require no preparation; they are handled
completely by balancer_get() */
return 0;
case StickyMode::SOURCE_IP:
/* calculate session_sticky from remote address */
return socket_address_sticky(request.remote_address);
case StickyMode::SESSION_MODULO:
/* calculate session_sticky from beng-proxy session id */
return lb_session_get(request.headers,
cluster_config.session_cookie.c_str());
case StickyMode::COOKIE:
/* calculate session_sticky from beng-lb cookie */
return MakeCookieHash();
case StickyMode::JVM_ROUTE:
/* calculate session_sticky from JSESSIONID cookie suffix */
return lb_jvm_route_get(request.headers, cluster_config);
}
assert(false);
gcc_unreachable();
}
/**
* Is the specified error a server failure, that justifies
* blacklisting the server for a while?
*/
static bool
is_server_failure(GError *error)
{
return error->domain == http_client_quark() &&
error->code != HTTP_CLIENT_UNSPECIFIED;
}
/*
* HTTP response handler
*
*/
void
LbRequest::OnHttpResponse(http_status_t status, StringMap &&_headers,
Istream *response_body)
{
HttpHeaders headers(std::move(_headers));
if (request.method == HTTP_METHOD_HEAD)
/* pass Content-Length, even though there is no response body
(RFC 2616 14.13) */
headers.MoveToBuffer("content-length");
if (new_cookie != 0) {
char buffer[64];
/* "Discard" must be last, to work around an Android bug*/
snprintf(buffer, sizeof(buffer),
"beng_lb_node=0-%x; HttpOnly; Path=/; Version=1; Discard",
new_cookie);
headers.Write("cookie2", "$Version=\"1\"");
headers.Write("set-cookie", buffer);
}
http_server_response(&request, status, std::move(headers), response_body);
Destroy();
}
void
LbRequest::OnHttpError(GError *error)
{
if (is_server_failure(error))
failure_add(tcp_stock_item_get_address(*stock_item));
lb_connection_log_gerror(2, &connection, "Error", error);
if (!send_fallback(request, cluster_config.fallback)) {
const char *msg = connection.listener.verbose_response
? error->message
: "Server failure";
http_server_send_message(&request, HTTP_STATUS_BAD_GATEWAY, msg);
}
g_error_free(error);
Destroy();
}
/*
* stock callback
*
*/
void
LbRequest::OnStockItemReady(StockItem &item)
{
stock_item = &item;
const char *peer_subject = connection.ssl_filter != nullptr
? ssl_filter_get_peer_subject(connection.ssl_filter)
: nullptr;
const char *peer_issuer_subject = connection.ssl_filter != nullptr
? ssl_filter_get_peer_issuer_subject(connection.ssl_filter)
: nullptr;
auto &headers = request.headers;
lb_forward_request_headers(request.pool, headers,
request.local_host_and_port,
request.remote_host,
peer_subject, peer_issuer_subject,
cluster_config.mangle_via);
auto *lease = NewFromPool<StockItemLease>(request.pool, item);
http_client_request(request.pool,
connection.instance.event_loop,
tcp_stock_item_get(item),
tcp_stock_item_get_domain(item) == AF_LOCAL
? FdType::FD_SOCKET : FdType::FD_TCP,
*lease,
item.GetStockName(),
NULL, NULL,
request.method, request.uri,
HttpHeaders(std::move(headers)),
body.Steal(), true,
*this, cancel_ptr);
}
void
LbRequest::OnStockItemError(GError *error)
{
lb_connection_log_gerror(2, &connection, "Connect error", error);
body.Clear();
if (!send_fallback(request, cluster_config.fallback)) {
const char *msg = connection.listener.verbose_response
? error->message
: "Connection failure";
http_server_send_message(&request, HTTP_STATUS_BAD_GATEWAY,
msg);
}
g_error_free(error);
}
/*
* constructor
*
*/
void
ForwardHttpRequest(LbConnection &connection,
HttpServerRequest &request,
const LbClusterConfig &cluster_config,
CancellablePointer &cancel_ptr)
{
const auto request2 =
NewFromPool<LbRequest>(request.pool,
connection, cluster_config,
*connection.instance.tcp_balancer,
request, cancel_ptr);
SocketAddress bind_address = SocketAddress::Null();
const bool transparent_source = cluster_config.transparent_source;
if (transparent_source) {
bind_address = request.remote_address;
/* reset the port to 0 to allow the kernel to choose one */
if (bind_address.GetFamily() == AF_INET) {
struct sockaddr_in *s_in = (struct sockaddr_in *)
p_memdup(&request.pool, bind_address.GetAddress(),
bind_address.GetSize());
s_in->sin_port = 0;
bind_address = SocketAddress((const struct sockaddr *)s_in,
bind_address.GetSize());
} else if (bind_address.GetFamily() == AF_INET6) {
struct sockaddr_in6 *s_in = (struct sockaddr_in6 *)
p_memdup(&request.pool, bind_address.GetAddress(),
bind_address.GetSize());
s_in->sin6_port = 0;
bind_address = SocketAddress((const struct sockaddr *)s_in,
bind_address.GetSize());
}
}
if (cluster_config.HasZeroConf()) {
/* TODO: generalize the Zeroconf code, implement sticky */
auto *cluster2 = connection.instance.clusters.Find(cluster_config.name);
if (cluster2 == nullptr) {
http_server_send_message(&request,
HTTP_STATUS_INTERNAL_SERVER_ERROR,
"Zeroconf cluster not found");
return;
}
const auto member = cluster2->Pick(request2->GetStickyHash());
if (member.first == nullptr) {
http_server_send_message(&request,
HTTP_STATUS_INTERNAL_SERVER_ERROR,
"Zeroconf cluster is empty");
return;
}
assert(member.second.IsDefined());
tcp_stock_get(*connection.instance.tcp_stock, request.pool,
member.first,
transparent_source, bind_address,
member.second,
20,
*request2, request2->cancel_ptr);
return;
}
tcp_balancer_get(request2->balancer, request.pool,
transparent_source,
bind_address,
request2->GetStickyHash(),
cluster_config.address_list,
20,
*request2, request2->cancel_ptr);
}
<commit_msg>lb/ForwardHttpRequest: move code to method Start()<commit_after>/*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "ForwardHttpRequest.hxx"
#include "lb_instance.hxx"
#include "lb_connection.hxx"
#include "lb_config.hxx"
#include "lb_session.hxx"
#include "lb_cookie.hxx"
#include "lb_jvm_route.hxx"
#include "lb_headers.hxx"
#include "lb_log.hxx"
#include "ssl/ssl_filter.hxx"
#include "address_sticky.hxx"
#include "http_server/http_server.hxx"
#include "http_server/Request.hxx"
#include "http_server/Handler.hxx"
#include "http_client.hxx"
#include "tcp_stock.hxx"
#include "tcp_balancer.hxx"
#include "http_response.hxx"
#include "http_headers.hxx"
#include "stock/GetHandler.hxx"
#include "stock/Item.hxx"
#include "stock/Lease.hxx"
#include "strmap.hxx"
#include "failure.hxx"
#include "bulldog.hxx"
#include "pool.hxx"
#include "net/SocketAddress.hxx"
#include "net/SocketDescriptor.hxx"
#include "istream/istream.hxx"
#include "istream/UnusedHoldPtr.hxx"
#include "util/Cancellable.hxx"
struct LbRequest final
: Cancellable, StockGetHandler, HttpResponseHandler {
LbConnection &connection;
const LbClusterConfig &cluster_config;
TcpBalancer &balancer;
HttpServerRequest &request;
/**
* The request body.
*/
UnusedHoldIstreamPtr body;
CancellablePointer cancel_ptr;
StockItem *stock_item;
unsigned new_cookie = 0;
LbRequest(LbConnection &_connection, const LbClusterConfig &_cluster_config,
TcpBalancer &_balancer,
HttpServerRequest &_request,
CancellablePointer &_cancel_ptr)
:connection(_connection), cluster_config(_cluster_config),
balancer(_balancer),
request(_request),
body(request.pool, request.body) {
_cancel_ptr = *this;
}
void Start();
void Destroy() {
DeleteFromPool(request.pool, this);
}
sticky_hash_t GetStickyHash();
sticky_hash_t MakeCookieHash();
/* virtual methods from class Cancellable */
void Cancel() override {
body.Clear();
CancellablePointer c(std::move(cancel_ptr));
Destroy();
c.Cancel();
}
/* virtual methods from class StockGetHandler */
void OnStockItemReady(StockItem &item) override;
void OnStockItemError(GError *error) override;
/* virtual methods from class HttpResponseHandler */
void OnHttpResponse(http_status_t status, StringMap &&headers,
Istream *body) override;
void OnHttpError(GError *error) override;
};
static void
SendResponse(HttpServerRequest &request,
const LbSimpleHttpResponse &response)
{
assert(response.IsDefined());
http_server_simple_response(request, response.status,
response.location.empty() ? nullptr : response.location.c_str(),
response.message.empty() ? nullptr : response.message.c_str());
}
static bool
send_fallback(HttpServerRequest &request,
const LbSimpleHttpResponse &fallback)
{
if (!fallback.IsDefined())
return false;
SendResponse(request, fallback);
return true;
}
/**
* Generate a cookie for sticky worker selection. Return only worker
* numbers that are not known to be failing. Returns 0 on total
* failure.
*/
static unsigned
generate_cookie(const AddressList *list)
{
assert(list->GetSize() >= 2);
const unsigned first = lb_cookie_generate(list->GetSize());
unsigned i = first;
do {
assert(i >= 1 && i <= list->GetSize());
const SocketAddress address = list->addresses[i % list->GetSize()];
if (failure_get_status(address) == FAILURE_OK &&
bulldog_check(address) && !bulldog_is_fading(address))
return i;
i = lb_cookie_next(list->GetSize(), i);
} while (i != first);
/* all nodes have failed */
return first;
}
sticky_hash_t
LbRequest::MakeCookieHash()
{
unsigned hash = lb_cookie_get(request.headers);
if (hash == 0)
new_cookie = hash = generate_cookie(&cluster_config.address_list);
return hash;
}
sticky_hash_t
LbRequest::GetStickyHash()
{
switch (cluster_config.sticky_mode) {
case StickyMode::NONE:
case StickyMode::FAILOVER:
/* these modes require no preparation; they are handled
completely by balancer_get() */
return 0;
case StickyMode::SOURCE_IP:
/* calculate session_sticky from remote address */
return socket_address_sticky(request.remote_address);
case StickyMode::SESSION_MODULO:
/* calculate session_sticky from beng-proxy session id */
return lb_session_get(request.headers,
cluster_config.session_cookie.c_str());
case StickyMode::COOKIE:
/* calculate session_sticky from beng-lb cookie */
return MakeCookieHash();
case StickyMode::JVM_ROUTE:
/* calculate session_sticky from JSESSIONID cookie suffix */
return lb_jvm_route_get(request.headers, cluster_config);
}
assert(false);
gcc_unreachable();
}
/**
* Is the specified error a server failure, that justifies
* blacklisting the server for a while?
*/
static bool
is_server_failure(GError *error)
{
return error->domain == http_client_quark() &&
error->code != HTTP_CLIENT_UNSPECIFIED;
}
/*
* HTTP response handler
*
*/
void
LbRequest::OnHttpResponse(http_status_t status, StringMap &&_headers,
Istream *response_body)
{
HttpHeaders headers(std::move(_headers));
if (request.method == HTTP_METHOD_HEAD)
/* pass Content-Length, even though there is no response body
(RFC 2616 14.13) */
headers.MoveToBuffer("content-length");
if (new_cookie != 0) {
char buffer[64];
/* "Discard" must be last, to work around an Android bug*/
snprintf(buffer, sizeof(buffer),
"beng_lb_node=0-%x; HttpOnly; Path=/; Version=1; Discard",
new_cookie);
headers.Write("cookie2", "$Version=\"1\"");
headers.Write("set-cookie", buffer);
}
http_server_response(&request, status, std::move(headers), response_body);
Destroy();
}
void
LbRequest::OnHttpError(GError *error)
{
if (is_server_failure(error))
failure_add(tcp_stock_item_get_address(*stock_item));
lb_connection_log_gerror(2, &connection, "Error", error);
if (!send_fallback(request, cluster_config.fallback)) {
const char *msg = connection.listener.verbose_response
? error->message
: "Server failure";
http_server_send_message(&request, HTTP_STATUS_BAD_GATEWAY, msg);
}
g_error_free(error);
Destroy();
}
/*
* stock callback
*
*/
void
LbRequest::OnStockItemReady(StockItem &item)
{
stock_item = &item;
const char *peer_subject = connection.ssl_filter != nullptr
? ssl_filter_get_peer_subject(connection.ssl_filter)
: nullptr;
const char *peer_issuer_subject = connection.ssl_filter != nullptr
? ssl_filter_get_peer_issuer_subject(connection.ssl_filter)
: nullptr;
auto &headers = request.headers;
lb_forward_request_headers(request.pool, headers,
request.local_host_and_port,
request.remote_host,
peer_subject, peer_issuer_subject,
cluster_config.mangle_via);
auto *lease = NewFromPool<StockItemLease>(request.pool, item);
http_client_request(request.pool,
connection.instance.event_loop,
tcp_stock_item_get(item),
tcp_stock_item_get_domain(item) == AF_LOCAL
? FdType::FD_SOCKET : FdType::FD_TCP,
*lease,
item.GetStockName(),
NULL, NULL,
request.method, request.uri,
HttpHeaders(std::move(headers)),
body.Steal(), true,
*this, cancel_ptr);
}
void
LbRequest::OnStockItemError(GError *error)
{
lb_connection_log_gerror(2, &connection, "Connect error", error);
body.Clear();
if (!send_fallback(request, cluster_config.fallback)) {
const char *msg = connection.listener.verbose_response
? error->message
: "Connection failure";
http_server_send_message(&request, HTTP_STATUS_BAD_GATEWAY,
msg);
}
g_error_free(error);
}
/*
* constructor
*
*/
inline void
LbRequest::Start()
{
SocketAddress bind_address = SocketAddress::Null();
const bool transparent_source = cluster_config.transparent_source;
if (transparent_source) {
bind_address = request.remote_address;
/* reset the port to 0 to allow the kernel to choose one */
if (bind_address.GetFamily() == AF_INET) {
struct sockaddr_in *s_in = (struct sockaddr_in *)
p_memdup(&request.pool, bind_address.GetAddress(),
bind_address.GetSize());
s_in->sin_port = 0;
bind_address = SocketAddress((const struct sockaddr *)s_in,
bind_address.GetSize());
} else if (bind_address.GetFamily() == AF_INET6) {
struct sockaddr_in6 *s_in = (struct sockaddr_in6 *)
p_memdup(&request.pool, bind_address.GetAddress(),
bind_address.GetSize());
s_in->sin6_port = 0;
bind_address = SocketAddress((const struct sockaddr *)s_in,
bind_address.GetSize());
}
}
if (cluster_config.HasZeroConf()) {
/* TODO: generalize the Zeroconf code, implement sticky */
auto *cluster2 = connection.instance.clusters.Find(cluster_config.name);
if (cluster2 == nullptr) {
http_server_send_message(&request,
HTTP_STATUS_INTERNAL_SERVER_ERROR,
"Zeroconf cluster not found");
return;
}
const auto member = cluster2->Pick(GetStickyHash());
if (member.first == nullptr) {
http_server_send_message(&request,
HTTP_STATUS_INTERNAL_SERVER_ERROR,
"Zeroconf cluster is empty");
return;
}
assert(member.second.IsDefined());
tcp_stock_get(*connection.instance.tcp_stock, request.pool,
member.first,
transparent_source, bind_address,
member.second,
20,
*this, cancel_ptr);
return;
}
tcp_balancer_get(balancer, request.pool,
transparent_source,
bind_address,
GetStickyHash(),
cluster_config.address_list,
20,
*this, cancel_ptr);
}
void
ForwardHttpRequest(LbConnection &connection,
HttpServerRequest &request,
const LbClusterConfig &cluster_config,
CancellablePointer &cancel_ptr)
{
const auto request2 =
NewFromPool<LbRequest>(request.pool,
connection, cluster_config,
*connection.instance.tcp_balancer,
request, cancel_ptr);
request2->Start();
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <queue>
#include <vector>
#include <utility>
#include <iostream>
#include <string>
#include <stack>
#include <queue>
using namespace std;
queue<string> lv1;
queue<string> lv2;
queue<string> lv3;
queue<string> lv4;
string temp;
int templv;
int temptime=0;
int usernum;
int users=0;
int read(int now){
if(now < temptime || users>usernum) return 0;
do{
if(temp.empty()){
}else{
switch(templv){
case 1:
lv1.push(temp);break;
case 2:
lv2.push(temp);break;
case 3:
lv3.push(temp);break;
case 4:
lv4.push(temp);break;
}
}
users++;
if(users<=usernum){
temp.resize(21); //需要预先分配空间
scanf("%d%d%s",&temptime,&templv,&temp[0]);
}
else
return 0;
}while(temptime<=now);
}
int pop(){
printf("pop");
if(lv4.size()>0){
printf("%s\n",lv4.front().c_str());
lv4.pop();
return 4;
}
if(lv3.size()>0){
printf("%s\n",lv3.front().c_str());
lv3.pop();
return 3;
}
if(lv2.size()>0){
printf("%s\n",lv2.front().c_str());
lv2.pop();
return 2;
}
if(lv1.size()>0){
printf("%s\n",lv1.front().c_str());
lv1.pop();
return 1;
}
return 0;
}
int main(int argc, char const *argv[])
{
int time;
scanf("%d%d",&usernum,&time);
for (int i = 0; i <= time && i< usernum *5; ++i)
{
read(i);
//cout<<i<<"\n"<<lv1.size()<<lv2.size()<<lv3.size()<<endl;
if(i%5==0)
pop();
}
//while(pop()){}
return 0;
}<commit_msg>update uoj2254<commit_after>#include <stdio.h>
#include <queue>
#include <vector>
#include <utility>
#include <iostream>
#include <string>
#include <stack>
#include <queue>
using namespace std;
queue<string> lv1;
queue<string> lv2;
queue<string> lv3;
queue<string> lv4;
string temp;
int templv;
int temptime=0;
int usernum;
int users=0;
int read(int now){
if(now < temptime || users>usernum) return 0;
do{
if(temp.empty()){
}else{
switch(templv){
case 1:
lv1.push(temp);break;
case 2:
lv2.push(temp);break;
case 3:
lv3.push(temp);break;
case 4:
lv4.push(temp);break;
}
}
users++;
if(users<=usernum){
temp.resize(21); //需要预先分配空间
scanf("%d%d%s",&temptime,&templv,&temp[0]);
}
else
return 0;
}while(temptime<=now);
}
int pop(){
printf("pop");
if(lv4.size()>0){
printf("%s\n",lv4.front().c_str());
lv4.pop();
return 4;
}
if(lv3.size()>0){
printf("%s\n",lv3.front().c_str());
lv3.pop();
return 3;
}
if(lv2.size()>0){
printf("%s\n",lv2.front().c_str());
lv2.pop();
return 2;
}
if(lv1.size()>0){
printf("%s\n",lv1.front().c_str());
lv1.pop();
return 1;
}
return 0;
}
int main(int argc, char const *argv[])
{
int time;
scanf("%d%d",&usernum,&time);
for (int i = 0; i <= time ; ++i)
{
read(i);
//cout<<i<<"\n"<<lv1.size()<<lv2.size()<<lv3.size()<<endl;
if(i%5==0)
pop();
}
//while(pop()){}
return 0;
}<|endoftext|>
|
<commit_before>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnordmetric/util/runtimeexception.h>
#include <fnordmetric/util/uri.h>
namespace fnordmetric {
namespace util {
URI::URI(const std::string& uri_str) : port_(0) {
parse(uri_str);
}
void URI::parse(const std::string& uri_str) {
URI::parseURI(
uri_str,
&scheme_,
&userinfo_,
&host_,
&port_,
&path_,
&query_,
&fragment_);
}
const std::string& URI::scheme() const {
return scheme_;
}
const std::string& URI::userinfo() const {
return userinfo_;
}
const std::string& URI::host() const {
return host_;
}
const unsigned URI::port() const {
return port_;
}
const std::string& URI::path() const {
return path_;
}
const std::string& URI::query() const {
return query_;
}
const std::vector<std::pair<std::string, std::string>> URI::queryParams()
const {
std::vector<std::pair<std::string, std::string>> params;
if (query_.size() > 0) {
URI::parseQueryString(query_, ¶ms);
}
return params;
}
const std::string& URI::fragment() const {
return fragment_;
}
std::string URI::toString() const {
std::string uri_str;
uri_str.append(scheme());
uri_str.append(":");
if (host_.size() > 0) {
uri_str.append("//");
if (userinfo_.size() > 0) {
uri_str.append(userinfo_);
uri_str.append("@");
}
uri_str.append(host_);
if (port_ > 0) { // FIXPAUL hasPort
uri_str.append(":");
uri_str.append(std::to_string(port_));
}
}
uri_str.append(path_);
if (query_.size() > 0) {
uri_str.append("?");
uri_str.append(query_);
}
if (fragment_.size() > 0) {
uri_str.append("#");
uri_str.append(fragment_);
}
return uri_str;
}
void URI::parseURI(
const std::string& uri_str,
std::string* scheme,
std::string* userinfo,
std::string* host,
unsigned* port,
std::string* path,
std::string* query,
std::string* fragment) {
const char* begin = uri_str.c_str();
const char* end = begin + uri_str.size();
/* scheme */
bool has_scheme = false;
for (const char* cur = begin; cur < end; ++cur) {
if (cur[0] == ':') {
*scheme = std::string(begin, cur - begin);
begin = cur + 1;
has_scheme = true;
break;
}
}
if (!has_scheme) {
RAISE(util::RuntimeException, "invalid URI: must begin with scheme:");
}
/* authority */
if (begin < end - 2 && begin[0] == '/' && begin[1] == '/') {
begin += 2;
const char* cur = begin;
for (; cur < end && *cur != '/' && *cur != '?' && *cur != '#'; ++cur);
if (cur > begin) {
const char* abegin = begin;
const char* aend = cur;
/* userinfo */
for (const char* acur = abegin; acur < aend; ++acur) {
if (*acur == '/' || *acur == '?' || *acur == '#') {
break;
}
if (*acur == '@') {
*userinfo = std::string(abegin, acur - abegin);
abegin = acur + 1;
break;
}
}
/* host */
const char* acur = abegin;
for (; acur < aend &&
*acur != '/' &&
*acur != '?' &&
*acur != '#' &&
*acur != ':'; ++acur);
*host = std::string(abegin, acur - abegin);
/* port */
if (acur < aend - 1 && *acur == ':') {
abegin = ++acur;
for (; *acur >= '0' && *acur <= '9'; ++acur);
if (acur > abegin) {
*port = std::stoi(std::string(abegin, acur - abegin));
}
}
}
begin = cur;
}
/* path */
if (begin < end) {
const char* cur = begin;
for (; cur < end && *cur != '?' && *cur != '#'; ++cur);
if (cur > begin) {
*path = std::string(begin, cur - begin);
}
begin = cur;
}
/* query */
if (begin < end && *begin == '?') {
const char* cur = ++begin;
for (; cur < end && *cur != '#'; ++cur);
if (cur > begin) {
*query = std::string(begin, cur - begin);
}
begin = cur;
}
/* fragment */
if (begin < end - 1 && *begin == '#') {
*fragment = std::string(begin + 1, end - begin - 1);
}
}
void URI::parseQueryString(
const std::string& query,
std::vector<std::pair<std::string, std::string>>* params) {
const char* begin = query.c_str();
const char* end = begin + query.size();
for (const char* cur = begin; cur < end; ++cur) {
for (; cur < end && *cur != '=' && *cur != '&'; cur++);
if (cur > begin && cur < end && *cur == '=' ) {
std::string key_str(begin, cur - begin);
const char* val = ++cur;
for (; cur < end && *cur != '=' && *cur != '&'; cur++);
if (cur > val) {
std::string val_str(val, cur - val);
params->emplace_back(key_str, val_str);
begin = cur + 1;
} else {
break;
}
} else {
break;
}
}
}
}
}
<commit_msg>catch all conversion errors<commit_after>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnordmetric/util/runtimeexception.h>
#include <fnordmetric/util/uri.h>
namespace fnordmetric {
namespace util {
URI::URI(const std::string& uri_str) : port_(0) {
parse(uri_str);
}
void URI::parse(const std::string& uri_str) {
URI::parseURI(
uri_str,
&scheme_,
&userinfo_,
&host_,
&port_,
&path_,
&query_,
&fragment_);
}
const std::string& URI::scheme() const {
return scheme_;
}
const std::string& URI::userinfo() const {
return userinfo_;
}
const std::string& URI::host() const {
return host_;
}
const unsigned URI::port() const {
return port_;
}
const std::string& URI::path() const {
return path_;
}
const std::string& URI::query() const {
return query_;
}
const std::vector<std::pair<std::string, std::string>> URI::queryParams()
const {
std::vector<std::pair<std::string, std::string>> params;
if (query_.size() > 0) {
URI::parseQueryString(query_, ¶ms);
}
return params;
}
const std::string& URI::fragment() const {
return fragment_;
}
std::string URI::toString() const {
std::string uri_str;
uri_str.append(scheme());
uri_str.append(":");
if (host_.size() > 0) {
uri_str.append("//");
if (userinfo_.size() > 0) {
uri_str.append(userinfo_);
uri_str.append("@");
}
uri_str.append(host_);
if (port_ > 0) { // FIXPAUL hasPort
uri_str.append(":");
uri_str.append(std::to_string(port_));
}
}
uri_str.append(path_);
if (query_.size() > 0) {
uri_str.append("?");
uri_str.append(query_);
}
if (fragment_.size() > 0) {
uri_str.append("#");
uri_str.append(fragment_);
}
return uri_str;
}
void URI::parseURI(
const std::string& uri_str,
std::string* scheme,
std::string* userinfo,
std::string* host,
unsigned* port,
std::string* path,
std::string* query,
std::string* fragment) {
const char* begin = uri_str.c_str();
const char* end = begin + uri_str.size();
/* scheme */
bool has_scheme = false;
for (const char* cur = begin; cur < end; ++cur) {
if (cur[0] == ':') {
*scheme = std::string(begin, cur - begin);
begin = cur + 1;
has_scheme = true;
break;
}
}
if (!has_scheme) {
RAISE(util::RuntimeException, "invalid URI: must begin with scheme:");
}
/* authority */
if (begin < end - 2 && begin[0] == '/' && begin[1] == '/') {
begin += 2;
const char* cur = begin;
for (; cur < end && *cur != '/' && *cur != '?' && *cur != '#'; ++cur);
if (cur > begin) {
const char* abegin = begin;
const char* aend = cur;
/* userinfo */
for (const char* acur = abegin; acur < aend; ++acur) {
if (*acur == '/' || *acur == '?' || *acur == '#') {
break;
}
if (*acur == '@') {
*userinfo = std::string(abegin, acur - abegin);
abegin = acur + 1;
break;
}
}
/* host */
const char* acur = abegin;
for (; acur < aend &&
*acur != '/' &&
*acur != '?' &&
*acur != '#' &&
*acur != ':'; ++acur);
*host = std::string(abegin, acur - abegin);
/* port */
if (acur < aend - 1 && *acur == ':') {
abegin = ++acur;
for (; *acur >= '0' && *acur <= '9'; ++acur);
if (acur > abegin) {
std::string port_str(abegin, acur - abegin);
try {
*port = std::stoi(port_str);
} catch (const std::exception& e) {
RAISE(
util::RuntimeException,
"invalid URI: invalid port: %s",
port_str.c_str());
}
}
}
}
begin = cur;
}
/* path */
if (begin < end) {
const char* cur = begin;
for (; cur < end && *cur != '?' && *cur != '#'; ++cur);
if (cur > begin) {
*path = std::string(begin, cur - begin);
}
begin = cur;
}
/* query */
if (begin < end && *begin == '?') {
const char* cur = ++begin;
for (; cur < end && *cur != '#'; ++cur);
if (cur > begin) {
*query = std::string(begin, cur - begin);
}
begin = cur;
}
/* fragment */
if (begin < end - 1 && *begin == '#') {
*fragment = std::string(begin + 1, end - begin - 1);
}
}
void URI::parseQueryString(
const std::string& query,
std::vector<std::pair<std::string, std::string>>* params) {
const char* begin = query.c_str();
const char* end = begin + query.size();
for (const char* cur = begin; cur < end; ++cur) {
for (; cur < end && *cur != '=' && *cur != '&'; cur++);
if (cur > begin && cur < end && *cur == '=' ) {
std::string key_str(begin, cur - begin);
const char* val = ++cur;
for (; cur < end && *cur != '=' && *cur != '&'; cur++);
if (cur > val) {
std::string val_str(val, cur - val);
params->emplace_back(key_str, val_str);
begin = cur + 1;
} else {
break;
}
} else {
break;
}
}
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkPaint.h"
#include "SkRandom.h"
namespace skiagm {
class MovePathGM : public GM {
public:
MovePathGM() {}
protected:
SkString onShortName() {
return SkString("movepath");
}
SkISize onISize() { return make_isize(1240, 390); }
void drawPath(SkPath& path,SkCanvas* canvas,SkColor color,
const SkRect& clip,SkPaint::Cap cap,
SkPaint::Style style, SkPath::FillType fill,
SkScalar strokeWidth) {
path.setFillType(fill);
SkPaint paint;
paint.setStrokeCap(cap);
paint.setStrokeWidth(strokeWidth);
paint.setColor(color);
paint.setStyle(style);
canvas->save();
canvas->clipRect(clip);
canvas->drawPath(path, paint);
canvas->restore();
}
virtual void onDraw(SkCanvas* canvas) {
struct FillAndName {
SkPath::FillType fFill;
const char* fName;
};
static const FillAndName gFills[] = {
{SkPath::kWinding_FillType, "Winding"},
{SkPath::kEvenOdd_FillType, "Even / Odd"},
{SkPath::kInverseWinding_FillType, "Inverse Winding"},
{SkPath::kInverseEvenOdd_FillType, "Inverse Even / Odd"},
};
struct StyleAndName {
SkPaint::Style fStyle;
const char* fName;
};
static const StyleAndName gStyles[] = {
{SkPaint::kFill_Style, "Fill"},
{SkPaint::kStroke_Style, "Stroke"},
{SkPaint::kStrokeAndFill_Style, "Stroke And Fill"},
};
struct CapAndName {
SkPaint::Cap fCap;
const char* fName;
};
static const CapAndName gCaps[] = {
{SkPaint::kButt_Cap, "Butt"},
{SkPaint::kRound_Cap, "Round"},
{SkPaint::kSquare_Cap, "Square"},
};
struct PathAndName {
SkPath fPath;
const char* fName;
};
PathAndName path;
path.fPath.moveTo(50*SK_Scalar1, 15*SK_Scalar1);
path.fName = "moveTo";
SkPaint titlePaint;
titlePaint.setColor(SK_ColorBLACK);
titlePaint.setAntiAlias(true);
titlePaint.setLCDRenderText(true);
titlePaint.setTextSize(15 * SK_Scalar1);
const char title[] = "Lone Move Drawn Into Rectangle Clips With "
"Indicated Style, Fill and Linecaps, with stroke width 10";
canvas->drawText(title, strlen(title),
20 * SK_Scalar1,
20 * SK_Scalar1,
titlePaint);
SkRandom rand;
SkRect rect = SkRect::MakeWH(100*SK_Scalar1, 30*SK_Scalar1);
canvas->save();
canvas->translate(10 * SK_Scalar1, 30 * SK_Scalar1);
canvas->save();
for (size_t cap = 0; cap < SK_ARRAY_COUNT(gCaps); ++cap) {
if (0 < cap) {
canvas->translate((rect.width() + 40 * SK_Scalar1) * SK_ARRAY_COUNT(gStyles), 0);
}
canvas->save();
for (size_t fill = 0; fill < SK_ARRAY_COUNT(gFills); ++fill) {
if (0 < fill) {
canvas->translate(0, rect.height() + 40 * SK_Scalar1);
}
canvas->save();
for (size_t style = 0; style < SK_ARRAY_COUNT(gStyles); ++style) {
if (0 < style) {
canvas->translate(rect.width() + 40 * SK_Scalar1, 0);
}
SkColor color = 0xff007000;
this->drawPath(path.fPath, canvas, color, rect,
gCaps[cap].fCap, gStyles[style].fStyle,
gFills[fill].fFill, SK_Scalar1*10);
SkPaint rectPaint;
rectPaint.setColor(SK_ColorBLACK);
rectPaint.setStyle(SkPaint::kStroke_Style);
rectPaint.setStrokeWidth(-1);
rectPaint.setAntiAlias(true);
canvas->drawRect(rect, rectPaint);
SkPaint labelPaint;
labelPaint.setColor(color);
labelPaint.setAntiAlias(true);
labelPaint.setLCDRenderText(true);
labelPaint.setTextSize(10 * SK_Scalar1);
canvas->drawText(gStyles[style].fName,
strlen(gStyles[style].fName),
0, rect.height() + 12 * SK_Scalar1,
labelPaint);
canvas->drawText(gFills[fill].fName,
strlen(gFills[fill].fName),
0, rect.height() + 24 * SK_Scalar1,
labelPaint);
canvas->drawText(gCaps[cap].fName,
strlen(gCaps[cap].fName),
0, rect.height() + 36 * SK_Scalar1,
labelPaint);
}
canvas->restore();
}
canvas->restore();
}
canvas->restore();
canvas->restore();
}
private:
typedef GM INHERITED;
};
class MoveClosePathGM : public GM {
public:
MoveClosePathGM() {}
protected:
SkString onShortName() {
return SkString("moveclosepath");
}
SkISize onISize() { return make_isize(1240, 390); }
void drawPath(SkPath& path,SkCanvas* canvas,SkColor color,
const SkRect& clip,SkPaint::Cap cap,
SkPaint::Style style, SkPath::FillType fill,
SkScalar strokeWidth) {
path.setFillType(fill);
SkPaint paint;
paint.setStrokeCap(cap);
paint.setStrokeWidth(strokeWidth);
paint.setColor(color);
paint.setStyle(style);
canvas->save();
canvas->clipRect(clip);
canvas->drawPath(path, paint);
canvas->restore();
}
virtual void onDraw(SkCanvas* canvas) {
struct FillAndName {
SkPath::FillType fFill;
const char* fName;
};
static const FillAndName gFills[] = {
{SkPath::kWinding_FillType, "Winding"},
{SkPath::kEvenOdd_FillType, "Even / Odd"},
{SkPath::kInverseWinding_FillType, "Inverse Winding"},
{SkPath::kInverseEvenOdd_FillType, "Inverse Even / Odd"},
};
struct StyleAndName {
SkPaint::Style fStyle;
const char* fName;
};
static const StyleAndName gStyles[] = {
{SkPaint::kFill_Style, "Fill"},
{SkPaint::kStroke_Style, "Stroke"},
{SkPaint::kStrokeAndFill_Style, "Stroke And Fill"},
};
struct CapAndName {
SkPaint::Cap fCap;
const char* fName;
};
static const CapAndName gCaps[] = {
{SkPaint::kButt_Cap, "Butt"},
{SkPaint::kRound_Cap, "Round"},
{SkPaint::kSquare_Cap, "Square"},
};
struct PathAndName {
SkPath fPath;
const char* fName;
};
PathAndName path;
path.fPath.moveTo(50*SK_Scalar1, 15*SK_Scalar1);
path.fPath.close();
path.fName = "moveTo-close";
SkPaint titlePaint;
titlePaint.setColor(SK_ColorBLACK);
titlePaint.setAntiAlias(true);
titlePaint.setLCDRenderText(true);
titlePaint.setTextSize(15 * SK_Scalar1);
const char title[] = "Move Close Drawn Into Rectangle Clips With "
"Indicated Style, Fill and Linecaps, with stroke width 10";
canvas->drawText(title, strlen(title),
20 * SK_Scalar1,
20 * SK_Scalar1,
titlePaint);
SkRandom rand;
SkRect rect = SkRect::MakeWH(100*SK_Scalar1, 30*SK_Scalar1);
canvas->save();
canvas->translate(10 * SK_Scalar1, 30 * SK_Scalar1);
canvas->save();
for (size_t cap = 0; cap < SK_ARRAY_COUNT(gCaps); ++cap) {
if (0 < cap) {
canvas->translate((rect.width() + 40 * SK_Scalar1) * SK_ARRAY_COUNT(gStyles), 0);
}
canvas->save();
for (size_t fill = 0; fill < SK_ARRAY_COUNT(gFills); ++fill) {
if (0 < fill) {
canvas->translate(0, rect.height() + 40 * SK_Scalar1);
}
canvas->save();
for (size_t style = 0; style < SK_ARRAY_COUNT(gStyles); ++style) {
if (0 < style) {
canvas->translate(rect.width() + 40 * SK_Scalar1, 0);
}
SkColor color = 0xff007000;
this->drawPath(path.fPath, canvas, color, rect,
gCaps[cap].fCap, gStyles[style].fStyle,
gFills[fill].fFill, SK_Scalar1*10);
SkPaint rectPaint;
rectPaint.setColor(SK_ColorBLACK);
rectPaint.setStyle(SkPaint::kStroke_Style);
rectPaint.setStrokeWidth(-1);
rectPaint.setAntiAlias(true);
canvas->drawRect(rect, rectPaint);
SkPaint labelPaint;
labelPaint.setColor(color);
labelPaint.setAntiAlias(true);
labelPaint.setLCDRenderText(true);
labelPaint.setTextSize(10 * SK_Scalar1);
canvas->drawText(gStyles[style].fName,
strlen(gStyles[style].fName),
0, rect.height() + 12 * SK_Scalar1,
labelPaint);
canvas->drawText(gFills[fill].fName,
strlen(gFills[fill].fName),
0, rect.height() + 24 * SK_Scalar1,
labelPaint);
canvas->drawText(gCaps[cap].fName,
strlen(gCaps[cap].fName),
0, rect.height() + 36 * SK_Scalar1,
labelPaint);
}
canvas->restore();
}
canvas->restore();
}
canvas->restore();
canvas->restore();
}
private:
typedef GM INHERITED;
};
class MoveMovePathGM : public GM {
public:
MoveMovePathGM() {}
protected:
SkString onShortName() {
return SkString("movemovepath");
}
SkISize onISize() { return make_isize(1240, 390); }
void drawPath(SkPath& path,SkCanvas* canvas,SkColor color,
const SkRect& clip,SkPaint::Cap cap,
SkPaint::Style style, SkPath::FillType fill,
SkScalar strokeWidth) {
path.setFillType(fill);
SkPaint paint;
paint.setStrokeCap(cap);
paint.setStrokeWidth(strokeWidth);
paint.setColor(color);
paint.setStyle(style);
canvas->save();
canvas->clipRect(clip);
canvas->drawPath(path, paint);
canvas->restore();
}
virtual void onDraw(SkCanvas* canvas) {
struct FillAndName {
SkPath::FillType fFill;
const char* fName;
};
static const FillAndName gFills[] = {
{SkPath::kWinding_FillType, "Winding"},
{SkPath::kEvenOdd_FillType, "Even / Odd"},
{SkPath::kInverseWinding_FillType, "Inverse Winding"},
{SkPath::kInverseEvenOdd_FillType, "Inverse Even / Odd"},
};
struct StyleAndName {
SkPaint::Style fStyle;
const char* fName;
};
static const StyleAndName gStyles[] = {
{SkPaint::kFill_Style, "Fill"},
{SkPaint::kStroke_Style, "Stroke"},
{SkPaint::kStrokeAndFill_Style, "Stroke And Fill"},
};
struct CapAndName {
SkPaint::Cap fCap;
const char* fName;
};
static const CapAndName gCaps[] = {
{SkPaint::kButt_Cap, "Butt"},
{SkPaint::kRound_Cap, "Round"},
{SkPaint::kSquare_Cap, "Square"},
};
struct PathAndName {
SkPath fPath;
const char* fName;
};
PathAndName path;
path.fPath.moveTo(50*SK_Scalar1, 15*SK_Scalar1);
path.fPath.moveTo(75*SK_Scalar1, 15*SK_Scalar1);
path.fName = "moveTo-moveTo";
SkPaint titlePaint;
titlePaint.setColor(SK_ColorBLACK);
titlePaint.setAntiAlias(true);
titlePaint.setLCDRenderText(true);
titlePaint.setTextSize(15 * SK_Scalar1);
const char title[] = "Move Move Drawn Into Rectangle Clips With "
"Indicated Style, Fill and Linecaps, with stroke width 10";
canvas->drawText(title, strlen(title),
20 * SK_Scalar1,
20 * SK_Scalar1,
titlePaint);
SkRandom rand;
SkRect rect = SkRect::MakeWH(100*SK_Scalar1, 30*SK_Scalar1);
canvas->save();
canvas->translate(10 * SK_Scalar1, 30 * SK_Scalar1);
canvas->save();
for (size_t cap = 0; cap < SK_ARRAY_COUNT(gCaps); ++cap) {
if (0 < cap) {
canvas->translate((rect.width() + 40 * SK_Scalar1) * SK_ARRAY_COUNT(gStyles), 0);
}
canvas->save();
for (size_t fill = 0; fill < SK_ARRAY_COUNT(gFills); ++fill) {
if (0 < fill) {
canvas->translate(0, rect.height() + 40 * SK_Scalar1);
}
canvas->save();
for (size_t style = 0; style < SK_ARRAY_COUNT(gStyles); ++style) {
if (0 < style) {
canvas->translate(rect.width() + 40 * SK_Scalar1, 0);
}
SkColor color = 0xff007000;
this->drawPath(path.fPath, canvas, color, rect,
gCaps[cap].fCap, gStyles[style].fStyle,
gFills[fill].fFill, SK_Scalar1*10);
SkPaint rectPaint;
rectPaint.setColor(SK_ColorBLACK);
rectPaint.setStyle(SkPaint::kStroke_Style);
rectPaint.setStrokeWidth(-1);
rectPaint.setAntiAlias(true);
canvas->drawRect(rect, rectPaint);
SkPaint labelPaint;
labelPaint.setColor(color);
labelPaint.setAntiAlias(true);
labelPaint.setLCDRenderText(true);
labelPaint.setTextSize(10 * SK_Scalar1);
canvas->drawText(gStyles[style].fName,
strlen(gStyles[style].fName),
0, rect.height() + 12 * SK_Scalar1,
labelPaint);
canvas->drawText(gFills[fill].fName,
strlen(gFills[fill].fName),
0, rect.height() + 24 * SK_Scalar1,
labelPaint);
canvas->drawText(gCaps[cap].fName,
strlen(gCaps[cap].fName),
0, rect.height() + 36 * SK_Scalar1,
labelPaint);
}
canvas->restore();
}
canvas->restore();
}
canvas->restore();
canvas->restore();
}
private:
typedef GM INHERITED;
};
class MoveCloseMoveClosePathGM : public GM {
public:
MoveCloseMoveClosePathGM() {}
protected:
SkString onShortName() {
return SkString("moveclosemoveclosepath");
}
SkISize onISize() { return make_isize(1240, 390); }
void drawPath(SkPath& path,SkCanvas* canvas,SkColor color,
const SkRect& clip,SkPaint::Cap cap,
SkPaint::Style style, SkPath::FillType fill,
SkScalar strokeWidth) {
path.setFillType(fill);
SkPaint paint;
paint.setStrokeCap(cap);
paint.setStrokeWidth(strokeWidth);
paint.setColor(color);
paint.setStyle(style);
canvas->save();
canvas->clipRect(clip);
canvas->drawPath(path, paint);
canvas->restore();
}
virtual void onDraw(SkCanvas* canvas) {
struct FillAndName {
SkPath::FillType fFill;
const char* fName;
};
static const FillAndName gFills[] = {
{SkPath::kWinding_FillType, "Winding"},
{SkPath::kEvenOdd_FillType, "Even / Odd"},
{SkPath::kInverseWinding_FillType, "Inverse Winding"},
{SkPath::kInverseEvenOdd_FillType, "Inverse Even / Odd"},
};
struct StyleAndName {
SkPaint::Style fStyle;
const char* fName;
};
static const StyleAndName gStyles[] = {
{SkPaint::kFill_Style, "Fill"},
{SkPaint::kStroke_Style, "Stroke"},
{SkPaint::kStrokeAndFill_Style, "Stroke And Fill"},
};
struct CapAndName {
SkPaint::Cap fCap;
const char* fName;
};
static const CapAndName gCaps[] = {
{SkPaint::kButt_Cap, "Butt"},
{SkPaint::kRound_Cap, "Round"},
{SkPaint::kSquare_Cap, "Square"},
};
struct PathAndName {
SkPath fPath;
const char* fName;
};
PathAndName path;
path.fPath.moveTo(50*SK_Scalar1, 15*SK_Scalar1);
path.fPath.close();
path.fPath.moveTo(75*SK_Scalar1, 15*SK_Scalar1);
path.fPath.close();
path.fName = "moveTo-close-moveTo-close";
SkPaint titlePaint;
titlePaint.setColor(SK_ColorBLACK);
titlePaint.setAntiAlias(true);
titlePaint.setLCDRenderText(true);
titlePaint.setTextSize(15 * SK_Scalar1);
const char title[] = "Move-Close-Move-Close Drawn Into Rectangle Clips With "
"Indicated Style, Fill and Linecaps, with stroke width 10";
canvas->drawText(title, strlen(title),
20 * SK_Scalar1,
20 * SK_Scalar1,
titlePaint);
SkRandom rand;
SkRect rect = SkRect::MakeWH(100*SK_Scalar1, 30*SK_Scalar1);
canvas->save();
canvas->translate(10 * SK_Scalar1, 30 * SK_Scalar1);
canvas->save();
for (size_t cap = 0; cap < SK_ARRAY_COUNT(gCaps); ++cap) {
if (0 < cap) {
canvas->translate((rect.width() + 40 * SK_Scalar1) * SK_ARRAY_COUNT(gStyles), 0);
}
canvas->save();
for (size_t fill = 0; fill < SK_ARRAY_COUNT(gFills); ++fill) {
if (0 < fill) {
canvas->translate(0, rect.height() + 40 * SK_Scalar1);
}
canvas->save();
for (size_t style = 0; style < SK_ARRAY_COUNT(gStyles); ++style) {
if (0 < style) {
canvas->translate(rect.width() + 40 * SK_Scalar1, 0);
}
SkColor color = 0xff007000;
this->drawPath(path.fPath, canvas, color, rect,
gCaps[cap].fCap, gStyles[style].fStyle,
gFills[fill].fFill, SK_Scalar1*10);
SkPaint rectPaint;
rectPaint.setColor(SK_ColorBLACK);
rectPaint.setStyle(SkPaint::kStroke_Style);
rectPaint.setStrokeWidth(-1);
rectPaint.setAntiAlias(true);
canvas->drawRect(rect, rectPaint);
SkPaint labelPaint;
labelPaint.setColor(color);
labelPaint.setAntiAlias(true);
labelPaint.setLCDRenderText(true);
labelPaint.setTextSize(10 * SK_Scalar1);
canvas->drawText(gStyles[style].fName,
strlen(gStyles[style].fName),
0, rect.height() + 12 * SK_Scalar1,
labelPaint);
canvas->drawText(gFills[fill].fName,
strlen(gFills[fill].fName),
0, rect.height() + 24 * SK_Scalar1,
labelPaint);
canvas->drawText(gCaps[cap].fName,
strlen(gCaps[cap].fName),
0, rect.height() + 36 * SK_Scalar1,
labelPaint);
}
canvas->restore();
}
canvas->restore();
}
canvas->restore();
canvas->restore();
}
private:
typedef GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static GM* MPathFactory(void*) { return new MovePathGM; }
static GMRegistry regMPath(MPathFactory);
static GM* MCPathFactory(void*) { return new MoveClosePathGM; }
static GMRegistry regMCPath(MCPathFactory);
static GM* MMPathFactory(void*) { return new MoveMovePathGM; }
static GMRegistry regMMPath(MMPathFactory);
static GM* MCMCPathFactory(void*) { return new MoveCloseMoveClosePathGM; }
static GMRegistry regMCMCPath(MCMCPathFactory);
}
<commit_msg>Removing unnecessary gm tests. Unreviewed but approved by reed@google.com.<commit_after><|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.