text
stringlengths
54
60.6k
<commit_before>// Copyright 2010 Gregory Szorc // // 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 <zippylog/zippylog.hpp> #include <zippylog/device/server.hpp> #include <iostream> #include <string> using ::zippylog::device::Server; using ::std::cout; using ::std::endl; using ::std::string; using ::std::vector; #ifdef LINUX static volatile sig_atomic_t active = 1; void signal_handler(int signo) { active = 0; signal(signo, SIG_DFL); } #endif int main(int argc, const char * const argv[]) { #ifdef LINUX // TODO this signal handling is horribly naive signal(SIGINT, signal_handler); signal(SIGTERM, signal_handler); #endif try { ::zippylog::initialize_library(); Server server(argv[1]); #ifdef LINUX server.RunAsync(); while (active) pause(); #elif WINDOWS server.Run(); #else #error "not implemented on this platform" #endif } catch (string s) { cout << "Exception:" << endl; cout << s; return 1; } catch (char * s) { cout << "Exception: " << s << endl; return 1; } catch (...) { cout << "received an exception" << endl; return 1; } ::zippylog::shutdown_library(); return 0; } <commit_msg>catch exceptions better<commit_after>// Copyright 2010 Gregory Szorc // // 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 <zippylog/zippylog.hpp> #include <zippylog/device/server.hpp> #include <iostream> #include <string> using ::zippylog::device::Server; using ::std::cout; using ::std::endl; using ::std::string; using ::std::vector; #ifdef LINUX static volatile sig_atomic_t active = 1; void signal_handler(int signo) { active = 0; signal(signo, SIG_DFL); } #endif int main(int argc, const char * const argv[]) { #ifdef LINUX // TODO this signal handling is horribly naive signal(SIGINT, signal_handler); signal(SIGTERM, signal_handler); #endif try { ::zippylog::initialize_library(); Server server(argv[1]); #ifdef LINUX server.RunAsync(); while (active) pause(); #elif WINDOWS server.Run(); #else #error "not implemented on this platform" #endif } catch (::std::exception e) { cout << "Exception: " << e.what() << endl; return 1; } ::zippylog::shutdown_library(); return 0; } <|endoftext|>
<commit_before>#include "qcsvtoxml.h" #include <algorithm> #include <QFileDialog> #include <QTextStream> #include <QXmlStreamWriter> QCSVToXML::QCSVToXML(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); connect(this->ui.actionLoad, &QAction::triggered, this, &QCSVToXML::loadAction); connect(this->ui.actionExport, &QAction::triggered, this, &QCSVToXML::saveAction); connect(this->ui.lineEditElement, &QLineEdit::textChanged, this, &QCSVToXML::refreshXmlPreview); connect(this->ui.lineEditNamespace, &QLineEdit::textChanged, this, &QCSVToXML::refreshXmlPreview); connect(this->ui.lineEditNamespaceUri, &QLineEdit::textChanged, this, &QCSVToXML::refreshXmlPreview); connect(this->ui.lineEditRoot, &QLineEdit::textChanged, this, &QCSVToXML::refreshXmlPreview); connect(this->ui.checkBoxAttributeAsElement, &QCheckBox::toggled, this, &QCSVToXML::refreshXmlPreview); connect(this->ui.checkBoxFirstRowAsAttributes, &QCheckBox::toggled, this, &QCSVToXML::refreshXmlPreview); } QCSVToXML::~QCSVToXML() { } void QCSVToXML::loadAction() { this->load( QFileDialog::getOpenFileName( this, tr("Load File"), this->settings.value( "workingDirectory", QApplication::applicationDirPath()).toString(), tr("CSV files (*.csv)"))); } void QCSVToXML::saveAction() { this->save( QFileDialog::getSaveFileName( this, tr("Save File"), this->settings.value( "workingDirectory", QApplication::applicationDirPath()).toString(), tr("XML files (*.xml)"))); } void QCSVToXML::load(const QString &filename) { if (filename.isEmpty()) { return; } QFile file(filename); QFileInfo fileInfo(file); this->settings.setValue("workingDirectory", fileInfo.absolutePath()); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return; } this->csvContents.clear(); this->ui.lineEditElement->setText(fileInfo.baseName()); this->ui.lineEditRoot->setText(fileInfo.baseName() + "s"); QTextStream in(&file); while (!in.atEnd()) { QString line = in.readLine(); while (line.count('"') % 2 != 0 && !in.atEnd()) { // If we have an odd number of quotes there must be a newline in // one of the fields. (or RFC 4180 is not being followed, in which // case we don't care about handling the file properly.) line += '\n' + in.readLine(); } bool quoted = false; int start = 0; std::vector<QString> elements; for (int i = 0; i <= line.length(); ++i) { if (i == line.length()) { elements.push_back(line.mid(start)); } else if (line[i] == '"') { quoted = !quoted; } else if (line[i] == ',' && !quoted) { elements.push_back(line.mid(start, i - start)); start = i + 1; } } for (int i = 0; i < elements.size(); ++i) { // remove quotes surrounding quoted fields. elements[i].replace( QRegularExpression( "^\\s*\"(.*)\"\\s*$", QRegularExpression::DotMatchesEverythingOption), "\\1"); // unescape quotes. elements[i].replace("\"\"", "\""); } this->csvContents.push_back(elements); } this->populateAttributeGroupBox(); this->refreshXmlPreview(); } void QCSVToXML::save(const QString &filename) { if (filename.isEmpty()) { return; } QFile file(filename); QFileInfo fileInfo(file); this->settings.setValue("workingDirectory", fileInfo.absolutePath()); } void QCSVToXML::populateAttributeGroupBox() { if (this->csvContents.empty() || this->csvContents[0].size() < this->ui.formLayoutWidgetAttributes->rowCount()) { this->fieldLineEdits.clear(); this->ui.verticalLayoutGroupBoxAttributes->removeWidget(this->ui.widgetAttributes); delete this->ui.widgetAttributes; this->ui.widgetAttributes = new QWidget(this->ui.groupBoxAttributes); this->ui.formLayoutWidgetAttributes = new QFormLayout(this->ui.widgetAttributes); this->ui.verticalLayoutGroupBoxAttributes->addWidget(this->ui.widgetAttributes); } for (int i = this->ui.formLayoutWidgetAttributes->rowCount(); i < this->csvContents[0].size(); ++i) { QLineEdit *lineEdit = new QLineEdit(this->ui.widgetAttributes); if (this->ui.checkBoxFirstRowAsAttributes->isChecked()) { lineEdit->setText(this->csvContents[0][i]); } else { lineEdit->setText(QString("Attribute %1").arg(QString::number(i))); } this->fieldLineEdits.push_back(lineEdit); this->ui.formLayoutWidgetAttributes->addRow(QString("Field %1:").arg(QString::number(i)), lineEdit); } } void QCSVToXML::refreshXmlPreview() { if (this->csvContents.empty()) { this->ui.textBrowserXmlOutput->clear(); return; } QString xml; QXmlStreamWriter writer(&xml); writer.setAutoFormatting(true); writer.writeStartDocument(); writer.writeStartElement(this->ui.lineEditRoot->text().replace(' ', '_')); writer.writeStartElement(this->ui.lineEditElement->text().replace(' ', '_')); int dataRow = (this->ui.checkBoxFirstRowAsAttributes->isChecked() && this->csvContents.size() > 1) ? 1 : 0; for (int i = 0; i < std::min(this->csvContents[dataRow].size(), this->csvContents[0].size()); ++i) { if (this->ui.checkBoxAttributeAsElement->isChecked()) { writer.writeTextElement(this->fieldLineEdits[i]->text().replace(' ', '_'), this->csvContents[dataRow][i]); } else { writer.writeAttribute(this->ui.lineEditNamespaceUri->text().replace(' ', '_'), this->fieldLineEdits[i]->text(), this->csvContents[dataRow][i]); } } writer.writeEndElement(); writer.writeEndElement(); writer.writeEndDocument(); this->ui.textBrowserXmlOutput->setText(xml); } <commit_msg>Spaces replaced with underscores in attribute names too...<commit_after>#include "qcsvtoxml.h" #include <algorithm> #include <QFileDialog> #include <QTextStream> #include <QXmlStreamWriter> QCSVToXML::QCSVToXML(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); connect(this->ui.actionLoad, &QAction::triggered, this, &QCSVToXML::loadAction); connect(this->ui.actionExport, &QAction::triggered, this, &QCSVToXML::saveAction); connect(this->ui.lineEditElement, &QLineEdit::textChanged, this, &QCSVToXML::refreshXmlPreview); connect(this->ui.lineEditNamespace, &QLineEdit::textChanged, this, &QCSVToXML::refreshXmlPreview); connect(this->ui.lineEditNamespaceUri, &QLineEdit::textChanged, this, &QCSVToXML::refreshXmlPreview); connect(this->ui.lineEditRoot, &QLineEdit::textChanged, this, &QCSVToXML::refreshXmlPreview); connect(this->ui.checkBoxAttributeAsElement, &QCheckBox::toggled, this, &QCSVToXML::refreshXmlPreview); connect(this->ui.checkBoxFirstRowAsAttributes, &QCheckBox::toggled, this, &QCSVToXML::refreshXmlPreview); } QCSVToXML::~QCSVToXML() { } void QCSVToXML::loadAction() { this->load( QFileDialog::getOpenFileName( this, tr("Load File"), this->settings.value( "workingDirectory", QApplication::applicationDirPath()).toString(), tr("CSV files (*.csv)"))); } void QCSVToXML::saveAction() { this->save( QFileDialog::getSaveFileName( this, tr("Save File"), this->settings.value( "workingDirectory", QApplication::applicationDirPath()).toString(), tr("XML files (*.xml)"))); } void QCSVToXML::load(const QString &filename) { if (filename.isEmpty()) { return; } QFile file(filename); QFileInfo fileInfo(file); this->settings.setValue("workingDirectory", fileInfo.absolutePath()); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return; } this->csvContents.clear(); this->ui.lineEditElement->setText(fileInfo.baseName()); this->ui.lineEditRoot->setText(fileInfo.baseName() + "s"); QTextStream in(&file); while (!in.atEnd()) { QString line = in.readLine(); while (line.count('"') % 2 != 0 && !in.atEnd()) { // If we have an odd number of quotes there must be a newline in // one of the fields. (or RFC 4180 is not being followed, in which // case we don't care about handling the file properly.) line += '\n' + in.readLine(); } bool quoted = false; int start = 0; std::vector<QString> elements; for (int i = 0; i <= line.length(); ++i) { if (i == line.length()) { elements.push_back(line.mid(start)); } else if (line[i] == '"') { quoted = !quoted; } else if (line[i] == ',' && !quoted) { elements.push_back(line.mid(start, i - start)); start = i + 1; } } for (int i = 0; i < elements.size(); ++i) { // remove quotes surrounding quoted fields. elements[i].replace( QRegularExpression( "^\\s*\"(.*)\"\\s*$", QRegularExpression::DotMatchesEverythingOption), "\\1"); // unescape quotes. elements[i].replace("\"\"", "\""); } this->csvContents.push_back(elements); } this->populateAttributeGroupBox(); this->refreshXmlPreview(); } void QCSVToXML::save(const QString &filename) { if (filename.isEmpty()) { return; } QFile file(filename); QFileInfo fileInfo(file); this->settings.setValue("workingDirectory", fileInfo.absolutePath()); } void QCSVToXML::populateAttributeGroupBox() { if (this->csvContents.empty() || this->csvContents[0].size() < this->ui.formLayoutWidgetAttributes->rowCount()) { this->fieldLineEdits.clear(); this->ui.verticalLayoutGroupBoxAttributes->removeWidget(this->ui.widgetAttributes); delete this->ui.widgetAttributes; this->ui.widgetAttributes = new QWidget(this->ui.groupBoxAttributes); this->ui.formLayoutWidgetAttributes = new QFormLayout(this->ui.widgetAttributes); this->ui.verticalLayoutGroupBoxAttributes->addWidget(this->ui.widgetAttributes); } for (int i = this->ui.formLayoutWidgetAttributes->rowCount(); i < this->csvContents[0].size(); ++i) { QLineEdit *lineEdit = new QLineEdit(this->ui.widgetAttributes); if (this->ui.checkBoxFirstRowAsAttributes->isChecked()) { lineEdit->setText(this->csvContents[0][i]); } else { lineEdit->setText(QString("Attribute %1").arg(QString::number(i))); } this->fieldLineEdits.push_back(lineEdit); this->ui.formLayoutWidgetAttributes->addRow(QString("Field %1:").arg(QString::number(i)), lineEdit); } } void QCSVToXML::refreshXmlPreview() { if (this->csvContents.empty()) { this->ui.textBrowserXmlOutput->clear(); return; } QString xml; QXmlStreamWriter writer(&xml); writer.setAutoFormatting(true); writer.writeStartDocument(); writer.writeStartElement(this->ui.lineEditRoot->text().replace(' ', '_')); writer.writeStartElement(this->ui.lineEditElement->text().replace(' ', '_')); int dataRow = (this->ui.checkBoxFirstRowAsAttributes->isChecked() && this->csvContents.size() > 1) ? 1 : 0; for (int i = 0; i < std::min(this->csvContents[dataRow].size(), this->csvContents[0].size()); ++i) { if (this->ui.checkBoxAttributeAsElement->isChecked()) { writer.writeTextElement(this->fieldLineEdits[i]->text().replace(' ', '_'), this->csvContents[dataRow][i]); } else { writer.writeAttribute(this->ui.lineEditNamespaceUri->text().replace(' ', '_'), this->fieldLineEdits[i]->text().replace(' ', '_'), this->csvContents[dataRow][i]); } } writer.writeEndElement(); writer.writeEndElement(); writer.writeEndDocument(); this->ui.textBrowserXmlOutput->setText(xml); } <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include "caf/config.hpp" #include "caf/detail/parser/add_ascii.hpp" #include "caf/detail/parser/chars.hpp" #include "caf/detail/parser/read_ipv6_address.hpp" #include "caf/detail/parser/state.hpp" #include "caf/detail/scope_guard.hpp" #include "caf/pec.hpp" #include "caf/uri.hpp" CAF_PUSH_UNUSED_LABEL_WARNING #include "caf/detail/parser/fsm.hpp" namespace caf { namespace detail { namespace parser { // foo://example.com:8042/over/there?name=ferret#nose // \_/ \______________/\_________/ \_________/ \__/ // | | | | | // scheme authority path query fragment // | _____________________|__ // / \ / \. // urn:example:animal:ferret:nose // Unlike our other parsers, the URI parsers only check for validity and // generate ranges for the subcomponents. URIs can't have linebreaks, so we can // safely keep track of the position by looking at the column. template <class Iterator, class Sentinel> void read_uri_percent_encoded(state<Iterator, Sentinel>& ps, std::string& str) { uint8_t char_code = 0; auto g = make_scope_guard([&] { if (ps.code <= pec::trailing_character) str += static_cast<char>(char_code); }); start(); state(init) { transition(read_nibble, hexadecimal_chars, add_ascii<16>(char_code, ch)) } state(read_nibble) { transition(done, hexadecimal_chars, add_ascii<16>(char_code, ch)) } term_state(done) { // nop } fin(); } inline bool uri_unprotected_char(char c) { return in_whitelist(alphanumeric_chars, c) || in_whitelist("-._~", c); } #define read_next_char(next_state, dest) \ transition(next_state, uri_unprotected_char, dest += ch) \ fsm_transition(read_uri_percent_encoded(ps, dest), next_state, '%') template <class Iterator, class Sentinel, class Consumer> void read_uri_query(state<Iterator, Sentinel>& ps, Consumer&& consumer) { // Local variables. uri::query_map result; std::string key; std::string value; // Utility functions. auto take_str = [&](std::string& str) { using std::swap; std::string res; swap(str, res); return std::move(res); }; auto push = [&] { result.emplace(take_str(key), take_str(value)); }; // Call consumer on exit. auto g = make_scope_guard([&] { if (ps.code <= pec::trailing_character) consumer.query(std::move(result)); }); // FSM declaration. start(); // query may be empty term_state(init) { read_next_char(read_key, key) } state(read_key) { read_next_char(read_key, key) transition(read_value, '=') } term_state(read_value, push()) { read_next_char(read_value, value) transition(init, '&', push()) } fin(); } template <class Iterator, class Sentinel, class Consumer> void read_uri(state<Iterator, Sentinel>& ps, Consumer&& consumer) { // Local variables. std::string str; uint16_t port = 0; // Replaces `str` with a default constructed string to make sure we're never // operating on a moved-from string object. auto take_str = [&] { using std::swap; std::string res; swap(str, res); return std::move(res); }; // Allowed character sets. auto path_char = [](char c) { return in_whitelist(alphanumeric_chars, c) || c == '/'; }; // Utility setters for avoiding code duplication. auto set_path = [&] { consumer.path(take_str()); }; auto set_host = [&] { consumer.host(take_str()); }; auto set_userinfo = [&] { consumer.userinfo(take_str()); }; // Consumer for reading IPv6 addresses. struct { Consumer& f; void value(ipv6_address addr) { f.host(addr); } } ip_consumer{consumer}; // FSM declaration. start(); state(init) { epsilon(read_scheme) } state(read_scheme) { read_next_char(read_scheme, str) transition(have_scheme, ':', consumer.scheme(take_str())) } state(have_scheme) { transition(disambiguate_path, '/') read_next_char(read_path, str) fsm_transition(read_uri_percent_encoded(ps, str), read_path, '%') } // This state is terminal, because "file:/" is a valid URI. term_state(disambiguate_path, consumer.path("/")) { transition(start_authority, '/') epsilon(read_path, any_char, str += '/') } state(start_authority) { read_next_char(read_authority, str) fsm_transition(read_ipv6_address(ps, ip_consumer), await_end_of_ipv6, '[') } state(await_end_of_ipv6) { transition(end_of_ipv6_host, ']') } term_state(end_of_ipv6_host) { transition(start_port, ':') epsilon(end_of_authority) } term_state(end_of_host) { transition(start_port, ':', set_host()) epsilon(end_of_authority, "/?#", set_host()) } term_state(read_authority, set_host()) { read_next_char(read_authority, str) transition(start_host, '@', set_userinfo()) transition(start_port, ':', set_host()) epsilon(end_of_authority, "/?#", set_host()) } state(start_host) { read_next_char(read_host, str) fsm_transition(read_ipv6_address(ps, ip_consumer), await_end_of_ipv6, '[') } term_state(read_host, set_host()) { read_next_char(read_host, str) transition(start_port, ':', set_host()) epsilon(end_of_authority, "/?#", set_host()) } state(start_port) { transition(read_port, decimal_chars, add_ascii<10>(port, ch)) } term_state(read_port, consumer.port(port)) { transition(read_port, decimal_chars, add_ascii<10>(port, ch), pec::integer_overflow) epsilon(end_of_authority, "/?#", consumer.port(port)) } term_state(end_of_authority) { transition(read_path, '/') transition(start_query, '?') transition(read_fragment, '#') } term_state(read_path, set_path()) { transition(read_path, path_char, str += ch) fsm_transition(read_uri_percent_encoded(ps, str), read_path, '%') transition(start_query, '?', set_path()) transition(read_fragment, '#', set_path()) } term_state(start_query) { fsm_epsilon(read_uri_query(ps, consumer), end_of_query) } unstable_state(end_of_query) { transition(read_fragment, '#') epsilon(done) } term_state(read_fragment, consumer.fragment(take_str())) { read_next_char(read_fragment, str) } term_state(done) { // nop } fin(); } } // namespace parser } // namespace detail } // namespace caf #include "caf/detail/parser/fsm_undef.hpp" CAF_POP_WARNINGS <commit_msg>Fix commenting style<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include "caf/config.hpp" #include "caf/detail/parser/add_ascii.hpp" #include "caf/detail/parser/chars.hpp" #include "caf/detail/parser/read_ipv6_address.hpp" #include "caf/detail/parser/state.hpp" #include "caf/detail/scope_guard.hpp" #include "caf/pec.hpp" #include "caf/uri.hpp" CAF_PUSH_UNUSED_LABEL_WARNING #include "caf/detail/parser/fsm.hpp" namespace caf { namespace detail { namespace parser { // foo://example.com:8042/over/there?name=ferret#nose // \_/ \______________/\_________/ \_________/ \__/ // | | | | | // scheme authority path query fragment // | _____________________|__ // / \ / \. // urn:example:animal:ferret:nose // Unlike our other parsers, the URI parsers only check for validity and // generate ranges for the subcomponents. URIs can't have linebreaks, so we can // safely keep track of the position by looking at the column. template <class Iterator, class Sentinel> void read_uri_percent_encoded(state<Iterator, Sentinel>& ps, std::string& str) { uint8_t char_code = 0; auto g = make_scope_guard([&] { if (ps.code <= pec::trailing_character) str += static_cast<char>(char_code); }); start(); state(init) { transition(read_nibble, hexadecimal_chars, add_ascii<16>(char_code, ch)) } state(read_nibble) { transition(done, hexadecimal_chars, add_ascii<16>(char_code, ch)) } term_state(done) { // nop } fin(); } inline bool uri_unprotected_char(char c) { return in_whitelist(alphanumeric_chars, c) || in_whitelist("-._~", c); } #define read_next_char(next_state, dest) \ transition(next_state, uri_unprotected_char, dest += ch) \ fsm_transition(read_uri_percent_encoded(ps, dest), next_state, '%') template <class Iterator, class Sentinel, class Consumer> void read_uri_query(state<Iterator, Sentinel>& ps, Consumer&& consumer) { // Local variables. uri::query_map result; std::string key; std::string value; // Utility functions. auto take_str = [&](std::string& str) { using std::swap; std::string res; swap(str, res); return std::move(res); }; auto push = [&] { result.emplace(take_str(key), take_str(value)); }; // Call consumer on exit. auto g = make_scope_guard([&] { if (ps.code <= pec::trailing_character) consumer.query(std::move(result)); }); // FSM declaration. start(); // Query may be empty. term_state(init) { read_next_char(read_key, key) } state(read_key) { read_next_char(read_key, key) transition(read_value, '=') } term_state(read_value, push()) { read_next_char(read_value, value) transition(init, '&', push()) } fin(); } template <class Iterator, class Sentinel, class Consumer> void read_uri(state<Iterator, Sentinel>& ps, Consumer&& consumer) { // Local variables. std::string str; uint16_t port = 0; // Replaces `str` with a default constructed string to make sure we're never // operating on a moved-from string object. auto take_str = [&] { using std::swap; std::string res; swap(str, res); return std::move(res); }; // Allowed character sets. auto path_char = [](char c) { return in_whitelist(alphanumeric_chars, c) || c == '/'; }; // Utility setters for avoiding code duplication. auto set_path = [&] { consumer.path(take_str()); }; auto set_host = [&] { consumer.host(take_str()); }; auto set_userinfo = [&] { consumer.userinfo(take_str()); }; // Consumer for reading IPv6 addresses. struct { Consumer& f; void value(ipv6_address addr) { f.host(addr); } } ip_consumer{consumer}; // FSM declaration. start(); state(init) { epsilon(read_scheme) } state(read_scheme) { read_next_char(read_scheme, str) transition(have_scheme, ':', consumer.scheme(take_str())) } state(have_scheme) { transition(disambiguate_path, '/') read_next_char(read_path, str) fsm_transition(read_uri_percent_encoded(ps, str), read_path, '%') } // This state is terminal, because "file:/" is a valid URI. term_state(disambiguate_path, consumer.path("/")) { transition(start_authority, '/') epsilon(read_path, any_char, str += '/') } state(start_authority) { read_next_char(read_authority, str) fsm_transition(read_ipv6_address(ps, ip_consumer), await_end_of_ipv6, '[') } state(await_end_of_ipv6) { transition(end_of_ipv6_host, ']') } term_state(end_of_ipv6_host) { transition(start_port, ':') epsilon(end_of_authority) } term_state(end_of_host) { transition(start_port, ':', set_host()) epsilon(end_of_authority, "/?#", set_host()) } term_state(read_authority, set_host()) { read_next_char(read_authority, str) transition(start_host, '@', set_userinfo()) transition(start_port, ':', set_host()) epsilon(end_of_authority, "/?#", set_host()) } state(start_host) { read_next_char(read_host, str) fsm_transition(read_ipv6_address(ps, ip_consumer), await_end_of_ipv6, '[') } term_state(read_host, set_host()) { read_next_char(read_host, str) transition(start_port, ':', set_host()) epsilon(end_of_authority, "/?#", set_host()) } state(start_port) { transition(read_port, decimal_chars, add_ascii<10>(port, ch)) } term_state(read_port, consumer.port(port)) { transition(read_port, decimal_chars, add_ascii<10>(port, ch), pec::integer_overflow) epsilon(end_of_authority, "/?#", consumer.port(port)) } term_state(end_of_authority) { transition(read_path, '/') transition(start_query, '?') transition(read_fragment, '#') } term_state(read_path, set_path()) { transition(read_path, path_char, str += ch) fsm_transition(read_uri_percent_encoded(ps, str), read_path, '%') transition(start_query, '?', set_path()) transition(read_fragment, '#', set_path()) } term_state(start_query) { fsm_epsilon(read_uri_query(ps, consumer), end_of_query) } unstable_state(end_of_query) { transition(read_fragment, '#') epsilon(done) } term_state(read_fragment, consumer.fragment(take_str())) { read_next_char(read_fragment, str) } term_state(done) { // nop } fin(); } } // namespace parser } // namespace detail } // namespace caf #include "caf/detail/parser/fsm_undef.hpp" CAF_POP_WARNINGS <|endoftext|>
<commit_before><commit_msg>add a copy method to the AST<commit_after><|endoftext|>
<commit_before>#include "qhotkey.h" #include "qhotkey_p.h" #include <QDebug> #include <QX11Info> #include <QThreadStorage> #include <X11/Xlib.h> #include <xcb/xcb.h> //compability to pre Qt 5.8 #ifndef Q_FALLTHROUGH #define Q_FALLTHROUGH() (void)0 #endif class QHotkeyPrivateX11 : public QHotkeyPrivate { public: // QAbstractNativeEventFilter interface bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) Q_DECL_OVERRIDE; protected: // QHotkeyPrivate interface quint32 nativeKeycode(Qt::Key keycode, bool &ok) Q_DECL_OVERRIDE; quint32 nativeModifiers(Qt::KeyboardModifiers modifiers, bool &ok) Q_DECL_OVERRIDE; bool registerShortcut(QHotkey::NativeShortcut shortcut) Q_DECL_OVERRIDE; bool unregisterShortcut(QHotkey::NativeShortcut shortcut) Q_DECL_OVERRIDE; private: static const QVector<quint32> specialModifiers; static const quint32 validModsMask; static QString formatX11Error(Display *display, int errorCode); class HotkeyErrorHandler { public: HotkeyErrorHandler(); ~HotkeyErrorHandler(); static bool hasError; static QString errorString; private: XErrorHandler prevHandler; static int handleError(Display *display, XErrorEvent *error); }; }; NATIVE_INSTANCE(QHotkeyPrivateX11) const QVector<quint32> QHotkeyPrivateX11::specialModifiers = {0, Mod2Mask, LockMask, (Mod2Mask | LockMask)}; const quint32 QHotkeyPrivateX11::validModsMask = ShiftMask | ControlMask | Mod1Mask | Mod4Mask; bool QHotkeyPrivateX11::nativeEventFilter(const QByteArray &eventType, void *message, long *result) { Q_UNUSED(eventType); Q_UNUSED(result); xcb_generic_event_t *genericEvent = static_cast<xcb_generic_event_t *>(message); if (genericEvent->response_type == XCB_KEY_PRESS) { xcb_key_press_event_t *keyEvent = static_cast<xcb_key_press_event_t *>(message); this->activateShortcut({keyEvent->detail, keyEvent->state & QHotkeyPrivateX11::validModsMask}); } return false; } quint32 QHotkeyPrivateX11::nativeKeycode(Qt::Key keycode, bool &ok) { KeySym keysym = XStringToKeysym(QKeySequence(keycode).toString(QKeySequence::NativeText).toLatin1().constData()); if (keysym == NoSymbol) { //not found -> just use the key if(keycode <= 0xFFFF) keysym = keycode; else return 0; } Display *display = QX11Info::display(); if(display) { auto res = XKeysymToKeycode(QX11Info::display(), keysym); if(res != 0) ok = true; return res; } else return 0; } quint32 QHotkeyPrivateX11::nativeModifiers(Qt::KeyboardModifiers modifiers, bool &ok) { quint32 nMods = 0; if (modifiers & Qt::ShiftModifier) nMods |= ShiftMask; if (modifiers & Qt::ControlModifier) nMods |= ControlMask; if (modifiers & Qt::AltModifier) nMods |= Mod1Mask; if (modifiers & Qt::MetaModifier) nMods |= Mod4Mask; ok = true; return nMods; } bool QHotkeyPrivateX11::registerShortcut(QHotkey::NativeShortcut shortcut) { Display *display = QX11Info::display(); if(!display) return false; HotkeyErrorHandler errorHandler; for(quint32 specialMod : QHotkeyPrivateX11::specialModifiers) { XGrabKey(display, shortcut.key, shortcut.modifier | specialMod, DefaultRootWindow(display), True, GrabModeAsync, GrabModeAsync); } XSync(display, False); if(errorHandler.hasError) { qCWarning(logQHotkey) << "Failed to register hotkey. Error:" << qPrintable(errorHandler.errorString); this->unregisterShortcut(shortcut); return false; } else return true; } bool QHotkeyPrivateX11::unregisterShortcut(QHotkey::NativeShortcut shortcut) { Display *display = QX11Info::display(); if(!display) return false; HotkeyErrorHandler errorHandler; for(quint32 specialMod : QHotkeyPrivateX11::specialModifiers) { XUngrabKey(display, shortcut.key, shortcut.modifier | specialMod, DefaultRootWindow(display)); } XSync(display, False); if(errorHandler.hasError) { qCWarning(logQHotkey) << "Failed to unregister hotkey. Error:" << qPrintable(errorHandler.errorString); return false; } else return true; } QString QHotkeyPrivateX11::formatX11Error(Display *display, int errorCode) { char errStr[256]; XGetErrorText(display, errorCode, errStr, 256); return QString::fromLatin1(errStr); } // ---------- QHotkeyPrivateX11::HotkeyErrorHandler implementation ---------- bool QHotkeyPrivateX11::HotkeyErrorHandler::hasError = false; QString QHotkeyPrivateX11::HotkeyErrorHandler::errorString; QHotkeyPrivateX11::HotkeyErrorHandler::HotkeyErrorHandler() { prevHandler = XSetErrorHandler(&HotkeyErrorHandler::handleError); } QHotkeyPrivateX11::HotkeyErrorHandler::~HotkeyErrorHandler() { XSetErrorHandler(prevHandler); hasError = false; errorString.clear(); } int QHotkeyPrivateX11::HotkeyErrorHandler::handleError(Display *display, XErrorEvent *error) { switch (error->error_code) { case BadAccess: case BadValue: case BadWindow: if (error->request_code == 33 || //grab key error->request_code == 34) {// ungrab key hasError = true; errorString = QHotkeyPrivateX11::formatX11Error(display, error->error_code); return 1; } Q_FALLTHROUGH(); // fall through default: return 0; } } <commit_msg>X11 Media Key Support<commit_after>#include "qhotkey.h" #include "qhotkey_p.h" #include <QDebug> #include <QX11Info> #include <QThreadStorage> #include <X11/Xlib.h> #include <xcb/xcb.h> //compability to pre Qt 5.8 #ifndef Q_FALLTHROUGH #define Q_FALLTHROUGH() (void)0 #endif class QHotkeyPrivateX11 : public QHotkeyPrivate { public: // QAbstractNativeEventFilter interface bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) Q_DECL_OVERRIDE; protected: // QHotkeyPrivate interface quint32 nativeKeycode(Qt::Key keycode, bool &ok) Q_DECL_OVERRIDE; quint32 nativeModifiers(Qt::KeyboardModifiers modifiers, bool &ok) Q_DECL_OVERRIDE; QString getX11String(Qt::Key keycode); bool registerShortcut(QHotkey::NativeShortcut shortcut) Q_DECL_OVERRIDE; bool unregisterShortcut(QHotkey::NativeShortcut shortcut) Q_DECL_OVERRIDE; private: static const QVector<quint32> specialModifiers; static const quint32 validModsMask; static QString formatX11Error(Display *display, int errorCode); class HotkeyErrorHandler { public: HotkeyErrorHandler(); ~HotkeyErrorHandler(); static bool hasError; static QString errorString; private: XErrorHandler prevHandler; static int handleError(Display *display, XErrorEvent *error); }; }; NATIVE_INSTANCE(QHotkeyPrivateX11) const QVector<quint32> QHotkeyPrivateX11::specialModifiers = {0, Mod2Mask, LockMask, (Mod2Mask | LockMask)}; const quint32 QHotkeyPrivateX11::validModsMask = ShiftMask | ControlMask | Mod1Mask | Mod4Mask; bool QHotkeyPrivateX11::nativeEventFilter(const QByteArray &eventType, void *message, long *result) { Q_UNUSED(eventType); Q_UNUSED(result); xcb_generic_event_t *genericEvent = static_cast<xcb_generic_event_t *>(message); if (genericEvent->response_type == XCB_KEY_PRESS) { xcb_key_press_event_t *keyEvent = static_cast<xcb_key_press_event_t *>(message); this->activateShortcut({keyEvent->detail, keyEvent->state & QHotkeyPrivateX11::validModsMask}); } return false; } QString QHotkeyPrivateX11::getX11String(Qt::Key keycode) { switch(keycode){ case Qt::Key_MediaLast : case Qt::Key_MediaPrevious : return "XF86AudioPrev"; case Qt::Key_MediaNext : return "XF86AudioNext"; case Qt::Key_MediaPause : case Qt::Key_MediaPlay : case Qt::Key_MediaTogglePlayPause : return "XF86AudioPlay"; case Qt::Key_MediaRecord : return "XF86AudioRecord"; case Qt::Key_MediaStop : return "XF86AudioStop"; default : return QKeySequence(keycode).toString(QKeySequence::NativeText); } } quint32 QHotkeyPrivateX11::nativeKeycode(Qt::Key keycode, bool &ok) { QString keyString = getX11String(keycode); KeySym keysym = XStringToKeysym(keyString.toLatin1().constData()); if (keysym == NoSymbol) { //not found -> just use the key if(keycode <= 0xFFFF) keysym = keycode; else return 0; } Display *display = QX11Info::display(); if(display) { auto res = XKeysymToKeycode(QX11Info::display(), keysym); if(res != 0) ok = true; return res; } else return 0; } quint32 QHotkeyPrivateX11::nativeModifiers(Qt::KeyboardModifiers modifiers, bool &ok) { quint32 nMods = 0; if (modifiers & Qt::ShiftModifier) nMods |= ShiftMask; if (modifiers & Qt::ControlModifier) nMods |= ControlMask; if (modifiers & Qt::AltModifier) nMods |= Mod1Mask; if (modifiers & Qt::MetaModifier) nMods |= Mod4Mask; ok = true; return nMods; } bool QHotkeyPrivateX11::registerShortcut(QHotkey::NativeShortcut shortcut) { Display *display = QX11Info::display(); if(!display) return false; HotkeyErrorHandler errorHandler; for(quint32 specialMod : QHotkeyPrivateX11::specialModifiers) { XGrabKey(display, shortcut.key, shortcut.modifier | specialMod, DefaultRootWindow(display), True, GrabModeAsync, GrabModeAsync); } XSync(display, False); if(errorHandler.hasError) { qCWarning(logQHotkey) << "Failed to register hotkey. Error:" << qPrintable(errorHandler.errorString); this->unregisterShortcut(shortcut); return false; } else return true; } bool QHotkeyPrivateX11::unregisterShortcut(QHotkey::NativeShortcut shortcut) { Display *display = QX11Info::display(); if(!display) return false; HotkeyErrorHandler errorHandler; for(quint32 specialMod : QHotkeyPrivateX11::specialModifiers) { XUngrabKey(display, shortcut.key, shortcut.modifier | specialMod, DefaultRootWindow(display)); } XSync(display, False); if(errorHandler.hasError) { qCWarning(logQHotkey) << "Failed to unregister hotkey. Error:" << qPrintable(errorHandler.errorString); return false; } else return true; } QString QHotkeyPrivateX11::formatX11Error(Display *display, int errorCode) { char errStr[256]; XGetErrorText(display, errorCode, errStr, 256); return QString::fromLatin1(errStr); } // ---------- QHotkeyPrivateX11::HotkeyErrorHandler implementation ---------- bool QHotkeyPrivateX11::HotkeyErrorHandler::hasError = false; QString QHotkeyPrivateX11::HotkeyErrorHandler::errorString; QHotkeyPrivateX11::HotkeyErrorHandler::HotkeyErrorHandler() { prevHandler = XSetErrorHandler(&HotkeyErrorHandler::handleError); } QHotkeyPrivateX11::HotkeyErrorHandler::~HotkeyErrorHandler() { XSetErrorHandler(prevHandler); hasError = false; errorString.clear(); } int QHotkeyPrivateX11::HotkeyErrorHandler::handleError(Display *display, XErrorEvent *error) { switch (error->error_code) { case BadAccess: case BadValue: case BadWindow: if (error->request_code == 33 || //grab key error->request_code == 34) {// ungrab key hasError = true; errorString = QHotkeyPrivateX11::formatX11Error(display, error->error_code); return 1; } Q_FALLTHROUGH(); // fall through default: return 0; } } <|endoftext|>
<commit_before>#include "qhotkey.h" #include "qhotkey_p.h" #include <QDebug> #include <QX11Info> #include <QThreadStorage> #include <QTimer> #include <X11/Xlib.h> #include <xcb/xcb.h> //compability to pre Qt 5.8 #ifndef Q_FALLTHROUGH #define Q_FALLTHROUGH() (void)0 #endif class QHotkeyPrivateX11 : public QHotkeyPrivate { public: // QAbstractNativeEventFilter interface bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) Q_DECL_OVERRIDE; protected: // QHotkeyPrivate interface quint32 nativeKeycode(Qt::Key keycode, bool &ok) Q_DECL_OVERRIDE; quint32 nativeModifiers(Qt::KeyboardModifiers modifiers, bool &ok) Q_DECL_OVERRIDE; QString getX11String(Qt::Key keycode); bool registerShortcut(QHotkey::NativeShortcut shortcut) Q_DECL_OVERRIDE; bool unregisterShortcut(QHotkey::NativeShortcut shortcut) Q_DECL_OVERRIDE; private: static const QVector<quint32> specialModifiers; static const quint32 validModsMask; QTimer *releaseTimer = nullptr; xcb_key_press_event_t prevHandledEvent; xcb_key_press_event_t prevEvent; static QString formatX11Error(Display *display, int errorCode); class HotkeyErrorHandler { public: HotkeyErrorHandler(); ~HotkeyErrorHandler(); static bool hasError; static QString errorString; private: XErrorHandler prevHandler; static int handleError(Display *display, XErrorEvent *error); }; }; NATIVE_INSTANCE(QHotkeyPrivateX11) bool QHotkeyPrivate::isPlatformSupported() { return QX11Info::isPlatformX11(); } const QVector<quint32> QHotkeyPrivateX11::specialModifiers = {0, Mod2Mask, LockMask, (Mod2Mask | LockMask)}; const quint32 QHotkeyPrivateX11::validModsMask = ShiftMask | ControlMask | Mod1Mask | Mod4Mask; bool QHotkeyPrivateX11::nativeEventFilter(const QByteArray &eventType, void *message, long *result) { Q_UNUSED(eventType) Q_UNUSED(result) xcb_generic_event_t *genericEvent = static_cast<xcb_generic_event_t *>(message); if (genericEvent->response_type == XCB_KEY_PRESS) { xcb_key_press_event_t keyEvent = *static_cast<xcb_key_press_event_t *>(message); this->prevEvent = keyEvent; if (this->prevHandledEvent.response_type == XCB_KEY_RELEASE) { if(this->prevHandledEvent.time == keyEvent.time) return false; } this->activateShortcut({keyEvent.detail, keyEvent.state & QHotkeyPrivateX11::validModsMask}); } else if (genericEvent->response_type == XCB_KEY_RELEASE) { xcb_key_release_event_t keyEvent = *static_cast<xcb_key_release_event_t *>(message); this->prevEvent = keyEvent; QTimer *timer = new QTimer(this); timer->setSingleShot(true); timer->setInterval(50); connect(timer, &QTimer::timeout, this, [this, keyEvent, timer] { if(this->prevEvent.time == keyEvent.time && this->prevEvent.response_type == keyEvent.response_type && this->prevEvent.detail == keyEvent.detail){ this->releaseShortcut({keyEvent.detail, keyEvent.state & QHotkeyPrivateX11::validModsMask}); } delete timer; }); timer->start(); this->releaseTimer = timer; this->prevHandledEvent = keyEvent; } return false; } QString QHotkeyPrivateX11::getX11String(Qt::Key keycode) { switch(keycode){ case Qt::Key_MediaLast : case Qt::Key_MediaPrevious : return "XF86AudioPrev"; case Qt::Key_MediaNext : return "XF86AudioNext"; case Qt::Key_MediaPause : case Qt::Key_MediaPlay : case Qt::Key_MediaTogglePlayPause : return "XF86AudioPlay"; case Qt::Key_MediaRecord : return "XF86AudioRecord"; case Qt::Key_MediaStop : return "XF86AudioStop"; default : return QKeySequence(keycode).toString(QKeySequence::NativeText); } } quint32 QHotkeyPrivateX11::nativeKeycode(Qt::Key keycode, bool &ok) { QString keyString = getX11String(keycode); KeySym keysym = XStringToKeysym(keyString.toLatin1().constData()); if (keysym == NoSymbol) { //not found -> just use the key if(keycode <= 0xFFFF) keysym = keycode; else return 0; } if(QX11Info::isPlatformX11()) { auto res = XKeysymToKeycode(QX11Info::display(), keysym); if(res != 0) ok = true; return res; } else return 0; } quint32 QHotkeyPrivateX11::nativeModifiers(Qt::KeyboardModifiers modifiers, bool &ok) { quint32 nMods = 0; if (modifiers & Qt::ShiftModifier) nMods |= ShiftMask; if (modifiers & Qt::ControlModifier) nMods |= ControlMask; if (modifiers & Qt::AltModifier) nMods |= Mod1Mask; if (modifiers & Qt::MetaModifier) nMods |= Mod4Mask; ok = true; return nMods; } bool QHotkeyPrivateX11::registerShortcut(QHotkey::NativeShortcut shortcut) { Display *display = QX11Info::display(); if(!display) return false; HotkeyErrorHandler errorHandler; for(quint32 specialMod : QHotkeyPrivateX11::specialModifiers) { XGrabKey(display, shortcut.key, shortcut.modifier | specialMod, DefaultRootWindow(display), True, GrabModeAsync, GrabModeAsync); } XSync(display, False); if(errorHandler.hasError) { error = errorHandler.errorString; this->unregisterShortcut(shortcut); return false; } else return true; } bool QHotkeyPrivateX11::unregisterShortcut(QHotkey::NativeShortcut shortcut) { Display *display = QX11Info::display(); if(!display) return false; HotkeyErrorHandler errorHandler; for(quint32 specialMod : QHotkeyPrivateX11::specialModifiers) { XUngrabKey(display, shortcut.key, shortcut.modifier | specialMod, DefaultRootWindow(display)); } XSync(display, False); if(errorHandler.hasError) { error = errorHandler.errorString; return false; } else return true; } QString QHotkeyPrivateX11::formatX11Error(Display *display, int errorCode) { char errStr[256]; XGetErrorText(display, errorCode, errStr, 256); return QString::fromLatin1(errStr); } // ---------- QHotkeyPrivateX11::HotkeyErrorHandler implementation ---------- bool QHotkeyPrivateX11::HotkeyErrorHandler::hasError = false; QString QHotkeyPrivateX11::HotkeyErrorHandler::errorString; QHotkeyPrivateX11::HotkeyErrorHandler::HotkeyErrorHandler() { prevHandler = XSetErrorHandler(&HotkeyErrorHandler::handleError); } QHotkeyPrivateX11::HotkeyErrorHandler::~HotkeyErrorHandler() { XSetErrorHandler(prevHandler); hasError = false; errorString.clear(); } int QHotkeyPrivateX11::HotkeyErrorHandler::handleError(Display *display, XErrorEvent *error) { switch (error->error_code) { case BadAccess: case BadValue: case BadWindow: if (error->request_code == 33 || //grab key error->request_code == 34) {// ungrab key hasError = true; errorString = QHotkeyPrivateX11::formatX11Error(display, error->error_code); return 1; } Q_FALLTHROUGH(); // fall through default: return 0; } } <commit_msg>fix SIGSEGV on wayland<commit_after>#include "qhotkey.h" #include "qhotkey_p.h" #include <QDebug> #include <QX11Info> #include <QThreadStorage> #include <QTimer> #include <X11/Xlib.h> #include <xcb/xcb.h> //compability to pre Qt 5.8 #ifndef Q_FALLTHROUGH #define Q_FALLTHROUGH() (void)0 #endif class QHotkeyPrivateX11 : public QHotkeyPrivate { public: // QAbstractNativeEventFilter interface bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) Q_DECL_OVERRIDE; protected: // QHotkeyPrivate interface quint32 nativeKeycode(Qt::Key keycode, bool &ok) Q_DECL_OVERRIDE; quint32 nativeModifiers(Qt::KeyboardModifiers modifiers, bool &ok) Q_DECL_OVERRIDE; QString getX11String(Qt::Key keycode); bool registerShortcut(QHotkey::NativeShortcut shortcut) Q_DECL_OVERRIDE; bool unregisterShortcut(QHotkey::NativeShortcut shortcut) Q_DECL_OVERRIDE; private: static const QVector<quint32> specialModifiers; static const quint32 validModsMask; QTimer *releaseTimer = nullptr; xcb_key_press_event_t prevHandledEvent; xcb_key_press_event_t prevEvent; static QString formatX11Error(Display *display, int errorCode); class HotkeyErrorHandler { public: HotkeyErrorHandler(); ~HotkeyErrorHandler(); static bool hasError; static QString errorString; private: XErrorHandler prevHandler; static int handleError(Display *display, XErrorEvent *error); }; }; NATIVE_INSTANCE(QHotkeyPrivateX11) bool QHotkeyPrivate::isPlatformSupported() { return QX11Info::isPlatformX11(); } const QVector<quint32> QHotkeyPrivateX11::specialModifiers = {0, Mod2Mask, LockMask, (Mod2Mask | LockMask)}; const quint32 QHotkeyPrivateX11::validModsMask = ShiftMask | ControlMask | Mod1Mask | Mod4Mask; bool QHotkeyPrivateX11::nativeEventFilter(const QByteArray &eventType, void *message, long *result) { Q_UNUSED(eventType) Q_UNUSED(result) xcb_generic_event_t *genericEvent = static_cast<xcb_generic_event_t *>(message); if (genericEvent->response_type == XCB_KEY_PRESS) { xcb_key_press_event_t keyEvent = *static_cast<xcb_key_press_event_t *>(message); this->prevEvent = keyEvent; if (this->prevHandledEvent.response_type == XCB_KEY_RELEASE) { if(this->prevHandledEvent.time == keyEvent.time) return false; } this->activateShortcut({keyEvent.detail, keyEvent.state & QHotkeyPrivateX11::validModsMask}); } else if (genericEvent->response_type == XCB_KEY_RELEASE) { xcb_key_release_event_t keyEvent = *static_cast<xcb_key_release_event_t *>(message); this->prevEvent = keyEvent; QTimer *timer = new QTimer(this); timer->setSingleShot(true); timer->setInterval(50); connect(timer, &QTimer::timeout, this, [this, keyEvent, timer] { if(this->prevEvent.time == keyEvent.time && this->prevEvent.response_type == keyEvent.response_type && this->prevEvent.detail == keyEvent.detail){ this->releaseShortcut({keyEvent.detail, keyEvent.state & QHotkeyPrivateX11::validModsMask}); } delete timer; }); timer->start(); this->releaseTimer = timer; this->prevHandledEvent = keyEvent; } return false; } QString QHotkeyPrivateX11::getX11String(Qt::Key keycode) { switch(keycode){ case Qt::Key_MediaLast : case Qt::Key_MediaPrevious : return "XF86AudioPrev"; case Qt::Key_MediaNext : return "XF86AudioNext"; case Qt::Key_MediaPause : case Qt::Key_MediaPlay : case Qt::Key_MediaTogglePlayPause : return "XF86AudioPlay"; case Qt::Key_MediaRecord : return "XF86AudioRecord"; case Qt::Key_MediaStop : return "XF86AudioStop"; default : return QKeySequence(keycode).toString(QKeySequence::NativeText); } } quint32 QHotkeyPrivateX11::nativeKeycode(Qt::Key keycode, bool &ok) { QString keyString = getX11String(keycode); KeySym keysym = XStringToKeysym(keyString.toLatin1().constData()); if (keysym == NoSymbol) { //not found -> just use the key if(keycode <= 0xFFFF) keysym = keycode; else return 0; } if(QX11Info::isPlatformX11()) { auto res = XKeysymToKeycode(QX11Info::display(), keysym); if(res != 0) ok = true; return res; } else return 0; } quint32 QHotkeyPrivateX11::nativeModifiers(Qt::KeyboardModifiers modifiers, bool &ok) { quint32 nMods = 0; if (modifiers & Qt::ShiftModifier) nMods |= ShiftMask; if (modifiers & Qt::ControlModifier) nMods |= ControlMask; if (modifiers & Qt::AltModifier) nMods |= Mod1Mask; if (modifiers & Qt::MetaModifier) nMods |= Mod4Mask; ok = true; return nMods; } bool QHotkeyPrivateX11::registerShortcut(QHotkey::NativeShortcut shortcut) { Display *display = QX11Info::display(); if(!display || !QX11Info::isPlatformX11()) return false; HotkeyErrorHandler errorHandler; for(quint32 specialMod : QHotkeyPrivateX11::specialModifiers) { XGrabKey(display, shortcut.key, shortcut.modifier | specialMod, DefaultRootWindow(display), True, GrabModeAsync, GrabModeAsync); } XSync(display, False); if(errorHandler.hasError) { error = errorHandler.errorString; this->unregisterShortcut(shortcut); return false; } else return true; } bool QHotkeyPrivateX11::unregisterShortcut(QHotkey::NativeShortcut shortcut) { Display *display = QX11Info::display(); if(!display) return false; HotkeyErrorHandler errorHandler; for(quint32 specialMod : QHotkeyPrivateX11::specialModifiers) { XUngrabKey(display, shortcut.key, shortcut.modifier | specialMod, DefaultRootWindow(display)); } XSync(display, False); if(errorHandler.hasError) { error = errorHandler.errorString; return false; } else return true; } QString QHotkeyPrivateX11::formatX11Error(Display *display, int errorCode) { char errStr[256]; XGetErrorText(display, errorCode, errStr, 256); return QString::fromLatin1(errStr); } // ---------- QHotkeyPrivateX11::HotkeyErrorHandler implementation ---------- bool QHotkeyPrivateX11::HotkeyErrorHandler::hasError = false; QString QHotkeyPrivateX11::HotkeyErrorHandler::errorString; QHotkeyPrivateX11::HotkeyErrorHandler::HotkeyErrorHandler() { prevHandler = XSetErrorHandler(&HotkeyErrorHandler::handleError); } QHotkeyPrivateX11::HotkeyErrorHandler::~HotkeyErrorHandler() { XSetErrorHandler(prevHandler); hasError = false; errorString.clear(); } int QHotkeyPrivateX11::HotkeyErrorHandler::handleError(Display *display, XErrorEvent *error) { switch (error->error_code) { case BadAccess: case BadValue: case BadWindow: if (error->request_code == 33 || //grab key error->request_code == 34) {// ungrab key hasError = true; errorString = QHotkeyPrivateX11::formatX11Error(display, error->error_code); return 1; } Q_FALLTHROUGH(); // fall through default: return 0; } } <|endoftext|>
<commit_before><commit_msg>comienzo read/write<commit_after><|endoftext|>
<commit_before>/** This source adapted from https://github.com/kmicklas/variadic-static_variant * * Copyright (C) 2013 Kenneth Micklas * * 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. * **/ #pragma once #include <stdexcept> #include <typeinfo> #include <fc/exception/exception.hpp> #include <boost/core/typeinfo.hpp> namespace fc { // Implementation details, the user should not import this: namespace impl { template<int N, typename... Ts> struct storage_ops; template<typename X, typename... Ts> struct position; template<int Pos, typename... Ts> struct type_at; template<typename... Ts> struct type_info; template<typename StaticVariant> struct copy_construct { typedef void result_type; StaticVariant& sv; copy_construct( StaticVariant& s ):sv(s){} template<typename T> void operator()( const T& v )const { sv.init(v); } }; template<typename StaticVariant> struct move_construct { typedef void result_type; StaticVariant& sv; move_construct( StaticVariant& s ):sv(s){} template<typename T> void operator()( T& v )const { sv.init( std::move(v) ); } }; template<int N, typename T, typename... Ts> struct storage_ops<N, T&, Ts...> { static void del(int n, void *data) {} static void con(int n, void *data) {} template<typename visitor> static typename visitor::result_type apply(int n, void *data, visitor& v) {} template<typename visitor> static typename visitor::result_type apply(int n, void *data, const visitor& v) {} template<typename visitor> static typename visitor::result_type apply(int n, const void *data, visitor& v) {} template<typename visitor> static typename visitor::result_type apply(int n, const void *data, const visitor& v) {} }; template<int N, typename T, typename... Ts> struct storage_ops<N, T, Ts...> { static void del(int n, void *data) { if(n == N) reinterpret_cast<T*>(data)->~T(); else storage_ops<N + 1, Ts...>::del(n, data); } static void con(int n, void *data) { if(n == N) new(reinterpret_cast<T*>(data)) T(); else storage_ops<N + 1, Ts...>::con(n, data); } template<typename visitor> static typename visitor::result_type apply(int n, void *data, visitor& v) { if(n == N) return v(*reinterpret_cast<T*>(data)); else return storage_ops<N + 1, Ts...>::apply(n, data, v); } template<typename visitor> static typename visitor::result_type apply(int n, void *data, const visitor& v) { if(n == N) return v(*reinterpret_cast<T*>(data)); else return storage_ops<N + 1, Ts...>::apply(n, data, v); } template<typename visitor> static typename visitor::result_type apply(int n, const void *data, visitor& v) { if(n == N) return v(*reinterpret_cast<const T*>(data)); else return storage_ops<N + 1, Ts...>::apply(n, data, v); } template<typename visitor> static typename visitor::result_type apply(int n, const void *data, const visitor& v) { if(n == N) return v(*reinterpret_cast<const T*>(data)); else return storage_ops<N + 1, Ts...>::apply(n, data, v); } }; template<int N> struct storage_ops<N> { static void del(int n, void *data) { FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid."); } static void con(int n, void *data) { FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." ); } template<typename visitor> static typename visitor::result_type apply(int n, void *data, visitor& v) { FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." ); } template<typename visitor> static typename visitor::result_type apply(int n, void *data, const visitor& v) { FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." ); } template<typename visitor> static typename visitor::result_type apply(int n, const void *data, visitor& v) { FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." ); } template<typename visitor> static typename visitor::result_type apply(int n, const void *data, const visitor& v) { FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." ); } }; template<typename X> struct position<X> { static const int pos = -1; }; template<typename X, typename... Ts> struct position<X, X, Ts...> { static const int pos = 0; }; template<typename X, typename T, typename... Ts> struct position<X, T, Ts...> { static const int pos = position<X, Ts...>::pos != -1 ? position<X, Ts...>::pos + 1 : -1; }; template<typename T, typename... Ts> struct type_at<0, T, Ts...> { using type = T; }; template<int Pos, typename T, typename... Ts> struct type_at<Pos, T, Ts...> { using type = typename type_at<Pos - 1, Ts...>::type; }; template<typename T, typename... Ts> struct type_info<T&, Ts...> { static const bool no_reference_types = false; static const bool no_duplicates = position<T, Ts...>::pos == -1 && type_info<Ts...>::no_duplicates; static const size_t size = type_info<Ts...>::size > sizeof(T&) ? type_info<Ts...>::size : sizeof(T&); static const size_t count = 1 + type_info<Ts...>::count; }; template<typename T, typename... Ts> struct type_info<T, Ts...> { static const bool no_reference_types = type_info<Ts...>::no_reference_types; static const bool no_duplicates = position<T, Ts...>::pos == -1 && type_info<Ts...>::no_duplicates; static const size_t size = type_info<Ts...>::size > sizeof(T) ? type_info<Ts...>::size : sizeof(T&); static const size_t count = 1 + type_info<Ts...>::count; }; template<> struct type_info<> { static const bool no_reference_types = true; static const bool no_duplicates = true; static const size_t count = 0; static const size_t size = 0; }; } // namespace impl template<typename... Types> class static_variant { static_assert(impl::type_info<Types...>::no_reference_types, "Reference types are not permitted in static_variant."); static_assert(impl::type_info<Types...>::no_duplicates, "static_variant type arguments contain duplicate types."); alignas(__int128) char storage[impl::type_info<Types...>::size]; int _tag; template<typename X> void init(const X& x) { _tag = impl::position<X, Types...>::pos; new(storage) X(x); } template<typename X> void init(X&& x) { _tag = impl::position<X, Types...>::pos; new(storage) X( std::move(x) ); } template<typename StaticVariant> friend struct impl::copy_construct; template<typename StaticVariant> friend struct impl::move_construct; public: template<typename X> struct tag { static_assert( impl::position<X, Types...>::pos != -1, "Type not in static_variant." ); static const int value = impl::position<X, Types...>::pos; }; static_variant() { _tag = 0; impl::storage_ops<0, Types...>::con(0, storage); } template<typename... Other> static_variant( const static_variant<Other...>& cpy ) { cpy.visit( impl::copy_construct<static_variant>(*this) ); } static_variant( const static_variant& cpy ) { cpy.visit( impl::copy_construct<static_variant>(*this) ); } static_variant( static_variant&& mv ) { mv.visit( impl::move_construct<static_variant>(*this) ); } template<typename X> static_variant(const X& v) { static_assert( impl::position<X, Types...>::pos != -1, "Type not in static_variant." ); init(v); } ~static_variant() { impl::storage_ops<0, Types...>::del(_tag, storage); } template<typename X> static_variant& operator=(const X& v) { static_assert( impl::position<X, Types...>::pos != -1, "Type not in static_variant." ); this->~static_variant(); init(v); return *this; } static_variant& operator=( const static_variant& v ) { if( this == &v ) return *this; this->~static_variant(); v.visit( impl::copy_construct<static_variant>(*this) ); return *this; } static_variant& operator=( static_variant&& v ) { if( this == &v ) return *this; this->~static_variant(); v.visit( impl::move_construct<static_variant>(*this) ); return *this; } friend bool operator == ( const static_variant& a, const static_variant& b ) { return a.which() == b.which(); } friend bool operator < ( const static_variant& a, const static_variant& b ) { return a.which() < b.which(); } template<typename X> X& get() { static_assert( impl::position<X, Types...>::pos != -1, "Type not in static_variant." ); if(_tag == impl::position<X, Types...>::pos) { void* tmp(storage); return *reinterpret_cast<X*>(tmp); } else { FC_THROW_EXCEPTION( fc::assert_exception, "static_variant does not contain a value of type ${t}", ("t",fc::get_typename<X>::name()) ); // std::string("static_variant does not contain value of type ") + typeid(X).name() // ); } } template<typename X> const X& get() const { static_assert( impl::position<X, Types...>::pos != -1, "Type not in static_variant." ); if(_tag == impl::position<X, Types...>::pos) { const void* tmp(storage); return *reinterpret_cast<const X*>(tmp); } else { FC_THROW_EXCEPTION( fc::assert_exception, "static_variant does not contain a value of type ${t}", ("t",fc::get_typename<X>::name()) ); } } template<typename visitor> typename visitor::result_type visit(visitor& v) { return impl::storage_ops<0, Types...>::apply(_tag, storage, v); } template<typename visitor> typename visitor::result_type visit(const visitor& v) { return impl::storage_ops<0, Types...>::apply(_tag, storage, v); } template<typename visitor> typename visitor::result_type visit(visitor& v)const { return impl::storage_ops<0, Types...>::apply(_tag, storage, v); } template<typename visitor> typename visitor::result_type visit(const visitor& v)const { return impl::storage_ops<0, Types...>::apply(_tag, storage, v); } static int count() { return impl::type_info<Types...>::count; } void set_which( int w ) { FC_ASSERT( w < count() ); this->~static_variant(); _tag = w; impl::storage_ops<0, Types...>::con(_tag, storage); } int which() const {return _tag;} template<typename X> bool contains() const { return which() == tag<X>::value; } template<typename X> static constexpr int position() { return impl::position<X, Types...>::pos; } template<int Pos, std::enable_if_t<Pos < impl::type_info<Types...>::size,int> = 1> using type_at = typename impl::type_at<Pos, Types...>::type; }; template<typename Result> struct visitor { typedef Result result_type; }; struct from_static_variant { variant& var; from_static_variant( variant& dv ):var(dv){} typedef void result_type; template<typename T> void operator()( const T& v )const { to_variant( v, var ); } }; struct to_static_variant { const variant& var; to_static_variant( const variant& dv ):var(dv){} typedef void result_type; template<typename T> void operator()( T& v )const { from_variant( var, v ); } }; template<typename... T> void to_variant( const fc::static_variant<T...>& s, fc::variant& v ) { variant tmp; variants vars(2); vars[0] = s.which(); s.visit( from_static_variant(vars[1]) ); v = std::move(vars); } template<typename... T> void from_variant( const fc::variant& v, fc::static_variant<T...>& s ) { auto ar = v.get_array(); if( ar.size() < 2 ) return; s.set_which( ar[0].as_uint64() ); s.visit( to_static_variant(ar[1]) ); } template<typename... T> struct get_typename { static const char* name() { return BOOST_CORE_TYPEID(static_variant<T...>).name(); } }; } // namespace fc <commit_msg>more correct alignas #1853<commit_after>/** This source adapted from https://github.com/kmicklas/variadic-static_variant * * Copyright (C) 2013 Kenneth Micklas * * 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. * **/ #pragma once #include <stdexcept> #include <typeinfo> #include <fc/exception/exception.hpp> #include <boost/core/typeinfo.hpp> namespace fc { // Implementation details, the user should not import this: namespace impl { template<int N, typename... Ts> struct storage_ops; template<typename X, typename... Ts> struct position; template<int Pos, typename... Ts> struct type_at; template<typename... Ts> struct type_info; template<typename StaticVariant> struct copy_construct { typedef void result_type; StaticVariant& sv; copy_construct( StaticVariant& s ):sv(s){} template<typename T> void operator()( const T& v )const { sv.init(v); } }; template<typename StaticVariant> struct move_construct { typedef void result_type; StaticVariant& sv; move_construct( StaticVariant& s ):sv(s){} template<typename T> void operator()( T& v )const { sv.init( std::move(v) ); } }; template<int N, typename T, typename... Ts> struct storage_ops<N, T&, Ts...> { static void del(int n, void *data) {} static void con(int n, void *data) {} template<typename visitor> static typename visitor::result_type apply(int n, void *data, visitor& v) {} template<typename visitor> static typename visitor::result_type apply(int n, void *data, const visitor& v) {} template<typename visitor> static typename visitor::result_type apply(int n, const void *data, visitor& v) {} template<typename visitor> static typename visitor::result_type apply(int n, const void *data, const visitor& v) {} }; template<int N, typename T, typename... Ts> struct storage_ops<N, T, Ts...> { static void del(int n, void *data) { if(n == N) reinterpret_cast<T*>(data)->~T(); else storage_ops<N + 1, Ts...>::del(n, data); } static void con(int n, void *data) { if(n == N) new(reinterpret_cast<T*>(data)) T(); else storage_ops<N + 1, Ts...>::con(n, data); } template<typename visitor> static typename visitor::result_type apply(int n, void *data, visitor& v) { if(n == N) return v(*reinterpret_cast<T*>(data)); else return storage_ops<N + 1, Ts...>::apply(n, data, v); } template<typename visitor> static typename visitor::result_type apply(int n, void *data, const visitor& v) { if(n == N) return v(*reinterpret_cast<T*>(data)); else return storage_ops<N + 1, Ts...>::apply(n, data, v); } template<typename visitor> static typename visitor::result_type apply(int n, const void *data, visitor& v) { if(n == N) return v(*reinterpret_cast<const T*>(data)); else return storage_ops<N + 1, Ts...>::apply(n, data, v); } template<typename visitor> static typename visitor::result_type apply(int n, const void *data, const visitor& v) { if(n == N) return v(*reinterpret_cast<const T*>(data)); else return storage_ops<N + 1, Ts...>::apply(n, data, v); } }; template<int N> struct storage_ops<N> { static void del(int n, void *data) { FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid."); } static void con(int n, void *data) { FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." ); } template<typename visitor> static typename visitor::result_type apply(int n, void *data, visitor& v) { FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." ); } template<typename visitor> static typename visitor::result_type apply(int n, void *data, const visitor& v) { FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." ); } template<typename visitor> static typename visitor::result_type apply(int n, const void *data, visitor& v) { FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." ); } template<typename visitor> static typename visitor::result_type apply(int n, const void *data, const visitor& v) { FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." ); } }; template<typename X> struct position<X> { static const int pos = -1; }; template<typename X, typename... Ts> struct position<X, X, Ts...> { static const int pos = 0; }; template<typename X, typename T, typename... Ts> struct position<X, T, Ts...> { static const int pos = position<X, Ts...>::pos != -1 ? position<X, Ts...>::pos + 1 : -1; }; template<typename T, typename... Ts> struct type_at<0, T, Ts...> { using type = T; }; template<int Pos, typename T, typename... Ts> struct type_at<Pos, T, Ts...> { using type = typename type_at<Pos - 1, Ts...>::type; }; template<typename T, typename... Ts> struct type_info<T&, Ts...> { static const bool no_reference_types = false; static const bool no_duplicates = position<T, Ts...>::pos == -1 && type_info<Ts...>::no_duplicates; static const size_t size = type_info<Ts...>::size > sizeof(T&) ? type_info<Ts...>::size : sizeof(T&); static const size_t count = 1 + type_info<Ts...>::count; }; template<typename T, typename... Ts> struct type_info<T, Ts...> { static const bool no_reference_types = type_info<Ts...>::no_reference_types; static const bool no_duplicates = position<T, Ts...>::pos == -1 && type_info<Ts...>::no_duplicates; static const size_t size = type_info<Ts...>::size > sizeof(T) ? type_info<Ts...>::size : sizeof(T&); static const size_t count = 1 + type_info<Ts...>::count; }; template<> struct type_info<> { static const bool no_reference_types = true; static const bool no_duplicates = true; static const size_t count = 0; static const size_t size = 0; }; } // namespace impl template<typename... Types> class static_variant { static_assert(impl::type_info<Types...>::no_reference_types, "Reference types are not permitted in static_variant."); static_assert(impl::type_info<Types...>::no_duplicates, "static_variant type arguments contain duplicate types."); alignas(Types...) char storage[impl::type_info<Types...>::size]; int _tag; template<typename X> void init(const X& x) { _tag = impl::position<X, Types...>::pos; new(storage) X(x); } template<typename X> void init(X&& x) { _tag = impl::position<X, Types...>::pos; new(storage) X( std::move(x) ); } template<typename StaticVariant> friend struct impl::copy_construct; template<typename StaticVariant> friend struct impl::move_construct; public: template<typename X> struct tag { static_assert( impl::position<X, Types...>::pos != -1, "Type not in static_variant." ); static const int value = impl::position<X, Types...>::pos; }; static_variant() { _tag = 0; impl::storage_ops<0, Types...>::con(0, storage); } template<typename... Other> static_variant( const static_variant<Other...>& cpy ) { cpy.visit( impl::copy_construct<static_variant>(*this) ); } static_variant( const static_variant& cpy ) { cpy.visit( impl::copy_construct<static_variant>(*this) ); } static_variant( static_variant&& mv ) { mv.visit( impl::move_construct<static_variant>(*this) ); } template<typename X> static_variant(const X& v) { static_assert( impl::position<X, Types...>::pos != -1, "Type not in static_variant." ); init(v); } ~static_variant() { impl::storage_ops<0, Types...>::del(_tag, storage); } template<typename X> static_variant& operator=(const X& v) { static_assert( impl::position<X, Types...>::pos != -1, "Type not in static_variant." ); this->~static_variant(); init(v); return *this; } static_variant& operator=( const static_variant& v ) { if( this == &v ) return *this; this->~static_variant(); v.visit( impl::copy_construct<static_variant>(*this) ); return *this; } static_variant& operator=( static_variant&& v ) { if( this == &v ) return *this; this->~static_variant(); v.visit( impl::move_construct<static_variant>(*this) ); return *this; } friend bool operator == ( const static_variant& a, const static_variant& b ) { return a.which() == b.which(); } friend bool operator < ( const static_variant& a, const static_variant& b ) { return a.which() < b.which(); } template<typename X> X& get() { static_assert( impl::position<X, Types...>::pos != -1, "Type not in static_variant." ); if(_tag == impl::position<X, Types...>::pos) { void* tmp(storage); return *reinterpret_cast<X*>(tmp); } else { FC_THROW_EXCEPTION( fc::assert_exception, "static_variant does not contain a value of type ${t}", ("t",fc::get_typename<X>::name()) ); // std::string("static_variant does not contain value of type ") + typeid(X).name() // ); } } template<typename X> const X& get() const { static_assert( impl::position<X, Types...>::pos != -1, "Type not in static_variant." ); if(_tag == impl::position<X, Types...>::pos) { const void* tmp(storage); return *reinterpret_cast<const X*>(tmp); } else { FC_THROW_EXCEPTION( fc::assert_exception, "static_variant does not contain a value of type ${t}", ("t",fc::get_typename<X>::name()) ); } } template<typename visitor> typename visitor::result_type visit(visitor& v) { return impl::storage_ops<0, Types...>::apply(_tag, storage, v); } template<typename visitor> typename visitor::result_type visit(const visitor& v) { return impl::storage_ops<0, Types...>::apply(_tag, storage, v); } template<typename visitor> typename visitor::result_type visit(visitor& v)const { return impl::storage_ops<0, Types...>::apply(_tag, storage, v); } template<typename visitor> typename visitor::result_type visit(const visitor& v)const { return impl::storage_ops<0, Types...>::apply(_tag, storage, v); } static int count() { return impl::type_info<Types...>::count; } void set_which( int w ) { FC_ASSERT( w < count() ); this->~static_variant(); _tag = w; impl::storage_ops<0, Types...>::con(_tag, storage); } int which() const {return _tag;} template<typename X> bool contains() const { return which() == tag<X>::value; } template<typename X> static constexpr int position() { return impl::position<X, Types...>::pos; } template<int Pos, std::enable_if_t<Pos < impl::type_info<Types...>::size,int> = 1> using type_at = typename impl::type_at<Pos, Types...>::type; }; template<typename Result> struct visitor { typedef Result result_type; }; struct from_static_variant { variant& var; from_static_variant( variant& dv ):var(dv){} typedef void result_type; template<typename T> void operator()( const T& v )const { to_variant( v, var ); } }; struct to_static_variant { const variant& var; to_static_variant( const variant& dv ):var(dv){} typedef void result_type; template<typename T> void operator()( T& v )const { from_variant( var, v ); } }; template<typename... T> void to_variant( const fc::static_variant<T...>& s, fc::variant& v ) { variant tmp; variants vars(2); vars[0] = s.which(); s.visit( from_static_variant(vars[1]) ); v = std::move(vars); } template<typename... T> void from_variant( const fc::variant& v, fc::static_variant<T...>& s ) { auto ar = v.get_array(); if( ar.size() < 2 ) return; s.set_which( ar[0].as_uint64() ); s.visit( to_static_variant(ar[1]) ); } template<typename... T> struct get_typename { static const char* name() { return BOOST_CORE_TYPEID(static_variant<T...>).name(); } }; } // namespace fc <|endoftext|>
<commit_before>#include "StdAfx.h" #include "RawDecoder.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009 Klaus Post 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 http://www.klauspost.com */ namespace RawSpeed { RawDecoder::RawDecoder(FileMap* file) : mRaw(RawImage::create()), mFile(file) { decoderVersion = 0; } RawDecoder::~RawDecoder(void) { for (uint32 i = 0 ; i < errors.size(); i++) { free((void*)errors[i]); } errors.clear(); } void RawDecoder::decodeUncompressed(TiffIFD *rawIFD) { uint32 nslices = rawIFD->getEntry(STRIPOFFSETS)->count; const uint32 *offsets = rawIFD->getEntry(STRIPOFFSETS)->getIntArray(); const uint32 *counts = rawIFD->getEntry(STRIPBYTECOUNTS)->getIntArray(); uint32 yPerSlice = rawIFD->getEntry(ROWSPERSTRIP)->getInt(); uint32 width = rawIFD->getEntry(IMAGEWIDTH)->getInt(); uint32 height = rawIFD->getEntry(IMAGELENGTH)->getInt(); uint32 bitPerPixel = rawIFD->getEntry(BITSPERSAMPLE)->getInt(); vector<RawSlice> slices; uint32 offY = 0; for (uint32 s = 0; s < nslices; s++) { RawSlice slice; slice.offset = offsets[s]; slice.count = counts[s]; if (offY + yPerSlice > height) slice.h = height - offY; else slice.h = yPerSlice; offY += yPerSlice; if (mFile->isValid(slice.offset + slice.count)) // Only decode if size is valid slices.push_back(slice); } if (0 == slices.size()) ThrowRDE("RAW Decoder: No valid slices found. File probably truncated."); mRaw->dim = iPoint2D(width, offY); mRaw->bpp = 2; mRaw->createData(); mRaw->whitePoint = (1<<bitPerPixel)-1; offY = 0; for (uint32 i = 0; i < slices.size(); i++) { RawSlice slice = slices[i]; ByteStream in(mFile->getData(slice.offset), slice.count); iPoint2D size(width, slice.h); iPoint2D pos(0, offY); bitPerPixel = (int)((__int64)(slice.count * 8) / (slice.h * width)); try { readUncompressedRaw(in, size, pos, width*bitPerPixel / 8, bitPerPixel, true); } catch (RawDecoderException e) { if (i>0) errors.push_back(_strdup(e.what())); else throw; } catch (IOException e) { if (i>0) errors.push_back(_strdup(e.what())); else ThrowRDE("RAW decoder: IO error occurred in first slice, unable to decode more. Error is: %s", e.what()); } offY += slice.h; } } void RawDecoder::readUncompressedRaw(ByteStream &input, iPoint2D& size, iPoint2D& offset, int inputPitch, int bitPerPixel, bool MSBOrder) { uchar8* data = mRaw->getData(); uint32 outPitch = mRaw->pitch; uint32 w = size.x; uint32 h = size.y; uint32 cpp = mRaw->getCpp(); if (input.getRemainSize() < (inputPitch*h)) { if ((int)input.getRemainSize() > inputPitch) h = input.getRemainSize() / inputPitch - 1; else ThrowIOE("readUncompressedRaw: Not enough data to decode a single line. Image file truncated."); } if (bitPerPixel > 16) ThrowRDE("readUncompressedRaw: Unsupported bit depth"); uint32 skipBits = inputPitch - w * bitPerPixel / 8; // Skip per line if (offset.y > mRaw->dim.y) ThrowRDE("readUncompressedRaw: Invalid y offset"); if (offset.x + size.x > mRaw->dim.x) ThrowRDE("readUncompressedRaw: Invalid x offset"); uint32 y = offset.y; h = MIN(h + (uint32)offset.y, (uint32)mRaw->dim.y); if (MSBOrder) { BitPumpMSB bits(&input); w *= cpp; for (; y < h; y++) { ushort16* dest = (ushort16*) & data[offset.x*sizeof(ushort16)*cpp+y*outPitch]; bits.checkPos(); for (uint32 x = 0 ; x < w; x++) { uint32 b = bits.getBits(bitPerPixel); dest[x] = b; } bits.skipBits(skipBits); } } else { if (bitPerPixel == 16 && getHostEndianness() == little) { BitBlt(&data[offset.x*sizeof(ushort16)*cpp+y*outPitch], outPitch, input.getData(), inputPitch, w*mRaw->bpp, h - y); return; } if (bitPerPixel == 12 && (int)w == inputPitch * 8 / 12 && getHostEndianness() == little) { Decode12BitRaw(input, w, h); return; } BitPumpPlain bits(&input); w *= cpp; for (; y < h; y++) { ushort16* dest = (ushort16*) & data[offset.x*sizeof(ushort16)+y*outPitch]; bits.checkPos(); for (uint32 x = 0 ; x < w; x++) { uint32 b = bits.getBits(bitPerPixel); dest[x] = b; } bits.skipBits(skipBits); } } } void RawDecoder::Decode12BitRaw(ByteStream &input, uint32 w, uint32 h) { uchar8* data = mRaw->getData(); uint32 pitch = mRaw->pitch; const uchar8 *in = input.getData(); if (input.getRemainSize() < ((w*12/8)*h)) { if ((uint32)input.getRemainSize() > (w*12/8)) h = input.getRemainSize() / (w*12/8) - 1; else ThrowIOE("readUncompressedRaw: Not enough data to decode a single line. Image file truncated."); } for (uint32 y = 0; y < h; y++) { ushort16* dest = (ushort16*) & data[y*pitch]; for (uint32 x = 0 ; x < w; x += 2) { uint32 g1 = *in++; uint32 g2 = *in++; dest[x] = g1 | ((g2 & 0xf) << 8); uint32 g3 = *in++; dest[x+1] = (g2 >> 4) | (g3 << 4); } } } void RawDecoder::checkCameraSupported(CameraMetaData *meta, string make, string model, string mode) { TrimSpaces(make); TrimSpaces(model); Camera* cam = meta->getCamera(make, model, mode); if (!cam) { if (mode.length() == 0) printf("Unable to find camera in database: %s %s %s\n", make.c_str(), model.c_str(), mode.c_str()); return; // Assume true. } if (!cam->supported) ThrowRDE("Camera not supported (explicit). Sorry."); if (cam->decoderVersion > decoderVersion) ThrowRDE("Camera not supported in this version. Update RawSpeed for support."); hints = cam->hints; } void RawDecoder::setMetaData(CameraMetaData *meta, string make, string model, string mode) { TrimSpaces(make); TrimSpaces(model); Camera *cam = meta->getCamera(make, model, mode); if (!cam) { printf("Unable to find camera in database: %s %s %s\nPlease upload file to ftp.rawstudio.org, thanks!\n", make.c_str(), model.c_str(), mode.c_str()); return; } iPoint2D new_size = cam->cropSize; // If crop size is negative, use relative cropping if (new_size.x <= 0) new_size.x = mRaw->dim.x - cam->cropPos.x + new_size.x; if (new_size.y <= 0) new_size.y = mRaw->dim.y - cam->cropPos.y + new_size.y; mRaw->subFrame(cam->cropPos, new_size); mRaw->cfa = cam->cfa; // Shift CFA to match crop if (cam->cropPos.x & 1) mRaw->cfa.shiftLeft(); if (cam->cropPos.y & 1) mRaw->cfa.shiftDown(); mRaw->blackLevel = cam->black; mRaw->whitePoint = cam->white; } void RawDecoder::TrimSpaces(string& str) { // Trim Both leading and trailing spaces size_t startpos = str.find_first_not_of(" \t"); // Find the first character position after excluding leading blank spaces size_t endpos = str.find_last_not_of(" \t"); // Find the first character position from reverse af // if all spaces or empty return an empty string if ((string::npos == startpos) || (string::npos == endpos)) { str = ""; } else str = str.substr(startpos, endpos - startpos + 1); } void *RawDecoderDecodeThread(void *_this) { RawDecoderThread* me = (RawDecoderThread*)_this; try { me->parent->decodeThreaded(me); } catch (RawDecoderException ex) { me->error = _strdup(ex.what()); } catch (IOException ex) { me->error = _strdup(ex.what()); } pthread_exit(NULL); return 0; } void RawDecoder::startThreads() { uint32 threads; threads = getThreadCount(); int y_offset = 0; int y_per_thread = (mRaw->dim.y + threads - 1) / threads; RawDecoderThread *t = new RawDecoderThread[threads]; pthread_attr_t attr; /* Initialize and set thread detached attribute */ pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (uint32 i = 0; i < threads; i++) { t[i].start_y = y_offset; t[i].end_y = MIN(y_offset + y_per_thread, mRaw->dim.y); t[i].parent = this; pthread_create(&t[i].threadid, &attr, RawDecoderDecodeThread, &t[i]); y_offset = t[i].end_y; } void *status; for (uint32 i = 0; i < threads; i++) { pthread_join(t[i].threadid, &status); if (t[i].error) { errors.push_back(t[i].error); } } if (errors.size() >= threads) ThrowRDE("RawDecoder::startThreads: All threads reported errors. Cannot load image."); delete[] t; } void RawDecoder::decodeThreaded(RawDecoderThread * t) { ThrowRDE("Internal Error: This class does not support threaded decoding"); } } // namespace RawSpeed<commit_msg>Use our own type for 64 bit int.<commit_after>#include "StdAfx.h" #include "RawDecoder.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009 Klaus Post 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 http://www.klauspost.com */ namespace RawSpeed { RawDecoder::RawDecoder(FileMap* file) : mRaw(RawImage::create()), mFile(file) { decoderVersion = 0; } RawDecoder::~RawDecoder(void) { for (uint32 i = 0 ; i < errors.size(); i++) { free((void*)errors[i]); } errors.clear(); } void RawDecoder::decodeUncompressed(TiffIFD *rawIFD) { uint32 nslices = rawIFD->getEntry(STRIPOFFSETS)->count; const uint32 *offsets = rawIFD->getEntry(STRIPOFFSETS)->getIntArray(); const uint32 *counts = rawIFD->getEntry(STRIPBYTECOUNTS)->getIntArray(); uint32 yPerSlice = rawIFD->getEntry(ROWSPERSTRIP)->getInt(); uint32 width = rawIFD->getEntry(IMAGEWIDTH)->getInt(); uint32 height = rawIFD->getEntry(IMAGELENGTH)->getInt(); uint32 bitPerPixel = rawIFD->getEntry(BITSPERSAMPLE)->getInt(); vector<RawSlice> slices; uint32 offY = 0; for (uint32 s = 0; s < nslices; s++) { RawSlice slice; slice.offset = offsets[s]; slice.count = counts[s]; if (offY + yPerSlice > height) slice.h = height - offY; else slice.h = yPerSlice; offY += yPerSlice; if (mFile->isValid(slice.offset + slice.count)) // Only decode if size is valid slices.push_back(slice); } if (0 == slices.size()) ThrowRDE("RAW Decoder: No valid slices found. File probably truncated."); mRaw->dim = iPoint2D(width, offY); mRaw->bpp = 2; mRaw->createData(); mRaw->whitePoint = (1<<bitPerPixel)-1; offY = 0; for (uint32 i = 0; i < slices.size(); i++) { RawSlice slice = slices[i]; ByteStream in(mFile->getData(slice.offset), slice.count); iPoint2D size(width, slice.h); iPoint2D pos(0, offY); bitPerPixel = (int)((uint64)(slice.count * 8) / (slice.h * width)); try { readUncompressedRaw(in, size, pos, width*bitPerPixel / 8, bitPerPixel, true); } catch (RawDecoderException e) { if (i>0) errors.push_back(_strdup(e.what())); else throw; } catch (IOException e) { if (i>0) errors.push_back(_strdup(e.what())); else ThrowRDE("RAW decoder: IO error occurred in first slice, unable to decode more. Error is: %s", e.what()); } offY += slice.h; } } void RawDecoder::readUncompressedRaw(ByteStream &input, iPoint2D& size, iPoint2D& offset, int inputPitch, int bitPerPixel, bool MSBOrder) { uchar8* data = mRaw->getData(); uint32 outPitch = mRaw->pitch; uint32 w = size.x; uint32 h = size.y; uint32 cpp = mRaw->getCpp(); if (input.getRemainSize() < (inputPitch*h)) { if ((int)input.getRemainSize() > inputPitch) h = input.getRemainSize() / inputPitch - 1; else ThrowIOE("readUncompressedRaw: Not enough data to decode a single line. Image file truncated."); } if (bitPerPixel > 16) ThrowRDE("readUncompressedRaw: Unsupported bit depth"); uint32 skipBits = inputPitch - w * bitPerPixel / 8; // Skip per line if (offset.y > mRaw->dim.y) ThrowRDE("readUncompressedRaw: Invalid y offset"); if (offset.x + size.x > mRaw->dim.x) ThrowRDE("readUncompressedRaw: Invalid x offset"); uint32 y = offset.y; h = MIN(h + (uint32)offset.y, (uint32)mRaw->dim.y); if (MSBOrder) { BitPumpMSB bits(&input); w *= cpp; for (; y < h; y++) { ushort16* dest = (ushort16*) & data[offset.x*sizeof(ushort16)*cpp+y*outPitch]; bits.checkPos(); for (uint32 x = 0 ; x < w; x++) { uint32 b = bits.getBits(bitPerPixel); dest[x] = b; } bits.skipBits(skipBits); } } else { if (bitPerPixel == 16 && getHostEndianness() == little) { BitBlt(&data[offset.x*sizeof(ushort16)*cpp+y*outPitch], outPitch, input.getData(), inputPitch, w*mRaw->bpp, h - y); return; } if (bitPerPixel == 12 && (int)w == inputPitch * 8 / 12 && getHostEndianness() == little) { Decode12BitRaw(input, w, h); return; } BitPumpPlain bits(&input); w *= cpp; for (; y < h; y++) { ushort16* dest = (ushort16*) & data[offset.x*sizeof(ushort16)+y*outPitch]; bits.checkPos(); for (uint32 x = 0 ; x < w; x++) { uint32 b = bits.getBits(bitPerPixel); dest[x] = b; } bits.skipBits(skipBits); } } } void RawDecoder::Decode12BitRaw(ByteStream &input, uint32 w, uint32 h) { uchar8* data = mRaw->getData(); uint32 pitch = mRaw->pitch; const uchar8 *in = input.getData(); if (input.getRemainSize() < ((w*12/8)*h)) { if ((uint32)input.getRemainSize() > (w*12/8)) h = input.getRemainSize() / (w*12/8) - 1; else ThrowIOE("readUncompressedRaw: Not enough data to decode a single line. Image file truncated."); } for (uint32 y = 0; y < h; y++) { ushort16* dest = (ushort16*) & data[y*pitch]; for (uint32 x = 0 ; x < w; x += 2) { uint32 g1 = *in++; uint32 g2 = *in++; dest[x] = g1 | ((g2 & 0xf) << 8); uint32 g3 = *in++; dest[x+1] = (g2 >> 4) | (g3 << 4); } } } void RawDecoder::checkCameraSupported(CameraMetaData *meta, string make, string model, string mode) { TrimSpaces(make); TrimSpaces(model); Camera* cam = meta->getCamera(make, model, mode); if (!cam) { if (mode.length() == 0) printf("Unable to find camera in database: %s %s %s\n", make.c_str(), model.c_str(), mode.c_str()); return; // Assume true. } if (!cam->supported) ThrowRDE("Camera not supported (explicit). Sorry."); if (cam->decoderVersion > decoderVersion) ThrowRDE("Camera not supported in this version. Update RawSpeed for support."); hints = cam->hints; } void RawDecoder::setMetaData(CameraMetaData *meta, string make, string model, string mode) { TrimSpaces(make); TrimSpaces(model); Camera *cam = meta->getCamera(make, model, mode); if (!cam) { printf("Unable to find camera in database: %s %s %s\nPlease upload file to ftp.rawstudio.org, thanks!\n", make.c_str(), model.c_str(), mode.c_str()); return; } iPoint2D new_size = cam->cropSize; // If crop size is negative, use relative cropping if (new_size.x <= 0) new_size.x = mRaw->dim.x - cam->cropPos.x + new_size.x; if (new_size.y <= 0) new_size.y = mRaw->dim.y - cam->cropPos.y + new_size.y; mRaw->subFrame(cam->cropPos, new_size); mRaw->cfa = cam->cfa; // Shift CFA to match crop if (cam->cropPos.x & 1) mRaw->cfa.shiftLeft(); if (cam->cropPos.y & 1) mRaw->cfa.shiftDown(); mRaw->blackLevel = cam->black; mRaw->whitePoint = cam->white; } void RawDecoder::TrimSpaces(string& str) { // Trim Both leading and trailing spaces size_t startpos = str.find_first_not_of(" \t"); // Find the first character position after excluding leading blank spaces size_t endpos = str.find_last_not_of(" \t"); // Find the first character position from reverse af // if all spaces or empty return an empty string if ((string::npos == startpos) || (string::npos == endpos)) { str = ""; } else str = str.substr(startpos, endpos - startpos + 1); } void *RawDecoderDecodeThread(void *_this) { RawDecoderThread* me = (RawDecoderThread*)_this; try { me->parent->decodeThreaded(me); } catch (RawDecoderException ex) { me->error = _strdup(ex.what()); } catch (IOException ex) { me->error = _strdup(ex.what()); } pthread_exit(NULL); return 0; } void RawDecoder::startThreads() { uint32 threads; threads = getThreadCount(); int y_offset = 0; int y_per_thread = (mRaw->dim.y + threads - 1) / threads; RawDecoderThread *t = new RawDecoderThread[threads]; pthread_attr_t attr; /* Initialize and set thread detached attribute */ pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (uint32 i = 0; i < threads; i++) { t[i].start_y = y_offset; t[i].end_y = MIN(y_offset + y_per_thread, mRaw->dim.y); t[i].parent = this; pthread_create(&t[i].threadid, &attr, RawDecoderDecodeThread, &t[i]); y_offset = t[i].end_y; } void *status; for (uint32 i = 0; i < threads; i++) { pthread_join(t[i].threadid, &status); if (t[i].error) { errors.push_back(t[i].error); } } if (errors.size() >= threads) ThrowRDE("RawDecoder::startThreads: All threads reported errors. Cannot load image."); delete[] t; } void RawDecoder::decodeThreaded(RawDecoderThread * t) { ThrowRDE("Internal Error: This class does not support threaded decoding"); } } // namespace RawSpeed<|endoftext|>
<commit_before> #include <layout/form_layout.h> #include <layout/box_layout.h> #include <gui/application.h> #include <gui/cocoa_style.h> namespace { //////////////////////////////////////// void build_form_window( const std::shared_ptr<gui::window> &win ) { using layout::form_layout; gui::builder builder( win ); auto layout = builder.new_layout<form_layout>( layout::direction::RIGHT ); layout->set_pad( 12.0, 12.0, 12.0, 12.0 ); layout->set_spacing( 12.0, 12.0 ); auto row = layout->new_row(); builder.make_label( row.first, "Hello World" ); builder.make_button( row.second, "Press Me" ); row = layout->new_row(); builder.make_label( row.first, "Goodbye World" ); builder.make_button( row.second, "Me Too" ); } void build_box_window( const std::shared_ptr<gui::window> &win ) { using layout::box_layout; gui::builder builder( win ); auto layout = builder.new_layout<box_layout>( layout::direction::DOWN ); layout->set_pad( 12.0, 12.0, 12.0, 12.0 ); layout->set_spacing( 12.0, 12.0 ); builder.make_label( layout->new_area(), "Hello World" ); builder.make_button( layout->new_area(), "Press Me" ); builder.make_label( layout->new_area(), "Goodbye World" ); builder.make_button( layout->new_area(), "Me Too" ); } //////////////////////////////////////// int safemain( int argc, char **argv ) { auto app = std::make_shared<gui::application>(); app->push(); app->set_style( std::make_shared<gui::cocoa_style>() ); auto win1 = app->new_window(); build_form_window( win1 ); win1->show(); auto win2 = app->new_window(); build_box_window( win2 ); win2->show(); int code = app->run(); app->pop(); return code; } //////////////////////////////////////// } //////////////////////////////////////// int main( int argc, char *argv[] ) { int ret = -1; try { ret = safemain( argc, argv ); } catch ( std::exception &e ) { print_exception( std::cerr, e ); } return ret; } //////////////////////////////////////// <commit_msg>Added grid test.<commit_after> #include <sstream> #include <layout/form_layout.h> #include <layout/box_layout.h> #include <layout/grid_layout.h> #include <gui/application.h> #include <gui/cocoa_style.h> namespace { //////////////////////////////////////// void build_form_window( const std::shared_ptr<gui::window> &win ) { using layout::form_layout; gui::builder builder( win ); auto layout = builder.new_layout<form_layout>( layout::direction::RIGHT ); layout->set_pad( 12.0, 12.0, 12.0, 12.0 ); layout->set_spacing( 12.0, 12.0 ); auto row = layout->new_row(); builder.make_label( row.first, "Hello World" ); builder.make_button( row.second, "Press Me" ); row = layout->new_row(); builder.make_label( row.first, "Goodbye World" ); builder.make_button( row.second, "Me Too" ); } void build_box_window( const std::shared_ptr<gui::window> &win ) { using layout::box_layout; gui::builder builder( win ); auto layout = builder.new_layout<box_layout>( layout::direction::DOWN ); layout->set_pad( 12.0, 12.0, 12.0, 12.0 ); layout->set_spacing( 12.0, 12.0 ); builder.make_label( layout->new_area(), "Hello World" ); builder.make_button( layout->new_area(), "Press Me" ); builder.make_label( layout->new_area(), "Goodbye World" ); builder.make_button( layout->new_area(), "Me Too" ); } void build_grid_window( const std::shared_ptr<gui::window> &win ) { using layout::grid_layout; gui::builder builder( win ); auto layout = builder.new_layout<grid_layout>(); layout->set_pad( 12.0, 12.0, 12.0, 12.0 ); layout->set_spacing( 12.0, 12.0 ); for ( size_t i = 0; i < 5; ++i ) layout->new_column( 1.0 ); int count = 0; for ( size_t i = 0; i < 5; ++i ) { auto cols = layout->new_row(); for ( auto a: cols ) { std::stringstream tmp; tmp << ++count; builder.make_label( a, tmp.str() ); } } } //////////////////////////////////////// int safemain( int argc, char **argv ) { auto app = std::make_shared<gui::application>(); app->push(); app->set_style( std::make_shared<gui::cocoa_style>() ); auto win1 = app->new_window(); build_form_window( win1 ); win1->show(); auto win2 = app->new_window(); build_box_window( win2 ); win2->show(); auto win3 = app->new_window(); build_grid_window( win3 ); win3->show(); int code = app->run(); app->pop(); return code; } //////////////////////////////////////// } //////////////////////////////////////// int main( int argc, char *argv[] ) { int ret = -1; try { ret = safemain( argc, argv ); } catch ( std::exception &e ) { print_exception( std::cerr, e ); } return ret; } //////////////////////////////////////// <|endoftext|>
<commit_before><commit_msg>Remove device get_default().<commit_after><|endoftext|>
<commit_before>//----------------------------------------------------------- // // Copyright (C) 2017 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, 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. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // //----------------------------------------------------------- #include <deal.II/sundials/copy.h> #ifdef DEAL_II_WITH_SUNDIALS DEAL_II_NAMESPACE_OPEN namespace SUNDIALS { namespace internal { namespace { /** * SUNDIALS provides different macros for getting the local length of a * vector for serial and parallel vectors (as well as various parallel * vectors that are not yet supported by deal.II). This function provides * a generic interface to both and does a (checked) conversion from long * int (the type SUNDIALS uses for lengths) to std::size_t. */ inline std::size_t N_Vector_length(const N_Vector &vec) { const N_Vector_ID id = N_VGetVectorID(vec); long int length = -1; switch (id) { case SUNDIALS_NVEC_SERIAL: { length = NV_LENGTH_S(vec); break; } case SUNDIALS_NVEC_PARALLEL: { length = NV_LOCLENGTH_P(vec); break; } default: Assert(false, ExcNotImplemented()); } Assert(length >= 0, ExcInternalError()); return static_cast<std::size_t>(length); } } #ifdef DEAL_II_WITH_MPI #ifdef DEAL_II_WITH_TRILINOS void copy(TrilinosWrappers::MPI::Vector &dst, const N_Vector &src) { IndexSet is = dst.locally_owned_elements(); AssertDimension(is.n_elements(), N_Vector_length(src)); for (unsigned int i=0; i<is.n_elements(); ++i) { dst[is.nth_index_in_set(i)] = NV_Ith_P(src, i); } dst.compress(VectorOperation::insert); } void copy(N_Vector &dst, const TrilinosWrappers::MPI::Vector &src) { IndexSet is = src.locally_owned_elements(); AssertDimension(is.n_elements(), N_Vector_length(dst)); for (unsigned int i=0; i<is.n_elements(); ++i) { NV_Ith_P(dst, i) = src[is.nth_index_in_set(i)]; } } void copy(TrilinosWrappers::MPI::BlockVector &dst, const N_Vector &src) { IndexSet is = dst.locally_owned_elements(); AssertDimension(is.n_elements(), N_Vector_length(src)); for (unsigned int i=0; i<is.n_elements(); ++i) { dst[is.nth_index_in_set(i)] = NV_Ith_P(src, i); } dst.compress(VectorOperation::insert); } void copy(N_Vector &dst, const TrilinosWrappers::MPI::BlockVector &src) { IndexSet is = src.locally_owned_elements(); AssertDimension(is.n_elements(), N_Vector_length(dst)); for (unsigned int i=0; i<is.n_elements(); ++i) { NV_Ith_P(dst, i) = src[is.nth_index_in_set(i)]; } } #endif //DEAL_II_WITH_TRILINOS #ifdef DEAL_II_WITH_PETSC void copy(PETScWrappers::MPI::Vector &dst, const N_Vector &src) { IndexSet is = dst.locally_owned_elements(); AssertDimension(is.n_elements(), N_Vector_length(src)); for (unsigned int i=0; i<is.n_elements(); ++i) { dst[is.nth_index_in_set(i)] = NV_Ith_P(src, i); } dst.compress(VectorOperation::insert); } void copy(N_Vector &dst, const PETScWrappers::MPI::Vector &src) { IndexSet is = src.locally_owned_elements(); AssertDimension(is.n_elements(), N_Vector_length(dst)); for (unsigned int i=0; i<is.n_elements(); ++i) { NV_Ith_P(dst, i) = src[is.nth_index_in_set(i)]; } } void copy(PETScWrappers::MPI::BlockVector &dst, const N_Vector &src) { IndexSet is = dst.locally_owned_elements(); AssertDimension(is.n_elements(), N_Vector_length(src)); for (unsigned int i=0; i<is.n_elements(); ++i) { dst[is.nth_index_in_set(i)] = NV_Ith_P(src, i); } dst.compress(VectorOperation::insert); } void copy(N_Vector &dst, const PETScWrappers::MPI::BlockVector &src) { IndexSet is = src.locally_owned_elements(); AssertDimension(is.n_elements(), N_Vector_length(dst)); for (unsigned int i=0; i<is.n_elements(); ++i) { NV_Ith_P(dst, i) = src[is.nth_index_in_set(i)]; } } #endif //DEAL_II_WITH_PETSC #endif //mpi void copy(BlockVector<double> &dst, const N_Vector &src) { AssertDimension(N_Vector_length(src), dst.size()); for (unsigned int i=0; i<dst.size(); ++i) { dst[i] = NV_Ith_S(src, i); } } void copy(N_Vector &dst, const BlockVector<double> &src) { AssertDimension(N_Vector_length(dst), src.size()); for (unsigned int i=0; i<src.size(); ++i) { NV_Ith_S(dst, i) = src[i]; } } void copy(Vector<double> &dst, const N_Vector &src) { AssertDimension(N_Vector_length(src), dst.size()); for (unsigned int i=0; i<dst.size(); ++i) { dst[i] = NV_Ith_S(src, i); } } void copy(N_Vector &dst, const Vector<double> &src) { AssertDimension(N_Vector_length(dst), src.size()); for (unsigned int i=0; i<src.size(); ++i) { NV_Ith_S(dst, i) = src[i]; } } } } DEAL_II_NAMESPACE_CLOSE #endif <commit_msg>Move a function out of an anonymous namespace.<commit_after>//----------------------------------------------------------- // // Copyright (C) 2017 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, 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. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // //----------------------------------------------------------- #include <deal.II/sundials/copy.h> #ifdef DEAL_II_WITH_SUNDIALS DEAL_II_NAMESPACE_OPEN namespace SUNDIALS { namespace internal { /** * SUNDIALS provides different macros for getting the local length of a * vector for serial and parallel vectors (as well as various parallel * vectors that are not yet supported by deal.II). This function provides * a generic interface to both and does a (checked) conversion from long * int (the type SUNDIALS uses for lengths) to std::size_t. */ inline std::size_t N_Vector_length(const N_Vector &vec) { const N_Vector_ID id = N_VGetVectorID(vec); long int length = -1; switch (id) { case SUNDIALS_NVEC_SERIAL: { length = NV_LENGTH_S(vec); break; } case SUNDIALS_NVEC_PARALLEL: { length = NV_LOCLENGTH_P(vec); break; } default: Assert(false, ExcNotImplemented()); } Assert(length >= 0, ExcInternalError()); return static_cast<std::size_t>(length); } #ifdef DEAL_II_WITH_MPI #ifdef DEAL_II_WITH_TRILINOS void copy(TrilinosWrappers::MPI::Vector &dst, const N_Vector &src) { IndexSet is = dst.locally_owned_elements(); AssertDimension(is.n_elements(), N_Vector_length(src)); for (unsigned int i=0; i<is.n_elements(); ++i) { dst[is.nth_index_in_set(i)] = NV_Ith_P(src, i); } dst.compress(VectorOperation::insert); } void copy(N_Vector &dst, const TrilinosWrappers::MPI::Vector &src) { IndexSet is = src.locally_owned_elements(); AssertDimension(is.n_elements(), N_Vector_length(dst)); for (unsigned int i=0; i<is.n_elements(); ++i) { NV_Ith_P(dst, i) = src[is.nth_index_in_set(i)]; } } void copy(TrilinosWrappers::MPI::BlockVector &dst, const N_Vector &src) { IndexSet is = dst.locally_owned_elements(); AssertDimension(is.n_elements(), N_Vector_length(src)); for (unsigned int i=0; i<is.n_elements(); ++i) { dst[is.nth_index_in_set(i)] = NV_Ith_P(src, i); } dst.compress(VectorOperation::insert); } void copy(N_Vector &dst, const TrilinosWrappers::MPI::BlockVector &src) { IndexSet is = src.locally_owned_elements(); AssertDimension(is.n_elements(), N_Vector_length(dst)); for (unsigned int i=0; i<is.n_elements(); ++i) { NV_Ith_P(dst, i) = src[is.nth_index_in_set(i)]; } } #endif //DEAL_II_WITH_TRILINOS #ifdef DEAL_II_WITH_PETSC void copy(PETScWrappers::MPI::Vector &dst, const N_Vector &src) { IndexSet is = dst.locally_owned_elements(); AssertDimension(is.n_elements(), N_Vector_length(src)); for (unsigned int i=0; i<is.n_elements(); ++i) { dst[is.nth_index_in_set(i)] = NV_Ith_P(src, i); } dst.compress(VectorOperation::insert); } void copy(N_Vector &dst, const PETScWrappers::MPI::Vector &src) { IndexSet is = src.locally_owned_elements(); AssertDimension(is.n_elements(), N_Vector_length(dst)); for (unsigned int i=0; i<is.n_elements(); ++i) { NV_Ith_P(dst, i) = src[is.nth_index_in_set(i)]; } } void copy(PETScWrappers::MPI::BlockVector &dst, const N_Vector &src) { IndexSet is = dst.locally_owned_elements(); AssertDimension(is.n_elements(), N_Vector_length(src)); for (unsigned int i=0; i<is.n_elements(); ++i) { dst[is.nth_index_in_set(i)] = NV_Ith_P(src, i); } dst.compress(VectorOperation::insert); } void copy(N_Vector &dst, const PETScWrappers::MPI::BlockVector &src) { IndexSet is = src.locally_owned_elements(); AssertDimension(is.n_elements(), N_Vector_length(dst)); for (unsigned int i=0; i<is.n_elements(); ++i) { NV_Ith_P(dst, i) = src[is.nth_index_in_set(i)]; } } #endif //DEAL_II_WITH_PETSC #endif //mpi void copy(BlockVector<double> &dst, const N_Vector &src) { AssertDimension(N_Vector_length(src), dst.size()); for (unsigned int i=0; i<dst.size(); ++i) { dst[i] = NV_Ith_S(src, i); } } void copy(N_Vector &dst, const BlockVector<double> &src) { AssertDimension(N_Vector_length(dst), src.size()); for (unsigned int i=0; i<src.size(); ++i) { NV_Ith_S(dst, i) = src[i]; } } void copy(Vector<double> &dst, const N_Vector &src) { AssertDimension(N_Vector_length(src), dst.size()); for (unsigned int i=0; i<dst.size(); ++i) { dst[i] = NV_Ith_S(src, i); } } void copy(N_Vector &dst, const Vector<double> &src) { AssertDimension(N_Vector_length(dst), src.size()); for (unsigned int i=0; i<src.size(); ++i) { NV_Ith_S(dst, i) = src[i]; } } } } DEAL_II_NAMESPACE_CLOSE #endif <|endoftext|>
<commit_before><commit_msg>Separate Best AI stats from game results<commit_after><|endoftext|>
<commit_before>/* * * NRF24L01+ to Message Protocol gateway * Copyright (C) 2013 Dustin Brewer * License: MIT */ #include <algorithm> #include <unordered_map> #include <string> #include <sstream> #include <vector> #include <ctime> #include "csiphash.c" #include "StringSplit.h" #include "IMessageProtocol.h" #include "IRadioNetwork.h" #include "RF24Node.h" RF24Node::RF24Node(IRadioNetwork& _network, IMessageProtocol& _msg_proto, char _key[16]) : msg_proto(_msg_proto), network(_network), key(_key) { } void RF24Node::begin(void) { this->msg_proto.set_on_message_callback([this](std::string subject, std::string body) { this->handle_receive_message(subject, body); }); this->msg_proto.begin(); this->network.begin(); } void RF24Node::end(void) { this->msg_proto.end(); } void RF24Node::loop(void) { this->network.update(); while (this->network.available()) { RF24NetworkHeader header; this->network.peek(header); switch (header.type) { case PKT_POWER: this->handle_receive_power(header); break; case PKT_TEMP: this->handle_receive_temp(header); break; case PKT_HUMID: this->handle_receive_humidity(header); break; case PKT_SWITCH: this->handle_receive_switch(header); break; case PKT_MOISTURE: this->handle_receive_moisture(header); break; case PKT_ENERGY: this->handle_receive_energy(header); break; case PKT_RGB: // Not Implemented break; case PKT_TIME: this->handle_receive_timesync(header); break; case PKT_CHALLENGE: this->handle_receive_challenge(header); break; default: break; } } this->msg_proto.loop(); } bool RF24Node::write(RF24NetworkHeader& header,const void* message, size_t len) { const uint8_t max_retries = 1; bool ok = false; uint8_t retries = max_retries; while (!ok && retries-- > 0) { ok = this->network.write(header, message, len); } return ok; } /** * Upon receiving a command via the C++/Python IPC topic, queue the message */ void RF24Node::handle_receive_message(std::string subject, std::string body) { if (this->debug) printf("Received '%s' via topic '%s' from MQTT\n", subject.c_str(), body.c_str()); std::vector<std::string> elements = split(subject, '/'); uint16_t to_node = std::stoul("0" + elements[3], nullptr, 0); uint8_t type_command = std::stoi(elements[4], nullptr); uint8_t type = type_command % 64; if (type_command < 64) { // Asking for sensor data is unsupported return; } this->queued_payloads[to_node][type] = body; if (this->debug) printf("Queuing: '%s' for node 0%o, payload type %d\n", body.c_str(), to_node, type); pkt_challenge_t payload; payload.type = type; RF24NetworkHeader header(to_node, PKT_CHALLENGE); this->write(header, &payload, sizeof(payload)); } /* * Upon receiving a header specifying a challenge response, store the challenge */ void RF24Node::handle_receive_challenge(RF24NetworkHeader& header) { if (this->debug) printf("Handling challenge request for node 0%o.\n", header.from_node); // Read the challenge request response pkt_challenge_t payload; this->network.read(header, &payload, sizeof(payload)); switch (payload.type) { case PKT_SWITCH: this->handle_send_switch(header.from_node, this->queued_payloads[header.from_node][payload.type], payload.challenge); break; case PKT_RGB: // Not implemented break; } } /* * Upon receiving a header specifying a timesync request, send the time to the node */ void RF24Node::handle_receive_timesync(RF24NetworkHeader& header) { if (this->debug) printf("Handling timesync request for node 0%o.\n", header.from_node); // Read in the packet; not used this->network.read(header, nullptr, 0); // Set the current timestamp pkt_time_t t = { time(0) }; // Send the packet (timestamp) to the desired node RF24NetworkHeader new_header(header.from_node, PKT_TIME); this->write(new_header, &t, sizeof(t)); } /* * Publish temps on MQTT */ void RF24Node::handle_receive_temp(RF24NetworkHeader& header) { pkt_temp_t payload; this->network.read(header, &payload, sizeof(payload)); std::stringstream s_value; s_value << payload.id << "|" << (double)(payload.temp / 10.0); std::string topic = this->generate_msg_proto_subject(header); std::string value = s_value.str(); if (this->debug) printf("Republishing Temp: %s:%s\n", topic.c_str(), value.c_str()); this->msg_proto.send_message(topic, value); } /* * Publish humidity on MQTT */ void RF24Node::handle_receive_humidity(RF24NetworkHeader& header) { pkt_humid_t payload; this->network.read(header, &payload, sizeof(payload)); std::stringstream s_value; s_value << payload.id << "|" << ((double)(payload.humidity / 10.0)); std::string topic = this->generate_msg_proto_subject(header); std::string value = s_value.str(); if (this->debug) printf("Republishing Humidity: %s:%s\n", topic.c_str(), value.c_str()); this->msg_proto.send_message(topic, value); } /* * Publish power on MQTT */ void RF24Node::handle_receive_power(RF24NetworkHeader& header) { pkt_power_t payload; this->network.read(header, &payload, sizeof(payload)); std::stringstream s_value; s_value << payload.battery << "|" << payload.solar << "|" << payload.vcc << "|" << payload.vs; std::string topic = this->generate_msg_proto_subject(header); std::string value = s_value.str(); if (this->debug) printf("Republishing Power: %s:%s\n", topic.c_str(), value.c_str()); this->msg_proto.send_message(topic, value); } /* * Publish moisture on MQTT */ void RF24Node::handle_receive_moisture(RF24NetworkHeader& header) { pkt_moisture_t payload; this->network.read(header, &payload, sizeof(payload)); std::stringstream s_value; s_value << payload.id << "|" << payload.moisture; std::string topic = this->generate_msg_proto_subject(header); std::string value = s_value.str(); if (this->debug) printf("Republishing Moisture: %s:%s\n", topic.c_str(), value.c_str()); this->msg_proto.send_message(topic, value); } /* * Publish energy on MQTT */ void RF24Node::handle_receive_energy(RF24NetworkHeader& header) { pkt_energy_t payload; this->network.read(header, &payload, sizeof(payload)); std::stringstream s_value; s_value << payload.id << "|" << payload.energy; std::string topic = this->generate_msg_proto_subject(header); std::string value = s_value.str(); if (this->debug) printf("Republishing Energy: %s:%s\n", topic.c_str(), value.c_str()); this->msg_proto.send_message(topic, value); } /* * Publish switch on MQTT */ void RF24Node::handle_receive_switch(RF24NetworkHeader& header) { pkt_switch_t payload; this->network.read(header, &payload, sizeof(payload)); std::stringstream s_value; s_value << payload.id << "|" << payload.state << "|" << payload.timer; std::string topic = this->generate_msg_proto_subject(header); std::string value = s_value.str(); if (this->debug) printf("Republishing Switch: %s:%s\n", topic.c_str(), value.c_str()); this->msg_proto.send_message(topic, value); } void RF24Node::handle_send_switch(uint16_t node, std::string queued_payload, time_t challenge) { std::vector<std::string> elements = split(queued_payload.c_str(), '|'); pkt_switch_t payload; payload.id = std::stoi(elements[0], nullptr, 0); payload.state = std::stoi(elements[1], nullptr, 0); payload.timer = std::stoi(elements[2], nullptr, 0); this->generate_siphash(challenge, payload.hash); if (this->debug) { printf("Republishing Switch Command: 0%o:%s\n", node, queued_payload.c_str()); printf("-- payload: %d, %d, %d\n", payload.id, payload.state, payload.timer); printf("-- using siphashed (%d, %d, %d, %d, %d, %d, %d, %d) challenge %lu\n", payload.hash[0], payload.hash[1], payload.hash[2], payload.hash[3], payload.hash[4], payload.hash[5], payload.hash[6], payload.hash[7], challenge); } // Send a challenge request to the appropriate node RF24NetworkHeader header(node, PKT_SWITCH); this->write(header, &payload, sizeof(payload)); } std::string RF24Node::generate_msg_proto_subject(RF24NetworkHeader& header) { char from_node_oct[5]; sprintf(from_node_oct, "%o", header.from_node); std::stringstream s_topic; s_topic << "/sensornet/out/" << from_node_oct << "/" << std::to_string(header.type); return s_topic.str(); } void RF24Node::generate_siphash(time_t challenge, unsigned char (&hash)[8]) { // Convert the challenge into a byte array char challenge_array[4]; for(int i = 0; i <= 3; i++) { challenge_array[i] = (challenge >> (8 * i) ) & 0xFF; } // Generate the hash uint64_t siphash = siphash24(challenge_array, sizeof(challenge_array), this->key); // Convert the siphash into a byte array for(unsigned int i = 0; i < sizeof(hash); i++) { hash[i] = (siphash >> (8 * i) ) & 0xFF; } } <commit_msg>Handle Challenge improvements<commit_after>/* * * NRF24L01+ to Message Protocol gateway * Copyright (C) 2013 Dustin Brewer * License: MIT */ #include <algorithm> #include <unordered_map> #include <string> #include <sstream> #include <vector> #include <ctime> #include "csiphash.c" #include "StringSplit.h" #include "IMessageProtocol.h" #include "IRadioNetwork.h" #include "RF24Node.h" RF24Node::RF24Node(IRadioNetwork& _network, IMessageProtocol& _msg_proto, char _key[16]) : msg_proto(_msg_proto), network(_network), key(_key) { } void RF24Node::begin(void) { this->msg_proto.set_on_message_callback([this](std::string subject, std::string body) { this->handle_receive_message(subject, body); }); this->msg_proto.begin(); this->network.begin(); } void RF24Node::end(void) { this->msg_proto.end(); } void RF24Node::loop(void) { this->network.update(); while (this->network.available()) { RF24NetworkHeader header; this->network.peek(header); switch (header.type) { case PKT_POWER: this->handle_receive_power(header); break; case PKT_TEMP: this->handle_receive_temp(header); break; case PKT_HUMID: this->handle_receive_humidity(header); break; case PKT_SWITCH: this->handle_receive_switch(header); break; case PKT_MOISTURE: this->handle_receive_moisture(header); break; case PKT_ENERGY: this->handle_receive_energy(header); break; case PKT_RGB: // Not Implemented break; case PKT_TIME: this->handle_receive_timesync(header); break; case PKT_CHALLENGE: this->handle_receive_challenge(header); break; default: break; } } this->msg_proto.loop(); } bool RF24Node::write(RF24NetworkHeader& header,const void* message, size_t len) { const uint8_t max_retries = 1; bool ok = false; uint8_t retries = max_retries; while (!ok && retries-- > 0) { ok = this->network.write(header, message, len); } return ok; } /** * Upon receiving a command via the C++/Python IPC topic, queue the message */ void RF24Node::handle_receive_message(std::string subject, std::string body) { if (this->debug) printf("Received '%s' via topic '%s' from MQTT\n", subject.c_str(), body.c_str()); std::vector<std::string> elements = split(subject, '/'); uint16_t to_node = std::stoul("0" + elements[3], nullptr, 0); uint8_t type_command = std::stoi(elements[4], nullptr); uint8_t type = type_command % 64; if (type_command < 64) { // Asking for sensor data is unsupported return; } this->queued_payloads[to_node][type] = body; if (this->debug) printf("Queuing: '%s' for node 0%o, payload type %d\n", body.c_str(), to_node, type); pkt_challenge_t payload; payload.type = type; RF24NetworkHeader header(to_node, PKT_CHALLENGE); this->write(header, &payload, sizeof(payload)); } /* * Upon receiving a header specifying a challenge response, store the challenge */ void RF24Node::handle_receive_challenge(RF24NetworkHeader& header) { if (this->debug) printf("Handling challenge request for node 0%o.\n", header.from_node); // Read the challenge request response pkt_challenge_t payload; this->network.read(header, &payload, sizeof(payload)); if (this->queued_payloads.find(header.from_node) == this->queued_payloads.end() || this->queued_payloads[header.from_node].find(payload.type) == this->queued_payloads[header.from_node].end()) { if (this->debug) printf("No queued payload for for node 0%o of payload type %d.\n", header.from_node, payload.type); return; } switch (payload.type) { case PKT_SWITCH: this->handle_send_switch(header.from_node, this->queued_payloads[header.from_node][payload.type], payload.challenge); break; case PKT_RGB: // Not implemented break; } this->queued_payloads[header.from_node].erase(payload.type); } /* * Upon receiving a header specifying a timesync request, send the time to the node */ void RF24Node::handle_receive_timesync(RF24NetworkHeader& header) { if (this->debug) printf("Handling timesync request for node 0%o.\n", header.from_node); // Read in the packet; not used this->network.read(header, nullptr, 0); // Set the current timestamp pkt_time_t t = { time(0) }; // Send the packet (timestamp) to the desired node RF24NetworkHeader new_header(header.from_node, PKT_TIME); this->write(new_header, &t, sizeof(t)); } /* * Publish temps on MQTT */ void RF24Node::handle_receive_temp(RF24NetworkHeader& header) { pkt_temp_t payload; this->network.read(header, &payload, sizeof(payload)); std::stringstream s_value; s_value << payload.id << "|" << (double)(payload.temp / 10.0); std::string topic = this->generate_msg_proto_subject(header); std::string value = s_value.str(); if (this->debug) printf("Republishing Temp: %s:%s\n", topic.c_str(), value.c_str()); this->msg_proto.send_message(topic, value); } /* * Publish humidity on MQTT */ void RF24Node::handle_receive_humidity(RF24NetworkHeader& header) { pkt_humid_t payload; this->network.read(header, &payload, sizeof(payload)); std::stringstream s_value; s_value << payload.id << "|" << ((double)(payload.humidity / 10.0)); std::string topic = this->generate_msg_proto_subject(header); std::string value = s_value.str(); if (this->debug) printf("Republishing Humidity: %s:%s\n", topic.c_str(), value.c_str()); this->msg_proto.send_message(topic, value); } /* * Publish power on MQTT */ void RF24Node::handle_receive_power(RF24NetworkHeader& header) { pkt_power_t payload; this->network.read(header, &payload, sizeof(payload)); std::stringstream s_value; s_value << payload.battery << "|" << payload.solar << "|" << payload.vcc << "|" << payload.vs; std::string topic = this->generate_msg_proto_subject(header); std::string value = s_value.str(); if (this->debug) printf("Republishing Power: %s:%s\n", topic.c_str(), value.c_str()); this->msg_proto.send_message(topic, value); } /* * Publish moisture on MQTT */ void RF24Node::handle_receive_moisture(RF24NetworkHeader& header) { pkt_moisture_t payload; this->network.read(header, &payload, sizeof(payload)); std::stringstream s_value; s_value << payload.id << "|" << payload.moisture; std::string topic = this->generate_msg_proto_subject(header); std::string value = s_value.str(); if (this->debug) printf("Republishing Moisture: %s:%s\n", topic.c_str(), value.c_str()); this->msg_proto.send_message(topic, value); } /* * Publish energy on MQTT */ void RF24Node::handle_receive_energy(RF24NetworkHeader& header) { pkt_energy_t payload; this->network.read(header, &payload, sizeof(payload)); std::stringstream s_value; s_value << payload.id << "|" << payload.energy; std::string topic = this->generate_msg_proto_subject(header); std::string value = s_value.str(); if (this->debug) printf("Republishing Energy: %s:%s\n", topic.c_str(), value.c_str()); this->msg_proto.send_message(topic, value); } /* * Publish switch on MQTT */ void RF24Node::handle_receive_switch(RF24NetworkHeader& header) { pkt_switch_t payload; this->network.read(header, &payload, sizeof(payload)); std::stringstream s_value; s_value << payload.id << "|" << payload.state << "|" << payload.timer; std::string topic = this->generate_msg_proto_subject(header); std::string value = s_value.str(); if (this->debug) printf("Republishing Switch: %s:%s\n", topic.c_str(), value.c_str()); this->msg_proto.send_message(topic, value); } void RF24Node::handle_send_switch(uint16_t node, std::string queued_payload, time_t challenge) { std::vector<std::string> elements = split(queued_payload.c_str(), '|'); pkt_switch_t payload; payload.id = std::stoi(elements[0], nullptr, 0); payload.state = std::stoi(elements[1], nullptr, 0); payload.timer = std::stoi(elements[2], nullptr, 0); this->generate_siphash(challenge, payload.hash); if (this->debug) { printf("Republishing Switch Command: 0%o:%s\n", node, queued_payload.c_str()); printf("-- payload: %d, %d, %d\n", payload.id, payload.state, payload.timer); printf("-- using siphashed (%d, %d, %d, %d, %d, %d, %d, %d) challenge %lu\n", payload.hash[0], payload.hash[1], payload.hash[2], payload.hash[3], payload.hash[4], payload.hash[5], payload.hash[6], payload.hash[7], challenge); } // Send a challenge request to the appropriate node RF24NetworkHeader header(node, PKT_SWITCH); this->write(header, &payload, sizeof(payload)); } std::string RF24Node::generate_msg_proto_subject(RF24NetworkHeader& header) { char from_node_oct[5]; sprintf(from_node_oct, "%o", header.from_node); std::stringstream s_topic; s_topic << "/sensornet/out/" << from_node_oct << "/" << std::to_string(header.type); return s_topic.str(); } void RF24Node::generate_siphash(time_t challenge, unsigned char (&hash)[8]) { // Convert the challenge into a byte array char challenge_array[4]; for(int i = 0; i <= 3; i++) { challenge_array[i] = (challenge >> (8 * i) ) & 0xFF; } // Generate the hash uint64_t siphash = siphash24(challenge_array, sizeof(challenge_array), this->key); // Convert the siphash into a byte array for(unsigned int i = 0; i < sizeof(hash); i++) { hash[i] = (siphash >> (8 * i) ) & 0xFF; } } <|endoftext|>
<commit_before>#ifndef _SNARKFRONT_RANK_1_OPS_HPP_ #define _SNARKFRONT_RANK_1_OPS_HPP_ #include <algorithm> #include <cassert> #include <cstdint> #include <vector> #include "PowersOf2.hpp" #include <Rank1DSL.hpp> // snarklib #include "TLsingleton.hpp" namespace snarkfront { //////////////////////////////////////////////////////////////////////////////// // variable consistency, enforce valid values // // constrain rank-1 variable to 0 and 1 values template <template <typename> class SYS, typename FR> void rank1_booleanity(SYS<FR>& S, const snarklib::R1Variable<FR>& x) { #ifdef USE_ASSERT assert(! x.zeroIndex()); #endif S.addConstraint(x * (FR::one() - x) == FR::zero()); // only roots are 0 and 1 } template <template <typename> class SYS, typename FR> void rank1_booleanity(SYS<FR>& S, const snarklib::R1Term<FR>& x) { #ifdef USE_ASSERT assert(x.isVariable()); #endif rank1_booleanity(S, x.var()); } template <template <typename> class SYS, typename FR> void rank1_booleanity(SYS<FR>& S, const std::vector<snarklib::R1Term<FR>>& x) { for (const auto& a : x) rank1_booleanity(S, a); } // constrain between a scalar in [0, 2^k) and representation as k bits template <template <typename> class SYS, typename FR> void rank1_split(SYS<FR>& S, const snarklib::R1Term<FR>& x, const std::vector<snarklib::R1Term<FR>>& b) { #ifdef USE_ASSERT assert(x.isVariable()); #endif snarklib::R1Combination<FR> LC; LC.reserveTerms(b.size()); for (std::size_t i = 0; i < b.size(); ++i) { if (! b[i].zeroTerm()) LC.addTerm( TL<PowersOf2<FR>>::singleton()->lookUp(i) * b[i]); } S.addConstraint(LC == x); } //////////////////////////////////////////////////////////////////////////////// // operators // #define DEFN_R1OP(NAME, XYZ) \ template <typename FR> \ class R1_ ## NAME \ { \ public: \ typedef FR FieldType; \ static snarklib::R1Constraint<FR> constraint( \ const snarklib::R1Term<FR>& x, \ const snarklib::R1Term<FR>& y, \ const snarklib::R1Term<FR>& z) { \ return XYZ ; \ } \ }; // AND, OR, XOR, SAME, CMPLMNT DEFN_R1OP(AND, x * y == z) DEFN_R1OP(OR, x + y - z == x * y) DEFN_R1OP(XOR, x + y - z == ((FR::one() + FR::one()) * x) * y) DEFN_R1OP(SAME, x + y + z - FR::one() == ((FR::one() + FR::one()) * x) * y) DEFN_R1OP(CMPLMNT, x + z == FR::one()) // ADD, SUB, MUL DEFN_R1OP(ADD, x + y == z) DEFN_R1OP(SUB, x - y == z) DEFN_R1OP(MUL, x * y == z) #undef DEFN_R1OP //////////////////////////////////////////////////////////////////////////////// // function to apply operators // template <template <typename> class SYS, typename R1OP> void rank1_op( SYS<typename R1OP::FieldType>& S, const snarklib::R1Term<typename R1OP::FieldType>& x, const snarklib::R1Term<typename R1OP::FieldType>& y, const snarklib::R1Term<typename R1OP::FieldType>& z) { S.addConstraint(R1OP::constraint(x, y, z)); } //////////////////////////////////////////////////////////////////////////////// // bit shift and rotate // template <typename FR> void rank1_shiftleft(std::vector<snarklib::R1Term<FR>>& x, const std::size_t n) { #ifdef USE_ASSERT assert(! x.empty()); #endif if (0 == n) return; // do nothing const auto N = n % x.size(); for (std::size_t i = x.size() - 1; i >= N; --i) { x[i] = x[i - N]; } for (std::size_t i = 0; i < N; ++i) { x[i] = snarklib::R1Term<FR>(); } } template <typename FR> void rank1_shiftright(std::vector<snarklib::R1Term<FR>>& x, const std::size_t n) { #ifdef USE_ASSERT assert(! x.empty()); #endif if (0 == n) return; // do nothing const auto N = n % x.size(); for (std::size_t i = 0; i < x.size() - N; ++i) { x[i] = x[i + N]; } for (std::size_t i = x.size() - N; i < x.size(); ++i) { x[i] = snarklib::R1Term<FR>(); } } template <typename FR> void rank1_rotateleft(std::vector<snarklib::R1Term<FR>>& x, const std::size_t n) { #ifdef USE_ASSERT assert(! x.empty()); #endif if (0 == n) return; // do nothing const auto N = n % x.size(); std::vector<snarklib::R1Term<FR>> v(x.size()); for (std::size_t i = 0; i < x.size(); ++i) { v[(i + N) % x.size()] = x[i]; } x = v; } template <typename FR> void rank1_rotateright(std::vector<snarklib::R1Term<FR>>& x, const std::size_t n) { #ifdef USE_ASSERT assert(! x.empty()); #endif if (0 == n) return; // do nothing const auto N = n % x.size(); std::vector<snarklib::R1Term<FR>> v(x.size()); for (std::size_t i = 0; i < x.size(); ++i) { v[i] = x[(i + N) % x.size()]; } x = v; } //////////////////////////////////////////////////////////////////////////////// // convert between bitwise word types // template <typename FR> std::vector<snarklib::R1Term<FR>> rank1_xword( const std::vector<snarklib::R1Term<FR>>& x, const std::size_t returnSize) { std::vector<snarklib::R1Term<FR>> v(returnSize, FR::zero()); if (1 == x.size()) { // convert bool to word for (std::size_t i = 0; i < returnSize; ++i) v[i] = x[0]; } else { // convert between 32-bit and 64-bit words const auto N = std::min(returnSize, x.size()); for (std::size_t i = 0; i < N; ++i) v[i] = x[i]; } return v; } } // namespace snarkfront #endif <commit_msg>rank1_xword comments include bool and 8-bit<commit_after>#ifndef _SNARKFRONT_RANK_1_OPS_HPP_ #define _SNARKFRONT_RANK_1_OPS_HPP_ #include <algorithm> #include <cassert> #include <cstdint> #include <vector> #include "PowersOf2.hpp" #include <Rank1DSL.hpp> // snarklib #include "TLsingleton.hpp" namespace snarkfront { //////////////////////////////////////////////////////////////////////////////// // variable consistency, enforce valid values // // constrain rank-1 variable to 0 and 1 values template <template <typename> class SYS, typename FR> void rank1_booleanity(SYS<FR>& S, const snarklib::R1Variable<FR>& x) { #ifdef USE_ASSERT assert(! x.zeroIndex()); #endif S.addConstraint(x * (FR::one() - x) == FR::zero()); // only roots are 0 and 1 } template <template <typename> class SYS, typename FR> void rank1_booleanity(SYS<FR>& S, const snarklib::R1Term<FR>& x) { #ifdef USE_ASSERT assert(x.isVariable()); #endif rank1_booleanity(S, x.var()); } template <template <typename> class SYS, typename FR> void rank1_booleanity(SYS<FR>& S, const std::vector<snarklib::R1Term<FR>>& x) { for (const auto& a : x) rank1_booleanity(S, a); } // constrain between a scalar in [0, 2^k) and representation as k bits template <template <typename> class SYS, typename FR> void rank1_split(SYS<FR>& S, const snarklib::R1Term<FR>& x, const std::vector<snarklib::R1Term<FR>>& b) { #ifdef USE_ASSERT assert(x.isVariable()); #endif snarklib::R1Combination<FR> LC; LC.reserveTerms(b.size()); for (std::size_t i = 0; i < b.size(); ++i) { if (! b[i].zeroTerm()) LC.addTerm( TL<PowersOf2<FR>>::singleton()->lookUp(i) * b[i]); } S.addConstraint(LC == x); } //////////////////////////////////////////////////////////////////////////////// // operators // #define DEFN_R1OP(NAME, XYZ) \ template <typename FR> \ class R1_ ## NAME \ { \ public: \ typedef FR FieldType; \ static snarklib::R1Constraint<FR> constraint( \ const snarklib::R1Term<FR>& x, \ const snarklib::R1Term<FR>& y, \ const snarklib::R1Term<FR>& z) { \ return XYZ ; \ } \ }; // AND, OR, XOR, SAME, CMPLMNT DEFN_R1OP(AND, x * y == z) DEFN_R1OP(OR, x + y - z == x * y) DEFN_R1OP(XOR, x + y - z == ((FR::one() + FR::one()) * x) * y) DEFN_R1OP(SAME, x + y + z - FR::one() == ((FR::one() + FR::one()) * x) * y) DEFN_R1OP(CMPLMNT, x + z == FR::one()) // ADD, SUB, MUL DEFN_R1OP(ADD, x + y == z) DEFN_R1OP(SUB, x - y == z) DEFN_R1OP(MUL, x * y == z) #undef DEFN_R1OP //////////////////////////////////////////////////////////////////////////////// // function to apply operators // template <template <typename> class SYS, typename R1OP> void rank1_op( SYS<typename R1OP::FieldType>& S, const snarklib::R1Term<typename R1OP::FieldType>& x, const snarklib::R1Term<typename R1OP::FieldType>& y, const snarklib::R1Term<typename R1OP::FieldType>& z) { S.addConstraint(R1OP::constraint(x, y, z)); } //////////////////////////////////////////////////////////////////////////////// // bit shift and rotate // template <typename FR> void rank1_shiftleft(std::vector<snarklib::R1Term<FR>>& x, const std::size_t n) { #ifdef USE_ASSERT assert(! x.empty()); #endif if (0 == n) return; // do nothing const auto N = n % x.size(); for (std::size_t i = x.size() - 1; i >= N; --i) { x[i] = x[i - N]; } for (std::size_t i = 0; i < N; ++i) { x[i] = snarklib::R1Term<FR>(); } } template <typename FR> void rank1_shiftright(std::vector<snarklib::R1Term<FR>>& x, const std::size_t n) { #ifdef USE_ASSERT assert(! x.empty()); #endif if (0 == n) return; // do nothing const auto N = n % x.size(); for (std::size_t i = 0; i < x.size() - N; ++i) { x[i] = x[i + N]; } for (std::size_t i = x.size() - N; i < x.size(); ++i) { x[i] = snarklib::R1Term<FR>(); } } template <typename FR> void rank1_rotateleft(std::vector<snarklib::R1Term<FR>>& x, const std::size_t n) { #ifdef USE_ASSERT assert(! x.empty()); #endif if (0 == n) return; // do nothing const auto N = n % x.size(); std::vector<snarklib::R1Term<FR>> v(x.size()); for (std::size_t i = 0; i < x.size(); ++i) { v[(i + N) % x.size()] = x[i]; } x = v; } template <typename FR> void rank1_rotateright(std::vector<snarklib::R1Term<FR>>& x, const std::size_t n) { #ifdef USE_ASSERT assert(! x.empty()); #endif if (0 == n) return; // do nothing const auto N = n % x.size(); std::vector<snarklib::R1Term<FR>> v(x.size()); for (std::size_t i = 0; i < x.size(); ++i) { v[i] = x[(i + N) % x.size()]; } x = v; } //////////////////////////////////////////////////////////////////////////////// // bitwise conversion between unsigned integers and bool // template <typename FR> std::vector<snarklib::R1Term<FR>> rank1_xword( const std::vector<snarklib::R1Term<FR>>& x, const std::size_t returnSize) { std::vector<snarklib::R1Term<FR>> v(returnSize, FR::zero()); if (1 == x.size()) { // convert bool to 8-bit, 32-bit, or 64-bit for (std::size_t i = 0; i < returnSize; ++i) v[i] = x[0]; } else { // if destination type is bool, returnSize is 1 so takes 0th bit // otherwise, bitwise slices between unsigned integer types const auto N = std::min(returnSize, x.size()); for (std::size_t i = 0; i < N; ++i) v[i] = x[i]; } return v; } } // namespace snarkfront #endif <|endoftext|>
<commit_before>/* Copyright 2014 Adam Grandquist Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @author Adam Grandquist * @copyright Apache */ #include "ReQL-CPP.hpp" #include "ReQL.hpp" <commit_msg>Implement connection methods.<commit_after>/* Copyright 2014 Adam Grandquist Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @author Adam Grandquist * @copyright Apache */ #include "ReQL-CPP.hpp" #include "ReQL.hpp" #include <cstdlib> using namespace ReQL; Connection::Connection() { conn = (struct _ReQL_Conn_s *)new _ReQL_Conn_t(); conn = (struct _ReQL_Conn_s *)_reql_new_connection((_ReQL_Conn_t *)conn); if (!conn) { return; } char *buf; if (_reql_connect((_ReQL_Conn_t *)conn, &buf)) { } free(buf); } Connection::Connection(std::string host) { conn = (struct _ReQL_Conn_s *)new _ReQL_Conn_t(); conn = (struct _ReQL_Conn_s *)_reql_new_connection((_ReQL_Conn_t *)conn); if (!conn) { return; } char *buf; if (_reql_connect((_ReQL_Conn_t *)conn, &buf)) { } free(buf); } Connection::Connection(std::string host, std::string port) { conn = (struct _ReQL_Conn_s *)new _ReQL_Conn_t(); conn = (struct _ReQL_Conn_s *)_reql_new_connection((_ReQL_Conn_t *)conn); if (!conn) { return; } char *buf; if (_reql_connect((_ReQL_Conn_t *)conn, &buf)) { } free(buf); } Connection::Connection(std::string host, std::string port, std::string key) { conn = (struct _ReQL_Conn_s *)new _ReQL_Conn_t(); conn = (struct _ReQL_Conn_s *)_reql_new_connection((_ReQL_Conn_t *)conn); if (!conn) { return; } char *buf; if (_reql_connect((_ReQL_Conn_t *)conn, &buf)) { } free(buf); } Connection connect() { return Connection(); } Connection connect(std::string host) { return Connection(host); } Connection connect(std::string host, std::string port) { return Connection(host, port); } Connection connect(std::string host, std::string port, std::string key) { return Connection(host, port, key); } <|endoftext|>
<commit_before>/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * 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 <fnord-base/io/fileutil.h> #include <fnord-base/io/mmappedfile.h> #include <fnord-base/util/binarymessagereader.h> #include <fnord-base/util/binarymessagewriter.h> #include <fnord-cstable/CSTableBuilder.h> #include <fnord-cstable/CSTableWriter.h> #include <fnord-cstable/CSTableReader.h> #include <fnord-cstable/UInt64ColumnWriter.h> #include <fnord-cstable/UInt64ColumnReader.h> #include <fnord-cstable/RecordMaterializer.h> #include <fnord-msg/MessageDecoder.h> #include <fnord-tsdb/RecordSet.h> namespace fnord { namespace tsdb { RecordSet::RecordSet( RefPtr<msg::MessageSchema> schema, const String& filename_prefix, RecordSetState state /* = RecordSetState{} */) : schema_(schema), filename_prefix_(filename_prefix), state_(state) { auto id_index_fn = [this] (uint64_t id, const void* data, size_t size) { commitlog_ids_.emplace(id); }; for (const auto& o : state_.old_commitlogs) { loadCommitlog(o, id_index_fn); } if (!state.commitlog.isEmpty()) { loadCommitlog(state.commitlog.get(), id_index_fn); } } RecordSet::RecordSetState RecordSet::getState() const { std::unique_lock<std::mutex> lk(mutex_); return state_; } size_t RecordSet::commitlogSize() const { std::unique_lock<std::mutex> lk(mutex_); return commitlog_ids_.size(); } void RecordSet::addRecord(uint64_t record_id, const Buffer& message) { util::BinaryMessageWriter buf; buf.appendUInt64(record_id); buf.appendVarUInt(message.size()); buf.append(message.data(), message.size()); std::unique_lock<std::mutex> lk(mutex_); if (commitlog_ids_.count(record_id) > 0) { return; } String commitlog; uint64_t commitlog_size; if (state_.commitlog.isEmpty()) { commitlog = filename_prefix_ + rnd_.hex64() + ".log"; commitlog_size = 0; } else { commitlog = state_.commitlog.get(); commitlog_size = state_.commitlog_size; } auto file = File::openFile(commitlog, File::O_WRITE | File::O_CREATEOROPEN); file.truncate(commitlog_size + buf.size()); file.seekTo(commitlog_size); file.write(buf.data(), buf.size()); state_.commitlog = Some(commitlog); state_.commitlog_size = commitlog_size + buf.size(); commitlog_ids_.emplace(record_id); } void RecordSet::rollCommitlog() { std::unique_lock<std::mutex> lk(mutex_); if (state_.commitlog.isEmpty()) { return; } auto old_log = state_.commitlog.get(); FileUtil::truncate(old_log, state_.commitlog_size); state_.old_commitlogs.emplace(old_log); state_.commitlog = None<String>(); state_.commitlog_size = 0; } void RecordSet::compact() { std::unique_lock<std::mutex> compact_lk(compact_mutex_, std::defer_lock); if (!compact_lk.try_lock()) { return; // compaction is already running } std::unique_lock<std::mutex> lk(mutex_); auto snap = state_; lk.unlock(); if (snap.old_commitlogs.size() == 0) { return; } cstable::CSTableBuilder outfile(schema_.get()); cstable::UInt64ColumnWriter id_col(0, 0); Set<uint64_t> old_id_set; Set<uint64_t> new_id_set; if (!snap.datafile.isEmpty()) { cstable::CSTableReader reader(snap.datafile.get()); cstable::RecordMaterializer record_reader(schema_, &reader); auto msgid_col_ref = reader.getColumnReader("__msgid"); auto msgid_col = dynamic_cast<cstable::UInt64ColumnReader*>(msgid_col_ref.get()); auto n = reader.numRecords(); for (int i = 0; i < n; ++i) { uint64_t msgid; uint64_t r; uint64_t d; msgid_col->next(&r, &d, &msgid); old_id_set.emplace(msgid); msg::MessageObject record; record_reader.nextRecord(&record); outfile.addRecord(record); id_col.addDatum(0, 0, msgid); } } for (const auto& cl : snap.old_commitlogs) { loadCommitlog(cl, [this, &outfile, &old_id_set, &new_id_set, &id_col] ( uint64_t id, const void* data, size_t size) { if (new_id_set.count(id) > 0) { return; } new_id_set.emplace(id); if (old_id_set.count(id) > 0) { return; } msg::MessageObject record; msg::MessageDecoder::decode(data, size, *schema_, &record); outfile.addRecord(record); id_col.addDatum(0, 0, id); }); } auto outfile_path = filename_prefix_ + rnd_.hex64() + ".cst"; cstable::CSTableWriter outfile_writer( outfile_path, outfile.numRecords()); outfile.write(&outfile_writer); outfile_writer.addColumn("__msgid", &id_col); outfile_writer.commit(); lk.lock(); state_.datafile = Some(outfile_path); for (const auto& cl : snap.old_commitlogs) { state_.old_commitlogs.erase(cl); } for (const auto& id : new_id_set) { commitlog_ids_.erase(id); } } void RecordSet::loadCommitlog( const String& filename, Function<void (uint64_t, const void*, size_t)> fn) { io::MmappedFile mmap(File::openFile(filename, File::O_READ)); util::BinaryMessageReader reader(mmap.data(), mmap.size()); while (reader.remaining() > 0) { auto id = *reader.readUInt64(); auto len = reader.readVarUInt(); auto data = reader.read(len); fn(id, data, len); } } RecordSet::RecordSetState::RecordSetState() : commitlog_size(0) {} } // namespace tsdb } // namespace fnord <commit_msg>neste record materialization...<commit_after>/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * 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 <fnord-base/io/fileutil.h> #include <fnord-base/io/mmappedfile.h> #include <fnord-base/util/binarymessagereader.h> #include <fnord-base/util/binarymessagewriter.h> #include <fnord-cstable/CSTableBuilder.h> #include <fnord-cstable/CSTableWriter.h> #include <fnord-cstable/CSTableReader.h> #include <fnord-cstable/UInt64ColumnWriter.h> #include <fnord-cstable/UInt64ColumnReader.h> #include <fnord-cstable/RecordMaterializer.h> #include <fnord-msg/MessageDecoder.h> #include <fnord-tsdb/RecordSet.h> namespace fnord { namespace tsdb { RecordSet::RecordSet( RefPtr<msg::MessageSchema> schema, const String& filename_prefix, RecordSetState state /* = RecordSetState{} */) : schema_(schema), filename_prefix_(filename_prefix), state_(state) { auto id_index_fn = [this] (uint64_t id, const void* data, size_t size) { commitlog_ids_.emplace(id); }; for (const auto& o : state_.old_commitlogs) { loadCommitlog(o, id_index_fn); } if (!state.commitlog.isEmpty()) { loadCommitlog(state.commitlog.get(), id_index_fn); } } RecordSet::RecordSetState RecordSet::getState() const { std::unique_lock<std::mutex> lk(mutex_); return state_; } size_t RecordSet::commitlogSize() const { std::unique_lock<std::mutex> lk(mutex_); return commitlog_ids_.size(); } void RecordSet::addRecord(uint64_t record_id, const Buffer& message) { util::BinaryMessageWriter buf; buf.appendUInt64(record_id); buf.appendVarUInt(message.size()); buf.append(message.data(), message.size()); std::unique_lock<std::mutex> lk(mutex_); if (commitlog_ids_.count(record_id) > 0) { return; } String commitlog; uint64_t commitlog_size; if (state_.commitlog.isEmpty()) { commitlog = filename_prefix_ + rnd_.hex64() + ".log"; commitlog_size = 0; } else { commitlog = state_.commitlog.get(); commitlog_size = state_.commitlog_size; } auto file = File::openFile(commitlog, File::O_WRITE | File::O_CREATEOROPEN); file.truncate(commitlog_size + buf.size()); file.seekTo(commitlog_size); file.write(buf.data(), buf.size()); state_.commitlog = Some(commitlog); state_.commitlog_size = commitlog_size + buf.size(); commitlog_ids_.emplace(record_id); } void RecordSet::rollCommitlog() { std::unique_lock<std::mutex> lk(mutex_); if (state_.commitlog.isEmpty()) { return; } auto old_log = state_.commitlog.get(); FileUtil::truncate(old_log, state_.commitlog_size); state_.old_commitlogs.emplace(old_log); state_.commitlog = None<String>(); state_.commitlog_size = 0; } void RecordSet::compact() { std::unique_lock<std::mutex> compact_lk(compact_mutex_, std::defer_lock); if (!compact_lk.try_lock()) { return; // compaction is already running } std::unique_lock<std::mutex> lk(mutex_); auto snap = state_; lk.unlock(); if (snap.old_commitlogs.size() == 0) { return; } cstable::CSTableBuilder outfile(schema_.get()); cstable::UInt64ColumnWriter id_col(0, 0); Set<uint64_t> old_id_set; Set<uint64_t> new_id_set; if (!snap.datafile.isEmpty()) { cstable::CSTableReader reader(snap.datafile.get()); cstable::RecordMaterializer record_reader(schema_.get(), &reader); auto msgid_col_ref = reader.getColumnReader("__msgid"); auto msgid_col = dynamic_cast<cstable::UInt64ColumnReader*>(msgid_col_ref.get()); auto n = reader.numRecords(); for (int i = 0; i < n; ++i) { uint64_t msgid; uint64_t r; uint64_t d; msgid_col->next(&r, &d, &msgid); old_id_set.emplace(msgid); msg::MessageObject record; record_reader.nextRecord(&record); outfile.addRecord(record); id_col.addDatum(0, 0, msgid); } } for (const auto& cl : snap.old_commitlogs) { loadCommitlog(cl, [this, &outfile, &old_id_set, &new_id_set, &id_col] ( uint64_t id, const void* data, size_t size) { if (new_id_set.count(id) > 0) { return; } new_id_set.emplace(id); if (old_id_set.count(id) > 0) { return; } msg::MessageObject record; msg::MessageDecoder::decode(data, size, *schema_, &record); outfile.addRecord(record); id_col.addDatum(0, 0, id); }); } auto outfile_path = filename_prefix_ + rnd_.hex64() + ".cst"; cstable::CSTableWriter outfile_writer( outfile_path, outfile.numRecords()); outfile.write(&outfile_writer); outfile_writer.addColumn("__msgid", &id_col); outfile_writer.commit(); lk.lock(); state_.datafile = Some(outfile_path); for (const auto& cl : snap.old_commitlogs) { state_.old_commitlogs.erase(cl); } for (const auto& id : new_id_set) { commitlog_ids_.erase(id); } } void RecordSet::loadCommitlog( const String& filename, Function<void (uint64_t, const void*, size_t)> fn) { io::MmappedFile mmap(File::openFile(filename, File::O_READ)); util::BinaryMessageReader reader(mmap.data(), mmap.size()); while (reader.remaining() > 0) { auto id = *reader.readUInt64(); auto len = reader.readVarUInt(); auto data = reader.read(len); fn(id, data, len); } } RecordSet::RecordSetState::RecordSetState() : commitlog_size(0) {} } // namespace tsdb } // namespace fnord <|endoftext|>
<commit_before>/* This file is part of https://github.com/borneq/IniParser The MIT License (MIT), see file LICENSE */ #include "StrTools.h" //http://stackoverflow.com/questions/1798112/removing-leading-and-trailing-spaces-from-a-string string StrTools::trim(const string& str) { const string whitespace = " \t"; const auto strBegin = str.find_first_not_of(whitespace); if (strBegin == string::npos) return ""; // no content const auto strEnd = str.find_last_not_of(whitespace); const auto strRange = strEnd - strBegin + 1; return str.substr(strBegin, strRange); } string StrTools::trimLeft(const string& str) { const auto strBegin = str.find_first_not_of(" \t"); if (strBegin == string::npos) return ""; // no content return str.substr(strBegin, str.length() - strBegin); } string StrTools::trimRight(const string& str) { const auto strEnd = str.find_last_not_of(" \t"); if (strEnd == string::npos) return ""; // no content return str.substr(0, strEnd + 1); } <commit_msg>trim \r at line end because ini can have Windows endings and prog is on Linux<commit_after>/* This file is part of https://github.com/borneq/IniParser The MIT License (MIT), see file LICENSE */ #include "StrTools.h" //http://stackoverflow.com/questions/1798112/removing-leading-and-trailing-spaces-from-a-string string StrTools::trim(const string& str) { const string whitespace = " \t\r"; const auto strBegin = str.find_first_not_of(whitespace); if (strBegin == string::npos) return ""; // no content const auto strEnd = str.find_last_not_of(whitespace); const auto strRange = strEnd - strBegin + 1; return str.substr(strBegin, strRange); } string StrTools::trimLeft(const string& str) { const auto strBegin = str.find_first_not_of(" \t"); if (strBegin == string::npos) return ""; // no content return str.substr(strBegin, str.length() - strBegin); } string StrTools::trimRight(const string& str) { const auto strEnd = str.find_last_not_of(" \t\r"); if (strEnd == string::npos) return ""; // no content return str.substr(0, strEnd + 1); } <|endoftext|>
<commit_before>// // example macro for reconstruction of the TPC raw data // // The path to the Calibration parameters is for the moment hard-wired in the code // Taken from /afs/ // // void recTPC(Int_t type, const char *filename="data.root") { // // Set path to calibration data // // type variable = 0 - cosmic test // = 1 - laser test AliCDBManager * man = AliCDBManager::Instance(); man->SetDefaultStorage("local://$ALICE_ROOT"); man->SetRun(0); man->SetSpecificStorage("TPC","local:///afs/cern.ch/user/m/mivanov/public/Calib"); // // Set reconstruction parameters // AliLog::SetClassDebugLevel("AliTPCclustererMI",2); AliTPCRecoParam * tpcRecoParam = 0; if (type==0) tpcRecoParam = AliTPCRecoParam::GetCosmicTestParam(kTRUE); if (type>0) tpcRecoParam = AliTPCRecoParam::GetLaserTestParam(kTRUE); tpcRecoParam->Dump(); AliTPCReconstructor::SetRecoParam(tpcRecoParam); AliTPCReconstructor::SetStreamLevel(1); // // // AliReconstruction rec; rec.SetSpecificStorage("TPC","local:///afs/cern.ch/user/m/mivanov/public/Calib"); rec.SetLoadAlignData(""); rec.SetWriteESDfriend(kTRUE); rec.SetInput(filename); rec.SetEquipmentIdMap("EquipmentIdMap.data"); rec.SetRunReconstruction("TPC"); rec.SetOption("TPC","PedestalSubtraction OldRCUFormat"); // rec.SetRunLocalReconstruction(""); // rec.SetRunTracking("TPC"); rec.SetFillESD("TPC"); rec.SetFillTriggerESD(kFALSE); rec.SetRunVertexFinder(kFALSE); AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 2, 1., 10., 1); AliTracker::SetFieldMap(field,1); rec.SetWriteAlignmentData(kTRUE); rec.Run(); } void recTracking(Int_t type, const char *filename="data.root", Int_t nevents=1) { // // Set path to calibration data // AliCDBManager * man = AliCDBManager::Instance(); man->SetDefaultStorage("local://$ALICE_ROOT"); man->SetRun(0); man->SetSpecificStorage("TPC","local:///afs/cern.ch/user/m/mivanov/public/Calib"); // // Set reconstruction parameters // AliLog::SetClassDebugLevel("AliTPCclustererMI",2); AliTPCRecoParam * tpcRecoParam = 0; if (type==0) tpcRecoParam = AliTPCRecoParam::GetCosmicTestParam(kTRUE); if (type>0) tpcRecoParam = AliTPCRecoParam::GetLaserTestParam(kTRUE); AliTPCReconstructor::SetRecoParam(tpcRecoParam); AliTPCReconstructor::SetStreamLevel(1); // // // AliReconstruction rec; //rec.SetSpecificStorage("TPC","local:///afs/cern.ch/user/m/mivanov/public/Calib"); rec.SetLoadAlignData(""); rec.SetWriteESDfriend(kTRUE); rec.SetInput(filename); rec.SetEquipmentIdMap("EquipmentIdMap.data"); //rec.SetRunReconstruction("TPC"); rec.SetOption("TPC","PedestalSubtraction OldRCUFormat"); rec.SetRunLocalReconstruction(""); rec.SetRunTracking("TPC"); rec.SetFillESD("TPC"); rec.SetFillTriggerESD(kFALSE); rec.SetRunVertexFinder(kFALSE); AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 2, 1., 10., 1); AliTracker::SetFieldMap(field,1); rec.SetWriteAlignmentData(kTRUE); rec.Run(0,nevents); } <commit_msg>Changes due change of the CalibDB interface (Marian)<commit_after>// // example macro for reconstruction of the TPC raw data // // The path to the Calibration parameters is for the moment hard-wired in the code // Taken from /afs/ // // void recTPC(Int_t type, const char *filename="data.root") { // // Set path to calibration data // // type variable = 0 - cosmic test // = 1 - laser test AliCDBManager * man = AliCDBManager::Instance(); man->SetDefaultStorage("local://$ALICE_ROOT"); man->SetRun(0); man->SetSpecificStorage("TPC/*/*","local:///afs/cern.ch/user/m/mivanov/public/Calib"); // // Set reconstruction parameters // AliLog::SetClassDebugLevel("AliTPCclustererMI",2); AliTPCRecoParam * tpcRecoParam = 0; if (type==0) tpcRecoParam = AliTPCRecoParam::GetCosmicTestParam(kTRUE); if (type>0) tpcRecoParam = AliTPCRecoParam::GetLaserTestParam(kTRUE); tpcRecoParam->Dump(); AliTPCReconstructor::SetRecoParam(tpcRecoParam); AliTPCReconstructor::SetStreamLevel(1); // // // AliReconstruction rec; rec.SetDefaultStorage("local://$ALICE_ROOT"); rec.SetSpecificStorage("TPC/*/*","local:///afs/cern.ch/user/m/mivanov/public/Calib"); rec.SetLoadAlignData(""); rec.SetWriteESDfriend(kTRUE); rec.SetInput(filename); rec.SetEquipmentIdMap("EquipmentIdMap.data"); rec.SetRunReconstruction("TPC"); rec.SetOption("TPC","PedestalSubtraction OldRCUFormat"); // rec.SetRunLocalReconstruction(""); // rec.SetRunTracking("TPC"); rec.SetFillESD("TPC"); rec.SetFillTriggerESD(kFALSE); rec.SetRunVertexFinder(kFALSE); AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 2, 1., 10., 1); AliTracker::SetFieldMap(field,1); rec.SetWriteAlignmentData(kTRUE); rec.Run(); } void recTracking(Int_t type, const char *filename="data.root", Int_t nevents=1) { // // Set path to calibration data // AliCDBManager * man = AliCDBManager::Instance(); man->SetDefaultStorage("local://$ALICE_ROOT"); man->SetRun(0); man->SetSpecificStorage("TPC/*/*","local:///afs/cern.ch/user/m/mivanov/public/Calib"); // // Set reconstruction parameters // AliLog::SetClassDebugLevel("AliTPCclustererMI",2); AliTPCRecoParam * tpcRecoParam = 0; if (type==0) tpcRecoParam = AliTPCRecoParam::GetCosmicTestParam(kTRUE); if (type>0) tpcRecoParam = AliTPCRecoParam::GetLaserTestParam(kTRUE); AliTPCReconstructor::SetRecoParam(tpcRecoParam); AliTPCReconstructor::SetStreamLevel(1); // // // AliReconstruction rec; rec.SetSpecificStorage("TPC/*/*","local:///afs/cern.ch/user/m/mivanov/public/Calib"); rec.SetLoadAlignData(""); rec.SetWriteESDfriend(kTRUE); rec.SetInput(filename); rec.SetEquipmentIdMap("EquipmentIdMap.data"); //rec.SetRunReconstruction("TPC"); rec.SetOption("TPC","PedestalSubtraction OldRCUFormat"); rec.SetRunLocalReconstruction(""); rec.SetRunTracking("TPC"); rec.SetFillESD("TPC"); rec.SetFillTriggerESD(kFALSE); rec.SetRunVertexFinder(kFALSE); AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 2, 1., 10., 1); AliTracker::SetFieldMap(field,1); rec.SetWriteAlignmentData(kTRUE); rec.Run(0,nevents); } <|endoftext|>
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "jvm_callback_op.h" #include "exception.h" #include "utilities.h" #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/c/c_api.h" #include "tensorflow/c/c_api_internal.h" #include "tensorflow/c/eager/c_api.h" #include "tensorflow/c/eager/c_api_internal.h" #include "tensorflow/core/common_runtime/eager/tensor_handle.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/kernel_def.pb_text.h" #include "tensorflow/core/framework/common_shape_fns.h" #include "tensorflow/core/lib/core/coding.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/platform/macros.h" #include "tensorflow/core/platform/mutex.h" namespace tensorflow { REGISTER_OP("JVMCallback") .Input("input: Tin") .Output("output: Tout") .Attr("id: int") .Attr("jvm_pointer: string") .Attr("registry_pointer: string") .Attr("Tin: list(type) >= 0") .Attr("Tout: list(type) >=0") .SetIsStateful() .SetShapeFn(shape_inference::UnknownShape) .Doc(R"doc( Invokes a JVM callback function, `f` to compute `f(input)->output`. This operation is considered stateful. For a stateless version, see `JVMCallback`. id: A unique ID representing a registered JVM callback function in this address space. jvm_pointer: A pointer to an existing JVM instance represented as a string. This is the JVM that will be used when invoking this JVM callback. registry_pointer: Pointer to the JVM callbacks registry class. input: List of tensors that will provide input to the op. output: Output tensors from the op. Tin: Data types of the inputs to the op. Tout: Data types of the outputs from the op. The length of the list specifies the number of outputs. )doc"); REGISTER_OP("JVMCallbackStateless") .Input("input: Tin") .Output("output: Tout") .Attr("id: int") .Attr("jvm_pointer: string") .Attr("registry_pointer: string") .Attr("Tin: list(type) >= 0") .Attr("Tout: list(type) >= 0") .SetShapeFn(shape_inference::UnknownShape) .Doc(R"doc( A stateless version of `JVMCallback`. )doc"); namespace { // Given the 'call', prepares the inputs as a JNI long array that is appropriate for calling the registry. jlongArray MakeInputs(JVMCall* call) { unsigned long n = call->inputs.size(); jlongArray inputs = call->env->NewLongArray(static_cast<jsize>(n)); jlong* inputs_array = call->env->GetLongArrayElements(inputs, nullptr); for (int64 i = 0; i < n; ++i) { const Tensor& t = call->inputs[i]; TFE_TensorHandle* tensor; // if (call->gpu) { // // TODO: Obtain the device from the tensor itself, rather than from the call. // tensor = new TFE_TensorHandle(t, call->device, call->device); // } else { // tensor = new TFE_TensorHandle(t, nullptr, nullptr); // } tensor = new TFE_TensorHandle(t, nullptr, nullptr); inputs_array[i] = reinterpret_cast<jlong>(tensor); } call->env->ReleaseLongArrayElements(inputs, inputs_array, 0); return inputs; } // Process the return values by converting them back to TensorFlow tensors and adding them to the call outputs. void ProcessOutputs(JVMCall* call, jlongArray call_outputs, TF_Status* status) { call->outputs.clear(); jsize n = call->env->GetArrayLength(call_outputs); jlong* outputs_array = call->env->GetLongArrayElements(call_outputs, nullptr); for (int i = 0; i < n; ++i) { static_assert(sizeof(jlong) >= sizeof(TFE_TensorHandle*), "Cannot package C object pointers as a Java long"); if (outputs_array[i] == 0) { status->status = errors::InvalidArgument("One of the op output tensors has been disposed already."); return; } auto* h = reinterpret_cast<TFE_TensorHandle*>(outputs_array[i]); if (h == nullptr) { status->status = errors::InvalidArgument("Could not obtain tensor handle to one of the outputs."); return; } if (!status->status.ok()) return; const tensorflow::Tensor* t = nullptr; status->status = h->handle->Tensor(&t); call->outputs.push_back(*t); } call->env->ReleaseLongArrayElements(call_outputs, outputs_array, 0); } // Calls the registered JVM function through the registry. Status CallJVMFunction(JVMCall* call) { // Prepare the call arguments. jlongArray call_inputs = MakeInputs(call); // Invoke the registry 'call' method. if (call->registry != nullptr && call->call_method_id != nullptr) { auto outputs = (jlongArray) call->env->CallStaticObjectMethod( call->registry, call->call_method_id, call->id, call_inputs); jthrowable exc(call->env->ExceptionOccurred()); call->env->ExceptionClear(); if (exc) { // Get the exception string representation to use as the error message. jclass throwableCls(call->env->FindClass("java/lang/Throwable")); jmethodID toString = call->env->GetMethodID(throwableCls, "toString", "()Ljava/lang/String;"); jstring exc_string = (jstring) call->env->CallObjectMethod(exc, toString); const char* c_exc_string = call->env->GetStringUTFChars(exc_string, 0); tensorflow::StringPiece tf_exc_string(c_exc_string); call->env->ReleaseStringUTFChars(exc_string, c_exc_string); // Get the exception class name and convert it to a TensorFlow error code. jclass excObjCls(call->env->GetObjectClass(exc)); jclass classCls(call->env->FindClass("java/lang/Class")); jmethodID getName(call->env->GetMethodID(classCls, "getName", "()Ljava/lang/String;")); jstring clsName(static_cast<jstring>(call->env->CallObjectMethod(excObjCls, getName))); const char* clsNameCString = call->env->GetStringUTFChars(clsName, 0); std::string clsNameCppString(clsNameCString); int error_code = tf_error_code(clsNameCppString); call->env->ReleaseStringUTFChars(clsName, clsNameCString); return tensorflow::Status((tensorflow::error::Code) error_code, tf_exc_string); } if (outputs == nullptr) { return errors::Unknown("Failed to run JVM callback function."); } // Process the return values and convert them back to TensorFlow tensors. auto* status = new TF_Status; ProcessOutputs(call, outputs, status); return status->status; } else { return errors::Unknown("Failed to run JVM callback function. Could not find registry class or its 'call' method."); } } struct JVMWrapper { JavaVM* jvm_; mutex lock; JVMWrapper(JavaVM* jvm_) : jvm_(jvm_) { } }; static std::vector<JVMWrapper*> jvms; struct JVMThreadHelper { JNIEnv* env; JavaVM* jvm_; JVMThreadHelper() : jvm_(nullptr) { } ~JVMThreadHelper() { if (jvm_ != nullptr) jvm_->DetachCurrentThread(); } void set_jvm(JavaVM* jvm) { if (jvm_ != nullptr) { if (jvm_ != jvm) throw "Multiple JVMs detected per thread."; return; } jvm_ = jvm; int jvmEnvStatus = jvm_->GetEnv((void**) &env, JNI_VERSION_1_6); if (jvmEnvStatus == JNI_EDETACHED) jvm_->AttachCurrentThread((void**) &env, nullptr); } }; JVMWrapper& get_jvm_wrapper(JavaVM* jvm_) { for (JVMWrapper* wrapper : jvms) if (wrapper->jvm_ == jvm_) return *wrapper; /* the JVM isn't in the array */ jvms.push_back(new JVMWrapper(jvm_)); return **jvms.rbegin(); } thread_local JVMThreadHelper jvm_thread; } // namespace class JVMCallbackOp : public OpKernel { public: explicit JVMCallbackOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("id", &id_)); std::string jvm_pointer; OP_REQUIRES_OK(ctx, ctx->GetAttr("jvm_pointer", &jvm_pointer)); jvm_ = pointerFromString<JavaVM*>(jvm_pointer); mutex_lock l(get_jvm_wrapper(jvm_).lock); jvm_thread.set_jvm(jvm_); JNIEnv* env = jvm_thread.env; std::string registry_pointer; OP_REQUIRES_OK(ctx, ctx->GetAttr("registry_pointer", &registry_pointer)); registry_ = pointerFromString<jclass>(registry_pointer); call_method_id_ = env->GetStaticMethodID(registry_, "call", "(I[J)[J"); gpu_ = ctx->device_type().type_string() == DEVICE_GPU; } void Compute(OpKernelContext* ctx) override { mutex_lock l(get_jvm_wrapper(jvm_).lock); jvm_thread.set_jvm(jvm_); JNIEnv* env = jvm_thread.env; JVMCall call; call.env = env; call.registry = registry_; call.call_method_id = call_method_id_; call.device = dynamic_cast<Device*>(ctx->device()); call.gpu = gpu_; call.id = id_; for (int i = 0; i < ctx->num_inputs(); ++i) { call.inputs.push_back(ctx->input(i)); } Status s = CallJVMFunction(&call); OP_REQUIRES_OK(ctx, s); OP_REQUIRES(ctx, static_cast<int32>(call.outputs.size()) == ctx->num_outputs(), errors::InvalidArgument(id_, " returns ", call.outputs.size(), " values, but expects to see ", ctx->num_outputs(), " values.")); for (size_t i = 0; i < call.outputs.size(); ++i) { const auto& t = call.outputs[i]; OP_REQUIRES( ctx, t.dtype() == output_type(i), errors::InvalidArgument(i, "-th value returned by ", id_, " is ", DataTypeString(t.dtype()), ", but expects ", DataTypeString(output_type(i)))); ctx->set_output(i, t); } } private: int id_; JavaVM* jvm_; jclass registry_; jmethodID call_method_id_; // True if and only if this op has been placed on a GPU. bool gpu_; TF_DISALLOW_COPY_AND_ASSIGN(JVMCallbackOp); }; namespace kernel_factory { struct KernelRegistration { KernelRegistration(const KernelDef& d, StringPiece c, kernel_factory::OpKernelRegistrar::Factory f) : def(d), kernel_class_name(c.ToString()), factory(f) {} const KernelDef def; const string kernel_class_name; const kernel_factory::OpKernelRegistrar::Factory factory; }; auto jvmCallbackOpInitializer = []{ auto* reg = reinterpret_cast<std::unordered_multimap<string, KernelRegistration>*>(GlobalKernelRegistry()); if (reg->find(strings::StrCat("JVMCallback:", DeviceTypeString(DEVICE_CPU), ":")) == reg->end()) { REGISTER_KERNEL_BUILDER(Name("JVMCallback").Device(DEVICE_CPU), JVMCallbackOp); REGISTER_KERNEL_BUILDER(Name("JVMCallbackStateless").Device(DEVICE_CPU), JVMCallbackOp); } if (reg->find(strings::StrCat("JVMCallback:", DeviceTypeString(DEVICE_GPU), ":")) == reg->end()) { REGISTER_KERNEL_BUILDER(Name("JVMCallback").Device(DEVICE_GPU), JVMCallbackOp); REGISTER_KERNEL_BUILDER(Name("JVMCallbackStateless").Device(DEVICE_GPU), JVMCallbackOp); } return 0; }(); } } // namespace tensorflow <commit_msg>[JNI] Temporary bug fix.<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "jvm_callback_op.h" #include "exception.h" #include "utilities.h" #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/c/c_api.h" #include "tensorflow/c/c_api_internal.h" #include "tensorflow/c/eager/c_api.h" #include "tensorflow/c/eager/c_api_internal.h" #include "tensorflow/core/common_runtime/eager/tensor_handle.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/kernel_def.pb_text.h" #include "tensorflow/core/framework/common_shape_fns.h" #include "tensorflow/core/lib/core/coding.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/platform/macros.h" #include "tensorflow/core/platform/mutex.h" namespace tensorflow { REGISTER_OP("JVMCallback") .Input("input: Tin") .Output("output: Tout") .Attr("id: int") .Attr("jvm_pointer: string") .Attr("registry_pointer: string") .Attr("Tin: list(type) >= 0") .Attr("Tout: list(type) >=0") .SetIsStateful() .SetShapeFn(shape_inference::UnknownShape) .Doc(R"doc( Invokes a JVM callback function, `f` to compute `f(input)->output`. This operation is considered stateful. For a stateless version, see `JVMCallback`. id: A unique ID representing a registered JVM callback function in this address space. jvm_pointer: A pointer to an existing JVM instance represented as a string. This is the JVM that will be used when invoking this JVM callback. registry_pointer: Pointer to the JVM callbacks registry class. input: List of tensors that will provide input to the op. output: Output tensors from the op. Tin: Data types of the inputs to the op. Tout: Data types of the outputs from the op. The length of the list specifies the number of outputs. )doc"); REGISTER_OP("JVMCallbackStateless") .Input("input: Tin") .Output("output: Tout") .Attr("id: int") .Attr("jvm_pointer: string") .Attr("registry_pointer: string") .Attr("Tin: list(type) >= 0") .Attr("Tout: list(type) >= 0") .SetShapeFn(shape_inference::UnknownShape) .Doc(R"doc( A stateless version of `JVMCallback`. )doc"); namespace { // Given the 'call', prepares the inputs as a JNI long array that is appropriate for calling the registry. jlongArray MakeInputs(JVMCall* call) { unsigned long n = call->inputs.size(); jlongArray inputs = call->env->NewLongArray(static_cast<jsize>(n)); jlong* inputs_array = call->env->GetLongArrayElements(inputs, nullptr); for (int64 i = 0; i < n; ++i) { const Tensor& t = call->inputs[i]; TFE_TensorHandle* tensor; // if (call->gpu) { // // TODO: !!! [CALLBACK] Obtain the device from the tensor itself, rather than from the call. // tensor = new TFE_TensorHandle(t, call->device, call->device); // } else { // tensor = new TFE_TensorHandle(t, nullptr, nullptr); // } tensor = new TFE_TensorHandle(t, nullptr, nullptr); inputs_array[i] = reinterpret_cast<jlong>(tensor); } call->env->ReleaseLongArrayElements(inputs, inputs_array, 0); return inputs; } // Process the return values by converting them back to TensorFlow tensors and adding them to the call outputs. void ProcessOutputs(JVMCall* call, jlongArray call_outputs, TF_Status* status) { call->outputs.clear(); jsize n = call->env->GetArrayLength(call_outputs); jlong* outputs_array = call->env->GetLongArrayElements(call_outputs, nullptr); for (int i = 0; i < n; ++i) { static_assert(sizeof(jlong) >= sizeof(TFE_TensorHandle*), "Cannot package C object pointers as a Java long"); if (outputs_array[i] == 0) { status->status = errors::InvalidArgument("One of the op output tensors has been disposed already."); return; } auto* h = reinterpret_cast<TFE_TensorHandle*>(outputs_array[i]); if (h == nullptr) { status->status = errors::InvalidArgument("Could not obtain tensor handle to one of the outputs."); return; } if (!status->status.ok()) return; const tensorflow::Tensor* t = nullptr; status->status = h->handle->Tensor(&t); call->outputs.push_back(*t); } call->env->ReleaseLongArrayElements(call_outputs, outputs_array, 0); } // Calls the registered JVM function through the registry. Status CallJVMFunction(JVMCall* call) { // Prepare the call arguments. jlongArray call_inputs = MakeInputs(call); // Invoke the registry 'call' method. if (call->registry != nullptr && call->call_method_id != nullptr) { auto outputs = (jlongArray) call->env->CallStaticObjectMethod( call->registry, call->call_method_id, call->id, call_inputs); jthrowable exc(call->env->ExceptionOccurred()); call->env->ExceptionClear(); if (exc) { // Get the exception string representation to use as the error message. jclass throwableCls(call->env->FindClass("java/lang/Throwable")); jmethodID toString = call->env->GetMethodID(throwableCls, "toString", "()Ljava/lang/String;"); jstring exc_string = (jstring) call->env->CallObjectMethod(exc, toString); const char* c_exc_string = call->env->GetStringUTFChars(exc_string, 0); tensorflow::StringPiece tf_exc_string(c_exc_string); call->env->ReleaseStringUTFChars(exc_string, c_exc_string); // Get the exception class name and convert it to a TensorFlow error code. jclass excObjCls(call->env->GetObjectClass(exc)); jclass classCls(call->env->FindClass("java/lang/Class")); jmethodID getName(call->env->GetMethodID(classCls, "getName", "()Ljava/lang/String;")); jstring clsName(static_cast<jstring>(call->env->CallObjectMethod(excObjCls, getName))); const char* clsNameCString = call->env->GetStringUTFChars(clsName, 0); std::string clsNameCppString(clsNameCString); int error_code = tf_error_code(clsNameCppString); call->env->ReleaseStringUTFChars(clsName, clsNameCString); return tensorflow::Status((tensorflow::error::Code) error_code, tf_exc_string); } if (outputs == nullptr) { return errors::Unknown("Failed to run JVM callback function."); } // Process the return values and convert them back to TensorFlow tensors. auto* status = new TF_Status; ProcessOutputs(call, outputs, status); return status->status; } else { return errors::Unknown("Failed to run JVM callback function. Could not find registry class or its 'call' method."); } } struct JVMWrapper { JavaVM* jvm_; mutex lock; JVMWrapper(JavaVM* jvm_) : jvm_(jvm_) { } }; static std::vector<JVMWrapper*> jvms; struct JVMThreadHelper { JNIEnv* env; JavaVM* jvm_; JVMThreadHelper() : jvm_(nullptr) { } ~JVMThreadHelper() { if (jvm_ != nullptr) jvm_->DetachCurrentThread(); } void set_jvm(JavaVM* jvm) { if (jvm_ != nullptr) { if (jvm_ != jvm) throw "Multiple JVMs detected per thread."; return; } jvm_ = jvm; int jvmEnvStatus = jvm_->GetEnv((void**) &env, JNI_VERSION_1_6); if (jvmEnvStatus == JNI_EDETACHED) jvm_->AttachCurrentThread((void**) &env, nullptr); } }; JVMWrapper& get_jvm_wrapper(JavaVM* jvm_) { for (JVMWrapper* wrapper : jvms) if (wrapper->jvm_ == jvm_) return *wrapper; /* the JVM isn't in the array */ jvms.push_back(new JVMWrapper(jvm_)); return **jvms.rbegin(); } thread_local JVMThreadHelper jvm_thread; } // namespace class JVMCallbackOp : public OpKernel { public: explicit JVMCallbackOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("id", &id_)); std::string jvm_pointer; OP_REQUIRES_OK(ctx, ctx->GetAttr("jvm_pointer", &jvm_pointer)); jvm_ = pointerFromString<JavaVM*>(jvm_pointer); mutex_lock l(get_jvm_wrapper(jvm_).lock); jvm_thread.set_jvm(jvm_); JNIEnv* env = jvm_thread.env; std::string registry_pointer; OP_REQUIRES_OK(ctx, ctx->GetAttr("registry_pointer", &registry_pointer)); registry_ = pointerFromString<jclass>(registry_pointer); call_method_id_ = env->GetStaticMethodID(registry_, "call", "(I[J)[J"); gpu_ = ctx->device_type().type_string() == DEVICE_GPU; } void Compute(OpKernelContext* ctx) override { mutex_lock l(get_jvm_wrapper(jvm_).lock); jvm_thread.set_jvm(jvm_); JNIEnv* env = jvm_thread.env; JVMCall call; call.env = env; call.registry = registry_; call.call_method_id = call_method_id_; call.device = dynamic_cast<Device*>(ctx->device()); call.gpu = gpu_; call.id = id_; for (int i = 0; i < ctx->num_inputs(); ++i) { call.inputs.push_back(ctx->input(i)); } Status s = CallJVMFunction(&call); OP_REQUIRES_OK(ctx, s); OP_REQUIRES(ctx, static_cast<int32>(call.outputs.size()) == ctx->num_outputs(), errors::InvalidArgument(id_, " returns ", call.outputs.size(), " values, but expects to see ", ctx->num_outputs(), " values.")); for (size_t i = 0; i < call.outputs.size(); ++i) { const auto& t = call.outputs[i]; OP_REQUIRES( ctx, t.dtype() == output_type(i), errors::InvalidArgument(i, "-th value returned by ", id_, " is ", DataTypeString(t.dtype()), ", but expects ", DataTypeString(output_type(i)))); ctx->set_output(i, t); } } private: int id_; JavaVM* jvm_; jclass registry_; jmethodID call_method_id_; // True if and only if this op has been placed on a GPU. bool gpu_; TF_DISALLOW_COPY_AND_ASSIGN(JVMCallbackOp); }; namespace kernel_factory { struct KernelRegistration { KernelRegistration(const KernelDef& d, StringPiece c, kernel_factory::OpKernelRegistrar::Factory f) : def(d), kernel_class_name(c.ToString()), factory(f) {} const KernelDef def; const string kernel_class_name; const kernel_factory::OpKernelRegistrar::Factory factory; }; auto jvmCallbackOpInitializer = []{ auto* reg = reinterpret_cast<std::unordered_multimap<string, KernelRegistration>*>(GlobalKernelRegistry()); if (reg->find(strings::StrCat("JVMCallback:", DeviceTypeString(DEVICE_CPU), ":")) == reg->end()) { REGISTER_KERNEL_BUILDER(Name("JVMCallback").Device(DEVICE_CPU), JVMCallbackOp); REGISTER_KERNEL_BUILDER(Name("JVMCallbackStateless").Device(DEVICE_CPU), JVMCallbackOp); } // TODO: !!! [CALLBACK] Temporary. // if (reg->find(strings::StrCat("JVMCallback:", DeviceTypeString(DEVICE_GPU), ":")) == reg->end()) { // REGISTER_KERNEL_BUILDER(Name("JVMCallback").Device(DEVICE_GPU), JVMCallbackOp); // REGISTER_KERNEL_BUILDER(Name("JVMCallbackStateless").Device(DEVICE_GPU), JVMCallbackOp); // } return 0; }(); } } // namespace tensorflow <|endoftext|>
<commit_before>// casnddrv.cpp // CoreAudio (MacOS X) Sound Driver for Crystal Space // // Created by mreda on Sun Nov 11 2001. // Copyright (c) 2001 Matt Reda. All rights reserved. #include "cssysdef.h" #include "csver.h" #include "cssys/sysfunc.h" #include "csutil/scf.h" #include "ivaria/reporter.h" #include "iutil/objreg.h" #include "isound/renderer.h" #include "casnddrv.h" #define SAMPLES_PER_BUFFER (8 * 1024) CS_IMPLEMENT_PLUGIN SCF_IMPLEMENT_FACTORY(csSoundDriverCoreAudio); SCF_EXPORT_CLASS_TABLE(casnddrv) SCF_EXPORT_CLASS (csSoundDriverCoreAudio, "crystalspace.sound.driver.coreaudio", "Crystal Space CoreAudio Sound driver for MacOS X") SCF_EXPORT_CLASS_TABLE_END SCF_IMPLEMENT_IBASE(csSoundDriverCoreAudio) SCF_IMPLEMENTS_INTERFACE(iSoundDriver) SCF_IMPLEMENTS_EMBEDDED_INTERFACE(iComponent) SCF_IMPLEMENT_IBASE_END; SCF_IMPLEMENT_EMBEDDED_IBASE(csSoundDriverCoreAudio::eiComponent) SCF_IMPLEMENTS_INTERFACE(iComponent) SCF_IMPLEMENT_EMBEDDED_IBASE_END // CoreAudio IO proc static OSStatus AudioProc(AudioDeviceID inDevice, const AudioTimeStamp *inNow, const AudioBufferList *inInputData, const AudioTimeStamp *inInputTime, AudioBufferList *outOutputData, const AudioTimeStamp *inOutputTime, void *inClientData); // Constructor csSoundDriverCoreAudio::csSoundDriverCoreAudio(iBase *base) { SCF_CONSTRUCT_IBASE(base); SCF_CONSTRUCT_EMBEDDED_IBASE(scfiComponent); reg = NULL; soundRender = NULL; memory = NULL; memorySize = 0; frequency = 0; is16Bit = false; isStereo = false; isPlaying = false; } // Destructor csSoundDriverCoreAudio::~csSoundDriverCoreAudio() { if (isPlaying == true) Close(); } // Open // Open the driver and begin playing bool csSoundDriverCoreAudio::Open(iSoundRender *render, int freq, bool bit16, bool stereo) { // Report driver information csReport(reg, CS_REPORTER_SEVERITY_NOTIFY, CS_SOUND_DRIVER, CS_PLATFORM_NAME " CoreAudio sound driver for Crystal Space " CS_VERSION_NUMBER "\nWritten by Matt Reda <[email protected]>"); OSStatus status; UInt32 propertySize, bufferSize; // bufferSize is in bytes AudioStreamBasicDescription outStreamDesc; // Get output device propertySize = sizeof(audioDevice); status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &propertySize, &audioDevice); if ((status != 0) || (audioDevice == kAudioDeviceUnknown)) return false; // Set buffer size propertySize = sizeof(bufferSize); bufferSize = SAMPLES_PER_BUFFER * sizeof(float); status = AudioDeviceSetProperty(audioDevice, NULL, 0, false, kAudioDevicePropertyBufferSize, propertySize, &bufferSize); if (status != 0) return false; // Get stream information propertySize = sizeof(outStreamDesc); status = AudioDeviceGetProperty(audioDevice, 0, false, kAudioDevicePropertyStreamFormat, &propertySize, &outStreamDesc); if (status != 0) return false; // Creation went ok, copy to local variables soundRender = render; isStereo = true; is16Bit = true; frequency = (int) outStreamDesc.mSampleRate; // Allocate memory memorySize = SAMPLES_PER_BUFFER * sizeof(short); memory = (short *) malloc(memorySize); // Add callback status = AudioDeviceAddIOProc(audioDevice, AudioProc, this); if (status != 0) return false; // Begin playback status = AudioDeviceStart(audioDevice, AudioProc); if (status != 0) return false; return true; } // Close // Stop playback and clean up void csSoundDriverCoreAudio::Close() { if (isPlaying == true) { OSStatus status; status = AudioDeviceStop(audioDevice, AudioProc); if (status != 0) return; status = AudioDeviceRemoveIOProc(audioDevice, AudioProc); if (status != 0) return; free(memory); memorySize = 0; isPlaying = false; }; } // LockMemory // Return memor buffer and size void csSoundDriverCoreAudio::LockMemory(void **mem, int *memsize) { *mem = memory; *memsize = memorySize; } // UnlockMemory void csSoundDriverCoreAudio::UnlockMemory() { // Do nothing } // IsBackground // Return true to indicate driver can play in background bool csSoundDriverCoreAudio::IsBackground() { return true; } // Is16Bits // Return whether or not driver is set up for 16 bit playback bool csSoundDriverCoreAudio::Is16Bits() { return is16Bit; } // IsStereo // Indicate whether the driver is set up for stereo playback bool csSoundDriverCoreAudio::IsStereo() { return isStereo; } // GetFrequency // Return playback frequency int csSoundDriverCoreAudio::GetFrequency() { return frequency; } // IsHandleVoidSound // Return false to indicate driver needs input to create silence bool csSoundDriverCoreAudio::IsHandleVoidSound() { return false; } // CreateSamples // Ask the renderer for samples, and then scale them void csSoundDriverCoreAudio::CreateSamples(float *buffer) { // Create new samples soundRender->MixingFunction(); // Copy and scale Crystal Space samples to float the CoreAudio can use for (int i = 0; i < SAMPLES_PER_BUFFER; i++) buffer[i] = memory[i] * (1.0f / SHRT_MAX); }; // AudioProc // Create samples in output buffer - that will be played automatically static OSStatus AudioProc(AudioDeviceID inDevice, const AudioTimeStamp *inNow, const AudioBufferList *inInputData, const AudioTimeStamp *inInputTime, AudioBufferList *outOutputData, const AudioTimeStamp *inOutputTime, void *inClientData) { csSoundDriverCoreAudio *driver = (csSoundDriverCoreAudio *) inClientData; float *buffer = (float *) outOutputData->mBuffers[0].mData; driver->CreateSamples(buffer); return 0; }; <commit_msg>Fixed small bug that prevented the freeing of resources when the driver is closed<commit_after>// casnddrv.cpp // CoreAudio (MacOS X) Sound Driver for Crystal Space // // Created by mreda on Sun Nov 11 2001. // Copyright (c) 2001 Matt Reda. All rights reserved. #include "cssysdef.h" #include "csver.h" #include "cssys/sysfunc.h" #include "csutil/scf.h" #include "ivaria/reporter.h" #include "iutil/objreg.h" #include "isound/renderer.h" #include "casnddrv.h" #define SAMPLES_PER_BUFFER (8 * 1024) CS_IMPLEMENT_PLUGIN SCF_IMPLEMENT_FACTORY(csSoundDriverCoreAudio); SCF_EXPORT_CLASS_TABLE(casnddrv) SCF_EXPORT_CLASS (csSoundDriverCoreAudio, "crystalspace.sound.driver.coreaudio", "Crystal Space CoreAudio Sound driver for MacOS X") SCF_EXPORT_CLASS_TABLE_END SCF_IMPLEMENT_IBASE(csSoundDriverCoreAudio) SCF_IMPLEMENTS_INTERFACE(iSoundDriver) SCF_IMPLEMENTS_EMBEDDED_INTERFACE(iComponent) SCF_IMPLEMENT_IBASE_END; SCF_IMPLEMENT_EMBEDDED_IBASE(csSoundDriverCoreAudio::eiComponent) SCF_IMPLEMENTS_INTERFACE(iComponent) SCF_IMPLEMENT_EMBEDDED_IBASE_END // CoreAudio IO proc static OSStatus AudioProc(AudioDeviceID inDevice, const AudioTimeStamp *inNow, const AudioBufferList *inInputData, const AudioTimeStamp *inInputTime, AudioBufferList *outOutputData, const AudioTimeStamp *inOutputTime, void *inClientData); // Constructor csSoundDriverCoreAudio::csSoundDriverCoreAudio(iBase *base) { SCF_CONSTRUCT_IBASE(base); SCF_CONSTRUCT_EMBEDDED_IBASE(scfiComponent); reg = NULL; soundRender = NULL; memory = NULL; memorySize = 0; frequency = 0; is16Bit = false; isStereo = false; isPlaying = false; } // Destructor csSoundDriverCoreAudio::~csSoundDriverCoreAudio() { if (isPlaying == true) Close(); } // Open // Open the driver and begin playing bool csSoundDriverCoreAudio::Open(iSoundRender *render, int freq, bool bit16, bool stereo) { // Report driver information csReport(reg, CS_REPORTER_SEVERITY_NOTIFY, CS_SOUND_DRIVER, CS_PLATFORM_NAME " CoreAudio sound driver for Crystal Space " CS_VERSION_NUMBER "\nWritten by Matt Reda <[email protected]>"); OSStatus status; UInt32 propertySize, bufferSize; // bufferSize is in bytes AudioStreamBasicDescription outStreamDesc; // Get output device propertySize = sizeof(audioDevice); status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &propertySize, &audioDevice); if ((status != 0) || (audioDevice == kAudioDeviceUnknown)) return false; // Set buffer size propertySize = sizeof(bufferSize); bufferSize = SAMPLES_PER_BUFFER * sizeof(float); status = AudioDeviceSetProperty(audioDevice, NULL, 0, false, kAudioDevicePropertyBufferSize, propertySize, &bufferSize); if (status != 0) return false; // Get stream information propertySize = sizeof(outStreamDesc); status = AudioDeviceGetProperty(audioDevice, 0, false, kAudioDevicePropertyStreamFormat, &propertySize, &outStreamDesc); if (status != 0) return false; // Creation went ok, copy to local variables soundRender = render; isStereo = (outStreamDesc.mChannelsPerFrame == 2); is16Bit = true; frequency = (int) outStreamDesc.mSampleRate; // Allocate memory memorySize = SAMPLES_PER_BUFFER * sizeof(short); memory = (short *) malloc(memorySize); // Add callback status = AudioDeviceAddIOProc(audioDevice, AudioProc, this); if (status != 0) return false; // Begin playback status = AudioDeviceStart(audioDevice, AudioProc); if (status != 0) return false; // Indicate that Initialization has completed isPlaying = true; return true; } // Close // Stop playback and clean up void csSoundDriverCoreAudio::Close() { if (isPlaying == true) { OSStatus status; status = AudioDeviceStop(audioDevice, AudioProc); if (status != 0) return; status = AudioDeviceRemoveIOProc(audioDevice, AudioProc); if (status != 0) return; free(memory); memorySize = 0; isPlaying = false; }; } // LockMemory // Return memor buffer and size void csSoundDriverCoreAudio::LockMemory(void **mem, int *memsize) { *mem = memory; *memsize = memorySize; } // UnlockMemory void csSoundDriverCoreAudio::UnlockMemory() { // Do nothing } // IsBackground // Return true to indicate driver can play in background bool csSoundDriverCoreAudio::IsBackground() { return true; } // Is16Bits // Return whether or not driver is set up for 16 bit playback bool csSoundDriverCoreAudio::Is16Bits() { return is16Bit; } // IsStereo // Indicate whether the driver is set up for stereo playback bool csSoundDriverCoreAudio::IsStereo() { return isStereo; } // GetFrequency // Return playback frequency int csSoundDriverCoreAudio::GetFrequency() { return frequency; } // IsHandleVoidSound // Return false to indicate driver needs input to create silence bool csSoundDriverCoreAudio::IsHandleVoidSound() { return false; } // CreateSamples // Ask the renderer for samples, and then scale them void csSoundDriverCoreAudio::CreateSamples(float *buffer) { // Create new samples soundRender->MixingFunction(); // Copy and scale Crystal Space samples to the floats that CoreAudio can use float scaleFactor = 1.0f / SHRT_MAX; for (int i = 0; i < SAMPLES_PER_BUFFER; i++) buffer[i] = memory[i] * scaleFactor; }; // AudioProc // Create samples in output buffer - that will be played automatically static OSStatus AudioProc(AudioDeviceID inDevice, const AudioTimeStamp *inNow, const AudioBufferList *inInputData, const AudioTimeStamp *inInputTime, AudioBufferList *outOutputData, const AudioTimeStamp *inOutputTime, void *inClientData) { csSoundDriverCoreAudio *driver = (csSoundDriverCoreAudio *) inClientData; float *buffer = (float *) outOutputData->mBuffers[0].mData; driver->CreateSamples(buffer); return 0; }; <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2008-2009, 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 <cassert> #include <algorithm> #include "IECoreMaya/Parameter.h" #include "IECoreMaya/ToMayaObjectConverter.h" #include "IECoreMaya/FromMayaObjectConverter.h" #include "IECoreMaya/FloatSplineParameterHandler.h" #include "IECoreMaya/MArrayIter.h" #include "IECore/SplineParameter.h" #include "maya/MFnCompoundAttribute.h" #include "maya/MRampAttribute.h" #include "maya/MFloatArray.h" #include "maya/MIntArray.h" #include "maya/MGlobal.h" #include "maya/MFnDagNode.h" using namespace IECoreMaya; using namespace Imath; using namespace boost; template<> ParameterHandler::Description< FloatSplineParameterHandler< IECore::Splineff > > FloatSplineParameterHandler< IECore::Splineff >::g_registrar( IECore::SplineffParameter::staticTypeId() ); template<> ParameterHandler::Description< FloatSplineParameterHandler< IECore::Splinedd > > FloatSplineParameterHandler< IECore::Splinedd >::g_registrar( IECore::SplineddParameter::staticTypeId() ); template<typename S> MStatus FloatSplineParameterHandler<S>::update( IECore::ConstParameterPtr parameter, MObject &attribute ) const { assert( parameter ); typename IECore::TypedParameter< S >::ConstPtr p = IECore::runTimeCast<const IECore::TypedParameter< S > >( parameter ); if( !p ) { return MS::kFailure; } MFnCompoundAttribute fnCAttr( attribute ); if( !fnCAttr.hasObj( attribute ) ) { return MS::kFailure; } /// \todo See if the attribute is of type CurveRamp - can't do this yet as we can't construct /// an MRampAttribute from just the MObject. We need either the node, too, or an MPlug return MS::kSuccess; } template<typename S> MObject FloatSplineParameterHandler<S>::create( IECore::ConstParameterPtr parameter, const MString &attributeName ) const { assert( parameter ); typename IECore::TypedParameter< S >::ConstPtr p = IECore::runTimeCast<const IECore::TypedParameter< S > >( parameter ); if( !p ) { return MObject::kNullObj; } MRampAttribute fnRAttr; MObject result = fnRAttr.createCurveRamp( attributeName, attributeName ); update( parameter, result ); return result; } template<typename S> MStatus FloatSplineParameterHandler<S>::setValue( IECore::ConstParameterPtr parameter, MPlug &plug ) const { assert( parameter ); typename IECore::TypedParameter< S >::ConstPtr p = IECore::runTimeCast<const IECore::TypedParameter< S > >( parameter ); if( !p ) { return MS::kFailure; } MRampAttribute fnRAttr( plug ); if ( !fnRAttr.isCurveRamp() ) { return MS::kFailure; } const S &spline = p->getTypedValue(); MStatus s; MIntArray indicesToReuse; plug.getExistingArrayAttributeIndices( indicesToReuse, &s ); assert( s ); int nextNewLogicalIndex = 0; if( indicesToReuse.length() ) { nextNewLogicalIndex = 1 + *std::max_element( MArrayIter<MIntArray>::begin( indicesToReuse ), MArrayIter<MIntArray>::end( indicesToReuse ) ); } assert( indicesToReuse.length() == fnRAttr.getNumEntries() ); size_t pointsSizeMinus2 = spline.points.size() - 2; unsigned pointIndex = 0; unsigned numExpectedPoints = 0; for ( typename S::PointContainer::const_iterator it = spline.points.begin(); it != spline.points.end(); ++it, ++pointIndex ) { // we commonly double up the endpoints on cortex splines to force interpolation to the end. // maya does this implicitly, so we skip duplicated endpoints when passing the splines into maya. // this avoids users having to be responsible for managing the duplicates, and gives them some consistency // with the splines they edit elsewhere in maya. if( pointIndex==1 && *it == *spline.points.begin() || pointIndex==pointsSizeMinus2 && *it == *spline.points.rbegin() ) { continue; } MPlug pointPlug; if( indicesToReuse.length() ) { pointPlug = plug.elementByLogicalIndex( indicesToReuse[0] ); indicesToReuse.remove( 0 ); } else { // this creates us a new spline point for us, and avoids the bug in MRampAttribute::addEntries which // somehow manages to create duplicate logical indexes. pointPlug = plug.elementByLogicalIndex( nextNewLogicalIndex++ ); } s = pointPlug.child( 0 ).setValue( it->first ); assert( s ); s = pointPlug.child( 1 ).setValue( it->second ); assert( s ); s = pointPlug.child( 2 ).setValue( MRampAttribute::kSpline ); assert( s ); numExpectedPoints++; } // delete any of the original indices which we didn't reuse. we can't use MRampAttrubute::deleteEntries // here as it's utterly unreliable. if( indicesToReuse.length() ) { MString plugName = plug.name(); MObject node = plug.node(); MFnDagNode fnDAGN( node ); if( fnDAGN.hasObj( node ) ) { plugName = fnDAGN.fullPathName() + "." + plug.partialName(); } for( unsigned i=0; i<indicesToReuse.length(); i++ ) { // using mel because there's no equivalant api method as far as i know. MString command = "removeMultiInstance -b true \"" + plugName + "[" + indicesToReuse[i] + "]\""; s = MGlobal::executeCommand( command ); assert( s ); if( !s ) { return s; } } } #ifndef NDEBUG { MIntArray allLogicalIndices; plug.getExistingArrayAttributeIndices( allLogicalIndices ); assert( fnRAttr.getNumEntries() == numExpectedPoints ); assert( fnRAttr.getNumEntries() == allLogicalIndices.length() ); // the MRampAttribute has the wonderful "feature" that addEntries() is somehow capable // of creating duplicate logical array indices, which causes no end of trouble // down the line. check that we've managed to avoid this pitfall. std::set<int> uniqueIndices; std::copy( MArrayIter<MIntArray>::begin( allLogicalIndices ), MArrayIter<MIntArray>::end( allLogicalIndices ), std::insert_iterator<std::set<int> >( uniqueIndices, uniqueIndices.begin() ) ); assert( uniqueIndices.size()==allLogicalIndices.length() ); // then check that every element of the ramp has a suitable equivalent in // the original spline MIntArray indices; MFloatArray positions; MFloatArray values; MIntArray interps; fnRAttr.getEntries( indices, positions, values, interps, &s ); assert( s ); assert( numExpectedPoints == positions.length() ); assert( numExpectedPoints == values.length() ); assert( numExpectedPoints == interps.length() ); assert( numExpectedPoints == indices.length() ); for ( unsigned i = 0; i < positions.length(); i++ ) { float position = positions[ i ]; float value = values[ i ]; bool found = false; for ( typename S::PointContainer::const_iterator it = spline.points.begin(); it != spline.points.end() && !found; ++it ) { if ( fabs( it->first - position ) < 1.e-3f && fabs( it->second - value ) < 1.e-3f ) { found = true; } } assert( found ); } } #endif return MS::kSuccess; } template<typename S> MStatus FloatSplineParameterHandler<S>::setValue( const MPlug &plug, IECore::ParameterPtr parameter ) const { assert( parameter ); typename IECore::TypedParameter< S >::Ptr p = IECore::runTimeCast<IECore::TypedParameter< S > >( parameter ); if( !p ) { return MS::kFailure; } S spline; MStatus s; MRampAttribute fnRAttr( plug, &s ); assert( s ); if ( !fnRAttr.isCurveRamp() ) { return MS::kFailure; } if ( fnRAttr.getNumEntries( &s ) > 0 ) { assert( s ); MIntArray indices; MFloatArray positions; MFloatArray values; MIntArray interps; fnRAttr.getEntries( indices, positions, values, interps, &s ); assert( s ); if ( positions.length() != values.length() || positions.length() != interps.length() || positions.length() != indices.length() ) { return MS::kFailure; } for ( unsigned i = 0; i < positions.length(); i ++) { spline.points.insert( typename S::PointContainer::value_type( static_cast< typename S::XType >( positions[i] ), static_cast< typename S::YType >( values[ i ] ) ) ); } } // maya seems to do an implicit doubling up of the end points to cause interpolation to the ends. // our spline has no such implicit behaviour so we explicitly double up. if( spline.points.size() ) { #ifndef NDEBUG size_t oldSplineSize = spline.points.size(); #endif assert( spline.points.begin()->first <= spline.points.rbegin()->first ); spline.points.insert( *spline.points.begin() ); spline.points.insert( *spline.points.rbegin() ); assert( spline.points.size() == oldSplineSize + 2 ); } p->setTypedValue( spline ); if( spline.points.size() ) { assert( spline.points.size() >= 2 ); assert( spline.points.size() == fnRAttr.getNumEntries() + 2 ); } return MS::kSuccess; } <commit_msg>Got interpolation working as spline interpolation again.<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2008-2009, 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 <cassert> #include <algorithm> #include "IECoreMaya/Parameter.h" #include "IECoreMaya/ToMayaObjectConverter.h" #include "IECoreMaya/FromMayaObjectConverter.h" #include "IECoreMaya/FloatSplineParameterHandler.h" #include "IECoreMaya/MArrayIter.h" #include "IECore/SplineParameter.h" #include "maya/MFnCompoundAttribute.h" #include "maya/MRampAttribute.h" #include "maya/MFloatArray.h" #include "maya/MIntArray.h" #include "maya/MGlobal.h" #include "maya/MFnDagNode.h" using namespace IECoreMaya; using namespace Imath; using namespace boost; template<> ParameterHandler::Description< FloatSplineParameterHandler< IECore::Splineff > > FloatSplineParameterHandler< IECore::Splineff >::g_registrar( IECore::SplineffParameter::staticTypeId() ); template<> ParameterHandler::Description< FloatSplineParameterHandler< IECore::Splinedd > > FloatSplineParameterHandler< IECore::Splinedd >::g_registrar( IECore::SplineddParameter::staticTypeId() ); template<typename S> MStatus FloatSplineParameterHandler<S>::update( IECore::ConstParameterPtr parameter, MObject &attribute ) const { assert( parameter ); typename IECore::TypedParameter< S >::ConstPtr p = IECore::runTimeCast<const IECore::TypedParameter< S > >( parameter ); if( !p ) { return MS::kFailure; } MFnCompoundAttribute fnCAttr( attribute ); if( !fnCAttr.hasObj( attribute ) ) { return MS::kFailure; } /// \todo See if the attribute is of type CurveRamp - can't do this yet as we can't construct /// an MRampAttribute from just the MObject. We need either the node, too, or an MPlug return MS::kSuccess; } template<typename S> MObject FloatSplineParameterHandler<S>::create( IECore::ConstParameterPtr parameter, const MString &attributeName ) const { assert( parameter ); typename IECore::TypedParameter< S >::ConstPtr p = IECore::runTimeCast<const IECore::TypedParameter< S > >( parameter ); if( !p ) { return MObject::kNullObj; } MRampAttribute fnRAttr; MObject result = fnRAttr.createCurveRamp( attributeName, attributeName ); update( parameter, result ); return result; } template<typename S> MStatus FloatSplineParameterHandler<S>::setValue( IECore::ConstParameterPtr parameter, MPlug &plug ) const { assert( parameter ); typename IECore::TypedParameter< S >::ConstPtr p = IECore::runTimeCast<const IECore::TypedParameter< S > >( parameter ); if( !p ) { return MS::kFailure; } MRampAttribute fnRAttr( plug ); if ( !fnRAttr.isCurveRamp() ) { return MS::kFailure; } const S &spline = p->getTypedValue(); MStatus s; MIntArray indicesToReuse; plug.getExistingArrayAttributeIndices( indicesToReuse, &s ); assert( s ); int nextNewLogicalIndex = 0; if( indicesToReuse.length() ) { nextNewLogicalIndex = 1 + *std::max_element( MArrayIter<MIntArray>::begin( indicesToReuse ), MArrayIter<MIntArray>::end( indicesToReuse ) ); } assert( indicesToReuse.length() == fnRAttr.getNumEntries() ); size_t pointsSizeMinus2 = spline.points.size() - 2; unsigned pointIndex = 0; unsigned numExpectedPoints = 0; for ( typename S::PointContainer::const_iterator it = spline.points.begin(); it != spline.points.end(); ++it, ++pointIndex ) { // we commonly double up the endpoints on cortex splines to force interpolation to the end. // maya does this implicitly, so we skip duplicated endpoints when passing the splines into maya. // this avoids users having to be responsible for managing the duplicates, and gives them some consistency // with the splines they edit elsewhere in maya. if( pointIndex==1 && *it == *spline.points.begin() || pointIndex==pointsSizeMinus2 && *it == *spline.points.rbegin() ) { continue; } MPlug pointPlug; if( indicesToReuse.length() ) { pointPlug = plug.elementByLogicalIndex( indicesToReuse[0] ); indicesToReuse.remove( 0 ); } else { // this creates us a new spline point for us, and avoids the bug in MRampAttribute::addEntries which // somehow manages to create duplicate logical indexes. pointPlug = plug.elementByLogicalIndex( nextNewLogicalIndex++ ); } s = pointPlug.child( 0 ).setValue( it->first ); assert( s ); s = pointPlug.child( 1 ).setValue( it->second ); assert( s ); // hardcoding interpolation of 3 (spline) because the MRampAttribute::MInterpolation enum values don't actually // correspond to the necessary plug values at all. s = pointPlug.child( 2 ).setValue( 3 ); assert( s ); numExpectedPoints++; } // delete any of the original indices which we didn't reuse. we can't use MRampAttrubute::deleteEntries // here as it's utterly unreliable. if( indicesToReuse.length() ) { MString plugName = plug.name(); MObject node = plug.node(); MFnDagNode fnDAGN( node ); if( fnDAGN.hasObj( node ) ) { plugName = fnDAGN.fullPathName() + "." + plug.partialName(); } for( unsigned i=0; i<indicesToReuse.length(); i++ ) { // using mel because there's no equivalant api method as far as i know. MString command = "removeMultiInstance -b true \"" + plugName + "[" + indicesToReuse[i] + "]\""; s = MGlobal::executeCommand( command ); assert( s ); if( !s ) { return s; } } } #ifndef NDEBUG { MIntArray allLogicalIndices; plug.getExistingArrayAttributeIndices( allLogicalIndices ); assert( fnRAttr.getNumEntries() == numExpectedPoints ); assert( fnRAttr.getNumEntries() == allLogicalIndices.length() ); // the MRampAttribute has the wonderful "feature" that addEntries() is somehow capable // of creating duplicate logical array indices, which causes no end of trouble // down the line. check that we've managed to avoid this pitfall. std::set<int> uniqueIndices; std::copy( MArrayIter<MIntArray>::begin( allLogicalIndices ), MArrayIter<MIntArray>::end( allLogicalIndices ), std::insert_iterator<std::set<int> >( uniqueIndices, uniqueIndices.begin() ) ); assert( uniqueIndices.size()==allLogicalIndices.length() ); // then check that every element of the ramp has a suitable equivalent in // the original spline MIntArray indices; MFloatArray positions; MFloatArray values; MIntArray interps; fnRAttr.getEntries( indices, positions, values, interps, &s ); assert( s ); assert( numExpectedPoints == positions.length() ); assert( numExpectedPoints == values.length() ); assert( numExpectedPoints == interps.length() ); assert( numExpectedPoints == indices.length() ); for ( unsigned i = 0; i < positions.length(); i++ ) { float position = positions[ i ]; float value = values[ i ]; bool found = false; for ( typename S::PointContainer::const_iterator it = spline.points.begin(); it != spline.points.end() && !found; ++it ) { if ( fabs( it->first - position ) < 1.e-3f && fabs( it->second - value ) < 1.e-3f ) { found = true; } } assert( found ); } } #endif return MS::kSuccess; } template<typename S> MStatus FloatSplineParameterHandler<S>::setValue( const MPlug &plug, IECore::ParameterPtr parameter ) const { assert( parameter ); typename IECore::TypedParameter< S >::Ptr p = IECore::runTimeCast<IECore::TypedParameter< S > >( parameter ); if( !p ) { return MS::kFailure; } S spline; MStatus s; MRampAttribute fnRAttr( plug, &s ); assert( s ); if ( !fnRAttr.isCurveRamp() ) { return MS::kFailure; } if ( fnRAttr.getNumEntries( &s ) > 0 ) { assert( s ); MIntArray indices; MFloatArray positions; MFloatArray values; MIntArray interps; fnRAttr.getEntries( indices, positions, values, interps, &s ); assert( s ); if ( positions.length() != values.length() || positions.length() != interps.length() || positions.length() != indices.length() ) { return MS::kFailure; } for ( unsigned i = 0; i < positions.length(); i ++) { spline.points.insert( typename S::PointContainer::value_type( static_cast< typename S::XType >( positions[i] ), static_cast< typename S::YType >( values[ i ] ) ) ); } } // maya seems to do an implicit doubling up of the end points to cause interpolation to the ends. // our spline has no such implicit behaviour so we explicitly double up. if( spline.points.size() ) { #ifndef NDEBUG size_t oldSplineSize = spline.points.size(); #endif assert( spline.points.begin()->first <= spline.points.rbegin()->first ); spline.points.insert( *spline.points.begin() ); spline.points.insert( *spline.points.rbegin() ); assert( spline.points.size() == oldSplineSize + 2 ); } p->setTypedValue( spline ); if( spline.points.size() ) { assert( spline.points.size() >= 2 ); assert( spline.points.size() == fnRAttr.getNumEntries() + 2 ); } return MS::kSuccess; } <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in LICENSE #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "OgreRenderingModule.h" #include "Renderer.h" #include "EC_Placeable.h" #include "EC_Mesh.h" #include "EC_OgreCustomObject.h" #include "EC_AnimationController.h" #include "EC_Camera.h" #include "EC_Light.h" #include "EC_OgreCompositor.h" #include "EC_RttTarget.h" #include "EC_SelectionBox.h" #include "EC_Material.h" #include "OgreWorld.h" #include "OgreMeshAsset.h" #include "OgreParticleAsset.h" #include "OgreSkeletonAsset.h" #include "OgreMaterialAsset.h" #include "OgreProfiler.h" #ifdef OGRE_HAS_PROFILER_HOOKS #include "OgreProfilerHook.h" #endif #include "TextureAsset.h" #include "Application.h" #include "Entity.h" #include "Scene.h" #include "AssetAPI.h" #include "AssetCache.h" #include "GenericAssetFactory.h" #include "NullAssetFactory.h" #include "Profiler.h" #include "ConsoleAPI.h" #include "SceneAPI.h" #include "IComponentFactory.h" #include "MemoryLeakCheck.h" namespace OgreRenderer { std::string OgreRenderingModule::CACHE_RESOURCE_GROUP = "CACHED_ASSETS_GROUP"; #ifdef OGRE_HAS_PROFILER_HOOKS DWORD mainThreadId; void Profiler_BeginBlock(const char *name) { #ifdef PROFILING if (GetCurrentThreadId() != mainThreadId) return; Framework *fw = Framework::Instance(); Profiler *p = fw ? fw->GetProfiler() : 0; if (p) p->StartBlock((std::string("OGRE_") + name).c_str()); #endif } void Profiler_EndBlock() { #ifdef PROFILING if (GetCurrentThreadId() != mainThreadId) return; Framework *fw = Framework::Instance(); Profiler *p = fw ? fw->GetProfiler() : 0; if (p) { ProfilerNodeTree *treeNode = p->CurrentNode(); if (!treeNode) return; p->EndBlock(treeNode->Name()); } #endif } #endif OgreRenderingModule::OgreRenderingModule() : IModule("OgreRendering") { #ifdef OGRE_HAS_PROFILER_HOOKS mainThreadId = GetCurrentThreadId(); OgreProfiler_BeginBlock = Profiler_BeginBlock; OgreProfiler_EndBlock = Profiler_EndBlock; #endif } OgreRenderingModule::~OgreRenderingModule() { } void OgreRenderingModule::Load() { framework_->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_Placeable>)); framework_->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_Mesh>)); framework_->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_Light>)); framework_->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_OgreCustomObject>)); framework_->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_AnimationController>)); framework_->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_Camera>)); framework_->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_OgreCompositor>)); framework_->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_RttTarget>)); framework_->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_SelectionBox>)); framework_->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_Material>)); // Create asset type factories for each asset OgreRenderingModule provides to the system. framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<OgreMeshAsset>("OgreMesh"))); // Loading materials crashes Ogre in headless mode because we don't have Ogre Renderer running, so only register the Ogre material asset type if not in headless mode. if (!framework_->IsHeadless()) { framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<OgreMaterialAsset>("OgreMaterial"))); framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<TextureAsset>("Texture"))); framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<OgreParticleAsset>("OgreParticle"))); framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<OgreSkeletonAsset>("OgreSkeleton"))); } else { framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new NullAssetFactory("OgreMaterial"))); framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new NullAssetFactory("Texture"))); framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new NullAssetFactory("OgreParticle"))); framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new NullAssetFactory("OgreSkeleton"))); } } void OgreRenderingModule::Initialize() { std::string ogreConfigFilename = Application::InstallationDirectory().toStdString() + "ogre.cfg"; ///\todo Unicode support! #if defined (_WINDOWS) && (_DEBUG) std::string pluginsFilename = "pluginsd.cfg"; #elif defined (_WINDOWS) std::string pluginsFilename = "plugins.cfg"; #elif defined(__APPLE__) std::string pluginsFilename = "plugins-mac.cfg"; #else std::string pluginsFilename = "plugins-unix.cfg"; #endif pluginsFilename = Application::InstallationDirectory().toStdString() + pluginsFilename; ///\todo Unicode support! std::string windowTitle = Application::FullIdentifier().toStdString(); renderer = boost::make_shared<OgreRenderer::Renderer>(framework_, ogreConfigFilename, pluginsFilename, windowTitle); assert(renderer); assert(!renderer->IsInitialized()); // Initializing the Renderer crashes inside Ogre if the current working directory is not the same as the directory where Ogre plugins reside in. // So, temporarily set the working dir to the installation directory, and restore it after succeeding to load the plugins. QString cwd = Application::CurrentWorkingDirectory(); Application::SetCurrentWorkingDirectory(Application::InstallationDirectory()); framework_->App()->SetSplashMessage("Initializing Ogre"); renderer->Initialize(); // Restore the original cwd to not disturb the environment we are running in. Application::SetCurrentWorkingDirectory(cwd); // Register renderer. framework_->RegisterRenderer(renderer.get()); framework_->RegisterDynamicObject("renderer", renderer.get()); // Connect to scene change signals. connect(framework_->Scene(), SIGNAL(SceneAdded(const QString&)), this, SLOT(OnSceneAdded(const QString&))); connect(framework_->Scene(), SIGNAL(SceneRemoved(const QString&)), this, SLOT(OnSceneRemoved(const QString&))); // Add asset cache directory as its own resource group to ogre to support threaded loading. if (GetFramework()->Asset()->GetAssetCache()) { std::string cacheResourceDir = GetFramework()->Asset()->GetAssetCache()->CacheDirectory().toStdString(); if (!Ogre::ResourceGroupManager::getSingleton().resourceLocationExists(cacheResourceDir, CACHE_RESOURCE_GROUP)) Ogre::ResourceGroupManager::getSingleton().addResourceLocation(cacheResourceDir, "FileSystem", CACHE_RESOURCE_GROUP); } framework_->Console()->RegisterCommand("renderStats", "Prints out render statistics.", this, SLOT(ConsoleStats())); #if OGRE_PROFILING == 1 framework_->Console()->RegisterCommand("ogreProf", "Toggles visibility of the Ogre profiler overlay.", this, SLOT(ToggleOgreProfilerOverlay())); #endif framework_->Console()->RegisterCommand("setMaterialAttribute", "Sets an attribute on a material asset", this, SLOT(SetMaterialAttribute(const QStringList &))); } void OgreRenderingModule::Uninitialize() { // We're shutting down. Force a release of all loaded asset objects from the Asset API so that // no refs to Ogre assets remain - below 'renderer.reset()' is going to delete Ogre::Root. framework_->Asset()->ForgetAllAssets(); // Clear up the renderer object, so that it will not be left dangling. framework_->RegisterRenderer(0); } void OgreRenderingModule::ConsoleStats() { if (framework_->IsHeadless()) return; if (renderer) { const Ogre::RenderTarget::FrameStats& stats = renderer->GetCurrentRenderWindow()->getStatistics(); ConsoleAPI *c = framework_->Console(); c->Print("Average FPS: " + QString::number(stats.avgFPS)); c->Print("Worst FPS: " + QString::number(stats.worstFPS)); c->Print("Best FPS: " + QString::number(stats.bestFPS)); c->Print("Triangles: " + QString::number(stats.triangleCount)); c->Print("Batches: " + QString::number(stats.batchCount)); return; } else LogError("No renderer found!"); } void OgreRenderingModule::ToggleOgreProfilerOverlay() { #if OGRE_PROFILING == 1 if (!framework_->IsHeadless()) { bool enabled = Ogre::Profiler::getSingleton().getEnabled(); Ogre::Profiler::getSingleton().setEnabled(!enabled); } #else LogError("OgreRenderingModule::ToggleOgreProfilerOverlay: Ogre built without profiling support, cannot show profiler overlay."); #endif } void OgreRenderingModule::OnSceneAdded(const QString& name) { ScenePtr scene = GetFramework()->Scene()->GetScene(name); if (!scene) { LogError("OgreRenderingModule::OnSceneAdded: Could not find created scene"); return; } // Add an OgreWorld to the scene OgreWorldPtr newWorld = boost::make_shared<OgreWorld>(renderer.get(), scene); renderer->ogreWorlds[scene.get()] = newWorld; scene->setProperty(OgreWorld::PropertyName(), QVariant::fromValue<QObject*>(newWorld.get())); } void OgreRenderingModule::OnSceneRemoved(const QString& name) { // Remove the OgreWorld from the scene ScenePtr scene = GetFramework()->Scene()->GetScene(name); if (!scene) { LogError("OgreRenderingModule::OnSceneRemoved: Could not find scene about to be removed"); return; } OgreWorld* worldPtr = scene->GetWorld<OgreWorld>().get(); if (worldPtr) { scene->setProperty(OgreWorld::PropertyName(), QVariant()); renderer->ogreWorlds.erase(scene.get()); } } void OgreRenderingModule::SetMaterialAttribute(const QStringList &params) { if (params.size() < 3) { LogError("OgreRenderingModule::SetMaterialAttribute: Usage: SetMaterialAttribute(asset,attribute,value)"); return; } AssetPtr assetPtr = framework_->Asset()->GetAsset(framework_->Asset()->ResolveAssetRef("", params[0])); if (!assetPtr || !assetPtr->IsLoaded()) { LogError("OgreRenderingModule::SetMaterialAttribute: No asset found or not loaded"); return; } OgreMaterialAsset* matAsset = dynamic_cast<OgreMaterialAsset*>(assetPtr.get()); if (!matAsset) { LogError("OgreRenderingModule::SetMaterialAttribute: Not a material asset"); return; } matAsset->SetAttribute(params[1], params[2]); } } // ~namespace OgreRenderer using namespace OgreRenderer; extern "C" { DLLEXPORT void TundraPluginMain(Framework *fw) { Framework::SetInstance(fw); // Inside this DLL, remember the pointer to the global framework object. fw->RegisterModule(new OgreRenderer::OgreRenderingModule()); } } <commit_msg>Implement cross-platform build for ogre profiling code.<commit_after>// For conditions of distribution and use, see copyright notice in LICENSE #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "OgreRenderingModule.h" #include "Renderer.h" #include "EC_Placeable.h" #include "EC_Mesh.h" #include "EC_OgreCustomObject.h" #include "EC_AnimationController.h" #include "EC_Camera.h" #include "EC_Light.h" #include "EC_OgreCompositor.h" #include "EC_RttTarget.h" #include "EC_SelectionBox.h" #include "EC_Material.h" #include "OgreWorld.h" #include "OgreMeshAsset.h" #include "OgreParticleAsset.h" #include "OgreSkeletonAsset.h" #include "OgreMaterialAsset.h" #include "OgreProfiler.h" #ifdef OGRE_HAS_PROFILER_HOOKS #include "OgreProfilerHook.h" #endif #include "TextureAsset.h" #include "Application.h" #include "Entity.h" #include "Scene.h" #include "AssetAPI.h" #include "AssetCache.h" #include "GenericAssetFactory.h" #include "NullAssetFactory.h" #include "Profiler.h" #include "ConsoleAPI.h" #include "SceneAPI.h" #include "IComponentFactory.h" #include "MemoryLeakCheck.h" namespace OgreRenderer { std::string OgreRenderingModule::CACHE_RESOURCE_GROUP = "CACHED_ASSETS_GROUP"; #ifdef OGRE_HAS_PROFILER_HOOKS #ifdef WIN32 DWORD mainThreadId; #endif void Profiler_BeginBlock(const char *name) { #if defined(PROFILING) && defined(WIN32) if (GetCurrentThreadId() != mainThreadId) return; Framework *fw = Framework::Instance(); Profiler *p = fw ? fw->GetProfiler() : 0; if (p) p->StartBlock((std::string("OGRE_") + name).c_str()); #endif } void Profiler_EndBlock() { #if defined(PROFILING) && defined(WIN32) if (GetCurrentThreadId() != mainThreadId) return; Framework *fw = Framework::Instance(); Profiler *p = fw ? fw->GetProfiler() : 0; if (p) { ProfilerNodeTree *treeNode = p->CurrentNode(); if (!treeNode) return; p->EndBlock(treeNode->Name()); } #endif } #endif OgreRenderingModule::OgreRenderingModule() : IModule("OgreRendering") { #ifdef OGRE_HAS_PROFILER_HOOKS #ifdef WIN32 mainThreadId = GetCurrentThreadId(); #endif OgreProfiler_BeginBlock = Profiler_BeginBlock; OgreProfiler_EndBlock = Profiler_EndBlock; #endif } OgreRenderingModule::~OgreRenderingModule() { } void OgreRenderingModule::Load() { framework_->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_Placeable>)); framework_->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_Mesh>)); framework_->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_Light>)); framework_->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_OgreCustomObject>)); framework_->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_AnimationController>)); framework_->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_Camera>)); framework_->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_OgreCompositor>)); framework_->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_RttTarget>)); framework_->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_SelectionBox>)); framework_->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_Material>)); // Create asset type factories for each asset OgreRenderingModule provides to the system. framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<OgreMeshAsset>("OgreMesh"))); // Loading materials crashes Ogre in headless mode because we don't have Ogre Renderer running, so only register the Ogre material asset type if not in headless mode. if (!framework_->IsHeadless()) { framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<OgreMaterialAsset>("OgreMaterial"))); framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<TextureAsset>("Texture"))); framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<OgreParticleAsset>("OgreParticle"))); framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<OgreSkeletonAsset>("OgreSkeleton"))); } else { framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new NullAssetFactory("OgreMaterial"))); framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new NullAssetFactory("Texture"))); framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new NullAssetFactory("OgreParticle"))); framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new NullAssetFactory("OgreSkeleton"))); } } void OgreRenderingModule::Initialize() { std::string ogreConfigFilename = Application::InstallationDirectory().toStdString() + "ogre.cfg"; ///\todo Unicode support! #if defined (_WINDOWS) && (_DEBUG) std::string pluginsFilename = "pluginsd.cfg"; #elif defined (_WINDOWS) std::string pluginsFilename = "plugins.cfg"; #elif defined(__APPLE__) std::string pluginsFilename = "plugins-mac.cfg"; #else std::string pluginsFilename = "plugins-unix.cfg"; #endif pluginsFilename = Application::InstallationDirectory().toStdString() + pluginsFilename; ///\todo Unicode support! std::string windowTitle = Application::FullIdentifier().toStdString(); renderer = boost::make_shared<OgreRenderer::Renderer>(framework_, ogreConfigFilename, pluginsFilename, windowTitle); assert(renderer); assert(!renderer->IsInitialized()); // Initializing the Renderer crashes inside Ogre if the current working directory is not the same as the directory where Ogre plugins reside in. // So, temporarily set the working dir to the installation directory, and restore it after succeeding to load the plugins. QString cwd = Application::CurrentWorkingDirectory(); Application::SetCurrentWorkingDirectory(Application::InstallationDirectory()); framework_->App()->SetSplashMessage("Initializing Ogre"); renderer->Initialize(); // Restore the original cwd to not disturb the environment we are running in. Application::SetCurrentWorkingDirectory(cwd); // Register renderer. framework_->RegisterRenderer(renderer.get()); framework_->RegisterDynamicObject("renderer", renderer.get()); // Connect to scene change signals. connect(framework_->Scene(), SIGNAL(SceneAdded(const QString&)), this, SLOT(OnSceneAdded(const QString&))); connect(framework_->Scene(), SIGNAL(SceneRemoved(const QString&)), this, SLOT(OnSceneRemoved(const QString&))); // Add asset cache directory as its own resource group to ogre to support threaded loading. if (GetFramework()->Asset()->GetAssetCache()) { std::string cacheResourceDir = GetFramework()->Asset()->GetAssetCache()->CacheDirectory().toStdString(); if (!Ogre::ResourceGroupManager::getSingleton().resourceLocationExists(cacheResourceDir, CACHE_RESOURCE_GROUP)) Ogre::ResourceGroupManager::getSingleton().addResourceLocation(cacheResourceDir, "FileSystem", CACHE_RESOURCE_GROUP); } framework_->Console()->RegisterCommand("renderStats", "Prints out render statistics.", this, SLOT(ConsoleStats())); #if OGRE_PROFILING == 1 framework_->Console()->RegisterCommand("ogreProf", "Toggles visibility of the Ogre profiler overlay.", this, SLOT(ToggleOgreProfilerOverlay())); #endif framework_->Console()->RegisterCommand("setMaterialAttribute", "Sets an attribute on a material asset", this, SLOT(SetMaterialAttribute(const QStringList &))); } void OgreRenderingModule::Uninitialize() { // We're shutting down. Force a release of all loaded asset objects from the Asset API so that // no refs to Ogre assets remain - below 'renderer.reset()' is going to delete Ogre::Root. framework_->Asset()->ForgetAllAssets(); // Clear up the renderer object, so that it will not be left dangling. framework_->RegisterRenderer(0); } void OgreRenderingModule::ConsoleStats() { if (framework_->IsHeadless()) return; if (renderer) { const Ogre::RenderTarget::FrameStats& stats = renderer->GetCurrentRenderWindow()->getStatistics(); ConsoleAPI *c = framework_->Console(); c->Print("Average FPS: " + QString::number(stats.avgFPS)); c->Print("Worst FPS: " + QString::number(stats.worstFPS)); c->Print("Best FPS: " + QString::number(stats.bestFPS)); c->Print("Triangles: " + QString::number(stats.triangleCount)); c->Print("Batches: " + QString::number(stats.batchCount)); return; } else LogError("No renderer found!"); } void OgreRenderingModule::ToggleOgreProfilerOverlay() { #if OGRE_PROFILING == 1 if (!framework_->IsHeadless()) { bool enabled = Ogre::Profiler::getSingleton().getEnabled(); Ogre::Profiler::getSingleton().setEnabled(!enabled); } #else LogError("OgreRenderingModule::ToggleOgreProfilerOverlay: Ogre built without profiling support, cannot show profiler overlay."); #endif } void OgreRenderingModule::OnSceneAdded(const QString& name) { ScenePtr scene = GetFramework()->Scene()->GetScene(name); if (!scene) { LogError("OgreRenderingModule::OnSceneAdded: Could not find created scene"); return; } // Add an OgreWorld to the scene OgreWorldPtr newWorld = boost::make_shared<OgreWorld>(renderer.get(), scene); renderer->ogreWorlds[scene.get()] = newWorld; scene->setProperty(OgreWorld::PropertyName(), QVariant::fromValue<QObject*>(newWorld.get())); } void OgreRenderingModule::OnSceneRemoved(const QString& name) { // Remove the OgreWorld from the scene ScenePtr scene = GetFramework()->Scene()->GetScene(name); if (!scene) { LogError("OgreRenderingModule::OnSceneRemoved: Could not find scene about to be removed"); return; } OgreWorld* worldPtr = scene->GetWorld<OgreWorld>().get(); if (worldPtr) { scene->setProperty(OgreWorld::PropertyName(), QVariant()); renderer->ogreWorlds.erase(scene.get()); } } void OgreRenderingModule::SetMaterialAttribute(const QStringList &params) { if (params.size() < 3) { LogError("OgreRenderingModule::SetMaterialAttribute: Usage: SetMaterialAttribute(asset,attribute,value)"); return; } AssetPtr assetPtr = framework_->Asset()->GetAsset(framework_->Asset()->ResolveAssetRef("", params[0])); if (!assetPtr || !assetPtr->IsLoaded()) { LogError("OgreRenderingModule::SetMaterialAttribute: No asset found or not loaded"); return; } OgreMaterialAsset* matAsset = dynamic_cast<OgreMaterialAsset*>(assetPtr.get()); if (!matAsset) { LogError("OgreRenderingModule::SetMaterialAttribute: Not a material asset"); return; } matAsset->SetAttribute(params[1], params[2]); } } // ~namespace OgreRenderer using namespace OgreRenderer; extern "C" { DLLEXPORT void TundraPluginMain(Framework *fw) { Framework::SetInstance(fw); // Inside this DLL, remember the pointer to the global framework object. fw->RegisterModule(new OgreRenderer::OgreRenderingModule()); } } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright (c) 2011, Michael P. Gerlek ([email protected]) * * 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 Hobu, Inc. or Flaxen Geo Consulting nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #include "AppSupport.hpp" #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include <pdal/FileUtils.hpp> #include <pdal/Utils.hpp> #include <pdal/PipelineManager.hpp> #include <pdal/PipelineReader.hpp> #include <pdal/StageFactory.hpp> std::string AppSupport::inferReaderDriver(const std::string& filename, pdal::Options& options) { std::string ext = boost::filesystem::extension(filename); pdal::Option& fn = options.getOptionByRef("filename"); fn.setValue<std::string>(filename); // maybe this should live in StageFactory? std::map<std::string, std::string> drivers; drivers["las"] = "drivers.las.reader"; drivers["laz"] = "drivers.las.reader"; drivers["bin"] = "drivers.terrasolid.reader"; drivers["qi"] = "drivers.qfit.reader"; drivers["xml"] = "drivers.pipeline.reader"; drivers["nitf"] = "drivers.nitf.reader"; drivers["ntf"] = "drivers.nitf.reader"; if (boost::algorithm::iequals(filename, "STDIN")) { return drivers["xml"]; } if (ext == "") return ""; ext = ext.substr(1, ext.length()-1); if (ext == "") return ""; boost::to_lower(ext); std::string driver = drivers[ext]; return driver; // will be "" if not found } std::string AppSupport::inferWriterDriver(const std::string& filename, pdal::Options& options) { std::string ext = boost::filesystem::extension(filename); boost::to_lower(ext); if (boost::algorithm::iequals(ext,".laz")) { options.add("compression", true); } options.add<std::string>("filename", filename); // maybe this should live in StageFactory? std::map<std::string, std::string> drivers; drivers["las"] = "drivers.las.writer"; drivers["laz"] = "drivers.las.writer"; drivers["xyz"] = "drivers.text.writer"; drivers["txt"] = "drivers.text.writer"; drivers["pcd"] = "drivers.pcd.writer"; if (boost::algorithm::iequals(filename, "STDOUT")) { return drivers["txt"]; } if (ext == "") return drivers["txt"]; ext = ext.substr(1, ext.length()-1); if (ext == "") return drivers["txt"]; boost::to_lower(ext); std::string driver = drivers[ext]; return driver; // will be "" if not found } pdal::Stage* AppSupport::makeReader(pdal::Options& options) { const std::string inputFile = options.getValueOrThrow<std::string>("filename"); if (!pdal::FileUtils::fileExists(inputFile)) { throw app_runtime_error("file not found: " + inputFile); } pdal::StageFactory factory; std::string driver = factory.inferReaderDriver(inputFile, options); if (driver == "") { throw app_runtime_error("Cannot determine input file type of " + inputFile); } pdal::Stage* stage = factory.createReader(driver, options); if (!stage) { throw app_runtime_error("reader creation failed"); } return stage; } pdal::Writer* AppSupport::makeWriter(pdal::Options& options, pdal::Stage& stage) { const std::string outputFile = options.getValueOrThrow<std::string>("filename"); pdal::StageFactory factory; std::string driver = factory.inferWriterDriver(outputFile, options); if (driver == "") { throw app_runtime_error("Cannot determine output file type of " + outputFile); } pdal::Writer* writer = factory.createWriter(driver, stage, options); if (!writer) { throw app_runtime_error("writer creation failed"); } return writer; } PercentageCallback::PercentageCallback(double major, double minor) : m_lastMajorPerc(-1 * major) , m_lastMinorPerc(-1 * minor) , m_done(false) { return; } void PercentageCallback::callback() { if (m_done) return; double currPerc = getPercentComplete(); if (pdal::Utils::compare_distance<double>(currPerc, 100.0)) { std::cerr << "100" << std::endl; m_done = true; } else if (currPerc >= m_lastMajorPerc + 10.0) { std::cerr << (int)currPerc << std::flush; m_lastMajorPerc = currPerc; m_lastMinorPerc = currPerc; } else if (currPerc >= m_lastMinorPerc + 2.0) { std::cerr << '.' << std::flush; m_lastMinorPerc = currPerc; } return; } ShellScriptCallback::ShellScriptCallback(std::vector<std::string> const& command) { double major_tick(10.0); double minor_tick(2.0); if (!command.size()) { m_command = ""; } else { m_command = command[0]; if (command.size() == 3) { major_tick = boost::lexical_cast<double>(command[1]); minor_tick = boost::lexical_cast<double>(command[2]); } else if (command.size() == 2) { major_tick = boost::lexical_cast<double>(command[1]); } } PercentageCallback(major_tick, minor_tick); return; } void ShellScriptCallback::callback() { if (m_done) return; double currPerc = getPercentComplete(); if (pdal::Utils::compare_distance<double>(currPerc, 100.0)) { m_done = true; } else if (currPerc >= m_lastMajorPerc + 10.0) { std::string output; int stat = pdal::Utils::run_shell_command(m_command + " " + boost::lexical_cast<std::string>(static_cast<int>(currPerc)), output); } else if (currPerc >= m_lastMinorPerc + 2.0) { m_lastMinorPerc = currPerc; } return; } HeartbeatCallback::HeartbeatCallback() { return; } void HeartbeatCallback::callback() { std::cerr << '.'; return; } <commit_msg>add percentage updates to ShellScriptCallback<commit_after>/****************************************************************************** * Copyright (c) 2011, Michael P. Gerlek ([email protected]) * * 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 Hobu, Inc. or Flaxen Geo Consulting nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #include "AppSupport.hpp" #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include <pdal/FileUtils.hpp> #include <pdal/Utils.hpp> #include <pdal/PipelineManager.hpp> #include <pdal/PipelineReader.hpp> #include <pdal/StageFactory.hpp> std::string AppSupport::inferReaderDriver(const std::string& filename, pdal::Options& options) { std::string ext = boost::filesystem::extension(filename); pdal::Option& fn = options.getOptionByRef("filename"); fn.setValue<std::string>(filename); // maybe this should live in StageFactory? std::map<std::string, std::string> drivers; drivers["las"] = "drivers.las.reader"; drivers["laz"] = "drivers.las.reader"; drivers["bin"] = "drivers.terrasolid.reader"; drivers["qi"] = "drivers.qfit.reader"; drivers["xml"] = "drivers.pipeline.reader"; drivers["nitf"] = "drivers.nitf.reader"; drivers["ntf"] = "drivers.nitf.reader"; if (boost::algorithm::iequals(filename, "STDIN")) { return drivers["xml"]; } if (ext == "") return ""; ext = ext.substr(1, ext.length()-1); if (ext == "") return ""; boost::to_lower(ext); std::string driver = drivers[ext]; return driver; // will be "" if not found } std::string AppSupport::inferWriterDriver(const std::string& filename, pdal::Options& options) { std::string ext = boost::filesystem::extension(filename); boost::to_lower(ext); if (boost::algorithm::iequals(ext,".laz")) { options.add("compression", true); } options.add<std::string>("filename", filename); // maybe this should live in StageFactory? std::map<std::string, std::string> drivers; drivers["las"] = "drivers.las.writer"; drivers["laz"] = "drivers.las.writer"; drivers["xyz"] = "drivers.text.writer"; drivers["txt"] = "drivers.text.writer"; drivers["pcd"] = "drivers.pcd.writer"; if (boost::algorithm::iequals(filename, "STDOUT")) { return drivers["txt"]; } if (ext == "") return drivers["txt"]; ext = ext.substr(1, ext.length()-1); if (ext == "") return drivers["txt"]; boost::to_lower(ext); std::string driver = drivers[ext]; return driver; // will be "" if not found } pdal::Stage* AppSupport::makeReader(pdal::Options& options) { const std::string inputFile = options.getValueOrThrow<std::string>("filename"); if (!pdal::FileUtils::fileExists(inputFile)) { throw app_runtime_error("file not found: " + inputFile); } pdal::StageFactory factory; std::string driver = factory.inferReaderDriver(inputFile, options); if (driver == "") { throw app_runtime_error("Cannot determine input file type of " + inputFile); } pdal::Stage* stage = factory.createReader(driver, options); if (!stage) { throw app_runtime_error("reader creation failed"); } return stage; } pdal::Writer* AppSupport::makeWriter(pdal::Options& options, pdal::Stage& stage) { const std::string outputFile = options.getValueOrThrow<std::string>("filename"); pdal::StageFactory factory; std::string driver = factory.inferWriterDriver(outputFile, options); if (driver == "") { throw app_runtime_error("Cannot determine output file type of " + outputFile); } pdal::Writer* writer = factory.createWriter(driver, stage, options); if (!writer) { throw app_runtime_error("writer creation failed"); } return writer; } PercentageCallback::PercentageCallback(double major, double minor) : m_lastMajorPerc(-1 * major) , m_lastMinorPerc(-1 * minor) , m_done(false) { return; } void PercentageCallback::callback() { if (m_done) return; double currPerc = getPercentComplete(); if (pdal::Utils::compare_distance<double>(currPerc, 100.0)) { std::cerr << "100" << std::endl; m_done = true; } else if (currPerc >= m_lastMajorPerc + 10.0) { std::cerr << (int)currPerc << std::flush; m_lastMajorPerc = currPerc; m_lastMinorPerc = currPerc; } else if (currPerc >= m_lastMinorPerc + 2.0) { std::cerr << '.' << std::flush; m_lastMinorPerc = currPerc; } return; } ShellScriptCallback::ShellScriptCallback(std::vector<std::string> const& command) { double major_tick(10.0); double minor_tick(2.0); if (!command.size()) { m_command = ""; } else { m_command = command[0]; if (command.size() == 3) { major_tick = boost::lexical_cast<double>(command[1]); minor_tick = boost::lexical_cast<double>(command[2]); } else if (command.size() == 2) { major_tick = boost::lexical_cast<double>(command[1]); } } PercentageCallback(major_tick, minor_tick); return; } void ShellScriptCallback::callback() { if (m_done) return; double currPerc = getPercentComplete(); if (pdal::Utils::compare_distance<double>(currPerc, 100.0)) { m_done = true; } else if (currPerc >= m_lastMajorPerc + 10.0) { std::string output; int stat = pdal::Utils::run_shell_command(m_command + " " + boost::lexical_cast<std::string>(static_cast<int>(currPerc)), output); m_lastMajorPerc = currPerc; m_lastMinorPerc = currPerc; } else if (currPerc >= m_lastMinorPerc + 2.0) { m_lastMinorPerc = currPerc; } return; } HeartbeatCallback::HeartbeatCallback() { return; } void HeartbeatCallback::callback() { std::cerr << '.'; return; } <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/ozone/platform/egl/egl_surface_factory.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkSurface.h" #include "ui/ozone/public/surface_ozone_egl.h" #include "ui/ozone/public/surface_ozone_canvas.h" #include "ui/ozone/public/surface_factory_ozone.h" #include "ui/gfx/skia_util.h" #include "ui/gfx/vsync_provider.h" #include "base/logging.h" #include "egl_wrapper.h" #ifndef GL_BGRA_EXT #define GL_BGRA_EXT 0x80E1 #endif #include <fcntl.h> /* For O_RDWR */ #include <unistd.h> /* For open(), creat() */ #include <linux/fb.h> #include <sys/ioctl.h> #define OZONE_EGL_WINDOW_WIDTH 1024 #define OZONE_EGL_WINDOW_HEIGTH 768 namespace ui { class EglOzoneCanvas: public ui::SurfaceOzoneCanvas { public: EglOzoneCanvas(); virtual ~EglOzoneCanvas(); // SurfaceOzoneCanvas overrides: virtual void ResizeCanvas(const gfx::Size& viewport_size) override; //virtual skia::RefPtr<SkCanvas> GetCanvas() override { // return skia::SharePtr<SkCanvas>(surface_->getCanvas()); //} virtual void PresentCanvas(const gfx::Rect& damage) override; virtual scoped_ptr<gfx::VSyncProvider> CreateVSyncProvider() override { return scoped_ptr<gfx::VSyncProvider>(); } private: skia::RefPtr<SkSurface> surface_; ozone_egl_UserData userDate_; }; EglOzoneCanvas::EglOzoneCanvas() { memset(&userDate_,0,sizeof(userDate_)); } EglOzoneCanvas::~EglOzoneCanvas() { ozone_egl_textureShutDown (&userDate_); } void EglOzoneCanvas::ResizeCanvas(const gfx::Size& viewport_size) { if(userDate_.width == viewport_size.width() && userDate_.height==viewport_size.height()) { return; } else if(userDate_.width != 0 && userDate_.height !=0) { ozone_egl_textureShutDown (&userDate_); } surface_ = skia::AdoptRef(SkSurface::NewRaster( SkImageInfo::Make(viewport_size.width(), viewport_size.height(), kN32_SkColorType, kPremul_SkAlphaType))); userDate_.width = viewport_size.width(); userDate_.height = viewport_size.height(); userDate_.colorType = GL_BGRA_EXT; ozone_egl_textureInit ( &userDate_); } void EglOzoneCanvas::PresentCanvas(const gfx::Rect& damage) { SkImageInfo info; size_t row_bytes; userDate_.data = (char *) surface_->peekPixels(&info, &row_bytes); ozone_egl_textureDraw(&userDate_); ozone_egl_swap(); } class OzoneEgl : public ui::SurfaceOzoneEGL { public: OzoneEgl(gfx::AcceleratedWidget window_id){ native_window_ = window_id; } virtual ~OzoneEgl() { native_window_=0; } virtual intptr_t GetNativeWindow() override { return native_window_; } virtual bool OnSwapBuffers() override { return true; } virtual bool ResizeNativeWindow(const gfx::Size& viewport_size) override { return true; } virtual scoped_ptr<gfx::VSyncProvider> CreateVSyncProvider() override { return scoped_ptr<gfx::VSyncProvider>(); } private: intptr_t native_window_; }; SurfaceFactoryEgl::SurfaceFactoryEgl():init_(false) { } SurfaceFactoryEgl::~SurfaceFactoryEgl() { DestroySingleWindow(); } EGLint g_width; EGLint g_height; bool SurfaceFactoryEgl::CreateSingleWindow() { struct fb_var_screeninfo fb_var; int fb_fd = open("/dev/fb0", O_RDWR); if(init_) { return true; } if (ioctl(fb_fd, FBIOGET_VSCREENINFO, &fb_var)) { LOG(FATAL) << "failed to get fb var info errno: " << errno; g_width = 640; g_height = 480; } else { g_width = fb_var.xres; g_height = fb_var.yres; } close(fb_fd); if(!ozone_egl_setup(0, 0, g_width, g_height)) { LOG(FATAL) << "CreateSingleWindow"; return false; } init_ = true; return true; } void SurfaceFactoryEgl::DestroySingleWindow() { ozone_egl_destroy(); init_ = false; } intptr_t SurfaceFactoryEgl::GetNativeDisplay() { return (intptr_t)ozone_egl_getNativedisp(); } //gfx::AcceleratedWidget SurfaceFactoryEgl::GetAcceleratedWidget() { // if (!CreateSingleWindow()) // LOG(FATAL) << "failed to create window"; // return (gfx::AcceleratedWidget)GetNativeDisplay(); //} scoped_ptr<ui::SurfaceOzoneEGL> SurfaceFactoryEgl::CreateEGLSurfaceForWidget( gfx::AcceleratedWidget widget) { return make_scoped_ptr<ui::SurfaceOzoneEGL>( new OzoneEgl(widget)); } bool SurfaceFactoryEgl::LoadEGLGLES2Bindings( AddGLLibraryCallback add_gl_library, SetGLGetProcAddressProcCallback set_gl_get_proc_address) { return false; } const int32* SurfaceFactoryEgl::GetEGLSurfaceProperties( const int32* desired_list) { return ozone_egl_getConfigAttribs(); } scoped_ptr<ui::SurfaceOzoneCanvas> SurfaceFactoryEgl::CreateCanvasForWidget( gfx::AcceleratedWidget widget){ LOG(ERROR) << "-CreateCanvasForWidget-"; scoped_ptr<EglOzoneCanvas> canvas(new EglOzoneCanvas()); return canvas.PassAs<ui::SurfaceOzoneCanvas>(); } } // namespace ui <commit_msg>overriding OnSwapBuffersAsync<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/ozone/platform/egl/egl_surface_factory.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkSurface.h" #include "ui/ozone/public/surface_ozone_egl.h" #include "ui/ozone/public/surface_ozone_canvas.h" #include "ui/ozone/public/surface_factory_ozone.h" #include "ui/gfx/skia_util.h" #include "ui/gfx/vsync_provider.h" #include "base/logging.h" #include "egl_wrapper.h" #ifndef GL_BGRA_EXT #define GL_BGRA_EXT 0x80E1 #endif #include <fcntl.h> /* For O_RDWR */ #include <unistd.h> /* For open(), creat() */ #include <linux/fb.h> #include <sys/ioctl.h> #define OZONE_EGL_WINDOW_WIDTH 1024 #define OZONE_EGL_WINDOW_HEIGTH 768 namespace ui { class EglOzoneCanvas: public ui::SurfaceOzoneCanvas { public: EglOzoneCanvas(); virtual ~EglOzoneCanvas(); // SurfaceOzoneCanvas overrides: virtual void ResizeCanvas(const gfx::Size& viewport_size) override; //virtual skia::RefPtr<SkCanvas> GetCanvas() override { // return skia::SharePtr<SkCanvas>(surface_->getCanvas()); //} virtual void PresentCanvas(const gfx::Rect& damage) override; virtual scoped_ptr<gfx::VSyncProvider> CreateVSyncProvider() override { return scoped_ptr<gfx::VSyncProvider>(); } private: skia::RefPtr<SkSurface> surface_; ozone_egl_UserData userDate_; }; EglOzoneCanvas::EglOzoneCanvas() { memset(&userDate_,0,sizeof(userDate_)); } EglOzoneCanvas::~EglOzoneCanvas() { ozone_egl_textureShutDown (&userDate_); } void EglOzoneCanvas::ResizeCanvas(const gfx::Size& viewport_size) { if(userDate_.width == viewport_size.width() && userDate_.height==viewport_size.height()) { return; } else if(userDate_.width != 0 && userDate_.height !=0) { ozone_egl_textureShutDown (&userDate_); } surface_ = skia::AdoptRef(SkSurface::NewRaster( SkImageInfo::Make(viewport_size.width(), viewport_size.height(), kN32_SkColorType, kPremul_SkAlphaType))); userDate_.width = viewport_size.width(); userDate_.height = viewport_size.height(); userDate_.colorType = GL_BGRA_EXT; ozone_egl_textureInit ( &userDate_); } void EglOzoneCanvas::PresentCanvas(const gfx::Rect& damage) { SkImageInfo info; size_t row_bytes; userDate_.data = (char *) surface_->peekPixels(&info, &row_bytes); ozone_egl_textureDraw(&userDate_); ozone_egl_swap(); } class OzoneEgl : public ui::SurfaceOzoneEGL { public: OzoneEgl(gfx::AcceleratedWidget window_id){ native_window_ = window_id; } virtual ~OzoneEgl() { native_window_=0; } virtual intptr_t GetNativeWindow() override { return native_window_; } virtual bool OnSwapBuffers() override { return true; } virtual bool OnSwapBuffersAsync(const SwapCompletionCallback& callback) override { return true; } virtual bool ResizeNativeWindow(const gfx::Size& viewport_size) override { return true; } virtual scoped_ptr<gfx::VSyncProvider> CreateVSyncProvider() override { return scoped_ptr<gfx::VSyncProvider>(); } private: intptr_t native_window_; }; SurfaceFactoryEgl::SurfaceFactoryEgl():init_(false) { } SurfaceFactoryEgl::~SurfaceFactoryEgl() { DestroySingleWindow(); } EGLint g_width; EGLint g_height; bool SurfaceFactoryEgl::CreateSingleWindow() { struct fb_var_screeninfo fb_var; int fb_fd = open("/dev/fb0", O_RDWR); if(init_) { return true; } if (ioctl(fb_fd, FBIOGET_VSCREENINFO, &fb_var)) { LOG(FATAL) << "failed to get fb var info errno: " << errno; g_width = 640; g_height = 480; } else { g_width = fb_var.xres; g_height = fb_var.yres; } close(fb_fd); if(!ozone_egl_setup(0, 0, g_width, g_height)) { LOG(FATAL) << "CreateSingleWindow"; return false; } init_ = true; return true; } void SurfaceFactoryEgl::DestroySingleWindow() { ozone_egl_destroy(); init_ = false; } intptr_t SurfaceFactoryEgl::GetNativeDisplay() { return (intptr_t)ozone_egl_getNativedisp(); } //gfx::AcceleratedWidget SurfaceFactoryEgl::GetAcceleratedWidget() { // if (!CreateSingleWindow()) // LOG(FATAL) << "failed to create window"; // return (gfx::AcceleratedWidget)GetNativeDisplay(); //} scoped_ptr<ui::SurfaceOzoneEGL> SurfaceFactoryEgl::CreateEGLSurfaceForWidget( gfx::AcceleratedWidget widget) { return make_scoped_ptr<ui::SurfaceOzoneEGL>( new OzoneEgl(widget)); } bool SurfaceFactoryEgl::LoadEGLGLES2Bindings( AddGLLibraryCallback add_gl_library, SetGLGetProcAddressProcCallback set_gl_get_proc_address) { return false; } const int32* SurfaceFactoryEgl::GetEGLSurfaceProperties( const int32* desired_list) { return ozone_egl_getConfigAttribs(); } scoped_ptr<ui::SurfaceOzoneCanvas> SurfaceFactoryEgl::CreateCanvasForWidget( gfx::AcceleratedWidget widget){ LOG(ERROR) << "-CreateCanvasForWidget-"; scoped_ptr<EglOzoneCanvas> canvas(new EglOzoneCanvas()); return canvas.PassAs<ui::SurfaceOzoneCanvas>(); } } // namespace ui <|endoftext|>
<commit_before>#include <iostream> #include <bw/channelselector.h> #include <bw/thresholding.h> #include <bw/connectedcomponents.h> #include <bw/regionfeatures.h> #include <bw/extern_templates.h> int main(int argc, char** argv) { using namespace vigra; using namespace BW; if(argc != 3) { std::cout << "usage: ./ccpipeline hdf5file hdf5group" << std::endl; return 0; } std::string hdf5file(argv[1]); std::string hdf5group(argv[2]); typedef TinyVector<int, 3> V; V blockShape(100,100,100); //extract channel 0 { SourceHDF5<4, float> source(hdf5file, hdf5group); SinkHDF5<3, float> sink("01_channel0.h5", "channel0"); sink.setBlockShape(blockShape); ChannelSelector<4, float> cs(&source, blockShape); cs.run(0, 0, &sink); } //threshold { SourceHDF5<3, float> source("01_channel0.h5", "channel0"); SinkHDF5<3, vigra::UInt8> sink("02_thresh.h5", "thresh"); sink.setBlockShape(blockShape); Thresholding<3, float> bs(&source, blockShape); bs.run(0.5, 0, 1, &sink); } //connected components { SourceHDF5<3, UInt8> source("02_thresh.h5", "thresh"); ConnectedComponents<3> bs(&source, blockShape); bs.writeResult("03_cc.h5", "cc", 1); } //region features { SourceHDF5<3, float> sourceData("02_thresh.h5", "thresh"); SourceHDF5<3, uint32_t> sourceLabels("02_thresh.h5", "thresh"); RegionFeatures<3, float, uint32_t> rf(&sourceData, &sourceLabels, blockShape); vigra::MultiArray<2, float> out; rf.run("test_result.h5"); } } <commit_msg>example: add license<commit_after>/************************************************************************/ /* */ /* Copyright 2013 by Thorben Kroeger */ /* [email protected] */ /* */ /* 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 <iostream> #include <bw/channelselector.h> #include <bw/thresholding.h> #include <bw/connectedcomponents.h> #include <bw/regionfeatures.h> #include <bw/extern_templates.h> int main(int argc, char** argv) { using namespace vigra; using namespace BW; if(argc != 3) { std::cout << "usage: ./ccpipeline hdf5file hdf5group" << std::endl; return 0; } std::string hdf5file(argv[1]); std::string hdf5group(argv[2]); typedef TinyVector<int, 3> V; V blockShape(100,100,100); //extract channel 0 { SourceHDF5<4, float> source(hdf5file, hdf5group); SinkHDF5<3, float> sink("01_channel0.h5", "channel0"); sink.setBlockShape(blockShape); ChannelSelector<4, float> cs(&source, blockShape); cs.run(0, 0, &sink); } //threshold { SourceHDF5<3, float> source("01_channel0.h5", "channel0"); SinkHDF5<3, vigra::UInt8> sink("02_thresh.h5", "thresh"); sink.setBlockShape(blockShape); Thresholding<3, float> bs(&source, blockShape); bs.run(0.5, 0, 1, &sink); } //connected components { SourceHDF5<3, UInt8> source("02_thresh.h5", "thresh"); ConnectedComponents<3> bs(&source, blockShape); bs.writeResult("03_cc.h5", "cc", 1); } //region features { SourceHDF5<3, float> sourceData("02_thresh.h5", "thresh"); SourceHDF5<3, uint32_t> sourceLabels("02_thresh.h5", "thresh"); RegionFeatures<3, float, uint32_t> rf(&sourceData, &sourceLabels, blockShape); vigra::MultiArray<2, float> out; rf.run("test_result.h5"); } } <|endoftext|>
<commit_before>/* mockturtle: C++ logic network library * Copyright (C) 2018-2019 EPFL * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /*! \file balancing.hpp \brief Cut-based depth-optimization \author Mathias Soeken */ #pragma once #include <cstdint> #include <functional> #include <limits> #include <optional> #include <utility> #include <vector> #include <fmt/format.h> #include <kitty/dynamic_truth_table.hpp> #include "../utils/node_map.hpp" #include "../utils/progress_bar.hpp" #include "../utils/stopwatch.hpp" #include "../views/topo_view.hpp" #include "cleanup.hpp" #include "cut_enumeration.hpp" namespace mockturtle { /*! \brief Parameters for balancing. */ struct balancing_params { /*! \brief Cut enumeration params. */ cut_enumeration_params cut_enumeration_ps; /*! \brief Show progress. */ bool progress{false}; /*! \brief Be verbose. */ bool verbose{false}; }; /*! \brief Statistics for balancing. */ struct balancing_stats { /*! \brief Total run-time. */ stopwatch<>::duration time_total{}; /*! \brief Cut enumeration run-time. */ cut_enumeration_stats cut_enumeration_st; /*! \brief Prints report. */ void report() const { fmt::print( "[i] total time = {:>5.2f} secs\n", to_seconds( time_total ) ); fmt::print( "[i] Cut enumeration stats\n" ); cut_enumeration_st.report(); } }; template<class Ntk> struct arrival_time_pair { signal<Ntk> f; uint32_t level; }; /*! \brief Callback function for `rebalancing_function_t`. * * This callback is used in the rebalancing function to announce a new candidate that * could be used for replacement in the main balancing algorithm. Using a callback * makes it possible to account for situations in which none, a single, or multiple * candidates are generated. * * The callback returns a pair composed of the output signal of the replacement * candidate and the level of the new candidate. Ideally, the rebalancing function * should not call the callback with candidates that a worse level. */ template<class Ntk> using rebalancing_function_callback_t = std::function<void(arrival_time_pair<Ntk> const&, uint32_t)>; template<class Ntk> using rebalancing_function_t = std::function<void(Ntk&, kitty::dynamic_truth_table const&, std::vector<arrival_time_pair<Ntk>> const&, uint32_t, uint32_t, rebalancing_function_callback_t<Ntk> const&)>; namespace detail { template<class Ntk> struct balancing_impl { balancing_impl( Ntk const& ntk, rebalancing_function_t<Ntk> const& rebalancing_fn, balancing_params const& ps, balancing_stats& st ) : ntk_( ntk ), rebalancing_fn_( rebalancing_fn ), ps_( ps ), st_( st ) { } Ntk run() { Ntk dest; node_map<arrival_time_pair<Ntk>, Ntk> old_to_new( ntk_ ); /* input arrival times and mapping */ old_to_new[ntk_.get_constant( false )] = {dest.get_constant( false ), 0u}; if ( ntk_.get_node( ntk_.get_constant( false ) ) != ntk_.get_node( ntk_.get_constant( true ) ) ) { old_to_new[ntk_.get_constant( true )] = {dest.get_constant( true ), 0u}; } ntk_.foreach_pi( [&]( auto const& n ) { old_to_new[n] = {dest.create_pi(), 0u}; } ); stopwatch<> t( st_.time_total ); const auto cuts = cut_enumeration<Ntk, true>( ntk_, ps_.cut_enumeration_ps, &st_.cut_enumeration_st ); uint32_t current_level{}; const auto size = ntk_.size(); progress_bar pbar{ntk_.size(), "balancing |{0}| node = {1:>4} / " + std::to_string( size ) + " current level = {2}", ps_.progress}; topo_view<Ntk>{ntk_}.foreach_node( [&]( auto const& n, auto index ) { pbar( index, index, current_level ); if ( ntk_.is_constant( n ) || ntk_.is_pi( n ) ) { return; } arrival_time_pair<Ntk> best{{}, std::numeric_limits<uint32_t>::max()}; uint32_t best_size{}; for ( auto& cut : cuts.cuts( ntk_.node_to_index( n ) ) ) { if ( cut->size() == 1u || kitty::is_const0( cuts.truth_table( *cut ) ) ) { continue; } std::vector<arrival_time_pair<Ntk>> arrival_times( cut->size() ); std::transform( cut->begin(), cut->end(), arrival_times.begin(), [&]( auto leaf ) { return old_to_new[ntk_.index_to_node( leaf )]; }); rebalancing_fn_( dest, cuts.truth_table( *cut ), arrival_times, best.level, best_size, [&]( arrival_time_pair<Ntk> const& cand, uint32_t cand_size ) { if ( cand.level < best.level || ( cand.level == best.level && cand_size < best_size ) ) { best = cand; best_size = cand_size; } }); } old_to_new[n] = best; current_level = std::max( current_level, best.level ); } ); ntk_.foreach_po( [&]( auto const& f ) { const auto s = old_to_new[f].f; dest.create_po( ntk_.is_complemented( f ) ? dest.create_not( s ) : s ); } ); return cleanup_dangling( dest ); } private: Ntk const& ntk_; rebalancing_function_t<Ntk> const& rebalancing_fn_; balancing_params const& ps_; balancing_stats& st_; }; } // namespace detail /*! Balancing of a logic network * * This function implements a dynamic-programming and cut-enumeration based * balancing algorithm. It returns a new network of the same type and performs * generic balancing by providing a rebalancing function. * \verbatim embed:rst Example .. code-block:: c++ const auto aig = ...; sop_balancing<aig_network> balance_fn; balance_params ps; ps.cut_enumeration_ps.cut_size = 6u; const auto balanced_aig = balance( aig, {balance_fn}, ps ); \endverbatim */ template<class Ntk> Ntk balancing( Ntk const& ntk, rebalancing_function_t<Ntk> const& rebalancing_fn = {}, balancing_params const& ps = {}, balancing_stats* pst = nullptr ) { static_assert( is_network_type_v<Ntk>, "Ntk is not a network type" ); static_assert( has_create_not_v<Ntk>, "Ntk does not implement the create_not method" ); static_assert( has_create_pi_v<Ntk>, "Ntk does not implement the create_pi method" ); static_assert( has_create_po_v<Ntk>, "Ntk does not implement the create_po method" ); static_assert( has_foreach_pi_v<Ntk>, "Ntk does not implement the foreach_pi method" ); static_assert( has_foreach_po_v<Ntk>, "Ntk does not implement the foreach_po method" ); static_assert( has_get_constant_v<Ntk>, "Ntk does not implement the get_constant method" ); static_assert( has_get_node_v<Ntk>, "Ntk does not implement the get_node method" ); static_assert( has_is_complemented_v<Ntk>, "Ntk does not implement the is_complemented method" ); static_assert( has_is_constant_v<Ntk>, "Ntk does not implement the is_constant method" ); static_assert( has_is_pi_v<Ntk>, "Ntk does not implement the is_pi method" ); static_assert( has_node_to_index_v<Ntk>, "Ntk does not implement the node_to_index method" ); static_assert( has_size_v<Ntk>, "Ntk does not implement the size method" ); balancing_stats st; const auto dest = detail::balancing_impl<Ntk>{ntk, rebalancing_fn, ps, st}.run(); if ( pst ) { *pst = st; } if ( ps.verbose ) { st.report(); } return dest; } } // namespace mockturtle <commit_msg>Only rewrite along critical path in balancing. (#353)<commit_after>/* mockturtle: C++ logic network library * Copyright (C) 2018-2019 EPFL * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /*! \file balancing.hpp \brief Cut-based depth-optimization \author Mathias Soeken */ #pragma once #include <cstdint> #include <functional> #include <limits> #include <memory> #include <optional> #include <utility> #include <vector> #include <fmt/format.h> #include <kitty/dynamic_truth_table.hpp> #include "../utils/cost_functions.hpp" #include "../utils/node_map.hpp" #include "../utils/progress_bar.hpp" #include "../utils/stopwatch.hpp" #include "../views/depth_view.hpp" #include "../views/topo_view.hpp" #include "cleanup.hpp" #include "cut_enumeration.hpp" namespace mockturtle { /*! \brief Parameters for balancing. */ struct balancing_params { /*! \brief Cut enumeration params. */ cut_enumeration_params cut_enumeration_ps; /*! \brief Optimize only on critical path. */ bool only_on_critical_path{false}; /*! \brief Show progress. */ bool progress{false}; /*! \brief Be verbose. */ bool verbose{false}; }; /*! \brief Statistics for balancing. */ struct balancing_stats { /*! \brief Total run-time. */ stopwatch<>::duration time_total{}; /*! \brief Cut enumeration run-time. */ cut_enumeration_stats cut_enumeration_st; /*! \brief Prints report. */ void report() const { fmt::print( "[i] total time = {:>5.2f} secs\n", to_seconds( time_total ) ); fmt::print( "[i] Cut enumeration stats\n" ); cut_enumeration_st.report(); } }; template<class Ntk> struct arrival_time_pair { signal<Ntk> f; uint32_t level; }; /*! \brief Callback function for `rebalancing_function_t`. * * This callback is used in the rebalancing function to announce a new candidate that * could be used for replacement in the main balancing algorithm. Using a callback * makes it possible to account for situations in which none, a single, or multiple * candidates are generated. * * The callback returns a pair composed of the output signal of the replacement * candidate and the level of the new candidate. Ideally, the rebalancing function * should not call the callback with candidates that a worse level. */ template<class Ntk> using rebalancing_function_callback_t = std::function<void(arrival_time_pair<Ntk> const&, uint32_t)>; template<class Ntk> using rebalancing_function_t = std::function<void(Ntk&, kitty::dynamic_truth_table const&, std::vector<arrival_time_pair<Ntk>> const&, uint32_t, uint32_t, rebalancing_function_callback_t<Ntk> const&)>; namespace detail { template<class Ntk, class CostFn> struct balancing_impl { balancing_impl( Ntk const& ntk, rebalancing_function_t<Ntk> const& rebalancing_fn, balancing_params const& ps, balancing_stats& st ) : ntk_( ntk ), rebalancing_fn_( rebalancing_fn ), ps_( ps ), st_( st ) { } Ntk run() { Ntk dest; node_map<arrival_time_pair<Ntk>, Ntk> old_to_new( ntk_ ); /* input arrival times and mapping */ old_to_new[ntk_.get_constant( false )] = {dest.get_constant( false ), 0u}; if ( ntk_.get_node( ntk_.get_constant( false ) ) != ntk_.get_node( ntk_.get_constant( true ) ) ) { old_to_new[ntk_.get_constant( true )] = {dest.get_constant( true ), 0u}; } ntk_.foreach_pi( [&]( auto const& n ) { old_to_new[n] = {dest.create_pi(), 0u}; } ); std::shared_ptr<depth_view<Ntk, CostFn>> depth_ntk; if ( ps_.only_on_critical_path ) { depth_ntk = std::make_shared<depth_view<Ntk, CostFn>>( ntk_ ); } stopwatch<> t( st_.time_total ); const auto cuts = cut_enumeration<Ntk, true>( ntk_, ps_.cut_enumeration_ps, &st_.cut_enumeration_st ); uint32_t current_level{}; const auto size = ntk_.size(); progress_bar pbar{ntk_.size(), "balancing |{0}| node = {1:>4} / " + std::to_string( size ) + " current level = {2}", ps_.progress}; topo_view<Ntk>{ntk_}.foreach_node( [&]( auto const& n, auto index ) { pbar( index, index, current_level ); if ( ntk_.is_constant( n ) || ntk_.is_pi( n ) ) { return; } if ( ps_.only_on_critical_path && !depth_ntk->is_on_critical_path( n ) ) { std::vector<signal<Ntk>> children; ntk_.foreach_fanin( n, [&]( auto const& f ) { const auto f_best = old_to_new[f].f; children.push_back( ntk_.is_complemented( f ) ? dest.create_not( f_best ) : f_best ); }); old_to_new[n] = {dest.clone_node( ntk_, n, children ), depth_ntk->level( n )}; return; } arrival_time_pair<Ntk> best{{}, std::numeric_limits<uint32_t>::max()}; uint32_t best_size{}; for ( auto& cut : cuts.cuts( ntk_.node_to_index( n ) ) ) { if ( cut->size() == 1u || kitty::is_const0( cuts.truth_table( *cut ) ) ) { continue; } std::vector<arrival_time_pair<Ntk>> arrival_times( cut->size() ); std::transform( cut->begin(), cut->end(), arrival_times.begin(), [&]( auto leaf ) { return old_to_new[ntk_.index_to_node( leaf )]; }); rebalancing_fn_( dest, cuts.truth_table( *cut ), arrival_times, best.level, best_size, [&]( arrival_time_pair<Ntk> const& cand, uint32_t cand_size ) { if ( cand.level < best.level || ( cand.level == best.level && cand_size < best_size ) ) { best = cand; best_size = cand_size; } }); } old_to_new[n] = best; current_level = std::max( current_level, best.level ); } ); ntk_.foreach_po( [&]( auto const& f ) { const auto s = old_to_new[f].f; dest.create_po( ntk_.is_complemented( f ) ? dest.create_not( s ) : s ); } ); return cleanup_dangling( dest ); } private: Ntk const& ntk_; rebalancing_function_t<Ntk> const& rebalancing_fn_; balancing_params const& ps_; balancing_stats& st_; }; } // namespace detail /*! Balancing of a logic network * * This function implements a dynamic-programming and cut-enumeration based * balancing algorithm. It returns a new network of the same type and performs * generic balancing by providing a rebalancing function. * * The template parameter `CostFn` is only used to compute the critical paths, * when the `only_on_critical_path` parameter is assigned true. Note that the * size for rewriting candidates is computed by the rebalancing function and * may not correspond to the cost given by CostFn. * \verbatim embed:rst Example .. code-block:: c++ const auto aig = ...; sop_balancing<aig_network> balance_fn; balance_params ps; ps.cut_enumeration_ps.cut_size = 6u; const auto balanced_aig = balance( aig, {balance_fn}, ps ); \endverbatim */ template<class Ntk, class CostFn = unit_cost<Ntk>> Ntk balancing( Ntk const& ntk, rebalancing_function_t<Ntk> const& rebalancing_fn = {}, balancing_params const& ps = {}, balancing_stats* pst = nullptr ) { static_assert( is_network_type_v<Ntk>, "Ntk is not a network type" ); static_assert( has_create_not_v<Ntk>, "Ntk does not implement the create_not method" ); static_assert( has_create_pi_v<Ntk>, "Ntk does not implement the create_pi method" ); static_assert( has_create_po_v<Ntk>, "Ntk does not implement the create_po method" ); static_assert( has_foreach_pi_v<Ntk>, "Ntk does not implement the foreach_pi method" ); static_assert( has_foreach_po_v<Ntk>, "Ntk does not implement the foreach_po method" ); static_assert( has_get_constant_v<Ntk>, "Ntk does not implement the get_constant method" ); static_assert( has_get_node_v<Ntk>, "Ntk does not implement the get_node method" ); static_assert( has_is_complemented_v<Ntk>, "Ntk does not implement the is_complemented method" ); static_assert( has_is_constant_v<Ntk>, "Ntk does not implement the is_constant method" ); static_assert( has_is_pi_v<Ntk>, "Ntk does not implement the is_pi method" ); static_assert( has_node_to_index_v<Ntk>, "Ntk does not implement the node_to_index method" ); static_assert( has_size_v<Ntk>, "Ntk does not implement the size method" ); balancing_stats st; const auto dest = detail::balancing_impl<Ntk, CostFn>{ntk, rebalancing_fn, ps, st}.run(); if ( pst ) { *pst = st; } if ( ps.verbose ) { st.report(); } return dest; } } // namespace mockturtle <|endoftext|>
<commit_before>#include "common.h" #include "World.h" #include "PositionComponent.h" #include "PlayerCameraComponent.h" void World::Init() { } void World::Update(DeltaTicks &, std::vector<Object *> &) { chunks.With([] (ChunksType &chunks) { //INFO(chunks.size()); }); if(cameraObj == nullptr) { return; } auto camera = cameraObj->Get<PlayerCameraComponent>(); if(camera != nullptr) { auto pos = cameraObj->Get<PositionComponent>(); if(pos != nullptr) { const unsigned char distance = 6; auto chunkSizeF = glm::fvec3(chunkSize); auto keyBase = glm::ivec3(glm::floor(pos->position.To<glm::fvec3>()) / chunkSizeF); auto jobM = engine->systems.Get<JobManager>(); /* clean up chunks outside distance */ chunks.With([this, distance, &keyBase] (ChunksType &chunks) { for(auto it = chunks.begin(); it != chunks.end();) { auto &keyTuple = it->first; auto obj = std::get<1>(it->second); if(abs(std::get<0>(keyTuple) -keyBase.x) > distance || abs(std::get<1>(keyTuple) -keyBase.y) > distance || abs(std::get<2>(keyTuple) -keyBase.z) > distance) { auto &status = std::get<0>(it->second); switch(status) { case ChunkStatus::Generating: status = ChunkStatus::Dying; break; case ChunkStatus::Alive: case ChunkStatus::Dead: if(obj != nullptr) { engine->RemoveObject(obj, false); obj->Pool(); } chunks.erase(it++); continue; } } ++it; } }); for(int d = 0; d <= distance; ++d) { for(int x = -d; x <= d; ++x) { for(int y = -d; y <= d; ++y) { for(int z = -d; z <= d; ++z) { auto key = keyBase + glm::ivec3(x, y, z); auto keyTuple = std::make_tuple(key.x, key.y, key.z); if(chunks.With<bool>([&keyTuple] (ChunksType &chunks) { return chunks.find(keyTuple) == chunks.end(); })) { chunks.With([&keyTuple] (ChunksType &chunks) { chunks.emplace(keyTuple, std::make_tuple(ChunkStatus::Generating, nullptr)); }); jobM->Do([this, jobM, key, keyTuple, chunkSizeF] () { auto dead = chunks.With<bool>([&keyTuple] (ChunksType &chunks) { auto &status = std::get<0>(chunks.at(keyTuple)); if(status == ChunkStatus::Dying) { status = ChunkStatus::Dead; return true; } else { return false; } }); if(dead) { return; } auto data = Generate(keyTuple); auto chunkObj = Chunk::New(chunkSize.x, chunkSize.y, chunkSize.z, std::move(data)); auto pos = chunkObj->Get<PositionComponent>(); auto chunkPos = glm::fvec3(key) * chunkSizeF; pos->position = Point(chunkPos.x, chunkPos.y, chunkPos.z + chunkSize.z, 1); jobM->Do([this, keyTuple, key, chunkSizeF, chunkObj] () { engine->AddObject(chunkObj); chunks.With([&keyTuple, chunkObj] (ChunksType &chunks) { chunks.at(keyTuple) = std::make_tuple(ChunkStatus::Alive, chunkObj); }); }, JobPriority::High, JobThread::Main); }, JobPriority::Normal, JobThread::Worker); } } } } } } } } void World::Destroy() { } void World::ObjectAdded(Object *obj) { auto camera = obj->Get<PlayerCameraComponent>(); if(camera != nullptr) { cameraObj = obj; } } std::vector<bool> World::Generate(const ChunkKeyType &keyTuple) const { /*const float start = -0.5, end = -0; static double factor = 1.0f; factor /= 1.0001f; auto r = factor * (start - end) + end;*/ const float scale = 0.5f; const float scaleX = scale, scaleY = scale * 2, scaleZ = scale; std::vector<bool> blocks; blocks.resize(chunkSize.x * chunkSize.y * chunkSize.z); float xIncr = 1.0f / chunkSize.x, yIncr = 1.0f / chunkSize.y, zIncr = 1.0f / chunkSize.z; int i = 0; for(float z = 0; z < 1; z += zIncr) { for(float x = 0; x < 1; x += xIncr) { for(float y = 0; y < 1; y += yIncr) { double random = noise.eval( ( std::get<0>(keyTuple) + x) * scaleX, ( std::get<1>(keyTuple) + y) * scaleY, (-std::get<2>(keyTuple) + z) * scaleZ ); blocks.at(i++) = random > 0.25f; } } } return blocks; } <commit_msg>Tweaked world generation cave factor<commit_after>#include "common.h" #include "World.h" #include "PositionComponent.h" #include "PlayerCameraComponent.h" void World::Init() { } void World::Update(DeltaTicks &, std::vector<Object *> &) { chunks.With([] (ChunksType &chunks) { //INFO(chunks.size()); }); if(cameraObj == nullptr) { return; } auto camera = cameraObj->Get<PlayerCameraComponent>(); if(camera != nullptr) { auto pos = cameraObj->Get<PositionComponent>(); if(pos != nullptr) { const unsigned char distance = 6; auto chunkSizeF = glm::fvec3(chunkSize); auto keyBase = glm::ivec3(glm::floor(pos->position.To<glm::fvec3>()) / chunkSizeF); auto jobM = engine->systems.Get<JobManager>(); /* clean up chunks outside distance */ chunks.With([this, distance, &keyBase] (ChunksType &chunks) { for(auto it = chunks.begin(); it != chunks.end();) { auto &keyTuple = it->first; auto obj = std::get<1>(it->second); if(abs(std::get<0>(keyTuple) -keyBase.x) > distance || abs(std::get<1>(keyTuple) -keyBase.y) > distance || abs(std::get<2>(keyTuple) -keyBase.z) > distance) { auto &status = std::get<0>(it->second); switch(status) { case ChunkStatus::Generating: status = ChunkStatus::Dying; break; case ChunkStatus::Alive: case ChunkStatus::Dead: if(obj != nullptr) { engine->RemoveObject(obj, false); obj->Pool(); } chunks.erase(it++); continue; } } ++it; } }); for(int d = 0; d <= distance; ++d) { for(int x = -d; x <= d; ++x) { for(int y = -d; y <= d; ++y) { for(int z = -d; z <= d; ++z) { auto key = keyBase + glm::ivec3(x, y, z); auto keyTuple = std::make_tuple(key.x, key.y, key.z); if(chunks.With<bool>([&keyTuple] (ChunksType &chunks) { return chunks.find(keyTuple) == chunks.end(); })) { chunks.With([&keyTuple] (ChunksType &chunks) { chunks.emplace(keyTuple, std::make_tuple(ChunkStatus::Generating, nullptr)); }); jobM->Do([this, jobM, key, keyTuple, chunkSizeF] () { auto dead = chunks.With<bool>([&keyTuple] (ChunksType &chunks) { auto &status = std::get<0>(chunks.at(keyTuple)); if(status == ChunkStatus::Dying) { status = ChunkStatus::Dead; return true; } else { return false; } }); if(dead) { return; } auto data = Generate(keyTuple); auto chunkObj = Chunk::New(chunkSize.x, chunkSize.y, chunkSize.z, std::move(data)); auto pos = chunkObj->Get<PositionComponent>(); auto chunkPos = glm::fvec3(key) * chunkSizeF; pos->position = Point(chunkPos.x, chunkPos.y, chunkPos.z + chunkSize.z, 1); jobM->Do([this, keyTuple, key, chunkSizeF, chunkObj] () { engine->AddObject(chunkObj); chunks.With([&keyTuple, chunkObj] (ChunksType &chunks) { chunks.at(keyTuple) = std::make_tuple(ChunkStatus::Alive, chunkObj); }); }, JobPriority::High, JobThread::Main); }, JobPriority::Normal, JobThread::Worker); } } } } } } } } void World::Destroy() { } void World::ObjectAdded(Object *obj) { auto camera = obj->Get<PlayerCameraComponent>(); if(camera != nullptr) { cameraObj = obj; } } std::vector<bool> World::Generate(const ChunkKeyType &keyTuple) const { /*const float start = -0.5, end = -0; static double factor = 1.0f; factor /= 1.0001f; auto r = factor * (start - end) + end;*/ const float scale = 0.5f; const float scaleX = scale, scaleY = scale * 2, scaleZ = scale; std::vector<bool> blocks; blocks.resize(chunkSize.x * chunkSize.y * chunkSize.z); float xIncr = 1.0f / chunkSize.x, yIncr = 1.0f / chunkSize.y, zIncr = 1.0f / chunkSize.z; int i = 0; for(float z = 0; z < 1; z += zIncr) { for(float x = 0; x < 1; x += xIncr) { for(float y = 0; y < 1; y += yIncr) { double random = noise.eval( ( std::get<0>(keyTuple) + x) * scaleX, ( std::get<1>(keyTuple) + y) * scaleY, (-std::get<2>(keyTuple) + z) * scaleZ ); blocks.at(i++) = random > 0.45f; } } } return blocks; } <|endoftext|>
<commit_before>// ---------------------------------------------------------------------------- // Callbacks.cpp // // // Authors: // Peter Polidoro [email protected] // ---------------------------------------------------------------------------- #include "Callbacks.h" namespace callbacks { // Callbacks must be non-blocking (avoid 'delay') // // modular_device.getParameterValue must be cast to either: // const char* // long // double // bool // ArduinoJson::JsonArray& // ArduinoJson::JsonObject& // // For more info read about ArduinoJson parsing https://github.com/janelia-arduino/ArduinoJson // // modular_device.getSavedVariableValue type must match the saved variable default type // modular_device.setSavedVariableValue type must match the saved variable default type void executeStandaloneCallbackCallback() { controller.executeStandaloneCallback(); } void getDspVar1Callback() { int value = controller.getDspVar1(); modular_device.addResultToResponse(value); } void setDspVar1Callback() { long value = modular_device.getParameterValue(constants::dsp_var1_parameter_name); controller.setDspVar1(value); } void getIntVar1Callback() { uint8_t value = controller.getIntVar1(); modular_device.addResultToResponse(value); } void setIntVar1Callback() { long value = modular_device.getParameterValue(constants::int_var1_parameter_name); controller.setIntVar1(value); } void getIntVar2Callback() { uint8_t value = controller.getIntVar2(); modular_device.addResultToResponse(value); } void setIntVar2Callback() { long value = modular_device.getParameterValue(constants::int_var2_parameter_name); controller.setIntVar2(value); } // Standalone Callbacks void addIntVar1ToDspVar1Callback() { int dis_var1 = controller.getDspVar1(); int int_var1 = controller.getIntVar1(); controller.setDspVar1(dis_var1+int_var1); } void subIntVar2FromDspVar1Callback() { int dis_var1 = controller.getDspVar1(); int int_var2 = controller.getIntVar2(); controller.setDspVar1(dis_var1-int_var2); } } <commit_msg>addToResponse -> writeToResponse.<commit_after>// ---------------------------------------------------------------------------- // Callbacks.cpp // // // Authors: // Peter Polidoro [email protected] // ---------------------------------------------------------------------------- #include "Callbacks.h" namespace callbacks { // Callbacks must be non-blocking (avoid 'delay') // // modular_device.getParameterValue must be cast to either: // const char* // long // double // bool // ArduinoJson::JsonArray& // ArduinoJson::JsonObject& // // For more info read about ArduinoJson parsing https://github.com/janelia-arduino/ArduinoJson // // modular_device.getSavedVariableValue type must match the saved variable default type // modular_device.setSavedVariableValue type must match the saved variable default type void executeStandaloneCallbackCallback() { controller.executeStandaloneCallback(); } void getDspVar1Callback() { int value = controller.getDspVar1(); modular_device.writeResultToResponse(value); } void setDspVar1Callback() { long value = modular_device.getParameterValue(constants::dsp_var1_parameter_name); controller.setDspVar1(value); } void getIntVar1Callback() { uint8_t value = controller.getIntVar1(); modular_device.writeResultToResponse(value); } void setIntVar1Callback() { long value = modular_device.getParameterValue(constants::int_var1_parameter_name); controller.setIntVar1(value); } void getIntVar2Callback() { uint8_t value = controller.getIntVar2(); modular_device.writeResultToResponse(value); } void setIntVar2Callback() { long value = modular_device.getParameterValue(constants::int_var2_parameter_name); controller.setIntVar2(value); } // Standalone Callbacks void addIntVar1ToDspVar1Callback() { int dis_var1 = controller.getDspVar1(); int int_var1 = controller.getIntVar1(); controller.setDspVar1(dis_var1+int_var1); } void subIntVar2FromDspVar1Callback() { int dis_var1 = controller.getDspVar1(); int int_var2 = controller.getIntVar2(); controller.setDspVar1(dis_var1-int_var2); } } <|endoftext|>
<commit_before>/** \file undistort.cc Apply Lensfun corrections to a PNM file in place. This means, the original file is overwritten. The command line parameters are: - path to the PNM file - x coordinate of top left corner - y coordinate of top left corner - x coordinate of top right corner - y coordinate of top right corner - x coordinate of bottom left corner - y coordinate of bottom left corner - x coordinate of bottom right corner - y coordinate of bottom right corner All coordinates are pixel coordinates, with the top left of the image the origin. The corners must be the corners of a perfect rectangle which was taken a picture of, e.g. a sheet of paper. These are used for the perspective correction as well as the rotation, so that the edges of the rectangle are parellel to the image borders. The program returns the position and the dimensions of the rectangle <b>in the output image</b> to stdout in JSON format: \code{.json} [x₀, y₀, width, height] \endcode Here, x₀ and y₀ are the coordinates of the top left corner, and width and height are the dimensions of the rectangle. This program does not apply colour corrections such as vignetting correction, as those are handled by kamscan.py using flat field images. */ #include <fstream> #include <vector> #include <iterator> #include <iostream> #include <string> #include <algorithm> #include <cmath> #include "lensfun.h" /** Class for bitmap data. In case of 2 bytes per channel, network byte order is assumed. */ class Image { public: Image(int width, int height, int channel_size, int channels); Image() {}; Image(const Image &image); /** Get the channel intensity at a certian coordinate. \param x x coordinate \param y y coordinate \param channel index of the channel (for greyscale, it is always zero; for RGB, it is 0, 1, or 2) \return raw integer value of the intensity of this channel at this position */ int get(int x, int y, int channel); /** Get the channel intensity at a certian coordinate. The coordinates are floats and may contain fractions. In this case, the intensity is calculated using bilinear interpolation between the four pixels around this coordinate. \param x x coordinate \param y y coordinate \param channel index of the channel (for greyscale, it is always zero; for RGB, it is 0, 1, or 2) \return raw integer value of the intensity of this channel at this position */ int get(float x, float y, int channel); /** Set the channel intensity at a certian coordinate. \param x x coordinate \param y y coordinate \param channel index of the channel (for greyscale, it is always zero; for RGB, it is 0, 1, or 2) \param value raw integer value of the intensity of this channel at this position */ void set(int x, int y, int channel, int value); /** Determine the channel descriptions. This is used by Lensfun internally and necessary if you want to apply colour corrections, e.g. vignetting correction. \return the components of each pixel */ int components(); /** Determine the pixel format à la Lensfun. It is derived from channel_size. \return the pixel format as it is needed by Lensfun */ lfPixelFormat pixel_format(); int width, height; ///< width and height of the image in pixels int channels; ///< number of channels; may be 1 (greyscale) or 3 (RGB) /** the raw data (1:1 dump of the PNM content, without header) */ std::vector<unsigned char> data; private: friend std::istream& operator >>(std::istream &inputStream, Image &other); friend std::ostream& operator <<(std::ostream &outputStream, const Image &other); int channel_size; ///< width of one channel in bytes; may be 1 or 2 }; Image::Image(int width, int height, int channel_size, int channels) : width(width), height(height), channel_size(channel_size), channels(channels) { data.resize(width * height * channel_size * channels); } Image::Image(const Image &image) : width(image.width), height(image.height), channel_size(image.channel_size), channels(image.channels) { } int Image::get(int x, int y, int channel) { if (x < 0 || x >= width || y < 0 || y >= height) return 0; int position = channel_size * (channels * (y * width + x) + channel); int result = static_cast<int>(data[position]); if (channel_size == 2) result = (result << 8) + static_cast<int>(data[position + 1]); return result; } int Image::get(float x, float y, int channel) { float dummy; int x0 = static_cast<int>(x); int y0 = static_cast<int>(y); float i0 = static_cast<float>(get(x0, y0, channel)); float i1 = static_cast<float>(get(x0 + 1, y0, channel)); float i2 = static_cast<float>(get(x0, y0 + 1, channel)); float i3 = static_cast<float>(get(x0 + 1, y0 + 1, channel)); float fraction_x = std::modf(x, &dummy); float i01 = (1 - fraction_x) * i0 + fraction_x * i1; float i23 = (1 - fraction_x) * i2 + fraction_x * i3; float fraction_y = std::modf(y, &dummy); return static_cast<int>(std::round((1 - fraction_y) * i01 + fraction_y * i23)); } void Image::set(int x, int y, int channel, int value) { if (x >= 0 && x < width && y >= 0 && y < height) { int position = channel_size * (channels * (y * width + x) + channel); if (channel_size == 1) data[position] = static_cast<unsigned char>(value); else if (channel_size == 2) { data[position] = static_cast<unsigned char>(value >> 8); data[position + 1] = static_cast<unsigned char>(value & 256); } } } int Image::components() { switch (channels) { case 1: return LF_CR_1(INTENSITY); case 3: return LF_CR_3(RED, GREEN, BLUE); default: throw std::runtime_error("Invalid value of 'channels'."); } } lfPixelFormat Image::pixel_format() { switch (channel_size) { case 1: return LF_PF_U8; case 2: return LF_PF_U16; default: throw std::runtime_error("Invalid value of 'channel_size'."); } } std::istream& operator >>(std::istream &inputStream, Image &other) { std::string magic_number; int maximum_color_value; inputStream >> magic_number; if (magic_number == "P5") other.channels = 1; else if (magic_number == "P6") other.channels = 3; else throw std::runtime_error("Invalid input file. Must start with 'P5' or 'P6'."); inputStream >> other.width >> other.height >> maximum_color_value; inputStream.get(); // skip the trailing white space switch (maximum_color_value) { case 255: other.channel_size = 1; break; case 65535: other.channel_size = 2; break; default: throw std::runtime_error("Invalid PPM file: Maximum color value must be 255 or 65535."); } size_t size = other.width * other.height * other.channel_size * other.channels; other.data.resize(size); inputStream.read(reinterpret_cast<char*>(other.data.data()), size); return inputStream; } std::ostream& operator <<(std::ostream &outputStream, const Image &other) { outputStream << (other.channels == 3 ? "P6" : "P5") << "\n" << other.width << " " << other.height << "\n" << (other.channel_size == 1 ? "255" : "65535") << "\n"; outputStream.write(reinterpret_cast<const char*>(other.data.data()), other.data.size()); return outputStream; } int main(int argc, char* argv[]) { if (argc != 10) { std::cerr << "You must give path to input file as well as all four corner coordinates.\n"; return -1; } lfDatabase ldb; if (ldb.Load() != LF_NO_ERROR) { std::cerr << "Database could not be loaded\n"; return -1; } const lfCamera *camera; const lfCamera **cameras = ldb.FindCamerasExt(NULL, "NEX-7"); if (cameras && !cameras[1]) camera = cameras[0]; else { std::cerr << "Cannot find unique camera in database. " << sizeof(cameras) << " cameras found.\n"; lf_free(cameras); return -1; } lf_free(cameras); const lfLens *lens; const lfLens **lenses = ldb.FindLenses(camera, NULL, "E 50mm f/1.8 OSS (kamscan)"); if (lenses && !lenses[1]) { lens = lenses[0]; } else if (!lenses) { std::cerr << "Cannot find lens in database\n"; lf_free(lenses); return -1; } else { std::cerr << "Lens name ambiguous\n"; } lf_free(lenses); Image image; { std::ifstream file(argv[1], std::ios::binary); file >> image; } lfModifier modifier(camera->CropFactor, image.width, image.height, image.pixel_format()); lfModifier pc_coord_modifier(camera->CropFactor, image.width, image.height, image.pixel_format(), true); lfModifier back_modifier(camera->CropFactor, image.width, image.height, image.pixel_format(), true); if (!modifier.EnableDistortionCorrection(lens, 50) || !back_modifier.EnableDistortionCorrection(lens, 50) || !pc_coord_modifier.EnableDistortionCorrection(lens, 50)) { std::cerr << "Failed to activate undistortion\n"; return -1; } if (image.channels == 3) if (!modifier.EnableTCACorrection(lens, 50)) { std::cerr << "Failed to activate un-TCA\n"; return -1; } std::vector<float> x, y; x.push_back(std::stof(argv[2])); y.push_back(std::stof(argv[3])); x.push_back(std::stof(argv[6])); y.push_back(std::stof(argv[7])); x.push_back(std::stof(argv[4])); y.push_back(std::stof(argv[5])); x.push_back(std::stof(argv[8])); y.push_back(std::stof(argv[9])); x.push_back(std::stof(argv[2])); y.push_back(std::stof(argv[3])); x.push_back(std::stof(argv[4])); y.push_back(std::stof(argv[5])); std::vector<float> x_undist, y_undist; for (int i = 0; i < x.size(); i++) { float result[2]; pc_coord_modifier.ApplyGeometryDistortion(x[i], y[i], 1, 1, result); x_undist.push_back(result[0]); y_undist.push_back(result[1]); } if (!modifier.EnablePerspectiveCorrection(lens, 50, x_undist.data(), y_undist.data(), 6, 0) || !back_modifier.EnablePerspectiveCorrection(lens, 50, x_undist.data(), y_undist.data(), 6, 0)) { std::cerr << "Failed to activate perspective correction\n"; return -1; } std::vector<float> res(image.width * image.height * 2 * image.channels); if (image.channels == 3) modifier.ApplySubpixelGeometryDistortion(0, 0, image.width, image.height, res.data()); else modifier.ApplyGeometryDistortion(0, 0, image.width, image.height, res.data()); Image new_image = image; for (int x = 0; x < image.width; x++) for (int y = 0; y < image.height; y++) { int position = 2 * image.channels * (y * image.width + x); float source_x_R = res[position]; float source_y_R = res[position + 1]; new_image.set(x, y, 0, image.get(source_x_R, source_y_R, 0)); if (image.channels == 3) { float source_x_G = res[position + 2]; float source_y_G = res[position + 3]; float source_x_B = res[position + 4]; float source_y_B = res[position + 5]; new_image.set(x, y, 1, image.get(source_x_G, source_y_G, 1)); new_image.set(x, y, 2, image.get(source_x_B, source_y_B, 2)); } } std::ofstream file(argv[1], std::ios::binary); file << new_image; for (int i = 0; i < 4; i++) { float result[2]; back_modifier.ApplyGeometryDistortion(x[i], y[i], 1, 1, result); x[i] = result[0]; y[i] = result[1]; } std::cout << "[" << std::min(x[0], x[2]) << ", " << std::min(y[0], y[1]) << ", " << std::max(x[1], x[3]) - std::min(x[0], x[2]) << ", " << std::max(y[2], y[3]) - std::min(y[0], y[1]) << "]\n"; return 0; } <commit_msg>Improved source code layout.<commit_after>/** \file undistort.cc Apply Lensfun corrections to a PNM file in place. This means, the original file is overwritten. The command line parameters are: - path to the PNM file - x coordinate of top left corner - y coordinate of top left corner - x coordinate of top right corner - y coordinate of top right corner - x coordinate of bottom left corner - y coordinate of bottom left corner - x coordinate of bottom right corner - y coordinate of bottom right corner All coordinates are pixel coordinates, with the top left of the image the origin. The corners must be the corners of a perfect rectangle which was taken a picture of, e.g. a sheet of paper. These are used for the perspective correction as well as the rotation, so that the edges of the rectangle are parellel to the image borders. The program returns the position and the dimensions of the rectangle <b>in the output image</b> to stdout in JSON format: \code{.json} [x₀, y₀, width, height] \endcode Here, x₀ and y₀ are the coordinates of the top left corner, and width and height are the dimensions of the rectangle. This program does not apply colour corrections such as vignetting correction, as those are handled by kamscan.py using flat field images. */ #include <fstream> #include <vector> #include <iterator> #include <iostream> #include <string> #include <algorithm> #include <cmath> #include "lensfun.h" /** Class for bitmap data. In case of 2 bytes per channel, network byte order is assumed. */ class Image { public: Image(int width, int height, int channel_size, int channels); Image() {}; Image(const Image &image); /** Get the channel intensity at a certian coordinate. \param x x coordinate \param y y coordinate \param channel index of the channel (for greyscale, it is always zero; for RGB, it is 0, 1, or 2) \return raw integer value of the intensity of this channel at this position */ int get(int x, int y, int channel); /** Get the channel intensity at a certian coordinate. The coordinates are floats and may contain fractions. In this case, the intensity is calculated using bilinear interpolation between the four pixels around this coordinate. \param x x coordinate \param y y coordinate \param channel index of the channel (for greyscale, it is always zero; for RGB, it is 0, 1, or 2) \return raw integer value of the intensity of this channel at this position */ int get(float x, float y, int channel); /** Set the channel intensity at a certian coordinate. \param x x coordinate \param y y coordinate \param channel index of the channel (for greyscale, it is always zero; for RGB, it is 0, 1, or 2) \param value raw integer value of the intensity of this channel at this position */ void set(int x, int y, int channel, int value); /** Determine the channel descriptions. This is used by Lensfun internally and necessary if you want to apply colour corrections, e.g. vignetting correction. \return the components of each pixel */ int components(); /** Determine the pixel format à la Lensfun. It is derived from channel_size. \return the pixel format as it is needed by Lensfun */ lfPixelFormat pixel_format(); int width, height; ///< width and height of the image in pixels int channels; ///< number of channels; may be 1 (greyscale) or 3 (RGB) /** the raw data (1:1 dump of the PNM content, without header) */ std::vector<unsigned char> data; private: friend std::istream& operator>>(std::istream &inputStream, Image &other); friend std::ostream& operator<<(std::ostream &outputStream, const Image &other); int channel_size; ///< width of one channel in bytes; may be 1 or 2 }; Image::Image(int width, int height, int channel_size, int channels) : width(width), height(height), channel_size(channel_size), channels(channels) { data.resize(width * height * channel_size * channels); } Image::Image(const Image &image) : width(image.width), height(image.height), channel_size(image.channel_size), channels(image.channels) { } int Image::get(int x, int y, int channel) { if (x < 0 || x >= width || y < 0 || y >= height) return 0; int position = channel_size * (channels * (y * width + x) + channel); int result = static_cast<int>(data[position]); if (channel_size == 2) result = (result << 8) + static_cast<int>(data[position + 1]); return result; } int Image::get(float x, float y, int channel) { float dummy; int x0 = static_cast<int>(x); int y0 = static_cast<int>(y); float i0 = static_cast<float>(get(x0, y0, channel)); float i1 = static_cast<float>(get(x0 + 1, y0, channel)); float i2 = static_cast<float>(get(x0, y0 + 1, channel)); float i3 = static_cast<float>(get(x0 + 1, y0 + 1, channel)); float fraction_x = std::modf(x, &dummy); float i01 = (1 - fraction_x) * i0 + fraction_x * i1; float i23 = (1 - fraction_x) * i2 + fraction_x * i3; float fraction_y = std::modf(y, &dummy); return static_cast<int>(std::round((1 - fraction_y) * i01 + fraction_y * i23)); } void Image::set(int x, int y, int channel, int value) { if (x >= 0 && x < width && y >= 0 && y < height) { int position = channel_size * (channels * (y * width + x) + channel); if (channel_size == 1) data[position] = static_cast<unsigned char>(value); else if (channel_size == 2) { data[position] = static_cast<unsigned char>(value >> 8); data[position + 1] = static_cast<unsigned char>(value & 256); } } } int Image::components() { switch (channels) { case 1: return LF_CR_1(INTENSITY); case 3: return LF_CR_3(RED, GREEN, BLUE); default: throw std::runtime_error("Invalid value of 'channels'."); } } lfPixelFormat Image::pixel_format() { switch (channel_size) { case 1: return LF_PF_U8; case 2: return LF_PF_U16; default: throw std::runtime_error("Invalid value of 'channel_size'."); } } std::istream& operator>>(std::istream &inputStream, Image &other) { std::string magic_number; int maximum_color_value; inputStream >> magic_number; if (magic_number == "P5") other.channels = 1; else if (magic_number == "P6") other.channels = 3; else throw std::runtime_error("Invalid input file. Must start with 'P5' or 'P6'."); inputStream >> other.width >> other.height >> maximum_color_value; inputStream.get(); // skip the trailing white space switch (maximum_color_value) { case 255: other.channel_size = 1; break; case 65535: other.channel_size = 2; break; default: throw std::runtime_error("Invalid PPM file: Maximum color value must be 255 or 65535."); } size_t size = other.width * other.height * other.channel_size * other.channels; other.data.resize(size); inputStream.read(reinterpret_cast<char*>(other.data.data()), size); return inputStream; } std::ostream& operator<<(std::ostream &outputStream, const Image &other) { outputStream << (other.channels == 3 ? "P6" : "P5") << "\n" << other.width << " " << other.height << "\n" << (other.channel_size == 1 ? "255" : "65535") << "\n"; outputStream.write(reinterpret_cast<const char*>(other.data.data()), other.data.size()); return outputStream; } int main(int argc, char* argv[]) { if (argc != 10) { std::cerr << "You must give path to input file as well as all four corner coordinates.\n"; return -1; } lfDatabase ldb; if (ldb.Load() != LF_NO_ERROR) { std::cerr << "Database could not be loaded\n"; return -1; } const lfCamera *camera; const lfCamera **cameras = ldb.FindCamerasExt(NULL, "NEX-7"); if (cameras && !cameras[1]) camera = cameras[0]; else { std::cerr << "Cannot find unique camera in database. " << sizeof(cameras) << " cameras found.\n"; lf_free(cameras); return -1; } lf_free(cameras); const lfLens *lens; const lfLens **lenses = ldb.FindLenses(camera, NULL, "E 50mm f/1.8 OSS (kamscan)"); if (lenses && !lenses[1]) { lens = lenses[0]; } else if (!lenses) { std::cerr << "Cannot find lens in database\n"; lf_free(lenses); return -1; } else { std::cerr << "Lens name ambiguous\n"; } lf_free(lenses); Image image; { std::ifstream file(argv[1], std::ios::binary); file >> image; } lfModifier modifier(camera->CropFactor, image.width, image.height, image.pixel_format()); lfModifier pc_coord_modifier(camera->CropFactor, image.width, image.height, image.pixel_format(), true); lfModifier back_modifier(camera->CropFactor, image.width, image.height, image.pixel_format(), true); if (!modifier.EnableDistortionCorrection(lens, 50) || !back_modifier.EnableDistortionCorrection(lens, 50) || !pc_coord_modifier.EnableDistortionCorrection(lens, 50)) { std::cerr << "Failed to activate undistortion\n"; return -1; } if (image.channels == 3) if (!modifier.EnableTCACorrection(lens, 50)) { std::cerr << "Failed to activate un-TCA\n"; return -1; } std::vector<float> x, y; x.push_back(std::stof(argv[2])); y.push_back(std::stof(argv[3])); x.push_back(std::stof(argv[6])); y.push_back(std::stof(argv[7])); x.push_back(std::stof(argv[4])); y.push_back(std::stof(argv[5])); x.push_back(std::stof(argv[8])); y.push_back(std::stof(argv[9])); x.push_back(std::stof(argv[2])); y.push_back(std::stof(argv[3])); x.push_back(std::stof(argv[4])); y.push_back(std::stof(argv[5])); std::vector<float> x_undist, y_undist; for (int i = 0; i < x.size(); i++) { float result[2]; pc_coord_modifier.ApplyGeometryDistortion(x[i], y[i], 1, 1, result); x_undist.push_back(result[0]); y_undist.push_back(result[1]); } if (!modifier.EnablePerspectiveCorrection(lens, 50, x_undist.data(), y_undist.data(), 6, 0) || !back_modifier.EnablePerspectiveCorrection(lens, 50, x_undist.data(), y_undist.data(), 6, 0)) { std::cerr << "Failed to activate perspective correction\n"; return -1; } std::vector<float> res(image.width * image.height * 2 * image.channels); if (image.channels == 3) modifier.ApplySubpixelGeometryDistortion(0, 0, image.width, image.height, res.data()); else modifier.ApplyGeometryDistortion(0, 0, image.width, image.height, res.data()); Image new_image = image; for (int x = 0; x < image.width; x++) for (int y = 0; y < image.height; y++) { int position = 2 * image.channels * (y * image.width + x); float source_x_R = res[position]; float source_y_R = res[position + 1]; new_image.set(x, y, 0, image.get(source_x_R, source_y_R, 0)); if (image.channels == 3) { float source_x_G = res[position + 2]; float source_y_G = res[position + 3]; float source_x_B = res[position + 4]; float source_y_B = res[position + 5]; new_image.set(x, y, 1, image.get(source_x_G, source_y_G, 1)); new_image.set(x, y, 2, image.get(source_x_B, source_y_B, 2)); } } std::ofstream file(argv[1], std::ios::binary); file << new_image; for (int i = 0; i < 4; i++) { float result[2]; back_modifier.ApplyGeometryDistortion(x[i], y[i], 1, 1, result); x[i] = result[0]; y[i] = result[1]; } std::cout << "[" << std::min(x[0], x[2]) << ", " << std::min(y[0], y[1]) << ", " << std::max(x[1], x[3]) - std::min(x[0], x[2]) << ", " << std::max(y[2], y[3]) - std::min(y[0], y[1]) << "]\n"; return 0; } <|endoftext|>
<commit_before>#include <silicium/http/receive_request.hpp> #include <silicium/http/generate_response.hpp> #include <silicium/asio/writing_observable.hpp> #include <silicium/asio/tcp_acceptor.hpp> #include <silicium/observable/transform.hpp> #include <silicium/observable/spawn_coroutine.hpp> #include <silicium/observable/spawn_observable.hpp> #include <silicium/sink/iterator_sink.hpp> #include <silicium/terminate_on_exception.hpp> #include <iostream> #include <boost/algorithm/string/predicate.hpp> #if SILICIUM_HAS_SPAWN_COROUTINE namespace { template <class YieldContext> void serve_client(boost::asio::ip::tcp::socket &client, YieldContext &&yield) { auto maybe_request = Si::http::receive_request(client, yield); if (maybe_request.is_error()) { //The header was incomplete, maybe the connecting was closed. //If we want to know the reason, the error_extracting_source remembered it: boost::system::error_code error = maybe_request.error(); boost::ignore_unused_variable_warning(error); return; } if (!maybe_request.get()) { //syntax error in the request return; } Si::http::request const &request = *maybe_request.get(); if (boost::algorithm::iequals(request.method, "CONNECT")) { boost::asio::ip::tcp::socket proxy_socket(client.get_io_service()); } else { std::vector<char> response; { auto response_writer = Si::make_container_sink(response); Si::http::generate_status_line(response_writer, "HTTP/1.0", "200", "OK"); boost::string_ref const content = "Hello, visitor!"; Si::http::generate_header(response_writer, "Content-Length", boost::lexical_cast<Si::noexcept_string>(content.size())); Si::http::finish_headers(response_writer); Si::append(response_writer, content); } //you can handle the error if you want boost::system::error_code error = Si::asio::write(client, Si::make_memory_range(response), yield); } //ignore shutdown failures, they do not matter here boost::system::error_code error; client.shutdown(boost::asio::ip::tcp::socket::shutdown_both, error); } boost::system::error_code spawn_server(boost::asio::io_service &io) { boost::system::error_code ec; //use a unique_ptr to support older versions of Boost where acceptor was not movable auto acceptor = Si::make_unique<boost::asio::ip::tcp::acceptor>(io); acceptor->open(boost::asio::ip::tcp::v4(), ec); if (ec) { return ec; } acceptor->bind(boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4(), 8080), ec); if (ec) { return ec; } acceptor->listen(boost::asio::ip::tcp::acceptor::max_connections, ec); if (ec) { return ec; } Si::spawn_observable( Si::transform( Si::asio::make_tcp_acceptor(std::move(acceptor)), [](Si::asio::tcp_acceptor_result maybe_client) { auto client = maybe_client.get(); Si::spawn_coroutine([client](Si::spawn_context yield) { serve_client(*client, yield); }); } ) ); return {}; } } #endif int main() { boost::asio::io_service io; #if SILICIUM_HAS_SPAWN_COROUTINE boost::system::error_code ec = spawn_server(io); if (ec) { std::cerr << ec << ": " << ec.message() << '\n'; return 1; } #else std::cerr << "This example requires coroutine support\n"; #endif io.run(); } <commit_msg>silence unused variable warning<commit_after>#include <silicium/http/receive_request.hpp> #include <silicium/http/generate_response.hpp> #include <silicium/asio/writing_observable.hpp> #include <silicium/asio/tcp_acceptor.hpp> #include <silicium/observable/transform.hpp> #include <silicium/observable/spawn_coroutine.hpp> #include <silicium/observable/spawn_observable.hpp> #include <silicium/sink/iterator_sink.hpp> #include <silicium/terminate_on_exception.hpp> #include <iostream> #include <boost/algorithm/string/predicate.hpp> #if SILICIUM_HAS_SPAWN_COROUTINE namespace { template <class YieldContext> void serve_client(boost::asio::ip::tcp::socket &client, YieldContext &&yield) { auto maybe_request = Si::http::receive_request(client, yield); if (maybe_request.is_error()) { //The header was incomplete, maybe the connecting was closed. //If we want to know the reason, the error_extracting_source remembered it: boost::system::error_code error = maybe_request.error(); boost::ignore_unused_variable_warning(error); return; } if (!maybe_request.get()) { //syntax error in the request return; } Si::http::request const &request = *maybe_request.get(); if (boost::algorithm::iequals(request.method, "CONNECT")) { boost::asio::ip::tcp::socket proxy_socket(client.get_io_service()); } else { std::vector<char> response; { auto response_writer = Si::make_container_sink(response); Si::http::generate_status_line(response_writer, "HTTP/1.0", "200", "OK"); boost::string_ref const content = "Hello, visitor!"; Si::http::generate_header(response_writer, "Content-Length", boost::lexical_cast<Si::noexcept_string>(content.size())); Si::http::finish_headers(response_writer); Si::append(response_writer, content); } //you can handle the error if you want boost::system::error_code error = Si::asio::write(client, Si::make_memory_range(response), yield); boost::ignore_unused_variable_warning(error); } //ignore shutdown failures, they do not matter here boost::system::error_code error; client.shutdown(boost::asio::ip::tcp::socket::shutdown_both, error); } boost::system::error_code spawn_server(boost::asio::io_service &io) { boost::system::error_code ec; //use a unique_ptr to support older versions of Boost where acceptor was not movable auto acceptor = Si::make_unique<boost::asio::ip::tcp::acceptor>(io); acceptor->open(boost::asio::ip::tcp::v4(), ec); if (ec) { return ec; } acceptor->bind(boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4(), 8080), ec); if (ec) { return ec; } acceptor->listen(boost::asio::ip::tcp::acceptor::max_connections, ec); if (ec) { return ec; } Si::spawn_observable( Si::transform( Si::asio::make_tcp_acceptor(std::move(acceptor)), [](Si::asio::tcp_acceptor_result maybe_client) { auto client = maybe_client.get(); Si::spawn_coroutine([client](Si::spawn_context yield) { serve_client(*client, yield); }); } ) ); return {}; } } #endif int main() { boost::asio::io_service io; #if SILICIUM_HAS_SPAWN_COROUTINE boost::system::error_code ec = spawn_server(io); if (ec) { std::cerr << ec << ": " << ec.message() << '\n'; return 1; } #else std::cerr << "This example requires coroutine support\n"; #endif io.run(); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef FLUSHER_H #define FLUSHER_H 1 #include "common.hh" #include "ep.hh" #include "dispatcher.hh" enum flusher_state { initializing, running, pausing, paused, stopping, stopped }; class Flusher; class FlusherStepper : public DispatcherCallback { public: FlusherStepper(Flusher* f) : flusher(f) { } bool callback(Dispatcher &d, TaskId t); private: Flusher *flusher; }; class Flusher { public: Flusher(EventuallyPersistentStore *st, Dispatcher *d) : store(st), _state(initializing), dispatcher(d), flushQueue(NULL) { } ~Flusher() { stop(); wait(); } bool stop(); void wait(); bool pause(); bool resume(); void initialize(TaskId); void start(void); void wake(void); bool step(Dispatcher&, TaskId); bool transition_state(enum flusher_state to); enum flusher_state state() const; const char * stateName() const; private: int doFlush(); void completeFlush(); void schedule_UNLOCKED(); EventuallyPersistentStore *store; volatile enum flusher_state _state; Mutex taskMutex; TaskId task; Dispatcher *dispatcher; const char * stateName(enum flusher_state st) const; // Current flush cycle state. int flushRv; std::queue<QueuedItem> *flushQueue; std::queue<QueuedItem> *rejectQueue; rel_time_t flushStart; DISALLOW_COPY_AND_ASSIGN(Flusher); }; #endif /* FLUSHER_H */ <commit_msg>bug 2208 - Log if the flusher isn't in stopped state at destruct time.<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef FLUSHER_H #define FLUSHER_H 1 #include "common.hh" #include "ep.hh" #include "dispatcher.hh" enum flusher_state { initializing, running, pausing, paused, stopping, stopped }; class Flusher; class FlusherStepper : public DispatcherCallback { public: FlusherStepper(Flusher* f) : flusher(f) { } bool callback(Dispatcher &d, TaskId t); private: Flusher *flusher; }; class Flusher { public: Flusher(EventuallyPersistentStore *st, Dispatcher *d) : store(st), _state(initializing), dispatcher(d), flushQueue(NULL) { } ~Flusher() { if (_state != stopped) { getLogger()->log(EXTENSION_LOG_WARN, NULL, "Flusher being destroyed in state %s\n", stateName(_state)); } } bool stop(); void wait(); bool pause(); bool resume(); void initialize(TaskId); void start(void); void wake(void); bool step(Dispatcher&, TaskId); bool transition_state(enum flusher_state to); enum flusher_state state() const; const char * stateName() const; private: int doFlush(); void completeFlush(); void schedule_UNLOCKED(); EventuallyPersistentStore *store; volatile enum flusher_state _state; Mutex taskMutex; TaskId task; Dispatcher *dispatcher; const char * stateName(enum flusher_state st) const; // Current flush cycle state. int flushRv; std::queue<QueuedItem> *flushQueue; std::queue<QueuedItem> *rejectQueue; rel_time_t flushStart; DISALLOW_COPY_AND_ASSIGN(Flusher); }; #endif /* FLUSHER_H */ <|endoftext|>
<commit_before>/* EEPROMEx.cpp - Extended EEPROM library Copyright (c) 2012 Thijs Elenbaas. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /****************************************************************************** * Includes ******************************************************************************/ #include "EEPROMex.h" /****************************************************************************** * Definitions ******************************************************************************/ #define _EEPROMEX_VERSION 1 // software version of this library #define _EEPROMEX_DEBUG // Enables logging of maximum of writes and out-of-memory /****************************************************************************** * Constructors ******************************************************************************/ // Boards with ATmega328, Duemilanove, Uno, Uno SMD, Lilypad - 1024 bytes (1 kilobyte) // Boards with ATmega1280 or 2560, Arduino Mega series – 4096 bytes (4 kilobytes) // Boards with ATmega168, Lilypad, old Nano, Diecimila – 512 bytes // By default we choose conservative settings EEPROMClassEx::EEPROMClassEx() : _allowedWrites(100) { } /****************************************************************************** * User API ******************************************************************************/ void EEPROMClassEx::setMemPool(int base, int memSize) { //Base can only be adjusted if no addresses have already been issued if (_nextAvailableaddress == _base) _base = base; _nextAvailableaddress=_base; //Ceiling can only be adjusted if not below issued addresses if (memSize >= _nextAvailableaddress ) _memSize = memSize; #ifdef _EEPROMEX_DEBUG if (_nextAvailableaddress != _base) Serial.println("Cannot change base, addresses have been issued"); if (memSize < _nextAvailableaddress ) Serial.println("Cannot change ceiling, below issued addresses"); #endif } void EEPROMClassEx::setMaxAllowedWrites(int allowedWrites) { #ifdef _EEPROMEX_DEBUG _allowedWrites = allowedWrites; #endif } int EEPROMClassEx::getAddress(int noOfBytes){ int availableaddress = _nextAvailableaddress; _nextAvailableaddress += noOfBytes; #ifdef _EEPROMEX_DEBUG if (_nextAvailableaddress > _memSize) { Serial.println("Attempt to write outside of EEPROM memory"); return -availableaddress; } else { return availableaddress; } #endif return availableaddress; } bool EEPROMClassEx::isReady() { return eeprom_is_ready(); } uint8_t EEPROMClassEx::read(int address) { return readByte(address); } bool EEPROMClassEx::readBit(int address, byte bit) { if (bit> 7) return false; if (!isReadOk(address+sizeof(uint8_t))) return false; byte byteVal = eeprom_read_byte((unsigned char *) address); byte bytePos = (1 << bit); return (byteVal & bytePos); } uint8_t EEPROMClassEx::readByte(int address) { if (!isReadOk(address+sizeof(uint8_t))) return 0; return eeprom_read_byte((unsigned char *) address); } uint16_t EEPROMClassEx::readInt(int address) { if (!isReadOk(address+sizeof(uint16_t))) return 0; return eeprom_read_word((uint16_t *) address); } uint32_t EEPROMClassEx::readLong(int address) { if (!isReadOk(address+sizeof(uint32_t))) return 0; return eeprom_read_dword((unsigned long *) address); } float EEPROMClassEx::readFloat(int address) { if (!isReadOk(address+sizeof(float))) return 0; float _value; readBlock<float>(address, _value); return _value; } double EEPROMClassEx::readDouble(int address) { if (!isReadOk(address+sizeof(double))) return 0; double _value; readBlock<double>(address, _value); return _value; } bool EEPROMClassEx::write(int address, uint8_t value) { return writeByte(address, value); } bool EEPROMClassEx::writeBit(int address, uint8_t bit, bool value) { updateBit(address, bit, value); return true; } bool EEPROMClassEx::writeByte(int address, uint8_t value) { if (!isWriteOk(address+sizeof(uint8_t))) return false; eeprom_write_byte((unsigned char *) address, value); return true; } bool EEPROMClassEx::writeInt(int address, uint16_t value) { if (!isWriteOk(address+sizeof(uint16_t))) return false; eeprom_write_word((uint16_t *) address, value); return true; } bool EEPROMClassEx::writeLong(int address, uint32_t value) { if (!isWriteOk(address+sizeof(uint32_t))) return false; eeprom_write_dword((unsigned long *) address, value); return true; } bool EEPROMClassEx::writeFloat(int address, float value) { return (writeBlock<float>(address, value)!=0); } bool EEPROMClassEx::writeDouble(int address, double value) { return (writeBlock<float>(address, value)!=0); } bool EEPROMClassEx::update(int address, uint8_t value) { return (updateByte(address, value)); } bool EEPROMClassEx::updateBit(int address, uint8_t bit, bool value) { if (bit> 7) return false; byte byteValInput = readByte(address); byte byteValOutput = byteValInput; // Set bit if (value) { byteValOutput |= (1 << bit); //Set bit to 1 } else { byteValOutput &= ~(1 << bit); //Set bit to 0 } // Store if different from input if (byteValOutput!=byteValInput) { writeByte(address, byteValOutput); } return true; } bool EEPROMClassEx::updateByte(int address, uint8_t value) { return (updateBlock<uint8_t>(address, value)!=0); } bool EEPROMClassEx::updateInt(int address, uint16_t value) { return (updateBlock<uint16_t>(address, value)!=0); } bool EEPROMClassEx::updateLong(int address, uint32_t value) { return (updateBlock<uint32_t>(address, value)!=0); } bool EEPROMClassEx::updateFloat(int address, float value) { return (updateBlock<float>(address, value)!=0); } bool EEPROMClassEx::updateDouble(int address, double value) { return (writeBlock<double>(address, value)!=0); } bool EEPROMClassEx::isWriteOk(int address) { #ifdef _EEPROMEX_DEBUG _writeCounts++; if (_allowedWrites == 0 || _writeCounts > _allowedWrites ) { Serial.println("Exceeded maximum number of writes"); return false; } if (address > _memSize) { Serial.println("Attempt to write outside of EEPROM memory"); return false; } else { return true; } #endif return true; } bool EEPROMClassEx::isReadOk(int address) { #ifdef _EEPROMEX_DEBUG if (address > _memSize) { Serial.println("Attempt to write outside of EEPROM memory"); return false; } else { return true; } #endif return true; } int EEPROMClassEx::_base= 0; int EEPROMClassEx::_memSize= 512; int EEPROMClassEx::_nextAvailableaddress= 0; int EEPROMClassEx::_writeCounts =0; EEPROMClassEx EEPROM; <commit_msg>Disable EEPROMex debug mode<commit_after>/* EEPROMEx.cpp - Extended EEPROM library Copyright (c) 2012 Thijs Elenbaas. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /****************************************************************************** * Includes ******************************************************************************/ #include "EEPROMex.h" /****************************************************************************** * Definitions ******************************************************************************/ #define _EEPROMEX_VERSION 1 // software version of this library //#define _EEPROMEX_DEBUG // Enables logging of maximum of writes and out-of-memory /****************************************************************************** * Constructors ******************************************************************************/ // Boards with ATmega328, Duemilanove, Uno, Uno SMD, Lilypad - 1024 bytes (1 kilobyte) // Boards with ATmega1280 or 2560, Arduino Mega series – 4096 bytes (4 kilobytes) // Boards with ATmega168, Lilypad, old Nano, Diecimila – 512 bytes // By default we choose conservative settings EEPROMClassEx::EEPROMClassEx() : _allowedWrites(100) { } /****************************************************************************** * User API ******************************************************************************/ void EEPROMClassEx::setMemPool(int base, int memSize) { //Base can only be adjusted if no addresses have already been issued if (_nextAvailableaddress == _base) _base = base; _nextAvailableaddress=_base; //Ceiling can only be adjusted if not below issued addresses if (memSize >= _nextAvailableaddress ) _memSize = memSize; #ifdef _EEPROMEX_DEBUG if (_nextAvailableaddress != _base) Serial.println("Cannot change base, addresses have been issued"); if (memSize < _nextAvailableaddress ) Serial.println("Cannot change ceiling, below issued addresses"); #endif } void EEPROMClassEx::setMaxAllowedWrites(int allowedWrites) { #ifdef _EEPROMEX_DEBUG _allowedWrites = allowedWrites; #endif } int EEPROMClassEx::getAddress(int noOfBytes){ int availableaddress = _nextAvailableaddress; _nextAvailableaddress += noOfBytes; #ifdef _EEPROMEX_DEBUG if (_nextAvailableaddress > _memSize) { Serial.println("Attempt to write outside of EEPROM memory"); return -availableaddress; } else { return availableaddress; } #endif return availableaddress; } bool EEPROMClassEx::isReady() { return eeprom_is_ready(); } uint8_t EEPROMClassEx::read(int address) { return readByte(address); } bool EEPROMClassEx::readBit(int address, byte bit) { if (bit> 7) return false; if (!isReadOk(address+sizeof(uint8_t))) return false; byte byteVal = eeprom_read_byte((unsigned char *) address); byte bytePos = (1 << bit); return (byteVal & bytePos); } uint8_t EEPROMClassEx::readByte(int address) { if (!isReadOk(address+sizeof(uint8_t))) return 0; return eeprom_read_byte((unsigned char *) address); } uint16_t EEPROMClassEx::readInt(int address) { if (!isReadOk(address+sizeof(uint16_t))) return 0; return eeprom_read_word((uint16_t *) address); } uint32_t EEPROMClassEx::readLong(int address) { if (!isReadOk(address+sizeof(uint32_t))) return 0; return eeprom_read_dword((unsigned long *) address); } float EEPROMClassEx::readFloat(int address) { if (!isReadOk(address+sizeof(float))) return 0; float _value; readBlock<float>(address, _value); return _value; } double EEPROMClassEx::readDouble(int address) { if (!isReadOk(address+sizeof(double))) return 0; double _value; readBlock<double>(address, _value); return _value; } bool EEPROMClassEx::write(int address, uint8_t value) { return writeByte(address, value); } bool EEPROMClassEx::writeBit(int address, uint8_t bit, bool value) { updateBit(address, bit, value); return true; } bool EEPROMClassEx::writeByte(int address, uint8_t value) { if (!isWriteOk(address+sizeof(uint8_t))) return false; eeprom_write_byte((unsigned char *) address, value); return true; } bool EEPROMClassEx::writeInt(int address, uint16_t value) { if (!isWriteOk(address+sizeof(uint16_t))) return false; eeprom_write_word((uint16_t *) address, value); return true; } bool EEPROMClassEx::writeLong(int address, uint32_t value) { if (!isWriteOk(address+sizeof(uint32_t))) return false; eeprom_write_dword((unsigned long *) address, value); return true; } bool EEPROMClassEx::writeFloat(int address, float value) { return (writeBlock<float>(address, value)!=0); } bool EEPROMClassEx::writeDouble(int address, double value) { return (writeBlock<float>(address, value)!=0); } bool EEPROMClassEx::update(int address, uint8_t value) { return (updateByte(address, value)); } bool EEPROMClassEx::updateBit(int address, uint8_t bit, bool value) { if (bit> 7) return false; byte byteValInput = readByte(address); byte byteValOutput = byteValInput; // Set bit if (value) { byteValOutput |= (1 << bit); //Set bit to 1 } else { byteValOutput &= ~(1 << bit); //Set bit to 0 } // Store if different from input if (byteValOutput!=byteValInput) { writeByte(address, byteValOutput); } return true; } bool EEPROMClassEx::updateByte(int address, uint8_t value) { return (updateBlock<uint8_t>(address, value)!=0); } bool EEPROMClassEx::updateInt(int address, uint16_t value) { return (updateBlock<uint16_t>(address, value)!=0); } bool EEPROMClassEx::updateLong(int address, uint32_t value) { return (updateBlock<uint32_t>(address, value)!=0); } bool EEPROMClassEx::updateFloat(int address, float value) { return (updateBlock<float>(address, value)!=0); } bool EEPROMClassEx::updateDouble(int address, double value) { return (writeBlock<double>(address, value)!=0); } bool EEPROMClassEx::isWriteOk(int address) { #ifdef _EEPROMEX_DEBUG _writeCounts++; if (_allowedWrites == 0 || _writeCounts > _allowedWrites ) { Serial.println("Exceeded maximum number of writes"); return false; } if (address > _memSize) { Serial.println("Attempt to write outside of EEPROM memory"); return false; } else { return true; } #endif return true; } bool EEPROMClassEx::isReadOk(int address) { #ifdef _EEPROMEX_DEBUG if (address > _memSize) { Serial.println("Attempt to write outside of EEPROM memory"); return false; } else { return true; } #endif return true; } int EEPROMClassEx::_base= 0; int EEPROMClassEx::_memSize= 512; int EEPROMClassEx::_nextAvailableaddress= 0; int EEPROMClassEx::_writeCounts =0; EEPROMClassEx EEPROM; <|endoftext|>
<commit_before>/* * 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 Library 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. * * ola-artnet.cpp * Configure an ArtNet device * Copyright (C) 2005-2009 Simon Newton */ #include <errno.h> #include <getopt.h> #include <ola/network/IPV4Address.h> #include <ola/plugin_id.h> #include <plugins/artnet/messages/ArtnetConfigMessages.pb.h> #include <iostream> #include <string> #include "examples/OlaConfigurator.h" using std::cout; using std::endl; using std::string; typedef struct { string command; // argv[0] int device_id; // device id bool help; // help bool has_name; string name; // short name bool has_long_name; string long_name; // long name bool has_subnet; int subnet; // the subnet bool has_net; int net; // the net address unsigned int universe; bool fetch_node_list; } options; /* * A class that configures Artnet devices */ class ArtnetConfigurator: public OlaConfigurator { public: explicit ArtnetConfigurator(const options &opts): OlaConfigurator(opts.device_id, ola::OLA_PLUGIN_ARTNET), m_options(opts) {} void HandleConfigResponse(const string &reply, const string &error); void SendConfigRequest(); private: void SendOptionRequest(); void SendNodeListRequest(); void DisplayOptions(const ola::plugin::artnet::OptionsReply &reply); void DisplayNodeList(const ola::plugin::artnet::NodeListReply &reply); options m_options; }; /* * Handle the device config reply */ void ArtnetConfigurator::HandleConfigResponse(const string &reply, const string &error) { Terminate(); if (!error.empty()) { cout << error << endl; return; } ola::plugin::artnet::Reply reply_pb; if (!reply_pb.ParseFromString(reply)) { cout << "Protobuf parsing failed" << endl; return; } if (reply_pb.type() == ola::plugin::artnet::Reply::ARTNET_OPTIONS_REPLY && reply_pb.has_options()) { DisplayOptions(reply_pb.options()); return; } else if (reply_pb.type() == ola::plugin::artnet::Reply::ARTNET_NODE_LIST_REPLY && reply_pb.has_node_list()) { DisplayNodeList(reply_pb.node_list()); } else { cout << "Invalid response type or missing options field" << endl; } } /* * Send a request */ void ArtnetConfigurator::SendConfigRequest() { if (m_options.fetch_node_list) SendNodeListRequest(); else SendOptionRequest(); } /** * Send an options request, which may involve setting options */ void ArtnetConfigurator::SendOptionRequest() { ola::plugin::artnet::Request request; request.set_type(ola::plugin::artnet::Request::ARTNET_OPTIONS_REQUEST); ola::plugin::artnet::OptionsRequest *options = request.mutable_options(); if (m_options.has_name) options->set_short_name(m_options.name); if (m_options.has_long_name) options->set_long_name(m_options.long_name); if (m_options.has_subnet) options->set_subnet(m_options.subnet); if (m_options.has_net) options->set_net(m_options.net); SendMessage(request); } /** * Send a request for the node list */ void ArtnetConfigurator::SendNodeListRequest() { ola::plugin::artnet::Request request; request.set_type(ola::plugin::artnet::Request::ARTNET_NODE_LIST_REQUEST); ola::plugin::artnet::NodeListRequest *node_list_request = request.mutable_node_list(); node_list_request->set_universe(m_options.universe); SendMessage(request); } /* * Display the widget parameters */ void ArtnetConfigurator::DisplayOptions( const ola::plugin::artnet::OptionsReply &reply) { cout << "Name: " << reply.short_name() << endl; cout << "Long Name: " << reply.long_name() << endl; cout << "Subnet: " << reply.subnet() << endl; cout << "Net: " << reply.net() << endl; } /** * Display the list of discovered nodes */ void ArtnetConfigurator::DisplayNodeList( const ola::plugin::artnet::NodeListReply &reply) { unsigned int nodes = reply.node_size(); for (unsigned int i = 0; i < nodes; i++) { const ola::plugin::artnet::OutputNode &node = reply.node(i); ola::network::IPV4Address address(node.ip_address()); cout << address << endl; } } /* * Parse our cmd line options */ int ParseOptions(int argc, char *argv[], options *opts) { static struct option long_options[] = { {"dev", required_argument, 0, 'd'}, {"help", no_argument, 0, 'h'}, {"long_name", required_argument, 0, 'l'}, {"name", required_argument, 0, 'n'}, {"subnet", required_argument, 0, 's'}, {"net", required_argument, 0, 'e'}, {"universes", required_argument, 0, 'u'}, {0, 0, 0, 0} }; int c; int option_index = 0; while (1) { c = getopt_long(argc, argv, "d:e:hl:n:s:u:", long_options, &option_index); if (c == -1) break; switch (c) { case 0: break; case 'd': opts->device_id = atoi(optarg); break; case 'e': opts->net = atoi(optarg); opts->has_net = true; break; case 'h': opts->help = true; break; case 'l': opts->long_name = optarg; opts->has_long_name = true; break; case 'n': opts->name = optarg; opts->has_name = true; break; case 's': opts->subnet = atoi(optarg); opts->has_subnet = true; break; case 'u': opts->universe = atoi(optarg); opts->fetch_node_list = true; break; case '?': break; } } return 0; } /* * Display the help message */ void DisplayHelpAndExit(const options &opts) { cout << "Usage: " << opts.command << " -d <dev_id> -n <name> -l <long_name> -s <subnet>\n\n" "Configure ArtNet Devices managed by OLA.\n\n" " -e, --net Set the net parameter of the ArtNet device\n" " -h, --help Display this help message and exit.\n" " -l, --long_name Set the long name of the ArtNet device\n" " -n, --name Set the name of the ArtNet device\n" " -s, --subnet Set the subnet of the ArtNet device\n" " -u, --universe List the IPs of devices for this universe\n" << endl; exit(0); } /* * The main function */ int main(int argc, char*argv[]) { options opts; opts.command = argv[0]; opts.device_id = -1; opts.help = false; opts.has_name = false; opts.has_long_name = false; opts.has_subnet = false; opts.has_net = false; opts.fetch_node_list = false; opts.universe = 0; ParseOptions(argc, argv, &opts); if (opts.help || opts.device_id < 0) DisplayHelpAndExit(opts); ArtnetConfigurator configurator(opts); if (!configurator.Setup()) { cout << "error: " << strerror(errno) << endl; exit(1); } configurator.Run(); return 0; } <commit_msg>Show the dev option in the help for ola_artnet<commit_after>/* * 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 Library 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. * * ola-artnet.cpp * Configure an ArtNet device * Copyright (C) 2005-2009 Simon Newton */ #include <errno.h> #include <getopt.h> #include <ola/network/IPV4Address.h> #include <ola/plugin_id.h> #include <plugins/artnet/messages/ArtnetConfigMessages.pb.h> #include <iostream> #include <string> #include "examples/OlaConfigurator.h" using std::cout; using std::endl; using std::string; typedef struct { string command; // argv[0] int device_id; // device id bool help; // help bool has_name; string name; // short name bool has_long_name; string long_name; // long name bool has_subnet; int subnet; // the subnet bool has_net; int net; // the net address unsigned int universe; bool fetch_node_list; } options; /* * A class that configures Artnet devices */ class ArtnetConfigurator: public OlaConfigurator { public: explicit ArtnetConfigurator(const options &opts): OlaConfigurator(opts.device_id, ola::OLA_PLUGIN_ARTNET), m_options(opts) {} void HandleConfigResponse(const string &reply, const string &error); void SendConfigRequest(); private: void SendOptionRequest(); void SendNodeListRequest(); void DisplayOptions(const ola::plugin::artnet::OptionsReply &reply); void DisplayNodeList(const ola::plugin::artnet::NodeListReply &reply); options m_options; }; /* * Handle the device config reply */ void ArtnetConfigurator::HandleConfigResponse(const string &reply, const string &error) { Terminate(); if (!error.empty()) { cout << error << endl; return; } ola::plugin::artnet::Reply reply_pb; if (!reply_pb.ParseFromString(reply)) { cout << "Protobuf parsing failed" << endl; return; } if (reply_pb.type() == ola::plugin::artnet::Reply::ARTNET_OPTIONS_REPLY && reply_pb.has_options()) { DisplayOptions(reply_pb.options()); return; } else if (reply_pb.type() == ola::plugin::artnet::Reply::ARTNET_NODE_LIST_REPLY && reply_pb.has_node_list()) { DisplayNodeList(reply_pb.node_list()); } else { cout << "Invalid response type or missing options field" << endl; } } /* * Send a request */ void ArtnetConfigurator::SendConfigRequest() { if (m_options.fetch_node_list) SendNodeListRequest(); else SendOptionRequest(); } /** * Send an options request, which may involve setting options */ void ArtnetConfigurator::SendOptionRequest() { ola::plugin::artnet::Request request; request.set_type(ola::plugin::artnet::Request::ARTNET_OPTIONS_REQUEST); ola::plugin::artnet::OptionsRequest *options = request.mutable_options(); if (m_options.has_name) options->set_short_name(m_options.name); if (m_options.has_long_name) options->set_long_name(m_options.long_name); if (m_options.has_subnet) options->set_subnet(m_options.subnet); if (m_options.has_net) options->set_net(m_options.net); SendMessage(request); } /** * Send a request for the node list */ void ArtnetConfigurator::SendNodeListRequest() { ola::plugin::artnet::Request request; request.set_type(ola::plugin::artnet::Request::ARTNET_NODE_LIST_REQUEST); ola::plugin::artnet::NodeListRequest *node_list_request = request.mutable_node_list(); node_list_request->set_universe(m_options.universe); SendMessage(request); } /* * Display the widget parameters */ void ArtnetConfigurator::DisplayOptions( const ola::plugin::artnet::OptionsReply &reply) { cout << "Name: " << reply.short_name() << endl; cout << "Long Name: " << reply.long_name() << endl; cout << "Subnet: " << reply.subnet() << endl; cout << "Net: " << reply.net() << endl; } /** * Display the list of discovered nodes */ void ArtnetConfigurator::DisplayNodeList( const ola::plugin::artnet::NodeListReply &reply) { unsigned int nodes = reply.node_size(); for (unsigned int i = 0; i < nodes; i++) { const ola::plugin::artnet::OutputNode &node = reply.node(i); ola::network::IPV4Address address(node.ip_address()); cout << address << endl; } } /* * Parse our cmd line options */ int ParseOptions(int argc, char *argv[], options *opts) { static struct option long_options[] = { {"dev", required_argument, 0, 'd'}, {"help", no_argument, 0, 'h'}, {"long_name", required_argument, 0, 'l'}, {"name", required_argument, 0, 'n'}, {"subnet", required_argument, 0, 's'}, {"net", required_argument, 0, 'e'}, {"universes", required_argument, 0, 'u'}, {0, 0, 0, 0} }; int c; int option_index = 0; while (1) { c = getopt_long(argc, argv, "d:e:hl:n:s:u:", long_options, &option_index); if (c == -1) break; switch (c) { case 0: break; case 'd': opts->device_id = atoi(optarg); break; case 'e': opts->net = atoi(optarg); opts->has_net = true; break; case 'h': opts->help = true; break; case 'l': opts->long_name = optarg; opts->has_long_name = true; break; case 'n': opts->name = optarg; opts->has_name = true; break; case 's': opts->subnet = atoi(optarg); opts->has_subnet = true; break; case 'u': opts->universe = atoi(optarg); opts->fetch_node_list = true; break; case '?': break; } } return 0; } /* * Display the help message */ void DisplayHelpAndExit(const options &opts) { cout << "Usage: " << opts.command << " -d <dev_id> -n <name> -l <long_name> -s <subnet>\n\n" "Configure ArtNet Devices managed by OLA.\n\n" " -d, --dev The ArtNet device to configure\n" " -e, --net Set the net parameter of the ArtNet device\n" " -h, --help Display this help message and exit.\n" " -l, --long_name Set the long name of the ArtNet device\n" " -n, --name Set the name of the ArtNet device\n" " -s, --subnet Set the subnet of the ArtNet device\n" " -u, --universe List the IPs of devices for this universe\n" << endl; exit(0); } /* * The main function */ int main(int argc, char*argv[]) { options opts; opts.command = argv[0]; opts.device_id = -1; opts.help = false; opts.has_name = false; opts.has_long_name = false; opts.has_subnet = false; opts.has_net = false; opts.fetch_node_list = false; opts.universe = 0; ParseOptions(argc, argv, &opts); if (opts.help || opts.device_id < 0) DisplayHelpAndExit(opts); ArtnetConfigurator configurator(opts); if (!configurator.Setup()) { cout << "error: " << strerror(errno) << endl; exit(1); } configurator.Run(); return 0; } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ #include "AliMUONCalibrationData.h" #include "AliCDBEntry.h" #include "AliCDBManager.h" #include "AliCodeTimer.h" #include "AliLog.h" #include "AliMUONTriggerEfficiencyCells.h" #include "AliMUONTriggerLut.h" #include "AliMUONVStore.h" #include "AliMUONVStore.h" #include "AliMUONVCalibParam.h" #include <Riostream.h> #include <TClass.h> #include <TMap.h> //----------------------------------------------------------------------------- /// \class AliMUONCalibrationData /// /// For the moment, this class stores pedestals, gains, hv (for tracker) /// and lut, masks and efficiencies (for trigger) that are fetched from the CDB. /// /// This class is to be considered as a convenience class. /// Its aim is to ease retrieval of calibration data from the /// condition database. /// /// It acts as a "facade" to a bunch of underlying /// containers/calibration classes. /// /// \author Laurent Aphecetche //----------------------------------------------------------------------------- /// \cond CLASSIMP ClassImp(AliMUONCalibrationData) /// \endcond //_____________________________________________________________________________ AliMUONCalibrationData::AliMUONCalibrationData(Int_t runNumber, Bool_t deferredInitialization) : TObject(), fIsValid(kTRUE), fRunNumber(runNumber), fGains(0x0), fPedestals(0x0), fHV(0x0), fLocalTriggerBoardMasks(0x0), fRegionalTriggerBoardMasks(0x0), fGlobalTriggerBoardMasks(0x0), fTriggerLut(0x0), fTriggerEfficiency(0x0), fCapacitances(0x0), fNeighbours(0x0) { /// Default ctor. // If deferredInitialization is false, we read *all* calibrations // at once. // So when using this class to access only one kind of calibrations (e.g. // only pedestals), you should put deferredInitialization to kTRUE, which // will instruct this object to fetch the data only when neeeded. if ( deferredInitialization == kFALSE ) { Gains(); Pedestals(); HV(); LocalTriggerBoardMasks(0); RegionalTriggerBoardMasks(0); GlobalTriggerBoardMasks(); TriggerLut(); TriggerEfficiency(); Capacitances(); Neighbours(); } } //_____________________________________________________________________________ AliMUONCalibrationData::~AliMUONCalibrationData() { /// Destructor. Note that we're the owner of our pointers. Reset(); } //_____________________________________________________________________________ AliMUONVStore* AliMUONCalibrationData::Capacitances() const { /// Create (if needed) and return the internal store for capacitances. if (!fCapacitances) { fCapacitances = CreateCapacitances(fRunNumber); } return fCapacitances; } //_____________________________________________________________________________ AliMUONVStore* AliMUONCalibrationData::CreateCapacitances(Int_t runNumber) { /// Create capa store from OCDB for a given run return dynamic_cast<AliMUONVStore*>(CreateObject(runNumber,"MUON/Calib/Capacitances")); } //_____________________________________________________________________________ AliMUONVStore* AliMUONCalibrationData::CreateGains(Int_t runNumber) { /// Create a new gain store from the OCDB for a given run return dynamic_cast<AliMUONVStore*>(CreateObject(runNumber,"MUON/Calib/Gains")); } //_____________________________________________________________________________ AliMUONVCalibParam* AliMUONCalibrationData::CreateGlobalTriggerBoardMasks(Int_t runNumber) { /// Create the internal store for GlobalTriggerBoardMasks from OCDB return dynamic_cast<AliMUONVCalibParam*>(CreateObject(runNumber,"MUON/Calib/GlobalTriggerBoardMasks")); } //_____________________________________________________________________________ TMap* AliMUONCalibrationData::CreateHV(Int_t runNumber) { /// Create a new HV map from the OCDB for a given run return dynamic_cast<TMap*>(CreateObject(runNumber,"MUON/Calib/HV")); } //_____________________________________________________________________________ AliMUONVStore* AliMUONCalibrationData::CreateLocalTriggerBoardMasks(Int_t runNumber) { /// Get the internal store for LocalTriggerBoardMasks from OCDB return dynamic_cast<AliMUONVStore*>(CreateObject(runNumber,"MUON/Calib/LocalTriggerBoardMasks")); } //_____________________________________________________________________________ AliMUONVStore* AliMUONCalibrationData::CreateNeighbours(Int_t runNumber) { /// Create a neighbour store from the OCDB for a given run return dynamic_cast<AliMUONVStore*>(CreateObject(runNumber,"MUON/Calib/Neighbours")); } //_____________________________________________________________________________ TObject* AliMUONCalibrationData::CreateObject(Int_t runNumber, const char* path) { /// Access the CDB for a given path (e.g. MUON/Calib/Pedestals), /// and return the corresponding TObject. AliCodeTimerAutoClass(Form("%d : %s",runNumber,path)); AliCDBManager* man = AliCDBManager::Instance(); Bool_t undefStorage(kFALSE); if ( !man->IsDefaultStorageSet() ) { TString storage("local://$ALICE_ROOT"); AliInfoClass(Form("CDB Storage not set. Will use %s for MUON stuff",storage.Data())); man->SetDefaultStorage(storage.Data()); undefStorage = kTRUE; } Bool_t cacheStatus = man->GetCacheFlag(); man->SetCacheFlag(kFALSE); AliCDBEntry* entry = AliCDBManager::Instance()->Get(path,runNumber); man->SetCacheFlag(cacheStatus); if (entry) { TObject* object = entry->GetObject(); entry->SetOwner(kFALSE); delete entry; return object; } if ( undefStorage ) { man->UnsetDefaultStorage(); } return 0x0; } //_____________________________________________________________________________ AliMUONVStore* AliMUONCalibrationData::CreatePedestals(Int_t runNumber) { /// Create a new pedestal store from the OCDB for a given run return dynamic_cast<AliMUONVStore*>(CreateObject(runNumber,"MUON/Calib/Pedestals")); } //_____________________________________________________________________________ AliMUONVStore* AliMUONCalibrationData::CreateRegionalTriggerBoardMasks(Int_t runNumber) { /// Create the internal store for RegionalTriggerBoardMasks from OCDB return dynamic_cast<AliMUONVStore*>(CreateObject(runNumber,"MUON/Calib/RegionalTriggerBoardMasks")); } //_____________________________________________________________________________ AliMUONTriggerEfficiencyCells* AliMUONCalibrationData::CreateTriggerEfficiency(Int_t runNumber) { /// Create trigger efficiency object from OCBD return dynamic_cast<AliMUONTriggerEfficiencyCells*>(CreateObject(runNumber,"MUON/Calib/TriggerEfficiency")); } //_____________________________________________________________________________ AliMUONTriggerLut* AliMUONCalibrationData::CreateTriggerLut(Int_t runNumber) { /// Create trigger LUT from OCDB return dynamic_cast<AliMUONTriggerLut*>(CreateObject(runNumber,"MUON/Calib/TriggerLut")); } //_____________________________________________________________________________ AliMUONVStore* AliMUONCalibrationData::Gains() const { /// Create (if needed) and return the internal store for gains. if (!fGains) { fGains = CreateGains(fRunNumber); } return fGains; } //_____________________________________________________________________________ AliMUONVCalibParam* AliMUONCalibrationData::Gains(Int_t detElemId, Int_t manuId) const { /// Return the gains for a given (detElemId, manuId) pair /// Note that, unlike the DeadChannel case, if the result is 0x0, that's an /// error (meaning that we should get gains for all channels). AliMUONVStore* gains = Gains(); if (!gains) { return 0x0; } return static_cast<AliMUONVCalibParam*>(gains->FindObject(detElemId,manuId)); } //_____________________________________________________________________________ AliMUONVCalibParam* AliMUONCalibrationData::GlobalTriggerBoardMasks() const { /// Return the masks for the global trigger board. if (!fGlobalTriggerBoardMasks) { fGlobalTriggerBoardMasks = CreateGlobalTriggerBoardMasks(fRunNumber); } return fGlobalTriggerBoardMasks; } //_____________________________________________________________________________ TMap* AliMUONCalibrationData::HV() const { /// Return the calibration for a given (detElemId, manuId) pair if (!fHV) { fHV = CreateHV(fRunNumber); } return fHV; } //_____________________________________________________________________________ AliMUONVStore* AliMUONCalibrationData::Neighbours() const { /// Create (if needed) and return the internal store for neighbours. if (!fNeighbours) { fNeighbours = CreateNeighbours(fRunNumber); } return fNeighbours; } //_____________________________________________________________________________ AliMUONVCalibParam* AliMUONCalibrationData::LocalTriggerBoardMasks(Int_t localBoardNumber) const { /// Return the masks for a given trigger local board. if (!fLocalTriggerBoardMasks) { fLocalTriggerBoardMasks = CreateLocalTriggerBoardMasks(fRunNumber); } if ( fLocalTriggerBoardMasks ) { AliMUONVCalibParam* ltbm = static_cast<AliMUONVCalibParam*>(fLocalTriggerBoardMasks->FindObject(localBoardNumber)); if (!ltbm) { AliError(Form("Could not get mask for localBoardNumber=%d",localBoardNumber)); } return ltbm; } return 0x0; } //_____________________________________________________________________________ AliMUONVStore* AliMUONCalibrationData::Pedestals() const { /// Return pedestals if (!fPedestals) { fPedestals = CreatePedestals(fRunNumber); } return fPedestals; } //_____________________________________________________________________________ AliMUONVCalibParam* AliMUONCalibrationData::Pedestals(Int_t detElemId, Int_t manuId) const { /// Return the pedestals for a given (detElemId, manuId) pair. /// A return value of 0x0 is considered an error, meaning we should get /// pedestals for all channels. AliMUONVStore* pedestals = Pedestals(); if (!pedestals) { return 0x0; } return static_cast<AliMUONVCalibParam*>(pedestals->FindObject(detElemId,manuId)); } //_____________________________________________________________________________ void AliMUONCalibrationData::Print(Option_t*) const { /// A very basic dump of our guts. cout << "RunNumber " << RunNumber() << " fGains=" << fGains << " fPedestals=" << fPedestals << " fHV=" << fHV << " fLocalTriggerBoardMasks=" << fLocalTriggerBoardMasks << " fRegionalTriggerBoardMasks=" << fRegionalTriggerBoardMasks << " fGlobalTriggerBoardMasks=" << fGlobalTriggerBoardMasks << " fTriggerLut=" << fTriggerLut << endl; } //_____________________________________________________________________________ AliMUONVCalibParam* AliMUONCalibrationData::RegionalTriggerBoardMasks(Int_t regionalBoardNumber) const { /// Return the masks for a given trigger regional board. if ( !fRegionalTriggerBoardMasks ) { fRegionalTriggerBoardMasks = CreateRegionalTriggerBoardMasks(fRunNumber); } if ( fRegionalTriggerBoardMasks ) { AliMUONVCalibParam* rtbm = static_cast<AliMUONVCalibParam*>(fRegionalTriggerBoardMasks->FindObject(regionalBoardNumber)); if (!rtbm) { AliError(Form("Could not get mask for regionalBoard index=%d",regionalBoardNumber)); } return rtbm; } return 0x0; } //_____________________________________________________________________________ AliMUONTriggerEfficiencyCells* AliMUONCalibrationData::TriggerEfficiency() const { /// Return the trigger efficiency. if (!fTriggerEfficiency) { fTriggerEfficiency = CreateTriggerEfficiency(fRunNumber); } return fTriggerEfficiency; } //_____________________________________________________________________________ AliMUONTriggerLut* AliMUONCalibrationData::TriggerLut() const { /// Return the trigger look up table. if (!fTriggerLut) { fTriggerLut = CreateTriggerLut(fRunNumber); } return fTriggerLut; } //_____________________________________________________________________________ void AliMUONCalibrationData::Reset() { /// Reset all data delete fPedestals; fPedestals = 0x0; delete fGains; fGains = 0x0; delete fHV; fHV = 0x0; delete fLocalTriggerBoardMasks; fLocalTriggerBoardMasks = 0x0; delete fRegionalTriggerBoardMasks; fRegionalTriggerBoardMasks = 0x0; delete fGlobalTriggerBoardMasks; fGlobalTriggerBoardMasks = 0x0; delete fTriggerLut; fTriggerLut = 0x0; delete fTriggerEfficiency; fTriggerEfficiency = 0x0; delete fCapacitances; fCapacitances = 0x0; delete fNeighbours; fNeighbours = 0x0; } <commit_msg>Do not set default CDB storage in this class, return error if it is not set. (Laurent)<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ #include "AliMUONCalibrationData.h" #include "AliCDBEntry.h" #include "AliCDBManager.h" #include "AliCodeTimer.h" #include "AliLog.h" #include "AliMUONTriggerEfficiencyCells.h" #include "AliMUONTriggerLut.h" #include "AliMUONVStore.h" #include "AliMUONVStore.h" #include "AliMUONVCalibParam.h" #include <Riostream.h> #include <TClass.h> #include <TMap.h> //----------------------------------------------------------------------------- /// \class AliMUONCalibrationData /// /// For the moment, this class stores pedestals, gains, hv (for tracker) /// and lut, masks and efficiencies (for trigger) that are fetched from the CDB. /// /// This class is to be considered as a convenience class. /// Its aim is to ease retrieval of calibration data from the /// condition database. /// /// It acts as a "facade" to a bunch of underlying /// containers/calibration classes. /// /// \author Laurent Aphecetche //----------------------------------------------------------------------------- /// \cond CLASSIMP ClassImp(AliMUONCalibrationData) /// \endcond //_____________________________________________________________________________ AliMUONCalibrationData::AliMUONCalibrationData(Int_t runNumber, Bool_t deferredInitialization) : TObject(), fIsValid(kTRUE), fRunNumber(runNumber), fGains(0x0), fPedestals(0x0), fHV(0x0), fLocalTriggerBoardMasks(0x0), fRegionalTriggerBoardMasks(0x0), fGlobalTriggerBoardMasks(0x0), fTriggerLut(0x0), fTriggerEfficiency(0x0), fCapacitances(0x0), fNeighbours(0x0) { /// Default ctor. // If deferredInitialization is false, we read *all* calibrations // at once. // So when using this class to access only one kind of calibrations (e.g. // only pedestals), you should put deferredInitialization to kTRUE, which // will instruct this object to fetch the data only when neeeded. if ( deferredInitialization == kFALSE ) { Gains(); Pedestals(); HV(); LocalTriggerBoardMasks(0); RegionalTriggerBoardMasks(0); GlobalTriggerBoardMasks(); TriggerLut(); TriggerEfficiency(); Capacitances(); Neighbours(); } } //_____________________________________________________________________________ AliMUONCalibrationData::~AliMUONCalibrationData() { /// Destructor. Note that we're the owner of our pointers. Reset(); } //_____________________________________________________________________________ AliMUONVStore* AliMUONCalibrationData::Capacitances() const { /// Create (if needed) and return the internal store for capacitances. if (!fCapacitances) { fCapacitances = CreateCapacitances(fRunNumber); } return fCapacitances; } //_____________________________________________________________________________ AliMUONVStore* AliMUONCalibrationData::CreateCapacitances(Int_t runNumber) { /// Create capa store from OCDB for a given run return dynamic_cast<AliMUONVStore*>(CreateObject(runNumber,"MUON/Calib/Capacitances")); } //_____________________________________________________________________________ AliMUONVStore* AliMUONCalibrationData::CreateGains(Int_t runNumber) { /// Create a new gain store from the OCDB for a given run return dynamic_cast<AliMUONVStore*>(CreateObject(runNumber,"MUON/Calib/Gains")); } //_____________________________________________________________________________ AliMUONVCalibParam* AliMUONCalibrationData::CreateGlobalTriggerBoardMasks(Int_t runNumber) { /// Create the internal store for GlobalTriggerBoardMasks from OCDB return dynamic_cast<AliMUONVCalibParam*>(CreateObject(runNumber,"MUON/Calib/GlobalTriggerBoardMasks")); } //_____________________________________________________________________________ TMap* AliMUONCalibrationData::CreateHV(Int_t runNumber) { /// Create a new HV map from the OCDB for a given run return dynamic_cast<TMap*>(CreateObject(runNumber,"MUON/Calib/HV")); } //_____________________________________________________________________________ AliMUONVStore* AliMUONCalibrationData::CreateLocalTriggerBoardMasks(Int_t runNumber) { /// Get the internal store for LocalTriggerBoardMasks from OCDB return dynamic_cast<AliMUONVStore*>(CreateObject(runNumber,"MUON/Calib/LocalTriggerBoardMasks")); } //_____________________________________________________________________________ AliMUONVStore* AliMUONCalibrationData::CreateNeighbours(Int_t runNumber) { /// Create a neighbour store from the OCDB for a given run return dynamic_cast<AliMUONVStore*>(CreateObject(runNumber,"MUON/Calib/Neighbours")); } //_____________________________________________________________________________ TObject* AliMUONCalibrationData::CreateObject(Int_t runNumber, const char* path) { /// Access the CDB for a given path (e.g. MUON/Calib/Pedestals), /// and return the corresponding TObject. AliCodeTimerAutoClass(Form("%d : %s",runNumber,path)); AliCDBManager* man = AliCDBManager::Instance(); if ( !man->IsDefaultStorageSet() ) { AliErrorClass("CDB Storage not set. Must use AliCDBManager::Instance()->SetDefaultStorage() first."); return 0x0; } Bool_t cacheStatus = man->GetCacheFlag(); man->SetCacheFlag(kFALSE); AliCDBEntry* entry = AliCDBManager::Instance()->Get(path,runNumber); man->SetCacheFlag(cacheStatus); if (entry) { TObject* object = entry->GetObject(); entry->SetOwner(kFALSE); delete entry; return object; } return 0x0; } //_____________________________________________________________________________ AliMUONVStore* AliMUONCalibrationData::CreatePedestals(Int_t runNumber) { /// Create a new pedestal store from the OCDB for a given run return dynamic_cast<AliMUONVStore*>(CreateObject(runNumber,"MUON/Calib/Pedestals")); } //_____________________________________________________________________________ AliMUONVStore* AliMUONCalibrationData::CreateRegionalTriggerBoardMasks(Int_t runNumber) { /// Create the internal store for RegionalTriggerBoardMasks from OCDB return dynamic_cast<AliMUONVStore*>(CreateObject(runNumber,"MUON/Calib/RegionalTriggerBoardMasks")); } //_____________________________________________________________________________ AliMUONTriggerEfficiencyCells* AliMUONCalibrationData::CreateTriggerEfficiency(Int_t runNumber) { /// Create trigger efficiency object from OCBD return dynamic_cast<AliMUONTriggerEfficiencyCells*>(CreateObject(runNumber,"MUON/Calib/TriggerEfficiency")); } //_____________________________________________________________________________ AliMUONTriggerLut* AliMUONCalibrationData::CreateTriggerLut(Int_t runNumber) { /// Create trigger LUT from OCDB return dynamic_cast<AliMUONTriggerLut*>(CreateObject(runNumber,"MUON/Calib/TriggerLut")); } //_____________________________________________________________________________ AliMUONVStore* AliMUONCalibrationData::Gains() const { /// Create (if needed) and return the internal store for gains. if (!fGains) { fGains = CreateGains(fRunNumber); } return fGains; } //_____________________________________________________________________________ AliMUONVCalibParam* AliMUONCalibrationData::Gains(Int_t detElemId, Int_t manuId) const { /// Return the gains for a given (detElemId, manuId) pair /// Note that, unlike the DeadChannel case, if the result is 0x0, that's an /// error (meaning that we should get gains for all channels). AliMUONVStore* gains = Gains(); if (!gains) { return 0x0; } return static_cast<AliMUONVCalibParam*>(gains->FindObject(detElemId,manuId)); } //_____________________________________________________________________________ AliMUONVCalibParam* AliMUONCalibrationData::GlobalTriggerBoardMasks() const { /// Return the masks for the global trigger board. if (!fGlobalTriggerBoardMasks) { fGlobalTriggerBoardMasks = CreateGlobalTriggerBoardMasks(fRunNumber); } return fGlobalTriggerBoardMasks; } //_____________________________________________________________________________ TMap* AliMUONCalibrationData::HV() const { /// Return the calibration for a given (detElemId, manuId) pair if (!fHV) { fHV = CreateHV(fRunNumber); } return fHV; } //_____________________________________________________________________________ AliMUONVStore* AliMUONCalibrationData::Neighbours() const { /// Create (if needed) and return the internal store for neighbours. if (!fNeighbours) { fNeighbours = CreateNeighbours(fRunNumber); } return fNeighbours; } //_____________________________________________________________________________ AliMUONVCalibParam* AliMUONCalibrationData::LocalTriggerBoardMasks(Int_t localBoardNumber) const { /// Return the masks for a given trigger local board. if (!fLocalTriggerBoardMasks) { fLocalTriggerBoardMasks = CreateLocalTriggerBoardMasks(fRunNumber); } if ( fLocalTriggerBoardMasks ) { AliMUONVCalibParam* ltbm = static_cast<AliMUONVCalibParam*>(fLocalTriggerBoardMasks->FindObject(localBoardNumber)); if (!ltbm) { AliError(Form("Could not get mask for localBoardNumber=%d",localBoardNumber)); } return ltbm; } return 0x0; } //_____________________________________________________________________________ AliMUONVStore* AliMUONCalibrationData::Pedestals() const { /// Return pedestals if (!fPedestals) { fPedestals = CreatePedestals(fRunNumber); } return fPedestals; } //_____________________________________________________________________________ AliMUONVCalibParam* AliMUONCalibrationData::Pedestals(Int_t detElemId, Int_t manuId) const { /// Return the pedestals for a given (detElemId, manuId) pair. /// A return value of 0x0 is considered an error, meaning we should get /// pedestals for all channels. AliMUONVStore* pedestals = Pedestals(); if (!pedestals) { return 0x0; } return static_cast<AliMUONVCalibParam*>(pedestals->FindObject(detElemId,manuId)); } //_____________________________________________________________________________ void AliMUONCalibrationData::Print(Option_t*) const { /// A very basic dump of our guts. cout << "RunNumber " << RunNumber() << " fGains=" << fGains << " fPedestals=" << fPedestals << " fHV=" << fHV << " fLocalTriggerBoardMasks=" << fLocalTriggerBoardMasks << " fRegionalTriggerBoardMasks=" << fRegionalTriggerBoardMasks << " fGlobalTriggerBoardMasks=" << fGlobalTriggerBoardMasks << " fTriggerLut=" << fTriggerLut << endl; } //_____________________________________________________________________________ AliMUONVCalibParam* AliMUONCalibrationData::RegionalTriggerBoardMasks(Int_t regionalBoardNumber) const { /// Return the masks for a given trigger regional board. if ( !fRegionalTriggerBoardMasks ) { fRegionalTriggerBoardMasks = CreateRegionalTriggerBoardMasks(fRunNumber); } if ( fRegionalTriggerBoardMasks ) { AliMUONVCalibParam* rtbm = static_cast<AliMUONVCalibParam*>(fRegionalTriggerBoardMasks->FindObject(regionalBoardNumber)); if (!rtbm) { AliError(Form("Could not get mask for regionalBoard index=%d",regionalBoardNumber)); } return rtbm; } return 0x0; } //_____________________________________________________________________________ AliMUONTriggerEfficiencyCells* AliMUONCalibrationData::TriggerEfficiency() const { /// Return the trigger efficiency. if (!fTriggerEfficiency) { fTriggerEfficiency = CreateTriggerEfficiency(fRunNumber); } return fTriggerEfficiency; } //_____________________________________________________________________________ AliMUONTriggerLut* AliMUONCalibrationData::TriggerLut() const { /// Return the trigger look up table. if (!fTriggerLut) { fTriggerLut = CreateTriggerLut(fRunNumber); } return fTriggerLut; } //_____________________________________________________________________________ void AliMUONCalibrationData::Reset() { /// Reset all data delete fPedestals; fPedestals = 0x0; delete fGains; fGains = 0x0; delete fHV; fHV = 0x0; delete fLocalTriggerBoardMasks; fLocalTriggerBoardMasks = 0x0; delete fRegionalTriggerBoardMasks; fRegionalTriggerBoardMasks = 0x0; delete fGlobalTriggerBoardMasks; fGlobalTriggerBoardMasks = 0x0; delete fTriggerLut; fTriggerLut = 0x0; delete fTriggerEfficiency; fTriggerEfficiency = 0x0; delete fCapacitances; fCapacitances = 0x0; delete fNeighbours; fNeighbours = 0x0; } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ // /// \ingroup macros /// \file MUONGenerateGeometryData.C /// \brief Macro for generating the geometry data files: /// transform.dat, svmap.dat. /// /// To be run from aliroot: /// /// .x MUONGenerateGeometryData.C /// /// The generated files do not replace the existing ones /// but have different names (with extension ".out"). /// /// \author: I. Hrivnacova, IPN Orsay #if !defined(__CINT__) || defined(__MAKECINT__) #include "AliMUON.h" #include "AliMUONGeometryBuilder.h" #include "AliMUONGeometryTransformer.h" #include "AliRun.h" #include <Riostream.h> #endif void MUONGenerateGeometryData(Bool_t transforms = true, Bool_t svmaps = true, Bool_t writeEnvelopes = true) { /// \param transforms option to generete transform.dat /// \param svmaps option to generete svmap.dat /// \param writeEnvelope option to include virtual envelopes /// in the volume paths // Initialize gAlice->Init("$ALICE_ROOT/MUON/Config.C"); cout << "Init done " << endl; // Get MUON detector AliMUON* muon = (AliMUON*)gAlice->GetModule("MUON"); if (!muon) { cerr << "MUON detector not defined." << endl; return; } // Get geometry builder AliMUONGeometryBuilder* builder = muon ->GetGeometryBuilder(); if (transforms) { cout << "Generating transformation file ..." << endl; builder->GetTransformer()->WriteTransformations("transform.dat.out"); } if (svmaps) { cout << "Generating svmaps file ..." << endl; builder->WriteSVMaps("svmap.dat.out", true, writeEnvelopes); } } <commit_msg>Adding setting default CDB storage and run number, now required by the framework. (Javier)<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ // /// \ingroup macros /// \file MUONGenerateGeometryData.C /// \brief Macro for generating the geometry data files: /// transform.dat, svmap.dat. /// /// To be run from aliroot: /// /// .x MUONGenerateGeometryData.C /// /// The generated files do not replace the existing ones /// but have different names (with extension ".out"). /// /// \author: I. Hrivnacova, IPN Orsay #if !defined(__CINT__) || defined(__MAKECINT__) #include "AliMUON.h" #include "AliMUONGeometryBuilder.h" #include "AliMUONGeometryTransformer.h" #include "AliRun.h" #include "AliCDBManager.h" #include <Riostream.h> #endif void MUONGenerateGeometryData(Bool_t transforms = true, Bool_t svmaps = true, Bool_t writeEnvelopes = true) { /// \param transforms option to generete transform.dat /// \param svmaps option to generete svmap.dat /// \param writeEnvelope option to include virtual envelopes /// in the volume paths // Default CDB and run number AliCDBManager* man = AliCDBManager::Instance(); man->SetDefaultStorage("local://$ALICE_ROOT"); man->SetRun(0); // Initialize gAlice->Init("$ALICE_ROOT/MUON/Config.C"); cout << "Init done " << endl; // Get MUON detector AliMUON* muon = (AliMUON*)gAlice->GetModule("MUON"); if (!muon) { cerr << "MUON detector not defined." << endl; return; } // Get geometry builder AliMUONGeometryBuilder* builder = muon ->GetGeometryBuilder(); if (transforms) { cout << "Generating transformation file ..." << endl; builder->GetTransformer()->WriteTransformations("transform.dat.out"); } if (svmaps) { cout << "Generating svmaps file ..." << endl; builder->WriteSVMaps("svmap.dat.out", true, writeEnvelopes); } } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <sys/stat.h> #ifdef ENABLE_LLVM #include <llvm/Support/ManagedStatic.h> #endif #include "environment.hpp" #include "oop.hpp" #include "type_info.hpp" #include "exception.hpp" #include "config.h" #include "paths.h" using namespace std; using namespace rubinius; /** * Main rbx entry point. * * The main function here handles the environment settings and command-line * arguments passed to it. It then boots the VM, runs the appropriate file * (`loader`), and returns 0 if no errors occur along the way. * * If there is an Assertion raised or an Exception, it prints the backtrace * supplied. This function is the wrapper for the entire VM, as it deals with * anything that could possibly happen to the VM. It's like the person * playing whack-a-mole, in that if something tries to come out of the VM * that's evil (such as a failed assertion or exception), it catches it and * skins it and shows it to the user. */ int main(int argc, char** argv) { int exit_code = 0; // Ensure to destruct an Environment before calling llvm_shutdown(), which // follows this block. Because Environment's destructor uses LLVM API, it // must precede llvm_shutdown(). { Environment env(argc, argv); env.setup_cpp_terminate(); try { if(const char* var = getenv("RBX_OPTIONS")) { env.load_string(var); } if(const char* path = getenv("RBX_OPTFILE")) { env.load_conf(path); } env.run_from_filesystem(); } catch(Assertion *e) { std::cout << "VM Assertion:" << std::endl; std::cout << " " << e->reason << std::endl << std::endl; e->print_backtrace(); std::cout << std::endl << "Ruby backtrace:" << std::endl; env.state->vm()->print_backtrace(); delete e; exit_code = 1; } catch(RubyException &e) { std::cout << "Ruby Exception hit toplevel:\n"; // Prints Ruby backtrace, and VM backtrace if captured e.show(env.state); exit_code = 1; } catch(TypeError &e) { /* TypeError's here are dealt with specially so that they can deliver * more information, such as _why_ there was a type error issue. * * This has the same name as the RubyException TypeError (run `5 + "string"` * as an example), but these are NOT the same - this exception is raised * internally when cNil gets passed to an array method, for instance, when * an array was expected. */ std::cout << "Type Error detected:" << std::endl; TypeInfo* wanted = env.state->vm()->find_type(e.type); if(!e.object->reference_p()) { std::cout << " Tried to use non-reference value " << e.object; } else { TypeInfo* was = env.state->vm()->find_type(e.object->type_id()); std::cout << " Tried to use object of type " << was->type_name << " (" << was->type << ")"; } std::cout << " as type " << wanted->type_name << " (" << wanted->type << ")" << std::endl; e.print_backtrace(); std::cout << "Ruby backtrace:" << std::endl; env.state->vm()->print_backtrace(); exit_code = 1; } catch(MissingRuntime& e) { std::cerr << std::endl; std::cerr << e.what() << std::endl; std::cerr << "Rubinius was configured to find the directories relative to:" << std::endl; std::cerr << std::endl << " " << RBX_PREFIX_PATH << std::endl << std::endl; std::cerr << "Set the environment variable RBX_PREFIX_PATH to the directory"; std::cerr << std::endl; std::cerr << "that is the prefix of the following runtime directories:" << std::endl; std::cerr << std::endl; std::cerr << " BIN_PATH: " << RBX_BIN_PATH << std::endl; std::cerr << " RUNTIME_PATH: " << RBX_RUNTIME_PATH << std::endl; std::cerr << " KERNEL_PATH: " << RBX_KERNEL_PATH << std::endl; std::cerr << " LIB_PATH: " << RBX_LIB_PATH << std::endl; std::cerr << " VENDOR_PATH: " << RBX_VENDOR_PATH << std::endl; std::cerr << " GEMS_PATH: " << RBX_GEMS_PATH << std::endl; std::cerr << std::endl; exit_code = 1; } catch(BadKernelFile& e) { std::cout << "ERROR: Unable to load: " << e.what() << std::endl << std::endl; std::cout << "Please run the following commands to rebuild:" << std::endl; std::cout << " rake clean" << std::endl; std::cout << " rake or rake install" << std::endl << std::endl; std::cout << "If the problem persists, please open an issue at:" << std::endl; std::cout << " http://github.com/rubinius/rubinius\n"; exit_code = 1; } catch(VMException &e) { std::cout << "Unknown VM exception detected." << std::endl; e.print_backtrace(); exit_code = 1; } catch(std::runtime_error& e) { std::cout << "Runtime exception: " << e.what() << std::endl; exit_code = 1; } if(!exit_code) { env.halt(env.state); exit_code = env.exit_code(env.state); } } #ifdef ENABLE_LLVM llvm::llvm_shutdown(); #endif return exit_code; } <commit_msg>Fix crash on unexpected abort / VM exit<commit_after>#include <iostream> #include <fstream> #include <sys/stat.h> #ifdef ENABLE_LLVM #include <llvm/Support/ManagedStatic.h> #endif #include "environment.hpp" #include "oop.hpp" #include "type_info.hpp" #include "exception.hpp" #include "config.h" #include "paths.h" using namespace std; using namespace rubinius; /** * Main rbx entry point. * * The main function here handles the environment settings and command-line * arguments passed to it. It then boots the VM, runs the appropriate file * (`loader`), and returns 0 if no errors occur along the way. * * If there is an Assertion raised or an Exception, it prints the backtrace * supplied. This function is the wrapper for the entire VM, as it deals with * anything that could possibly happen to the VM. It's like the person * playing whack-a-mole, in that if something tries to come out of the VM * that's evil (such as a failed assertion or exception), it catches it and * skins it and shows it to the user. */ int main(int argc, char** argv) { int exit_code = 0; // Ensure to destruct an Environment before calling llvm_shutdown(), which // follows this block. Because Environment's destructor uses LLVM API, it // must precede llvm_shutdown(). { Environment env(argc, argv); env.setup_cpp_terminate(); try { if(const char* var = getenv("RBX_OPTIONS")) { env.load_string(var); } if(const char* path = getenv("RBX_OPTFILE")) { env.load_conf(path); } env.run_from_filesystem(); } catch(Assertion *e) { std::cout << "VM Assertion:" << std::endl; std::cout << " " << e->reason << std::endl << std::endl; e->print_backtrace(); std::cout << std::endl << "Ruby backtrace:" << std::endl; env.state->vm()->print_backtrace(); delete e; exit_code = 1; } catch(RubyException &e) { std::cout << "Ruby Exception hit toplevel:\n"; // Prints Ruby backtrace, and VM backtrace if captured e.show(env.state); exit_code = 1; } catch(TypeError &e) { /* TypeError's here are dealt with specially so that they can deliver * more information, such as _why_ there was a type error issue. * * This has the same name as the RubyException TypeError (run `5 + "string"` * as an example), but these are NOT the same - this exception is raised * internally when cNil gets passed to an array method, for instance, when * an array was expected. */ std::cout << "Type Error detected:" << std::endl; TypeInfo* wanted = env.state->vm()->find_type(e.type); if(!e.object->reference_p()) { std::cout << " Tried to use non-reference value " << e.object; } else { TypeInfo* was = env.state->vm()->find_type(e.object->type_id()); std::cout << " Tried to use object of type " << was->type_name << " (" << was->type << ")"; } std::cout << " as type " << wanted->type_name << " (" << wanted->type << ")" << std::endl; e.print_backtrace(); std::cout << "Ruby backtrace:" << std::endl; env.state->vm()->print_backtrace(); exit_code = 1; } catch(MissingRuntime& e) { std::cerr << std::endl; std::cerr << e.what() << std::endl; std::cerr << "Rubinius was configured to find the directories relative to:" << std::endl; std::cerr << std::endl << " " << RBX_PREFIX_PATH << std::endl << std::endl; std::cerr << "Set the environment variable RBX_PREFIX_PATH to the directory"; std::cerr << std::endl; std::cerr << "that is the prefix of the following runtime directories:" << std::endl; std::cerr << std::endl; std::cerr << " BIN_PATH: " << RBX_BIN_PATH << std::endl; std::cerr << " RUNTIME_PATH: " << RBX_RUNTIME_PATH << std::endl; std::cerr << " KERNEL_PATH: " << RBX_KERNEL_PATH << std::endl; std::cerr << " LIB_PATH: " << RBX_LIB_PATH << std::endl; std::cerr << " VENDOR_PATH: " << RBX_VENDOR_PATH << std::endl; std::cerr << " GEMS_PATH: " << RBX_GEMS_PATH << std::endl; std::cerr << std::endl; exit_code = 1; } catch(BadKernelFile& e) { std::cout << "ERROR: Unable to load: " << e.what() << std::endl << std::endl; std::cout << "Please run the following commands to rebuild:" << std::endl; std::cout << " rake clean" << std::endl; std::cout << " rake or rake install" << std::endl << std::endl; std::cout << "If the problem persists, please open an issue at:" << std::endl; std::cout << " http://github.com/rubinius/rubinius\n"; exit_code = 1; } catch(VMException &e) { std::cout << "Unknown VM exception detected." << std::endl; e.print_backtrace(); exit_code = 1; } catch(std::runtime_error& e) { std::cout << "Runtime exception: " << e.what() << std::endl; exit_code = 1; } env.halt(env.state); if(!exit_code) { exit_code = env.exit_code(env.state); } } #ifdef ENABLE_LLVM llvm::llvm_shutdown(); #endif return exit_code; } <|endoftext|>
<commit_before>#include "llvm/jit_operations.hpp" #include "llvm/access_memory.hpp" #include "builtin/access_variable.hpp" namespace rubinius { class Inliner { JITOperations& ops_; InlineCache* cache_; int count_; BasicBlock* after_; public: Inliner(JITOperations& ops, InlineCache* cache, int count, BasicBlock* after) : ops_(ops) , cache_(cache) , count_(count) , after_(after) {} Value* recv() { return ops_.stack_back(count_); } Value* arg(int which) { return ops_.stack_back(count_ - which); } void consider() { executor callee = cache_->method->execute; if(callee == Primitives::tuple_at && count_ == 1) { call_tuple_at(); } else if(callee == Primitives::tuple_put && count_ == 2) { call_tuple_put(); // If the cache has only ever had one class, inline! } else if(cache_->classes_seen() == 1) { AccessManagedMemory memguard(ops_.state()); Executable* meth = cache_->method; if(AccessVariable* acc = try_as<AccessVariable>(meth)) { inline_ivar_access(cache_->tracked_class(0), acc); } } } void inline_ivar_access(Class* klass, AccessVariable* acc) { if(acc->write()->true_p()) return; if(count_ != 0) return; acc->add_inliner(ops_.vmmethod()); ops_.state()->add_accessor_inlined(); Value* self = ops_.stack_top(); BasicBlock* use_send = ops_.new_block("use_send"); ops_.check_reference_class(self, klass->class_id(), use_send); // Figure out if we should use the table ivar lookup or // the slot ivar lookup. TypeInfo* ti = klass->type_info(); TypeInfo::Slots::iterator it = ti->slots.find(acc->name()->index()); Value* ivar = 0; if(it != ti->slots.end()) { int offset = ti->slot_locations[it->second]; ivar = ops_.get_object_slot(ops_.stack_top(), offset); } else { Signature sig2(ops_.state(), "Object"); sig2 << "VM"; sig2 << "Object"; sig2 << "Object"; Value* call_args2[] = { ops_.vm(), ops_.stack_top(), ops_.constant(acc->name()) }; ivar = sig2.call("rbx_get_ivar", call_args2, 3, "ivar", ops_.current_block()); } ops_.stack_pop(); ops_.stack_push(ivar); ops_.create_branch(after_); ops_.set_block(use_send); after_->moveAfter(use_send); } void call_tuple_at() { Value* rec = recv(); // bool is_tuple = recv->flags & mask; Value* cmp = ops_.check_type_bits(rec, rubinius::Tuple::type); BasicBlock* is_tuple = ops_.new_block("is_tuple"); BasicBlock* access = ops_.new_block("tuple_at"); BasicBlock* is_other = ops_.new_block("is_other"); ops_.create_conditional_branch(is_tuple, is_other, cmp); ops_.set_block(is_tuple); Value* index_val = arg(0); Value* fix_cmp = ops_.check_if_fixnum(index_val); // Check that index is not over the end of the Tuple Value* tup = ops_.upcast(rec, "Tuple"); Value* index = ops_.tag_strip32(index_val); Value* full_size = ops_.get_tuple_size(tup); Value* size_cmp = ops_.create_less_than(index, full_size, "is_in_bounds"); // Combine fix_cmp and size_cmp to validate entry into access code Value* access_cmp = ops_.create_and(fix_cmp, size_cmp, "access_cmp"); ops_.create_conditional_branch(access, is_other, access_cmp); ops_.set_block(access); ops_.stack_remove(2); Value* idx[] = { ConstantInt::get(Type::Int32Ty, 0), ConstantInt::get(Type::Int32Ty, offset::tuple_field), index }; Value* gep = ops_.create_gep(tup, idx, 3, "field_pos"); ops_.stack_push(ops_.create_load(gep, "tuple_at")); ops_.create_branch(after_); ops_.set_block(is_other); } void call_tuple_put() { Value* rec = recv(); Value* cmp = ops_.check_type_bits(rec, rubinius::Tuple::type); BasicBlock* is_tuple = ops_.new_block("is_tuple"); BasicBlock* access = ops_.new_block("tuple_put"); BasicBlock* is_other = ops_.new_block("is_other"); ops_.create_conditional_branch(is_tuple, is_other, cmp); ops_.set_block(is_tuple); Value* index_val = arg(0); Value* fix_cmp = ops_.check_if_fixnum(index_val); Value* tup = ops_.upcast(rec, "Tuple"); Value* index = ops_.tag_strip32(index_val); Value* full_size = ops_.get_tuple_size(tup); Value* size_cmp = ops_.create_less_than(index, full_size, "is_in_bounds"); // Combine fix_cmp and size_cmp to validate entry into access code Value* access_cmp = ops_.create_and(fix_cmp, size_cmp, "access_cmp"); ops_.create_conditional_branch(access, is_other, access_cmp); ops_.set_block(access); Value* value = arg(1); ops_.stack_remove(3); Value* idx[] = { ConstantInt::get(Type::Int32Ty, 0), ConstantInt::get(Type::Int32Ty, offset::tuple_field), index }; Value* gep = ops_.create_gep(tup, idx, 3, "field_pos"); ops_.create_store(value, gep); ops_.write_barrier(tup, value); ops_.stack_push(value); ops_.create_branch(after_); ops_.set_block(is_other); } }; } <commit_msg>Disable accessor inlining for now<commit_after>#include "llvm/jit_operations.hpp" #include "llvm/access_memory.hpp" #include "builtin/access_variable.hpp" namespace rubinius { class Inliner { JITOperations& ops_; InlineCache* cache_; int count_; BasicBlock* after_; public: Inliner(JITOperations& ops, InlineCache* cache, int count, BasicBlock* after) : ops_(ops) , cache_(cache) , count_(count) , after_(after) {} Value* recv() { return ops_.stack_back(count_); } Value* arg(int which) { return ops_.stack_back(count_ - which); } void consider() { executor callee = cache_->method->execute; if(callee == Primitives::tuple_at && count_ == 1) { call_tuple_at(); } else if(callee == Primitives::tuple_put && count_ == 2) { call_tuple_put(); // If the cache has only ever had one class, inline! /* } else if(cache_->classes_seen() == 1) { AccessManagedMemory memguard(ops_.state()); Executable* meth = cache_->method; if(AccessVariable* acc = try_as<AccessVariable>(meth)) { inline_ivar_access(cache_->tracked_class(0), acc); } */ } } void inline_ivar_access(Class* klass, AccessVariable* acc) { if(acc->write()->true_p()) return; if(count_ != 0) return; acc->add_inliner(ops_.vmmethod()); ops_.state()->add_accessor_inlined(); Value* self = ops_.stack_top(); BasicBlock* use_send = ops_.new_block("use_send"); ops_.check_reference_class(self, klass->class_id(), use_send); // Figure out if we should use the table ivar lookup or // the slot ivar lookup. TypeInfo* ti = klass->type_info(); TypeInfo::Slots::iterator it = ti->slots.find(acc->name()->index()); Value* ivar = 0; if(it != ti->slots.end()) { int offset = ti->slot_locations[it->second]; ivar = ops_.get_object_slot(ops_.stack_top(), offset); } else { Signature sig2(ops_.state(), "Object"); sig2 << "VM"; sig2 << "Object"; sig2 << "Object"; Value* call_args2[] = { ops_.vm(), ops_.stack_top(), ops_.constant(acc->name()) }; ivar = sig2.call("rbx_get_ivar", call_args2, 3, "ivar", ops_.current_block()); } ops_.stack_pop(); ops_.stack_push(ivar); ops_.create_branch(after_); ops_.set_block(use_send); after_->moveAfter(use_send); } void call_tuple_at() { Value* rec = recv(); // bool is_tuple = recv->flags & mask; Value* cmp = ops_.check_type_bits(rec, rubinius::Tuple::type); BasicBlock* is_tuple = ops_.new_block("is_tuple"); BasicBlock* access = ops_.new_block("tuple_at"); BasicBlock* is_other = ops_.new_block("is_other"); ops_.create_conditional_branch(is_tuple, is_other, cmp); ops_.set_block(is_tuple); Value* index_val = arg(0); Value* fix_cmp = ops_.check_if_fixnum(index_val); // Check that index is not over the end of the Tuple Value* tup = ops_.upcast(rec, "Tuple"); Value* index = ops_.tag_strip32(index_val); Value* full_size = ops_.get_tuple_size(tup); Value* size_cmp = ops_.create_less_than(index, full_size, "is_in_bounds"); // Combine fix_cmp and size_cmp to validate entry into access code Value* access_cmp = ops_.create_and(fix_cmp, size_cmp, "access_cmp"); ops_.create_conditional_branch(access, is_other, access_cmp); ops_.set_block(access); ops_.stack_remove(2); Value* idx[] = { ConstantInt::get(Type::Int32Ty, 0), ConstantInt::get(Type::Int32Ty, offset::tuple_field), index }; Value* gep = ops_.create_gep(tup, idx, 3, "field_pos"); ops_.stack_push(ops_.create_load(gep, "tuple_at")); ops_.create_branch(after_); ops_.set_block(is_other); } void call_tuple_put() { Value* rec = recv(); Value* cmp = ops_.check_type_bits(rec, rubinius::Tuple::type); BasicBlock* is_tuple = ops_.new_block("is_tuple"); BasicBlock* access = ops_.new_block("tuple_put"); BasicBlock* is_other = ops_.new_block("is_other"); ops_.create_conditional_branch(is_tuple, is_other, cmp); ops_.set_block(is_tuple); Value* index_val = arg(0); Value* fix_cmp = ops_.check_if_fixnum(index_val); Value* tup = ops_.upcast(rec, "Tuple"); Value* index = ops_.tag_strip32(index_val); Value* full_size = ops_.get_tuple_size(tup); Value* size_cmp = ops_.create_less_than(index, full_size, "is_in_bounds"); // Combine fix_cmp and size_cmp to validate entry into access code Value* access_cmp = ops_.create_and(fix_cmp, size_cmp, "access_cmp"); ops_.create_conditional_branch(access, is_other, access_cmp); ops_.set_block(access); Value* value = arg(1); ops_.stack_remove(3); Value* idx[] = { ConstantInt::get(Type::Int32Ty, 0), ConstantInt::get(Type::Int32Ty, offset::tuple_field), index }; Value* gep = ops_.create_gep(tup, idx, 3, "field_pos"); ops_.create_store(value, gep); ops_.write_barrier(tup, value); ops_.stack_push(value); ops_.create_branch(after_); ops_.set_block(is_other); } }; } <|endoftext|>
<commit_before>/* * copyright: (c) RDO-Team, 2011 * filename : main.cpp * author : Evgeny Proydakov * email : [email protected] * date : 16.06.2011 * bref : Test rdo_common * indent : 4T */ // ====================================================================== PCH // ====================================================================== INCLUDES #include <boost/regex.hpp> // ====================================================================== SYNOPSIS #include "rdo_common/rdocommon.h" #include "rdo_common/rdofile.h" #include "rdo_common/rdotime.h" #include "rdo_common/test/rdo_common_test/resource.h" #include <config-tiles.h> // =============================================================================== #define BOOST_TEST_MODULE test_rdo_common #include <boost/test/included/unit_test.hpp> BOOST_AUTO_TEST_SUITE(test_rdo_common) BOOST_AUTO_TEST_CASE(test_rdo_common_1) { // TODO HELP ME !!!! tstring str1 = rdo::format(IDS_STRING101); tstring str2 = rdo::format(IDS_STRING102, 22); tstring str3 = rdo::format(IDS_STRING103, str1.c_str(), 33, str2.c_str()); } BOOST_AUTO_TEST_CASE(test_create_file) { BOOST_CHECK(rdo::File::create(_T(tstring(resource_directory) + tstring(test_file_name)))); } BOOST_AUTO_TEST_CASE(test_exist_file) { BOOST_CHECK(rdo::File::exist(_T(tstring(resource_directory) + tstring(test_file_name)))); } BOOST_AUTO_TEST_CASE(test_read_only_file) { BOOST_CHECK(!rdo::File::read_only(_T(tstring(resource_directory) + tstring(test_file_name)))); } BOOST_AUTO_TEST_CASE(test_remove_file) { BOOST_CHECK(rdo::File::unlink(_T(tstring(resource_directory) + tstring(test_file_name)))); } BOOST_AUTO_TEST_CASE(test_rdo_check_data) { // TODO EDIT REGEX rdo::Time time1 = rdo::Time::local(); tstring time_str = time1.asString(); boost::regex expression("(.*)"); boost::cmatch what; BOOST_CHECK(boost::regex_match(time_str.c_str(), what, expression)); } BOOST_AUTO_TEST_SUITE_END()<commit_msg> - библиотечные инклюды располагаются в INCLUDES - инклюды проекта располагаются SYNOPSIS - инклюды проекта указываются от корня сорсов<commit_after>/* * copyright: (c) RDO-Team, 2011 * filename : main.cpp * author : Evgeny Proydakov * email : [email protected] * date : 16.06.2011 * bref : Test rdo_common * indent : 4T */ // ====================================================================== PCH // ====================================================================== INCLUDES #include <boost/regex.hpp> #define BOOST_TEST_MODULE test_rdo_common #include <boost/test/included/unit_test.hpp> // ====================================================================== SYNOPSIS #include "rdo_common/rdocommon.h" #include "rdo_common/rdofile.h" #include "rdo_common/rdotime.h" #include "rdo_common/test/rdo_common_test/resource.h" #include "rdo_common/test/rdo_common_test/config-tiles.h" // =============================================================================== BOOST_AUTO_TEST_SUITE(test_rdo_common) BOOST_AUTO_TEST_CASE(test_rdo_common_1) { // TODO HELP ME !!!! tstring str1 = rdo::format(IDS_STRING101); tstring str2 = rdo::format(IDS_STRING102, 22); tstring str3 = rdo::format(IDS_STRING103, str1.c_str(), 33, str2.c_str()); } BOOST_AUTO_TEST_CASE(test_create_file) { BOOST_CHECK(rdo::File::create(_T(tstring(resource_directory) + tstring(test_file_name)))); } BOOST_AUTO_TEST_CASE(test_exist_file) { BOOST_CHECK(rdo::File::exist(_T(tstring(resource_directory) + tstring(test_file_name)))); } BOOST_AUTO_TEST_CASE(test_read_only_file) { BOOST_CHECK(!rdo::File::read_only(_T(tstring(resource_directory) + tstring(test_file_name)))); } BOOST_AUTO_TEST_CASE(test_remove_file) { BOOST_CHECK(rdo::File::unlink(_T(tstring(resource_directory) + tstring(test_file_name)))); } BOOST_AUTO_TEST_CASE(test_rdo_check_data) { // TODO EDIT REGEX rdo::Time time1 = rdo::Time::local(); tstring time_str = time1.asString(); boost::regex expression("(.*)"); boost::cmatch what; BOOST_CHECK(boost::regex_match(time_str.c_str(), what, expression)); } BOOST_AUTO_TEST_SUITE_END()<|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include "geometry/point.hpp" #include "geometry/triangle.hpp" #include "triangulation/figure_definition.hpp" #include "triangulation/triangulation.hpp" struct HUI : public FigureDefinition { int parameter(double x, double y) { //return !(y > x + 3 || y > 12 - x || (y > 2 && y < 4 && y < x && y < 9 - x)); return (y<=1 && ((y<=x && y>=x-2) || (y>=4-x && y<=6-x))) || (y>=1 && y<=2 && (y<=x && y<=6-x)) || (y>=2 && y<=3 && (y>=4-x && y>=x-2)) || (y>=3 && y<=4 && ((y<=x && y>=x-2) || (y>=4-x && y<=6-x))) || (y<=2 && y<=x-6 && y>=x-8) || (y>=2 && y<=3 && (y>=10-x && y>=x-8)) || (y>=3 && y<=4 && ((y<=x-6 && y>=x-8) || (y>=10-x && y<=12-x))) || (y<=4 && x>=12 && x<=14) || (x>=14 && x<=16 && y>=x-14 && y<=x-12) || (y<=4 && x>=16 && x<=18) || (y>=19-x && y>=x-11); } }; HUI hui; // Triangulacia nahui Triangulation triangulation(&hui); void print(void) { FILE *gmain; gmain = fopen("main", "w"); fprintf(gmain, "plot 'data' with lines\npause mouse close\n"); fclose(gmain); triangulation.dump("data"); system("gnuplot main"); unlink("main"); unlink("data"); } void demo() { triangulation.make_grid(19, 6); print(); triangulation.make_it_smaller(); print(); triangulation.make_it_smaller(); print(); } int main() { triangulation.make_grid(19, 6); triangulation.make_it_smaller(); triangulation.make_it_smaller(); triangulation.write(stdout); return 0; } <commit_msg>Better defaults in triangulate.cpp<commit_after>#include <cstdio> #include <cstdlib> #include "geometry/point.hpp" #include "geometry/triangle.hpp" #include "triangulation/figure_definition.hpp" #include "triangulation/triangulation.hpp" struct HUI : public FigureDefinition { int parameter(double x, double y) { //return !(y > x + 3 || y > 12 - x || (y > 2 && y < 4 && y < x && y < 9 - x)); return (y<=1 && ((y<=x && y>=x-2) || (y>=4-x && y<=6-x))) || (y>=1 && y<=2 && (y<=x && y<=6-x)) || (y>=2 && y<=3 && (y>=4-x && y>=x-2)) || (y>=3 && y<=4 && ((y<=x && y>=x-2) || (y>=4-x && y<=6-x))) || (y<=2 && y<=x-6 && y>=x-8) || (y>=2 && y<=3 && (y>=10-x && y>=x-8)) || (y>=3 && y<=4 && ((y<=x-6 && y>=x-8) || (y>=10-x && y<=12-x))) || (y<=4 && x>=12 && x<=14) || (x>=14 && x<=16 && y>=x-14 && y<=x-12) || (y<=4 && x>=16 && x<=18) || (y>=19-x && y>=x-11); } }; HUI hui; // Triangulacia nahui Triangulation triangulation(&hui); void print(void) { FILE *gmain; gmain = fopen("main", "w"); fprintf(gmain, "plot 'data' with lines\npause mouse close\n"); fclose(gmain); triangulation.dump("data"); system("gnuplot main"); unlink("main"); unlink("data"); } void demo() { triangulation.make_grid(19, 6); print(); triangulation.make_it_smaller(); print(); triangulation.make_it_smaller(); print(); } void run() { triangulation.make_grid(19, 6); triangulation.make_it_smaller(); triangulation.make_it_smaller(); triangulation.write(stdout); } int main() { demo(); return 0; } <|endoftext|>
<commit_before>/* Copyright 2013 Roman Kurbatov * * 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. * * This file was modified by Yurii Litvinov to make it comply with the requirements of trikRuntime * project. See git revision history for detailed changes. */ #include "netConfigWidget.h" #include <QtNetwork/QNetworkInterface> #include <QtNetwork/QNetworkAddressEntry> #include <QtNetwork/QHostAddress> #include <QtNetwork/QAbstractSocket> #include <QtGui/QKeyEvent> #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #include <QtGui/QScrollBar> #else #include <QtWidgets/QScrollBar> #endif #include <QtCore/QDebug> #include <trikWiFi/trikWiFi.h> #include <trikWiFi/wpaConfigurer.h> using namespace trikGui; using namespace trikWiFi; NetConfigWidget::NetConfigWidget(QString const &configPath, QWidget *parent) : QWidget(parent) , mWiFi(new TrikWiFi("/tmp/trikwifi", "/run/wpa_supplicant/wlan0", this)) , mConnectionState(notConnected) { setAttribute(Qt::WA_DeleteOnClose); setWindowState(Qt::WindowFullScreen); WpaConfigurer::configureWpaSupplicant(configPath + "wpa-config.xml", *mWiFi); QList<NetworkConfiguration> const networksFromWpaSupplicant = mWiFi->listNetworks(); foreach (NetworkConfiguration const &networkConfiguration, networksFromWpaSupplicant) { mNetworksAvailableForConnection.insert(networkConfiguration.ssid, networkConfiguration.id); } connect(mWiFi.data(), SIGNAL(scanFinished()), this, SLOT(scanForAvailableNetworksDoneSlot())); connect(mWiFi.data(), SIGNAL(connected()), this, SLOT(connectedSlot())); connect(mWiFi.data(), SIGNAL(disconnected()), this, SLOT(disconnectedSlot())); mWiFi->scan(); mConnectionIconLabel.setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); mIpLabel.setText(tr("IP:")); mIpLabel.setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); mAvailableNetworksLabel.setText(tr("Available networks:")); mAvailableNetworksView.setModel(&mAvailableNetworksModel); mAvailableNetworksView.setSelectionMode(QAbstractItemView::SingleSelection); mIpAddressLayout.addWidget(&mConnectionIconLabel); mIpAddressLayout.addWidget(&mIpLabel); mIpAddressLayout.addWidget(&mIpValueLabel); mMainLayout.addLayout(&mIpAddressLayout); mMainLayout.addWidget(&mAvailableNetworksLabel); mMainLayout.addWidget(&mAvailableNetworksView); setLayout(&mMainLayout); Status const connectionStatus = mWiFi->status(); mConnectionState = connectionStatus.connected ? connected : notConnected; setConnectionStatus(connectionStatus); } NetConfigWidget::~NetConfigWidget() { } QString NetConfigWidget::menuEntry() { return tr("Network config"); } void NetConfigWidget::scanForAvailableNetworksDoneSlot() { mAvailableNetworksModel.clear(); foreach (ScanResult const &result, mWiFi->scanResults()) { mAvailableNetworksModel.appendRow(new QStandardItem(result.ssid)); } updateConnectionStatusesInNetworkList(); } void NetConfigWidget::connectedSlot() { mConnectionState = connected; setConnectionStatus(mWiFi->status()); } void NetConfigWidget::disconnectedSlot() { if (mConnectionState != connecting) { mConnectionState = notConnected; } setConnectionStatus(mWiFi->status()); // Now to determine reason of disconnect --- maybe the network is out of range now. mWiFi->scan(); } void NetConfigWidget::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Meta: case Qt::Key_Left: { close(); break; } case Qt::Key_Enter: { connectToSelectedNetwork(); } default: { QWidget::keyPressEvent(event); break; } } } void NetConfigWidget::setConnectionStatus(trikWiFi::Status const &status) { QPixmap pixmap; switch (mConnectionState) { case connected: pixmap.load("://resources/connected.png"); mIpValueLabel.setText(status.ipAddress); mCurrentSsid = status.ssid; break; case connecting: pixmap.load("://resources/unknownConnectionStatus.png"); mIpValueLabel.setText(tr("connecting...")); mCurrentSsid = ""; break; case notConnected: pixmap.load("://resources/notConnected.png"); mIpValueLabel.setText(tr("no connection")); mCurrentSsid = ""; break; } mConnectionIconLabel.setPixmap(pixmap); updateConnectionStatusesInNetworkList(); } void NetConfigWidget::updateConnectionStatusesInNetworkList() { for (int i = 0; i < mAvailableNetworksModel.rowCount(); ++i) { QStandardItem * const item = mAvailableNetworksModel.item(i); QFont font = item->font(); font.setBold(false); item->setFont(font); if (item->text() == mCurrentSsid) { item->setIcon(QIcon("://resources/connectedToNetwork.png")); font.setBold(true); item->setFont(font); } else if (mNetworksAvailableForConnection.contains(item->text())) { item->setIcon(QIcon("://resources/notConnectedToNetwork.png")); } else { item->setIcon(QIcon("://resources/connectionToNetworkImpossible.png")); } } mAvailableNetworksView.setFocus(); mAvailableNetworksView.selectionModel()->select( mAvailableNetworksModel.index(0, 0) , QItemSelectionModel::ClearAndSelect ); } void NetConfigWidget::connectToSelectedNetwork() { QModelIndexList const selected = mAvailableNetworksView.selectionModel()->selectedIndexes(); if (selected.size() != 1) { return; } QString const ssid = mAvailableNetworksModel.itemFromIndex(selected[0])->text(); if (ssid == mCurrentSsid) { return; } if (!mNetworksAvailableForConnection.contains(ssid)) { return; } mConnectionState = connecting; mWiFi->connect(mNetworksAvailableForConnection[ssid]); } <commit_msg>Updating connection state when connecting to a network for a first time<commit_after>/* Copyright 2013 Roman Kurbatov * * 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. * * This file was modified by Yurii Litvinov to make it comply with the requirements of trikRuntime * project. See git revision history for detailed changes. */ #include "netConfigWidget.h" #include <QtNetwork/QNetworkInterface> #include <QtNetwork/QNetworkAddressEntry> #include <QtNetwork/QHostAddress> #include <QtNetwork/QAbstractSocket> #include <QtGui/QKeyEvent> #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #include <QtGui/QScrollBar> #else #include <QtWidgets/QScrollBar> #endif #include <QtCore/QDebug> #include <trikWiFi/trikWiFi.h> #include <trikWiFi/wpaConfigurer.h> using namespace trikGui; using namespace trikWiFi; NetConfigWidget::NetConfigWidget(QString const &configPath, QWidget *parent) : QWidget(parent) , mWiFi(new TrikWiFi("/tmp/trikwifi", "/run/wpa_supplicant/wlan0", this)) , mConnectionState(notConnected) { setAttribute(Qt::WA_DeleteOnClose); setWindowState(Qt::WindowFullScreen); WpaConfigurer::configureWpaSupplicant(configPath + "wpa-config.xml", *mWiFi); QList<NetworkConfiguration> const networksFromWpaSupplicant = mWiFi->listNetworks(); foreach (NetworkConfiguration const &networkConfiguration, networksFromWpaSupplicant) { mNetworksAvailableForConnection.insert(networkConfiguration.ssid, networkConfiguration.id); } connect(mWiFi.data(), SIGNAL(scanFinished()), this, SLOT(scanForAvailableNetworksDoneSlot())); connect(mWiFi.data(), SIGNAL(connected()), this, SLOT(connectedSlot())); connect(mWiFi.data(), SIGNAL(disconnected()), this, SLOT(disconnectedSlot())); mWiFi->scan(); mConnectionIconLabel.setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); mIpLabel.setText(tr("IP:")); mIpLabel.setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); mAvailableNetworksLabel.setText(tr("Available networks:")); mAvailableNetworksView.setModel(&mAvailableNetworksModel); mAvailableNetworksView.setSelectionMode(QAbstractItemView::SingleSelection); mIpAddressLayout.addWidget(&mConnectionIconLabel); mIpAddressLayout.addWidget(&mIpLabel); mIpAddressLayout.addWidget(&mIpValueLabel); mMainLayout.addLayout(&mIpAddressLayout); mMainLayout.addWidget(&mAvailableNetworksLabel); mMainLayout.addWidget(&mAvailableNetworksView); setLayout(&mMainLayout); Status const connectionStatus = mWiFi->status(); mConnectionState = connectionStatus.connected ? connected : notConnected; setConnectionStatus(connectionStatus); } NetConfigWidget::~NetConfigWidget() { } QString NetConfigWidget::menuEntry() { return tr("Network config"); } void NetConfigWidget::scanForAvailableNetworksDoneSlot() { mAvailableNetworksModel.clear(); foreach (ScanResult const &result, mWiFi->scanResults()) { mAvailableNetworksModel.appendRow(new QStandardItem(result.ssid)); } updateConnectionStatusesInNetworkList(); } void NetConfigWidget::connectedSlot() { mConnectionState = connected; setConnectionStatus(mWiFi->status()); } void NetConfigWidget::disconnectedSlot() { if (mConnectionState != connecting) { mConnectionState = notConnected; } setConnectionStatus(mWiFi->status()); // Now to determine reason of disconnect --- maybe the network is out of range now. mWiFi->scan(); } void NetConfigWidget::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Meta: case Qt::Key_Left: { close(); break; } case Qt::Key_Enter: { connectToSelectedNetwork(); } default: { QWidget::keyPressEvent(event); break; } } } void NetConfigWidget::setConnectionStatus(trikWiFi::Status const &status) { QPixmap pixmap; switch (mConnectionState) { case connected: pixmap.load("://resources/connected.png"); mIpValueLabel.setText(status.ipAddress); mCurrentSsid = status.ssid; break; case connecting: pixmap.load("://resources/unknownConnectionStatus.png"); mIpValueLabel.setText(tr("connecting...")); mCurrentSsid = ""; break; case notConnected: pixmap.load("://resources/notConnected.png"); mIpValueLabel.setText(tr("no connection")); mCurrentSsid = ""; break; } mConnectionIconLabel.setPixmap(pixmap); updateConnectionStatusesInNetworkList(); } void NetConfigWidget::updateConnectionStatusesInNetworkList() { for (int i = 0; i < mAvailableNetworksModel.rowCount(); ++i) { QStandardItem * const item = mAvailableNetworksModel.item(i); QFont font = item->font(); font.setBold(false); item->setFont(font); if (item->text() == mCurrentSsid) { item->setIcon(QIcon("://resources/connectedToNetwork.png")); font.setBold(true); item->setFont(font); } else if (mNetworksAvailableForConnection.contains(item->text())) { item->setIcon(QIcon("://resources/notConnectedToNetwork.png")); } else { item->setIcon(QIcon("://resources/connectionToNetworkImpossible.png")); } } mAvailableNetworksView.setFocus(); mAvailableNetworksView.selectionModel()->select( mAvailableNetworksModel.index(0, 0) , QItemSelectionModel::ClearAndSelect ); } void NetConfigWidget::connectToSelectedNetwork() { QModelIndexList const selected = mAvailableNetworksView.selectionModel()->selectedIndexes(); if (selected.size() != 1) { return; } QString const ssid = mAvailableNetworksModel.itemFromIndex(selected[0])->text(); if (ssid == mCurrentSsid) { return; } if (!mNetworksAvailableForConnection.contains(ssid)) { return; } mConnectionState = connecting; setConnectionStatus(Status()); mWiFi->connect(mNetworksAvailableForConnection[ssid]); } <|endoftext|>
<commit_before>/* * Copyright 2011 Jonathan Anderson * * 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 <sstream> #include "capsicum.h" using namespace capsh; using std::ostringstream; using std::string; bool capsh::inCapabilityMode() throw(CError) { unsigned int mode; if (cap_getmode(&mode) < 0) throw CError("cap_getmode()"); return (mode != 0); } void capsh::assertNotInCapabilityMode(const string& action) throw(CError, CapabilityModeException) { if (inCapabilityMode()) throw CapabilityModeException(action); } string capsh::rightsString(cap_rights_t rights) { ostringstream oss; if (rights & CAP_READ) oss << "CAP_READ "; if (rights & CAP_WRITE) oss << "CAP_WRITE "; if (rights & CAP_SEEK) oss << "CAP_SEEK "; if (rights & CAP_GETPEERNAME) oss << "CAP_GETPEERNAME "; if (rights & CAP_GETSOCKNAME) oss << "CAP_GETSOCKNAME "; if (rights & CAP_FCHFLAGS) oss << "CAP_FCHFLAGS "; if (rights & CAP_IOCTL) oss << "CAP_IOCTL "; if (rights & CAP_FSTAT) oss << "CAP_FSTAT "; if (rights & CAP_MMAP) oss << "CAP_MMAP "; if (rights & CAP_FCNTL) oss << "CAP_FCNTL "; if (rights & CAP_POLL_KEVENT) oss << "CAP_POLL_KEVENT "; if (rights & CAP_FSYNC) oss << "CAP_FSYNC "; if (rights & CAP_FCHOWN) oss << "CAP_FCHOWN "; if (rights & CAP_FCHMOD) oss << "CAP_FCHMOD "; if (rights & CAP_FTRUNCATE) oss << "CAP_FTRUNCATE "; if (rights & CAP_FLOCK) oss << "CAP_FLOCK "; if (rights & CAP_FSTATFS) oss << "CAP_FSTATFS "; if (rights & CAP_FEXECVE) oss << "CAP_FEXECVE "; if (rights & CAP_FPATHCONF) oss << "CAP_FPATHCONF "; if (rights & CAP_FUTIMES) oss << "CAP_FUTIMES "; if (rights & CAP_ACL_GET) oss << "CAP_ACL_GET "; if (rights & CAP_ACL_SET) oss << "CAP_ACL_SET "; if (rights & CAP_ACL_DELETE) oss << "CAP_ACL_DELETE "; if (rights & CAP_ACL_CHECK) oss << "CAP_ACL_CHECK "; if (rights & CAP_EXTATTR_GET) oss << "CAP_EXTATTR_GET "; if (rights & CAP_EXTATTR_SET) oss << "CAP_EXTATTR_SET "; if (rights & CAP_EXTATTR_DELETE) oss << "CAP_EXTATTR_DELETE "; if (rights & CAP_EXTATTR_LIST) oss << "CAP_EXTATTR_LIST "; if (rights & CAP_MAC_GET) oss << "CAP_MAC_GET "; if (rights & CAP_MAC_SET) oss << "CAP_MAC_SET "; if (rights & CAP_ACCEPT) oss << "CAP_ACCEPT "; if (rights & CAP_CONNECT) oss << "CAP_CONNECT "; if (rights & CAP_BIND) oss << "CAP_BIND "; if (rights & CAP_GETSOCKOPT) oss << "CAP_GETSOCKOPT "; if (rights & CAP_SETSOCKOPT) oss << "CAP_SETSOCKOPT "; if (rights & CAP_LISTEN) oss << "CAP_LISTEN "; if (rights & CAP_SHUTDOWN) oss << "CAP_SHUTDOWN "; if (rights & CAP_PEELOFF) oss << "CAP_PEELOFF "; if (rights & CAP_LOOKUP) oss << "CAP_LOOKUP "; if (rights & CAP_SEM_POST) oss << "CAP_SEM_POST "; if (rights & CAP_SEM_WAIT) oss << "CAP_SEM_WAIT "; if (rights & CAP_SEM_GETVALUE) oss << "CAP_SEM_GETVALUE "; if (rights & CAP_POST_KEVENT) oss << "CAP_POST_KEVENT "; if (rights & CAP_PDGETPID) oss << "CAP_PDGETPID "; if (rights & CAP_PDKILL) oss << "CAP_PDKILL "; if (rights & CAP_MAPEXEC) oss << "CAP_MAPEXEC "; if (rights & CAP_TTYHOOK) oss << "CAP_TTYHOOK "; if (rights & CAP_FCHDIR) oss << "CAP_FCHDIR "; if (rights & CAP_FSCK) oss << "CAP_FSCK "; if (rights & CAP_CREATE) oss << "CAP_CREATE "; if (rights & CAP_DELETE) oss << "CAP_DELETE "; if (rights & CAP_MKDIR) oss << "CAP_MKDIR "; if (rights & CAP_RMDIR) oss << "CAP_RMDIR "; if (rights & CAP_MKFIFO) oss << "CAP_MKFIFO "; return oss.str(); } <commit_msg>CAP_KEVENT -> CAP_POST_EVENT, etc.<commit_after>/* * Copyright 2011 Jonathan Anderson * * 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 <sstream> #include "capsicum.h" using namespace capsh; using std::ostringstream; using std::string; bool capsh::inCapabilityMode() throw(CError) { unsigned int mode; if (cap_getmode(&mode) < 0) throw CError("cap_getmode()"); return (mode != 0); } void capsh::assertNotInCapabilityMode(const string& action) throw(CError, CapabilityModeException) { if (inCapabilityMode()) throw CapabilityModeException(action); } string capsh::rightsString(cap_rights_t rights) { ostringstream oss; if (rights & CAP_READ) oss << "CAP_READ "; if (rights & CAP_WRITE) oss << "CAP_WRITE "; if (rights & CAP_SEEK) oss << "CAP_SEEK "; if (rights & CAP_GETPEERNAME) oss << "CAP_GETPEERNAME "; if (rights & CAP_GETSOCKNAME) oss << "CAP_GETSOCKNAME "; if (rights & CAP_FCHFLAGS) oss << "CAP_FCHFLAGS "; if (rights & CAP_IOCTL) oss << "CAP_IOCTL "; if (rights & CAP_FSTAT) oss << "CAP_FSTAT "; if (rights & CAP_MMAP) oss << "CAP_MMAP "; if (rights & CAP_FCNTL) oss << "CAP_FCNTL "; if (rights & CAP_POLL_EVENT) oss << "CAP_POLL_KEVENT "; if (rights & CAP_FSYNC) oss << "CAP_FSYNC "; if (rights & CAP_FCHOWN) oss << "CAP_FCHOWN "; if (rights & CAP_FCHMOD) oss << "CAP_FCHMOD "; if (rights & CAP_FTRUNCATE) oss << "CAP_FTRUNCATE "; if (rights & CAP_FLOCK) oss << "CAP_FLOCK "; if (rights & CAP_FSTATFS) oss << "CAP_FSTATFS "; if (rights & CAP_FEXECVE) oss << "CAP_FEXECVE "; if (rights & CAP_FPATHCONF) oss << "CAP_FPATHCONF "; if (rights & CAP_FUTIMES) oss << "CAP_FUTIMES "; if (rights & CAP_ACL_GET) oss << "CAP_ACL_GET "; if (rights & CAP_ACL_SET) oss << "CAP_ACL_SET "; if (rights & CAP_ACL_DELETE) oss << "CAP_ACL_DELETE "; if (rights & CAP_ACL_CHECK) oss << "CAP_ACL_CHECK "; if (rights & CAP_EXTATTR_GET) oss << "CAP_EXTATTR_GET "; if (rights & CAP_EXTATTR_SET) oss << "CAP_EXTATTR_SET "; if (rights & CAP_EXTATTR_DELETE) oss << "CAP_EXTATTR_DELETE "; if (rights & CAP_EXTATTR_LIST) oss << "CAP_EXTATTR_LIST "; if (rights & CAP_MAC_GET) oss << "CAP_MAC_GET "; if (rights & CAP_MAC_SET) oss << "CAP_MAC_SET "; if (rights & CAP_ACCEPT) oss << "CAP_ACCEPT "; if (rights & CAP_CONNECT) oss << "CAP_CONNECT "; if (rights & CAP_BIND) oss << "CAP_BIND "; if (rights & CAP_GETSOCKOPT) oss << "CAP_GETSOCKOPT "; if (rights & CAP_SETSOCKOPT) oss << "CAP_SETSOCKOPT "; if (rights & CAP_LISTEN) oss << "CAP_LISTEN "; if (rights & CAP_SHUTDOWN) oss << "CAP_SHUTDOWN "; if (rights & CAP_PEELOFF) oss << "CAP_PEELOFF "; if (rights & CAP_LOOKUP) oss << "CAP_LOOKUP "; if (rights & CAP_SEM_POST) oss << "CAP_SEM_POST "; if (rights & CAP_SEM_WAIT) oss << "CAP_SEM_WAIT "; if (rights & CAP_SEM_GETVALUE) oss << "CAP_SEM_GETVALUE "; if (rights & CAP_POST_EVENT) oss << "CAP_POST_KEVENT "; if (rights & CAP_PDGETPID) oss << "CAP_PDGETPID "; if (rights & CAP_PDKILL) oss << "CAP_PDKILL "; if (rights & CAP_MAPEXEC) oss << "CAP_MAPEXEC "; if (rights & CAP_TTYHOOK) oss << "CAP_TTYHOOK "; if (rights & CAP_FCHDIR) oss << "CAP_FCHDIR "; if (rights & CAP_FSCK) oss << "CAP_FSCK "; if (rights & CAP_CREATE) oss << "CAP_CREATE "; if (rights & CAP_DELETE) oss << "CAP_DELETE "; if (rights & CAP_MKDIR) oss << "CAP_MKDIR "; if (rights & CAP_RMDIR) oss << "CAP_RMDIR "; if (rights & CAP_MKFIFO) oss << "CAP_MKFIFO "; return oss.str(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: sdgrffilter.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: kz $ $Date: 2005-01-13 17:24:45 $ * * 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 _SD_SDGRFFILTER_HXX #define _SD_SDGRFFILTER_HXX #include <tools/errinf.hxx> #include "sdfilter.hxx" // --------------- // - SdCGMFilter - // --------------- class SdGRFFilter : public SdFilter { public: SdGRFFilter ( SfxMedium& rMedium, ::sd::DrawDocShell& rDocShell, sal_Bool bShowProgress ); virtual ~SdGRFFilter (void); sal_Bool Import(); sal_Bool Export(); static void HandleGraphicFilterError( USHORT nFilterError, ULONG nStreamError = ERRCODE_NONE ); private: static GDIMetaFile ImplRemoveClipRegionActions( const GDIMetaFile& rMtf ); static BitmapEx ImplGetBitmapFromMetaFile( const GDIMetaFile& rMtf, BOOL bTransparent, const Size* pSizePixel = NULL ); bool mbHideSpell; }; #endif // _SD_SDGRFFILTER_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.5.242); FILE MERGED 2005/09/05 13:20:00 rt 1.5.242.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sdgrffilter.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-09 02:59:56 $ * * 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 _SD_SDGRFFILTER_HXX #define _SD_SDGRFFILTER_HXX #include <tools/errinf.hxx> #include "sdfilter.hxx" // --------------- // - SdCGMFilter - // --------------- class SdGRFFilter : public SdFilter { public: SdGRFFilter ( SfxMedium& rMedium, ::sd::DrawDocShell& rDocShell, sal_Bool bShowProgress ); virtual ~SdGRFFilter (void); sal_Bool Import(); sal_Bool Export(); static void HandleGraphicFilterError( USHORT nFilterError, ULONG nStreamError = ERRCODE_NONE ); private: static GDIMetaFile ImplRemoveClipRegionActions( const GDIMetaFile& rMtf ); static BitmapEx ImplGetBitmapFromMetaFile( const GDIMetaFile& rMtf, BOOL bTransparent, const Size* pSizePixel = NULL ); bool mbHideSpell; }; #endif // _SD_SDGRFFILTER_HXX <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include <cassert> #include "sampler.h" #include "vec2.h" #include "bsdf.h" using namespace std; struct sas { sas() : tp(0), n(0) { } scalar tp; int n; }; scalar solid_angle_area(scalar t0, scalar t1, scalar p0, scalar p1) { return (t1 - t0) * (cos(p0) - cos(p1)); } scalar solid_angle_weighted_area(scalar t0, scalar t1, scalar p0, scalar p1) { return (t1 - t0) * (cos(2 * p0) - cos(2 * p1)) * 0.5; } void compare_bsdf(const BRDF& brdf, uint num_samples) { UniformSampler sampler; Vec3 incoming_dir = Vec3{0.0f, sqrt(0.5), sqrt(0.5)}; const int theta_grid = 1; const int phi_grid = 1000; sas r[theta_grid][phi_grid]; for (auto i = 0u; i < num_samples; ++i) { // compute the pdf scalar p; scalar refl; Vec3 dir = brdf.sample(incoming_dir, sampler, p, refl); scalar theta, phi; dir.to_euler(theta, phi); int theta_i = theta / (2 * PI) * theta_grid ; int phi_i = phi / (PI / 2) * phi_grid ; assert(0 <= theta_i && theta_i < theta_grid); assert(0 <= phi_i && phi_i < phi_grid); r[theta_i][phi_i].n += 1; r[theta_i][phi_i].tp += p; } const int num_cells = theta_grid * phi_grid; scalar total_integral = 0; for (int y = 0; y < theta_grid; ++y) { for (int x = 0; x < phi_grid; ++x) { scalar disp = num_cells * scalar(r[y][x].n) / num_samples; cout << setw(12) << disp; total_integral += disp; } cout << endl; } cout << total_integral / num_cells << endl << endl; total_integral = 0; for (int y = 0; y < theta_grid; ++y) { scalar t0 = y * 2 * PI / theta_grid; scalar t1 = (y + 1)* 2 * PI / theta_grid; for (int x = 0; x < phi_grid; ++x) { scalar p0 = x * 0.5 * PI / phi_grid; scalar p1 = (x + 1) * 0.5 * PI / phi_grid; scalar disp = r[y][x].n == 0 ? 0 : num_cells * (r[y][x].tp / r[y][x].n) * solid_angle_area(t0, t1, p0, p1); cout << setw(12) << disp; total_integral += disp; } cout << endl; } cout << total_integral / num_cells << endl << endl; total_integral = 0; for (int y = 0; y < theta_grid; ++y) { scalar t0 = y * 2 * PI / theta_grid; scalar t1 = (y + 1)* 2 * PI / theta_grid; for (int x = 0; x < phi_grid; ++x) { scalar p0 = x * 0.5 * PI / phi_grid; scalar p1 = (x + 1) * 0.5 * PI / phi_grid; scalar a = r[y][x].n == 0 ? 0 : num_cells * (r[y][x].tp / r[y][x].n) * solid_angle_area(t0, t1, p0, p1); scalar b = num_cells * scalar(r[y][x].n) / num_samples; scalar disp = a - b; cout << setw(12) << disp * 100; total_integral += disp; } cout << endl; } cout << total_integral / num_cells << endl << endl; } int main(int argc, char** args) { //compare_bsdf(OrenNayar(1.0, 0.3), 100000000); UniformSampler sampler; for (int i = 0; i < 1000; ++i) { auto v = uniform_sample_disc(sampler.sample_2d()); cout << v[0] << " " << v[1] << endl; } } <commit_msg>Adds sampling tests<commit_after>#include <iostream> #include <iomanip> #include <cassert> #include "materials/multilayered.h" #include "geometries.h" #include "sampler.h" #include "vec2.h" #include "bsdf.h" using namespace std; struct sas { sas() : tp(0), n(0) { } scalar tp; int n; }; scalar solid_angle_area(scalar t0, scalar t1, scalar p0, scalar p1) { return (t1 - t0) * (cos(p0) - cos(p1)); } scalar solid_angle_weighted_area(scalar t0, scalar t1, scalar p0, scalar p1) { return (t1 - t0) * (cos(2 * p0) - cos(2 * p1)) * 0.5; } void compare_bsdf(const BRDF& brdf, uint num_samples) { UniformSampler sampler; Vec3 incoming_dir = Vec3{0.0f, sqrt(0.5), sqrt(0.5)}; const int theta_grid = 1; const int phi_grid = 1000; sas r[theta_grid][phi_grid]; for (auto i = 0u; i < num_samples; ++i) { // compute the pdf scalar p; scalar refl; Vec3 dir = brdf.sample(incoming_dir, sampler, p, refl); scalar theta, phi; dir.to_euler(theta, phi); int theta_i = theta / (2 * PI) * theta_grid ; int phi_i = phi / (PI / 2) * phi_grid ; assert(0 <= theta_i && theta_i < theta_grid); assert(0 <= phi_i && phi_i < phi_grid); r[theta_i][phi_i].n += 1; r[theta_i][phi_i].tp += p; } const int num_cells = theta_grid * phi_grid; scalar total_integral = 0; for (int y = 0; y < theta_grid; ++y) { for (int x = 0; x < phi_grid; ++x) { scalar disp = num_cells * scalar(r[y][x].n) / num_samples; cout << setw(12) << disp; total_integral += disp; } cout << endl; } cout << total_integral / num_cells << endl << endl; total_integral = 0; for (int y = 0; y < theta_grid; ++y) { scalar t0 = y * 2 * PI / theta_grid; scalar t1 = (y + 1)* 2 * PI / theta_grid; for (int x = 0; x < phi_grid; ++x) { scalar p0 = x * 0.5 * PI / phi_grid; scalar p1 = (x + 1) * 0.5 * PI / phi_grid; scalar disp = r[y][x].n == 0 ? 0 : num_cells * (r[y][x].tp / r[y][x].n) * solid_angle_area(t0, t1, p0, p1); cout << setw(12) << disp; total_integral += disp; } cout << endl; } cout << total_integral / num_cells << endl << endl; total_integral = 0; for (int y = 0; y < theta_grid; ++y) { scalar t0 = y * 2 * PI / theta_grid; scalar t1 = (y + 1)* 2 * PI / theta_grid; for (int x = 0; x < phi_grid; ++x) { scalar p0 = x * 0.5 * PI / phi_grid; scalar p1 = (x + 1) * 0.5 * PI / phi_grid; scalar a = r[y][x].n == 0 ? 0 : num_cells * (r[y][x].tp / r[y][x].n) * solid_angle_area(t0, t1, p0, p1); scalar b = num_cells * scalar(r[y][x].n) / num_samples; scalar disp = a - b; cout << setw(12) << disp * 100; total_integral += disp; } cout << endl; } cout << total_integral / num_cells << endl << endl; } void compare_tld(const GTR& tld, uint num_samples) { UniformSampler sampler; const int theta_grid = 1; const int phi_grid = 100; sas r[theta_grid][phi_grid]; for (auto i = 0u; i < num_samples; ++i) { // compute the pdf scalar p; Vec3 dir = tld.sample_micronormal(sampler, p); scalar theta, phi; dir.to_euler(theta, phi); int theta_i = theta / (2 * PI) * theta_grid ; int phi_i = phi / (PI / 2) * phi_grid ; assert(0 <= theta_i && theta_i < theta_grid); assert(0 <= phi_i && phi_i < phi_grid); r[theta_i][phi_i].n += 1; r[theta_i][phi_i].tp += p; } const int num_cells = theta_grid * phi_grid; scalar total_integral = 0; for (int y = 0; y < theta_grid; ++y) { for (int x = 0; x < phi_grid; ++x) { scalar disp = num_cells * scalar(r[y][x].n) / num_samples; cout << setw(12) << disp; total_integral += disp; } cout << endl; } cout << total_integral / num_cells << endl << endl; total_integral = 0; for (int y = 0; y < theta_grid; ++y) { scalar t0 = y * 2 * PI / theta_grid; scalar t1 = (y + 1)* 2 * PI / theta_grid; for (int x = 0; x < phi_grid; ++x) { scalar p0 = x * 0.5 * PI / phi_grid; scalar p1 = (x + 1) * 0.5 * PI / phi_grid; scalar disp = r[y][x].n == 0 ? 0 : num_cells * (r[y][x].tp / r[y][x].n) * solid_angle_area(t0, t1, p0, p1); cout << setw(12) << disp; total_integral += disp; } cout << endl; } cout << total_integral / num_cells << endl << endl; total_integral = 0; for (int y = 0; y < theta_grid; ++y) { scalar t0 = y * 2 * PI / theta_grid; scalar t1 = (y + 1)* 2 * PI / theta_grid; for (int x = 0; x < phi_grid; ++x) { scalar p0 = x * 0.5 * PI / phi_grid; scalar p1 = (x + 1) * 0.5 * PI / phi_grid; scalar a = r[y][x].n == 0 ? 0 : num_cells * (r[y][x].tp / r[y][x].n) * solid_angle_area(t0, t1, p0, p1); scalar b = num_cells * scalar(r[y][x].n) / num_samples; scalar disp = a - b; cout << setw(12) << disp * 100; total_integral += disp; } cout << endl; } cout << total_integral / num_cells << endl << endl; } scalar compute_rho_hd(shared_ptr<Material> mat, const Vec3& incoming, uint num_samples) { spectrum r; auto p = make_shared<Plane>(Vec3(0, 0, 1), 0.0); Shape s(p, mat); Ray ray(incoming, -incoming); UniformSampler sampler; auto t = p->intersect(ray); assert(t.is()); Intersection isect(&s, 0, ray, t.get()); uint valid_samples = 0; for (auto i = 0u; i < num_samples; ++i) { scalar p; spectrum reflectance; Vec3 d = mat->sample_bsdf(isect, -ray.direction.normal(), sampler, p, reflectance); if (p == 0) continue; r += reflectance / p * d.z; ++valid_samples; } return (r / scalar(num_samples)).luminance(); } int main(int argc, char** args) { using namespace refraction_index; //compare_bsdf(OrenNayar(1.0, 0.3), 100000000); //auto mat = make_shared<MirrorMaterial>(); auto base_mat = make_shared<RoughColorMaterial>(0.0, spectrum(0.0)); auto mat = make_shared<MaterialTLDAdapter>(AIR, CROWN_GLASS, make_shared<GTR>(0.001)); vector<scalar> angles({0.0, 5.0, 10.0, 20.0, 30.0, 45.0, 60.0, 80.0, 85.0, 89.0}); for (auto deg: angles) { scalar angle = deg * PI / 180.0; auto incoming = Vec3(sin(angle), 0.0, cos(angle)).normal(); cerr << setw(4) << deg << ": " << compute_rho_hd(mat, incoming, 1000000) << " " << fresnel_reflectance_schlick(incoming, Vec3::z_axis, AIR, CROWN_GLASS) << endl; } // compare_tld(GTR(0.1), 10000000); return 0; } <|endoftext|>
<commit_before>#include "includes/peciman.h" #include <graphics.h> int CanMovePeciman(pacmanController peciman, int nextDirection) // Untuk mencek apakah ada tembok atau tidak, jika tidak maka akan return true { switch(nextDirection) { case RIGHT : return levelMap[peciman.pos.x+1][peciman.pos.y].Wall == REMPTY; case LEFT : return levelMap[peciman.pos.x-1][peciman.pos.y].Wall == REMPTY; case UP : return levelMap[peciman.pos.x][peciman.pos.y-1].Wall == REMPTY; case DOWN : return levelMap[peciman.pos.x][peciman.pos.y+1].Wall == REMPTY; } } void DrawPacman(pacmanController peciman) { int posX = peciman.pos.x * GRIDSIZE; //peciman.pos.x *= GRIDSIZE; int posY = peciman.pos.y * GRIDSIZE; switch (peciman.direction) { case UP: if (peciman.state == 1) // if open { readimagefile("assets/images/PacmanUpOpen.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE); } else // close { readimagefile("assets/images/PacmanUpClose.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE); } break; case DOWN: if (peciman.state == 1) // if open { readimagefile("assets/images/PacmanDownOpen.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE); } else // close { readimagefile("assets/images/PacmanDownClose.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE); } break; case RIGHT: if (peciman.state == 1) // if open { readimagefile("assets/images/PacmanRightOpen.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE); } else // close { readimagefile("assets/images/PacmanRightClose.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE); } break; case LEFT: if (peciman.state == 1) // if open { readimagefile("assets/images/PacmanLeftOpen.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE); } else// close { readimagefile("assets/images/PacmanLeftClose.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE); } break; } if (CanMovePeciman(peciman , peciman.nextDirection)) { peciman.direction = peciman.nextDirection; } } void InitPacman (pacmanController *peciman, int i, int j) // keadaan awal peciman { peciman->pos.x = i; peciman->pos.y = j; peciman->direction = RIGHT; peciman->nextDirection = RIGHT; peciman->state = 1; } void changeState(pacmanController *peciman) { if (peciman->state == 0) { peciman->state = 1; // change to open } else { peciman->state = 0; // change to close } } void BlackSquare(int posX, int posY) { setcolor(0); bar(posX * GRIDSIZE, posY* GRIDSIZE, (posX * GRIDSIZE) + GRIDSIZE, posY*GRIDSIZE + GRIDSIZE); } void Move(pacmanController *peciman) { setfillstyle(SOLID_FILL, 0); switch(peciman->direction) { case RIGHT : if (peciman->pos.x == 19){ BlackSquare(peciman->pos.x, peciman->pos.y); peciman->pos.x = 0; levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN; levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY; } else if(levelMap[peciman->pos.x+1][peciman->pos.y].Wall == 0){ // Cek apakah ada tembok atau tidak dan print ke array index selanjutnya BlackSquare(peciman->pos.x, peciman->pos.y); levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY; peciman->pos.x++; levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN; } break; case LEFT : if (peciman->pos.x == 0){ BlackSquare(peciman->pos.x, peciman->pos.y); peciman->pos.x = 19 ; levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN; levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY; } else if(levelMap[peciman->pos.x-1][peciman->pos.y].Wall == 0 ){ BlackSquare(peciman->pos.x, peciman->pos.y); levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY; peciman->pos.x--; levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN; } break; case UP : if (peciman->pos.y == 0){ BlackSquare(peciman->pos.x, peciman->pos.y); peciman->pos.x = 19; levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN; levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY; } else if(levelMap[peciman->pos.x][peciman->pos.y-1].Wall == 0){ BlackSquare(peciman->pos.x, peciman->pos.y); levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY; peciman->pos.y--; levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN; } break; case DOWN : if (peciman->pos.y == 19){ BlackSquare(peciman->pos.x, peciman->pos.y); peciman->pos.y = 0; levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN; levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY; } else if(levelMap[peciman->pos.x][peciman->pos.y+1].Wall == 0){ BlackSquare(peciman->pos.x, peciman->pos.y); levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY; peciman->pos.y++; levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN; } break; } DrawPacman(*peciman); // men-draw pacman sesuai dengan arah yang telah ditentukan } <commit_msg>Remove some useless code<commit_after>#include "includes/peciman.h" #include <graphics.h> int CanMovePeciman(pacmanController peciman, int nextDirection) // Untuk mencek apakah ada tembok atau tidak, jika tidak maka akan return true { switch(nextDirection) { case RIGHT : return levelMap[peciman.pos.x+1][peciman.pos.y].Wall == REMPTY; case LEFT : return levelMap[peciman.pos.x-1][peciman.pos.y].Wall == REMPTY; case UP : return levelMap[peciman.pos.x][peciman.pos.y-1].Wall == REMPTY; case DOWN : return levelMap[peciman.pos.x][peciman.pos.y+1].Wall == REMPTY; } } void DrawPacman(pacmanController peciman) { int posX = peciman.pos.x * GRIDSIZE; //peciman.pos.x *= GRIDSIZE; int posY = peciman.pos.y * GRIDSIZE; switch (peciman.direction) { case UP: if (peciman.state == 1) // if open { readimagefile("assets/images/PacmanUpOpen.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE); } else // close { readimagefile("assets/images/PacmanUpClose.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE); } break; case DOWN: if (peciman.state == 1) // if open { readimagefile("assets/images/PacmanDownOpen.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE); } else // close { readimagefile("assets/images/PacmanDownClose.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE); } break; case RIGHT: if (peciman.state == 1) // if open { readimagefile("assets/images/PacmanRightOpen.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE); } else // close { readimagefile("assets/images/PacmanRightClose.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE); } break; case LEFT: if (peciman.state == 1) // if open { readimagefile("assets/images/PacmanLeftOpen.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE); } else// close { readimagefile("assets/images/PacmanLeftClose.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE); } break; } if (CanMovePeciman(peciman , peciman.nextDirection)) { peciman.direction = peciman.nextDirection; } } void InitPacman (pacmanController *peciman, int i, int j) // keadaan awal peciman { peciman->pos.x = i; peciman->pos.y = j; peciman->direction = RIGHT; peciman->nextDirection = peciman->direction; peciman->state = 1; } void changeState(pacmanController *peciman) { if (peciman->state == 0) { peciman->state = 1; // change to open } else { peciman->state = 0; // change to close } } void BlackSquare(int posX, int posY) { setcolor(0); bar(posX * GRIDSIZE, posY* GRIDSIZE, (posX * GRIDSIZE) + GRIDSIZE, posY*GRIDSIZE + GRIDSIZE); } void Move(pacmanController *peciman) { setfillstyle(SOLID_FILL, 0); switch(peciman->direction) { case RIGHT : if (peciman->pos.x == 19){ BlackSquare(peciman->pos.x, peciman->pos.y); peciman->pos.x = 0; levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN; } else if(levelMap[peciman->pos.x+1][peciman->pos.y].Wall == 0){ // Cek apakah ada tembok atau tidak dan print ke array index selanjutnya BlackSquare(peciman->pos.x, peciman->pos.y); levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY; peciman->pos.x++; levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN; } break; case LEFT : if (peciman->pos.x == 0){ BlackSquare(peciman->pos.x, peciman->pos.y); peciman->pos.x = 19 ; levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN; } else if(levelMap[peciman->pos.x-1][peciman->pos.y].Wall == 0 ){ BlackSquare(peciman->pos.x, peciman->pos.y); levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY; peciman->pos.x--; levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN; } break; case UP : if (peciman->pos.y == 0){ BlackSquare(peciman->pos.x, peciman->pos.y); peciman->pos.x = 19; levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN; } else if(levelMap[peciman->pos.x][peciman->pos.y-1].Wall == 0){ BlackSquare(peciman->pos.x, peciman->pos.y); levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY; peciman->pos.y--; levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN; } break; case DOWN : if (peciman->pos.y == 19){ BlackSquare(peciman->pos.x, peciman->pos.y); peciman->pos.y = 0; levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN; } else if(levelMap[peciman->pos.x][peciman->pos.y+1].Wall == 0){ BlackSquare(peciman->pos.x, peciman->pos.y); levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY; peciman->pos.y++; levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN; } break; } DrawPacman(*peciman); // men-draw pacman sesuai dengan arah yang telah ditentukan } <|endoftext|>
<commit_before>#include "stdafx.h" #include "vao.h" bool gl::vao::use_vao = true; gl::vao::vao() { if (!use_vao) return; glGenVertexArrays(1, *this); } gl::vao::~vao() { if (!use_vao) return; glDeleteVertexArrays(1, *this); } void gl::vao::setup_attrib(gl::buffer &buffer, int attrib, int size, int type, int stride, int offset) { if (use_vao) { bind(); buffer.bind(buffer::ARRAY_BUFFER); glVertexAttribPointer(attrib, size, type, GL_FALSE, stride, reinterpret_cast<void*>(offset)); glEnableVertexAttribArray(attrib); } else { params.push_back({buffer, attrib, size, type, stride, offset}); active = nullptr; } } void gl::vao::setup_ebo(buffer &e) { if (use_vao) { bind(); e.bind(buffer::ELEMENT_ARRAY_BUFFER); } else { ebo = &e; active = nullptr; } } void gl::vao::bind() { if (active == this) return; active = this; if (use_vao) { glBindVertexArray(*this); } else { for (attrib_params &param : params) { param.buffer.bind(gl::buffer::ARRAY_BUFFER); glVertexAttribPointer(param.attrib, param.size, param.type, GL_FALSE, param.stride, reinterpret_cast<void*>(param.offset)); glEnableVertexAttribArray(param.attrib); } for (size_t i = params.size(); i < 4; i++) glDisableVertexAttribArray(i); if (ebo) ebo->bind(gl::buffer::ELEMENT_ARRAY_BUFFER); else gl::buffer::unbind(gl::buffer::ELEMENT_ARRAY_BUFFER); } } void gl::vao::unbind() { active = nullptr; } <commit_msg>really unbind vao<commit_after>#include "stdafx.h" #include "vao.h" bool gl::vao::use_vao = true; gl::vao::vao() { if (!use_vao) return; glGenVertexArrays(1, *this); } gl::vao::~vao() { if (!use_vao) return; unbind(); glDeleteVertexArrays(1, *this); } void gl::vao::setup_attrib(gl::buffer &buffer, int attrib, int size, int type, int stride, int offset) { if (use_vao) { bind(); buffer.bind(buffer::ARRAY_BUFFER); glVertexAttribPointer(attrib, size, type, GL_FALSE, stride, reinterpret_cast<void*>(offset)); glEnableVertexAttribArray(attrib); } else { params.push_back({buffer, attrib, size, type, stride, offset}); active = nullptr; } } void gl::vao::setup_ebo(buffer &e) { if (use_vao) { bind(); e.bind(buffer::ELEMENT_ARRAY_BUFFER); } else { ebo = &e; active = nullptr; } } void gl::vao::bind() { if (active == this) return; active = this; if (use_vao) { glBindVertexArray(*this); } else { for (attrib_params &param : params) { param.buffer.bind(gl::buffer::ARRAY_BUFFER); glVertexAttribPointer(param.attrib, param.size, param.type, GL_FALSE, param.stride, reinterpret_cast<void*>(param.offset)); glEnableVertexAttribArray(param.attrib); } for (size_t i = params.size(); i < 4; i++) glDisableVertexAttribArray(i); if (ebo) ebo->bind(gl::buffer::ELEMENT_ARRAY_BUFFER); else gl::buffer::unbind(gl::buffer::ELEMENT_ARRAY_BUFFER); } } void gl::vao::unbind() { active = nullptr; if (use_vao) { glBindVertexArray(0); } else { for (size_t i = 0; i < 4; i++) glDisableVertexAttribArray(i); } } <|endoftext|>
<commit_before>#include "uspeech.h" char signal::getPhoneme(){ sample(); if(power()>SILENCE){ int k = complexity(power()); overview[6] = overview[5]; overview[5] = overview[4]; overview[4] = overview[3]; overview[3] = overview[2]; overview[2] = overview[1]; overview[1] = overview[0]; overview[0] = k; int coeff = 0; char f = 0; while(f<6){ coeff += overview[f]; f++; } coeff /= 7; #if F_DETECTION > 0 micPower = 0.05 * maxPower() + (1 - 0.05) * micPower; if (micPower>37) { return 'f'; } #endif if(coeff<30 && coeff>20){ return 'u'; } else { if(coeff<33){ return 'e'; } else{ if(coeff<46){ return 'o'; } else{ if(coeff<60){ return 'v'; } else{ if(coeff<80){ return 'h'; } else{ if(coeff>80){ return 's'; } else{ return 'm'; } } } } } } } else{ return ' '; } } void signal::formantAnal(){ int i = 0; int k = 0; while(i<18){ if((long)(filters[i]-filters[i-1]) > 0 & (long)(filters[i]-filters[i+1]) < 0){ if(k < 3){ formants[k] = i; } } i++; } }<commit_msg>Added comments<commit_after>#include "uspeech.h" /** * The recognizer function */ char signal::getPhoneme(){ sample(); if(power()>SILENCE){ //Low pass filter for noise removal int k = complexity(power()); overview[6] = overview[5]; overview[5] = overview[4]; overview[4] = overview[3]; overview[3] = overview[2]; overview[2] = overview[1]; overview[1] = overview[0]; overview[0] = k; int coeff = 0; char f = 0; while(f<6){ coeff += overview[f]; f++; } coeff /= 7; //Serial.println(coeff); //Use this for debugging #if F_DETECTION > 0 micPower = 0.05 * maxPower() + (1 - 0.05) * micPower; //Serial.println(micPower)//If you are having trouble with fs if (micPower > 37/*Replace this value (37) with your own*/) { return 'f'; } #endif //Twiddle with the numbers here if your getting false triggers //This is the main recognizer part if(coeff<30 && coeff>20){ return 'u'; } else { if(coeff<33){ return 'e'; } else{ if(coeff<46){ return 'o'; } else{ if(coeff<60){ return 'v'; } else{ if(coeff<80){ return 'h'; } else{ if(coeff>80){ return 's'; } else{ return 'm'; } } } } } } } else{ return ' '; } } void signal::formantAnal(){ int i = 0; int k = 0; while(i<18){ if((long)(filters[i]-filters[i-1]) > 0 & (long)(filters[i]-filters[i+1]) < 0){ if(k < 3){ formants[k] = i; } } i++; } } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <vector> #include <stdexcept> #include <boost/compute.hpp> #include <algorithm> #include <QtGui> #include <QtOpenGL> #include <boost/compute/command_queue.hpp> #include <boost/compute/kernel.hpp> #include <boost/compute/program.hpp> #include <boost/compute/source.hpp> #include <boost/compute/system.hpp> #include <boost/compute/interop/opengl.hpp> using namespace std; namespace compute = boost::compute; int main (int argc, char* argv[]) { // get the default compute device compute::device gpu = compute::system::default_device(); // create a compute context and command queue compute::context ctx(gpu); compute::command_queue queue(ctx, gpu); //set some default values for when no commandline arguments are given //create accuracy variable int accuracy = 90; // create vector on device compute::vector<int> device_accuracy(1); // copy from host to device compute::copy(accuracy, accuracy, device_accuracy.begin()); //create polygons variable int polygons = 50; // create vector on device compute::vector<int> device_polygons(1); // copy from host to device compute::copy(host_data, host_data + 5, device_vector.begin()); //create vertices variable int vertices = 6; // create vector on device compute::vector<int> device_vertices(1); // copy from host to device compute::copy(host_data, host_data + 5, device_vector.begin()); //read input commandline arguments for (int i = 1; i < argc; ++i) { if (std::string(argv[i]) == "-a") { //initialise desired accuracy variable according to commandline argument -a accuracy = ; // copy from host to device compute::copy(accuracy, accuracy, device_accuracy.begin()); } if (std::string(argv[i]) == "-p") { //initialise maximum polygons variable according to commandline argument -p polygons = ; // copy from host to device compute::copy(accuracy, accuracy, device_accuracy.begin()); } if (std::string(argv[i]) == "-v") { //initialise maximum verices per polygon variable according to commandline argument -v vertices = ; // copy from host to device compute::copy(accuracy, accuracy, device_accuracy.begin()); } } //create leaderDNA variable // generate random dna vector on the host std::vector<float> leaderDNA(1000000); std::generate(leaderDNA.begin(), leaderDNA.end(), rand); // create vector on the device compute::vector<float> device_leaderDNA(1000000, ctx); // copy data to the device compute::copy( leaderDNA.begin(), leaderDNA.end(), device_leaderDNA.begin(), queue ); //create mutatedDNA variable // create data array on host int host_data[] = { 1, 3, 5, 7, 9 }; // create vector on device compute::vector<int> device_vector(5); // copy from host to device compute::copy(host_data, host_data + 5, device_vector.begin()); //create leaderDNArender variable // create data array on host int host_data[] = { 1, 3, 5, 7, 9 }; // create vector on device compute::vector<int> device_vector(5); // copy from host to device compute::copy(host_data, host_data + 5, device_vector.begin()); //create mutatedDNArender variable // create data array on host int host_data[] = { 1, 3, 5, 7, 9 }; // create vector on device compute::vector<int> device_vector(5); // copy from host to device compute::copy(host_data, host_data + 5, device_vector.begin()); //create original image variable + load image into gpu memory if (std::string(argv[i]) == "") { //load file according to commandline argument into gpu vector //get x(max), y(max). (image dimensions) //make image vector on device compute::vector<float> originalimage(ctx, n); // copy data to the device compute::copy( host_vector.begin(), host_vector.end(), device_vector.begin(), queue ); } //run render loop until desired accuracy is reached while (leaderaccuracy<accuracy) { //render leader DNA to a raster image in opengl texture boost::compute::function<int (int)> renderDNA = boost::compute::make_function_from_source<int (int)>( "renderDNA", "int renderDNA(int x) { //for each shape in dna { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, gl_texture_); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(0, 0); glTexCoord2f(0, 1); glVertex2f(0, h); glTexCoord2f(1, 1); glVertex2f(w, h); glTexCoord2f(1, 0); glVertex2f(w, 0); glEnd(); } }" ); //compute fitness of leader dna image //compute what % match DNAimage is to original image boost::compute::function<int (int)> computefitnesspercent = boost::compute::make_function_from_source<int (int)>( "computefitnesspercent", "int computefitnesspercent(int x) { }" ); while () { //mutate from the leaderDNA boost::compute::function<int (int)> mutateDNA = boost::compute::make_function_from_source<int (int)>( "mutateDNA", "int mutateDNA(int DNA) { //mutate input DNA randomly mutated_shape = RANDINT(NUM_SHAPES); double roulette = RANDDOUBLE(3); //mutate color //randomly change mutated_shape colour //change red //up //down //change green //up //down //change blue //up //down //change alpha //up //down //mutate shape //randomly move one vertex in mutated_shape //randomly pick vertex //move up //move down //move left //move right //mutate stacking //randomly move one shape up or down stack //randomly select shape //move shape up stack //move shape down stack //100% mutation (create new random dna) ); //render mutated DNA to a raster image in opengl texture boost::compute::function<int (int)> renderDNA = boost::compute::make_function_from_source<int (int)>( "renderDNA", "int renderDNA(int x) { //for each shape in dna { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, gl_texture_); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(0, 0); glTexCoord2f(0, 1); glVertex2f(0, h); glTexCoord2f(1, 1); glVertex2f(w, h); glTexCoord2f(1, 0); glVertex2f(w, 0); glEnd(); } }" ); //compute what % match mutated dna image is to original image boost::compute::function<int (int)> computefitnesspercent = boost::compute::make_function_from_source<int (int)>( "computefitnesspercent", "int computefitnesspercent(int x) { //get x, y size of images to be compared //for each x,y value //give % match between leaderDNAimage(x,y) and mutatedDNAimage(x,y) //calculate average % value and store to mutatedDNAfitness }" ); //check if mutated dna image is fitter, if so overwrite leaderDNA if (mutatedDNAfitness > leaderDNAfitness) { //overwrite leaderDNA leaderDNA = mutatedDNA; //save dna to disk as filename.dna pFile = fopen ("%filename.dna","w"); fprintf (pFile, DNA); fclose (pFile); } //perform final render, output svg and raster image //render final DNA to a raster image in opengl texture boost::compute::function<int (int)> renderDNA = boost::compute::make_function_from_source<int (int)>( "renderDNA", "int renderDNA(int x) { //for each shape in dna { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, gl_texture_); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(0, 0); glTexCoord2f(0, 1); glVertex2f(0, h); glTexCoord2f(1, 1); glVertex2f(w, h); glTexCoord2f(1, 0); glVertex2f(w, 0); glEnd(); } }" ); //copy raster image from gpu to main memory //save raster image to disk as filename.render.png pFile = fopen ("%filename.render.png","w"); fprintf (pFile, leaderDNAimage); fclose (pFile); //render mutated DNA to a vector image boost::compute::function<int (int)> renderDNA = boost::compute::make_function_from_source<int (int)>( "renderDNAvector", "int renderDNAvector(DNA) { //initialise svg string //for each shape in dna { //add shape to svg } }" //close svg string ); //copy vector image from gpu to main memory //save vector image to disk as filename.render.svg pFile = fopen ("%filename.render.svg","w"); fprintf (pFile, leaderDNAvector); fclose (pFile); }<commit_msg>commandline argument handling<commit_after>#include <iostream> #include <string> #include <vector> #include <stdexcept> #include <boost/compute.hpp> #include <algorithm> #include <QtGui> #include <QtOpenGL> #include <boost/compute/command_queue.hpp> #include <boost/compute/kernel.hpp> #include <boost/compute/program.hpp> #include <boost/compute/source.hpp> #include <boost/compute/system.hpp> #include <boost/compute/interop/opengl.hpp> using namespace std; namespace compute = boost::compute; int main (int argc, char* argv[]) { // get the default compute device compute::device gpu = compute::system::default_device(); // create a compute context and command queue compute::context ctx(gpu); compute::command_queue queue(ctx, gpu); //set some default values for when no commandline arguments are given //create accuracy variable int accuracy = 90; // create vector on device compute::vector<int> device_accuracy(1); // copy from host to device compute::copy(accuracy, accuracy, device_accuracy.begin()); //create polygons variable int polygons = 50; // create vector on device compute::vector<int> device_polygons(1); // copy from host to device compute::copy(host_data, host_data + 5, device_vector.begin()); //create vertices variable int vertices = 6; // create vector on device compute::vector<int> device_vertices(1); // copy from host to device compute::copy(host_data, host_data + 5, device_vector.begin()); //read input commandline arguments for (int i = 1; i < argc; ++i) { if (std::string(argv[i]) == "-a") { //initialise desired accuracy variable according to commandline argument -a accuracy = argv[i + 1]; // copy from host to device compute::copy(accuracy, accuracy, device_accuracy.begin()); } if (std::string(argv[i]) == "-p") { //initialise maximum polygons variable according to commandline argument -p polygons = argv[i + 1]; // copy from host to device compute::copy(accuracy, accuracy, device_accuracy.begin()); } if (std::string(argv[i]) == "-v") { //initialise maximum verices per polygon variable according to commandline argument -v vertices = argv[i + 1]; // copy from host to device compute::copy(accuracy, accuracy, device_accuracy.begin()); } } //create leaderDNA variable // generate random dna vector on the host std::vector<int> leaderDNA(1000000); std::generate(leaderDNA.begin(), leaderDNA.end(), rand); // create vector on the device compute::vector<int> device_leaderDNA(1000000, ctx); // copy data to the device compute::copy( leaderDNA.begin(), leaderDNA.end(), device_leaderDNA.begin(), queue ); //create mutatedDNA variable // create data array on host int host_data[] = { 1, 3, 5, 7, 9 }; // create vector on device compute::vector<int> device_vector(5); // copy from host to device compute::copy(host_data, host_data + 5, device_vector.begin()); //create leaderDNArender variable // create data array on host int host_data[] = { 1, 3, 5, 7, 9 }; // create vector on device compute::vector<int> device_vector(5); // copy from host to device compute::copy(host_data, host_data + 5, device_vector.begin()); //create mutatedDNArender variable // create data array on host int host_data[] = { 1, 3, 5, 7, 9 }; // create vector on device compute::vector<int> device_vector(5); // copy from host to device compute::copy(host_data, host_data + 5, device_vector.begin()); //create original image variable + load image into gpu memory if (std::string(argv[i]) == "") { //load file according to commandline argument into gpu vector //get x(max), y(max). (image dimensions) //make image vector on device compute::vector<int> originalimage(ctx, n); // copy data to the device compute::copy( host_vector.begin(), host_vector.end(), device_vector.begin(), queue ); } //run render loop until desired accuracy is reached while (leaderaccuracy<accuracy) { //render leader DNA to a raster image in opengl texture boost::compute::function<int (int)> renderDNA = boost::compute::make_function_from_source<int (int)>( "renderDNA", "int renderDNA(int x) { //for each shape in dna { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, gl_texture_); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(0, 0); glTexCoord2f(0, 1); glVertex2f(0, h); glTexCoord2f(1, 1); glVertex2f(w, h); glTexCoord2f(1, 0); glVertex2f(w, 0); glEnd(); } }" ); //compute fitness of leader dna image //compute what % match DNAimage is to original image boost::compute::function<int (int)> computefitnesspercent = boost::compute::make_function_from_source<int (int)>( "computefitnesspercent", "int computefitnesspercent(int x) { }" ); while () { //mutate from the leaderDNA boost::compute::function<int (int)> mutateDNA = boost::compute::make_function_from_source<int (int)>( "mutateDNA", "int mutateDNA(int DNA) { //mutate input DNA randomly mutated_shape = RANDINT(NUM_SHAPES); double roulette = RANDDOUBLE(3); //mutate color //randomly change mutated_shape colour //change red //up //down //change green //up //down //change blue //up //down //change alpha //up //down //mutate shape //randomly move one vertex in mutated_shape //randomly pick vertex //move up //move down //move left //move right //mutate stacking //randomly move one shape up or down stack //randomly select shape //move shape up stack //move shape down stack //100% mutation (create new random dna) ); //render mutated DNA to a raster image in opengl texture boost::compute::function<int (int)> renderDNA = boost::compute::make_function_from_source<int (int)>( "renderDNA", "int renderDNA(int x) { //for each shape in dna { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, gl_texture_); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(0, 0); glTexCoord2f(0, 1); glVertex2f(0, h); glTexCoord2f(1, 1); glVertex2f(w, h); glTexCoord2f(1, 0); glVertex2f(w, 0); glEnd(); } }" ); //compute what % match mutated dna image is to original image boost::compute::function<int (int)> computefitnesspercent = boost::compute::make_function_from_source<int (int)>( "computefitnesspercent", "int computefitnesspercent(int x) { //get x, y size of images to be compared //for each x,y value //give % match between leaderDNAimage(x,y) and mutatedDNAimage(x,y) //calculate average % value and store to mutatedDNAfitness }" ); //check if mutated dna image is fitter, if so overwrite leaderDNA if (mutatedDNAfitness > leaderDNAfitness) { //overwrite leaderDNA leaderDNA = mutatedDNA; //save dna to disk as filename.dna pFile = fopen ("%filename.dna","w"); fprintf (pFile, DNA); fclose (pFile); } //perform final render, output svg and raster image //render final DNA to a raster image in opengl texture boost::compute::function<int (int)> renderDNA = boost::compute::make_function_from_source<int (int)>( "renderDNA", "int renderDNA(int x) { //for each shape in dna { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, gl_texture_); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(0, 0); glTexCoord2f(0, 1); glVertex2f(0, h); glTexCoord2f(1, 1); glVertex2f(w, h); glTexCoord2f(1, 0); glVertex2f(w, 0); glEnd(); } }" ); //copy raster image from gpu to main memory //save raster image to disk as filename.render.png pFile = fopen ("%filename.render.png","w"); fprintf (pFile, leaderDNAimage); fclose (pFile); //render mutated DNA to a vector image boost::compute::function<int (int)> renderDNA = boost::compute::make_function_from_source<int (int)>( "renderDNAvector", "int renderDNAvector(DNA) { //initialise svg string //for each shape in dna { //add shape to svg } }" //close svg string ); //copy vector image from gpu to main memory //save vector image to disk as filename.render.svg pFile = fopen ("%filename.render.svg","w"); fprintf (pFile, leaderDNAvector); fclose (pFile); }<|endoftext|>
<commit_before>#ifndef SILICIUM_TO_UNIQUE_HPP #define SILICIUM_TO_UNIQUE_HPP #include <memory> namespace Si { template <class T> auto to_unique(T &&t) -> std::unique_ptr<typename std::decay<T>::type> { typedef typename std::decay<T>::type decayed_T; return std::unique_ptr<decayed_T>(new decayed_T(std::forward<T>(t))); } } namespace Si { using Si::to_unique; } #endif <commit_msg>remove redundant using declaration<commit_after>#ifndef SILICIUM_TO_UNIQUE_HPP #define SILICIUM_TO_UNIQUE_HPP #include <memory> namespace Si { template <class T> auto to_unique(T &&t) -> std::unique_ptr<typename std::decay<T>::type> { typedef typename std::decay<T>::type decayed_T; return std::unique_ptr<decayed_T>(new decayed_T(std::forward<T>(t))); } } #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef DATABASE_HH_ #define DATABASE_HH_ #include "dht/i_partitioner.hh" #include "config/ks_meta_data.hh" #include "locator/abstract_replication_strategy.hh" #include "core/sstring.hh" #include "core/shared_ptr.hh" #include "net/byteorder.hh" #include "utils/UUID.hh" #include "utils/hash.hh" #include "db_clock.hh" #include "gc_clock.hh" #include <functional> #include <cstdint> #include <unordered_map> #include <map> #include <set> #include <iostream> #include <boost/functional/hash.hpp> #include <experimental/optional> #include <string.h> #include "types.hh" #include "compound.hh" #include "core/future.hh" #include "cql3/column_specification.hh" #include <limits> #include <cstddef> #include "schema.hh" #include "timestamp.hh" #include "tombstone.hh" #include "atomic_cell.hh" #include "query-request.hh" #include "query-result.hh" #include "keys.hh" #include "mutation.hh" class frozen_mutation; namespace sstables { class sstable; } namespace db { template<typename T> class serializer; class commitlog; class config; } class memtable { public: using partitions_type = std::map<dht::decorated_key, mutation_partition, dht::decorated_key::less_comparator>; private: schema_ptr _schema; partitions_type partitions; public: using const_mutation_partition_ptr = std::unique_ptr<const mutation_partition>; public: explicit memtable(schema_ptr schema); schema_ptr schema() const { return _schema; } mutation_partition& find_or_create_partition(const dht::decorated_key& key); mutation_partition& find_or_create_partition_slow(partition_key_view key); row& find_or_create_row_slow(const partition_key& partition_key, const clustering_key& clustering_key); const_mutation_partition_ptr find_partition(const dht::decorated_key& key) const; void apply(const mutation& m); void apply(const frozen_mutation& m); const partitions_type& all_partitions() const; }; class column_family { public: struct config { sstring datadir; bool enable_disk_writes = true; bool enable_disk_reads = true; }; private: schema_ptr _schema; config _config; std::vector<memtable> _memtables; // generation -> sstable. Ordered by key so we can easily get the most recent. std::map<unsigned long, std::unique_ptr<sstables::sstable>> _sstables; unsigned _sstable_generation = 1; private: memtable& active_memtable() { return _memtables.back(); } struct merge_comparator; public: // Queries can be satisfied from multiple data sources, so they are returned // as temporaries. // // FIXME: in case a query is satisfied from a single memtable, avoid a copy using const_mutation_partition_ptr = std::unique_ptr<const mutation_partition>; using const_row_ptr = std::unique_ptr<const row>; public: column_family(schema_ptr schema, config cfg); column_family(column_family&&) = default; ~column_family(); schema_ptr schema() const { return _schema; } const_mutation_partition_ptr find_partition(const dht::decorated_key& key) const; const_mutation_partition_ptr find_partition_slow(const partition_key& key) const; const_row_ptr find_row(const dht::decorated_key& partition_key, const clustering_key& clustering_key) const; void apply(const frozen_mutation& m); void apply(const mutation& m); // Returns at most "cmd.limit" rows future<lw_shared_ptr<query::result>> query(const query::read_command& cmd) const; future<> populate(sstring datadir); void seal_active_memtable(); const std::vector<memtable>& testonly_all_memtables() const; private: // Iterate over all partitions. Protocol is the same as std::all_of(), // so that iteration can be stopped by returning false. // Func signature: bool (const decorated_key& dk, const mutation_partition& mp) template <typename Func> bool for_all_partitions(Func&& func) const; future<> probe_file(sstring sstdir, sstring fname); public: // Iterate over all partitions. Protocol is the same as std::all_of(), // so that iteration can be stopped by returning false. bool for_all_partitions_slow(std::function<bool (const dht::decorated_key&, const mutation_partition&)> func) const; friend std::ostream& operator<<(std::ostream& out, const column_family& cf); }; class user_types_metadata { std::unordered_map<bytes, user_type> _user_types; public: user_type get_type(bytes name) const { return _user_types.at(name); } const std::unordered_map<bytes, user_type>& get_all_types() const { return _user_types; } void add_type(user_type type) { auto i = _user_types.find(type->_name); assert(i == _user_types.end() || type->is_compatible_with(*i->second)); _user_types[type->_name] = std::move(type); } void remove_type(user_type type) { _user_types.erase(type->_name); } }; class keyspace { public: struct config { sstring datadir; bool enable_disk_reads = true; bool enable_disk_writes = true; }; private: std::unique_ptr<locator::abstract_replication_strategy> _replication_strategy; config _config; public: explicit keyspace(config cfg) : _config(std::move(cfg)) {} user_types_metadata _user_types; void create_replication_strategy(::config::ks_meta_data& ksm); locator::abstract_replication_strategy& get_replication_strategy(); column_family::config make_column_family_config(const schema& s) const; private: sstring column_family_directory(const sstring& name, utils::UUID uuid) const; }; class no_such_keyspace : public std::runtime_error { public: using runtime_error::runtime_error; }; class no_such_column_family : public std::runtime_error { public: using runtime_error::runtime_error; }; // Policy for distributed<database>: // broadcast metadata writes // local metadata reads // use shard_of() for data class database { std::unordered_map<sstring, keyspace> _keyspaces; std::unordered_map<utils::UUID, column_family> _column_families; std::unordered_map<std::pair<sstring, sstring>, utils::UUID, utils::tuple_hash> _ks_cf_to_uuid; std::unique_ptr<db::commitlog> _commitlog; std::unique_ptr<db::config> _cfg; future<> init_commitlog(); future<> apply_in_memory(const frozen_mutation&); future<> populate(sstring datadir); public: database(); database(const db::config&); database(database&&) = default; ~database(); db::commitlog* commitlog() const { return _commitlog.get(); } future<> init_from_data_directory(); keyspace& add_keyspace(sstring name, keyspace k); /** Adds cf with auto-generated UUID. */ void add_column_family(column_family&&); void add_column_family(const utils::UUID&, column_family&&); /* throws std::out_of_range if missing */ const utils::UUID& find_uuid(const sstring& ks, const sstring& cf) const throw (std::out_of_range); const utils::UUID& find_uuid(const schema_ptr&) const throw (std::out_of_range); /* below, find* throws no_such_<type> on fail */ keyspace& find_or_create_keyspace(const sstring& name); keyspace& find_keyspace(const sstring& name) throw (no_such_keyspace); const keyspace& find_keyspace(const sstring& name) const throw (no_such_keyspace); bool has_keyspace(const sstring& name) const; void update_keyspace(const sstring& name); void drop_keyspace(const sstring& name); column_family& find_column_family(const sstring& ks, const sstring& name) throw (no_such_column_family); const column_family& find_column_family(const sstring& ks, const sstring& name) const throw (no_such_column_family); column_family& find_column_family(const utils::UUID&) throw (no_such_column_family); const column_family& find_column_family(const utils::UUID&) const throw (no_such_column_family); column_family& find_column_family(const schema_ptr&) throw (no_such_column_family); const column_family& find_column_family(const schema_ptr&) const throw (no_such_column_family); schema_ptr find_schema(const sstring& ks_name, const sstring& cf_name) const throw (no_such_column_family); schema_ptr find_schema(const utils::UUID&) const throw (no_such_column_family); future<> stop(); unsigned shard_of(const dht::token& t); unsigned shard_of(const mutation& m); unsigned shard_of(const frozen_mutation& m); future<lw_shared_ptr<query::result>> query(const query::read_command& cmd); future<> apply(const frozen_mutation&); keyspace::config make_keyspace_config(sstring name) const; friend std::ostream& operator<<(std::ostream& out, const database& db); }; // FIXME: stub class secondary_index_manager {}; inline void column_family::apply(const mutation& m) { return active_memtable().apply(m); } inline void column_family::apply(const frozen_mutation& m) { return active_memtable().apply(m); } #endif /* DATABASE_HH_ */ <commit_msg>db: add simple memtable sealing policy<commit_after>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef DATABASE_HH_ #define DATABASE_HH_ #include "dht/i_partitioner.hh" #include "config/ks_meta_data.hh" #include "locator/abstract_replication_strategy.hh" #include "core/sstring.hh" #include "core/shared_ptr.hh" #include "net/byteorder.hh" #include "utils/UUID.hh" #include "utils/hash.hh" #include "db_clock.hh" #include "gc_clock.hh" #include <functional> #include <cstdint> #include <unordered_map> #include <map> #include <set> #include <iostream> #include <boost/functional/hash.hpp> #include <experimental/optional> #include <string.h> #include "types.hh" #include "compound.hh" #include "core/future.hh" #include "cql3/column_specification.hh" #include <limits> #include <cstddef> #include "schema.hh" #include "timestamp.hh" #include "tombstone.hh" #include "atomic_cell.hh" #include "query-request.hh" #include "query-result.hh" #include "keys.hh" #include "mutation.hh" class frozen_mutation; namespace sstables { class sstable; } namespace db { template<typename T> class serializer; class commitlog; class config; } class memtable { public: using partitions_type = std::map<dht::decorated_key, mutation_partition, dht::decorated_key::less_comparator>; private: schema_ptr _schema; partitions_type partitions; public: using const_mutation_partition_ptr = std::unique_ptr<const mutation_partition>; public: explicit memtable(schema_ptr schema); schema_ptr schema() const { return _schema; } mutation_partition& find_or_create_partition(const dht::decorated_key& key); mutation_partition& find_or_create_partition_slow(partition_key_view key); row& find_or_create_row_slow(const partition_key& partition_key, const clustering_key& clustering_key); const_mutation_partition_ptr find_partition(const dht::decorated_key& key) const; void apply(const mutation& m); void apply(const frozen_mutation& m); const partitions_type& all_partitions() const; }; class column_family { public: struct config { sstring datadir; bool enable_disk_writes = true; bool enable_disk_reads = true; }; private: schema_ptr _schema; config _config; std::vector<memtable> _memtables; // generation -> sstable. Ordered by key so we can easily get the most recent. std::map<unsigned long, std::unique_ptr<sstables::sstable>> _sstables; unsigned _sstable_generation = 1; unsigned _mutation_count = 0; private: memtable& active_memtable() { return _memtables.back(); } struct merge_comparator; public: // Queries can be satisfied from multiple data sources, so they are returned // as temporaries. // // FIXME: in case a query is satisfied from a single memtable, avoid a copy using const_mutation_partition_ptr = std::unique_ptr<const mutation_partition>; using const_row_ptr = std::unique_ptr<const row>; public: column_family(schema_ptr schema, config cfg); column_family(column_family&&) = default; ~column_family(); schema_ptr schema() const { return _schema; } const_mutation_partition_ptr find_partition(const dht::decorated_key& key) const; const_mutation_partition_ptr find_partition_slow(const partition_key& key) const; const_row_ptr find_row(const dht::decorated_key& partition_key, const clustering_key& clustering_key) const; void apply(const frozen_mutation& m); void apply(const mutation& m); // Returns at most "cmd.limit" rows future<lw_shared_ptr<query::result>> query(const query::read_command& cmd) const; future<> populate(sstring datadir); void seal_active_memtable(); const std::vector<memtable>& testonly_all_memtables() const; private: // Iterate over all partitions. Protocol is the same as std::all_of(), // so that iteration can be stopped by returning false. // Func signature: bool (const decorated_key& dk, const mutation_partition& mp) template <typename Func> bool for_all_partitions(Func&& func) const; future<> probe_file(sstring sstdir, sstring fname); void seal_on_overflow(); public: // Iterate over all partitions. Protocol is the same as std::all_of(), // so that iteration can be stopped by returning false. bool for_all_partitions_slow(std::function<bool (const dht::decorated_key&, const mutation_partition&)> func) const; friend std::ostream& operator<<(std::ostream& out, const column_family& cf); }; class user_types_metadata { std::unordered_map<bytes, user_type> _user_types; public: user_type get_type(bytes name) const { return _user_types.at(name); } const std::unordered_map<bytes, user_type>& get_all_types() const { return _user_types; } void add_type(user_type type) { auto i = _user_types.find(type->_name); assert(i == _user_types.end() || type->is_compatible_with(*i->second)); _user_types[type->_name] = std::move(type); } void remove_type(user_type type) { _user_types.erase(type->_name); } }; class keyspace { public: struct config { sstring datadir; bool enable_disk_reads = true; bool enable_disk_writes = true; }; private: std::unique_ptr<locator::abstract_replication_strategy> _replication_strategy; config _config; public: explicit keyspace(config cfg) : _config(std::move(cfg)) {} user_types_metadata _user_types; void create_replication_strategy(::config::ks_meta_data& ksm); locator::abstract_replication_strategy& get_replication_strategy(); column_family::config make_column_family_config(const schema& s) const; private: sstring column_family_directory(const sstring& name, utils::UUID uuid) const; }; class no_such_keyspace : public std::runtime_error { public: using runtime_error::runtime_error; }; class no_such_column_family : public std::runtime_error { public: using runtime_error::runtime_error; }; // Policy for distributed<database>: // broadcast metadata writes // local metadata reads // use shard_of() for data class database { std::unordered_map<sstring, keyspace> _keyspaces; std::unordered_map<utils::UUID, column_family> _column_families; std::unordered_map<std::pair<sstring, sstring>, utils::UUID, utils::tuple_hash> _ks_cf_to_uuid; std::unique_ptr<db::commitlog> _commitlog; std::unique_ptr<db::config> _cfg; future<> init_commitlog(); future<> apply_in_memory(const frozen_mutation&); future<> populate(sstring datadir); public: database(); database(const db::config&); database(database&&) = default; ~database(); db::commitlog* commitlog() const { return _commitlog.get(); } future<> init_from_data_directory(); keyspace& add_keyspace(sstring name, keyspace k); /** Adds cf with auto-generated UUID. */ void add_column_family(column_family&&); void add_column_family(const utils::UUID&, column_family&&); /* throws std::out_of_range if missing */ const utils::UUID& find_uuid(const sstring& ks, const sstring& cf) const throw (std::out_of_range); const utils::UUID& find_uuid(const schema_ptr&) const throw (std::out_of_range); /* below, find* throws no_such_<type> on fail */ keyspace& find_or_create_keyspace(const sstring& name); keyspace& find_keyspace(const sstring& name) throw (no_such_keyspace); const keyspace& find_keyspace(const sstring& name) const throw (no_such_keyspace); bool has_keyspace(const sstring& name) const; void update_keyspace(const sstring& name); void drop_keyspace(const sstring& name); column_family& find_column_family(const sstring& ks, const sstring& name) throw (no_such_column_family); const column_family& find_column_family(const sstring& ks, const sstring& name) const throw (no_such_column_family); column_family& find_column_family(const utils::UUID&) throw (no_such_column_family); const column_family& find_column_family(const utils::UUID&) const throw (no_such_column_family); column_family& find_column_family(const schema_ptr&) throw (no_such_column_family); const column_family& find_column_family(const schema_ptr&) const throw (no_such_column_family); schema_ptr find_schema(const sstring& ks_name, const sstring& cf_name) const throw (no_such_column_family); schema_ptr find_schema(const utils::UUID&) const throw (no_such_column_family); future<> stop(); unsigned shard_of(const dht::token& t); unsigned shard_of(const mutation& m); unsigned shard_of(const frozen_mutation& m); future<lw_shared_ptr<query::result>> query(const query::read_command& cmd); future<> apply(const frozen_mutation&); keyspace::config make_keyspace_config(sstring name) const; friend std::ostream& operator<<(std::ostream& out, const database& db); }; // FIXME: stub class secondary_index_manager {}; inline void column_family::apply(const mutation& m) { active_memtable().apply(m); seal_on_overflow(); } inline void column_family::seal_on_overflow() { // FIXME: something better if (++_mutation_count == 10000) { _mutation_count = 0; seal_active_memtable(); } } inline void column_family::apply(const frozen_mutation& m) { active_memtable().apply(m); seal_on_overflow(); } #endif /* DATABASE_HH_ */ <|endoftext|>
<commit_before>/*! * VerbalExpressions C++ Library v0.1 * https://github.com/whackashoe/C++VerbalExpressions * * The MIT License (MIT) * * Copyright (c) 2013 whackashoe * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERBAL_EXPRESSIONS_H_ #define VERBAL_EXPRESSIONS_H_ #define USE_BOOST #ifdef USE_BOOST #include <boost/regex.hpp> namespace veregex = boost; #else #include <regex> namespace veregex = std; #endif #include <iostream> #include <string> #include <vector> #include <algorithm> class VerEx { private: std::string prefixes; std::string source; std::string suffixes; std::string pattern; enum Flags { GLOBAL = 1, MULTILINE = 2, CASEINSENSITIVE = 4 }; friend std::ostream& operator<<(std::ostream &strm, VerEx &v) { return strm << v.pattern; } unsigned int checkFlags() { unsigned int result = 0; if(modifiers & CASEINSENSITIVE) result |= veregex::regex::icase; return result; } const std::string reduceLines(const std::string & value) { std::string ret = value; std::size_t pos = ret.find("\n"); if(pos == std::string::npos) return ret; return ret.substr(0, pos); } public: unsigned int modifiers; VerEx() : prefixes(""), source(""), suffixes(""), pattern(""), modifiers(0){}; VerEx& operator=(const VerEx& ve) = default; ~VerEx() = default; VerEx & add(const std::string & value) { source = source + value; pattern = prefixes + source + suffixes; return (*this); } VerEx & startOfLine(bool enable) { prefixes = enable ? "^" : ""; return add(""); } inline VerEx & startOfLine() { return startOfLine(true); } VerEx & endOfLine(bool enable) { suffixes = enable ? "$" : ""; return add(""); } inline VerEx & endOfLine() { return endOfLine(true); } VerEx & then(const std::string & value) { return add("(?:" + value + ")"); } VerEx & find(const std::string & value) { return then(value); } VerEx & maybe(const std::string & value) { return add("(?:" + value + ")?"); } VerEx & anything() { return add("(?:.*)"); } VerEx & anythingBut(const std::string & value) { return add("(?:[^" + value + "]*)"); } VerEx & something() { return add("(?:.+)"); } VerEx & somethingBut(const std::string & value) { return add("(?:[^" + value + "]+)"); } const std::string replace(const std::string & source, const std::string & value) { return veregex::regex_replace( source, veregex::regex(pattern, checkFlags()), value); } VerEx & lineBreak() { return add("(?:(?:\\n)|(?:\\r\\n))"); } inline VerEx & br() { return lineBreak(); } VerEx & tab() { return add("\\t"); } VerEx & word() { return add("\\w+"); } VerEx & anyOf(const std::string & value) { return add( "[" + value + "]" ); } VerEx & any(const std::string & value) { return anyOf(value); } VerEx & range(std::vector<std::string> args) { std::stringstream value; value << "["; for(unsigned int _from = 0; _from < args.size(); _from += 2) { unsigned int _to = _from+1; if (args.size() <= _to) break; int from = atoi(args[_from].c_str()); int to = atoi(args[_to].c_str()); value << from << "-" << to; } value << "]"; return add(value.str()); } VerEx & addModifier(char modifier) { switch (modifier) { case 'i': modifiers |= CASEINSENSITIVE; break; case 'm': modifiers |= MULTILINE; break; case 'g': modifiers |= GLOBAL; break; default: break; } return (*this); } VerEx & removeModifier(char modifier) { switch (modifier) { case 'i': modifiers ^= CASEINSENSITIVE; break; case 'm': modifiers ^= MULTILINE; break; case 'g': modifiers ^= GLOBAL; break; default: break; } return (*this); } VerEx & withAnyCase(bool enable) { if (enable) addModifier( 'i' ); else removeModifier( 'i' ); return (*this); } inline VerEx & withAnyCase() { return withAnyCase(true); } VerEx & searchOneLine(bool enable) { if (enable) removeModifier( 'm' ); else addModifier( 'm' ); return (*this); } inline VerEx & searchOneLine() { return searchOneLine(true); } VerEx & searchGlobal(bool enable) { if (enable) addModifier( 'g' ); else removeModifier( 'g' ); return (*this); } inline VerEx & searchGlobal() { return searchGlobal(true); } VerEx & multiple(const std::string & value) { if(value.at(0) != '*' && value.at(0) != '+') add("+"); return add(value); } VerEx & alt(const std::string & value) { if (prefixes.find("(") == std::string::npos) prefixes += "("; if (suffixes.find(")") == std::string::npos) suffixes = ")" + suffixes; add( ")|(" ); return then(value); } bool test(const std::string & value) { std::string toTest; if(modifiers & MULTILINE) toTest = value; else toTest = reduceLines(value); if(modifiers & GLOBAL) return veregex::regex_search(toTest, boost::regex(pattern, checkFlags())); else return veregex::regex_match(toTest, boost::regex(pattern, checkFlags())); } }; #endif <commit_msg>change inner boost to alias<commit_after>/*! * VerbalExpressions C++ Library v0.1 * https://github.com/whackashoe/C++VerbalExpressions * * The MIT License (MIT) * * Copyright (c) 2013 whackashoe * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERBAL_EXPRESSIONS_H_ #define VERBAL_EXPRESSIONS_H_ #define USE_BOOST #ifdef USE_BOOST #include <boost/regex.hpp> namespace veregex = boost; #else #include <regex> namespace veregex = std; #endif #include <iostream> #include <string> #include <vector> #include <algorithm> class VerEx { private: std::string prefixes; std::string source; std::string suffixes; std::string pattern; enum Flags { GLOBAL = 1, MULTILINE = 2, CASEINSENSITIVE = 4 }; friend std::ostream& operator<<(std::ostream &strm, VerEx &v) { return strm << v.pattern; } unsigned int checkFlags() { unsigned int result = 0; if(modifiers & CASEINSENSITIVE) result |= veregex::regex::icase; return result; } const std::string reduceLines(const std::string & value) { std::string ret = value; std::size_t pos = ret.find("\n"); if(pos == std::string::npos) return ret; return ret.substr(0, pos); } public: unsigned int modifiers; VerEx() : prefixes(""), source(""), suffixes(""), pattern(""), modifiers(0){}; VerEx& operator=(const VerEx& ve) = default; ~VerEx() = default; VerEx & add(const std::string & value) { source = source + value; pattern = prefixes + source + suffixes; return (*this); } VerEx & startOfLine(bool enable) { prefixes = enable ? "^" : ""; return add(""); } inline VerEx & startOfLine() { return startOfLine(true); } VerEx & endOfLine(bool enable) { suffixes = enable ? "$" : ""; return add(""); } inline VerEx & endOfLine() { return endOfLine(true); } VerEx & then(const std::string & value) { return add("(?:" + value + ")"); } VerEx & find(const std::string & value) { return then(value); } VerEx & maybe(const std::string & value) { return add("(?:" + value + ")?"); } VerEx & anything() { return add("(?:.*)"); } VerEx & anythingBut(const std::string & value) { return add("(?:[^" + value + "]*)"); } VerEx & something() { return add("(?:.+)"); } VerEx & somethingBut(const std::string & value) { return add("(?:[^" + value + "]+)"); } const std::string replace(const std::string & source, const std::string & value) { return veregex::regex_replace( source, veregex::regex(pattern, checkFlags()), value); } VerEx & lineBreak() { return add("(?:(?:\\n)|(?:\\r\\n))"); } inline VerEx & br() { return lineBreak(); } VerEx & tab() { return add("\\t"); } VerEx & word() { return add("\\w+"); } VerEx & anyOf(const std::string & value) { return add( "[" + value + "]" ); } VerEx & any(const std::string & value) { return anyOf(value); } VerEx & range(std::vector<std::string> args) { std::stringstream value; value << "["; for(unsigned int _from = 0; _from < args.size(); _from += 2) { unsigned int _to = _from+1; if (args.size() <= _to) break; int from = atoi(args[_from].c_str()); int to = atoi(args[_to].c_str()); value << from << "-" << to; } value << "]"; return add(value.str()); } VerEx & addModifier(char modifier) { switch (modifier) { case 'i': modifiers |= CASEINSENSITIVE; break; case 'm': modifiers |= MULTILINE; break; case 'g': modifiers |= GLOBAL; break; default: break; } return (*this); } VerEx & removeModifier(char modifier) { switch (modifier) { case 'i': modifiers ^= CASEINSENSITIVE; break; case 'm': modifiers ^= MULTILINE; break; case 'g': modifiers ^= GLOBAL; break; default: break; } return (*this); } VerEx & withAnyCase(bool enable) { if (enable) addModifier( 'i' ); else removeModifier( 'i' ); return (*this); } inline VerEx & withAnyCase() { return withAnyCase(true); } VerEx & searchOneLine(bool enable) { if (enable) removeModifier( 'm' ); else addModifier( 'm' ); return (*this); } inline VerEx & searchOneLine() { return searchOneLine(true); } VerEx & searchGlobal(bool enable) { if (enable) addModifier( 'g' ); else removeModifier( 'g' ); return (*this); } inline VerEx & searchGlobal() { return searchGlobal(true); } VerEx & multiple(const std::string & value) { if(value.at(0) != '*' && value.at(0) != '+') add("+"); return add(value); } VerEx & alt(const std::string & value) { if (prefixes.find("(") == std::string::npos) prefixes += "("; if (suffixes.find(")") == std::string::npos) suffixes = ")" + suffixes; add( ")|(" ); return then(value); } bool test(const std::string & value) { std::string toTest; if(modifiers & MULTILINE) toTest = value; else toTest = reduceLines(value); if(modifiers & GLOBAL) return veregex::regex_search(toTest, veregex::regex(pattern, checkFlags())); else return veregex::regex_match(toTest, veregex::regex(pattern, checkFlags())); } }; #endif <|endoftext|>
<commit_before>#include <util/Logger.h> #include "ZoomView.h" namespace gui { static logger::LogChannel zoomviewlog("zoomviewlog", "[ZoomView] "); ZoomView::ZoomView() : _scale(1.0), _shift(0.0, 0.0), _zoomStep(1.1) { registerInput(_content, "painter"); registerOutput(_zoomed, "painter"); _content.registerBackwardSlot(_update); _content.registerBackwardSlot(_keyDown); _content.registerBackwardSlot(_keyUp); _content.registerBackwardSlot(_mouseDown); _content.registerBackwardSlot(_mouseUp); _content.registerBackwardSlot(_mouseMove); _content.registerBackwardCallback(&ZoomView::onInputSet, this); _content.registerBackwardCallback(&ZoomView::onModified, this); _content.registerBackwardCallback(&ZoomView::onContentChanged, this); _content.registerBackwardCallback(&ZoomView::onSizeChanged, this); _zoomed.registerForwardSlot(_modified); _zoomed.registerForwardSlot(_contentChanged); _zoomed.registerForwardSlot(_sizeChanged); _zoomed.registerForwardCallback(&ZoomView::onUpdate, this); _zoomed.registerForwardCallback(&ZoomView::onKeyUp, this); _zoomed.registerForwardCallback(&ZoomView::onKeyDown, this); _zoomed.registerForwardCallback(&ZoomView::onMouseUp, this); _zoomed.registerForwardCallback(&ZoomView::onMouseDown, this); _zoomed.registerForwardCallback(&ZoomView::onMouseMove, this); } void ZoomView::onInputSet(const pipeline::InputSet<Painter>& signal) { LOG_ALL(zoomviewlog) << "got a new painter" << std::endl; if (!_zoomed) _zoomed.createData(); _zoomed->setContent(_content); _modified(); } void ZoomView::onModified(const pipeline::Modified& signal) { // just pass this signal on _modified(); } void ZoomView::onContentChanged(const ContentChanged& signal) { _contentChanged(); } void ZoomView::onSizeChanged(const SizeChanged& signal) { _zoomed->updateSize(); _sizeChanged(SizeChanged(_zoomed->getSize())); } void ZoomView::onUpdate(const pipeline::Update& signal) { _update(signal); _zoomed->setScale(_scale); _zoomed->setShift(_shift); } void ZoomView::onKeyUp(const KeyUp& signal) { // pass on the signal _keyUp(signal); } void ZoomView::onKeyDown(KeyDown& signal) { LOG_ALL(zoomviewlog) << "a key was pressed" << std::endl; if (signal.key == keys::R) { LOG_ALL(zoomviewlog) << "resetting scale and shift" << std::endl; _scale = 1.0; _shift = util::point<double>(0.0, 0.0); _modified(); signal.processed = true; } else { _keyDown(signal); } } void ZoomView::onMouseUp(const MouseUp& signal) { LOG_ALL(zoomviewlog) << "a button was released" << std::endl; MouseUp zoomedSignal = signal; zoomedSignal.position /= _scale; zoomedSignal.position -= _shift; _mouseUp(zoomedSignal); } void ZoomView::onMouseDown(const MouseDown& signal) { LOG_ALL(zoomviewlog) << "a button was pressed" << std::endl; MouseDown zoomedSignal = signal; zoomedSignal.position /= _scale; zoomedSignal.position -= _shift; _mouseDown(zoomedSignal); if (zoomedSignal.processed) return; util::point<double> position = signal.position; LOG_ALL(zoomviewlog) << "mouse button " << signal.button << " down, position is " << position << std::endl; if (signal.button == buttons::Left) { LOG_ALL(zoomviewlog) << "it's the left mouse button -- start dragging mode" << std::endl; _dragging = true; _buttonDown = position; return; } // in the following, treat x and y zoom-corrected: position.x /= _scale; position.y /= _scale; // if control is pressed, increase zoom speed double zoomStep = _zoomStep; if (signal.modifiers & keys::ControlDown) zoomStep *= 2; // mouse wheel up if (signal.button == buttons::WheelUp) { LOG_ALL(zoomviewlog) << "it's the left wheel up" << std::endl; _scale *= zoomStep; _shift += position*(1.0/zoomStep - 1.0); LOG_ALL(zoomviewlog) << "mouse wheel up, new zoom " << _scale << ", shift " << _shift << ", position was " << position << std::endl; } // mouse wheel down if (signal.button == buttons::WheelDown) { LOG_ALL(zoomviewlog) << "it's the left wheel down" << std::endl; _scale *= 1.0/zoomStep; _shift += position*(zoomStep - 1.0); LOG_ALL(zoomviewlog) << "mouse wheel down, new zoom " << _scale << ", shift " << _shift << ", position was " << position << std::endl; } _modified(); } void ZoomView::onMouseMove(const MouseMove& signal) { LOG_ALL(zoomviewlog) << "the mouse is moved" << std::endl; MouseMove zoomedSignal = signal; zoomedSignal.position /= _scale; zoomedSignal.position -= _shift; _mouseMove(zoomedSignal); if (zoomedSignal.processed) return; if (!_dragging) { return; } LOG_ALL(zoomviewlog) << "I am in dragging mode" << std::endl; double amp = 1.0; if (signal.modifiers & keys::ControlDown) amp = 10.0; // mouse is dragged if (signal.modifiers & buttons::LeftDown) { LOG_ALL(zoomviewlog) << "left button is still pressed" << std::endl; util::point<double> moved = signal.position - _buttonDown; _shift += moved*amp/_scale; _buttonDown = signal.position; _zoomed->setShift(_shift); _modified(); } else { LOG_ALL(zoomviewlog) << "left button released -- stop dragging" << std::endl; _dragging = false; } } } // namespace gui <commit_msg>made ZoomView only react to mouse events if control is pressed<commit_after>#include <util/Logger.h> #include "ZoomView.h" namespace gui { static logger::LogChannel zoomviewlog("zoomviewlog", "[ZoomView] "); ZoomView::ZoomView() : _scale(1.0), _shift(0.0, 0.0), _zoomStep(1.1) { registerInput(_content, "painter"); registerOutput(_zoomed, "painter"); _content.registerBackwardSlot(_update); _content.registerBackwardSlot(_keyDown); _content.registerBackwardSlot(_keyUp); _content.registerBackwardSlot(_mouseDown); _content.registerBackwardSlot(_mouseUp); _content.registerBackwardSlot(_mouseMove); _content.registerBackwardCallback(&ZoomView::onInputSet, this); _content.registerBackwardCallback(&ZoomView::onModified, this); _content.registerBackwardCallback(&ZoomView::onContentChanged, this); _content.registerBackwardCallback(&ZoomView::onSizeChanged, this); _zoomed.registerForwardSlot(_modified); _zoomed.registerForwardSlot(_contentChanged); _zoomed.registerForwardSlot(_sizeChanged); _zoomed.registerForwardCallback(&ZoomView::onUpdate, this); _zoomed.registerForwardCallback(&ZoomView::onKeyUp, this); _zoomed.registerForwardCallback(&ZoomView::onKeyDown, this); _zoomed.registerForwardCallback(&ZoomView::onMouseUp, this); _zoomed.registerForwardCallback(&ZoomView::onMouseDown, this); _zoomed.registerForwardCallback(&ZoomView::onMouseMove, this); } void ZoomView::onInputSet(const pipeline::InputSet<Painter>& signal) { LOG_ALL(zoomviewlog) << "got a new painter" << std::endl; if (!_zoomed) _zoomed.createData(); _zoomed->setContent(_content); _modified(); } void ZoomView::onModified(const pipeline::Modified& signal) { // just pass this signal on _modified(); } void ZoomView::onContentChanged(const ContentChanged& signal) { _contentChanged(); } void ZoomView::onSizeChanged(const SizeChanged& signal) { _zoomed->updateSize(); _sizeChanged(SizeChanged(_zoomed->getSize())); } void ZoomView::onUpdate(const pipeline::Update& signal) { _update(signal); _zoomed->setScale(_scale); _zoomed->setShift(_shift); } void ZoomView::onKeyUp(const KeyUp& signal) { // pass on the signal _keyUp(signal); } void ZoomView::onKeyDown(KeyDown& signal) { LOG_ALL(zoomviewlog) << "a key was pressed" << std::endl; if (signal.key == keys::R) { LOG_ALL(zoomviewlog) << "resetting scale and shift" << std::endl; _scale = 1.0; _shift = util::point<double>(0.0, 0.0); _modified(); signal.processed = true; } else { _keyDown(signal); } } void ZoomView::onMouseUp(const MouseUp& signal) { LOG_ALL(zoomviewlog) << "a button was released" << std::endl; MouseUp zoomedSignal = signal; zoomedSignal.position /= _scale; zoomedSignal.position -= _shift; _mouseUp(zoomedSignal); } void ZoomView::onMouseDown(const MouseDown& signal) { LOG_ALL(zoomviewlog) << "a button was pressed" << std::endl; MouseDown zoomedSignal = signal; zoomedSignal.position /= _scale; zoomedSignal.position -= _shift; _mouseDown(zoomedSignal); if (zoomedSignal.processed || !(signal.modifiers & keys::ControlDown)) return; util::point<double> position = signal.position; LOG_ALL(zoomviewlog) << "mouse button " << signal.button << " down, position is " << position << std::endl; if (signal.button == buttons::Left) { LOG_ALL(zoomviewlog) << "it's the left mouse button -- start dragging mode" << std::endl; _dragging = true; _buttonDown = position; return; } // in the following, treat x and y zoom-corrected: position.x /= _scale; position.y /= _scale; // if shift is pressed, increase zoom speed double zoomStep = _zoomStep; if (signal.modifiers & keys::ShiftDown) zoomStep *= 2; // mouse wheel up if (signal.button == buttons::WheelUp) { LOG_ALL(zoomviewlog) << "it's the left wheel up" << std::endl; _scale *= zoomStep; _shift += position*(1.0/zoomStep - 1.0); LOG_ALL(zoomviewlog) << "mouse wheel up, new zoom " << _scale << ", shift " << _shift << ", position was " << position << std::endl; } // mouse wheel down if (signal.button == buttons::WheelDown) { LOG_ALL(zoomviewlog) << "it's the left wheel down" << std::endl; _scale *= 1.0/zoomStep; _shift += position*(zoomStep - 1.0); LOG_ALL(zoomviewlog) << "mouse wheel down, new zoom " << _scale << ", shift " << _shift << ", position was " << position << std::endl; } _modified(); } void ZoomView::onMouseMove(const MouseMove& signal) { LOG_ALL(zoomviewlog) << "the mouse is moved" << std::endl; MouseMove zoomedSignal = signal; zoomedSignal.position /= _scale; zoomedSignal.position -= _shift; _mouseMove(zoomedSignal); if (zoomedSignal.processed || !(signal.modifiers & keys::ControlDown)) return; if (!_dragging) { return; } LOG_ALL(zoomviewlog) << "I am in dragging mode" << std::endl; double amp = 1.0; if (signal.modifiers & keys::ShiftDown) amp = 10.0; // mouse is dragged if (signal.modifiers & buttons::LeftDown) { LOG_ALL(zoomviewlog) << "left button is still pressed" << std::endl; util::point<double> moved = signal.position - _buttonDown; _shift += moved*amp/_scale; _buttonDown = signal.position; _zoomed->setShift(_shift); _modified(); } else { LOG_ALL(zoomviewlog) << "left button released -- stop dragging" << std::endl; _dragging = false; } } } // namespace gui <|endoftext|>
<commit_before>/* * Copyright (c) 2017-2018 Tuukka Norri * This code is licensed under MIT license (see LICENSE for details). */ #include <boost/format.hpp> #include <sys/stat.h> #include <libbio/fasta_reader.hh> #include <vcf2multialign/read_single_fasta_seq.hh> #include <vcf2multialign/types.hh> namespace lb = libbio; namespace v2m = vcf2multialign; namespace { class delegate : public libbio::fasta_reader_delegate { protected: v2m::vector_type *m_reference{}; char const *m_identifier{}; bool m_found_seq{}; public: delegate(v2m::vector_type &reference, char const *identifier): m_reference(&reference), m_identifier(identifier) { } virtual bool handle_comment_line(lb::fasta_reader &reader, std::string_view const &sv) override { return true; } virtual bool handle_identifier(lb::fasta_reader &reader, std::string_view const &sv) override { if (m_found_seq) return false; if ((!m_identifier) || sv == m_identifier) { m_found_seq = true; std::cerr << " reading sequence with identifier " << sv << "…" << std::flush; } return true; } virtual bool handle_sequence_line(lb::fasta_reader &reader, std::string_view const &sv) override { if (!m_found_seq) return false; std::copy(sv.begin(), sv.end(), std::back_inserter(*m_reference)); return true; } }; } namespace vcf2multialign { // Read the contents of a FASTA file into a single sequence. void read_single_fasta_seq(lb::mmap_handle <char> &ref_fasta_handle, vector_type &reference, char const *ref_seq_name) { lb::fasta_reader reader; delegate cb(reference, ref_seq_name); std::cerr << "Reading reference FASTA into memory…"; reader.parse(ref_fasta_handle, cb); std::cerr << " Done." << std::endl; } } <commit_msg>Output the reference length when done<commit_after>/* * Copyright (c) 2017-2018 Tuukka Norri * This code is licensed under MIT license (see LICENSE for details). */ #include <boost/format.hpp> #include <sys/stat.h> #include <libbio/fasta_reader.hh> #include <vcf2multialign/read_single_fasta_seq.hh> #include <vcf2multialign/types.hh> namespace lb = libbio; namespace v2m = vcf2multialign; namespace { class delegate : public libbio::fasta_reader_delegate { protected: v2m::vector_type *m_reference{}; char const *m_identifier{}; bool m_found_seq{}; public: delegate(v2m::vector_type &reference, char const *identifier): m_reference(&reference), m_identifier(identifier) { } virtual bool handle_comment_line(lb::fasta_reader &reader, std::string_view const &sv) override { return true; } virtual bool handle_identifier(lb::fasta_reader &reader, std::string_view const &sv) override { if (m_found_seq) return false; if ((!m_identifier) || sv == m_identifier) { m_found_seq = true; std::cerr << " reading sequence with identifier " << sv << "…" << std::flush; } return true; } virtual bool handle_sequence_line(lb::fasta_reader &reader, std::string_view const &sv) override { if (!m_found_seq) return false; std::copy(sv.begin(), sv.end(), std::back_inserter(*m_reference)); return true; } }; } namespace vcf2multialign { // Read the contents of a FASTA file into a single sequence. void read_single_fasta_seq(lb::mmap_handle <char> &ref_fasta_handle, vector_type &reference, char const *ref_seq_name) { lb::fasta_reader reader; delegate cb(reference, ref_seq_name); std::cerr << "Reading reference FASTA into memory…"; reader.parse(ref_fasta_handle, cb); std::cerr << " Done. Reference length was " << reference.size() << '.' << std::endl; } } <|endoftext|>
<commit_before>#include "Geometry.hpp" #include "Line.hpp" #include "PolylineCollection.hpp" #include "clipper.hpp" #include <algorithm> #include <list> #include <map> #include <set> #include <vector> #ifdef SLIC3R_DEBUG #include "SVG.hpp" #endif using namespace boost::polygon; // provides also high() and low() namespace Slic3r { namespace Geometry { static bool sort_points (Point a, Point b) { return (a.x < b.x) || (a.x == b.x && a.y < b.y); } /* This implementation is based on Andrew's monotone chain 2D convex hull algorithm */ void convex_hull(Points &points, Polygon* hull) { assert(points.size() >= 3); // sort input points std::sort(points.begin(), points.end(), sort_points); int n = points.size(), k = 0; hull->points.resize(2*n); // Build lower hull for (int i = 0; i < n; i++) { while (k >= 2 && points[i].ccw(hull->points[k-2], hull->points[k-1]) <= 0) k--; hull->points[k++] = points[i]; } // Build upper hull for (int i = n-2, t = k+1; i >= 0; i--) { while (k >= t && points[i].ccw(hull->points[k-2], hull->points[k-1]) <= 0) k--; hull->points[k++] = points[i]; } hull->points.resize(k); assert( hull->points.front().coincides_with(hull->points.back()) ); hull->points.pop_back(); } /* accepts an arrayref of points and returns a list of indices according to a nearest-neighbor walk */ void chained_path(Points &points, std::vector<Points::size_type> &retval, Point start_near) { PointPtrs my_points; std::map<Point*,Points::size_type> indices; my_points.reserve(points.size()); for (Points::iterator it = points.begin(); it != points.end(); ++it) { my_points.push_back(&*it); indices[&*it] = it - points.begin(); } retval.reserve(points.size()); while (!my_points.empty()) { Points::size_type idx = start_near.nearest_point_index(my_points); start_near = *my_points[idx]; retval.push_back(indices[ my_points[idx] ]); my_points.erase(my_points.begin() + idx); } } void chained_path(Points &points, std::vector<Points::size_type> &retval) { if (points.empty()) return; // can't call front() on empty vector chained_path(points, retval, points.front()); } /* retval and items must be different containers */ template<class T> void chained_path_items(Points &points, T &items, T &retval) { std::vector<Points::size_type> indices; chained_path(points, indices); for (std::vector<Points::size_type>::const_iterator it = indices.begin(); it != indices.end(); ++it) retval.push_back(items[*it]); } template void chained_path_items(Points &points, ClipperLib::PolyNodes &items, ClipperLib::PolyNodes &retval); Line MedialAxis::edge_to_line(const VD::edge_type &edge) { Line line; line.a.x = edge.vertex0()->x(); line.a.y = edge.vertex0()->y(); line.b.x = edge.vertex1()->x(); line.b.y = edge.vertex1()->y(); return line; } void MedialAxis::build(Polylines* polylines) { /* // build bounding box (we use it for clipping infinite segments) // --> we have no infinite segments this->bb = BoundingBox(this->lines); */ construct_voronoi(this->lines.begin(), this->lines.end(), &this->vd); // collect valid edges (i.e. prune those not belonging to MAT) // note: this keeps twins, so it contains twice the number of the valid edges this->edges.clear(); for (VD::const_edge_iterator edge = this->vd.edges().begin(); edge != this->vd.edges().end(); ++edge) { if (this->is_valid_edge(*edge)) this->edges.insert(&*edge); } // count valid segments for each vertex std::map< const VD::vertex_type*,std::list<const VD::edge_type*> > vertex_edges; std::list<const VD::vertex_type*> entry_nodes; for (VD::const_vertex_iterator vertex = this->vd.vertices().begin(); vertex != this->vd.vertices().end(); ++vertex) { // get a reference to the list of valid edges originating from this vertex std::list<const VD::edge_type*>& edges = vertex_edges[&*vertex]; // get one random edge originating from this vertex const VD::edge_type* edge = vertex->incident_edge(); do { if (this->edges.count(edge) > 0) // only count valid edges edges.push_back(edge); edge = edge->rot_next(); // next edge originating from this vertex } while (edge != vertex->incident_edge()); // if there's only one edge starting at this vertex then it's a leaf if (edges.size() == 1) entry_nodes.push_back(&*vertex); } // iterate through the leafs to prune short branches for (std::list<const VD::vertex_type*>::const_iterator vertex = entry_nodes.begin(); vertex != entry_nodes.end(); ++vertex) { const VD::vertex_type* v = *vertex; // start a polyline from this vertex Polyline polyline; polyline.points.push_back(Point(v->x(), v->y())); // keep track of visited edges to prevent infinite loops std::set<const VD::edge_type*> visited_edges; do { // get edge starting from v const VD::edge_type* edge = vertex_edges[v].front(); // if we picked the edge going backwards (thus the twin of the previous edge) if (visited_edges.count(edge->twin()) > 0) { edge = vertex_edges[v].back(); } // avoid getting twice on the same edge if (visited_edges.count(edge) > 0) break; visited_edges.insert(edge); // get ending vertex for this edge and append it to the polyline v = edge->vertex1(); polyline.points.push_back(Point( v->x(), v->y() )); // if two edges start at this vertex (one forward one backwards) then // it's not branching and we can go on } while (vertex_edges[v].size() == 2); // if this branch is too short, invalidate all of its edges so that // they will be ignored when building actual polylines in the loop below if (polyline.length() < this->width) { for (std::set<const VD::edge_type*>::const_iterator edge = visited_edges.begin(); edge != visited_edges.end(); ++edge) { (void)this->edges.erase(*edge); (void)this->edges.erase((*edge)->twin()); } } } // iterate through the valid edges to build polylines while (!this->edges.empty()) { const VD::edge_type& edge = **this->edges.begin(); // start a polyline Polyline polyline; polyline.points.push_back(Point( edge.vertex0()->x(), edge.vertex0()->y() )); polyline.points.push_back(Point( edge.vertex1()->x(), edge.vertex1()->y() )); // remove this edge and its twin from the available edges (void)this->edges.erase(&edge); (void)this->edges.erase(edge.twin()); // get next points this->process_edge_neighbors(edge, &polyline.points); // get previous points Points pp; this->process_edge_neighbors(*edge.twin(), &pp); polyline.points.insert(polyline.points.begin(), pp.rbegin(), pp.rend()); // append polyline to result polylines->push_back(polyline); } } void MedialAxis::process_edge_neighbors(const VD::edge_type& edge, Points* points) { // Since rot_next() works on the edge starting point but we want // to find neighbors on the ending point, we just swap edge with // its twin. const VD::edge_type& twin = *edge.twin(); // count neighbors for this edge std::vector<const VD::edge_type*> neighbors; for (const VD::edge_type* neighbor = twin.rot_next(); neighbor != &twin; neighbor = neighbor->rot_next()) { if (this->edges.count(neighbor) > 0) neighbors.push_back(neighbor); } // if we have a single neighbor then we can continue recursively if (neighbors.size() == 1) { const VD::edge_type& neighbor = *neighbors.front(); points->push_back(Point( neighbor.vertex1()->x(), neighbor.vertex1()->y() )); (void)this->edges.erase(&neighbor); (void)this->edges.erase(neighbor.twin()); this->process_edge_neighbors(neighbor, points); } } bool MedialAxis::is_valid_edge(const VD::edge_type& edge) const { // if we only process segments representing closed loops, none if the // infinite edges (if any) would be part of our MAT anyway if (edge.is_secondary() || edge.is_infinite()) return false; /* If the cells sharing this edge have a common vertex, we're not interested in this edge. Why? Because it means that the edge lies on the bisector of two contiguous input lines and it was included in the Voronoi graph because it's the locus of centers of circles tangent to both vertices. Due to the "thin" nature of our input, these edges will be very short and not part of our wanted output. The best way would be to just filter out the edges that are not the locus of the maximally inscribed disks (requirement of MAT) but I don't know how to do it. Maybe we could check the relative angle of the two segments (we are only interested in facing segments). */ const VD::cell_type &cell1 = *edge.cell(); const VD::cell_type &cell2 = *edge.twin()->cell(); if (cell1.contains_segment() && cell2.contains_segment()) { Line segment1 = this->retrieve_segment(cell1); Line segment2 = this->retrieve_segment(cell2); if (segment1.a == segment2.b || segment1.b == segment2.a) return false; if (fabs(segment1.atan2_() - segment2.atan2_()) < PI/3) { //printf("segment1 atan2 = %f, segment2 atan2 = %f\n", segment1.atan2_(), segment2.atan2_()); //printf(" => SAME ATAN2\n"); return false; } } return true; } Line MedialAxis::retrieve_segment(const VD::cell_type& cell) const { VD::cell_type::source_index_type index = cell.source_index() - this->points.size(); return this->lines[index]; } } } <commit_msg>Consider contour thickness when validating medial axis segments<commit_after>#include "Geometry.hpp" #include "Line.hpp" #include "PolylineCollection.hpp" #include "clipper.hpp" #include <algorithm> #include <list> #include <map> #include <set> #include <vector> #ifdef SLIC3R_DEBUG #include "SVG.hpp" #endif using namespace boost::polygon; // provides also high() and low() namespace Slic3r { namespace Geometry { static bool sort_points (Point a, Point b) { return (a.x < b.x) || (a.x == b.x && a.y < b.y); } /* This implementation is based on Andrew's monotone chain 2D convex hull algorithm */ void convex_hull(Points &points, Polygon* hull) { assert(points.size() >= 3); // sort input points std::sort(points.begin(), points.end(), sort_points); int n = points.size(), k = 0; hull->points.resize(2*n); // Build lower hull for (int i = 0; i < n; i++) { while (k >= 2 && points[i].ccw(hull->points[k-2], hull->points[k-1]) <= 0) k--; hull->points[k++] = points[i]; } // Build upper hull for (int i = n-2, t = k+1; i >= 0; i--) { while (k >= t && points[i].ccw(hull->points[k-2], hull->points[k-1]) <= 0) k--; hull->points[k++] = points[i]; } hull->points.resize(k); assert( hull->points.front().coincides_with(hull->points.back()) ); hull->points.pop_back(); } /* accepts an arrayref of points and returns a list of indices according to a nearest-neighbor walk */ void chained_path(Points &points, std::vector<Points::size_type> &retval, Point start_near) { PointPtrs my_points; std::map<Point*,Points::size_type> indices; my_points.reserve(points.size()); for (Points::iterator it = points.begin(); it != points.end(); ++it) { my_points.push_back(&*it); indices[&*it] = it - points.begin(); } retval.reserve(points.size()); while (!my_points.empty()) { Points::size_type idx = start_near.nearest_point_index(my_points); start_near = *my_points[idx]; retval.push_back(indices[ my_points[idx] ]); my_points.erase(my_points.begin() + idx); } } void chained_path(Points &points, std::vector<Points::size_type> &retval) { if (points.empty()) return; // can't call front() on empty vector chained_path(points, retval, points.front()); } /* retval and items must be different containers */ template<class T> void chained_path_items(Points &points, T &items, T &retval) { std::vector<Points::size_type> indices; chained_path(points, indices); for (std::vector<Points::size_type>::const_iterator it = indices.begin(); it != indices.end(); ++it) retval.push_back(items[*it]); } template void chained_path_items(Points &points, ClipperLib::PolyNodes &items, ClipperLib::PolyNodes &retval); Line MedialAxis::edge_to_line(const VD::edge_type &edge) { Line line; line.a.x = edge.vertex0()->x(); line.a.y = edge.vertex0()->y(); line.b.x = edge.vertex1()->x(); line.b.y = edge.vertex1()->y(); return line; } void MedialAxis::build(Polylines* polylines) { /* // build bounding box (we use it for clipping infinite segments) // --> we have no infinite segments this->bb = BoundingBox(this->lines); */ construct_voronoi(this->lines.begin(), this->lines.end(), &this->vd); // collect valid edges (i.e. prune those not belonging to MAT) // note: this keeps twins, so it contains twice the number of the valid edges this->edges.clear(); for (VD::const_edge_iterator edge = this->vd.edges().begin(); edge != this->vd.edges().end(); ++edge) { if (this->is_valid_edge(*edge)) this->edges.insert(&*edge); } // count valid segments for each vertex std::map< const VD::vertex_type*,std::list<const VD::edge_type*> > vertex_edges; std::list<const VD::vertex_type*> entry_nodes; for (VD::const_vertex_iterator vertex = this->vd.vertices().begin(); vertex != this->vd.vertices().end(); ++vertex) { // get a reference to the list of valid edges originating from this vertex std::list<const VD::edge_type*>& edges = vertex_edges[&*vertex]; // get one random edge originating from this vertex const VD::edge_type* edge = vertex->incident_edge(); do { if (this->edges.count(edge) > 0) // only count valid edges edges.push_back(edge); edge = edge->rot_next(); // next edge originating from this vertex } while (edge != vertex->incident_edge()); // if there's only one edge starting at this vertex then it's a leaf if (edges.size() == 1) entry_nodes.push_back(&*vertex); } // iterate through the leafs to prune short branches for (std::list<const VD::vertex_type*>::const_iterator vertex = entry_nodes.begin(); vertex != entry_nodes.end(); ++vertex) { const VD::vertex_type* v = *vertex; // start a polyline from this vertex Polyline polyline; polyline.points.push_back(Point(v->x(), v->y())); // keep track of visited edges to prevent infinite loops std::set<const VD::edge_type*> visited_edges; do { // get edge starting from v const VD::edge_type* edge = vertex_edges[v].front(); // if we picked the edge going backwards (thus the twin of the previous edge) if (visited_edges.count(edge->twin()) > 0) { edge = vertex_edges[v].back(); } // avoid getting twice on the same edge if (visited_edges.count(edge) > 0) break; visited_edges.insert(edge); // get ending vertex for this edge and append it to the polyline v = edge->vertex1(); polyline.points.push_back(Point( v->x(), v->y() )); // if two edges start at this vertex (one forward one backwards) then // it's not branching and we can go on } while (vertex_edges[v].size() == 2); // if this branch is too short, invalidate all of its edges so that // they will be ignored when building actual polylines in the loop below if (polyline.length() < this->width) { for (std::set<const VD::edge_type*>::const_iterator edge = visited_edges.begin(); edge != visited_edges.end(); ++edge) { (void)this->edges.erase(*edge); (void)this->edges.erase((*edge)->twin()); } } } // iterate through the valid edges to build polylines while (!this->edges.empty()) { const VD::edge_type& edge = **this->edges.begin(); // start a polyline Polyline polyline; polyline.points.push_back(Point( edge.vertex0()->x(), edge.vertex0()->y() )); polyline.points.push_back(Point( edge.vertex1()->x(), edge.vertex1()->y() )); // remove this edge and its twin from the available edges (void)this->edges.erase(&edge); (void)this->edges.erase(edge.twin()); // get next points this->process_edge_neighbors(edge, &polyline.points); // get previous points Points pp; this->process_edge_neighbors(*edge.twin(), &pp); polyline.points.insert(polyline.points.begin(), pp.rbegin(), pp.rend()); // append polyline to result polylines->push_back(polyline); } } void MedialAxis::process_edge_neighbors(const VD::edge_type& edge, Points* points) { // Since rot_next() works on the edge starting point but we want // to find neighbors on the ending point, we just swap edge with // its twin. const VD::edge_type& twin = *edge.twin(); // count neighbors for this edge std::vector<const VD::edge_type*> neighbors; for (const VD::edge_type* neighbor = twin.rot_next(); neighbor != &twin; neighbor = neighbor->rot_next()) { if (this->edges.count(neighbor) > 0) neighbors.push_back(neighbor); } // if we have a single neighbor then we can continue recursively if (neighbors.size() == 1) { const VD::edge_type& neighbor = *neighbors.front(); points->push_back(Point( neighbor.vertex1()->x(), neighbor.vertex1()->y() )); (void)this->edges.erase(&neighbor); (void)this->edges.erase(neighbor.twin()); this->process_edge_neighbors(neighbor, points); } } bool MedialAxis::is_valid_edge(const VD::edge_type& edge) const { // if we only process segments representing closed loops, none if the // infinite edges (if any) would be part of our MAT anyway if (edge.is_secondary() || edge.is_infinite()) return false; /* If the cells sharing this edge have a common vertex, we're not interested in this edge. Why? Because it means that the edge lies on the bisector of two contiguous input lines and it was included in the Voronoi graph because it's the locus of centers of circles tangent to both vertices. Due to the "thin" nature of our input, these edges will be very short and not part of our wanted output. The best way would be to just filter out the edges that are not the locus of the maximally inscribed disks (requirement of MAT) but I don't know how to do it. Maybe we could check the relative angle of the two segments (we are only interested in facing segments). */ const VD::cell_type &cell1 = *edge.cell(); const VD::cell_type &cell2 = *edge.twin()->cell(); if (cell1.contains_segment() && cell2.contains_segment()) { Line segment1 = this->retrieve_segment(cell1); Line segment2 = this->retrieve_segment(cell2); if (segment1.a == segment2.b || segment1.b == segment2.a) return false; if (fabs(segment1.atan2_() - segment2.atan2_()) < PI/3) return false; // we can assume that distance between any of the vertices and any of the cell segments // is about the same Point p0( edge.vertex0()->x(), edge.vertex0()->y() ); double dist = p0.distance_to(segment1); // if distance between this edge and the thin area boundary is greater // than half the max width, then it's not a true medial axis segment; // if it's too small then it's not suitable for extrusion since it would // exceed the desired shape too much (this also traps some very narrow // areas caused by collapsing/mitering that we should ignore) if (dist > this->width/2 || dist < this->width/10) return false; } return true; } Line MedialAxis::retrieve_segment(const VD::cell_type& cell) const { VD::cell_type::source_index_type index = cell.source_index() - this->points.size(); return this->lines[index]; } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fmtcol.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:48:41 $ * * 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 _FMTCOL_HXX #define _FMTCOL_HXX #ifndef _SVARRAY_HXX //autogen #include <svtools/svarray.hxx> #endif #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif #ifndef _FORMAT_HXX #include <format.hxx> #endif #ifndef _SWTYPES_HXX #include <swtypes.hxx> // fuer MAXLEVEL #endif class SwDoc; // fuer friend class SwFmtColl : public SwFmt { protected: SwFmtColl( SwAttrPool& rPool, const sal_Char* pFmtName, const USHORT* pWhichRanges, SwFmtColl* pDerFrom, USHORT nFmtWhich ) : SwFmt( rPool, pFmtName, pWhichRanges, pDerFrom, nFmtWhich ) { SetAuto( FALSE ); } SwFmtColl( SwAttrPool& rPool, const String &rFmtName, const USHORT* pWhichRanges, SwFmtColl* pDerFrom, USHORT nFmtWhich ) : SwFmt( rPool, rFmtName, pWhichRanges, pDerFrom, nFmtWhich ) { SetAuto( FALSE ); } private: // erstmal wird nicht kopiert und nicht zugewiesen SwFmtColl(const SwFmtColl & ); const SwFmtColl &operator=(const SwFmtColl &); }; class SW_DLLPUBLIC SwTxtFmtColl: public SwFmtColl { friend class SwDoc; SwTxtFmtColl(const SwTxtFmtColl & rRef); protected: BYTE nOutlineLevel; SwTxtFmtColl *pNextTxtFmtColl; SwTxtFmtColl( SwAttrPool& rPool, const sal_Char* pFmtCollName, SwTxtFmtColl* pDerFrom = 0, USHORT nFmtWh = RES_TXTFMTCOLL ) : SwFmtColl( rPool, pFmtCollName, aTxtFmtCollSetRange, pDerFrom, nFmtWh ), nOutlineLevel( NO_NUMBERING ) { pNextTxtFmtColl = this; } SwTxtFmtColl( SwAttrPool& rPool, const String &rFmtCollName, SwTxtFmtColl* pDerFrom = 0, USHORT nFmtWh = RES_TXTFMTCOLL ) : SwFmtColl( rPool, rFmtCollName, aTxtFmtCollSetRange, pDerFrom, nFmtWh ), nOutlineLevel( NO_NUMBERING ) { pNextTxtFmtColl = this; } public: // zum "abfischen" von UL-/LR-/FontHeight Aenderungen virtual void Modify( SfxPoolItem*, SfxPoolItem* ); TYPEINFO(); //Bereits in Basisklasse Client drin. void SetOutlineLevel( BYTE ); inline BYTE GetOutlineLevel() const { return nOutlineLevel; } inline void SetNextTxtFmtColl(SwTxtFmtColl& rNext); SwTxtFmtColl& GetNextTxtFmtColl() const { return *pNextTxtFmtColl; } BOOL IsAtDocNodeSet() const; /*----------------- JP 09.08.94 17:36 ------------------- wird die Funktionalitaet von Zeichenvorlagen an Absatzvorlagen ueberhaupt benoetigt ?? Wenn, ja dann muessen im TextNode und hier in der TxtCollection ein 2. Attset fuer die Char-Attribute angelegt werden; damit die Vererbung und der Zugriff auf die gesetzen Attribute richtig funktioniert!! virtual BOOL SetDerivedFrom( SwFmtColl* pDerFrom = 0 ); inline SwCharFmt* GetCharFmt() const; inline BOOL IsCharFmtSet() const; void SetCharFmt(SwCharFmt *); void ResetCharFmt(); inline BOOL SwTxtFmtColl::IsCharFmtSet() const { return aCharDepend.GetRegisteredIn() ? TRUE : FALSE; } inline SwCharFmt* SwTxtFmtColl::GetCharFmt() const { return (SwCharFmt*)aCharDepend.GetRegisteredIn(); } --------------------------------------------------*/ }; typedef SwTxtFmtColl* SwTxtFmtCollPtr; SV_DECL_PTRARR(SwTxtFmtColls,SwTxtFmtCollPtr,2,4) class SwGrfFmtColl: public SwFmtColl { friend class SwDoc; protected: SwGrfFmtColl( SwAttrPool& rPool, const sal_Char* pFmtCollName, SwGrfFmtColl* pDerFrom = 0 ) : SwFmtColl( rPool, pFmtCollName, aGrfFmtCollSetRange, pDerFrom, RES_GRFFMTCOLL ) {} SwGrfFmtColl( SwAttrPool& rPool, const String &rFmtCollName, SwGrfFmtColl* pDerFrom = 0 ) : SwFmtColl( rPool, rFmtCollName, aGrfFmtCollSetRange, pDerFrom, RES_GRFFMTCOLL ) {} public: TYPEINFO(); //Bereits in Basisklasse Client drin. }; typedef SwGrfFmtColl* SwGrfFmtCollPtr; SV_DECL_PTRARR(SwGrfFmtColls,SwGrfFmtCollPtr,2,4) //FEATURE::CONDCOLL // --------- Bedingte Vorlagen ------------------------------- enum Master_CollConditions { PARA_IN_LIST = 0x0001, PARA_IN_OUTLINE = 0x0002, PARA_IN_FRAME = 0x0004, PARA_IN_TABLEHEAD = 0x0008, PARA_IN_TABLEBODY = 0x0010, PARA_IN_SECTION = 0x0020, PARA_IN_FOOTENOTE = 0x0040, PARA_IN_FOOTER = 0x0080, PARA_IN_HEADER = 0x0100, PARA_IN_ENDNOTE = 0x0200, // ... USRFLD_EXPRESSION = (int)0x8000 }; class SW_DLLPUBLIC SwCollCondition : public SwClient { ULONG nCondition; union { ULONG nSubCondition; String* pFldExpression; } aSubCondition; public: TYPEINFO(); //Bereits in Basisklasse Client drin. SwCollCondition( SwTxtFmtColl* pColl, ULONG nMasterCond, ULONG nSubCond = 0 ); SwCollCondition( SwTxtFmtColl* pColl, ULONG nMasterCond, const String& rSubExp ); virtual ~SwCollCondition(); // @@@ public copy ctor, but no copy assignment? SwCollCondition( const SwCollCondition& rCpy ); private: // @@@ public copy ctor, but no copy assignment? SwCollCondition & operator= (const SwCollCondition &); public: int operator==( const SwCollCondition& rCmp ) const; int operator!=( const SwCollCondition& rCmp ) const { return ! (*this == rCmp); } ULONG GetCondition() const { return nCondition; } ULONG GetSubCondition() const { return aSubCondition.nSubCondition; } const String* GetFldExpression() const { return aSubCondition.pFldExpression; } void SetCondition( ULONG nCond, ULONG nSubCond ); SwTxtFmtColl* GetTxtFmtColl() const { return (SwTxtFmtColl*)GetRegisteredIn(); } }; typedef SwCollCondition* SwCollConditionPtr; SV_DECL_PTRARR_DEL( SwFmtCollConditions, SwCollConditionPtr, 0, 5 ); class SW_DLLPUBLIC SwConditionTxtFmtColl : public SwTxtFmtColl { friend class SwDoc; protected: SwFmtCollConditions aCondColls; SwConditionTxtFmtColl( SwAttrPool& rPool, const sal_Char* pFmtCollName, SwTxtFmtColl* pDerFrom = 0 ) : SwTxtFmtColl( rPool, pFmtCollName, pDerFrom, RES_CONDTXTFMTCOLL ) {} SwConditionTxtFmtColl( SwAttrPool& rPool, const String &rFmtCollName, SwTxtFmtColl* pDerFrom = 0 ) : SwTxtFmtColl( rPool, rFmtCollName, pDerFrom, RES_CONDTXTFMTCOLL ) {} public: TYPEINFO(); //Bereits in Basisklasse Client drin. virtual ~SwConditionTxtFmtColl(); // zum "abfischen" von Aenderungen // virtual void Modify( SfxPoolItem*, SfxPoolItem* ); const SwCollCondition* HasCondition( const SwCollCondition& rCond ) const; const SwFmtCollConditions& GetCondColls() const { return aCondColls; } void InsertCondition( const SwCollCondition& rCond ); BOOL RemoveCondition( const SwCollCondition& rCond ); void SetConditions( const SwFmtCollConditions& ); }; //FEATURE::CONDCOLL // ------------- Inline Implementierungen -------------------- inline void SwTxtFmtColl::SetNextTxtFmtColl( SwTxtFmtColl& rNext ) { pNextTxtFmtColl = &rNext; } #endif <commit_msg>INTEGRATION: CWS writercorehandoff (1.6.4); FILE MERGED 2006/07/31 06:20:58 fme 1.6.4.1: #i50348# Resync<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fmtcol.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2006-08-14 15:23:18 $ * * 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 _FMTCOL_HXX #define _FMTCOL_HXX #ifndef _SVARRAY_HXX //autogen #include <svtools/svarray.hxx> #endif #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif #ifndef _FORMAT_HXX #include <format.hxx> #endif #ifndef _SWTYPES_HXX #include <swtypes.hxx> // fuer MAXLEVEL #endif class SwDoc; // fuer friend class SwFmtColl : public SwFmt { protected: SwFmtColl( SwAttrPool& rPool, const sal_Char* pFmtName, const USHORT* pWhichRanges, SwFmtColl* pDerFrom, USHORT nFmtWhich ) : SwFmt( rPool, pFmtName, pWhichRanges, pDerFrom, nFmtWhich ) { SetAuto( FALSE ); } SwFmtColl( SwAttrPool& rPool, const String &rFmtName, const USHORT* pWhichRanges, SwFmtColl* pDerFrom, USHORT nFmtWhich ) : SwFmt( rPool, rFmtName, pWhichRanges, pDerFrom, nFmtWhich ) { SetAuto( FALSE ); } private: // erstmal wird nicht kopiert und nicht zugewiesen SwFmtColl(const SwFmtColl & ); const SwFmtColl &operator=(const SwFmtColl &); }; class SW_DLLPUBLIC SwTxtFmtColl: public SwFmtColl { friend class SwDoc; SwTxtFmtColl(const SwTxtFmtColl & rRef); protected: BYTE nOutlineLevel; SwTxtFmtColl *pNextTxtFmtColl; SwTxtFmtColl( SwAttrPool& rPool, const sal_Char* pFmtCollName, SwTxtFmtColl* pDerFrom = 0, USHORT nFmtWh = RES_TXTFMTCOLL ) : SwFmtColl( rPool, pFmtCollName, aTxtFmtCollSetRange, pDerFrom, nFmtWh ), nOutlineLevel( NO_NUMBERING ) { pNextTxtFmtColl = this; } SwTxtFmtColl( SwAttrPool& rPool, const String &rFmtCollName, SwTxtFmtColl* pDerFrom = 0, USHORT nFmtWh = RES_TXTFMTCOLL ) : SwFmtColl( rPool, rFmtCollName, aTxtFmtCollSetRange, pDerFrom, nFmtWh ), nOutlineLevel( NO_NUMBERING ) { pNextTxtFmtColl = this; } public: // zum "abfischen" von UL-/LR-/FontHeight Aenderungen virtual void Modify( SfxPoolItem*, SfxPoolItem* ); TYPEINFO(); //Bereits in Basisklasse Client drin. void SetOutlineLevel( BYTE ); inline BYTE GetOutlineLevel() const { return nOutlineLevel; } inline void SetNextTxtFmtColl(SwTxtFmtColl& rNext); SwTxtFmtColl& GetNextTxtFmtColl() const { return *pNextTxtFmtColl; } BOOL IsAtDocNodeSet() const; /*----------------- JP 09.08.94 17:36 ------------------- wird die Funktionalitaet von Zeichenvorlagen an Absatzvorlagen ueberhaupt benoetigt ?? Wenn, ja dann muessen im TextNode und hier in der TxtCollection ein 2. Attset fuer die Char-Attribute angelegt werden; damit die Vererbung und der Zugriff auf die gesetzen Attribute richtig funktioniert!! virtual BOOL SetDerivedFrom( SwFmtColl* pDerFrom = 0 ); inline SwCharFmt* GetCharFmt() const; inline BOOL IsCharFmtSet() const; void SetCharFmt(SwCharFmt *); void ResetCharFmt(); inline BOOL SwTxtFmtColl::IsCharFmtSet() const { return aCharDepend.GetRegisteredIn() ? TRUE : FALSE; } inline SwCharFmt* SwTxtFmtColl::GetCharFmt() const { return (SwCharFmt*)aCharDepend.GetRegisteredIn(); } --------------------------------------------------*/ }; typedef SwTxtFmtColl* SwTxtFmtCollPtr; SV_DECL_PTRARR(SwTxtFmtColls,SwTxtFmtCollPtr,2,4) class SwGrfFmtColl: public SwFmtColl { friend class SwDoc; protected: SwGrfFmtColl( SwAttrPool& rPool, const sal_Char* pFmtCollName, SwGrfFmtColl* pDerFrom = 0 ) : SwFmtColl( rPool, pFmtCollName, aGrfFmtCollSetRange, pDerFrom, RES_GRFFMTCOLL ) {} SwGrfFmtColl( SwAttrPool& rPool, const String &rFmtCollName, SwGrfFmtColl* pDerFrom = 0 ) : SwFmtColl( rPool, rFmtCollName, aGrfFmtCollSetRange, pDerFrom, RES_GRFFMTCOLL ) {} public: TYPEINFO(); //Bereits in Basisklasse Client drin. }; typedef SwGrfFmtColl* SwGrfFmtCollPtr; SV_DECL_PTRARR(SwGrfFmtColls,SwGrfFmtCollPtr,2,4) //FEATURE::CONDCOLL // --------- Bedingte Vorlagen ------------------------------- enum Master_CollConditions { PARA_IN_LIST = 0x0001, PARA_IN_OUTLINE = 0x0002, PARA_IN_FRAME = 0x0004, PARA_IN_TABLEHEAD = 0x0008, PARA_IN_TABLEBODY = 0x0010, PARA_IN_SECTION = 0x0020, PARA_IN_FOOTENOTE = 0x0040, PARA_IN_FOOTER = 0x0080, PARA_IN_HEADER = 0x0100, PARA_IN_ENDNOTE = 0x0200, // ... USRFLD_EXPRESSION = (int)0x8000 }; class SW_DLLPUBLIC SwCollCondition : public SwClient { ULONG nCondition; union { ULONG nSubCondition; String* pFldExpression; } aSubCondition; public: TYPEINFO(); //Bereits in Basisklasse Client drin. SwCollCondition( SwTxtFmtColl* pColl, ULONG nMasterCond, ULONG nSubCond = 0 ); SwCollCondition( SwTxtFmtColl* pColl, ULONG nMasterCond, const String& rSubExp ); virtual ~SwCollCondition(); // @@@ public copy ctor, but no copy assignment? SwCollCondition( const SwCollCondition& rCpy ); private: // @@@ public copy ctor, but no copy assignment? SwCollCondition & operator= (const SwCollCondition &); public: int operator==( const SwCollCondition& rCmp ) const; int operator!=( const SwCollCondition& rCmp ) const { return ! (*this == rCmp); } ULONG GetCondition() const { return nCondition; } ULONG GetSubCondition() const { return aSubCondition.nSubCondition; } const String* GetFldExpression() const { return aSubCondition.pFldExpression; } void SetCondition( ULONG nCond, ULONG nSubCond ); SwTxtFmtColl* GetTxtFmtColl() const { return (SwTxtFmtColl*)GetRegisteredIn(); } }; typedef SwCollCondition* SwCollConditionPtr; SV_DECL_PTRARR_DEL( SwFmtCollConditions, SwCollConditionPtr, 0, 5 ) class SW_DLLPUBLIC SwConditionTxtFmtColl : public SwTxtFmtColl { friend class SwDoc; protected: SwFmtCollConditions aCondColls; SwConditionTxtFmtColl( SwAttrPool& rPool, const sal_Char* pFmtCollName, SwTxtFmtColl* pDerFrom = 0 ) : SwTxtFmtColl( rPool, pFmtCollName, pDerFrom, RES_CONDTXTFMTCOLL ) {} SwConditionTxtFmtColl( SwAttrPool& rPool, const String &rFmtCollName, SwTxtFmtColl* pDerFrom = 0 ) : SwTxtFmtColl( rPool, rFmtCollName, pDerFrom, RES_CONDTXTFMTCOLL ) {} public: TYPEINFO(); //Bereits in Basisklasse Client drin. virtual ~SwConditionTxtFmtColl(); // zum "abfischen" von Aenderungen // virtual void Modify( SfxPoolItem*, SfxPoolItem* ); const SwCollCondition* HasCondition( const SwCollCondition& rCond ) const; const SwFmtCollConditions& GetCondColls() const { return aCondColls; } void InsertCondition( const SwCollCondition& rCond ); BOOL RemoveCondition( const SwCollCondition& rCond ); void SetConditions( const SwFmtCollConditions& ); }; //FEATURE::CONDCOLL // ------------- Inline Implementierungen -------------------- inline void SwTxtFmtColl::SetNextTxtFmtColl( SwTxtFmtColl& rNext ) { pNextTxtFmtColl = &rNext; } #endif <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #ifndef PCL_FEATURES_IMPL_FEATURE_H_ #define PCL_FEATURES_IMPL_FEATURE_H_ #include <pcl/search/pcl_search.h> ////////////////////////////////////////////////////////////////////////////////////////////// inline void pcl::solvePlaneParameters (const Eigen::Matrix3f &covariance_matrix, const Eigen::Vector4f &point, Eigen::Vector4f &plane_parameters, float &curvature) { solvePlaneParameters (covariance_matrix, plane_parameters [0], plane_parameters [1], plane_parameters [2], curvature); plane_parameters[3] = 0; // Hessian form (D = nc . p_plane (centroid here) + p) plane_parameters[3] = -1 * plane_parameters.dot (point); } ////////////////////////////////////////////////////////////////////////////////////////////// inline void pcl::solvePlaneParameters (const Eigen::Matrix3f &covariance_matrix, float &nx, float &ny, float &nz, float &curvature) { // Avoid getting hung on Eigen's optimizers // for (int i = 0; i < 9; ++i) // if (!pcl_isfinite (covariance_matrix.coeff (i))) // { // //PCL_WARN ("[pcl::solvePlaneParameteres] Covariance matrix has NaN/Inf values!\n"); // nx = ny = nz = curvature = std::numeric_limits<float>::quiet_NaN (); // return; // } // Extract the smallest eigenvalue and its eigenvector EIGEN_ALIGN16 Eigen::Vector3f::Scalar eigen_value = -1; EIGEN_ALIGN16 Eigen::Vector3f eigen_vector; pcl::eigen33 (covariance_matrix, eigen_value, eigen_vector); nx = eigen_vector [0]; ny = eigen_vector [1]; nz = eigen_vector [2]; // Compute the curvature surface change float eig_sum = covariance_matrix.coeff (0) + covariance_matrix.coeff (4) + covariance_matrix.coeff (8); if (eig_sum != 0) curvature = fabs ( eigen_value / eig_sum ); else curvature = 0; } ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointOutT> bool pcl::Feature<PointInT, PointOutT>::initCompute () { if (!PCLBase<PointInT>::initCompute ()) { PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ()); return (false); } // If the dataset is empty, just return if (input_->points.empty ()) { PCL_ERROR ("[pcl::%s::compute] input_ is empty!\n", getClassName ().c_str ()); // Cleanup deinitCompute (); return (false); } // If no search surface has been defined, use the input dataset as the search surface itself if (!surface_) { fake_surface_ = true; surface_ = input_; } // Check if a space search locator was given if (!tree_) { if (surface_->isOrganized () && input_->isOrganized ()) tree_.reset (new pcl::search::OrganizedNeighbor<PointInT> ()); else tree_.reset (new pcl::search::KdTree<PointInT> (false)); } // Send the surface dataset to the spatial locator tree_->setInputCloud (surface_); // Do a fast check to see if the search parameters are well defined if (search_radius_ != 0.0) { if (k_ != 0) { PCL_ERROR ("[pcl::%s::compute] ", getClassName ().c_str ()); PCL_ERROR ("Both radius (%f) and K (%d) defined! ", search_radius_, k_); PCL_ERROR ("Set one of them to zero first and then re-run compute ().\n"); // Cleanup deinitCompute (); return (false); } else // Use the radiusSearch () function { search_parameter_ = search_radius_; if (surface_ == input_) // if the two surfaces are the same { // Declare the search locator definition int (KdTree::*radiusSearch)(int index, double radius, std::vector<int> &k_indices, std::vector<float> &k_distances, unsigned int max_nn) const = &KdTree::radiusSearch; search_method_ = boost::bind (radiusSearch, boost::ref (tree_), _1, _2, _3, _4, 0); } // Declare the search locator definition int (KdTree::*radiusSearchSurface)(const PointCloudIn &cloud, int index, double radius, std::vector<int> &k_indices, std::vector<float> &k_distances, unsigned int max_nn) const = &pcl::search::Search<PointInT>::radiusSearch; search_method_surface_ = boost::bind (radiusSearchSurface, boost::ref (tree_), _1, _2, _3, _4, _5, 0); } } else { if (k_ != 0) // Use the nearestKSearch () function { search_parameter_ = k_; if (surface_ == input_) // if the two surfaces are the same { // Declare the search locator definition int (KdTree::*nearestKSearch)(int index, int k, std::vector<int> &k_indices, std::vector<float> &k_distances) const = &KdTree::nearestKSearch; search_method_ = boost::bind (nearestKSearch, boost::ref (tree_), _1, _2, _3, _4); } // Declare the search locator definition int (KdTree::*nearestKSearchSurface)(const PointCloudIn &cloud, int index, int k, std::vector<int> &k_indices, std::vector<float> &k_distances) const = &KdTree::nearestKSearch; search_method_surface_ = boost::bind (nearestKSearchSurface, boost::ref (tree_), _1, _2, _3, _4, _5); } else { PCL_ERROR ("[pcl::%s::compute] Neither radius nor K defined! ", getClassName ().c_str ()); PCL_ERROR ("Set one of them to a positive number first and then re-run compute ().\n"); // Cleanup deinitCompute (); return (false); } } return (true); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointOutT> bool pcl::Feature<PointInT, PointOutT>::deinitCompute () { // Reset the surface if (fake_surface_) { surface_.reset (); fake_surface_ = false; } return (true); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointOutT> void pcl::Feature<PointInT, PointOutT>::compute (PointCloudOut &output) { if (!initCompute ()) { output.width = output.height = 0; output.points.clear (); return; } // Copy the header output.header = input_->header; // Resize the output dataset if (output.points.size () != indices_->size ()) output.points.resize (indices_->size ()); // Check if the output will be computed for all points or only a subset if (indices_->size () != input_->points.size ()) { output.width = (int) indices_->size (); output.height = 1; } else { output.width = input_->width; output.height = input_->height; } output.is_dense = input_->is_dense; // Perform the actual feature computation computeFeature (output); deinitCompute (); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointOutT> void pcl::Feature<PointInT, PointOutT>::computeEigen (pcl::PointCloud<Eigen::MatrixXf> &output) { if (!initCompute ()) { output.width = output.height = 0; output.points.resize (0, 0); return; } // Copy the properties #ifndef USE_ROS output.properties.acquisition_time = input_->header.stamp; #endif output.properties.sensor_origin = input_->sensor_origin_; output.properties.sensor_orientation = input_->sensor_orientation_; // Check if the output will be computed for all points or only a subset if (indices_->size () != input_->points.size ()) { output.width = (int) indices_->size (); output.height = 1; } else { output.width = input_->width; output.height = input_->height; } output.is_dense = input_->is_dense; // Perform the actual feature computation computeFeatureEigen (output); deinitCompute (); } ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT, typename PointOutT> bool pcl::FeatureFromNormals<PointInT, PointNT, PointOutT>::initCompute () { if (!Feature<PointInT, PointOutT>::initCompute ()) { PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ()); return (false); } // Check if input normals are set if (!normals_) { PCL_ERROR ("[pcl::%s::initCompute] No input dataset containing normals was given!\n", getClassName ().c_str ()); Feature<PointInT, PointOutT>::deinitCompute (); return (false); } // Check if the size of normals is the same as the size of the surface if (normals_->points.size () != surface_->points.size ()) { PCL_ERROR ("[pcl::%s::initCompute] ", getClassName ().c_str ()); PCL_ERROR ("The number of points in the input dataset (%u) differs from ", surface_->points.size ()); PCL_ERROR ("the number of points in the dataset containing the normals (%u)!\n", normals_->points.size ()); Feature<PointInT, PointOutT>::deinitCompute (); return (false); } return (true); } ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointLT, typename PointOutT> bool pcl::FeatureFromLabels<PointInT, PointLT, PointOutT>::initCompute () { if (!Feature<PointInT, PointOutT>::initCompute ()) { PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ()); return (false); } // Check if input normals are set if (!labels_) { PCL_ERROR ("[pcl::%s::initCompute] No input dataset containing labels was given!\n", getClassName ().c_str ()); Feature<PointInT, PointOutT>::deinitCompute (); return (false); } // Check if the size of normals is the same as the size of the surface if (labels_->points.size () != surface_->points.size ()) { PCL_ERROR ("[pcl::%s::initCompute] The number of points in the input dataset differs from the number of points in the dataset containing the labels!\n", getClassName ().c_str ()); Feature<PointInT, PointOutT>::deinitCompute (); return (false); } return (true); } #endif //#ifndef PCL_FEATURES_IMPL_FEATURE_H_ <commit_msg>commented out time<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #ifndef PCL_FEATURES_IMPL_FEATURE_H_ #define PCL_FEATURES_IMPL_FEATURE_H_ #include <pcl/search/pcl_search.h> ////////////////////////////////////////////////////////////////////////////////////////////// inline void pcl::solvePlaneParameters (const Eigen::Matrix3f &covariance_matrix, const Eigen::Vector4f &point, Eigen::Vector4f &plane_parameters, float &curvature) { solvePlaneParameters (covariance_matrix, plane_parameters [0], plane_parameters [1], plane_parameters [2], curvature); plane_parameters[3] = 0; // Hessian form (D = nc . p_plane (centroid here) + p) plane_parameters[3] = -1 * plane_parameters.dot (point); } ////////////////////////////////////////////////////////////////////////////////////////////// inline void pcl::solvePlaneParameters (const Eigen::Matrix3f &covariance_matrix, float &nx, float &ny, float &nz, float &curvature) { // Avoid getting hung on Eigen's optimizers // for (int i = 0; i < 9; ++i) // if (!pcl_isfinite (covariance_matrix.coeff (i))) // { // //PCL_WARN ("[pcl::solvePlaneParameteres] Covariance matrix has NaN/Inf values!\n"); // nx = ny = nz = curvature = std::numeric_limits<float>::quiet_NaN (); // return; // } // Extract the smallest eigenvalue and its eigenvector EIGEN_ALIGN16 Eigen::Vector3f::Scalar eigen_value = -1; EIGEN_ALIGN16 Eigen::Vector3f eigen_vector; pcl::eigen33 (covariance_matrix, eigen_value, eigen_vector); nx = eigen_vector [0]; ny = eigen_vector [1]; nz = eigen_vector [2]; // Compute the curvature surface change float eig_sum = covariance_matrix.coeff (0) + covariance_matrix.coeff (4) + covariance_matrix.coeff (8); if (eig_sum != 0) curvature = fabs ( eigen_value / eig_sum ); else curvature = 0; } ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointOutT> bool pcl::Feature<PointInT, PointOutT>::initCompute () { if (!PCLBase<PointInT>::initCompute ()) { PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ()); return (false); } // If the dataset is empty, just return if (input_->points.empty ()) { PCL_ERROR ("[pcl::%s::compute] input_ is empty!\n", getClassName ().c_str ()); // Cleanup deinitCompute (); return (false); } // If no search surface has been defined, use the input dataset as the search surface itself if (!surface_) { fake_surface_ = true; surface_ = input_; } // Check if a space search locator was given if (!tree_) { if (surface_->isOrganized () && input_->isOrganized ()) tree_.reset (new pcl::search::OrganizedNeighbor<PointInT> ()); else tree_.reset (new pcl::search::KdTree<PointInT> (false)); } // Send the surface dataset to the spatial locator tree_->setInputCloud (surface_); // Do a fast check to see if the search parameters are well defined if (search_radius_ != 0.0) { if (k_ != 0) { PCL_ERROR ("[pcl::%s::compute] ", getClassName ().c_str ()); PCL_ERROR ("Both radius (%f) and K (%d) defined! ", search_radius_, k_); PCL_ERROR ("Set one of them to zero first and then re-run compute ().\n"); // Cleanup deinitCompute (); return (false); } else // Use the radiusSearch () function { search_parameter_ = search_radius_; if (surface_ == input_) // if the two surfaces are the same { // Declare the search locator definition int (KdTree::*radiusSearch)(int index, double radius, std::vector<int> &k_indices, std::vector<float> &k_distances, unsigned int max_nn) const = &KdTree::radiusSearch; search_method_ = boost::bind (radiusSearch, boost::ref (tree_), _1, _2, _3, _4, 0); } // Declare the search locator definition int (KdTree::*radiusSearchSurface)(const PointCloudIn &cloud, int index, double radius, std::vector<int> &k_indices, std::vector<float> &k_distances, unsigned int max_nn) const = &pcl::search::Search<PointInT>::radiusSearch; search_method_surface_ = boost::bind (radiusSearchSurface, boost::ref (tree_), _1, _2, _3, _4, _5, 0); } } else { if (k_ != 0) // Use the nearestKSearch () function { search_parameter_ = k_; if (surface_ == input_) // if the two surfaces are the same { // Declare the search locator definition int (KdTree::*nearestKSearch)(int index, int k, std::vector<int> &k_indices, std::vector<float> &k_distances) const = &KdTree::nearestKSearch; search_method_ = boost::bind (nearestKSearch, boost::ref (tree_), _1, _2, _3, _4); } // Declare the search locator definition int (KdTree::*nearestKSearchSurface)(const PointCloudIn &cloud, int index, int k, std::vector<int> &k_indices, std::vector<float> &k_distances) const = &KdTree::nearestKSearch; search_method_surface_ = boost::bind (nearestKSearchSurface, boost::ref (tree_), _1, _2, _3, _4, _5); } else { PCL_ERROR ("[pcl::%s::compute] Neither radius nor K defined! ", getClassName ().c_str ()); PCL_ERROR ("Set one of them to a positive number first and then re-run compute ().\n"); // Cleanup deinitCompute (); return (false); } } return (true); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointOutT> bool pcl::Feature<PointInT, PointOutT>::deinitCompute () { // Reset the surface if (fake_surface_) { surface_.reset (); fake_surface_ = false; } return (true); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointOutT> void pcl::Feature<PointInT, PointOutT>::compute (PointCloudOut &output) { if (!initCompute ()) { output.width = output.height = 0; output.points.clear (); return; } // Copy the header output.header = input_->header; // Resize the output dataset if (output.points.size () != indices_->size ()) output.points.resize (indices_->size ()); // Check if the output will be computed for all points or only a subset if (indices_->size () != input_->points.size ()) { output.width = (int) indices_->size (); output.height = 1; } else { output.width = input_->width; output.height = input_->height; } output.is_dense = input_->is_dense; // Perform the actual feature computation computeFeature (output); deinitCompute (); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointOutT> void pcl::Feature<PointInT, PointOutT>::computeEigen (pcl::PointCloud<Eigen::MatrixXf> &output) { if (!initCompute ()) { output.width = output.height = 0; output.points.resize (0, 0); return; } // Copy the properties //#ifndef USE_ROS // output.properties.acquisition_time = input_->header.stamp; //#endif output.properties.sensor_origin = input_->sensor_origin_; output.properties.sensor_orientation = input_->sensor_orientation_; // Check if the output will be computed for all points or only a subset if (indices_->size () != input_->points.size ()) { output.width = (int) indices_->size (); output.height = 1; } else { output.width = input_->width; output.height = input_->height; } output.is_dense = input_->is_dense; // Perform the actual feature computation computeFeatureEigen (output); deinitCompute (); } ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT, typename PointOutT> bool pcl::FeatureFromNormals<PointInT, PointNT, PointOutT>::initCompute () { if (!Feature<PointInT, PointOutT>::initCompute ()) { PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ()); return (false); } // Check if input normals are set if (!normals_) { PCL_ERROR ("[pcl::%s::initCompute] No input dataset containing normals was given!\n", getClassName ().c_str ()); Feature<PointInT, PointOutT>::deinitCompute (); return (false); } // Check if the size of normals is the same as the size of the surface if (normals_->points.size () != surface_->points.size ()) { PCL_ERROR ("[pcl::%s::initCompute] ", getClassName ().c_str ()); PCL_ERROR ("The number of points in the input dataset (%u) differs from ", surface_->points.size ()); PCL_ERROR ("the number of points in the dataset containing the normals (%u)!\n", normals_->points.size ()); Feature<PointInT, PointOutT>::deinitCompute (); return (false); } return (true); } ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointLT, typename PointOutT> bool pcl::FeatureFromLabels<PointInT, PointLT, PointOutT>::initCompute () { if (!Feature<PointInT, PointOutT>::initCompute ()) { PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ()); return (false); } // Check if input normals are set if (!labels_) { PCL_ERROR ("[pcl::%s::initCompute] No input dataset containing labels was given!\n", getClassName ().c_str ()); Feature<PointInT, PointOutT>::deinitCompute (); return (false); } // Check if the size of normals is the same as the size of the surface if (labels_->points.size () != surface_->points.size ()) { PCL_ERROR ("[pcl::%s::initCompute] The number of points in the input dataset differs from the number of points in the dataset containing the labels!\n", getClassName ().c_str ()); Feature<PointInT, PointOutT>::deinitCompute (); return (false); } return (true); } #endif //#ifndef PCL_FEATURES_IMPL_FEATURE_H_ <|endoftext|>
<commit_before>#include <fstream> #include <string> #include <string.h> #include <iostream> #include "io.hh" #include "conf.hh" #include "HmmSet.hh" #include "Distributions.hh" int main(int argc, char *argv[]) { conf::Config config; HmmSet first_model; HmmSet second_model; try { config("usage: cmpmodel [OPTION...]\n") ('h', "help", "", "", "display help") ('\0', "base1=BASENAME", "arg", "", "base filename for the first model") ('\0', "gk1=FILE", "arg", "", "Mixture base distributions for the first model") ('\0', "mc1=FILE", "arg", "", "Mixture coefficients for the states of the first model") ('\0', "ph1=FILE", "arg", "", "HMM definitions for the first model") ('\0', "base2=BASENAME", "arg", "", "base filename for the second model") ('\0', "gk2=FILE", "arg", "", "Mixture base distributions for the second model") ('\0', "mc2=FILE", "arg", "", "Mixture coefficients for the states of the second model") ('\0', "ph2=FILE", "arg", "", "HMM definitions for the second model") ('k', "kl", "", "", "Kullback-Leibler divergence from the first to the second model") ('s', "skl", "", "", "Symmetrized Kullback-Leibler divergence") ('i', "info=INT", "arg", "0", "info level") ; config.default_parse(argc, argv); // Initialize the HMM model if (config["info"].get_int()) std::cout << "Loading HMMs\n"; // Sanity check if (!(config["kl"].specified || config["skl"].specified)) throw std::string("Must give either --kl or --skl (or both)"); // Load the first model if (config["base1"].specified) first_model.read_all(config["base1"].get_str()); else if (config["gk1"].specified && config["mc1"].specified && config["ph1"].specified) { first_model.read_gk(config["gk1"].get_str()); first_model.read_mc(config["mc1"].get_str()); first_model.read_ph(config["ph1"].get_str()); } else throw std::string("Must give either --base1 or all --gk1, --mc1 and --ph1"); // Load the second model if (config["base2"].specified) second_model.read_all(config["base2"].get_str()); else if (config["gk2"].specified && config["mc2"].specified && config["ph2"].specified) { second_model.read_gk(config["gk2"].get_str()); second_model.read_mc(config["mc2"].get_str()); second_model.read_ph(config["ph2"].get_str()); } else throw std::string("Must give either --base2 or all --gk2, --mc2 and --ph2"); // Model similarity check if (first_model.num_states() != second_model.num_states()) throw std::string("Both models should have the same number of states"); // Compute Kullback-Leiblers double kl=0; for (int i=0; i<first_model.num_states(); i++) { HmmState &first_model_state = first_model.state(i); Mixture *first_model_mixture = first_model.get_emission_pdf(first_model_state.emission_pdf); HmmState &second_model_state = second_model.state(i); Mixture *second_model_mixture = second_model.get_emission_pdf(second_model_state.emission_pdf); if (config["kl"].specified) { kl = first_model_mixture->kullback_leibler(*second_model_mixture, 10000); std::cout << "kl-divergence, state " << i << ": " << kl << std::endl; } if (config["skl"].specified) { kl += second_model_mixture->kullback_leibler(*first_model_mixture, 10000); std::cout << "symmetric kl-divergence, state " << i << ": " << kl << std::endl; } } } // Handle errors catch (HmmSet::UnknownHmm &e) { fprintf(stderr, "Unknown HMM in transcription, " "writing incompletely taught models\n"); abort(); } catch (std::exception &e) { fprintf(stderr, "exception: %s\n", e.what()); abort(); } catch (std::string &str) { fprintf(stderr, "exception: %s\n", str.c_str()); abort(); } } <commit_msg>small fix<commit_after>#include <fstream> #include <string> #include <string.h> #include <iostream> #include "io.hh" #include "conf.hh" #include "HmmSet.hh" #include "Distributions.hh" int main(int argc, char *argv[]) { conf::Config config; HmmSet first_model; HmmSet second_model; try { config("usage: cmpmodel [OPTION...]\n") ('h', "help", "", "", "display help") ('\0', "base1=BASENAME", "arg", "", "base filename for the first model") ('\0', "gk1=FILE", "arg", "", "Mixture base distributions for the first model") ('\0', "mc1=FILE", "arg", "", "Mixture coefficients for the states of the first model") ('\0', "ph1=FILE", "arg", "", "HMM definitions for the first model") ('\0', "base2=BASENAME", "arg", "", "base filename for the second model") ('\0', "gk2=FILE", "arg", "", "Mixture base distributions for the second model") ('\0', "mc2=FILE", "arg", "", "Mixture coefficients for the states of the second model") ('\0', "ph2=FILE", "arg", "", "HMM definitions for the second model") ('k', "kl", "", "", "Kullback-Leibler divergence from the first to the second model") ('s', "skl", "", "", "Symmetrized Kullback-Leibler divergence") ('i', "info=INT", "arg", "0", "info level") ; config.default_parse(argc, argv); // Initialize the HMM model if (config["info"].get_int()) std::cout << "Loading HMMs\n"; // Sanity check if (!(config["kl"].specified || config["skl"].specified)) throw std::string("Must give either --kl or --skl (or both)"); // Load the first model if (config["base1"].specified) first_model.read_all(config["base1"].get_str()); else if (config["gk1"].specified && config["mc1"].specified && config["ph1"].specified) { first_model.read_gk(config["gk1"].get_str()); first_model.read_mc(config["mc1"].get_str()); first_model.read_ph(config["ph1"].get_str()); } else throw std::string("Must give either --base1 or all --gk1, --mc1 and --ph1"); // Load the second model if (config["base2"].specified) second_model.read_all(config["base2"].get_str()); else if (config["gk2"].specified && config["mc2"].specified && config["ph2"].specified) { second_model.read_gk(config["gk2"].get_str()); second_model.read_mc(config["mc2"].get_str()); second_model.read_ph(config["ph2"].get_str()); } else throw std::string("Must give either --base2 or all --gk2, --mc2 and --ph2"); // Model similarity check if (first_model.num_states() != second_model.num_states()) throw std::string("Both models should have the same number of states"); // Compute Kullback-Leiblers double kl=0; for (int i=0; i<first_model.num_states(); i++) { HmmState &first_model_state = first_model.state(i); Mixture *first_model_mixture = first_model.get_emission_pdf(first_model_state.emission_pdf); HmmState &second_model_state = second_model.state(i); Mixture *second_model_mixture = second_model.get_emission_pdf(second_model_state.emission_pdf); kl = first_model_mixture->kullback_leibler(*second_model_mixture, 10000); if (config["kl"].specified) std::cout << "kl-divergence, state " << i << ": " << kl << std::endl; if (config["skl"].specified) { kl += second_model_mixture->kullback_leibler(*first_model_mixture, 10000); std::cout << "symmetric kl-divergence, state " << i << ": " << kl << std::endl; } } } // Handle errors catch (HmmSet::UnknownHmm &e) { fprintf(stderr, "Unknown HMM in transcription, " "writing incompletely taught models\n"); abort(); } catch (std::exception &e) { fprintf(stderr, "exception: %s\n", e.what()); abort(); } catch (std::string &str) { fprintf(stderr, "exception: %s\n", str.c_str()); abort(); } } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Baozeng Ding <[email protected]> // author: Vassil Vassilev <[email protected]> //------------------------------------------------------------------------------ #include "ASTNullDerefProtection.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/Mangle.h" #include "clang/Basic/SourceLocation.h" #include "clang/Sema/Lookup.h" using namespace clang; namespace cling { ASTNullDerefProtection::ASTNullDerefProtection(clang::Sema* S) : TransactionTransformer(S) { } ASTNullDerefProtection::~ASTNullDerefProtection() { } bool ASTNullDerefProtection::isDeclCandidate(FunctionDecl * FDecl) { if(m_NonNullArgIndexs.count(FDecl)) return true; std::bitset<32> ArgIndexs; for (specific_attr_iterator<NonNullAttr> I = FDecl->specific_attr_begin<NonNullAttr>(), E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) { NonNullAttr *NonNull = *I; for (NonNullAttr::args_iterator i = NonNull->args_begin(), e = NonNull->args_end(); i != e; ++i) { ArgIndexs.set(*i); } } if (ArgIndexs.any()) { m_NonNullArgIndexs.insert(std::make_pair(FDecl, ArgIndexs)); return true; } return false; } Stmt* ASTNullDerefProtection::SynthesizeCheck(SourceLocation Loc, Expr* Arg ){ ASTContext& Context = m_Sema->getASTContext(); Scope* S = m_Sema->getScopeForContext(m_Sema->CurContext); //copied from DynamicLookup.cpp NamespaceDecl* NSD = utils::Lookup::Namespace(m_Sema, "cling"); NamespaceDecl* clingRuntimeNSD = utils::Lookup::Namespace(m_Sema, "runtime", NSD); // Find and set up "NullDerefException" DeclarationName Name = &Context.Idents.get("NullDerefException"); LookupResult R(*m_Sema, Name, SourceLocation(), Sema::LookupOrdinaryName, Sema::ForRedeclaration); m_Sema->LookupQualifiedName(R, clingRuntimeNSD); CXXRecordDecl* NullDerefDecl = R.getAsSingle<CXXRecordDecl>(); // Lookup Sema type CXXRecordDecl* SemaRD = dyn_cast<CXXRecordDecl>(utils::Lookup::Named(m_Sema, "Sema", utils::Lookup::Namespace(m_Sema, "clang"))); QualType SemaRDTy = Context.getTypeDeclType(SemaRD); Expr* VoidSemaArg = utils::Synthesize::CStyleCastPtrExpr(m_Sema, SemaRDTy, (uint64_t)m_Sema); // Lookup Expr type CXXRecordDecl* ExprRD = dyn_cast<CXXRecordDecl>(utils::Lookup::Named(m_Sema, "Expr", utils::Lookup::Namespace(m_Sema, "clang"))); QualType ExprRDTy = Context.getTypeDeclType(ExprRD); Expr* VoidExprArg = utils::Synthesize::CStyleCastPtrExpr(m_Sema, ExprRDTy, (uint64_t)Arg); Expr *args[] = {VoidSemaArg, VoidExprArg}; QualType NullDerefDeclTy = Context.getTypeDeclType(NullDerefDecl); TypeSourceInfo* TSI = Context.getTrivialTypeSourceInfo(NullDerefDeclTy, SourceLocation()); ExprResult ConstructorCall = m_Sema->BuildCXXTypeConstructExpr(TSI,Loc, MultiExprArg(args, 2),Loc); Expr* Throw = m_Sema->ActOnCXXThrow(S, Loc, ConstructorCall.take()).take(); // Check whether we can get the argument'value. If the argument is // null, throw an exception direclty. If the argument is not null // then ignore this argument and continue to deal with the next // argument with the nonnull attribute. bool Result = false; if (Arg->EvaluateAsBooleanCondition(Result, Context)) { if(!Result) { return Throw; } return Arg; } // The argument's value cannot be decided, so we add a UnaryOp // operation to check its value at runtime. DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreImpCasts()); assert(DRE && "No declref expr?"); ExprResult ER = m_Sema->ActOnUnaryOp(S, Loc, tok::exclaim, DRE); Decl* varDecl = 0; Stmt* varStmt = 0; Sema::FullExprArg FullCond(m_Sema->MakeFullExpr(ER.take())); StmtResult IfStmt = m_Sema->ActOnIfStmt(Loc, FullCond, varDecl, Throw, Loc, varStmt); return IfStmt.take(); } void ASTNullDerefProtection::Transform() { FunctionDecl* FD = getTransaction()->getWrapperFD(); if (!FD) return; CompoundStmt* CS = dyn_cast<CompoundStmt>(FD->getBody()); assert(CS && "Function body not a CompundStmt?"); Scope* S = m_Sema->getScopeForContext(m_Sema->CurContext); ASTContext* Context = &m_Sema->getASTContext(); DeclContext* DC = FD->getTranslationUnitDecl(); llvm::SmallVector<Stmt*, 4> Stmts; SourceLocation Loc = FD->getBody()->getLocStart(); for (CompoundStmt::body_iterator I = CS->body_begin(), EI = CS->body_end(); I != EI; ++I) { CallExpr* CE = dyn_cast<CallExpr>(*I); if (CE) { if (FunctionDecl* FDecl = CE->getDirectCallee()) { if(FDecl && isDeclCandidate(FDecl)) { SourceLocation CallLoc = CE->getLocStart(); decl_map_t::const_iterator it = m_NonNullArgIndexs.find(FDecl); const std::bitset<32>& ArgIndexs = it->second; Sema::ContextRAII pushedDC(*m_Sema, FDecl); for (int index = 0; index < 32; ++index) { if (!ArgIndexs.test(index)) continue; // Get the argument with the nonnull attribute. Expr* Arg = CE->getArg(index); Stmts.push_back(SynthesizeCheck(CallLoc, Arg)); } } } //Stmts.push_back(CE); } else { if (BinaryOperator* BinOp = dyn_cast<BinaryOperator>(*I)) { SourceLocation SL = BinOp->getLocStart(); Expr* LHS = BinOp->getLHS()->IgnoreImpCasts(); Expr* RHS = BinOp->getRHS()->IgnoreImpCasts(); UnaryOperator* LUO = dyn_cast<UnaryOperator>(LHS); UnaryOperator* RUO = dyn_cast<UnaryOperator>(RHS); if (LUO && LUO->getOpcode() == UO_Deref) { Expr* Op = dyn_cast<DeclRefExpr>(LUO->getSubExpr()->IgnoreImpCasts()); if (Op) { bool Result = false; if (Op->EvaluateAsBooleanCondition(Result, *Context)) { if(!Result) { Expr* Throw = InsertThrow(&SL, Op); Stmts.push_back(Throw); } } else { Stmts.push_back(SynthesizeCheck(SL, Op)); } } } if (RUO && RUO->getOpcode() == UO_Deref) { Expr* Op = dyn_cast<DeclRefExpr>(RUO->getSubExpr()->IgnoreImpCasts()); if (Op) { bool Result = false; if (Op->EvaluateAsBooleanCondition(Result, *Context)) { if(!Result) { Expr* Throw = InsertThrow(&SL, Op); Stmts.push_back(Throw); } } else { Stmts.push_back(SynthesizeCheck(SL, Op)); } } } } } Stmts.push_back(*I); } llvm::ArrayRef<Stmt*> StmtsRef(Stmts.data(), Stmts.size()); CompoundStmt* CSBody = new (*Context)CompoundStmt(*Context, StmtsRef, Loc, Loc); FD->setBody(CSBody); DC->removeDecl(FD); DC->addDecl(FD); } } // end namespace cling <commit_msg>Use the correct routine.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Baozeng Ding <[email protected]> // author: Vassil Vassilev <[email protected]> //------------------------------------------------------------------------------ #include "ASTNullDerefProtection.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/Mangle.h" #include "clang/Basic/SourceLocation.h" #include "clang/Sema/Lookup.h" using namespace clang; namespace cling { ASTNullDerefProtection::ASTNullDerefProtection(clang::Sema* S) : TransactionTransformer(S) { } ASTNullDerefProtection::~ASTNullDerefProtection() { } bool ASTNullDerefProtection::isDeclCandidate(FunctionDecl * FDecl) { if(m_NonNullArgIndexs.count(FDecl)) return true; std::bitset<32> ArgIndexs; for (specific_attr_iterator<NonNullAttr> I = FDecl->specific_attr_begin<NonNullAttr>(), E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) { NonNullAttr *NonNull = *I; for (NonNullAttr::args_iterator i = NonNull->args_begin(), e = NonNull->args_end(); i != e; ++i) { ArgIndexs.set(*i); } } if (ArgIndexs.any()) { m_NonNullArgIndexs.insert(std::make_pair(FDecl, ArgIndexs)); return true; } return false; } Stmt* ASTNullDerefProtection::SynthesizeCheck(SourceLocation Loc, Expr* Arg ){ ASTContext& Context = m_Sema->getASTContext(); Scope* S = m_Sema->getScopeForContext(m_Sema->CurContext); //copied from DynamicLookup.cpp NamespaceDecl* NSD = utils::Lookup::Namespace(m_Sema, "cling"); NamespaceDecl* clingRuntimeNSD = utils::Lookup::Namespace(m_Sema, "runtime", NSD); // Find and set up "NullDerefException" DeclarationName Name = &Context.Idents.get("NullDerefException"); LookupResult R(*m_Sema, Name, SourceLocation(), Sema::LookupOrdinaryName, Sema::ForRedeclaration); m_Sema->LookupQualifiedName(R, clingRuntimeNSD); CXXRecordDecl* NullDerefDecl = R.getAsSingle<CXXRecordDecl>(); // Lookup Sema type CXXRecordDecl* SemaRD = dyn_cast<CXXRecordDecl>(utils::Lookup::Named(m_Sema, "Sema", utils::Lookup::Namespace(m_Sema, "clang"))); QualType SemaRDTy = Context.getTypeDeclType(SemaRD); Expr* VoidSemaArg = utils::Synthesize::CStyleCastPtrExpr(m_Sema, SemaRDTy, (uint64_t)m_Sema); // Lookup Expr type CXXRecordDecl* ExprRD = dyn_cast<CXXRecordDecl>(utils::Lookup::Named(m_Sema, "Expr", utils::Lookup::Namespace(m_Sema, "clang"))); QualType ExprRDTy = Context.getTypeDeclType(ExprRD); Expr* VoidExprArg = utils::Synthesize::CStyleCastPtrExpr(m_Sema, ExprRDTy, (uint64_t)Arg); Expr *args[] = {VoidSemaArg, VoidExprArg}; QualType NullDerefDeclTy = Context.getTypeDeclType(NullDerefDecl); TypeSourceInfo* TSI = Context.getTrivialTypeSourceInfo(NullDerefDeclTy, SourceLocation()); ExprResult ConstructorCall = m_Sema->BuildCXXTypeConstructExpr(TSI,Loc, MultiExprArg(args, 2),Loc); Expr* Throw = m_Sema->ActOnCXXThrow(S, Loc, ConstructorCall.take()).take(); // Check whether we can get the argument'value. If the argument is // null, throw an exception direclty. If the argument is not null // then ignore this argument and continue to deal with the next // argument with the nonnull attribute. bool Result = false; if (Arg->EvaluateAsBooleanCondition(Result, Context)) { if(!Result) { return Throw; } return Arg; } // The argument's value cannot be decided, so we add a UnaryOp // operation to check its value at runtime. DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreImpCasts()); assert(DRE && "No declref expr?"); ExprResult ER = m_Sema->ActOnUnaryOp(S, Loc, tok::exclaim, DRE); Decl* varDecl = 0; Stmt* varStmt = 0; Sema::FullExprArg FullCond(m_Sema->MakeFullExpr(ER.take())); StmtResult IfStmt = m_Sema->ActOnIfStmt(Loc, FullCond, varDecl, Throw, Loc, varStmt); return IfStmt.take(); } void ASTNullDerefProtection::Transform() { FunctionDecl* FD = getTransaction()->getWrapperFD(); if (!FD) return; CompoundStmt* CS = dyn_cast<CompoundStmt>(FD->getBody()); assert(CS && "Function body not a CompundStmt?"); Scope* S = m_Sema->getScopeForContext(m_Sema->CurContext); ASTContext* Context = &m_Sema->getASTContext(); DeclContext* DC = FD->getTranslationUnitDecl(); llvm::SmallVector<Stmt*, 4> Stmts; SourceLocation Loc = FD->getBody()->getLocStart(); for (CompoundStmt::body_iterator I = CS->body_begin(), EI = CS->body_end(); I != EI; ++I) { CallExpr* CE = dyn_cast<CallExpr>(*I); if (CE) { if (FunctionDecl* FDecl = CE->getDirectCallee()) { if(FDecl && isDeclCandidate(FDecl)) { SourceLocation CallLoc = CE->getLocStart(); decl_map_t::const_iterator it = m_NonNullArgIndexs.find(FDecl); const std::bitset<32>& ArgIndexs = it->second; Sema::ContextRAII pushedDC(*m_Sema, FDecl); for (int index = 0; index < 32; ++index) { if (!ArgIndexs.test(index)) continue; // Get the argument with the nonnull attribute. Expr* Arg = CE->getArg(index); Stmts.push_back(SynthesizeCheck(CallLoc, Arg)); } } } //Stmts.push_back(CE); } else { if (BinaryOperator* BinOp = dyn_cast<BinaryOperator>(*I)) { SourceLocation SL = BinOp->getLocStart(); Expr* LHS = BinOp->getLHS()->IgnoreImpCasts(); Expr* RHS = BinOp->getRHS()->IgnoreImpCasts(); UnaryOperator* LUO = dyn_cast<UnaryOperator>(LHS); UnaryOperator* RUO = dyn_cast<UnaryOperator>(RHS); if (LUO && LUO->getOpcode() == UO_Deref) { Expr* Op = dyn_cast<DeclRefExpr>(LUO->getSubExpr()->IgnoreImpCasts()); if (Op) { bool Result = false; if (Op->EvaluateAsBooleanCondition(Result, *Context)) { if(!Result) { Stmts.push_back(SynthesizeCheck(SL, Op)); } } else { Stmts.push_back(SynthesizeCheck(SL, Op)); } } } if (RUO && RUO->getOpcode() == UO_Deref) { Expr* Op = dyn_cast<DeclRefExpr>(RUO->getSubExpr()->IgnoreImpCasts()); if (Op) { bool Result = false; if (Op->EvaluateAsBooleanCondition(Result, *Context)) { if(!Result) { Stmts.push_back(SynthesizeCheck(SL, Op)); } } else { Stmts.push_back(SynthesizeCheck(SL, Op)); } } } } } Stmts.push_back(*I); } llvm::ArrayRef<Stmt*> StmtsRef(Stmts.data(), Stmts.size()); CompoundStmt* CSBody = new (*Context)CompoundStmt(*Context, StmtsRef, Loc, Loc); FD->setBody(CSBody); DC->removeDecl(FD); DC->addDecl(FD); } } // end namespace cling <|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXQt - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2010-2011 Razor team * Authors: * Petr Vanek <[email protected]> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "iconthemeconfig.h" #include <LXQt/Settings> #include <QStringList> #include <QStringBuilder> #include <QIcon> IconThemeConfig::IconThemeConfig(LXQt::Settings* settings, QWidget* parent): QWidget(parent), m_settings(settings) { setupUi(this); initIconsThemes(); initControls(); connect(iconThemeList, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(iconThemeSelected(QTreeWidgetItem*,int))); connect(iconFollowColorSchemeCB, &QAbstractButton::toggled, this, [this] (bool checked) { m_settings->setValue("icon_follow_color_scheme", checked); }); } void IconThemeConfig::initIconsThemes() { QStringList processed; const QStringList baseDirs = QIcon::themeSearchPaths(); static const QStringList iconNames = QStringList() << QStringLiteral("document-open") << QStringLiteral("document-new") << QStringLiteral("edit-undo") << QStringLiteral("media-playback-start"); const int iconNamesN = iconNames.size(); iconThemeList->setColumnCount(iconNamesN + 2); QList<QTreeWidgetItem *> items; foreach (const QString &baseDirName, baseDirs) { QDir baseDir(baseDirName); if (!baseDir.exists()) continue; const QFileInfoList dirs = baseDir.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name); foreach (const QFileInfo &dir, dirs) { if (!processed.contains(dir.canonicalFilePath())) { processed << dir.canonicalFilePath(); IconThemeInfo theme(QDir(dir.canonicalFilePath())); if (theme.isValid() && (!theme.isHidden())) { QTreeWidgetItem *item = new QTreeWidgetItem((QTreeWidget*)0); item->setSizeHint(0, QSize(42,42)); // make icons non-cropped item->setData(0, Qt::UserRole, theme.name()); const QVector<QIcon> icons = theme.icons(iconNames); const int K = icons.size(); for (int i = 0; i < K; ++i) { item->setIcon(i, icons.at(i)); } QString themeDescription; if (theme.comment().isEmpty()) { themeDescription = theme.text(); } else { themeDescription = theme.text() % QStringLiteral(" (") % theme.comment() % QStringLiteral(")"); } item->setText(iconNamesN + 1, themeDescription); items.append(item); } } } } iconThemeList->insertTopLevelItems(0, items); for (int i=0; i<iconThemeList->header()->count()-1; ++i) { iconThemeList->resizeColumnToContents(i); } } void IconThemeConfig::initControls() { QString currentTheme = QIcon::themeName(); QTreeWidgetItemIterator it(iconThemeList); while (*it) { if ((*it)->data(0, Qt::UserRole).toString() == currentTheme) { iconThemeList->setCurrentItem((*it)); break; } ++it; } iconFollowColorSchemeCB->setChecked(m_settings->value("icon_follow_color_theme", true).toBool()); update(); } IconThemeConfig::~IconThemeConfig() { } void IconThemeConfig::iconThemeSelected(QTreeWidgetItem *item, int column) { Q_UNUSED(column); const QString theme = item->data(0, Qt::UserRole).toString(); if (!theme.isEmpty()) { // Ensure that this widget also updates it's own icons QIcon::setThemeName(theme); m_settings->setValue("icon_theme", theme); m_settings->sync(); } } <commit_msg>appearance: Fix typo from @aca544479<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXQt - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2010-2011 Razor team * Authors: * Petr Vanek <[email protected]> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "iconthemeconfig.h" #include <LXQt/Settings> #include <QStringList> #include <QStringBuilder> #include <QIcon> IconThemeConfig::IconThemeConfig(LXQt::Settings* settings, QWidget* parent): QWidget(parent), m_settings(settings) { setupUi(this); initIconsThemes(); initControls(); connect(iconThemeList, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(iconThemeSelected(QTreeWidgetItem*,int))); connect(iconFollowColorSchemeCB, &QAbstractButton::toggled, this, [this] (bool checked) { m_settings->setValue("icon_follow_color_scheme", checked); }); } void IconThemeConfig::initIconsThemes() { QStringList processed; const QStringList baseDirs = QIcon::themeSearchPaths(); static const QStringList iconNames = QStringList() << QStringLiteral("document-open") << QStringLiteral("document-new") << QStringLiteral("edit-undo") << QStringLiteral("media-playback-start"); const int iconNamesN = iconNames.size(); iconThemeList->setColumnCount(iconNamesN + 2); QList<QTreeWidgetItem *> items; foreach (const QString &baseDirName, baseDirs) { QDir baseDir(baseDirName); if (!baseDir.exists()) continue; const QFileInfoList dirs = baseDir.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name); foreach (const QFileInfo &dir, dirs) { if (!processed.contains(dir.canonicalFilePath())) { processed << dir.canonicalFilePath(); IconThemeInfo theme(QDir(dir.canonicalFilePath())); if (theme.isValid() && (!theme.isHidden())) { QTreeWidgetItem *item = new QTreeWidgetItem((QTreeWidget*)0); item->setSizeHint(0, QSize(42,42)); // make icons non-cropped item->setData(0, Qt::UserRole, theme.name()); const QVector<QIcon> icons = theme.icons(iconNames); const int K = icons.size(); for (int i = 0; i < K; ++i) { item->setIcon(i, icons.at(i)); } QString themeDescription; if (theme.comment().isEmpty()) { themeDescription = theme.text(); } else { themeDescription = theme.text() % QStringLiteral(" (") % theme.comment() % QStringLiteral(")"); } item->setText(iconNamesN + 1, themeDescription); items.append(item); } } } } iconThemeList->insertTopLevelItems(0, items); for (int i=0; i<iconThemeList->header()->count()-1; ++i) { iconThemeList->resizeColumnToContents(i); } } void IconThemeConfig::initControls() { QString currentTheme = QIcon::themeName(); QTreeWidgetItemIterator it(iconThemeList); while (*it) { if ((*it)->data(0, Qt::UserRole).toString() == currentTheme) { iconThemeList->setCurrentItem((*it)); break; } ++it; } iconFollowColorSchemeCB->setChecked(m_settings->value("icon_follow_color_scheme", true).toBool()); update(); } IconThemeConfig::~IconThemeConfig() { } void IconThemeConfig::iconThemeSelected(QTreeWidgetItem *item, int column) { Q_UNUSED(column); const QString theme = item->data(0, Qt::UserRole).toString(); if (!theme.isEmpty()) { // Ensure that this widget also updates it's own icons QIcon::setThemeName(theme); m_settings->setValue("icon_theme", theme); m_settings->sync(); } } <|endoftext|>
<commit_before>/******************************************************************************\ * File: vcs.cpp * Purpose: Implementation of wxExVCS class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/config.h> #include <wx/extension/vcs.h> #include <wx/extension/configdlg.h> #include <wx/extension/defs.h> #include <wx/extension/frame.h> #include <wx/extension/log.h> #include <wx/extension/stcdlg.h> #include <wx/extension/util.h> wxExVCS* wxExVCS::m_Self = NULL; #if wxUSE_GUI wxExSTCEntryDialog* wxExVCS::m_STCEntryDialog = NULL; #endif wxExVCS::wxExVCS() : m_Command(VCS_NO_COMMAND) , m_FileName(wxExFileName()) { Initialize(); } wxExVCS::wxExVCS(int command_id, const wxExFileName& filename) : m_Command(GetType(command_id)) , m_FileName(filename) { Initialize(); } wxExVCS::wxExVCS(wxExCommand type, const wxExFileName& filename) : m_Command(type) , m_FileName(filename) { Initialize(); } bool wxExVCS::CheckVCS(const wxFileName& fn) const { // these cannot be combined, as AppendDir is a void (2.9.1). wxFileName path(filename); path.AppendDir(".svn"); return path.DirExists(); } bool wxExVCS::CheckGIT(const wxFileName& fn) const { // The .git dir only exists in the root, so check all components. wxFileName root(filename.GetPath()); while (root.DirExists() && root.GetDirCount() > 0) { wxFileName path(root); path.AppendDir(".git"); if (path.DirExists()) { return true; } root.RemoveLastDir(); } return false; } #if wxUSE_GUI int wxExVCS::ConfigDialog( wxWindow* parent, const wxString& title) const { std::vector<wxExConfigItem> v; std::map<long, const wxString> choices; choices.insert(std::make_pair(VCS_NONE, _("None"))); choices.insert(std::make_pair(VCS_GIT, "GIT")); choices.insert(std::make_pair(VCS_SVN, "SVN")); choices.insert(std::make_pair(VCS_AUTO, "Auto")); v.push_back(wxExConfigItem("VCS", choices)); v.push_back(wxExConfigItem("GIT", CONFIG_FILEPICKERCTRL)); v.push_back(wxExConfigItem("SVN", CONFIG_FILEPICKERCTRL)); v.push_back(wxExConfigItem(_("Comparator"), CONFIG_FILEPICKERCTRL)); return wxExConfigDialog(parent, v, title).ShowModal(); } #endif bool wxExVCS::DirExists(const wxFileName& filename) const { switch (GetVCS()) { case VCS_AUTO: if (CheckVCS(filename)) { return true; } else { return CheckGIT(filename); } break; case VCS_GIT: return CheckGIT(filename); break; case VCS_NONE: break; // prevent wxFAIL case VCS_SVN: return CheckVCS(filename); break; default: wxFAIL; } return false; } long wxExVCS::Execute() { wxASSERT(m_Command != VCS_NO_COMMAND); wxString cwd; wxString file; if (!m_FileName.IsOk()) { cwd = wxGetCwd(); wxSetWorkingDirectory(wxExConfigFirstOf(_("Base folder"))); if (m_Command == VCS_ADD) { file = " " + wxExConfigFirstOf(_("Path")); } } else { if (GetVCS() == VCS_GIT) { cwd = wxGetCwd(); wxSetWorkingDirectory(m_FileName.GetPath()); file = " \"" + m_FileName.GetFullName() + "\""; } else { file = " \"" + m_FileName.GetFullPath() + "\""; } } wxString comment; if (m_Command == VCS_COMMIT) { comment = " -m \"" + wxExConfigFirstOf(_("Revision comment")) + "\""; } wxString subcommand; if (UseSubcommand()) { subcommand = wxConfigBase::Get()->Read(_("Subcommand")); if (!subcommand.empty()) { subcommand = " " + subcommand; } } wxString flags; if (UseFlags()) { flags = wxConfigBase::Get()->Read(_("Flags")); if (!flags.empty()) { flags = " " + flags; // If we specified help flags, we do not need a file argument. if (flags.Contains("help")) { file.clear(); } } } m_CommandWithFlags = m_CommandString + flags; wxString vcs_bin; switch (GetVCS()) { case VCS_GIT: vcs_bin = wxConfigBase::Get()->Read("GIT", "git"); break; case VCS_SVN: vcs_bin = wxConfigBase::Get()->Read("SVN", "svn"); break; default: wxFAIL; } if (vcs_bin.empty()) { wxLogError(GetVCSName() + " " + _("path is empty")); return -1; } const wxString commandline = vcs_bin + " " + m_CommandString + subcommand + flags + comment + file; #if wxUSE_STATUSBAR wxExFrame::StatusText(commandline); #endif wxArrayString output; wxArrayString errors; long retValue; // Call wxExcute to execute the cvs command and // collect the output and the errors. if ((retValue = wxExecute( commandline, output, errors)) == -1) { // See also process, same log is shown. wxLogError(_("Cannot execute") + ": " + commandline); } else { wxExLog::Get()->Log(commandline); } if (!cwd.empty()) { wxSetWorkingDirectory(cwd); } m_Output.clear(); // First output the errors. for ( size_t i = 0; i < errors.GetCount(); i++) { m_Output += errors[i] + "\n"; } // Then the normal output, will be empty if there are errors. for ( size_t j = 0; j < output.GetCount(); j++) { m_Output += output[j] + "\n"; } return retValue; } #if wxUSE_GUI wxStandardID wxExVCS::ExecuteDialog(wxWindow* parent) { if (ShowDialog(parent) == wxID_CANCEL) { return wxID_CANCEL; } if (UseFlags()) { wxConfigBase::Get()->Write(m_FlagsKey, wxConfigBase::Get()->Read(_("Flags"))); } const auto retValue = Execute(); return (retValue != -1 ? wxID_OK: wxID_CANCEL); } #endif wxExVCS* wxExVCS::Get(bool createOnDemand) { if (m_Self == NULL && createOnDemand) { m_Self = new wxExVCS; // Add default VCS. if (!wxConfigBase::Get()->Exists("VCS")) { // TODO: Add SVN only if svn bin exists on linux. wxConfigBase::Get()->Write("VCS", (long)VCS_SVN); } } return m_Self; } wxExVCS::wxExCommand wxExVCS::GetType(int command_id) const { if (command_id > ID_VCS_LOWEST && command_id < ID_VCS_HIGHEST) { return (wxExCommand)(command_id - ID_VCS_LOWEST); } else if (command_id > ID_EDIT_VCS_LOWEST && command_id < ID_EDIT_VCS_HIGHEST) { return (wxExCommand)(command_id - ID_EDIT_VCS_LOWEST); } else { wxFAIL; return VCS_NO_COMMAND; } } long wxExVCS::GetVCS() const { return wxConfigBase::Get()->ReadLong("VCS", VCS_SVN); } const wxString wxExVCS::GetVCSName() const { wxString text; switch (GetVCS()) { case VCS_GIT: text = "GIT"; break; case VCS_SVN: text = "SVN"; break; default: wxFAIL; } return text; } void wxExVCS::Initialize() { if (Use() && m_Command != VCS_NO_COMMAND) { switch (GetVCS()) { case VCS_GIT: switch (m_Command) { case VCS_ADD: m_CommandString = "add"; break; case VCS_BLAME: m_CommandString = "blame"; break; case VCS_CAT: break; case VCS_COMMIT: m_CommandString = "commit"; break; case VCS_DIFF: m_CommandString = "diff"; break; case VCS_HELP: m_CommandString = "help"; break; case VCS_INFO: break; case VCS_LOG: m_CommandString = "log"; break; case VCS_LS: break; case VCS_PROPLIST: break; case VCS_PROPSET: break; case VCS_PUSH: m_CommandString = "push"; break; case VCS_REVERT: m_CommandString = "revert"; break; case VCS_SHOW: m_CommandString = "show"; break; case VCS_STAT: m_CommandString = "status"; break; case VCS_UPDATE: m_CommandString = "update"; break; default: wxFAIL; break; } break; case VCS_SVN: switch (m_Command) { case VCS_ADD: m_CommandString = "add"; break; case VCS_BLAME: m_CommandString = "blame"; break; case VCS_CAT: m_CommandString = "cat"; break; case VCS_COMMIT: m_CommandString = "commit"; break; case VCS_DIFF: m_CommandString = "diff"; break; case VCS_HELP: m_CommandString = "help"; break; case VCS_INFO: m_CommandString = "info"; break; case VCS_LOG: m_CommandString = "log"; break; case VCS_LS: m_CommandString = "ls"; break; case VCS_PROPLIST: m_CommandString = "proplist"; break; case VCS_PROPSET: m_CommandString = "propset"; break; case VCS_PUSH: break; case VCS_REVERT: m_CommandString = "revert"; break; case VCS_SHOW: break; case VCS_STAT: m_CommandString = "stat"; break; case VCS_UPDATE: m_CommandString = "update"; break; default: wxFAIL; break; } break; default: wxFAIL; } m_Caption = GetVCSName() + " " + m_CommandString; // Currently no flags, as no command was executed. m_CommandWithFlags = m_CommandString; // Use general key. m_FlagsKey = wxString::Format("cvsflags/name%d", m_Command); } m_Output.clear(); } bool wxExVCS::IsOpenCommand() const { return m_Command == wxExVCS::VCS_BLAME || m_Command == wxExVCS::VCS_CAT || m_Command == wxExVCS::VCS_DIFF; } #if wxUSE_GUI wxStandardID wxExVCS::Request(wxWindow* parent) { wxStandardID retValue; if ((retValue = ExecuteDialog(parent)) == wxID_OK) { ShowOutput(parent); } return retValue; } #endif wxExVCS* wxExVCS::Set(wxExVCS* vcs) { wxExVCS* old = m_Self; m_Self = vcs; return old; } #if wxUSE_GUI int wxExVCS::ShowDialog(wxWindow* parent) { std::vector<wxExConfigItem> v; if (m_Command == VCS_COMMIT) { v.push_back(wxExConfigItem( _("Revision comment"), CONFIG_COMBOBOX, wxEmptyString, true)); // required } if (!m_FileName.IsOk() && m_Command != VCS_HELP) { v.push_back(wxExConfigItem( _("Base folder"), CONFIG_COMBOBOXDIR, wxEmptyString, true, 1000)); if (m_Command == VCS_ADD) { v.push_back(wxExConfigItem( _("Path"), CONFIG_COMBOBOX, wxEmptyString, true)); // required } } if (UseFlags()) { wxConfigBase::Get()->Write( _("Flags"), wxConfigBase::Get()->Read(m_FlagsKey)); v.push_back(wxExConfigItem(_("Flags"))); } if (UseSubcommand()) { v.push_back(wxExConfigItem(_("Subcommand"))); } return wxExConfigDialog(parent, v, m_Caption).ShowModal(); } #endif #if wxUSE_GUI void wxExVCS::ShowOutput(wxWindow* parent) const { wxString caption = m_Caption; if (m_Command != VCS_HELP) { caption += " " + (m_FileName.IsOk() ? m_FileName.GetFullName(): wxExConfigFirstOf(_("Base folder"))); } // Create a dialog for contents. if (m_STCEntryDialog == NULL) { m_STCEntryDialog = new wxExSTCEntryDialog( parent, caption, m_Output, wxEmptyString, wxOK, wxID_ANY, wxDefaultPosition, wxSize(350, 50)); } else { m_STCEntryDialog->SetText(m_Output); m_STCEntryDialog->SetTitle(caption); } // Add a lexer when appropriate. if (m_Command == VCS_CAT || m_Command == VCS_BLAME) { if (m_FileName.GetLexer().IsOk()) { m_STCEntryDialog->SetLexer(m_FileName.GetLexer().GetScintillaLexer()); } } else if (m_Command == VCS_DIFF) { m_STCEntryDialog->SetLexer("diff"); } else { m_STCEntryDialog->SetLexer(wxEmptyString); } m_STCEntryDialog->Show(); } #endif bool wxExVCS::Use() const { return GetVCS() != VCS_NONE; } bool wxExVCS::UseFlags() const { return m_Command != VCS_UPDATE && m_Command != VCS_HELP; } bool wxExVCS::UseSubcommand() const { return m_Command == VCS_HELP; } <commit_msg>vcs auto fixes<commit_after>/******************************************************************************\ * File: vcs.cpp * Purpose: Implementation of wxExVCS class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/config.h> #include <wx/extension/vcs.h> #include <wx/extension/configdlg.h> #include <wx/extension/defs.h> #include <wx/extension/frame.h> #include <wx/extension/log.h> #include <wx/extension/stcdlg.h> #include <wx/extension/util.h> wxExVCS* wxExVCS::m_Self = NULL; #if wxUSE_GUI wxExSTCEntryDialog* wxExVCS::m_STCEntryDialog = NULL; #endif wxExVCS::wxExVCS() : m_Command(VCS_NO_COMMAND) , m_FileName(wxExFileName()) { Initialize(); } wxExVCS::wxExVCS(int command_id, const wxExFileName& filename) : m_Command(GetType(command_id)) , m_FileName(filename) { Initialize(); } wxExVCS::wxExVCS(wxExCommand type, const wxExFileName& filename) : m_Command(type) , m_FileName(filename) { Initialize(); } bool wxExVCS::CheckVCS(const wxFileName& fn) const { // these cannot be combined, as AppendDir is a void (2.9.1). wxFileName path(filename); path.AppendDir(".svn"); return path.DirExists(); } bool wxExVCS::CheckGIT(const wxFileName& fn) const { // The .git dir only exists in the root, so check all components. wxFileName root(filename.GetPath()); while (root.DirExists() && root.GetDirCount() > 0) { wxFileName path(root); path.AppendDir(".git"); if (path.DirExists()) { return true; } root.RemoveLastDir(); } return false; } #if wxUSE_GUI int wxExVCS::ConfigDialog( wxWindow* parent, const wxString& title) const { std::vector<wxExConfigItem> v; std::map<long, const wxString> choices; choices.insert(std::make_pair(VCS_NONE, _("None"))); choices.insert(std::make_pair(VCS_GIT, "GIT")); choices.insert(std::make_pair(VCS_SVN, "SVN")); choices.insert(std::make_pair(VCS_AUTO, "Auto")); v.push_back(wxExConfigItem("VCS", choices)); v.push_back(wxExConfigItem("GIT", CONFIG_FILEPICKERCTRL)); v.push_back(wxExConfigItem("SVN", CONFIG_FILEPICKERCTRL)); v.push_back(wxExConfigItem(_("Comparator"), CONFIG_FILEPICKERCTRL)); return wxExConfigDialog(parent, v, title).ShowModal(); } #endif bool wxExVCS::DirExists(const wxFileName& filename) const { switch (GetVCS()) { case VCS_AUTO: if (CheckVCS(filename)) { return true; } else { return CheckGIT(filename); } break; case VCS_GIT: return CheckGIT(filename); break; case VCS_NONE: break; // prevent wxFAIL case VCS_SVN: return CheckVCS(filename); break; default: wxFAIL; } return false; } long wxExVCS::Execute() { wxASSERT(m_Command != VCS_NO_COMMAND); wxString cwd; wxString file; if (!m_FileName.IsOk()) { cwd = wxGetCwd(); wxSetWorkingDirectory(wxExConfigFirstOf(_("Base folder"))); if (m_Command == VCS_ADD) { file = " " + wxExConfigFirstOf(_("Path")); } } else { if (GetVCS() == VCS_GIT) { cwd = wxGetCwd(); wxSetWorkingDirectory(m_FileName.GetPath()); file = " \"" + m_FileName.GetFullName() + "\""; } else { file = " \"" + m_FileName.GetFullPath() + "\""; } } wxString comment; if (m_Command == VCS_COMMIT) { comment = " -m \"" + wxExConfigFirstOf(_("Revision comment")) + "\""; } wxString subcommand; if (UseSubcommand()) { subcommand = wxConfigBase::Get()->Read(_("Subcommand")); if (!subcommand.empty()) { subcommand = " " + subcommand; } } wxString flags; if (UseFlags()) { flags = wxConfigBase::Get()->Read(_("Flags")); if (!flags.empty()) { flags = " " + flags; // If we specified help flags, we do not need a file argument. if (flags.Contains("help")) { file.clear(); } } } m_CommandWithFlags = m_CommandString + flags; wxString vcs_bin; switch (GetVCS()) { case VCS_GIT: vcs_bin = wxConfigBase::Get()->Read("GIT", "git"); break; case VCS_SVN: vcs_bin = wxConfigBase::Get()->Read("SVN", "svn"); break; default: wxFAIL; } if (vcs_bin.empty()) { wxLogError(GetVCSName() + " " + _("path is empty")); return -1; } const wxString commandline = vcs_bin + " " + m_CommandString + subcommand + flags + comment + file; #if wxUSE_STATUSBAR wxExFrame::StatusText(commandline); #endif wxArrayString output; wxArrayString errors; long retValue; // Call wxExcute to execute the cvs command and // collect the output and the errors. if ((retValue = wxExecute( commandline, output, errors)) == -1) { // See also process, same log is shown. wxLogError(_("Cannot execute") + ": " + commandline); } else { wxExLog::Get()->Log(commandline); } if (!cwd.empty()) { wxSetWorkingDirectory(cwd); } m_Output.clear(); // First output the errors. for ( size_t i = 0; i < errors.GetCount(); i++) { m_Output += errors[i] + "\n"; } // Then the normal output, will be empty if there are errors. for ( size_t j = 0; j < output.GetCount(); j++) { m_Output += output[j] + "\n"; } return retValue; } #if wxUSE_GUI wxStandardID wxExVCS::ExecuteDialog(wxWindow* parent) { if (ShowDialog(parent) == wxID_CANCEL) { return wxID_CANCEL; } if (UseFlags()) { wxConfigBase::Get()->Write(m_FlagsKey, wxConfigBase::Get()->Read(_("Flags"))); } const auto retValue = Execute(); return (retValue != -1 ? wxID_OK: wxID_CANCEL); } #endif wxExVCS* wxExVCS::Get(bool createOnDemand) { if (m_Self == NULL && createOnDemand) { m_Self = new wxExVCS; // Add default VCS. if (!wxConfigBase::Get()->Exists("VCS")) { // TODO: Add SVN only if svn bin exists on linux. wxConfigBase::Get()->Write("VCS", (long)VCS_SVN); } } return m_Self; } wxExVCS::wxExCommand wxExVCS::GetType(int command_id) const { if (command_id > ID_VCS_LOWEST && command_id < ID_VCS_HIGHEST) { return (wxExCommand)(command_id - ID_VCS_LOWEST); } else if (command_id > ID_EDIT_VCS_LOWEST && command_id < ID_EDIT_VCS_HIGHEST) { return (wxExCommand)(command_id - ID_EDIT_VCS_LOWEST); } else { wxFAIL; return VCS_NO_COMMAND; } } long wxExVCS::GetVCS() const { long vcs = wxConfigBase::Get()->ReadLong("VCS", VCS_SVN); if (vcs == VCS_AUTO) { if (CheckVCS(m_FileName)) { vcs = VCS_SVN; } else if (CheckGIT(m_FileName)) { vcs = VCS_GIT; } } return vcs; } const wxString wxExVCS::GetVCSName() const { wxString text; switch (GetVCS()) { case VCS_GIT: text = "GIT"; break; case VCS_SVN: text = "SVN"; break; default: wxFAIL; } return text; } void wxExVCS::Initialize() { if (Use() && m_Command != VCS_NO_COMMAND) { switch (GetVCS()) { case VCS_GIT: switch (m_Command) { case VCS_ADD: m_CommandString = "add"; break; case VCS_BLAME: m_CommandString = "blame"; break; case VCS_CAT: break; case VCS_COMMIT: m_CommandString = "commit"; break; case VCS_DIFF: m_CommandString = "diff"; break; case VCS_HELP: m_CommandString = "help"; break; case VCS_INFO: break; case VCS_LOG: m_CommandString = "log"; break; case VCS_LS: break; case VCS_PROPLIST: break; case VCS_PROPSET: break; case VCS_PUSH: m_CommandString = "push"; break; case VCS_REVERT: m_CommandString = "revert"; break; case VCS_SHOW: m_CommandString = "show"; break; case VCS_STAT: m_CommandString = "status"; break; case VCS_UPDATE: m_CommandString = "update"; break; default: wxFAIL; break; } break; case VCS_SVN: switch (m_Command) { case VCS_ADD: m_CommandString = "add"; break; case VCS_BLAME: m_CommandString = "blame"; break; case VCS_CAT: m_CommandString = "cat"; break; case VCS_COMMIT: m_CommandString = "commit"; break; case VCS_DIFF: m_CommandString = "diff"; break; case VCS_HELP: m_CommandString = "help"; break; case VCS_INFO: m_CommandString = "info"; break; case VCS_LOG: m_CommandString = "log"; break; case VCS_LS: m_CommandString = "ls"; break; case VCS_PROPLIST: m_CommandString = "proplist"; break; case VCS_PROPSET: m_CommandString = "propset"; break; case VCS_PUSH: break; case VCS_REVERT: m_CommandString = "revert"; break; case VCS_SHOW: break; case VCS_STAT: m_CommandString = "stat"; break; case VCS_UPDATE: m_CommandString = "update"; break; default: wxFAIL; break; } break; default: wxFAIL; } m_Caption = GetVCSName() + " " + m_CommandString; // Currently no flags, as no command was executed. m_CommandWithFlags = m_CommandString; // Use general key. m_FlagsKey = wxString::Format("cvsflags/name%d", m_Command); } m_Output.clear(); } bool wxExVCS::IsOpenCommand() const { return m_Command == wxExVCS::VCS_BLAME || m_Command == wxExVCS::VCS_CAT || m_Command == wxExVCS::VCS_DIFF; } #if wxUSE_GUI wxStandardID wxExVCS::Request(wxWindow* parent) { wxStandardID retValue; if ((retValue = ExecuteDialog(parent)) == wxID_OK) { ShowOutput(parent); } return retValue; } #endif wxExVCS* wxExVCS::Set(wxExVCS* vcs) { wxExVCS* old = m_Self; m_Self = vcs; return old; } #if wxUSE_GUI int wxExVCS::ShowDialog(wxWindow* parent) { std::vector<wxExConfigItem> v; if (m_Command == VCS_COMMIT) { v.push_back(wxExConfigItem( _("Revision comment"), CONFIG_COMBOBOX, wxEmptyString, true)); // required } if (!m_FileName.IsOk() && m_Command != VCS_HELP) { v.push_back(wxExConfigItem( _("Base folder"), CONFIG_COMBOBOXDIR, wxEmptyString, true, 1000)); if (m_Command == VCS_ADD) { v.push_back(wxExConfigItem( _("Path"), CONFIG_COMBOBOX, wxEmptyString, true)); // required } } if (UseFlags()) { wxConfigBase::Get()->Write( _("Flags"), wxConfigBase::Get()->Read(m_FlagsKey)); v.push_back(wxExConfigItem(_("Flags"))); } if (UseSubcommand()) { v.push_back(wxExConfigItem(_("Subcommand"))); } return wxExConfigDialog(parent, v, m_Caption).ShowModal(); } #endif #if wxUSE_GUI void wxExVCS::ShowOutput(wxWindow* parent) const { wxString caption = m_Caption; if (m_Command != VCS_HELP) { caption += " " + (m_FileName.IsOk() ? m_FileName.GetFullName(): wxExConfigFirstOf(_("Base folder"))); } // Create a dialog for contents. if (m_STCEntryDialog == NULL) { m_STCEntryDialog = new wxExSTCEntryDialog( parent, caption, m_Output, wxEmptyString, wxOK, wxID_ANY, wxDefaultPosition, wxSize(350, 50)); } else { m_STCEntryDialog->SetText(m_Output); m_STCEntryDialog->SetTitle(caption); } // Add a lexer when appropriate. if (m_Command == VCS_CAT || m_Command == VCS_BLAME) { if (m_FileName.GetLexer().IsOk()) { m_STCEntryDialog->SetLexer(m_FileName.GetLexer().GetScintillaLexer()); } } else if (m_Command == VCS_DIFF) { m_STCEntryDialog->SetLexer("diff"); } else { m_STCEntryDialog->SetLexer(wxEmptyString); } m_STCEntryDialog->Show(); } #endif bool wxExVCS::Use() const { return GetVCS() != VCS_NONE; } bool wxExVCS::UseFlags() const { return m_Command != VCS_UPDATE && m_Command != VCS_HELP; } bool wxExVCS::UseSubcommand() const { return m_Command == VCS_HELP; } <|endoftext|>
<commit_before>/** * CFunction * * Created for Copasi by Stefan Hoops * (C) Stefan Hoops 2001 */ #define COPASI_TRACE_CONSTRUCTION #include "copasi.h" #include "CFunctionParameter.h" #include "CFunctionParameters.h" #include "CFunction.h" CFunction::CFunction() { CONSTRUCTOR_TRACE; mReversible = TriUnspecified; } CFunction::CFunction(const CFunction & src) { CONSTRUCTOR_TRACE; mType = src.mType; mName = src.mName; mDescription = src.mDescription; mReversible = src.mReversible; mUsageDescriptions = CCopasiVectorNS < CUsageRange > (src.mUsageDescriptions); mParameters = CFunctionParameters(src.mParameters); } CFunction::~CFunction() { cleanup(); DESTRUCTOR_TRACE; } void CFunction::cleanup() { mUsageDescriptions.cleanup(); mParameters.cleanup(); } void CFunction::load(CReadConfig & configBuffer, CReadConfig::Mode mode) { cleanup(); if (configBuffer.getVersion() < "4") { C_INT32 Type; CUsageRange UsageDescription; mode = CReadConfig::SEARCH; configBuffer.getVariable("User-defined", "C_INT32", &Type, mode); switch (Type) { case 1: mType = CFunction::UserDefined; break; default: fatalError(); } configBuffer.getVariable("Reversible", "C_INT32", &mReversible); configBuffer.getVariable("Substrates", "C_INT32", &Type); UsageDescription.setUsage("SUBSTRATES"); UsageDescription.setLow(Type); mUsageDescriptions.add(UsageDescription); configBuffer.getVariable("Products", "C_INT32", &Type); UsageDescription.setUsage("PRODUCTS"); UsageDescription.setLow(Type); mUsageDescriptions.add(UsageDescription); mode = CReadConfig::SEARCH; } else { configBuffer.getVariable("FunctionType", "C_INT32", &mType, mode); mode = CReadConfig::NEXT; } configBuffer.getVariable("FunctionName", "string", &mName, mode); configBuffer.getVariable("Description", "string", &mDescription); if (configBuffer.getVersion() >= "4") { unsigned C_INT32 Size; configBuffer.getVariable("Reversible", "C_INT32", &mReversible); configBuffer.getVariable("UsageDescriptionSize", "C_INT32", &Size); mUsageDescriptions.load(configBuffer, Size); mParameters.load(configBuffer); } // For older file version the parameters have to be build from information // dependend on the function type. Luckilly, only user defined functions are // the only ones occuring in those files. } void CFunction::save(CWriteConfig & configBuffer) { configBuffer.setVariable("FunctionType", "C_INT32", &mType); configBuffer.setVariable("FunctionName", "string", &mName); configBuffer.setVariable("Description", "string", &mDescription); configBuffer.setVariable("Reversible", "C_INT32", &mReversible); unsigned C_INT32 Size = mUsageDescriptions.size(); configBuffer.setVariable("UsageDescriptionSize", "C_INT32", &Size); mUsageDescriptions.save(configBuffer); mParameters.save(configBuffer); } void CFunction::saveOld(CWriteConfig & configBuffer) { C_INT32 dummy, i, sizem, sizep; unsigned C_INT32 pos; string tmpstr1, tmpstr2; if (mType == UserDefined) dummy = 1; else dummy = 0; configBuffer.setVariable("UDKType", "string", &mName); configBuffer.setVariable("User-defined", "C_INT32", &dummy); configBuffer.setVariable("Reversible", "C_INT32", &mReversible); dummy = mUsageDescriptions["SUBSTRATES"]->getLow(); configBuffer.setVariable("Substrates", "C_INT32", &dummy); dummy = mUsageDescriptions["PRODUCTS"]->getLow(); configBuffer.setVariable("Products", "C_INT32", &dummy); sizem = mParameters.getUsageRanges()["MODIFIER"]->getLow(); configBuffer.setVariable("Modifiers", "C_INT32", &sizem); sizep = mParameters.getUsageRanges()["PARAMETER"]->getLow(); configBuffer.setVariable("Constants", "C_INT32", &sizep); for (i = 0, pos = 0; i < sizem; i++) { tmpstr1 = mParameters.getParameterByUsage("MODIFIER", pos).getName(); tmpstr2 = StringPrint("Modifier%d", i); configBuffer.setVariable(tmpstr2, "string", &tmpstr1); } for (i = 0, pos = 0; i < sizep; i++) { tmpstr1 = mParameters.getParameterByUsage("PARAMETER", pos).getName(); tmpstr2 = StringPrint("Paramter%d", i); configBuffer.setVariable(tmpstr2, "string", &tmpstr1); } configBuffer.setVariable("FunctionName", "string", &mName); configBuffer.setVariable("Description", "string", &mDescription); // unsigned C_INT32 Size = mUsageDescriptions.size(); // configBuffer.setVariable("UsageDescriptionSize", "C_INT32", &Size); // mUsageDescriptions.save(configBuffer); // mParameters.save(configBuffer); } void CFunction::setName(const string& name) { mName = name; } const string & CFunction::getName() const { return mName; } void CFunction::setDescription(const string & description) { mDescription = description; } const string & CFunction::getDescription() const { return mDescription; } void CFunction::setType(const CFunction::Type & type) { mType = type; } const CFunction::Type & CFunction::getType() const { return mType; } void CFunction::setReversible(const TriLogic & reversible) { mReversible = reversible; } const TriLogic & CFunction::isReversible() const { return mReversible; } CFunctionParameters & CFunction::getParameters() { return mParameters; } CCopasiVectorNS < CUsageRange > & CFunction::getUsageDescriptions() { return mUsageDescriptions; } unsigned C_INT32 CFunction::getParameterPosition(const string & name) { return mParameters[0] - mParameters[name]; } C_FLOAT64 CFunction::calcValue(const CCallParameters & callParameters) const { return 0.0; } void CFunction::addUsage(const string& usage, C_INT32 low, C_INT32 high) { CUsageRange *u; u = new CUsageRange(); u->setUsage(usage); u->setLow(low); u->setHigh(high); mUsageDescriptions.add(u); } void CFunction::addParameter(const string & name, const CFunctionParameter::DataType & type, const string & usage) { mParameters.add(name, type, usage); } <commit_msg>fixed a bug in saveOld()<commit_after>/** * CFunction * * Created for Copasi by Stefan Hoops * (C) Stefan Hoops 2001 */ #define COPASI_TRACE_CONSTRUCTION #include "copasi.h" #include "CFunctionParameter.h" #include "CFunctionParameters.h" #include "CFunction.h" CFunction::CFunction() { CONSTRUCTOR_TRACE; mReversible = TriUnspecified; } CFunction::CFunction(const CFunction & src) { CONSTRUCTOR_TRACE; mType = src.mType; mName = src.mName; mDescription = src.mDescription; mReversible = src.mReversible; mUsageDescriptions = CCopasiVectorNS < CUsageRange > (src.mUsageDescriptions); mParameters = CFunctionParameters(src.mParameters); } CFunction::~CFunction() { cleanup(); DESTRUCTOR_TRACE; } void CFunction::cleanup() { mUsageDescriptions.cleanup(); mParameters.cleanup(); } void CFunction::load(CReadConfig & configBuffer, CReadConfig::Mode mode) { cleanup(); if (configBuffer.getVersion() < "4") { C_INT32 Type; CUsageRange UsageDescription; mode = CReadConfig::SEARCH; configBuffer.getVariable("User-defined", "C_INT32", &Type, mode); switch (Type) { case 1: mType = CFunction::UserDefined; break; default: fatalError(); } configBuffer.getVariable("Reversible", "C_INT32", &mReversible); configBuffer.getVariable("Substrates", "C_INT32", &Type); UsageDescription.setUsage("SUBSTRATES"); UsageDescription.setLow(Type); mUsageDescriptions.add(UsageDescription); configBuffer.getVariable("Products", "C_INT32", &Type); UsageDescription.setUsage("PRODUCTS"); UsageDescription.setLow(Type); mUsageDescriptions.add(UsageDescription); mode = CReadConfig::SEARCH; } else { configBuffer.getVariable("FunctionType", "C_INT32", &mType, mode); mode = CReadConfig::NEXT; } configBuffer.getVariable("FunctionName", "string", &mName, mode); configBuffer.getVariable("Description", "string", &mDescription); if (configBuffer.getVersion() >= "4") { unsigned C_INT32 Size; configBuffer.getVariable("Reversible", "C_INT32", &mReversible); configBuffer.getVariable("UsageDescriptionSize", "C_INT32", &Size); mUsageDescriptions.load(configBuffer, Size); mParameters.load(configBuffer); } // For older file version the parameters have to be build from information // dependend on the function type. Luckilly, only user defined functions are // the only ones occuring in those files. } void CFunction::save(CWriteConfig & configBuffer) { configBuffer.setVariable("FunctionType", "C_INT32", &mType); configBuffer.setVariable("FunctionName", "string", &mName); configBuffer.setVariable("Description", "string", &mDescription); configBuffer.setVariable("Reversible", "C_INT32", &mReversible); unsigned C_INT32 Size = mUsageDescriptions.size(); configBuffer.setVariable("UsageDescriptionSize", "C_INT32", &Size); mUsageDescriptions.save(configBuffer); mParameters.save(configBuffer); } void CFunction::saveOld(CWriteConfig & configBuffer) { C_INT32 dummy, i, sizem, sizep; unsigned C_INT32 pos; string tmpstr1, tmpstr2; CCopasiVectorNS < CUsageRange > tmpusage; if (mType == UserDefined) dummy = 1; else dummy = 0; configBuffer.setVariable("UDKType", "string", &mName); configBuffer.setVariable("User-defined", "C_INT32", &dummy); configBuffer.setVariable("Reversible", "C_INT32", &mReversible); dummy = mUsageDescriptions["SUBSTRATES"]->getLow(); configBuffer.setVariable("Substrates", "C_INT32", &dummy); dummy = mUsageDescriptions["PRODUCTS"]->getLow(); configBuffer.setVariable("Products", "C_INT32", &dummy); tmpusage = mParameters.getUsageRanges(); i = tmpusage.getIndex("MODIFIER"); if (i == -1) sizem = 0; else sizem = tmpusage[i]->getLow(); configBuffer.setVariable("Modifiers", "C_INT32", &sizem); sizep = mParameters.getUsageRanges()["PARAMETER"]->getLow(); configBuffer.setVariable("Constants", "C_INT32", &sizep); for (i = 0, pos = 0; i < sizem; i++) { tmpstr1 = mParameters.getParameterByUsage("MODIFIER", pos).getName(); tmpstr2 = StringPrint("Modifier%d", i); configBuffer.setVariable(tmpstr2, "string", &tmpstr1); } for (i = 0, pos = 0; i < sizep; i++) { tmpstr1 = mParameters.getParameterByUsage("PARAMETER", pos).getName(); tmpstr2 = StringPrint("Paramter%d", i); configBuffer.setVariable(tmpstr2, "string", &tmpstr1); } configBuffer.setVariable("FunctionName", "string", &mName); configBuffer.setVariable("Description", "string", &mDescription); // unsigned C_INT32 Size = mUsageDescriptions.size(); // configBuffer.setVariable("UsageDescriptionSize", "C_INT32", &Size); // mUsageDescriptions.save(configBuffer); // mParameters.save(configBuffer); } void CFunction::setName(const string& name) { mName = name; } const string & CFunction::getName() const { return mName; } void CFunction::setDescription(const string & description) { mDescription = description; } const string & CFunction::getDescription() const { return mDescription; } void CFunction::setType(const CFunction::Type & type) { mType = type; } const CFunction::Type & CFunction::getType() const { return mType; } void CFunction::setReversible(const TriLogic & reversible) { mReversible = reversible; } const TriLogic & CFunction::isReversible() const { return mReversible; } CFunctionParameters & CFunction::getParameters() { return mParameters; } CCopasiVectorNS < CUsageRange > & CFunction::getUsageDescriptions() { return mUsageDescriptions; } unsigned C_INT32 CFunction::getParameterPosition(const string & name) { return mParameters[0] - mParameters[name]; } C_FLOAT64 CFunction::calcValue(const CCallParameters & callParameters) const { return 0.0; } void CFunction::addUsage(const string& usage, C_INT32 low, C_INT32 high) { CUsageRange *u; u = new CUsageRange(); u->setUsage(usage); u->setLow(low); u->setHigh(high); mUsageDescriptions.add(u); } void CFunction::addParameter(const string & name, const CFunctionParameter::DataType & type, const string & usage) { mParameters.add(name, type, usage); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: postit.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2008-02-19 13:34:29 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _POSTIT_HXX #define _POSTIT_HXX #ifndef _WINDOW_HXX #include <vcl/window.hxx> #endif #ifndef _SDR_OVERLAY_OVERLAYOBJECT_HXX #include <svx/sdr/overlay/overlayobject.hxx> #endif //TODO: move to cxx // does not work with forward declaration, why?? #ifndef _LINEINFO_HXX #include <vcl/lineinfo.hxx> #endif #ifndef _BGFX_POLYGON_B2DPOLYGON_HXX #include <basegfx/polygon/b2dpolygon.hxx> #endif class SwPostItMgr; class SwPostItField; class SwFmtFld; class OutlinerView; class Outliner; class ScrollBar; class SwEditWin; class SwView; class SwPostIt; class Edit; class MultiLineEdit; class SwRect; class PopupMenu; class SwPostItAnkor: public sdr::overlay::OverlayObjectWithBasePosition { protected: /* 6------------7 1 / /4\ ---------------5 2 - 3 */ basegfx::B2DPoint maSecondPosition; basegfx::B2DPoint maThirdPosition; basegfx::B2DPoint maFourthPosition; basegfx::B2DPoint maFifthPosition; basegfx::B2DPoint maSixthPosition; basegfx::B2DPoint maSeventhPosition; private: // object's geometry basegfx::B2DPolygon maTriangle; basegfx::B2DPolygon maLine; basegfx::B2DPolygon maLineTop; LineInfo mLineInfo; unsigned long mHeight; bool mbShadowedEffect; protected: // helpers to fill and reset geometry void implEnsureGeometry(); void implResetGeometry(); // helpers to paint geometry void implDrawGeometry(OutputDevice& rOutputDevice, Color aColor, double fOffX, double fOffY); Color implBlendColor(const Color aOriginal, sal_Int16 nChange); virtual void drawGeometry(OutputDevice& rOutputDevice); virtual void createBaseRange(OutputDevice& rOutputDevice); public: SwPostItAnkor(const basegfx::B2DPoint& rBasePos, const basegfx::B2DPoint& rSecondPos, const basegfx::B2DPoint& rThirdPos, const basegfx::B2DPoint& rFourthPos, const basegfx::B2DPoint& rFifthPos, const basegfx::B2DPoint& rSixthPos, const basegfx::B2DPoint& rSeventhPos, Color aBaseColor, const LineInfo &aLineInfo, bool bShadowedEffect); virtual ~SwPostItAnkor(); const basegfx::B2DPoint& GetSecondPosition() const { return maSecondPosition; } const basegfx::B2DPoint& GetThirdPosition() const { return maThirdPosition; } const basegfx::B2DPoint& GetFourthPosition() const { return maFourthPosition; } const basegfx::B2DPoint& GetFifthPosition() const { return maFifthPosition; } const basegfx::B2DPoint& GetSixthPosition() const { return maSixthPosition; } const basegfx::B2DPoint& GetSeventhPosition() const { return maSeventhPosition; } void SetAllPosition(const basegfx::B2DPoint& rPoint1, const basegfx::B2DPoint& rPoint2, const basegfx::B2DPoint& rPoint3, const basegfx::B2DPoint& rPoint4, const basegfx::B2DPoint& rPoint5, const basegfx::B2DPoint& rPoint6, const basegfx::B2DPoint& rPoint7); void SetColorLineInfo(Color aBaseColor,const LineInfo& aLineInfo); void SetSecondPosition(const basegfx::B2DPoint& rNew); void SetThirdPosition(const basegfx::B2DPoint& rNew); void SetFourthPosition(const basegfx::B2DPoint& rNew); void SetFifthPosition(const basegfx::B2DPoint& rNew); void SetSixthPosition(const basegfx::B2DPoint& rNew); void SetSeventhPosition(const basegfx::B2DPoint& rNew); void SetLineInfo(const LineInfo &aLineInfo); void SetHeight(const unsigned long aHeight) {mHeight = aHeight;}; bool getShadowedEffect() const { return mbShadowedEffect; } void setShadowedEffect(bool bNew); //sal_Bool isHit(const basegfx::B2DPoint& rPos, double fTol) const; // transform object coordinates. Transforms maBasePosition // and invalidates on change virtual void transform(const basegfx::B2DHomMatrix& rMatrix); }; class PostItTxt : public Window { private: OutlinerView* mpOutlinerView; SwPostIt* mpPostIt; Color mColorDark; Color mColorLight; bool mMouseOver; BOOL mbShowPopup; protected: virtual void Paint( const Rectangle& rRect); virtual void KeyInput( const KeyEvent& rKeyEvt ); virtual void MouseMove( const MouseEvent& rMEvt ); virtual void MouseButtonDown( const MouseEvent& rMEvt ); virtual void MouseButtonUp( const MouseEvent& rMEvt ); virtual void Command( const CommandEvent& rCEvt ); virtual void DataChanged( const DataChangedEvent& aData); virtual void LoseFocus(); public: virtual void GetFocus(); void SetColor(Color &aColorDark,Color &aColorLight); public: PostItTxt(Window* pParent, WinBits nBits); ~PostItTxt(); void SetTextView( OutlinerView* aEditView ) { mpOutlinerView = aEditView; } DECL_LINK( WindowEventListener, VclSimpleEvent* ); }; class SwPostIt : public Window { private: SwView* mpView; sdr::overlay::OverlayManager* pOverlayManager; OutlinerView* mpOutlinerView; Outliner* mpOutliner; PostItTxt* mpPostItTxt; MultiLineEdit* mpMeta; ScrollBar* mpVScrollbar; SwFmtFld* mpFmtFld; SwPostItField* mpFld; SwPostItAnkor* mpAnkor; SwPostItMgr* mpMgr; bool mbMeta; bool mbReadonly; Color mColorAnkor; Color mColorDark; Color mColorLight; basegfx::B2DPolygon aPopupTriangle; Rectangle mRectMetaButton; PopupMenu* mpButtonPopup; sal_Int32 mnEventId; bool mbMarginSide; protected: virtual void DataChanged( const DataChangedEvent& aEvent); virtual void LoseFocus(); virtual void MouseButtonDown( const MouseEvent& rMEvt ); virtual void Paint( const Rectangle& rRect); virtual void Resize(); virtual void GetFocus(); DECL_LINK(ScrollHdl, ScrollBar*); void InitControls(); public: SwPostIt( Window* pParent, WinBits nBits,SwFmtFld* aField,SwPostItMgr* aMgr,bool bMarginSide); ~SwPostIt(); void SetSizePixel( const Size& rNewSize ); void SetPosSizePixelRect( long nX, long nY,long nWidth, long nHeight,const SwRect &aRect,const long PageBorder, USHORT nFlags = WINDOW_POSSIZE_ALL ); void TranslateTopPosition(const long aAmount); void MetaInfo(const bool bMeta); void SetPostItText(); PostItTxt* PostItText() { return mpPostItTxt;} ScrollBar* Scrollbar() { return mpVScrollbar;} SwPostItAnkor* Ankor() { return mpAnkor;} OutlinerView* View() { return mpOutlinerView;} SwView* DocView() { return mpView;} Outliner* Engine() { return mpOutliner;} SwPostItMgr* Mgr() { return mpMgr; } SwEditWin* EditWin(); long GetPostItTextHeight(); void UpdateData(); void SwitchToPostIt(USHORT aDirection); void SwitchToFieldPos(bool bAfter = true); void ExecuteCommand(USHORT aSlot); void Delete(USHORT aType); void Hide(USHORT aType); void DoResize() { Resize(); } void ShowAnkorOnly(const Point &aPoint); void ShowNote(); void HideNote(); void ResetAttributes(); void SetReadonly(BOOL bSet); BOOL IsReadOnly() { return mbReadonly;} void SetColor(Color &aColorDark,Color &aColorLight, Color &aColorAnkor); Color ColorDark(); Color ColorLight(); Color ColorAnkor(); void Rescale(); sal_Int32 GetMetaHeight(); sal_Int32 GetMinimumSizeWithMeta(); sal_Int32 GetMinimumSizeWithoutMeta(); sal_Int32 GetMetaButtonAreaWidth(); sal_Int32 GetScrollbarWidth(); void SetSpellChecking(bool bEnable); /* //void ClearModifyFlag() { mpOutliner->SetModified(); } //BOOL IsModified() const { return mpOutliner->IsModified();} void SetStartLine(USHORT nLine){nStartLine = nLine;} virtual void Command( const CommandEvent& rCEvt ); void HandleWheelCommand( const CommandEvent& rCEvt ); void SetTextEncoding(rtl_TextEncoding eEncoding); */ }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.2.78); FILE MERGED 2008/04/01 15:56:17 thb 1.2.78.2: #i85898# Stripping all external header guards 2008/03/31 16:52:40 rt 1.2.78.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: postit.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _POSTIT_HXX #define _POSTIT_HXX #include <vcl/window.hxx> #include <svx/sdr/overlay/overlayobject.hxx> //TODO: move to cxx // does not work with forward declaration, why?? #ifndef _LINEINFO_HXX #include <vcl/lineinfo.hxx> #endif #include <basegfx/polygon/b2dpolygon.hxx> class SwPostItMgr; class SwPostItField; class SwFmtFld; class OutlinerView; class Outliner; class ScrollBar; class SwEditWin; class SwView; class SwPostIt; class Edit; class MultiLineEdit; class SwRect; class PopupMenu; class SwPostItAnkor: public sdr::overlay::OverlayObjectWithBasePosition { protected: /* 6------------7 1 / /4\ ---------------5 2 - 3 */ basegfx::B2DPoint maSecondPosition; basegfx::B2DPoint maThirdPosition; basegfx::B2DPoint maFourthPosition; basegfx::B2DPoint maFifthPosition; basegfx::B2DPoint maSixthPosition; basegfx::B2DPoint maSeventhPosition; private: // object's geometry basegfx::B2DPolygon maTriangle; basegfx::B2DPolygon maLine; basegfx::B2DPolygon maLineTop; LineInfo mLineInfo; unsigned long mHeight; bool mbShadowedEffect; protected: // helpers to fill and reset geometry void implEnsureGeometry(); void implResetGeometry(); // helpers to paint geometry void implDrawGeometry(OutputDevice& rOutputDevice, Color aColor, double fOffX, double fOffY); Color implBlendColor(const Color aOriginal, sal_Int16 nChange); virtual void drawGeometry(OutputDevice& rOutputDevice); virtual void createBaseRange(OutputDevice& rOutputDevice); public: SwPostItAnkor(const basegfx::B2DPoint& rBasePos, const basegfx::B2DPoint& rSecondPos, const basegfx::B2DPoint& rThirdPos, const basegfx::B2DPoint& rFourthPos, const basegfx::B2DPoint& rFifthPos, const basegfx::B2DPoint& rSixthPos, const basegfx::B2DPoint& rSeventhPos, Color aBaseColor, const LineInfo &aLineInfo, bool bShadowedEffect); virtual ~SwPostItAnkor(); const basegfx::B2DPoint& GetSecondPosition() const { return maSecondPosition; } const basegfx::B2DPoint& GetThirdPosition() const { return maThirdPosition; } const basegfx::B2DPoint& GetFourthPosition() const { return maFourthPosition; } const basegfx::B2DPoint& GetFifthPosition() const { return maFifthPosition; } const basegfx::B2DPoint& GetSixthPosition() const { return maSixthPosition; } const basegfx::B2DPoint& GetSeventhPosition() const { return maSeventhPosition; } void SetAllPosition(const basegfx::B2DPoint& rPoint1, const basegfx::B2DPoint& rPoint2, const basegfx::B2DPoint& rPoint3, const basegfx::B2DPoint& rPoint4, const basegfx::B2DPoint& rPoint5, const basegfx::B2DPoint& rPoint6, const basegfx::B2DPoint& rPoint7); void SetColorLineInfo(Color aBaseColor,const LineInfo& aLineInfo); void SetSecondPosition(const basegfx::B2DPoint& rNew); void SetThirdPosition(const basegfx::B2DPoint& rNew); void SetFourthPosition(const basegfx::B2DPoint& rNew); void SetFifthPosition(const basegfx::B2DPoint& rNew); void SetSixthPosition(const basegfx::B2DPoint& rNew); void SetSeventhPosition(const basegfx::B2DPoint& rNew); void SetLineInfo(const LineInfo &aLineInfo); void SetHeight(const unsigned long aHeight) {mHeight = aHeight;}; bool getShadowedEffect() const { return mbShadowedEffect; } void setShadowedEffect(bool bNew); //sal_Bool isHit(const basegfx::B2DPoint& rPos, double fTol) const; // transform object coordinates. Transforms maBasePosition // and invalidates on change virtual void transform(const basegfx::B2DHomMatrix& rMatrix); }; class PostItTxt : public Window { private: OutlinerView* mpOutlinerView; SwPostIt* mpPostIt; Color mColorDark; Color mColorLight; bool mMouseOver; BOOL mbShowPopup; protected: virtual void Paint( const Rectangle& rRect); virtual void KeyInput( const KeyEvent& rKeyEvt ); virtual void MouseMove( const MouseEvent& rMEvt ); virtual void MouseButtonDown( const MouseEvent& rMEvt ); virtual void MouseButtonUp( const MouseEvent& rMEvt ); virtual void Command( const CommandEvent& rCEvt ); virtual void DataChanged( const DataChangedEvent& aData); virtual void LoseFocus(); public: virtual void GetFocus(); void SetColor(Color &aColorDark,Color &aColorLight); public: PostItTxt(Window* pParent, WinBits nBits); ~PostItTxt(); void SetTextView( OutlinerView* aEditView ) { mpOutlinerView = aEditView; } DECL_LINK( WindowEventListener, VclSimpleEvent* ); }; class SwPostIt : public Window { private: SwView* mpView; sdr::overlay::OverlayManager* pOverlayManager; OutlinerView* mpOutlinerView; Outliner* mpOutliner; PostItTxt* mpPostItTxt; MultiLineEdit* mpMeta; ScrollBar* mpVScrollbar; SwFmtFld* mpFmtFld; SwPostItField* mpFld; SwPostItAnkor* mpAnkor; SwPostItMgr* mpMgr; bool mbMeta; bool mbReadonly; Color mColorAnkor; Color mColorDark; Color mColorLight; basegfx::B2DPolygon aPopupTriangle; Rectangle mRectMetaButton; PopupMenu* mpButtonPopup; sal_Int32 mnEventId; bool mbMarginSide; protected: virtual void DataChanged( const DataChangedEvent& aEvent); virtual void LoseFocus(); virtual void MouseButtonDown( const MouseEvent& rMEvt ); virtual void Paint( const Rectangle& rRect); virtual void Resize(); virtual void GetFocus(); DECL_LINK(ScrollHdl, ScrollBar*); void InitControls(); public: SwPostIt( Window* pParent, WinBits nBits,SwFmtFld* aField,SwPostItMgr* aMgr,bool bMarginSide); ~SwPostIt(); void SetSizePixel( const Size& rNewSize ); void SetPosSizePixelRect( long nX, long nY,long nWidth, long nHeight,const SwRect &aRect,const long PageBorder, USHORT nFlags = WINDOW_POSSIZE_ALL ); void TranslateTopPosition(const long aAmount); void MetaInfo(const bool bMeta); void SetPostItText(); PostItTxt* PostItText() { return mpPostItTxt;} ScrollBar* Scrollbar() { return mpVScrollbar;} SwPostItAnkor* Ankor() { return mpAnkor;} OutlinerView* View() { return mpOutlinerView;} SwView* DocView() { return mpView;} Outliner* Engine() { return mpOutliner;} SwPostItMgr* Mgr() { return mpMgr; } SwEditWin* EditWin(); long GetPostItTextHeight(); void UpdateData(); void SwitchToPostIt(USHORT aDirection); void SwitchToFieldPos(bool bAfter = true); void ExecuteCommand(USHORT aSlot); void Delete(USHORT aType); void Hide(USHORT aType); void DoResize() { Resize(); } void ShowAnkorOnly(const Point &aPoint); void ShowNote(); void HideNote(); void ResetAttributes(); void SetReadonly(BOOL bSet); BOOL IsReadOnly() { return mbReadonly;} void SetColor(Color &aColorDark,Color &aColorLight, Color &aColorAnkor); Color ColorDark(); Color ColorLight(); Color ColorAnkor(); void Rescale(); sal_Int32 GetMetaHeight(); sal_Int32 GetMinimumSizeWithMeta(); sal_Int32 GetMinimumSizeWithoutMeta(); sal_Int32 GetMetaButtonAreaWidth(); sal_Int32 GetScrollbarWidth(); void SetSpellChecking(bool bEnable); /* //void ClearModifyFlag() { mpOutliner->SetModified(); } //BOOL IsModified() const { return mpOutliner->IsModified();} void SetStartLine(USHORT nLine){nStartLine = nLine;} virtual void Command( const CommandEvent& rCEvt ); void HandleWheelCommand( const CommandEvent& rCEvt ); void SetTextEncoding(rtl_TextEncoding eEncoding); */ }; #endif <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2013-2014 winlin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef SRS_CORE_HPP #define SRS_CORE_HPP /* #include <srs_core.hpp> */ /** * the core provides the common defined macros, utilities, * user must include the srs_core.hpp before any header, or maybe * build failed. */ // for int64_t print using PRId64 format. #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include <inttypes.h> #include <assert.h> #define srs_assert(expression) assert(expression) #include <stddef.h> #include <sys/types.h> #include <st.h> // generated by configure. #include <srs_auto_headers.hpp> // free the p and set to NULL. // p must be a T*. #define srs_freep(p) \ if (p) { \ delete p; \ p = NULL; \ } \ (void)0 // free the p which represents a array #define srs_freepa(p) \ if (p) { \ delete[] p; \ p = NULL; \ } \ (void)0 // current release version #define RTMP_SIG_SRS_VERSION "0.9.0" // server info. #define RTMP_SIG_SRS_KEY "srs" #define RTMP_SIG_SRS_ROLE "origin server" #define RTMP_SIG_SRS_NAME RTMP_SIG_SRS_KEY"(simple rtmp server)" #define RTMP_SIG_SRS_URL "https://"RTMP_SIG_SRS_URL_SHORT #define RTMP_SIG_SRS_URL_SHORT "github.com/winlinvip/simple-rtmp-server" #define RTMP_SIG_SRS_WEB "http://blog.csdn.net/win_lin" #define RTMP_SIG_SRS_EMAIL "[email protected]" #define RTMP_SIG_SRS_LICENSE "The MIT License (MIT)" #define RTMP_SIG_SRS_COPYRIGHT "Copyright (c) 2013-2014 winlin" #define RTMP_SIG_SRS_PRIMARY_AUTHROS "winlin,wenjiegit" // compare #define srs_min(a, b) (((a) < (b))? (a) : (b)) #define srs_max(a, b) (((a) < (b))? (b) : (a)) // get current system time in ms, use cache to avoid performance problem extern int64_t srs_get_system_time_ms(); // the deamon st-thread will update it. extern void srs_update_system_time_ms(); // signal defines. #define SIGNAL_RELOAD SIGHUP #include <string> // replace utility extern std::string srs_replace(std::string str, std::string old_str, std::string new_str); // dns resolve utility, return the resolved ip address. extern std::string srs_dns_resolve(std::string host); // resolve the vhost in query string // @param app, may contains the vhost in query string format: // app?vhost=request_vhost // app...vhost...request_vhost extern void srs_vhost_resolve(std::string& vhost, std::string& app); // close the netfd, and close the underlayer fd. extern void srs_close_stfd(st_netfd_t& stfd); /** * disable copy constructor of class */ #define disable_default_copy(className)\ private:\ /** \ * disable the copy constructor and operator=, donot allow directly copy. \ */ \ className(const className&); \ className& operator= (const className&) #endif<commit_msg>change version to 0.9.1<commit_after>/* The MIT License (MIT) Copyright (c) 2013-2014 winlin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef SRS_CORE_HPP #define SRS_CORE_HPP /* #include <srs_core.hpp> */ /** * the core provides the common defined macros, utilities, * user must include the srs_core.hpp before any header, or maybe * build failed. */ // for int64_t print using PRId64 format. #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include <inttypes.h> #include <assert.h> #define srs_assert(expression) assert(expression) #include <stddef.h> #include <sys/types.h> #include <st.h> // generated by configure. #include <srs_auto_headers.hpp> // free the p and set to NULL. // p must be a T*. #define srs_freep(p) \ if (p) { \ delete p; \ p = NULL; \ } \ (void)0 // free the p which represents a array #define srs_freepa(p) \ if (p) { \ delete[] p; \ p = NULL; \ } \ (void)0 // current release version #define RTMP_SIG_SRS_VERSION "0.9.1" // server info. #define RTMP_SIG_SRS_KEY "srs" #define RTMP_SIG_SRS_ROLE "origin server" #define RTMP_SIG_SRS_NAME RTMP_SIG_SRS_KEY"(simple rtmp server)" #define RTMP_SIG_SRS_URL "https://"RTMP_SIG_SRS_URL_SHORT #define RTMP_SIG_SRS_URL_SHORT "github.com/winlinvip/simple-rtmp-server" #define RTMP_SIG_SRS_WEB "http://blog.csdn.net/win_lin" #define RTMP_SIG_SRS_EMAIL "[email protected]" #define RTMP_SIG_SRS_LICENSE "The MIT License (MIT)" #define RTMP_SIG_SRS_COPYRIGHT "Copyright (c) 2013-2014 winlin" #define RTMP_SIG_SRS_PRIMARY_AUTHROS "winlin,wenjiegit" // compare #define srs_min(a, b) (((a) < (b))? (a) : (b)) #define srs_max(a, b) (((a) < (b))? (b) : (a)) // get current system time in ms, use cache to avoid performance problem extern int64_t srs_get_system_time_ms(); // the deamon st-thread will update it. extern void srs_update_system_time_ms(); // signal defines. #define SIGNAL_RELOAD SIGHUP #include <string> // replace utility extern std::string srs_replace(std::string str, std::string old_str, std::string new_str); // dns resolve utility, return the resolved ip address. extern std::string srs_dns_resolve(std::string host); // resolve the vhost in query string // @param app, may contains the vhost in query string format: // app?vhost=request_vhost // app...vhost...request_vhost extern void srs_vhost_resolve(std::string& vhost, std::string& app); // close the netfd, and close the underlayer fd. extern void srs_close_stfd(st_netfd_t& stfd); /** * disable copy constructor of class */ #define disable_default_copy(className)\ private:\ /** \ * disable the copy constructor and operator=, donot allow directly copy. \ */ \ className(const className&); \ className& operator= (const className&) #endif<|endoftext|>
<commit_before>/** * File : E.cpp * Author : Kazune Takahashi * Created : 11/25/2018, 12:14:31 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; const ll M = 1000000007; int T; ll a[310]; ll DP[310][1000]; ll cnt(ll i, ll l) { if (0 <= l && l <= a[i]) { return 1; } else { return 0; } } int main() { cin >> T; for (auto i = 1; i <= T; i++) { cin >> a[i]; } for (auto i = 0; i < 1000; i++) { DP[0][i] = 0; } DP[0][0] = 1; for (auto i = 1; i <= T; i++) { for (auto j = 0; j < 1000; j++) { DP[i][j] = 0; for (auto k = 0; k <= min(2 * j, 999); k++) { DP[i][j] += DP[i - 1][k] * cnt(i, 2 * j - k); DP[i][j] %= M; } } } for (auto i = 0; i < 4; i++) { for (auto j = 0; j < 100; j++) { cerr << "DP[" << i << "][" << j << "] = " << DP[i][j] << endl; } } ll ans = 0; for (auto i = 1; i <= T; i++) { if (a[i] > 0) { ans++; } } for (auto i = 1; i <= T; i++) { ans += DP[i][1]; ans %= M; } cout << ans << endl; }<commit_msg>tried E.cpp to 'E'<commit_after>/** * File : E.cpp * Author : Kazune Takahashi * Created : 11/25/2018, 12:14:31 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; const ll M = 1000000007; int T; ll a[310]; ll DP[310][1000]; ll cnt(ll i, ll l) { if (0 <= l && l <= a[i]) { return 1; } else { return 0; } } int main() { cin >> T; for (auto i = 1; i <= T; i++) { cin >> a[i]; } for (auto i = 0; i < 1000; i++) { DP[0][i] = 0; } DP[0][0] = 1; for (auto i = 1; i <= T; i++) { for (auto j = 0; j < 1000; j++) { DP[i][j] = 0; for (auto k = 0; k <= min(2 * j, 999); k++) { DP[i][j] += DP[i - 1][k] * cnt(i, 2 * j - k); DP[i][j] %= M; } } } for (auto i = 0; i < T; i++) { for (auto j = 0; j < 1000; j++) { cerr << "DP[" << i << "][" << j << "] = " << DP[i][j] << endl; } } ll ans = 0; for (auto i = 1; i <= T; i++) { if (a[i] > 0) { ans++; } } for (auto i = 1; i <= T; i++) { ans += DP[i][1]; ans %= M; } cout << ans << endl; }<|endoftext|>
<commit_before>AliPhysicsSelectionTask* AddTaskPhysicsSelection(Bool_t mCAnalysisFlag = kFALSE, Bool_t deprecatedFlag = kTRUE, UInt_t computeBG = 0, Bool_t useSpecialOutput=kFALSE) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskPhysicsSelection", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskPhysicsSelection", "This task requires an input event handler"); return NULL; } AliVEventHandler *inputHandler=mgr->GetInputEventHandler(); TString inputDataType = inputHandler->GetDataType(); // can be "ESD" or "AOD" // Configure analysis //=========================================================================== AliPhysicsSelectionTask *task = new AliPhysicsSelectionTask(); task->SetUseSpecialOutput(useSpecialOutput); // RS: optionally use special output // this makes physics selection to work using AliMultiInputEventHandler if (inputHandler && (inputHandler->IsA() == AliMultiInputEventHandler::Class())) { AliMultiInputEventHandler *multiInputHandler=(AliMultiInputEventHandler*)inputHandler; AliInputEventHandler *ih = multiInputHandler->GetFirstInputEventHandler(); if (!ih) { ::Error("AddTaskPhysicsSelection","ESD or AOD input handler is missing"); return NULL; } ih->SetEventSelection(multiInputHandler->GetEventSelection()); inputDataType = ih->GetDataType(); // can be "ESD" or "AOD" } mgr->AddTask(task); AliPhysicsSelection* physSel = task->GetPhysicsSelection(); if (mCAnalysisFlag) physSel->SetAnalyzeMC(); if (computeBG) physSel->SetComputeBG(computeBG); if(!deprecatedFlag) AliFatal("The BG ID flag is deprecated. Please use the OADB to configure the cuts"); AliAnalysisDataContainer *cinput0 = mgr->GetCommonInputContainer(); AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("cstatsout", TList::Class(), AliAnalysisManager::kOutputContainer, "EventStat_temp.root"); // if (useSpecialOutput) coutput1->SetSpecialOutput(); // RS: optionally use special output // mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task,1,coutput1); return task; } <commit_msg>Reverted "new AliPhysicsSelectionTask()" call to "new AliPhysicsSelectionTask("")"<commit_after>AliPhysicsSelectionTask* AddTaskPhysicsSelection(Bool_t mCAnalysisFlag = kFALSE, Bool_t deprecatedFlag = kTRUE, UInt_t computeBG = 0, Bool_t useSpecialOutput=kFALSE) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskPhysicsSelection", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskPhysicsSelection", "This task requires an input event handler"); return NULL; } AliVEventHandler *inputHandler=mgr->GetInputEventHandler(); TString inputDataType = inputHandler->GetDataType(); // can be "ESD" or "AOD" // Configure analysis //=========================================================================== AliPhysicsSelectionTask *task = new AliPhysicsSelectionTask(""); task->SetUseSpecialOutput(useSpecialOutput); // RS: optionally use special output // this makes physics selection to work using AliMultiInputEventHandler if (inputHandler && (inputHandler->IsA() == AliMultiInputEventHandler::Class())) { AliMultiInputEventHandler *multiInputHandler=(AliMultiInputEventHandler*)inputHandler; AliInputEventHandler *ih = multiInputHandler->GetFirstInputEventHandler(); if (!ih) { ::Error("AddTaskPhysicsSelection","ESD or AOD input handler is missing"); return NULL; } ih->SetEventSelection(multiInputHandler->GetEventSelection()); inputDataType = ih->GetDataType(); // can be "ESD" or "AOD" } mgr->AddTask(task); AliPhysicsSelection* physSel = task->GetPhysicsSelection(); if (mCAnalysisFlag) physSel->SetAnalyzeMC(); if (computeBG) physSel->SetComputeBG(computeBG); if(!deprecatedFlag) AliFatal("The BG ID flag is deprecated. Please use the OADB to configure the cuts"); AliAnalysisDataContainer *cinput0 = mgr->GetCommonInputContainer(); AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("cstatsout", TList::Class(), AliAnalysisManager::kOutputContainer, "EventStat_temp.root"); // if (useSpecialOutput) coutput1->SetSpecialOutput(); // RS: optionally use special output // mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task,1,coutput1); return task; } <|endoftext|>
<commit_before>#include <cassert> #include <cstring> #include <iostream> #include "Packet.h" #include "VpnPacket.h" // #define HOSTGATOR int open_raw_socket_for_listening() { static constexpr auto AF_PACKET = 17; static constexpr auto PF_PACKET = AF_PACKET; static constexpr auto SOCK_RAW_ = 3; static constexpr auto ETH_P_ALL = 0x0003; int sd_incoming = socket(PF_PACKET, SOCK_RAW_, htons(ETH_P_ALL)); return sd_incoming; } int main() { int sd_incoming = open_raw_socket_for_listening(); if (sd_incoming == -1) { std::cerr << "Error while opening raw socket: socket() error " << errno << ": " << strerror(errno) << std::endl; exit(1); } std::cout << "Listening on the wire..." << std::endl; while (true) { // Raw packet capture uint8_t buffer[Ip::IP_MAXPACKET]; socklen_t size; struct sockaddr_in from; socklen_t fromlen = sizeof(from); size = recvfrom(sd_incoming, reinterpret_cast<char*>(buffer), sizeof(buffer), 0, reinterpret_cast<struct sockaddr*>(&from), &fromlen); // std::cout << std::endl << "Receiving " << size << " bytes" << std::endl; // There are two possible cases: // 1. In HostGator VPS, we receive IP packets (layer 3). // 2. In Linux box, we receive DataLink packets (layer 2). // So it is better to use IP packets since it works everywhere. Ip* ip; #ifdef HOSTGATOR // Layer 3: IP packet ip = reinterpret_cast<Ip*>(buffer); #else { // Layer 2: Ethernet packet Eth* eth = reinterpret_cast<Eth*>(buffer); eth->print_header(); eth->print_header_raw(); if (ntohs(eth->h_proto) != Eth::ETH_P_IP) continue; // Layer 3: IP packet ip = reinterpret_cast<Ip*>(eth->payload()); size -= eth->header_len(); } #endif // HOSTGATOR // Layer 3 ip->print_header(); ip->print_header_raw(); { // Verify that our IP checksum algorithm is correct uint16_t original_checksum = ip->check; ip->check = 0; ip->check = ip->checksum(); if (ip->check != original_checksum) { std::cerr << "IP checksum does not match " << original_checksum << " != " << ip->check << std::endl; } } // Layer 4 switch (ip->protocol) { case Ip::IPPROTO_TCP: { Tcp* tcp = reinterpret_cast<Tcp*>(ip->payload()); // Skip processing SSH packets if (ntohs(tcp->source) == 22 || ntohs(tcp->dest) == 22) { continue; } tcp->print_header(); tcp->print_header_raw(); std::cout << "Payload:" << std::endl; Util::print_raw(tcp->payload(), ip->total_len() - ip->header_len() - tcp->header_len()); { // Verify that our TCP checksum algorithm is correct // How to disable checksum offloading: ethtool -K eth0 rx off tx off (https://stackoverflow.com/questions/15538786/how-is-tcps-checksum-calculated-when-we-use-tcpdump-to-capture-packets-which-we) int len = ip->total_len() - ip->header_len(); uint16_t original_checksum = tcp->check; tcp->check = 0; tcp->check = tcp->checksum(len, ip->saddr, ip->daddr); if (tcp->check != original_checksum) { std::cerr << "TCP checksum does not match " << original_checksum << " != " << tcp->check << std::endl; } } std::cout << std::endl; break; } case Ip::IPPROTO_UDP: { Udp* udp = reinterpret_cast<Udp*>(ip->payload()); udp->print_header(); udp->print_header_raw(); std::cout << "Payload:" << std::endl; udp->print_payload_raw(); // std::cout << "Payload:" << std::endl; // Util::print_raw(udp->payload(), ip->total_len() - ip->header_len() - udp->header_len()); { // Verify that our UDP checksum algorithm is correct int len = ip->total_len() - ip->header_len(); uint16_t original_checksum = udp->check; udp->check = 0; udp->check = udp->checksum(len, ip->saddr, ip->daddr); if (udp->check != original_checksum) { std::cerr << "UDP checksum does not match " << original_checksum << " != " << udp->check << std::endl; } } std::cout << std::endl; break; } case Ip::IPPROTO_ICMP: { Icmp* icmp = reinterpret_cast<Icmp*>(ip->payload()); icmp->print_header(); { // Verify that our ICMP checksum algorithm is correct int len = ip->total_len() - ip->header_len(); uint16_t original_checksum = icmp->check; icmp->check = 0; icmp->check = icmp->checksum(len); if (icmp->check != original_checksum) { std::cerr << "ICMP checksum does not match " << original_checksum << " != " << icmp->check << std::endl; } } std::cout << std::endl; break; } default: // Ignore non TCP, UDP or ICMP packet continue; } } return 0; } <commit_msg>Print known packets only<commit_after>#include <cassert> #include <cstring> #include <iostream> #include "Packet.h" #include "VpnPacket.h" // #define HOSTGATOR int open_raw_socket_for_listening() { static constexpr auto AF_PACKET = 17; static constexpr auto PF_PACKET = AF_PACKET; static constexpr auto SOCK_RAW_ = 3; static constexpr auto ETH_P_ALL = 0x0003; int sd_incoming = socket(PF_PACKET, SOCK_RAW_, htons(ETH_P_ALL)); return sd_incoming; } int main() { int sd_incoming = open_raw_socket_for_listening(); if (sd_incoming == -1) { std::cerr << "Error while opening raw socket: socket() error " << errno << ": " << strerror(errno) << std::endl; exit(1); } std::cout << "Listening on the wire..." << std::endl; while (true) { // Raw packet capture uint8_t buffer[Ip::IP_MAXPACKET]; socklen_t size; struct sockaddr_in from; socklen_t fromlen = sizeof(from); size = recvfrom(sd_incoming, reinterpret_cast<char*>(buffer), sizeof(buffer), 0, reinterpret_cast<struct sockaddr*>(&from), &fromlen); // std::cout << std::endl << "Receiving " << size << " bytes" << std::endl; // There are two possible cases: // 1. In HostGator VPS, we receive IP packets (layer 3). // 2. In Linux box, we receive DataLink packets (layer 2). // So it is better to use IP packets since it works everywhere. Ip* ip; #ifdef HOSTGATOR // Layer 3: IP packet ip = reinterpret_cast<Ip*>(buffer); #else { // Layer 2: Ethernet packet Eth* eth = reinterpret_cast<Eth*>(buffer); // eth->print_header(); // eth->print_header_raw(); if (ntohs(eth->h_proto) != Eth::ETH_P_IP) continue; // Layer 3: IP packet ip = reinterpret_cast<Ip*>(eth->payload()); size -= eth->header_len(); } #endif // HOSTGATOR // Layer 3 { // Verify that our IP checksum algorithm is correct uint16_t original_checksum = ip->check; ip->check = 0; ip->check = ip->checksum(); if (ip->check != original_checksum) { std::cerr << "IP checksum does not match " << original_checksum << " != " << ip->check << std::endl; } } // Layer 4 switch (ip->protocol) { case Ip::IPPROTO_TCP: { Tcp* tcp = reinterpret_cast<Tcp*>(ip->payload()); // Skip processing SSH packets if (ntohs(tcp->source) == 22 || ntohs(tcp->dest) == 22) { continue; } ip->print_header(); ip->print_header_raw(); tcp->print_header(); tcp->print_header_raw(); std::cout << "Payload:" << std::endl; Util::print_raw(tcp->payload(), ip->total_len() - ip->header_len() - tcp->header_len()); { // Verify that our TCP checksum algorithm is correct // How to disable checksum offloading: ethtool -K eth0 rx off tx off (https://stackoverflow.com/questions/15538786/how-is-tcps-checksum-calculated-when-we-use-tcpdump-to-capture-packets-which-we) int len = ip->total_len() - ip->header_len(); uint16_t original_checksum = tcp->check; tcp->check = 0; tcp->check = tcp->checksum(len, ip->saddr, ip->daddr); if (tcp->check != original_checksum) { std::cerr << "TCP checksum does not match " << original_checksum << " != " << tcp->check << std::endl; } } std::cout << std::endl; break; } case Ip::IPPROTO_UDP: { Udp* udp = reinterpret_cast<Udp*>(ip->payload()); ip->print_header(); ip->print_header_raw(); udp->print_header(); udp->print_header_raw(); std::cout << "Payload:" << std::endl; udp->print_payload_raw(); // std::cout << "Payload:" << std::endl; // Util::print_raw(udp->payload(), ip->total_len() - ip->header_len() - udp->header_len()); { // Verify that our UDP checksum algorithm is correct int len = ip->total_len() - ip->header_len(); uint16_t original_checksum = udp->check; udp->check = 0; udp->check = udp->checksum(len, ip->saddr, ip->daddr); if (udp->check != original_checksum) { std::cerr << "UDP checksum does not match " << original_checksum << " != " << udp->check << std::endl; } } std::cout << std::endl; break; } case Ip::IPPROTO_ICMP: { Icmp* icmp = reinterpret_cast<Icmp*>(ip->payload()); ip->print_header(); ip->print_header_raw(); icmp->print_header(); { // Verify that our ICMP checksum algorithm is correct int len = ip->total_len() - ip->header_len(); uint16_t original_checksum = icmp->check; icmp->check = 0; icmp->check = icmp->checksum(len); if (icmp->check != original_checksum) { std::cerr << "ICMP checksum does not match " << original_checksum << " != " << icmp->check << std::endl; } } std::cout << std::endl; break; } default: // Ignore non TCP, UDP or ICMP packet continue; } } return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2009 Manjeet Dahiya * * Author: * Manjeet Dahiya * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include "QXmppStanza.h" #include "QXmppUtils.h" #include "QXmppConstants.h" #include <QDomElement> #include <QXmlStreamWriter> uint QXmppStanza::s_uniqeIdNo = 0; QXmppStanza::Error::Error(): m_type(static_cast<QXmppStanza::Error::Type>(-1)), m_code(0), m_condition(static_cast<QXmppStanza::Error::Condition>(-1)), m_text("") { } QXmppStanza::Error::Error(Type type, Condition cond, const QString& text): m_type(type), m_code(0), m_condition(cond), m_text(text) { } QXmppStanza::Error::Error(const QString& type, const QString& cond, const QString& text): m_code(0), m_text(text) { setTypeFromStr(type); setConditionFromStr(cond); } void QXmppStanza::Error::setText(const QString& text) { m_text = text; } void QXmppStanza::Error::setCode(int code) { m_code = code; } void QXmppStanza::Error::setCondition(QXmppStanza::Error::Condition cond) { m_condition = cond; } void QXmppStanza::Error::setType(QXmppStanza::Error::Type type) { m_type = type; } QString QXmppStanza::Error::getText() const { return m_text; } int QXmppStanza::Error::getCode() const { return m_code; } QXmppStanza::Error::Condition QXmppStanza::Error::getCondition() const { return m_condition; } QXmppStanza::Error::Type QXmppStanza::Error::getType() const { return m_type; } QString QXmppStanza::Error::getTypeStr() const { switch(getType()) { case Cancel: return "cancel"; case Continue: return "continue"; case Modify: return "modify"; case Auth: return "auth"; case Wait: return "wait"; default: return ""; } } QString QXmppStanza::Error::getConditionStr() const { switch(getCondition()) { case BadRequest: return "bad-request"; case Conflict: return "conflict"; case FeatureNotImplemented: return "feature-not-implemented"; case Forbidden: return "forbidden"; case Gone: return "gone"; case InternalServerError: return "internal-server-error"; case ItemNotFound: return "item-not-found"; case JidMalformed: return "jid-malformed"; case NotAcceptable: return "not-acceptable"; case NotAllowed: return "not-allowed"; case NotAuthorized: return "not-authorized"; case PaymentRequired: return "payment-required"; case RecipientUnavailable: return "recipient-unavailable"; case Redirect: return "redirect"; case RegistrationRequired: return "registration-required"; case RemoteServerNotFound: return "remote-server-not-found"; case RemoteServerTimeout: return "remote-server-timeout"; case ResourceConstraint: return "resource-constraint"; case ServiceUnavailable: return "service-unavailable"; case SubscriptionRequired: return "subscription-required"; case UndefinedCondition: return "undefined-condition"; case UnexpectedRequest: return "unexpected-request"; default: return ""; } } void QXmppStanza::Error::setTypeFromStr(const QString& type) { if(type == "cancel") setType(Cancel); else if(type == "continue") setType(Continue); else if(type == "modify") setType(Modify); else if(type == "auth") setType(Auth); else if(type == "wait") setType(Wait); else setType(static_cast<QXmppStanza::Error::Type>(-1)); } void QXmppStanza::Error::setConditionFromStr(const QString& type) { if(type == "bad-request") setCondition(BadRequest); else if(type == "conflict") setCondition(Conflict); else if(type == "feature-not-implemented") setCondition(FeatureNotImplemented); else if(type == "forbidden") setCondition(Forbidden); else if(type == "gone") setCondition(Gone); else if(type == "internal-server-error") setCondition(InternalServerError); else if(type == "item-not-found") setCondition(ItemNotFound); else if(type == "jid-malformed") setCondition(JidMalformed); else if(type == "not-acceptable") setCondition(NotAcceptable); else if(type == "not-allowed") setCondition(NotAllowed); else if(type == "not-authorized") setCondition(NotAuthorized); else if(type == "payment-required") setCondition(PaymentRequired); else if(type == "recipient-unavailable") setCondition(RecipientUnavailable); else if(type == "redirect") setCondition(Redirect); else if(type == "registration-required") setCondition(RegistrationRequired); else if(type == "remote-server-not-found") setCondition(RemoteServerNotFound); else if(type == "remote-server-timeout") setCondition(RemoteServerTimeout); else if(type == "resource-constraint") setCondition(ResourceConstraint); else if(type == "service-unavailable") setCondition(ServiceUnavailable); else if(type == "subscription-required") setCondition(SubscriptionRequired); else if(type == "undefined-condition") setCondition(UndefinedCondition); else if(type == "unexpected-request") setCondition(UnexpectedRequest); else setCondition(static_cast<QXmppStanza::Error::Condition>(-1)); } void QXmppStanza::Error::toXml( QXmlStreamWriter *writer ) const { QString cond = getConditionStr(); QString type = getTypeStr(); if(cond.isEmpty() && type.isEmpty()) return; writer->writeStartElement("error"); helperToXmlAddAttribute(writer, "type", type); if (m_code > 0) helperToXmlAddAttribute(writer, "code", QString::number(m_code)); if(!cond.isEmpty()) { writer->writeStartElement(cond); helperToXmlAddAttribute(writer,"xmlns", ns_stanza); writer->writeEndElement(); } if(!m_text.isEmpty()) { writer->writeStartElement("text"); helperToXmlAddAttribute(writer,"xml:lang", "en"); helperToXmlAddAttribute(writer,"xmlns", ns_stanza); writer->writeCharacters(m_text); writer->writeEndElement(); } writer->writeEndElement(); } QXmppStanza::QXmppStanza(const QString& from, const QString& to) : QXmppPacket(), m_to(to), m_from(from) { } QXmppStanza::~QXmppStanza() { } QString QXmppStanza::getTo() const { return m_to; } QString QXmppStanza::getFrom() const { return m_from; } QString QXmppStanza::getId() const { return m_id; } QString QXmppStanza::getLang() const { return m_lang; } void QXmppStanza::setTo(const QString& to) { m_to = to; } void QXmppStanza::setFrom(const QString& from) { m_from = from; } void QXmppStanza::setId(const QString& id) { m_id = id; } void QXmppStanza::setLang(const QString& lang) { m_lang = lang; } void QXmppStanza::generateAndSetNextId() { // get back ++s_uniqeIdNo; m_id = "qxmpp" + QString::number(s_uniqeIdNo); } QXmppStanza::Error QXmppStanza::getError() const { return m_error; } void QXmppStanza::setError(QXmppStanza::Error& error) { m_error = error; } QXmppElementList QXmppStanza::getExtensions() const { return m_extensions; } void QXmppStanza::setExtensions(const QXmppElementList &extensions) { m_extensions = extensions; } bool QXmppStanza::isErrorStanza() { return !(m_error.getTypeStr().isEmpty() && m_error.getConditionStr().isEmpty()); } QXmppStanza::Error QXmppStanza::parseError(const QDomElement &errorElement) { QXmppStanza::Error error; if(errorElement.isNull()) return error; QString type = errorElement.attribute("type"); QString text; QString cond; QDomElement element = errorElement.firstChildElement(); while(!element.isNull()) { if(element.tagName() == "text") text = element.text(); else if(element.namespaceURI() == ns_stanza) { cond = element.tagName(); } element = element.nextSiblingElement(); } error.setCode(errorElement.attribute("code").toInt()); error.setConditionFromStr(cond); error.setTypeFromStr(type); error.setText(text); return error; } <commit_msg>fix for compile time warning messages<commit_after>/* * Copyright (C) 2008-2009 Manjeet Dahiya * * Author: * Manjeet Dahiya * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include "QXmppStanza.h" #include "QXmppUtils.h" #include "QXmppConstants.h" #include <QDomElement> #include <QXmlStreamWriter> uint QXmppStanza::s_uniqeIdNo = 0; QXmppStanza::Error::Error(): m_code(0), m_type(static_cast<QXmppStanza::Error::Type>(-1)), m_condition(static_cast<QXmppStanza::Error::Condition>(-1)), m_text("") { } QXmppStanza::Error::Error(Type type, Condition cond, const QString& text): m_code(0), m_type(type), m_condition(cond), m_text(text) { } QXmppStanza::Error::Error(const QString& type, const QString& cond, const QString& text): m_code(0), m_text(text) { setTypeFromStr(type); setConditionFromStr(cond); } void QXmppStanza::Error::setText(const QString& text) { m_text = text; } void QXmppStanza::Error::setCode(int code) { m_code = code; } void QXmppStanza::Error::setCondition(QXmppStanza::Error::Condition cond) { m_condition = cond; } void QXmppStanza::Error::setType(QXmppStanza::Error::Type type) { m_type = type; } QString QXmppStanza::Error::getText() const { return m_text; } int QXmppStanza::Error::getCode() const { return m_code; } QXmppStanza::Error::Condition QXmppStanza::Error::getCondition() const { return m_condition; } QXmppStanza::Error::Type QXmppStanza::Error::getType() const { return m_type; } QString QXmppStanza::Error::getTypeStr() const { switch(getType()) { case Cancel: return "cancel"; case Continue: return "continue"; case Modify: return "modify"; case Auth: return "auth"; case Wait: return "wait"; default: return ""; } } QString QXmppStanza::Error::getConditionStr() const { switch(getCondition()) { case BadRequest: return "bad-request"; case Conflict: return "conflict"; case FeatureNotImplemented: return "feature-not-implemented"; case Forbidden: return "forbidden"; case Gone: return "gone"; case InternalServerError: return "internal-server-error"; case ItemNotFound: return "item-not-found"; case JidMalformed: return "jid-malformed"; case NotAcceptable: return "not-acceptable"; case NotAllowed: return "not-allowed"; case NotAuthorized: return "not-authorized"; case PaymentRequired: return "payment-required"; case RecipientUnavailable: return "recipient-unavailable"; case Redirect: return "redirect"; case RegistrationRequired: return "registration-required"; case RemoteServerNotFound: return "remote-server-not-found"; case RemoteServerTimeout: return "remote-server-timeout"; case ResourceConstraint: return "resource-constraint"; case ServiceUnavailable: return "service-unavailable"; case SubscriptionRequired: return "subscription-required"; case UndefinedCondition: return "undefined-condition"; case UnexpectedRequest: return "unexpected-request"; default: return ""; } } void QXmppStanza::Error::setTypeFromStr(const QString& type) { if(type == "cancel") setType(Cancel); else if(type == "continue") setType(Continue); else if(type == "modify") setType(Modify); else if(type == "auth") setType(Auth); else if(type == "wait") setType(Wait); else setType(static_cast<QXmppStanza::Error::Type>(-1)); } void QXmppStanza::Error::setConditionFromStr(const QString& type) { if(type == "bad-request") setCondition(BadRequest); else if(type == "conflict") setCondition(Conflict); else if(type == "feature-not-implemented") setCondition(FeatureNotImplemented); else if(type == "forbidden") setCondition(Forbidden); else if(type == "gone") setCondition(Gone); else if(type == "internal-server-error") setCondition(InternalServerError); else if(type == "item-not-found") setCondition(ItemNotFound); else if(type == "jid-malformed") setCondition(JidMalformed); else if(type == "not-acceptable") setCondition(NotAcceptable); else if(type == "not-allowed") setCondition(NotAllowed); else if(type == "not-authorized") setCondition(NotAuthorized); else if(type == "payment-required") setCondition(PaymentRequired); else if(type == "recipient-unavailable") setCondition(RecipientUnavailable); else if(type == "redirect") setCondition(Redirect); else if(type == "registration-required") setCondition(RegistrationRequired); else if(type == "remote-server-not-found") setCondition(RemoteServerNotFound); else if(type == "remote-server-timeout") setCondition(RemoteServerTimeout); else if(type == "resource-constraint") setCondition(ResourceConstraint); else if(type == "service-unavailable") setCondition(ServiceUnavailable); else if(type == "subscription-required") setCondition(SubscriptionRequired); else if(type == "undefined-condition") setCondition(UndefinedCondition); else if(type == "unexpected-request") setCondition(UnexpectedRequest); else setCondition(static_cast<QXmppStanza::Error::Condition>(-1)); } void QXmppStanza::Error::toXml( QXmlStreamWriter *writer ) const { QString cond = getConditionStr(); QString type = getTypeStr(); if(cond.isEmpty() && type.isEmpty()) return; writer->writeStartElement("error"); helperToXmlAddAttribute(writer, "type", type); if (m_code > 0) helperToXmlAddAttribute(writer, "code", QString::number(m_code)); if(!cond.isEmpty()) { writer->writeStartElement(cond); helperToXmlAddAttribute(writer,"xmlns", ns_stanza); writer->writeEndElement(); } if(!m_text.isEmpty()) { writer->writeStartElement("text"); helperToXmlAddAttribute(writer,"xml:lang", "en"); helperToXmlAddAttribute(writer,"xmlns", ns_stanza); writer->writeCharacters(m_text); writer->writeEndElement(); } writer->writeEndElement(); } QXmppStanza::QXmppStanza(const QString& from, const QString& to) : QXmppPacket(), m_to(to), m_from(from) { } QXmppStanza::~QXmppStanza() { } QString QXmppStanza::getTo() const { return m_to; } QString QXmppStanza::getFrom() const { return m_from; } QString QXmppStanza::getId() const { return m_id; } QString QXmppStanza::getLang() const { return m_lang; } void QXmppStanza::setTo(const QString& to) { m_to = to; } void QXmppStanza::setFrom(const QString& from) { m_from = from; } void QXmppStanza::setId(const QString& id) { m_id = id; } void QXmppStanza::setLang(const QString& lang) { m_lang = lang; } void QXmppStanza::generateAndSetNextId() { // get back ++s_uniqeIdNo; m_id = "qxmpp" + QString::number(s_uniqeIdNo); } QXmppStanza::Error QXmppStanza::getError() const { return m_error; } void QXmppStanza::setError(QXmppStanza::Error& error) { m_error = error; } QXmppElementList QXmppStanza::getExtensions() const { return m_extensions; } void QXmppStanza::setExtensions(const QXmppElementList &extensions) { m_extensions = extensions; } bool QXmppStanza::isErrorStanza() { return !(m_error.getTypeStr().isEmpty() && m_error.getConditionStr().isEmpty()); } QXmppStanza::Error QXmppStanza::parseError(const QDomElement &errorElement) { QXmppStanza::Error error; if(errorElement.isNull()) return error; QString type = errorElement.attribute("type"); QString text; QString cond; QDomElement element = errorElement.firstChildElement(); while(!element.isNull()) { if(element.tagName() == "text") text = element.text(); else if(element.namespaceURI() == ns_stanza) { cond = element.tagName(); } element = element.nextSiblingElement(); } error.setCode(errorElement.attribute("code").toInt()); error.setConditionFromStr(cond); error.setTypeFromStr(type); error.setText(text); return error; } <|endoftext|>
<commit_before>// Copyright 2017 Adam Smith // 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 <type_traits> #include <cstdint> #include <string> #include <memory> #include <vector> #ifndef ASMITH_REFLECTION_CLASS_HPP #define ASMITH_REFLECTION_CLASS_HPP namespace asmith { class reflection_variable; class reflection_function; class reflection_constructor; class reflection_destructor; class reflection_class { public: virtual ~reflection_class() {} virtual const char* get_name() const = 0; virtual size_t get_size() const = 0; virtual size_t get_variable_count() const = 0; virtual const reflection_variable& get_variable(size_t) const = 0; virtual size_t get_function_count() const = 0; virtual const reflection_function& get_function(size_t) const = 0; virtual size_t get_constructor_count() const = 0; virtual const reflection_constructor& get_constructor(size_t) const = 0; virtual const reflection_destructor& get_destructor() const = 0; virtual size_t get_parent_count() const = 0; virtual const reflection_class& get_parent_class(size_t) const = 0; }; class auto_reflection_class : public reflection_class { private: std::vector<std::shared_ptr<reflection_class>> mParents; std::vector<std::shared_ptr<reflection_constructor>> mConstructors; std::vector<std::shared_ptr<reflection_variable>> mVariables; std::vector<std::shared_ptr<reflection_function>> mFunctions; std::shared_ptr<reflection_destructor> mDestructor; const std::string mName; const size_t mSize; public: auto_reflection_class(const std::string& aName, const size_t aSize) : mName(aName), mSize(aSize) {} //! \todo Add parent_classes, constructors, variables and destructor template<class CLASS, class RETURN, class... PARAMS> auto_reflection_class& function(const std::string& aName, RETURN(CLASS::*aPtr)(PARAMS...), const size_t aModifiers) { mFunctions.push_back(std::shared_ptr<reflection_function>( new typedef auto_reflection_function<CLASS, RETURN, PARAMS...>(aName, aPtr, aModifiers); )); return *this; } // Inherited from reflection_class const char* get_name() const override { mName.c_str(); } size_t get_size() const override { return mSize; } size_t get_variable_count() const override { return mVariables.size(); } const reflection_variable& get_variable(size_t aIndex) const override { return *mVariables[aIndex]; } size_t get_function_count() const override { return mFunctions.size(); } const reflection_function& get_function(size_t aIndex) const override { return *mFunctions[aIndex]; } size_t get_constructor_count() const override { return mConstructors.size(); } const reflection_constructor& get_constructor(size_t aIndex) const override { return *mConstructors[aIndex]; } const reflection_destructor& get_destructor() const override { return *mDestructor; } size_t get_parent_count() const override { return mParents.size(); } const reflection_class& get_parent_class(size_t aIndex) const override { return *mParents[aIndex]; } }; } #endif<commit_msg>Reflect function & parent classes<commit_after>// Copyright 2017 Adam Smith // 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 <type_traits> #include <cstdint> #include <string> #include <memory> #include <vector> #ifndef ASMITH_REFLECTION_CLASS_HPP #define ASMITH_REFLECTION_CLASS_HPP namespace asmith { class reflection_variable; class reflection_function; class reflection_constructor; class reflection_destructor; class reflection_class { public: virtual ~reflection_class() {} virtual const char* get_name() const = 0; virtual size_t get_size() const = 0; virtual size_t get_variable_count() const = 0; virtual const reflection_variable& get_variable(size_t) const = 0; virtual size_t get_function_count() const = 0; virtual const reflection_function& get_function(size_t) const = 0; virtual size_t get_constructor_count() const = 0; virtual const reflection_constructor& get_constructor(size_t) const = 0; virtual const reflection_destructor& get_destructor() const = 0; virtual size_t get_parent_count() const = 0; virtual const reflection_class& get_parent_class(size_t) const = 0; }; template<class T> const reflection_class& reflect() { return T::REFLECTION; } class auto_reflection_class : public reflection_class { private: std::vector<const reflection_class*> mParents; std::vector<std::shared_ptr<reflection_constructor>> mConstructors; std::vector<std::shared_ptr<reflection_variable>> mVariables; std::vector<std::shared_ptr<reflection_function>> mFunctions; std::shared_ptr<reflection_destructor> mDestructor; const std::string mName; const size_t mSize; public: auto_reflection_class(const std::string& aName, const size_t aSize) : mName(aName), mSize(aSize) {} //! \todo Add constructors, variables and destructor template<class CLASS> auto_reflection_class& parent() { mFunctions.push_back(&reflect<CLASS>()); return *this; } template<class CLASS, class RETURN, class... PARAMS> auto_reflection_class& function(const std::string& aName, RETURN(CLASS::*aPtr)(PARAMS...), const size_t aModifiers) { mFunctions.push_back(std::shared_ptr<reflection_function>( new typedef auto_reflection_function<CLASS, RETURN, PARAMS...>(aName, aPtr, aModifiers); )); return *this; } // Inherited from reflection_class const char* get_name() const override { mName.c_str(); } size_t get_size() const override { return mSize; } size_t get_variable_count() const override { return mVariables.size(); } const reflection_variable& get_variable(size_t aIndex) const override { return *mVariables[aIndex]; } size_t get_function_count() const override { return mFunctions.size(); } const reflection_function& get_function(size_t aIndex) const override { return *mFunctions[aIndex]; } size_t get_constructor_count() const override { return mConstructors.size(); } const reflection_constructor& get_constructor(size_t aIndex) const override { return *mConstructors[aIndex]; } const reflection_destructor& get_destructor() const override { return *mDestructor; } size_t get_parent_count() const override { return mParents.size(); } const reflection_class& get_parent_class(size_t aIndex) const override { return *mParents[aIndex]; } }; } #endif<|endoftext|>
<commit_before>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_CORE_MAIN_MENU_MAIN_MENU_HPP #define RJ_CORE_MAIN_MENU_MAIN_MENU_HPP #include "background.hpp" #include "component_manager.hpp" #include "items.hpp" #include "menu_levels.hpp" #include "menu_start.hpp" #include "submenu_manager.hpp" #include "title.hpp" #include <rectojump/core/game_window.hpp> #include <rectojump/core/render.hpp> #include <rectojump/game/background/background_manager.hpp> #include <rectojump/game/components/player.hpp> #include <rectojump/game/factory.hpp> #include <rectojump/global/common.hpp> #include <rectojump/global/config_settings.hpp> #include <rectojump/shared/level_manager/level_manager.hpp> #include <rectojump/shared/data_manager.hpp> #include <rectojump/shared/utils.hpp> #include <SFML/Graphics.hpp> namespace rj { template<typename Game_Handler> class main_menu { Game_Handler& m_gamehandler; game_window& m_gamewindow; data_manager& m_datamgr; level_manager& m_lvmgr; background_manager& m_backgroundmgr; sf::Font m_font{m_datamgr.get_as<sf::Font>("Fipps-Regular.otf")}; const vec2f m_center{/*settings::get_window_size<vec2f>() / 2.f*/}; // TODO: clang frontend crash const sf::Color m_def_fontcolor{to_rgb("#797979") /*"#797979"_rgb*/}; // TODO: QTC dont supports that custom literals yet const sf::Color m_act_fontcolor{to_rgb("#f15ede") /*"#f15ede"_rgb*/}; // background background<main_menu<Game_Handler>> m_background{*this}; // components (menus) component_manager<main_menu<Game_Handler>> m_componentmgr{*this}; comp_ptr<menu_start<main_menu<Game_Handler>>> m_start{m_componentmgr.template create_comp<menu_start<main_menu<Game_Handler>>, menu_state::menu_start>()}; comp_ptr<menu_levels<main_menu<Game_Handler>>> m_levels{m_componentmgr.template create_comp<menu_levels<main_menu<Game_Handler>>, menu_state::menu_levels>()}; // other components (not menus) title m_title; // menu state submenu_manager<menu_state, menu_state::menu_start> m_submenumgr; mlk::event_delegates<menu_state> m_on_menu_switch; public: main_menu(Game_Handler& gh) : m_gamehandler{gh}, m_gamewindow{gh.get_gamewindow()}, m_datamgr{gh.get_datamgr()}, m_lvmgr{gh.get_levelmgr()}, m_backgroundmgr{gh.get_backgroundmgr()}, m_center{settings::get_window_size<vec2f>() / 2.f}, m_title{m_gamehandler.get_render(), m_font, m_center} {this->init();} void update(dur duration) { m_submenumgr.update_current_state(duration); m_background.update(duration); m_title.update(duration); } void render() { m_background.render(); m_submenumgr.render_current_state(); m_title.render(); } void on_key_up() {m_submenumgr.event_up();} void on_key_down() {m_submenumgr.event_down();} void on_key_backspace() { // activate prev state from submenu auto ptr(m_componentmgr.get_comp_from_type(m_submenumgr.get_current_state())); if(ptr != nullptr) if(ptr->is_accessing_submenu()) { ptr->on_key_backspace(); return; } // activate prev state this->do_menu_switch_back(); } bool is_active(menu_state s) const noexcept {return m_submenumgr.get_current_state() == s;} void call_current_itemevent() {m_submenumgr.event_current();} void do_menu_switch(menu_state s) { m_submenumgr.switch_state(s); m_on_menu_switch[s](); } void do_menu_switch_back() { m_submenumgr.activate_prev_state(); m_on_menu_switch[m_submenumgr.get_current_state()](); } auto get_gamehandler() -> decltype(m_gamehandler)& {return m_gamehandler;} const sf::Font& get_font() const noexcept {return m_font;} const vec2f& get_center() const noexcept {return m_center;} const sf::Color& get_act_fontcolor() const noexcept {return m_act_fontcolor;} const sf::Color& get_def_fontcolor() const noexcept {return m_def_fontcolor;} private: void init() { m_submenumgr.add_menu(menu_state::menu_start, m_start); m_submenumgr.add_menu(menu_state::menu_levels, m_levels); this->setup_events(); this->setup_interface(); } void setup_events() { // menu switch m_on_menu_switch[menu_state::menu_levels] += [this]{m_title.set_text("Levels");}; m_on_menu_switch[menu_state::menu_start] += [this]{m_title.set_text("Recto Jump");}; // start menu: // item events: m_start->get_items().on_event("play", [this]{this->do_menu_switch(menu_state::menu_levels);}); m_start->get_items().on_event("editor", [this]{}); m_start->get_items().on_event("quit", [this]{m_gamewindow.stop();}); // level menu: // item events: m_levels->get_items().on_event("lv_download", [this]{m_gamehandler.get_popupmgr().create_popup("Not available yet.");}); // level_squares events: m_levels->on_level_load += [this](const level_id& id){m_gamehandler.load_level(id);}; } void setup_interface() { } }; } #endif // RJ_CORE_MAIN_MENU_MAIN_MENU_HPP <commit_msg>main_menu: added menu getters<commit_after>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_CORE_MAIN_MENU_MAIN_MENU_HPP #define RJ_CORE_MAIN_MENU_MAIN_MENU_HPP #include "background.hpp" #include "component_manager.hpp" #include "items.hpp" #include "menu_levels.hpp" #include "menu_start.hpp" #include "submenu_manager.hpp" #include "title.hpp" #include <rectojump/core/game_window.hpp> #include <rectojump/core/render.hpp> #include <rectojump/game/background/background_manager.hpp> #include <rectojump/game/components/player.hpp> #include <rectojump/game/factory.hpp> #include <rectojump/global/common.hpp> #include <rectojump/global/config_settings.hpp> #include <rectojump/shared/level_manager/level_manager.hpp> #include <rectojump/shared/data_manager.hpp> #include <rectojump/shared/utils.hpp> #include <SFML/Graphics.hpp> namespace rj { template<typename Game_Handler> class main_menu { Game_Handler& m_gamehandler; game_window& m_gamewindow; data_manager& m_datamgr; level_manager& m_lvmgr; background_manager& m_backgroundmgr; sf::Font m_font{m_datamgr.get_as<sf::Font>("Fipps-Regular.otf")}; const vec2f m_center{/*settings::get_window_size<vec2f>() / 2.f*/}; // TODO: clang frontend crash const sf::Color m_def_fontcolor{to_rgb("#797979") /*"#797979"_rgb*/}; // TODO: QTC dont supports that custom literals yet const sf::Color m_act_fontcolor{to_rgb("#f15ede") /*"#f15ede"_rgb*/}; // background background<main_menu<Game_Handler>> m_background{*this}; // components (menus) component_manager<main_menu<Game_Handler>> m_componentmgr{*this}; comp_ptr<menu_start<main_menu<Game_Handler>>> m_start{m_componentmgr.template create_comp<menu_start<main_menu<Game_Handler>>, menu_state::menu_start>()}; comp_ptr<menu_levels<main_menu<Game_Handler>>> m_levels{m_componentmgr.template create_comp<menu_levels<main_menu<Game_Handler>>, menu_state::menu_levels>()}; // other components (not menus) title m_title; // menu state submenu_manager<menu_state, menu_state::menu_start> m_submenumgr; mlk::event_delegates<menu_state> m_on_menu_switch; public: main_menu(Game_Handler& gh) : m_gamehandler{gh}, m_gamewindow{gh.get_gamewindow()}, m_datamgr{gh.get_datamgr()}, m_lvmgr{gh.get_levelmgr()}, m_backgroundmgr{gh.get_backgroundmgr()}, m_center{settings::get_window_size<vec2f>() / 2.f}, m_title{m_gamehandler.get_render(), m_font, m_center} {this->init();} void update(dur duration) { m_submenumgr.update_current_state(duration); m_background.update(duration); m_title.update(duration); } void render() { m_background.render(); m_submenumgr.render_current_state(); m_title.render(); } void on_key_up() {m_submenumgr.event_up();} void on_key_down() {m_submenumgr.event_down();} void on_key_backspace() { // activate prev state from submenu auto ptr(m_componentmgr.get_comp_from_type(m_submenumgr.get_current_state())); if(ptr != nullptr) if(ptr->is_accessing_submenu()) { ptr->on_key_backspace(); return; } // activate prev state this->do_menu_switch_back(); } bool is_active(menu_state s) const noexcept {return m_submenumgr.get_current_state() == s;} void call_current_itemevent() {m_submenumgr.event_current();} void do_menu_switch(menu_state s) { m_submenumgr.switch_state(s); m_on_menu_switch[s](); } void do_menu_switch_back() { m_submenumgr.activate_prev_state(); m_on_menu_switch[m_submenumgr.get_current_state()](); } auto get_gamehandler() noexcept -> decltype(m_gamehandler)& {return m_gamehandler;} auto get_menu_start() noexcept -> decltype(m_start)& {return m_start;} auto get_menu_levels() noexcept -> decltype(m_levels)& {return m_levels;} const sf::Font& get_font() const noexcept {return m_font;} const vec2f& get_center() const noexcept {return m_center;} const sf::Color& get_act_fontcolor() const noexcept {return m_act_fontcolor;} const sf::Color& get_def_fontcolor() const noexcept {return m_def_fontcolor;} private: void init() { m_submenumgr.add_menu(menu_state::menu_start, m_start); m_submenumgr.add_menu(menu_state::menu_levels, m_levels); this->setup_events(); this->setup_interface(); } void setup_events() { // menu switch m_on_menu_switch[menu_state::menu_levels] += [this]{m_title.set_text("Levels");}; m_on_menu_switch[menu_state::menu_start] += [this]{m_title.set_text("Recto Jump");}; // start menu: // item events: m_start->get_items().on_event("play", [this]{this->do_menu_switch(menu_state::menu_levels);}); m_start->get_items().on_event("editor", [this]{}); m_start->get_items().on_event("quit", [this]{m_gamewindow.stop();}); // level menu: // item events: m_levels->get_items().on_event("lv_download", [this]{m_gamehandler.get_popupmgr().create_popup("Not available yet.");}); // level_squares events: m_levels->on_level_load += [this](const level_id& id){m_gamehandler.load_level(id);}; } void setup_interface() { } }; } #endif // RJ_CORE_MAIN_MENU_MAIN_MENU_HPP <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #include <osl/diagnose.h> #include <rtl/ustrbuf.hxx> #include "resourceprovider.hxx" #include <osl/mutex.hxx> #include <vcl/svapp.hxx> #include <tools/simplerm.hxx> #include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp> #include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp> #include <svtools/svtools.hrc> //------------------------------------------------------------ // namespace directives //------------------------------------------------------------ using rtl::OUString; using namespace ::com::sun::star::ui::dialogs::ExtendedFilePickerElementIds; using namespace ::com::sun::star::ui::dialogs::CommonFilePickerElementIds; //------------------------------------------------------------ // //------------------------------------------------------------ #define FOLDERPICKER_TITLE 500 #define FOLDER_PICKER_DEF_DESCRIPTION 501 //------------------------------------------------------------ // we have to translate control ids to resource ids //------------------------------------------------------------ struct _Entry { sal_Int32 ctrlId; sal_Int16 resId; }; _Entry CtrlIdToResIdTable[] = { { CHECKBOX_AUTOEXTENSION, STR_SVT_FILEPICKER_AUTO_EXTENSION }, { CHECKBOX_PASSWORD, STR_SVT_FILEPICKER_PASSWORD }, { CHECKBOX_FILTEROPTIONS, STR_SVT_FILEPICKER_FILTER_OPTIONS }, { CHECKBOX_READONLY, STR_SVT_FILEPICKER_READONLY }, { CHECKBOX_LINK, STR_SVT_FILEPICKER_INSERT_AS_LINK }, { CHECKBOX_PREVIEW, STR_SVT_FILEPICKER_SHOW_PREVIEW }, { PUSHBUTTON_PLAY, STR_SVT_FILEPICKER_PLAY }, { LISTBOX_VERSION_LABEL, STR_SVT_FILEPICKER_VERSION }, { LISTBOX_TEMPLATE_LABEL, STR_SVT_FILEPICKER_TEMPLATES }, { LISTBOX_IMAGE_TEMPLATE_LABEL, STR_SVT_FILEPICKER_IMAGE_TEMPLATE }, { CHECKBOX_SELECTION, STR_SVT_FILEPICKER_SELECTION }, { FOLDERPICKER_TITLE, STR_SVT_FOLDERPICKER_DEFAULT_TITLE }, { FOLDER_PICKER_DEF_DESCRIPTION, STR_SVT_FOLDERPICKER_DEFAULT_DESCRIPTION } }; const sal_Int32 SIZE_TABLE = SAL_N_ELEMENTS( CtrlIdToResIdTable ); //------------------------------------------------------------ // //------------------------------------------------------------ sal_Int16 CtrlIdToResId( sal_Int32 aControlId ) { sal_Int16 aResId = -1; for ( sal_Int32 i = 0; i < SIZE_TABLE; i++ ) { if ( CtrlIdToResIdTable[i].ctrlId == aControlId ) { aResId = CtrlIdToResIdTable[i].resId; break; } } return aResId; } //------------------------------------------------------------ // //------------------------------------------------------------ class CResourceProvider_Impl { public: //------------------------------------- // //------------------------------------- CResourceProvider_Impl( ) { const SolarMutexGuard aGuard; com::sun::star::lang::Locale aLoc( Application::GetSettings().GetUILocale() ); m_ResMgr = new SimpleResMgr( CREATEVERSIONRESMGR_NAME( fps_office ), aLoc ); } //------------------------------------- // //------------------------------------- ~CResourceProvider_Impl( ) { delete m_ResMgr; } //------------------------------------- // //------------------------------------- OUString getResString( sal_Int16 aId ) { OUString aResOUString; try { OSL_ASSERT( m_ResMgr ); // translate the control id to a resource id sal_Int16 aResId = CtrlIdToResId( aId ); if ( aResId > -1 ) aResOUString = m_ResMgr->ReadString( aResId ); } catch(...) { } return aResOUString; } public: SimpleResMgr* m_ResMgr; }; //------------------------------------------------------------ // //------------------------------------------------------------ CResourceProvider::CResourceProvider( ) : m_pImpl( new CResourceProvider_Impl() ) { } //------------------------------------------------------------ // //------------------------------------------------------------ CResourceProvider::~CResourceProvider( ) { delete m_pImpl; } //------------------------------------------------------------ // //------------------------------------------------------------ OUString CResourceProvider::getResString( sal_Int16 aId ) { return m_pImpl->getResString( aId ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>fix build on Windows: use OUString<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #include <osl/diagnose.h> #include <rtl/ustrbuf.hxx> #include "resourceprovider.hxx" #include <osl/mutex.hxx> #include <vcl/svapp.hxx> #include <tools/simplerm.hxx> #include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp> #include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp> #include <svtools/svtools.hrc> //------------------------------------------------------------ // namespace directives //------------------------------------------------------------ using rtl::OUString; using namespace ::com::sun::star::ui::dialogs::ExtendedFilePickerElementIds; using namespace ::com::sun::star::ui::dialogs::CommonFilePickerElementIds; //------------------------------------------------------------ // //------------------------------------------------------------ #define FOLDERPICKER_TITLE 500 #define FOLDER_PICKER_DEF_DESCRIPTION 501 //------------------------------------------------------------ // we have to translate control ids to resource ids //------------------------------------------------------------ struct _Entry { sal_Int32 ctrlId; sal_Int16 resId; }; _Entry CtrlIdToResIdTable[] = { { CHECKBOX_AUTOEXTENSION, STR_SVT_FILEPICKER_AUTO_EXTENSION }, { CHECKBOX_PASSWORD, STR_SVT_FILEPICKER_PASSWORD }, { CHECKBOX_FILTEROPTIONS, STR_SVT_FILEPICKER_FILTER_OPTIONS }, { CHECKBOX_READONLY, STR_SVT_FILEPICKER_READONLY }, { CHECKBOX_LINK, STR_SVT_FILEPICKER_INSERT_AS_LINK }, { CHECKBOX_PREVIEW, STR_SVT_FILEPICKER_SHOW_PREVIEW }, { PUSHBUTTON_PLAY, STR_SVT_FILEPICKER_PLAY }, { LISTBOX_VERSION_LABEL, STR_SVT_FILEPICKER_VERSION }, { LISTBOX_TEMPLATE_LABEL, STR_SVT_FILEPICKER_TEMPLATES }, { LISTBOX_IMAGE_TEMPLATE_LABEL, STR_SVT_FILEPICKER_IMAGE_TEMPLATE }, { CHECKBOX_SELECTION, STR_SVT_FILEPICKER_SELECTION }, { FOLDERPICKER_TITLE, STR_SVT_FOLDERPICKER_DEFAULT_TITLE }, { FOLDER_PICKER_DEF_DESCRIPTION, STR_SVT_FOLDERPICKER_DEFAULT_DESCRIPTION } }; const sal_Int32 SIZE_TABLE = SAL_N_ELEMENTS( CtrlIdToResIdTable ); //------------------------------------------------------------ // //------------------------------------------------------------ sal_Int16 CtrlIdToResId( sal_Int32 aControlId ) { sal_Int16 aResId = -1; for ( sal_Int32 i = 0; i < SIZE_TABLE; i++ ) { if ( CtrlIdToResIdTable[i].ctrlId == aControlId ) { aResId = CtrlIdToResIdTable[i].resId; break; } } return aResId; } //------------------------------------------------------------ // //------------------------------------------------------------ class CResourceProvider_Impl { public: //------------------------------------- // //------------------------------------- CResourceProvider_Impl( ) { const SolarMutexGuard aGuard; com::sun::star::lang::Locale aLoc( Application::GetSettings().GetUILocale() ); m_ResMgr = new SimpleResMgr( OUString( "fps_office" ), aLoc ); } //------------------------------------- // //------------------------------------- ~CResourceProvider_Impl( ) { delete m_ResMgr; } //------------------------------------- // //------------------------------------- OUString getResString( sal_Int16 aId ) { OUString aResOUString; try { OSL_ASSERT( m_ResMgr ); // translate the control id to a resource id sal_Int16 aResId = CtrlIdToResId( aId ); if ( aResId > -1 ) aResOUString = m_ResMgr->ReadString( aResId ); } catch(...) { } return aResOUString; } public: SimpleResMgr* m_ResMgr; }; //------------------------------------------------------------ // //------------------------------------------------------------ CResourceProvider::CResourceProvider( ) : m_pImpl( new CResourceProvider_Impl() ) { } //------------------------------------------------------------ // //------------------------------------------------------------ CResourceProvider::~CResourceProvider( ) { delete m_pImpl; } //------------------------------------------------------------ // //------------------------------------------------------------ OUString CResourceProvider::getResString( sal_Int16 aId ) { return m_pImpl->getResString( aId ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: registerservices.cxx,v $ * * $Revision: 1.24 $ * * last change: $Author: obo $ $Date: 2004-09-09 17:09:56 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ //_________________________________________________________________________________________________________________ // includes of my own project //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_MACROS_REGISTRATION_HXX_ #include <macros/registration.hxx> #endif /*================================================================================================================= Add new include and new register info to for new services. Example: #ifndef __YOUR_SERVICE_1_HXX_ #include <service1.hxx> #endif #ifndef __YOUR_SERVICE_2_HXX_ #include <service2.hxx> #endif COMPONENTGETIMPLEMENTATIONENVIRONMENT COMPONENTWRITEINFO ( COMPONENTINFO( Service1 ) COMPONENTINFO( Service2 ) ) COMPONENTGETFACTORY ( IFFACTORIE( Service1 ) else IFFACTORIE( Service2 ) ) =================================================================================================================*/ #ifndef __FRAMEWORK_SERVICES_URLTRANSFORMER_HXX_ #include <services/urltransformer.hxx> #endif #ifndef __FRAMEWORK_SERVICES_DESKTOP_HXX_ #include <services/desktop.hxx> #endif #ifndef __FRAMEWORK_SERVICES_DOCUMENTPROPERTIES_HXX_ #include <services/documentproperties.hxx> #endif #ifndef __FRAMEWORK_SERVICES_FRAME_HXX_ #include <services/frame.hxx> #endif #ifndef __FRAMEWORK_SERVICES_MODULEMANAGER_HXX_ #include <services/modulemanager.hxx> #endif #ifndef __FRAMEWORK_JOBS_JOBEXECUTOR_HXX_ #include <jobs/jobexecutor.hxx> #endif #ifndef __FRAMEWORK_DISPATCH_SOUNDHANDLER_HXX_ #include <dispatch/soundhandler.hxx> #endif #ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDERSUPPLIER_HXX_ #include <recording/dispatchrecordersupplier.hxx> #endif #ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_ #include <recording/dispatchrecorder.hxx> #endif #ifndef __FRAMEWORK_DISPATCH_MAILTODISPATCHER_HXX_ #include <dispatch/mailtodispatcher.hxx> #endif #ifndef __FRAMEWORK_DISPATCH_SERVICEHANDLER_HXX_ #include <dispatch/servicehandler.hxx> #endif #ifndef __FRAMEWORK_JOBS_JOBDISPATCH_HXX_ #include <jobs/jobdispatch.hxx> #endif #ifndef __FRAMEWORK_SERVICES_BACKINGCOMP_HXX_ #include <services/backingcomp.hxx> #endif #ifndef __FRAMEWORK_SERVICES_DISPATCHHELPER_HXX_ #include <services/dispatchhelper.hxx> #endif #ifndef __FRAMEWORK_SERVICES_LAYOUTMANAGER_HXX_ #include <services/layoutmanager.hxx> #endif #ifndef __FRAMEWORK_SERVICES_LICENSE_HXX_ #include <services/license.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_UIELEMENTFACTORYMANAGER_HXX_ #include <uifactory/uielementfactorymanager.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_POPUPMENUCONTROLLERFACTORY_HXX_ #include <uifactory/popupmenucontrollerfactory.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_FONTMENUCONTROLLER_HXX_ #include <uielement/fontmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_FONTSIZEMENUCONTROLLER_HXX_ #include <uielement/fontsizemenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_OBJECTMENUCONTROLLER_HXX_ #include <uielement/objectmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_HEADERMENUCONTROLLER_HXX_ #include <uielement/headermenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_FOOTERMENUCONTROLLER_HXX_ #include <uielement/footermenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_CONTROLMENUCONTROLLER_HXX_ #include <uielement/controlmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_MACROSMENUCONTROLLER_HXX_ #include <uielement/macrosmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_UICOMMANDDESCRIPTION_HXX_ #include <uielement/uicommanddescription.hxx> #endif #ifndef __FRAMEWORK_UICONFIGURATION_UICONFIGMANAGER_HXX_ #include <uiconfiguration/uiconfigurationmanager.hxx> #endif #ifndef __FRAMEWORK_UICONFIGURATION_MODULEUICFGSUPPLIER_HXX_ #include <uiconfiguration/moduleuicfgsupplier.hxx> #endif #ifndef __FRAMEWORK_UICONFIGURATION_MODULEUICONFIGMANAGER_HXX_ #include <uiconfiguration/moduleuiconfigurationmanager.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_MENUBARFACTORY_HXX_ #include <uifactory/menubarfactory.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_TOOLBOXFACTORY_HXX_ #include <uifactory/toolboxfactory.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_ADDONSTOOLBOXFACTORY_HXX_ #include <uifactory/addonstoolboxfactory.hxx> #endif #ifndef __FRAMEWORK_UICONFIGURATION_WINDOWSTATECONFIGURATION_HXX_ #include "uiconfiguration/windowstateconfiguration.hxx" #endif #ifndef __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_ #include <uielement/toolbarsmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_TOOLBARCONTROLLERFACTORY_HXX_ #include "uifactory/toolbarcontrollerfactory.hxx" #endif #ifndef __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_ #include <uielement/toolbarsmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_RECENTFILESMENUCONTROLLER_HXX_ #include <uielement/recentfilesmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_STATUSBARFACTORY_HXX_ #include <uifactory/statusbarfactory.hxx> #endif COMPONENTGETIMPLEMENTATIONENVIRONMENT COMPONENTWRITEINFO ( COMPONENTINFO( ::framework::URLTransformer ) COMPONENTINFO( ::framework::Desktop ) COMPONENTINFO( ::framework::Frame ) COMPONENTINFO( ::framework::DocumentProperties ) COMPONENTINFO( ::framework::SoundHandler ) COMPONENTINFO( ::framework::JobExecutor ) COMPONENTINFO( ::framework::DispatchRecorderSupplier ) COMPONENTINFO( ::framework::DispatchRecorder ) COMPONENTINFO( ::framework::MailToDispatcher ) COMPONENTINFO( ::framework::ServiceHandler ) COMPONENTINFO( ::framework::JobDispatch ) COMPONENTINFO( ::framework::BackingComp ) COMPONENTINFO( ::framework::DispatchHelper ) COMPONENTINFO( ::framework::LayoutManager ) COMPONENTINFO( ::framework::License ) COMPONENTINFO( ::framework::UIElementFactoryManager ) COMPONENTINFO( ::framework::PopupMenuControllerFactory ) COMPONENTINFO( ::framework::FontMenuController ) COMPONENTINFO( ::framework::FontSizeMenuController ) COMPONENTINFO( ::framework::ObjectMenuController ) COMPONENTINFO( ::framework::HeaderMenuController ) COMPONENTINFO( ::framework::FooterMenuController ) COMPONENTINFO( ::framework::ControlMenuController ) COMPONENTINFO( ::framework::MacrosMenuController ) COMPONENTINFO( ::framework::UICommandDescription ) COMPONENTINFO( ::framework::ModuleManager ) COMPONENTINFO( ::framework::UIConfigurationManager ) COMPONENTINFO( ::framework::ModuleUIConfigurationManagerSupplier ) COMPONENTINFO( ::framework::ModuleUIConfigurationManager ) COMPONENTINFO( ::framework::MenuBarFactory ) COMPONENTINFO( ::framework::ToolBoxFactory ) COMPONENTINFO( ::framework::AddonsToolBoxFactory ) COMPONENTINFO( ::framework::WindowStateConfiguration ) COMPONENTINFO( ::framework::ToolbarsMenuController ) COMPONENTINFO( ::framework::ToolbarControllerFactory ) COMPONENTINFO( ::framework::ToolbarsMenuController ) COMPONENTINFO( ::framework::RecentFilesMenuController ) COMPONENTINFO( ::framework::StatusBarFactory ) ) COMPONENTGETFACTORY ( IFFACTORY( ::framework::URLTransformer ) else IFFACTORY( ::framework::Desktop ) else IFFACTORY( ::framework::Frame ) else IFFACTORY( ::framework::DocumentProperties ) else IFFACTORY( ::framework::SoundHandler ) else IFFACTORY( ::framework::JobExecutor ) else IFFACTORY( ::framework::DispatchRecorderSupplier ) else IFFACTORY( ::framework::DispatchRecorder ) else IFFACTORY( ::framework::MailToDispatcher ) else IFFACTORY( ::framework::ServiceHandler ) else IFFACTORY( ::framework::JobDispatch ) else IFFACTORY( ::framework::BackingComp ) else IFFACTORY( ::framework::DispatchHelper ) else IFFACTORY( ::framework::LayoutManager ) else IFFACTORY( ::framework::License ) else IFFACTORY( ::framework::UIElementFactoryManager ) else IFFACTORY( ::framework::PopupMenuControllerFactory ) else IFFACTORY( ::framework::FontMenuController ) else IFFACTORY( ::framework::FontSizeMenuController ) else IFFACTORY( ::framework::ObjectMenuController ) else IFFACTORY( ::framework::HeaderMenuController ) else IFFACTORY( ::framework::FooterMenuController ) else IFFACTORY( ::framework::ControlMenuController ) else IFFACTORY( ::framework::MacrosMenuController ) else IFFACTORY( ::framework::UICommandDescription ) else IFFACTORY( ::framework::ModuleManager ) else IFFACTORY( ::framework::UIConfigurationManager ) else IFFACTORY( ::framework::ModuleUIConfigurationManagerSupplier ) else IFFACTORY( ::framework::ModuleUIConfigurationManager ) else IFFACTORY( ::framework::MenuBarFactory ) else IFFACTORY( ::framework::ToolBoxFactory ) else IFFACTORY( ::framework::AddonsToolBoxFactory ) else IFFACTORY( ::framework::WindowStateConfiguration ) else IFFACTORY( ::framework::ToolbarsMenuController ) else IFFACTORY( ::framework::ToolbarControllerFactory ) else IFFACTORY( ::framework::ToolbarsMenuController ) else IFFACTORY( ::framework::RecentFilesMenuController ) else IFFACTORY( ::framework::StatusBarFactory ) ) <commit_msg>INTEGRATION: CWS keyconfig01 (1.19.36); FILE MERGED 2004/07/10 18:16:52 as 1.19.36.4: RESYNC: (1.19-1.22); FILE MERGED resolve merge conflict 2004/07/08 06:45:42 as 1.19.36.3: #i29863# support localized UI config, support new UI directory structure, adopt converter tool to support accelerators 2004/06/22 07:57:39 as 1.19.36.2: #i29863# second revision of shortcut configuration 2004/06/04 09:34:57 as 1.19.36.1: #i29863# new services for accelerator config<commit_after>/************************************************************************* * * $RCSfile: registerservices.cxx,v $ * * $Revision: 1.25 $ * * last change: $Author: rt $ $Date: 2004-09-20 10:08:44 $ * * 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): _______________________________________ * * ************************************************************************/ //_________________________________________________________________________________________________________________ // includes of my own project //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_MACROS_REGISTRATION_HXX_ #include <macros/registration.hxx> #endif /*================================================================================================================= Add new include and new register info to for new services. Example: #ifndef __YOUR_SERVICE_1_HXX_ #include <service1.hxx> #endif #ifndef __YOUR_SERVICE_2_HXX_ #include <service2.hxx> #endif COMPONENTGETIMPLEMENTATIONENVIRONMENT COMPONENTWRITEINFO ( COMPONENTINFO( Service1 ) COMPONENTINFO( Service2 ) ) COMPONENTGETFACTORY ( IFFACTORIE( Service1 ) else IFFACTORIE( Service2 ) ) =================================================================================================================*/ #ifndef __FRAMEWORK_SERVICES_URLTRANSFORMER_HXX_ #include <services/urltransformer.hxx> #endif #ifndef __FRAMEWORK_SERVICES_DESKTOP_HXX_ #include <services/desktop.hxx> #endif #ifndef __FRAMEWORK_SERVICES_DOCUMENTPROPERTIES_HXX_ #include <services/documentproperties.hxx> #endif #ifndef __FRAMEWORK_SERVICES_FRAME_HXX_ #include <services/frame.hxx> #endif #ifndef __FRAMEWORK_SERVICES_MODULEMANAGER_HXX_ #include <services/modulemanager.hxx> #endif #ifndef __FRAMEWORK_JOBS_JOBEXECUTOR_HXX_ #include <jobs/jobexecutor.hxx> #endif #ifndef __FRAMEWORK_DISPATCH_SOUNDHANDLER_HXX_ #include <dispatch/soundhandler.hxx> #endif #ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDERSUPPLIER_HXX_ #include <recording/dispatchrecordersupplier.hxx> #endif #ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_ #include <recording/dispatchrecorder.hxx> #endif #ifndef __FRAMEWORK_DISPATCH_MAILTODISPATCHER_HXX_ #include <dispatch/mailtodispatcher.hxx> #endif #ifndef __FRAMEWORK_DISPATCH_SERVICEHANDLER_HXX_ #include <dispatch/servicehandler.hxx> #endif #ifndef __FRAMEWORK_JOBS_JOBDISPATCH_HXX_ #include <jobs/jobdispatch.hxx> #endif #ifndef __FRAMEWORK_SERVICES_BACKINGCOMP_HXX_ #include <services/backingcomp.hxx> #endif #ifndef __FRAMEWORK_SERVICES_DISPATCHHELPER_HXX_ #include <services/dispatchhelper.hxx> #endif #ifndef __FRAMEWORK_SERVICES_LAYOUTMANAGER_HXX_ #include <services/layoutmanager.hxx> #endif #ifndef __FRAMEWORK_SERVICES_LICENSE_HXX_ #include <services/license.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_UIELEMENTFACTORYMANAGER_HXX_ #include <uifactory/uielementfactorymanager.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_POPUPMENUCONTROLLERFACTORY_HXX_ #include <uifactory/popupmenucontrollerfactory.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_FONTMENUCONTROLLER_HXX_ #include <uielement/fontmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_FONTSIZEMENUCONTROLLER_HXX_ #include <uielement/fontsizemenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_OBJECTMENUCONTROLLER_HXX_ #include <uielement/objectmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_HEADERMENUCONTROLLER_HXX_ #include <uielement/headermenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_FOOTERMENUCONTROLLER_HXX_ #include <uielement/footermenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_CONTROLMENUCONTROLLER_HXX_ #include <uielement/controlmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_MACROSMENUCONTROLLER_HXX_ #include <uielement/macrosmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_UICOMMANDDESCRIPTION_HXX_ #include <uielement/uicommanddescription.hxx> #endif #ifndef __FRAMEWORK_UICONFIGURATION_UICONFIGMANAGER_HXX_ #include <uiconfiguration/uiconfigurationmanager.hxx> #endif #ifndef __FRAMEWORK_UICONFIGURATION_MODULEUICFGSUPPLIER_HXX_ #include <uiconfiguration/moduleuicfgsupplier.hxx> #endif #ifndef __FRAMEWORK_UICONFIGURATION_MODULEUICONFIGMANAGER_HXX_ #include <uiconfiguration/moduleuiconfigurationmanager.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_MENUBARFACTORY_HXX_ #include <uifactory/menubarfactory.hxx> #endif #ifndef __FRAMEWORK_ACCELERATORS_GLOBALACCELERATORCONFIGURATION_HXX_ #include <accelerators/globalacceleratorconfiguration.hxx> #endif #ifndef __FRAMEWORK_ACCELERATORS_MODULEACCELERATORCONFIGURATION_HXX_ #include <accelerators/moduleacceleratorconfiguration.hxx> #endif #ifndef __FRAMEWORK_ACCELERATORS_DOCUMENTACCELERATORCONFIGURATION_HXX_ #include <accelerators/documentacceleratorconfiguration.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_TOOLBOXFACTORY_HXX_ #include <uifactory/toolboxfactory.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_ADDONSTOOLBOXFACTORY_HXX_ #include <uifactory/addonstoolboxfactory.hxx> #endif #ifndef __FRAMEWORK_UICONFIGURATION_WINDOWSTATECONFIGURATION_HXX_ #include "uiconfiguration/windowstateconfiguration.hxx" #endif #ifndef __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_ #include <uielement/toolbarsmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_TOOLBARCONTROLLERFACTORY_HXX_ #include "uifactory/toolbarcontrollerfactory.hxx" #endif #ifndef __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_ #include <uielement/toolbarsmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_RECENTFILESMENUCONTROLLER_HXX_ #include <uielement/recentfilesmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_STATUSBARFACTORY_HXX_ #include <uifactory/statusbarfactory.hxx> #endif COMPONENTGETIMPLEMENTATIONENVIRONMENT COMPONENTWRITEINFO ( COMPONENTINFO( ::framework::URLTransformer ) COMPONENTINFO( ::framework::Desktop ) COMPONENTINFO( ::framework::Frame ) COMPONENTINFO( ::framework::DocumentProperties ) COMPONENTINFO( ::framework::SoundHandler ) COMPONENTINFO( ::framework::JobExecutor ) COMPONENTINFO( ::framework::DispatchRecorderSupplier ) COMPONENTINFO( ::framework::DispatchRecorder ) COMPONENTINFO( ::framework::MailToDispatcher ) COMPONENTINFO( ::framework::ServiceHandler ) COMPONENTINFO( ::framework::JobDispatch ) COMPONENTINFO( ::framework::BackingComp ) COMPONENTINFO( ::framework::DispatchHelper ) COMPONENTINFO( ::framework::LayoutManager ) COMPONENTINFO( ::framework::License ) COMPONENTINFO( ::framework::UIElementFactoryManager ) COMPONENTINFO( ::framework::PopupMenuControllerFactory ) COMPONENTINFO( ::framework::FontMenuController ) COMPONENTINFO( ::framework::FontSizeMenuController ) COMPONENTINFO( ::framework::ObjectMenuController ) COMPONENTINFO( ::framework::HeaderMenuController ) COMPONENTINFO( ::framework::FooterMenuController ) COMPONENTINFO( ::framework::ControlMenuController ) COMPONENTINFO( ::framework::MacrosMenuController ) COMPONENTINFO( ::framework::UICommandDescription ) COMPONENTINFO( ::framework::ModuleManager ) COMPONENTINFO( ::framework::UIConfigurationManager ) COMPONENTINFO( ::framework::ModuleUIConfigurationManagerSupplier ) COMPONENTINFO( ::framework::ModuleUIConfigurationManager ) COMPONENTINFO( ::framework::MenuBarFactory ) COMPONENTINFO( ::framework::GlobalAcceleratorConfiguration ) COMPONENTINFO( ::framework::ModuleAcceleratorConfiguration ) COMPONENTINFO( ::framework::DocumentAcceleratorConfiguration ) COMPONENTINFO( ::framework::ToolBoxFactory ) COMPONENTINFO( ::framework::AddonsToolBoxFactory ) COMPONENTINFO( ::framework::WindowStateConfiguration ) COMPONENTINFO( ::framework::ToolbarsMenuController ) COMPONENTINFO( ::framework::ToolbarControllerFactory ) COMPONENTINFO( ::framework::ToolbarsMenuController ) COMPONENTINFO( ::framework::RecentFilesMenuController ) COMPONENTINFO( ::framework::StatusBarFactory ) ) COMPONENTGETFACTORY ( IFFACTORY( ::framework::URLTransformer ) else IFFACTORY( ::framework::Desktop ) else IFFACTORY( ::framework::Frame ) else IFFACTORY( ::framework::DocumentProperties ) else IFFACTORY( ::framework::SoundHandler ) else IFFACTORY( ::framework::JobExecutor ) else IFFACTORY( ::framework::DispatchRecorderSupplier ) else IFFACTORY( ::framework::DispatchRecorder ) else IFFACTORY( ::framework::MailToDispatcher ) else IFFACTORY( ::framework::ServiceHandler ) else IFFACTORY( ::framework::JobDispatch ) else IFFACTORY( ::framework::BackingComp ) else IFFACTORY( ::framework::DispatchHelper ) else IFFACTORY( ::framework::LayoutManager ) else IFFACTORY( ::framework::License ) else IFFACTORY( ::framework::UIElementFactoryManager ) else IFFACTORY( ::framework::PopupMenuControllerFactory ) else IFFACTORY( ::framework::FontMenuController ) else IFFACTORY( ::framework::FontSizeMenuController ) else IFFACTORY( ::framework::ObjectMenuController ) else IFFACTORY( ::framework::HeaderMenuController ) else IFFACTORY( ::framework::FooterMenuController ) else IFFACTORY( ::framework::ControlMenuController ) else IFFACTORY( ::framework::MacrosMenuController ) else IFFACTORY( ::framework::UICommandDescription ) else IFFACTORY( ::framework::ModuleManager ) else IFFACTORY( ::framework::UIConfigurationManager ) else IFFACTORY( ::framework::ModuleUIConfigurationManagerSupplier ) else IFFACTORY( ::framework::ModuleUIConfigurationManager ) else IFFACTORY( ::framework::MenuBarFactory ) else IFFACTORY( ::framework::GlobalAcceleratorConfiguration ) else IFFACTORY( ::framework::ModuleAcceleratorConfiguration ) else IFFACTORY( ::framework::DocumentAcceleratorConfiguration ) else IFFACTORY( ::framework::ToolBoxFactory ) else IFFACTORY( ::framework::AddonsToolBoxFactory ) else IFFACTORY( ::framework::WindowStateConfiguration ) else IFFACTORY( ::framework::ToolbarsMenuController ) else IFFACTORY( ::framework::ToolbarControllerFactory ) else IFFACTORY( ::framework::ToolbarsMenuController ) else IFFACTORY( ::framework::RecentFilesMenuController ) else IFFACTORY( ::framework::StatusBarFactory ) ) <|endoftext|>
<commit_before>/* * tests_SGLGraph.cpp * * Created on: Oct 11, 2013 * * Author: Alexandre Baron */ #include "gtest/gtest.h" #include "SGLGraph.h" using namespace SGL; using namespace std; //*********************************FIXTURES************************************ //***************************************************************************** // GraphTest fixture // ***************************************************************************** class GraphTest: public ::testing::Test { public: SGLGraph<int> graph; protected: void addVertices(int nbr, int p_from); }; void GraphTest::addVertices(int p_nbr, int p_from) { for (int i = 0; i < p_nbr; i++) { graph.addVertex(p_from); p_from++; } } TEST_F(GraphTest, constructor) { EXPECT_EQ((int)graph.size(), 0); EXPECT_EQ((int)graph.order(), 0); } TEST_F(GraphTest, LogicOnEmptyGraph) { EXPECT_THROW(graph.deleteEdge(42, 21), logic_error); EXPECT_THROW(graph.deleteVertex(42), logic_error); EXPECT_THROW(graph.hasEdge(42, 21), logic_error); EXPECT_THROW(graph.vertexInDegree(42), logic_error); EXPECT_THROW(graph.vertexOutDegree(42), logic_error); EXPECT_THROW(graph.vertexNeighborhood(42), logic_error); } TEST_F(GraphTest, addVertex) { graph.addVertex(42); EXPECT_THROW(graph.addVertex(42), logic_error); graph.addVertex(21); } TEST_F(GraphTest, deleteVertex) { graph.addVertex(42); EXPECT_THROW(graph.deleteVertex(41), logic_error); graph.deleteVertex(42); EXPECT_THROW(graph.deleteVertex(42), logic_error); } TEST_F(GraphTest, hasVertex) { EXPECT_FALSE(graph.hasVertex(42)); graph.addVertex(42); EXPECT_TRUE(graph.hasVertex(42)); graph.deleteVertex(42); EXPECT_FALSE(graph.hasVertex(42)); addVertices(2, 42); EXPECT_TRUE(graph.hasVertex(42)); EXPECT_TRUE(graph.hasVertex(43)); } TEST_F(GraphTest, vertexInDegree) { graph.addVertex(42); EXPECT_EQ((int)graph.vertexInDegree(42), 0); graph.addVertex(21); graph.addEdge(21, 42); EXPECT_EQ((int)graph.vertexInDegree(42), 1); graph.addVertex(84); graph.addEdge(84, 42); EXPECT_EQ((int)graph.vertexInDegree(42), 2); graph.deleteVertex(84); EXPECT_EQ((int)graph.vertexInDegree(42), 1); graph.deleteVertex(21); EXPECT_EQ((int)graph.vertexInDegree(42), 0); graph.deleteVertex(42); EXPECT_THROW(graph.vertexInDegree(42), logic_error); } TEST_F(GraphTest, vertexOutDegree) { graph.addVertex(42); EXPECT_EQ((int)graph.vertexOutDegree(42), 0); graph.addVertex(21); graph.addEdge(42, 21); EXPECT_EQ((int)graph.vertexOutDegree(42), 1); graph.addVertex(84); graph.addEdge(42, 84); EXPECT_EQ((int)graph.vertexOutDegree(42), 2); graph.deleteVertex(84); EXPECT_EQ((int)graph.vertexOutDegree(42), 1); graph.deleteVertex(21); EXPECT_EQ((int)graph.vertexOutDegree(42), 0); graph.deleteVertex(42); EXPECT_THROW(graph.vertexOutDegree(42), logic_error); } TEST_F(GraphTest, vertexIsSource) { EXPECT_THROW(graph.vertexIsSource(42), logic_error); graph.addVertex(42); EXPECT_TRUE(graph.vertexIsSource(42)); graph.addVertex(21); graph.addEdge(21, 42); EXPECT_FALSE(graph.vertexIsSource(42)); graph.deleteVertex(21); EXPECT_TRUE(graph.vertexIsSource(42)); graph.addVertex(21); graph.addEdge(42, 21); EXPECT_TRUE(graph.vertexIsSource(42)); } TEST_F(GraphTest, vertexIsSink) { EXPECT_THROW(graph.vertexIsSink(42), logic_error); graph.addVertex(42); EXPECT_TRUE(graph.vertexIsSink(42)); graph.addVertex(21); graph.addEdge(21, 42); EXPECT_TRUE(graph.vertexIsSink(42)); graph.deleteVertex(21); EXPECT_TRUE(graph.vertexIsSink(42)); graph.addVertex(21); graph.addEdge(42, 21); EXPECT_FALSE(graph.vertexIsSink(42)); } TEST_F(GraphTest, vertexNeighborhood) { addVertices(6, 42); // Two edges coming to 42 graph.addEdge(43, 42); graph.addEdge(44, 42); // Two edges coming from 42 graph.addEdge(42, 44); graph.addEdge(42, 45); vector<int> neighbors = graph.vertexNeighborhood(42); vector<int>::const_iterator found; // Neighborhood of 42 should be 3 vertices EXPECT_EQ((int)neighbors.size(), 3); for (int i = 43; i < 46; i++) { // each of the concerned vertices should be in the vector found = std::find(neighbors.begin(), neighbors.end(), i); EXPECT_NE(found, neighbors.end()); } // Vertices which aren't in 42's neighborhood shouldn't be in the vector found = std::find(neighbors.begin(), neighbors.end(), 46); EXPECT_EQ(found, neighbors.end()); // Let's test the "closed" parameter (should include the vertex itself in the vector) neighbors = graph.vertexNeighborhood(42, true); EXPECT_EQ((int)neighbors.size(), 4); for (int i = 42; i < 46; i++) { // each of the concerned vertices should be in the vector found = std::find(neighbors.begin(), neighbors.end(), i); EXPECT_NE(found, neighbors.end()); } // Vertices which aren't in 42's neighborhood shouldn't be in the vector graph.addEdge(46, 43); found = std::find(neighbors.begin(), neighbors.end(), 46); EXPECT_EQ(found, neighbors.end()); found = std::find(neighbors.begin(), neighbors.end(), 47); EXPECT_EQ(found, neighbors.end()); } TEST_F(GraphTest, vertices) { vector<int> vertices = graph.vertices(); EXPECT_EQ((int)vertices.size(), 0); addVertices(6, 42); vertices = graph.vertices(); vector<int>::const_iterator found; EXPECT_EQ((int)vertices.size(), 6); for (int i = 42; i < 48; i++) { // each of the concerned vertices should be in the vector found = std::find(vertices.begin(), vertices.end(), i); EXPECT_NE(found, vertices.end()); } } TEST_F(GraphTest, addEdge) { EXPECT_THROW(graph.addEdge(41, 42), logic_error); addVertices(2, 42); graph.addEdge(42, 43); graph.addEdge(43, 42); EXPECT_THROW(graph.addEdge(42, 41), logic_error); EXPECT_THROW(graph.addEdge(41, 43), logic_error); } TEST_F(GraphTest, deleteEdge) { EXPECT_THROW(graph.deleteEdge(42, 41), logic_error); addVertices(2, 42); EXPECT_THROW(graph.deleteEdge(42, 41), logic_error); EXPECT_THROW(graph.deleteEdge(41, 43), logic_error); graph.addEdge(42, 43); EXPECT_THROW(graph.deleteEdge(43, 42), logic_error); graph.addEdge(43, 42); graph.deleteEdge(42, 43); graph.deleteEdge(43, 42); EXPECT_THROW(graph.deleteEdge(42, 43), logic_error); EXPECT_THROW(graph.deleteEdge(43, 42), logic_error); } TEST_F(GraphTest, hasEdge) { EXPECT_THROW(graph.addEdge(41, 42), logic_error); addVertices(2, 42); EXPECT_FALSE(graph.hasEdge(42, 43)); graph.addEdge(42, 43); EXPECT_FALSE(graph.hasEdge(43, 42)); EXPECT_TRUE(graph.hasEdge(42, 43)); graph.addEdge(43, 42); EXPECT_TRUE(graph.hasEdge(43, 42)); EXPECT_TRUE(graph.hasEdge(42, 43)); graph.deleteEdge(42, 43); EXPECT_TRUE(graph.hasEdge(43, 42)); EXPECT_FALSE(graph.hasEdge(42, 43)); graph.deleteEdge(43, 42); EXPECT_FALSE(graph.hasEdge(43, 42)); EXPECT_FALSE(graph.hasEdge(42, 43)); } TEST_F(GraphTest, display) { cout << graph; addVertices(6, 42); cout << graph; graph.addEdge(42, 43); graph.addEdge(42, 45); graph.addEdge(43, 46); graph.addEdge(43, 42); graph.addEdge(46, 45); graph.addEdge(46, 42); graph.addEdge(47, 42); graph.addEdge(47, 43); graph.addEdge(47, 44); graph.addEdge(47, 45); graph.addEdge(47, 46); graph.addEdge(47, 47); cout << graph; } TEST_F(GraphTest, areEqual) { SGLGraph<int> copy(graph); EXPECT_TRUE(copy == graph); graph.addVertex(42); graph.addVertex(43); EXPECT_FALSE(copy == graph); copy.addVertex(42); copy.addVertex(43); EXPECT_TRUE(copy == graph); graph.addEdge(42, 43); graph.addEdge(43, 42); EXPECT_FALSE(copy == graph); copy.addEdge(42, 43); EXPECT_FALSE(copy == graph); copy.addEdge(43, 42); EXPECT_TRUE(copy == graph); } TEST_F(GraphTest, CopyConstructor) { SGLGraph<int> copy(graph); EXPECT_EQ((int)copy.size(), 0); EXPECT_EQ((int)copy.order(), 0); addVertices(6, 42); EXPECT_EQ((int)graph.order(), 6); SGLGraph<int> copy2(graph); vector<int> vertices = copy2.vertices(); vector<int>::const_iterator found; EXPECT_EQ(graph.order(), copy2.order()); for (int i = 42; i < 48; i++) { // each of the concerned vertices should be in the vector found = std::find(vertices.begin(), vertices.end(), i); EXPECT_NE(found, vertices.end()); } } TEST_F(GraphTest, AssignmentOperator) { // from empty graph to empty graph SGLGraph<int> copy; EXPECT_EQ((int)graph.size(), 0); EXPECT_EQ((int)graph.order(), 0); copy = graph; EXPECT_EQ((int)copy.size(), 0); EXPECT_EQ((int)copy.order(), 0); // from full graph to empty graph addVertices(6, 42); graph.addEdge(42, 43); graph.addEdge(42, 45); graph.addEdge(43, 46); copy = graph; EXPECT_TRUE(copy == graph); // from empty graph to full graph SGLGraph<int> copy2; copy = copy2; EXPECT_TRUE(copy == copy2); // from full graph to full graph copy = graph; addVertices(2, 1); graph.addEdge(46, 45); graph.addEdge(46, 42); copy = graph; EXPECT_TRUE(copy == graph); } <commit_msg>Correction of the unit tests names<commit_after>/* * tests_theGraph.cpp * * Created on: Oct 11, 2013 * * Author: Alexandre Baron */ #include "gtest/gtest.h" #include "SGL.h" using namespace SGL; using namespace std; //*********************************FIXTURES************************************ //***************************************************************************** // GraphTest fixture // ***************************************************************************** class GraphTest: public ::testing::Test { public: graph<int> theGraph; protected: void addVertices(int nbr, int p_from); }; void GraphTest::addVertices(int p_nbr, int p_from) { for (int i = 0; i < p_nbr; i++) { theGraph.addVertex(p_from); p_from++; } } TEST_F(GraphTest, constructor) { EXPECT_EQ((int)theGraph.size(), 0); EXPECT_EQ((int)theGraph.order(), 0); } TEST_F(GraphTest, LogicOnEmptyGraph) { EXPECT_THROW(theGraph.deleteEdge(42, 21), logic_error); EXPECT_THROW(theGraph.deleteVertex(42), logic_error); EXPECT_THROW(theGraph.hasEdge(42, 21), logic_error); EXPECT_THROW(theGraph.vertexInDegree(42), logic_error); EXPECT_THROW(theGraph.vertexOutDegree(42), logic_error); EXPECT_THROW(theGraph.vertexNeighborhood(42), logic_error); } TEST_F(GraphTest, addVertex) { theGraph.addVertex(42); EXPECT_THROW(theGraph.addVertex(42), logic_error); theGraph.addVertex(21); } TEST_F(GraphTest, deleteVertex) { theGraph.addVertex(42); EXPECT_THROW(theGraph.deleteVertex(41), logic_error); theGraph.deleteVertex(42); EXPECT_THROW(theGraph.deleteVertex(42), logic_error); } TEST_F(GraphTest, hasVertex) { EXPECT_FALSE(theGraph.hasVertex(42)); theGraph.addVertex(42); EXPECT_TRUE(theGraph.hasVertex(42)); theGraph.deleteVertex(42); EXPECT_FALSE(theGraph.hasVertex(42)); addVertices(2, 42); EXPECT_TRUE(theGraph.hasVertex(42)); EXPECT_TRUE(theGraph.hasVertex(43)); } TEST_F(GraphTest, vertexInDegree) { theGraph.addVertex(42); EXPECT_EQ((int)theGraph.vertexInDegree(42), 0); theGraph.addVertex(21); theGraph.addEdge(21, 42); EXPECT_EQ((int)theGraph.vertexInDegree(42), 1); theGraph.addVertex(84); theGraph.addEdge(84, 42); EXPECT_EQ((int)theGraph.vertexInDegree(42), 2); theGraph.deleteVertex(84); EXPECT_EQ((int)theGraph.vertexInDegree(42), 1); theGraph.deleteVertex(21); EXPECT_EQ((int)theGraph.vertexInDegree(42), 0); theGraph.deleteVertex(42); EXPECT_THROW(theGraph.vertexInDegree(42), logic_error); } TEST_F(GraphTest, vertexOutDegree) { theGraph.addVertex(42); EXPECT_EQ((int)theGraph.vertexOutDegree(42), 0); theGraph.addVertex(21); theGraph.addEdge(42, 21); EXPECT_EQ((int)theGraph.vertexOutDegree(42), 1); theGraph.addVertex(84); theGraph.addEdge(42, 84); EXPECT_EQ((int)theGraph.vertexOutDegree(42), 2); theGraph.deleteVertex(84); EXPECT_EQ((int)theGraph.vertexOutDegree(42), 1); theGraph.deleteVertex(21); EXPECT_EQ((int)theGraph.vertexOutDegree(42), 0); theGraph.deleteVertex(42); EXPECT_THROW(theGraph.vertexOutDegree(42), logic_error); } TEST_F(GraphTest, vertexIsSource) { EXPECT_THROW(theGraph.vertexIsSource(42), logic_error); theGraph.addVertex(42); EXPECT_TRUE(theGraph.vertexIsSource(42)); theGraph.addVertex(21); theGraph.addEdge(21, 42); EXPECT_FALSE(theGraph.vertexIsSource(42)); theGraph.deleteVertex(21); EXPECT_TRUE(theGraph.vertexIsSource(42)); theGraph.addVertex(21); theGraph.addEdge(42, 21); EXPECT_TRUE(theGraph.vertexIsSource(42)); } TEST_F(GraphTest, vertexIsSink) { EXPECT_THROW(theGraph.vertexIsSink(42), logic_error); theGraph.addVertex(42); EXPECT_TRUE(theGraph.vertexIsSink(42)); theGraph.addVertex(21); theGraph.addEdge(21, 42); EXPECT_TRUE(theGraph.vertexIsSink(42)); theGraph.deleteVertex(21); EXPECT_TRUE(theGraph.vertexIsSink(42)); theGraph.addVertex(21); theGraph.addEdge(42, 21); EXPECT_FALSE(theGraph.vertexIsSink(42)); } TEST_F(GraphTest, vertexNeighborhood) { addVertices(6, 42); // Two edges coming to 42 theGraph.addEdge(43, 42); theGraph.addEdge(44, 42); // Two edges coming from 42 theGraph.addEdge(42, 44); theGraph.addEdge(42, 45); vector<int> neighbors = theGraph.vertexNeighborhood(42); vector<int>::const_iterator found; // Neighborhood of 42 should be 3 vertices EXPECT_EQ((int)neighbors.size(), 3); for (int i = 43; i < 46; i++) { // each of the concerned vertices should be in the vector found = std::find(neighbors.begin(), neighbors.end(), i); EXPECT_NE(found, neighbors.end()); } // Vertices which aren't in 42's neighborhood shouldn't be in the vector found = std::find(neighbors.begin(), neighbors.end(), 46); EXPECT_EQ(found, neighbors.end()); // Let's test the "closed" parameter (should include the vertex itself in the vector) neighbors = theGraph.vertexNeighborhood(42, true); EXPECT_EQ((int)neighbors.size(), 4); for (int i = 42; i < 46; i++) { // each of the concerned vertices should be in the vector found = std::find(neighbors.begin(), neighbors.end(), i); EXPECT_NE(found, neighbors.end()); } // Vertices which aren't in 42's neighborhood shouldn't be in the vector theGraph.addEdge(46, 43); found = std::find(neighbors.begin(), neighbors.end(), 46); EXPECT_EQ(found, neighbors.end()); found = std::find(neighbors.begin(), neighbors.end(), 47); EXPECT_EQ(found, neighbors.end()); } TEST_F(GraphTest, vertices) { vector<int> vertices = theGraph.vertices(); EXPECT_EQ((int)vertices.size(), 0); addVertices(6, 42); vertices = theGraph.vertices(); vector<int>::const_iterator found; EXPECT_EQ((int)vertices.size(), 6); for (int i = 42; i < 48; i++) { // each of the concerned vertices should be in the vector found = std::find(vertices.begin(), vertices.end(), i); EXPECT_NE(found, vertices.end()); } } TEST_F(GraphTest, addEdge) { EXPECT_THROW(theGraph.addEdge(41, 42), logic_error); addVertices(2, 42); theGraph.addEdge(42, 43); theGraph.addEdge(43, 42); EXPECT_THROW(theGraph.addEdge(42, 41), logic_error); EXPECT_THROW(theGraph.addEdge(41, 43), logic_error); } TEST_F(GraphTest, deleteEdge) { EXPECT_THROW(theGraph.deleteEdge(42, 41), logic_error); addVertices(2, 42); EXPECT_THROW(theGraph.deleteEdge(42, 41), logic_error); EXPECT_THROW(theGraph.deleteEdge(41, 43), logic_error); theGraph.addEdge(42, 43); EXPECT_THROW(theGraph.deleteEdge(43, 42), logic_error); theGraph.addEdge(43, 42); theGraph.deleteEdge(42, 43); theGraph.deleteEdge(43, 42); EXPECT_THROW(theGraph.deleteEdge(42, 43), logic_error); EXPECT_THROW(theGraph.deleteEdge(43, 42), logic_error); } TEST_F(GraphTest, hasEdge) { EXPECT_THROW(theGraph.addEdge(41, 42), logic_error); addVertices(2, 42); EXPECT_FALSE(theGraph.hasEdge(42, 43)); theGraph.addEdge(42, 43); EXPECT_FALSE(theGraph.hasEdge(43, 42)); EXPECT_TRUE(theGraph.hasEdge(42, 43)); theGraph.addEdge(43, 42); EXPECT_TRUE(theGraph.hasEdge(43, 42)); EXPECT_TRUE(theGraph.hasEdge(42, 43)); theGraph.deleteEdge(42, 43); EXPECT_TRUE(theGraph.hasEdge(43, 42)); EXPECT_FALSE(theGraph.hasEdge(42, 43)); theGraph.deleteEdge(43, 42); EXPECT_FALSE(theGraph.hasEdge(43, 42)); EXPECT_FALSE(theGraph.hasEdge(42, 43)); } TEST_F(GraphTest, display) { cout << theGraph; addVertices(6, 42); cout << theGraph; theGraph.addEdge(42, 43); theGraph.addEdge(42, 45); theGraph.addEdge(43, 46); theGraph.addEdge(43, 42); theGraph.addEdge(46, 45); theGraph.addEdge(46, 42); theGraph.addEdge(47, 42); theGraph.addEdge(47, 43); theGraph.addEdge(47, 44); theGraph.addEdge(47, 45); theGraph.addEdge(47, 46); theGraph.addEdge(47, 47); cout << theGraph; } TEST_F(GraphTest, areEqual) { graph<int> copy(theGraph); EXPECT_TRUE(copy == theGraph); theGraph.addVertex(42); theGraph.addVertex(43); EXPECT_FALSE(copy == theGraph); copy.addVertex(42); copy.addVertex(43); EXPECT_TRUE(copy == theGraph); theGraph.addEdge(42, 43); theGraph.addEdge(43, 42); EXPECT_FALSE(copy == theGraph); copy.addEdge(42, 43); EXPECT_FALSE(copy == theGraph); copy.addEdge(43, 42); EXPECT_TRUE(copy == theGraph); } TEST_F(GraphTest, CopyConstructor) { graph<int> copy(theGraph); EXPECT_EQ((int)copy.size(), 0); EXPECT_EQ((int)copy.order(), 0); addVertices(6, 42); EXPECT_EQ((int)theGraph.order(), 6); graph<int> copy2(theGraph); vector<int> vertices = copy2.vertices(); vector<int>::const_iterator found; EXPECT_EQ(theGraph.order(), copy2.order()); for (int i = 42; i < 48; i++) { // each of the concerned vertices should be in the vector found = std::find(vertices.begin(), vertices.end(), i); EXPECT_NE(found, vertices.end()); } } TEST_F(GraphTest, AssignmentOperator) { // from empty graph to empty graph graph<int> copy; EXPECT_EQ((int)theGraph.size(), 0); EXPECT_EQ((int)theGraph.order(), 0); copy = theGraph; EXPECT_EQ((int)copy.size(), 0); EXPECT_EQ((int)copy.order(), 0); // from full graph to empty graph addVertices(6, 42); theGraph.addEdge(42, 43); theGraph.addEdge(42, 45); theGraph.addEdge(43, 46); copy = theGraph; EXPECT_TRUE(copy == theGraph); // from empty graph to full graph graph<int> copy2; copy = copy2; EXPECT_TRUE(copy == copy2); // from full graph to full graph copy = theGraph; addVertices(2, 1); theGraph.addEdge(46, 45); theGraph.addEdge(46, 42); copy = theGraph; EXPECT_TRUE(copy == theGraph); } <|endoftext|>
<commit_before>#line 2 "quanta/core/object/object.cpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. */ #include <quanta/core/config.hpp> #include <togo/core/log/log.hpp> #include <togo/core/error/assert.hpp> #include <togo/core/utility/utility.hpp> #include <togo/core/memory/memory.hpp> #include <quanta/core/string/unmanaged_string.hpp> #include <quanta/core/object/internal.hpp> #include <quanta/core/object/object.hpp> namespace quanta { /// Set type. /// /// Returns true if type changed. bool object::set_type(Object& obj, ObjectValueType const type) { if (object::type(obj) == type) { return false; } object::clear_value(obj); internal::set_property(obj, M_TYPE, 0, unsigned_cast(type)); if (type == ObjectValueType::null) { internal::clear_property(obj, M_VALUE_GUESS); } else if (type == ObjectValueType::expression) { object::clear_value_markers(obj); object::clear_source(obj); object::clear_tags(obj); object::clear_quantity(obj); } return true; } /// Reset value to type default. /// /// This does not clear children if the object is an expression. void object::clear_value(Object& obj) { auto& a = memory::default_allocator(); switch (object::type(obj)) { case ObjectValueType::null: break; case ObjectValueType::boolean: obj.value.boolean = false; break; case ObjectValueType::integer: obj.value.numeric.integer = 0; unmanaged_string::clear(obj.value.numeric.unit, a); break; case ObjectValueType::decimal: obj.value.numeric.decimal = 0.0f; unmanaged_string::clear(obj.value.numeric.unit, a); break; case ObjectValueType::time: obj.value.time = {}; internal::clear_property(obj, M_TM_PROPERTIES); break; case ObjectValueType::string: unmanaged_string::clear(obj.value.string, a); break; case ObjectValueType::expression: break; } } /// Copy an object. void object::copy(Object& dst, Object const& src, bool const children IGEN_DEFAULT(true)) { auto& a = memory::default_allocator(); object::clear_value(dst); dst.properties = src.properties; dst.source = src.source; dst.sub_source = src.sub_source; unmanaged_string::set(dst.name, src.name, a); switch (object::type(src)) { case ObjectValueType::null: break; case ObjectValueType::boolean: dst.value.boolean = src.value.boolean; break; case ObjectValueType::integer: dst.value.numeric.integer = src.value.numeric.integer; unmanaged_string::set(dst.value.numeric.unit, src.value.numeric.unit, a); break; case ObjectValueType::decimal: dst.value.numeric.decimal = src.value.numeric.decimal; unmanaged_string::set(dst.value.numeric.unit, src.value.numeric.unit, a); break; case ObjectValueType::time: dst.value.time = src.value.time; break; case ObjectValueType::string: unmanaged_string::set(dst.value.string, src.value.string, a); break; case ObjectValueType::expression: break; } array::copy(dst.tags, src.tags); if (children) { array::copy(dst.children, src.children); } if (object::has_quantity(src)) { if (object::has_quantity(dst)) { object::copy(*dst.quantity, *src.quantity); } else { dst.quantity = TOGO_CONSTRUCT(a, Object, *src.quantity); } } } /// Create quantity or clear existing quantity. Object& object::make_quantity(Object& obj) { if (object::has_quantity(obj)) { object::clear(*obj.quantity); } else { obj.quantity = TOGO_CONSTRUCT_DEFAULT(memory::default_allocator(), Object); } return *obj.quantity; } /// Set to null and clear all properties. void object::clear(Object& obj) { object::clear_name(obj); object::set_null(obj); object::clear_value_markers(obj); object::clear_source(obj); object::clear_tags(obj); object::clear_children(obj); object::clear_quantity(obj); } /// Resolve time value from context. /// /// Relative date parts are taken from the context time. /// If the time value does not specify a zone offset, it is adjusted to the /// zone offset of the context (time assumed to be zone-local). void object::resolve_time(Object& obj, Time context) { TOGO_ASSERTE(object::is_type(obj, ObjectValueType::time)); if (!object::is_zoned(obj)) { time::adjust_zone_offset(obj.value.time, context.zone_offset); } // context is only used as a date, so we don't want the zone offset to shove // our value into another date as we apply it time::adjust_zone_utc(context); auto ct = time::clock_seconds_utc(obj.value.time); unsigned rel_parts = internal::get_property(obj, M_TM_CONTEXTUAL_YEAR | M_TM_CONTEXTUAL_MONTH, 0); if (!object::has_date(obj)) { obj.value.time.sec = time::date_seconds_utc(context); if (object::has_clock(obj)) { obj.value.time.sec += ct; object::set_time_type(obj, ObjectTimeType::date_and_clock); } else { object::set_time_type(obj, ObjectTimeType::date); } } else if (rel_parts) { Date date = time::gregorian::date_utc(obj.value.time); Date const context_date = time::gregorian::date_utc(context); if (rel_parts & M_TM_CONTEXTUAL_MONTH) { date.month = context_date.month; date.year = context_date.year; // implied } else/* if (rel_parts & M_TM_CONTEXTUAL_YEAR)*/ { date.year = context_date.year; } time::gregorian::set_utc(obj.value.time, date); if (object::has_clock(obj)) { obj.value.time.sec = time::date_seconds_utc(obj.value.time) + ct; } } internal::clear_property(obj, M_TM_UNZONED | M_TM_CONTEXTUAL_MONTH | M_TM_CONTEXTUAL_YEAR); } IGEN_PRIVATE Object const* object::find_impl( Array<Object> const& collection, StringRef const& name, ObjectNameHash const name_hash ) { if (name_hash == OBJECT_NAME_NULL || array::empty(collection)) { return nullptr; } for (Object const& item : collection) { if (name_hash == item.name.hash) { #if defined(TOGO_DEBUG) if (name.valid() && !string::compare_equal(name, object::name(item))) { TOGO_LOG_DEBUGF( "hashes matched, but names mismatched: '%.*s' != '%.*s' (lookup_name != name)\n", name.size, name.data, item.name.size, item.name.data ); } #else (void)name; #endif return &item; } } return nullptr; } /// Find tag by name. Object* object::find_tag(Object& obj, StringRef const& name) { ObjectNameHash const name_hash = object::hash_name(name); return const_cast<Object*>(object::find_impl(obj.tags, name, name_hash)); } /// Find tag by name. Object const* object::find_tag(Object const& obj, StringRef const& name) { ObjectNameHash const name_hash = object::hash_name(name); return object::find_impl(obj.tags, name, name_hash); } /// Find tag by name hash. Object* object::find_tag(Object& obj, ObjectNameHash const name_hash) { return const_cast<Object*>( object::find_impl(obj.tags, StringRef{}, name_hash) ); } /// Find tag by name hash. Object const* object::find_tag(Object const& obj, ObjectNameHash const name_hash) { return object::find_impl(obj.tags, StringRef{}, name_hash); } /// Find tag by name. Object* object::find_child(Object& obj, StringRef const& name) { ObjectNameHash const name_hash = object::hash_name(name); return const_cast<Object*>(object::find_impl(obj.children, name, name_hash)); } /// Find tag by name. Object const* object::find_child(Object const& obj, StringRef const& name) { ObjectNameHash const name_hash = object::hash_name(name); return object::find_impl(obj.children, name, name_hash); } /// Find tag by name hash. Object* object::find_child(Object& obj, ObjectNameHash const name_hash) { return const_cast<Object*>( object::find_impl(obj.children, StringRef{}, name_hash) ); } /// Find tag by name hash. Object const* object::find_child(Object const& obj, ObjectNameHash const name_hash) { return object::find_impl(obj.children, StringRef{}, name_hash); } } // namespace quanta <commit_msg>lib/core/object/object: doc corrections.<commit_after>#line 2 "quanta/core/object/object.cpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. */ #include <quanta/core/config.hpp> #include <togo/core/log/log.hpp> #include <togo/core/error/assert.hpp> #include <togo/core/utility/utility.hpp> #include <togo/core/memory/memory.hpp> #include <quanta/core/string/unmanaged_string.hpp> #include <quanta/core/object/internal.hpp> #include <quanta/core/object/object.hpp> namespace quanta { /// Set type. /// /// Returns true if type changed. bool object::set_type(Object& obj, ObjectValueType const type) { if (object::type(obj) == type) { return false; } object::clear_value(obj); internal::set_property(obj, M_TYPE, 0, unsigned_cast(type)); if (type == ObjectValueType::null) { internal::clear_property(obj, M_VALUE_GUESS); } else if (type == ObjectValueType::expression) { object::clear_value_markers(obj); object::clear_source(obj); object::clear_tags(obj); object::clear_quantity(obj); } return true; } /// Reset value to type default. /// /// This does not clear children if the object is an expression. void object::clear_value(Object& obj) { auto& a = memory::default_allocator(); switch (object::type(obj)) { case ObjectValueType::null: break; case ObjectValueType::boolean: obj.value.boolean = false; break; case ObjectValueType::integer: obj.value.numeric.integer = 0; unmanaged_string::clear(obj.value.numeric.unit, a); break; case ObjectValueType::decimal: obj.value.numeric.decimal = 0.0f; unmanaged_string::clear(obj.value.numeric.unit, a); break; case ObjectValueType::time: obj.value.time = {}; internal::clear_property(obj, M_TM_PROPERTIES); break; case ObjectValueType::string: unmanaged_string::clear(obj.value.string, a); break; case ObjectValueType::expression: break; } } /// Copy an object. void object::copy(Object& dst, Object const& src, bool const children IGEN_DEFAULT(true)) { auto& a = memory::default_allocator(); object::clear_value(dst); dst.properties = src.properties; dst.source = src.source; dst.sub_source = src.sub_source; unmanaged_string::set(dst.name, src.name, a); switch (object::type(src)) { case ObjectValueType::null: break; case ObjectValueType::boolean: dst.value.boolean = src.value.boolean; break; case ObjectValueType::integer: dst.value.numeric.integer = src.value.numeric.integer; unmanaged_string::set(dst.value.numeric.unit, src.value.numeric.unit, a); break; case ObjectValueType::decimal: dst.value.numeric.decimal = src.value.numeric.decimal; unmanaged_string::set(dst.value.numeric.unit, src.value.numeric.unit, a); break; case ObjectValueType::time: dst.value.time = src.value.time; break; case ObjectValueType::string: unmanaged_string::set(dst.value.string, src.value.string, a); break; case ObjectValueType::expression: break; } array::copy(dst.tags, src.tags); if (children) { array::copy(dst.children, src.children); } if (object::has_quantity(src)) { if (object::has_quantity(dst)) { object::copy(*dst.quantity, *src.quantity); } else { dst.quantity = TOGO_CONSTRUCT(a, Object, *src.quantity); } } } /// Create quantity or clear existing quantity. Object& object::make_quantity(Object& obj) { if (object::has_quantity(obj)) { object::clear(*obj.quantity); } else { obj.quantity = TOGO_CONSTRUCT_DEFAULT(memory::default_allocator(), Object); } return *obj.quantity; } /// Set to null and clear all properties. void object::clear(Object& obj) { object::clear_name(obj); object::set_null(obj); object::clear_value_markers(obj); object::clear_source(obj); object::clear_tags(obj); object::clear_children(obj); object::clear_quantity(obj); } /// Resolve time value from context. /// /// Relative date parts are taken from the context time. /// If the time value does not specify a zone offset, it is adjusted to the /// zone offset of the context (time assumed to be zone-local). void object::resolve_time(Object& obj, Time context) { TOGO_ASSERTE(object::is_type(obj, ObjectValueType::time)); if (!object::is_zoned(obj)) { time::adjust_zone_offset(obj.value.time, context.zone_offset); } // context is only used as a date, so we don't want the zone offset to shove // our value into another date as we apply it time::adjust_zone_utc(context); auto ct = time::clock_seconds_utc(obj.value.time); unsigned rel_parts = internal::get_property(obj, M_TM_CONTEXTUAL_YEAR | M_TM_CONTEXTUAL_MONTH, 0); if (!object::has_date(obj)) { obj.value.time.sec = time::date_seconds_utc(context); if (object::has_clock(obj)) { obj.value.time.sec += ct; object::set_time_type(obj, ObjectTimeType::date_and_clock); } else { object::set_time_type(obj, ObjectTimeType::date); } } else if (rel_parts) { Date date = time::gregorian::date_utc(obj.value.time); Date const context_date = time::gregorian::date_utc(context); if (rel_parts & M_TM_CONTEXTUAL_MONTH) { date.month = context_date.month; date.year = context_date.year; // implied } else/* if (rel_parts & M_TM_CONTEXTUAL_YEAR)*/ { date.year = context_date.year; } time::gregorian::set_utc(obj.value.time, date); if (object::has_clock(obj)) { obj.value.time.sec = time::date_seconds_utc(obj.value.time) + ct; } } internal::clear_property(obj, M_TM_UNZONED | M_TM_CONTEXTUAL_MONTH | M_TM_CONTEXTUAL_YEAR); } IGEN_PRIVATE Object const* object::find_impl( Array<Object> const& collection, StringRef const& name, ObjectNameHash const name_hash ) { if (name_hash == OBJECT_NAME_NULL || array::empty(collection)) { return nullptr; } for (Object const& item : collection) { if (name_hash == item.name.hash) { #if defined(TOGO_DEBUG) if (name.valid() && !string::compare_equal(name, object::name(item))) { TOGO_LOG_DEBUGF( "hashes matched, but names mismatched: '%.*s' != '%.*s' (lookup_name != name)\n", name.size, name.data, item.name.size, item.name.data ); } #else (void)name; #endif return &item; } } return nullptr; } /// Find tag by name. Object* object::find_tag(Object& obj, StringRef const& name) { ObjectNameHash const name_hash = object::hash_name(name); return const_cast<Object*>(object::find_impl(obj.tags, name, name_hash)); } /// Find tag by name. Object const* object::find_tag(Object const& obj, StringRef const& name) { ObjectNameHash const name_hash = object::hash_name(name); return object::find_impl(obj.tags, name, name_hash); } /// Find tag by name hash. Object* object::find_tag(Object& obj, ObjectNameHash const name_hash) { return const_cast<Object*>( object::find_impl(obj.tags, StringRef{}, name_hash) ); } /// Find tag by name hash. Object const* object::find_tag(Object const& obj, ObjectNameHash const name_hash) { return object::find_impl(obj.tags, StringRef{}, name_hash); } /// Find child by name. Object* object::find_child(Object& obj, StringRef const& name) { ObjectNameHash const name_hash = object::hash_name(name); return const_cast<Object*>(object::find_impl(obj.children, name, name_hash)); } /// Find child by name. Object const* object::find_child(Object const& obj, StringRef const& name) { ObjectNameHash const name_hash = object::hash_name(name); return object::find_impl(obj.children, name, name_hash); } /// Find child by name hash. Object* object::find_child(Object& obj, ObjectNameHash const name_hash) { return const_cast<Object*>( object::find_impl(obj.children, StringRef{}, name_hash) ); } /// Find child by name hash. Object const* object::find_child(Object const& obj, ObjectNameHash const name_hash) { return object::find_impl(obj.children, StringRef{}, name_hash); } } // namespace quanta <|endoftext|>
<commit_before>// // MSX.cpp // Clock Signal // // Created by Thomas Harte on 24/11/2017. // Copyright © 2017 Thomas Harte. All rights reserved. // #include "MSX.hpp" #include "../../Processors/Z80/Z80.hpp" #include "../../Components/1770/1770.hpp" #include "../../Components/9918/9918.hpp" #include "../../Components/8255/i8255.hpp" #include "../../Components/AY38910/AY38910.hpp" #include "../CRTMachine.hpp" #include "../ConfigurationTarget.hpp" namespace MSX { class i8255PortHandler: public Intel::i8255::PortHandler { }; class AYPortHandler: public GI::AY38910::PortHandler { }; class ConcreteMachine: public Machine, public CPU::Z80::BusHandler, public CRTMachine::Machine, public ConfigurationTarget::Machine { public: ConcreteMachine(): z80_(*this), i8255_(i8255_port_handler_) { ay_.set_port_handler(&ay_port_handler_); set_clock_rate(3579545); } void setup_output(float aspect_ratio) override { vdp_.reset(new TI::TMS9918(TI::TMS9918::TMS9918A)); } void close_output() override { } std::shared_ptr<Outputs::CRT::CRT> get_crt() override { return vdp_->get_crt(); } std::shared_ptr<Outputs::Speaker> get_speaker() override { return nullptr; } void run_for(const Cycles cycles) override { z80_.run_for(cycles); } void configure_as_target(const StaticAnalyser::Target &target) override { } bool insert_media(const StaticAnalyser::Media &media) override { return true; } HalfCycles perform_machine_cycle(const CPU::Z80::PartialMachineCycle &cycle) { uint16_t address = cycle.address ? *cycle.address : 0x0000; switch(cycle.operation) { case CPU::Z80::PartialMachineCycle::ReadOpcode: case CPU::Z80::PartialMachineCycle::Read: *cycle.value = read_pointers_[address >> 14][address & 16383]; break; case CPU::Z80::PartialMachineCycle::Write: write_pointers_[address >> 14][address & 16383] = *cycle.value; break; case CPU::Z80::PartialMachineCycle::Input: switch(address & 0xff) { case 0x98: case 0x99: *cycle.value = vdp_->get_register(address); break; case 0xa2: ay_.set_control_lines(static_cast<GI::AY38910::ControlLines>(GI::AY38910::BDIR | GI::AY38910::BC1)); ay_.set_data_input(*cycle.value); break; case 0xa8: case 0xa9: case 0xaa: case 0xab: *cycle.value = i8255_.get_register(address); break; } break; case CPU::Z80::PartialMachineCycle::Output: switch(address & 0xff) { case 0x98: case 0x99: vdp_->set_register(address, *cycle.value); break; case 0xa0: ay_.set_control_lines(static_cast<GI::AY38910::ControlLines>(GI::AY38910::BDIR | GI::AY38910::BC2 | GI::AY38910::BC1)); ay_.set_data_input(*cycle.value); break; case 0xa1: ay_.set_control_lines(static_cast<GI::AY38910::ControlLines>(GI::AY38910::BDIR | GI::AY38910::BC2)); ay_.set_data_input(*cycle.value); break; case 0xa8: case 0xa9: case 0xaa: case 0xab: i8255_.set_register(address, *cycle.value); break; } break; default: break; } // Per the best information I currently have, the MSX inserts an extra cycle into each opcode read, // but otherwise runs without pause. return HalfCycles((cycle.operation == CPU::Z80::PartialMachineCycle::ReadOpcode) ? 2 : 0);; } // Obtains the system ROMs. bool set_rom_fetcher(const std::function<std::vector<std::unique_ptr<std::vector<uint8_t>>>(const std::string &machine, const std::vector<std::string> &names)> &roms_with_names) override { auto roms = roms_with_names( "MSX", { "basic.rom", "main_msx1.rom" }); if(!roms[0] || !roms[1]) return false; basic_ = std::move(*roms[0]); basic_.resize(16384); main_ = std::move(*roms[1]); main_.resize(16384); return true; } private: CPU::Z80::Processor<ConcreteMachine, false, false> z80_; std::unique_ptr<TI::TMS9918> vdp_; Intel::i8255::i8255<i8255PortHandler> i8255_; GI::AY38910::AY38910 ay_; i8255PortHandler i8255_port_handler_; AYPortHandler ay_port_handler_; uint8_t *read_pointers_[4]; uint8_t *write_pointers_[4]; uint8_t ram_[65536]; std::vector<uint8_t> basic_, main_; }; } using namespace MSX; Machine *Machine::MSX() { return new ConcreteMachine; } Machine::~Machine() {} <commit_msg>Adds just enough of the MSX memory map for the Z80 to appear to try to do useful things.<commit_after>// // MSX.cpp // Clock Signal // // Created by Thomas Harte on 24/11/2017. // Copyright © 2017 Thomas Harte. All rights reserved. // #include "MSX.hpp" #include "../../Processors/Z80/Z80.hpp" #include "../../Components/1770/1770.hpp" #include "../../Components/9918/9918.hpp" #include "../../Components/8255/i8255.hpp" #include "../../Components/AY38910/AY38910.hpp" #include "../CRTMachine.hpp" #include "../ConfigurationTarget.hpp" namespace MSX { class i8255PortHandler: public Intel::i8255::PortHandler { }; class AYPortHandler: public GI::AY38910::PortHandler { }; class ConcreteMachine: public Machine, public CPU::Z80::BusHandler, public CRTMachine::Machine, public ConfigurationTarget::Machine { public: ConcreteMachine(): z80_(*this), i8255_(i8255_port_handler_) { ay_.set_port_handler(&ay_port_handler_); set_clock_rate(3579545); } void setup_output(float aspect_ratio) override { vdp_.reset(new TI::TMS9918(TI::TMS9918::TMS9918A)); } void close_output() override { } std::shared_ptr<Outputs::CRT::CRT> get_crt() override { return vdp_->get_crt(); } std::shared_ptr<Outputs::Speaker> get_speaker() override { return nullptr; } void run_for(const Cycles cycles) override { z80_.run_for(cycles); } void configure_as_target(const StaticAnalyser::Target &target) override { } bool insert_media(const StaticAnalyser::Media &media) override { return true; } HalfCycles perform_machine_cycle(const CPU::Z80::PartialMachineCycle &cycle) { uint16_t address = cycle.address ? *cycle.address : 0x0000; switch(cycle.operation) { case CPU::Z80::PartialMachineCycle::ReadOpcode: case CPU::Z80::PartialMachineCycle::Read: *cycle.value = read_pointers_[address >> 14][address & 16383]; break; case CPU::Z80::PartialMachineCycle::Write: write_pointers_[address >> 14][address & 16383] = *cycle.value; break; case CPU::Z80::PartialMachineCycle::Input: switch(address & 0xff) { case 0x98: case 0x99: *cycle.value = vdp_->get_register(address); break; case 0xa2: ay_.set_control_lines(static_cast<GI::AY38910::ControlLines>(GI::AY38910::BDIR | GI::AY38910::BC1)); ay_.set_data_input(*cycle.value); break; case 0xa8: case 0xa9: case 0xaa: case 0xab: *cycle.value = i8255_.get_register(address); break; } break; case CPU::Z80::PartialMachineCycle::Output: switch(address & 0xff) { case 0x98: case 0x99: printf("VDP %d %02x\n", address&1, *cycle.value); vdp_->set_register(address, *cycle.value); break; case 0xa0: ay_.set_control_lines(static_cast<GI::AY38910::ControlLines>(GI::AY38910::BDIR | GI::AY38910::BC2 | GI::AY38910::BC1)); ay_.set_data_input(*cycle.value); break; case 0xa1: ay_.set_control_lines(static_cast<GI::AY38910::ControlLines>(GI::AY38910::BDIR | GI::AY38910::BC2)); ay_.set_data_input(*cycle.value); break; case 0xa8: case 0xa9: case 0xaa: case 0xab: printf("8255 %d %02x\n", address&3, *cycle.value); i8255_.set_register(address, *cycle.value); break; } break; default: break; } // Per the best information I currently have, the MSX inserts an extra cycle into each opcode read, // but otherwise runs without pause. return HalfCycles((cycle.operation == CPU::Z80::PartialMachineCycle::ReadOpcode) ? 2 : 0);; } // Obtains the system ROMs. bool set_rom_fetcher(const std::function<std::vector<std::unique_ptr<std::vector<uint8_t>>>(const std::string &machine, const std::vector<std::string> &names)> &roms_with_names) override { auto roms = roms_with_names( "MSX", { "basic.rom", "main_msx1.rom" }); if(!roms[0] || !roms[1]) return false; basic_ = std::move(*roms[0]); basic_.resize(16384); main_ = std::move(*roms[1]); main_.resize(16384); for(size_t c = 0; c < 4; ++c) { write_pointers_[c] = &ram_[c * 16384]; read_pointers_[c] = &ram_[c * 16384]; } read_pointers_[0] = main_.data(); write_pointers_[0] = scratch_; read_pointers_[1] = basic_.data(); write_pointers_[1] = scratch_; return true; } private: CPU::Z80::Processor<ConcreteMachine, false, false> z80_; std::unique_ptr<TI::TMS9918> vdp_; Intel::i8255::i8255<i8255PortHandler> i8255_; GI::AY38910::AY38910 ay_; i8255PortHandler i8255_port_handler_; AYPortHandler ay_port_handler_; uint8_t *read_pointers_[4]; uint8_t *write_pointers_[4]; uint8_t ram_[65536]; uint8_t scratch_[16384]; std::vector<uint8_t> basic_, main_; }; } using namespace MSX; Machine *Machine::MSX() { return new ConcreteMachine; } Machine::~Machine() {} <|endoftext|>
<commit_before>// illarionserver - server for the game Illarion // Copyright 2011 Illarion e.V. // // This file is part of illarionserver. // // illarionserver 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. // // illarionserver 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 illarionserver. If not, see <http://www.gnu.org/licenses/>. #include "InitialConnection.hpp" #include "Config.hpp" #include "Logger.hpp" #include "netinterface/NetInterface.hpp" #include <memory> #include <thread> auto InitialConnection::create() -> std::shared_ptr<InitialConnection> { std::shared_ptr<InitialConnection> ptr(new InitialConnection()); std::thread servicethread([shared_this = ptr->shared_from_this()] { shared_this->run_service(); }); servicethread.detach(); return ptr; } auto InitialConnection::getNewPlayers() -> NewPlayerVector & { return newPlayers; } void InitialConnection::run_service() { using boost::asio::ip::tcp; int port = Config::instance().port; auto endpoint = tcp::endpoint(tcp::v4(), port); acceptor = std::make_unique<tcp::acceptor>(io_service, endpoint); auto newConnection = std::make_shared<NetInterface>(io_service); using std::placeholders::_1; acceptor->async_accept(newConnection->getSocket(), [shared_this = shared_from_this(), newConnection](auto &&PH1) { shared_this->accept_connection(newConnection, PH1); }); Logger::info(LogFacility::Other) << "Starting the IO Service!" << Log::end; io_service.run(); } void InitialConnection::accept_connection(const std::shared_ptr<NetInterface> &connection, const boost::system::error_code &error) { if (!error) { if (connection->activate()) { newPlayers.push_back(connection); } else { Logger::error(LogFacility::Other) << "Error while activating connection!" << Log::end; } auto newConnection = std::make_shared<NetInterface>(io_service); using std::placeholders::_1; acceptor->async_accept(newConnection->getSocket(), [shared_this = shared_from_this(), newConnection](auto &&PH1) { shared_this->accept_connection(newConnection, PH1); }); } else { Logger::error(LogFacility::Other) << "Could not accept connection: " << error.message() << Log::end; } } InitialConnection::~InitialConnection() { io_service.stop(); } <commit_msg>Log and abort on io service start-up failure<commit_after>// illarionserver - server for the game Illarion // Copyright 2011 Illarion e.V. // // This file is part of illarionserver. // // illarionserver 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. // // illarionserver 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 illarionserver. If not, see <http://www.gnu.org/licenses/>. #include "InitialConnection.hpp" #include "Config.hpp" #include "Logger.hpp" #include "netinterface/NetInterface.hpp" #include <cstdlib> #include <memory> #include <thread> auto InitialConnection::create() -> std::shared_ptr<InitialConnection> { std::shared_ptr<InitialConnection> ptr(new InitialConnection()); std::thread servicethread([shared_this = ptr->shared_from_this()] { shared_this->run_service(); }); servicethread.detach(); return ptr; } auto InitialConnection::getNewPlayers() -> NewPlayerVector & { return newPlayers; } void InitialConnection::run_service() { try { using boost::asio::ip::tcp; int port = Config::instance().port; auto endpoint = tcp::endpoint(tcp::v4(), port); acceptor = std::make_unique<tcp::acceptor>(io_service, endpoint); auto newConnection = std::make_shared<NetInterface>(io_service); using std::placeholders::_1; acceptor->async_accept(newConnection->getSocket(), [shared_this = shared_from_this(), newConnection](auto &&PH1) { shared_this->accept_connection(newConnection, PH1); }); Logger::info(LogFacility::Other) << "Starting the io service." << Log::end; io_service.run(); } catch (const boost::system::system_error &e) { Logger::critical(LogFacility::Other) << "Failed to start io service: " << e.what() << Log::end; std::abort(); } } void InitialConnection::accept_connection(const std::shared_ptr<NetInterface> &connection, const boost::system::error_code &error) { if (!error) { if (connection->activate()) { newPlayers.push_back(connection); } else { Logger::error(LogFacility::Other) << "Error while activating connection!" << Log::end; } auto newConnection = std::make_shared<NetInterface>(io_service); using std::placeholders::_1; acceptor->async_accept(newConnection->getSocket(), [shared_this = shared_from_this(), newConnection](auto &&PH1) { shared_this->accept_connection(newConnection, PH1); }); } else { Logger::error(LogFacility::Other) << "Could not accept connection: " << error.message() << Log::end; } } InitialConnection::~InitialConnection() { io_service.stop(); } <|endoftext|>
<commit_before>/* Copyright (c) 2014, J.D. Koftinoff Software, Ltd. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of J.D. Koftinoff Software, Ltd. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "JDKSAvdeccMCU_World.hpp" #include "JDKSAvdeccMCU_Aps.hpp" namespace JDKSAvdeccMCU { ApsStateMachine::ApsStateMachine( ApsStateMachine::StateVariables *events, ApsStateMachine::StateActions *actions, ApsStateMachine::States *states ) : m_variables( events ), m_actions( actions ), m_states( states ) { m_variables->setOwner( this ); m_actions->setOwner( this ); m_states->setOwner( this ); m_variables->clear(); m_actions->clear(); m_states->clear(); } ApsStateMachine::~ApsStateMachine() { m_variables->setOwner( 0 ); m_actions->setOwner( 0 ); m_states->setOwner( 0 ); } bool ApsStateMachine::run() { return getStates()->run(); } } <commit_msg>Parameter name is variables not events<commit_after>/* Copyright (c) 2014, J.D. Koftinoff Software, Ltd. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of J.D. Koftinoff Software, Ltd. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "JDKSAvdeccMCU_World.hpp" #include "JDKSAvdeccMCU_Aps.hpp" namespace JDKSAvdeccMCU { ApsStateMachine::ApsStateMachine( ApsStateMachine::StateVariables *variables, ApsStateMachine::StateActions *actions, ApsStateMachine::States *states ) : m_variables( variables ), m_actions( actions ), m_states( states ) { m_variables->setOwner( this ); m_actions->setOwner( this ); m_states->setOwner( this ); m_variables->clear(); m_actions->clear(); m_states->clear(); } ApsStateMachine::~ApsStateMachine() { m_variables->setOwner( 0 ); m_actions->setOwner( 0 ); m_states->setOwner( 0 ); } bool ApsStateMachine::run() { return getStates()->run(); } } <|endoftext|>
<commit_before>void recTPC2007(Int_t type, const char *filename="data.root") { // .x recTPC(0,"rfio:/castor/cern.ch/alice/tpc/2007/12/13/00/07000011524011.980.root") // // Set path to calibration data // // type variable = 0 - cosmic test // = 1 - laser test // // Set reconstruction parameters //// gSystem->Load("/afs/cern.ch/alice/tpctest/root/HEAD/lib/libRAliEn.so"); TGrid::Connect("alien://"); // AliLog::SetClassDebugLevel("AliTPCclustererMI",2); AliTPCRecoParam * tpcRecoParam = 0; if (type==0) tpcRecoParam = AliTPCRecoParam::GetCosmicTestParam(kTRUE); if (type>0) tpcRecoParam = AliTPCRecoParam::GetLaserTestParam(kTRUE); tpcRecoParam->SetTimeInterval(60,1000); tpcRecoParam->Dump(); AliTPCReconstructor::SetRecoParam(tpcRecoParam); AliTPCReconstructor::SetStreamLevel(1); AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 2, 1., 10., 1); AliTracker::SetFieldMap(field,1); // // AliReconstruction rec; rec.SetDefaultStorage("alien://folder=/alice/data/2007/LHC07w/OCDB/"); rec.SetWriteESDfriend(kTRUE); rec.SetInput(filename); rec.SetRunReconstruction("TPC"); rec.SetEquipmentIdMap("EquipmentIdMap.data"); // rec.SetOption("TPC","PedestalSubtraction OldRCUFormat"); rec.SetFillESD("TPC"); rec.SetFillTriggerESD(kFALSE); rec.SetRunVertexFinder(kFALSE); rec.Run(); } <commit_msg>Changing parameters (Marian)<commit_after>void recTPC2007(Int_t type, const char *filename="data.root") { // .L $ALICE_ROOT/TPC/macros/recTPC2007.C // recTPC2007(0,"rfio:/castor/cern.ch/alice/data/2007/12/16/11/07000013151011.20.root") //recTPC2007(0,"alien:///alice/data/2007/LHC07w_TPC/000012674/raw/07000012674011.90.root") // recTPC2007(0,"/data/test2007/07000012674011/07000012674011.90.root") // // Set path to calibration data // // type variable = 0 - cosmic test // = 1 - laser test // // Set reconstruction parameters //// //gSystem->Load("/afs/cern.ch/alice/tpctest/root/HEAD/lib/libRAliEn.so"); //gSystem->Load("$ROOTSYS/lib/libXrdClient.so") TGrid::Connect("alien://"); // AliLog::SetClassDebugLevel("AliTPCclustererMI",2); AliTPCRecoParam * tpcRecoParam = 0; if (type==0) tpcRecoParam = AliTPCRecoParam::GetCosmicTestParam(kTRUE); if (type>0) tpcRecoParam = AliTPCRecoParam::GetLaserTestParam(kTRUE); tpcRecoParam->SetTimeInterval(60,940); tpcRecoParam->Dump(); // // // tpcRecoParam->SetMinMaxCutAbs(4.); // tpcRecoParam->SetMinLeftRightCutAbs(6.); // tpcRecoParam->SetMinUpDownCutAbs(7.); // tpcRecoParam->SetMinMaxCutSigma(4.); // tpcRecoParam->SetMinLeftRightCutSigma(6.); // tpcRecoParam->SetMinUpDownCutSigma(7.); // // AliTPCReconstructor::SetRecoParam(tpcRecoParam); AliTPCReconstructor::SetStreamLevel(100); AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 2, 1., 10., 1); AliTracker::SetFieldMap(field,1); // // AliReconstruction rec; rec.SetDefaultStorage("alien://folder=/alice/data/2007/LHC07w/OCDB/"); rec.SetWriteESDfriend(kTRUE); rec.SetInput(filename); rec.SetRunReconstruction("TPC"); rec.SetEquipmentIdMap("EquipmentIdMap.data"); // rec.SetOption("TPC","PedestalSubtraction OldRCUFormat"); rec.SetFillESD("TPC"); rec.SetFillTriggerESD(kFALSE); rec.SetRunVertexFinder(kFALSE); rec.SetCleanESD(kFALSE); rec.Run(); } <|endoftext|>
<commit_before>/********************************************************************** // @@@ START COPYRIGHT @@@ // // 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. // // @@@ END COPYRIGHT @@@ **********************************************************************/ /* -*-C++-*- **************************************************************************** * * File: Helper functions for use by bin/clitest.cpp * Description: Test driver useing exe util cli interface * * * * **************************************************************************** */ #include "blobtest.h" Int32 extractLengthOfLobColumn(CliGlobals *cliglob, char *lobHandle, Int64 &lengthOfLob, char *lobColumnName, char *tableName) { Int32 retcode = 0; char * query = new char[4096]; ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL); //Use lob handle to retrieve the lob length. char lobLengthResult[200]; str_cpy_all(lobLengthResult," ",200); Int32 lobLengthResultLen = 0; str_sprintf(query,"extract loblength (lob '%s') LENGTH %ld ",lobHandle, lengthOfLob); retcode = cliInterface.executeImmediate(query,lobLengthResult,&lobLengthResultLen,FALSE); delete query; return retcode; } Int32 extractLobHandle(CliGlobals *cliglob, char *& lobHandle, char *lobColumnName, char *tableName) { Int32 retcode = 0; ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL); char * query = new char[4096]; Int32 lobHandleLen = 0; str_sprintf(query,"select %s from %s",lobColumnName,tableName); retcode = cliInterface.executeImmediate(query,lobHandle,&lobHandleLen,FALSE); lobHandle[lobHandleLen]='\0'; delete query; return retcode; } Int32 extractLobToBuffer(CliGlobals *cliglob, char * lobHandle, Int64 &lengthOfLob, char *lobColumnName, char *tableName) { Int32 retcode = 0; ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL); // Extract lob data into a buffer. char * query = new char [500]; char *lobFinalBuf = new char[lengthOfLob]; char statusBuf[200] = {'\0'}; Int32 statusBufLen = 0; Int64 lobExtractLen = 10000; char *lobDataBuf = new char[lobExtractLen]; str_sprintf(query,"extract lobtobuffer(lob '%s', LOCATION %ld, SIZE %ld) ", lobHandle, (Int64)lobDataBuf, lobExtractLen); retcode = cliInterface.executeImmediatePrepare(query); short i = 0; while ((retcode != 100) && !(retcode<0)) { retcode = cliInterface.clearExecFetchClose(NULL,NULL,statusBuf, &statusBufLen); if (retcode>= 0) { memcpy((char*)&(lobFinalBuf[i]),(char *)lobDataBuf,lobExtractLen); i += lobExtractLen; } } if (retcode ==100 || retcode ==0) { FILE * lobFileId = fopen("lob_output_file","w"); int byteCount=fwrite(lobFinalBuf,sizeof(char),lengthOfLob, lobFileId); cout << "Writing " << byteCount << " bytes from user buffer to file lob_output_file in current directory" << endl; fclose(lobFileId); } str_sprintf(query,"extract lobtobuffer(lob '%s', LOCATION %ld, SIZE 0) ", lobHandle, (Int64)lobDataBuf); cliInterface.clearExecFetchClose(NULL,NULL,statusBuf, &statusBufLen); delete lobFinalBuf; delete query; delete lobDataBuf; return retcode; } Int32 extractLobToFileInChunks(CliGlobals *cliglob, char * lobHandle, char *filename,Int64 &lengthOfLob, char *lobColumnName, char *tableName) { Int32 retcode = 0; ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL); // Extract lob data into a buffer. char * query = new char [500]; char statusBuf[200] = {'\0'}; Int32 statusBufLen = 0; Int64 lobExtractLen = 10000; char *lobDataBuf = new char[lobExtractLen]; Int64 *inputOutputAddr = &lobExtractLen; str_sprintf(query,"extract lobtobuffer(lob '%s', LOCATION %ld, SIZE %ld) ", lobHandle, (Int64)lobDataBuf, lobExtractLen); retcode = cliInterface.executeImmediatePrepare(query); short i = 0; FILE * lobFileId = fopen(filename,"a+"); int byteCount = 0; while ((retcode != 100) && !(retcode<0)) { retcode = cliInterface.clearExecFetchClose(NULL,NULL,statusBuf, &statusBufLen); if (retcode>= 0) { byteCount=fwrite(lobDataBuf,sizeof(char),*inputOutputAddr, lobFileId); cout << "Wrote " << byteCount << " bytes to file : " << filename << endl; } } lobExtractLen = 0; str_sprintf(query,"extract lobtobuffer(lob '%s', LOCATION %ld, SIZE %ld) ", lobHandle, (Int64)lobDataBuf, lobExtractLen); retcode = cliInterface.executeImmediatePrepare(query); cliInterface.clearExecFetchClose(NULL,NULL,statusBuf, &statusBufLen); fclose(lobFileId); delete query; delete lobDataBuf; return retcode; } Int32 insertBufferToLob(CliGlobals *cliglob, char *tableName) { Int32 retcode = 0; ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL); // Extract lob data into a buffer. char * query = new char [500]; char statusBuf[200] = {'\0'}; Int32 statusBufLen = 0; Int64 lobInsertLen = 10; char *lobDataBuf = new char[lobInsertLen]; memcpy(lobDataBuf, "xxxxxyyyyy",10); str_sprintf(query,"insert into %s values (1, buffertolob (LOCATION %ld, SIZE %ld))", tableName,(Int64)lobDataBuf, lobInsertLen); retcode = cliInterface.executeImmediate(query); if (retcode <0) { cliInterface.executeImmediate("rollback work"); delete query; delete lobDataBuf; return retcode; } retcode = cliInterface.executeImmediate("commit work"); delete query; delete lobDataBuf; return retcode; } Int32 updateBufferToLob(CliGlobals *cliglob, char *tableName, char *columnName) { Int32 retcode = 0; ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL); // Extract lob data into a buffer. char * query = new char [500]; char statusBuf[200] = {'\0'}; Int32 statusBufLen = 0; Int64 lobUpdateLen = 20; char *lobDataBuf = new char[lobUpdateLen]; memcpy(lobDataBuf, "zzzzzzzzzzzzzzzzzzzz",20); str_sprintf(query,"update %s set %s= buffertolob(LOCATION %ld, SIZE %ld)", tableName,columnName, (Int64)lobDataBuf, lobUpdateLen); retcode = cliInterface.executeImmediate(query); if (retcode <0) { cliInterface.executeImmediate("rollback work"); delete query; delete lobDataBuf; return retcode; } retcode = cliInterface.executeImmediate("commit work"); delete query; delete lobDataBuf; return retcode; } Int32 updateAppendBufferToLob(CliGlobals *cliglob, char *tableName, char *columnName) { Int32 retcode = 0; ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL); // Extract lob data into a buffer. char * query = new char [500]; char statusBuf[200] = {'\0'}; Int32 statusBufLen = 0; Int64 lobUpdateLen = 15; char *lobDataBuf = new char[lobUpdateLen]; memcpy(lobDataBuf, "aaaaabbbbbccccc",15); str_sprintf(query,"update %s set %s=buffertolob (LOCATION %ld, SIZE %ld,append)", tableName, columnName,(Int64)lobDataBuf, lobUpdateLen); retcode = cliInterface.executeImmediate(query); if (retcode <0) { cliInterface.executeImmediate("rollback work"); delete query; delete lobDataBuf; return retcode; } retcode = cliInterface.executeImmediate("commit work"); delete query; delete lobDataBuf; return retcode; } Int32 updateBufferToLobHandle(CliGlobals *cliglob,char *handle) { Int32 retcode = 0; ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL); // update lob data into via a buffer. char * query = new char [500]; char statusBuf[200] = {'\0'}; Int32 statusBufLen = 0; Int64 lobUpdateLen = 20; char *lobDataBuf = new char[lobUpdateLen]; memcpy(lobDataBuf, "zzzzzzzzzzzzzzzzzzzz",20); str_sprintf(query,"update lob (LOB '%s' , LOCATION %ld, SIZE %ld)", handle, (Int64)lobDataBuf, lobUpdateLen); retcode = cliInterface.executeImmediate(query); if (retcode <0) { cliInterface.executeImmediate("rollback work"); delete query; delete lobDataBuf; return retcode; } retcode = cliInterface.executeImmediate("commit work"); delete query; delete lobDataBuf; return retcode; } Int32 updateAppendBufferToLobHandle(CliGlobals *cliglob,char *handle, Int64 lobUpdateLen, Int64 sourceAddress) { Int32 retcode = 0; ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL); // update lob data into via a buffer. char * query = new char [500]; char statusBuf[200] = {'\0'}; Int32 statusBufLen = 0; char *lobDataBuf = new char[lobUpdateLen]; memcpy(lobDataBuf, (char *)sourceAddress,lobUpdateLen); str_sprintf(query,"update lob (LOB '%s' , LOCATION %ld, SIZE %ld,append )", handle, (Int64)lobDataBuf, lobUpdateLen); retcode = cliInterface.executeImmediate(query); if (retcode <0) { cliInterface.executeImmediate("rollback work"); delete query; delete lobDataBuf; return retcode; } retcode = cliInterface.executeImmediate("commit work"); delete query; delete lobDataBuf; return retcode; } Int32 updateTruncateLobHandle(CliGlobals *cliglob,char *handle) { Int32 retcode = 0; ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL); // update lob data into via a buffer. char * query = new char [500]; char statusBuf[200] = {'\0'}; Int32 statusBufLen = 0; Int64 lobUpdateLen = 20; char *lobDataBuf = new char[lobUpdateLen]; memcpy(lobDataBuf, "zzzzzzzzzzzzzzzzzzzz",20); str_sprintf(query,"update lob (LOB '%s' , empty_blob())", handle); retcode = cliInterface.executeImmediate(query); if (retcode <0) { cliInterface.executeImmediate("rollback work"); delete query; delete lobDataBuf; return retcode; } retcode = cliInterface.executeImmediate("commit work"); delete query; delete lobDataBuf; return retcode; } <commit_msg>[TRAFODION-2754] Get statistics cores sqlci or mxosrvr at str_sprintf()<commit_after>/********************************************************************** // @@@ START COPYRIGHT @@@ // // 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. // // @@@ END COPYRIGHT @@@ **********************************************************************/ /* -*-C++-*- **************************************************************************** * * File: Helper functions for use by bin/clitest.cpp * Description: Test driver useing exe util cli interface * * * * **************************************************************************** */ #include "blobtest.h" Int32 extractLengthOfLobColumn(CliGlobals *cliglob, char *lobHandle, Int64 &lengthOfLob, char *lobColumnName, char *tableName) { Int32 retcode = 0; char * query = new char[4096]; ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL); //Use lob handle to retrieve the lob length. char lobLengthResult[200]; str_cpy_all(lobLengthResult," ",200); Int32 lobLengthResultLen = 0; sprintf(query,"extract loblength (lob '%s') LOCATION %lu ",lobHandle, (unsigned long)&lengthOfLob); retcode = cliInterface.executeImmediate(query,lobLengthResult,&lobLengthResultLen,FALSE); delete query; return retcode; } Int32 extractLobHandle(CliGlobals *cliglob, char *& lobHandle, char *lobColumnName, char *tableName) { Int32 retcode = 0; ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL); char * query = new char[4096]; Int32 lobHandleLen = 0; sprintf(query,"select %s from %s",lobColumnName,tableName); retcode = cliInterface.executeImmediate(query,lobHandle,&lobHandleLen,FALSE); lobHandle[lobHandleLen]='\0'; delete query; return retcode; } Int32 extractLobToBuffer(CliGlobals *cliglob, char * lobHandle, Int64 &lengthOfLob, char *lobColumnName, char *tableName) { Int32 retcode = 0; ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL); // Extract lob data into a buffer. char * query = new char [500]; char *lobFinalBuf = new char[lengthOfLob]; char statusBuf[200] = {'\0'}; Int32 statusBufLen = 0; Int64 lobExtractLen = 10000; char *lobDataBuf = new char[lobExtractLen]; sprintf(query,"extract lobtobuffer(lob '%s', LOCATION %lu, SIZE %ld) ", lobHandle, (unsigned long)lobDataBuf, lobExtractLen); retcode = cliInterface.executeImmediatePrepare(query); short i = 0; while ((retcode != 100) && !(retcode<0)) { retcode = cliInterface.clearExecFetchClose(NULL,NULL,statusBuf, &statusBufLen); if (retcode>= 0) { memcpy((char*)&(lobFinalBuf[i]),(char *)lobDataBuf,lobExtractLen); i += lobExtractLen; } } if (retcode ==100 || retcode ==0) { FILE * lobFileId = fopen("lob_output_file","w"); int byteCount=fwrite(lobFinalBuf,sizeof(char),lengthOfLob, lobFileId); cout << "Writing " << byteCount << " bytes from user buffer to file lob_output_file in current directory" << endl; fclose(lobFileId); } sprintf(query,"extract lobtobuffer(lob '%s', LOCATION %lu, SIZE 0) ", lobHandle, (unsigned long)lobDataBuf); cliInterface.clearExecFetchClose(NULL,NULL,statusBuf, &statusBufLen); delete lobFinalBuf; delete query; delete lobDataBuf; return retcode; } Int32 extractLobToFileInChunks(CliGlobals *cliglob, char * lobHandle, char *filename,Int64 &lengthOfLob, char *lobColumnName, char *tableName) { Int32 retcode = 0; ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL); // Extract lob data into a buffer. char * query = new char [500]; char statusBuf[200] = {'\0'}; Int32 statusBufLen = 0; Int64 lobExtractLen = 10000; char *lobDataBuf = new char[lobExtractLen]; Int64 *inputOutputAddr = &lobExtractLen; sprintf(query,"extract lobtobuffer(lob '%s', LOCATION %lu, SIZE %lu) ", lobHandle, (unsigned long)lobDataBuf, (unsigned long)inputOutputAddr); retcode = cliInterface.executeImmediatePrepare(query); short i = 0; FILE * lobFileId = fopen(filename,"a+"); int byteCount = 0; while ((retcode != 100) && !(retcode<0)) { retcode = cliInterface.clearExecFetchClose(NULL,NULL,statusBuf, &statusBufLen); if (retcode>= 0) { byteCount=fwrite(lobDataBuf,sizeof(char),*inputOutputAddr, lobFileId); cout << "Wrote " << byteCount << " bytes to file : " << filename << endl; } } lobExtractLen = 0; sprintf(query,"extract lobtobuffer(lob '%s', LOCATION %lu, SIZE %ld) ", lobHandle, (unsigned long)lobDataBuf, (unsigned long)inputOutputAddr); retcode = cliInterface.executeImmediatePrepare(query); cliInterface.clearExecFetchClose(NULL,NULL,statusBuf, &statusBufLen); fclose(lobFileId); delete query; delete lobDataBuf; return retcode; } Int32 insertBufferToLob(CliGlobals *cliglob, char *tableName) { Int32 retcode = 0; ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL); // Extract lob data into a buffer. char * query = new char [500]; char statusBuf[200] = {'\0'}; Int32 statusBufLen = 0; Int64 lobInsertLen = 10; char *lobDataBuf = new char[lobInsertLen]; memcpy(lobDataBuf, "xxxxxyyyyy",10); sprintf(query,"insert into %s values (1, buffertolob (LOCATION %lu, SIZE %ld))", tableName, (unsigned long)lobDataBuf, lobInsertLen); retcode = cliInterface.executeImmediate(query); if (retcode <0) { cliInterface.executeImmediate("rollback work"); delete query; delete lobDataBuf; return retcode; } retcode = cliInterface.executeImmediate("commit work"); delete query; delete lobDataBuf; return retcode; } Int32 updateBufferToLob(CliGlobals *cliglob, char *tableName, char *columnName) { Int32 retcode = 0; ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL); // Extract lob data into a buffer. char * query = new char [500]; char statusBuf[200] = {'\0'}; Int32 statusBufLen = 0; Int64 lobUpdateLen = 20; char *lobDataBuf = new char[lobUpdateLen]; memcpy(lobDataBuf, "zzzzzzzzzzzzzzzzzzzz",20); sprintf(query,"update %s set %s= buffertolob(LOCATION %lu, SIZE %ld)", tableName,columnName, (unsigned long)lobDataBuf, lobUpdateLen); retcode = cliInterface.executeImmediate(query); if (retcode <0) { cliInterface.executeImmediate("rollback work"); delete query; delete lobDataBuf; return retcode; } retcode = cliInterface.executeImmediate("commit work"); delete query; delete lobDataBuf; return retcode; } Int32 updateAppendBufferToLob(CliGlobals *cliglob, char *tableName, char *columnName) { Int32 retcode = 0; ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL); // Extract lob data into a buffer. char * query = new char [500]; char statusBuf[200] = {'\0'}; Int32 statusBufLen = 0; Int64 lobUpdateLen = 15; char *lobDataBuf = new char[lobUpdateLen]; memcpy(lobDataBuf, "aaaaabbbbbccccc",15); sprintf(query,"update %s set %s=buffertolob (LOCATION %lu, SIZE %ld,append)", tableName, columnName, (unsigned long)lobDataBuf, lobUpdateLen); retcode = cliInterface.executeImmediate(query); if (retcode <0) { cliInterface.executeImmediate("rollback work"); delete query; delete lobDataBuf; return retcode; } retcode = cliInterface.executeImmediate("commit work"); delete query; delete lobDataBuf; return retcode; } Int32 updateBufferToLobHandle(CliGlobals *cliglob,char *handle) { Int32 retcode = 0; ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL); // update lob data into via a buffer. char * query = new char [500]; char statusBuf[200] = {'\0'}; Int32 statusBufLen = 0; Int64 lobUpdateLen = 20; char *lobDataBuf = new char[lobUpdateLen]; memcpy(lobDataBuf, "zzzzzzzzzzzzzzzzzzzz",20); sprintf(query,"update lob (LOB '%s' , LOCATION %lu, SIZE %ld)", handle, (unsigned long)lobDataBuf, lobUpdateLen); retcode = cliInterface.executeImmediate(query); if (retcode <0) { cliInterface.executeImmediate("rollback work"); delete query; delete lobDataBuf; return retcode; } retcode = cliInterface.executeImmediate("commit work"); delete query; delete lobDataBuf; return retcode; } Int32 updateAppendBufferToLobHandle(CliGlobals *cliglob,char *handle, Int64 lobUpdateLen, Int64 sourceAddress) { Int32 retcode = 0; ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL); // update lob data into via a buffer. char * query = new char [500]; char statusBuf[200] = {'\0'}; Int32 statusBufLen = 0; char *lobDataBuf = new char[lobUpdateLen]; memcpy(lobDataBuf, (char *)sourceAddress,lobUpdateLen); sprintf(query,"update lob (LOB '%s' , LOCATION %lu, SIZE %ld,append )", handle, (unsigned long)lobDataBuf, lobUpdateLen); retcode = cliInterface.executeImmediate(query); if (retcode <0) { cliInterface.executeImmediate("rollback work"); delete query; delete lobDataBuf; return retcode; } retcode = cliInterface.executeImmediate("commit work"); delete query; delete lobDataBuf; return retcode; } Int32 updateTruncateLobHandle(CliGlobals *cliglob,char *handle) { Int32 retcode = 0; ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL); // update lob data into via a buffer. char * query = new char [500]; char statusBuf[200] = {'\0'}; Int32 statusBufLen = 0; Int64 lobUpdateLen = 20; char *lobDataBuf = new char[lobUpdateLen]; memcpy(lobDataBuf, "zzzzzzzzzzzzzzzzzzzz",20); sprintf(query,"update lob (LOB '%s' , empty_blob())", handle); retcode = cliInterface.executeImmediate(query); if (retcode <0) { cliInterface.executeImmediate("rollback work"); delete query; delete lobDataBuf; return retcode; } retcode = cliInterface.executeImmediate("commit work"); delete query; delete lobDataBuf; return retcode; } <|endoftext|>
<commit_before>#include "GL.h" #include "PrimitiveRenderer.h" #include <VBO.h> #include "../system/StringUtils.h" #include <iostream> using namespace std; PrimitiveRenderer::PrimitiveRenderer() { } static set<int> readCompressedFormats() { set<int> r; GLint num_compressed_format; glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &num_compressed_format); if (num_compressed_format > 0) { GLint * compressed_format = new GLint[num_compressed_format * sizeof(GLint)]; glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, compressed_format); for (unsigned int i = 0; i < num_compressed_format; i++) { r.insert(compressed_format[i]); } delete[] compressed_format; } return r; } static set<string> readExtensions() { set<string> r; GLint numExtensions; glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions); if (numExtensions > 0) { for (int i = 0; i < numExtensions; i++) { const GLubyte * e = glGetStringi(GL_EXTENSIONS, i); r.insert((const char *)e); } } return r; } void PrimitiveRenderer::initializeBase() { #ifdef _WIN32 GLenum err = glewInit(); if (GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); assert(0); } fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION)); #endif glPolygonOffset(1, 2); glClearColor(0.98f, 0.98f, 0.98f, 1.0f); glActiveTexture(GL_TEXTURE0); glStencilFuncSeparate(GL_FRONT, GL_EQUAL, 0, 0xff); glStencilFuncSeparate(GL_BACK, GL_NEVER, 0, 0xff); glStencilOpSeparate(GL_FRONT, GL_DECR_WRAP, GL_KEEP, GL_KEEP); glStencilOpSeparate(GL_BACK, GL_INCR_WRAP, GL_KEEP, GL_KEEP); #if 0 #if 1 static const GLfloat light0_pos[4] = { -50.0f, 50.0f, 0.0f, 0.0f }; #else static const GLfloat light0_pos[4] = { 0.0f, 0.0f, +50.0f, 0.0f }; #endif // white light static const GLfloat light0_color[4] = { 0.6f, 0.6f, 0.6f, 1.0f }; static const GLfloat light1_pos[4] = { 50.0f, 50.0f, 0.0f, 0.0f }; // cold blue light static const GLfloat light1_color[4] = { 0.4f, 0.4f, 1.0f, 1.0f }; #endif #if 0 /* light */ glLightfv(GL_LIGHT0, GL_POSITION, light0_pos); glLightfv(GL_LIGHT0, GL_DIFFUSE, light0_color); glEnable(GL_LIGHT0); glLightfv(GL_LIGHT1, GL_POSITION, light1_pos); glLightfv(GL_LIGHT1, GL_DIFFUSE, light1_color); glEnable(GL_LIGHT1); #endif set<int> compressed_formats = readCompressedFormats(); set<string> extensions = readExtensions(); // GL_ARB_ES2_compatibility // GL_ARB_ES3_compatibility // GL_ARB_texture_storage // GL_ARB_compressed_texture_pixel_storage // GL_EXT_abgr, GL_EXT_bgra has_dxt1 = extensions.count("GL_EXT_texture_compression_dxt1"); has_etc1 = extensions.count("OES_compressed_ETC1_RGB8_texture"); has_rgtc = extensions.count("GL_ARB_texture_compression_rgtc") || extensions.count("GL_EXT_texture_compression_rgtc"); // GL_IMG_texture_compression_pvrtc" // GL_AMD_compressed_ATC_texture / GL_ATI_texture_compression_atitc // GL_OES_texture_compression_S3TC / GL_EXT_texture_compression_s3tc // EXT_texture_rg : RED and RG modes const char * version_str = (const char *)glGetString(GL_VERSION); if (version_str) { // OpenGL ES 3.0 Apple A7 GPU - 75.9.3 // 3.0 Mesa 11.0.2 cerr << "got version: " << version_str << endl; vector<string> parts = StringUtils::split(version_str); if (parts.size() >= 3 && parts[0] == "OpenGL" && parts[1] == "ES") { const string & es_version = parts[2]; cerr << "got OpenGL ES: " << es_version << endl; if (es_version == "3.0") { cerr << "has etc1" << endl; has_etc1 = true; is_es3 = true; } has_rgb565 = true; } else if (parts.size() >= 2 && parts[1] == "Mesa") { } else { assert(0); } } int ii; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &ii); max_texture_size = ii; cerr << "Maximum texture size is " << max_texture_size << endl; // MAX_VERTEX_TEXTURE_IMAGE_UNITS => how many textures a vertex shader can read } void PrimitiveRenderer::blend(bool t) { if (t != blend_enabled) { blend_enabled = t; if (t) glEnable(GL_BLEND); else glDisable(GL_BLEND); } } void PrimitiveRenderer::stencilTest(bool t) { if (t != stencil_test_enabled) { stencil_test_enabled = t; if (t) glEnable(GL_STENCIL_TEST); else glDisable(GL_STENCIL_TEST); } } void PrimitiveRenderer::stencilMask(int m) { if (m != current_stencil_mask) { current_stencil_mask = m; glStencilMask(m); } } void PrimitiveRenderer::depthTest(bool t) { if (t != depth_test_enabled) { depth_test_enabled = t; if (t) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); } } void PrimitiveRenderer::depthMask(bool m) { if (m != current_depth_mask) { current_depth_mask = m; glDepthMask(m ? GL_TRUE : GL_FALSE); } } void PrimitiveRenderer::cullFace(bool t) { if (t != cull_face_enabled) { cull_face_enabled = t; if (t) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); } } void PrimitiveRenderer::setLineWidth(float w) { if (w != current_line_width) { current_line_width = w; glLineWidth(w); } } void PrimitiveRenderer::bind(const canvas::TextureRef & texture) { int id = texture.getTextureId(); if (!id) { cerr << "trying to bind zero tex" << endl; assert(0); } else if (id != current_texture_2d) { current_texture_2d = id; glBindTexture(GL_TEXTURE_2D, id); } } void PrimitiveRenderer::bind(const VBO & vbo) { int a = vbo.getVertexArrayId(); if (!a) { cerr << "trying to bind zero vao" << endl; assert(0); } else if (a != current_vertex_array) { current_vertex_array = a; glBindVertexArray(a); // glBindBuffer(GL_ARRAY_BUFFER, vbo.getVertexBufferId()); // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo.getIndexBufferId()); } } void PrimitiveRenderer::use(const gpufw::shader_program & program) { int id = program.getProgramObjectId(); if (!id) { assert(0); } else if (id != current_program) { current_program = id; glUseProgram(id); } } void PrimitiveRenderer::clear(int clear_bits) { int gl_bits = 0; if (clear_bits & COLOR_BUFFER_BIT) { colorMask(true, true, true, true); gl_bits |= GL_COLOR_BUFFER_BIT; } if (clear_bits & DEPTH_BUFFER_BIT || clear_bits & DEPTH_STENCIL_BUFFER_BIT) { depthMask(true); gl_bits |= GL_DEPTH_BUFFER_BIT; } if (clear_bits & STENCIL_BUFFER_BIT || clear_bits & DEPTH_STENCIL_BUFFER_BIT) { stencilMask(0xff); gl_bits |= GL_STENCIL_BUFFER_BIT; } if (gl_bits) { glClear(gl_bits); } } void PrimitiveRenderer::colorMask(bool r, bool g, bool b, bool a) { if (r != current_red_mask || g != current_green_mask || b != current_blue_mask || a != current_alpha_mask) { current_red_mask = r; current_green_mask = g; current_blue_mask = b; current_alpha_mask = a; glColorMask( r ? GL_TRUE : GL_FALSE, g ? GL_TRUE : GL_FALSE, b ? GL_TRUE : GL_FALSE, a ? GL_TRUE : GL_FALSE ); } } void PrimitiveRenderer::setCompositionMode(CompositionMode mode) { if (mode != current_composition_mode) { current_composition_mode = mode; switch (mode) { case COPY: glBlendFunc(GL_ONE, GL_ZERO); break; case NORMAL: glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); break; case MULTIPLY: glBlendFunc(GL_ZERO, GL_SRC_COLOR); break; } } } void PrimitiveRenderer::viewport(unsigned int x, unsigned int y, unsigned int w, unsigned int h) { if (w != current_display_size.x || h != current_display_size.y) { current_display_size = glm::ivec2(w, h); cerr << "updating viewport\n"; glViewport(0, 0, (unsigned int)(w * display_scale), (unsigned int)(h * display_scale)); } } void PrimitiveRenderer::pushGroupMarker(const char * name) { #ifdef GL_ES glPushGroupMarkerEXT(0, name); #endif } void PrimitiveRenderer::popGroupMarker() { #ifdef GL_ES glPopGroupMarkerEXT(); #endif } void PrimitiveRenderer::invalidateFramebuffer(int bits) { int n = 0; GLenum v[4]; if (bits & STENCIL_BUFFER_BIT) { v[n++] = GL_STENCIL_ATTACHMENT; } if (bits & DEPTH_BUFFER_BIT) { v[n++] = GL_DEPTH_ATTACHMENT; } if (n) { if (is_es3) { glInvalidateFramebuffer(GL_FRAMEBUFFER, n, &v[0]); } else { #ifdef GL_ES // glBindFramebuffer(GL_FRAMEBUFFER, current_framebuffer); // glDiscardFramebufferEXT(GL_FRAMEBUFFER, n, &v[0]); #endif } } } <commit_msg>add RGB565 for Mesa, assert that RGB565 is available<commit_after>#include "GL.h" #include "PrimitiveRenderer.h" #include <VBO.h> #include "../system/StringUtils.h" #include <iostream> using namespace std; PrimitiveRenderer::PrimitiveRenderer() { } static set<int> readCompressedFormats() { set<int> r; GLint num_compressed_format; glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &num_compressed_format); if (num_compressed_format > 0) { GLint * compressed_format = new GLint[num_compressed_format * sizeof(GLint)]; glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, compressed_format); for (unsigned int i = 0; i < num_compressed_format; i++) { r.insert(compressed_format[i]); } delete[] compressed_format; } return r; } static set<string> readExtensions() { set<string> r; GLint numExtensions; glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions); if (numExtensions > 0) { for (int i = 0; i < numExtensions; i++) { const GLubyte * e = glGetStringi(GL_EXTENSIONS, i); r.insert((const char *)e); } } return r; } void PrimitiveRenderer::initializeBase() { #ifdef _WIN32 GLenum err = glewInit(); if (GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); assert(0); } fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION)); #endif glPolygonOffset(1, 2); glClearColor(0.98f, 0.98f, 0.98f, 1.0f); glActiveTexture(GL_TEXTURE0); glStencilFuncSeparate(GL_FRONT, GL_EQUAL, 0, 0xff); glStencilFuncSeparate(GL_BACK, GL_NEVER, 0, 0xff); glStencilOpSeparate(GL_FRONT, GL_DECR_WRAP, GL_KEEP, GL_KEEP); glStencilOpSeparate(GL_BACK, GL_INCR_WRAP, GL_KEEP, GL_KEEP); #if 0 #if 1 static const GLfloat light0_pos[4] = { -50.0f, 50.0f, 0.0f, 0.0f }; #else static const GLfloat light0_pos[4] = { 0.0f, 0.0f, +50.0f, 0.0f }; #endif // white light static const GLfloat light0_color[4] = { 0.6f, 0.6f, 0.6f, 1.0f }; static const GLfloat light1_pos[4] = { 50.0f, 50.0f, 0.0f, 0.0f }; // cold blue light static const GLfloat light1_color[4] = { 0.4f, 0.4f, 1.0f, 1.0f }; #endif #if 0 /* light */ glLightfv(GL_LIGHT0, GL_POSITION, light0_pos); glLightfv(GL_LIGHT0, GL_DIFFUSE, light0_color); glEnable(GL_LIGHT0); glLightfv(GL_LIGHT1, GL_POSITION, light1_pos); glLightfv(GL_LIGHT1, GL_DIFFUSE, light1_color); glEnable(GL_LIGHT1); #endif set<int> compressed_formats = readCompressedFormats(); set<string> extensions = readExtensions(); // GL_ARB_ES2_compatibility // GL_ARB_ES3_compatibility // GL_ARB_texture_storage // GL_ARB_compressed_texture_pixel_storage // GL_EXT_abgr, GL_EXT_bgra has_dxt1 = extensions.count("GL_EXT_texture_compression_dxt1"); has_etc1 = extensions.count("OES_compressed_ETC1_RGB8_texture"); has_rgtc = extensions.count("GL_ARB_texture_compression_rgtc") || extensions.count("GL_EXT_texture_compression_rgtc"); // GL_IMG_texture_compression_pvrtc" // GL_AMD_compressed_ATC_texture / GL_ATI_texture_compression_atitc // GL_OES_texture_compression_S3TC / GL_EXT_texture_compression_s3tc // EXT_texture_rg : RED and RG modes const char * version_str = (const char *)glGetString(GL_VERSION); if (version_str) { // OpenGL ES 3.0 Apple A7 GPU - 75.9.3 // 3.0 Mesa 11.0.2 cerr << "got version: " << version_str << endl; vector<string> parts = StringUtils::split(version_str); if (parts.size() >= 3 && parts[0] == "OpenGL" && parts[1] == "ES") { const string & es_version = parts[2]; cerr << "got OpenGL ES: " << es_version << endl; if (es_version == "3.0") { cerr << "has etc1" << endl; has_etc1 = true; is_es3 = true; } has_rgb565 = true; } else if (parts.size() >= 2 && parts[1] == "Mesa") { has_rgb565 = true; } else { assert(0); } } assert(has_rgb565); int ii; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &ii); max_texture_size = ii; cerr << "Maximum texture size is " << max_texture_size << endl; // MAX_VERTEX_TEXTURE_IMAGE_UNITS => how many textures a vertex shader can read } void PrimitiveRenderer::blend(bool t) { if (t != blend_enabled) { blend_enabled = t; if (t) glEnable(GL_BLEND); else glDisable(GL_BLEND); } } void PrimitiveRenderer::stencilTest(bool t) { if (t != stencil_test_enabled) { stencil_test_enabled = t; if (t) glEnable(GL_STENCIL_TEST); else glDisable(GL_STENCIL_TEST); } } void PrimitiveRenderer::stencilMask(int m) { if (m != current_stencil_mask) { current_stencil_mask = m; glStencilMask(m); } } void PrimitiveRenderer::depthTest(bool t) { if (t != depth_test_enabled) { depth_test_enabled = t; if (t) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); } } void PrimitiveRenderer::depthMask(bool m) { if (m != current_depth_mask) { current_depth_mask = m; glDepthMask(m ? GL_TRUE : GL_FALSE); } } void PrimitiveRenderer::cullFace(bool t) { if (t != cull_face_enabled) { cull_face_enabled = t; if (t) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); } } void PrimitiveRenderer::setLineWidth(float w) { if (w != current_line_width) { current_line_width = w; glLineWidth(w); } } void PrimitiveRenderer::bind(const canvas::TextureRef & texture) { int id = texture.getTextureId(); if (!id) { cerr << "trying to bind zero tex" << endl; assert(0); } else if (id != current_texture_2d) { current_texture_2d = id; glBindTexture(GL_TEXTURE_2D, id); } } void PrimitiveRenderer::bind(const VBO & vbo) { int a = vbo.getVertexArrayId(); if (!a) { cerr << "trying to bind zero vao" << endl; assert(0); } else if (a != current_vertex_array) { current_vertex_array = a; glBindVertexArray(a); // glBindBuffer(GL_ARRAY_BUFFER, vbo.getVertexBufferId()); // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo.getIndexBufferId()); } } void PrimitiveRenderer::use(const gpufw::shader_program & program) { int id = program.getProgramObjectId(); if (!id) { assert(0); } else if (id != current_program) { current_program = id; glUseProgram(id); } } void PrimitiveRenderer::clear(int clear_bits) { int gl_bits = 0; if (clear_bits & COLOR_BUFFER_BIT) { colorMask(true, true, true, true); gl_bits |= GL_COLOR_BUFFER_BIT; } if (clear_bits & DEPTH_BUFFER_BIT || clear_bits & DEPTH_STENCIL_BUFFER_BIT) { depthMask(true); gl_bits |= GL_DEPTH_BUFFER_BIT; } if (clear_bits & STENCIL_BUFFER_BIT || clear_bits & DEPTH_STENCIL_BUFFER_BIT) { stencilMask(0xff); gl_bits |= GL_STENCIL_BUFFER_BIT; } if (gl_bits) { glClear(gl_bits); } } void PrimitiveRenderer::colorMask(bool r, bool g, bool b, bool a) { if (r != current_red_mask || g != current_green_mask || b != current_blue_mask || a != current_alpha_mask) { current_red_mask = r; current_green_mask = g; current_blue_mask = b; current_alpha_mask = a; glColorMask( r ? GL_TRUE : GL_FALSE, g ? GL_TRUE : GL_FALSE, b ? GL_TRUE : GL_FALSE, a ? GL_TRUE : GL_FALSE ); } } void PrimitiveRenderer::setCompositionMode(CompositionMode mode) { if (mode != current_composition_mode) { current_composition_mode = mode; switch (mode) { case COPY: glBlendFunc(GL_ONE, GL_ZERO); break; case NORMAL: glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); break; case MULTIPLY: glBlendFunc(GL_ZERO, GL_SRC_COLOR); break; } } } void PrimitiveRenderer::viewport(unsigned int x, unsigned int y, unsigned int w, unsigned int h) { if (w != current_display_size.x || h != current_display_size.y) { current_display_size = glm::ivec2(w, h); cerr << "updating viewport\n"; glViewport(0, 0, (unsigned int)(w * display_scale), (unsigned int)(h * display_scale)); } } void PrimitiveRenderer::pushGroupMarker(const char * name) { #ifdef GL_ES glPushGroupMarkerEXT(0, name); #endif } void PrimitiveRenderer::popGroupMarker() { #ifdef GL_ES glPopGroupMarkerEXT(); #endif } void PrimitiveRenderer::invalidateFramebuffer(int bits) { int n = 0; GLenum v[4]; if (bits & STENCIL_BUFFER_BIT) { v[n++] = GL_STENCIL_ATTACHMENT; } if (bits & DEPTH_BUFFER_BIT) { v[n++] = GL_DEPTH_ATTACHMENT; } if (n) { if (is_es3) { glInvalidateFramebuffer(GL_FRAMEBUFFER, n, &v[0]); } else { #ifdef GL_ES // glBindFramebuffer(GL_FRAMEBUFFER, current_framebuffer); // glDiscardFramebufferEXT(GL_FRAMEBUFFER, n, &v[0]); #endif } } } <|endoftext|>
<commit_before>#include "inbuilt.h" #include <cstdio> #include <cstdlib> #include <cstring> static const char pushya[] = R"(:code (pushya) dex sta LSB,x sty MSB,x + rts ;code)"; static const char oneplus[] = R"(:code 1+ inc LSB,x bne + inc MSB,x + rts ;code)"; static const char oneminus[] = R"(:code 1- lda LSB, x bne + dec MSB, x + dec LSB, x rts ;code)"; static const char plus[] = R"(:code + lda LSB, x clc adc LSB + 1, x sta LSB + 1, x lda MSB, x adc MSB + 1, x sta MSB + 1, x inx rts ;code)"; static const char minus[] = R"(:code - lda LSB + 1, x sec sbc LSB, x sta LSB + 1, x lda MSB + 1, x sbc MSB, x sta MSB + 1, x inx rts ;code)"; static const char twoplus[] = R"(: 2+ 1+ 1+ ;)"; static const char cfetch[] = R"(:code c@ lda LSB,x sta + + 1 lda MSB,x sta + + 2 + lda $cafe sta LSB,x lda #0 sta MSB,x rts ;code)"; static const char cstore[] = R"(:code c! lda LSB,x sta + + 1 lda MSB,x sta + + 2 lda LSB+1,x + sta $1234 inx inx rts ;code)"; static const char swap[] = R"(:code swap ldy MSB, x lda MSB + 1, x sta MSB, x sty MSB + 1, x ldy LSB, x lda LSB + 1, x sta LSB, x sty LSB + 1, x rts ;code)"; static const char lit[] = R"(:code (lit) dex pla sta W pla sta W + 1 ldy #1 lda (W), y sta LSB, x iny lda (W), y sta MSB, x lda W clc adc #3 sta + + 1 lda W + 1 adc #0 sta + + 2 + jmp $1234 ;code)"; static const char rot[] = R"(:code rot ldy MSB+2, x lda MSB+1, x sta MSB+2, x lda MSB, x sta MSB+1, x sty MSB, x ldy LSB+2, x lda LSB+1, x sta LSB+2, x lda LSB, x sta LSB+1, x sty LSB, x rts ;code)"; static const char over[] = R"(:code over dex lda MSB + 2, x sta MSB, x lda LSB + 2, x sta LSB, x rts ;code)"; static const char qdup[] = R"(:code ?dup lda MSB,x ora LSB,x beq + dex lda MSB + 1, x sta MSB, x lda LSB + 1, x sta LSB, x + rts ;code)"; static const char dup[] = R"(:code dup dex lda MSB + 1, x sta MSB, x lda LSB + 1, x sta LSB, x rts ;code)"; static const char twodup[] = R"(: 2dup over over ;)"; static const char equal[] = R"(:code = ldy #0 lda LSB, x cmp LSB + 1, x bne + lda MSB, x cmp MSB + 1, x bne + dey + inx sty MSB, x sty LSB, x rts ;code)"; static const char zequal[] = R"(:code 0= ldy #0 lda MSB, x bne + lda LSB, x bne + dey + sty MSB, x sty LSB, x rts ;code)"; static const char and_[] = R"(:code and lda MSB, x and MSB + 1, x sta MSB + 1, x lda LSB, x and LSB + 1, x sta LSB + 1, x inx rts ;code)"; static const char store[] = R"(:code ! lda LSB, x sta W lda MSB, x sta W + 1 ldy #0 lda LSB+1, x sta (W), y iny lda MSB+1, x sta (W), y inx inx rts ;code)"; static const char fetch[] = R"(:code @ lda LSB,x sta W lda MSB,x sta W+1 ldy #0 lda (W),y sta LSB,x iny lda (W),y sta MSB,x rts ;code)"; static const char fill[] = R"(:code fill lda LSB, x tay lda LSB + 2, x sta .fdst lda MSB + 2, x sta .fdst + 1 lda LSB + 1, x eor #$ff sta W lda MSB + 1, x eor #$ff sta W + 1 inx inx inx - inc W bne + inc W + 1 bne + rts + .fdst = * + 1 sty $ffff ; overwrite ; advance inc .fdst bne - inc .fdst + 1 jmp -)"; static const char ifcmp[] = R"(:code (if) inx lda MSB-1,x ora LSB-1,x rts ;code)"; static const char mul[] = ": * m* drop ;"; static const char zless[] = R"(:code 0< lda MSB,x and #$80 beq + lda #$ff + sta MSB,x sta LSB,x rts ;code)"; static const char twomul[] = R"(:code 2* asl LSB,x rol MSB,x rts ;code)"; static const char depth[] = R"(:code depth txa eor #$ff tay iny dex sty LSB,x lda #0 sta MSB,x rts ;code)"; static const char do_[] = R"(:code (do) ; ( limit first -- ) pla sta W pla tay lda MSB+1,x pha lda LSB+1,x pha lda MSB,x pha lda LSB,x pha inx inx tya pha lda W pha rts ;code)"; static const char rat[] = R"(:code r@ txa tsx ldy $103,x sty W ldy $104,x tax dex sty MSB,x lda W sta LSB,x rts ;code)"; static const char cr[] = ": cr $d emit ;"; static const char emit[] = R"(:code emit lda LSB,x inx jmp $ffd2 ; PUTCHR ;code)"; static const char litstring[] = ": (litstring) r> 1+ dup 1+ swap c@ 2dup + 1- >r ;"; static const char tor[] = R"(:code >r pla sta W pla sta W+1 inc W bne + inc W+1 + lda MSB,x pha lda LSB,x pha inx jmp (W) ;code)"; static const char branch[] = R"(:code (branch) pla sta W pla sta W + 1 ldy #2 lda (W), y sta + + 2 dey lda (W), y sta + + 1 + jmp $1234 ;code)"; static const char loop[] = R"(:code (loop) stx W tsx inc 103,x bne + inc 104,x + lda 103,x cmp 105,x beq + - ; loop not finished, return ldx W rts + lda 104,x cmp 106,x bne - ; loop done pla clc adc #4 ; skip loop jmp in calling code sta W2 pla adc #0 sta W2+1 txa clc adc #6 ; pop loop counters tax txs ldx W jmp (W2) ;code)"; static const char negate[] = ": negate invert 1+ ;"; static const char invert[] = R"(:code invert lda MSB,x eor #$ff sta MSB,x lda LSB,x eor #$ff sta LSB,x rts ;code)"; // ----- const char* getDefinition(const char* wordName) { struct Pair { const char* name; const char* definition; }; static const Pair defs[] = { { "invert", invert }, { ">r", tor }, { "emit", emit }, { "cr", cr }, { "r@", rat }, { "depth", depth }, { "2*", twomul }, { "*", mul }, { "!", store }, { "+", plus }, { "-", minus }, { "0=", zequal }, { "0<", zless }, { "1+", oneplus }, { "1-", oneminus }, { "2+", twoplus }, { "2dup", twodup }, { "=", equal }, { "@", fetch }, { "and", and_ }, { "c!", cstore }, { "c@", cfetch }, { "dup", dup }, { "?dup", qdup }, { "fill", fill }, { "over", over }, { "rot", rot }, { "swap", swap }, { "negate", negate }, // internal { "(loop)", loop }, { "(do)", do_ }, { "(lit)", lit }, { "(litstring)", litstring }, { "(if)", ifcmp }, { "(pushya)", pushya }, { nullptr, nullptr } }; const Pair* it = defs; while (it->name) { if (!strcmp(it->name, wordName)) { return it->definition; } ++it; } fprintf(stderr, "Cannot find definition for '%s'\n", wordName); exit(1); return nullptr; } <commit_msg>added quit<commit_after>#include "inbuilt.h" #include <cstdio> #include <cstdlib> #include <cstring> static const char pushya[] = R"(:code (pushya) dex sta LSB,x sty MSB,x + rts ;code)"; static const char oneplus[] = R"(:code 1+ inc LSB,x bne + inc MSB,x + rts ;code)"; static const char oneminus[] = R"(:code 1- lda LSB, x bne + dec MSB, x + dec LSB, x rts ;code)"; static const char plus[] = R"(:code + lda LSB, x clc adc LSB + 1, x sta LSB + 1, x lda MSB, x adc MSB + 1, x sta MSB + 1, x inx rts ;code)"; static const char minus[] = R"(:code - lda LSB + 1, x sec sbc LSB, x sta LSB + 1, x lda MSB + 1, x sbc MSB, x sta MSB + 1, x inx rts ;code)"; static const char twoplus[] = R"(: 2+ 1+ 1+ ;)"; static const char cfetch[] = R"(:code c@ lda LSB,x sta + + 1 lda MSB,x sta + + 2 + lda $cafe sta LSB,x lda #0 sta MSB,x rts ;code)"; static const char cstore[] = R"(:code c! lda LSB,x sta + + 1 lda MSB,x sta + + 2 lda LSB+1,x + sta $1234 inx inx rts ;code)"; static const char swap[] = R"(:code swap ldy MSB, x lda MSB + 1, x sta MSB, x sty MSB + 1, x ldy LSB, x lda LSB + 1, x sta LSB, x sty LSB + 1, x rts ;code)"; static const char lit[] = R"(:code (lit) dex pla sta W pla sta W + 1 ldy #1 lda (W), y sta LSB, x iny lda (W), y sta MSB, x lda W clc adc #3 sta + + 1 lda W + 1 adc #0 sta + + 2 + jmp $1234 ;code)"; static const char rot[] = R"(:code rot ldy MSB+2, x lda MSB+1, x sta MSB+2, x lda MSB, x sta MSB+1, x sty MSB, x ldy LSB+2, x lda LSB+1, x sta LSB+2, x lda LSB, x sta LSB+1, x sty LSB, x rts ;code)"; static const char over[] = R"(:code over dex lda MSB + 2, x sta MSB, x lda LSB + 2, x sta LSB, x rts ;code)"; static const char qdup[] = R"(:code ?dup lda MSB,x ora LSB,x beq + dex lda MSB + 1, x sta MSB, x lda LSB + 1, x sta LSB, x + rts ;code)"; static const char dup[] = R"(:code dup dex lda MSB + 1, x sta MSB, x lda LSB + 1, x sta LSB, x rts ;code)"; static const char twodup[] = R"(: 2dup over over ;)"; static const char equal[] = R"(:code = ldy #0 lda LSB, x cmp LSB + 1, x bne + lda MSB, x cmp MSB + 1, x bne + dey + inx sty MSB, x sty LSB, x rts ;code)"; static const char zequal[] = R"(:code 0= ldy #0 lda MSB, x bne + lda LSB, x bne + dey + sty MSB, x sty LSB, x rts ;code)"; static const char and_[] = R"(:code and lda MSB, x and MSB + 1, x sta MSB + 1, x lda LSB, x and LSB + 1, x sta LSB + 1, x inx rts ;code)"; static const char store[] = R"(:code ! lda LSB, x sta W lda MSB, x sta W + 1 ldy #0 lda LSB+1, x sta (W), y iny lda MSB+1, x sta (W), y inx inx rts ;code)"; static const char fetch[] = R"(:code @ lda LSB,x sta W lda MSB,x sta W+1 ldy #0 lda (W),y sta LSB,x iny lda (W),y sta MSB,x rts ;code)"; static const char fill[] = R"(:code fill lda LSB, x tay lda LSB + 2, x sta .fdst lda MSB + 2, x sta .fdst + 1 lda LSB + 1, x eor #$ff sta W lda MSB + 1, x eor #$ff sta W + 1 inx inx inx - inc W bne + inc W + 1 bne + rts + .fdst = * + 1 sty $ffff ; overwrite ; advance inc .fdst bne - inc .fdst + 1 jmp -)"; static const char ifcmp[] = R"(:code (if) inx lda MSB-1,x ora LSB-1,x rts ;code)"; static const char mul[] = ": * m* drop ;"; static const char zless[] = R"(:code 0< lda MSB,x and #$80 beq + lda #$ff + sta MSB,x sta LSB,x rts ;code)"; static const char twomul[] = R"(:code 2* asl LSB,x rol MSB,x rts ;code)"; static const char depth[] = R"(:code depth txa eor #$ff tay iny dex sty LSB,x lda #0 sta MSB,x rts ;code)"; static const char do_[] = R"(:code (do) ; ( limit first -- ) pla sta W pla tay lda MSB+1,x pha lda LSB+1,x pha lda MSB,x pha lda LSB,x pha inx inx tya pha lda W pha rts ;code)"; static const char rat[] = R"(:code r@ txa tsx ldy $103,x sty W ldy $104,x tax dex sty MSB,x lda W sta LSB,x rts ;code)"; static const char cr[] = ": cr $d emit ;"; static const char emit[] = R"(:code emit lda LSB,x inx jmp $ffd2 ; PUTCHR ;code)"; static const char litstring[] = ": (litstring) r> 1+ dup 1+ swap c@ 2dup + 1- >r ;"; static const char tor[] = R"(:code >r pla sta W pla sta W+1 inc W bne + inc W+1 + lda MSB,x pha lda LSB,x pha inx jmp (W) ;code)"; static const char branch[] = R"(:code (branch) pla sta W pla sta W + 1 ldy #2 lda (W), y sta + + 2 dey lda (W), y sta + + 1 + jmp $1234 ;code)"; static const char loop[] = R"(:code (loop) stx W tsx inc 103,x bne + inc 104,x + lda 103,x cmp 105,x beq + - ; loop not finished, return ldx W rts + lda 104,x cmp 106,x bne - ; loop done pla clc adc #4 ; skip loop jmp in calling code sta W2 pla adc #0 sta W2+1 txa clc adc #6 ; pop loop counters tax txs ldx W jmp (W2) ;code)"; static const char negate[] = ": negate invert 1+ ;"; static const char invert[] = R"(:code invert lda MSB,x eor #$ff sta MSB,x lda LSB,x eor #$ff sta LSB,x rts ;code)"; static const char quit[] = R"(:code quit ldx #$ff txs rts ;code)"; // ----- const char* getDefinition(const char* wordName) { struct Pair { const char* name; const char* definition; }; static const Pair defs[] = { { "quit", quit }, { "invert", invert }, { ">r", tor }, { "emit", emit }, { "cr", cr }, { "r@", rat }, { "depth", depth }, { "2*", twomul }, { "*", mul }, { "!", store }, { "+", plus }, { "-", minus }, { "0=", zequal }, { "0<", zless }, { "1+", oneplus }, { "1-", oneminus }, { "2+", twoplus }, { "2dup", twodup }, { "=", equal }, { "@", fetch }, { "and", and_ }, { "c!", cstore }, { "c@", cfetch }, { "dup", dup }, { "?dup", qdup }, { "fill", fill }, { "over", over }, { "rot", rot }, { "swap", swap }, { "negate", negate }, // internal { "(loop)", loop }, { "(do)", do_ }, { "(lit)", lit }, { "(litstring)", litstring }, { "(if)", ifcmp }, { "(pushya)", pushya }, { nullptr, nullptr } }; const Pair* it = defs; while (it->name) { if (!strcmp(it->name, wordName)) { return it->definition; } ++it; } fprintf(stderr, "Cannot find definition for '%s'\n", wordName); exit(1); return nullptr; } <|endoftext|>
<commit_before>#include <turner/msturn> #include <turner/test> #include <catch2/generators/catch_generators.hpp> namespace { using namespace turner_test; TEST_CASE("msturn") { SECTION("method registry") { CHECK(turner::msturn::allocate == 0x0003); CHECK(turner::msturn::allocate_success == 0x0103); CHECK(turner::msturn::allocate_error == 0x0113); CHECK(turner::msturn::send_request == 0x0004); CHECK(turner::msturn::data_indication == 0x0115); CHECK(turner::msturn::set_active_destination == 0x0006); CHECK(turner::msturn::set_active_destination_success == 0x0106); CHECK(turner::msturn::set_active_destination_error == 0x0116); } SECTION("attribute registry") { CHECK(turner::msturn::mapped_address == 0x0001); CHECK(turner::msturn::username == 0x0006); CHECK(turner::msturn::message_integrity == 0x0008); CHECK(turner::msturn::error_code == 0x0009); CHECK(turner::msturn::unknown_attributes == 0x000a); CHECK(turner::msturn::lifetime == 0x000d); CHECK(turner::msturn::alternate_server == 0x000e); CHECK(turner::msturn::bandwidth == 0x0010); CHECK(turner::msturn::destination_address == 0x0011); CHECK(turner::msturn::remote_address == 0x0012); CHECK(turner::msturn::data == 0x0013); CHECK(turner::msturn::nonce == 0x0014); CHECK(turner::msturn::realm == 0x0015); CHECK(turner::msturn::requested_address_family == 0x0017); CHECK(turner::msturn::ms_version == 0x8008); CHECK(turner::msturn::xor_mapped_address == 0x8020); CHECK(turner::msturn::ms_alternate_host_name == 0x8032); CHECK(turner::msturn::app_id == 0x8037); CHECK(turner::msturn::secure_tag == 0x8039); CHECK(turner::msturn::ms_sequence_number == 0x8050); CHECK(turner::msturn::ms_service_quality == 0x8055); CHECK(turner::msturn::ms_alternate_mapped_address == 0x8090); CHECK(turner::msturn::multiplexed_session_id == 0x8095); } } } // namespace <commit_msg>Make Catch2 and MSVC play nice together<commit_after>#include <turner/msturn> #include <turner/test> #include <catch2/generators/catch_generators.hpp> namespace { using namespace turner_test; TEST_CASE("msturn") { SECTION("method registry") { CHECK(turner::msturn::allocate == 0x0003_u16); CHECK(turner::msturn::allocate_success == 0x0103_u16); CHECK(turner::msturn::allocate_error == 0x0113_u16); CHECK(turner::msturn::send_request == 0x0004_u16); CHECK(turner::msturn::data_indication == 0x0115_u16); CHECK(turner::msturn::set_active_destination == 0x0006_u16); CHECK(turner::msturn::set_active_destination_success == 0x0106_u16); CHECK(turner::msturn::set_active_destination_error == 0x0116_u16); } SECTION("attribute registry") { CHECK(turner::msturn::mapped_address == 0x0001_u16); CHECK(turner::msturn::username == 0x0006_u16); CHECK(turner::msturn::message_integrity == 0x0008_u16); CHECK(turner::msturn::error_code == 0x0009_u16); CHECK(turner::msturn::unknown_attributes == 0x000a_u16); CHECK(turner::msturn::lifetime == 0x000d_u16); CHECK(turner::msturn::alternate_server == 0x000e_u16); CHECK(turner::msturn::bandwidth == 0x0010_u16); CHECK(turner::msturn::destination_address == 0x0011_u16); CHECK(turner::msturn::remote_address == 0x0012_u16); CHECK(turner::msturn::data == 0x0013_u16); CHECK(turner::msturn::nonce == 0x0014_u16); CHECK(turner::msturn::realm == 0x0015_u16); CHECK(turner::msturn::requested_address_family == 0x0017_u16); CHECK(turner::msturn::ms_version == 0x8008_u16); CHECK(turner::msturn::xor_mapped_address == 0x8020_u16); CHECK(turner::msturn::ms_alternate_host_name == 0x8032_u16); CHECK(turner::msturn::app_id == 0x8037_u16); CHECK(turner::msturn::secure_tag == 0x8039_u16); CHECK(turner::msturn::ms_sequence_number == 0x8050_u16); CHECK(turner::msturn::ms_service_quality == 0x8055_u16); CHECK(turner::msturn::ms_alternate_mapped_address == 0x8090_u16); CHECK(turner::msturn::multiplexed_session_id == 0x8095_u16); } } } // namespace <|endoftext|>
<commit_before>/* Copyright (C) 2013,2018 Rodrigo Jose Hernandez Cordoba 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 <cstring> #include <cstdio> #include <cassert> #include "zlib.h" #include "aeongames/Package.h" #include "aeongames/CRC.h" namespace AeonGames { #define CHUNK 16384 /* Decompress from file source to memory dest until stream ends or EOF. read_inflated_data() returns Z_OK on success, Z_MEM_ERROR if memory could not be allocated for processing, Z_DATA_ERROR if the deflate data is invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and the version of the library linked do not match, or Z_ERRNO if there is an error reading or writing the files. */ static int read_inflated_data ( FILE* source, uint8_t* buffer, uint32_t buffer_size ) { int ret; z_stream strm; unsigned char in[CHUNK]; /* allocate inflate state */ strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; ret = inflateInit ( &strm ); if ( ret != Z_OK ) { return ret; } strm.avail_out = buffer_size; strm.next_out = buffer; /* decompress until deflate stream ends or end of file */ do { strm.avail_in = static_cast<uInt> ( fread ( in, 1, CHUNK, source ) ); if ( ferror ( source ) ) { ( void ) inflateEnd ( &strm ); return Z_ERRNO; } if ( strm.avail_in == 0 ) { break; } strm.next_in = in; ret = inflate ( &strm, Z_NO_FLUSH ); assert ( ret != Z_STREAM_ERROR ); /* state not clobbered */ switch ( ret ) { case Z_NEED_DICT: ret = Z_DATA_ERROR; /* and fall through */ case Z_DATA_ERROR: case Z_MEM_ERROR: ( void ) inflateEnd ( &strm ); return ret; } /* done when inflate() says it's done */ } while ( ret != Z_STREAM_END ); /* clean up and return */ ( void ) inflateEnd ( &strm ); return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR; } static int CompareDirectoryEntries ( const void * A, const void * B ) { const uint32_t a = *reinterpret_cast<const uint32_t*> ( A ); const PKGDirectoryEntry* b = reinterpret_cast<const PKGDirectoryEntry*> ( B ); if ( a > b->path ) { return 1; } else if ( a < b->path ) { return -1; } return 0; } Package::Package() : mHeader{}, mHandle{}, mDirectory{}, mStringTable{} { } Package::~Package() { Close(); } bool Package::Open ( const char* filename ) { Close(); if ( ( mHandle = fopen ( filename, "rb" ) ) == nullptr ) { //AEONGAMES_LOG_ERROR ( "Could not open file %s", filename ); return false; } fread ( &mHeader, sizeof ( PKGHeader ), 1, mHandle ); if ( strncmp ( mHeader.id, "AEONPKG\0", 8 ) != 0 ) { Close(); return false; } mDirectory.resize ( mHeader.file_count ); for ( uint32_t i = 0; i < mHeader.file_count; ++i ) { fread ( &mDirectory[i], sizeof ( PKGDirectoryEntry ), 1, mHandle ); } mStringTable.resize ( mHeader.file_size - mHeader.string_table_offset ); fseek ( mHandle, mHeader.string_table_offset, SEEK_SET ); fread ( mStringTable.data(), sizeof ( uint8_t ), mHeader.file_size - mHeader.string_table_offset, mHandle ); return true; } void Package::Close() { if ( mHandle != nullptr ) { fclose ( mHandle ); mHandle = nullptr; } mDirectory.clear(); mStringTable.clear(); memset ( &mHeader, 0, sizeof ( PKGHeader ) ); } uint32_t Package::GetFileCount() const { return mHeader.file_count; } uint32_t Package::GetFileSize ( uint32_t crc ) const { PKGDirectoryEntry* directory_entry = reinterpret_cast<PKGDirectoryEntry*> ( bsearch ( &crc, mDirectory.data(), mHeader.file_count, sizeof ( PKGDirectoryEntry ), CompareDirectoryEntries ) ); if ( directory_entry != nullptr ) { return directory_entry->uncompressed_size; } return 0; } const PKGDirectoryEntry* Package::GetFileByIndex ( uint32_t index ) const { return ( index < mHeader.file_count ) ? &mDirectory[index] : nullptr; } struct StringTableEntry { uint32_t CRC; /// String CRC uint32_t offset; /// String Offset }; static int CompareCRCs ( const void * A, const void * B ) { const uint32_t a = *reinterpret_cast<const uint32_t*> ( A ); const StringTableEntry* b = reinterpret_cast<const StringTableEntry*> ( B ); if ( a > b->CRC ) { return 1; } else if ( a < b->CRC ) { return -1; } return 0; } const char* Package::GetFilePath ( uint32_t crc ) const { StringTableEntry* entry = reinterpret_cast<StringTableEntry*> ( bsearch ( &crc, mStringTable.data() + sizeof ( uint32_t ), *reinterpret_cast<const uint32_t*> ( mStringTable.data() ), sizeof ( StringTableEntry ), CompareCRCs ) ); if ( entry != NULL ) { return reinterpret_cast<const char*> ( mStringTable.data() ) + entry->offset; } return nullptr; } const PKGDirectoryEntry* Package::ContainsFile ( uint32_t crc ) const { PKGDirectoryEntry* directory_entry = reinterpret_cast<PKGDirectoryEntry*> ( bsearch ( &crc, mDirectory.data(), mHeader.file_count, sizeof ( PKGDirectoryEntry ), CompareDirectoryEntries ) ); return directory_entry; } bool Package::LoadFile ( uint32_t crc, uint8_t* buffer, uint32_t buffer_size ) const { PKGDirectoryEntry* directory_entry = reinterpret_cast<PKGDirectoryEntry*> ( bsearch ( &crc, mDirectory.data(), mHeader.file_count, sizeof ( PKGDirectoryEntry ), CompareDirectoryEntries ) ); if ( directory_entry == nullptr ) { return false; } if ( directory_entry->uncompressed_size < buffer_size ) { //AEONGAMES_LOG_ERROR ( "Insuficient Buffer Size in %s line %i.", __FUNCTION__, __LINE__ ); return false; } if ( !fseek ( mHandle, directory_entry->offset, SEEK_SET ) ) { return false; } switch ( directory_entry->compression_type ) { case NONE: if ( fread ( buffer, buffer_size, 1, mHandle ) == 0 ) { //AEONGAMES_LOG_ERROR ( "fread Failed in %s line %i.", __FUNCTION__, __LINE__ ); return false; } break; case ZLIB: if ( read_inflated_data ( mHandle, buffer, buffer_size ) != Z_OK ) { //AEONGAMES_LOG_ERROR ( "fread Failed in %s line %i.", __FUNCTION__, __LINE__ ); return false; } break; default: //AEONGAMES_LOG_ERROR ( "Unrecognized compression type, or type not supported: %i", directory_entry->compression_type ); return false; } return true; } } <commit_msg>Linux Build Fix<commit_after>/* Copyright (C) 2013,2018 Rodrigo Jose Hernandez Cordoba 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 <cstring> #include <cstdio> #include <cstdlib> #include <cassert> #include "zlib.h" #include "aeongames/Package.h" #include "aeongames/CRC.h" namespace AeonGames { #define CHUNK 16384 /* Decompress from file source to memory dest until stream ends or EOF. read_inflated_data() returns Z_OK on success, Z_MEM_ERROR if memory could not be allocated for processing, Z_DATA_ERROR if the deflate data is invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and the version of the library linked do not match, or Z_ERRNO if there is an error reading or writing the files. */ static int read_inflated_data ( FILE* source, uint8_t* buffer, uint32_t buffer_size ) { int ret; z_stream strm; unsigned char in[CHUNK]; /* allocate inflate state */ strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; ret = inflateInit ( &strm ); if ( ret != Z_OK ) { return ret; } strm.avail_out = buffer_size; strm.next_out = buffer; /* decompress until deflate stream ends or end of file */ do { strm.avail_in = static_cast<uInt> ( fread ( in, 1, CHUNK, source ) ); if ( ferror ( source ) ) { ( void ) inflateEnd ( &strm ); return Z_ERRNO; } if ( strm.avail_in == 0 ) { break; } strm.next_in = in; ret = inflate ( &strm, Z_NO_FLUSH ); assert ( ret != Z_STREAM_ERROR ); /* state not clobbered */ switch ( ret ) { case Z_NEED_DICT: ret = Z_DATA_ERROR; /* and fall through */ case Z_DATA_ERROR: case Z_MEM_ERROR: ( void ) inflateEnd ( &strm ); return ret; } /* done when inflate() says it's done */ } while ( ret != Z_STREAM_END ); /* clean up and return */ ( void ) inflateEnd ( &strm ); return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR; } static int CompareDirectoryEntries ( const void * A, const void * B ) { const uint32_t a = *reinterpret_cast<const uint32_t*> ( A ); const PKGDirectoryEntry* b = reinterpret_cast<const PKGDirectoryEntry*> ( B ); if ( a > b->path ) { return 1; } else if ( a < b->path ) { return -1; } return 0; } Package::Package() : mHeader{}, mHandle{}, mDirectory{}, mStringTable{} { } Package::~Package() { Close(); } bool Package::Open ( const char* filename ) { Close(); if ( ( mHandle = fopen ( filename, "rb" ) ) == nullptr ) { //AEONGAMES_LOG_ERROR ( "Could not open file %s", filename ); return false; } fread ( &mHeader, sizeof ( PKGHeader ), 1, mHandle ); if ( strncmp ( mHeader.id, "AEONPKG\0", 8 ) != 0 ) { Close(); return false; } mDirectory.resize ( mHeader.file_count ); for ( uint32_t i = 0; i < mHeader.file_count; ++i ) { fread ( &mDirectory[i], sizeof ( PKGDirectoryEntry ), 1, mHandle ); } mStringTable.resize ( mHeader.file_size - mHeader.string_table_offset ); fseek ( mHandle, mHeader.string_table_offset, SEEK_SET ); fread ( mStringTable.data(), sizeof ( uint8_t ), mHeader.file_size - mHeader.string_table_offset, mHandle ); return true; } void Package::Close() { if ( mHandle != nullptr ) { fclose ( mHandle ); mHandle = nullptr; } mDirectory.clear(); mStringTable.clear(); memset ( &mHeader, 0, sizeof ( PKGHeader ) ); } uint32_t Package::GetFileCount() const { return mHeader.file_count; } uint32_t Package::GetFileSize ( uint32_t crc ) const { PKGDirectoryEntry* directory_entry = reinterpret_cast<PKGDirectoryEntry*> ( bsearch ( &crc, mDirectory.data(), mHeader.file_count, sizeof ( PKGDirectoryEntry ), CompareDirectoryEntries ) ); if ( directory_entry != nullptr ) { return directory_entry->uncompressed_size; } return 0; } const PKGDirectoryEntry* Package::GetFileByIndex ( uint32_t index ) const { return ( index < mHeader.file_count ) ? &mDirectory[index] : nullptr; } struct StringTableEntry { uint32_t CRC; /// String CRC uint32_t offset; /// String Offset }; static int CompareCRCs ( const void * A, const void * B ) { const uint32_t a = *reinterpret_cast<const uint32_t*> ( A ); const StringTableEntry* b = reinterpret_cast<const StringTableEntry*> ( B ); if ( a > b->CRC ) { return 1; } else if ( a < b->CRC ) { return -1; } return 0; } const char* Package::GetFilePath ( uint32_t crc ) const { StringTableEntry* entry = reinterpret_cast<StringTableEntry*> ( bsearch ( &crc, mStringTable.data() + sizeof ( uint32_t ), *reinterpret_cast<const uint32_t*> ( mStringTable.data() ), sizeof ( StringTableEntry ), CompareCRCs ) ); if ( entry != NULL ) { return reinterpret_cast<const char*> ( mStringTable.data() ) + entry->offset; } return nullptr; } const PKGDirectoryEntry* Package::ContainsFile ( uint32_t crc ) const { PKGDirectoryEntry* directory_entry = reinterpret_cast<PKGDirectoryEntry*> ( bsearch ( &crc, mDirectory.data(), mHeader.file_count, sizeof ( PKGDirectoryEntry ), CompareDirectoryEntries ) ); return directory_entry; } bool Package::LoadFile ( uint32_t crc, uint8_t* buffer, uint32_t buffer_size ) const { PKGDirectoryEntry* directory_entry = reinterpret_cast<PKGDirectoryEntry*> ( bsearch ( &crc, mDirectory.data(), mHeader.file_count, sizeof ( PKGDirectoryEntry ), CompareDirectoryEntries ) ); if ( directory_entry == nullptr ) { return false; } if ( directory_entry->uncompressed_size < buffer_size ) { //AEONGAMES_LOG_ERROR ( "Insuficient Buffer Size in %s line %i.", __FUNCTION__, __LINE__ ); return false; } if ( !fseek ( mHandle, directory_entry->offset, SEEK_SET ) ) { return false; } switch ( directory_entry->compression_type ) { case NONE: if ( fread ( buffer, buffer_size, 1, mHandle ) == 0 ) { //AEONGAMES_LOG_ERROR ( "fread Failed in %s line %i.", __FUNCTION__, __LINE__ ); return false; } break; case ZLIB: if ( read_inflated_data ( mHandle, buffer, buffer_size ) != Z_OK ) { //AEONGAMES_LOG_ERROR ( "fread Failed in %s line %i.", __FUNCTION__, __LINE__ ); return false; } break; default: //AEONGAMES_LOG_ERROR ( "Unrecognized compression type, or type not supported: %i", directory_entry->compression_type ); return false; } return true; } } <|endoftext|>
<commit_before>// Simple Chatterbox client written in C++ // Depends on boost 1.55 and MinGW. // // To build on Windows 64-bit systems, we used the excellent MinGW Distro // from nuwen.net. Build command is: // g++ -std=c++0x -Wall -o cbclient cbclient.cpp -lboost_thread -lboost_system -lws2_32 // // When building on Windows XP SP3, define NTDDI_VERSION=0x05010300. // The build command becomes: // g++ -std=c++0x -Wall -DNTDDI_VERSION=0x05010300 -o cbclient cbclient.cpp -lboost_thread -lboost_system -lws2_32 // // If you are not using the MinGW Distro from nuwen.net, you'll need to // build the Boost libraries yourself. This could possibly be a difficult // but worthy task. Be strong. // // Caution when building Boost 1.55 under MinGW on XP. You SHOULD convert the build.bat // from Unix line endings to DOS line endings and you MUST ensure that the TMP and // TEMP user variables do not point to directories names that have spaces in them. // // Usage: // cbclient <chatterbox-host> [<chatterbox-port>] // Default chatterbox-port is 20000 // #include <iostream> #include <string> #include <sstream> #include <array> #include <boost/thread.hpp> #include <boost/asio.hpp> using std::cout; using std::cin; using std::cerr; using std::endl; using std::string; using boost::asio::ip::tcp; bool get_cmdline_args(int argc, char* argv[], string &host, string &port); string socket_gets(tcp::socket& socket); void socket_puts(tcp::socket& socket, const string& msg); int main(int argc, char* argv[]) { string host, port; if(get_cmdline_args(argc, argv, host, port) == false) { cout << "Usage: cbclient <chatterbox-host> [<chatterbox-port>]"; return 1; } try { cout << "Connecting to chatterbox server at " << host << ':' << port << endl; boost::asio::io_service io_service; tcp::resolver resolver(io_service); tcp::resolver::query query(host, port); auto endpoint_iterator = resolver.resolve(query); tcp::socket socket(io_service); boost::asio::connect(socket, endpoint_iterator); // Read and display the chatterbox welcome message. cout << socket_gets(socket) << endl; // Let user enter an id string user_id; getline(cin, user_id); // Send the user ID socket_puts(socket, user_id); // Say goodbye socket_puts(socket, "bye"); } catch (std::exception& e) { cerr << e.what() << endl; } //boost::thread t; return 0; } string socket_gets(tcp::socket& socket) { std::array<char, 512> buf; boost::system::error_code error; size_t len = socket.read_some(boost::asio::buffer(buf), error); if(error) throw boost::system::system_error(error); std::stringstream ss; ss.write(buf.data(), len); return ss.str(); } void socket_puts(tcp::socket& socket, const string& msg) { // boost::system::error_code ignored_error; boost::asio::write(socket, boost::asio::buffer(msg) /*, ignored_error*/); } bool get_cmdline_args(int argc, char* argv[], string &host, string &port) { if(argc < 2 || argc > 3) { return false; } if(argc > 1) { host = argv[1]; } port = "20000"; if(argc > 2) { port = argv[2]; } return true; } <commit_msg>Add listen and send threads.<commit_after>// Simple Chatterbox client written in C++ // Depends on boost 1.55 and MinGW. // // To build on Windows 64-bit systems, we used the excellent MinGW Distro // from nuwen.net. Build command is: // g++ -std=c++0x -Wall -o cbclient cbclient.cpp -lboost_thread -lboost_system -lws2_32 // // When building on Windows XP SP3, define NTDDI_VERSION=0x05010300. // The build command becomes: // g++ -std=c++0x -Wall -DNTDDI_VERSION=0x05010300 -o cbclient cbclient.cpp -lboost_thread -lboost_system -lws2_32 // // If you are not using the MinGW Distro from nuwen.net, you'll need to // build the Boost libraries yourself. This could possibly be a difficult // but worthy task. Be strong. // // Caution when building Boost 1.55 under MinGW on XP. You SHOULD convert the build.bat // from Unix line endings to DOS line endings and you MUST ensure that the TMP and // TEMP user variables do not point to directory names that have spaces in them. // // Usage: // cbclient <chatterbox-host> [<chatterbox-port>] // Default chatterbox-port is 20000 // #include <iostream> #include <string> #include <sstream> #include <array> #include <boost/thread.hpp> #include <boost/asio.hpp> using std::ostream; using std::cout; using std::cin; using std::cerr; using std::endl; using std::string; using boost::asio::ip::tcp; bool get_cmdline_args(int argc, char* argv[], string &host, string &port); string socket_gets(tcp::socket& socket); void socket_puts(tcp::socket& socket, const string& msg); void do_listen(tcp::socket& socket); void do_talk(tcp::socket& socket); string chomp(const string& s); void put_to_stream(ostream& o, const string& s); // Ugh, I know, global variables, but this will change. We're experimenting // for now. bool done_chatting = false; boost::mutex done_chatting_mtx; boost::mutex output_mtx; bool get_done_chatting(); void set_done_chatting(); int main(int argc, char* argv[]) { string host, port; if(get_cmdline_args(argc, argv, host, port) == false) { cout << "Usage: cbclient <chatterbox-host> [<chatterbox-port>]"; return 1; } try { cout << "Connecting to chatterbox server at " << host << ':' << port << endl; boost::asio::io_service io_service; tcp::resolver resolver(io_service); tcp::resolver::query query(host, port); auto endpoint_iterator = resolver.resolve(query); tcp::socket socket(io_service); boost::asio::connect(socket, endpoint_iterator); // Read and display the chatterbox welcome message. cout << socket_gets(socket) << endl; // Let user enter an id string user_id; getline(cin, user_id); user_id += '\n'; // Send the user ID socket_puts(socket, user_id); cout << done_chatting << endl; boost::thread listen_thread(do_listen, boost::ref(socket)); boost::thread talk_thread(do_talk, boost::ref(socket)); listen_thread.join(); talk_thread.join(); } catch (std::exception& e) { cerr << e.what() << endl; } return 0; } void do_listen(tcp::socket& socket) { cout << "In do_listen()" << endl; while(!get_done_chatting()) { string msg_received = socket_gets(socket); cout << '<' << chomp(msg_received) << '>' << endl; if(msg_received == "bye") { set_done_chatting(); } } } void do_talk(tcp::socket& socket) { cout << "In do_talk()" << endl; while(!get_done_chatting()) { string msg_to_send; getline(cin, msg_to_send); msg_to_send += '\n'; socket_puts(socket, msg_to_send); if(chomp(msg_to_send) == "bye") { set_done_chatting(); } } } void put_to_stream(ostream& o, const string& s) { boost::lock_guard<boost::mutex> guard(output_mtx); o << s; } string chomp(const string& s) { const std::string whitespaces (" \t\f\v\n\r"); string chomped = s; std::size_t found = chomped.find_last_not_of(whitespaces); if (found != std::string::npos) chomped.erase(found+1); else chomped.clear(); return chomped; } bool get_done_chatting() { boost::lock_guard<boost::mutex> guard(done_chatting_mtx); return done_chatting; } void set_done_chatting() { boost::lock_guard<boost::mutex> guard(done_chatting_mtx); done_chatting = true; } string socket_gets(tcp::socket& socket) { std::array<char, 512> buf; boost::system::error_code error; size_t len = socket.read_some(boost::asio::buffer(buf), error); if(error) throw boost::system::system_error(error); std::stringstream ss; ss.write(buf.data(), len); return ss.str(); } void socket_puts(tcp::socket& socket, const string& msg) { // boost::system::error_code ignored_error; boost::asio::write(socket, boost::asio::buffer(msg) /*, ignored_error*/); } bool get_cmdline_args(int argc, char* argv[], string &host, string &port) { if(argc < 2 || argc > 3) { return false; } if(argc > 1) { host = argv[1]; } port = "20000"; if(argc > 2) { port = argv[2]; } return true; } <|endoftext|>
<commit_before>/* * hdfs_wfx.cpp file written and maintained by Calin Cocan * Created on: May 15, 2015 * * Double Commander * ------------------------------------------------------------------------- * WFX plugin for working with HDFS * * Based on: * GVFS plugin for Double Commander * Copyright (C) 2009-2010 Koblov Alexander ([email protected]) * * and * * GVFS plugin for Tux Commander * Copyright (C) 2008-2009 Tomas Bzatek <[email protected]>* * * * This work is free: you can redistribute it and/or modify it under the terms of Apache License Version 2.0 * * 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 License for more details. * You should have received a copy of the License along with this program. If not, see <http://choosealicense.com/licenses/apache-2.0/>. ********************************************************************************************************************* */ #include "wfxplugin.h" #include <stddef.h> #include <string.h> #include "JVMState.h" #include "gendef.h" #include "Logger.h" #include "Utilities.h" #include "FileEnumerator.h" #include "HDFSAccessor.h" #include "ProgressInfo.h" HANDLE INVALID_HANDLE = (HANDLE) -1; tProgressProc gProgressProc; tRequestProc gRequestProc; int gPluginNo; char logPath[MAX_PATH]; size_t pathSize = MAX_PATH; int FsInit(int PluginNr, tProgressProc pProgressProc, tLogProc pLogProc, tRequestProc pRequestProc) { gProgressProc = pProgressProc; gRequestProc = pRequestProc; gPluginNo = PluginNr; #ifdef HDFS_WFX_DEBUG Logger::getInstance()->init(true, true, pLogProc, PluginNr); #else Logger::getInstance()->init(true, false, pLogProc, PluginNr); #endif LOGGING("FSInit"); char javaLauncherPath[MAX_PATH]; size_t pathSize = MAX_PATH; // if (pRequestProc != NULL) // { // char returnedText[100]; // strcpy(returnedText, "ReturnedTText"); // BOOL rv = pRequestProc(PluginNr, 3, "CustomTitle", "CustomText", returnedText, 100); // LOGGING("requestProc val %d, message %s", rv, returnedText); // } JVMState::instance()->initialize(Utilities::getJavaLauncherPath(javaLauncherPath, &pathSize)); int initialized = HDFSAccessor::instance()->initialize(); LOGGING("HDFSAccesstor initialization done %d", initialized); return 0; } HANDLE FsFindFirst(char* Path, WIN32_FIND_DATAA *FindData) { LOGGING("FsFindFirst on path %s", Path); memset(FindData, 0, sizeof(WIN32_FIND_DATAA)); FileEnumerator* fEnum = HDFSAccessor::instance()->getFolderContent(Path); HANDLE handle = INVALID_HANDLE; if (fEnum != NULL) { if (fEnum->getNext(FindData)) { handle = fEnum; } else { delete fEnum; } } return handle; } BOOL FsFindNext(HANDLE Hdl, WIN32_FIND_DATAA *FindData) { LOGGING("FsFindNext"); memset(FindData, 0, sizeof(WIN32_FIND_DATAA)); FileEnumerator* fEnum = (FileEnumerator*) Hdl; bool retVal = fEnum->getNext(FindData); return retVal; } int FsFindClose(HANDLE Hdl) { LOGGING("FsFindClose"); if (Hdl != NULL && Hdl != INVALID_HANDLE) { FileEnumerator* fEnum = (FileEnumerator*) Hdl; delete fEnum; Hdl = NULL; } return FS_FILE_OK; } BOOL FsMkDir(char* Path) { LOGGING("FsMkDir %s", Path); return HDFSAccessor::instance()->mkdir(Path); } BOOL FsRemoveDir(char* RemoteName) { LOGGING("FsRemoveDir %s", RemoteName); return HDFSAccessor::instance()->deletePath(RemoteName); } int FsRenMovFile(char* OldName, char* NewName, BOOL Move, BOOL OverWrite, RemoteInfoStruct* ri) { LOGGING("FsRenMovFile oldName %s -> newName %s - Move: %d - Overwrite: %d", OldName, NewName, Move, OverWrite); bool success = false; if (Move) { success = HDFSAccessor::instance()->rename(OldName, NewName); } else { success = HDFSAccessor::instance()->copy(OldName, NewName); } return success ? FS_FILE_OK : FS_FILE_NOTFOUND; } int FsGetFile(char* RemoteName, char* LocalName, int CopyFlags, RemoteInfoStruct* ri) { LOGGING("FsGetFile from %s to %s wiht copy flags %d", RemoteName, LocalName, CopyFlags); ProgressInfo* progressInfo = new ProgressInfo(RemoteName, LocalName, gProgressProc, gPluginNo); bool success = HDFSAccessor::instance()->getFile(RemoteName, LocalName, progressInfo); delete progressInfo; return success ? FS_FILE_OK : FS_FILE_READERROR; //FS_FILE_READERROR, FS_FILE_USERABORT, FS_FILE_NOTFOUND, FS_FILE_NOTSUPPORTED } int FsPutFile(char* LocalName, char* RemoteName, int CopyFlags) { LOGGING("FsPutFile Local path %s in HDFS path %s with flags %d", LocalName, RemoteName, CopyFlags); ProgressInfo* progressInfo = new ProgressInfo(LocalName, RemoteName, gProgressProc, gPluginNo); bool success = HDFSAccessor::instance()->putFile(LocalName, RemoteName, true, progressInfo); delete progressInfo; return success ? FS_FILE_OK : FS_FILE_WRITEERROR; } int FsExecuteFile(HWND MainWin, char* RemoteName, char* Verb) { LOGGING("FsExecuteFile %s verb %s", RemoteName, Verb); return -1; } BOOL FsDeleteFile(char* RemoteName) { LOGGING("FsDeleteFile %s", RemoteName); return HDFSAccessor::instance()->deletePath(RemoteName); return 0; } BOOL FsSetTime(char* RemoteName, FILETIME *CreationTime, FILETIME *LastAccessTime, FILETIME *LastWriteTime) { LOGGING("FsSetTime %s", RemoteName); return 0; } BOOL FsDisconnect(char *DisconnectRoot) { LOGGING("FsDisconnect root %s", DisconnectRoot); JVMState::instance()->detach(); return 0; } void FsSetDefaultParams(FsDefaultParamStruct* dps) { LOGGING("FsSetDefaultParams %s version %d:%d size %d", dps->DefaultIniName, dps->PluginInterfaceVersionHi, dps->PluginInterfaceVersionLow, dps->size); } void FsGetDefRootName(char* DefRootName, int maxlen) { #ifdef HDFS_WFX_DEBUG Logger::getInstance()->init(true, true); #else Logger::getInstance()->init(true, false); #endif LOGGING("FsGetDefRootName"); strncpy(DefRootName, "HDFS", maxlen); } <commit_msg>temporary remove progress<commit_after>/* * hdfs_wfx.cpp file written and maintained by Calin Cocan * Created on: May 15, 2015 * * Double Commander * ------------------------------------------------------------------------- * WFX plugin for working with HDFS * * Based on: * GVFS plugin for Double Commander * Copyright (C) 2009-2010 Koblov Alexander ([email protected]) * * and * * GVFS plugin for Tux Commander * Copyright (C) 2008-2009 Tomas Bzatek <[email protected]>* * * * This work is free: you can redistribute it and/or modify it under the terms of Apache License Version 2.0 * * 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 License for more details. * You should have received a copy of the License along with this program. If not, see <http://choosealicense.com/licenses/apache-2.0/>. ********************************************************************************************************************* */ #include "wfxplugin.h" #include <stddef.h> #include <string.h> #include "JVMState.h" #include "gendef.h" #include "Logger.h" #include "Utilities.h" #include "FileEnumerator.h" #include "HDFSAccessor.h" #include "ProgressInfo.h" HANDLE INVALID_HANDLE = (HANDLE) -1; tProgressProc gProgressProc; tRequestProc gRequestProc; int gPluginNo; char logPath[MAX_PATH]; size_t pathSize = MAX_PATH; int FsInit(int PluginNr, tProgressProc pProgressProc, tLogProc pLogProc, tRequestProc pRequestProc) { gProgressProc = pProgressProc; gRequestProc = pRequestProc; gPluginNo = PluginNr; #ifdef HDFS_WFX_DEBUG Logger::getInstance()->init(true, true, pLogProc, PluginNr); #else Logger::getInstance()->init(true, false, pLogProc, PluginNr); #endif LOGGING("FSInit"); char javaLauncherPath[MAX_PATH]; size_t pathSize = MAX_PATH; // if (pRequestProc != NULL) // { // char returnedText[100]; // strcpy(returnedText, "ReturnedTText"); // BOOL rv = pRequestProc(PluginNr, 3, "CustomTitle", "CustomText", returnedText, 100); // LOGGING("requestProc val %d, message %s", rv, returnedText); // } JVMState::instance()->initialize(Utilities::getJavaLauncherPath(javaLauncherPath, &pathSize)); int initialized = HDFSAccessor::instance()->initialize(); LOGGING("HDFSAccesstor initialization done %d", initialized); return 0; } HANDLE FsFindFirst(char* Path, WIN32_FIND_DATAA *FindData) { LOGGING("FsFindFirst on path %s", Path); memset(FindData, 0, sizeof(WIN32_FIND_DATAA)); FileEnumerator* fEnum = HDFSAccessor::instance()->getFolderContent(Path); HANDLE handle = INVALID_HANDLE; if (fEnum != NULL) { if (fEnum->getNext(FindData)) { handle = fEnum; } else { delete fEnum; } } return handle; } BOOL FsFindNext(HANDLE Hdl, WIN32_FIND_DATAA *FindData) { LOGGING("FsFindNext"); memset(FindData, 0, sizeof(WIN32_FIND_DATAA)); FileEnumerator* fEnum = (FileEnumerator*) Hdl; bool retVal = fEnum->getNext(FindData); return retVal; } int FsFindClose(HANDLE Hdl) { LOGGING("FsFindClose"); if (Hdl != NULL && Hdl != INVALID_HANDLE) { FileEnumerator* fEnum = (FileEnumerator*) Hdl; delete fEnum; Hdl = NULL; } return FS_FILE_OK; } BOOL FsMkDir(char* Path) { LOGGING("FsMkDir %s", Path); return HDFSAccessor::instance()->mkdir(Path); } BOOL FsRemoveDir(char* RemoteName) { LOGGING("FsRemoveDir %s", RemoteName); return HDFSAccessor::instance()->deletePath(RemoteName); } int FsRenMovFile(char* OldName, char* NewName, BOOL Move, BOOL OverWrite, RemoteInfoStruct* ri) { LOGGING("FsRenMovFile oldName %s -> newName %s - Move: %d - Overwrite: %d", OldName, NewName, Move, OverWrite); bool success = false; if (Move) { success = HDFSAccessor::instance()->rename(OldName, NewName); } else { success = HDFSAccessor::instance()->copy(OldName, NewName); } return success ? FS_FILE_OK : FS_FILE_NOTFOUND; } int FsGetFile(char* RemoteName, char* LocalName, int CopyFlags, RemoteInfoStruct* ri) { LOGGING("FsGetFile from %s to %s wiht copy flags %d", RemoteName, LocalName, CopyFlags); ProgressInfo* progressInfo = NULL;//new ProgressInfo(RemoteName, LocalName, gProgressProc, gPluginNo); bool success = HDFSAccessor::instance()->getFile(RemoteName, LocalName, progressInfo); delete progressInfo; return success ? FS_FILE_OK : FS_FILE_READERROR; //FS_FILE_READERROR, FS_FILE_USERABORT, FS_FILE_NOTFOUND, FS_FILE_NOTSUPPORTED } int FsPutFile(char* LocalName, char* RemoteName, int CopyFlags) { LOGGING("FsPutFile Local path %s in HDFS path %s with flags %d", LocalName, RemoteName, CopyFlags); ProgressInfo* progressInfo = NULL;//new ProgressInfo(LocalName, RemoteName, gProgressProc, gPluginNo); bool success = HDFSAccessor::instance()->putFile(LocalName, RemoteName, true, progressInfo); delete progressInfo; return success ? FS_FILE_OK : FS_FILE_WRITEERROR; } int FsExecuteFile(HWND MainWin, char* RemoteName, char* Verb) { LOGGING("FsExecuteFile %s verb %s", RemoteName, Verb); return -1; } BOOL FsDeleteFile(char* RemoteName) { LOGGING("FsDeleteFile %s", RemoteName); return HDFSAccessor::instance()->deletePath(RemoteName); return 0; } BOOL FsSetTime(char* RemoteName, FILETIME *CreationTime, FILETIME *LastAccessTime, FILETIME *LastWriteTime) { LOGGING("FsSetTime %s", RemoteName); return 0; } BOOL FsDisconnect(char *DisconnectRoot) { LOGGING("FsDisconnect root %s", DisconnectRoot); JVMState::instance()->detach(); return 0; } void FsSetDefaultParams(FsDefaultParamStruct* dps) { LOGGING("FsSetDefaultParams %s version %d:%d size %d", dps->DefaultIniName, dps->PluginInterfaceVersionHi, dps->PluginInterfaceVersionLow, dps->size); } void FsGetDefRootName(char* DefRootName, int maxlen) { #ifdef HDFS_WFX_DEBUG Logger::getInstance()->init(true, true); #else Logger::getInstance()->init(true, false); #endif LOGGING("FsGetDefRootName"); strncpy(DefRootName, "HDFS", maxlen); } <|endoftext|>
<commit_before>/* Copyright (C) 2016 iNuron NV This file is part of Open vStorage Open Source Edition (OSE), as available from http://www.openvstorage.org and http://www.openvstorage.com. This file is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License v3 (GNU AGPLv3) as published by the Free Software Foundation, in version 3 as it comes in the <LICENSE.txt> file of the Open vStorage OSE distribution. Open vStorage is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #include "manifest_cache.h" namespace alba { namespace proxy_client { ManifestCache &ManifestCache::getInstance() { static ManifestCache instance; return instance; } static size_t _manifest_cache_capacity = 10000; void ManifestCache::set_capacity(size_t capacity) { _manifest_cache_capacity = capacity; } void ManifestCache::add(std::string namespace_, std::string object_name, std::shared_ptr<Manifest> mfp) { ALBA_LOG(DEBUG, "ManifestCache::add"); std::shared_ptr<manifest_cache> mcp = nullptr; std::shared_ptr<std::mutex> mp = nullptr; { std::lock_guard<std::mutex> lock(_level1_mutex); auto it1 = _level1.find(namespace_); if (it1 == _level1.end()) { ALBA_LOG(INFO, "ManifestCache::add namespace:'" << namespace_ << "' : new manifest cache"); std::shared_ptr<manifest_cache> mc(new manifest_cache); std::shared_ptr<std::mutex> mm(new std::mutex); auto p = std::make_pair(mc, mm); _level1[namespace_] = std::move(p); it1 = _level1.find(namespace_); } else { ALBA_LOG(DEBUG, "ManifestCache::add namespace:'" << namespace_ << "' : existing manifest cache"); } const auto &v = it1->second; mcp = v.first; mp = v.second; } manifest_cache &manifest_cache = *mcp; std::mutex &m = *mp; { std::lock_guard<std::mutex> lock(m); auto it2 = manifest_cache.find(object_name); if (it2 != manifest_cache.end()) { manifest_cache.erase(it2); } if (manifest_cache.size() > _manifest_cache_capacity) { auto it_victim = manifest_cache.begin(); auto victim = it_victim->first; using namespace alba::stuff; ALBA_LOG(DEBUG, "cache '" << namespace_ << "' full(" << _manifest_cache_capacity << "), evicting victim: " << victim); manifest_cache.erase(it_victim); } manifest_cache[object_name] = std::move(mfp); } } std::shared_ptr<Manifest> ManifestCache::find(const std::string &namespace_, const std::string &object_name) { std::pair<std::shared_ptr<manifest_cache>, std::shared_ptr<std::mutex>> vp; { std::lock_guard<std::mutex> g(_level1_mutex); auto it = _level1.find(namespace_); if (it == _level1.end()) { return nullptr; } else { vp = it->second; } } auto &map = *vp.first; auto &mm = *vp.second; { std::lock_guard<std::mutex> g(mm); const auto &map_it = map.find(object_name); if (map_it == map.end()) { return nullptr; } else { return map_it->second; } } } void ManifestCache::invalidate_namespace(const std::string &namespace_) { ALBA_LOG(DEBUG, "ManifestCache::invalidate_namespace(" << namespace_ << ")"); std::lock_guard<std::mutex> g(_level1_mutex); auto it = _level1.find(namespace_); if (it != _level1.end()) { _level1.erase(it); } } } } <commit_msg>pick random victim<commit_after>/* Copyright (C) 2016 iNuron NV This file is part of Open vStorage Open Source Edition (OSE), as available from http://www.openvstorage.org and http://www.openvstorage.com. This file is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License v3 (GNU AGPLv3) as published by the Free Software Foundation, in version 3 as it comes in the <LICENSE.txt> file of the Open vStorage OSE distribution. Open vStorage is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #include "manifest_cache.h" namespace alba { namespace proxy_client { ManifestCache &ManifestCache::getInstance() { static ManifestCache instance; return instance; } static size_t _manifest_cache_capacity = 10000; void ManifestCache::set_capacity(size_t capacity) { _manifest_cache_capacity = capacity; } void ManifestCache::add(std::string namespace_, std::string object_name, std::shared_ptr<Manifest> mfp) { ALBA_LOG(DEBUG, "ManifestCache::add"); std::shared_ptr<manifest_cache> mcp = nullptr; std::shared_ptr<std::mutex> mp = nullptr; { std::lock_guard<std::mutex> lock(_level1_mutex); auto it1 = _level1.find(namespace_); if (it1 == _level1.end()) { ALBA_LOG(INFO, "ManifestCache::add namespace:'" << namespace_ << "' : new manifest cache"); std::shared_ptr<manifest_cache> mc(new manifest_cache); std::shared_ptr<std::mutex> mm(new std::mutex); auto p = std::make_pair(mc, mm); _level1[namespace_] = std::move(p); it1 = _level1.find(namespace_); } else { ALBA_LOG(DEBUG, "ManifestCache::add namespace:'" << namespace_ << "' : existing manifest cache"); } const auto &v = it1->second; mcp = v.first; mp = v.second; } manifest_cache &manifest_cache = *mcp; std::mutex &m = *mp; { std::lock_guard<std::mutex> lock(m); auto it2 = manifest_cache.find(object_name); if (it2 != manifest_cache.end()) { manifest_cache.erase(it2); } if (manifest_cache.size() > _manifest_cache_capacity) { auto it_victim = manifest_cache.begin(); int size = manifest_cache.size(); if (size > 0) { std::advance(it_victim, rand() % size); // O(size) :( } auto victim = it_victim->first; using namespace alba::stuff; ALBA_LOG(DEBUG, "cache '" << namespace_ << "' full(" << _manifest_cache_capacity << "), evicting victim: " << victim); manifest_cache.erase(it_victim); } manifest_cache[object_name] = std::move(mfp); } } std::shared_ptr<Manifest> ManifestCache::find(const std::string &namespace_, const std::string &object_name) { std::pair<std::shared_ptr<manifest_cache>, std::shared_ptr<std::mutex>> vp; { std::lock_guard<std::mutex> g(_level1_mutex); auto it = _level1.find(namespace_); if (it == _level1.end()) { return nullptr; } else { vp = it->second; } } auto &map = *vp.first; auto &mm = *vp.second; { std::lock_guard<std::mutex> g(mm); const auto &map_it = map.find(object_name); if (map_it == map.end()) { return nullptr; } else { return map_it->second; } } } void ManifestCache::invalidate_namespace(const std::string &namespace_) { ALBA_LOG(DEBUG, "ManifestCache::invalidate_namespace(" << namespace_ << ")"); std::lock_guard<std::mutex> g(_level1_mutex); auto it = _level1.find(namespace_); if (it != _level1.end()) { _level1.erase(it); } } } } <|endoftext|>
<commit_before>/******************************************************************************\ * File: test.cpp * Purpose: Implementation for wxextension cpp unit testing * Author: Anton van Wezenbeek * RCS-ID: $Id$ * Created: za 17 jan 2009 11:51:20 CET * * Copyright (c) 2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <TestCaller.h> #include "test.h" void wxExAppTestFixture::setUp() { m_Grid = new wxExGrid(wxTheApp->GetTopWindow()); m_ListView = new wxExListView(wxTheApp->GetTopWindow()); m_Notebook = new wxExNotebook(wxTheApp->GetTopWindow(), NULL); m_STC = new wxExSTC(wxTheApp->GetTopWindow(), wxExFileName("test.h")); m_STCShell = new wxExSTCShell(wxTheApp->GetTopWindow()); m_SVN = new wxExSVN(SVN_STAT, "test.h"); } void wxExAppTestFixture::testConstructors() { } void wxExAppTestFixture::testMethods() { // test wxExApp CPPUNIT_ASSERT(wxExApp::GetConfig() != NULL); CPPUNIT_ASSERT(wxExApp::GetLexers() != NULL); CPPUNIT_ASSERT(wxExApp::GetPrinter() != NULL); CPPUNIT_ASSERT(!wxExTool::GetToolInfo().empty()); // test wxExGrid CPPUNIT_ASSERT(m_Grid->CreateGrid(5, 5)); m_Grid->SelectAll(); m_Grid->SetGridCellValue(wxGridCellCoords(0, 0), "test"); CPPUNIT_ASSERT(m_Grid->GetCellValue(0, 0) == "test"); m_Grid->SetCellsValue(wxGridCellCoords(0, 0), "test1\ttest2\ntest3\ttest4\n"); CPPUNIT_ASSERT(m_Grid->GetCellValue(0, 0) == "test1"); // test wxExListView m_ListView->SetSingleStyle(wxLC_REPORT); // wxLC_ICON); m_ListView->InsertColumn("String", wxExColumn::COL_STRING); m_ListView->InsertColumn("Number", wxExColumn::COL_INT); CPPUNIT_ASSERT(m_ListView->FindColumn("String") == 0); CPPUNIT_ASSERT(m_ListView->FindColumn("Number") == 1); // test wxExNotebook (parent should not be NULL) wxWindow* page1 = new wxWindow(wxTheApp->GetTopWindow(), wxID_ANY); wxWindow* page2 = new wxWindow(wxTheApp->GetTopWindow(), wxID_ANY); CPPUNIT_ASSERT(m_Notebook->AddPage(page1, "key1") != NULL); CPPUNIT_ASSERT(m_Notebook->AddPage(page2, "key2") != NULL); CPPUNIT_ASSERT(m_Notebook->AddPage(page1, "key1") == NULL); CPPUNIT_ASSERT(m_Notebook->GetKeyByPage(page1) == "key1"); CPPUNIT_ASSERT(m_Notebook->GetPageByKey("key1") == page1); CPPUNIT_ASSERT(m_Notebook->SetPageText("key1", "keyx", "hello")); CPPUNIT_ASSERT(m_Notebook->GetPageByKey("keyx") == page1); CPPUNIT_ASSERT(m_Notebook->DeletePage("keyx")); CPPUNIT_ASSERT(m_Notebook->GetPageByKey("keyx") == NULL); // test wxExSTC CPPUNIT_ASSERT(m_STC->GetFileName().GetFullName() == "test.h"); // do the same test as with wxExFile in base for a binary file CPPUNIT_ASSERT(m_STC->Open(wxExFileName("../base/test.bin"))); const wxCharBuffer& buffer = m_STC->GetTextRaw(); wxLogMessage(buffer.data()); CPPUNIT_ASSERT(buffer.length() == 40); // test wxExSTCShell m_STCShell->Prompt("test1"); m_STCShell->Prompt("test2"); m_STCShell->Prompt("test3"); m_STCShell->Prompt("test4"); // Prompting does not add a command to history... // TODO: Make a better test. CPPUNIT_ASSERT(!m_STCShell->GetHistory().Contains("test4")); // test wxExSVN CPPUNIT_ASSERT(m_SVN->Execute(false) == 0); // do not use a dialog // The output depends on the svn stat, of course, // so do not assert on it. m_SVN->GetOutput(); // test various wxEx methods that need the app const wxString header = wxExHeader(wxExFileName("test.h"), m_Config, "hello test"); CPPUNIT_ASSERT(header.Contains("hello test")); // test util CPPUNIT_ASSERT(wxExClipboardAdd("test")); CPPUNIT_ASSERT(wxExClipboardGet() == "test"); CPPUNIT_ASSERT(wxExGetNumberOfLines("test\ntest\n") == 3); CPPUNIT_ASSERT(wxExGetLineNumberFromText("test on line: 1200") == 1200); CPPUNIT_ASSERT(wxExLog("hello from wxextension test")); CPPUNIT_ASSERT(!wxExMatchesOneOf(wxFileName("test.txt"), "*.cpp")); CPPUNIT_ASSERT(wxExMatchesOneOf(wxFileName("test.txt"), "*.cpp;*.txt")); CPPUNIT_ASSERT(wxExSkipWhiteSpace("t es t") == "t es t"); } void wxExAppTestFixture::tearDown() { } wxExTestSuite::wxExTestSuite() : CppUnit::TestSuite("wxextension test suite") { addTest(new CppUnit::TestCaller<wxExAppTestFixture>( "testConstructors", &wxExAppTestFixture::testConstructors)); addTest(new CppUnit::TestCaller<wxExAppTestFixture>( "testMethods", &wxExAppTestFixture::testMethods)); } <commit_msg>fixed compile error, but test still not ok, it does not return<commit_after>/******************************************************************************\ * File: test.cpp * Purpose: Implementation for wxextension cpp unit testing * Author: Anton van Wezenbeek * RCS-ID: $Id$ * Created: za 17 jan 2009 11:51:20 CET * * Copyright (c) 2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <TestCaller.h> #include "test.h" void wxExAppTestFixture::setUp() { m_Grid = new wxExGrid(wxTheApp->GetTopWindow()); m_ListView = new wxExListView(wxTheApp->GetTopWindow()); m_Notebook = new wxExNotebook(wxTheApp->GetTopWindow(), NULL); m_STC = new wxExSTC(wxTheApp->GetTopWindow(), wxExFileName("test.h")); m_STCShell = new wxExSTCShell(wxTheApp->GetTopWindow()); m_SVN = new wxExSVN(SVN_STAT, "test.h"); } void wxExAppTestFixture::testConstructors() { } void wxExAppTestFixture::testMethods() { // test wxExApp CPPUNIT_ASSERT(wxExApp::GetConfig() != NULL); CPPUNIT_ASSERT(wxExApp::GetLexers() != NULL); CPPUNIT_ASSERT(wxExApp::GetPrinter() != NULL); CPPUNIT_ASSERT(!wxExTool::GetToolInfo().empty()); // test wxExGrid CPPUNIT_ASSERT(m_Grid->CreateGrid(5, 5)); m_Grid->SelectAll(); m_Grid->SetGridCellValue(wxGridCellCoords(0, 0), "test"); CPPUNIT_ASSERT(m_Grid->GetCellValue(0, 0) == "test"); m_Grid->SetCellsValue(wxGridCellCoords(0, 0), "test1\ttest2\ntest3\ttest4\n"); CPPUNIT_ASSERT(m_Grid->GetCellValue(0, 0) == "test1"); // test wxExListView m_ListView->SetSingleStyle(wxLC_REPORT); // wxLC_ICON); m_ListView->InsertColumn("String", wxExColumn::COL_STRING); m_ListView->InsertColumn("Number", wxExColumn::COL_INT); CPPUNIT_ASSERT(m_ListView->FindColumn("String") == 0); CPPUNIT_ASSERT(m_ListView->FindColumn("Number") == 1); // test wxExNotebook (parent should not be NULL) wxWindow* page1 = new wxWindow(wxTheApp->GetTopWindow(), wxID_ANY); wxWindow* page2 = new wxWindow(wxTheApp->GetTopWindow(), wxID_ANY); CPPUNIT_ASSERT(m_Notebook->AddPage(page1, "key1") != NULL); CPPUNIT_ASSERT(m_Notebook->AddPage(page2, "key2") != NULL); CPPUNIT_ASSERT(m_Notebook->AddPage(page1, "key1") == NULL); CPPUNIT_ASSERT(m_Notebook->GetKeyByPage(page1) == "key1"); CPPUNIT_ASSERT(m_Notebook->GetPageByKey("key1") == page1); CPPUNIT_ASSERT(m_Notebook->SetPageText("key1", "keyx", "hello")); CPPUNIT_ASSERT(m_Notebook->GetPageByKey("keyx") == page1); CPPUNIT_ASSERT(m_Notebook->DeletePage("keyx")); CPPUNIT_ASSERT(m_Notebook->GetPageByKey("keyx") == NULL); // test wxExSTC CPPUNIT_ASSERT(m_STC->GetFileName().GetFullName() == "test.h"); // do the same test as with wxExFile in base for a binary file CPPUNIT_ASSERT(m_STC->Open(wxExFileName("../base/test.bin"))); const wxCharBuffer& buffer = m_STC->GetTextRaw(); wxLogMessage(buffer.data()); CPPUNIT_ASSERT(buffer.length() == 40); // test wxExSTCShell m_STCShell->Prompt("test1"); m_STCShell->Prompt("test2"); m_STCShell->Prompt("test3"); m_STCShell->Prompt("test4"); // Prompting does not add a command to history... // TODO: Make a better test. CPPUNIT_ASSERT(!m_STCShell->GetHistory().Contains("test4")); // test wxExSVN CPPUNIT_ASSERT(m_SVN->Execute(false) == 0); // do not use a dialog // The output depends on the svn stat, of course, // so do not assert on it. m_SVN->GetOutput(); // test various wxEx methods that need the app const wxString header = wxExHeader(wxExFileName("test.h"), wxExApp::GetConfig(), "hello test"); CPPUNIT_ASSERT(header.Contains("hello test")); // test util CPPUNIT_ASSERT(wxExClipboardAdd("test")); CPPUNIT_ASSERT(wxExClipboardGet() == "test"); CPPUNIT_ASSERT(wxExGetNumberOfLines("test\ntest\n") == 3); CPPUNIT_ASSERT(wxExGetLineNumberFromText("test on line: 1200") == 1200); CPPUNIT_ASSERT(wxExLog("hello from wxextension test")); CPPUNIT_ASSERT(!wxExMatchesOneOf(wxFileName("test.txt"), "*.cpp")); CPPUNIT_ASSERT(wxExMatchesOneOf(wxFileName("test.txt"), "*.cpp;*.txt")); CPPUNIT_ASSERT(wxExSkipWhiteSpace("t es t") == "t es t"); } void wxExAppTestFixture::tearDown() { } wxExTestSuite::wxExTestSuite() : CppUnit::TestSuite("wxextension test suite") { addTest(new CppUnit::TestCaller<wxExAppTestFixture>( "testConstructors", &wxExAppTestFixture::testConstructors)); addTest(new CppUnit::TestCaller<wxExAppTestFixture>( "testMethods", &wxExAppTestFixture::testMethods)); } <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "gtest/gtest.h" #include "MooseFunctor.h" #include "FaceInfo.h" #include "libmesh/elem.h" #include "libmesh/quadrature_gauss.h" using namespace libMesh; using namespace Moose; template <typename T> class TestFunctor : public FunctorBase<T> { public: using typename FunctorBase<T>::FunctorType; using typename FunctorBase<T>::FunctorReturnType; using typename FunctorBase<T>::ValueType; using typename FunctorBase<T>::GradientType; using typename FunctorBase<T>::DotType; TestFunctor() = default; private: ValueType evaluate(const Moose::ElemArg &, unsigned int) const override final { return 0; } ValueType evaluate(const Moose::ElemFromFaceArg &, unsigned int) const override final { return 0; } ValueType evaluate(const Moose::FaceArg &, unsigned int) const override final { return 0; } ValueType evaluate(const Moose::SingleSidedFaceArg &, unsigned int) const override final { return 0; } ValueType evaluate(const Moose::ElemQpArg &, unsigned int) const override final { return 0; } ValueType evaluate(const Moose::ElemSideQpArg &, unsigned int) const override final { return 0; } }; TEST(MooseFunctorTest, testArgs) { TestFunctor<Real> test; Node node0(0); node0.set_id(0); Node node1(1); node1.set_id(1); Node node2(2); node2.set_id(2); auto elem = Elem::build(EDGE2); elem->set_node(0) = &node0; elem->set_node(1) = &node1; auto neighbor = Elem::build(EDGE2); neighbor->set_node(0) = &node1; neighbor->set_node(1) = &node2; elem->set_neighbor(1, neighbor.get()); FaceInfo fi(elem.get(), 1, neighbor.get()); QGauss qrule(1, CONSTANT); auto elem_arg = Moose::ElemArg{elem.get(), false, false}; auto face = Moose::FaceArg({&fi, FV::LimiterType::CentralDifference, true, false, false, INVALID_BLOCK_ID, INVALID_BLOCK_ID}); auto single_face = Moose::SingleSidedFaceArg( {&fi, FV::LimiterType::CentralDifference, true, false, false, INVALID_BLOCK_ID}); auto elem_from_face = Moose::ElemFromFaceArg({elem.get(), &fi, false, false, INVALID_BLOCK_ID}); auto elem_qp = std::make_tuple(elem.get(), 0, &qrule); auto elem_side_qp = std::make_tuple(elem.get(), 0, 0, &qrule); auto test_dot = [&test](const auto & arg) { try { test.dot(arg); ASSERT_TRUE(false); } catch (std::runtime_error & e) { ASSERT_TRUE(std::string(e.what()).find("not implemented") != std::string::npos); } }; test_dot(elem_arg); test_dot(face); test_dot(single_face); test_dot(elem_from_face); test_dot(elem_qp); test_dot(elem_side_qp); auto test_gradient = [&test](const auto & arg) { try { test.gradient(arg); ASSERT_TRUE(false); } catch (std::runtime_error & e) { ASSERT_TRUE(std::string(e.what()).find("not implemented") != std::string::npos); } }; test_gradient(elem_arg); test_gradient(face); test_gradient(single_face); test_gradient(elem_from_face); test_gradient(elem_qp); test_gradient(elem_side_qp); ConstantFunctor<Real> cf(2); EXPECT_EQ(cf(elem_arg), 2); EXPECT_EQ(cf(elem_from_face), 2); EXPECT_EQ(cf(face), 2); EXPECT_EQ(cf(single_face), 2); EXPECT_EQ(cf(elem_from_face), 2); EXPECT_EQ(cf(elem_qp), 2); EXPECT_EQ(cf(elem_side_qp), 2); auto constant_gradient_test = [&cf](const auto & arg) { const auto result = cf.gradient(arg); for (const auto i : make_range(unsigned(LIBMESH_DIM))) EXPECT_EQ(result(i), 0); }; constant_gradient_test(elem_arg); constant_gradient_test(elem_from_face); constant_gradient_test(face); constant_gradient_test(single_face); constant_gradient_test(elem_from_face); constant_gradient_test(elem_qp); constant_gradient_test(elem_side_qp); EXPECT_EQ(cf.dot(elem_arg), 0); EXPECT_EQ(cf.dot(elem_from_face), 0); EXPECT_EQ(cf.dot(face), 0); EXPECT_EQ(cf.dot(single_face), 0); EXPECT_EQ(cf.dot(elem_from_face), 0); EXPECT_EQ(cf.dot(elem_qp), 0); EXPECT_EQ(cf.dot(elem_side_qp), 0); } <commit_msg>Unit test VectorComponentFunctor<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "gtest/gtest.h" #include "MooseFunctor.h" #include "FaceInfo.h" #include "VectorComponentFunctor.h" #include "GreenGaussGradient.h" #include "MeshGeneratorMesh.h" #include "GeneratedMeshGenerator.h" #include "AppFactory.h" #include "libmesh/elem.h" #include "libmesh/quadrature_gauss.h" #include "libmesh/type_tensor.h" using namespace libMesh; using namespace Moose; using namespace FV; template <typename T> class TestFunctor : public FunctorBase<T> { public: using typename FunctorBase<T>::ValueType; TestFunctor() = default; private: ValueType evaluate(const ElemArg &, unsigned int) const override final { return 0; } ValueType evaluate(const ElemFromFaceArg &, unsigned int) const override final { return 0; } ValueType evaluate(const FaceArg &, unsigned int) const override final { return 0; } ValueType evaluate(const SingleSidedFaceArg &, unsigned int) const override final { return 0; } ValueType evaluate(const ElemQpArg &, unsigned int) const override final { return 0; } ValueType evaluate(const ElemSideQpArg &, unsigned int) const override final { return 0; } }; template <typename T> class WithGradientTestFunctor : public TestFunctor<T> { public: using typename TestFunctor<T>::GradientType; WithGradientTestFunctor(const MooseMesh & mesh) : _mesh(mesh) {} bool isExtrapolatedBoundaryFace(const FaceInfo & fi) const override { return !fi.neighborPtr(); } private: using TestFunctor<T>::evaluateGradient; GradientType evaluateGradient(const ElemArg & elem_arg, unsigned int) const override final { return greenGaussGradient(elem_arg, *this, true, _mesh); } GradientType evaluateGradient(const FaceArg & face, unsigned int) const override final { const auto & fi = *face.fi; if (!isExtrapolatedBoundaryFace(fi)) { const auto elem_arg = face.makeElem(); const auto elem_gradient = this->gradient(elem_arg); const auto neighbor_arg = face.makeNeighbor(); const auto linear_interp_gradient = fi.gC() * elem_gradient + (1 - fi.gC()) * this->gradient(neighbor_arg); return linear_interp_gradient + outer_product(((*this)(neighbor_arg) - (*this)(elem_arg)) / fi.dCFMag() - linear_interp_gradient * fi.eCF(), fi.eCF()); } // One term expansion if (!fi.neighborPtr()) return this->gradient(face.makeElem()); else return this->gradient(face.makeNeighbor()); } const MooseMesh & _mesh; }; TEST(MooseFunctorTest, testArgs) { TestFunctor<Real> test; Node node0(0); node0.set_id(0); Node node1(1); node1.set_id(1); Node node2(2); node2.set_id(2); auto elem = Elem::build(EDGE2); elem->set_node(0) = &node0; elem->set_node(1) = &node1; auto neighbor = Elem::build(EDGE2); neighbor->set_node(0) = &node1; neighbor->set_node(1) = &node2; elem->set_neighbor(1, neighbor.get()); FaceInfo fi(elem.get(), 1, neighbor.get()); QGauss qrule(1, CONSTANT); auto elem_arg = ElemArg{elem.get(), false, false}; auto face = FaceArg({&fi, LimiterType::CentralDifference, true, false, false, INVALID_BLOCK_ID, INVALID_BLOCK_ID}); auto single_face = SingleSidedFaceArg( {&fi, LimiterType::CentralDifference, true, false, false, INVALID_BLOCK_ID}); auto elem_from_face = ElemFromFaceArg({elem.get(), &fi, false, false, INVALID_BLOCK_ID}); auto elem_qp = std::make_tuple(elem.get(), 0, &qrule); auto elem_side_qp = std::make_tuple(elem.get(), 0, 0, &qrule); // Test not-implemented errors { auto test_dot = [&test](const auto & arg) { try { test.dot(arg); ASSERT_TRUE(false); } catch (std::runtime_error & e) { ASSERT_TRUE(std::string(e.what()).find("not implemented") != std::string::npos); } }; test_dot(elem_arg); test_dot(face); test_dot(single_face); test_dot(elem_from_face); test_dot(elem_qp); test_dot(elem_side_qp); auto test_gradient = [&test](const auto & arg) { try { test.gradient(arg); ASSERT_TRUE(false); } catch (std::runtime_error & e) { ASSERT_TRUE(std::string(e.what()).find("not implemented") != std::string::npos); } }; test_gradient(elem_arg); test_gradient(face); test_gradient(single_face); test_gradient(elem_from_face); test_gradient(elem_qp); test_gradient(elem_side_qp); } auto zero_gradient_test = [](const auto & functor, const auto & arg) { const auto result = functor.gradient(arg); for (const auto i : make_range(unsigned(LIBMESH_DIM))) EXPECT_EQ(result(i), 0); }; // Test ConstantFunctor { ConstantFunctor<Real> cf(2); EXPECT_EQ(cf(elem_arg), 2); EXPECT_EQ(cf(elem_from_face), 2); EXPECT_EQ(cf(face), 2); EXPECT_EQ(cf(single_face), 2); EXPECT_EQ(cf(elem_from_face), 2); EXPECT_EQ(cf(elem_qp), 2); EXPECT_EQ(cf(elem_side_qp), 2); zero_gradient_test(cf, elem_arg); zero_gradient_test(cf, elem_from_face); zero_gradient_test(cf, face); zero_gradient_test(cf, single_face); zero_gradient_test(cf, elem_from_face); zero_gradient_test(cf, elem_qp); zero_gradient_test(cf, elem_side_qp); EXPECT_EQ(cf.dot(elem_arg), 0); EXPECT_EQ(cf.dot(elem_from_face), 0); EXPECT_EQ(cf.dot(face), 0); EXPECT_EQ(cf.dot(single_face), 0); EXPECT_EQ(cf.dot(elem_from_face), 0); EXPECT_EQ(cf.dot(elem_qp), 0); EXPECT_EQ(cf.dot(elem_side_qp), 0); } // Test VectorComponentFunctor { const char * argv[2] = {"foo", "\0"}; MultiMooseEnum coord_type_enum("XYZ RZ RSPHERICAL", "XYZ"); const auto nx = 2; auto app = AppFactory::createAppShared("MooseUnitApp", 1, (char **)argv); auto * factory = &app->getFactory(); std::string mesh_type = "MeshGeneratorMesh"; std::shared_ptr<MeshGeneratorMesh> mesh; { InputParameters params = factory->getValidParams(mesh_type); mesh = factory->create<MeshGeneratorMesh>(mesh_type, "moose_mesh", params); } app->actionWarehouse().mesh() = mesh; { std::unique_ptr<MeshBase> lm_mesh; InputParameters params = factory->getValidParams("GeneratedMeshGenerator"); params.set<unsigned int>("nx") = nx; params.set<unsigned int>("ny") = nx; params.set<MooseEnum>("dim") = "2"; auto mesh_gen = factory->create<GeneratedMeshGenerator>("GeneratedMeshGenerator", "mesh_gen", params); lm_mesh = mesh_gen->generate(); mesh->setMeshBase(std::move(lm_mesh)); } mesh->prepare(); mesh->setCoordSystem({}, coord_type_enum); // Build the face info const auto & all_fi = mesh->allFaceInfo(); mesh->computeFaceInfoFaceCoords(); WithGradientTestFunctor<RealVectorValue> vec_test_func(*mesh); VectorComponentFunctor<Real> vec_comp(vec_test_func, 0); EXPECT_EQ(vec_comp(elem_arg), 0); EXPECT_EQ(vec_comp(elem_from_face), 0); EXPECT_EQ(vec_comp(face), 0); EXPECT_EQ(vec_comp(single_face), 0); EXPECT_EQ(vec_comp(elem_from_face), 0); EXPECT_EQ(vec_comp(elem_qp), 0); EXPECT_EQ(vec_comp(elem_side_qp), 0); const auto & mesh_fi = all_fi.front(); const auto vec_elem_arg = ElemArg{&mesh_fi.elem(), false, false}; auto vec_face_arg = FaceArg({&mesh_fi, LimiterType::CentralDifference, true, false, false, mesh_fi.elem().subdomain_id(), mesh_fi.neighborPtr() ? mesh_fi.neighbor().subdomain_id() : INVALID_BLOCK_ID}); zero_gradient_test(vec_comp, vec_elem_arg); zero_gradient_test(vec_comp, vec_face_arg); } } <|endoftext|>
<commit_before>#include "layers/layer_z.h" #include "core/exception.h" #include "core/ptree_utils.h" #include "ts/ts.h" using namespace std; using namespace cv; using namespace sem; /** * @brief class for testing layer Z initialization, the main, SEM learning algorithm */ class LayerZInitTest : public ::testing::Test { protected: virtual void SetUp() { nb_afferents_ = 50; PTree params; params.put(LayerZ::PARAM_NB_AFFERENTS, nb_afferents_); params.put(LayerZ::PARAM_NB_OUTPUT_NODES, 10); config_.Params(params); // IO config_.Input(LayerZ::KEY_INPUT_SPIKES, NAME_INPUT_SPIKES); config_.Output(LayerZ::KEY_OUTPUT_SPIKES, NAME_OUTPUT_SPIKES); config_.Output(LayerZ::KEY_OUTPUT_MEMBRANE_POT, NAME_OUTPUT_MEM_POT); } // members LayerZ to_; ///< test object LayerConfig config_; ///< default layer configuration int nb_afferents_; // name of keys in signal static const string NAME_INPUT_SPIKES; ///< no. of afferent spikes static const string NAME_OUTPUT_SPIKES; ///< no. of output spikes/size of output layer static const string NAME_OUTPUT_MEM_POT; ///< membrane potential }; // initialize static members const string LayerZInitTest::NAME_INPUT_SPIKES = "in"; const string LayerZInitTest::NAME_OUTPUT_SPIKES = "out"; const string LayerZInitTest::NAME_OUTPUT_MEM_POT = "mem_pot"; /** * @brief test validation of missing params */ TEST_F(LayerZInitTest, MissingParams) { // remove key to output nodes PTree params = config_.Params(); params.erase(LayerZ::PARAM_NB_OUTPUT_NODES); config_.Params(params); LayerZ to; EXPECT_THROW(to.Reset(config_), std::exception); } /** * @brief test parameter validation */ TEST_F(LayerZInitTest, InvalidParams) { { PTree params = config_.Params(); params.put(LayerZ::PARAM_DELTA_T, -0.1f); config_.Params(params); LayerZ to; EXPECT_THROW(to.Reset(config_), ExceptionValueError); } { PTree params = config_.Params(); params.put(LayerZ::PARAM_DELTA_T, 0.f); config_.Params(params); LayerZ to; EXPECT_THROW(to.Reset(config_), ExceptionValueError); } { PTree params = config_.Params(); params.put(LayerZ::PARAM_DELTA_T, -0.f); config_.Params(params); LayerZ to; EXPECT_THROW(to.Reset(config_), ExceptionValueError); } { PTree params = config_.Params(); params.put(LayerZ::PARAM_LEN_HISTORY, -3); config_.Params(params); LayerZ to; EXPECT_THROW(to.Reset(config_), ExceptionValueError); } { PTree params = config_.Params(); params.put(LayerZ::PARAM_LEN_HISTORY, 0); config_.Params(params); LayerZ to; EXPECT_THROW(to.Reset(config_), ExceptionValueError); } { PTree params = config_.Params(); params.put(LayerZ::PARAM_NB_AFFERENTS, 0); config_.Params(params); LayerZ to; EXPECT_THROW(to.Reset(config_), ExceptionValueError); } { PTree params = config_.Params(); params.put(LayerZ::PARAM_NB_AFFERENTS, -3); config_.Params(params); LayerZ to; EXPECT_THROW(to.Reset(config_), ExceptionValueError); } { PTree params = config_.Params(); params.put(LayerZ::PARAM_WTA_FREQ, -1); config_.Params(params); LayerZ to; EXPECT_THROW(to.Reset(config_), ExceptionValueError); } } TEST_F(LayerZInitTest, IONames) { LayerConfig cfg; cfg.Params(config_.Params()); { LayerZ to; EXPECT_THROW(to.IONames(cfg), std::exception); } { cfg.Input(LayerZ::KEY_INPUT_SPIKES, NAME_INPUT_SPIKES); LayerZ to; EXPECT_THROW(to.IONames(cfg), std::exception) << "still missing required output spikes"; } { cfg.Output(LayerZ::KEY_OUTPUT_SPIKES, NAME_OUTPUT_SPIKES); LayerZ to; EXPECT_NO_THROW(to.IONames(cfg)) << "all required IO names present"; } } <commit_msg>turn InvalidParams test into value-parameterized test<commit_after>#include "layers/layer_z.h" #include "core/exception.h" #include "core/ptree_utils.h" #include "ts/ts.h" using namespace std; using namespace cv; using namespace sem; // name of keys in signal const string NAME_INPUT_SPIKES = "in"; ///< no. of afferent spikes const string NAME_OUTPUT_SPIKES = "out"; ///< no. of output spikes/size of output layer const string NAME_OUTPUT_MEM_POT = "mem_pot"; ///< membrane potential /** * @brief mixin for testing layer Z, the main, SEM learning algorithm * Because we expect to test using fixutres as well as parametrized tests * Since these two test types are derived differently mixins solves the problem of defining a common base * The solution is adopted from this StackOverflow post: * @see http://stackoverflow.com/questions/3152326/google-test-parameterized-tests-which-use-an-existing-test-fixture-class * * T specifies test type (fixture or parameterized) */ template <class T> class LayerZTestBase : public T { protected: virtual void SetUp() { nb_afferents_ = 50; params_ = PTree(); params_.put(LayerZ::PARAM_NB_AFFERENTS, nb_afferents_); params_.put(LayerZ::PARAM_NB_OUTPUT_NODES, 10); config_.Params(params_); // IO config_.Input(LayerZ::KEY_INPUT_SPIKES, NAME_INPUT_SPIKES); config_.Output(LayerZ::KEY_OUTPUT_SPIKES, NAME_OUTPUT_SPIKES); config_.Output(LayerZ::KEY_OUTPUT_MEMBRANE_POT, NAME_OUTPUT_MEM_POT); } // members LayerConfig config_; ///< default layer configuration PTree params_; ///< default params int nb_afferents_; }; /** * @brief class for testing layer z initialization routines */ class LayerZInitTest : public LayerZTestBase<testing::Test > { protected: // members LayerZ to_; ///< test object }; /** * @brief test validation of missing params */ TEST_F(LayerZInitTest, MissingParams) { // remove key to output nodes params_.erase(LayerZ::PARAM_NB_OUTPUT_NODES); config_.Params(params_); EXPECT_THROW(LayerZ().Reset(config_), std::exception); } TEST_F(LayerZInitTest, IONames) { LayerConfig cfg; cfg.Params(config_.Params()); { LayerZ to; EXPECT_THROW(to.IONames(cfg), std::exception); } { cfg.Input(LayerZ::KEY_INPUT_SPIKES, NAME_INPUT_SPIKES); LayerZ to; EXPECT_THROW(to.IONames(cfg), std::exception) << "still missing required output spikes"; } { cfg.Output(LayerZ::KEY_OUTPUT_SPIKES, NAME_OUTPUT_SPIKES); LayerZ to; EXPECT_NO_THROW(to.IONames(cfg)) << "all required IO names present"; } } typedef std::pair<std::string, float > TParamPairSF; /// convinience typdef to use as test params below /** * @brief Parameterized test for testing layer z parameter value validation * Using paramterized tests allows us to try different value more easily */ class LayerZParamsTest : public LayerZTestBase<testing::TestWithParam<TParamPairSF > > { protected: }; // if you're using QTCreator, don't mind the ..._EvalGenerator_ warning at the bottom INSTANTIATE_TEST_CASE_P(TestWithParams, LayerZParamsTest, testing::Values(TParamPairSF(LayerZ::PARAM_DELTA_T, -1.f), TParamPairSF(LayerZ::PARAM_DELTA_T, -0.f), TParamPairSF(LayerZ::PARAM_DELTA_T, 0.f), TParamPairSF(LayerZ::PARAM_LEN_HISTORY, -3), TParamPairSF(LayerZ::PARAM_LEN_HISTORY, 0), TParamPairSF(LayerZ::PARAM_NB_AFFERENTS, 0), TParamPairSF(LayerZ::PARAM_NB_AFFERENTS, -3), TParamPairSF(LayerZ::PARAM_WTA_FREQ, -0.001f), TParamPairSF(LayerZ::PARAM_WTA_FREQ, -1.f))); TEST_P(LayerZParamsTest, InvalidParams) { TParamPairSF tp = GetParam(); params_.put(tp.first, tp.second); config_.Params(params_); EXPECT_THROW(LayerZ().Reset(config_), ExceptionValueError); } <|endoftext|>
<commit_before>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (c) 2010 Arjen Hiemstra <[email protected]> * Copyright (c) 2011 Laszlo Papp <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "objectmanager.h" #include "selectionmanager.h" #include "newobjectcommand.h" #include "deleteobjectcommand.h" #include "propertychangedcommand.h" #include "historymanager.h" #include "core/debughelper.h" #include "engine/gameproject.h" #include "engine/gameobject.h" #include "engine/scene.h" #include "engine/game.h" #include "engine/component.h" #include <KDE/KLocalizedString> #include <KDE/KMimeType> #include <KDE/KDirWatch> #include <QtCore/QFileInfo> #include <QtCore/QDir> #include <QtCore/QStringBuilder> using namespace GluonCreator; template<> GLUON_CREATOR_VISIBILITY ObjectManager* GluonCore::Singleton<ObjectManager>::m_instance = 0; QString ObjectManager::humanifyClassName( const QString& fixThis, bool justRemoveNamespace ) const { QString fixedString; const QString classname = fixThis.right( fixThis.length() - fixThis.lastIndexOf( ':' ) - 1 ); if( justRemoveNamespace ) return classname; const int length = classname.size(); for( int i = 0; i < length; ++i ) { const QChar current = classname.at( i ); if( i == 0 ) { // Always upper-case the first word, whether it is or not... fixedString = current.toUpper(); } else { if( current.isUpper() ) { fixedString = fixedString % ' ' % current; } else { fixedString = fixedString % current; } } } return fixedString; } GluonEngine::Asset* ObjectManager::createNewAsset( const QString& fileName, const QString& className, const QString& name ) { DEBUG_BLOCK GluonCore::GluonObject* newChild = 0; if( className.isEmpty() ) { KMimeType::Ptr type = KMimeType::findByFileContent( fileName ); DEBUG_TEXT( QString( "Creating asset for file %1 of mimetype %2" ).arg( fileName ).arg( type->name() ) ); newChild = GluonCore::GluonObjectFactory::instance()->instantiateObjectByMimetype( type->name() ); } else { newChild = GluonCore::GluonObjectFactory::instance()->instantiateObjectByName( className ); } GluonEngine::Asset* newAsset = qobject_cast< GluonEngine::Asset* >( newChild ); if( newAsset ) { setupAsset( newAsset, fileName, name ); return newAsset; } return 0; } void ObjectManager::setupAsset( GluonEngine::Asset* newAsset, const QString& fileName, const QString& name ) { GluonEngine::Game::instance()->gameProject()->addChild( newAsset ); newAsset->setGameProject( GluonEngine::Game::instance()->gameProject() ); QFileInfo info( fileName ); if( name.isNull() ) { newAsset->setName( info.fileName() ); } else { newAsset->setName( name ); } if( !QDir::current().exists( "Assets" ) ) QDir::current().mkdir( "Assets" ); QUrl newLocation( QString( "Assets/%1" ).arg( newAsset->fullyQualifiedFileName() ) ); QFile( fileName ).copy( newLocation.toLocalFile() ); newAsset->setFile( newLocation ); newAsset->load(); QString path( newAsset->absolutePath() ); m_assets.insert( path, newAsset ); KDirWatch::self()->addFile( path ); HistoryManager::instance()->addCommand( new NewObjectCommand( newAsset ) ); } void ObjectManager::changeProperty( GluonCore::GluonObject* object, QString& property, QVariant& oldValue, QVariant& newValue ) { HistoryManager::instance()->addCommand( new PropertyChangedCommand( object, property, oldValue, newValue ) ); } GluonEngine::Component* ObjectManager::createNewComponent( const QString& type, GluonEngine::GameObject* parent ) { DEBUG_BLOCK GluonCore::GluonObject* newObj = GluonCore::GluonObjectFactory::instance()->instantiateObjectByName( type ); if( newObj ) { newObj->setName( humanifyClassName( newObj->metaObject()->className(), true ) ); GluonEngine::Component* comp = qobject_cast<GluonEngine::Component*>( newObj ); parent->addComponent( comp ); // Initialize the component comp->initialize(); emit newComponent( comp ); HistoryManager::instance()->addCommand( new NewObjectCommand( comp ) ); return comp; } return 0; } GluonEngine::GameObject* ObjectManager::createNewGameObject() { DEBUG_FUNC_NAME GluonEngine::GameObject* newObj = new GluonEngine::GameObject(); newObj->setName( humanifyClassName( newObj->metaObject()->className(), false ) ); DEBUG_TEXT( QString( "Creating object: %1" ).arg( newObj->name() ) ); SelectionManager::SelectionList selection = SelectionManager::instance()->selection(); if( selection.size() > 0 ) { GluonEngine::GameObject* obj = qobject_cast<GluonEngine::GameObject*>( selection.at( 0 ) ); if( obj ) { DEBUG_TEXT( QString( "Item %1 selected in Scene tree - assign new object as child" ).arg( obj->fullyQualifiedName() ) ); obj->addChild( newObj ); } } if( newObj->parentGameObject() == 0 ) { DEBUG_TEXT( QString( "No parent game object yet - assign as child to Scene root" ) ); GluonEngine::Game::instance()->currentScene()->sceneContents()->addChild( newObj ); } emit newGameObject( newObj ); HistoryManager::instance()->addCommand( new NewObjectCommand( newObj ) ); return newObj; } void ObjectManager::deleteGameObject( GluonEngine::GameObject* object ) { if(!object && !object->parentGameObject()) { qDebug() << "No parent game object for the object specified for deleting"; } if (!object->parentGameObject()->removeChild(object)) qDebug() << "Could not add the game object to the scene tree"; emit gameObjectDeleted(); HistoryManager::instance()->addCommand( new DeleteObjectCommand( object, object->parentGameObject() ) ); } GluonEngine::Scene* ObjectManager::createNewScene() { GluonEngine::Scene* newScn = new GluonEngine::Scene(); newScn->setName( i18n( "NewScene" ) ); newScn->setGameProject( GluonEngine::Game::instance()->gameProject() ); GluonEngine::Game::instance()->gameProject()->addChild( newScn ); emit newScene( newScn ); HistoryManager::instance()->addCommand( new NewObjectCommand( newScn ) ); return newScn; } void ObjectManager::watchCurrentAssets() { DEBUG_FUNC_NAME QObjectList assets = GluonEngine::Game::instance()->gameProject()->children(); foreach( QObject* child, assets ) { GluonEngine::Asset* asset = qobject_cast<GluonEngine::Asset*>( child ); if( asset ) { QString path( asset->absolutePath() ); DEBUG_TEXT( QString( "Watching %1 for changes." ).arg( path ) ); KDirWatch::self()->addFile( path ); m_assets.insert( path, asset ); } } } void ObjectManager::assetDirty( const QString& file) { GluonEngine::Asset* asset = m_assets.value(file); if( asset ) { asset->reload(); GluonEngine::Game::instance()->drawAll(); } } void ObjectManager::assetDeleted( const QString& file) { m_assets.remove(file); KDirWatch::self()->removeFile( file ); QFileInfo fi(file); if( fi.isFile()) { QFile::remove(file); } else if( fi.isDir()) { QDir d; d.rmpath(file); } } void ObjectManager::assetDeleted( GluonEngine::Asset* asset ) { assetDeleted( asset->absolutePath() ); } ObjectManager::ObjectManager() { m_objectId = 0; m_sceneId = 0; connect( KDirWatch::self(), SIGNAL( dirty( const QString& ) ), SLOT( assetDirty( const QString& ) ) ); connect( KDirWatch::self(), SIGNAL( created( const QString& ) ), SLOT( assetDirty( const QString& ) ) ); } ObjectManager::~ObjectManager() { } <commit_msg>New assets are given a different name if it already exists<commit_after>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (c) 2010 Arjen Hiemstra <[email protected]> * Copyright (c) 2011 Laszlo Papp <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "objectmanager.h" #include "selectionmanager.h" #include "newobjectcommand.h" #include "deleteobjectcommand.h" #include "propertychangedcommand.h" #include "historymanager.h" #include "core/debughelper.h" #include "engine/gameproject.h" #include "engine/gameobject.h" #include "engine/scene.h" #include "engine/game.h" #include "engine/component.h" #include <KDE/KLocalizedString> #include <KDE/KMimeType> #include <KDE/KDirWatch> #include <QtCore/QFileInfo> #include <QtCore/QDir> #include <QtCore/QStringBuilder> using namespace GluonCreator; template<> GLUON_CREATOR_VISIBILITY ObjectManager* GluonCore::Singleton<ObjectManager>::m_instance = 0; QString ObjectManager::humanifyClassName( const QString& fixThis, bool justRemoveNamespace ) const { QString fixedString; const QString classname = fixThis.right( fixThis.length() - fixThis.lastIndexOf( ':' ) - 1 ); if( justRemoveNamespace ) return classname; const int length = classname.size(); for( int i = 0; i < length; ++i ) { const QChar current = classname.at( i ); if( i == 0 ) { // Always upper-case the first word, whether it is or not... fixedString = current.toUpper(); } else { if( current.isUpper() ) { fixedString = fixedString % ' ' % current; } else { fixedString = fixedString % current; } } } return fixedString; } GluonEngine::Asset* ObjectManager::createNewAsset( const QString& fileName, const QString& className, const QString& name ) { DEBUG_BLOCK GluonCore::GluonObject* newChild = 0; if( className.isEmpty() ) { KMimeType::Ptr type = KMimeType::findByFileContent( fileName ); DEBUG_TEXT( QString( "Creating asset for file %1 of mimetype %2" ).arg( fileName ).arg( type->name() ) ); newChild = GluonCore::GluonObjectFactory::instance()->instantiateObjectByMimetype( type->name() ); } else { newChild = GluonCore::GluonObjectFactory::instance()->instantiateObjectByName( className ); } GluonEngine::Asset* newAsset = qobject_cast< GluonEngine::Asset* >( newChild ); if( newAsset ) { setupAsset( newAsset, fileName, name ); return newAsset; } return 0; } void ObjectManager::setupAsset( GluonEngine::Asset* newAsset, const QString& fileName, const QString& name ) { GluonEngine::Game::instance()->gameProject()->addChild( newAsset ); newAsset->setGameProject( GluonEngine::Game::instance()->gameProject() ); QFileInfo info( fileName ); if( name.isNull() ) { newAsset->setName( info.fileName() ); } else { newAsset->setName( name ); } if( !QDir::current().exists( "Assets" ) ) QDir::current().mkdir( "Assets" ); QUrl newLocation( QString( "Assets/%1" ).arg( newAsset->fullyQualifiedFileName() ) ); int i = 0; QStringList theSplitName = newAsset->name().split('.'); QString firstName = theSplitName.takeAt(0); while(QFile::exists(newLocation.toLocalFile())) { i++; QString newName = firstName.append( QString( " (%1)." ).arg( i ) ).append( theSplitName.join(".") ); newAsset->setName( newName ); newLocation = QUrl( QString( "Assets/%1" ).arg( newAsset->fullyQualifiedFileName() ) ); } QFile( fileName ).copy( newLocation.toLocalFile() ); newAsset->setFile( newLocation ); newAsset->load(); QString path( newAsset->absolutePath() ); m_assets.insert( path, newAsset ); KDirWatch::self()->addFile( path ); HistoryManager::instance()->addCommand( new NewObjectCommand( newAsset ) ); } void ObjectManager::changeProperty( GluonCore::GluonObject* object, QString& property, QVariant& oldValue, QVariant& newValue ) { HistoryManager::instance()->addCommand( new PropertyChangedCommand( object, property, oldValue, newValue ) ); } GluonEngine::Component* ObjectManager::createNewComponent( const QString& type, GluonEngine::GameObject* parent ) { DEBUG_BLOCK GluonCore::GluonObject* newObj = GluonCore::GluonObjectFactory::instance()->instantiateObjectByName( type ); if( newObj ) { newObj->setName( humanifyClassName( newObj->metaObject()->className(), true ) ); GluonEngine::Component* comp = qobject_cast<GluonEngine::Component*>( newObj ); parent->addComponent( comp ); // Initialize the component comp->initialize(); emit newComponent( comp ); HistoryManager::instance()->addCommand( new NewObjectCommand( comp ) ); return comp; } return 0; } GluonEngine::GameObject* ObjectManager::createNewGameObject() { DEBUG_FUNC_NAME GluonEngine::GameObject* newObj = new GluonEngine::GameObject(); newObj->setName( humanifyClassName( newObj->metaObject()->className(), false ) ); DEBUG_TEXT( QString( "Creating object: %1" ).arg( newObj->name() ) ); SelectionManager::SelectionList selection = SelectionManager::instance()->selection(); if( selection.size() > 0 ) { GluonEngine::GameObject* obj = qobject_cast<GluonEngine::GameObject*>( selection.at( 0 ) ); if( obj ) { DEBUG_TEXT( QString( "Item %1 selected in Scene tree - assign new object as child" ).arg( obj->fullyQualifiedName() ) ); obj->addChild( newObj ); } } if( newObj->parentGameObject() == 0 ) { DEBUG_TEXT( QString( "No parent game object yet - assign as child to Scene root" ) ); GluonEngine::Game::instance()->currentScene()->sceneContents()->addChild( newObj ); } emit newGameObject( newObj ); HistoryManager::instance()->addCommand( new NewObjectCommand( newObj ) ); return newObj; } void ObjectManager::deleteGameObject( GluonEngine::GameObject* object ) { if(!object && !object->parentGameObject()) { qDebug() << "No parent game object for the object specified for deleting"; } if (!object->parentGameObject()->removeChild(object)) qDebug() << "Could not add the game object to the scene tree"; emit gameObjectDeleted(); HistoryManager::instance()->addCommand( new DeleteObjectCommand( object, object->parentGameObject() ) ); } GluonEngine::Scene* ObjectManager::createNewScene() { GluonEngine::Scene* newScn = new GluonEngine::Scene(); newScn->setName( i18n( "NewScene" ) ); newScn->setGameProject( GluonEngine::Game::instance()->gameProject() ); GluonEngine::Game::instance()->gameProject()->addChild( newScn ); emit newScene( newScn ); HistoryManager::instance()->addCommand( new NewObjectCommand( newScn ) ); return newScn; } void ObjectManager::watchCurrentAssets() { DEBUG_FUNC_NAME QObjectList assets = GluonEngine::Game::instance()->gameProject()->children(); foreach( QObject* child, assets ) { GluonEngine::Asset* asset = qobject_cast<GluonEngine::Asset*>( child ); if( asset ) { QString path( asset->absolutePath() ); DEBUG_TEXT( QString( "Watching %1 for changes." ).arg( path ) ); KDirWatch::self()->addFile( path ); m_assets.insert( path, asset ); } } } void ObjectManager::assetDirty( const QString& file) { GluonEngine::Asset* asset = m_assets.value(file); if( asset ) { asset->reload(); GluonEngine::Game::instance()->drawAll(); } } void ObjectManager::assetDeleted( const QString& file) { m_assets.remove(file); KDirWatch::self()->removeFile( file ); QFileInfo fi(file); if( fi.isFile()) { QFile::remove(file); } else if( fi.isDir()) { QDir d; d.rmpath(file); } } void ObjectManager::assetDeleted( GluonEngine::Asset* asset ) { assetDeleted( asset->absolutePath() ); } ObjectManager::ObjectManager() { m_objectId = 0; m_sceneId = 0; connect( KDirWatch::self(), SIGNAL( dirty( const QString& ) ), SLOT( assetDirty( const QString& ) ) ); connect( KDirWatch::self(), SIGNAL( created( const QString& ) ), SLOT( assetDirty( const QString& ) ) ); } ObjectManager::~ObjectManager() { } <|endoftext|>
<commit_before>#include <ros/ros.h> #include <ros/package.h> #include <cvt_ros/RGBDSubscriber.h> #include <tf2_ros/transform_listener.h> #include <cvt/cl/OpenCL.h> #include <cvt/cl/CLPlatform.h> #include <cvt/vision/TSDFVolume.h> #include <cvt/vision/CameraCalibration.h> using namespace cvt_ros; class TSDFMeshing : public RGBDSubscriber { public: TSDFMeshing() : RGBDSubscriber(), _tfListener( _tfBuffer ), _volume( 0 ), _factorDepthToMeter( (float)(0xFFFF) / 1000.0f ), _nMaps( 0 ) { init(); } TSDFMeshing( const cvt::Matrix3f& intrinsics ) : RGBDSubscriber( intrinsics ), _tfListener( _tfBuffer ), _volume( 0 ), _factorDepthToMeter( (float)(0xFFFF) / 1000.0f ), _nMaps( 0 ) { init(); } private: typedef std::vector<cvt::CLPlatform> CLPlatformVec; tf2_ros::Buffer _tfBuffer; tf2_ros::TransformListener _tfListener; std::string _base, _moving; ros::Duration _timeout; cvt::Matrix4f _gridToWorld; cvt::TSDFVolume* _volume; float _factorDepthToMeter; uint32_t _nMaps; CLPlatformVec _platforms; void init() { ros::NodeHandle nh( "~" ); _moving = "direct_vo"; _base = "world"; double dt = 0.4; nh.param<std::string>( "moving_frame", _moving, _moving ); nh.param<std::string>( "base_frame", _base, _base ); ROS_INFO( "BASE: %s", _base.c_str() ); ROS_INFO( "MOVING: %s", _moving.c_str() ); nh.param<double>( "time_out", dt, dt ); _timeout.fromSec( dt ); cvt::CLPlatform::get( _platforms ); cvt::CL::setDefaultDevice( _platforms[ 0 ].defaultDevice() ); createTSDF( 2, 2, 2, 0.004f ); _volume->clear(); } void imageCallback( const cvt::Image& rgb, const cvt::Image& depth ) { cvt::Image depthCL; depth.convert( depthCL, cvt::IFormat::GRAY_UINT16, cvt::IALLOCATOR_CL ); try { geometry_msgs::TransformStamped transform = _tfBuffer.lookupTransform( _moving, _base, _rgbHeader.stamp, _timeout ); cvt::Quaternionf q; q.x = transform.transform.rotation.x; q.y = transform.transform.rotation.y; q.z = transform.transform.rotation.z; q.w = transform.transform.rotation.w; cvt::Matrix4f pose( q.toMatrix3() ); pose[ 0 ][ 3 ] = transform.transform.translation.x; pose[ 1 ][ 3 ] = transform.transform.translation.y; pose[ 2 ][ 3 ] = transform.transform.translation.z; // Add to the TSDF std::cout << _intrinsics << std::endl; _volume->addDepthMap( _intrinsics, pose, depthCL, _factorDepthToMeter ); _nMaps++; ROS_INFO( "Volume contains %d depthmaps", _nMaps ); } catch ( const tf2::TransformException& e ){ ROS_WARN( "Error in transform lookup: %s", e.what() ); return; } // TODO: publish / display current mesh -> not in each step if( _nMaps % 200 == 0 ){ cvt::SceneMesh mesh( "TSDF_MESH" ); _volume->toSceneMesh( mesh ); mesh.transform( _gridToWorld ); meshToOBJ( "tsdf.obj", mesh ); } } void createTSDF( uint32_t size_x, uint32_t size_y, uint32_t size_z, float resolution ) { // compute the number of needed "Voxels" int nx = size_x / resolution; if( nx > 512 ){ nx = 512; resolution = ( float )size_x / ( float )nx; } int ny = size_y / resolution; if( ny > 512 ){ ny = 512; resolution = ( float )size_y / ( float )ny; nx = size_x / resolution; } int nz = size_z / resolution; if( nz > 512 ){ nz = 512; resolution = ( float )size_z / ( float )nz; nx = size_x / resolution; ny = size_y / resolution; } ROS_INFO( "%d, %d, %d", nx, ny, nz ); _gridToWorld = cvt::Matrix4f( resolution, 0.0f, 0.0f, -( float )size_x / 2.0f, 0.0f, resolution, 0.0f, -( float )size_y / 2.0f, 0.0f, 0.0f, resolution, ( float )0.0f, 0.0f, 0.0f, 0.0f, 1.0f ); std::cout << "GRID2WORLD: " <<_gridToWorld << std::endl; // _gridToWorld = cvt::Matrix4f( 2.0f / ( float )( 512 ), 0.0f, 0.0f, -0.25f, // 0.0f, 2.0f / ( float )( 512 ), 0.0f, -1.5f, // 0.0f, 0.0f, 2.0f / ( float ) ( 512 ), -0.5f, // 0.0f, 0.0f, 0.0f, 0.25 ); // _gridToWorld *= 4.0f; if( _volume != 0 ){ delete _volume; } _volume = new cvt::TSDFVolume( _gridToWorld, nx, ny, nz, 15.0f * resolution ); //_volume = new cvt::TSDFVolume( _gridToWorld, 512, 512, 512, 0.07f ); } void meshToOBJ( const cvt::String& file, const cvt::SceneMesh& mesh ) const { FILE* f = fopen( file.c_str(), "wb" ); ROS_INFO( "MESH: vertices -> %ul, normals -> %lu, faces -> %ul", mesh.vertexSize(), mesh.normalSize(), mesh.faceSize() ); for( size_t idx = 0; idx < mesh.vertexSize(); idx++ ) { cvt::Vector3f vtx = mesh.vertex( idx ); fprintf( f, "v %f %f %f\n", vtx.x, vtx.y, vtx.z ); } for( size_t idx = 0; idx < mesh.normalSize(); idx++ ) { cvt::Vector3f vtx = mesh.normal( idx ); fprintf( f, "vn %f %f %f\n", vtx.x, vtx.y, vtx.z ); } const unsigned int* faces = mesh.faces(); for( size_t idx = 0; idx < mesh.faceSize(); idx++ ) { fprintf( f, "f %d//%d %d//%d %d//%d\n", *( faces) + 1, *( faces) + 1, *( faces + 1 ) + 1, *( faces + 1 ) + 1, *( faces + 2 ) + 1, *( faces + 2 ) + 1 ); faces += 3; } fclose( f ); } }; int main( int argc, char* argv[] ) { ros::init( argc, argv, "tsdf_meshing"); ros::NodeHandle nh( "~" ); bool useCalibFile = false; std::string filename = "xtion_rgb.xml"; nh.param<std::string>( "calib_file", filename, filename ); nh.param<bool>( "use_calib_file", useCalibFile, useCalibFile ); ROS_INFO( "Using Calibration file: %d", useCalibFile ); if( useCalibFile ){ try { // load calibration cvt::String resourcePath; resourcePath.sprintf( "%s/resources/%s", ros::package::getPath( "cvt_ros" ).c_str(), filename.c_str() ); ROS_INFO( "Calibration file: %s", resourcePath.c_str() ); cvt::CameraCalibration calib; calib.load( resourcePath.c_str() ); TSDFMeshing mesher( calib.intrinsics() ); ros::spin(); } catch( cvt::Exception& e ){ ROS_ERROR( "%s", e.what() ); return 1; } } else { TSDFMeshing mesher; ros::spin(); } return 0; } <commit_msg> modified: src/tsdf_meshing.cpp<commit_after>#include <ros/ros.h> #include <ros/package.h> #include <cvt_ros/RGBDSubscriber.h> #include <tf2_ros/transform_listener.h> #include <cvt/cl/OpenCL.h> #include <cvt/cl/CLPlatform.h> #include <cvt/vision/TSDFVolume.h> #include <cvt/vision/CameraCalibration.h> using namespace cvt_ros; class TSDFMeshing : public RGBDSubscriber { public: TSDFMeshing() : RGBDSubscriber(), _tfListener( _tfBuffer ), _volume( 0 ), _factorDepthToMeter( (float)(0xFFFF) / 1000.0f ), _nMaps( 0 ) { init(); } TSDFMeshing( const cvt::Matrix3f& intrinsics ) : RGBDSubscriber( intrinsics ), _tfListener( _tfBuffer ), _volume( 0 ), _factorDepthToMeter( (float)(0xFFFF) / 1000.0f ), _nMaps( 0 ) { init(); } private: typedef std::vector<cvt::CLPlatform> CLPlatformVec; tf2_ros::Buffer _tfBuffer; tf2_ros::TransformListener _tfListener; std::string _base, _moving; ros::Duration _timeout; cvt::Matrix4f _gridToWorld; cvt::TSDFVolume* _volume; float _factorDepthToMeter; uint32_t _nMaps; CLPlatformVec _platforms; void init() { ros::NodeHandle nh( "~" ); _moving = "direct_vo"; _base = "world"; double dt = 0.4; nh.param<std::string>( "moving_frame", _moving, _moving ); nh.param<std::string>( "base_frame", _base, _base ); ROS_INFO( "BASE: %s", _base.c_str() ); ROS_INFO( "MOVING: %s", _moving.c_str() ); nh.param<double>( "time_out", dt, dt ); _timeout.fromSec( dt ); cvt::CLPlatform::get( _platforms ); cvt::CL::setDefaultDevice( _platforms[ 0 ].defaultDevice() ); createTSDF( 2, 2, 2, 0.004f ); _volume->clear(); } void imageCallback( const cvt::Image& rgb, const cvt::Image& depth ) { cvt::Image depthCL; depth.convert( depthCL, cvt::IFormat::GRAY_UINT16, cvt::IALLOCATOR_CL ); try { geometry_msgs::TransformStamped transform = _tfBuffer.lookupTransform( _moving, _base, _rgbHeader.stamp, _timeout ); cvt::Quaternionf q; q.x = transform.transform.rotation.x; q.y = transform.transform.rotation.y; q.z = transform.transform.rotation.z; q.w = transform.transform.rotation.w; cvt::Matrix4f pose( q.toMatrix3() ); pose[ 0 ][ 3 ] = transform.transform.translation.x; pose[ 1 ][ 3 ] = transform.transform.translation.y; pose[ 2 ][ 3 ] = transform.transform.translation.z; // Add to the TSDF std::cout << _intrinsics << std::endl; _volume->addDepthMap( _intrinsics, pose, depthCL, _factorDepthToMeter ); _nMaps++; ROS_INFO( "Volume contains %d depthmaps", _nMaps ); } catch ( const tf2::TransformException& e ){ ROS_WARN( "Error in transform lookup: %s", e.what() ); return; } // TODO: publish / display current mesh -> not in each step if( _nMaps % 200 == 0 ){ cvt::SceneMesh mesh( "TSDF_MESH" ); _volume->toSceneMesh( mesh ); mesh.transform( _gridToWorld ); meshToOBJ( "tsdf.obj", mesh ); } } void createTSDF( uint32_t size_x, uint32_t size_y, uint32_t size_z, float resolution ) { // compute the number of needed "Voxels" int nx = size_x / resolution; if( nx > 512 ){ nx = 512; resolution = ( float )size_x / ( float )nx; } int ny = size_y / resolution; if( ny > 512 ){ ny = 512; resolution = ( float )size_y / ( float )ny; nx = size_x / resolution; } int nz = size_z / resolution; if( nz > 512 ){ nz = 512; resolution = ( float )size_z / ( float )nz; nx = size_x / resolution; ny = size_y / resolution; } ROS_INFO( "%d, %d, %d", nx, ny, nz ); _gridToWorld = cvt::Matrix4f( resolution, 0.0f, 0.0f, -( float )size_x / 2.0f, 0.0f, resolution, 0.0f, -( float )size_y / 2.0f, 0.0f, 0.0f, resolution, ( float )0.0f, 0.0f, 0.0f, 0.0f, 1.0f ); std::cout << "GRID2WORLD: " <<_gridToWorld << std::endl; // _gridToWorld = cvt::Matrix4f( 2.0f / ( float )( 512 ), 0.0f, 0.0f, -0.25f, // 0.0f, 2.0f / ( float )( 512 ), 0.0f, -1.5f, // 0.0f, 0.0f, 2.0f / ( float ) ( 512 ), -0.5f, // 0.0f, 0.0f, 0.0f, 0.25 ); // _gridToWorld *= 4.0f; if( _volume != 0 ){ delete _volume; } _volume = new cvt::TSDFVolume( _gridToWorld, nx, ny, nz, 15.0f * resolution ); //_volume = new cvt::TSDFVolume( _gridToWorld, 512, 512, 512, 0.07f ); } void meshToOBJ( const cvt::String& file, const cvt::SceneMesh& mesh ) const { FILE* f = fopen( file.c_str(), "wb" ); ROS_INFO( "MESH: vertices -> %zd, normals -> %zd, faces -> %zd", mesh.vertexSize(), mesh.normalSize(), mesh.faceSize() ); for( size_t idx = 0; idx < mesh.vertexSize(); idx++ ) { cvt::Vector3f vtx = mesh.vertex( idx ); fprintf( f, "v %f %f %f\n", vtx.x, vtx.y, vtx.z ); } for( size_t idx = 0; idx < mesh.normalSize(); idx++ ) { cvt::Vector3f vtx = mesh.normal( idx ); fprintf( f, "vn %f %f %f\n", vtx.x, vtx.y, vtx.z ); } const unsigned int* faces = mesh.faces(); for( size_t idx = 0; idx < mesh.faceSize(); idx++ ) { fprintf( f, "f %d//%d %d//%d %d//%d\n", *( faces) + 1, *( faces) + 1, *( faces + 1 ) + 1, *( faces + 1 ) + 1, *( faces + 2 ) + 1, *( faces + 2 ) + 1 ); faces += 3; } fclose( f ); } }; int main( int argc, char* argv[] ) { ros::init( argc, argv, "tsdf_meshing"); ros::NodeHandle nh( "~" ); bool useCalibFile = false; std::string filename = "xtion_rgb.xml"; nh.param<std::string>( "calib_file", filename, filename ); nh.param<bool>( "use_calib_file", useCalibFile, useCalibFile ); ROS_INFO( "Using Calibration file: %d", useCalibFile ); if( useCalibFile ){ try { // load calibration cvt::String resourcePath; resourcePath.sprintf( "%s/resources/%s", ros::package::getPath( "cvt_ros" ).c_str(), filename.c_str() ); ROS_INFO( "Calibration file: %s", resourcePath.c_str() ); cvt::CameraCalibration calib; calib.load( resourcePath.c_str() ); TSDFMeshing mesher( calib.intrinsics() ); ros::spin(); } catch( cvt::Exception& e ){ ROS_ERROR( "%s", e.what() ); return 1; } } else { TSDFMeshing mesher; ros::spin(); } return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2009 by Marc Boris Duerner, Tommi Maekitalo * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * 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 <cxxtools/http/socket.h> #include <cxxtools/http/server.h> #include <cxxtools/log.h> #include <cassert> log_define("cxxtools.http.socket") namespace cxxtools { namespace http { void Socket::ParseEvent::onMethod(const std::string& method) { _request.method(method); } void Socket::ParseEvent::onUrl(const std::string& url) { _request.url(url); } void Socket::ParseEvent::onUrlParam(const std::string& q) { _request.qparams(q); } Socket::Socket(SelectorBase& selector, Server& server) : TcpSocket(server), _server(server), _parseEvent(_request), _parser(_parseEvent, false), _responder(0) { log_info("connection accepted from " << getPeerAddr()); _stream.attachDevice(*this); _stream.buffer().beginRead(); cxxtools::connect(_stream.buffer().inputReady, *this, &Socket::onInput); cxxtools::connect(_stream.buffer().outputReady, *this, &Socket::onOutput); cxxtools::connect(_timer.timeout, *this, &Socket::onTimeout); _timer.start(_server.readTimeout()); addSelector(selector); } Socket::~Socket() { if (_responder) _responder->release(); } void Socket::removeSelector() { TcpSocket::setSelector(0); _timer.setSelector(0); } void Socket::addSelector(SelectorBase& selector) { selector.add(*this); selector.add(_timer); } void Socket::onInput(StreamBuffer& sb) { log_trace("onInput"); log_debug(this << " read data from " << getPeerAddr()); if (sb.in_avail() == 0 || sb.device()->eof()) { log_debug("end of stream"); close(); delete this; return; } _timer.start(_server.readTimeout()); if ( _responder == 0 ) { _parser.advance(sb); if (_parser.fail()) { _responder = _server.getDefaultResponder(_request); _responder->replyError(_reply.body(), _request, _reply, std::runtime_error("invalid http header")); _responder->release(); _responder = 0; sendReply(); onOutput(sb); return; } if (_parser.end()) { _responder = _server.getResponder(_request); try { _responder->beginRequest(_stream, _request); } catch (const std::exception& e) { _reply.setHeader("Connection", "close"); _responder->replyError(_reply.body(), _request, _reply, e); _responder->release(); _responder = 0; sendReply(); onOutput(sb); return; } _contentLength = _request.header().contentLength(); if (_contentLength == 0) { _server.addReadySockets(this); return; } } else { sb.beginRead(); } } if (_responder) { if (sb.in_avail() > 0) { try { std::size_t s = _responder->readBody(_stream); assert(s > 0); _contentLength -= s; } catch (const std::exception& e) { _reply.setHeader("Connection", "close"); _responder->replyError(_reply.body(), _request, _reply, e); _responder->release(); _responder = 0; sendReply(); onOutput(sb); return; } } if (_contentLength <= 0) { _server.addReadySockets(this); } else { sb.beginRead(); } } } bool Socket::doReply() { log_trace("http::Socket::doReply"); try { _responder->reply(_reply.body(), _request, _reply); } catch (const std::exception& e) { log_warn("responder reported error: " << e.what()); _reply.clear(); _responder->replyError(_reply.body(), _request, _reply, e); } _responder->release(); _responder = 0; sendReply(); return onOutput(_stream.buffer()); } bool Socket::onOutput(StreamBuffer& sb) { log_trace("onOutput"); log_debug(this << " send data to " << getPeerAddr()); sb.beginWrite(); if ( sb.out_avail() ) { _timer.start(_server.writeTimeout()); } else { bool keepAlive = _request.header().keepAlive(); if (keepAlive) { std::string connection = _reply.getHeader("Connection"); if (connection == "close" || (connection.empty() && (_reply.header().httpVersionMajor() < 1 || _reply.header().httpVersionMinor() < 1))) { keepAlive = false; } } if (keepAlive) { log_debug("do keep alive"); _timer.start(_server.keepAliveTimeout()); _request.clear(); _reply.clear(); _parser.reset(false); _stream.buffer().beginRead(); } else { log_debug("don't do keep alive"); close(); delete this; return false; } } return true; } void Socket::onTimeout() { log_debug("timeout"); close(); delete this; } void Socket::sendReply() { const std::string contentLength = "Content-Length"; const std::string server = "Server"; const std::string connection = "Connection"; const std::string date = "Date"; _stream << "HTTP/" << _reply.header().httpVersionMajor() << '.' << _reply.header().httpVersionMinor() << ' ' << _reply.header().httpReturnCode() << ' ' << _reply.header().httpReturnText() << "\r\n"; for (ReplyHeader::const_iterator it = _reply.header().begin(); it != _reply.header().end(); ++it) { _stream << it->first << ": " << it->second << "\r\n"; } if (!_reply.header().hasHeader(contentLength)) { _stream << "Content-Length: " << _reply.bodySize() << "\r\n"; } if (!_reply.header().hasHeader(server)) { _stream << "Server: cxxtools-Net-Server\r\n"; } if (!_reply.header().hasHeader(connection)) { _stream << "Connection: " << (_request.header().keepAlive() ? "keep-alive" : "close") << "\r\n"; } if (!_reply.header().hasHeader(date)) { _stream << "Date: " << MessageHeader::htdateCurrent() << "\r\n"; } _stream << "\r\n"; _reply.sendBody(_stream); } } // namespace http } // namespace cxxtools <commit_msg>do not debug-output this pointer - it is mostly useless<commit_after>/* * Copyright (C) 2009 by Marc Boris Duerner, Tommi Maekitalo * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * 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 <cxxtools/http/socket.h> #include <cxxtools/http/server.h> #include <cxxtools/log.h> #include <cassert> log_define("cxxtools.http.socket") namespace cxxtools { namespace http { void Socket::ParseEvent::onMethod(const std::string& method) { _request.method(method); } void Socket::ParseEvent::onUrl(const std::string& url) { _request.url(url); } void Socket::ParseEvent::onUrlParam(const std::string& q) { _request.qparams(q); } Socket::Socket(SelectorBase& selector, Server& server) : TcpSocket(server), _server(server), _parseEvent(_request), _parser(_parseEvent, false), _responder(0) { log_info("connection accepted from " << getPeerAddr()); _stream.attachDevice(*this); _stream.buffer().beginRead(); cxxtools::connect(_stream.buffer().inputReady, *this, &Socket::onInput); cxxtools::connect(_stream.buffer().outputReady, *this, &Socket::onOutput); cxxtools::connect(_timer.timeout, *this, &Socket::onTimeout); _timer.start(_server.readTimeout()); addSelector(selector); } Socket::~Socket() { if (_responder) _responder->release(); } void Socket::removeSelector() { TcpSocket::setSelector(0); _timer.setSelector(0); } void Socket::addSelector(SelectorBase& selector) { selector.add(*this); selector.add(_timer); } void Socket::onInput(StreamBuffer& sb) { log_trace("onInput"); log_debug(this << " read data from " << getPeerAddr()); if (sb.in_avail() == 0 || sb.device()->eof()) { log_debug("end of stream"); close(); delete this; return; } _timer.start(_server.readTimeout()); if ( _responder == 0 ) { _parser.advance(sb); if (_parser.fail()) { _responder = _server.getDefaultResponder(_request); _responder->replyError(_reply.body(), _request, _reply, std::runtime_error("invalid http header")); _responder->release(); _responder = 0; sendReply(); onOutput(sb); return; } if (_parser.end()) { _responder = _server.getResponder(_request); try { _responder->beginRequest(_stream, _request); } catch (const std::exception& e) { _reply.setHeader("Connection", "close"); _responder->replyError(_reply.body(), _request, _reply, e); _responder->release(); _responder = 0; sendReply(); onOutput(sb); return; } _contentLength = _request.header().contentLength(); if (_contentLength == 0) { _server.addReadySockets(this); return; } } else { sb.beginRead(); } } if (_responder) { if (sb.in_avail() > 0) { try { std::size_t s = _responder->readBody(_stream); assert(s > 0); _contentLength -= s; } catch (const std::exception& e) { _reply.setHeader("Connection", "close"); _responder->replyError(_reply.body(), _request, _reply, e); _responder->release(); _responder = 0; sendReply(); onOutput(sb); return; } } if (_contentLength <= 0) { _server.addReadySockets(this); } else { sb.beginRead(); } } } bool Socket::doReply() { log_trace("http::Socket::doReply"); try { _responder->reply(_reply.body(), _request, _reply); } catch (const std::exception& e) { log_warn("responder reported error: " << e.what()); _reply.clear(); _responder->replyError(_reply.body(), _request, _reply, e); } _responder->release(); _responder = 0; sendReply(); return onOutput(_stream.buffer()); } bool Socket::onOutput(StreamBuffer& sb) { log_trace("onOutput"); log_debug("send data to " << getPeerAddr()); sb.beginWrite(); if ( sb.out_avail() ) { _timer.start(_server.writeTimeout()); } else { bool keepAlive = _request.header().keepAlive(); if (keepAlive) { std::string connection = _reply.getHeader("Connection"); if (connection == "close" || (connection.empty() && (_reply.header().httpVersionMajor() < 1 || _reply.header().httpVersionMinor() < 1))) { keepAlive = false; } } if (keepAlive) { log_debug("do keep alive"); _timer.start(_server.keepAliveTimeout()); _request.clear(); _reply.clear(); _parser.reset(false); _stream.buffer().beginRead(); } else { log_debug("don't do keep alive"); close(); delete this; return false; } } return true; } void Socket::onTimeout() { log_debug("timeout"); close(); delete this; } void Socket::sendReply() { const std::string contentLength = "Content-Length"; const std::string server = "Server"; const std::string connection = "Connection"; const std::string date = "Date"; _stream << "HTTP/" << _reply.header().httpVersionMajor() << '.' << _reply.header().httpVersionMinor() << ' ' << _reply.header().httpReturnCode() << ' ' << _reply.header().httpReturnText() << "\r\n"; for (ReplyHeader::const_iterator it = _reply.header().begin(); it != _reply.header().end(); ++it) { _stream << it->first << ": " << it->second << "\r\n"; } if (!_reply.header().hasHeader(contentLength)) { _stream << "Content-Length: " << _reply.bodySize() << "\r\n"; } if (!_reply.header().hasHeader(server)) { _stream << "Server: cxxtools-Net-Server\r\n"; } if (!_reply.header().hasHeader(connection)) { _stream << "Connection: " << (_request.header().keepAlive() ? "keep-alive" : "close") << "\r\n"; } if (!_reply.header().hasHeader(date)) { _stream << "Date: " << MessageHeader::htdateCurrent() << "\r\n"; } _stream << "\r\n"; _reply.sendBody(_stream); } } // namespace http } // namespace cxxtools <|endoftext|>
<commit_before>#include "coders_crux.gen.h" // Contains FB32 palette #include "number_font.h" #include "ElementCube.h" #include "Element.h" #include "periodic.h" /* Order of adding electrons according to WolframAlpha: 1. Right 2. Left 3. Top 4. Bottom Repeat pattern as needed. */ enum LewisSides { LRight = 0, LLeft = 1, LTop = 2, LBottom = 3, LFirst = LRight, LLast = LBottom }; void ElementCube::Init(int cubeId, int initialElementNum) { this->cubeId = cubeId; this->cube = CubeID(cubeId); currentElementNum = initialElementNum; Element::GetRawElement(currentElementNum, &currentElement); isDirty = true; // Initialize video: v.attach(cube); v.initMode(FB32); v.fb32.fill(BG_COLOR); // Load the palette: for (int j = 0, h = 0; j < PALETTE_COUNT; j++, h += 3) { v.colormap[j].set(palette[h], palette[h + 1], palette[h + 2]); } } ElementCube::ElementCube() { } ElementCube::ElementCube(int cubeId, int initialElementNum) { Init(cubeId, initialElementNum); } ElementCube::ElementCube(int cubeId, const char* initialElementSymbol) { Init(cubeId, Element::GetRawElementNum(initialElementSymbol)); } void ElementCube::GoToNextElement() { currentElementNum++; if (currentElementNum >= Element::GetRawElementCount()) { currentElementNum = 0; } Element::GetRawElement(currentElementNum, &currentElement); isDirty = true; } void ElementCube::ResetElement() { currentElement.ResetToBasicState(); isDirty = true;//TODO: Right now the cubes get marked as dirty when they shouldn't. } int ElementCube::GetCubeId() { return cubeId; } Element* ElementCube::GetElement() { return &currentElement; } void ElementCube::SetDirty() { isDirty = true; } void ElementCube::Render() { if (!isDirty) { return; } //LOG("Cube %d is dirty! Redrawing.\n", (int)cube); // Clear the screen: v.fb32.fill(BG_COLOR); // Draw the element symbol: const char* symbol = currentElement.GetSymbol(); int chars = strlen(symbol); int stringWidth = chars * CODERS_CRUX_GLYPH_WIDTH + (chars - 1) * LETTER_SPACING; int stringHeight = CODERS_CRUX_GLYPH_HEIGHT - LETTER_DESCENDER_HEIGHT; // Add space for +/- symbol if (currentElement.GetCharge() != 0) { stringWidth += 3 + LETTER_SPACING; // Add space for number if (abs(currentElement.GetCharge()) > 1) { stringWidth += NUMBER_FONT_GLYPH_WIDTH + LETTER_SPACING; } } int x = SCREEN_WIDTH / 2 - stringWidth / 2; int y = SCREEN_HEIGHT / 2 - stringHeight / 2; // Draw the symbol: for (int i = 0; i < chars; i++) { //LOG("Drawing '%c'\n", symbol[i]); DrawCharAt(x, y, symbol[i]); x += CODERS_CRUX_GLYPH_WIDTH + LETTER_SPACING; } // Draw the +/- symbol: if (currentElement.GetCharge() != 0 && currentElement.HasBondType(BondType_Ionic)) { // Draw the line for the dash v.fb32.plot(vec(x + 0, y + 1), CHARGE_COLOR); v.fb32.plot(vec(x + 1, y + 1), CHARGE_COLOR); v.fb32.plot(vec(x + 2, y + 1), CHARGE_COLOR); // Draw the nubs for the plus for positive charge if (currentElement.GetCharge() > 0) { v.fb32.plot(vec(x + 1, y + 0), CHARGE_COLOR); v.fb32.plot(vec(x + 1, y + 2), CHARGE_COLOR); } // Draw the number if (abs(currentElement.GetCharge()) > 1) { DrawNumAt(x + 3 + LETTER_SPACING, y - 1, currentElement.GetCharge(), CHARGE_COLOR); } } // Draw covalent bond lines: for (int i = 0; i < BondSide_Count; i++) { BondSide side = (BondSide)i; if (currentElement.GetBondTypeFor(side) == BondType_Covalent) { DrawCovalentLine(side, stringWidth, stringHeight); } } // Draw potential reaction: if (currentElement.HasBondType(BondType_Potential)) { // Draw border on the cube //NOTE: Relies on screen being square. for (int i = 0; i < SCREEN_WIDTH; i++) { v.fb32.plot(vec(i, 0), POTENTIAL_COLOR); v.fb32.plot(vec(i, SCREEN_HEIGHT - 1), POTENTIAL_COLOR); v.fb32.plot(vec(0, i), POTENTIAL_COLOR); v.fb32.plot(vec(SCREEN_WIDTH - 1, i), POTENTIAL_COLOR); } } // Draw electrons: DrawLewisDots(stringWidth, stringHeight); isDirty = false; } void ElementCube::DrawCharAt(int x, int y, char c) { // Convert char to glyph id: if (c >= 'a' && c <= 'z') { c = c - 'a' + 26; } else if (c >= 'A' && c <= 'Z') { c -= 'A'; } else { Assert(false); }//Invalid character //This function seems broken, or I am misunderstanding its purpose. //v.fb32.bitmap(vec(x, y), vec(CODERS_CRUX_GLYPH_WIDTH, CODERS_CRUX_GLYPH_HEIGHT), &coders_crux[c * CODERS_CRUX_GLYPH_SIZE], CODERS_CRUX_GLYPH_WIDTH); for (int i = 0; i < CODERS_CRUX_GLYPH_HEIGHT; i++) { for (int j = 0; j < CODERS_CRUX_GLYPH_WIDTH; j++) { v.fb32.plot(vec(x + j, y + i), coders_crux[j + i * CODERS_CRUX_GLYPH_WIDTH + c * CODERS_CRUX_GLYPH_SIZE]); } } } void ElementCube::DrawNumAt(int x, int y, int num, int color) { if (num < 0 || num >= 10) { num = 10; // Draw the bad number symbol } for (int i = 0; i < NUMBER_FONT_GLYPH_HEIGHT; i++) { for (int j = 0; j < NUMBER_FONT_GLYPH_WIDTH; j++) { if (number_font[j + i * NUMBER_FONT_GLYPH_WIDTH + num * NUMBER_FONT_GLYPH_SIZE]) { v.fb32.plot(vec(x + j, y + i), color); } } } } void ElementCube::DrawCovalentLine(BondSide side, int stringWidth, int stringHeight) { int x = 0; int y = 0; switch (side) { case BondSide_Right: x = SCREEN_WIDTH / 2 + stringWidth / 2; y = SCREEN_HEIGHT / 2; for (int i = 6; (x + i) < SCREEN_WIDTH; i++) { v.fb32.plot(vec(x + i, y), CHARGE_COLOR); } break; case BondSide_Bottom: x = SCREEN_WIDTH / 2; y = SCREEN_HEIGHT / 2 + stringHeight / 2; for (int i = 4; (y + i) < SCREEN_HEIGHT; i++) { v.fb32.plot(vec(x, y + i), CHARGE_COLOR); } break; case BondSide_Left: x = SCREEN_WIDTH / 2 - stringWidth / 2; y = SCREEN_HEIGHT / 2; for (int i = 6; (x - i) >= 0; i++) { v.fb32.plot(vec(x - i, y), CHARGE_COLOR); } break; case BondSide_Top: x = SCREEN_WIDTH / 2; y = SCREEN_HEIGHT / 2 - stringHeight / 2; for (int i = 4; (y - i) >= 0; i++) { v.fb32.plot(vec(x, y - i), CHARGE_COLOR); } break; default: AssertAlways(); } } void ElementCube::DrawLewisDots(int stringWidth, int stringHeight) { //TODO: This is a bit of a hack. We need to properly set the outer electron count to 0 when the orbital is filled. if (currentElement.GetCharge() != 0 && currentElement.GetNumOuterElectrons() == 8) { return; } int numOuterElectrons = currentElement.GetNumOuterElectrons() - currentElement.GetSharedElectrons(); for (int s = LFirst; s <= LLast; s++) { // Calculate the number of electrons on this side int e = (numOuterElectrons + 3 - s) / 4; int x = SCREEN_WIDTH / 2; int y = SCREEN_HEIGHT / 2; // Calulate offset to get on the correct side: switch (s) { case LRight: x += stringWidth / 2 + 2; y += LETTER_DESCENDER_HEIGHT / 2; break; case LLeft: x -= stringWidth / 2 + 2; y += LETTER_DESCENDER_HEIGHT / 2; break; case LTop: x++; // Looks more natural one pixel to the right y -= stringHeight / 2 + 2; break; case LBottom: x++; // Looks more natural one pixel to the right y += stringHeight / 2 + 2; break; } // Calculate offset for electron separation: switch (s) { case LRight: case LLeft: y -= (e - 1) * 2; break; case LTop: case LBottom: x -= (e - 1) * 2; break; } // Draw the electrons: for ( ; e > 0; e--) { v.fb32.plot(vec(x, y), ELECTRON_COLOR); switch (s) { case LRight: case LLeft: y += 2; break; case LTop: case LBottom: x += 2; break; } } } } <commit_msg>Make border for potential reactions thicker.<commit_after>#include "coders_crux.gen.h" // Contains FB32 palette #include "number_font.h" #include "ElementCube.h" #include "Element.h" #include "periodic.h" /* Order of adding electrons according to WolframAlpha: 1. Right 2. Left 3. Top 4. Bottom Repeat pattern as needed. */ enum LewisSides { LRight = 0, LLeft = 1, LTop = 2, LBottom = 3, LFirst = LRight, LLast = LBottom }; void ElementCube::Init(int cubeId, int initialElementNum) { this->cubeId = cubeId; this->cube = CubeID(cubeId); currentElementNum = initialElementNum; Element::GetRawElement(currentElementNum, &currentElement); isDirty = true; // Initialize video: v.attach(cube); v.initMode(FB32); v.fb32.fill(BG_COLOR); // Load the palette: for (int j = 0, h = 0; j < PALETTE_COUNT; j++, h += 3) { v.colormap[j].set(palette[h], palette[h + 1], palette[h + 2]); } } ElementCube::ElementCube() { } ElementCube::ElementCube(int cubeId, int initialElementNum) { Init(cubeId, initialElementNum); } ElementCube::ElementCube(int cubeId, const char* initialElementSymbol) { Init(cubeId, Element::GetRawElementNum(initialElementSymbol)); } void ElementCube::GoToNextElement() { currentElementNum++; if (currentElementNum >= Element::GetRawElementCount()) { currentElementNum = 0; } Element::GetRawElement(currentElementNum, &currentElement); isDirty = true; } void ElementCube::ResetElement() { currentElement.ResetToBasicState(); isDirty = true;//TODO: Right now the cubes get marked as dirty when they shouldn't. } int ElementCube::GetCubeId() { return cubeId; } Element* ElementCube::GetElement() { return &currentElement; } void ElementCube::SetDirty() { isDirty = true; } void ElementCube::Render() { if (!isDirty) { return; } //LOG("Cube %d is dirty! Redrawing.\n", (int)cube); // Clear the screen: v.fb32.fill(BG_COLOR); // Draw the element symbol: const char* symbol = currentElement.GetSymbol(); int chars = strlen(symbol); int stringWidth = chars * CODERS_CRUX_GLYPH_WIDTH + (chars - 1) * LETTER_SPACING; int stringHeight = CODERS_CRUX_GLYPH_HEIGHT - LETTER_DESCENDER_HEIGHT; // Add space for +/- symbol if (currentElement.GetCharge() != 0) { stringWidth += 3 + LETTER_SPACING; // Add space for number if (abs(currentElement.GetCharge()) > 1) { stringWidth += NUMBER_FONT_GLYPH_WIDTH + LETTER_SPACING; } } int x = SCREEN_WIDTH / 2 - stringWidth / 2; int y = SCREEN_HEIGHT / 2 - stringHeight / 2; // Draw the symbol: for (int i = 0; i < chars; i++) { //LOG("Drawing '%c'\n", symbol[i]); DrawCharAt(x, y, symbol[i]); x += CODERS_CRUX_GLYPH_WIDTH + LETTER_SPACING; } // Draw the +/- symbol: if (currentElement.GetCharge() != 0 && currentElement.HasBondType(BondType_Ionic)) { // Draw the line for the dash v.fb32.plot(vec(x + 0, y + 1), CHARGE_COLOR); v.fb32.plot(vec(x + 1, y + 1), CHARGE_COLOR); v.fb32.plot(vec(x + 2, y + 1), CHARGE_COLOR); // Draw the nubs for the plus for positive charge if (currentElement.GetCharge() > 0) { v.fb32.plot(vec(x + 1, y + 0), CHARGE_COLOR); v.fb32.plot(vec(x + 1, y + 2), CHARGE_COLOR); } // Draw the number if (abs(currentElement.GetCharge()) > 1) { DrawNumAt(x + 3 + LETTER_SPACING, y - 1, currentElement.GetCharge(), CHARGE_COLOR); } } // Draw covalent bond lines: for (int i = 0; i < BondSide_Count; i++) { BondSide side = (BondSide)i; if (currentElement.GetBondTypeFor(side) == BondType_Covalent) { DrawCovalentLine(side, stringWidth, stringHeight); } } // Draw potential reaction: if (currentElement.HasBondType(BondType_Potential)) { // Draw border on the cube //NOTE: Relies on screen being square. for (int i = 0; i < SCREEN_WIDTH; i++) { v.fb32.plot(vec(i, 0), POTENTIAL_COLOR); v.fb32.plot(vec(i, 1), POTENTIAL_COLOR); v.fb32.plot(vec(i, SCREEN_HEIGHT - 1), POTENTIAL_COLOR); v.fb32.plot(vec(i, SCREEN_HEIGHT - 2), POTENTIAL_COLOR); v.fb32.plot(vec(0, i), POTENTIAL_COLOR); v.fb32.plot(vec(1, i), POTENTIAL_COLOR); v.fb32.plot(vec(SCREEN_WIDTH - 1, i), POTENTIAL_COLOR); v.fb32.plot(vec(SCREEN_WIDTH - 2, i), POTENTIAL_COLOR); } } // Draw electrons: DrawLewisDots(stringWidth, stringHeight); isDirty = false; } void ElementCube::DrawCharAt(int x, int y, char c) { // Convert char to glyph id: if (c >= 'a' && c <= 'z') { c = c - 'a' + 26; } else if (c >= 'A' && c <= 'Z') { c -= 'A'; } else { Assert(false); }//Invalid character //This function seems broken, or I am misunderstanding its purpose. //v.fb32.bitmap(vec(x, y), vec(CODERS_CRUX_GLYPH_WIDTH, CODERS_CRUX_GLYPH_HEIGHT), &coders_crux[c * CODERS_CRUX_GLYPH_SIZE], CODERS_CRUX_GLYPH_WIDTH); for (int i = 0; i < CODERS_CRUX_GLYPH_HEIGHT; i++) { for (int j = 0; j < CODERS_CRUX_GLYPH_WIDTH; j++) { v.fb32.plot(vec(x + j, y + i), coders_crux[j + i * CODERS_CRUX_GLYPH_WIDTH + c * CODERS_CRUX_GLYPH_SIZE]); } } } void ElementCube::DrawNumAt(int x, int y, int num, int color) { if (num < 0 || num >= 10) { num = 10; // Draw the bad number symbol } for (int i = 0; i < NUMBER_FONT_GLYPH_HEIGHT; i++) { for (int j = 0; j < NUMBER_FONT_GLYPH_WIDTH; j++) { if (number_font[j + i * NUMBER_FONT_GLYPH_WIDTH + num * NUMBER_FONT_GLYPH_SIZE]) { v.fb32.plot(vec(x + j, y + i), color); } } } } void ElementCube::DrawCovalentLine(BondSide side, int stringWidth, int stringHeight) { int x = 0; int y = 0; switch (side) { case BondSide_Right: x = SCREEN_WIDTH / 2 + stringWidth / 2; y = SCREEN_HEIGHT / 2; for (int i = 6; (x + i) < SCREEN_WIDTH; i++) { v.fb32.plot(vec(x + i, y), CHARGE_COLOR); } break; case BondSide_Bottom: x = SCREEN_WIDTH / 2; y = SCREEN_HEIGHT / 2 + stringHeight / 2; for (int i = 4; (y + i) < SCREEN_HEIGHT; i++) { v.fb32.plot(vec(x, y + i), CHARGE_COLOR); } break; case BondSide_Left: x = SCREEN_WIDTH / 2 - stringWidth / 2; y = SCREEN_HEIGHT / 2; for (int i = 6; (x - i) >= 0; i++) { v.fb32.plot(vec(x - i, y), CHARGE_COLOR); } break; case BondSide_Top: x = SCREEN_WIDTH / 2; y = SCREEN_HEIGHT / 2 - stringHeight / 2; for (int i = 4; (y - i) >= 0; i++) { v.fb32.plot(vec(x, y - i), CHARGE_COLOR); } break; default: AssertAlways(); } } void ElementCube::DrawLewisDots(int stringWidth, int stringHeight) { //TODO: This is a bit of a hack. We need to properly set the outer electron count to 0 when the orbital is filled. if (currentElement.GetCharge() != 0 && currentElement.GetNumOuterElectrons() == 8) { return; } int numOuterElectrons = currentElement.GetNumOuterElectrons() - currentElement.GetSharedElectrons(); for (int s = LFirst; s <= LLast; s++) { // Calculate the number of electrons on this side int e = (numOuterElectrons + 3 - s) / 4; int x = SCREEN_WIDTH / 2; int y = SCREEN_HEIGHT / 2; // Calulate offset to get on the correct side: switch (s) { case LRight: x += stringWidth / 2 + 2; y += LETTER_DESCENDER_HEIGHT / 2; break; case LLeft: x -= stringWidth / 2 + 2; y += LETTER_DESCENDER_HEIGHT / 2; break; case LTop: x++; // Looks more natural one pixel to the right y -= stringHeight / 2 + 2; break; case LBottom: x++; // Looks more natural one pixel to the right y += stringHeight / 2 + 2; break; } // Calculate offset for electron separation: switch (s) { case LRight: case LLeft: y -= (e - 1) * 2; break; case LTop: case LBottom: x -= (e - 1) * 2; break; } // Draw the electrons: for ( ; e > 0; e--) { v.fb32.plot(vec(x, y), ELECTRON_COLOR); switch (s) { case LRight: case LLeft: y += 2; break; case LTop: case LBottom: x += 2; break; } } } } <|endoftext|>
<commit_before>/************************************************************** COSC 501 Elliott Plack 14 NOV 2013 Due date: 30 NOV 2013 Problem: Write a program that plays the game of HANGMAN(guessing a mystery word). Read a word to be guessed from a file into successive elements of the array WORD. The player must guess the letters belonging to WORD. A single guessing session should be terminated when either all letters have been guessed correctly (player wins) or a specified number of incorrect guesses have been made (computer wins). A run must consist of at least two sessions: one player wins and one computer wins. The player decides whether or not to start a new session. ***************************************************************/ #include <iomanip> #include <iostream> #include <fstream> #include <string> #include <time.h> // for random using namespace std; ifstream inFile; // define ifstream to inFile command void readString(); void initialize(unsigned long); // function to initalize everything void guess(); void hangmanDraw(int, int, string); // global variables string word; // word to be read from file (the solution) string solution; // solution (guessed by user) unsigned long wordLength; // length of word // functions int main() // reads in the file and sets the functions in motion { readString(); // reads the file and stores variables initialize(wordLength); // sends length of word to initialize function cout << "Let's play hangman!\n"; guess(); // game logic return 0; } void readString() { int random20 = 0; // random number string dictionary[20]; // 20 words to load from file inFile.open("Words4Hangman.txt"); // open input file while (inFile.good()) { for (int i = 0; i < 20; i++) { inFile >> dictionary[i]; // load file and fill dict } } inFile.close(); // close the file srand((int)time(NULL)); // initialize random seed random20 = (rand() % 20); // set random to 20 +- word = dictionary[rand() % 20]; // set word = to a random letter in the dictionary cout << word << endl; // cheater! (testing) wordLength = word.size(); // size (length) of the string } void initialize(unsigned long wordLength) { solution.assign(wordLength, '*'); // fills up the solution string (an array) with as many *s as the word length } void guess() { char guessLetter = ' '; // letter to guess int winning = 0, goodGuess = 0; // variable to check if the game is won or the guess is good int guessesCounter = 7; // hangman countdown hangmanDraw(guessesCounter, winning, solution); // show blank while ((guessesCounter <= 7) && (winning == 0)) { cout << "Guess a letter: "; cin >> guessLetter; guessLetter = toupper(guessLetter); // make guess uppercase for (unsigned long i = 0; i < wordLength; i++) // loop through word looking for guess { if (guessLetter == word[i]) { //cout << "char " << (i + 1) /* +1 because first is 0*/ << " is " << guessLetter << endl; // outputs that guess was correct solution[i] = guessLetter; // set the i char in solution to guessLetter goodGuess = 1; // sets the flag goodGuess = 1 for the logic below } } if (solution == word) // thus victory { winning = 1; // you won hangmanDraw(guessesCounter, winning, solution); } else if (goodGuess == 1) { goodGuess = 0; // clear flag for next run hangmanDraw(guessesCounter, winning, solution); } else { guessesCounter--; // decrement guess hangmanDraw(guessesCounter, winning, solution); } } } void hangmanDraw(int guessNumber, int winningResult, string solutionDisplay) { // set up strings for game string hD01 = " /\\ /\\__ _ _ __ __ _ _ __ ___ __ _ _ __ \n"; // have to escape out backslash string hD02 = " / /_/ / _` | '_ \\ / _` | '_ ` _ \\ / _` | '_ \\ \n"; // have to escape out backslash string hD03 = " / __ / (_| | | | | (_| | | | | | | (_| | | | |\n"; string hD04 = " \\/ /_/ \\__,_|_| |_|\\__, |_| |_| |_|\\__,_|_| |_|\n"; // have to escape out backslash string hD05 = " |___/ \n"; string hD06 = " by Elliott Plack \n"; string hD07 = " \n"; string hD08 = " _______ \n"; string hD09 = " |/ | ______________________ \n"; string hD10 = " | | | \n"; string hD11 = " | | Your Progress | \n"; string hD12 = " | | | \n"; string hD13 = " | | | \n"; string hD14 = " | | | \n"; string hD15 = " ___|___ |______________________| \n"; // set up body parts string head = "(_)"; string neck = "|"; string leftArm = "\\"; string rightArm = "/"; string torso = "|"; string leftLeg = "/"; string rightLeg = "\\"; const char space = ' '; string youWon = "YOU WON !!"; string youLose = "YOU DIED !"; //system("CLS"); // clear the input screen if (guessNumber <= 7) { switch (guessNumber) { case 7: hD13 = hD13.replace(25, wordLength, solutionDisplay); cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07 << hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15; break; case 6: hD10 = hD10.replace(12, 3, head); hD13 = hD13.replace(25, wordLength, solutionDisplay); cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07 << hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15; break; case 5: hD10 = hD10.replace(12, 3, head); hD11 = hD11.replace(12, 1, leftArm); hD13 = hD13.replace(25, wordLength, solutionDisplay); cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07 << hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15; break; case 4: hD10 = hD10.replace(12, 3, head); hD11 = hD11.replace(12, 2, leftArm + neck); hD13 = hD13.replace(25, wordLength, solutionDisplay); cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07 << hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15; break; case 3: hD10 = hD10.replace(12, 3, head); hD11 = hD11.replace(12, 3, leftArm + neck + rightArm); hD13 = hD13.replace(25, wordLength, solutionDisplay); cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07 << hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15; break; case 2: hD10 = hD10.replace(12, 3, head); hD11 = hD11.replace(12, 3, leftArm + neck + rightArm); hD12 = hD12.replace(13, 1, torso); hD13 = hD13.replace(25, wordLength, solutionDisplay); cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07 << hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15; break; case 1: hD10 = hD10.replace(12, 3, head); hD11 = hD11.replace(12, 3, leftArm + neck + rightArm); hD12 = hD12.replace(13, 1, torso); hD13 = hD13.replace(12, 2, leftLeg + space); hD13 = hD13.replace(25, wordLength, solutionDisplay); cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07 << hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15; break; case 0: hD10 = hD10.replace(12, 3, head); hD11 = hD11.replace(12, 3, leftArm + neck + rightArm); hD12 = hD12.replace(13, 1, torso); hD13 = hD13.replace(12, 3, leftLeg + space + rightLeg); hD13 = hD13.replace(25, wordLength, solutionDisplay); hD14 = hD14.replace(31, 10, youLose); cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07 << hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15; break; default: cout << "\aError!"; break; } } else if (winningResult == 1) { hD13 = hD13.replace(25, wordLength, solutionDisplay); hD14 = hD14.replace(31, 10, youWon); cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07 << hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15; } }<commit_msg>changed greater than logic<commit_after>/************************************************************** COSC 501 Elliott Plack 14 NOV 2013 Due date: 30 NOV 2013 Problem: Write a program that plays the game of HANGMAN(guessing a mystery word). Read a word to be guessed from a file into successive elements of the array WORD. The player must guess the letters belonging to WORD. A single guessing session should be terminated when either all letters have been guessed correctly (player wins) or a specified number of incorrect guesses have been made (computer wins). A run must consist of at least two sessions: one player wins and one computer wins. The player decides whether or not to start a new session. ***************************************************************/ #include <iomanip> #include <iostream> #include <fstream> #include <string> #include <time.h> // for random using namespace std; ifstream inFile; // define ifstream to inFile command void readString(); void initialize(unsigned long); // function to initalize everything void guess(); void hangmanDraw(int, int, string); // global variables string word; // word to be read from file (the solution) string solution; // solution (guessed by user) unsigned long wordLength; // length of word // functions int main() // reads in the file and sets the functions in motion { readString(); // reads the file and stores variables initialize(wordLength); // sends length of word to initialize function cout << "Let's play hangman!\n"; guess(); // game logic return 0; } void readString() { int random20 = 0; // random number string dictionary[20]; // 20 words to load from file inFile.open("Words4Hangman.txt"); // open input file while (inFile.good()) { for (int i = 0; i < 20; i++) { inFile >> dictionary[i]; // load file and fill dict } } inFile.close(); // close the file srand((int)time(NULL)); // initialize random seed random20 = (rand() % 20); // set random to 20 +- word = dictionary[rand() % 20]; // set word = to a random letter in the dictionary cout << word << endl; // cheater! (testing) wordLength = word.size(); // size (length) of the string } void initialize(unsigned long wordLength) { solution.assign(wordLength, '*'); // fills up the solution string (an array) with as many *s as the word length } void guess() { char guessLetter = ' '; // letter to guess int winning = 0, goodGuess = 0; // variable to check if the game is won or the guess is good int guessesCounter = 7; // hangman countdown hangmanDraw(guessesCounter, winning, solution); // show blank while ((guessesCounter > 0) && (winning == 0)) { cout << "Guess a letter: "; cin >> guessLetter; guessLetter = toupper(guessLetter); // make guess uppercase for (unsigned long i = 0; i < wordLength; i++) // loop through word looking for guess { if (guessLetter == word[i]) { //cout << "char " << (i + 1) /* +1 because first is 0*/ << " is " << guessLetter << endl; // outputs that guess was correct solution[i] = guessLetter; // set the i char in solution to guessLetter goodGuess = 1; // sets the flag goodGuess = 1 for the logic below } } if (solution == word) // thus victory { winning = 1; // you won hangmanDraw(guessesCounter, winning, solution); } else if (goodGuess == 1) { goodGuess = 0; // clear flag for next run hangmanDraw(guessesCounter, winning, solution); } else { guessesCounter--; // decrement guess hangmanDraw(guessesCounter, winning, solution); } } } void hangmanDraw(int guessNumber, int winningResult, string solutionDisplay) { // set up strings for game string hD01 = " /\\ /\\__ _ _ __ __ _ _ __ ___ __ _ _ __ \n"; // have to escape out backslash string hD02 = " / /_/ / _` | '_ \\ / _` | '_ ` _ \\ / _` | '_ \\ \n"; // have to escape out backslash string hD03 = " / __ / (_| | | | | (_| | | | | | | (_| | | | |\n"; string hD04 = " \\/ /_/ \\__,_|_| |_|\\__, |_| |_| |_|\\__,_|_| |_|\n"; // have to escape out backslash string hD05 = " |___/ \n"; string hD06 = " by Elliott Plack \n"; string hD07 = " \n"; string hD08 = " _______ \n"; string hD09 = " |/ | ______________________ \n"; string hD10 = " | | | \n"; string hD11 = " | | Your Progress | \n"; string hD12 = " | | | \n"; string hD13 = " | | | \n"; string hD14 = " | | | \n"; string hD15 = " ___|___ |______________________| \n"; // set up body parts string head = "(_)"; string neck = "|"; string leftArm = "\\"; string rightArm = "/"; string torso = "|"; string leftLeg = "/"; string rightLeg = "\\"; const char space = ' '; string youWon = "YOU WON !!"; string youLose = "YOU DIED !"; //system("CLS"); // clear the input screen if (guessNumber <= 7) { switch (guessNumber) { case 7: hD13 = hD13.replace(25, wordLength, solutionDisplay); cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07 << hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15; break; case 6: hD10 = hD10.replace(12, 3, head); hD13 = hD13.replace(25, wordLength, solutionDisplay); cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07 << hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15; break; case 5: hD10 = hD10.replace(12, 3, head); hD11 = hD11.replace(12, 1, leftArm); hD13 = hD13.replace(25, wordLength, solutionDisplay); cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07 << hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15; break; case 4: hD10 = hD10.replace(12, 3, head); hD11 = hD11.replace(12, 2, leftArm + neck); hD13 = hD13.replace(25, wordLength, solutionDisplay); cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07 << hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15; break; case 3: hD10 = hD10.replace(12, 3, head); hD11 = hD11.replace(12, 3, leftArm + neck + rightArm); hD13 = hD13.replace(25, wordLength, solutionDisplay); cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07 << hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15; break; case 2: hD10 = hD10.replace(12, 3, head); hD11 = hD11.replace(12, 3, leftArm + neck + rightArm); hD12 = hD12.replace(13, 1, torso); hD13 = hD13.replace(25, wordLength, solutionDisplay); cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07 << hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15; break; case 1: hD10 = hD10.replace(12, 3, head); hD11 = hD11.replace(12, 3, leftArm + neck + rightArm); hD12 = hD12.replace(13, 1, torso); hD13 = hD13.replace(12, 2, leftLeg + space); hD13 = hD13.replace(25, wordLength, solutionDisplay); cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07 << hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15; break; case 0: hD10 = hD10.replace(12, 3, head); hD11 = hD11.replace(12, 3, leftArm + neck + rightArm); hD12 = hD12.replace(13, 1, torso); hD13 = hD13.replace(12, 3, leftLeg + space + rightLeg); hD13 = hD13.replace(25, wordLength, solutionDisplay); hD14 = hD14.replace(31, 10, youLose); cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07 << hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15; break; default: cout << "\aError!"; break; } } else if (winningResult == 1) { hD13 = hD13.replace(25, wordLength, solutionDisplay); hD14 = hD14.replace(31, 10, youWon); cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07 << hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15; } }<|endoftext|>
<commit_before><commit_msg>Update TGClient.cxx<commit_after><|endoftext|>
<commit_before>/* This file is part of the Grantlee template system. Copyright (c) 2008,2010 Stephen Kelly <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the Licence, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "markupdirector.h" #include "markupdirector_p.h" using namespace Grantlee; void MarkupDirectorPrivate::processClosingElements( QTextBlock::iterator it ) { Q_Q( AbstractMarkupBuilder ); // The order of closing elements is determined by the order they were opened in. // The order of opened elements is in the openElements member list. // see testDifferentStartDoubleFinish and testDifferentStartDoubleFinishReverseOrder if ( m_openElements.isEmpty() ) return; QSet<int> elementsToClose = getElementsToClose( it ); int previousSize; int remainingSize = elementsToClose.size(); while ( !elementsToClose.isEmpty() ) { int tag = m_openElements.last(); if ( elementsToClose.contains( tag ) ) { switch ( tag ) { case Strong: q->endStrong(); break; case Emph: q->endEmph(); break; case Underline: q->endUnderline(); break; case StrikeOut: q->endStrikeout(); break; case SpanFontPointSize: q->endFontPointSize(); break; case SpanFontFamily: q->endFontFamily(); break; case SpanBackground: q->endBackground(); break; case SpanForeground: q->endForeground(); break; case Anchor: q->endAnchor(); break; case SubScript: q->endSubscript(); break; case SuperScript: q->endSuperscript(); break; default: break; } m_openElements.removeLast(); elementsToClose.remove( tag ); } previousSize = remainingSize; remainingSize = elementsToClose.size(); if ( previousSize == remainingSize ) { // Iterated once through without closing any tags. // This means that there's overlap in the tags, such as // 'text with <b>some <i>formatting</i></b><i> tags</i>' // See testOverlap. // The top element in openElements must be a blocker, so close it on next iteration. elementsToClose.insert( m_openElements.last() ); } } } QSet< int > MarkupDirectorPrivate::getElementsToClose( QTextBlock::iterator it ) const { QSet<int> closedElements; if ( it.atEnd() ) { // End of block?. Close all open tags. QSet< int > elementsToClose = m_openElements.toSet(); return elementsToClose.unite( m_elementsToOpen ); } QTextFragment fragment = it.fragment(); if ( !fragment.isValid() ) return closedElements; QTextCharFormat fragmentFormat = fragment.charFormat(); int fontWeight = fragmentFormat.fontWeight(); bool fontItalic = fragmentFormat.fontItalic(); bool fontUnderline = fragmentFormat.fontUnderline(); bool fontStrikeout = fragmentFormat.fontStrikeOut(); QBrush fontForeground = fragmentFormat.foreground(); QBrush fontBackground = fragmentFormat.background(); QString fontFamily = fragmentFormat.fontFamily(); int fontPointSize = fragmentFormat.font().pointSize(); QString anchorHref = fragmentFormat.anchorHref(); QTextCharFormat::VerticalAlignment vAlign = fragmentFormat.verticalAlignment(); bool superscript = ( vAlign == QTextCharFormat::AlignSuperScript ); bool subscript = ( vAlign == QTextCharFormat::AlignSubScript ); if ( !fontStrikeout && ( m_openElements.contains( StrikeOut ) || m_elementsToOpen.contains( StrikeOut ) ) ) { closedElements.insert( StrikeOut ); } if ( !fontUnderline && ( m_openElements.contains( Underline ) || m_elementsToOpen.contains( Underline ) ) && !( m_openElements.contains( Anchor ) || m_elementsToOpen.contains( Anchor ) ) ) { closedElements.insert( Underline ); } if ( !fontItalic && ( m_openElements.contains( Emph ) || m_elementsToOpen.contains( Emph ) ) ) { closedElements.insert( Emph ); } if ( fontWeight != QFont::Bold && ( m_openElements.contains( Strong ) || m_elementsToOpen.contains( Strong ) ) ) { closedElements.insert( Strong ); } if (( m_openElements.contains( SpanFontPointSize ) || m_elementsToOpen.contains( SpanFontPointSize ) ) && ( m_openFontPointSize != fontPointSize ) ) { closedElements.insert( SpanFontPointSize ); } if (( m_openElements.contains( SpanFontFamily ) || m_elementsToOpen.contains( SpanFontFamily ) ) && ( m_openFontFamily != fontFamily ) ) { closedElements.insert( SpanFontFamily ); } if (( m_openElements.contains( SpanBackground ) && ( m_openBackground != fontBackground ) ) || ( m_elementsToOpen.contains( SpanBackground ) && ( m_backgroundToOpen != fontBackground ) ) ) { closedElements.insert( SpanBackground ); } if (( m_openElements.contains( SpanForeground ) && ( m_openForeground != fontForeground ) ) || ( m_elementsToOpen.contains( SpanForeground ) && ( m_foregroundToOpen != fontForeground ) ) ) { closedElements.insert( SpanForeground ); } if (( m_openElements.contains( Anchor ) && ( m_openAnchorHref != anchorHref ) ) || ( m_elementsToOpen.contains( Anchor ) && ( m_anchorHrefToOpen != anchorHref ) ) ) { closedElements.insert( Anchor ); } if ( !subscript && ( m_openElements.contains( SubScript ) || m_elementsToOpen.contains( SubScript ) ) ) { closedElements.insert( SubScript ); } if ( !superscript && ( m_openElements.contains( SuperScript ) || m_elementsToOpen.contains( SuperScript ) ) ) { closedElements.insert( SuperScript ); } return closedElements; } QList< int > MarkupDirectorPrivate::sortOpeningOrder( QSet< int > openingOrder, QTextBlock::iterator it ) const { QList< int > sortedOpenedElements; // This is an insertion sort in a way. elements in openingOrder are assumed to be out of order. // The rest of the block is traversed until there are no more elements to sort, or the end is reached. while ( openingOrder.size() != 0 ) { if ( !it.atEnd() ) { it++; if ( !it.atEnd() ) { // Because I've iterated, this returns the elements that will // be closed by the next fragment. QSet<int> elementsToClose = getElementsToClose( it ); // The exact order these are opened in is irrelevant, as all will be closed on the same block. // See testDoubleFormat. Q_FOREACH( int tag, elementsToClose ) { if ( openingOrder.remove( tag ) ) { sortedOpenedElements.prepend( tag ); } } } } else { // End of block. Need to close all open elements. // Order irrelevant in this case. Q_FOREACH( int tag, openingOrder ) { sortedOpenedElements.prepend( tag ); } break; } } return sortedOpenedElements; } QList< int > MarkupDirectorPrivate::getElementsToOpen( QTextBlock::iterator it ) { QTextFragment fragment = it.fragment(); if ( !fragment.isValid() ) { return QList< int >(); } QTextCharFormat fragmentFormat = fragment.charFormat(); int fontWeight = fragmentFormat.fontWeight(); bool fontItalic = fragmentFormat.fontItalic(); bool fontUnderline = fragmentFormat.fontUnderline(); bool fontStrikeout = fragmentFormat.fontStrikeOut(); QBrush fontForeground = fragmentFormat.foreground(); QBrush fontBackground = fragmentFormat.background(); QString fontFamily = fragmentFormat.fontFamily(); int fontPointSize = fragmentFormat.font().pointSize(); QString anchorHref = fragmentFormat.anchorHref(); QTextCharFormat::VerticalAlignment vAlign = fragmentFormat.verticalAlignment(); bool superscript = ( vAlign == QTextCharFormat::AlignSuperScript ); bool subscript = ( vAlign == QTextCharFormat::AlignSubScript ); if ( superscript && !( m_openElements.contains( SuperScript ) ) ) { m_elementsToOpen.insert( SuperScript ); } if ( subscript && !( m_openElements.contains( SubScript ) ) ) { m_elementsToOpen.insert( SubScript ); } if ( !anchorHref.isEmpty() && !( m_openElements.contains( Anchor ) ) && ( m_openAnchorHref != anchorHref ) ) { m_elementsToOpen.insert( Anchor ); m_anchorHrefToOpen = anchorHref; } if ( fontForeground != Qt::NoBrush && !( m_openElements.contains( SpanForeground ) ) // Can only open one foreground element at a time. && ( fontForeground != m_openForeground ) && !(( m_openElements.contains( Anchor ) // If inside an anchor, only open a foreground span tag if || m_elementsToOpen.contains( Anchor ) ) // it is not blue. Qt sort of enforces links being blue && ( fontForeground == Qt::blue ) ) // and underlined. See qt bug 203510. ) { m_elementsToOpen.insert( SpanForeground ); m_foregroundToOpen = fontForeground; } if ( fontBackground != Qt::NoBrush && !( m_openElements.contains( SpanBackground ) ) && ( fontBackground != m_openBackground ) ) { m_elementsToOpen.insert( SpanBackground ); m_backgroundToOpen = fontBackground; } if ( !fontFamily.isEmpty() && !( m_openElements.contains( SpanFontFamily ) ) && ( fontFamily != m_openFontFamily ) ) { m_elementsToOpen.insert( SpanFontFamily ); m_fontFamilyToOpen = fontFamily; } if (( QTextCharFormat().font().pointSize() != fontPointSize ) // Different from the default. && !( m_openElements.contains( SpanFontPointSize ) ) && ( fontPointSize != m_openFontPointSize ) ) { m_elementsToOpen.insert( SpanFontPointSize ); m_fontPointSizeToOpen = fontPointSize; } // Only open a new bold tag if one is not already open. // eg, <b>some <i>mixed</i> format</b> should be as is, rather than // <b>some </b><b><i>mixed</i></b><b> format</b> if ( fontWeight == QFont::Bold && !( m_openElements.contains( Strong ) ) ) { m_elementsToOpen.insert( Strong ); } if ( fontItalic && !( m_openElements.contains( Emph ) ) ) { m_elementsToOpen.insert( Emph ); } if ( fontUnderline && !( m_openElements.contains( Underline ) ) && !( m_openElements.contains( Anchor ) || m_elementsToOpen.contains( Anchor ) ) // Can't change the underline state of a link. ) { m_elementsToOpen.insert( Underline ); } if ( fontStrikeout && !( m_openElements.contains( StrikeOut ) ) ) { m_elementsToOpen.insert( StrikeOut ); } if ( m_elementsToOpen.size() <= 1 ) { return m_elementsToOpen.toList(); } return sortOpeningOrder( m_elementsToOpen, it ); } void MarkupDirectorPrivate::processOpeningElements( QTextBlock::iterator it ) { Q_Q( AbstractMarkupBuilder ); QTextFragment fragment = it.fragment(); if ( !fragment.isValid() ) return; QTextCharFormat fragmentFormat = fragment.charFormat(); QList<int> elementsToOpenList = getElementsToOpen( it ); Q_FOREACH( int tag, elementsToOpenList ) { switch ( tag ) { case Strong: q->beginStrong(); break; case Emph: q->beginEmph(); break; case Underline: q->beginUnderline(); break; case StrikeOut: q->beginStrikeout(); break; case SpanFontPointSize: q->beginFontPointSize( fragmentFormat.font().pointSize() ); m_openFontPointSize = fragmentFormat.font().pointSize(); break; case SpanFontFamily: q->beginFontFamily( fragmentFormat.fontFamily() ); m_openFontFamily = fragmentFormat.fontFamily(); break; case SpanBackground: q->beginBackground( fragmentFormat.background() ); m_openBackground = fragmentFormat.background(); break; case SpanForeground: q->beginForeground( fragmentFormat.foreground() ); m_openForeground = fragmentFormat.foreground(); break; case Anchor: { // TODO: Multiple anchor names here. QStringList anchorNames = fragmentFormat.anchorNames(); if ( !anchorNames.isEmpty() ) { while ( !anchorNames.isEmpty() ) { QString n = anchorNames.last(); anchorNames.removeLast(); if ( anchorNames.isEmpty() ) { // Doesn't matter if anchorHref is empty. q->beginAnchor( fragmentFormat.anchorHref(), n ); break; } else { // Empty <a> tags allow multiple names for the same section. q->beginAnchor( QString(), n ); q->endAnchor(); } } } else { q->beginAnchor( fragmentFormat.anchorHref() ); } m_openAnchorHref = fragmentFormat.anchorHref(); break; } case SuperScript: q->beginSuperscript(); break; case SubScript: q->beginSubscript(); break; default: break; } m_openElements.append( tag ); m_elementsToOpen.remove( tag ); } } <commit_msg>Remove a style specific hack. Make test pass with Qt 4.6<commit_after>/* This file is part of the Grantlee template system. Copyright (c) 2008,2010 Stephen Kelly <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the Licence, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "markupdirector.h" #include "markupdirector_p.h" using namespace Grantlee; void MarkupDirectorPrivate::processClosingElements( QTextBlock::iterator it ) { Q_Q( AbstractMarkupBuilder ); // The order of closing elements is determined by the order they were opened in. // The order of opened elements is in the openElements member list. // see testDifferentStartDoubleFinish and testDifferentStartDoubleFinishReverseOrder if ( m_openElements.isEmpty() ) return; QSet<int> elementsToClose = getElementsToClose( it ); int previousSize; int remainingSize = elementsToClose.size(); while ( !elementsToClose.isEmpty() ) { int tag = m_openElements.last(); if ( elementsToClose.contains( tag ) ) { switch ( tag ) { case Strong: q->endStrong(); break; case Emph: q->endEmph(); break; case Underline: q->endUnderline(); break; case StrikeOut: q->endStrikeout(); break; case SpanFontPointSize: q->endFontPointSize(); break; case SpanFontFamily: q->endFontFamily(); break; case SpanBackground: q->endBackground(); break; case SpanForeground: q->endForeground(); break; case Anchor: q->endAnchor(); break; case SubScript: q->endSubscript(); break; case SuperScript: q->endSuperscript(); break; default: break; } m_openElements.removeLast(); elementsToClose.remove( tag ); } previousSize = remainingSize; remainingSize = elementsToClose.size(); if ( previousSize == remainingSize ) { // Iterated once through without closing any tags. // This means that there's overlap in the tags, such as // 'text with <b>some <i>formatting</i></b><i> tags</i>' // See testOverlap. // The top element in openElements must be a blocker, so close it on next iteration. elementsToClose.insert( m_openElements.last() ); } } } QSet< int > MarkupDirectorPrivate::getElementsToClose( QTextBlock::iterator it ) const { QSet<int> closedElements; if ( it.atEnd() ) { // End of block?. Close all open tags. QSet< int > elementsToClose = m_openElements.toSet(); return elementsToClose.unite( m_elementsToOpen ); } QTextFragment fragment = it.fragment(); if ( !fragment.isValid() ) return closedElements; QTextCharFormat fragmentFormat = fragment.charFormat(); int fontWeight = fragmentFormat.fontWeight(); bool fontItalic = fragmentFormat.fontItalic(); bool fontUnderline = fragmentFormat.fontUnderline(); bool fontStrikeout = fragmentFormat.fontStrikeOut(); QBrush fontForeground = fragmentFormat.foreground(); QBrush fontBackground = fragmentFormat.background(); QString fontFamily = fragmentFormat.fontFamily(); int fontPointSize = fragmentFormat.font().pointSize(); QString anchorHref = fragmentFormat.anchorHref(); QTextCharFormat::VerticalAlignment vAlign = fragmentFormat.verticalAlignment(); bool superscript = ( vAlign == QTextCharFormat::AlignSuperScript ); bool subscript = ( vAlign == QTextCharFormat::AlignSubScript ); if ( !fontStrikeout && ( m_openElements.contains( StrikeOut ) || m_elementsToOpen.contains( StrikeOut ) ) ) { closedElements.insert( StrikeOut ); } if ( !fontUnderline && ( m_openElements.contains( Underline ) || m_elementsToOpen.contains( Underline ) ) && !( m_openElements.contains( Anchor ) || m_elementsToOpen.contains( Anchor ) ) ) { closedElements.insert( Underline ); } if ( !fontItalic && ( m_openElements.contains( Emph ) || m_elementsToOpen.contains( Emph ) ) ) { closedElements.insert( Emph ); } if ( fontWeight != QFont::Bold && ( m_openElements.contains( Strong ) || m_elementsToOpen.contains( Strong ) ) ) { closedElements.insert( Strong ); } if (( m_openElements.contains( SpanFontPointSize ) || m_elementsToOpen.contains( SpanFontPointSize ) ) && ( m_openFontPointSize != fontPointSize ) ) { closedElements.insert( SpanFontPointSize ); } if (( m_openElements.contains( SpanFontFamily ) || m_elementsToOpen.contains( SpanFontFamily ) ) && ( m_openFontFamily != fontFamily ) ) { closedElements.insert( SpanFontFamily ); } if (( m_openElements.contains( SpanBackground ) && ( m_openBackground != fontBackground ) ) || ( m_elementsToOpen.contains( SpanBackground ) && ( m_backgroundToOpen != fontBackground ) ) ) { closedElements.insert( SpanBackground ); } if (( m_openElements.contains( SpanForeground ) && ( m_openForeground != fontForeground ) ) || ( m_elementsToOpen.contains( SpanForeground ) && ( m_foregroundToOpen != fontForeground ) ) ) { closedElements.insert( SpanForeground ); } if (( m_openElements.contains( Anchor ) && ( m_openAnchorHref != anchorHref ) ) || ( m_elementsToOpen.contains( Anchor ) && ( m_anchorHrefToOpen != anchorHref ) ) ) { closedElements.insert( Anchor ); } if ( !subscript && ( m_openElements.contains( SubScript ) || m_elementsToOpen.contains( SubScript ) ) ) { closedElements.insert( SubScript ); } if ( !superscript && ( m_openElements.contains( SuperScript ) || m_elementsToOpen.contains( SuperScript ) ) ) { closedElements.insert( SuperScript ); } return closedElements; } QList< int > MarkupDirectorPrivate::sortOpeningOrder( QSet< int > openingOrder, QTextBlock::iterator it ) const { QList< int > sortedOpenedElements; // This is an insertion sort in a way. elements in openingOrder are assumed to be out of order. // The rest of the block is traversed until there are no more elements to sort, or the end is reached. while ( openingOrder.size() != 0 ) { if ( !it.atEnd() ) { it++; if ( !it.atEnd() ) { // Because I've iterated, this returns the elements that will // be closed by the next fragment. QSet<int> elementsToClose = getElementsToClose( it ); // The exact order these are opened in is irrelevant, as all will be closed on the same block. // See testDoubleFormat. Q_FOREACH( int tag, elementsToClose ) { if ( openingOrder.remove( tag ) ) { sortedOpenedElements.prepend( tag ); } } } } else { // End of block. Need to close all open elements. // Order irrelevant in this case. Q_FOREACH( int tag, openingOrder ) { sortedOpenedElements.prepend( tag ); } break; } } return sortedOpenedElements; } QList< int > MarkupDirectorPrivate::getElementsToOpen( QTextBlock::iterator it ) { QTextFragment fragment = it.fragment(); if ( !fragment.isValid() ) { return QList< int >(); } QTextCharFormat fragmentFormat = fragment.charFormat(); int fontWeight = fragmentFormat.fontWeight(); bool fontItalic = fragmentFormat.fontItalic(); bool fontUnderline = fragmentFormat.fontUnderline(); bool fontStrikeout = fragmentFormat.fontStrikeOut(); QBrush fontForeground = fragmentFormat.foreground(); QBrush fontBackground = fragmentFormat.background(); QString fontFamily = fragmentFormat.fontFamily(); int fontPointSize = fragmentFormat.font().pointSize(); QString anchorHref = fragmentFormat.anchorHref(); QTextCharFormat::VerticalAlignment vAlign = fragmentFormat.verticalAlignment(); bool superscript = ( vAlign == QTextCharFormat::AlignSuperScript ); bool subscript = ( vAlign == QTextCharFormat::AlignSubScript ); if ( superscript && !( m_openElements.contains( SuperScript ) ) ) { m_elementsToOpen.insert( SuperScript ); } if ( subscript && !( m_openElements.contains( SubScript ) ) ) { m_elementsToOpen.insert( SubScript ); } if ( !anchorHref.isEmpty() && !( m_openElements.contains( Anchor ) ) && ( m_openAnchorHref != anchorHref ) ) { m_elementsToOpen.insert( Anchor ); m_anchorHrefToOpen = anchorHref; } if ( fontForeground != Qt::NoBrush && !( m_openElements.contains( SpanForeground ) ) // Can only open one foreground element at a time. && ( fontForeground != m_openForeground ) && !(( m_openElements.contains( Anchor ) // Links can't have a foreground color. || m_elementsToOpen.contains( Anchor ) ) ) ) { m_elementsToOpen.insert( SpanForeground ); m_foregroundToOpen = fontForeground; } if ( fontBackground != Qt::NoBrush && !( m_openElements.contains( SpanBackground ) ) && ( fontBackground != m_openBackground ) ) { m_elementsToOpen.insert( SpanBackground ); m_backgroundToOpen = fontBackground; } if ( !fontFamily.isEmpty() && !( m_openElements.contains( SpanFontFamily ) ) && ( fontFamily != m_openFontFamily ) ) { m_elementsToOpen.insert( SpanFontFamily ); m_fontFamilyToOpen = fontFamily; } if (( QTextCharFormat().font().pointSize() != fontPointSize ) // Different from the default. && !( m_openElements.contains( SpanFontPointSize ) ) && ( fontPointSize != m_openFontPointSize ) ) { m_elementsToOpen.insert( SpanFontPointSize ); m_fontPointSizeToOpen = fontPointSize; } // Only open a new bold tag if one is not already open. // eg, <b>some <i>mixed</i> format</b> should be as is, rather than // <b>some </b><b><i>mixed</i></b><b> format</b> if ( fontWeight == QFont::Bold && !( m_openElements.contains( Strong ) ) ) { m_elementsToOpen.insert( Strong ); } if ( fontItalic && !( m_openElements.contains( Emph ) ) ) { m_elementsToOpen.insert( Emph ); } if ( fontUnderline && !( m_openElements.contains( Underline ) ) && !( m_openElements.contains( Anchor ) || m_elementsToOpen.contains( Anchor ) ) // Can't change the underline state of a link. ) { m_elementsToOpen.insert( Underline ); } if ( fontStrikeout && !( m_openElements.contains( StrikeOut ) ) ) { m_elementsToOpen.insert( StrikeOut ); } if ( m_elementsToOpen.size() <= 1 ) { return m_elementsToOpen.toList(); } return sortOpeningOrder( m_elementsToOpen, it ); } void MarkupDirectorPrivate::processOpeningElements( QTextBlock::iterator it ) { Q_Q( AbstractMarkupBuilder ); QTextFragment fragment = it.fragment(); if ( !fragment.isValid() ) return; QTextCharFormat fragmentFormat = fragment.charFormat(); QList<int> elementsToOpenList = getElementsToOpen( it ); Q_FOREACH( int tag, elementsToOpenList ) { switch ( tag ) { case Strong: q->beginStrong(); break; case Emph: q->beginEmph(); break; case Underline: q->beginUnderline(); break; case StrikeOut: q->beginStrikeout(); break; case SpanFontPointSize: q->beginFontPointSize( fragmentFormat.font().pointSize() ); m_openFontPointSize = fragmentFormat.font().pointSize(); break; case SpanFontFamily: q->beginFontFamily( fragmentFormat.fontFamily() ); m_openFontFamily = fragmentFormat.fontFamily(); break; case SpanBackground: q->beginBackground( fragmentFormat.background() ); m_openBackground = fragmentFormat.background(); break; case SpanForeground: q->beginForeground( fragmentFormat.foreground() ); m_openForeground = fragmentFormat.foreground(); break; case Anchor: { // TODO: Multiple anchor names here. QStringList anchorNames = fragmentFormat.anchorNames(); if ( !anchorNames.isEmpty() ) { while ( !anchorNames.isEmpty() ) { QString n = anchorNames.last(); anchorNames.removeLast(); if ( anchorNames.isEmpty() ) { // Doesn't matter if anchorHref is empty. q->beginAnchor( fragmentFormat.anchorHref(), n ); break; } else { // Empty <a> tags allow multiple names for the same section. q->beginAnchor( QString(), n ); q->endAnchor(); } } } else { q->beginAnchor( fragmentFormat.anchorHref() ); } m_openAnchorHref = fragmentFormat.anchorHref(); break; } case SuperScript: q->beginSuperscript(); break; case SubScript: q->beginSubscript(); break; default: break; } m_openElements.append( tag ); m_elementsToOpen.remove( tag ); } } <|endoftext|>
<commit_before>#include <SFML/Graphics.hpp> #include <iostream> using namespace std; #define M_PI 3.14f #define LIGHT_RADIUS 400 struct Line { sf::Vector2f a, b; inline void create(float x1, float y1, float x2, float y2) { a = { x1, y1 }; b = { x2, y2 }; } inline void create(sf::Vector2f A, sf::Vector2f B) { a = A; b = B; } void draw(sf::RenderTarget& tgt, sf::Color clr) { vector<sf::Vertex> arr = { sf::Vertex(a, clr), sf::Vertex(b, clr) }; tgt.draw(&arr[0], arr.size(), sf::Lines); } }; struct Object { std::vector<sf::Vector2f> points; inline void add(float x, float y) { points.push_back(sf::Vector2f(x, y)); } inline int getLineCount() { return points.size(); } inline Line getLine(int i) { Line ret; ret.create(points[i], points[(i == points.size() - 1) ? 0 : (i + 1)]); return ret; } void draw(sf::RenderTarget& tgt) { std::vector<sf::Vertex> varr(points.size()); for (int i = 0; i < varr.size(); i++) { varr[i].position = points[i]; varr[i].color = sf::Color::Green; } varr.push_back(sf::Vertex(points[0], sf::Color::Green)); tgt.draw(&varr[0], varr.size(), sf::LineStrip); } }; inline float length(sf::Vector2f p1, sf::Vector2f p2) { return sqrt(pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2)); } inline float crossProduct(sf::Vector2f v, sf::Vector2f w) { return v.x*w.y - v.y*w.x; } bool doIntersect(Line l1, Line l2, sf::Vector2f& ret) { sf::Vector2f p = l1.a; sf::Vector2f q = l2.a; sf::Vector2f r = l1.b - p; sf::Vector2f s = l2.b - q; //p + T * r = q + U * s float T = crossProduct((q - p), s) / crossProduct(r, s); float U = crossProduct((q - p), r) / crossProduct(r, s); // collinear if (crossProduct(r, s) == 0 && crossProduct((q - p), r) == 0) return false; // i guess i can ignore (for now) if two lines are collinear else if (crossProduct(r, s) != 0 && (T >= 0 && T <= 1) && (U >= 0 && U <= 1)) { // parallel - not intersecting ret = q + U*s; return true; // pointOfIntersection = q + U*s; } return false; } int main() { sf::RenderWindow wnd(sf::VideoMode(800, 600), "Intersection"); sf::Event event; Line q; q.create(150, 50, 250, 100); vector<Object> objs(2); objs[0].add(400, 300); objs[0].add(400, 315); objs[0].add(375, 335); objs[0].add(400, 350); objs[0].add(450, 350); objs[0].add(450, 300); objs[0].add(425, 275); objs[1].add(550, 500); objs[1].add(550, 700); objs[1].add(750, 700); objs[1].add(750, 500); sf::CircleShape inter; inter.setRadius(4); inter.setOrigin(4, 4); while (wnd.isOpen()) { while (wnd.pollEvent(event)) { if (event.type == sf::Event::Closed) wnd.close(); else if (event.type == sf::Event::Resized) wnd.setView(sf::View(sf::FloatRect(0, 0, event.size.width, event.size.height))); } wnd.clear(); q.a = sf::Vector2f(sf::Mouse::getPosition(wnd)); std::vector<sf::Vertex> varr; varr.push_back(sf::Vertex(q.a, sf::Color::White)); for (float angle = 0; angle < 2 * M_PI; angle += 2 * M_PI / 32) { sf::Vector2f resPos = q.b = sf::Vector2f(q.a.x + cos(angle) * LIGHT_RADIUS, q.a.y + sin(angle) * LIGHT_RADIUS); for (int j = 0; j < objs.size(); j++) { sf::Vector2f interPos; int cnt = objs[j].getLineCount(); for (int i = 0; i < cnt; i++) if (doIntersect(q, objs[j].getLine(i), interPos)) if (length(q.a, resPos) > length(q.a, interPos)) resPos = interPos; } inter.setPosition(resPos); q.b = resPos; // RADIAL GRADIENT: sf::Color resColor(255, 255, 255, 255 - length(q.a, q.b)*(255.0f / LIGHT_RADIUS)); varr.push_back(sf::Vertex(resPos, resColor)); //q.draw(wnd, sf::Color::Red); //wnd.draw(inter); } varr.push_back(varr[1]); wnd.draw(&varr[0], varr.size(), sf::TrianglesFan); for (int i = 0; i < objs.size(); i++) objs[i].draw(wnd); wnd.display(); } return 0; }<commit_msg>Light detail (1/2)<commit_after>#include <SFML/Graphics.hpp> #include <unordered_map> #include <iostream> #define _USE_MATH_DEFINES #include <math.h> using namespace std; #define LIGHT_RADIUS 400 enum LightDetail { LIGHTDETAIL_LOW, LIGHTDETAIL_MEDIUM, LIGHTDETAIL_HIGH }; struct Line { sf::Vector2f a, b; inline void create(float x1, float y1, float x2, float y2) { a = { x1, y1 }; b = { x2, y2 }; } inline void create(sf::Vector2f A, sf::Vector2f B) { a = A; b = B; } void draw(sf::RenderTarget& tgt, sf::Color clr) { vector<sf::Vertex> arr = { sf::Vertex(a, clr), sf::Vertex(b, clr) }; tgt.draw(&arr[0], arr.size(), sf::Lines); } }; struct Object { std::vector<sf::Vector2f> points; inline void add(float x, float y) { points.push_back(sf::Vector2f(x, y)); } inline int getLineCount() { return points.size(); } Line getLine(int i) { Line ret; ret.create(points[i], points[(i == points.size() - 1) ? 0 : (i + 1)]); return ret; } void draw(sf::RenderTarget& tgt) { std::vector<sf::Vertex> varr(points.size()); for (int i = 0; i < varr.size(); i++) { varr[i].position = points[i]; varr[i].color = sf::Color::Green; } varr.push_back(sf::Vertex(points[0], sf::Color::Green)); tgt.draw(&varr[0], varr.size(), sf::LineStrip); } }; inline float length(sf::Vector2f p1, sf::Vector2f p2) { return sqrt(pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2)); } inline float crossProduct(sf::Vector2f v, sf::Vector2f w) { return v.x*w.y - v.y*w.x; } bool doIntersect(Line l1, Line l2, sf::Vector2f& ret) { sf::Vector2f p = l1.a; sf::Vector2f q = l2.a; sf::Vector2f r = l1.b - p; sf::Vector2f s = l2.b - q; //p + T * r = q + U * s float T = crossProduct((q - p), s) / crossProduct(r, s); float U = crossProduct((q - p), r) / crossProduct(r, s); // collinear if (crossProduct(r, s) == 0 && crossProduct((q - p), r) == 0) return false; // i guess i can ignore (for now) if two lines are collinear else if (crossProduct(r, s) != 0 && (T >= 0 && T <= 1) && (U >= 0 && U <= 1)) { // intersecting ret = q + U*s; return true; // pointOfIntersection = q + U*s; } return false; } int main() { sf::RenderWindow wnd(sf::VideoMode(800, 600), "Intersection"); sf::Event event; Line q; q.create(150, 50, 250, 100); vector<Object> objs(2); objs[0].add(400, 300); objs[0].add(400, 315); objs[0].add(375, 335); objs[0].add(400, 350); objs[0].add(450, 350); objs[0].add(450, 300); objs[0].add(425, 275); objs[1].add(550, 500); objs[1].add(550, 700); objs[1].add(750, 700); objs[1].add(750, 500); sf::CircleShape inter; inter.setRadius(4); inter.setOrigin(4, 4); sf::Clock fpsClock; float fps; char precisionMode = LIGHTDETAIL_MEDIUM; while (wnd.isOpen()) { while (wnd.pollEvent(event)) { if (event.type == sf::Event::Closed) wnd.close(); else if (event.type == sf::Event::Resized) wnd.setView(sf::View(sf::FloatRect(0, 0, event.size.width, event.size.height))); else if (event.type == sf::Event::KeyPressed) printf("FPS: %.3fs\n", fps); } fps = fpsClock.restart().asMilliseconds() / 1000.0f; wnd.clear(); q.a = sf::Vector2f(sf::Mouse::getPosition(wnd)); bool skipObject = false; //std::vector<sf::Vertex> varr; //varr.push_back(sf::Vertex(q.a, sf::Color::White)); unordered_map<int, bool> highDefColObjs; for (float angle = 0; angle < 2 * M_PI; angle += 2 * M_PI / 32) { sf::Vector2f resPos = q.b = sf::Vector2f(q.a.x + cos(angle) * LIGHT_RADIUS, q.a.y + sin(angle) * LIGHT_RADIUS); skipObject = false; for (int j = 0; j < objs.size(); j++) { sf::Vector2f interPos; int cnt = objs[j].getLineCount(); for (int i = 0; i < cnt; i++) { if (doIntersect(q, objs[j].getLine(i), interPos)) { if (length(q.a, resPos) > length(q.a, interPos)) { resPos = interPos; highDefColObjs[j] = true; } skipObject = true; } } } if (skipObject && precisionMode == LIGHTDETAIL_MEDIUM) continue; inter.setPosition(resPos); q.b = resPos; // RADIAL GRADIENT: //sf::Color resColor(255, 255, 255, 255 - length(q.a, q.b)*(255.0f / LIGHT_RADIUS)); //varr.push_back(sf::Vertex(resPos, resColor)); q.draw(wnd, sf::Color::Red); wnd.draw(inter); } if (precisionMode > LIGHTDETAIL_LOW) { for (int j = 0; j < objs.size(); j++) { if (!highDefColObjs[j]) continue; Object* obj = &objs[j]; for (int i = 0; i < obj->points.size(); i++) { sf::Vector2f point = obj->points[i]; if (length(q.a, point) > LIGHT_RADIUS) continue; float newAngle = atan2(point.y - q.a.y, point.x - q.a.x); printf("%.4f\n", newAngle); // TODO: (newAngle - 0.01f) and (newAngle + 0.01f) cases q.b = sf::Vector2f(q.a.x + cos(newAngle) * LIGHT_RADIUS, q.a.y + sin(newAngle) * LIGHT_RADIUS); sf::Vector2f interPos, resPos = q.b; //for (int k = std::max(i - 1, 0); k < std::min(i + 1, (int)obj->points.size()); k++) { for (int k = 0; k < (int)obj->points.size(); k++) { if (doIntersect(q, obj->getLine(k), interPos)) { if (length(q.a, resPos) > length(q.a, interPos)) { resPos = interPos; } } } q.b = resPos; q.draw(wnd, sf::Color::Blue); } } } //varr.push_back(varr[1]); //wnd.draw(&varr[0], varr.size(), sf::TrianglesFan); for (int i = 0; i < objs.size(); i++) objs[i].draw(wnd); wnd.display(); } return 0; }<|endoftext|>
<commit_before>/*- * Copyright (c) 2013 David Chisnall * All rights reserved. * * This software was developed by SRI International and the University of * Cambridge Computer Laboratory under DARPA/AFRL contract (FA8750-10-C-0237) * ("CTSRD"), as part of the DARPA CRASH research programme. * * 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 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 AUTHOR 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. * * $FreeBSD$ */ #include "input_buffer.hh" #include <ctype.h> #include <limits.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/mman.h> #include <assert.h> #ifndef MAP_PREFAULT_READ #define MAP_PREFAULT_READ 0 #endif namespace dtc { void input_buffer::skip_spaces() { if (cursor >= size) { return; } if (cursor < 0) { return; } char c = buffer[cursor]; while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\f') || (c == '\v') || (c == '\r')) { cursor++; if (cursor > size) { c = '\0'; } else { c = buffer[cursor]; } } } input_buffer input_buffer::buffer_from_offset(int offset, int s) { if (s == 0) { s = size - offset; } if (offset > size) { return input_buffer(); } if (s > (size-offset)) { return input_buffer(); } return input_buffer(&buffer[offset], s); } bool input_buffer::consume(const char *str) { int len = strlen(str); if (len > size - cursor) { return false; } else { for (int i=0 ; i<len ; ++i) { if (str[i] != buffer[cursor + i]) { return false; } } cursor += len; return true; } return false; } bool input_buffer::consume_integer(long long &outInt) { // The first character must be a digit. Hex and octal strings // are prefixed by 0 and 0x, respectively. if (!isdigit((*this)[0])) { return false; } char *end=0; outInt = strtoll(&buffer[cursor], &end, 0); if (end == &buffer[cursor]) { return false; } cursor = end - buffer; return true; } bool input_buffer::consume_hex_byte(uint8_t &outByte) { if (!ishexdigit((*this)[0]) && !ishexdigit((*this)[1])) { return false; } outByte = (digittoint((*this)[0]) << 4) | digittoint((*this)[1]); cursor += 2; return true; } input_buffer& input_buffer::next_token() { int start; do { start = cursor; skip_spaces(); // Parse /* comments if (((*this)[0] == '/') && ((*this)[1] == '*')) { // eat the start of the comment ++(*this); ++(*this); do { // Find the ending * of */ while ((**this != '\0') && (**this != '*')) { ++(*this); } // Eat the * ++(*this); } while ((**this != '\0') && (**this != '/')); // Eat the / ++(*this); } // Parse // comments if (((*this)[0] == '/') && ((*this)[1] == '/')) { // eat the start of the comment ++(*this); ++(*this); // Find the ending * of */ while (**this != '\n') { ++(*this); } // Eat the \n ++(*this); } } while (start != cursor); return *this; } void input_buffer::parse_error(const char *msg) { int line_count = 1; int line_start = 0; int line_end = cursor; for (int i=cursor ; i>0 ; --i) { if (buffer[i] == '\n') { line_count++; if (line_start == 0) { line_start = i+1; } } } for (int i=cursor+1 ; i<size ; ++i) { if (buffer[i] == '\n') { line_end = i; break; } } fprintf(stderr, "Error on line %d: %s\n", line_count, msg); fwrite(&buffer[line_start], line_end-line_start, 1, stderr); putc('\n', stderr); for (int i=0 ; i<(cursor-line_start) ; ++i) { putc(' ', stderr); } putc('^', stderr); putc('\n', stderr); } void input_buffer::dump() { fprintf(stderr, "Current cursor: %d\n", cursor); fwrite(&buffer[cursor], size-cursor, 1, stderr); } mmap_input_buffer::mmap_input_buffer(int fd) : input_buffer(0, 0) { struct stat sb; if (fstat(fd, &sb)) { perror("Failed to stat file"); } size = sb.st_size; buffer = (const char*)mmap(0, size, PROT_READ, MAP_PREFAULT_READ, fd, 0); if (buffer == 0) { perror("Failed to mmap file"); } } mmap_input_buffer::~mmap_input_buffer() { if (buffer != 0) { munmap((void*)buffer, size); } } stream_input_buffer::stream_input_buffer() : input_buffer(0, 0) { int c; while ((c = fgetc(stdin)) != EOF) { b.push_back(c); } buffer = b.data(); size = b.size(); } } // namespace dtc <commit_msg>Make carets line up in dtc diagnostics if the line starts with a tab.<commit_after>/*- * Copyright (c) 2013 David Chisnall * All rights reserved. * * This software was developed by SRI International and the University of * Cambridge Computer Laboratory under DARPA/AFRL contract (FA8750-10-C-0237) * ("CTSRD"), as part of the DARPA CRASH research programme. * * 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 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 AUTHOR 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. * * $FreeBSD$ */ #include "input_buffer.hh" #include <ctype.h> #include <limits.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/mman.h> #include <assert.h> #ifndef MAP_PREFAULT_READ #define MAP_PREFAULT_READ 0 #endif namespace dtc { void input_buffer::skip_spaces() { if (cursor >= size) { return; } if (cursor < 0) { return; } char c = buffer[cursor]; while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\f') || (c == '\v') || (c == '\r')) { cursor++; if (cursor > size) { c = '\0'; } else { c = buffer[cursor]; } } } input_buffer input_buffer::buffer_from_offset(int offset, int s) { if (s == 0) { s = size - offset; } if (offset > size) { return input_buffer(); } if (s > (size-offset)) { return input_buffer(); } return input_buffer(&buffer[offset], s); } bool input_buffer::consume(const char *str) { int len = strlen(str); if (len > size - cursor) { return false; } else { for (int i=0 ; i<len ; ++i) { if (str[i] != buffer[cursor + i]) { return false; } } cursor += len; return true; } return false; } bool input_buffer::consume_integer(long long &outInt) { // The first character must be a digit. Hex and octal strings // are prefixed by 0 and 0x, respectively. if (!isdigit((*this)[0])) { return false; } char *end=0; outInt = strtoll(&buffer[cursor], &end, 0); if (end == &buffer[cursor]) { return false; } cursor = end - buffer; return true; } bool input_buffer::consume_hex_byte(uint8_t &outByte) { if (!ishexdigit((*this)[0]) && !ishexdigit((*this)[1])) { return false; } outByte = (digittoint((*this)[0]) << 4) | digittoint((*this)[1]); cursor += 2; return true; } input_buffer& input_buffer::next_token() { int start; do { start = cursor; skip_spaces(); // Parse /* comments if (((*this)[0] == '/') && ((*this)[1] == '*')) { // eat the start of the comment ++(*this); ++(*this); do { // Find the ending * of */ while ((**this != '\0') && (**this != '*')) { ++(*this); } // Eat the * ++(*this); } while ((**this != '\0') && (**this != '/')); // Eat the / ++(*this); } // Parse // comments if (((*this)[0] == '/') && ((*this)[1] == '/')) { // eat the start of the comment ++(*this); ++(*this); // Find the ending * of */ while (**this != '\n') { ++(*this); } // Eat the \n ++(*this); } } while (start != cursor); return *this; } void input_buffer::parse_error(const char *msg) { int line_count = 1; int line_start = 0; int line_end = cursor; for (int i=cursor ; i>0 ; --i) { if (buffer[i] == '\n') { line_count++; if (line_start == 0) { line_start = i+1; } } } for (int i=cursor+1 ; i<size ; ++i) { if (buffer[i] == '\n') { line_end = i; break; } } fprintf(stderr, "Error on line %d: %s\n", line_count, msg); fwrite(&buffer[line_start], line_end-line_start, 1, stderr); putc('\n', stderr); for (int i=0 ; i<(cursor-line_start) ; ++i) { char c = (buffer[i+line_start] == '\t') ? '\t' : ' '; putc(c, stderr); } putc('^', stderr); putc('\n', stderr); } void input_buffer::dump() { fprintf(stderr, "Current cursor: %d\n", cursor); fwrite(&buffer[cursor], size-cursor, 1, stderr); } mmap_input_buffer::mmap_input_buffer(int fd) : input_buffer(0, 0) { struct stat sb; if (fstat(fd, &sb)) { perror("Failed to stat file"); } size = sb.st_size; buffer = (const char*)mmap(0, size, PROT_READ, MAP_PREFAULT_READ, fd, 0); if (buffer == 0) { perror("Failed to mmap file"); } } mmap_input_buffer::~mmap_input_buffer() { if (buffer != 0) { munmap((void*)buffer, size); } } stream_input_buffer::stream_input_buffer() : input_buffer(0, 0) { int c; while ((c = fgetc(stdin)) != EOF) { b.push_back(c); } buffer = b.data(); size = b.size(); } } // namespace dtc <|endoftext|>
<commit_before>/* * Copyright (C) 2010-2011 Dmitry Marakasov * * This file is part of glosm. * * glosm 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. * * glosm 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 glosm. If not, see <http://www.gnu.org/licenses/>. */ #include <glosm/SphericalProjection.hh> #include <glosm/geomath.h> #include <cmath> #include <stdexcept> SphericalProjection::SphericalProjection() : Projection(&ProjectImpl, &UnProjectImpl) { } Vector3f SphericalProjection::ProjectImpl(const Vector3i& point, const Vector3i& ref) { double point_angle_x = ((double)point.x - (double)ref.x) * GEOM_DEG_TO_RAD; double point_angle_y = (double)point.y * GEOM_DEG_TO_RAD; double point_height = (double)point.z / GEOM_UNITSINMETER; double ref_angle_y = (double)ref.y * GEOM_DEG_TO_RAD; double ref_height = (double)ref.z / GEOM_UNITSINMETER; Vector3d point_vector( (WGS84_EARTH_EQ_RADIUS + point_height) * sin(point_angle_x) * cos(point_angle_y), (WGS84_EARTH_EQ_RADIUS + point_height) * sin(point_angle_y), (WGS84_EARTH_EQ_RADIUS + point_height) * cos(point_angle_x) * cos(point_angle_y) ); return Vector3f( point_vector.x, point_vector.y * cos(ref_angle_y) - point_vector.z * sin(ref_angle_y), point_vector.y * sin(ref_angle_y) + point_vector.z * cos(ref_angle_y) - WGS84_EARTH_EQ_RADIUS - ref_height ); } Vector3i SphericalProjection::UnProjectImpl(const Vector3f& point, const Vector3i& ref) { throw std::runtime_error("SphericalProjection::UnProjectImpl not implemented"); return Vector3i(); } <commit_msg>~50% more effecient SphericalProjection<commit_after>/* * Copyright (C) 2010-2011 Dmitry Marakasov * * This file is part of glosm. * * glosm 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. * * glosm 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 glosm. If not, see <http://www.gnu.org/licenses/>. */ #include <glosm/SphericalProjection.hh> #include <glosm/geomath.h> #include <cmath> #include <stdexcept> SphericalProjection::SphericalProjection() : Projection(&ProjectImpl, &UnProjectImpl) { } Vector3f SphericalProjection::ProjectImpl(const Vector3i& point, const Vector3i& ref) { double point_angle_x = ((double)point.x - (double)ref.x) * GEOM_DEG_TO_RAD; double point_angle_y = (double)point.y * GEOM_DEG_TO_RAD; double point_height = (double)point.z / GEOM_UNITSINMETER; double ref_angle_y = (double)ref.y * GEOM_DEG_TO_RAD; double ref_height = (double)ref.z / GEOM_UNITSINMETER; /* using sqrt(1-sin^2) instead of cos and vice versa gives * ~30% performance gain (thx Komzpa). Precision loss this * brings should be insignificant */ double cosy = cos(point_angle_y); double sinx = sin(point_angle_x); Vector3d point_vector( (WGS84_EARTH_EQ_RADIUS + point_height) * sinx * cosy, (WGS84_EARTH_EQ_RADIUS + point_height) * sqrt(1.0 - cosy * cosy), (WGS84_EARTH_EQ_RADIUS + point_height) * sqrt(1.0 - sinx * sinx) * cosy ); /* additional ~20% performance gain */ double cosay = cos(ref_angle_y); double sinay = sqrt(1.0 - cosay * cosay); return Vector3f( point_vector.x, point_vector.y * cosay - point_vector.z * sinay, point_vector.y * sinay + point_vector.z * cosay - WGS84_EARTH_EQ_RADIUS - ref_height ); } Vector3i SphericalProjection::UnProjectImpl(const Vector3f& point, const Vector3i& ref) { throw std::runtime_error("SphericalProjection::UnProjectImpl not implemented"); return Vector3i(); } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include "S3ExtWrapper.cpp" #define KEYID "AKIAIAFSMJUMQWXB2PUQ" #define SECRET "oCTLHlu3qJ+lpBH/+JcIlnNuDebFObFNFeNvzBF0" class S3Reader_fake : public S3Reader { public: S3Reader_fake(const char *url); virtual ~S3Reader_fake(); virtual bool Init(int segid, int segnum, int chunksize); virtual bool Destroy(); protected: virtual string getKeyURL(const string key); virtual bool ValidateURL(); }; S3Reader_fake::S3Reader_fake(const char *url) : S3Reader(url) {} S3Reader_fake::~S3Reader_fake() {} bool S3Reader_fake::Destroy() { // reset filedownloader if (this->filedownloader) { this->filedownloader->destroy(); delete this->filedownloader; } // Free keylist if (this->keylist) { delete this->keylist; } return true; } bool S3Reader_fake::Init(int segid, int segnum, int chunksize) { // set segment id and num this->segid = segid; // fake this->segnum = segnum; // fake this->contentindex = this->segid; this->chunksize = chunksize; // Validate url first if (!this->ValidateURL()) { S3ERROR("validate url fail %s\n", this->url.c_str()); } // TODO: As separated function for generating url this->keylist = ListBucket_FakeHTTP("localhost", this->bucket.c_str()); // this->keylist = ListBucket_FakeHTTP("localhost", "metro.pivotal.io"); if (!this->keylist) { return false; } this->getNextDownloader(); return this->filedownloader ? true : false; } string S3Reader_fake::getKeyURL(const string key) { stringstream sstr; sstr << this->schema << "://" << "localhost/"; sstr << this->bucket << "/" << key; return sstr.str(); } bool S3Reader_fake::ValidateURL() { this->schema = "http"; this->region = "raycom"; int ibegin, iend; ibegin = find_Nth(this->url, 3, "/"); iend = find_Nth(this->url, 4, "/"); if ((iend == string::npos) || (ibegin == string::npos)) { return false; } this->bucket = url.substr(ibegin + 1, iend - ibegin - 1); this->prefix = ""; return true; } void ExtWrapperTest(const char *url, uint64_t buffer_size, const char *md5_str, int segid, int segnum, uint64_t chunksize) { InitConfig(NULL, NULL); s3ext_secret = string("SECRET"); s3ext_accessid = string("KEYID"); s3ext_segid = segid; s3ext_segnum = segnum; MD5Calc m; S3ExtBase *myData; uint64_t nread = 0; uint64_t buf_len = buffer_size; char *buf = (char *)malloc(buffer_size); ASSERT_NE((void *)NULL, buf); if (strncmp(url, "http://localhost/", 17) == 0) { myData = new S3Reader_fake(url); } else { myData = new S3Reader(url); } ASSERT_NE((void *)NULL, myData); ASSERT_TRUE(myData->Init(segid, segnum, chunksize)); while (1) { nread = buf_len; ASSERT_TRUE(myData->TransferData(buf, nread)); if (nread == 0) break; m.Update(buf, nread); } EXPECT_STREQ(md5_str, m.Get()); delete myData; free(buf); } #ifdef AWSTEST TEST(ExtWrapper, normal) { ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "138fc555074671912125ba692c678246", 0, 1, 64 * 1024 * 1024); } TEST(ExtWrapper, normal_2segs) { ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "a861acda78891b48b25a2788e028a740", 0, 2, 64 * 1024 * 1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "db05de0ec7e0808268e2363d3572dc7f", 1, 2, 64 * 1024 * 1024); } TEST(ExtWrapper, normal_3segs) { ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "4d9ccad20bca50d2d1bc9c4eb4958e2c", 0, 3, 64 * 1024 * 1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "561597859d093905e2b21e896259ae79", 1, 3, 64 * 1024 * 1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "98d4e5348356ceee46d15c4e5f37845b", 2, 3, 64 * 1024 * 1024); } TEST(ExtWrapper, normal_4segs) { ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "b87b5d79e2bcb8dc1d0fd289fbfa5829", 0, 4, 64 * 1024 * 1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "4df154611d394c60084bb5b97bdb19be", 1, 4, 64 * 1024 * 1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "238affbb831ff27df9d09afeeb2e59f9", 2, 4, 64 * 1024 * 1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "dceb001d03d54d61874d27c9f04596b1", 3, 4, 64 * 1024 * 1024); } #endif // AWSTEST TEST(FakeExtWrapper, simple) { ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "138fc555074671912125ba692c678246", 0, 1, 64 * 1024 * 1024); } TEST(FakeExtWrapper, normal_2segs) { ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "a861acda78891b48b25a2788e028a740", 0, 2, 64 * 1024 * 1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "db05de0ec7e0808268e2363d3572dc7f", 1, 2, 64 * 1024 * 1024); } TEST(FakeExtWrapper, normal_3segs) { ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "4d9ccad20bca50d2d1bc9c4eb4958e2c", 0, 3, 64 * 1024 * 1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "561597859d093905e2b21e896259ae79", 1, 3, 64 * 1024 * 1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "98d4e5348356ceee46d15c4e5f37845b", 2, 3, 64 * 1024 * 1024); } TEST(FakeExtWrapper, normal_4segs) { ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "b87b5d79e2bcb8dc1d0fd289fbfa5829", 0, 4, 64 * 1024 * 1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "4df154611d394c60084bb5b97bdb19be", 1, 4, 64 * 1024 * 1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "238affbb831ff27df9d09afeeb2e59f9", 2, 4, 64 * 1024 * 1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "dceb001d03d54d61874d27c9f04596b1", 3, 4, 64 * 1024 * 1024); } TEST(FakeExtWrapper, bigfile) { ExtWrapperTest("http://localhost/bigfile/", 64 * 1024, "83c7ab787e3f1d1e7880dcae954ab4a4", 0, 1, 64 * 1024 * 1024); } <commit_msg>fix a define issue<commit_after>#include "gtest/gtest.h" #include "S3ExtWrapper.cpp" #define KEYID "AKIAIAFSMJUMQWXB2PUQ" #define SECRET "oCTLHlu3qJ+lpBH/+JcIlnNuDebFObFNFeNvzBF0" class S3Reader_fake : public S3Reader { public: S3Reader_fake(const char *url); virtual ~S3Reader_fake(); virtual bool Init(int segid, int segnum, int chunksize); virtual bool Destroy(); protected: virtual string getKeyURL(const string key); virtual bool ValidateURL(); }; S3Reader_fake::S3Reader_fake(const char *url) : S3Reader(url) {} S3Reader_fake::~S3Reader_fake() {} bool S3Reader_fake::Destroy() { // reset filedownloader if (this->filedownloader) { this->filedownloader->destroy(); delete this->filedownloader; } // Free keylist if (this->keylist) { delete this->keylist; } return true; } bool S3Reader_fake::Init(int segid, int segnum, int chunksize) { // set segment id and num this->segid = segid; // fake this->segnum = segnum; // fake this->contentindex = this->segid; this->chunksize = chunksize; // Validate url first if (!this->ValidateURL()) { S3ERROR("validate url fail %s\n", this->url.c_str()); } // TODO: As separated function for generating url this->keylist = ListBucket_FakeHTTP("localhost", this->bucket.c_str()); // this->keylist = ListBucket_FakeHTTP("localhost", "metro.pivotal.io"); if (!this->keylist) { return false; } this->getNextDownloader(); return this->filedownloader ? true : false; } string S3Reader_fake::getKeyURL(const string key) { stringstream sstr; sstr << this->schema << "://" << "localhost/"; sstr << this->bucket << "/" << key; return sstr.str(); } bool S3Reader_fake::ValidateURL() { this->schema = "http"; this->region = "raycom"; int ibegin, iend; ibegin = find_Nth(this->url, 3, "/"); iend = find_Nth(this->url, 4, "/"); if ((iend == string::npos) || (ibegin == string::npos)) { return false; } this->bucket = url.substr(ibegin + 1, iend - ibegin - 1); this->prefix = ""; return true; } void ExtWrapperTest(const char *url, uint64_t buffer_size, const char *md5_str, int segid, int segnum, uint64_t chunksize) { InitConfig(NULL, NULL); s3ext_secret = string(SECRET); s3ext_accessid = string(KEYID); s3ext_segid = segid; s3ext_segnum = segnum; MD5Calc m; S3ExtBase *myData; uint64_t nread = 0; uint64_t buf_len = buffer_size; char *buf = (char *)malloc(buffer_size); ASSERT_NE((void *)NULL, buf); if (strncmp(url, "http://localhost/", 17) == 0) { myData = new S3Reader_fake(url); } else { myData = new S3Reader(url); } ASSERT_NE((void *)NULL, myData); ASSERT_TRUE(myData->Init(segid, segnum, chunksize)); while (1) { nread = buf_len; ASSERT_TRUE(myData->TransferData(buf, nread)); if (nread == 0) break; m.Update(buf, nread); } EXPECT_STREQ(md5_str, m.Get()); delete myData; free(buf); } #ifdef AWSTEST TEST(ExtWrapper, normal) { ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "138fc555074671912125ba692c678246", 0, 1, 64 * 1024 * 1024); } TEST(ExtWrapper, normal_2segs) { ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "a861acda78891b48b25a2788e028a740", 0, 2, 64 * 1024 * 1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "db05de0ec7e0808268e2363d3572dc7f", 1, 2, 64 * 1024 * 1024); } TEST(ExtWrapper, normal_3segs) { ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "4d9ccad20bca50d2d1bc9c4eb4958e2c", 0, 3, 64 * 1024 * 1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "561597859d093905e2b21e896259ae79", 1, 3, 64 * 1024 * 1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "98d4e5348356ceee46d15c4e5f37845b", 2, 3, 64 * 1024 * 1024); } TEST(ExtWrapper, normal_4segs) { ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "b87b5d79e2bcb8dc1d0fd289fbfa5829", 0, 4, 64 * 1024 * 1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "4df154611d394c60084bb5b97bdb19be", 1, 4, 64 * 1024 * 1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "238affbb831ff27df9d09afeeb2e59f9", 2, 4, 64 * 1024 * 1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "dceb001d03d54d61874d27c9f04596b1", 3, 4, 64 * 1024 * 1024); } #endif // AWSTEST TEST(FakeExtWrapper, simple) { ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "138fc555074671912125ba692c678246", 0, 1, 64 * 1024 * 1024); } TEST(FakeExtWrapper, normal_2segs) { ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "a861acda78891b48b25a2788e028a740", 0, 2, 64 * 1024 * 1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "db05de0ec7e0808268e2363d3572dc7f", 1, 2, 64 * 1024 * 1024); } TEST(FakeExtWrapper, normal_3segs) { ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "4d9ccad20bca50d2d1bc9c4eb4958e2c", 0, 3, 64 * 1024 * 1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "561597859d093905e2b21e896259ae79", 1, 3, 64 * 1024 * 1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "98d4e5348356ceee46d15c4e5f37845b", 2, 3, 64 * 1024 * 1024); } TEST(FakeExtWrapper, normal_4segs) { ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "b87b5d79e2bcb8dc1d0fd289fbfa5829", 0, 4, 64 * 1024 * 1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "4df154611d394c60084bb5b97bdb19be", 1, 4, 64 * 1024 * 1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "238affbb831ff27df9d09afeeb2e59f9", 2, 4, 64 * 1024 * 1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "dceb001d03d54d61874d27c9f04596b1", 3, 4, 64 * 1024 * 1024); } TEST(FakeExtWrapper, bigfile) { ExtWrapperTest("http://localhost/bigfile/", 64 * 1024, "83c7ab787e3f1d1e7880dcae954ab4a4", 0, 1, 64 * 1024 * 1024); } <|endoftext|>
<commit_before>/** * @file * @author Jason Lingle * @brief Implementation of src/core/init_state.hxx */ #include <iostream> #include <typeinfo> #include <ctime> #include <new> #include <algorithm> #include <GL/gl.h> #include <SDL.h> #include <tcl.h> #include "init_state.hxx" #include "src/abendstern.hxx" #include "src/globals.hxx" #include "src/graphics/imgload.hxx" #include "src/test_state.hxx" #include "src/fasttrig.hxx" #include "src/background/background_object.hxx" #include "src/background/star_field.hxx" #include "src/background/explosion_pool.hxx" #include "src/ship/sys/system_textures.hxx" #include "src/graphics/vec.hxx" #include "src/graphics/mat.hxx" #include "src/graphics/matops.hxx" #include "src/graphics/shader.hxx" #include "src/graphics/cmn_shaders.hxx" #include "src/graphics/glhelp.hxx" #include "src/graphics/gl32emu.hxx" #include "src/graphics/font.hxx" #include "src/graphics/asgi.hxx" #include "src/audio/audio.hxx" #include "src/secondary/namegen.hxx" #include "src/tcl_iface/bridge.hxx" #include "src/exit_conditions.hxx" using namespace std; #if defined(AB_OPENGL_14) #define LOGO "images/a14.png" #elif defined(AB_OPENGL_21) #define LOGO "images/a21.png" #else #define LOGO "images/a.png" #endif #define PRELIM_LOGO "images/a.png" //For LSD-mode Easter Egg static bool hasPressedL=false, hasPressedS=false, hasPressedD=false; InitState::InitState() { currStep = 0; currStepProgress = 0; static float (*const stepsToLoad[])() = { &InitState::miscLoader, &InitState::initFontLoader, &InitState::systexLoader, &InitState::starLoader, &InitState::backgroundLoader, &InitState::keyboardDelay, }; steps = stepsToLoad; numSteps = lenof(stepsToLoad); hasPainted=headless; if (!headless) { if (!preliminaryRunMode) SDL_ShowCursor(SDL_DISABLE); glGenTextures(1, &logo); vao = newVAO(); glBindVertexArray(vao); vbo = newVBO(); const char* error=loadImage(preliminaryRunMode? PRELIM_LOGO : LOGO, logo); if (error) { cerr << error << endl; exit(EXIT_MALFORMED_DATA); } //We can't set the buffer up yet, because vheight //has not yet been calculated. } } InitState::~InitState() { if (!headless) { glDeleteTextures(1, &logo); glDeleteBuffers(1, &vbo); glDeleteVertexArrays(1, &vao); } } GameState* InitState::update(float) { if (!hasPainted && !headless) return NULL; if (currStep < numSteps) { currStepProgress = steps[currStep](); if (currStepProgress > 1.0f) { currStepProgress = 0; ++currStep; } } else { if (hasPressedL && hasPressedS && hasPressedD) { enableLSDMode(); shader::textureReplace.unload(); shader::basic.unload(); } //Start the root interpreter Tcl_Interp* root=newInterpreter(false); if (TCL_ERROR == Tcl_EvalFile(root, "tcl/autoexec.tcl")) { cerr << "FATAL: Autoexec did not run successfully: " << Tcl_GetStringResult(root) << endl; Tcl_Obj* options=Tcl_GetReturnOptions(root, TCL_ERROR); Tcl_Obj* key=Tcl_NewStringObj("-errorinfo", -1); Tcl_Obj* stackTrace; Tcl_IncrRefCount(key); Tcl_DictObjGet(NULL, options, key, &stackTrace); Tcl_DecrRefCount(key); cerr << "Stack trace:\n" << Tcl_GetStringFromObj(stackTrace, NULL) << endl; exit(EXIT_SCRIPTING_BUG); } if (this == state) { cerr << "FATAL: Autoexec did not change GameState" << endl; exit(EXIT_SCRIPTING_BUG); } if (!headless) { SDL_EnableUNICODE(1); SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); //Tcl is taking over in a somewhat rude way, so //handle as gracefully as possible state->configureGL(); } } return NULL; } void InitState::draw() { hasPainted=true; const shader::textureReplaceV quad[4] = { { {{0.5f-vheight/2,0 ,0,1}}, {{0,1}} }, { {{0.5f+vheight/2,0 ,0,1}}, {{1,1}} }, { {{0.5f-vheight/2,vheight,0,1}}, {{0,0}} }, { {{0.5f+vheight/2,vheight,0,1}}, {{1,0}} }, }; shader::textureReplaceU uni; uni.colourMap=0; glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(quad), quad, GL_STATIC_DRAW); shader::textureReplace->setupVBO(); glBindTexture(GL_TEXTURE_2D, logo); shader::textureReplace->activate(&uni); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); static const float progressH = 0.02f; static const float progressW = 0.3f; float currProgress = currStep/(float)numSteps + currStepProgress/numSteps; float baseX = 0.5f - progressW/2; #if defined(AB_OPENGL_14) asgi::colour(1.0f, 0.4f, 0.2f, 0.75f); #elif defined(AB_OPENGL_21) asgi::colour(0.2f, 1.0f, 0.4f, 0.75f); #else asgi::colour(0.2f, 0.3f, 0.9f, 0.75f); #endif asgi::begin(asgi::Quads); asgi::vertex(baseX, 4*progressH); asgi::vertex(baseX, 5*progressH); asgi::vertex(baseX + currProgress*progressW, 5*progressH); asgi::vertex(baseX + currProgress*progressW, 4*progressH); asgi::end(); asgi::begin(asgi::Quads); asgi::vertex(baseX, 2.75f*progressH); asgi::vertex(baseX, 3.75f*progressH); asgi::vertex(baseX + currStepProgress*progressW, 3.75*progressH); asgi::vertex(baseX + currStepProgress*progressW, 2.75*progressH); asgi::end(); } void InitState::keyboard(SDL_KeyboardEvent* e) { if (e->keysym.sym == SDLK_l) hasPressedL = true; else if (e->keysym.sym == SDLK_s) hasPressedS = true; else if (e->keysym.sym == SDLK_d) hasPressedD = true; } float InitState::miscLoader() { initTable(); //Trig tables sparkCountMultiplier=1; if (conf["conf"]["audio_enabled"]) audio::init(); prepareTclBridge(); namegenLoad(); return 2; } float InitState::starLoader() { initStarLists(); return 2; } float InitState::backgroundLoader() { if (!headless && !loadBackgroundObjects()) exit(EXIT_MALFORMED_DATA); return 2; } float InitState::systexLoader() { if (!headless) system_texture::load(); return 2; } float InitState::initFontLoader() { float mult = (preliminaryRunMode? 2.0f : min(vheight,1.0f)); float size = conf["conf"]["hud"]["font_size"]; new (sysfont) Font("fonts/westm", size*mult, false); new (sysfontStipple) Font("fonts/westm", size*mult, true ); new (smallFont) Font("fonts/unifont", size*mult/1.5f, false); new (smallFontStipple)Font("fonts/unifont", size*mult/1.5f, true ); return 2; } //Delays for 500 ms to wait for keystrokes float InitState::keyboardDelay() { if (preliminaryRunMode) return 2; //Don't wait static Uint32 start = SDL_GetTicks(); Uint32 end = SDL_GetTicks(); return (end-start)/512.0f; } <commit_msg>Always use light-blue progress bar when loading prelim run mode.<commit_after>/** * @file * @author Jason Lingle * @brief Implementation of src/core/init_state.hxx */ #include <iostream> #include <typeinfo> #include <ctime> #include <new> #include <algorithm> #include <GL/gl.h> #include <SDL.h> #include <tcl.h> #include "init_state.hxx" #include "src/abendstern.hxx" #include "src/globals.hxx" #include "src/graphics/imgload.hxx" #include "src/test_state.hxx" #include "src/fasttrig.hxx" #include "src/background/background_object.hxx" #include "src/background/star_field.hxx" #include "src/background/explosion_pool.hxx" #include "src/ship/sys/system_textures.hxx" #include "src/graphics/vec.hxx" #include "src/graphics/mat.hxx" #include "src/graphics/matops.hxx" #include "src/graphics/shader.hxx" #include "src/graphics/cmn_shaders.hxx" #include "src/graphics/glhelp.hxx" #include "src/graphics/gl32emu.hxx" #include "src/graphics/font.hxx" #include "src/graphics/asgi.hxx" #include "src/audio/audio.hxx" #include "src/secondary/namegen.hxx" #include "src/tcl_iface/bridge.hxx" #include "src/exit_conditions.hxx" using namespace std; #if defined(AB_OPENGL_14) #define LOGO "images/a14.png" #elif defined(AB_OPENGL_21) #define LOGO "images/a21.png" #else #define LOGO "images/a.png" #endif #define PRELIM_LOGO "images/a.png" //For LSD-mode Easter Egg static bool hasPressedL=false, hasPressedS=false, hasPressedD=false; InitState::InitState() { currStep = 0; currStepProgress = 0; static float (*const stepsToLoad[])() = { &InitState::miscLoader, &InitState::initFontLoader, &InitState::systexLoader, &InitState::starLoader, &InitState::backgroundLoader, &InitState::keyboardDelay, }; steps = stepsToLoad; numSteps = lenof(stepsToLoad); hasPainted=headless; if (!headless) { if (!preliminaryRunMode) SDL_ShowCursor(SDL_DISABLE); glGenTextures(1, &logo); vao = newVAO(); glBindVertexArray(vao); vbo = newVBO(); const char* error=loadImage(preliminaryRunMode? PRELIM_LOGO : LOGO, logo); if (error) { cerr << error << endl; exit(EXIT_MALFORMED_DATA); } //We can't set the buffer up yet, because vheight //has not yet been calculated. } } InitState::~InitState() { if (!headless) { glDeleteTextures(1, &logo); glDeleteBuffers(1, &vbo); glDeleteVertexArrays(1, &vao); } } GameState* InitState::update(float) { if (!hasPainted && !headless) return NULL; if (currStep < numSteps) { currStepProgress = steps[currStep](); if (currStepProgress > 1.0f) { currStepProgress = 0; ++currStep; } } else { if (hasPressedL && hasPressedS && hasPressedD) { enableLSDMode(); shader::textureReplace.unload(); shader::basic.unload(); } //Start the root interpreter Tcl_Interp* root=newInterpreter(false); if (TCL_ERROR == Tcl_EvalFile(root, "tcl/autoexec.tcl")) { cerr << "FATAL: Autoexec did not run successfully: " << Tcl_GetStringResult(root) << endl; Tcl_Obj* options=Tcl_GetReturnOptions(root, TCL_ERROR); Tcl_Obj* key=Tcl_NewStringObj("-errorinfo", -1); Tcl_Obj* stackTrace; Tcl_IncrRefCount(key); Tcl_DictObjGet(NULL, options, key, &stackTrace); Tcl_DecrRefCount(key); cerr << "Stack trace:\n" << Tcl_GetStringFromObj(stackTrace, NULL) << endl; exit(EXIT_SCRIPTING_BUG); } if (this == state) { cerr << "FATAL: Autoexec did not change GameState" << endl; exit(EXIT_SCRIPTING_BUG); } if (!headless) { SDL_EnableUNICODE(1); SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); //Tcl is taking over in a somewhat rude way, so //handle as gracefully as possible state->configureGL(); } } return NULL; } void InitState::draw() { hasPainted=true; const shader::textureReplaceV quad[4] = { { {{0.5f-vheight/2,0 ,0,1}}, {{0,1}} }, { {{0.5f+vheight/2,0 ,0,1}}, {{1,1}} }, { {{0.5f-vheight/2,vheight,0,1}}, {{0,0}} }, { {{0.5f+vheight/2,vheight,0,1}}, {{1,0}} }, }; shader::textureReplaceU uni; uni.colourMap=0; glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(quad), quad, GL_STATIC_DRAW); shader::textureReplace->setupVBO(); glBindTexture(GL_TEXTURE_2D, logo); shader::textureReplace->activate(&uni); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); static const float progressH = 0.02f; static const float progressW = 0.3f; float currProgress = currStep/(float)numSteps + currStepProgress/numSteps; float baseX = 0.5f - progressW/2; if (!preliminaryRunMode) { #if defined(AB_OPENGL_14) asgi::colour(1.0f, 0.4f, 0.2f, 0.75f); #elif defined(AB_OPENGL_21) asgi::colour(0.2f, 1.0f, 0.4f, 0.75f); #else asgi::colour(0.2f, 0.3f, 0.9f, 0.75f); #endif } else { asgi::colour(0.2f, 0.3f, 0.9f, 0.75f); } asgi::begin(asgi::Quads); asgi::vertex(baseX, 4*progressH); asgi::vertex(baseX, 5*progressH); asgi::vertex(baseX + currProgress*progressW, 5*progressH); asgi::vertex(baseX + currProgress*progressW, 4*progressH); asgi::end(); asgi::begin(asgi::Quads); asgi::vertex(baseX, 2.75f*progressH); asgi::vertex(baseX, 3.75f*progressH); asgi::vertex(baseX + currStepProgress*progressW, 3.75*progressH); asgi::vertex(baseX + currStepProgress*progressW, 2.75*progressH); asgi::end(); } void InitState::keyboard(SDL_KeyboardEvent* e) { if (e->keysym.sym == SDLK_l) hasPressedL = true; else if (e->keysym.sym == SDLK_s) hasPressedS = true; else if (e->keysym.sym == SDLK_d) hasPressedD = true; } float InitState::miscLoader() { initTable(); //Trig tables sparkCountMultiplier=1; if (conf["conf"]["audio_enabled"]) audio::init(); prepareTclBridge(); namegenLoad(); return 2; } float InitState::starLoader() { initStarLists(); return 2; } float InitState::backgroundLoader() { if (!headless && !loadBackgroundObjects()) exit(EXIT_MALFORMED_DATA); return 2; } float InitState::systexLoader() { if (!headless) system_texture::load(); return 2; } float InitState::initFontLoader() { float mult = (preliminaryRunMode? 2.0f : min(vheight,1.0f)); float size = conf["conf"]["hud"]["font_size"]; new (sysfont) Font("fonts/westm", size*mult, false); new (sysfontStipple) Font("fonts/westm", size*mult, true ); new (smallFont) Font("fonts/unifont", size*mult/1.5f, false); new (smallFontStipple)Font("fonts/unifont", size*mult/1.5f, true ); return 2; } //Delays for 500 ms to wait for keystrokes float InitState::keyboardDelay() { if (preliminaryRunMode) return 2; //Don't wait static Uint32 start = SDL_GetTicks(); Uint32 end = SDL_GetTicks(); return (end-start)/512.0f; } <|endoftext|>