text
stringlengths 54
60.6k
|
---|
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <[email protected]>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "IndexWriter.h"
#include <fnord-fts/AnalyzerAdapter.h>
using namespace fnord;
namespace cm {
RefPtr<IndexWriter> IndexWriter::openIndex(const String& index_path) {
if (!FileUtil::exists(index_path) || !FileUtil::isDirectory(index_path)) {
RAISEF(kIllegalArgumentError, "invalid index path: $0", index_path);
}
/* set up feature schema */
FeatureSchema feature_schema;
feature_schema.registerFeature("shop_id", 1, 1);
feature_schema.registerFeature("category1", 2, 1);
feature_schema.registerFeature("category2", 3, 1);
feature_schema.registerFeature("category3", 4, 1);
feature_schema.registerFeature("title~de", 5, 2);
/* open mdb */
auto db_path = FileUtil::joinPaths(index_path, "db");
FileUtil::mkdir_p(db_path);
auto db = mdb::MDB::open(db_path);
db->setMaxSize(1000000 * 512000);
/* open docs store */
auto docs_path = FileUtil::joinPaths(index_path, "docs");
FileUtil::mkdir_p(docs_path);
RefPtr<DocStore> docs(new DocStore(docs_path));
/* open lucene */
RefPtr<fnord::fts::Analyzer> analyzer(new fnord::fts::Analyzer("./conf"));
auto adapter = std::make_shared<fnord::fts::AnalyzerAdapter>(analyzer);
auto fts_path = FileUtil::joinPaths(index_path, "fts");
auto fts =
fts::newLucene<fts::IndexWriter>(
fts::FSDirectory::open(StringUtil::convertUTF8To16(fts_path)),
adapter,
true,
fts::IndexWriter::MaxFieldLengthLIMITED);
return RefPtr<IndexWriter>(new IndexWriter(feature_schema, db, docs, fts));
}
IndexWriter::IndexWriter(
FeatureSchema schema,
RefPtr<mdb::MDB> db,
RefPtr<DocStore> docs,
std::shared_ptr<fts::IndexWriter> fts) :
schema_(schema),
db_(db),
feature_idx_(new FeatureIndexWriter(&schema_)),
docs_(docs),
fts_(fts) {}
IndexWriter::~IndexWriter() {
fts_->close();
}
void IndexWriter::updateDocument(const IndexRequest& index_request) {
stat_documents_indexed_total_.incr(1);
auto doc = docs_->updateDocument(index_request);
rebuildFTS(doc);
stat_documents_indexed_success_.incr(1);
}
void IndexWriter::commit() {
fts_->commit();
}
void IndexWriter::rebuildFTS(DocID docid) {
auto doc = docs_->findDocument(docid);
rebuildFTS(doc);
}
void IndexWriter::rebuildFTS(RefPtr<Document> doc) {
stat_documents_indexed_fts_.incr(1);
auto fts_doc = fts::newLucene<fts::Document>();
fnord::logDebug(
"cm.indexwriter",
"Rebuilding FTS Index for docid=$0",
doc->docID().docid);
HashMap<String, String> fts_fields_anal;
for (const auto& f : doc->fields()) {
/* title~LANG */
if (StringUtil::beginsWith(f.first, "title~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "title~","text~");
fts_fields_anal[k] += " ";
fts_fields_anal[k] += f.second;
}
/* description~LANG */
if (StringUtil::beginsWith(f.first, "description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "description~","text~");
fts_fields_anal[k] += " ";
fts_fields_anal[k] += f.second;
}
/* tags_as_text~LANG */
if (StringUtil::beginsWith(f.first, "tags_as_text~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "tags_as_text~","text~");
fts_fields_anal[k] += " ";
fts_fields_anal[k] += f.second;
}
}
for (const auto& f : fts_fields_anal) {
fts_doc->add(
fts::newLucene<fts::Field>(
StringUtil::convertUTF8To16(f.first),
StringUtil::convertUTF8To16(f.second),
fts::Field::STORE_NO,
fts::Field::INDEX_ANALYZED));
}
fts_->addDocument(fts_doc);
}
void IndexWriter::rebuildFTS() {
docs_->listDocuments([this] (const DocID& docid) -> bool {
rebuildFTS(docid);
return true;
});
}
RefPtr<mdb::MDB> IndexWriter::featureDB() {
return db_;
}
void IndexWriter::exportStats(const String& prefix) {
exportStat(
StringUtil::format("$0/documents_indexed_total", prefix),
&stat_documents_indexed_total_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_success", prefix),
&stat_documents_indexed_success_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_error", prefix),
&stat_documents_indexed_error_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_fts", prefix),
&stat_documents_indexed_fts_,
fnord::stats::ExportMode::EXPORT_DELTA);
}
} // namespace cm
<commit_msg>index docid<commit_after>/**
* Copyright (c) 2015 - The CM Authors <[email protected]>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "IndexWriter.h"
#include <fnord-fts/AnalyzerAdapter.h>
using namespace fnord;
namespace cm {
RefPtr<IndexWriter> IndexWriter::openIndex(const String& index_path) {
if (!FileUtil::exists(index_path) || !FileUtil::isDirectory(index_path)) {
RAISEF(kIllegalArgumentError, "invalid index path: $0", index_path);
}
/* set up feature schema */
FeatureSchema feature_schema;
feature_schema.registerFeature("shop_id", 1, 1);
feature_schema.registerFeature("category1", 2, 1);
feature_schema.registerFeature("category2", 3, 1);
feature_schema.registerFeature("category3", 4, 1);
feature_schema.registerFeature("title~de", 5, 2);
/* open mdb */
auto db_path = FileUtil::joinPaths(index_path, "db");
FileUtil::mkdir_p(db_path);
auto db = mdb::MDB::open(db_path);
db->setMaxSize(1000000 * 512000);
/* open docs store */
auto docs_path = FileUtil::joinPaths(index_path, "docs");
FileUtil::mkdir_p(docs_path);
RefPtr<DocStore> docs(new DocStore(docs_path));
/* open lucene */
RefPtr<fnord::fts::Analyzer> analyzer(new fnord::fts::Analyzer("./conf"));
auto adapter = std::make_shared<fnord::fts::AnalyzerAdapter>(analyzer);
auto fts_path = FileUtil::joinPaths(index_path, "fts");
auto fts =
fts::newLucene<fts::IndexWriter>(
fts::FSDirectory::open(StringUtil::convertUTF8To16(fts_path)),
adapter,
true,
fts::IndexWriter::MaxFieldLengthLIMITED);
return RefPtr<IndexWriter>(new IndexWriter(feature_schema, db, docs, fts));
}
IndexWriter::IndexWriter(
FeatureSchema schema,
RefPtr<mdb::MDB> db,
RefPtr<DocStore> docs,
std::shared_ptr<fts::IndexWriter> fts) :
schema_(schema),
db_(db),
feature_idx_(new FeatureIndexWriter(&schema_)),
docs_(docs),
fts_(fts) {}
IndexWriter::~IndexWriter() {
fts_->close();
}
void IndexWriter::updateDocument(const IndexRequest& index_request) {
stat_documents_indexed_total_.incr(1);
auto doc = docs_->updateDocument(index_request);
rebuildFTS(doc);
stat_documents_indexed_success_.incr(1);
}
void IndexWriter::commit() {
fts_->commit();
}
void IndexWriter::rebuildFTS(DocID docid) {
auto doc = docs_->findDocument(docid);
rebuildFTS(doc);
}
void IndexWriter::rebuildFTS(RefPtr<Document> doc) {
stat_documents_indexed_fts_.incr(1);
auto fts_doc = fts::newLucene<fts::Document>();
fnord::logDebug(
"cm.indexwriter",
"Rebuilding FTS Index for docid=$0",
doc->docID().docid);
HashMap<String, String> fts_fields_anal;
for (const auto& f : doc->fields()) {
/* title~LANG */
if (StringUtil::beginsWith(f.first, "title~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "title~","text~");
fts_fields_anal[k] += " ";
fts_fields_anal[k] += f.second;
}
/* description~LANG */
if (StringUtil::beginsWith(f.first, "description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "description~","text~");
fts_fields_anal[k] += " ";
fts_fields_anal[k] += f.second;
}
/* tags_as_text~LANG */
if (StringUtil::beginsWith(f.first, "tags_as_text~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "tags_as_text~","text~");
fts_fields_anal[k] += " ";
fts_fields_anal[k] += f.second;
}
}
fts_doc->add(
fts::newLucene<fts::Field>(
L"docid",
StringUtil::convertUTF8To16(doc->docID().docid),
fts::Field::STORE_YES,
fts::Field::INDEX_NO));
for (const auto& f : fts_fields_anal) {
fts_doc->add(
fts::newLucene<fts::Field>(
StringUtil::convertUTF8To16(f.first),
StringUtil::convertUTF8To16(f.second),
fts::Field::STORE_NO,
fts::Field::INDEX_ANALYZED));
}
fts_->addDocument(fts_doc);
}
void IndexWriter::rebuildFTS() {
docs_->listDocuments([this] (const DocID& docid) -> bool {
rebuildFTS(docid);
return true;
});
}
RefPtr<mdb::MDB> IndexWriter::featureDB() {
return db_;
}
void IndexWriter::exportStats(const String& prefix) {
exportStat(
StringUtil::format("$0/documents_indexed_total", prefix),
&stat_documents_indexed_total_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_success", prefix),
&stat_documents_indexed_success_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_error", prefix),
&stat_documents_indexed_error_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_fts", prefix),
&stat_documents_indexed_fts_,
fnord::stats::ExportMode::EXPORT_DELTA);
}
} // namespace cm
<|endoftext|> |
<commit_before>/**
* HAL
*
* Copyright (c) 2014 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License.
* Please see the LICENSE included with this distribution for details.
*/
#include "HAL/JSFunction.hpp"
#include "HAL/JSString.hpp"
#include "HAL/JSValue.hpp"
#include "HAL/JSUndefined.hpp"
#include "HAL/detail/JSUtil.hpp"
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <cassert>
namespace HAL {
JSFunction::JSFunction(const JSContext& js_context, const JSString& body, const std::vector<JSString>& parameter_names, const JSString& function_name, const JSString& source_url, int starting_line_number)
: JSObject(js_context, MakeFunction(js_context, body, parameter_names, function_name, source_url, starting_line_number)) {
}
JSFunction::JSFunction(const JSContext& js_context, const JSString& function_name, const JSFunctionCallback& callback)
: JSObject(js_context, MakeFunction(js_context, function_name, callback)) {
}
JSObjectRef JSFunction::MakeFunction(const JSContext& js_context, const JSString& body, const std::vector<JSString>& parameter_names, const JSString& function_name, const JSString& source_url, int starting_line_number) {
JSValueRef exception { nullptr };
JSStringRef source_url_ref = (source_url.length() > 0) ? static_cast<JSStringRef>(source_url) : nullptr;
JSObjectRef js_object_ref = nullptr;
if (!parameter_names.empty()) {
std::vector<JSStringRef> parameter_name_array = detail::to_vector(parameter_names);
js_object_ref = JSObjectMakeFunction(static_cast<JSContextRef>(js_context), static_cast<JSStringRef>(function_name), static_cast<unsigned>(parameter_name_array.size()), ¶meter_name_array[0], static_cast<JSStringRef>(body), source_url_ref, starting_line_number, &exception);
} else {
js_object_ref = JSObjectMakeFunction(static_cast<JSContextRef>(js_context), static_cast<JSStringRef>(function_name), 0, nullptr, static_cast<JSStringRef>(body), source_url_ref, starting_line_number, &exception);
}
if (exception) {
// If this assert fails then we need to JSValueUnprotect
// js_object_ref.
assert(!js_object_ref);
detail::ThrowRuntimeError("JSFunction", JSValue(js_context, exception));
}
return js_object_ref;
}
std::unordered_map<std::intptr_t, JSFunctionCallback> JSFunction::js_object_ref_to_js_function__;
void JSFunction::RegisterJSFunctionCallback(JSObjectRef js_object_ref, JSFunctionCallback callback) {
HAL_JSOBJECT_LOCK_GUARD_STATIC;
const auto key = reinterpret_cast<std::intptr_t>(js_object_ref);
const auto value = callback;
const auto position = js_object_ref_to_js_function__.find(key);
const bool found = position != js_object_ref_to_js_function__.end();
if (found) {
HAL_LOG_DEBUG("JSFunction::RegisterJSFunctionCallback: JSObjectRef ", js_object_ref, " already registered");
} else {
const auto insert_result = js_object_ref_to_js_function__.emplace(key, value);
const bool inserted = insert_result.second;
assert(inserted);
}
}
void JSFunction::UnRegisterJSFunctionCallback(JSObjectRef js_object_ref) {
HAL_JSOBJECT_LOCK_GUARD_STATIC;
const auto key = reinterpret_cast<std::intptr_t>(js_object_ref);
const auto position = js_object_ref_to_js_function__.find(key);
const bool found = position != js_object_ref_to_js_function__.end();
if (found) {
js_object_ref_to_js_function__.erase(key);
}
}
JSFunctionCallback JSFunction::FindJSFunctionCallback(JSObjectRef js_object_ref) {
HAL_JSOBJECT_LOCK_GUARD_STATIC;
const auto key = reinterpret_cast<std::intptr_t>(js_object_ref);
const auto position = js_object_ref_to_js_function__.find(key);
const bool found = position != js_object_ref_to_js_function__.end();
if (found) {
return position->second;
} else {
return nullptr;
}
}
JSValueRef JSFunction::JSObjectCallAsFunctionCallback(JSContextRef context_ref, JSObjectRef function_ref, JSObjectRef this_object_ref, size_t argument_count, const JSValueRef arguments_array[], JSValueRef* exception) {
const auto callback = FindJSFunctionCallback(function_ref);
if (callback == nullptr) {
return JSValueMakeUndefined(context_ref);
}
const auto ctx = JSContext(context_ref);
std::vector<JSValue> arguments;
arguments.reserve(argument_count);
for (size_t i = 0; i < argument_count; i++) {
arguments.push_back(JSValue(ctx, arguments_array[i]));
}
auto this_object = JSObject(ctx, this_object_ref);
return static_cast<JSValueRef>(callback(arguments, this_object));
}
JSObjectRef JSFunction::MakeFunction(const JSContext& js_context, const JSString& function_name, const JSFunctionCallback& callback) {
JSObjectRef js_object_ref = JSObjectMakeFunctionWithCallback(static_cast<JSContextRef>(js_context), static_cast<JSStringRef>(function_name), JSFunction::JSObjectCallAsFunctionCallback);
JSFunction::RegisterJSFunctionCallback(js_object_ref, callback);
return js_object_ref;
}
JSFunction::~JSFunction() HAL_NOEXCEPT {
JSFunction::UnRegisterJSFunctionCallback(js_object_ref__);
}
} // namespace HAL {
<commit_msg>JSFunction unregister optimization<commit_after>/**
* HAL
*
* Copyright (c) 2014 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License.
* Please see the LICENSE included with this distribution for details.
*/
#include "HAL/JSFunction.hpp"
#include "HAL/JSString.hpp"
#include "HAL/JSValue.hpp"
#include "HAL/JSUndefined.hpp"
#include "HAL/detail/JSUtil.hpp"
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <cassert>
namespace HAL {
JSFunction::JSFunction(const JSContext& js_context, const JSString& body, const std::vector<JSString>& parameter_names, const JSString& function_name, const JSString& source_url, int starting_line_number)
: JSObject(js_context, MakeFunction(js_context, body, parameter_names, function_name, source_url, starting_line_number)) {
}
JSFunction::JSFunction(const JSContext& js_context, const JSString& function_name, const JSFunctionCallback& callback)
: JSObject(js_context, MakeFunction(js_context, function_name, callback)) {
}
JSObjectRef JSFunction::MakeFunction(const JSContext& js_context, const JSString& body, const std::vector<JSString>& parameter_names, const JSString& function_name, const JSString& source_url, int starting_line_number) {
JSValueRef exception { nullptr };
JSStringRef source_url_ref = (source_url.length() > 0) ? static_cast<JSStringRef>(source_url) : nullptr;
JSObjectRef js_object_ref = nullptr;
if (!parameter_names.empty()) {
std::vector<JSStringRef> parameter_name_array = detail::to_vector(parameter_names);
js_object_ref = JSObjectMakeFunction(static_cast<JSContextRef>(js_context), static_cast<JSStringRef>(function_name), static_cast<unsigned>(parameter_name_array.size()), ¶meter_name_array[0], static_cast<JSStringRef>(body), source_url_ref, starting_line_number, &exception);
} else {
js_object_ref = JSObjectMakeFunction(static_cast<JSContextRef>(js_context), static_cast<JSStringRef>(function_name), 0, nullptr, static_cast<JSStringRef>(body), source_url_ref, starting_line_number, &exception);
}
if (exception) {
// If this assert fails then we need to JSValueUnprotect
// js_object_ref.
assert(!js_object_ref);
detail::ThrowRuntimeError("JSFunction", JSValue(js_context, exception));
}
return js_object_ref;
}
std::unordered_map<std::intptr_t, JSFunctionCallback> JSFunction::js_object_ref_to_js_function__;
void JSFunction::RegisterJSFunctionCallback(JSObjectRef js_object_ref, JSFunctionCallback callback) {
HAL_JSOBJECT_LOCK_GUARD_STATIC;
const auto key = reinterpret_cast<std::intptr_t>(js_object_ref);
const auto value = callback;
const auto position = js_object_ref_to_js_function__.find(key);
const bool found = position != js_object_ref_to_js_function__.end();
if (found) {
HAL_LOG_DEBUG("JSFunction::RegisterJSFunctionCallback: JSObjectRef ", js_object_ref, " already registered");
} else {
const auto insert_result = js_object_ref_to_js_function__.emplace(key, value);
const bool inserted = insert_result.second;
assert(inserted);
}
}
void JSFunction::UnRegisterJSFunctionCallback(JSObjectRef js_object_ref) {
HAL_JSOBJECT_LOCK_GUARD_STATIC;
const auto key = reinterpret_cast<std::intptr_t>(js_object_ref);
js_object_ref_to_js_function__.erase(key);
}
JSFunctionCallback JSFunction::FindJSFunctionCallback(JSObjectRef js_object_ref) {
HAL_JSOBJECT_LOCK_GUARD_STATIC;
const auto key = reinterpret_cast<std::intptr_t>(js_object_ref);
const auto position = js_object_ref_to_js_function__.find(key);
const bool found = position != js_object_ref_to_js_function__.end();
if (found) {
return position->second;
} else {
return nullptr;
}
}
JSValueRef JSFunction::JSObjectCallAsFunctionCallback(JSContextRef context_ref, JSObjectRef function_ref, JSObjectRef this_object_ref, size_t argument_count, const JSValueRef arguments_array[], JSValueRef* exception) {
const auto callback = FindJSFunctionCallback(function_ref);
if (callback == nullptr) {
return JSValueMakeUndefined(context_ref);
}
const auto ctx = JSContext(context_ref);
std::vector<JSValue> arguments;
arguments.reserve(argument_count);
for (size_t i = 0; i < argument_count; i++) {
arguments.push_back(JSValue(ctx, arguments_array[i]));
}
auto this_object = JSObject(ctx, this_object_ref);
return static_cast<JSValueRef>(callback(arguments, this_object));
}
JSObjectRef JSFunction::MakeFunction(const JSContext& js_context, const JSString& function_name, const JSFunctionCallback& callback) {
JSObjectRef js_object_ref = JSObjectMakeFunctionWithCallback(static_cast<JSContextRef>(js_context), static_cast<JSStringRef>(function_name), JSFunction::JSObjectCallAsFunctionCallback);
JSFunction::RegisterJSFunctionCallback(js_object_ref, callback);
return js_object_ref;
}
JSFunction::~JSFunction() HAL_NOEXCEPT {
JSFunction::UnRegisterJSFunctionCallback(js_object_ref__);
}
} // namespace HAL {
<|endoftext|> |
<commit_before>// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#ifndef ROSETTASTONE_TARGETING_HPP
#define ROSETTASTONE_TARGETING_HPP
#include <Rosetta/Models/Entity.hpp>
namespace RosettaStone::Generic
{
bool IsValidTarget(Entity* source, Entity* target);
} // namespace RosettaStone::Generic
#endif // ROSETTASTONE_TARGETING_HPP
<commit_msg>docs: Add missing comments for documentation using doxygen<commit_after>// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#ifndef ROSETTASTONE_TARGETING_HPP
#define ROSETTASTONE_TARGETING_HPP
#include <Rosetta/Models/Entity.hpp>
namespace RosettaStone::Generic
{
//! Checks the target is valid.
//! \param source A source entity.
//! \param target A target entity.
//! \return true if the target is valid, false otherwise.
bool IsValidTarget(Entity* source, Entity* target);
} // namespace RosettaStone::Generic
#endif // ROSETTASTONE_TARGETING_HPP
<|endoftext|> |
<commit_before>/*
* Copyright 2012 Bram van der Kroef
*
* This file is part of LESS CSS Compiler.
*
* LESS CSS Compiler 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.
*
* LESS CSS Compiler 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 LESS CSS Compiler. If not, see <http://www.gnu.org/licenses/>.
*
* Author: Bram van der Kroef <[email protected]>
*/
#include "LessParser.h"
bool LessParser::parseStatement(Stylesheet* stylesheet) {
return parseRuleset(stylesheet) || parseAtRuleOrVariable(stylesheet);
}
bool LessParser::parseAtRuleOrVariable (Stylesheet* stylesheet) {
string keyword, import;
TokenList* rule;
AtRule* atrule = NULL;
if (tokenizer->getTokenType() != Token::ATKEYWORD)
return false;
keyword = tokenizer->getToken()->str;
tokenizer->readNextToken();
skipWhitespace();
if (!parseVariable(keyword)) {
rule = new TokenList();
while(parseAny(rule)) {};
if (!parseBlock(rule)) {
if (tokenizer->getTokenType() != Token::DELIMITER) {
throw new ParseException(tokenizer->getToken()->str,
"delimiter (';') at end of @-rule");
}
tokenizer->readNextToken();
skipWhitespace();
}
// parse import
if (keyword == "@import") {
if (rule->size() != 1 ||
rule->front()->type != Token::STRING)
throw new ParseException(*rule->toString(), "A string with the \
file path");
import = rule->front()->str;
if (import.size() < 5 ||
import.substr(import.size() - 5, 4) != ".css") {
if (import.size() < 6 || import.substr(import.size() - 6, 5) != ".less")
import.insert(import.size() - 1, ".less");
importFile(import.substr(1, import.size() - 2), stylesheet);
return true;
}
}
atrule = new AtRule(new string(keyword));
atrule->setRule(rule);
stylesheet->addAtRule(atrule);
}
return true;
}
bool LessParser::parseVariable (string keyword = "") {
TokenList* rule;
if (keyword == "") {
if (tokenizer->getTokenType() != Token::ATKEYWORD)
return false;
keyword = tokenizer->getToken()->str;
tokenizer->readNextToken();
skipWhitespace();
if (tokenizer->getTokenType() != Token::COLON)
throw new ParseException(tokenizer->getToken()->str,
"colon (':') following @keyword in \
variable declaration.");
} else if (tokenizer->getTokenType() != Token::COLON)
return false;
tokenizer->readNextToken();
skipWhitespace();
rule = parseValue();
if (rule == NULL || rule->size() == 0) {
throw new ParseException(tokenizer->getToken()->str,
"value for variable");
}
if (tokenizer->getTokenType() != Token::DELIMITER) {
throw new ParseException(tokenizer->getToken()->str,
"delimiter (';') at end of @-rule");
}
valueProcessor->putVariable(keyword, rule);
tokenizer->readNextToken();
skipWhitespace();
return true;
}
bool LessParser::parseRuleset (Stylesheet* stylesheet,
Selector* selector) {
Ruleset* ruleset = NULL;
ParameterRuleset* pruleset;
list<string> parameters;
list<string>::iterator pit;
if (selector == NULL)
selector = parseSelector();
if (tokenizer->getTokenType() != Token::BRACKET_OPEN) {
if (selector == NULL)
return false;
else {
throw new ParseException(tokenizer->getToken()->str,
"a declaration block ('{...}')");
}
}
tokenizer->readNextToken();
// add new scope for the ruleset
valueProcessor->pushScope();
if (selector->back()->type != Token::PAREN_CLOSED) {
ruleset = new Ruleset(selector);
stylesheet->addRuleset(ruleset);
} else {
ruleset = pruleset = new ParameterRuleset(selector);
parameterRulesets.push_back(pruleset);
// Add a NULL value to the local scope for each parameter so they
// don't get replaced in the ruleset. For example this statement:
// @x: 5; .class (@x: 0) {left: @x }
// 'left: @x' would be replaced with 'left: 5' if we didn't do this
parameters = pruleset->getKeywords();
for(pit = parameters.begin(); pit != parameters.end(); pit++) {
valueProcessor->putVariable(*pit, NULL);
}
}
skipWhitespace();
parseRulesetStatement(stylesheet, ruleset);
// remove scope
valueProcessor->popScope();
if (tokenizer->getTokenType() != Token::BRACKET_CLOSED) {
throw new ParseException(tokenizer->getToken()->str,
"end of declaration block ('}')");
}
tokenizer->readNextToken();
skipWhitespace();
return true;
}
bool LessParser::parseRulesetStatement (Stylesheet* stylesheet,
Ruleset* ruleset) {
Declaration* declaration;
Selector* selector = parseSelector();
TokenList* value;
if (selector == NULL) {
if (parseVariable()) {
parseRulesetStatement(stylesheet, ruleset);
return true;
}
return false;
}
// a selector followed by a ruleset is a nested rule
if (parseNestedRule(selector, ruleset, stylesheet)) {
parseRulesetStatement(stylesheet, ruleset);
return true;
// a selector by itself might be a mixin.
} else if (parseMixin(selector, ruleset, stylesheet)) {
delete selector;
if (tokenizer->getTokenType() == Token::DELIMITER) {
tokenizer->readNextToken();
skipWhitespace();
parseRulesetStatement(stylesheet, ruleset);
}
return true;
}
// if we can parse a property and the next token is a COLON then the
// statement is a declaration.
if (selector->size() > 1 &&
selector->front()->type == Token::IDENTIFIER &&
selector->at(1)->type == Token::COLON) {
declaration = new Declaration(new string(selector->front()->str));
delete selector->shift();
delete selector->shift();
// parse any leftover value parts.
value = CssParser::parseValue();
if (value != NULL) {
selector->push(value);
delete value;
}
valueProcessor->processValue(selector);
declaration->setValue(selector);
ruleset->addDeclaration(declaration);
if (tokenizer->getTokenType() == Token::DELIMITER) {
tokenizer->readNextToken();
skipWhitespace();
parseRulesetStatement(stylesheet, ruleset);
}
return true;
} else {
throw new ParseException(*selector->toString(),
"a mixin that has been defined");
}
}
bool LessParser::parseNestedRule(Selector* selector, Ruleset*
ruleset, Stylesheet* stylesheet) {
if (tokenizer->getTokenType() != Token::BRACKET_OPEN)
return false;
selector->addPrefix(ruleset->getSelector());
parseRuleset(stylesheet, selector);
return true;
}
Declaration* LessParser::parseDeclaration (string* property) {
Declaration* declaration;
skipWhitespace();
if (tokenizer->getTokenType() != Token::COLON)
return NULL;
tokenizer->readNextToken();
skipWhitespace();
declaration = new Declaration(property);
TokenList* value = parseValue();
if (value == NULL) {
throw new ParseException(tokenizer->getToken()->str,
"value for property");
}
declaration->setValue(value);
return declaration;
}
TokenList* LessParser::parseValue () {
TokenList* value = CssParser::parseValue();
if (value != NULL)
valueProcessor->processValue(value);
return value;
}
bool LessParser::parseMixin(Selector* selector, Ruleset* ruleset,
Stylesheet* stylesheet) {
Ruleset* mixin;
vector<Declaration*>* declarations;
vector<Declaration*>::iterator it;
if (processParameterMixin(selector, ruleset)) {
return true;
} else if((mixin = stylesheet->getRuleset(selector)) != NULL) {
declarations = mixin->getDeclarations();
for (it = declarations->begin(); it < declarations->end(); it++) {
ruleset->addDeclaration((*it)->clone());
}
return true;
}
return false;
}
bool LessParser::processParameterMixin(Selector* selector, Ruleset* parent) {
ParameterRuleset* mixin = getParameterRuleset(selector);
list<TokenList*>* arguments;
list<TokenList*>::iterator ait;
list<string> parameters;
list<string>::iterator pit;
vector<Declaration*>* declarations;
vector<Declaration*>::iterator it;
Declaration* declaration;
TokenList* variable;
TokenList* argsCombined;
if (mixin == NULL)
return false;
// new scope
valueProcessor->pushScope();
// pull values
arguments = processArguments(selector);
parameters = mixin->getKeywords();
argsCombined = new TokenList();
// combine with parameter names and add to local scope
ait = arguments->begin();
for(pit = parameters.begin(); pit != parameters.end(); pit++) {
if (ait != arguments->end()) {
valueProcessor->putVariable(*pit, *ait);
argsCombined->push((*ait)->clone());
ait++;
} else {
variable = mixin->getDefault(*pit);
if (variable == NULL) {
throw new ParseException(*selector->toString(),
"at least one more argument");
}
valueProcessor->putVariable(*pit, variable->clone());
argsCombined->push(variable->clone());
}
argsCombined->push(new Token(" ", Token::WHITESPACE));
}
if (argsCombined->size() > 0)
delete argsCombined->pop();
valueProcessor->putVariable("@arguments", argsCombined);
declarations = mixin->getDeclarations();
for (it = declarations->begin(); it < declarations->end(); it++) {
declaration = (*it)->clone();
valueProcessor->processValue(declaration->getValue());
parent->addDeclaration(declaration);
}
valueProcessor->popScope();
return true;
}
list<TokenList*>* LessParser::processArguments(TokenList* arguments) {
TokenList* value;
TokenListIterator* it = arguments->iterator();
Token* current;
list<TokenList*>* ret = new list<TokenList*>();
while (it->hasNext() &&
it->next()->type != Token::PAREN_OPEN) {
}
while (it->hasNext()) {
value = new TokenList();
while (it->hasNext()) {
current = it->next();
if (current->str == "," || current->type == Token::PAREN_CLOSED)
break;
value->push(current->clone());
}
valueProcessor->processValue(value);
ret->push_back(value);
}
return ret;
}
ParameterRuleset* LessParser::getParameterRuleset(Selector* selector) {
vector<ParameterRuleset*>::iterator it;
TokenList key;
TokenListIterator* tli = selector->iterator();
Token* current;
while (tli->hasNext()) {
current = tli->next();
if (current->type == Token::PAREN_OPEN)
break;
key.push(current->clone());
}
delete tli;
for (it = parameterRulesets.begin(); it < parameterRulesets.end(); it++) {
if ((*it)->getSelector()->equals(&key))
return *it;
}
return NULL;
}
void LessParser::importFile(string filename, Stylesheet* stylesheet) {
ifstream* in = new ifstream(filename.c_str());
if (in->fail() || in->bad())
throw new ParseException(filename, "existing file");
LessTokenizer* tokenizer = new LessTokenizer(in);
LessParser* parser = new LessParser(tokenizer);
parser->parseStylesheet(stylesheet);
in->close();
delete parser;
delete tokenizer;
delete in;
}
<commit_msg>Fixed bug so a mixin that takes parameters can have a space between the name and the arguments. '.selector (arg)' is now identical to '.selector(arg)'.<commit_after>/*
* Copyright 2012 Bram van der Kroef
*
* This file is part of LESS CSS Compiler.
*
* LESS CSS Compiler 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.
*
* LESS CSS Compiler 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 LESS CSS Compiler. If not, see <http://www.gnu.org/licenses/>.
*
* Author: Bram van der Kroef <[email protected]>
*/
#include "LessParser.h"
bool LessParser::parseStatement(Stylesheet* stylesheet) {
return parseRuleset(stylesheet) || parseAtRuleOrVariable(stylesheet);
}
bool LessParser::parseAtRuleOrVariable (Stylesheet* stylesheet) {
string keyword, import;
TokenList* rule;
AtRule* atrule = NULL;
if (tokenizer->getTokenType() != Token::ATKEYWORD)
return false;
keyword = tokenizer->getToken()->str;
tokenizer->readNextToken();
skipWhitespace();
if (!parseVariable(keyword)) {
rule = new TokenList();
while(parseAny(rule)) {};
if (!parseBlock(rule)) {
if (tokenizer->getTokenType() != Token::DELIMITER) {
throw new ParseException(tokenizer->getToken()->str,
"delimiter (';') at end of @-rule");
}
tokenizer->readNextToken();
skipWhitespace();
}
// parse import
if (keyword == "@import") {
if (rule->size() != 1 ||
rule->front()->type != Token::STRING)
throw new ParseException(*rule->toString(), "A string with the \
file path");
import = rule->front()->str;
if (import.size() < 5 ||
import.substr(import.size() - 5, 4) != ".css") {
if (import.size() < 6 || import.substr(import.size() - 6, 5) != ".less")
import.insert(import.size() - 1, ".less");
importFile(import.substr(1, import.size() - 2), stylesheet);
return true;
}
}
atrule = new AtRule(new string(keyword));
atrule->setRule(rule);
stylesheet->addAtRule(atrule);
}
return true;
}
bool LessParser::parseVariable (string keyword = "") {
TokenList* rule;
if (keyword == "") {
if (tokenizer->getTokenType() != Token::ATKEYWORD)
return false;
keyword = tokenizer->getToken()->str;
tokenizer->readNextToken();
skipWhitespace();
if (tokenizer->getTokenType() != Token::COLON)
throw new ParseException(tokenizer->getToken()->str,
"colon (':') following @keyword in \
variable declaration.");
} else if (tokenizer->getTokenType() != Token::COLON)
return false;
tokenizer->readNextToken();
skipWhitespace();
rule = parseValue();
if (rule == NULL || rule->size() == 0) {
throw new ParseException(tokenizer->getToken()->str,
"value for variable");
}
if (tokenizer->getTokenType() != Token::DELIMITER) {
throw new ParseException(tokenizer->getToken()->str,
"delimiter (';') at end of @-rule");
}
valueProcessor->putVariable(keyword, rule);
tokenizer->readNextToken();
skipWhitespace();
return true;
}
bool LessParser::parseRuleset (Stylesheet* stylesheet,
Selector* selector) {
Ruleset* ruleset = NULL;
ParameterRuleset* pruleset;
list<string> parameters;
list<string>::iterator pit;
if (selector == NULL)
selector = parseSelector();
if (tokenizer->getTokenType() != Token::BRACKET_OPEN) {
if (selector == NULL)
return false;
else {
throw new ParseException(tokenizer->getToken()->str,
"a declaration block ('{...}')");
}
}
tokenizer->readNextToken();
// add new scope for the ruleset
valueProcessor->pushScope();
if (selector->back()->type != Token::PAREN_CLOSED) {
ruleset = new Ruleset(selector);
stylesheet->addRuleset(ruleset);
} else {
ruleset = pruleset = new ParameterRuleset(selector);
parameterRulesets.push_back(pruleset);
// Add a NULL value to the local scope for each parameter so they
// don't get replaced in the ruleset. For example this statement:
// @x: 5; .class (@x: 0) {left: @x }
// 'left: @x' would be replaced with 'left: 5' if we didn't do this
parameters = pruleset->getKeywords();
for(pit = parameters.begin(); pit != parameters.end(); pit++) {
valueProcessor->putVariable(*pit, NULL);
}
}
skipWhitespace();
parseRulesetStatement(stylesheet, ruleset);
// remove scope
valueProcessor->popScope();
if (tokenizer->getTokenType() != Token::BRACKET_CLOSED) {
throw new ParseException(tokenizer->getToken()->str,
"end of declaration block ('}')");
}
tokenizer->readNextToken();
skipWhitespace();
return true;
}
bool LessParser::parseRulesetStatement (Stylesheet* stylesheet,
Ruleset* ruleset) {
Declaration* declaration;
Selector* selector = parseSelector();
TokenList* value;
if (selector == NULL) {
if (parseVariable()) {
parseRulesetStatement(stylesheet, ruleset);
return true;
}
return false;
}
// a selector followed by a ruleset is a nested rule
if (parseNestedRule(selector, ruleset, stylesheet)) {
parseRulesetStatement(stylesheet, ruleset);
return true;
// a selector by itself might be a mixin.
} else if (parseMixin(selector, ruleset, stylesheet)) {
delete selector;
if (tokenizer->getTokenType() == Token::DELIMITER) {
tokenizer->readNextToken();
skipWhitespace();
parseRulesetStatement(stylesheet, ruleset);
}
return true;
}
// if we can parse a property and the next token is a COLON then the
// statement is a declaration.
if (selector->size() > 1 &&
selector->front()->type == Token::IDENTIFIER &&
selector->at(1)->type == Token::COLON) {
declaration = new Declaration(new string(selector->front()->str));
delete selector->shift();
delete selector->shift();
// parse any leftover value parts.
value = CssParser::parseValue();
if (value != NULL) {
selector->push(value);
delete value;
}
valueProcessor->processValue(selector);
declaration->setValue(selector);
ruleset->addDeclaration(declaration);
if (tokenizer->getTokenType() == Token::DELIMITER) {
tokenizer->readNextToken();
skipWhitespace();
parseRulesetStatement(stylesheet, ruleset);
}
return true;
} else {
throw new ParseException(*selector->toString(),
"a mixin that has been defined");
}
}
bool LessParser::parseNestedRule(Selector* selector, Ruleset*
ruleset, Stylesheet* stylesheet) {
if (tokenizer->getTokenType() != Token::BRACKET_OPEN)
return false;
selector->addPrefix(ruleset->getSelector());
parseRuleset(stylesheet, selector);
return true;
}
Declaration* LessParser::parseDeclaration (string* property) {
Declaration* declaration;
skipWhitespace();
if (tokenizer->getTokenType() != Token::COLON)
return NULL;
tokenizer->readNextToken();
skipWhitespace();
declaration = new Declaration(property);
TokenList* value = parseValue();
if (value == NULL) {
throw new ParseException(tokenizer->getToken()->str,
"value for property");
}
declaration->setValue(value);
return declaration;
}
TokenList* LessParser::parseValue () {
TokenList* value = CssParser::parseValue();
if (value != NULL)
valueProcessor->processValue(value);
return value;
}
bool LessParser::parseMixin(Selector* selector, Ruleset* ruleset,
Stylesheet* stylesheet) {
Ruleset* mixin;
vector<Declaration*>* declarations;
vector<Declaration*>::iterator it;
if (processParameterMixin(selector, ruleset)) {
return true;
} else if((mixin = stylesheet->getRuleset(selector)) != NULL) {
declarations = mixin->getDeclarations();
for (it = declarations->begin(); it < declarations->end(); it++) {
ruleset->addDeclaration((*it)->clone());
}
return true;
}
return false;
}
bool LessParser::processParameterMixin(Selector* selector, Ruleset* parent) {
ParameterRuleset* mixin = getParameterRuleset(selector);
list<TokenList*>* arguments;
list<TokenList*>::iterator ait;
list<string> parameters;
list<string>::iterator pit;
vector<Declaration*>* declarations;
vector<Declaration*>::iterator it;
Declaration* declaration;
TokenList* variable;
TokenList* argsCombined;
if (mixin == NULL)
return false;
// new scope
valueProcessor->pushScope();
// pull values
arguments = processArguments(selector);
parameters = mixin->getKeywords();
argsCombined = new TokenList();
// combine with parameter names and add to local scope
ait = arguments->begin();
for(pit = parameters.begin(); pit != parameters.end(); pit++) {
if (ait != arguments->end()) {
valueProcessor->putVariable(*pit, *ait);
argsCombined->push((*ait)->clone());
ait++;
} else {
variable = mixin->getDefault(*pit);
if (variable == NULL) {
throw new ParseException(*selector->toString(),
"at least one more argument");
}
valueProcessor->putVariable(*pit, variable->clone());
argsCombined->push(variable->clone());
}
argsCombined->push(new Token(" ", Token::WHITESPACE));
}
if (argsCombined->size() > 0)
delete argsCombined->pop();
valueProcessor->putVariable("@arguments", argsCombined);
declarations = mixin->getDeclarations();
for (it = declarations->begin(); it < declarations->end(); it++) {
declaration = (*it)->clone();
valueProcessor->processValue(declaration->getValue());
parent->addDeclaration(declaration);
}
valueProcessor->popScope();
return true;
}
list<TokenList*>* LessParser::processArguments(TokenList* arguments) {
TokenList* value;
TokenListIterator* it = arguments->iterator();
Token* current;
list<TokenList*>* ret = new list<TokenList*>();
while (it->hasNext() &&
it->next()->type != Token::PAREN_OPEN) {
}
while (it->hasNext()) {
value = new TokenList();
while (it->hasNext()) {
current = it->next();
if (current->str == "," || current->type == Token::PAREN_CLOSED)
break;
value->push(current->clone());
}
valueProcessor->processValue(value);
ret->push_back(value);
}
return ret;
}
ParameterRuleset* LessParser::getParameterRuleset(Selector* selector) {
vector<ParameterRuleset*>::iterator it;
TokenList key;
TokenListIterator* tli = selector->iterator();
Token* current;
while (tli->hasNext()) {
current = tli->next();
if (current->type == Token::PAREN_OPEN)
break;
key.push(current->clone());
}
delete tli;
// delete trailing whitespace
while (key.back()->type == Token::WHITESPACE) {
delete key.pop();
}
for (it = parameterRulesets.begin(); it < parameterRulesets.end(); it++) {
if ((*it)->getSelector()->equals(&key))
return *it;
}
return NULL;
}
void LessParser::importFile(string filename, Stylesheet* stylesheet) {
ifstream* in = new ifstream(filename.c_str());
if (in->fail() || in->bad())
throw new ParseException(filename, "existing file");
LessTokenizer* tokenizer = new LessTokenizer(in);
LessParser* parser = new LessParser(tokenizer);
parser->parseStylesheet(stylesheet);
in->close();
delete parser;
delete tokenizer;
delete in;
}
<|endoftext|> |
<commit_before>/*
* author: Max Kellermann <[email protected]>
*/
#ifndef LINE_PARSER_HXX
#define LINE_PARSER_HXX
#include "util/StringUtil.hxx"
#include "util/CharUtil.hxx"
#include <stdexcept>
class LineParser {
char *p;
public:
using Error = std::runtime_error;
explicit LineParser(char *_p):p(StripLeft(_p)) {
StripRight(p);
}
void Strip() {
p = StripLeft(p);
}
char front() const {
return *p;
}
bool IsEnd() const {
return front() == 0;
}
void ExpectWhitespace() {
if (!IsWhitespaceNotNull(front()))
throw Error("Syntax error");
++p;
Strip();
}
void ExpectEnd() {
if (!IsEnd())
throw Error(std::string("Unexpected tokens at end of line: ") + p);
}
void ExpectSymbol(char symbol) {
if (front() != symbol)
throw Error(std::string("'") + symbol + "' expected");
++p;
Strip();
}
void ExpectSymbolAndEol(char symbol) {
ExpectSymbol(symbol);
if (!IsEnd())
throw Error(std::string("Unexpected tokens after '")
+ symbol + "': " + p);
}
bool SkipSymbol(char symbol) {
bool found = front() == symbol;
if (found)
++p;
return found;
}
bool SkipSymbol(char a, char b) {
bool found = p[0] == a && p[1] == b;
if (found)
p += 2;
return found;
}
/**
* If the next word matches the given parameter, then skip it and
* return true. If not, the method returns false, leaving the
* object unmodified.
*/
bool SkipWord(const char *word);
const char *NextWord();
char *NextValue();
char *NextUnescape();
bool NextBool();
unsigned NextPositiveInteger();
const char *ExpectWord();
/**
* Expect a non-empty value.
*/
char *ExpectValue();
/**
* Expect a non-empty value and end-of-line.
*/
char *ExpectValueAndEnd();
private:
char *NextUnquotedValue();
char *NextQuotedValue(char stop);
static constexpr bool IsWordChar(char ch) {
return IsAlphaNumericASCII(ch) || ch == '_';
}
static constexpr bool IsUnquotedChar(char ch) {
return IsWordChar(ch) || ch == '.' || ch == '-' || ch == ':';
}
static constexpr bool IsQuote(char ch) {
return ch == '"' || ch == '\'';
}
};
#endif
<commit_msg>LineParser: add method Rest()<commit_after>/*
* author: Max Kellermann <[email protected]>
*/
#ifndef LINE_PARSER_HXX
#define LINE_PARSER_HXX
#include "util/StringUtil.hxx"
#include "util/CharUtil.hxx"
#include <stdexcept>
class LineParser {
char *p;
public:
using Error = std::runtime_error;
explicit LineParser(char *_p):p(StripLeft(_p)) {
StripRight(p);
}
char *Rest() {
return p;
}
void Strip() {
p = StripLeft(p);
}
char front() const {
return *p;
}
bool IsEnd() const {
return front() == 0;
}
void ExpectWhitespace() {
if (!IsWhitespaceNotNull(front()))
throw Error("Syntax error");
++p;
Strip();
}
void ExpectEnd() {
if (!IsEnd())
throw Error(std::string("Unexpected tokens at end of line: ") + p);
}
void ExpectSymbol(char symbol) {
if (front() != symbol)
throw Error(std::string("'") + symbol + "' expected");
++p;
Strip();
}
void ExpectSymbolAndEol(char symbol) {
ExpectSymbol(symbol);
if (!IsEnd())
throw Error(std::string("Unexpected tokens after '")
+ symbol + "': " + p);
}
bool SkipSymbol(char symbol) {
bool found = front() == symbol;
if (found)
++p;
return found;
}
bool SkipSymbol(char a, char b) {
bool found = p[0] == a && p[1] == b;
if (found)
p += 2;
return found;
}
/**
* If the next word matches the given parameter, then skip it and
* return true. If not, the method returns false, leaving the
* object unmodified.
*/
bool SkipWord(const char *word);
const char *NextWord();
char *NextValue();
char *NextUnescape();
bool NextBool();
unsigned NextPositiveInteger();
const char *ExpectWord();
/**
* Expect a non-empty value.
*/
char *ExpectValue();
/**
* Expect a non-empty value and end-of-line.
*/
char *ExpectValueAndEnd();
private:
char *NextUnquotedValue();
char *NextQuotedValue(char stop);
static constexpr bool IsWordChar(char ch) {
return IsAlphaNumericASCII(ch) || ch == '_';
}
static constexpr bool IsUnquotedChar(char ch) {
return IsWordChar(ch) || ch == '.' || ch == '-' || ch == ':';
}
static constexpr bool IsQuote(char ch) {
return ch == '"' || ch == '\'';
}
};
#endif
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "HList.h"
#include "../events/SetCursorEvent.h"
#include "VisualizationBase/src/items/VList.h"
#include "VisualizationBase/src/Scene.h"
#include "VisualizationBase/src/cursor/LayoutCursor.h"
#include "FilePersistence/src/SystemClipboard.h"
#include "ModelBase/src/nodes/List.h"
namespace Interaction {
HList::HList()
{
}
HList* HList::instance()
{
static HList h;
return &h;
}
void HList::focusOutEvent(Visualization::Item *target, QFocusEvent *event)
{
Visualization::VList* list = static_cast<Visualization::VList*> (target);
if (list->node()->isEmpty() && list->style()->showTipWhenSelectedAndEmpty())
list->setUpdateNeeded(Visualization::Item::StandardUpdate);
GenericHandler::focusOutEvent(target, event);
}
void HList::keyPressEvent(Visualization::Item *target, QKeyEvent *event)
{
Visualization::VList* list = static_cast<Visualization::VList*> (target);
bool processed = false;
if (event->matches(QKeySequence::Paste) && list->scene()->mainCursor()->owner() == list &&
!list->ignoresCopyAndPaste())
{
processed = true;
FilePersistence::SystemClipboard clipboard;
int selIndex = list->correspondingSceneCursor<Visualization::LayoutCursor>()->index();
if (selIndex > list->length()) selIndex = list->length();
if (selIndex < 0) selIndex = 0;
selIndex += list->rangeBegin();
if (clipboard.numNodes() > 0)
{
Model::List* listNode = DCast<Model::List> (list->node());
FilePersistence::SystemClipboard clipboard;
listNode->beginModification("paste into list");
if (listNode) listNode->paste(clipboard, selIndex);
listNode->endModification();
target->setUpdateNeeded(Visualization::Item::StandardUpdate);
}
}
else if (event->modifiers() == (Qt::ControlModifier | Qt::ShiftModifier) && event->key() == Qt::Key_V &&
!list->ignoresCopyAndPaste())
{
processed = true;
FilePersistence::SystemClipboard clipboard;
int selIndex = list->focusedNodeIndex();
if (clipboard.numNodes() > 0 && selIndex >= 0)
{
Model::List* listNode = DCast<Model::List> (list->node());
FilePersistence::SystemClipboard clipboard;
listNode->beginModification("paste into list");
if (listNode) listNode->paste(clipboard, selIndex+1);
listNode->endModification();
target->setUpdateNeeded(Visualization::Item::StandardUpdate);
}
}
if (!list->suppressDefaultRemovalHandler() && event->modifiers() == Qt::NoModifier
&& (event->key() == Qt::Key_Delete || event->key() == Qt::Key_Backspace)
&& list->scene()->mainCursor() && list->scene()->mainCursor()->owner() == list)
{
processed = true;
int index = list->correspondingSceneCursor<Visualization::LayoutCursor>()->index();
if (event->key() == Qt::Key_Backspace) --index;
// Delete the node corresponding to index. Make sure not to delete invisible nodes, that this list is currently
// not displaying. Check the boundaries on the layout, not on the nodes() array.
if (index >=0 && index < list->length())
removeNodeAndSetCursor(list, index + list->rangeBegin());
}
if ( event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return
|| (event->key() == Qt::Key_Tab && event->modifiers() == Qt::NoModifier)
|| ( !list->suppressDefaultRemovalHandler() &&
(event->modifiers() == Qt::NoModifier || event->modifiers() == Qt::ShiftModifier)
&& !event->text().isEmpty() && event->text().at(0).isLetterOrNumber()))
{
bool enter = event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return;
bool createDown = enter && event->modifiers() == Qt::NoModifier && !list->style()->itemsStyle().isHorizontal();
bool createRight = enter && event->modifiers() == Qt::ShiftModifier && list->style()->itemsStyle().isHorizontal();
if ( !enter || (enter && list->isShowingEmptyTip()) || createDown || createRight )
{
auto newElem = list->node()->createDefaultElement();
if (newElem)
{
processed = true;
int index = -1;
if (list->isShowingEmptyTip()) index = 0;
else if (list->scene()->mainCursor() && list->scene()->mainCursor()->owner() == list)
index = list->correspondingSceneCursor<Visualization::LayoutCursor>()->index();
else
{
index = list->focusedItemIndex();
if (index >= 0) ++index;
}
// At this point, index indicates where in the LAYOUT we should put the new element.
if (index >= 0 && index + list->rangeBegin() <= list->node()->size())
{
list->node()->beginModification("add new list element");
list->node()->insert(index + list->rangeBegin(), newElem);
list->node()->endModification();
list->setUpdateNeeded(Visualization::Item::StandardUpdate);
target->scene()->addPostEventAction( new SetCursorEvent{list, newElem,
list->style()->itemsStyle().isHorizontal()
? SetCursorEvent::CursorOnLeft : SetCursorEvent::CursorOnTop});
// If this was not an enter key and not a tab, then it must have been a letter.
// Add a keyboard event for this letter
if (!enter && event->key() != Qt::Key_Tab )
{
qApp->postEvent(target->scene(), new QKeyEvent{QEvent::KeyPress, event->key(),
event->modifiers(), event->text(), event->isAutoRepeat(), (ushort)event->count()});
}
}
}
}
}
if (!processed) GenericHandler::keyPressEvent(target, event);
}
void HList::scheduleSetCursor(Visualization::VList* list, Model::Node* listNodeToSelect,
SetCursorEvent::CursorPlacement howToSelectItem)
{
list->scene()->addPostEventAction( new SetCursorEvent{list, listNodeToSelect, howToSelectItem});
}
void HList::scheduleSetCursor(Visualization::VList* list, int setCursorNodeIndex)
{
Q_ASSERT(setCursorNodeIndex >= 0 && setCursorNodeIndex <= list->node()->size());
list->scene()->addPostEventAction(new SetCursorEvent{
[=](){
int setCursorItemIndex = 0;
if (setCursorNodeIndex < list->rangeBegin()) setCursorItemIndex = 0;
else if (setCursorNodeIndex > list->rangeEnd()) setCursorItemIndex = list->length();
else setCursorItemIndex = setCursorNodeIndex - list->rangeBegin();
if (setCursorItemIndex == 0) return list->length() ? list->itemAt<Visualization::Item>(0) : list;
else return list->itemAt<Visualization::Item>(setCursorItemIndex-1);
},
[=](){
int setCursorItemIndex = 0;
if (setCursorNodeIndex < list->rangeBegin()) setCursorItemIndex = 0;
else if (setCursorNodeIndex > list->rangeEnd()) setCursorItemIndex = list->length();
else setCursorItemIndex = setCursorNodeIndex - list->rangeBegin();
if (setCursorItemIndex == 0)
return (list->style()->itemsStyle().isHorizontal()
? SetCursorEvent::CursorLeftOf : SetCursorEvent::CursorAboveOf);
else
return (list->style()->itemsStyle().isHorizontal()
? SetCursorEvent::CursorRightOf : SetCursorEvent::CursorBelowOf);
}
});
}
void HList::removeNodeAndSetCursor(Visualization::VList* list, int removeAtNodeIndex, bool setCursorDown,
SetCursorEvent::CursorPlacement howToSelectItem)
{
auto node = list->node();
Q_ASSERT(removeAtNodeIndex >= 0 && removeAtNodeIndex < node->size());
// Do not remove nodes which are not visible in this list.
if (removeAtNodeIndex < list->rangeBegin() || removeAtNodeIndex >= list->rangeEnd()) return;
node->beginModification("Remove list item");
node->remove(removeAtNodeIndex);
node->endModification();
list->setUpdateNeeded(Visualization::Item::StandardUpdate);
if (!setCursorDown) --removeAtNodeIndex;
if (removeAtNodeIndex >=0 && removeAtNodeIndex < node->size())
scheduleSetCursor(list, node->at<Model::Node>(removeAtNodeIndex), howToSelectItem);
else
scheduleSetCursor(list, removeAtNodeIndex < 0 ? 0 : removeAtNodeIndex);
}
void HList::removeNodeAndSetCursor(Visualization::VList* list, int removeAtNodeIndex)
{
auto node = list->node();
Q_ASSERT(removeAtNodeIndex >= 0 && removeAtNodeIndex < node->size());
// Do not remove nodes which are not visible in this list.
if (removeAtNodeIndex < list->rangeBegin() || removeAtNodeIndex >= list->rangeEnd()) return;
node->beginModification("Remove list item");
node->remove(removeAtNodeIndex);
node->endModification();
list->setUpdateNeeded(Visualization::Item::StandardUpdate);
scheduleSetCursor(list, removeAtNodeIndex);
}
void HList::removeNodeAndSetCursor(Visualization::VList* list, Model::Node* removeNode, bool setCursorDown,
SetCursorEvent::CursorPlacement howToSelectItem)
{
removeNodeAndSetCursor(list, list->node()->indexOf(removeNode), setCursorDown, howToSelectItem);
}
void HList::removeNodeAndSetCursor(Visualization::VList* list, Model::Node* removeNode)
{
removeNodeAndSetCursor(list, list->node()->indexOf(removeNode));
}
}
<commit_msg>Do no attempt to set a cursor on a deleted list<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "HList.h"
#include "../events/SetCursorEvent.h"
#include "VisualizationBase/src/items/VList.h"
#include "VisualizationBase/src/Scene.h"
#include "VisualizationBase/src/cursor/LayoutCursor.h"
#include "FilePersistence/src/SystemClipboard.h"
#include "ModelBase/src/nodes/List.h"
namespace Interaction {
HList::HList()
{
}
HList* HList::instance()
{
static HList h;
return &h;
}
void HList::focusOutEvent(Visualization::Item *target, QFocusEvent *event)
{
Visualization::VList* list = static_cast<Visualization::VList*> (target);
if (list->node()->isEmpty() && list->style()->showTipWhenSelectedAndEmpty())
list->setUpdateNeeded(Visualization::Item::StandardUpdate);
GenericHandler::focusOutEvent(target, event);
}
void HList::keyPressEvent(Visualization::Item *target, QKeyEvent *event)
{
Visualization::VList* list = static_cast<Visualization::VList*> (target);
bool processed = false;
if (event->matches(QKeySequence::Paste) && list->scene()->mainCursor()->owner() == list &&
!list->ignoresCopyAndPaste())
{
processed = true;
FilePersistence::SystemClipboard clipboard;
int selIndex = list->correspondingSceneCursor<Visualization::LayoutCursor>()->index();
if (selIndex > list->length()) selIndex = list->length();
if (selIndex < 0) selIndex = 0;
selIndex += list->rangeBegin();
if (clipboard.numNodes() > 0)
{
Model::List* listNode = DCast<Model::List> (list->node());
FilePersistence::SystemClipboard clipboard;
listNode->beginModification("paste into list");
if (listNode) listNode->paste(clipboard, selIndex);
listNode->endModification();
target->setUpdateNeeded(Visualization::Item::StandardUpdate);
}
}
else if (event->modifiers() == (Qt::ControlModifier | Qt::ShiftModifier) && event->key() == Qt::Key_V &&
!list->ignoresCopyAndPaste())
{
processed = true;
FilePersistence::SystemClipboard clipboard;
int selIndex = list->focusedNodeIndex();
if (clipboard.numNodes() > 0 && selIndex >= 0)
{
Model::List* listNode = DCast<Model::List> (list->node());
FilePersistence::SystemClipboard clipboard;
listNode->beginModification("paste into list");
if (listNode) listNode->paste(clipboard, selIndex+1);
listNode->endModification();
target->setUpdateNeeded(Visualization::Item::StandardUpdate);
}
}
if (!list->suppressDefaultRemovalHandler() && event->modifiers() == Qt::NoModifier
&& (event->key() == Qt::Key_Delete || event->key() == Qt::Key_Backspace)
&& list->scene()->mainCursor() && list->scene()->mainCursor()->owner() == list)
{
processed = true;
int index = list->correspondingSceneCursor<Visualization::LayoutCursor>()->index();
if (event->key() == Qt::Key_Backspace) --index;
// Delete the node corresponding to index. Make sure not to delete invisible nodes, that this list is currently
// not displaying. Check the boundaries on the layout, not on the nodes() array.
if (index >=0 && index < list->length())
removeNodeAndSetCursor(list, index + list->rangeBegin());
}
if ( event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return
|| (event->key() == Qt::Key_Tab && event->modifiers() == Qt::NoModifier)
|| ( !list->suppressDefaultRemovalHandler() &&
(event->modifiers() == Qt::NoModifier || event->modifiers() == Qt::ShiftModifier)
&& !event->text().isEmpty() && event->text().at(0).isLetterOrNumber()))
{
bool enter = event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return;
bool createDown = enter && event->modifiers() == Qt::NoModifier && !list->style()->itemsStyle().isHorizontal();
bool createRight = enter && event->modifiers() == Qt::ShiftModifier && list->style()->itemsStyle().isHorizontal();
if ( !enter || (enter && list->isShowingEmptyTip()) || createDown || createRight )
{
auto newElem = list->node()->createDefaultElement();
if (newElem)
{
processed = true;
int index = -1;
if (list->isShowingEmptyTip()) index = 0;
else if (list->scene()->mainCursor() && list->scene()->mainCursor()->owner() == list)
index = list->correspondingSceneCursor<Visualization::LayoutCursor>()->index();
else
{
index = list->focusedItemIndex();
if (index >= 0) ++index;
}
// At this point, index indicates where in the LAYOUT we should put the new element.
if (index >= 0 && index + list->rangeBegin() <= list->node()->size())
{
list->node()->beginModification("add new list element");
list->node()->insert(index + list->rangeBegin(), newElem);
list->node()->endModification();
list->setUpdateNeeded(Visualization::Item::StandardUpdate);
target->scene()->addPostEventAction( new SetCursorEvent{list, newElem,
list->style()->itemsStyle().isHorizontal()
? SetCursorEvent::CursorOnLeft : SetCursorEvent::CursorOnTop});
// If this was not an enter key and not a tab, then it must have been a letter.
// Add a keyboard event for this letter
if (!enter && event->key() != Qt::Key_Tab )
{
qApp->postEvent(target->scene(), new QKeyEvent{QEvent::KeyPress, event->key(),
event->modifiers(), event->text(), event->isAutoRepeat(), (ushort)event->count()});
}
}
}
}
}
if (!processed) GenericHandler::keyPressEvent(target, event);
}
void HList::scheduleSetCursor(Visualization::VList* list, Model::Node* listNodeToSelect,
SetCursorEvent::CursorPlacement howToSelectItem)
{
list->scene()->addPostEventAction( new SetCursorEvent{list, listNodeToSelect, howToSelectItem});
}
void HList::scheduleSetCursor(Visualization::VList* list, int setCursorNodeIndex)
{
Q_ASSERT(setCursorNodeIndex >= 0 && setCursorNodeIndex <= list->node()->size());
// We store these, since the target list might have been deleted
QList<Visualization::Item*> parentItems;
Visualization::Item* parent = list;
while (parent)
{
parentItems.prepend(parent);
parent = parent->parent();
}
auto deepestExistingItem = [parentItems]()
{
for (int i = 1; i < parentItems.size(); ++i)
if (!parentItems[i-1]->childItems().contains(parentItems[i]))
return parentItems[i-1];
return parentItems.last();
};
list->scene()->addPostEventAction(new SetCursorEvent{
[=](){
auto deepestItem = deepestExistingItem();
if (deepestItem != list) return deepestItem;
int setCursorItemIndex = 0;
if (setCursorNodeIndex < list->rangeBegin()) setCursorItemIndex = 0;
else if (setCursorNodeIndex > list->rangeEnd()) setCursorItemIndex = list->length();
else setCursorItemIndex = setCursorNodeIndex - list->rangeBegin();
if (setCursorItemIndex == 0) return list->length() ? list->itemAt<Visualization::Item>(0) : list;
else return list->itemAt<Visualization::Item>(setCursorItemIndex-1);
},
[=](){
auto deepestItem = deepestExistingItem();
if (deepestItem != list) return SetCursorEvent::CursorDefault;
int setCursorItemIndex = 0;
if (setCursorNodeIndex < list->rangeBegin()) setCursorItemIndex = 0;
else if (setCursorNodeIndex > list->rangeEnd()) setCursorItemIndex = list->length();
else setCursorItemIndex = setCursorNodeIndex - list->rangeBegin();
if (setCursorItemIndex == 0)
return (list->style()->itemsStyle().isHorizontal()
? SetCursorEvent::CursorLeftOf : SetCursorEvent::CursorAboveOf);
else
return (list->style()->itemsStyle().isHorizontal()
? SetCursorEvent::CursorRightOf : SetCursorEvent::CursorBelowOf);
}
});
}
void HList::removeNodeAndSetCursor(Visualization::VList* list, int removeAtNodeIndex, bool setCursorDown,
SetCursorEvent::CursorPlacement howToSelectItem)
{
auto node = list->node();
Q_ASSERT(removeAtNodeIndex >= 0 && removeAtNodeIndex < node->size());
// Do not remove nodes which are not visible in this list.
if (removeAtNodeIndex < list->rangeBegin() || removeAtNodeIndex >= list->rangeEnd()) return;
node->beginModification("Remove list item");
node->remove(removeAtNodeIndex);
node->endModification();
list->setUpdateNeeded(Visualization::Item::StandardUpdate);
if (!setCursorDown) --removeAtNodeIndex;
if (removeAtNodeIndex >=0 && removeAtNodeIndex < node->size())
scheduleSetCursor(list, node->at<Model::Node>(removeAtNodeIndex), howToSelectItem);
else
scheduleSetCursor(list, removeAtNodeIndex < 0 ? 0 : removeAtNodeIndex);
}
void HList::removeNodeAndSetCursor(Visualization::VList* list, int removeAtNodeIndex)
{
auto node = list->node();
Q_ASSERT(removeAtNodeIndex >= 0 && removeAtNodeIndex < node->size());
// Do not remove nodes which are not visible in this list.
if (removeAtNodeIndex < list->rangeBegin() || removeAtNodeIndex >= list->rangeEnd()) return;
node->beginModification("Remove list item");
node->remove(removeAtNodeIndex);
node->endModification();
list->setUpdateNeeded(Visualization::Item::StandardUpdate);
scheduleSetCursor(list, removeAtNodeIndex);
}
void HList::removeNodeAndSetCursor(Visualization::VList* list, Model::Node* removeNode, bool setCursorDown,
SetCursorEvent::CursorPlacement howToSelectItem)
{
removeNodeAndSetCursor(list, list->node()->indexOf(removeNode), setCursorDown, howToSelectItem);
}
void HList::removeNodeAndSetCursor(Visualization::VList* list, Model::Node* removeNode)
{
removeNodeAndSetCursor(list, list->node()->indexOf(removeNode));
}
}
<|endoftext|> |
<commit_before>#include "Platform/HardwareInfo.h"
#if INTRA_PLATFORM_OS==INTRA_PLATFORM_OS_Windows
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4668)
#endif
#include <Windows.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
namespace Intra {
SystemMemoryInfo SystemMemoryInfo::Get()
{
SystemMemoryInfo result;
MEMORYSTATUSEX statex;
statex.dwLength = sizeof (statex);
GlobalMemoryStatusEx(&statex);
result.TotalPhysicalMemory = statex.ullTotalPhys;
result.FreePhysicalMemory = statex.ullAvailPhys;
result.TotalSwapMemory = statex.ullTotalPageFile;
result.FreeSwapMemory = statex.ullAvailPageFile;
result.TotalVirtualMemory = statex.ullTotalVirtual;
result.FreeVirtualMemory = statex.ullAvailVirtual;
return result;
}
}
#elif(INTRA_PLATFORM_OS==INTRA_PLATFORM_OS_Linux)
#include <unistd.h>
namespace Intra {
SystemMemoryInfo SystemMemoryInfo::Get()
{
SystemMemoryInfo result;
/*#if(INTRA_PLATFORM_OS==INTRA_PLATFORM_OS_Linux || INTRA_PLATFORM_OS==INTRA_PLATFORM_OS_FreeBSD)
result.TotalPhysicalMemory = ulong64(sysconf(_SC_PHYS_PAGES))*sysconf(_SC_PAGE_SIZE);
#elif(INTRA_PLATFORM_OS==INTRA_PLATFORM_OS_MacOS)
ulong64 mem=0;
size_t len = sizeof(mem);
sysctlbyname("hw.memsize", &result.TotalPhysicalMemory, &len, null, 0);
#endif*/
struct sysinfo info;
sysinfo(&info);
result.TotalPhysicalMemory = info.totalram;
result.FreePhysicalMemory = info.freeram;
result.TotalSwapMemory = info.totalswap;
result.FreeSwapMemory = info.freeswap;
result.TotalVirtualMemory = result.TotalPhysicalMemory+result.TotalSwapMemory;
result.FreeVirtualMemory = result.FreePhysicalMemory+result.FreeSwapMemory;
return result;
}
}
#elif(INTRA_PLATFORM_OS==INTRA_PLATFORM_OS_FreeBSD)
#include <sys/types.h>
#include <sys/sysctl.h>
#include <sys/vmmeter.h>
#include <sys/limits.h>
#include <vm/vm_param.h>
static vmtotal getVMinfo()
{
vmtotal vm_info;
int mib[2] = {CTL_VM, VM_TOTAL};
size_t len = sizeof(vm_info);
sysctl(mib, 2, &vm_info, &len, null, 0);
return vm_info;
}
static int getSysCtl(int top_level, int next_level)
{
int mib[2] = {top_level, next_level}
size_t len = sizeof(ctlvalue);
int ctlvalue;
sysctl(mib, 2, &ctlvalue, &len, NULL, 0);
return ctlvalue;
}
SystemMemoryInfo SystemMemoryInfo::Get()
{
SystemMemoryInfo result;
vmtotal vmsize = getVMinfo();
result.TotalPhysicalMemory = vmsize.t_rm;
result.FreePhysicalMemory = getSysCtl(CTL_HW, HW_REALMEM);
result.TotalSwapMemory = result.TotalVirtualMemory-result.TotalPhysicalMemory;
result.FreeSwapMemory = result.FreeVirtualMemory-result.FreePhysicalMemory;
result.TotalVirtualMemory = vmsize.t_vm;
result.FreeVirtualMemory = vmsize.t_free*getSysCtl(CTL_HW, HW_PAGESIZE);
return result;
}
#endif
#if((INTRA_PLATFORM_ARCH==INTRA_PLATFORM_X86 || INTRA_PLATFORM_ARCH==INTRA_PLATFORM_X86_64) && !defined(__clang__) && defined(_MSC_VER))
#include <intrin.h>
#pragma comment(lib, "Advapi32.lib")
namespace Intra {
ProcessorInfo ProcessorInfo::Get()
{
int cpuInfo[12] = {-1};
__cpuid(cpuInfo, 0x80000002u);
__cpuid(cpuInfo+4, 0x80000003u);
__cpuid(cpuInfo+8, 0x80000004u);
ProcessorInfo result;
result.BrandString = String((const char*)cpuInfo);
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
result.LogicalProcessorNumber = (ushort)sysInfo.dwNumberOfProcessors;
//#ifdef INTRA_XP_SUPPORT
result.CoreNumber = result.LogicalProcessorNumber;
/*#else
SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX logicalProcInfoEx[16];
DWORD bufferLength = 16*sizeof(logicalProcInfoEx);
GetLogicalProcessorInformationEx(RelationProcessorPackage, logicalProcInfoEx, &bufferLength);
result.CoreNumber = ushort(bufferLength/sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX));
#endif*/
HKEY hKey;
long lError = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &hKey);
if(lError==ERROR_SUCCESS)
{
DWORD dwMHz, size=sizeof(dwMHz);
lError = RegQueryValueExA(hKey, "~MHz", null, null, (LPBYTE)&dwMHz, &size);
if(lError==ERROR_SUCCESS) result.Frequency = dwMHz*1000000ull;
}
return result;
}
}
#else
#include <IO/File.h>
namespace Intra {
ProcessorInfo ProcessorInfo::Get()
{
ProcessorInfo result;
#if(INTRA_PLATFORM_OS==INTRA_PLATFORM_OS_Linux)
String allCpuInfo = IO::DiskFile::ReadAsString("/proc/cpuinfo");
result.BrandString = allCpuInfo().Find(StringView("\nmodel name"))
.Find(':').Drop(2).ReadUntil('\n');
result.CoreNumber = allCpuInfo().Find(StringView("\ncpu cores"))
.Find(':').Drop(2).ReadUntil('\n').ParseAdvance<ushort>();
result.LogicalProcessorNumber = ushort(allCpuInfo().Count(StringView("processor ")));
result.Frequency = ulong64(1000000*allCpuInfo().Find(StringView("\ncpu MHz"))
.Find(':').Drop(2).ReadUntil('\n').ParseAdvance<double>());
#endif
return result;
}
}
#endif
<commit_msg>FreeBSD HWInfo fix<commit_after>#include "Platform/HardwareInfo.h"
#if INTRA_PLATFORM_OS==INTRA_PLATFORM_OS_Windows
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4668)
#endif
#include <Windows.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
namespace Intra {
SystemMemoryInfo SystemMemoryInfo::Get()
{
SystemMemoryInfo result;
MEMORYSTATUSEX statex;
statex.dwLength = sizeof (statex);
GlobalMemoryStatusEx(&statex);
result.TotalPhysicalMemory = statex.ullTotalPhys;
result.FreePhysicalMemory = statex.ullAvailPhys;
result.TotalSwapMemory = statex.ullTotalPageFile;
result.FreeSwapMemory = statex.ullAvailPageFile;
result.TotalVirtualMemory = statex.ullTotalVirtual;
result.FreeVirtualMemory = statex.ullAvailVirtual;
return result;
}
}
#elif(INTRA_PLATFORM_OS==INTRA_PLATFORM_OS_Linux)
#include <unistd.h>
namespace Intra {
SystemMemoryInfo SystemMemoryInfo::Get()
{
SystemMemoryInfo result;
/*#if(INTRA_PLATFORM_OS==INTRA_PLATFORM_OS_Linux || INTRA_PLATFORM_OS==INTRA_PLATFORM_OS_FreeBSD)
result.TotalPhysicalMemory = ulong64(sysconf(_SC_PHYS_PAGES))*sysconf(_SC_PAGE_SIZE);
#elif(INTRA_PLATFORM_OS==INTRA_PLATFORM_OS_MacOS)
ulong64 mem=0;
size_t len = sizeof(mem);
sysctlbyname("hw.memsize", &result.TotalPhysicalMemory, &len, null, 0);
#endif*/
struct sysinfo info;
sysinfo(&info);
result.TotalPhysicalMemory = info.totalram;
result.FreePhysicalMemory = info.freeram;
result.TotalSwapMemory = info.totalswap;
result.FreeSwapMemory = info.freeswap;
result.TotalVirtualMemory = result.TotalPhysicalMemory+result.TotalSwapMemory;
result.FreeVirtualMemory = result.FreePhysicalMemory+result.FreeSwapMemory;
return result;
}
}
#elif(INTRA_PLATFORM_OS==INTRA_PLATFORM_OS_FreeBSD)
#include <sys/types.h>
#include <sys/sysctl.h>
#include <sys/vmmeter.h>
#include <sys/limits.h>
#include <vm/vm_param.h>
static vmtotal getVMinfo()
{
vmtotal vm_info;
int mib[2] = {CTL_VM, VM_TOTAL};
size_t len = sizeof(vm_info);
sysctl(mib, 2, &vm_info, &len, null, 0);
return vm_info;
}
static int getSysCtl(int top_level, int next_level)
{
int mib[2] = {top_level, next_level};
size_t len = sizeof(ctlvalue);
int ctlvalue;
sysctl(mib, 2, &ctlvalue, &len, null, 0);
return ctlvalue;
}
namespace Intra {
SystemMemoryInfo SystemMemoryInfo::Get()
{
SystemMemoryInfo result;
vmtotal vmsize = getVMinfo();
result.TotalPhysicalMemory = ulong64(vmsize.t_rm);
result.FreePhysicalMemory = ulong64(getSysCtl(CTL_HW, HW_REALMEM));
result.TotalSwapMemory = result.TotalVirtualMemory-result.TotalPhysicalMemory);
result.FreeSwapMemory = result.FreeVirtualMemory-result.FreePhysicalMemory;
result.TotalVirtualMemory = ulong64(vmsize.t_vm);
result.FreeVirtualMemory = ulong64(vmsize.t_free)*ulong64(getSysCtl(CTL_HW, HW_PAGESIZE));
return result;
}
}
#endif
#if((INTRA_PLATFORM_ARCH==INTRA_PLATFORM_X86 || INTRA_PLATFORM_ARCH==INTRA_PLATFORM_X86_64) && !defined(__clang__) && defined(_MSC_VER))
#include <intrin.h>
#pragma comment(lib, "Advapi32.lib")
namespace Intra {
ProcessorInfo ProcessorInfo::Get()
{
int cpuInfo[12] = {-1};
__cpuid(cpuInfo, 0x80000002u);
__cpuid(cpuInfo+4, 0x80000003u);
__cpuid(cpuInfo+8, 0x80000004u);
ProcessorInfo result;
result.BrandString = String((const char*)cpuInfo);
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
result.LogicalProcessorNumber = (ushort)sysInfo.dwNumberOfProcessors;
//#ifdef INTRA_XP_SUPPORT
result.CoreNumber = result.LogicalProcessorNumber;
/*#else
SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX logicalProcInfoEx[16];
DWORD bufferLength = 16*sizeof(logicalProcInfoEx);
GetLogicalProcessorInformationEx(RelationProcessorPackage, logicalProcInfoEx, &bufferLength);
result.CoreNumber = ushort(bufferLength/sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX));
#endif*/
HKEY hKey;
long lError = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &hKey);
if(lError==ERROR_SUCCESS)
{
DWORD dwMHz, size=sizeof(dwMHz);
lError = RegQueryValueExA(hKey, "~MHz", null, null, (LPBYTE)&dwMHz, &size);
if(lError==ERROR_SUCCESS) result.Frequency = dwMHz*1000000ull;
}
return result;
}
}
#else
#include <IO/File.h>
namespace Intra {
ProcessorInfo ProcessorInfo::Get()
{
ProcessorInfo result;
#if(INTRA_PLATFORM_OS==INTRA_PLATFORM_OS_Linux)
String allCpuInfo = IO::DiskFile::ReadAsString("/proc/cpuinfo");
result.BrandString = allCpuInfo().Find(StringView("\nmodel name"))
.Find(':').Drop(2).ReadUntil('\n');
result.CoreNumber = allCpuInfo().Find(StringView("\ncpu cores"))
.Find(':').Drop(2).ReadUntil('\n').ParseAdvance<ushort>();
result.LogicalProcessorNumber = ushort(allCpuInfo().Count(StringView("processor ")));
result.Frequency = ulong64(1000000*allCpuInfo().Find(StringView("\ncpu MHz"))
.Find(':').Drop(2).ReadUntil('\n').ParseAdvance<double>());
#endif
return result;
}
}
#endif
<|endoftext|> |
<commit_before>
/*
*
* Error Codes
* 1.x - Sql Errors
* 2.x - New MP
* 3.x - Open MP
*
*/
// 1. Need to check and see if an mp is already open, prior to creating a new one,
// so i can reload what was there and what view was there...
// 2. Need to replace openview with OpenWindow
#include "MainWindow.h"
MainWindow::MainWindow(void)
: BWindow(BRect(100,100,900,700),"MasterPiece",B_DOCUMENT_WINDOW, B_ASYNCHRONOUS_CONTROLS, B_CURRENT_WORKSPACE)
{
BRect r(Bounds());
/* begin comment out group when not testing layout code */
BGroupLayout* mainGroup = new BGroupLayout(B_VERTICAL);
mainGrid = new BGridLayout();
SetLayout(mainGroup);
/* end comment out group when not testing layout code */
//BView *mainView = new BView(Bounds(), "mainview", B_FOLLOW_ALL, B_WILL_DRAW);
//AddChild(mainView); // comment out when testing layout code
rgb_color myColor = {215, 215, 215, 255};
//mainView->SetViewColor(myColor);
//r.bottom = 20;
mpMenuBar = new MPMenuBar(r);
//mainView->AddChild(mpMenuBar); // uncomment when not using layout code
mainGroup->AddView(0, mpMenuBar); // comment out when not testing layout code
mainGroup->SetInsets(0, 0, 0, 0);
mainGrid->SetInsets(0, 0, 0, 0);
mainGroup->AddItem(mainGrid);
BRect sumRect(Bounds());
sumRect.top = 0;
sumView = new SummaryView(sumRect);
//mainView->AddChild(sumView); // uncomment when not using grid layout
//mainGrid->AddView(sumView, 0, 0);
sumView->SetViewColor(myColor);
//sumView->Hide();
thoughtView = new ThoughtView(sumRect);
//mainView->AddChild(thoughtView);
//mainGrid->AddView(thoughtView, 0, 0);
thoughtView->SetViewColor(myColor);
//thoughtView->Hide();
sqlErrMsg = 0;
app_info info;
be_app->GetAppInfo(&info);
BPath path(&info.ref);
path.GetParent(&path);
BString tmpPath = path.Path();
tmpPath += "/MasterPiece.db";
sqlValue = sqlite3_open_v2(tmpPath, &mpdb, SQLITE_OPEN_READWRITE, NULL); // open masterpiece.db
if(sqlite3_errcode(mpdb) == 14) // if error is SQLITE_CANTOPEN, then create db with structure.
{
sqlValue = sqlite3_open_v2(tmpPath, &mpdb, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL); // create masterpiece.db
if(sqlite3_errcode(mpdb) == 0) // sqlite_ok
{
tmpString = "create table mptable(mpid integer primary key autoincrement, mpname text);";
tmpString += " create table ideatable(ideaid integer primary key autoincrement, ideadata blob, ideatype integer, mpid integer, ordernumber integer);";
tmpString += " create table itypetable(itypeid integer primary key autoincrement, itypename text, itypedescription text);";
sqlValue = sqlite3_exec(mpdb, tmpString, NULL, NULL, &sqlErrMsg);
if(sqlValue == SQLITE_OK) // if sql was successful
{
// ladida...
}
else // sql not successful
{
errorAlert = new ErrorAlert("1.1 SQL Error: ", sqlErrMsg);
errorAlert->Launch();
}
}
else // some kind of failure...
{
errorAlert = new ErrorAlert("1.0 Sql Error: ", sqlite3_errmsg(mpdb));
errorAlert->Launch();
}
}
else if(sqlite3_errcode(mpdb) == 0) // SQLITE_OK, it exists
{
// ladida
}
else // if error is not ok or not existing, then display error in alert.
{
errorAlert = new ErrorAlert("1.2 Sql Error: ", sqlite3_errmsg(mpdb));
errorAlert->Launch();
this->mpMenuBar->fileMenu->SetEnabled(false);
}
}
void MainWindow::Draw(BRect rect)
{
//rgb_color backColor = {215, 215, 215, 255};
}
void MainWindow::MessageReceived(BMessage *msg)
{
BRect r(Bounds());
switch (msg->what)
{
case MENU_NEW_MSG:
// 1. need to center the modal window on the parent...
// 2. check to see if course is currently open
if(!this->sumView->IsHidden()) this->sumView->Hide();
xPos = (r.right - r.left) / 2;
yPos = (r.bottom - r.top) / 2;
newWin = new NewWindow(BMessage(UPDATE_NEW_MP), BMessenger(this), xPos, yPos);
newWin->Show();
break;
case UPDATE_NEW_MP:
if(msg->FindString("mptitle", &mptitle) == B_OK && msg->FindInt64("mpid", &mpid) == B_OK)
{
this->SetTitle(mptitle);
// 1. need to figure out how to open the summaryview using the mpid
tmpString = mptitle;
tmpString += " Summary";
this->sumView->sumViewTitleString->SetText(tmpString);
//if(this->sumView->IsHidden()) this->sumView->Show();
mainGrid->AddView(sumView, 0, 0);
this->mpMenuBar->contentMenu->SetEnabled(true);
this->mpMenuBar->layoutMenu->SetEnabled(true);
this->mpMenuBar->closeFileMenuItem->SetEnabled(true);
// 1. call the function to populate summaryview passing the (mpid)
}
break;
case MENU_OPN_MSG:
xPos = (r.right - r.left) / 2;
yPos = (r.bottom - r.top) / 2;
openWin = new OpenWindow(BMessage(UPDATE_OPEN_MP), BMessenger(this), xPos, yPos, "");
openWin->Show();
break;
case UPDATE_OPEN_MP:
if(msg->FindString("opentitle", &mptitle) == B_OK && msg->FindInt64("openid", &mpid) == B_OK)
{
this->SetTitle(mptitle);
tmpString = mptitle;
tmpString += " Summary";
this->sumView->sumViewTitleString->SetText(tmpString);
mainGrid->AddView(sumView, 0, 0);
//if(this->sumView->IsHidden()) this->sumView->Show();
this->mpMenuBar->contentMenu->SetEnabled(true);
this->mpMenuBar->layoutMenu->SetEnabled(true);
this->mpMenuBar->closeFileMenuItem->SetEnabled(true);
}
break;
case MENU_CLS_MSG:
// 1. close course - simply clear values and hide views.
//if(!this->sumView->IsHidden()) this->sumView->Hide();
mainGrid->RemoveView(sumView);
this->SetTitle("MasterPiece");
this->mpMenuBar->closeFileMenuItem->SetEnabled(false);
break;
case MENU_THT_MSG:
//if(!this->sumView->IsHidden()) this->sumView->Hide();
//if(this->thoughtView->IsHidden()) this->thoughtView->Show();
mainGrid->RemoveView(sumView);
mainGrid->AddView(thoughtView);
// do something here...
break;
case MNG_LAYOUT_MSG:
// do something here...
break;
default:
{
BWindow::MessageReceived(msg);
break;
}
}
}
void MainWindow::FrameResized(float width, float height)
{
}
bool
MainWindow::QuitRequested(void)
{
sqlite3_free(sqlErrMsg);
sqlite3_close(mpdb);
be_app->PostMessage(B_QUIT_REQUESTED);
return true;
}
void MainWindow::PopulateSummaryView(int mpID)
{
//tmpString = "select thoughtID, thoughtData from ttable wher
// place code here to populate summary view based on input id...
}
<commit_msg>trying to figure out the addview removeview and how to control when to add it and when not to add it<commit_after>
/*
*
* Error Codes
* 1.x - Sql Errors
* 2.x - New MP
* 3.x - Open MP
*
*/
// 1. Need to check and see if an mp is already open, prior to creating a new one,
// so i can reload what was there and what view was there...
// 2. Need to replace openview with OpenWindow
#include "MainWindow.h"
MainWindow::MainWindow(void)
: BWindow(BRect(100,100,900,700),"MasterPiece",B_DOCUMENT_WINDOW, B_ASYNCHRONOUS_CONTROLS, B_CURRENT_WORKSPACE)
{
BRect r(Bounds());
/* begin comment out group when not testing layout code */
BGroupLayout* mainGroup = new BGroupLayout(B_VERTICAL);
mainGrid = new BGridLayout();
SetLayout(mainGroup);
/* end comment out group when not testing layout code */
//BView *mainView = new BView(Bounds(), "mainview", B_FOLLOW_ALL, B_WILL_DRAW);
//AddChild(mainView); // comment out when testing layout code
rgb_color myColor = {215, 215, 215, 255};
//mainView->SetViewColor(myColor);
//r.bottom = 20;
mpMenuBar = new MPMenuBar(r);
//mainView->AddChild(mpMenuBar); // uncomment when not using layout code
mainGroup->AddView(0, mpMenuBar); // comment out when not testing layout code
mainGroup->SetInsets(0, 0, 0, 0);
mainGrid->SetInsets(0, 0, 0, 0);
mainGroup->AddItem(mainGrid);
BRect sumRect(Bounds());
sumRect.top = 0;
sumView = new SummaryView(sumRect);
//mainView->AddChild(sumView); // uncomment when not using grid layout
//mainGrid->AddView(sumView, 0, 0);
sumView->SetViewColor(myColor);
//sumView->Hide();
thoughtView = new ThoughtView(sumRect);
//mainView->AddChild(thoughtView);
//mainGrid->AddView(thoughtView, 0, 0);
thoughtView->SetViewColor(myColor);
//thoughtView->Hide();
sqlErrMsg = 0;
app_info info;
be_app->GetAppInfo(&info);
BPath path(&info.ref);
path.GetParent(&path);
BString tmpPath = path.Path();
tmpPath += "/MasterPiece.db";
sqlValue = sqlite3_open_v2(tmpPath, &mpdb, SQLITE_OPEN_READWRITE, NULL); // open masterpiece.db
if(sqlite3_errcode(mpdb) == 14) // if error is SQLITE_CANTOPEN, then create db with structure.
{
sqlValue = sqlite3_open_v2(tmpPath, &mpdb, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL); // create masterpiece.db
if(sqlite3_errcode(mpdb) == 0) // sqlite_ok
{
tmpString = "create table mptable(mpid integer primary key autoincrement, mpname text);";
tmpString += " create table ideatable(ideaid integer primary key autoincrement, ideadata blob, ideatype integer, mpid integer, ordernumber integer);";
tmpString += " create table itypetable(itypeid integer primary key autoincrement, itypename text, itypedescription text);";
sqlValue = sqlite3_exec(mpdb, tmpString, NULL, NULL, &sqlErrMsg);
if(sqlValue == SQLITE_OK) // if sql was successful
{
// ladida...
}
else // sql not successful
{
errorAlert = new ErrorAlert("1.1 SQL Error: ", sqlErrMsg);
errorAlert->Launch();
}
}
else // some kind of failure...
{
errorAlert = new ErrorAlert("1.0 Sql Error: ", sqlite3_errmsg(mpdb));
errorAlert->Launch();
}
}
else if(sqlite3_errcode(mpdb) == 0) // SQLITE_OK, it exists
{
// ladida
}
else // if error is not ok or not existing, then display error in alert.
{
errorAlert = new ErrorAlert("1.2 Sql Error: ", sqlite3_errmsg(mpdb));
errorAlert->Launch();
this->mpMenuBar->fileMenu->SetEnabled(false);
}
}
void MainWindow::Draw(BRect rect)
{
//rgb_color backColor = {215, 215, 215, 255};
}
void MainWindow::MessageReceived(BMessage *msg)
{
BRect r(Bounds());
switch (msg->what)
{
case MENU_NEW_MSG:
// 1. need to center the modal window on the parent...
// 2. check to see if course is currently open
if(!this->sumView->IsHidden()) this->sumView->Hide();
xPos = (r.right - r.left) / 2;
yPos = (r.bottom - r.top) / 2;
newWin = new NewWindow(BMessage(UPDATE_NEW_MP), BMessenger(this), xPos, yPos);
newWin->Show();
break;
case UPDATE_NEW_MP:
if(msg->FindString("mptitle", &mptitle) == B_OK && msg->FindInt64("mpid", &mpid) == B_OK)
{
this->SetTitle(mptitle);
// 1. need to figure out how to open the summaryview using the mpid
tmpString = mptitle;
tmpString += " Summary";
this->sumView->sumViewTitleString->SetText(tmpString);
//if(this->sumView->IsHidden()) this->sumView->Show();
mainGrid->AddView(sumView, 0, 0);
this->mpMenuBar->contentMenu->SetEnabled(true);
this->mpMenuBar->layoutMenu->SetEnabled(true);
this->mpMenuBar->closeFileMenuItem->SetEnabled(true);
// 1. call the function to populate summaryview passing the (mpid)
}
break;
case MENU_OPN_MSG:
xPos = (r.right - r.left) / 2;
yPos = (r.bottom - r.top) / 2;
openWin = new OpenWindow(BMessage(UPDATE_OPEN_MP), BMessenger(this), xPos, yPos, "");
openWin->Show();
break;
case UPDATE_OPEN_MP:
if(msg->FindString("opentitle", &mptitle) == B_OK && msg->FindInt64("openid", &mpid) == B_OK)
{
this->SetTitle(mptitle);
tmpString = mptitle;
tmpString += " Summary";
this->sumView->sumViewTitleString->SetText(tmpString);
mainGrid->AddView(sumView, 0, 0);
//if(this->sumView->IsHidden()) this->sumView->Show();
this->mpMenuBar->contentMenu->SetEnabled(true);
this->mpMenuBar->layoutMenu->SetEnabled(true);
this->mpMenuBar->closeFileMenuItem->SetEnabled(true);
}
break;
case MENU_CLS_MSG:
// 1. close course - simply clear values and hide views.
//if(!this->sumView->IsHidden()) this->sumView->Hide();
mainGrid->RemoveView(sumView);
this->SetTitle("MasterPiece");
this->mpMenuBar->closeFileMenuItem->SetEnabled(false);
break;
case MENU_THT_MSG:
//if(!this->sumView->IsHidden()) this->sumView->Hide();
//if(this->thoughtView->IsHidden()) this->thoughtView->Show();
if(!this->sumView->IsHidden()) mainGrid->RemoveView(sumView);
mainGrid->AddView(thoughtView);
// when in a view, might want to invalidate the menu option so it can't be redone and screwed up for now
// do something here...
break;
case MNG_LAYOUT_MSG:
// do something here...
break;
default:
{
BWindow::MessageReceived(msg);
break;
}
}
}
void MainWindow::FrameResized(float width, float height)
{
}
bool
MainWindow::QuitRequested(void)
{
sqlite3_free(sqlErrMsg);
sqlite3_close(mpdb);
be_app->PostMessage(B_QUIT_REQUESTED);
return true;
}
void MainWindow::PopulateSummaryView(int mpID)
{
//tmpString = "select thoughtID, thoughtData from ttable wher
// place code here to populate summary view based on input id...
}
<|endoftext|> |
<commit_before>/**
** \file scheduler/job.hh
** \brief Definition of scheduler::Job.
*/
#ifndef SCHEDULER_JOB_HH
# define SCHEDULER_JOB_HH
# include <iosfwd>
# include <list>
# include <vector>
# include <libport/symbol.hh>
# include <libport/utime.hh>
# include "object/symbols.hh"
# include "object/urbi-exception.hh"
# include "scheduler/coroutine.hh"
# include "scheduler/fwd.hh"
# include "scheduler/tag.hh"
namespace scheduler
{
enum job_state
{
to_start, ///< Job needs to be started
running, ///< Job is waiting for the CPU
sleeping, ///< Job is sleeping until a specified deadline
waiting, ///< Job is waiting for changes to happen
joining, ///< Job is waiting for another job to terminate
zombie ///< Job wants to be dead but isn't really yet
};
/// A Job represents a thread of control, implemented using coroutines.
/// The scheduler decides which job to launch and resumes its execution.
/// The lifetime of a job is the following
///
/// \li Job() : job creation
///
/// \li start_job() : add job to the scheduler; the scheduler
/// will call run(), and the job will
/// yield() itself into the scheduler run
/// queue
///
/// \li work() : this method, which must be overridden,
/// does the real work
///
/// Due to the way coroutines work, a job may not delete itself
/// as once the coroutine structure has been freed, it is illegal to
/// continue its execution, even only to switch to another coroutine.
/// And if a job switches back to the scheduler before terminating its
/// destructor, the coroutine structure will not be freed. Because of
/// that, it is necessary for a job to be deleted by another one or
/// by the scheduler.
///
/// An additional constraint comes from the fact that even when a job
/// has terminated its work, its structure may not always be deleted.
/// For example, other jobs may have kept a reference to this job and
/// expect to retrieve some information (such as a result) after the
/// job termination.
///
/// We have several ways of dealing with those constraints and not leaking
/// memory upon a job termination:
///
/// \li 1. Make sure the job spits out all the useful information concerning
/// its state by the way of inter-job communication before asking to
/// be deleted.
///
/// \li 2. Make sure the job is kept alive as long as there is at least one
/// reference onto it, and that it gets deleted from another
/// coroutine, or from the main one.
class Job: public libport::RefCounted
{
public:
/// Create a job from another one.
///
/// \param model The parent job. The scheduler and tags will be inherited
// from it.
///
/// \param name The name of the new job, or a name derived from \a model
/// if none is provided.
Job (const Job& model, const libport::Symbol& name = SYMBOL ());
/// Create a new job.
///
/// \param scheduler The scheduler to which this job will be attached.
///
/// \param name The name of the new job, or an automatically created
/// one if none is provided.
explicit Job (Scheduler& scheduler,
const libport::Symbol& name = SYMBOL ());
/// Job destructor.
///
/// The destructor is in charge of unscheduling the job in the
/// scheduler.
virtual ~Job ();
/// Get this job scheduler.
///
/// \return A reference on the job scheduler.
Scheduler& scheduler_get () const;
/// Get the underlying coroutine corresponding to this job.
///
/// \return The coroutine structure.
Coro* coro_get () const;
/// Has this job terminated?
///
/// \return True if this job is in the \c zombie state.
bool terminated () const;
/// Start job by adding it to the scheduler.
void start_job ();
/// Run the job. This function is called from the scheduler.
void run ();
/// Terminate the job. The job will execute its cleanup method
/// and inform the scheduler that it is ready to be destroyed.
void terminate_now ();
/// Register this Job on its Scheduler so that it is rescheduled
/// during the next cycle. This should be called from the
/// currently scheduled job only but must be kept visible to be
/// callable from the primitives.
/// \sa yield_until(), yield_until_terminated(),
/// yield_until_things_changed()
void yield ();
/// As yield(), but ask not to be woken up before the deadline.
/// \sa yield(), yield_until_terminated(), yield_until_things_changed()
void yield_until (libport::utime_t deadline);
/// Wait for another job to terminate before resuming execution of
/// the current one. If the other job has already terminated, the
/// caller will continue its execution.
///
/// \param other The job to wait for.
///
/// \sa yield(), yield_until(), yield_until_things_changed()
void yield_until_terminated (Job& other);
/// Wait for any other task to be scheduled.
/// \sa yield(), yield_until_terminated(), yield_until()
void yield_until_things_changed ();
/// Mark the current job as side-effect free.
///
/// \param s True if the job is now side-effect free.
///
/// Indicate whether the current state of a job may influence other
/// parts of the system. This is used by the scheduler to choose
/// whether other jobs need scheduling or not. The default value
/// for \c side_effect_free is false.
void side_effect_free_set (bool s);
/// Is the current job side-effect free?
///
/// \return True if the job is currently side-effect free.
bool side_effect_free_get () const;
/// Raise an exception next time this job will be resumed.
///
/// \param e The exception to throw when the job will be scheduled
/// again.
void async_throw (const kernel::exception& e);
/// Maybe raise a deferred exception. Must be called from the scheduler
/// while resuming the job execution. For example, BlockedException
/// may be raised from here if the job has been blocked by a tag.
void check_for_pending_exception ();
/// Establish a permanent bi-directional link between two jobs.
///
/// \param other The job to link to.
void link (rJob other);
/// Get the job name
///
/// \return The job name as set from the constructor.
const libport::Symbol& name_get () const;
/// Throw an exception if the stack space for this job is near
/// exhaustion.
void check_stack_space () const;
/// Is the job frozen?
///
/// \return This depends from the job tags state.
virtual bool frozen () const;
/// Is the job blocked?
///
/// \return This depends from the job tags state.
virtual bool blocked () const;
/// Push a tag onto the current job tag stack.
///
/// \param rTag The tag to push.
void push_tag (rTag);
/// Pop the latest pushed tag from the job tag stack.
void pop_tag ();
/// Copy the tags from another job.
///
/// \param other The other job to copy tags from.
void copy_tags (const Job& other);
/// Get the current tags.
///
/// \return The tags attached to the current job.
tags_type tags_get () const;
/// Set the current tags.
///
/// \param tags Set the tags attached to the current job.
void tags_set (tags_type tags);
/// Get the current job state.
///
/// \return The current job state.
job_state state_get () const;
/// Set the current job state
///
/// \param state The new job state.
void state_set (job_state state);
/// Get this job deadline if it is sleeping.
///
/// \return The date on which this job needs to be awoken.
///
/// This function must not be called unless the job is in the
/// \c sleeping state.
libport::utime_t deadline_get () const;
/// Check if the job can be interrupted.
///
/// \return True if the job cannot be interrupted right now because
/// it is executing an atomic operation.
bool non_interruptible_get () const;
/// Indicate if the job can be interrupted or not
///
/// \param ni True if the job must not be interrupted until further
/// notice.
void non_interruptible_set (bool ni);
/// Remember the time we have been frozen since if not remembered
/// yet.
///
/// \param current_time The current time.
void notice_frozen (libport::utime_t current_time);
/// Note that we are not frozen anymore.
///
/// \param current_time The current time.
void notice_not_frozen (libport::utime_t current_time);
/// Return the origin since we have been frozen.
///
/// \return 0 if we have not been frozen, the date since we have
/// been frozen otherwise.
libport::utime_t frozen_since_get () const;
/// Return the current time shift.
///
/// \return The value to subtract from the system time to get the
/// unfrozen time of this runner.
libport::utime_t time_shift_get () const;
/// Set the current time shift.
///
/// \param ts The new time shift. This should probably only be used
/// at runner creation time.
void time_shift_set (libport::utime_t ts);
protected:
/// Must be implemented to do something useful. If an exception is
/// raised, it will be lost, but before that, it will be propagated
// into linked jobs.
virtual void work () = 0;
private:
/// Current job state, to be manipulated only from the job and the
/// scheduler.
job_state state_;
/// Current job deadline. The deadline is only meaningful when the
/// job state is \c sleeping.
libport::utime_t deadline_;
/// The last time we have been frozen (in system time), or 0 if we
/// are not currently frozen.
libport::utime_t frozen_since_;
/// The value we have to deduce from system time because we have
/// been frozen.
libport::utime_t time_shift_;
/// Ensure proper cleanup;
void terminate_cleanup ();
/// Scheduler in charge of this job. Do not delete.
Scheduler* scheduler_;
/// This job name.
libport::Symbol name_;
/// Other jobs to wake up when we terminate.
std::vector<rJob> to_wake_up_;
/// Coro structure corresponding to this job.
Coro* coro_;
/// Tags this job depends on.
scheduler::tags_type tags_;
/// List of jobs having a link to this one. If the current job
/// terminates with an exception, any linked job will throw the
/// exception as well when they resume. This must be a list, as
/// we may remove elements while we are iterating over it.
std::list<rJob> links_;
/// Is the current job non-interruptible? If yes, yielding will
/// do nothing and blocking operations may raise an exception.
bool non_interruptible_;
/// Is the current job side-effect free?
bool side_effect_free_;
/// The next exception to be propagated if any.
kernel::exception_ptr pending_exception_;
/// The exception being propagated if any.
kernel::exception_ptr current_exception_;
};
std::ostream& operator<< (std::ostream&, const Job&);
/// This exception will be raised to tell the job that it is currently
/// blocked and must try to unwind tags from its tag stack until it
/// is either dead or not blocked anymore.
struct BlockedException : public SchedulerException
{
COMPLETE_EXCEPTION (BlockedException);
};
// State names to string, for debugging purpose.
const char* state_name (job_state);
} // namespace scheduler
# include "scheduler/job.hxx"
#endif // !SCHEDULER_JOB_HH
<commit_msg>Better tags handling in at job handler.<commit_after>/**
** \file scheduler/job.hh
** \brief Definition of scheduler::Job.
*/
#ifndef SCHEDULER_JOB_HH
# define SCHEDULER_JOB_HH
# include <iosfwd>
# include <list>
# include <vector>
# include <libport/symbol.hh>
# include <libport/utime.hh>
# include "object/symbols.hh"
# include "object/urbi-exception.hh"
# include "scheduler/coroutine.hh"
# include "scheduler/fwd.hh"
# include "scheduler/tag.hh"
namespace scheduler
{
enum job_state
{
to_start, ///< Job needs to be started
running, ///< Job is waiting for the CPU
sleeping, ///< Job is sleeping until a specified deadline
waiting, ///< Job is waiting for changes to happen
joining, ///< Job is waiting for another job to terminate
zombie ///< Job wants to be dead but isn't really yet
};
/// A Job represents a thread of control, implemented using coroutines.
/// The scheduler decides which job to launch and resumes its execution.
/// The lifetime of a job is the following
///
/// \li Job() : job creation
///
/// \li start_job() : add job to the scheduler; the scheduler
/// will call run(), and the job will
/// yield() itself into the scheduler run
/// queue
///
/// \li work() : this method, which must be overridden,
/// does the real work
///
/// Due to the way coroutines work, a job may not delete itself
/// as once the coroutine structure has been freed, it is illegal to
/// continue its execution, even only to switch to another coroutine.
/// And if a job switches back to the scheduler before terminating its
/// destructor, the coroutine structure will not be freed. Because of
/// that, it is necessary for a job to be deleted by another one or
/// by the scheduler.
///
/// An additional constraint comes from the fact that even when a job
/// has terminated its work, its structure may not always be deleted.
/// For example, other jobs may have kept a reference to this job and
/// expect to retrieve some information (such as a result) after the
/// job termination.
///
/// We have several ways of dealing with those constraints and not leaking
/// memory upon a job termination:
///
/// \li 1. Make sure the job spits out all the useful information concerning
/// its state by the way of inter-job communication before asking to
/// be deleted.
///
/// \li 2. Make sure the job is kept alive as long as there is at least one
/// reference onto it, and that it gets deleted from another
/// coroutine, or from the main one.
class Job: public libport::RefCounted
{
public:
/// Create a job from another one.
///
/// \param model The parent job. The scheduler and tags will be inherited
// from it.
///
/// \param name The name of the new job, or a name derived from \a model
/// if none is provided.
Job (const Job& model, const libport::Symbol& name = SYMBOL ());
/// Create a new job.
///
/// \param scheduler The scheduler to which this job will be attached.
///
/// \param name The name of the new job, or an automatically created
/// one if none is provided.
explicit Job (Scheduler& scheduler,
const libport::Symbol& name = SYMBOL ());
/// Job destructor.
///
/// The destructor is in charge of unscheduling the job in the
/// scheduler.
virtual ~Job ();
/// Get this job scheduler.
///
/// \return A reference on the job scheduler.
Scheduler& scheduler_get () const;
/// Get the underlying coroutine corresponding to this job.
///
/// \return The coroutine structure.
Coro* coro_get () const;
/// Has this job terminated?
///
/// \return True if this job is in the \c zombie state.
bool terminated () const;
/// Start job by adding it to the scheduler.
void start_job ();
/// Run the job. This function is called from the scheduler.
void run ();
/// Terminate the job. The job will execute its cleanup method
/// and inform the scheduler that it is ready to be destroyed.
void terminate_now ();
/// Register this Job on its Scheduler so that it is rescheduled
/// during the next cycle. This should be called from the
/// currently scheduled job only but must be kept visible to be
/// callable from the primitives.
/// \sa yield_until(), yield_until_terminated(),
/// yield_until_things_changed()
void yield ();
/// As yield(), but ask not to be woken up before the deadline.
/// \sa yield(), yield_until_terminated(), yield_until_things_changed()
void yield_until (libport::utime_t deadline);
/// Wait for another job to terminate before resuming execution of
/// the current one. If the other job has already terminated, the
/// caller will continue its execution.
///
/// \param other The job to wait for.
///
/// \sa yield(), yield_until(), yield_until_things_changed()
void yield_until_terminated (Job& other);
/// Wait for any other task to be scheduled.
/// \sa yield(), yield_until_terminated(), yield_until()
void yield_until_things_changed ();
/// Mark the current job as side-effect free.
///
/// \param s True if the job is now side-effect free.
///
/// Indicate whether the current state of a job may influence other
/// parts of the system. This is used by the scheduler to choose
/// whether other jobs need scheduling or not. The default value
/// for \c side_effect_free is false.
void side_effect_free_set (bool s);
/// Is the current job side-effect free?
///
/// \return True if the job is currently side-effect free.
bool side_effect_free_get () const;
/// Raise an exception next time this job will be resumed.
///
/// \param e The exception to throw when the job will be scheduled
/// again.
void async_throw (const kernel::exception& e);
/// Maybe raise a deferred exception. Must be called from the scheduler
/// while resuming the job execution. For example, BlockedException
/// may be raised from here if the job has been blocked by a tag.
void check_for_pending_exception ();
/// Establish a permanent bi-directional link between two jobs.
///
/// \param other The job to link to.
void link (rJob other);
/// Get the job name
///
/// \return The job name as set from the constructor.
const libport::Symbol& name_get () const;
/// Throw an exception if the stack space for this job is near
/// exhaustion.
void check_stack_space () const;
/// Is the job frozen?
///
/// \return This depends from the job tags state.
virtual bool frozen () const;
/// Is the job blocked?
///
/// \return This depends from the job tags state.
virtual bool blocked () const;
/// Push a tag onto the current job tag stack.
///
/// \param rTag The tag to push.
void push_tag (rTag);
/// Pop the latest pushed tag from the job tag stack.
void pop_tag ();
/// Copy the tags from another job.
///
/// \param other The other job to copy tags from.
void copy_tags (const Job& other);
/// Get the current tags.
///
/// \return The tags attached to the current job.
tags_type tags_get () const;
/// Set the current tags.
///
/// \param tags Set the tags attached to the current job.
void tags_set (tags_type tags);
/// Get the current job state.
///
/// \return The current job state.
job_state state_get () const;
/// Set the current job state
///
/// \param state The new job state.
void state_set (job_state state);
/// Get this job deadline if it is sleeping.
///
/// \return The date on which this job needs to be awoken.
///
/// This function must not be called unless the job is in the
/// \c sleeping state.
libport::utime_t deadline_get () const;
/// Check if the job can be interrupted.
///
/// \return True if the job cannot be interrupted right now because
/// it is executing an atomic operation.
bool non_interruptible_get () const;
/// Indicate if the job can be interrupted or not
///
/// \param ni True if the job must not be interrupted until further
/// notice.
void non_interruptible_set (bool ni);
/// Remember the time we have been frozen since if not remembered
/// yet.
///
/// \param current_time The current time.
void notice_frozen (libport::utime_t current_time);
/// Note that we are not frozen anymore.
///
/// \param current_time The current time.
void notice_not_frozen (libport::utime_t current_time);
/// Return the origin since we have been frozen.
///
/// \return 0 if we have not been frozen, the date since we have
/// been frozen otherwise.
libport::utime_t frozen_since_get () const;
/// Return the current time shift.
///
/// \return The value to subtract from the system time to get the
/// unfrozen time of this runner.
libport::utime_t time_shift_get () const;
/// Set the current time shift.
///
/// \param ts The new time shift. This should probably only be used
/// at runner creation time.
void time_shift_set (libport::utime_t ts);
protected:
/// Must be implemented to do something useful. If an exception is
/// raised, it will be lost, but before that, it will be propagated
// into linked jobs.
virtual void work () = 0;
private:
/// Current job state, to be manipulated only from the job and the
/// scheduler.
job_state state_;
/// Current job deadline. The deadline is only meaningful when the
/// job state is \c sleeping.
libport::utime_t deadline_;
/// The last time we have been frozen (in system time), or 0 if we
/// are not currently frozen.
libport::utime_t frozen_since_;
/// The value we have to deduce from system time because we have
/// been frozen.
libport::utime_t time_shift_;
/// Ensure proper cleanup;
void terminate_cleanup ();
/// Scheduler in charge of this job. Do not delete.
Scheduler* scheduler_;
/// This job name.
libport::Symbol name_;
/// Other jobs to wake up when we terminate.
std::vector<rJob> to_wake_up_;
/// Coro structure corresponding to this job.
Coro* coro_;
protected:
/// Tags this job depends on.
scheduler::tags_type tags_;
private:
/// List of jobs having a link to this one. If the current job
/// terminates with an exception, any linked job will throw the
/// exception as well when they resume. This must be a list, as
/// we may remove elements while we are iterating over it.
std::list<rJob> links_;
/// Is the current job non-interruptible? If yes, yielding will
/// do nothing and blocking operations may raise an exception.
bool non_interruptible_;
/// Is the current job side-effect free?
bool side_effect_free_;
/// The next exception to be propagated if any.
kernel::exception_ptr pending_exception_;
/// The exception being propagated if any.
kernel::exception_ptr current_exception_;
};
std::ostream& operator<< (std::ostream&, const Job&);
/// This exception will be raised to tell the job that it is currently
/// blocked and must try to unwind tags from its tag stack until it
/// is either dead or not blocked anymore.
struct BlockedException : public SchedulerException
{
COMPLETE_EXCEPTION (BlockedException);
};
// State names to string, for debugging purpose.
const char* state_name (job_state);
} // namespace scheduler
# include "scheduler/job.hxx"
#endif // !SCHEDULER_JOB_HH
<|endoftext|> |
<commit_before>/******************************************************************************
Copyright (c) 2012, Benno Grolik <[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 Benno Grolik nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#include "MainWindow.h"
#include <QtGui>
#include <iostream>
#include "SlackPKG.h"
static const std::string sVersion= SWUN_VERSION ;
MainWindow::MainWindow()
{
m_packBE=new SlackPKG();
m_state=PackageBackend::ePBS_Unknown;
m_checkCLAction = new QAction(tr("&Check ChangeLog"), this);
m_checkSAction = new QAction(tr("CheckUpdate&State"), this);
m_updateAction = new QAction(tr("&Update System"), this);
m_restoreAction = new QAction(tr("&Restore"), this);
m_quitAction = new QAction(tr("&Quit"), this);
connect( m_restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));
connect( m_quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect( m_checkCLAction, SIGNAL(triggered()), this, SLOT(checkChangelog()));
connect( m_checkSAction, SIGNAL(triggered()), this, SLOT(checkState()));
connect( m_updateAction, SIGNAL(triggered()), this, SLOT(doUpdate()));
createTrayIcon();
connect(m_trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
m_timer = new QTimer(this);
m_timer->start(5000);
connect( m_timer, SIGNAL(timeout()), this, SLOT(checkChangelog()));
m_trayIcon->show();
setWindowTitle(tr("Swun"));
resize(400, 400);
}
MainWindow::~MainWindow()
{
delete m_packBE;
}
void
MainWindow::closeEvent(QCloseEvent *event)
{
if(m_trayIcon->isVisible())
{
hide();
event->ignore();
}
}
void
MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
const std::string& output=m_packBE->getOutput();
switch(reason)
{
case QSystemTrayIcon::Trigger:
m_trayIcon->showMessage("Swun",output.c_str(),
QSystemTrayIcon::Information,1000);
break;
case QSystemTrayIcon::DoubleClick:
m_trayIcon->showMessage("Swun",sVersion.c_str(),
QSystemTrayIcon::Information,1000);
break;
case QSystemTrayIcon::MiddleClick:
m_trayIcon->showMessage("Swun","sVersion.c_str()",
QSystemTrayIcon::Information,1000);
break;
default:
break;
}
}
void
MainWindow::checkChangelog()
{
static bool firstCall=true;
if(firstCall)
{
m_timer->start(3600000);
firstCall=false;
}
std::cout << "check changelog" << std::endl;
bool outdated=m_packBE->check();
std::string output=m_packBE->getOutput();
if(outdated)
{
m_trayIcon->showMessage("Swun",output.c_str());
m_state=PackageBackend::ePBS_ChangelogOutdated;
}
else
{
if(m_state==PackageBackend::ePBS_Unknown)
{
m_trayIcon->showMessage("Swun",output.c_str());
m_state=PackageBackend::ePBS_UpToDate;
}
}
updateIcon();
}
void
MainWindow::checkState()
{
std::cout << "check update State" << std::endl;
m_state=m_packBE->checkState();
std::string output=m_packBE->getOutput();
m_trayIcon->showMessage("Swun",output.c_str());
updateIcon();
}
void
MainWindow::doUpdate()
{
std::cout << "do an update" << std::endl;
m_packBE->doUpdate();
m_state=PackageBackend::ePBS_Unknown;
checkState();
}
void
MainWindow::createTrayIcon()
{
m_trayIconMenu = new QMenu(this);
m_trayIconMenu->addAction(m_checkCLAction);
m_trayIconMenu->addAction(m_checkSAction);
m_trayIconMenu->addAction(m_updateAction);
//m_trayIconMenu->addAction(m_restoreAction);
m_trayIconMenu->addAction(m_quitAction);
m_trayIcon = new QSystemTrayIcon(this);
m_trayIcon->setContextMenu(m_trayIconMenu);
updateIcon();
}
void
MainWindow::updateIcon()
{
switch(m_state)
{
case PackageBackend::ePBS_UpToDate:
m_trayIcon->setIcon(QIcon(":/images/uptodate.png"));
break;
case PackageBackend::ePBS_ChangelogOutdated:
m_trayIcon->setIcon(QIcon(":/images/newupdates.png"));
break;
case PackageBackend::ePBS_PackagesInstallable:
m_trayIcon->setIcon(QIcon(":/images/packages.png"));
break;
default:
m_trayIcon->setIcon(QIcon(":/images/unknown.png"));
break;
}
}
<commit_msg>fixed wrong quotes<commit_after>/******************************************************************************
Copyright (c) 2012, Benno Grolik <[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 Benno Grolik nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#include "MainWindow.h"
#include <QtGui>
#include <iostream>
#include "SlackPKG.h"
static const std::string sVersion= SWUN_VERSION ;
MainWindow::MainWindow()
{
m_packBE=new SlackPKG();
m_state=PackageBackend::ePBS_Unknown;
m_checkCLAction = new QAction(tr("&Check ChangeLog"), this);
m_checkSAction = new QAction(tr("CheckUpdate&State"), this);
m_updateAction = new QAction(tr("&Update System"), this);
m_restoreAction = new QAction(tr("&Restore"), this);
m_quitAction = new QAction(tr("&Quit"), this);
connect( m_restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));
connect( m_quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect( m_checkCLAction, SIGNAL(triggered()), this, SLOT(checkChangelog()));
connect( m_checkSAction, SIGNAL(triggered()), this, SLOT(checkState()));
connect( m_updateAction, SIGNAL(triggered()), this, SLOT(doUpdate()));
createTrayIcon();
connect(m_trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
m_timer = new QTimer(this);
m_timer->start(5000);
connect( m_timer, SIGNAL(timeout()), this, SLOT(checkChangelog()));
m_trayIcon->show();
setWindowTitle(tr("Swun"));
resize(400, 400);
}
MainWindow::~MainWindow()
{
delete m_packBE;
}
void
MainWindow::closeEvent(QCloseEvent *event)
{
if(m_trayIcon->isVisible())
{
hide();
event->ignore();
}
}
void
MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
const std::string& output=m_packBE->getOutput();
switch(reason)
{
case QSystemTrayIcon::Trigger:
m_trayIcon->showMessage("Swun",output.c_str(),
QSystemTrayIcon::Information,1000);
break;
case QSystemTrayIcon::DoubleClick:
m_trayIcon->showMessage("Swun",sVersion.c_str(),
QSystemTrayIcon::Information,1000);
break;
case QSystemTrayIcon::MiddleClick:
m_trayIcon->showMessage("Swun",sVersion.c_str(),
QSystemTrayIcon::Information,1000);
break;
default:
break;
}
}
void
MainWindow::checkChangelog()
{
static bool firstCall=true;
if(firstCall)
{
m_timer->start(3600000);
firstCall=false;
}
std::cout << "check changelog" << std::endl;
bool outdated=m_packBE->check();
std::string output=m_packBE->getOutput();
if(outdated)
{
m_trayIcon->showMessage("Swun",output.c_str());
m_state=PackageBackend::ePBS_ChangelogOutdated;
}
else
{
if(m_state==PackageBackend::ePBS_Unknown)
{
m_trayIcon->showMessage("Swun",output.c_str());
m_state=PackageBackend::ePBS_UpToDate;
}
}
updateIcon();
}
void
MainWindow::checkState()
{
std::cout << "check update State" << std::endl;
m_state=m_packBE->checkState();
std::string output=m_packBE->getOutput();
m_trayIcon->showMessage("Swun",output.c_str());
updateIcon();
}
void
MainWindow::doUpdate()
{
std::cout << "do an update" << std::endl;
m_packBE->doUpdate();
m_state=PackageBackend::ePBS_Unknown;
checkState();
}
void
MainWindow::createTrayIcon()
{
m_trayIconMenu = new QMenu(this);
m_trayIconMenu->addAction(m_checkCLAction);
m_trayIconMenu->addAction(m_checkSAction);
m_trayIconMenu->addAction(m_updateAction);
//m_trayIconMenu->addAction(m_restoreAction);
m_trayIconMenu->addAction(m_quitAction);
m_trayIcon = new QSystemTrayIcon(this);
m_trayIcon->setContextMenu(m_trayIconMenu);
updateIcon();
}
void
MainWindow::updateIcon()
{
switch(m_state)
{
case PackageBackend::ePBS_UpToDate:
m_trayIcon->setIcon(QIcon(":/images/uptodate.png"));
break;
case PackageBackend::ePBS_ChangelogOutdated:
m_trayIcon->setIcon(QIcon(":/images/newupdates.png"));
break;
case PackageBackend::ePBS_PackagesInstallable:
m_trayIcon->setIcon(QIcon(":/images/packages.png"));
break;
default:
m_trayIcon->setIcon(QIcon(":/images/unknown.png"));
break;
}
}
<|endoftext|> |
<commit_before>#include "MappedRead.h"
#include "Log.h"
//#include "Config.h"
#undef module_name
#define module_name "READ"
#ifdef INSTANCE_COUNTING
volatile int MappedRead::sInstanceCount = 0;
volatile int LocationScore::sInstanceCount = 0;
#endif
volatile int MappedRead::maxSeqCount = 0;
MappedRead::MappedRead(int const readid, int const qrymaxlen) :
ReadId(readid), Calculated(-1), qryMaxLen(qrymaxlen), TopScore(-1), Lock(0), EqualScoringID(0), EqualScoringCount(1), Scores(), nScores(0), iScores(0), Paired(
0), Status(0), Identity(0), NM(-1), Strand('?'), QStart(0), QEnd(0), mappingQlty(255), RevSeq(0), Seq(0), qlty(0), name(0), Buffer1(
0), Buffer2(0) {
#ifdef INSTANCE_COUNTING
AtomicInc(&sInstanceCount);
maxSeqCount = std::max(sInstanceCount, maxSeqCount);
#endif
}
void MappedRead::AllocBuffers() {
//static int const qryMaxLen = Config.GetInt("qry_max_len");
Buffer1 = new char[std::max(1, qryMaxLen) * 4];
Buffer2 = new char[std::max(1, qryMaxLen) * 4];
*(int*) Buffer1 = 0x212121;
*(int*) Buffer2 = 0x212121;
}
static inline char cpl(char c) {
if (c == 'A')
return 'T';
else if (c == 'T')
return 'A';
else if (c == 'C')
return 'G';
else if (c == 'G')
return 'C';
else
return c;
}
//// swaps two bases and complements them
//static inline void rc(char & c1, char & c2)
//{
// char x = c1;
// c1 = cpl(c2);
// c2 = cpl(x);
//}
char const * MappedRead::computeReverseSeq() {
if (RevSeq == 0) {
//static int const qryMaxLen = Config.GetInt("qry_max_len");
RevSeq = new char[qryMaxLen];
memset(RevSeq, 0, qryMaxLen);
char * fwd = Seq;
char * rev = RevSeq + length - 1;
for (int i = 0; i < length; ++i) {
*rev-- = cpl(*fwd++);
//Seq[i] = cpl(RevSeq[length - i - 1]);
}
}
return RevSeq;
}
void MappedRead::DeleteReadSeq() {
if (Seq != 0)
delete[] Seq;
Seq = 0;
if (RevSeq != 0)
delete[] RevSeq;
RevSeq = 0;
}
MappedRead::~MappedRead() {
//for (size_t i = 0; i < Scores.size(); ++i)
// delete Scores[i];
if (Scores != 0) {
delete[] Scores;
Scores = 0;
iScores = 0;
nScores = 0;
}
if (Buffer1 != 0)
delete[] Buffer1;
if (Buffer2 != 0)
delete[] Buffer2;
DeleteReadSeq();
if (qlty != 0) {
delete[] qlty;
qlty = 0;
}
if (name != 0)
delete[] name;
name = 0;
#ifdef INSTANCE_COUNTING
AtomicDec(&sInstanceCount);
#endif
}
void MappedRead::AllocScores(LocationScore * tmp, int const n) {
nScores = n;
iScores = n;
// Log.Message("Allocating %d scores.", nScores);
if (nScores > 0) {
Scores = new LocationScore[nScores];
memcpy(Scores, tmp, n * sizeof(LocationScore));
}
}
//LocationScore * MappedRead::AddScore(LocationScore const & score) {
// LocationScore * toInsert = new LocationScore(score);
// toInsert->Read = this;
// Scores.push_back(toInsert);
// return toInsert;
//}
LocationScore * MappedRead::AddScore(float const score, uint const loc, bool const reverse) {
Log.Error("AddScore");
throw "";
iScores += 1;
LocationScore * toInsert = &Scores[iScores - 1];
toInsert->Score.f = score;
toInsert->Location.m_Location = loc;
toInsert->Location.m_RefId = reverse;
toInsert->Read = this;
return toInsert;
//LocationScore * toInsert = new LocationScore(loc, reverse, score, this);
//toInsert->Read = this;
//Scores.push_back(toInsert);
//return toInsert;
}
void MappedRead::clearScores(bool const keepTop) {
if (TopScore != -1 && Scores != 0) {
LocationScore tmp = *TLS();
if (keepTop) {
//Scores = new LocationScore[1];
//Scores = (LocationScore *)realloc(Scores, 1 * sizeof(LocationScore));
Scores[0] = tmp;
TopScore = 0;
iScores = 1;
nScores = 1;
} else {
delete[] Scores;
TopScore = -1;
iScores = 0;
nScores = 0;
Scores = 0;
}
}
}
LocationScore * MappedRead::TLS() const {
if (TopScore == -1) {
Log.Error("Top score accessed without calculation (Read %i, ESID %i, ESC %i)", ReadId, EqualScoringID, EqualScoringCount);
throw "";
return 0;
}
return &Scores[TopScore];
}
int MappedRead::numScores() const {
return iScores;
}
bool MappedRead::hasCandidates() const {
return iScores > 0;
}
void PrintScores(MappedRead const * read) {
// Log.Green("Scores for read %i", read->ReadId);
// for (size_t i = 0; i < read->Scores.size(); ++i) {
// if (read->Scores[i] == 0)
// Log.Message("<0>");
// else
// Log.Message("Score %.2f for <%i, %i>", read->Scores[i]->Score.f, read->Scores[i]->Location.m_Location, read->Scores[i]->Location.m_RefId);
// }
}
//void MappedRead::TopN(uint n) {
// if (Scores.size() == 0)
// return;
//
// if (Calculated > 0 && Calculated != (int) Scores.size())
// Log.Error("TopN called for inconsistent scores may lead to unexpected results.");
//
// std::sort(Scores.begin(), Scores.end(), SortPred); // Sort scores from best to worst
// Unique(); // Remove double scores
// Scores.erase(std::remove_if(Scores.begin(), Scores.end(), IsZero), Scores.end()); // remove 0-pointer from last step
//
// // remove from back all but top n
// while (Scores.size() > n) {
// delete Scores[Scores.size() - 1];
// Scores.pop_back();
// }
//
// // realloc vector
// std::vector<LocationScore*>(Scores).swap(Scores);
//
// TopScore = 0;
// Calculated = n;
//}
//void MappedRead::Unique() {
// uint ci = 0;
// for (uint i = 1; i < Scores.size(); ++i) {
// if (UniquePred(Scores[ci], Scores[i])) {
// delete Scores[i];
// Scores[i] = 0;
// } else
// ci = i;
// }
//}
<commit_msg>Only keep best scoring CMR after score computation.<commit_after>#include "MappedRead.h"
#include "Log.h"
//#include "Config.h"
#undef module_name
#define module_name "READ"
#ifdef INSTANCE_COUNTING
volatile int MappedRead::sInstanceCount = 0;
volatile int LocationScore::sInstanceCount = 0;
#endif
volatile int MappedRead::maxSeqCount = 0;
MappedRead::MappedRead(int const readid, int const qrymaxlen) :
ReadId(readid), Calculated(-1), qryMaxLen(qrymaxlen), TopScore(-1), Lock(0), EqualScoringID(0), EqualScoringCount(1), Scores(), nScores(0), iScores(0), Paired(
0), Status(0), Identity(0), NM(-1), Strand('?'), QStart(0), QEnd(0), mappingQlty(255), RevSeq(0), Seq(0), qlty(0), name(0), Buffer1(
0), Buffer2(0) {
#ifdef INSTANCE_COUNTING
AtomicInc(&sInstanceCount);
maxSeqCount = std::max(sInstanceCount, maxSeqCount);
#endif
}
void MappedRead::AllocBuffers() {
//static int const qryMaxLen = Config.GetInt("qry_max_len");
Buffer1 = new char[std::max(1, qryMaxLen) * 4];
Buffer2 = new char[std::max(1, qryMaxLen) * 4];
*(int*) Buffer1 = 0x212121;
*(int*) Buffer2 = 0x212121;
}
static inline char cpl(char c) {
if (c == 'A')
return 'T';
else if (c == 'T')
return 'A';
else if (c == 'C')
return 'G';
else if (c == 'G')
return 'C';
else
return c;
}
//// swaps two bases and complements them
//static inline void rc(char & c1, char & c2)
//{
// char x = c1;
// c1 = cpl(c2);
// c2 = cpl(x);
//}
char const * MappedRead::computeReverseSeq() {
if (RevSeq == 0) {
//static int const qryMaxLen = Config.GetInt("qry_max_len");
RevSeq = new char[qryMaxLen];
memset(RevSeq, 0, qryMaxLen);
char * fwd = Seq;
char * rev = RevSeq + length - 1;
for (int i = 0; i < length; ++i) {
*rev-- = cpl(*fwd++);
//Seq[i] = cpl(RevSeq[length - i - 1]);
}
}
return RevSeq;
}
void MappedRead::DeleteReadSeq() {
if (Seq != 0)
delete[] Seq;
Seq = 0;
if (RevSeq != 0)
delete[] RevSeq;
RevSeq = 0;
}
MappedRead::~MappedRead() {
//for (size_t i = 0; i < Scores.size(); ++i)
// delete Scores[i];
if (Scores != 0) {
delete[] Scores;
Scores = 0;
iScores = 0;
nScores = 0;
}
if (Buffer1 != 0)
delete[] Buffer1;
if (Buffer2 != 0)
delete[] Buffer2;
DeleteReadSeq();
if (qlty != 0) {
delete[] qlty;
qlty = 0;
}
if (name != 0)
delete[] name;
name = 0;
#ifdef INSTANCE_COUNTING
AtomicDec(&sInstanceCount);
#endif
}
void MappedRead::AllocScores(LocationScore * tmp, int const n) {
nScores = n;
iScores = n;
// Log.Message("Allocating %d scores.", nScores);
if (nScores > 0) {
Scores = new LocationScore[nScores];
memcpy(Scores, tmp, n * sizeof(LocationScore));
}
}
//LocationScore * MappedRead::AddScore(LocationScore const & score) {
// LocationScore * toInsert = new LocationScore(score);
// toInsert->Read = this;
// Scores.push_back(toInsert);
// return toInsert;
//}
LocationScore * MappedRead::AddScore(float const score, uint const loc, bool const reverse) {
Log.Error("AddScore");
throw "";
iScores += 1;
LocationScore * toInsert = &Scores[iScores - 1];
toInsert->Score.f = score;
toInsert->Location.m_Location = loc;
toInsert->Location.m_RefId = reverse;
toInsert->Read = this;
return toInsert;
//LocationScore * toInsert = new LocationScore(loc, reverse, score, this);
//toInsert->Read = this;
//Scores.push_back(toInsert);
//return toInsert;
}
void MappedRead::clearScores(bool const keepTop) {
if (TopScore != -1 && Scores != 0) {
LocationScore tmp = *TLS();
delete[] Scores;
if (keepTop) {
Scores = new LocationScore[1];
//Scores = (LocationScore *)realloc(Scores, 1 * sizeof(LocationScore));
Scores[0] = tmp;
TopScore = 0;
iScores = 1;
nScores = 1;
} else {
TopScore = -1;
iScores = 0;
nScores = 0;
Scores = 0;
}
}
}
LocationScore * MappedRead::TLS() const {
if (TopScore == -1) {
Log.Error("Top score accessed without calculation (Read %i, ESID %i, ESC %i)", ReadId, EqualScoringID, EqualScoringCount);
throw "";
return 0;
}
return &Scores[TopScore];
}
int MappedRead::numScores() const {
return iScores;
}
bool MappedRead::hasCandidates() const {
return iScores > 0;
}
void PrintScores(MappedRead const * read) {
// Log.Green("Scores for read %i", read->ReadId);
// for (size_t i = 0; i < read->Scores.size(); ++i) {
// if (read->Scores[i] == 0)
// Log.Message("<0>");
// else
// Log.Message("Score %.2f for <%i, %i>", read->Scores[i]->Score.f, read->Scores[i]->Location.m_Location, read->Scores[i]->Location.m_RefId);
// }
}
//void MappedRead::TopN(uint n) {
// if (Scores.size() == 0)
// return;
//
// if (Calculated > 0 && Calculated != (int) Scores.size())
// Log.Error("TopN called for inconsistent scores may lead to unexpected results.");
//
// std::sort(Scores.begin(), Scores.end(), SortPred); // Sort scores from best to worst
// Unique(); // Remove double scores
// Scores.erase(std::remove_if(Scores.begin(), Scores.end(), IsZero), Scores.end()); // remove 0-pointer from last step
//
// // remove from back all but top n
// while (Scores.size() > n) {
// delete Scores[Scores.size() - 1];
// Scores.pop_back();
// }
//
// // realloc vector
// std::vector<LocationScore*>(Scores).swap(Scores);
//
// TopScore = 0;
// Calculated = n;
//}
//void MappedRead::Unique() {
// uint ci = 0;
// for (uint i = 1; i < Scores.size(); ++i) {
// if (UniquePred(Scores[ci], Scores[i])) {
// delete Scores[i];
// Scores[i] = 0;
// } else
// ci = i;
// }
//}
<|endoftext|> |
<commit_before>#include <Arduino.h>
#include "RemoteControl.h"
#include <IRLib.h>
IRrecv My_Receiver(7); // TODO: use whatPin
IRdecode My_Decoder;
RemoteControl::RemoteControl( int whatPin )
{
// initialize variables
pin = whatPin;
pin = 7; // TODO: fix
last_command = RemoteCommandNone;
My_Receiver.enableIRIn(); // Start the receiver
}
RemoteCommand RemoteControl::loop() {
RemoteCommand r = RemoteCommandNone;
if (My_Receiver.GetResults(&My_Decoder)) {
My_Decoder.decode(); //Decode the data
//My_Decoder.DumpResults(); //Show the results on serial monitor
if (My_Decoder.decode_type== NEC) {
switch(My_Decoder.value) {
case 0xFD609F: //Stop button
r = RemoteCommandStop;
break;
case 0xFD807F: // Play
case 0xFD20DF: // Setup
r = RemoteCommandStart;
break;
case 0xFD10EF:
r = RemoteCommandLeft;
break;
case 0xFD50AF:
r = RemoteCommandRight;
break;
case 0xFD906F:
r = RemoteCommandBoth;
break;
case 0xFFFFFFFF: // repeat last
r = last_command;
break;
}
}
My_Receiver.resume(); //Restart the receiver
}
last_command = r;
return r;
}
void RemoteControl::clearCommand() {
last_command = RemoteCommandNone;
}
#pragma mark - Private
<commit_msg>Add logging to RemoteControl class<commit_after>#include <Arduino.h>
#include "RemoteControl.h"
#include <IRLib.h>
IRrecv My_Receiver(7); // TODO: use whatPin
IRdecode My_Decoder;
#define MAD_REMOTE_LOGGING 0
RemoteControl::RemoteControl( int whatPin )
{
// initialize variables
pin = whatPin;
pin = 7; // TODO: fix
last_command = RemoteCommandNone;
My_Receiver.enableIRIn(); // Start the receiver
}
RemoteCommand RemoteControl::loop() {
RemoteCommand r = RemoteCommandNone;
if (My_Receiver.GetResults(&My_Decoder)) {
My_Decoder.decode(); //Decode the data
//My_Decoder.DumpResults(); //Show the results on serial monitor
if (My_Decoder.decode_type== NEC) {
#if MAD_REMOTE_LOGGING
Serial.print("Remote: "); Serial.println(My_Decoder.value);
#endif
switch(My_Decoder.value) {
case 0xFD609F: //Stop button
r = RemoteCommandStop;
break;
case 0xFD807F: // Play
case 0xFD20DF: // Setup
r = RemoteCommandStart;
break;
case 0xFD10EF:
#if MAD_REMOTE_LOGGING
Serial.println("Remote Left");
#endif
r = RemoteCommandLeft;
break;
case 0xFD50AF:
#if MAD_REMOTE_LOGGING
Serial.println("Remote Right");
#endif
r = RemoteCommandRight;
break;
case 0xFD906F:
r = RemoteCommandBoth;
break;
case 0xFFFFFFFF: // repeat last
r = last_command;
#if MAD_REMOTE_LOGGING
Serial.println("Remote Repeat Last");
#endif
break;
}
}
My_Receiver.resume(); //Restart the receiver
}
last_command = r;
return r;
}
void RemoteControl::clearCommand() {
last_command = RemoteCommandNone;
}
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// 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 "default.h"
#include "distribution2d.h"
#include "../common/scenegraph/scenegraph.h"
#include "../common/image/image.h"
namespace embree
{
/* name of the tutorial */
const char* tutorialName = "convert";
struct HeightField : public RefCount
{
HeightField (Ref<Image> texture, const BBox3fa& bounds)
: texture(texture), bounds(bounds) {}
const Vec3fa at(const size_t x, const size_t y)
{
const size_t width = texture->width;
const size_t height = texture->height;
const Color4 c = texture->get(x,y);
const Vec2f p(x/float(width-1),y/float(height-1));
const float px = p.x*(bounds.upper.x-bounds.lower.x) + bounds.lower.x;
const float py = c.r*(bounds.upper.y-bounds.lower.y) + bounds.lower.y;
const float pz = p.y*(bounds.upper.z-bounds.lower.z) + bounds.lower.z;
return Vec3fa(px,py,pz);
}
const AffineSpace3fa get(Vec2f p)
{
const size_t width = texture->width;
const size_t height = texture->height;
const size_t x = clamp((size_t)(p.x*(width-1)),(size_t)0,width-1);
const size_t y = clamp((size_t)(p.y*(height-1)),(size_t)0,height-1);
const Color4 c = texture->get(x,y);
const float px = p.x*(bounds.upper.x-bounds.lower.x) + bounds.lower.x;
const float py = c.r*(bounds.upper.y-bounds.lower.y) + bounds.lower.y;
const float pz = p.y*(bounds.upper.z-bounds.lower.z) + bounds.lower.z;
return AffineSpace3fa::translate(Vec3fa(px,py,pz));
}
Ref<SceneGraph::Node> geometry()
{
OBJMaterial material(1.0f,Vec3fa(0.5f),Vec3fa(0.0f),1.0f);
Ref<SceneGraph::MaterialNode> mnode = new SceneGraph::MaterialNode((Material&)material);
Ref<SceneGraph::TriangleMeshNode> mesh = new SceneGraph::TriangleMeshNode(mnode);
const size_t width = texture->width;
const size_t height = texture->height;
mesh->v.resize(height*width);
for (size_t y=0; y<height; y++)
for (size_t x=0; x<width; x++)
mesh->v[y*width+x] = at(x,y);
mesh->triangles.resize(2*(height-1)*(width-1));
for (size_t y=0; y<height-1; y++) {
for (size_t x=0; x<width-1; x++) {
const size_t p00 = (y+0)*width+(x+0);
const size_t p01 = (y+0)*width+(x+1);
const size_t p10 = (y+1)*width+(x+0);
const size_t p11 = (y+1)*width+(x+1);
const size_t tri = y*(width-1)+x;
mesh->triangles[2*tri+0] = SceneGraph::TriangleMeshNode::Triangle(p00,p01,p10);
mesh->triangles[2*tri+1] = SceneGraph::TriangleMeshNode::Triangle(p01,p11,p10);
}
}
return mesh.dynamicCast<SceneGraph::Node>();
}
private:
Ref<Image> texture;
BBox3fa bounds;
};
struct Instantiator : public RefCount
{
Instantiator(const Ref<HeightField>& heightField,
const Ref<SceneGraph::Node>& object, const Ref<Image>& distribution, float minDistance, size_t N)
: heightField(heightField), object(object), dist(nullptr), minDistance(minDistance), N(N)
{
/* create distribution */
size_t width = distribution->width;
size_t height = distribution->height;
float* values = new float[width*height];
for (size_t y=0; y<height; y++)
for (size_t x=0; x<width; x++)
values[y*width+x] = luminance(distribution->get(x,y));
dist = new Distribution2D(values,width,height);
delete values;
}
void instantiate(Ref<SceneGraph::GroupNode>& group)
{
for (size_t i=0; i<N; i++)
{
Vec2f r = Vec2f(random<float>(),random<float>());
Vec2f p = dist->sample(r);
p.x *= rcp(float(dist->width)); p.y *= rcp(float(dist->height));
float angle = 2.0f*float(pi)*random<float>();
const AffineSpace3fa space = heightField->get(p)*AffineSpace3fa::rotate(Vec3fa(0,1,0),angle);
group->add(new SceneGraph::TransformNode(space,object));
}
}
private:
Ref<HeightField> heightField;
Ref<SceneGraph::Node> object;
Ref<Distribution2D> dist;
float minDistance;
size_t N;
};
/* scene */
Ref<SceneGraph::GroupNode> g_scene = new SceneGraph::GroupNode;
Ref<HeightField> g_height_field = nullptr;
static void parseCommandLine(Ref<ParseStream> cin, const FileName& path)
{
while (true)
{
std::string tag = cin->getString();
if (tag == "") return;
/* parse command line parameters from a file */
else if (tag == "-c") {
FileName file = path + cin->getFileName();
parseCommandLine(new ParseStream(new LineCommentFilter(file, "#")), file.path());
}
/* load model */
else if (tag == "-i") {
g_scene->add(SceneGraph::load(path + cin->getFileName()));
}
/* load terrain */
else if (tag == "-terrain")
{
Ref<Image> tex = loadImage(path + cin->getFileName());
const Vec3fa lower = cin->getVec3fa();
const Vec3fa upper = cin->getVec3fa();
g_height_field = new HeightField(tex,BBox3fa(lower,upper));
g_scene->add(g_height_field->geometry());
}
/* distribute model */
else if (tag == "-distribute") {
Ref<SceneGraph::Node> object = SceneGraph::load(path + cin->getFileName());
Ref<Image> distribution = loadImage(path + cin->getFileName());
const float minDistance = cin->getFloat();
const size_t N = cin->getInt();
Ref<Instantiator> instantiator = new Instantiator(g_height_field,object,distribution,minDistance,N);
instantiator->instantiate(g_scene);
}
/* instantiate model a single time */
else if (tag == "-instantiate") {
Ref<SceneGraph::Node> object = SceneGraph::load(path + cin->getFileName());
const float px = cin->getFloat();
const float py = cin->getFloat();
const Vec2f p(px,py);
const float angle = cin->getFloat()/180.0f*float(pi);
const AffineSpace3fa space = g_height_field->get(p)*AffineSpace3fa::rotate(Vec3fa(0,1,0),angle);
g_scene->add(new SceneGraph::TransformNode(space,object));
}
/* output filename */
else if (tag == "-o") {
SceneGraph::store(g_scene.dynamicCast<SceneGraph::Node>(),path + cin->getFileName());
}
/* skip unknown command line parameter */
else {
std::cerr << "unknown command line parameter: " << tag << " ";
while (cin->peek() != "" && cin->peek()[0] != '-') std::cerr << cin->getString() << " ";
std::cerr << std::endl;
}
}
}
/* main function in embree namespace */
int main(int argc, char** argv)
{
/* create stream for parsing */
Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv));
/* parse command line */
parseCommandLine(stream, FileName());
return 0;
}
}
int main(int argc, char** argv)
{
try {
return embree::main(argc, argv);
}
catch (const std::exception& e) {
std::cout << "Error: " << e.what() << std::endl;
return 1;
}
catch (...) {
std::cout << "Error: unknown exception caught." << std::endl;
return 1;
}
}
<commit_msg>updates<commit_after>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// 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 "default.h"
#include "distribution2d.h"
#include "../common/scenegraph/scenegraph.h"
#include "../common/image/image.h"
namespace embree
{
/* name of the tutorial */
const char* tutorialName = "convert";
struct HeightField : public RefCount
{
HeightField (Ref<Image> texture, const BBox3fa& bounds)
: texture(texture), bounds(bounds) {}
const Vec3fa at(const size_t x, const size_t y)
{
const size_t width = texture->width;
const size_t height = texture->height;
const Color4 c = texture->get(x,y);
const Vec2f p(x/float(width-1),y/float(height-1));
const float px = p.x*(bounds.upper.x-bounds.lower.x) + bounds.lower.x;
const float py = c.r*(bounds.upper.y-bounds.lower.y) + bounds.lower.y;
const float pz = p.y*(bounds.upper.z-bounds.lower.z) + bounds.lower.z;
return Vec3fa(px,py,pz);
}
const AffineSpace3fa get(Vec2f p)
{
const size_t width = texture->width;
const size_t height = texture->height;
const size_t x = clamp((size_t)(p.x*(width-1)),(size_t)0,width-1);
const size_t y = clamp((size_t)(p.y*(height-1)),(size_t)0,height-1);
const Color4 c = texture->get(x,y);
const float px = p.x*(bounds.upper.x-bounds.lower.x) + bounds.lower.x;
const float py = c.r*(bounds.upper.y-bounds.lower.y) + bounds.lower.y;
const float pz = p.y*(bounds.upper.z-bounds.lower.z) + bounds.lower.z;
return AffineSpace3fa::translate(Vec3fa(px,py,pz));
}
Ref<SceneGraph::Node> geometry()
{
OBJMaterial material(1.0f,Vec3fa(1.0f),Vec3fa(0.0f),1.0f);
Ref<SceneGraph::MaterialNode> mnode = new SceneGraph::MaterialNode((Material&)material);
Ref<SceneGraph::TriangleMeshNode> mesh = new SceneGraph::TriangleMeshNode(mnode);
const size_t width = texture->width;
const size_t height = texture->height;
mesh->v.resize(height*width);
for (size_t y=0; y<height; y++)
for (size_t x=0; x<width; x++)
mesh->v[y*width+x] = at(x,y);
mesh->triangles.resize(2*(height-1)*(width-1));
for (size_t y=0; y<height-1; y++) {
for (size_t x=0; x<width-1; x++) {
const size_t p00 = (y+0)*width+(x+0);
const size_t p01 = (y+0)*width+(x+1);
const size_t p10 = (y+1)*width+(x+0);
const size_t p11 = (y+1)*width+(x+1);
const size_t tri = y*(width-1)+x;
mesh->triangles[2*tri+0] = SceneGraph::TriangleMeshNode::Triangle(p00,p01,p10);
mesh->triangles[2*tri+1] = SceneGraph::TriangleMeshNode::Triangle(p01,p11,p10);
}
}
return mesh.dynamicCast<SceneGraph::Node>();
}
private:
Ref<Image> texture;
BBox3fa bounds;
};
struct Instantiator : public RefCount
{
Instantiator(const Ref<HeightField>& heightField,
const Ref<SceneGraph::Node>& object, const Ref<Image>& distribution, float minDistance, size_t N)
: heightField(heightField), object(object), dist(nullptr), minDistance(minDistance), N(N)
{
/* create distribution */
size_t width = distribution->width;
size_t height = distribution->height;
float* values = new float[width*height];
for (size_t y=0; y<height; y++)
for (size_t x=0; x<width; x++)
values[y*width+x] = luminance(distribution->get(x,y));
dist = new Distribution2D(values,width,height);
delete values;
}
void instantiate(Ref<SceneGraph::GroupNode>& group)
{
for (size_t i=0; i<N; i++)
{
Vec2f r = Vec2f(random<float>(),random<float>());
Vec2f p = dist->sample(r);
p.x *= rcp(float(dist->width)); p.y *= rcp(float(dist->height));
float angle = 2.0f*float(pi)*random<float>();
const AffineSpace3fa space = heightField->get(p)*AffineSpace3fa::rotate(Vec3fa(0,1,0),angle);
group->add(new SceneGraph::TransformNode(space,object));
}
}
private:
Ref<HeightField> heightField;
Ref<SceneGraph::Node> object;
Ref<Distribution2D> dist;
float minDistance;
size_t N;
};
/* scene */
Ref<SceneGraph::GroupNode> g_scene = new SceneGraph::GroupNode;
Ref<HeightField> g_height_field = nullptr;
static void parseCommandLine(Ref<ParseStream> cin, const FileName& path)
{
while (true)
{
std::string tag = cin->getString();
if (tag == "") return;
/* parse command line parameters from a file */
else if (tag == "-c") {
FileName file = path + cin->getFileName();
parseCommandLine(new ParseStream(new LineCommentFilter(file, "#")), file.path());
}
/* load model */
else if (tag == "-i") {
g_scene->add(SceneGraph::load(path + cin->getFileName()));
}
/* load terrain */
else if (tag == "-terrain")
{
Ref<Image> tex = loadImage(path + cin->getFileName());
const Vec3fa lower = cin->getVec3fa();
const Vec3fa upper = cin->getVec3fa();
g_height_field = new HeightField(tex,BBox3fa(lower,upper));
g_scene->add(g_height_field->geometry());
}
/* distribute model */
else if (tag == "-distribute") {
Ref<SceneGraph::Node> object = SceneGraph::load(path + cin->getFileName());
Ref<Image> distribution = loadImage(path + cin->getFileName());
const float minDistance = cin->getFloat();
const size_t N = cin->getInt();
Ref<Instantiator> instantiator = new Instantiator(g_height_field,object,distribution,minDistance,N);
instantiator->instantiate(g_scene);
}
/* instantiate model a single time */
else if (tag == "-instantiate") {
Ref<SceneGraph::Node> object = SceneGraph::load(path + cin->getFileName());
const float px = cin->getFloat();
const float py = cin->getFloat();
const Vec2f p(px,py);
const float angle = cin->getFloat()/180.0f*float(pi);
const AffineSpace3fa space = g_height_field->get(p)*AffineSpace3fa::rotate(Vec3fa(0,1,0),angle);
g_scene->add(new SceneGraph::TransformNode(space,object));
}
/* output filename */
else if (tag == "-o") {
SceneGraph::store(g_scene.dynamicCast<SceneGraph::Node>(),path + cin->getFileName());
}
/* skip unknown command line parameter */
else {
std::cerr << "unknown command line parameter: " << tag << " ";
while (cin->peek() != "" && cin->peek()[0] != '-') std::cerr << cin->getString() << " ";
std::cerr << std::endl;
}
}
}
/* main function in embree namespace */
int main(int argc, char** argv)
{
/* create stream for parsing */
Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv));
/* parse command line */
parseCommandLine(stream, FileName());
return 0;
}
}
int main(int argc, char** argv)
{
try {
return embree::main(argc, argv);
}
catch (const std::exception& e) {
std::cout << "Error: " << e.what() << std::endl;
return 1;
}
catch (...) {
std::cout << "Error: unknown exception caught." << std::endl;
return 1;
}
}
<|endoftext|> |
<commit_before>
#include <libclientserver.h>
/**
* Init
*
* This should be called to intialize any base class member variables and state.
*
*/
void ClientBase::Init()
{
memset(&m_SoftTimeout, 0, sizeof(m_SoftTimeout));
memset(&m_HardTimeout, 0, sizeof(m_HardTimeout));
memset(&m_ReConnectTimeout, 0, sizeof(m_ReConnectTimeout));
m_SoftTimeout.tv_sec = 5;
m_HardTimeout.tv_sec = 30;
m_ReConnectTimeout.tv_sec = 1;
m_LastID = 1;
m_Handler = NULL;
}
/**
* WaitForConnect
*
* This function provides a method that will sleep until the client reaches a connected state to the server.
* Please be aware that this function will not return until a connection has been made.
* However when it returns it is possible the that client could have also been disconnected from the server again.
*/
void ClientBase::WaitForConnect()
{
struct timespec ts;
ts.tv_sec = 30;
ts.tv_nsec = 0;
while(WaitForConnect(&ts) == false) { }
}
/**
* WaitForConnect
* @param[in] Timeout The specified time to wait before returning
* @return If a connection was made.
*
* This function provides a method that will sleep until the client reaches a connected state to the server. Or until the value in timeout has elasped
* However when it returns it is possible the that client could have also been disconnected from the server again. Event when the function returns true.
*/
bool ClientBase::WaitForConnect(const struct timespec *Timeout)
{
ScopedLock lock(&m_ConnectedMutex);
while(IsConnected() == false)
{
if (m_ConnectedMutex.Wait(Timeout) == 0)
{
if (IsConnected())
return true;
}
}
return false;
}
/**
* SetReConnectTimeout
* @param[in] Timeout The time to wait before retrying a connection
*
* This function sets the retry time between connections to the server.
*
*/
void ClientBase::SetReConnectTimeout(const struct timespec *Timeout)
{
//FIXME: This should be called SetReconnectDelay
memcpy(&m_ReConnectTimeout, Timeout, sizeof(m_ReConnectTimeout));
}
/**
* SetSoftTimeout
* @params[in] Timeout value
*
* This function will set the default soft timeout value when sending requests
* The function will take a copy of the struture that SoftTimeout points to.
*
* The soft timeout values can be overridded by the server. If the server sends keepalive messages
*/
void ClientBase::SetSoftTimeout(const struct timespec *SoftTimeout)
{
memcpy(&m_SoftTimeout, SoftTimeout, sizeof(m_SoftTimeout));
}
/**
* SetHardTimeout
* @params[in] Timeout value
*
* This function will set the default hard timeout value when sending requests
* The function will take a copy of the struture that HardTimeout points to.
*
* The hard timeout value will never be ignored when sending requests.
* If it is ignored then it should be considered a bug.
*/
void ClientBase::SetHardTimeout(const struct timespec *HardTimeout)
{
memcpy(&m_HardTimeout, HardTimeout, sizeof(m_HardTimeout));
}
/**
* SetHandler
* @params[in] Handler
*
* Register a Handler class which is used by the client so that the client implmenetation can take certain actions when various events occur.
* These event happen during Disconnect / Connect / Errors
*
*/
void ClientBase::SetHandler(IClientHandler *Handler)
{
m_Handler = Handler;
}
/**
* SendRequest
* @param[in] request The Client Request
* @param[out] response The Server Response
* @param[in] SoftTimeout The soft timeout value
* @param[in] HardTimeout The hard timeout value
* @return True when a response is recived from the server
*
* This function is the full version of SendRequest with arugments for setting both the Soft/Hard timeout functions.
* the Soft/Hard timeout values that are specified to this function will override any default that have been set.
*
* If the function returns false. The contents of the response will be undefined.
*/
bool ClientBase::SendRequest(Request *request, Request *response, const struct timespec *SoftTimeout, const struct timespec *HardTimeout)
{
//FIXME: request should be const
struct RequestMapEntry Entry;
memset(&Entry, 0, sizeof(Entry));
Entry.id = m_LastID++;
Entry.Response = response;
Entry.ValidResponse = false;
Entry.KeepAlive = false;
request->SetID(Entry.id);
m_rmap.Add(&Entry);
if (DoSendRequest(request, SoftTimeout) == false) //Get Out quickly option - happens when we are disconnected
{
m_rmap.Remove(&Entry);
return false;
}
m_rmap.Wait(&Entry, SoftTimeout, HardTimeout);
m_rmap.Remove(&Entry);
return Entry.ValidResponse;
}
/**
* SendRequest
* @param[in] request The Client Request
* @param[out] response The Server Response
* @param[in] SoftTimeout The soft timeout value
*
* This function is the partial version of SendRequest with arugments for setting both the Soft timeout functions.
* the Soft timeout values that are specified to this function will override any default that have been set.
*
* the hard timeout value that will be used is the default configured value on the instance of the class.
*
* For more details please read the documentation on the full function.
*/
bool ClientBase::SendRequest(Request *request, Request *response, const struct timespec *SoftTimeout)
{
//FIXME: request should be const
return SendRequest(request, response, SoftTimeout, &m_HardTimeout);
}
/**
* SendRequest
* @param[in] request The Client Request
* @param[out] response The Server Response
*
* This is the basic function for sending a request where the default values of Soft/Hard timeout will be used.
* For more details please read the documentation on the full function.
*/
bool ClientBase::SendRequest(Request *request, Request *response)
{
return SendRequest(request, response, &m_SoftTimeout, &m_HardTimeout);
}
/**
* SendCommand
* @param[in] command
* @param[in] Timeout
* @return True when successful
*
* Note this function can return True even when sending the command is not successful. It Only states that the command was queued to be send to the server.
* If the Client is not Connected to the server then this function will immeditatly return false.
*/
bool ClientBase::SendCommand(Request *command, const struct timespec *Timeout)
{
//FIXME: command should be const
return DoSendCommand(command, Timeout);
}
/**
* SendCommand
* @param[in] command
* @param[in] Timeout
* @return True when successful
*
* Note this function can return True even when sending the command is not successful. It Only states that the command was queued to be send to the server.
* If the Client is not Connected to the server then this function will immeditatly return false.
*/
bool ClientBase::SendCommand(Request *command)
{
//FIXME: command should be const
return SendCommand(command, &m_SoftTimeout);
}
bool ClientBase::DoSendRequest(Request *request, const struct timespec *Timeout)
{
//FIXME: request should be const
std::string str = "REQUEST " + request->Encode() + "\n";
return SendLine(&str, Timeout);
}
bool ClientBase::DoSendCommand(Request *request, const struct timespec *Timeout)
{
//FIXME: request should be const
std::string str = "COMMAND " + request->Encode() + "\n";
return SendLine(&str, Timeout);
}
/**
* GetNextID
* @return The next avilable ID
*
* This function is used to generate a unique index for every request that is sent by the client
*/
uint64_t ClientBase::GetNextID()
{
ScopedLock lock(&m_LastIDMutex);
m_LastID++;
return m_LastID;
}
/**
* RaiseOnConnect
*
* This function is called when a client makes a connection to the server
*/
void ClientBase::RaiseOnConnect()
{
ScopedLock lock(&m_ConnectedMutex);
#ifdef DEBUG
if (IsConnected() == false)
abort(); //Apparently Not Connected. This is a bug in the dervied class for Raiseing the event when not connected
#endif
m_ConnectedMutex.WakeUpAll();
if (m_Handler != NULL)
m_Handler->OnConnect();
}
/**
* RaiseOnConnectError
* @param[in] err the contents of errno when the error occured
* @param[in] str a text version of the error
*
* The function is called every time a connection fails to the server
*/
void ClientBase::RaiseOnConnectError(int err, const std::string &str)
{
if (m_Handler != NULL)
m_Handler->OnConnectError(err, str);
}
/**
* RaiseOnSendError
* @param[in] err the contents of errno when the error occured
* @param[in] str a text version of the error
*
* The function is called when there is an error sending data to the server
*/
void ClientBase::RaiseOnSendError(int err, const std::string &str)
{
if (m_Handler != NULL)
m_Handler->OnSendError(err, str);
}
/**
* RaiseOnDisconnect
* @param[in] err the contents of errno when the error occured
* @param[in] str a text version of the error
*
* The function is called when the client disconnects from the server for any reason.
* Note that the err value may indicate success which is valid and only suggests that the connection
* was shutdown cleanly as requested
*/
void ClientBase::RaiseOnDisconnect(int err, const std::string &str)
{
if (m_Handler != NULL)
m_Handler->OnDisconnect(err, str);
}
/**
* RaiseOnResponse
* @param[in] response
*
* This function is called when a response is recived by the client
*/
void ClientBase::RaiseOnResponse(Request *response)
{
//FIXME: repsonse should be const
if (m_Handler != NULL)
{
if (m_Handler->OnResponse(response) == false)
{
return;
}
}
m_rmap.WakeUp(response);
}
/**
* RaiseOnKeepAlive
* @param[in] response
*
* This function is called when a keepalive is recived by the client
*/
void ClientBase::RaiseOnKeepAlive(Request *response)
{
//FIXME: repsonse should be const
if (m_Handler != NULL)
{
if (m_Handler->OnKeepAlive(response) == false)
{
return;
}
}
m_rmap.KeepAlive(response);
}
/**
* RaiseOnEvent
* @param[in] event
*
* This function is called when an event is recived by the client
*/
void ClientBase::RaiseOnEvent(Request *event)
{
//FIXME: event should be const
if (m_Handler != NULL)
{
if (m_Handler->OnEvent(event) == false)
{
return;
}
}
}
/**
* RaiseOnData
* @param[in] str
*
* This function is called when a line of data is recived by the client
*/
void ClientBase::RaiseOnData(const std::string *str)
{
std::string command = "";
std::string args = "";
if (String::SplitOne(str, &command, &args, " ") == false)
{
RaiseOnBadLine(str);
return;
}
if (command == "RESPONSE")
{
Request response;
if (response.Decode(&args) == false)
{
RaiseOnBadLine(str);
return;
}
printf("Response: %s\n", str->c_str());
RaiseOnResponse(&response);
return;
}
if (command == "KEEPALIVE")
{
Request keepalive;
if (keepalive.Decode(&args) == false)
{
RaiseOnBadLine(str);
return;
}
printf("KeepAlive: %s", str->c_str());
RaiseOnKeepAlive(&keepalive);
return;
}
if (command == "EVENT")
{
Request event;
if (event.Decode(&args) == false)
{
RaiseOnBadLine(str);
return;
}
printf("Event: %s", str->c_str());
RaiseOnEvent(&event);
return;
}
RaiseOnBadLine(str);
return;
}
/**
* RaiseOnBadLine
* @param[in] str
*
* This function is called when a line of bad data / non-parseable data is recived by the client
*/
void ClientBase::RaiseOnBadLine(const std::string *str)
{
if (m_Handler != NULL)
m_Handler->OnBadLine(str);
printf("BadLine: %s", str->c_str());
//FIXME: We should abort here if the handler doesnt handle
}
<commit_msg>Added another FIXME<commit_after>
#include <libclientserver.h>
/**
* Init
*
* This should be called to intialize any base class member variables and state.
*
*/
void ClientBase::Init()
{
memset(&m_SoftTimeout, 0, sizeof(m_SoftTimeout));
memset(&m_HardTimeout, 0, sizeof(m_HardTimeout));
memset(&m_ReConnectTimeout, 0, sizeof(m_ReConnectTimeout));
m_SoftTimeout.tv_sec = 5;
m_HardTimeout.tv_sec = 30;
m_ReConnectTimeout.tv_sec = 1;
m_LastID = 1;
m_Handler = NULL;
}
/**
* WaitForConnect
*
* This function provides a method that will sleep until the client reaches a connected state to the server.
* Please be aware that this function will not return until a connection has been made.
* However when it returns it is possible the that client could have also been disconnected from the server again.
*/
void ClientBase::WaitForConnect()
{
struct timespec ts;
ts.tv_sec = 30;
ts.tv_nsec = 0;
while(WaitForConnect(&ts) == false) { }
}
/**
* WaitForConnect
* @param[in] Timeout The specified time to wait before returning
* @return If a connection was made.
*
* This function provides a method that will sleep until the client reaches a connected state to the server. Or until the value in timeout has elasped
* However when it returns it is possible the that client could have also been disconnected from the server again. Event when the function returns true.
*/
bool ClientBase::WaitForConnect(const struct timespec *Timeout)
{
ScopedLock lock(&m_ConnectedMutex);
while(IsConnected() == false)
{
if (m_ConnectedMutex.Wait(Timeout) == 0)
{
if (IsConnected())
return true;
}
}
return false;
}
/**
* SetReConnectTimeout
* @param[in] Timeout The time to wait before retrying a connection
*
* This function sets the retry time between connections to the server.
*
*/
void ClientBase::SetReConnectTimeout(const struct timespec *Timeout)
{
//FIXME: This should be called SetReconnectDelay
memcpy(&m_ReConnectTimeout, Timeout, sizeof(m_ReConnectTimeout));
}
/**
* SetSoftTimeout
* @params[in] Timeout value
*
* This function will set the default soft timeout value when sending requests
* The function will take a copy of the struture that SoftTimeout points to.
*
* The soft timeout values can be overridded by the server. If the server sends keepalive messages
*/
void ClientBase::SetSoftTimeout(const struct timespec *SoftTimeout)
{
memcpy(&m_SoftTimeout, SoftTimeout, sizeof(m_SoftTimeout));
}
/**
* SetHardTimeout
* @params[in] Timeout value
*
* This function will set the default hard timeout value when sending requests
* The function will take a copy of the struture that HardTimeout points to.
*
* The hard timeout value will never be ignored when sending requests.
* If it is ignored then it should be considered a bug.
*/
void ClientBase::SetHardTimeout(const struct timespec *HardTimeout)
{
memcpy(&m_HardTimeout, HardTimeout, sizeof(m_HardTimeout));
}
/**
* SetHandler
* @params[in] Handler
*
* Register a Handler class which is used by the client so that the client implmenetation can take certain actions when various events occur.
* These event happen during Disconnect / Connect / Errors
*
*/
void ClientBase::SetHandler(IClientHandler *Handler)
{
m_Handler = Handler;
}
/**
* SendRequest
* @param[in] request The Client Request
* @param[out] response The Server Response
* @param[in] SoftTimeout The soft timeout value
* @param[in] HardTimeout The hard timeout value
* @return True when a response is recived from the server
*
* This function is the full version of SendRequest with arugments for setting both the Soft/Hard timeout functions.
* the Soft/Hard timeout values that are specified to this function will override any default that have been set.
*
* If the function returns false. The contents of the response will be undefined.
*/
bool ClientBase::SendRequest(Request *request, Request *response, const struct timespec *SoftTimeout, const struct timespec *HardTimeout)
{
//FIXME: request should be const
struct RequestMapEntry Entry;
memset(&Entry, 0, sizeof(Entry));
Entry.id = m_LastID++;
Entry.Response = response;
Entry.ValidResponse = false;
Entry.KeepAlive = false;
request->SetID(Entry.id);
m_rmap.Add(&Entry);
if (DoSendRequest(request, SoftTimeout) == false) //Get Out quickly option - happens when we are disconnected
{
m_rmap.Remove(&Entry);
return false;
}
m_rmap.Wait(&Entry, SoftTimeout, HardTimeout);
m_rmap.Remove(&Entry);
return Entry.ValidResponse;
}
/**
* SendRequest
* @param[in] request The Client Request
* @param[out] response The Server Response
* @param[in] SoftTimeout The soft timeout value
*
* This function is the partial version of SendRequest with arugments for setting both the Soft timeout functions.
* the Soft timeout values that are specified to this function will override any default that have been set.
*
* the hard timeout value that will be used is the default configured value on the instance of the class.
*
* For more details please read the documentation on the full function.
*/
bool ClientBase::SendRequest(Request *request, Request *response, const struct timespec *SoftTimeout)
{
//FIXME: request should be const
return SendRequest(request, response, SoftTimeout, &m_HardTimeout);
}
/**
* SendRequest
* @param[in] request The Client Request
* @param[out] response The Server Response
*
* This is the basic function for sending a request where the default values of Soft/Hard timeout will be used.
* For more details please read the documentation on the full function.
*/
bool ClientBase::SendRequest(Request *request, Request *response)
{
//FIXME: request should be const
return SendRequest(request, response, &m_SoftTimeout, &m_HardTimeout);
}
/**
* SendCommand
* @param[in] command
* @param[in] Timeout
* @return True when successful
*
* Note this function can return True even when sending the command is not successful. It Only states that the command was queued to be send to the server.
* If the Client is not Connected to the server then this function will immeditatly return false.
*/
bool ClientBase::SendCommand(Request *command, const struct timespec *Timeout)
{
//FIXME: command should be const
return DoSendCommand(command, Timeout);
}
/**
* SendCommand
* @param[in] command
* @param[in] Timeout
* @return True when successful
*
* Note this function can return True even when sending the command is not successful. It Only states that the command was queued to be send to the server.
* If the Client is not Connected to the server then this function will immeditatly return false.
*/
bool ClientBase::SendCommand(Request *command)
{
//FIXME: command should be const
return SendCommand(command, &m_SoftTimeout);
}
bool ClientBase::DoSendRequest(Request *request, const struct timespec *Timeout)
{
//FIXME: request should be const
std::string str = "REQUEST " + request->Encode() + "\n";
return SendLine(&str, Timeout);
}
bool ClientBase::DoSendCommand(Request *request, const struct timespec *Timeout)
{
//FIXME: request should be const
std::string str = "COMMAND " + request->Encode() + "\n";
return SendLine(&str, Timeout);
}
/**
* GetNextID
* @return The next avilable ID
*
* This function is used to generate a unique index for every request that is sent by the client
*/
uint64_t ClientBase::GetNextID()
{
ScopedLock lock(&m_LastIDMutex);
m_LastID++;
return m_LastID;
}
/**
* RaiseOnConnect
*
* This function is called when a client makes a connection to the server
*/
void ClientBase::RaiseOnConnect()
{
ScopedLock lock(&m_ConnectedMutex);
#ifdef DEBUG
if (IsConnected() == false)
abort(); //Apparently Not Connected. This is a bug in the dervied class for Raiseing the event when not connected
#endif
m_ConnectedMutex.WakeUpAll();
if (m_Handler != NULL)
m_Handler->OnConnect();
}
/**
* RaiseOnConnectError
* @param[in] err the contents of errno when the error occured
* @param[in] str a text version of the error
*
* The function is called every time a connection fails to the server
*/
void ClientBase::RaiseOnConnectError(int err, const std::string &str)
{
if (m_Handler != NULL)
m_Handler->OnConnectError(err, str);
}
/**
* RaiseOnSendError
* @param[in] err the contents of errno when the error occured
* @param[in] str a text version of the error
*
* The function is called when there is an error sending data to the server
*/
void ClientBase::RaiseOnSendError(int err, const std::string &str)
{
if (m_Handler != NULL)
m_Handler->OnSendError(err, str);
}
/**
* RaiseOnDisconnect
* @param[in] err the contents of errno when the error occured
* @param[in] str a text version of the error
*
* The function is called when the client disconnects from the server for any reason.
* Note that the err value may indicate success which is valid and only suggests that the connection
* was shutdown cleanly as requested
*/
void ClientBase::RaiseOnDisconnect(int err, const std::string &str)
{
if (m_Handler != NULL)
m_Handler->OnDisconnect(err, str);
}
/**
* RaiseOnResponse
* @param[in] response
*
* This function is called when a response is recived by the client
*/
void ClientBase::RaiseOnResponse(Request *response)
{
//FIXME: repsonse should be const
if (m_Handler != NULL)
{
if (m_Handler->OnResponse(response) == false)
{
return;
}
}
m_rmap.WakeUp(response);
}
/**
* RaiseOnKeepAlive
* @param[in] response
*
* This function is called when a keepalive is recived by the client
*/
void ClientBase::RaiseOnKeepAlive(Request *response)
{
//FIXME: repsonse should be const
if (m_Handler != NULL)
{
if (m_Handler->OnKeepAlive(response) == false)
{
return;
}
}
m_rmap.KeepAlive(response);
}
/**
* RaiseOnEvent
* @param[in] event
*
* This function is called when an event is recived by the client
*/
void ClientBase::RaiseOnEvent(Request *event)
{
//FIXME: event should be const
if (m_Handler != NULL)
{
if (m_Handler->OnEvent(event) == false)
{
return;
}
}
}
/**
* RaiseOnData
* @param[in] str
*
* This function is called when a line of data is recived by the client
*/
void ClientBase::RaiseOnData(const std::string *str)
{
std::string command = "";
std::string args = "";
if (String::SplitOne(str, &command, &args, " ") == false)
{
RaiseOnBadLine(str);
return;
}
if (command == "RESPONSE")
{
Request response;
if (response.Decode(&args) == false)
{
RaiseOnBadLine(str);
return;
}
printf("Response: %s\n", str->c_str());
RaiseOnResponse(&response);
return;
}
if (command == "KEEPALIVE")
{
Request keepalive;
if (keepalive.Decode(&args) == false)
{
RaiseOnBadLine(str);
return;
}
printf("KeepAlive: %s", str->c_str());
RaiseOnKeepAlive(&keepalive);
return;
}
if (command == "EVENT")
{
Request event;
if (event.Decode(&args) == false)
{
RaiseOnBadLine(str);
return;
}
printf("Event: %s", str->c_str());
RaiseOnEvent(&event);
return;
}
RaiseOnBadLine(str);
return;
}
/**
* RaiseOnBadLine
* @param[in] str
*
* This function is called when a line of bad data / non-parseable data is recived by the client
*/
void ClientBase::RaiseOnBadLine(const std::string *str)
{
if (m_Handler != NULL)
m_Handler->OnBadLine(str);
printf("BadLine: %s", str->c_str());
//FIXME: We should abort here if the handler doesnt handle
}
<|endoftext|> |
<commit_before>//Example to fit two histograms at the same time
//Author: Rene Brun
#include "TH2D.h"
#include "TF2.h"
#include "TCanvas.h"
#include "TStyle.h"
#include "TRandom3.h"
#include "TVirtualFitter.h"
#include "TList.h"
#include <vector>
#include <map>
#include <iostream>
double gauss2D(double *x, double *par) {
double z1 = double((x[0]-par[1])/par[2]);
double z2 = double((x[1]-par[3])/par[4]);
return par[0]*exp(-0.5*(z1*z1+z2*z2));
}
double my2Dfunc(double *x, double *par) {
double *p1 = &par[0];
double *p2 = &par[5];
return gauss2D(x,p1) + gauss2D(x,p2);
}
// data need to be globals to be visible by fcn
std::vector<std::pair<double, double> > coords;
std::vector<double > values;
std::vector<double > errors;
void myFcn(Int_t & /*nPar*/, Double_t * /*grad*/ , Double_t &fval, Double_t *p, Int_t /*iflag */ )
{
int n = coords.size();
double chi2 = 0;
double tmp,x[2];
for (int i = 0; i <n; ++i ) {
x[0] = coords[i].first;
x[1] = coords[i].second;
tmp = ( values[i] - my2Dfunc(x,p))/errors[i];
chi2 += tmp*tmp;
}
fval = chi2;
}
TRandom3 rndm;
void FillHisto(TH2D * h, int n, double * p) {
const double mx1 = p[1];
const double my1 = p[3];
const double sx1 = p[2];
const double sy1 = p[4];
const double mx2 = p[6];
const double my2 = p[8];
const double sx2 = p[7];
const double sy2 = p[9];
//const double w1 = p[0]*sx1*sy1/(p[5]*sx2*sy2);
const double w1 = 0.5;
double x, y;
for (int i = 0; i < n; ++i) {
// generate randoms with larger gaussians
rndm.Rannor(x,y);
double r = rndm.Rndm(1);
if (r < w1) {
x = x*sx1 + mx1;
y = y*sy1 + my1;
}
else {
x = x*sx2 + mx2;
y = y*sy2 + my2;
}
h->Fill(x,y);
}
}
int TwoHistoFit2D(bool global = true) {
// create two histograms
int nbx1 = 50;
int nby1 = 50;
int nbx2 = 50;
int nby2 = 50;
double xlow1 = 0.;
double ylow1 = 0.;
double xup1 = 10.;
double yup1 = 10.;
double xlow2 = 5.;
double ylow2 = 5.;
double xup2 = 20.;
double yup2 = 20.;
TH2D * h1 = new TH2D("h1","core",nbx1,xlow1,xup1,nby1,ylow1,yup1);
TH2D * h2 = new TH2D("h2","tails",nbx2,xlow2,xup2,nby2,ylow2,yup2);
double iniParams[10] = { 100, 6., 2., 7., 3, 100, 12., 3., 11., 2. };
// create fit function
TF2 * func = new TF2("func",my2Dfunc,xlow2,xup2,ylow2,yup2, 10);
func->SetParameters(iniParams);
// fill Histos
int n1 = 1000000;
int n2 = 1000000;
// h1->FillRandom("func", n1);
//h2->FillRandom("func",n2);
FillHisto(h1,n1,iniParams);
FillHisto(h2,n2,iniParams);
// scale histograms to same heights (for fitting)
double dx1 = (xup1-xlow1)/double(nbx1);
double dy1 = (yup1-ylow1)/double(nby1);
double dx2 = (xup2-xlow2)/double(nbx2);
double dy2 = (yup2-ylow2)/double(nby2);
// h1->Sumw2();
// h1->Scale( 1.0 / ( n1 * dx1 * dy1 ) );
// scale histo 2 to scale of 1
h2->Sumw2();
h2->Scale( ( double(n1) * dx1 * dy1 ) / ( double(n2) * dx2 * dy2 ) );
if (global) {
// fill data structure for fit (coordinates + values + errors)
std::cout << "Do global fit" << std::endl;
// fit now all the function together
// fill data structure for fit (coordinates + values + errors)
TAxis *xaxis1 = h1->GetXaxis();
TAxis *yaxis1 = h1->GetYaxis();
TAxis *xaxis2 = h2->GetXaxis();
TAxis *yaxis2 = h2->GetYaxis();
int nbinX1 = h1->GetNbinsX();
int nbinY1 = h1->GetNbinsY();
int nbinX2 = h2->GetNbinsX();
int nbinY2 = h2->GetNbinsY();
/// reset data structure
coords = std::vector<std::pair<double,double> >();
values = std::vector<double>();
errors = std::vector<double>();
for (int ix = 1; ix <= nbinX1; ++ix) {
for (int iy = 1; iy <= nbinY1; ++iy) {
if ( h1->GetBinContent(ix,iy) > 0 ) {
coords.push_back( std::make_pair(xaxis1->GetBinCenter(ix), yaxis1->GetBinCenter(iy) ) );
values.push_back( h1->GetBinContent(ix,iy) );
errors.push_back( h1->GetBinError(ix,iy) );
}
}
}
for (int ix = 1; ix <= nbinX2; ++ix) {
for (int iy = 1; iy <= nbinY2; ++iy) {
if ( h2->GetBinContent(ix,iy) > 0 ) {
coords.push_back( std::make_pair(xaxis2->GetBinCenter(ix), yaxis2->GetBinCenter(iy) ) );
values.push_back( h2->GetBinContent(ix,iy) );
errors.push_back( h2->GetBinError(ix,iy) );
}
}
}
TVirtualFitter::SetDefaultFitter("Minuit");
TVirtualFitter * minuit = TVirtualFitter::Fitter(0,10);
for (int i = 0; i < 10; ++i) {
minuit->SetParameter(i, func->GetParName(i), func->GetParameter(i), 0.01, 0,0);
}
minuit->SetFCN(myFcn);
double arglist[100];
arglist[0] = 0;
// set print level
minuit->ExecuteCommand("SET PRINT",arglist,2);
// minimize
arglist[0] = 5000; // number of function calls
arglist[1] = 0.01; // tolerance
minuit->ExecuteCommand("MIGRAD",arglist,2);
//get result
double minParams[10];
double parErrors[10];
for (int i = 0; i < 10; ++i) {
minParams[i] = minuit->GetParameter(i);
parErrors[i] = minuit->GetParError(i);
}
double chi2, edm, errdef;
int nvpar, nparx;
minuit->GetStats(chi2,edm,errdef,nvpar,nparx);
func->SetParameters(minParams);
func->SetParErrors(parErrors);
func->SetChisquare(chi2);
int ndf = coords.size()-nvpar;
func->SetNDF(ndf);
std::cout << "Chi2 Fit = " << chi2 << " ndf = " << ndf << " " << func->GetNDF() << std::endl;
// add to list of functions
h1->GetListOfFunctions()->Add(func);
h2->GetListOfFunctions()->Add(func);
}
else {
// fit independently
h1->Fit(func);
h2->Fit(func);
}
// Create a new canvas.
TCanvas * c1 = new TCanvas("c1","Two HIstogram Fit example",100,10,900,800);
c1->Divide(2,2);
gStyle->SetOptFit();
gStyle->SetStatY(0.6);
c1->cd(1);
h1->Draw();
func->SetRange(xlow1,ylow1,xup1,yup1);
func->DrawCopy("cont1 same");
c1->cd(2);
h1->Draw("lego");
func->DrawCopy("surf1 same");
c1->cd(3);
func->SetRange(xlow2,ylow2,xup2,yup2);
h2->Draw();
func->DrawCopy("cont1 same");
c1->cd(4);
h2->Draw("lego");
gPad->SetLogz();
func->Draw("surf1 same");
return 0;
}
<commit_msg>Must be executed with ACLIC<commit_after>//+ Example to fit two histograms at the same time
//Author: Rene Brun
#include "TH2D.h"
#include "TF2.h"
#include "TCanvas.h"
#include "TStyle.h"
#include "TRandom3.h"
#include "TVirtualFitter.h"
#include "TList.h"
#include <vector>
#include <map>
#include <iostream>
double gauss2D(double *x, double *par) {
double z1 = double((x[0]-par[1])/par[2]);
double z2 = double((x[1]-par[3])/par[4]);
return par[0]*exp(-0.5*(z1*z1+z2*z2));
}
double my2Dfunc(double *x, double *par) {
double *p1 = &par[0];
double *p2 = &par[5];
return gauss2D(x,p1) + gauss2D(x,p2);
}
// data need to be globals to be visible by fcn
std::vector<std::pair<double, double> > coords;
std::vector<double > values;
std::vector<double > errors;
void myFcn(Int_t & /*nPar*/, Double_t * /*grad*/ , Double_t &fval, Double_t *p, Int_t /*iflag */ )
{
int n = coords.size();
double chi2 = 0;
double tmp,x[2];
for (int i = 0; i <n; ++i ) {
x[0] = coords[i].first;
x[1] = coords[i].second;
tmp = ( values[i] - my2Dfunc(x,p))/errors[i];
chi2 += tmp*tmp;
}
fval = chi2;
}
TRandom3 rndm;
void FillHisto(TH2D * h, int n, double * p) {
const double mx1 = p[1];
const double my1 = p[3];
const double sx1 = p[2];
const double sy1 = p[4];
const double mx2 = p[6];
const double my2 = p[8];
const double sx2 = p[7];
const double sy2 = p[9];
//const double w1 = p[0]*sx1*sy1/(p[5]*sx2*sy2);
const double w1 = 0.5;
double x, y;
for (int i = 0; i < n; ++i) {
// generate randoms with larger gaussians
rndm.Rannor(x,y);
double r = rndm.Rndm(1);
if (r < w1) {
x = x*sx1 + mx1;
y = y*sy1 + my1;
}
else {
x = x*sx2 + mx2;
y = y*sy2 + my2;
}
h->Fill(x,y);
}
}
int TwoHistoFit2D(bool global = true) {
// create two histograms
int nbx1 = 50;
int nby1 = 50;
int nbx2 = 50;
int nby2 = 50;
double xlow1 = 0.;
double ylow1 = 0.;
double xup1 = 10.;
double yup1 = 10.;
double xlow2 = 5.;
double ylow2 = 5.;
double xup2 = 20.;
double yup2 = 20.;
TH2D * h1 = new TH2D("h1","core",nbx1,xlow1,xup1,nby1,ylow1,yup1);
TH2D * h2 = new TH2D("h2","tails",nbx2,xlow2,xup2,nby2,ylow2,yup2);
double iniParams[10] = { 100, 6., 2., 7., 3, 100, 12., 3., 11., 2. };
// create fit function
TF2 * func = new TF2("func",my2Dfunc,xlow2,xup2,ylow2,yup2, 10);
func->SetParameters(iniParams);
// fill Histos
int n1 = 1000000;
int n2 = 1000000;
// h1->FillRandom("func", n1);
//h2->FillRandom("func",n2);
FillHisto(h1,n1,iniParams);
FillHisto(h2,n2,iniParams);
// scale histograms to same heights (for fitting)
double dx1 = (xup1-xlow1)/double(nbx1);
double dy1 = (yup1-ylow1)/double(nby1);
double dx2 = (xup2-xlow2)/double(nbx2);
double dy2 = (yup2-ylow2)/double(nby2);
// h1->Sumw2();
// h1->Scale( 1.0 / ( n1 * dx1 * dy1 ) );
// scale histo 2 to scale of 1
h2->Sumw2();
h2->Scale( ( double(n1) * dx1 * dy1 ) / ( double(n2) * dx2 * dy2 ) );
if (global) {
// fill data structure for fit (coordinates + values + errors)
std::cout << "Do global fit" << std::endl;
// fit now all the function together
// fill data structure for fit (coordinates + values + errors)
TAxis *xaxis1 = h1->GetXaxis();
TAxis *yaxis1 = h1->GetYaxis();
TAxis *xaxis2 = h2->GetXaxis();
TAxis *yaxis2 = h2->GetYaxis();
int nbinX1 = h1->GetNbinsX();
int nbinY1 = h1->GetNbinsY();
int nbinX2 = h2->GetNbinsX();
int nbinY2 = h2->GetNbinsY();
/// reset data structure
coords = std::vector<std::pair<double,double> >();
values = std::vector<double>();
errors = std::vector<double>();
for (int ix = 1; ix <= nbinX1; ++ix) {
for (int iy = 1; iy <= nbinY1; ++iy) {
if ( h1->GetBinContent(ix,iy) > 0 ) {
coords.push_back( std::make_pair(xaxis1->GetBinCenter(ix), yaxis1->GetBinCenter(iy) ) );
values.push_back( h1->GetBinContent(ix,iy) );
errors.push_back( h1->GetBinError(ix,iy) );
}
}
}
for (int ix = 1; ix <= nbinX2; ++ix) {
for (int iy = 1; iy <= nbinY2; ++iy) {
if ( h2->GetBinContent(ix,iy) > 0 ) {
coords.push_back( std::make_pair(xaxis2->GetBinCenter(ix), yaxis2->GetBinCenter(iy) ) );
values.push_back( h2->GetBinContent(ix,iy) );
errors.push_back( h2->GetBinError(ix,iy) );
}
}
}
TVirtualFitter::SetDefaultFitter("Minuit");
TVirtualFitter * minuit = TVirtualFitter::Fitter(0,10);
for (int i = 0; i < 10; ++i) {
minuit->SetParameter(i, func->GetParName(i), func->GetParameter(i), 0.01, 0,0);
}
minuit->SetFCN(myFcn);
double arglist[100];
arglist[0] = 0;
// set print level
minuit->ExecuteCommand("SET PRINT",arglist,2);
// minimize
arglist[0] = 5000; // number of function calls
arglist[1] = 0.01; // tolerance
minuit->ExecuteCommand("MIGRAD",arglist,2);
//get result
double minParams[10];
double parErrors[10];
for (int i = 0; i < 10; ++i) {
minParams[i] = minuit->GetParameter(i);
parErrors[i] = minuit->GetParError(i);
}
double chi2, edm, errdef;
int nvpar, nparx;
minuit->GetStats(chi2,edm,errdef,nvpar,nparx);
func->SetParameters(minParams);
func->SetParErrors(parErrors);
func->SetChisquare(chi2);
int ndf = coords.size()-nvpar;
func->SetNDF(ndf);
std::cout << "Chi2 Fit = " << chi2 << " ndf = " << ndf << " " << func->GetNDF() << std::endl;
// add to list of functions
h1->GetListOfFunctions()->Add(func);
h2->GetListOfFunctions()->Add(func);
}
else {
// fit independently
h1->Fit(func);
h2->Fit(func);
}
// Create a new canvas.
TCanvas * c1 = new TCanvas("c1","Two HIstogram Fit example",100,10,900,800);
c1->Divide(2,2);
gStyle->SetOptFit();
gStyle->SetStatY(0.6);
c1->cd(1);
h1->Draw();
func->SetRange(xlow1,ylow1,xup1,yup1);
func->DrawCopy("cont1 same");
c1->cd(2);
h1->Draw("lego");
func->DrawCopy("surf1 same");
c1->cd(3);
func->SetRange(xlow2,ylow2,xup2,yup2);
h2->Draw();
func->DrawCopy("cont1 same");
c1->cd(4);
h2->Draw("lego");
gPad->SetLogz();
func->Draw("surf1 same");
return 0;
}
<|endoftext|> |
<commit_before>#include "TimeManager.h"
#include "Logger.h"
#include "Helpers\Helpers.h"
namespace star
{
TimeManager::TimeManager()
#ifdef _WIN32
:mFrequency()
,mF1()
,mF2()
#else
:mF1(0)
,mF2(0)
,mElapsed(0)
#endif
,mDeltaMs(0)
,mDeltaS(0)
,mDeltauS(0)
,mTotalMS(0)
{
}
TimeManager::~TimeManager()
{
}
void TimeManager::StartMonitoring()
{
#ifdef _WIN32
QueryPerformanceCounter(&mF1);
#else
timespec lTimeVal;
clock_gettime(CLOCK_MONOTONIC, &lTimeVal);
mF1 = lTimeVal.tv_sec + (lTimeVal.tv_nsec*NSMULTIPLIER);
#endif
}
void TimeManager::StopMonitoring()
{
#ifdef _WIN32
QueryPerformanceCounter(&mF2);
QueryPerformanceFrequency(&mFrequency);
mDeltauS = (mF2.QuadPart - mF1.QuadPart) * MICROMULTIPLIER / mFrequency.QuadPart;
mDeltaMs = (mF2.QuadPart - mF1.QuadPart) * MILLIMULTIPLIER / mFrequency.QuadPart;
mDeltaS = (mF2.QuadPart - mF1.QuadPart) * SECONDMULTIPLIER / mFrequency.QuadPart;
#else
timespec lTimeVal;
clock_gettime(CLOCK_MONOTONIC, &lTimeVal);
mF2 = lTimeVal.tv_sec + (lTimeVal.tv_nsec * NSMULTIPLIER);
mDeltauS = (mF2 - mF1) * MICROMULTIPLIER;
mDeltaMs = (mF2 - mF1) * MILLIMULTIPLIER;
mDeltaS = (mF2 - mF1);
#endif
mTotalMS += mDeltaMs;
}
float64 TimeManager::GetSeconds() const
{
return mDeltaS;
}
float64 TimeManager::GetMilliSeconds() const
{
return mDeltaMs;
}
float64 TimeManager::GetMicroSeconds() const
{
return mDeltauS;
}
float64 TimeManager::GetMilliSecondsSinceStart() const
{
return mTotalMS;
}
tstring TimeManager::GetTimeStamp()
{
int32 totalSeconds = int32(mTotalMS / 1000);
int32 seconds = totalSeconds % 60;
int32 minutes = totalSeconds / 60;
int32 hours = totalSeconds / 3600;
tstringstream strstr;
if(hours < 10)
{
strstr << _T("0");
}
strstr << hours << _T(":");
if(minutes < 10)
{
strstr << _T("0");
}
strstr << minutes << _T(":");
if(seconds < 10)
{
strstr << _T("0");
}
strstr << seconds;
return strstr.str();
}
float64 TimeManager::GetSecondsSinceStart() const
{
return mTotalMS / MILLIMULTIPLIER;
}
}
<commit_msg>Performance boost in TimeManager<commit_after>#include "TimeManager.h"
#include "Logger.h"
#include "Helpers\Helpers.h"
namespace star
{
TimeManager::TimeManager()
#ifdef _WIN32
:mFrequency()
,mF1()
,mF2()
#else
:mF1(0)
,mF2(0)
,mElapsed(0)
#endif
,mDeltaMs(0)
,mDeltaS(0)
,mDeltauS(0)
,mTotalMS(0)
{
#ifdef _WIN32
if(!QueryPerformanceFrequency(&mFrequency))
{
LOG(LogLevel::Error,
_T("TimeManager::TimeManager: QueryPerformanceFrequency failed! ") +
tstring(_T("Please contact the developers to report this error.")));
}
#endif
}
TimeManager::~TimeManager()
{
}
void TimeManager::StartMonitoring()
{
#ifdef _WIN32
QueryPerformanceCounter(&mF1);
#else
timespec lTimeVal;
clock_gettime(CLOCK_MONOTONIC, &lTimeVal);
mF1 = lTimeVal.tv_sec + (lTimeVal.tv_nsec*NSMULTIPLIER);
#endif
}
void TimeManager::StopMonitoring()
{
#ifdef _WIN32
QueryPerformanceCounter(&mF2);
mDeltauS = (mF2.QuadPart - mF1.QuadPart) * MICROMULTIPLIER / mFrequency.QuadPart;
mDeltaMs = (mF2.QuadPart - mF1.QuadPart) * MILLIMULTIPLIER / mFrequency.QuadPart;
mDeltaS = (mF2.QuadPart - mF1.QuadPart) * SECONDMULTIPLIER / mFrequency.QuadPart;
#else
timespec lTimeVal;
clock_gettime(CLOCK_MONOTONIC, &lTimeVal);
mF2 = lTimeVal.tv_sec + (lTimeVal.tv_nsec * NSMULTIPLIER);
mDeltauS = (mF2 - mF1) * MICROMULTIPLIER;
mDeltaMs = (mF2 - mF1) * MILLIMULTIPLIER;
mDeltaS = (mF2 - mF1);
#endif
mTotalMS += mDeltaMs;
}
float64 TimeManager::GetSeconds() const
{
return mDeltaS;
}
float64 TimeManager::GetMilliSeconds() const
{
return mDeltaMs;
}
float64 TimeManager::GetMicroSeconds() const
{
return mDeltauS;
}
float64 TimeManager::GetMilliSecondsSinceStart() const
{
return mTotalMS;
}
tstring TimeManager::GetTimeStamp()
{
int32 totalSeconds = int32(mTotalMS / 1000);
int32 seconds = totalSeconds % 60;
int32 minutes = totalSeconds / 60;
int32 hours = totalSeconds / 3600;
tstringstream strstr;
if(hours < 10)
{
strstr << _T("0");
}
strstr << hours << _T(":");
if(minutes < 10)
{
strstr << _T("0");
}
strstr << minutes << _T(":");
if(seconds < 10)
{
strstr << _T("0");
}
strstr << seconds;
return strstr.str();
}
float64 TimeManager::GetSecondsSinceStart() const
{
return mTotalMS / MILLIMULTIPLIER;
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <cmath>
using namespace std;
double getNumberFromString(string& s) {
unsigned int i = 1;
double number;
while (i < s.size() && s[i] != ',') {
i++;
}
number = stod(s.substr(0,i));
s.erase(s.begin(), s.begin() + i);
if (s[0] == ',') {
s.erase(s.begin());
}
return number;
}
// type = 0 for linear
// type = 1 for max value
void normalize(vector<double>& attribute, vector<pair<double,double>>& minMax) {
double max = *max_element(attribute.begin(), attribute.end());
double min = *min_element(attribute.begin(), attribute.end());
minMax.push_back(pair<double,double>(min,max));
for (auto it = attribute.begin(); it < attribute.end(); it++) {
*it = ((*it) - min) / (max - min);
}
}
void normalizeTestCase(vector<double>& attribute, vector<pair<double,double>> minMax) {
for (unsigned int i = 0; i < attribute.size(); i++) {
double max = minMax[i].second;
double min = minMax[i].first;
attribute[i] = (attribute[i] - min) / (max - min);
}
}
int main(int argc, char **argv) {
string line;
ifstream dataset, testcases;
vector<vector<double>> database;
vector<pair<double,double>> minMax;
// Expects dataset name as argument
// Optional k as argument
if(argc <= 1){
cout << "Error: missing dataset name. Correct usage: "
<< endl << argv[0] << " dataset_name [k]"
<< endl << "Terminating..." << endl;
return 0;
}
// Default value for K
int K = 3;
// K specified
if(argc == 3){
stringstream ss;
ss << argv[2];
ss >> K;
}
string dataset_name = argv[1];
//READING INPUT FILE
dataset.open("datasets/" + dataset_name + "_training.csv");
while (getline(dataset, line)) {
double value;
vector<double> dLine;
while (line.size() != 0) {
value = getNumberFromString(line);
dLine.push_back(value);
}
database.push_back(dLine);
}
dataset.close();
//NORMALIZING THE DATABASE
for (unsigned int i = 0; i < database[0].size(); i++) {
vector<double> temp;
for (unsigned int j = 0; j < database.size(); j++) {
temp.push_back(database[j][i]);
}
normalize(temp, minMax);
for (unsigned int j = 0; j < database.size(); j++) {
database[j][i] = temp[j];
}
}
vector<int> correctYes(2, 0);
vector<int> correctNo(2, 0);
testcases.open("datasets/" + dataset_name + "_test.csv");
while (getline(testcases, line)) {
double value;
vector<double> dLine;
while (line.size() != 0) {
value = getNumberFromString(line);
dLine.push_back(value);
}
normalizeTestCase(dLine, minMax);
vector<double> distances(database.size(), 0);
for (unsigned int i = 0; i < database.size(); i++) {
for (unsigned int j = 0; j < database[i].size() - 1; j++) {
distances[i] += pow(dLine[j] - database[i][j], 2);
//cout << dLine[j] << " " << database[i][j] << endl;
}
distances[i] = sqrt(distances[i]);
//cout << "Distance to example " << i+1 << " is " << distances[i] << "." << endl;
}
vector<int> count(2, 0);
for (int i = 0; i < K; i++) {
int neighbor = -1;
double lowest = 100000.0;
for (unsigned int j = 0; j < distances.size(); j++) {
if (distances[j] < lowest) {
lowest = distances[j];
neighbor = j;
}
}
count[database[neighbor][database[neighbor].size()-1]]++;
distances[neighbor] = 1000000;
}
if (count[0] > count[1]) {
if (dLine[dLine.size()-1] == 0) {
correctNo[1]++;
}
else {
correctNo[0]++;
}
}
else {
if (dLine[dLine.size()-1] == 1) {
correctYes[1]++;
}
else {
correctYes[0]++;
}
}
}
testcases.close();
// Flag to get statistics only, without labels
// Useful to easily past results from a file to a sheet
#ifdef STATS_FLAG
cout << correctYes[0] + correctYes[1] << "\t"
<< correctNo[0] + correctYes[1] << endl
<< correctNo[0] + correctNo[1] << "\t"
<< correctNo[1] + correctYes[0] << endl
<< correctYes[1] << "\t"
<< correctNo[0] + correctYes[1] << endl
<< correctNo[1] << "\t"
<< correctNo[1] + correctYes[0] << endl;
#else
cout << "Dataset: " << dataset_name << endl;
cout << "K: " << K << endl;
cout << "----------------" << endl;
cout << "Number of No examples in test: " << correctNo[1] + correctYes[0] << "." << endl;
cout << "Number of Yes examples in test: " << correctNo[0] + correctYes[1] << "." << endl;
cout << "----------------" << endl;
cout << "Number of examples classified as No: " << correctNo[0] + correctNo[1] << "." << endl;
cout << "Number of examples correctly classified as No: " << correctNo[1] << "." << endl;
cout << "----------------" << endl;
cout << "Number of examples classified as Yes: " << correctYes[0] + correctYes[1] << "." << endl;
cout << "Number of examples correctly classified as Yes: " << correctYes[1] << "." << endl;
cout << "----------------" << endl;
cout << "Total Precision: " << 100.0 * (correctNo[1] + correctYes[1]) / (correctNo[1] + correctYes[0] + correctNo[0] + correctYes[1]) << " percent" << endl;
cout << "Yes Precision: " << 100.0 * (correctYes[1]) / (correctYes[0] + correctYes[1]) << " percent" << endl;
cout << "No Precision: " << 100.0 * (correctNo[1]) / (correctNo[1] + correctNo[0]) << " percent" << endl;
#endif
return 0;
}<commit_msg>Trick to make sure K is odd. We hate draws.<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <cmath>
using namespace std;
double getNumberFromString(string& s) {
unsigned int i = 1;
double number;
while (i < s.size() && s[i] != ',') {
i++;
}
number = stod(s.substr(0,i));
s.erase(s.begin(), s.begin() + i);
if (s[0] == ',') {
s.erase(s.begin());
}
return number;
}
// type = 0 for linear
// type = 1 for max value
void normalize(vector<double>& attribute, vector<pair<double,double>>& minMax) {
double max = *max_element(attribute.begin(), attribute.end());
double min = *min_element(attribute.begin(), attribute.end());
minMax.push_back(pair<double,double>(min,max));
for (auto it = attribute.begin(); it < attribute.end(); it++) {
*it = ((*it) - min) / (max - min);
}
}
void normalizeTestCase(vector<double>& attribute, vector<pair<double,double>> minMax) {
for (unsigned int i = 0; i < attribute.size(); i++) {
double max = minMax[i].second;
double min = minMax[i].first;
attribute[i] = (attribute[i] - min) / (max - min);
}
}
int main(int argc, char **argv) {
string line;
ifstream dataset, testcases;
vector<vector<double>> database;
vector<pair<double,double>> minMax;
// Expects dataset name as argument
// Optional odd k as argument
if(argc <= 1){
cout << "Error: missing dataset name. Correct usage: "
<< endl << argv[0] << " dataset_name [k (odd)]"
<< endl << "Terminating..." << endl;
return 0;
}
// Default value for K
int K = 3;
// K specified
if(argc == 3){
stringstream ss;
ss << argv[2];
ss >> K;
// Trick to enforce K odd and guarantee there will be no draws
if(K%2 == 0){
K++;
}
}
string dataset_name = argv[1];
//READING INPUT FILE
dataset.open("datasets/" + dataset_name + "_training.csv");
while (getline(dataset, line)) {
double value;
vector<double> dLine;
while (line.size() != 0) {
value = getNumberFromString(line);
dLine.push_back(value);
}
database.push_back(dLine);
}
dataset.close();
//NORMALIZING THE DATABASE
for (unsigned int i = 0; i < database[0].size(); i++) {
vector<double> temp;
for (unsigned int j = 0; j < database.size(); j++) {
temp.push_back(database[j][i]);
}
normalize(temp, minMax);
for (unsigned int j = 0; j < database.size(); j++) {
database[j][i] = temp[j];
}
}
vector<int> correctYes(2, 0);
vector<int> correctNo(2, 0);
testcases.open("datasets/" + dataset_name + "_test.csv");
while (getline(testcases, line)) {
double value;
vector<double> dLine;
while (line.size() != 0) {
value = getNumberFromString(line);
dLine.push_back(value);
}
normalizeTestCase(dLine, minMax);
vector<double> distances(database.size(), 0);
for (unsigned int i = 0; i < database.size(); i++) {
for (unsigned int j = 0; j < database[i].size() - 1; j++) {
distances[i] += pow(dLine[j] - database[i][j], 2);
//cout << dLine[j] << " " << database[i][j] << endl;
}
distances[i] = sqrt(distances[i]);
//cout << "Distance to example " << i+1 << " is " << distances[i] << "." << endl;
}
vector<int> count(2, 0);
for (int i = 0; i < K; i++) {
int neighbor = -1;
double lowest = 100000.0;
for (unsigned int j = 0; j < distances.size(); j++) {
if (distances[j] < lowest) {
lowest = distances[j];
neighbor = j;
}
}
count[database[neighbor][database[neighbor].size()-1]]++;
distances[neighbor] = 1000000;
}
if (count[0] > count[1]) {
if (dLine[dLine.size()-1] == 0) {
correctNo[1]++;
}
else {
correctNo[0]++;
}
}
else {
if (dLine[dLine.size()-1] == 1) {
correctYes[1]++;
}
else {
correctYes[0]++;
}
}
}
testcases.close();
// Flag to get statistics only, without labels
// Useful to easily past results from a file to a sheet
#ifdef STATS_FLAG
cout << correctYes[0] + correctYes[1] << "\t"
<< correctNo[0] + correctYes[1] << endl
<< correctNo[0] + correctNo[1] << "\t"
<< correctNo[1] + correctYes[0] << endl
<< correctYes[1] << "\t"
<< correctNo[0] + correctYes[1] << endl
<< correctNo[1] << "\t"
<< correctNo[1] + correctYes[0] << endl;
#else
cout << "Dataset: " << dataset_name << endl;
cout << "K: " << K << endl;
cout << "----------------" << endl;
cout << "Number of No examples in test: " << correctNo[1] + correctYes[0] << "." << endl;
cout << "Number of Yes examples in test: " << correctNo[0] + correctYes[1] << "." << endl;
cout << "----------------" << endl;
cout << "Number of examples classified as No: " << correctNo[0] + correctNo[1] << "." << endl;
cout << "Number of examples correctly classified as No: " << correctNo[1] << "." << endl;
cout << "----------------" << endl;
cout << "Number of examples classified as Yes: " << correctYes[0] + correctYes[1] << "." << endl;
cout << "Number of examples correctly classified as Yes: " << correctYes[1] << "." << endl;
cout << "----------------" << endl;
cout << "Total Precision: " << 100.0 * (correctNo[1] + correctYes[1]) / (correctNo[1] + correctYes[0] + correctNo[0] + correctYes[1]) << " percent" << endl;
cout << "Yes Precision: " << 100.0 * (correctYes[1]) / (correctYes[0] + correctYes[1]) << " percent" << endl;
cout << "No Precision: " << 100.0 * (correctNo[1]) / (correctNo[1] + correctNo[0]) << " percent" << endl;
#endif
return 0;
}<|endoftext|> |
<commit_before>//
// ZX80O.cpp
// Clock Signal
//
// Created by Thomas Harte on 04/06/2017.
// Copyright © 2017 Thomas Harte. All rights reserved.
//
#include "ZX80O.hpp"
using namespace Storage::Tape;
ZX80O::ZX80O(const char *file_name) :
Storage::FileHolder(file_name) {
// Files can be no longer than 16 kb
if(file_stats_.st_size > 16384) throw ErrorNotZX80O;
// skip the system area
fseek(file_, 8, SEEK_SET);
// read the pointer to VARS and the alleged pointer to end of file
uint16_t vars = fgetc16le();
end_of_file_ = fgetc16le();
// VARs should be before end of file
if(vars > end_of_file_) throw ErrorNotZX80O;
// end of file should be no further than the actual file size
if(end_of_file_ - 0x4000 > file_stats_.st_size) throw ErrorNotZX80O;
// TODO: does it make sense to inspect the tokenised BASIC?
// It starts at 0x4028 and proceeds as [16-bit line number] [tokens] [0x76],
// but I'm as yet unable to find documentation of the tokens.
// then rewind and start again
virtual_reset();
}
void ZX80O::virtual_reset() {
fseek(file_, 0, SEEK_SET);
is_past_silence_ = false;
is_high_ = true;
bit_pointer_ = 9;
}
bool ZX80O::is_at_end() {
return ftell(file_) == end_of_file_ - 0x4000;
}
Tape::Pulse ZX80O::virtual_get_next_pulse() {
Tape::Pulse pulse;
// Start with 1 second of silence.
if(!is_past_silence_ || is_at_end()) {
pulse.type = Pulse::Type::Zero;
pulse.length.length = 5;
pulse.length.clock_rate = 1;
is_past_silence_ = true;
return pulse;
}
// For each byte, output 8 bits and then silence.
if(bit_pointer_ == 9) {
byte_ = (uint8_t)fgetc(file_);
bit_pointer_ = 0;
wave_pointer_ = 0;
}
// Bytes are stored MSB first.
if(bit_pointer_ < 8) {
// waves are of length 150µs
pulse.length.length = 3;
pulse.length.clock_rate = 20000;
if(is_high_) {
pulse.type = Pulse::Type::High;
is_high_ = false;
} else {
pulse.type = Pulse::Type::Low;
is_high_ = true;
int wave_count = (byte_ & (0x80 >> bit_pointer_)) ? 9 : 4;
wave_pointer_++;
if(wave_pointer_ == wave_count) {
bit_pointer_++;
wave_pointer_ = 0;
}
}
} else {
// post-waves silence is 1300µs
pulse.length.length = 13;
pulse.length.clock_rate = 10000;
pulse.type = Pulse::Type::Zero;
bit_pointer_++;
}
return pulse;
}
<commit_msg>Caveman debugging in place, it looks like this file is returning nonsense.<commit_after>//
// ZX80O.cpp
// Clock Signal
//
// Created by Thomas Harte on 04/06/2017.
// Copyright © 2017 Thomas Harte. All rights reserved.
//
#include "ZX80O.hpp"
using namespace Storage::Tape;
ZX80O::ZX80O(const char *file_name) :
Storage::FileHolder(file_name) {
// Files can be no longer than 16 kb
if(file_stats_.st_size > 16384) throw ErrorNotZX80O;
// skip the system area
fseek(file_, 8, SEEK_SET);
// read the pointer to VARS and the alleged pointer to end of file
uint16_t vars = fgetc16le();
end_of_file_ = fgetc16le();
// VARs should be before end of file
if(vars > end_of_file_) throw ErrorNotZX80O;
// end of file should be no further than the actual file size
if(end_of_file_ - 0x4000 > file_stats_.st_size) throw ErrorNotZX80O;
// TODO: does it make sense to inspect the tokenised BASIC?
// It starts at 0x4028 and proceeds as [16-bit line number] [tokens] [0x76],
// but I'm as yet unable to find documentation of the tokens.
// then rewind and start again
virtual_reset();
}
void ZX80O::virtual_reset() {
fseek(file_, 0, SEEK_SET);
is_past_silence_ = false;
is_high_ = true;
bit_pointer_ = 9;
}
bool ZX80O::is_at_end() {
return ftell(file_) == end_of_file_ - 0x4000;
}
Tape::Pulse ZX80O::virtual_get_next_pulse() {
Tape::Pulse pulse;
// Start with 1 second of silence.
if(!is_past_silence_ || is_at_end()) {
pulse.type = Pulse::Type::Zero;
pulse.length.length = 5;
pulse.length.clock_rate = 1;
is_past_silence_ = true;
return pulse;
}
// For each byte, output 8 bits and then silence.
if(bit_pointer_ == 9) {
byte_ = (uint8_t)fgetc(file_);
bit_pointer_ = 0;
wave_pointer_ = 0;
}
// Bytes are stored MSB first.
if(bit_pointer_ < 8) {
// waves are of length 150µs
pulse.length.length = 3;
pulse.length.clock_rate = 20000;
if(is_high_) {
pulse.type = Pulse::Type::High;
is_high_ = false;
printf("-");
} else {
pulse.type = Pulse::Type::Low;
is_high_ = true;
printf("_");
int wave_count = (byte_ & (0x80 >> bit_pointer_)) ? 9 : 4;
wave_pointer_++;
if(wave_pointer_ == wave_count) {
bit_pointer_++;
wave_pointer_ = 0;
}
}
} else {
// post-waves silence is 1300µs
pulse.length.length = 13;
pulse.length.clock_rate = 10000;
pulse.type = Pulse::Type::Zero;
bit_pointer_++;
printf("\n");
}
return pulse;
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2005-2007, Thorvald Natvig <[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 the Mumble Developers 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 FOUNDATION 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 "Message.h"
#include "Connection.h"
#include "PacketDataStream.h"
#ifdef Q_OS_UNIX
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#endif
#ifdef Q_OS_WIN
#include <winsock2.h>
#endif
Connection::Connection(QObject *p, QTcpSocket *qtsSock) : QObject(p) {
qtsSocket = qtsSock;
qtsSocket->setParent(this);
iPacketLength = -1;
bDisconnectedEmitted = false;
connect(qtsSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
connect(qtsSocket, SIGNAL(readyRead()), this, SLOT(socketRead()));
connect(qtsSocket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
qtLastPacket.restart();
}
Connection::~Connection() {
}
int Connection::activityTime() const {
return qtLastPacket.elapsed();
}
void Connection::socketRead() {
int iAvailable;
while (1) {
iAvailable = qtsSocket->bytesAvailable();
if (iPacketLength == -1) {
if (iAvailable < 3)
return;
unsigned char a_ucBuffer[3];
qtsSocket->read(reinterpret_cast<char *>(a_ucBuffer), 3);
iPacketLength = ((a_ucBuffer[0] << 16) & 0xff0000) + ((a_ucBuffer[1] << 8) & 0xff00) + a_ucBuffer[2];
iAvailable -= 3;
}
if ((iPacketLength != -1) && (iAvailable >= iPacketLength)) {
QByteArray qbaBuffer = qtsSocket->read(iPacketLength);
emit message(qbaBuffer);
iPacketLength = -1;
qtLastPacket.restart();
} else {
return;
}
}
}
void Connection::socketError(QAbstractSocket::SocketError) {
if (! bDisconnectedEmitted) {
bDisconnectedEmitted = true;
emit connectionClosed(qtsSocket->errorString());
}
qtsSocket->disconnectFromHost();
}
void Connection::socketDisconnected() {
if (! bDisconnectedEmitted) {
bDisconnectedEmitted = true;
emit connectionClosed(QString());
}
}
void Connection::sendMessage(const Message *mMsg) {
QByteArray qbaBuffer;
mMsg->messageToNetwork(qbaBuffer);
sendMessage(qbaBuffer);
}
void Connection::sendMessage(const QByteArray &qbaMsg) {
unsigned char a_ucBuffer[3];
if (qtsSocket->state() != QAbstractSocket::ConnectedState)
return;
if (qbaMsg.size() > 0xffff) {
qFatal("Connection: Oversized message (%d bytes)", qbaMsg.size());
}
a_ucBuffer[0]=(qbaMsg.size() >> 16) & 0xff;
a_ucBuffer[0]=(qbaMsg.size() >> 8) & 0xff;
a_ucBuffer[1]=(qbaMsg.size() & 0xff);
qtsSocket->write(reinterpret_cast<const char *>(a_ucBuffer), 3);
qtsSocket->write(qbaMsg);
}
void Connection::forceFlush() {
if (qtsSocket->state() != QAbstractSocket::ConnectedState)
return;
int nodelay;
qtsSocket->flush();
nodelay = 1;
setsockopt(qtsSocket->socketDescriptor(), IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char *>(&nodelay), sizeof(nodelay));
nodelay = 0;
setsockopt(qtsSocket->socketDescriptor(), IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char *>(&nodelay), sizeof(nodelay));
}
void Connection::disconnect() {
qtsSocket->disconnectFromHost();
}
QHostAddress Connection::peerAddress() const {
return qtsSocket->peerAddress();
}
quint16 Connection::peerPort() const {
return qtsSocket->peerPort();
}
<commit_msg>Fixup of Connection<commit_after>/* Copyright (C) 2005-2007, Thorvald Natvig <[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 the Mumble Developers 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 FOUNDATION 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 "Message.h"
#include "Connection.h"
#include "PacketDataStream.h"
#ifdef Q_OS_UNIX
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#endif
#ifdef Q_OS_WIN
#include <winsock2.h>
#endif
Connection::Connection(QObject *p, QTcpSocket *qtsSock) : QObject(p) {
qtsSocket = qtsSock;
qtsSocket->setParent(this);
iPacketLength = -1;
bDisconnectedEmitted = false;
connect(qtsSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
connect(qtsSocket, SIGNAL(readyRead()), this, SLOT(socketRead()));
connect(qtsSocket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
qtLastPacket.restart();
}
Connection::~Connection() {
}
int Connection::activityTime() const {
return qtLastPacket.elapsed();
}
void Connection::socketRead() {
int iAvailable;
while (1) {
iAvailable = qtsSocket->bytesAvailable();
if (iPacketLength == -1) {
if (iAvailable < 3)
return;
unsigned char a_ucBuffer[3];
qtsSocket->read(reinterpret_cast<char *>(a_ucBuffer), 3);
iPacketLength = ((a_ucBuffer[0] << 16) & 0xff0000) + ((a_ucBuffer[1] << 8) & 0xff00) + a_ucBuffer[2];
iAvailable -= 3;
}
if ((iPacketLength != -1) && (iAvailable >= iPacketLength)) {
QByteArray qbaBuffer = qtsSocket->read(iPacketLength);
emit message(qbaBuffer);
iPacketLength = -1;
qtLastPacket.restart();
} else {
return;
}
}
}
void Connection::socketError(QAbstractSocket::SocketError) {
if (! bDisconnectedEmitted) {
bDisconnectedEmitted = true;
emit connectionClosed(qtsSocket->errorString());
}
qtsSocket->disconnectFromHost();
}
void Connection::socketDisconnected() {
if (! bDisconnectedEmitted) {
bDisconnectedEmitted = true;
emit connectionClosed(QString());
}
}
void Connection::sendMessage(const Message *mMsg) {
QByteArray qbaBuffer;
mMsg->messageToNetwork(qbaBuffer);
sendMessage(qbaBuffer);
}
void Connection::sendMessage(const QByteArray &qbaMsg) {
unsigned char a_ucBuffer[3];
if (qtsSocket->state() != QAbstractSocket::ConnectedState)
return;
if (qbaMsg.size() > 0xffff) {
qFatal("Connection: Oversized message (%d bytes)", qbaMsg.size());
}
a_ucBuffer[0]=(qbaMsg.size() >> 16) & 0xff;
a_ucBuffer[1]=(qbaMsg.size() >> 8) & 0xff;
a_ucBuffer[2]=(qbaMsg.size() & 0xff);
qtsSocket->write(reinterpret_cast<const char *>(a_ucBuffer), 3);
qtsSocket->write(qbaMsg);
}
void Connection::forceFlush() {
if (qtsSocket->state() != QAbstractSocket::ConnectedState)
return;
int nodelay;
qtsSocket->flush();
nodelay = 1;
setsockopt(qtsSocket->socketDescriptor(), IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char *>(&nodelay), sizeof(nodelay));
nodelay = 0;
setsockopt(qtsSocket->socketDescriptor(), IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char *>(&nodelay), sizeof(nodelay));
}
void Connection::disconnect() {
qtsSocket->disconnectFromHost();
}
QHostAddress Connection::peerAddress() const {
return qtsSocket->peerAddress();
}
quint16 Connection::peerPort() const {
return qtsSocket->peerPort();
}
<|endoftext|> |
<commit_before>#include <nan.h>
#include <iostream>
#include <string>
#include <sstream>
#include <map>
#include <stdlib.h>
#include <stdio.h>
#include <poppler/qt4/poppler-form.h>
#include <poppler/qt4/poppler-qt4.h>
#include <cairo/cairo.h>
#include <cairo/cairo-pdf.h>
#include <QtCore/QBuffer>
#include <QtCore/QFile>
#include <QtGui/QImage>
#include "NodePoppler.h" // NOLINT(build/include)
using namespace std;
using v8::Number;
using v8::String;
using v8::Local;
using v8::Object;
using v8::Array;
using v8::Value;
using v8::Boolean;
inline bool fileExists (const std::string& name) {
if (FILE *file = fopen(name.c_str(), "r")) {
fclose(file);
return true;
} else {
return false;
}
}
// Cairo write and read functions (to QBuffer)
static cairo_status_t readPngFromBuffer(void *closure, unsigned char *data, unsigned int length) {
QBuffer *myBuffer = (QBuffer *)closure;
size_t bytes_read;
bytes_read = myBuffer->read((char *)data, length);
if (bytes_read != length)
return CAIRO_STATUS_READ_ERROR;
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t writePngToBuffer(void *closure, const unsigned char *data, unsigned int length) {
QBuffer *myBuffer = (QBuffer *)closure;
size_t bytes_wrote;
bytes_wrote = myBuffer->write((char *)data, length);
if (bytes_wrote != length)
return CAIRO_STATUS_READ_ERROR;
return CAIRO_STATUS_SUCCESS;
}
void createPdf(QBuffer *buffer, Poppler::Document *document) {
ostringstream ss;
Poppler::PDFConverter *converter = document->pdfConverter();
converter->setPDFOptions(converter->pdfOptions() | Poppler::PDFConverter::WithChanges);
converter->setOutputDevice(buffer);
if (!converter->convert()) {
// enum Error
// {
// NoError,
// FileLockedError,
// OpenOutputError,
// NotSupportedInputFileError
// };
ss << "Error occurred when converting PDF: " << converter->lastError();
throw ss.str();
}
}
void createImgPdf(QBuffer *buffer, Poppler::Document *document) {
// Initialize Cairo writing surface, and since we have images at 360 DPI, we'll set scaling. Width and Height are set for A4 dimensions.
cairo_surface_t *surface = cairo_pdf_surface_create_for_stream(writePngToBuffer, buffer, 595.00, 842.00);
cairo_t *cr = cairo_create(surface);
cairo_scale(cr, 0.2, 0.2);
int n = document->numPages();
for (int i = 0; i < n; i += 1) {
Poppler::Page *page = document->page(i);
// Save the page as PNG image to buffer. (We could use QFile if we want to save images to files)
QBuffer *pageImage = new QBuffer();
pageImage->open(QIODevice::ReadWrite);
QImage img = page->renderToImage(360, 360);
img.save(pageImage, "png");
pageImage->seek(0); // Reading does not work if we don't reset the pointer
// Ookay, let's try to make new page out of the image
cairo_surface_t *drawImageSurface = cairo_image_surface_create_from_png_stream(readPngFromBuffer, pageImage);
cairo_set_source_surface(cr, drawImageSurface, 0, 0);
cairo_paint(cr);
// Create new page if multipage document
if (n > 0) {
cairo_surface_show_page(surface);
cr = cairo_create(surface);
cairo_scale(cr, 0.2, 0.2);
}
pageImage->close();
}
// Close Cairo
cairo_destroy(cr);
cairo_surface_finish(surface);
cairo_surface_destroy (surface);
}
WriteFieldsParams v8ParamsToCpp(const Nan::FunctionCallbackInfo<v8::Value>& args) {
Local<Object> parameters;
string saveFormat = "imgpdf";
map<string, string> fields;
String::Utf8Value sourcePdfFileNameParam(args[0]->ToString());
string sourcePdfFileName = string(*sourcePdfFileNameParam);
Local<Object> changeFields = args[1]->ToObject();
Local<String> saveStr = Nan::New("save").ToLocalChecked();
// Check if any configuration parameters
if (args.Length() > 2) {
parameters = args[2]->ToObject();
Local<Value> saveParam = Nan::Get(parameters, saveStr).ToLocalChecked();
if (!saveParam->IsUndefined()) {
String::Utf8Value saveFormatParam(Nan::Get(parameters, saveStr).ToLocalChecked());
saveFormat = string(*saveFormatParam);
}
}
// Convert form fields to c++ map
Local<Array> fieldArray = changeFields->GetPropertyNames();
for (uint32_t i = 0; i < fieldArray->Length(); i += 1) {
Local<Value> name = fieldArray->Get(i);
Local<Value> value = changeFields->Get(name);
fields[std::string(*String::Utf8Value(name))] = std::string(*String::Utf8Value(value));
}
// Create and return PDF
struct WriteFieldsParams params(sourcePdfFileName, saveFormat, fields);
return params;
}
// Pdf creator that is not dependent on V8 internals (safe at async?)
QBuffer *writePdfFields(struct WriteFieldsParams params) {
ostringstream ss;
// If source file does not exist, throw error and return false
if (!fileExists(params.sourcePdfFileName)) {
ss << "File \"" << params.sourcePdfFileName << "\" does not exist";
throw ss.str();
}
// Open document and return false and throw error if something goes wrong
Poppler::Document *document = Poppler::Document::load(QString::fromStdString(params.sourcePdfFileName));
if (document == NULL) {
ss << "Error occurred when reading \"" << params.sourcePdfFileName << "\"";
throw ss.str();
}
// Fill form
int n = document->numPages();
stringstream idSS;
for (int i = 0; i < n; i += 1) {
Poppler::Page *page = document->page(i);
foreach (Poppler::FormField *field, page->formFields()) {
string fieldName = field->fullyQualifiedName().toStdString();
// Support writing fields by both fieldName and id.
// If fieldName is not present in params, try id.
if (params.fields.count(fieldName) == 0) {
idSS << field->id();
fieldName = idSS.str();
idSS.str("");
idSS.clear();
}
if (!field->isReadOnly() && field->isVisible() && params.fields.count(fieldName) ) {
// Text
if (field->type() == Poppler::FormField::FormText) {
Poppler::FormFieldText *textField = (Poppler::FormFieldText *) field;
textField->setText(QString::fromUtf8(params.fields[fieldName].c_str()));
}
// Choice
if (field->type() == Poppler::FormField::FormChoice) {
Poppler::FormFieldChoice *choiceField = (Poppler::FormFieldChoice *) field;
if (choiceField->isEditable()) {
choiceField->setEditChoice(QString::fromUtf8(params.fields[fieldName].c_str()));
}
else {
QStringList possibleChoices = choiceField->choices();
QString proposedChoice = QString::fromUtf8(params.fields[fieldName].c_str());
int index = possibleChoices.indexOf(proposedChoice);
if (index >= 0) {
QList<int> choiceList;
choiceList << index;
choiceField->setCurrentChoices(choiceList);
}
}
}
// Button
// ! TODO ! Note. Poppler doesn't support checkboxes with hashtag names (aka using exportValue).
if (field->type() == Poppler::FormField::FormButton) {
Poppler::FormFieldButton *buttonField = (Poppler::FormFieldButton *) field;
if (params.fields[fieldName].compare("true") == 0) {
buttonField->setState(true);
}
else {
buttonField->setState(false);
}
}
}
}
}
// Now save and return the document
QBuffer *bufferDevice = new QBuffer();
bufferDevice->open(QIODevice::ReadWrite);
// Get save parameters
if (params.saveFormat == "imgpdf") {
createImgPdf(bufferDevice, document);
}
else {
createPdf(bufferDevice, document);
}
return bufferDevice;
}
//***********************************
//
// Node.js methods
//
//***********************************
// Read PDF form fields
NAN_METHOD(ReadSync) {
// expect a number as the first argument
Nan::Utf8String *fileName = new Nan::Utf8String(info[0]);
ostringstream ss;
int n = 0;
// If file does not exist, throw error and return false
if (!fileExists(**fileName)) {
ss << "File \"" << **fileName << "\" does not exist";
Nan::ThrowError(Nan::New<String>(ss.str()).ToLocalChecked());
info.GetReturnValue().Set(Nan::False());
}
// Open document and return false and throw error if something goes wrong
Poppler::Document *document = Poppler::Document::load(**fileName);
if (document != NULL) {
// Get field list
n = document->numPages();
} else {
ss << "Error occurred when reading \"" << **fileName << "\"";
Nan::ThrowError(Nan::New<String>(ss.str()).ToLocalChecked());
info.GetReturnValue().Set(Nan::False());
}
// Store field value objects to v8 array
Local<Array> fieldArray = Nan::New<Array>();
int fieldNum = 0;
for (int i = 0; i < n; i += 1) {
Poppler::Page *page = document->page(i);
foreach (Poppler::FormField *field, page->formFields()) {
if (!field->isReadOnly() && field->isVisible()) {
// Make JavaScript object out of the fieldnames
Local<Object> obj = Nan::New<Object>();
Nan::Set(obj, Nan::New<String>("name").ToLocalChecked(), Nan::New<String>(field->fullyQualifiedName().toStdString()).ToLocalChecked());
Nan::Set(obj, Nan::New<String>("page").ToLocalChecked(), Nan::New<Number>(i));
// ! TODO ! Note. Poppler doesn't support checkboxes with hashtag names (aka using exportValue).
string fieldType;
// Set default value undefined
Nan::Set(obj, Nan::New<String>("value").ToLocalChecked(), Nan::Undefined());
Poppler::FormFieldButton *myButton;
Poppler::FormFieldChoice *myChoice;
Nan::Set(obj, Nan::New<String>("id").ToLocalChecked(), Nan::New<Number>(field->id()));
switch (field->type()) {
// FormButton
case Poppler::FormField::FormButton:
myButton = (Poppler::FormFieldButton *)field;
switch (myButton->buttonType()) {
// Push
case Poppler::FormFieldButton::Push: fieldType = "push_button"; break;
case Poppler::FormFieldButton::CheckBox:
fieldType = "checkbox";
Nan::Set(obj, Nan::New<String>("value").ToLocalChecked(), Nan::New<Boolean>(myButton->state()));
break;
case Poppler::FormFieldButton::Radio: fieldType = "radio"; break;
}
break;
// FormText
case Poppler::FormField::FormText:
Nan::Set(obj, Nan::New<String>("value").ToLocalChecked(), Nan::New<String>(((Poppler::FormFieldText *)field)->text().toStdString()).ToLocalChecked());
fieldType = "text";
break;
// FormChoice
case Poppler::FormField::FormChoice: {
Local<Array> choiceArray = Nan::New<Array>();
myChoice = (Poppler::FormFieldChoice *)field;
QStringList possibleChoices = myChoice->choices();
for (int i = 0; i < possibleChoices.size(); i++) {
Nan::Set(choiceArray, i, Nan::New<String>(possibleChoices.at(i).toStdString()).ToLocalChecked());
}
Nan::Set(obj, Nan::New<String>("choices").ToLocalChecked(), choiceArray);
switch (myChoice->choiceType()) {
case Poppler::FormFieldChoice::ComboBox: fieldType = "combobox"; break;
case Poppler::FormFieldChoice::ListBox: fieldType = "listbox"; break;
}
break;
}
// FormSignature
case Poppler::FormField::FormSignature: fieldType = "formsignature"; break;
default:
fieldType = "undefined";
break;
}
Nan::Set(obj, Nan::New<String>("type").ToLocalChecked(), Nan::New<String>(fieldType.c_str()).ToLocalChecked());
fieldArray->Set(fieldNum, obj);
fieldNum++;
}
}
}
info.GetReturnValue().Set(fieldArray);
}
// Write PDF form fields
NAN_METHOD(WriteSync) {
// Check and return parameters given at JavaScript function call
WriteFieldsParams params = v8ParamsToCpp(info);
// Create and return pdf
try
{
QBuffer *buffer = writePdfFields(params);
Local<Object> returnPdf = Nan::CopyBuffer((char *)buffer->data().data(), buffer->size()).ToLocalChecked();
buffer->close();
delete buffer;
info.GetReturnValue().Set(returnPdf);
}
catch (string error)
{
Nan::ThrowError(Nan::New<String>(error).ToLocalChecked());
info.GetReturnValue().Set(Nan::Null());
}
}
<commit_msg>Include qt5<commit_after>#include <nan.h>
#include <iostream>
#include <string>
#include <sstream>
#include <map>
#include <stdlib.h>
#include <stdio.h>
#include <poppler/qt5/poppler-form.h>
#include <poppler/qt5/poppler-qt5.h>
#include <cairo/cairo.h>
#include <cairo/cairo-pdf.h>
#include <QtCore/QBuffer>
#include <QtCore/QFile>
#include <QtGui/QImage>
#include "NodePoppler.h" // NOLINT(build/include)
using namespace std;
using v8::Number;
using v8::String;
using v8::Local;
using v8::Object;
using v8::Array;
using v8::Value;
using v8::Boolean;
inline bool fileExists (const std::string& name) {
if (FILE *file = fopen(name.c_str(), "r")) {
fclose(file);
return true;
} else {
return false;
}
}
// Cairo write and read functions (to QBuffer)
static cairo_status_t readPngFromBuffer(void *closure, unsigned char *data, unsigned int length) {
QBuffer *myBuffer = (QBuffer *)closure;
size_t bytes_read;
bytes_read = myBuffer->read((char *)data, length);
if (bytes_read != length)
return CAIRO_STATUS_READ_ERROR;
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t writePngToBuffer(void *closure, const unsigned char *data, unsigned int length) {
QBuffer *myBuffer = (QBuffer *)closure;
size_t bytes_wrote;
bytes_wrote = myBuffer->write((char *)data, length);
if (bytes_wrote != length)
return CAIRO_STATUS_READ_ERROR;
return CAIRO_STATUS_SUCCESS;
}
void createPdf(QBuffer *buffer, Poppler::Document *document) {
ostringstream ss;
Poppler::PDFConverter *converter = document->pdfConverter();
converter->setPDFOptions(converter->pdfOptions() | Poppler::PDFConverter::WithChanges);
converter->setOutputDevice(buffer);
if (!converter->convert()) {
// enum Error
// {
// NoError,
// FileLockedError,
// OpenOutputError,
// NotSupportedInputFileError
// };
ss << "Error occurred when converting PDF: " << converter->lastError();
throw ss.str();
}
}
void createImgPdf(QBuffer *buffer, Poppler::Document *document) {
// Initialize Cairo writing surface, and since we have images at 360 DPI, we'll set scaling. Width and Height are set for A4 dimensions.
cairo_surface_t *surface = cairo_pdf_surface_create_for_stream(writePngToBuffer, buffer, 595.00, 842.00);
cairo_t *cr = cairo_create(surface);
cairo_scale(cr, 0.2, 0.2);
int n = document->numPages();
for (int i = 0; i < n; i += 1) {
Poppler::Page *page = document->page(i);
// Save the page as PNG image to buffer. (We could use QFile if we want to save images to files)
QBuffer *pageImage = new QBuffer();
pageImage->open(QIODevice::ReadWrite);
QImage img = page->renderToImage(360, 360);
img.save(pageImage, "png");
pageImage->seek(0); // Reading does not work if we don't reset the pointer
// Ookay, let's try to make new page out of the image
cairo_surface_t *drawImageSurface = cairo_image_surface_create_from_png_stream(readPngFromBuffer, pageImage);
cairo_set_source_surface(cr, drawImageSurface, 0, 0);
cairo_paint(cr);
// Create new page if multipage document
if (n > 0) {
cairo_surface_show_page(surface);
cr = cairo_create(surface);
cairo_scale(cr, 0.2, 0.2);
}
pageImage->close();
}
// Close Cairo
cairo_destroy(cr);
cairo_surface_finish(surface);
cairo_surface_destroy (surface);
}
WriteFieldsParams v8ParamsToCpp(const Nan::FunctionCallbackInfo<v8::Value>& args) {
Local<Object> parameters;
string saveFormat = "imgpdf";
map<string, string> fields;
String::Utf8Value sourcePdfFileNameParam(args[0]->ToString());
string sourcePdfFileName = string(*sourcePdfFileNameParam);
Local<Object> changeFields = args[1]->ToObject();
Local<String> saveStr = Nan::New("save").ToLocalChecked();
// Check if any configuration parameters
if (args.Length() > 2) {
parameters = args[2]->ToObject();
Local<Value> saveParam = Nan::Get(parameters, saveStr).ToLocalChecked();
if (!saveParam->IsUndefined()) {
String::Utf8Value saveFormatParam(Nan::Get(parameters, saveStr).ToLocalChecked());
saveFormat = string(*saveFormatParam);
}
}
// Convert form fields to c++ map
Local<Array> fieldArray = changeFields->GetPropertyNames();
for (uint32_t i = 0; i < fieldArray->Length(); i += 1) {
Local<Value> name = fieldArray->Get(i);
Local<Value> value = changeFields->Get(name);
fields[std::string(*String::Utf8Value(name))] = std::string(*String::Utf8Value(value));
}
// Create and return PDF
struct WriteFieldsParams params(sourcePdfFileName, saveFormat, fields);
return params;
}
// Pdf creator that is not dependent on V8 internals (safe at async?)
QBuffer *writePdfFields(struct WriteFieldsParams params) {
ostringstream ss;
// If source file does not exist, throw error and return false
if (!fileExists(params.sourcePdfFileName)) {
ss << "File \"" << params.sourcePdfFileName << "\" does not exist";
throw ss.str();
}
// Open document and return false and throw error if something goes wrong
Poppler::Document *document = Poppler::Document::load(QString::fromStdString(params.sourcePdfFileName));
if (document == NULL) {
ss << "Error occurred when reading \"" << params.sourcePdfFileName << "\"";
throw ss.str();
}
// Fill form
int n = document->numPages();
stringstream idSS;
for (int i = 0; i < n; i += 1) {
Poppler::Page *page = document->page(i);
foreach (Poppler::FormField *field, page->formFields()) {
string fieldName = field->fullyQualifiedName().toStdString();
// Support writing fields by both fieldName and id.
// If fieldName is not present in params, try id.
if (params.fields.count(fieldName) == 0) {
idSS << field->id();
fieldName = idSS.str();
idSS.str("");
idSS.clear();
}
if (!field->isReadOnly() && field->isVisible() && params.fields.count(fieldName) ) {
// Text
if (field->type() == Poppler::FormField::FormText) {
Poppler::FormFieldText *textField = (Poppler::FormFieldText *) field;
textField->setText(QString::fromUtf8(params.fields[fieldName].c_str()));
}
// Choice
if (field->type() == Poppler::FormField::FormChoice) {
Poppler::FormFieldChoice *choiceField = (Poppler::FormFieldChoice *) field;
if (choiceField->isEditable()) {
choiceField->setEditChoice(QString::fromUtf8(params.fields[fieldName].c_str()));
}
else {
QStringList possibleChoices = choiceField->choices();
QString proposedChoice = QString::fromUtf8(params.fields[fieldName].c_str());
int index = possibleChoices.indexOf(proposedChoice);
if (index >= 0) {
QList<int> choiceList;
choiceList << index;
choiceField->setCurrentChoices(choiceList);
}
}
}
// Button
// ! TODO ! Note. Poppler doesn't support checkboxes with hashtag names (aka using exportValue).
if (field->type() == Poppler::FormField::FormButton) {
Poppler::FormFieldButton *buttonField = (Poppler::FormFieldButton *) field;
if (params.fields[fieldName].compare("true") == 0) {
buttonField->setState(true);
}
else {
buttonField->setState(false);
}
}
}
}
}
// Now save and return the document
QBuffer *bufferDevice = new QBuffer();
bufferDevice->open(QIODevice::ReadWrite);
// Get save parameters
if (params.saveFormat == "imgpdf") {
createImgPdf(bufferDevice, document);
}
else {
createPdf(bufferDevice, document);
}
return bufferDevice;
}
//***********************************
//
// Node.js methods
//
//***********************************
// Read PDF form fields
NAN_METHOD(ReadSync) {
// expect a number as the first argument
Nan::Utf8String *fileName = new Nan::Utf8String(info[0]);
ostringstream ss;
int n = 0;
// If file does not exist, throw error and return false
if (!fileExists(**fileName)) {
ss << "File \"" << **fileName << "\" does not exist";
Nan::ThrowError(Nan::New<String>(ss.str()).ToLocalChecked());
info.GetReturnValue().Set(Nan::False());
}
// Open document and return false and throw error if something goes wrong
Poppler::Document *document = Poppler::Document::load(**fileName);
if (document != NULL) {
// Get field list
n = document->numPages();
} else {
ss << "Error occurred when reading \"" << **fileName << "\"";
Nan::ThrowError(Nan::New<String>(ss.str()).ToLocalChecked());
info.GetReturnValue().Set(Nan::False());
}
// Store field value objects to v8 array
Local<Array> fieldArray = Nan::New<Array>();
int fieldNum = 0;
for (int i = 0; i < n; i += 1) {
Poppler::Page *page = document->page(i);
foreach (Poppler::FormField *field, page->formFields()) {
if (!field->isReadOnly() && field->isVisible()) {
// Make JavaScript object out of the fieldnames
Local<Object> obj = Nan::New<Object>();
Nan::Set(obj, Nan::New<String>("name").ToLocalChecked(), Nan::New<String>(field->fullyQualifiedName().toStdString()).ToLocalChecked());
Nan::Set(obj, Nan::New<String>("page").ToLocalChecked(), Nan::New<Number>(i));
// ! TODO ! Note. Poppler doesn't support checkboxes with hashtag names (aka using exportValue).
string fieldType;
// Set default value undefined
Nan::Set(obj, Nan::New<String>("value").ToLocalChecked(), Nan::Undefined());
Poppler::FormFieldButton *myButton;
Poppler::FormFieldChoice *myChoice;
Nan::Set(obj, Nan::New<String>("id").ToLocalChecked(), Nan::New<Number>(field->id()));
switch (field->type()) {
// FormButton
case Poppler::FormField::FormButton:
myButton = (Poppler::FormFieldButton *)field;
switch (myButton->buttonType()) {
// Push
case Poppler::FormFieldButton::Push: fieldType = "push_button"; break;
case Poppler::FormFieldButton::CheckBox:
fieldType = "checkbox";
Nan::Set(obj, Nan::New<String>("value").ToLocalChecked(), Nan::New<Boolean>(myButton->state()));
break;
case Poppler::FormFieldButton::Radio: fieldType = "radio"; break;
}
break;
// FormText
case Poppler::FormField::FormText:
Nan::Set(obj, Nan::New<String>("value").ToLocalChecked(), Nan::New<String>(((Poppler::FormFieldText *)field)->text().toStdString()).ToLocalChecked());
fieldType = "text";
break;
// FormChoice
case Poppler::FormField::FormChoice: {
Local<Array> choiceArray = Nan::New<Array>();
myChoice = (Poppler::FormFieldChoice *)field;
QStringList possibleChoices = myChoice->choices();
for (int i = 0; i < possibleChoices.size(); i++) {
Nan::Set(choiceArray, i, Nan::New<String>(possibleChoices.at(i).toStdString()).ToLocalChecked());
}
Nan::Set(obj, Nan::New<String>("choices").ToLocalChecked(), choiceArray);
switch (myChoice->choiceType()) {
case Poppler::FormFieldChoice::ComboBox: fieldType = "combobox"; break;
case Poppler::FormFieldChoice::ListBox: fieldType = "listbox"; break;
}
break;
}
// FormSignature
case Poppler::FormField::FormSignature: fieldType = "formsignature"; break;
default:
fieldType = "undefined";
break;
}
Nan::Set(obj, Nan::New<String>("type").ToLocalChecked(), Nan::New<String>(fieldType.c_str()).ToLocalChecked());
fieldArray->Set(fieldNum, obj);
fieldNum++;
}
}
}
info.GetReturnValue().Set(fieldArray);
}
// Write PDF form fields
NAN_METHOD(WriteSync) {
// Check and return parameters given at JavaScript function call
WriteFieldsParams params = v8ParamsToCpp(info);
// Create and return pdf
try
{
QBuffer *buffer = writePdfFields(params);
Local<Object> returnPdf = Nan::CopyBuffer((char *)buffer->data().data(), buffer->size()).ToLocalChecked();
buffer->close();
delete buffer;
info.GetReturnValue().Set(returnPdf);
}
catch (string error)
{
Nan::ThrowError(Nan::New<String>(error).ToLocalChecked());
info.GetReturnValue().Set(Nan::Null());
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
** libebml : parse EBML files, see http://embl.sourceforge.net/
**
** <file/class description>
**
** Copyright (C) 2002-2010 Steve Lhomme. All rights reserved.
**
** This file is part of libebml.
**
** 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
**
** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information.
**
** Contact [email protected] if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
/*!
\file
\version \$Id$
\author Steve Lhomme <robux4 @ users.sf.net>
\author Julien Coloos <suiryc @ users.sf.net>
*/
#include <cassert>
#include <string>
#include "ebml/EbmlBinary.h"
#include "ebml/StdIOCallback.h"
START_LIBEBML_NAMESPACE
EbmlBinary::EbmlBinary()
:EbmlElement(0, false), Data(nullptr)
{}
EbmlBinary::EbmlBinary(const EbmlBinary & ElementToClone)
:EbmlElement(ElementToClone)
{
if (ElementToClone.Data == nullptr)
Data = nullptr;
else {
Data = (binary *)malloc(GetSize() * sizeof(binary));
assert(Data != nullptr);
memcpy(Data, ElementToClone.Data, GetSize());
}
}
EbmlBinary::~EbmlBinary(void) {
if(Data)
free(Data);
}
EbmlBinary::operator const binary &() const {return *Data;}
filepos_t EbmlBinary::RenderData(IOCallback & output, bool /* bForceRender */, bool /* bWithDefault */)
{
output.writeFully(Data,GetSize());
return GetSize();
}
/*!
\note no Default binary value handled
*/
uint64 EbmlBinary::UpdateSize(bool /* bWithDefault */, bool /* bForceRender */)
{
return GetSize();
}
filepos_t EbmlBinary::ReadData(IOCallback & input, ScopeMode ReadFully)
{
if (Data != nullptr)
free(Data);
if (ReadFully == SCOPE_NO_DATA) {
Data = nullptr;
return GetSize();
}
if (!GetSize()) {
SetValueIsSet();
Data = nullptr;
return 0;
}
Data = (binary *)malloc(GetSize());
if (Data == nullptr)
throw CRTError(std::string("Error allocating data"));
SetValueIsSet();
return input.read(Data, GetSize());
}
bool EbmlBinary::operator==(const EbmlBinary & ElementToCompare) const
{
return ((GetSize() == ElementToCompare.GetSize()) && (GetSize() == 0 || !memcmp(Data, ElementToCompare.Data, GetSize())));
}
END_LIBEBML_NAMESPACE
<commit_msg>[clang-tidy] remove pointless void<commit_after>/****************************************************************************
** libebml : parse EBML files, see http://embl.sourceforge.net/
**
** <file/class description>
**
** Copyright (C) 2002-2010 Steve Lhomme. All rights reserved.
**
** This file is part of libebml.
**
** 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
**
** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information.
**
** Contact [email protected] if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
/*!
\file
\version \$Id$
\author Steve Lhomme <robux4 @ users.sf.net>
\author Julien Coloos <suiryc @ users.sf.net>
*/
#include <cassert>
#include <string>
#include "ebml/EbmlBinary.h"
#include "ebml/StdIOCallback.h"
START_LIBEBML_NAMESPACE
EbmlBinary::EbmlBinary()
:EbmlElement(0, false), Data(nullptr)
{}
EbmlBinary::EbmlBinary(const EbmlBinary & ElementToClone)
:EbmlElement(ElementToClone)
{
if (ElementToClone.Data == nullptr)
Data = nullptr;
else {
Data = (binary *)malloc(GetSize() * sizeof(binary));
assert(Data != nullptr);
memcpy(Data, ElementToClone.Data, GetSize());
}
}
EbmlBinary::~EbmlBinary() {
if(Data)
free(Data);
}
EbmlBinary::operator const binary &() const {return *Data;}
filepos_t EbmlBinary::RenderData(IOCallback & output, bool /* bForceRender */, bool /* bWithDefault */)
{
output.writeFully(Data,GetSize());
return GetSize();
}
/*!
\note no Default binary value handled
*/
uint64 EbmlBinary::UpdateSize(bool /* bWithDefault */, bool /* bForceRender */)
{
return GetSize();
}
filepos_t EbmlBinary::ReadData(IOCallback & input, ScopeMode ReadFully)
{
if (Data != nullptr)
free(Data);
if (ReadFully == SCOPE_NO_DATA) {
Data = nullptr;
return GetSize();
}
if (!GetSize()) {
SetValueIsSet();
Data = nullptr;
return 0;
}
Data = (binary *)malloc(GetSize());
if (Data == nullptr)
throw CRTError(std::string("Error allocating data"));
SetValueIsSet();
return input.read(Data, GetSize());
}
bool EbmlBinary::operator==(const EbmlBinary & ElementToCompare) const
{
return ((GetSize() == ElementToCompare.GetSize()) && (GetSize() == 0 || !memcmp(Data, ElementToCompare.Data, GetSize())));
}
END_LIBEBML_NAMESPACE
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkIGTLDevice.h"
//#include "mitkIGTTimeStamp.h"
#include <itkMutexLockHolder.h>
#include <itksys/SystemTools.hxx>
#include <cstring>
typedef itk::MutexLockHolder<itk::FastMutexLock> MutexLockHolder;
mitk::IGTLDevice::IGTLDevice() :
// m_Data(mitk::DeviceDataUnspecified),
m_State(mitk::IGTLDevice::Setup),
m_StopCommunication(false),
m_PortNumber(-1),
m_MultiThreader(NULL), m_ThreadID(0)
{
m_StopCommunicationMutex = itk::FastMutexLock::New();
m_StateMutex = itk::FastMutexLock::New();
m_SocketMutex = itk::FastMutexLock::New();
m_CommunicationFinishedMutex = itk::FastMutexLock::New();
// execution rights are owned by the application thread at the beginning
m_CommunicationFinishedMutex->Lock();
m_MultiThreader = itk::MultiThreader::New();
// m_Data = mitk::DeviceDataUnspecified;
}
mitk::IGTLDevice::~IGTLDevice()
{
/* stop communication and disconnect from igtl device */
if (GetState() == Running)
{
this->StopCommunication();
}
if (GetState() == Ready)
{
this->CloseConnection();
}
/* cleanup tracking thread */
if ((m_ThreadID != 0) && (m_MultiThreader.IsNotNull()))
{
m_MultiThreader->TerminateThread(m_ThreadID);
}
m_MultiThreader = NULL;
}
mitk::IGTLDevice::IGTLDeviceState mitk::IGTLDevice::GetState() const
{
MutexLockHolder lock(*m_StateMutex);
return m_State;
}
void mitk::IGTLDevice::SetState( IGTLDeviceState state )
{
itkDebugMacro("setting m_State to " << state);
MutexLockHolder lock(*m_StateMutex); // lock and unlock the mutex
if (m_State == state)
{
return;
}
m_State = state;
this->Modified();
}
//mitk::IGTLDeviceData mitk::IGTLDevice::GetData() const{
// return m_Data;
//}
//void mitk::IGTLDevice::SetData(mitk::IGTLDeviceData data){
// m_Data = data;
//}
bool mitk::IGTLDevice::SendMessage(igtl::MessageBase::Pointer msg)
{
// if (input == NULL)
// return SERIALSENDERROR;
// std::string message;
// if (addCRC == true)
// message = *input + CalcCRC(input) + std::string(1, CR);
// else
// message = *input + std::string(1, CR);
// //unsigned int messageLength = message.length() + 1; // +1 for CR
// // Clear send buffer
// this->ClearSendBuffer();
// // Send the date to the device
// MutexLockHolder lock(*m_SerialCommunicationMutex); // lock and unlock the mutex
// long returnvalue = m_SerialCommunication->Send(message);
// if (returnvalue == 0)
// return SERIALSENDERROR;
// else
// return NDIOKAY;
return true;
}
//mitk::NDIErrorCode mitk::IGTLDevice::Receive(std::string* answer, unsigned int numberOfBytes)
//{
// if (answer == NULL)
// return SERIALRECEIVEERROR;
// MutexLockHolder lock(*m_SerialCommunicationMutex); // lock and unlock the mutex
// long returnvalue = m_SerialCommunication->Receive(*answer, numberOfBytes); // never read more bytes than the device has send, the function will block until enough bytes are send...
// if (returnvalue == 0)
// return SERIALRECEIVEERROR;
// else
// return NDIOKAY;
//}
bool mitk::IGTLDevice::TestConnection()
{
// if (this->GetState() != Setup)
// {
// return mitk::TrackingSystemNotSpecified;
// }
// m_SerialCommunication = mitk::SerialCommunication::New();
// //m_DeviceProtocol = mitk::NDIProtocol::New();
// //m_DeviceProtocol->SetTrackingDevice(this);
// //m_DeviceProtocol->UseCRCOn();
// /* init local com port to standard com settings for a NDI tracking device:
// 9600 baud, 8 data bits, no parity, 1 stop bit, no hardware handshake
// */
// if (m_DeviceName.empty())
// m_SerialCommunication->SetPortNumber(m_PortNumber);
// else
// m_SerialCommunication->SetDeviceName(m_DeviceName);
// m_SerialCommunication->SetBaudRate(mitk::SerialCommunication::BaudRate9600);
// m_SerialCommunication->SetDataBits(mitk::SerialCommunication::DataBits8);
// m_SerialCommunication->SetParity(mitk::SerialCommunication::None);
// m_SerialCommunication->SetStopBits(mitk::SerialCommunication::StopBits1);
// m_SerialCommunication->SetSendTimeout(5000);
// m_SerialCommunication->SetReceiveTimeout(5000);
// if (m_SerialCommunication->OpenConnection() == 0) // error
// {
// m_SerialCommunication = NULL;
// return mitk::TrackingSystemNotSpecified;
// }
// /* Reset Tracking device by sending a serial break for 500ms */
// m_SerialCommunication->SendBreak(400);
// /* Read answer from tracking device (RESETBE6F) */
// static const std::string reset("RESETBE6F\r");
// std::string answer = "";
// this->Receive(&answer, reset.length()); // read answer (should be RESETBE6F)
// this->ClearReceiveBuffer(); // flush the receive buffer of all remaining data (carriage return, strings other than reset
// if (reset.compare(answer) != 0) // check for RESETBE6F
// {
// m_SerialCommunication->CloseConnection();
// m_SerialCommunication = NULL;
// mitkThrowException(mitk::IGTHardwareException) << "Hardware Reset of tracking device did not work";
// }
// /* Now the tracking device is reset, start initialization */
// NDIErrorCode returnvalue;
// /* initialize the tracking device */
// //returnvalue = m_DeviceProtocol->INIT();
// //if (returnvalue != NDIOKAY)
// //{
// // this->SetErrorMessage("Could not initialize the tracking device");
// // return mitk::TrackingSystemNotSpecified;
// //}
// mitk::TrackingDeviceType deviceType;
// returnvalue = m_DeviceProtocol->VER(deviceType);
// if ((returnvalue != NDIOKAY) || (deviceType == mitk::TrackingSystemNotSpecified))
// {
// m_SerialCommunication = NULL;
// return mitk::TrackingSystemNotSpecified;
// }
// m_SerialCommunication = NULL;
// return deviceType;
return true;
}
ITK_THREAD_RETURN_TYPE mitk::IGTLDevice::ThreadStartCommunication(void* pInfoStruct)
{
/* extract this pointer from Thread Info structure */
struct itk::MultiThreader::ThreadInfoStruct * pInfo =
(struct itk::MultiThreader::ThreadInfoStruct*)pInfoStruct;
if (pInfo == NULL)
{
return ITK_THREAD_RETURN_VALUE;
}
if (pInfo->UserData == NULL)
{
return ITK_THREAD_RETURN_VALUE;
}
IGTLDevice *igtlDevice = (IGTLDevice*)pInfo->UserData;
if (igtlDevice != NULL)
{
igtlDevice->RunCommunication();
}
igtlDevice->m_ThreadID = 0; // erase thread id because thread will end.
return ITK_THREAD_RETURN_VALUE;
}
void mitk::IGTLDevice::RunCommunication()
{
if (this->GetState() != Running)
return;
// keep lock until end of scope
MutexLockHolder communicationFinishedLockHolder(*m_CommunicationFinishedMutex);
// Because m_StopCommunication is used by two threads, access has to be guarded
// by a mutex. To minimize thread locking, a local copy is used here
bool localStopCommunication;
// update the local copy of m_StopCommunication
this->m_StopCommunicationMutex->Lock();
localStopCommunication = this->m_StopCommunication;
this->m_StopCommunicationMutex->Unlock();
while ((this->GetState() == Running) && (localStopCommunication == false))
{
//POLLLING
// Create a message buffer to receive header
igtl::MessageHeader::Pointer headerMsg;
headerMsg = igtl::MessageHeader::New();
// Initialize receive buffer
headerMsg->InitPack();
// Receive generic header from the socket
this->m_SocketMutex->Lock();
int r =
m_Socket->Receive(headerMsg->GetPackPointer(), headerMsg->GetPackSize(),1);
this->m_SocketMutex->Unlock();
if(r == 0)
{
//this->StopCommunication();
// an error was received, therefor the communication must be stopped
m_StopCommunicationMutex->Lock();
m_StopCommunication = true;
m_StopCommunicationMutex->Unlock();
}
else if (r == headerMsg->GetPackSize())
{
// Deserialize the header and check the CRC
int crcCheck = headerMsg->Unpack(1);
if (crcCheck & igtl::MessageHeader::UNPACK_HEADER)
{
// Allocate a time stamp
igtl::TimeStamp::Pointer ts;
ts = igtl::TimeStamp::New();
// Get time stamp
igtlUint32 sec;
igtlUint32 nanosec;
headerMsg->GetTimeStamp(ts);
ts->GetTimeStamp(&sec, &nanosec);
//check for invalid timestamps
if(sec != 0)
{
std::cerr << "Time stamp: "
<< sec << "."
<< nanosec << std::endl;
std::cerr << "Dev type and name: " << headerMsg->GetDeviceType() << " "
<< headerMsg->GetDeviceName() << std::endl;
headerMsg->Print(std::cout);
if (strcmp(headerMsg->GetDeviceType(), "IMAGE") == 0)
{
//ReceiveImage(socket, headerMsg);
}
}
}
}
else
{
//Message size information and actual data size don't match.
}
// m_MarkerPointsMutex->Lock(); // lock points data structure
// returnvalue = this->m_DeviceProtocol->POS3D(&m_MarkerPoints); // update points data structure with new position data from tracking device
// m_MarkerPointsMutex->Unlock();
// if (!((returnvalue == NDIOKAY) || (returnvalue == NDICRCERROR) || (returnvalue == NDICRCDOESNOTMATCH))) // right now, do not stop on crc errors
// {
// std::cout << "Error in POS3D: could not read data. Possibly no markers present." << std::endl;
// }
/* Update the local copy of m_StopCommunication */
this->m_StopCommunicationMutex->Lock();
localStopCommunication = m_StopCommunication;
this->m_StopCommunicationMutex->Unlock();
itksys::SystemTools::Delay(1);
}
// StopCommunication was called, thus the mode should be changed back to Ready now
// that the tracking loop has ended.
this->SetState(Ready);
MITK_DEBUG("IGTLDevice::RunCommunication") << "Reached end of communication.";
// returning from this function (and ThreadStartCommunication())
// this will end the thread
return;
}
bool mitk::IGTLDevice::StartCommunication()
{
if (this->GetState() != Ready)
return false;
this->SetState(Running); // go to mode Running
// update the local copy of m_StopCommunication
this->m_StopCommunicationMutex->Lock();
this->m_StopCommunication = false;
this->m_StopCommunicationMutex->Unlock();
// transfer the execution rights to tracking thread
m_CommunicationFinishedMutex->Unlock();
// start a new thread that executes the communication
m_ThreadID =
m_MultiThreader->SpawnThread(this->ThreadStartCommunication, this);
// mitk::IGTTimeStamp::GetInstance()->Start(this);
return true;
}
bool mitk::IGTLDevice::StopCommunication()
{
if (this->GetState() == Running) // Only if the object is in the correct state
{
// m_StopCommunication is used by two threads, so we have to ensure correct
// thread handling
m_StopCommunicationMutex->Lock();
m_StopCommunication = true;
m_StopCommunicationMutex->Unlock();
// we have to wait here that the other thread recognizes the STOP-command
// and executes it
m_CommunicationFinishedMutex->Lock();
// mitk::IGTTimeStamp::GetInstance()->Stop(this); // notify realtime clock
// StopCommunication was called, thus the mode should be changed back
// to Ready now that the tracking loop has ended.
this->SetState(Ready);
}
return true;
}
bool mitk::IGTLDevice::CloseConnection()
{
if (this->GetState() == Setup)
{
return true;
}
else if (this->GetState() == Running)
{
this->StopCommunication();
}
m_Socket->CloseSocket();
// //init before closing to force the field generator from aurora to switch itself off
// m_DeviceProtocol->INIT();
// /* close the serial connection */
// m_SerialCommunication->CloseConnection();
// /* invalidate all tools */
// this->InvalidateAll();
/* return to setup mode */
this->SetState(Setup);
// m_SerialCommunication = NULL;
return true;
}
<commit_msg>Transform messages can be received. It is implemented in a very simple way to check if the communication works.<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkIGTLDevice.h"
//#include "mitkIGTTimeStamp.h"
#include <itkMutexLockHolder.h>
#include <itksys/SystemTools.hxx>
#include <cstring>
#include <igtlTransformMessage.h>
typedef itk::MutexLockHolder<itk::FastMutexLock> MutexLockHolder;
mitk::IGTLDevice::IGTLDevice() :
// m_Data(mitk::DeviceDataUnspecified),
m_State(mitk::IGTLDevice::Setup),
m_StopCommunication(false),
m_PortNumber(-1),
m_MultiThreader(NULL), m_ThreadID(0)
{
m_StopCommunicationMutex = itk::FastMutexLock::New();
m_StateMutex = itk::FastMutexLock::New();
m_SocketMutex = itk::FastMutexLock::New();
m_CommunicationFinishedMutex = itk::FastMutexLock::New();
// execution rights are owned by the application thread at the beginning
m_CommunicationFinishedMutex->Lock();
m_MultiThreader = itk::MultiThreader::New();
// m_Data = mitk::DeviceDataUnspecified;
}
mitk::IGTLDevice::~IGTLDevice()
{
/* stop communication and disconnect from igtl device */
if (GetState() == Running)
{
this->StopCommunication();
}
if (GetState() == Ready)
{
this->CloseConnection();
}
/* cleanup tracking thread */
if ((m_ThreadID != 0) && (m_MultiThreader.IsNotNull()))
{
m_MultiThreader->TerminateThread(m_ThreadID);
}
m_MultiThreader = NULL;
}
mitk::IGTLDevice::IGTLDeviceState mitk::IGTLDevice::GetState() const
{
MutexLockHolder lock(*m_StateMutex);
return m_State;
}
void mitk::IGTLDevice::SetState( IGTLDeviceState state )
{
itkDebugMacro("setting m_State to " << state);
MutexLockHolder lock(*m_StateMutex); // lock and unlock the mutex
if (m_State == state)
{
return;
}
m_State = state;
this->Modified();
}
//mitk::IGTLDeviceData mitk::IGTLDevice::GetData() const{
// return m_Data;
//}
//void mitk::IGTLDevice::SetData(mitk::IGTLDeviceData data){
// m_Data = data;
//}
bool mitk::IGTLDevice::SendMessage(igtl::MessageBase::Pointer msg)
{
// if (input == NULL)
// return SERIALSENDERROR;
// std::string message;
// if (addCRC == true)
// message = *input + CalcCRC(input) + std::string(1, CR);
// else
// message = *input + std::string(1, CR);
// //unsigned int messageLength = message.length() + 1; // +1 for CR
// // Clear send buffer
// this->ClearSendBuffer();
// // Send the date to the device
// MutexLockHolder lock(*m_SerialCommunicationMutex); // lock and unlock the mutex
// long returnvalue = m_SerialCommunication->Send(message);
// if (returnvalue == 0)
// return SERIALSENDERROR;
// else
// return NDIOKAY;
return true;
}
//mitk::NDIErrorCode mitk::IGTLDevice::Receive(std::string* answer, unsigned int numberOfBytes)
//{
// if (answer == NULL)
// return SERIALRECEIVEERROR;
// MutexLockHolder lock(*m_SerialCommunicationMutex); // lock and unlock the mutex
// long returnvalue = m_SerialCommunication->Receive(*answer, numberOfBytes); // never read more bytes than the device has send, the function will block until enough bytes are send...
// if (returnvalue == 0)
// return SERIALRECEIVEERROR;
// else
// return NDIOKAY;
//}
bool mitk::IGTLDevice::TestConnection()
{
// if (this->GetState() != Setup)
// {
// return mitk::TrackingSystemNotSpecified;
// }
// m_SerialCommunication = mitk::SerialCommunication::New();
// //m_DeviceProtocol = mitk::NDIProtocol::New();
// //m_DeviceProtocol->SetTrackingDevice(this);
// //m_DeviceProtocol->UseCRCOn();
// /* init local com port to standard com settings for a NDI tracking device:
// 9600 baud, 8 data bits, no parity, 1 stop bit, no hardware handshake
// */
// if (m_DeviceName.empty())
// m_SerialCommunication->SetPortNumber(m_PortNumber);
// else
// m_SerialCommunication->SetDeviceName(m_DeviceName);
// m_SerialCommunication->SetBaudRate(mitk::SerialCommunication::BaudRate9600);
// m_SerialCommunication->SetDataBits(mitk::SerialCommunication::DataBits8);
// m_SerialCommunication->SetParity(mitk::SerialCommunication::None);
// m_SerialCommunication->SetStopBits(mitk::SerialCommunication::StopBits1);
// m_SerialCommunication->SetSendTimeout(5000);
// m_SerialCommunication->SetReceiveTimeout(5000);
// if (m_SerialCommunication->OpenConnection() == 0) // error
// {
// m_SerialCommunication = NULL;
// return mitk::TrackingSystemNotSpecified;
// }
// /* Reset Tracking device by sending a serial break for 500ms */
// m_SerialCommunication->SendBreak(400);
// /* Read answer from tracking device (RESETBE6F) */
// static const std::string reset("RESETBE6F\r");
// std::string answer = "";
// this->Receive(&answer, reset.length()); // read answer (should be RESETBE6F)
// this->ClearReceiveBuffer(); // flush the receive buffer of all remaining data (carriage return, strings other than reset
// if (reset.compare(answer) != 0) // check for RESETBE6F
// {
// m_SerialCommunication->CloseConnection();
// m_SerialCommunication = NULL;
// mitkThrowException(mitk::IGTHardwareException) << "Hardware Reset of tracking device did not work";
// }
// /* Now the tracking device is reset, start initialization */
// NDIErrorCode returnvalue;
// /* initialize the tracking device */
// //returnvalue = m_DeviceProtocol->INIT();
// //if (returnvalue != NDIOKAY)
// //{
// // this->SetErrorMessage("Could not initialize the tracking device");
// // return mitk::TrackingSystemNotSpecified;
// //}
// mitk::TrackingDeviceType deviceType;
// returnvalue = m_DeviceProtocol->VER(deviceType);
// if ((returnvalue != NDIOKAY) || (deviceType == mitk::TrackingSystemNotSpecified))
// {
// m_SerialCommunication = NULL;
// return mitk::TrackingSystemNotSpecified;
// }
// m_SerialCommunication = NULL;
// return deviceType;
return true;
}
ITK_THREAD_RETURN_TYPE mitk::IGTLDevice::ThreadStartCommunication(void* pInfoStruct)
{
/* extract this pointer from Thread Info structure */
struct itk::MultiThreader::ThreadInfoStruct * pInfo =
(struct itk::MultiThreader::ThreadInfoStruct*)pInfoStruct;
if (pInfo == NULL)
{
return ITK_THREAD_RETURN_VALUE;
}
if (pInfo->UserData == NULL)
{
return ITK_THREAD_RETURN_VALUE;
}
IGTLDevice *igtlDevice = (IGTLDevice*)pInfo->UserData;
if (igtlDevice != NULL)
{
igtlDevice->RunCommunication();
}
igtlDevice->m_ThreadID = 0; // erase thread id because thread will end.
return ITK_THREAD_RETURN_VALUE;
}
void mitk::IGTLDevice::RunCommunication()
{
if (this->GetState() != Running)
return;
// keep lock until end of scope
MutexLockHolder communicationFinishedLockHolder(*m_CommunicationFinishedMutex);
// Because m_StopCommunication is used by two threads, access has to be guarded
// by a mutex. To minimize thread locking, a local copy is used here
bool localStopCommunication;
// update the local copy of m_StopCommunication
this->m_StopCommunicationMutex->Lock();
localStopCommunication = this->m_StopCommunication;
this->m_StopCommunicationMutex->Unlock();
while ((this->GetState() == Running) && (localStopCommunication == false))
{
//POLLLING
// Create a message buffer to receive header
igtl::MessageHeader::Pointer headerMsg;
headerMsg = igtl::MessageHeader::New();
// Initialize receive buffer
headerMsg->InitPack();
// Receive generic header from the socket
this->m_SocketMutex->Lock();
int r =
m_Socket->Receive(headerMsg->GetPackPointer(), headerMsg->GetPackSize(),1);
this->m_SocketMutex->Unlock();
if(r == 0)
{
//this->StopCommunication();
// an error was received, therefor the communication must be stopped
m_StopCommunicationMutex->Lock();
m_StopCommunication = true;
m_StopCommunicationMutex->Unlock();
}
else if (r == headerMsg->GetPackSize())
{
// Deserialize the header and check the CRC
int crcCheck = headerMsg->Unpack(1);
if (crcCheck & igtl::MessageHeader::UNPACK_HEADER)
{
// Allocate a time stamp
igtl::TimeStamp::Pointer ts;
ts = igtl::TimeStamp::New();
// Get time stamp
igtlUint32 sec;
igtlUint32 nanosec;
headerMsg->GetTimeStamp(ts);
ts->GetTimeStamp(&sec, &nanosec);
//check for invalid timestamps
// if(sec != 0)
{
std::cerr << "Time stamp: "
<< sec << "."
<< nanosec << std::endl;
std::cerr << "Dev type and name: " << headerMsg->GetDeviceType() << " "
<< headerMsg->GetDeviceName() << std::endl;
headerMsg->Print(std::cout);
if (strcmp(headerMsg->GetDeviceType(), "TRANSFORM") == 0)
{
//ReceiveImage(socket, headerMsg);
// Create a message buffer to receive transform data
igtl::TransformMessage::Pointer transMsg;
transMsg = igtl::TransformMessage::New();
transMsg->SetMessageHeader(headerMsg);
transMsg->AllocatePack();
// Receive transform data from the socket
m_Socket->Receive(transMsg->GetPackBodyPointer(),
transMsg->GetPackBodySize());
// Deserialize the transform data
// If you want to skip CRC check, call Unpack() without argument.
int c = transMsg->Unpack(1);
if (c & igtl::MessageHeader::UNPACK_BODY) // if CRC check is OK
{
// Retrive the transform data
igtl::Matrix4x4 matrix;
transMsg->GetMatrix(matrix);
igtl::PrintMatrix(matrix);
std::cerr << std::endl;
}
}
}
}
}
else
{
//Message size information and actual data size don't match.
}
// m_MarkerPointsMutex->Lock(); // lock points data structure
// returnvalue = this->m_DeviceProtocol->POS3D(&m_MarkerPoints); // update points data structure with new position data from tracking device
// m_MarkerPointsMutex->Unlock();
// if (!((returnvalue == NDIOKAY) || (returnvalue == NDICRCERROR) || (returnvalue == NDICRCDOESNOTMATCH))) // right now, do not stop on crc errors
// {
// std::cout << "Error in POS3D: could not read data. Possibly no markers present." << std::endl;
// }
/* Update the local copy of m_StopCommunication */
this->m_StopCommunicationMutex->Lock();
localStopCommunication = m_StopCommunication;
this->m_StopCommunicationMutex->Unlock();
itksys::SystemTools::Delay(1);
}
// StopCommunication was called, thus the mode should be changed back to Ready now
// that the tracking loop has ended.
this->SetState(Ready);
MITK_DEBUG("IGTLDevice::RunCommunication") << "Reached end of communication.";
// returning from this function (and ThreadStartCommunication())
// this will end the thread
return;
}
bool mitk::IGTLDevice::StartCommunication()
{
if (this->GetState() != Ready)
return false;
this->SetState(Running); // go to mode Running
// update the local copy of m_StopCommunication
this->m_StopCommunicationMutex->Lock();
this->m_StopCommunication = false;
this->m_StopCommunicationMutex->Unlock();
// transfer the execution rights to tracking thread
m_CommunicationFinishedMutex->Unlock();
// start a new thread that executes the communication
m_ThreadID =
m_MultiThreader->SpawnThread(this->ThreadStartCommunication, this);
// mitk::IGTTimeStamp::GetInstance()->Start(this);
return true;
}
bool mitk::IGTLDevice::StopCommunication()
{
if (this->GetState() == Running) // Only if the object is in the correct state
{
// m_StopCommunication is used by two threads, so we have to ensure correct
// thread handling
m_StopCommunicationMutex->Lock();
m_StopCommunication = true;
m_StopCommunicationMutex->Unlock();
// we have to wait here that the other thread recognizes the STOP-command
// and executes it
m_CommunicationFinishedMutex->Lock();
// mitk::IGTTimeStamp::GetInstance()->Stop(this); // notify realtime clock
// StopCommunication was called, thus the mode should be changed back
// to Ready now that the tracking loop has ended.
this->SetState(Ready);
}
return true;
}
bool mitk::IGTLDevice::CloseConnection()
{
if (this->GetState() == Setup)
{
return true;
}
else if (this->GetState() == Running)
{
this->StopCommunication();
}
m_Socket->CloseSocket();
// //init before closing to force the field generator from aurora to switch itself off
// m_DeviceProtocol->INIT();
// /* close the serial connection */
// m_SerialCommunication->CloseConnection();
// /* invalidate all tools */
// this->InvalidateAll();
/* return to setup mode */
this->SetState(Setup);
// m_SerialCommunication = NULL;
return true;
}
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- *
* OpenSim: testMarkerData.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2016 Stanford University and the Authors *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain a *
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0. *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* -------------------------------------------------------------------------- */
#include <fstream>
#include <OpenSim/Common/Storage.h>
#include <OpenSim/Common/MarkerData.h>
#include <OpenSim/Auxiliary/auxiliaryTestFunctions.h>
using namespace OpenSim;
using namespace std;
int main() {
// Create a storage from a std file "std_storage.sto"
try {
//MarkerData md("TRCFileWithNANs.trc");
MarkerData md("TRCFileWithNANs.trc");
//MarkerData md = MarkerData("TRCFileWithNANS.trc");
int rStartFrame=-1;
int rEndFrame=-1;
md.findFrameRange(0.0, 1.0, rStartFrame, rEndFrame);
ASSERT(rStartFrame==0);
ASSERT(rEndFrame==4);
md.findFrameRange(0.004, 0.012, rStartFrame, rEndFrame);
ASSERT(rStartFrame==1);
ASSERT(rEndFrame==3);
// ToBeTested void averageFrames(double aThreshold = -1.0, double aStartTime = -SimTK::Infinity, double aEndTime = SimTK::Infinity);
ASSERT(md.getFileName()=="TRCFileWithNANs.trc");
Storage storage;
md.makeRdStorage(storage);
ASSERT(md.getUnits().getType()==Units(string("mm")).getType(), __FILE__, __LINE__);
//std::string mm("mm");
Units lengthUnit = Units::Millimeters;
ASSERT(md.getUnits().getType()==lengthUnit.getType(), __FILE__, __LINE__);
const Array<std::string>& markerNames = md.getMarkerNames();
ASSERT(markerNames.getSize()==14, __FILE__, __LINE__);
ASSERT(md.getMarkerIndex("toe")==0, __FILE__, __LINE__);
ASSERT(md.getMarkerIndex("lASIS")==13, __FILE__, __LINE__);
ASSERT(md.getMarkerIndex("NotFound")==-1, __FILE__, __LINE__);
ASSERT(md.getNumFrames()==5, __FILE__, __LINE__);
ASSERT(md.getStartFrameTime()==0.0, __FILE__, __LINE__);
ASSERT(md.getLastFrameTime()==0.016, __FILE__, __LINE__);
ASSERT(md.getDataRate()==250., __FILE__, __LINE__);
ASSERT(md.getCameraRate()==250., __FILE__, __LINE__);
//ToBeTested md.convertToUnits(Units(Units::Meters));
MarkerData md2("testNaNsParsing.trc");
double expectedData[] = {1006.513977, 1014.924316,-195.748917};
const MarkerFrame& frame2 = md2.getFrame(1);
ASSERT(frame2.getFrameTime()==.01, __FILE__, __LINE__);
const SimTK::Array_<SimTK::Vec3>& markers = frame2.getMarkers();
const SimTK::Vec3& m1 = markers[0];
ASSERT(SimTK::isNaN(m1[0]), __FILE__, __LINE__);
ASSERT(SimTK::isNaN(m1[1]), __FILE__, __LINE__);
ASSERT(SimTK::isNaN(m1[2]), __FILE__, __LINE__);
SimTK::Vec3 diff = (markers[1]-SimTK::Vec3(expectedData[0], expectedData[1], expectedData[2]));
ASSERT(diff.norm() < 1e-7, __FILE__, __LINE__);
MarkerData md3("testEformatParsing.trc");
double expectedData3[] = {-1.52E-01, 2.45E-01, -1.71E+00};
const MarkerFrame& frame3 = md3.getFrame(0);
const SimTK::Array_<SimTK::Vec3>& markers3 = frame3.getMarkers();
/*const SimTK::Vec3& m31 = */markers3[1];
/* SimTK::Vec3 diff3 = */(markers3[1]-SimTK::Vec3(expectedData3));
ASSERT(diff.norm() < 1e-7, __FILE__, __LINE__);
}
catch(const Exception& e) {
e.print(cerr);
return 1;
}
cout << "Done" << endl;
return 0;
}
<commit_msg>Add test to ensure STOFileAdapter is compatible with MarkerData.<commit_after>/* -------------------------------------------------------------------------- *
* OpenSim: testMarkerData.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2016 Stanford University and the Authors *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain a *
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0. *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* -------------------------------------------------------------------------- */
#include <fstream>
#include <OpenSim/Common/Storage.h>
#include <OpenSim/Common/MarkerData.h>
#include <OpenSim/Auxiliary/auxiliaryTestFunctions.h>
#include <unordered_set>
using namespace OpenSim;
using namespace std;
// Write STO file using STOFileAdapter, read it multiple times using MarkerData.
// Make sure the file does not contain duplicates in the header.
void testSTOFileAdapterWithMarkerData() {
TimeSeriesTable table{};
table.setColumnLabels({"0.x", "0.y", "0.z", "1.x", "1.y", "1.z"});
table.appendRow(0.1, {1, 1, 1, 1, 1, 1});
table.appendRow(0.2, {2, 2, 2, 2, 2, 2});
table.appendRow(0.3, {3, 3, 3, 3, 3, 3});
std::string filename{"table.sto"};
STOFileAdapter_<double>::write(table, filename);
MarkerData markerdata1{filename};
MarkerData markerdata2{filename};
MarkerData markerdata3{filename};
std::ifstream filestream{filename};
std::unordered_set<std::string> headerlines{};
for(std::string line; std::getline(filestream, line); )
if(!headerlines.insert(line).second)
throw Exception{"Test failed: found duplicates in header."};
std::remove(filename.c_str());
}
int main() {
// Create a storage from a std file "std_storage.sto"
try {
//MarkerData md("TRCFileWithNANs.trc");
MarkerData md("TRCFileWithNANs.trc");
//MarkerData md = MarkerData("TRCFileWithNANS.trc");
int rStartFrame=-1;
int rEndFrame=-1;
md.findFrameRange(0.0, 1.0, rStartFrame, rEndFrame);
ASSERT(rStartFrame==0);
ASSERT(rEndFrame==4);
md.findFrameRange(0.004, 0.012, rStartFrame, rEndFrame);
ASSERT(rStartFrame==1);
ASSERT(rEndFrame==3);
// ToBeTested void averageFrames(double aThreshold = -1.0, double aStartTime = -SimTK::Infinity, double aEndTime = SimTK::Infinity);
ASSERT(md.getFileName()=="TRCFileWithNANs.trc");
Storage storage;
md.makeRdStorage(storage);
ASSERT(md.getUnits().getType()==Units(string("mm")).getType(), __FILE__, __LINE__);
//std::string mm("mm");
Units lengthUnit = Units::Millimeters;
ASSERT(md.getUnits().getType()==lengthUnit.getType(), __FILE__, __LINE__);
const Array<std::string>& markerNames = md.getMarkerNames();
ASSERT(markerNames.getSize()==14, __FILE__, __LINE__);
ASSERT(md.getMarkerIndex("toe")==0, __FILE__, __LINE__);
ASSERT(md.getMarkerIndex("lASIS")==13, __FILE__, __LINE__);
ASSERT(md.getMarkerIndex("NotFound")==-1, __FILE__, __LINE__);
ASSERT(md.getNumFrames()==5, __FILE__, __LINE__);
ASSERT(md.getStartFrameTime()==0.0, __FILE__, __LINE__);
ASSERT(md.getLastFrameTime()==0.016, __FILE__, __LINE__);
ASSERT(md.getDataRate()==250., __FILE__, __LINE__);
ASSERT(md.getCameraRate()==250., __FILE__, __LINE__);
//ToBeTested md.convertToUnits(Units(Units::Meters));
MarkerData md2("testNaNsParsing.trc");
double expectedData[] = {1006.513977, 1014.924316,-195.748917};
const MarkerFrame& frame2 = md2.getFrame(1);
ASSERT(frame2.getFrameTime()==.01, __FILE__, __LINE__);
const SimTK::Array_<SimTK::Vec3>& markers = frame2.getMarkers();
const SimTK::Vec3& m1 = markers[0];
ASSERT(SimTK::isNaN(m1[0]), __FILE__, __LINE__);
ASSERT(SimTK::isNaN(m1[1]), __FILE__, __LINE__);
ASSERT(SimTK::isNaN(m1[2]), __FILE__, __LINE__);
SimTK::Vec3 diff = (markers[1]-SimTK::Vec3(expectedData[0], expectedData[1], expectedData[2]));
ASSERT(diff.norm() < 1e-7, __FILE__, __LINE__);
MarkerData md3("testEformatParsing.trc");
double expectedData3[] = {-1.52E-01, 2.45E-01, -1.71E+00};
const MarkerFrame& frame3 = md3.getFrame(0);
const SimTK::Array_<SimTK::Vec3>& markers3 = frame3.getMarkers();
/*const SimTK::Vec3& m31 = */markers3[1];
/* SimTK::Vec3 diff3 = */(markers3[1]-SimTK::Vec3(expectedData3));
ASSERT(diff.norm() < 1e-7, __FILE__, __LINE__);
testSTOFileAdapterWithMarkerData();
}
catch(const Exception& e) {
e.print(cerr);
return 1;
}
cout << "Done" << endl;
return 0;
}
<|endoftext|> |
<commit_before>// testConstrollers.cpp
// Author: Ajay Seth
/*
* Copyright (c) 2009, Stanford University. All rights reserved.
* Use of the OpenSim software in source form is permitted provided that the following
* conditions are met:
* 1. The software is used only for non-commercial research and education. It may not
* be used in relation to any commercial activity.
* 2. The software is not distributed or redistributed. Software distribution is allowed
* only through https://simtk.org/home/opensim.
* 3. Use of the OpenSim software or derivatives must be acknowledged in all publications,
* presentations, or documents describing work in which OpenSim or derivatives are used.
* 4. Credits to developers may not be removed from executables
* created from modifications of the source.
* 5. Modifications of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 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;
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR BUSINESS INTERRUPTION) 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.
*/
//==========================================================================================================
// testControllers builds OpenSim models using the OpenSim API and verifies that controllers
// behave as described.
//
// Tests Include:
// 1. Test a control set controller on a block with an ideal actuator
// 2. Test a corrective controller on a block with an ideal actuator
//
// Add tests here as new controller types are added to OpenSim
//
//==========================================================================================================
#include <iostream>
#include <OpenSim/Common/IO.h>
#include <OpenSim/Common/Exception.h>
#include <OpenSim/Simulation/Model/AnalysisSet.h>
#include <OpenSim/Simulation/Model/BodySet.h>
#include <OpenSim/Simulation/Manager/Manager.h>
#include <OpenSim/Analyses/Kinematics.h>
#include <OpenSim/Analyses/PointKinematics.h>
#include <OpenSim/Simulation/Model/Model.h>
#include <OpenSim/Simulation/SimbodyEngine/SliderJoint.h>
#include <OpenSim/Common/LoadOpenSimLibrary.h>
#include <OpenSim/Common/NaturalCubicSpline.h>
#include <OpenSim/Common/FunctionAdapter.h>
#include <OpenSim/Tools/CorrectionController.h>
#include <OpenSim/Actuators/CoordinateActuator.h>
#include <OpenSim/Simulation/Control/ControlSetController.h>
#include <OpenSim/Simulation/Control/ControlLinear.h>
using namespace OpenSim;
using namespace SimTK;
using namespace std;
//==========================================================================================================
bool testControlSetControllerOnBlock()
{
bool status = true;
// Create a new OpenSim model
Model osimModel;
osimModel.setName("osimModel");
// Get the ground body
OpenSim::Body& ground = osimModel.getGroundBody();
// Create a 20 kg, 0.1 m^3 block body
double blockMass = 20.0, blockSideLength = 0.1;
Vec3 blockMassCenter(0), groundOrigin(0), blockInGround(0, blockSideLength/2, 0);
Inertia blockIntertia = Inertia::brick(blockSideLength, blockSideLength, blockSideLength);
OpenSim::Body block("block", blockMass, blockMassCenter, blockMass*blockIntertia);
//Create a free joint with 6 degrees-of-freedom
SimTK::Vec3 noRotation(0);
SliderJoint blockToGround("",ground, blockInGround, noRotation, block, blockMassCenter, noRotation);
// Create 6 coordinates (degrees-of-freedom) between the ground and block
CoordinateSet& jointCoordinateSet = blockToGround.getCoordinateSet();
double posRange[2] = {-1, 1};
jointCoordinateSet[0].setName("xTranslation");
jointCoordinateSet[0].setMotionType(Coordinate::Translational);
jointCoordinateSet[0].setRange(posRange);
// Add the block body to the model
osimModel.addBody(&block);
// Define a single coordinate actuator.
CoordinateActuator actuator(jointCoordinateSet[0].getName());
actuator.setName("actuator");
// Add the actuator to the model
osimModel.addForce(&actuator);
double initialTime = 0;
double finalTime = 1.0;
// Define the initial and final control values
double controlForce[1] = {100};
// Create two control signals
ControlLinear control;
control.setName("actuator");
// Create a control set and add the controls to the set
ControlSet actuatorControls;
actuatorControls.append(&control);
actuatorControls.setMemoryOwner(false);
actuatorControls.setControlValues(initialTime, controlForce);
actuatorControls.setControlValues(finalTime, controlForce);
// Create a control set controller that simply applies controls from a ControlSet
ControlSetController actuatorController;
actuatorController.setControlSet(&actuatorControls);
// add the controller to the model
osimModel.addController(&actuatorController);
// Initialize the system and get the state representing the state system
SimTK::State& si = osimModel.initSystem();
// Specify zero slider joint kinematic states
CoordinateSet &coordinates = osimModel.updCoordinateSet();
coordinates[0].setValue(si, 0.0); // x translation
coordinates[0].setSpeedValue(si, 0.0); // x speed
// Create the integrator and manager for the simulation.
double accuracy = 1.0e-3;
SimTK::RungeKuttaMersonIntegrator integrator(osimModel.getSystem());
integrator.setMaximumStepSize(100);
integrator.setMinimumStepSize(1.0e-6);
integrator.setAccuracy(accuracy);
integrator.setAbsoluteTolerance(1.0e-4);
Manager manager(osimModel, integrator);
// Integrate from initial time to final time
manager.setInitialTime(initialTime);
manager.setFinalTime(finalTime);
std::cout<<"\n\nIntegrating from "<<initialTime<<" to "<<finalTime<<std::endl;
manager.integrate(si);
si.getQ().dump("Final position:");
double x_err = fabs(coordinates[0].getValue(si) - 0.5*(controlForce[0]/blockMass)*finalTime*finalTime);
if (x_err > accuracy){
cout << "ControlSetControllerOnBlock failed to produce the expected motion." << endl;
status = false;
}
// Save the simulation results
Storage states(manager.getStateStorage());
states.print("block_push.sto");
osimModel.disownAllComponents();
return status;
}// end of testControlSetControllerOnBlock()
//==========================================================================================================
bool testCorrectionControllerOnBlock()
{
bool status = true;
// Create a new OpenSim model
Model osimModel;
osimModel.setName("osimModel");
// Get the ground body
OpenSim::Body& ground = osimModel.getGroundBody();
// Create a 20 kg, 0.1 m^3 block body
double blockMass = 20.0, blockSideLength = 0.1;
Vec3 blockMassCenter(0), groundOrigin(0), blockInGround(0, blockSideLength/2, 0);
Inertia blockIntertia = Inertia::brick(blockSideLength, blockSideLength, blockSideLength);
OpenSim::Body block("block", blockMass, blockMassCenter, blockMass*blockIntertia);
//Create a free joint with 6 degrees-of-freedom
SimTK::Vec3 noRotation(0);
SliderJoint blockToGround("",ground, blockInGround, noRotation, block, blockMassCenter, noRotation);
// Create 6 coordinates (degrees-of-freedom) between the ground and block
CoordinateSet& jointCoordinateSet = blockToGround.getCoordinateSet();
double posRange[2] = {-1, 1};
jointCoordinateSet[0].setName("xTranslation");
jointCoordinateSet[0].setMotionType(Coordinate::Translational);
jointCoordinateSet[0].setRange(posRange);
// Add the block body to the model
osimModel.addBody(&block);
// Generate tracking data
Storage *desiredXTranslation = new Storage();
CorrectionController tracker;
// add the controller to the model
osimModel.addController(&tracker);
// Initialize the system and get the state representing the state system
SimTK::State& si = osimModel.initSystem();
// Create the integrator and manager for the simulation.
SimTK::RungeKuttaMersonIntegrator integrator(osimModel.getSystem());
integrator.setMaximumStepSize(1.0e-3);
integrator.setMinimumStepSize(1.0e-6);
integrator.setAccuracy(1.0e-3);
integrator.setAbsoluteTolerance(1.0e-4);
Manager manager(osimModel, integrator);
osimModel.disownAllComponents();
return status;
}// end of testCorrectionControllerOnBlock()
int main()
{
int status = 0;
if( !testControlSetControllerOnBlock()) {
status = 1;
cout << " testControlSetControllerOnBlock FAILED " << endl;
}
if( !testCorrectionControllerOnBlock()) {
status = 1;
cout << " testCorrectiveControllerOnBlock FAILED " << endl;
}
return status;
}
<commit_msg>Added a test for PrescribedController that is the same for ControlSetController.<commit_after>// testConstrollers.cpp
// Author: Ajay Seth
/*
* Copyright (c) 2009, Stanford University. All rights reserved.
* Use of the OpenSim software in source form is permitted provided that the following
* conditions are met:
* 1. The software is used only for non-commercial research and education. It may not
* be used in relation to any commercial activity.
* 2. The software is not distributed or redistributed. Software distribution is allowed
* only through https://simtk.org/home/opensim.
* 3. Use of the OpenSim software or derivatives must be acknowledged in all publications,
* presentations, or documents describing work in which OpenSim or derivatives are used.
* 4. Credits to developers may not be removed from executables
* created from modifications of the source.
* 5. Modifications of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 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;
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR BUSINESS INTERRUPTION) 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.
*/
//==========================================================================================================
// testControllers builds OpenSim models using the OpenSim API and verifies that controllers
// behave as described.
//
// Tests Include:
// 1. Test a control set controller on a block with an ideal actuator
// 2. Test a corrective controller on a block with an ideal actuator
//
// Add tests here as new controller types are added to OpenSim
//
//==========================================================================================================
#include <iostream>
#include <OpenSim/Common/IO.h>
#include <OpenSim/Common/Exception.h>
#include <OpenSim/Simulation/Model/AnalysisSet.h>
#include <OpenSim/Simulation/Model/BodySet.h>
#include <OpenSim/Simulation/Manager/Manager.h>
#include <OpenSim/Analyses/Kinematics.h>
#include <OpenSim/Analyses/PointKinematics.h>
#include <OpenSim/Simulation/Model/Model.h>
#include <OpenSim/Simulation/SimbodyEngine/SliderJoint.h>
#include <OpenSim/Common/LoadOpenSimLibrary.h>
#include <OpenSim/Common/NaturalCubicSpline.h>
#include <OpenSim/Common/FunctionAdapter.h>
#include <OpenSim/Common/Constant.h>
#include <OpenSim/Tools/CorrectionController.h>
#include <OpenSim/Actuators/CoordinateActuator.h>
#include <OpenSim/Simulation/Control/ControlSetController.h>
#include <OpenSim/Simulation/Control/PrescribedController.h>
#include <OpenSim/Simulation/Control/ControlLinear.h>
using namespace OpenSim;
using namespace SimTK;
using namespace std;
//==========================================================================================================
bool testControlSetControllerOnBlock()
{
bool status = true;
// Create a new OpenSim model
Model osimModel;
osimModel.setName("osimModel");
// Get the ground body
OpenSim::Body& ground = osimModel.getGroundBody();
// Create a 20 kg, 0.1 m^3 block body
double blockMass = 20.0, blockSideLength = 0.1;
Vec3 blockMassCenter(0), groundOrigin(0), blockInGround(0, blockSideLength/2, 0);
Inertia blockIntertia = Inertia::brick(blockSideLength, blockSideLength, blockSideLength);
OpenSim::Body block("block", blockMass, blockMassCenter, blockMass*blockIntertia);
//Create a free joint with 6 degrees-of-freedom
SimTK::Vec3 noRotation(0);
SliderJoint blockToGround("",ground, blockInGround, noRotation, block, blockMassCenter, noRotation);
// Create 6 coordinates (degrees-of-freedom) between the ground and block
CoordinateSet& jointCoordinateSet = blockToGround.getCoordinateSet();
double posRange[2] = {-1, 1};
jointCoordinateSet[0].setName("xTranslation");
jointCoordinateSet[0].setMotionType(Coordinate::Translational);
jointCoordinateSet[0].setRange(posRange);
// Add the block body to the model
osimModel.addBody(&block);
// Define a single coordinate actuator.
CoordinateActuator actuator(jointCoordinateSet[0].getName());
actuator.setName("actuator");
// Add the actuator to the model
osimModel.addForce(&actuator);
double initialTime = 0;
double finalTime = 1.0;
// Define the initial and final control values
double controlForce[1] = {100};
// Create two control signals
ControlLinear control;
control.setName("actuator");
// Create a control set and add the controls to the set
ControlSet actuatorControls;
actuatorControls.append(&control);
actuatorControls.setMemoryOwner(false);
actuatorControls.setControlValues(initialTime, controlForce);
actuatorControls.setControlValues(finalTime, controlForce);
// Create a control set controller that simply applies controls from a ControlSet
ControlSetController actuatorController;
actuatorController.setControlSet(&actuatorControls);
// add the controller to the model
osimModel.addController(&actuatorController);
// Initialize the system and get the state representing the state system
SimTK::State& si = osimModel.initSystem();
// Specify zero slider joint kinematic states
CoordinateSet &coordinates = osimModel.updCoordinateSet();
coordinates[0].setValue(si, 0.0); // x translation
coordinates[0].setSpeedValue(si, 0.0); // x speed
// Create the integrator and manager for the simulation.
double accuracy = 1.0e-3;
SimTK::RungeKuttaMersonIntegrator integrator(osimModel.getSystem());
integrator.setMaximumStepSize(100);
integrator.setMinimumStepSize(1.0e-6);
integrator.setAccuracy(accuracy);
integrator.setAbsoluteTolerance(1.0e-4);
Manager manager(osimModel, integrator);
// Integrate from initial time to final time
manager.setInitialTime(initialTime);
manager.setFinalTime(finalTime);
std::cout<<"\n\nIntegrating from "<<initialTime<<" to "<<finalTime<<std::endl;
manager.integrate(si);
si.getQ().dump("Final position:");
double x_err = fabs(coordinates[0].getValue(si) - 0.5*(controlForce[0]/blockMass)*finalTime*finalTime);
if (x_err > accuracy){
cout << "ControlSetControllerOnBlock failed to produce the expected motion." << endl;
status = false;
}
// Save the simulation results
Storage states(manager.getStateStorage());
states.print("block_push.sto");
osimModel.disownAllComponents();
return status;
}// end of testControlSetControllerOnBlock()
//==========================================================================================================
bool testPrescribedControllerOnBlock()
{
bool status = true;
// Create a new OpenSim model
Model osimModel;
osimModel.setName("osimModel");
// Get the ground body
OpenSim::Body& ground = osimModel.getGroundBody();
// Create a 20 kg, 0.1 m^3 block body
double blockMass = 20.0, blockSideLength = 0.1;
Vec3 blockMassCenter(0), groundOrigin(0), blockInGround(0, blockSideLength/2, 0);
Inertia blockIntertia = Inertia::brick(blockSideLength, blockSideLength, blockSideLength);
OpenSim::Body block("block", blockMass, blockMassCenter, blockMass*blockIntertia);
//Create a free joint with 6 degrees-of-freedom
SimTK::Vec3 noRotation(0);
SliderJoint blockToGround("",ground, blockInGround, noRotation, block, blockMassCenter, noRotation);
// Create 6 coordinates (degrees-of-freedom) between the ground and block
CoordinateSet& jointCoordinateSet = blockToGround.getCoordinateSet();
double posRange[2] = {-1, 1};
jointCoordinateSet[0].setName("xTranslation");
jointCoordinateSet[0].setMotionType(Coordinate::Translational);
jointCoordinateSet[0].setRange(posRange);
// Add the block body to the model
osimModel.addBody(&block);
// Define a single coordinate actuator.
CoordinateActuator actuator(jointCoordinateSet[0].getName());
actuator.setName("actuator");
// Add the actuator to the model
osimModel.addForce(&actuator);
double initialTime = 0;
double finalTime = 1.0;
// Define the initial and final control values
double controlForce = 100;
// Create a prescribed controller that simply applies a function of the force
PrescribedController actuatorController;
actuatorController.prescribeControlForActuator(0, new Constant(controlForce));
// add the controller to the model
osimModel.addController(&actuatorController);
// Initialize the system and get the state representing the state system
SimTK::State& si = osimModel.initSystem();
// Specify zero slider joint kinematic states
CoordinateSet &coordinates = osimModel.updCoordinateSet();
coordinates[0].setValue(si, 0.0); // x translation
coordinates[0].setSpeedValue(si, 0.0); // x speed
// Create the integrator and manager for the simulation.
double accuracy = 1.0e-3;
SimTK::RungeKuttaMersonIntegrator integrator(osimModel.getSystem());
integrator.setMaximumStepSize(100);
integrator.setMinimumStepSize(1.0e-6);
integrator.setAccuracy(accuracy);
integrator.setAbsoluteTolerance(1.0e-4);
Manager manager(osimModel, integrator);
// Integrate from initial time to final time
manager.setInitialTime(initialTime);
manager.setFinalTime(finalTime);
std::cout<<"\n\nIntegrating from "<<initialTime<<" to "<<finalTime<<std::endl;
manager.integrate(si);
si.getQ().dump("Final position:");
double x_err = fabs(coordinates[0].getValue(si) - 0.5*(controlForce/blockMass)*finalTime*finalTime);
if (x_err > accuracy){
cout << "PrescribedController failed to produce the expected motion of block." << endl;
status = false;
}
// Save the simulation results
Storage states(manager.getStateStorage());
states.print("block_push.sto");
osimModel.disownAllComponents();
return status;
}// end of testPrescribedControllerOnBlock()
//==========================================================================================================
bool testCorrectionControllerOnBlock()
{
bool status = true;
// Create a new OpenSim model
Model osimModel;
osimModel.setName("osimModel");
// Get the ground body
OpenSim::Body& ground = osimModel.getGroundBody();
// Create a 20 kg, 0.1 m^3 block body
double blockMass = 20.0, blockSideLength = 0.1;
Vec3 blockMassCenter(0), groundOrigin(0), blockInGround(0, blockSideLength/2, 0);
Inertia blockIntertia = Inertia::brick(blockSideLength, blockSideLength, blockSideLength);
OpenSim::Body block("block", blockMass, blockMassCenter, blockMass*blockIntertia);
//Create a free joint with 6 degrees-of-freedom
SimTK::Vec3 noRotation(0);
SliderJoint blockToGround("",ground, blockInGround, noRotation, block, blockMassCenter, noRotation);
// Create 6 coordinates (degrees-of-freedom) between the ground and block
CoordinateSet& jointCoordinateSet = blockToGround.getCoordinateSet();
double posRange[2] = {-1, 1};
jointCoordinateSet[0].setName("xTranslation");
jointCoordinateSet[0].setMotionType(Coordinate::Translational);
jointCoordinateSet[0].setRange(posRange);
// Add the block body to the model
osimModel.addBody(&block);
// Generate tracking data
Storage *desiredXTranslation = new Storage();
CorrectionController tracker;
// add the controller to the model
osimModel.addController(&tracker);
// Initialize the system and get the state representing the state system
SimTK::State& si = osimModel.initSystem();
// Create the integrator and manager for the simulation.
SimTK::RungeKuttaMersonIntegrator integrator(osimModel.getSystem());
integrator.setMaximumStepSize(1.0e-3);
integrator.setMinimumStepSize(1.0e-6);
integrator.setAccuracy(1.0e-3);
integrator.setAbsoluteTolerance(1.0e-4);
Manager manager(osimModel, integrator);
osimModel.disownAllComponents();
return status;
}// end of testCorrectionControllerOnBlock()
int main()
{
int status = 0;
if( !testControlSetControllerOnBlock()) {
status = 1;
cout << " testControlSetControllerOnBlock FAILED " << endl;
}
if(! testPrescribedControllerOnBlock()) {
status = 1;
cout << " testPrescribedControllerOnBlock FAILED " << endl;
}
if( !testCorrectionControllerOnBlock()) {
status = 1;
cout << " testCorrectiveControllerOnBlock FAILED " << endl;
}
return status;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <SDL2/SDL.h>
#include <GL/glew.h>
#include <GL/glu.h>
#include <SDL2/SDL_opengl.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "Cube.h"
#include "Origin.h"
#include "Shader.h"
#include "ShaderManager.h"
using namespace std;
using glm::vec3;
using glm::vec4;
const float STEP = 0.1f;
const float ANGLE_DELTA = 3.14f;
float window_width = 640.0f;
float window_height = 480.0f;
int main(int argc, char** argv) {
int result = SDL_Init(SDL_INIT_VIDEO);
if (result != 0) {
cerr << "Could not initialize SDL: " << SDL_GetError() << endl;
return 1;
}
SDL_Window* window = SDL_CreateWindow(argv[0], 0, 0, (int)window_width,
(int)window_height,
SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
if (window == nullptr) {
cerr << "Could not create window: " << SDL_GetError() << endl;
return 2;
}
SDL_ShowCursor(SDL_DISABLE);
SDL_SetRelativeMouseMode(SDL_TRUE);
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 );
SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );
SDL_GLContext gl_context = SDL_GL_CreateContext(window);
if (gl_context == nullptr) {
cerr << "Could not create OpenGL context: " << SDL_GetError() << endl;
return 3;
}
glewExperimental = GL_TRUE;
GLenum glewError = glewInit();
if (glewError != GLEW_OK) {
cerr << "Could not initialize GLEW: " << glewGetErrorString(glewError) << endl;
return 4;
}
glEnable(GL_DEPTH);
glEnable(GL_VERTEX_ARRAY);
glEnable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
auto shaders = ShaderManager();
auto shader_transform = shaders.get("transform");
shader_transform->apply();
auto cube = Cube();
auto shader_colour = shaders.get("colour");
shader_colour->apply();
auto origin = Origin();
auto eye = glm::vec3(0, 0, 5.0f);
auto at = glm::vec3(0, 0, 0);
auto up = glm::vec3(0, 1, 0);
auto view = glm::lookAt(eye, at, up);
shaders.updateViewMatrices(view);
auto proj = glm::perspective(45.f, window_width / window_height, 0.1f,
-100.f);
shaders.updateProjectionMatrices(proj);
float angle = 0.0f;
bool done = false;
SDL_Event event;
while (done == false) {
while (SDL_PollEvent(&event) != 0) {
if (event.type == SDL_QUIT) {
done = true;
} else if (event.type == SDL_KEYDOWN) {
switch (event.key.keysym.sym) {
case SDLK_ESCAPE:
cout << "[INFO] Exiting normally at user request." << endl;
done = true;
break;
default:
break;
}
} else if (event.type == SDL_MOUSEMOTION) {
cout << event.motion.xrel << " " << event.motion.yrel << endl;
const GLfloat X_SCALED = -(GLfloat)event.motion.xrel / window_width;
const GLfloat Y_SCALED = -(GLfloat)event.motion.yrel / window_height;
const GLfloat LEFT_RIGHT_ROT = X_SCALED * ANGLE_DELTA;
const GLfloat UP_DOWN_ROT = Y_SCALED * ANGLE_DELTA;
vec3 tempD(at - eye);
vec4 d(tempD.x, tempD.y, tempD.z, 0.0f);
vec3 right = cross(tempD, up);
mat4 rot;
rot = rotate(rot, UP_DOWN_ROT, right);
rot = rotate(rot, LEFT_RIGHT_ROT, up);
d = rot * d;
at.x = eye.x + d.x;
at.y = eye.y + d.y;
at.z = eye.z + d.z;
}
}
glm::vec3 direction = STEP * glm::normalize(at - eye);
glm::vec3 right = STEP * glm::normalize(glm::cross(direction, up));
auto keys = SDL_GetKeyboardState(nullptr);
if (keys[SDL_SCANCODE_W]) {
eye += direction;
at += direction;
}
if (keys[SDL_SCANCODE_S]) {
eye -= direction;
at -= direction;
}
if (keys[SDL_SCANCODE_D]) {
eye += right;
at += right;
}
if (keys[SDL_SCANCODE_A]) {
eye -= right;
at -= right;
}
if (keys[SDL_SCANCODE_SPACE]) {
eye += STEP * up;
at += STEP * up;
}
if (keys[SDL_SCANCODE_LCTRL]) {
eye -= STEP * up;
at -= STEP * up;
}
auto view = glm::lookAt(eye, at, up);
shaders.updateViewMatrices(view);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shader_colour->apply();
auto scale = glm::mat4();
scale = glm::scale(scale, glm::vec3(5.f, 5.f, 5.f));
shader_colour->updateWorldMatrix(scale);
origin.draw();
shader_transform->apply();
auto modelQuat = glm::quat();
modelQuat = glm::rotate(modelQuat, angle, glm::vec3(0, 1, 0));
auto modelMat = (glm::mat4)modelQuat;
shader_transform->updateWorldMatrix((glm::mat4)modelMat);
cube.draw();
glFlush();
SDL_GL_SwapWindow(window);
angle += 0.01f;
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}<commit_msg>Remove unused code.<commit_after>#include <iostream>
#include <SDL2/SDL.h>
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "Cube.h"
#include "Origin.h"
#include "Shader.h"
#include "ShaderManager.h"
using namespace std;
using glm::vec3;
using glm::vec4;
const float STEP = 0.1f;
const float ANGLE_DELTA = 3.14f;
float window_width = 640.0f;
float window_height = 480.0f;
int main(int argc, char** argv) {
int result = SDL_Init(SDL_INIT_VIDEO);
if (result != 0) {
cerr << "Could not initialize SDL: " << SDL_GetError() << endl;
return 1;
}
SDL_Window* window = SDL_CreateWindow(argv[0], 0, 0, (int)window_width,
(int)window_height,
SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
if (window == nullptr) {
cerr << "Could not create window: " << SDL_GetError() << endl;
return 2;
}
SDL_ShowCursor(SDL_DISABLE);
SDL_SetRelativeMouseMode(SDL_TRUE);
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 );
SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );
SDL_GLContext gl_context = SDL_GL_CreateContext(window);
if (gl_context == nullptr) {
cerr << "Could not create OpenGL context: " << SDL_GetError() << endl;
return 3;
}
glewExperimental = GL_TRUE;
GLenum glewError = glewInit();
if (glewError != GLEW_OK) {
cerr << "Could not initialize GLEW: " << glewGetErrorString(glewError) << endl;
return 4;
}
glEnable(GL_DEPTH);
glEnable(GL_VERTEX_ARRAY);
glEnable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
auto shaders = ShaderManager();
auto shader_transform = shaders.get("transform");
shader_transform->apply();
auto cube = Cube();
auto shader_colour = shaders.get("colour");
shader_colour->apply();
auto origin = Origin();
auto eye = glm::vec3(0, 0, 5.0f);
auto at = glm::vec3(0, 0, 0);
auto up = glm::vec3(0, 1, 0);
auto view = glm::lookAt(eye, at, up);
shaders.updateViewMatrices(view);
auto proj = glm::perspective(45.f, window_width / window_height, 0.1f,
-100.f);
shaders.updateProjectionMatrices(proj);
float angle = 0.0f;
bool done = false;
SDL_Event event;
while (!done) {
while (SDL_PollEvent(&event) != 0) {
if (event.type == SDL_QUIT) {
done = true;
} else if (event.type == SDL_KEYDOWN) {
switch (event.key.keysym.sym) {
case SDLK_ESCAPE:
cout << "[INFO] Exiting normally at user request." << endl;
done = true;
break;
default:
break;
}
} else if (event.type == SDL_MOUSEMOTION) {
cout << event.motion.xrel << " " << event.motion.yrel << endl;
const GLfloat X_SCALED = -(GLfloat)event.motion.xrel / window_width;
const GLfloat Y_SCALED = -(GLfloat)event.motion.yrel / window_height;
const GLfloat LEFT_RIGHT_ROT = X_SCALED * ANGLE_DELTA;
const GLfloat UP_DOWN_ROT = Y_SCALED * ANGLE_DELTA;
vec3 tempD(at - eye);
vec4 d(tempD.x, tempD.y, tempD.z, 0.0f);
vec3 right = cross(tempD, up);
mat4 rot;
rot = rotate(rot, UP_DOWN_ROT, right);
rot = rotate(rot, LEFT_RIGHT_ROT, up);
d = rot * d;
at.x = eye.x + d.x;
at.y = eye.y + d.y;
at.z = eye.z + d.z;
}
}
glm::vec3 direction = STEP * glm::normalize(at - eye);
glm::vec3 right = STEP * glm::normalize(glm::cross(direction, up));
auto keys = SDL_GetKeyboardState(nullptr);
if (keys[SDL_SCANCODE_W]) {
eye += direction;
at += direction;
}
if (keys[SDL_SCANCODE_S]) {
eye -= direction;
at -= direction;
}
if (keys[SDL_SCANCODE_D]) {
eye += right;
at += right;
}
if (keys[SDL_SCANCODE_A]) {
eye -= right;
at -= right;
}
if (keys[SDL_SCANCODE_SPACE]) {
eye += STEP * up;
at += STEP * up;
}
if (keys[SDL_SCANCODE_LCTRL]) {
eye -= STEP * up;
at -= STEP * up;
}
view = glm::lookAt(eye, at, up);
shaders.updateViewMatrices(view);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shader_colour->apply();
auto scale = glm::mat4();
scale = glm::scale(scale, glm::vec3(5.f, 5.f, 5.f));
shader_colour->updateWorldMatrix(scale);
origin.draw();
shader_transform->apply();
auto modelQuat = glm::quat();
modelQuat = glm::rotate(modelQuat, angle, glm::vec3(0, 1, 0));
auto modelMat = (glm::mat4)modelQuat;
shader_transform->updateWorldMatrix((glm::mat4)modelMat);
cube.draw();
glFlush();
SDL_GL_SwapWindow(window);
angle += 0.01f;
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}<|endoftext|> |
<commit_before>#include <iostream>
#include <fcntl.h>
#include <vector>
#include <boost/asio/posix/stream_descriptor.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
namespace ba = boost::asio;
std::vector<char> data(4096);
void start_read( ba::posix::stream_descriptor &desc );
void read_handler( boost::system::error_code const &e,
size_t bytes,
ba::posix::stream_descriptor &desc)
{
if( !e ) {
std::cout << "read " << bytes << "\n";
start_read( desc );
} else {
throw std::runtime_error( e.message( ) );
}
}
void start_read( ba::posix::stream_descriptor &desc )
{
desc.async_read_some( ba::buffer(data),
boost::bind( &read_handler,
ba::placeholders::error,
ba::placeholders::bytes_transferred,
boost::ref(desc)) );
}
int main( int argc, const char *argv[] ) try
{
ba::io_service ios;
ba::io_service::work w(ios);
ba::posix::stream_descriptor sd(ios);
int fd = open( argv[1], O_RDONLY );
std::cout << "Fd: " << fd << "\n";
sd.assign( fd );
start_read( sd );
while( 1 ) {
ios.run_one( );
}
return 0;
} catch( const std::exception &ex ) {
std::cerr << ex.what( ) << "\n";
return 1;
}
<commit_msg>draft<commit_after>#include <iostream>
#include <fcntl.h>
#include <vector>
#include <boost/asio/posix/stream_descriptor.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
namespace ba = boost::asio;
std::vector<char> data(4096);
void start_read( ba::posix::stream_descriptor &desc );
void read_handler( boost::system::error_code const &e,
size_t bytes,
ba::posix::stream_descriptor &desc)
{
if( !e ) {
std::cout << "read " << bytes << "\n";
start_read( desc );
} else {
std::cout << "read error: " << e.message( ) << "\n";
throw std::runtime_error( e.message( ) );
}
}
void start_read( ba::posix::stream_descriptor &desc )
{
desc.async_read_some( ba::buffer(data),
boost::bind( &read_handler,
ba::placeholders::error,
ba::placeholders::bytes_transferred,
boost::ref(desc)) );
}
int main( int argc, const char *argv[] ) try
{
ba::io_service ios;
ba::io_service::work w(ios);
ba::posix::stream_descriptor sd(ios);
int fd = open( argv[1], O_RDONLY );
std::cout << "Fd: " << fd << "\n";
sd.assign( fd );
start_read( sd );
while( 1 ) {
ios.run_one( );
}
return 0;
} catch( const std::exception &ex ) {
std::cerr << ex.what( ) << "\n";
return 1;
}
<|endoftext|> |
<commit_before>// $Id$
//
// Task to setup emcal related global objects.
//
// Author: C.Loizides
#include <TClonesArray.h>
#include <TGeoGlobalMagField.h>
#include <TGeoManager.h>
#include "AliAODEvent.h"
#include "AliAnalysisManager.h"
#include "AliCDBManager.h"
#include "AliEMCALGeometry.h"
#include "AliESDEvent.h"
#include "AliEmcalSetupTask.h"
#include "AliGeomManager.h"
#include "AliMagF.h"
#include "AliOADBContainer.h"
ClassImp(AliEmcalSetupTask)
//________________________________________________________________________
AliEmcalSetupTask::AliEmcalSetupTask() :
AliAnalysisTaskSE(),
fOcdbPath(),
fOadbPath("$ALICE_ROOT/OADB/EMCAL"),
fGeoPath("."),
fIsInit(kFALSE)
{
// Constructor.
}
//________________________________________________________________________
AliEmcalSetupTask::AliEmcalSetupTask(const char *name) :
AliAnalysisTaskSE(name),
fOcdbPath(),
fOadbPath("$ALICE_ROOT/OADB/EMCAL"),
fGeoPath("."),
fIsInit(kFALSE)
{
// Constructor.
fBranchNames = "ESD:AliESDHeader.,AliESDRun.";
}
//________________________________________________________________________
AliEmcalSetupTask::~AliEmcalSetupTask()
{
// Destructor.
}
//________________________________________________________________________
void AliEmcalSetupTask::UserExec(Option_t *)
{
// Main loop, called for each event.
if (fIsInit)
return;
AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();
if (!am) {
AliError("Manager zero, returning");
return;
}
am->LoadBranch("AliESDRun.");
am->LoadBranch("AliESDHeader.");
Int_t runno = InputEvent()->GetRunNumber();
TString geoname("EMCAL_FIRSTYEARV1");
Int_t year = 2010;
if (runno>139517) {
year = 2011;
geoname = "EMCAL_COMPLETEV1";
}
if (runno>170593) {
year = 2012;
geoname = "EMCAL_COMPLETE12SMV1";
}
AliEMCALGeometry *geom = AliEMCALGeometry::GetInstance(geoname);
if (!geom) {
AliFatal(Form("Can not create geometry: %s",geoname.Data()));
return;
}
AliCDBManager *man = 0;
if (fOcdbPath.Length()>0) {
AliInfo(Form("Setting up OCDB"));
man = AliCDBManager::Instance();
man->SetDefaultStorage(fOcdbPath);
man->SetRun(runno);
}
TGeoManager *geo = AliGeomManager::GetGeometry();
if (!geo) {
TString fname(gSystem->ExpandPathName(Form("%s/geometry_%d.root", fGeoPath.Data(), year)));
if (gSystem->AccessPathName(fname)==0) {
AliInfo(Form("Loading geometry from %s", fname.Data()));
AliGeomManager::LoadGeometry(fname);
} else if (man) {
AliInfo(Form("Loading geometry from OCDB"));
AliGeomManager::LoadGeometry();
}
}
if (geo) {
AliGeomManager::ApplyAlignObjsFromCDB("EMCAL");
AliInfo(Form("Locking geometry"));
geo->LockGeometry();
}
if (!TGeoGlobalMagField::Instance()->GetField()) { // construct field map
AliESDEvent *esdEv = dynamic_cast<AliESDEvent*>(InputEvent());
if (esdEv) {
AliInfo("Constructing field map from ESD run info");
esdEv->InitMagneticField();
} else {
AliAODEvent *aodEv = dynamic_cast<AliAODEvent*>(InputEvent());
Double_t curSol = 30000*aodEv->GetMagneticField()/5.00668;
Double_t curDip = 6000 *aodEv->GetMuonMagFieldScale();
AliMagF *field = AliMagF::CreateFieldMap(curSol,curDip);
TGeoGlobalMagField::Instance()->SetField(field);
}
}
if (fOadbPath.Length()>0) {
AliOADBContainer emcalgeoCont(Form("emcal"));
emcalgeoCont.InitFromFile(Form("%s/EMCALlocal2master.root",fOadbPath.Data()),
Form("AliEMCALgeo"));
TObjArray *mobj=dynamic_cast<TObjArray*>(emcalgeoCont.GetObject(runno,"EmcalMatrices"));
if (mobj) {
for(Int_t mod=0; mod < (geom->GetEMCGeometry())->GetNumberOfSuperModules(); mod++){
//AliInfo(Form("Misalignment matrix %d", mod));
geom->SetMisalMatrix((TGeoHMatrix*) mobj->At(mod),mod);
}
}
}
fIsInit = kTRUE;
}
<commit_msg>cosmetics<commit_after>// $Id$
//
// Task to setup emcal related global objects.
//
// Author: C.Loizides
#include "AliEmcalSetupTask.h"
#include <TClonesArray.h>
#include <TGeoGlobalMagField.h>
#include <TGeoManager.h>
#include "AliAODEvent.h"
#include "AliAnalysisManager.h"
#include "AliCDBManager.h"
#include "AliEMCALGeometry.h"
#include "AliESDEvent.h"
#include "AliGeomManager.h"
#include "AliMagF.h"
#include "AliOADBContainer.h"
ClassImp(AliEmcalSetupTask)
//________________________________________________________________________
AliEmcalSetupTask::AliEmcalSetupTask() :
AliAnalysisTaskSE(),
fOcdbPath(),
fOadbPath("$ALICE_ROOT/OADB/EMCAL"),
fGeoPath("."),
fIsInit(kFALSE)
{
// Constructor.
}
//________________________________________________________________________
AliEmcalSetupTask::AliEmcalSetupTask(const char *name) :
AliAnalysisTaskSE(name),
fOcdbPath(),
fOadbPath("$ALICE_ROOT/OADB/EMCAL"),
fGeoPath("."),
fIsInit(kFALSE)
{
// Constructor.
fBranchNames = "ESD:AliESDHeader.,AliESDRun.";
}
//________________________________________________________________________
AliEmcalSetupTask::~AliEmcalSetupTask()
{
// Destructor.
}
//________________________________________________________________________
void AliEmcalSetupTask::UserExec(Option_t *)
{
// Main loop, called for each event.
if (fIsInit)
return;
AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();
if (!am) {
AliError("Manager zero, returning");
return;
}
am->LoadBranch("AliESDRun.");
am->LoadBranch("AliESDHeader.");
Int_t runno = InputEvent()->GetRunNumber();
TString geoname("EMCAL_FIRSTYEARV1");
Int_t year = 2010;
if (runno>139517) {
year = 2011;
geoname = "EMCAL_COMPLETEV1";
}
if (runno>170593) {
year = 2012;
geoname = "EMCAL_COMPLETE12SMV1";
}
AliEMCALGeometry *geom = AliEMCALGeometry::GetInstance(geoname);
if (!geom) {
AliFatal(Form("Can not create geometry: %s",geoname.Data()));
return;
}
AliCDBManager *man = 0;
if (fOcdbPath.Length()>0) {
AliInfo(Form("Setting up OCDB"));
man = AliCDBManager::Instance();
man->SetDefaultStorage(fOcdbPath);
man->SetRun(runno);
}
TGeoManager *geo = AliGeomManager::GetGeometry();
if (!geo) {
TString fname(gSystem->ExpandPathName(Form("%s/geometry_%d.root", fGeoPath.Data(), year)));
if (gSystem->AccessPathName(fname)==0) {
AliInfo(Form("Loading geometry from %s", fname.Data()));
AliGeomManager::LoadGeometry(fname);
} else if (man) {
AliInfo(Form("Loading geometry from OCDB"));
AliGeomManager::LoadGeometry();
}
}
if (geo) {
AliGeomManager::ApplyAlignObjsFromCDB("EMCAL");
AliInfo(Form("Locking geometry"));
geo->LockGeometry();
}
if (!TGeoGlobalMagField::Instance()->GetField()) { // construct field map
AliESDEvent *esdEv = dynamic_cast<AliESDEvent*>(InputEvent());
if (esdEv) {
AliInfo("Constructing field map from ESD run info");
esdEv->InitMagneticField();
} else {
AliAODEvent *aodEv = dynamic_cast<AliAODEvent*>(InputEvent());
Double_t curSol = 30000*aodEv->GetMagneticField()/5.00668;
Double_t curDip = 6000 *aodEv->GetMuonMagFieldScale();
AliMagF *field = AliMagF::CreateFieldMap(curSol,curDip);
TGeoGlobalMagField::Instance()->SetField(field);
}
}
if (fOadbPath.Length()>0) {
AliOADBContainer emcalgeoCont(Form("emcal"));
emcalgeoCont.InitFromFile(Form("%s/EMCALlocal2master.root",fOadbPath.Data()),
Form("AliEMCALgeo"));
TObjArray *mobj=dynamic_cast<TObjArray*>(emcalgeoCont.GetObject(runno,"EmcalMatrices"));
if (mobj) {
for(Int_t mod=0; mod < (geom->GetEMCGeometry())->GetNumberOfSuperModules(); mod++){
//AliInfo(Form("Misalignment matrix %d", mod));
geom->SetMisalMatrix((TGeoHMatrix*) mobj->At(mod),mod);
}
}
}
fIsInit = kTRUE;
}
<|endoftext|> |
<commit_before>#include "RubyObject.h"
#include "common.h"
#include <vector>
#include <iostream>
using namespace std;
using namespace v8;
VALUE trueArg = Qtrue;
RubyObject::TplMap RubyObject::s_functionTemplates;
Local<Function> RubyObject::GetClass(VALUE klass)
{
HandleScope scope;
Persistent<FunctionTemplate> persistTpl;
TplMap::iterator it = s_functionTemplates.find(klass);
if (it == s_functionTemplates.end()) {
log("Creating new class: " << rb_class2name(klass) << endl);
Local<FunctionTemplate> tpl = FunctionTemplate::New(New, External::Wrap((void*)klass));
tpl->SetClassName(String::NewSymbol(rb_class2name(klass)));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
VALUE methods = rb_class_public_instance_methods(1, &trueArg, klass);
for (int i = 0; i < RARRAY_LEN(methods); i++) {
ID methodID = SYM2ID(rb_ary_entry(methods, i));
Local<String> methodName = String::New(rb_id2name(methodID));
Local<FunctionTemplate> methodTemplate =
FunctionTemplate::New(CallMethod, External::Wrap((void*)methodID));
tpl->PrototypeTemplate()->Set(methodName, methodTemplate->GetFunction());
}
persistTpl = s_functionTemplates[klass] = Persistent<FunctionTemplate>::New(tpl);
}
else {
log("Getting existing class: " << rb_class2name(klass) << endl);
persistTpl = it->second;
}
Local<Function> ctor = persistTpl->GetFunction();
return scope.Close(ctor);
}
struct NewInstanceCaller
{
NewInstanceCaller(std::vector<VALUE> &r, VALUE k, void* d) :
rubyArgs(r), klass(k), data(d) {}
VALUE operator()() const
{
if (data == NULL) {
return rb_class_new_instance(rubyArgs.size(), &rubyArgs[0], klass);
}
else {
VALUE obj = Data_Wrap_Struct(klass, NULL, NULL, data);
rb_obj_call_init(obj, rubyArgs.size(), &rubyArgs[0]);
return obj;
}
}
std::vector<VALUE>& rubyArgs;
VALUE klass;
void* data;
};
Handle<Value> RubyObject::New(const Arguments& args)
{
HandleScope scope;
if (args.IsConstructCall()) {
VALUE klass = VALUE(External::Unwrap(args.Data()));
// TODO: This has serious GC implications. Make weak? When can we delete the ptr?
Persistent<Object>* owner = NULL;
if (!args[0]->IsUndefined())
owner = new Persistent<Object>(Persistent<Object>::New(args[0].As<Object>()));
Local<Array> v8Args = args[1].As<Array>();
std::vector<VALUE> rubyArgs(v8Args->Length());
for (uint32_t i = 0; i < v8Args->Length(); i++) {
rubyArgs[i] = v8ToRuby(v8Args->Get(i));
}
log("Creating new " << rb_class2name(klass) << " with " << rubyArgs.size() << " args" << endl);
VALUE ex;
VALUE obj = SafeRubyCall(NewInstanceCaller(rubyArgs, klass, owner), ex);
if (ex != Qnil) {
ThrowException(rubyExToV8(ex));
return scope.Close(Undefined());
}
// Wrap the obj immediately to prevent it from being garbage collected
RubyObject *self = new RubyObject(obj);
self->Wrap(args.This());
return scope.Close(args.This());
}
else {
// TODO: Do we even need this?
std::vector<Handle<Value> > argv(args.Length());
for (int i = 0; i < args.Length(); i++) {
argv[i] = args[i];
}
VALUE klass = VALUE(External::Unwrap(args.Data()));
Local<Function> cons = RubyObject::GetClass(klass);
return scope.Close(cons->NewInstance(args.Length(), &argv[0]));
}
}
RubyObject::RubyObject(VALUE obj) : m_obj(obj)
{
rb_gc_register_address(&m_obj);
}
RubyObject::~RubyObject()
{
log("~RubyObject" << endl);
rb_gc_unregister_address(&m_obj);
}
struct MethodCaller
{
MethodCaller(VALUE o, VALUE m, const Arguments& args) :
obj(o), methodID(m), rubyArgs(args.Length())
{
// TODO: Is this right? Is there a way to determine if a block is expected?
if (args.Length() > 0 && args[args.Length()-1]->IsFunction()) {
log("Got a func!" << endl);
block = args[args.Length()-1].As<Function>();
rubyArgs.resize(args.Length()-1);
}
for (size_t i = 0; i < rubyArgs.size(); i++) {
rubyArgs[i] = v8ToRuby(args[i]);
}
}
VALUE operator()() const
{
log("Calling method: " << rb_id2name(methodID) << " with " << rubyArgs.size() << " args");
if (block.IsEmpty()) {
log(endl);
return rb_funcall2(obj, methodID, rubyArgs.size(), (VALUE*)&rubyArgs[0]);
}
else {
log(" and a block" << endl);
// TODO: Probably not available in Ruby < 1.9
return rb_block_call(obj, methodID, rubyArgs.size(),
(VALUE*)&rubyArgs[0], RUBY_METHOD_FUNC(BlockFunc),
(VALUE)this);
}
}
static VALUE BlockFunc(VALUE, VALUE data, int argc, const VALUE* rbArgv)
{
MethodCaller* self = reinterpret_cast<MethodCaller*>(data);
return CallV8FromRuby(Context::GetCurrent()->Global(), self->block,
argc, rbArgv);
}
VALUE obj;
VALUE methodID;
std::vector<VALUE> rubyArgs;
// TODO: Should this be persistent?
Local<Function> block;
};
Handle<Value> RubyObject::CallMethod(const Arguments& args)
{
HandleScope scope;
RubyObject *self = node::ObjectWrap::Unwrap<RubyObject>(args.This());
ID methodID = ID(External::Unwrap(args.Data()));
VALUE ex;
VALUE res = SafeRubyCall(MethodCaller(self->m_obj, methodID, args), ex);
if (ex != Qnil) {
return scope.Close(ThrowException(rubyExToV8(ex)));
}
return scope.Close(rubyToV8(res));
}
<commit_msg>Fixed mem leaks when inheriting<commit_after>#include "RubyObject.h"
#include "common.h"
#include <vector>
#include <iostream>
using namespace std;
using namespace v8;
VALUE trueArg = Qtrue;
RubyObject::TplMap RubyObject::s_functionTemplates;
Local<Function> RubyObject::GetClass(VALUE klass)
{
HandleScope scope;
Persistent<FunctionTemplate> persistTpl;
TplMap::iterator it = s_functionTemplates.find(klass);
if (it == s_functionTemplates.end()) {
log("Creating new class: " << rb_class2name(klass) << endl);
Local<FunctionTemplate> tpl = FunctionTemplate::New(New, External::Wrap((void*)klass));
tpl->SetClassName(String::NewSymbol(rb_class2name(klass)));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
VALUE methods = rb_class_public_instance_methods(1, &trueArg, klass);
for (int i = 0; i < RARRAY_LEN(methods); i++) {
ID methodID = SYM2ID(rb_ary_entry(methods, i));
Local<String> methodName = String::New(rb_id2name(methodID));
Local<FunctionTemplate> methodTemplate =
FunctionTemplate::New(CallMethod, External::Wrap((void*)methodID));
tpl->PrototypeTemplate()->Set(methodName, methodTemplate->GetFunction());
}
persistTpl = s_functionTemplates[klass] = Persistent<FunctionTemplate>::New(tpl);
}
else {
log("Getting existing class: " << rb_class2name(klass) << endl);
persistTpl = it->second;
}
Local<Function> ctor = persistTpl->GetFunction();
return scope.Close(ctor);
}
void OwnerWeakCB(Persistent<Value> value, void *data)
{
assert(value.IsNearDeath());
value.ClearWeak();
value.Dispose();
value.Clear();
Persistent<Object>* owner = static_cast<Persistent<Object>*>(data);
delete owner;
}
struct NewInstanceCaller
{
NewInstanceCaller(std::vector<VALUE> &r, VALUE k, void* d) :
rubyArgs(r), klass(k), data(d) {}
VALUE operator()() const
{
if (data == NULL) {
return rb_class_new_instance(rubyArgs.size(), &rubyArgs[0], klass);
}
else {
VALUE obj = Data_Wrap_Struct(klass, NULL, NULL, data);
rb_obj_call_init(obj, rubyArgs.size(), &rubyArgs[0]);
return obj;
}
}
std::vector<VALUE>& rubyArgs;
VALUE klass;
void* data;
};
Handle<Value> RubyObject::New(const Arguments& args)
{
HandleScope scope;
if (args.IsConstructCall()) {
VALUE klass = VALUE(External::Unwrap(args.Data()));
Persistent<Object>* owner = NULL;
if (!args[0]->IsUndefined()) {
owner = new Persistent<Object>(Persistent<Object>::New(args[0].As<Object>()));
owner->MakeWeak(owner, OwnerWeakCB);
// TODO: Keep this?
owner->MarkIndependent();
}
Local<Array> v8Args = args[1].As<Array>();
std::vector<VALUE> rubyArgs(v8Args->Length());
for (uint32_t i = 0; i < v8Args->Length(); i++) {
rubyArgs[i] = v8ToRuby(v8Args->Get(i));
}
log("Creating new " << rb_class2name(klass) << " with " << rubyArgs.size() << " args" << endl);
VALUE ex;
VALUE obj = SafeRubyCall(NewInstanceCaller(rubyArgs, klass, owner), ex);
if (ex != Qnil) {
ThrowException(rubyExToV8(ex));
return scope.Close(Undefined());
}
// Wrap the obj immediately to prevent it from being garbage collected
RubyObject *self = new RubyObject(obj);
self->Wrap(args.This());
return scope.Close(args.This());
}
else {
// TODO: Do we even need this?
std::vector<Handle<Value> > argv(args.Length());
for (int i = 0; i < args.Length(); i++) {
argv[i] = args[i];
}
VALUE klass = VALUE(External::Unwrap(args.Data()));
Local<Function> cons = RubyObject::GetClass(klass);
return scope.Close(cons->NewInstance(args.Length(), &argv[0]));
}
}
RubyObject::RubyObject(VALUE obj) : m_obj(obj)
{
rb_gc_register_address(&m_obj);
}
RubyObject::~RubyObject()
{
log("~RubyObject" << endl);
rb_gc_unregister_address(&m_obj);
}
struct MethodCaller
{
MethodCaller(VALUE o, VALUE m, const Arguments& args) :
obj(o), methodID(m), rubyArgs(args.Length())
{
// TODO: Is this right? Is there a way to determine if a block is expected?
if (args.Length() > 0 && args[args.Length()-1]->IsFunction()) {
log("Got a func!" << endl);
block = args[args.Length()-1].As<Function>();
rubyArgs.resize(args.Length()-1);
}
for (size_t i = 0; i < rubyArgs.size(); i++) {
rubyArgs[i] = v8ToRuby(args[i]);
}
}
VALUE operator()() const
{
log("Calling method: " << rb_id2name(methodID) << " with " << rubyArgs.size() << " args");
if (block.IsEmpty()) {
log(endl);
return rb_funcall2(obj, methodID, rubyArgs.size(), (VALUE*)&rubyArgs[0]);
}
else {
log(" and a block" << endl);
// TODO: Probably not available in Ruby < 1.9
return rb_block_call(obj, methodID, rubyArgs.size(),
(VALUE*)&rubyArgs[0], RUBY_METHOD_FUNC(BlockFunc),
(VALUE)this);
}
}
static VALUE BlockFunc(VALUE, VALUE data, int argc, const VALUE* rbArgv)
{
MethodCaller* self = reinterpret_cast<MethodCaller*>(data);
return CallV8FromRuby(Context::GetCurrent()->Global(), self->block,
argc, rbArgv);
}
VALUE obj;
VALUE methodID;
std::vector<VALUE> rubyArgs;
// TODO: Should this be persistent?
Local<Function> block;
};
Handle<Value> RubyObject::CallMethod(const Arguments& args)
{
HandleScope scope;
RubyObject *self = node::ObjectWrap::Unwrap<RubyObject>(args.This());
ID methodID = ID(External::Unwrap(args.Data()));
VALUE ex;
VALUE res = SafeRubyCall(MethodCaller(self->m_obj, methodID, args), ex);
if (ex != Qnil) {
return scope.Close(ThrowException(rubyExToV8(ex)));
}
return scope.Close(rubyToV8(res));
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
#include <omp.h>
#include "readjpeg.h"
void normalize( float * kernel ) {
int sum = 0;
for (int i = 0; i < 25; i++ ) {
sum += kernel[i];
}
for (int i = 0; i < 25 && sum != 0; i++ ) {
kernel[i] /= sum;
}
}
typedef struct
{
float r;
float g;
float b;
} pixel_t;
double timestamp()
{
struct timeval tv;
gettimeofday (&tv, 0);
return tv.tv_sec + 1e-6*tv.tv_usec;
}
void blur_frame(int width, int height, float* kernel, pixel_t *in, pixel_t *out){
}
void convert_to_pixel(pixel_t *out, frame_ptr in)
{
for(int y = 0; y < in->image_height; y++)
{
for(int x = 0; x < in->image_width; x++)
{
int r = (int)in->row_pointers[y][in->num_components*x + 0 ];
int g = (int)in->row_pointers[y][in->num_components*x + 1 ];
int b = (int)in->row_pointers[y][in->num_components*x + 2 ];
out[y*in->image_width+x].r = (float)r;
out[y*in->image_width+x].g = (float)g;
out[y*in->image_width+x].b = (float)b;
}
}
}
void convert_to_frame(frame_ptr out, pixel_t *in)
{
for(int y = 0; y < out->image_height; y++)
{
for(int x = 0; x < out->image_width; x++)
{
int r = (int)in[y*out->image_width + x].r;
int g = (int)in[y*out->image_width + x].g;
int b = (int)in[y*out->image_width + x].b;
out->row_pointers[y][out->num_components*x + 0 ] = r;
out->row_pointers[y][out->num_components*x + 1 ] = g;
out->row_pointers[y][out->num_components*x + 2 ] = b;
}
}
}
#define KERNX 5 //this is the x-size of the kernel. It will always be odd.
#define KERNY 5 //this is the y-size of the kernel. It will always be odd.
int conv2D(int data_size_X, int data_size_Y,
float* kernel, pixel_t* in, pixel_t* out)
{
// the x coordinate of the kernel's center
int kern_cent_X = (KERNX - 1)/2;
// the y coordinate of the kernel's center
int kern_cent_Y = (KERNY - 1)/2;
// main convolution loop
for(int x = 0; x < data_size_X; x++){ // the x coordinate of the output location we're focusing on
for(int y = 0; y < data_size_Y; y++){ // the y coordinate of theoutput location we're focusing on
for(int i = -kern_cent_X; i <= kern_cent_X; i++){ // kernel unflipped x coordinate
for(int j = -kern_cent_Y; j <= kern_cent_Y; j++){ // kernel unflipped y coordinate
// only do the operation if not out of bounds
if(x+i>-1 && x+i<data_size_X && y+j>-1 && y+j<data_size_Y){
//Note that the kernel is flipped
out[x+y*data_size_X].r +=
kernel[(kern_cent_X-i)+(kern_cent_Y-j)*KERNX] * in[(x+i) + (y+j)*data_size_X].r;
out[x+y*data_size_X].g +=
kernel[(kern_cent_X-i)+(kern_cent_Y-j)*KERNX] * in[(x+i) + (y+j)*data_size_X].g;
out[x+y*data_size_X].b +=
kernel[(kern_cent_X-i)+(kern_cent_Y-j)*KERNX] * in[(x+i) + (y+j)*data_size_X].b;
}
}
}
}
}
for (int i=0; i<data_size_X*data_size_Y; i++){
if (out[i].r<0){
out[i].r=0;
}
if (out[i].r>255){
out[i].r=255;
}
if (out[i].g<0){
out[i].g=0;
}
if (out[i].g>255){
out[i].g=255;
}
if (out[i].b<0){
out[i].b=0;
}
if (out[i].b>255){
out[i].b=255;
}
}
return 1;
}
int main(int argc, char *argv[])
{
float kernel_0[] = { 0, 0, 0, 0, 0, // "sharpen"
0, 0,-1, 0, 0,
0,-1, 5,-1, 0,
0, 0,-1, 0, 0,
0, 0, 0, 0, 0, }; normalize(kernel_0);
float kernel_1[]={ 1, 1, 1, 1, 1, // blur
1, 1, 1, 1, 1,
1, 1, 1, 1, 1,
1, 1, 1, 1, 1,
1, 1, 1, 1, 1, }; normalize(kernel_1);
float kernel_2[] = { 0, 0, 0, 0, 0, // darken
0, 0, 0, 0, 0,
0, 0,0.5, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0, };
float kernel_3[]={1,1,1,1,1, // weighted mean filter
1,2,2,2,1,
1,2,3,2,1,
1,2,2,2,1,
1,1,1,1,1, }; normalize(kernel_3);
float kernel_4[] = { 0, 0, 0, 0, 0, // "edge detect"
0, 1, 0,-1, 0,
0, 0, 0, 0, 0,
0,-1, 0, 1, 0,
0, 0, 0, 0, 0, };
float kernel_5[] = { 0, 0, 0, 0, 0, // "emboss"
0,-2,-1, 0, 0,
0,-1, 1, 1, 0,
0, 0, 1, 2, 0,
0, 0, 0, 0, 0, };
float kernel_6[] = {-1,-1,-1,-1,-1, // "edge detect"
-1,-1,-1,-1,-1,
-1,-1,24,-1,-1,
-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1, };
float* kernels[7] = {kernel_0, kernel_1, kernel_2, kernel_3, kernel_4,
kernel_5, kernel_6};
int c;
char *inName = NULL;
char *outName = NULL;
int width=-1,height=-1;
int kernel_num = 1;
frame_ptr frame;
pixel_t *inPix=NULL;
pixel_t *outPix=NULL;
while((c = getopt(argc, argv, "i:k:o:"))!=-1)
{
switch(c)
{
case 'i':
inName = optarg;
break;
case 'o':
outName = optarg;
break;
case 'k':
kernel_num = atoi(optarg);
break;
}
}
inName = inName==0 ? (char*)"cpt-kurt.jpg" : inName;
outName = outName==0 ? (char*)"output.jpg" : outName;
frame = read_JPEG_file(inName);
if(!frame)
{
printf("unable to read %s\n", inName);
exit(-1);
}
width = frame->image_width;
height = frame->image_height;
inPix = new pixel_t[width*height];
outPix = new pixel_t[width*height];
for (int i=0; i<width*height; i++){
outPix[i].r = 0;
outPix[i].g = 0;
outPix[i].b = 0;
}
convert_to_pixel(inPix, frame);
float* kernel = kernels[kernel_num];
double t0 = timestamp();
conv2D(width, height, kernel, inPix, outPix);
t0 = timestamp() - t0;
printf("%g sec\n", t0);
convert_to_frame(frame, outPix);
write_JPEG_file(outName,frame,75);
destroy_frame(frame);
delete [] inPix;
delete [] outPix;
return 0;
}
<commit_msg>Serial code not working<commit_after>#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
#include <omp.h>
#include "readjpeg.h"
void normalize( float * kernel ) {
int sum = 0;
for (int i = 0; i < 25; i++ ) {
sum += kernel[i];
}
for (int i = 0; i < 25 && sum != 0; i++ ) {
kernel[i] /= sum;
}
}
typedef struct
{
float r;
float g;
float b;
} pixel_t;
double timestamp()
{
struct timeval tv;
gettimeofday (&tv, 0);
return tv.tv_sec + 1e-6*tv.tv_usec;
}
void blur_frame(int width, int height, float* kernel, pixel_t *in, pixel_t *out){
}
void convert_to_pixel(pixel_t *out, frame_ptr in)
{
for(int y = 0; y < in->image_height; y++)
{
for(int x = 0; x < in->image_width; x++)
{
int r = (int)in->row_pointers[y][in->num_components*x + 0 ];
int g = (int)in->row_pointers[y][in->num_components*x + 1 ];
int b = (int)in->row_pointers[y][in->num_components*x + 2 ];
out[y*in->image_width+x].r = (float)r;
out[y*in->image_width+x].g = (float)g;
out[y*in->image_width+x].b = (float)b;
}
}
}
void convert_to_frame(frame_ptr out, pixel_t *in)
{
for(int y = 0; y < out->image_height; y++)
{
for(int x = 0; x < out->image_width; x++)
{
int r = (int)in[y*out->image_width + x].r;
int g = (int)in[y*out->image_width + x].g;
int b = (int)in[y*out->image_width + x].b;
out->row_pointers[y][out->num_components*x + 0 ] = r;
out->row_pointers[y][out->num_components*x + 1 ] = g;
out->row_pointers[y][out->num_components*x + 2 ] = b;
}
}
}
#define KERNX 5 //this is the x-size of the kernel. It will always be odd.
#define KERNY 5 //this is the y-size of the kernel. It will always be odd.
int conv2D(int cols, int rows, float* kernel, pixel_t* input, pixel_t* output) {
int x, y;
int i, j;
int m, z;
int a;
int AR[150];
int AG[150];
int AB[150];
int kern_cent = (KERNX - 1)/2;
for(y = 0; y < cols; y++)
for(x = 0; x < rows; x++)
{
z = 0;
for(j = -kern_cent; j <= kern_cent; j++)
for(i = -kern_cent; i <= kern_cent; i++)
{
for(m = 1; m <= kernel[(kern_cent+i)+(kern_cent+j)*KERNX]; m++)
{
AR[z] = input[(x+i) + (y+j)*cols].r;
AG[z] = input[(x+i) + (y+j)*cols].g;
AB[z] = input[(x+i) + (y+j)*cols].b;
z++;
}
}
for(j = 1; j < (z-1); j++)
{
a = AR[j];
i = j-1;
while(i >= 0 && AR[i] > a)
{
AR[i+1] = AR[i];
i = i-1;
}
AR[i+1] = a;
}
output[x+y*cols].r = AR[z/2];
output[x+y*cols].g = AG[z/2];
output[x+y*cols].b = AB[z/2];
}
return 1;
}
int main(int argc, char *argv[])
{
float kernel_0[] = { 0, 0, 0, 0, 0, // "sharpen"
0, 0,-1, 0, 0,
0,-1, 5,-1, 0,
0, 0,-1, 0, 0,
0, 0, 0, 0, 0, }; normalize(kernel_0);
float kernel_1[]={ 1, 1, 1, 1, 1, // blur
1, 1, 1, 1, 1,
1, 1, 1, 1, 1,
1, 1, 1, 1, 1,
1, 1, 1, 1, 1, }; normalize(kernel_1);
float kernel_2[] = { 0, 0, 0, 0, 0, // darken
0, 0, 0, 0, 0,
0, 0,0.5, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0, };
float kernel_3[]={1,1,1,1,1, // weighted mean filter
1,2,2,2,1,
1,2,3,2,1,
1,2,2,2,1,
1,1,1,1,1, }; normalize(kernel_3);
float kernel_4[] = { 0, 0, 0, 0, 0, // "edge detect"
0, 1, 0,-1, 0,
0, 0, 0, 0, 0,
0,-1, 0, 1, 0,
0, 0, 0, 0, 0, };
float kernel_5[] = { 0, 0, 0, 0, 0, // "emboss"
0,-2,-1, 0, 0,
0,-1, 1, 1, 0,
0, 0, 1, 2, 0,
0, 0, 0, 0, 0, };
float kernel_6[] = {-1,-1,-1,-1,-1, // "edge detect"
-1,-1,-1,-1,-1,
-1,-1,24,-1,-1,
-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1, };
float* kernels[7] = {kernel_0, kernel_1, kernel_2, kernel_3, kernel_4,
kernel_5, kernel_6};
int c;
char *inName = NULL;
char *outName = NULL;
int width=-1,height=-1;
int kernel_num = 1;
frame_ptr frame;
pixel_t *inPix=NULL;
pixel_t *outPix=NULL;
while((c = getopt(argc, argv, "i:k:o:"))!=-1)
{
switch(c)
{
case 'i':
inName = optarg;
break;
case 'o':
outName = optarg;
break;
case 'k':
kernel_num = atoi(optarg);
break;
}
}
inName = inName==0 ? (char*)"cpt-kurt.jpg" : inName;
outName = outName==0 ? (char*)"output.jpg" : outName;
frame = read_JPEG_file(inName);
if(!frame)
{
printf("unable to read %s\n", inName);
exit(-1);
}
width = frame->image_width;
height = frame->image_height;
inPix = new pixel_t[width*height];
outPix = new pixel_t[width*height];
for (int i=0; i<width*height; i++){
outPix[i].r = 0;
outPix[i].g = 0;
outPix[i].b = 0;
}
convert_to_pixel(inPix, frame);
float* kernel = kernels[kernel_num];
double t0 = timestamp();
conv2D(width, height, kernel, inPix, outPix);
t0 = timestamp() - t0;
printf("%g sec\n", t0);
convert_to_frame(frame, outPix);
write_JPEG_file(outName,frame,75);
destroy_frame(frame);
delete [] inPix;
delete [] outPix;
return 0;
}
<|endoftext|> |
<commit_before>#include "./include/bot.hpp"
#include "./include/packet.hpp"
#include "./include/server.hpp"
#include <thread>
#include <mutex>
namespace IRC {
Bot::Bot(const std::string& n, const std::string& pass, const std::vector<std::string>& _admins)
: nick(n) , password(pass),
start_time(std::chrono::system_clock::now()), packets_received(0), packets_sent(0), commands_executed(0)
{
std::lock_guard<std::mutex> guard(admins_mutex); // just in case, because admins is a shared resource and should always be protected.
for (auto& a : _admins)
admins.push_back(a);
}
Bot::~Bot() {
for (Server* s : servers) {
if (s)
delete s;
}
std::lock_guard<std::mutex> guard(commands_mutex);
for (CommandInterface* c : commands) {
if (c)
delete c;
}
}
void Bot::add_server(std::string n , const std::string& a , const int& port, bool with_ssl) {
for (const Server* s : servers) {
if (s->get_name() == n)
n.append("_");
}
servers.push_back( new Server(n , a , port, with_ssl) );
}
void Bot::connect_server(const std::string& server_name) {
auto it = _find_server_by_name(server_name);
if (it == servers.end())
return;
(*it)->start_connect();
(*it)->log_on(nick, password);
}
bool Bot::join_channel(const std::string& server_name , const std::string& channel_name) {
auto it = _find_server_by_name(server_name);
if (it == servers.end())
return false;
(*it)->join_channel(channel_name);
return true;
}
void Bot::add_a(const Bot::RELATIONSHIP& r , const std::string& user) {
switch(r) {
case RELATIONSHIP::ADMIN:
std::lock_guard<std::mutex> guard(admins_mutex);
admins.push_back(user);
break; // this is important!
case RELATIONSHIP::IGNORED:
std::lock_guard<std::mutex> guard(ignored_mutex);
ignored.push_back(user);
break;
}
}
void Bot::add_command( CommandInterface* cmd ) {
if (cmd->bot() != nullptr && cmd->bot() != this) {
std::cerr << "You tried to add a command that references a different bot.\n";
delete cmd;
return;
}
std::lock_guard<std::mutex> guard(commands_mutex);
commands.push_back(cmd);
}
void Bot::listen() {
std::vector<std::thread> threads;
for (Server* s : servers) {
threads.push_back(std::thread([this, s]{this->_listen_to_server(s);} ));
}
for (auto& t : threads)
t.join();
}
void Bot::_listen_to_server(Server* s) {
bool got_resp = true; /* checks if at least one server gives resp. */
while(got_resp) {
got_resp = false;
Packet p;
try {
p = s->receive();
} catch (std::exception& e) {
std::cerr << e.what() << '\n';
continue;
}
p.owner = s;
if (p.is_valid()) {
this->packets_received++;
this->_check_for_triggers(p);
got_resp = true;
}
got_resp = got_resp || !p.content.empty();
}
}
/* helpers */
void Bot::_check_for_triggers(const Packet& p) {
bool sender_is_admin = _is_admin(p.sender);
bool sender_is_ignored = _is_ignored(p.sender);
/* These are default commands, raw functionality, internal stuff... */
if (p.type == Packet::PacketType::NICK) {
/* update admins and ignored based on nick changes. */
std::unique_lock<std::mutex> guard_admin(admins_mutex); // using unique lock so that I can unlock before scope ends.
for (auto& s : admins)
if (s == p.sender)
s = p.content;
guard_admin.unlock();
std::lock_guard<std::mutex> guard_ignored(ignored_mutex);
for (auto& i : ignored)
if (i == p.sender)
i = p.content;
// not unlocking because Scope ends anyway.
} else if (p.type == Packet::PacketType::PRIVMSG && !sender_is_ignored) {
if (p.content.substr(0, 5) == "@help") {
std::lock_guard<std::mutex> guard(commands_mutex);
for (const auto command : this->commands) {
if (sender_is_admin || !command->requires_admin())
p.owner->privmsg(p.sender, command->trigger() + ": " + command->desc());
}
return;
} else if (p.content.substr(0, 6) == "@stats" && sender_is_admin) {
for (const auto& s : this->get_stats()) {
p.owner->privmsg(p.sender , s);
}
std::lock_guard<std::mutex> guard(commands_mutex);
for (const auto command : this->commands) {
p.owner->privmsg(p.sender, command->get_stats());
}
}
} else if (p.type == Packet::PacketType::INVITE && sender_is_admin) {
p.owner->join_channel( p.content );
} else if (p.type == Packet::PacketType::KICK) {
p.owner->join_channel( p.channel );
}
if (sender_is_ignored)
return;
std::lock_guard<std::mutex> guard(commands_mutex);
/* Here we go through the user-added Commands */
for (auto command : this->commands) { /* checks sender's perms.... */
if (command->triggered(p) && (sender_is_admin || !command->requires_admin())) {
command->run(p);
std::lock_guard<std::mutex> guard(stat_mutex); // stat-tracking commands requires this :)
this->commands_executed++;
}
}
}
// TODO: Just return Server*'s for less overhead and bullsh*t
std::vector<Server*>::iterator Bot::_find_server_by_name(const std::string& n) {
for (size_t i = 0; i < servers.size(); ++i) {
if (servers.at(i)->get_name() == n) {
return servers.begin() + i;
}
}
return servers.end();
}
bool Bot::_is_admin(const std::string& person) {
std::lock_guard<std::mutex> guard(this->admins_mutex); // protect admins
for (auto& a : admins)
if (a == person)
return true;
std::cout << person << " is not an admin.\n";
return false;
}
bool Bot::_is_ignored(const std::string& person) {
std::lock_guard<std::mutex> guard(this->ignored_mutex); // protect ignore list.
for (auto& a : ignored)
if (a == person)
return true;
return false;
}
std::vector<std::string> Bot::get_stats(void) {
std::lock_guard<std::mutex> guard(this->stat_mutex);
time_t t = std::chrono::system_clock::to_time_t(start_time);
return std::vector<std::string>{ "Up Since: " + std::string(std::ctime(&t)),
"Packets Received: " + std::to_string(this->packets_received),
"Packets Sent: " + std::to_string(this->packets_sent),
"Commands Executed: " + std::to_string(this->commands_executed)
};
}
};
<commit_msg>fix compliation errors caused by changes from last commit :)<commit_after>#include "./include/bot.hpp"
#include "./include/packet.hpp"
#include "./include/server.hpp"
#include <thread>
#include <mutex>
namespace IRC {
Bot::Bot(const std::string& n, const std::string& pass, const std::vector<std::string>& _admins)
: nick(n) , password(pass),
start_time(std::chrono::system_clock::now()), packets_received(0), packets_sent(0), commands_executed(0)
{
std::lock_guard<std::mutex> guard(admin_mutex); // just in case, because admins is a shared resource and should always be protected.
for (auto& a : _admins)
admins.push_back(a);
}
Bot::~Bot() {
for (Server* s : servers) {
if (s)
delete s;
}
std::lock_guard<std::mutex> guard(commands_mutex);
for (CommandInterface* c : commands) {
if (c)
delete c;
}
}
void Bot::add_server(std::string n , const std::string& a , const int& port, bool with_ssl) {
for (const Server* s : servers) {
if (s->get_name() == n)
n.append("_");
}
servers.push_back( new Server(n , a , port, with_ssl) );
}
void Bot::connect_server(const std::string& server_name) {
auto it = _find_server_by_name(server_name);
if (it == servers.end())
return;
(*it)->start_connect();
(*it)->log_on(nick, password);
}
bool Bot::join_channel(const std::string& server_name , const std::string& channel_name) {
auto it = _find_server_by_name(server_name);
if (it == servers.end())
return false;
(*it)->join_channel(channel_name);
return true;
}
void Bot::add_a(const Bot::RELATIONSHIP& r , const std::string& user) {
switch(r) {
case RELATIONSHIP::ADMIN: {
std::lock_guard<std::mutex> guard_admin(admin_mutex);
admins.push_back(user);
break; // this is important!
} case RELATIONSHIP::IGNORED: {
std::lock_guard<std::mutex> guard_ignored(ignored_mutex);
ignored.push_back(user);
break;
}}
}
void Bot::add_command( CommandInterface* cmd ) {
if (cmd->bot() != nullptr && cmd->bot() != this) {
std::cerr << "You tried to add a command that references a different bot.\n";
delete cmd;
return;
}
std::lock_guard<std::mutex> guard(commands_mutex);
commands.push_back(cmd);
}
void Bot::listen() {
std::vector<std::thread> threads;
for (Server* s : servers) {
threads.push_back(std::thread([this, s]{this->_listen_to_server(s);} ));
}
for (auto& t : threads)
t.join();
}
void Bot::_listen_to_server(Server* s) {
bool got_resp = true; /* checks if at least one server gives resp. */
while(got_resp) {
got_resp = false;
Packet p;
try {
p = s->receive();
} catch (std::exception& e) {
std::cerr << e.what() << '\n';
continue;
}
p.owner = s;
if (p.is_valid()) {
this->packets_received++;
this->_check_for_triggers(p);
got_resp = true;
}
got_resp = got_resp || !p.content.empty();
}
}
/* helpers */
void Bot::_check_for_triggers(const Packet& p) {
bool sender_is_admin = _is_admin(p.sender);
bool sender_is_ignored = _is_ignored(p.sender);
/* These are default commands, raw functionality, internal stuff... */
if (p.type == Packet::PacketType::NICK) {
/* update admins and ignored based on nick changes. */
std::unique_lock<std::mutex> guard_admin(admin_mutex); // using unique lock so that I can unlock before scope ends.
for (auto& s : admins)
if (s == p.sender)
s = p.content;
guard_admin.unlock();
std::lock_guard<std::mutex> guard_ignored(ignored_mutex);
for (auto& i : ignored)
if (i == p.sender)
i = p.content;
// not unlocking because Scope ends anyway.
} else if (p.type == Packet::PacketType::PRIVMSG && !sender_is_ignored) {
if (p.content.substr(0, 5) == "@help") {
std::lock_guard<std::mutex> guard(commands_mutex);
for (const auto command : this->commands) {
if (sender_is_admin || !command->requires_admin())
p.owner->privmsg(p.sender, command->trigger() + ": " + command->desc());
}
return;
} else if (p.content.substr(0, 6) == "@stats" && sender_is_admin) {
for (const auto& s : this->get_stats()) {
p.owner->privmsg(p.sender , s);
}
std::lock_guard<std::mutex> guard(commands_mutex);
for (const auto command : this->commands) {
p.owner->privmsg(p.sender, command->get_stats());
}
}
} else if (p.type == Packet::PacketType::INVITE && sender_is_admin) {
p.owner->join_channel( p.content );
} else if (p.type == Packet::PacketType::KICK) {
p.owner->join_channel( p.channel );
}
if (sender_is_ignored)
return;
std::lock_guard<std::mutex> guard(commands_mutex);
/* Here we go through the user-added Commands */
for (auto command : this->commands) { /* checks sender's perms.... */
if (command->triggered(p) && (sender_is_admin || !command->requires_admin())) {
command->run(p);
std::lock_guard<std::mutex> guard(stat_mutex); // stat-tracking commands requires this :)
this->commands_executed++;
}
}
}
// TODO: Just return Server*'s for less overhead and bullsh*t
std::vector<Server*>::iterator Bot::_find_server_by_name(const std::string& n) {
for (size_t i = 0; i < servers.size(); ++i) {
if (servers.at(i)->get_name() == n) {
return servers.begin() + i;
}
}
return servers.end();
}
bool Bot::_is_admin(const std::string& person) {
std::lock_guard<std::mutex> guard(this->admin_mutex); // protect admins
for (auto& a : admins)
if (a == person)
return true;
std::cout << person << " is not an admin.\n";
return false;
}
bool Bot::_is_ignored(const std::string& person) {
std::lock_guard<std::mutex> guard(this->ignored_mutex); // protect ignore list.
for (auto& a : ignored)
if (a == person)
return true;
return false;
}
std::vector<std::string> Bot::get_stats(void) {
std::lock_guard<std::mutex> guard(this->stat_mutex);
time_t t = std::chrono::system_clock::to_time_t(start_time);
return std::vector<std::string>{ "Up Since: " + std::string(std::ctime(&t)),
"Packets Received: " + std::to_string(this->packets_received),
"Packets Sent: " + std::to_string(this->packets_sent),
"Commands Executed: " + std::to_string(this->commands_executed)
};
}
};
<|endoftext|> |
<commit_before>#include "TpObserver.h"
TpObserver::TpObserver (const ChannelClassList &channelFilter,
QObject *parent )
: AbstractClientObserver(channelFilter)
, IObserver (parent)
, id(1) // Always ignore
{
}//TpObserver::TpObserver
void
TpObserver::setId (int i)
{
id = i;
}//TpObserver::setId
void
TpObserver::startMonitoring (const QString &strC)
{
strContact = strC;
}//TpObserver::startMonitoring
void
TpObserver::stopMonitoring ()
{
strContact.clear ();
}//TpObserver::stopMonitoring
void
TpObserver::observeChannels(
const MethodInvocationContextPtr<> & context,
const AccountPtr & account,
const ConnectionPtr & connection,
const QList <ChannelPtr> & channels,
const ChannelDispatchOperationPtr & dispatchOperation,
const QList <ChannelRequestPtr> & requestsSatisfied,
const QVariantMap & observerInfo)
{
bool bOk;
QString msg;
emit log ("Observer got something!");
if (strContact.isEmpty ())
{
context->setFinished ();
emit log ("But we weren't asked to notify anything, so go away");
return;
}
msg = QString("There are %1 channels in channels list")
.arg (channels.size ());
log (msg);
foreach (ChannelPtr channel, channels)
{
if (!channel->isReady ())
{
emit log ("Channel is not ready");
ChannelAccepter *closer = new ChannelAccepter(context,
account,
connection,
channels,
dispatchOperation,
requestsSatisfied,
observerInfo,
channel,
strContact,
this);
bOk =
QObject::connect (
closer, SIGNAL (log(const QString &, int)),
this , SIGNAL (log(const QString &, int)));
bOk =
QObject::connect (
closer, SIGNAL (callStarted ()),
this , SIGNAL (callStarted ()));
closer->init ();
break;
}
}
}//TpObserver::addDispatchOperation
ChannelAccepter::ChannelAccepter (
const MethodInvocationContextPtr<> & ctx,
const AccountPtr & act,
const ConnectionPtr & conn,
const QList <ChannelPtr> & chnls,
const ChannelDispatchOperationPtr & dispatchOp,
const QList <ChannelRequestPtr> & requestsSat,
const QVariantMap & obsInfo,
const ChannelPtr channel,
const QString & strNum,
QObject * parent)
: QObject(parent)
, context (ctx)
, account (act)
, connection (conn)
, channels (chnls)
, dispatchOperation (dispatchOp)
, requestsSatisfied (requestsSat)
, observerInfo (obsInfo)
, currentChannel (channel)
, strCheckNumber (strNum)
, mutex (QMutex::Recursive)
, nRefCount (0)
, bFailure (false)
{
}//ChannelAccepter::ChannelAccepter
bool
ChannelAccepter::init ()
{
bool bOk;
PendingReady *pendingReady;
QMutexLocker locker(&mutex);
nRefCount ++; // One for protection
nRefCount ++;
pendingReady = connection->becomeReady ();
bOk =
QObject::connect (
pendingReady, SIGNAL (finished (Tp::PendingOperation *)),
this , SLOT (onConnectionReady (Tp::PendingOperation *)));
if (bOk)
{
emit log ("Waiting for connection to become ready");
}
nRefCount ++;
pendingReady = account->becomeReady ();
bOk =
QObject::connect (
pendingReady, SIGNAL (finished (Tp::PendingOperation *)),
this , SLOT (onAccountReady (Tp::PendingOperation *)));
if (bOk)
{
emit log ("Waiting for account to become ready");
}
nRefCount ++;
pendingReady = currentChannel->becomeReady ();
bOk =
QObject::connect (
pendingReady, SIGNAL (finished (Tp::PendingOperation *)),
this , SLOT (onChannelReady (Tp::PendingOperation *)));
if (bOk)
{
emit log ("Waiting for channel to become ready");
}
emit log ("All become ready's sent");
decrefCleanup ();
return (bOk);
}//ChannelAccepter::init
void
ChannelAccepter::decrefCleanup ()
{
QMutexLocker locker(&mutex);
nRefCount--;
if (0 != nRefCount)
{
return;
}
emit log ("Everything ready. Cleaning up");
bool bCleanupLater = false;
do { // Not a loop
if (bFailure)
{
emit log ("Failed while waiting for something");
break;
}
QString msg;
msg = QString("Channel type = %1. isRequested = %2")
.arg (currentChannel->channelType ())
.arg (currentChannel->isRequested ());
emit log (msg);
ContactPtr contact = currentChannel->initiatorContact ();
msg = QString("Contact id = %1. alias = %2")
.arg (contact->id ())
.arg (contact->alias ());
emit log (msg);
int interested = 0;
if (0 == currentChannel->channelType().compare (
TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA))
{
interested++;
}
if (!currentChannel->isRequested ())
{
interested++;
}
if (contact->id ().contains (strCheckNumber))
{
interested++;
}
if (3 != interested)
{
emit log ("Channel that we're not interested in");
break;
}
emit log ("Incoming call from our number!");
emit callStarted ();
} while (0); // Not a loop
if (!bCleanupLater)
{
context->setFinished ();
this->deleteLater ();
}
}//ChannelAccepter::decrefCleanup
void
ChannelAccepter::onCallAccepted (Tp::PendingOperation *operation)
{
if (operation->isError ())
{
emit log ("Failed to accept call");
}
else
{
emit log ("Call accepted");
}
context->setFinished ();
this->deleteLater ();
}//ChannelAccepter::onCallAccepted
void
ChannelAccepter::onChannelReady (Tp::PendingOperation *operation)
{
do { // Not a loop
if (operation->isError ())
{
emit log ("Channel could not become ready");
bFailure = true;
}
if (!currentChannel->isReady ())
{
emit log ("Dammit the channel is still not ready");
}
else
{
emit log ("Channel is ready");
}
decrefCleanup ();
} while (0); // Not a loop
operation->deleteLater ();
}//ChannelAccepter::onChannelReady
void
ChannelAccepter::onConnectionReady (Tp::PendingOperation *operation)
{
do { // Not a loop
if (operation->isError ())
{
emit log ("Connection could not become ready");
bFailure = true;
}
if (!connection->isReady ())
{
emit log ("Dammit the connection is still not ready");
}
else
{
emit log ("Connection is ready");
}
decrefCleanup ();
} while (0); // Not a loop
operation->deleteLater ();
}//ChannelAccepter::onConnectionReady
void
ChannelAccepter::onAccountReady (Tp::PendingOperation *operation)
{
do { // Not a loop
if (operation->isError ())
{
emit log ("Account could not become ready");
bFailure = true;
}
if (!account->isReady ())
{
emit log ("Dammit the account is still not ready");
}
else
{
emit log ("Account is ready");
}
decrefCleanup ();
} while (0); // Not a loop
operation->deleteLater ();
}//ChannelAccepter::onAccountReady
<commit_msg>fix one warning<commit_after>#include "TpObserver.h"
TpObserver::TpObserver (const ChannelClassList &channelFilter,
QObject *parent )
: IObserver (parent)
, AbstractClientObserver(channelFilter)
, id(1) // Always ignore
{
}//TpObserver::TpObserver
void
TpObserver::setId (int i)
{
id = i;
}//TpObserver::setId
void
TpObserver::startMonitoring (const QString &strC)
{
strContact = strC;
}//TpObserver::startMonitoring
void
TpObserver::stopMonitoring ()
{
strContact.clear ();
}//TpObserver::stopMonitoring
void
TpObserver::observeChannels(
const MethodInvocationContextPtr<> & context,
const AccountPtr & account,
const ConnectionPtr & connection,
const QList <ChannelPtr> & channels,
const ChannelDispatchOperationPtr & dispatchOperation,
const QList <ChannelRequestPtr> & requestsSatisfied,
const QVariantMap & observerInfo)
{
bool bOk;
QString msg;
emit log ("Observer got something!");
if (strContact.isEmpty ())
{
context->setFinished ();
emit log ("But we weren't asked to notify anything, so go away");
return;
}
msg = QString("There are %1 channels in channels list")
.arg (channels.size ());
log (msg);
foreach (ChannelPtr channel, channels)
{
if (!channel->isReady ())
{
emit log ("Channel is not ready");
ChannelAccepter *closer = new ChannelAccepter(context,
account,
connection,
channels,
dispatchOperation,
requestsSatisfied,
observerInfo,
channel,
strContact,
this);
bOk =
QObject::connect (
closer, SIGNAL (log(const QString &, int)),
this , SIGNAL (log(const QString &, int)));
bOk =
QObject::connect (
closer, SIGNAL (callStarted ()),
this , SIGNAL (callStarted ()));
closer->init ();
break;
}
}
}//TpObserver::addDispatchOperation
ChannelAccepter::ChannelAccepter (
const MethodInvocationContextPtr<> & ctx,
const AccountPtr & act,
const ConnectionPtr & conn,
const QList <ChannelPtr> & chnls,
const ChannelDispatchOperationPtr & dispatchOp,
const QList <ChannelRequestPtr> & requestsSat,
const QVariantMap & obsInfo,
const ChannelPtr channel,
const QString & strNum,
QObject * parent)
: QObject(parent)
, context (ctx)
, account (act)
, connection (conn)
, channels (chnls)
, dispatchOperation (dispatchOp)
, requestsSatisfied (requestsSat)
, observerInfo (obsInfo)
, currentChannel (channel)
, strCheckNumber (strNum)
, mutex (QMutex::Recursive)
, nRefCount (0)
, bFailure (false)
{
}//ChannelAccepter::ChannelAccepter
bool
ChannelAccepter::init ()
{
bool bOk;
PendingReady *pendingReady;
QMutexLocker locker(&mutex);
nRefCount ++; // One for protection
nRefCount ++;
pendingReady = connection->becomeReady ();
bOk =
QObject::connect (
pendingReady, SIGNAL (finished (Tp::PendingOperation *)),
this , SLOT (onConnectionReady (Tp::PendingOperation *)));
if (bOk)
{
emit log ("Waiting for connection to become ready");
}
nRefCount ++;
pendingReady = account->becomeReady ();
bOk =
QObject::connect (
pendingReady, SIGNAL (finished (Tp::PendingOperation *)),
this , SLOT (onAccountReady (Tp::PendingOperation *)));
if (bOk)
{
emit log ("Waiting for account to become ready");
}
nRefCount ++;
pendingReady = currentChannel->becomeReady ();
bOk =
QObject::connect (
pendingReady, SIGNAL (finished (Tp::PendingOperation *)),
this , SLOT (onChannelReady (Tp::PendingOperation *)));
if (bOk)
{
emit log ("Waiting for channel to become ready");
}
emit log ("All become ready's sent");
decrefCleanup ();
return (bOk);
}//ChannelAccepter::init
void
ChannelAccepter::decrefCleanup ()
{
QMutexLocker locker(&mutex);
nRefCount--;
if (0 != nRefCount)
{
return;
}
emit log ("Everything ready. Cleaning up");
bool bCleanupLater = false;
do { // Not a loop
if (bFailure)
{
emit log ("Failed while waiting for something");
break;
}
QString msg;
msg = QString("Channel type = %1. isRequested = %2")
.arg (currentChannel->channelType ())
.arg (currentChannel->isRequested ());
emit log (msg);
ContactPtr contact = currentChannel->initiatorContact ();
msg = QString("Contact id = %1. alias = %2")
.arg (contact->id ())
.arg (contact->alias ());
emit log (msg);
int interested = 0;
if (0 == currentChannel->channelType().compare (
TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA))
{
interested++;
}
if (!currentChannel->isRequested ())
{
interested++;
}
if (contact->id ().contains (strCheckNumber))
{
interested++;
}
if (3 != interested)
{
emit log ("Channel that we're not interested in");
break;
}
emit log ("Incoming call from our number!");
emit callStarted ();
} while (0); // Not a loop
if (!bCleanupLater)
{
context->setFinished ();
this->deleteLater ();
}
}//ChannelAccepter::decrefCleanup
void
ChannelAccepter::onCallAccepted (Tp::PendingOperation *operation)
{
if (operation->isError ())
{
emit log ("Failed to accept call");
}
else
{
emit log ("Call accepted");
}
context->setFinished ();
this->deleteLater ();
}//ChannelAccepter::onCallAccepted
void
ChannelAccepter::onChannelReady (Tp::PendingOperation *operation)
{
do { // Not a loop
if (operation->isError ())
{
emit log ("Channel could not become ready");
bFailure = true;
}
if (!currentChannel->isReady ())
{
emit log ("Dammit the channel is still not ready");
}
else
{
emit log ("Channel is ready");
}
decrefCleanup ();
} while (0); // Not a loop
operation->deleteLater ();
}//ChannelAccepter::onChannelReady
void
ChannelAccepter::onConnectionReady (Tp::PendingOperation *operation)
{
do { // Not a loop
if (operation->isError ())
{
emit log ("Connection could not become ready");
bFailure = true;
}
if (!connection->isReady ())
{
emit log ("Dammit the connection is still not ready");
}
else
{
emit log ("Connection is ready");
}
decrefCleanup ();
} while (0); // Not a loop
operation->deleteLater ();
}//ChannelAccepter::onConnectionReady
void
ChannelAccepter::onAccountReady (Tp::PendingOperation *operation)
{
do { // Not a loop
if (operation->isError ())
{
emit log ("Account could not become ready");
bFailure = true;
}
if (!account->isReady ())
{
emit log ("Dammit the account is still not ready");
}
else
{
emit log ("Account is ready");
}
decrefCleanup ();
} while (0); // Not a loop
operation->deleteLater ();
}//ChannelAccepter::onAccountReady
<|endoftext|> |
<commit_before>/*
Copyright (c) Aleksey Fedotov
MIT license
*/
#include "Common/FileSystem.h"
#include "Common/Image.h"
#include "Common/OpenGLWindow.h"
#include "Common/OpenGL.h"
#include "Common/Camera.h"
#include "Common/Spectator.h"
#include <SDL.h>
#include <GL/glew.h>
#include <cassert>
#include <glm/gtc/type_ptr.hpp>
static const std::string vsSrc = R"(
#version 330 core
layout (location = 0) in vec4 position;
layout (location = 1) in vec2 texCoord0;
uniform mat4 worldViewProjMatrix;
out vec2 uv0;
void main()
{
gl_Position = worldViewProjMatrix * position;
uv0 = texCoord0;
}
)";
static const std::string fsSrc = R"(
#version 330 core
uniform sampler2D mainTex;
in vec2 uv0;
out vec4 fragColor;
void main()
{
fragColor = texture(mainTex, uv0);
}
)";
static const std::vector<float> quadVertices =
{
-1, -1, 0, 0, 0,
-1, 1, 0, 0, 1,
1, 1, 0, 1, 1,
1, -1, 0, 1, 0
};
static const std::vector<uint16_t> indices =
{
0, 1, 2,
0, 2, 3
};
static auto initVertexArray(GLuint vertexBuffer) -> GLuint
{
GLuint handle = 0;
glGenVertexArrays(1, &handle);
assert(handle);
glBindVertexArray(handle);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 5, reinterpret_cast<void *>(0));
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 5, reinterpret_cast<void *>(sizeof(float) * 3));
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
return handle;
}
static auto initTexture() -> GLuint
{
auto imageBytes = fs::readBytes("../../assets/Freeman.png");
auto image = img::loadPNG(imageBytes);
GLuint handle = 0;
glGenTextures(1, &handle);
assert(handle);
glBindTexture(GL_TEXTURE_2D, handle);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, image.data.data());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1);
glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
return handle;
}
// TODO more complex transform hierarchies
int main()
{
OpenGLWindow window(800, 600);
// Shader
auto shaderProgram = gl::createShaderProgram(vsSrc.c_str(), vsSrc.size(), fsSrc.c_str(), fsSrc.size());
glUseProgram(shaderProgram);
// Texture
auto texture = initTexture();
glBindTexture(GL_TEXTURE_2D, texture);
glActiveTexture(GL_TEXTURE0);
glUniform1i(glGetUniformLocation(shaderProgram, "mainTex"), 0);
// Mesh
auto vertexBuffer = gl::createVertexBuffer(quadVertices.data(), 4, 5);
auto indexBuffer = gl::createIndexBuffer(indices.data(), 6);
auto vertexArray = initVertexArray(vertexBuffer);
glBindVertexArray(vertexArray);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
// Some pipeline configuration
glDepthMask(GL_TRUE);
glEnable(GL_DEPTH_TEST);
glClearColor(0, 0.8, 0.8, 1);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glDisable(GL_BLEND);
glViewport(0, 0, 800, 600);
Camera cam;
cam.setPerspective(glm::degrees(60.0f), 800.0f / 600, 0.1f, 100.0f)
.getTransform().setLocalPosition({4, 4, 10}).lookAt({0, 0, 0}, {0, 1, 0});
Transform meshTransform;
auto matrixUniform = glGetUniformLocation(shaderProgram, "worldViewProjMatrix");
window.loop([&](auto dt, auto time)
{
updateSpectator(cam.getTransform(), window.getInput(), dt);
auto matrix = meshTransform.rotate({1, 0, 0}, dt).getWorldViewProjMatrix(cam);
glUniformMatrix4fv(matrixUniform, 1, GL_FALSE, glm::value_ptr(matrix));
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, nullptr);
});
glDeleteVertexArrays(1, &vertexArray);
glDeleteBuffers(1, &vertexBuffer);
glDeleteBuffers(1, &indexBuffer);
glDeleteTextures(1, &texture);
glDeleteProgram(shaderProgram);
return 0;
}<commit_msg>Anisotropy<commit_after>/*
Copyright (c) Aleksey Fedotov
MIT license
*/
#include "Common/FileSystem.h"
#include "Common/Image.h"
#include "Common/OpenGLWindow.h"
#include "Common/OpenGL.h"
#include "Common/Camera.h"
#include "Common/Spectator.h"
#include <SDL.h>
#include <GL/glew.h>
#include <cassert>
#include <glm/gtc/type_ptr.hpp>
static const std::string vsSrc = R"(
#version 330 core
layout (location = 0) in vec4 position;
layout (location = 1) in vec2 texCoord0;
uniform mat4 worldViewProjMatrix;
out vec2 uv0;
void main()
{
gl_Position = worldViewProjMatrix * position;
uv0 = texCoord0;
}
)";
static const std::string fsSrc = R"(
#version 330 core
uniform sampler2D mainTex;
in vec2 uv0;
out vec4 fragColor;
void main()
{
fragColor = texture(mainTex, uv0);
}
)";
static const std::vector<float> quadVertices =
{
-1, -1, 0, 0, 0,
-1, 1, 0, 0, 1,
1, 1, 0, 1, 1,
1, -1, 0, 1, 0
};
static const std::vector<uint16_t> indices =
{
0, 1, 2,
0, 2, 3
};
static auto initVertexArray(GLuint vertexBuffer) -> GLuint
{
GLuint handle = 0;
glGenVertexArrays(1, &handle);
assert(handle);
glBindVertexArray(handle);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 5, reinterpret_cast<void *>(0));
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 5, reinterpret_cast<void *>(sizeof(float) * 3));
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
return handle;
}
static auto initTexture() -> GLuint
{
auto imageBytes = fs::readBytes("../../assets/Freeman.png");
auto image = img::loadPNG(imageBytes);
GLuint handle = 0;
glGenTextures(1, &handle);
assert(handle);
glBindTexture(GL_TEXTURE_2D, handle);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, image.data.data());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 16);
glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
return handle;
}
// TODO more complex transform hierarchies
int main()
{
OpenGLWindow window(800, 600);
// Shader
auto shaderProgram = gl::createShaderProgram(vsSrc.c_str(), vsSrc.size(), fsSrc.c_str(), fsSrc.size());
glUseProgram(shaderProgram);
// Texture
auto texture = initTexture();
glBindTexture(GL_TEXTURE_2D, texture);
glActiveTexture(GL_TEXTURE0);
glUniform1i(glGetUniformLocation(shaderProgram, "mainTex"), 0);
// Mesh
auto vertexBuffer = gl::createVertexBuffer(quadVertices.data(), 4, 5);
auto indexBuffer = gl::createIndexBuffer(indices.data(), 6);
auto vertexArray = initVertexArray(vertexBuffer);
glBindVertexArray(vertexArray);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
// Some pipeline configuration
glDepthMask(GL_TRUE);
glEnable(GL_DEPTH_TEST);
glClearColor(0, 0.8, 0.8, 1);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glDisable(GL_BLEND);
glViewport(0, 0, 800, 600);
Camera cam;
cam.setPerspective(glm::degrees(60.0f), 800.0f / 600, 0.1f, 100.0f)
.getTransform().setLocalPosition({4, 4, 10}).lookAt({0, 0, 0}, {0, 1, 0});
Transform meshTransform;
auto matrixUniform = glGetUniformLocation(shaderProgram, "worldViewProjMatrix");
window.loop([&](auto dt, auto time)
{
updateSpectator(cam.getTransform(), window.getInput(), dt);
auto matrix = meshTransform.rotate({1, 0, 0}, dt).getWorldViewProjMatrix(cam);
glUniformMatrix4fv(matrixUniform, 1, GL_FALSE, glm::value_ptr(matrix));
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, nullptr);
});
glDeleteVertexArrays(1, &vertexArray);
glDeleteBuffers(1, &vertexBuffer);
glDeleteBuffers(1, &indexBuffer);
glDeleteTextures(1, &texture);
glDeleteProgram(shaderProgram);
return 0;
}<|endoftext|> |
<commit_before>// Copyright (C) 2016 xaizek <[email protected]>
//
// This file is part of uncov.
//
// uncov 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.
//
// uncov 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 uncov. If not, see <http://www.gnu.org/licenses/>.
#include "Invocation.hpp"
#include <boost/program_options.hpp>
#include <limits>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
namespace po = boost::program_options;
static po::variables_map parseOptions(const std::vector<std::string> &args);
static std::vector<po::option>
stopAtFirstPositional(std::vector<std::string> &args);
Invocation::Invocation(std::vector<std::string> args)
{
if (args.empty()) {
throw std::invalid_argument("Broken argument list.");
}
// Extract program name.
programName = args[0];
args.erase(args.cbegin());
if (args.empty()) {
error = "No arguments.";
return;
}
po::variables_map varMap;
try {
varMap = parseOptions(args);
} catch (const std::exception &e) {
error = e.what();
return;
}
printHelp = varMap.count("help");
printVersion = varMap.count("version");
args = varMap["positional"].as<std::vector<std::string>>();
if (printHelp || printVersion) {
return;
}
if (!args.empty()) {
auto isPath = [](const std::string &s) {
return s.substr(0, 1) == "." || s.find('/') != std::string::npos;
};
// Extract path to repository.
if (isPath(args.front())) {
repositoryPath = args.front();
args.erase(args.cbegin());
} else {
repositoryPath = ".";
}
}
if (args.empty()) {
error = "No subcommand specified.";
return;
}
// Extract subcommand and its arguments.
subcommandName = args.front();
args.erase(args.cbegin());
subcommandArgs = std::move(args);
}
/**
* @brief Parses command line-options.
*
* Positional arguments are returned in "positional" entry, which exists even
* when there is no positional arguments.
*
* @param args Command-line arguments.
*
* @returns Variables map of option values.
*/
static po::variables_map
parseOptions(const std::vector<std::string> &args)
{
po::options_description hiddenOpts;
hiddenOpts.add_options()
("positional", po::value<std::vector<std::string>>()
->default_value({}, ""),
"positional args");
po::positional_options_description positional_options;
positional_options.add("positional", -1);
po::options_description cmdline_options;
cmdline_options.add_options()
("help,h", "display help message")
("version,v", "display version");
po::options_description all_options;
all_options.add(cmdline_options).add(hiddenOpts);
auto parsed_from_cmdline =
po::command_line_parser(args)
.options(all_options)
.positional(positional_options)
.extra_style_parser(&stopAtFirstPositional)
.run();
po::variables_map varMap;
po::store(parsed_from_cmdline, varMap);
return varMap;
}
/**
* @brief Command-line option parser that captures as positional argument any
* element starting from the first positional argument.
*
* @param args Arguments.
*
* @returns Parsed arguments.
*/
static std::vector<po::option>
stopAtFirstPositional(std::vector<std::string> &args)
{
std::vector<po::option> result;
const std::string &tok = args[0];
if (!tok.empty() && tok.front() != '-') {
for (unsigned int i = 0U; i < args.size(); ++i) {
po::option opt;
opt.value.push_back(args[i]);
opt.original_tokens.push_back(args[i]);
opt.position_key = std::numeric_limits<int>::max();
result.push_back(opt);
}
args.clear();
}
return result;
}
std::string
Invocation::getUsage() const
{
return "Usage: " + programName
+ " [--help|-h] [--version|-v] [repo] subcommand [args...]";
}
const std::string &
Invocation::getError() const
{
return error;
}
const std::string &
Invocation::getRepositoryPath() const
{
return repositoryPath;
}
const std::string &
Invocation::getSubcommandName() const
{
return subcommandName;
}
const std::vector<std::string> &
Invocation::getSubcommandArgs() const
{
return subcommandArgs;
}
bool
Invocation::shouldPrintHelp() const
{
return printHelp;
}
bool
Invocation::shouldPrintVersion() const
{
return printVersion;
}
<commit_msg>Use camelCase in Invocation.cpp::parseOptions()<commit_after>// Copyright (C) 2016 xaizek <[email protected]>
//
// This file is part of uncov.
//
// uncov 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.
//
// uncov 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 uncov. If not, see <http://www.gnu.org/licenses/>.
#include "Invocation.hpp"
#include <boost/program_options.hpp>
#include <limits>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
namespace po = boost::program_options;
static po::variables_map parseOptions(const std::vector<std::string> &args);
static std::vector<po::option>
stopAtFirstPositional(std::vector<std::string> &args);
Invocation::Invocation(std::vector<std::string> args)
{
if (args.empty()) {
throw std::invalid_argument("Broken argument list.");
}
// Extract program name.
programName = args[0];
args.erase(args.cbegin());
if (args.empty()) {
error = "No arguments.";
return;
}
po::variables_map varMap;
try {
varMap = parseOptions(args);
} catch (const std::exception &e) {
error = e.what();
return;
}
printHelp = varMap.count("help");
printVersion = varMap.count("version");
args = varMap["positional"].as<std::vector<std::string>>();
if (printHelp || printVersion) {
return;
}
if (!args.empty()) {
auto isPath = [](const std::string &s) {
return s.substr(0, 1) == "." || s.find('/') != std::string::npos;
};
// Extract path to repository.
if (isPath(args.front())) {
repositoryPath = args.front();
args.erase(args.cbegin());
} else {
repositoryPath = ".";
}
}
if (args.empty()) {
error = "No subcommand specified.";
return;
}
// Extract subcommand and its arguments.
subcommandName = args.front();
args.erase(args.cbegin());
subcommandArgs = std::move(args);
}
/**
* @brief Parses command line-options.
*
* Positional arguments are returned in "positional" entry, which exists even
* when there is no positional arguments.
*
* @param args Command-line arguments.
*
* @returns Variables map of option values.
*/
static po::variables_map
parseOptions(const std::vector<std::string> &args)
{
po::options_description hiddenOpts;
hiddenOpts.add_options()
("positional", po::value<std::vector<std::string>>()
->default_value({}, ""),
"positional args");
po::positional_options_description positionalOptions;
positionalOptions.add("positional", -1);
po::options_description cmdlineOptions;
cmdlineOptions.add_options()
("help,h", "display help message")
("version,v", "display version");
po::options_description allOptions;
allOptions.add(cmdlineOptions).add(hiddenOpts);
auto parsed_from_cmdline =
po::command_line_parser(args)
.options(allOptions)
.positional(positionalOptions)
.extra_style_parser(&stopAtFirstPositional)
.run();
po::variables_map varMap;
po::store(parsed_from_cmdline, varMap);
return varMap;
}
/**
* @brief Command-line option parser that captures as positional argument any
* element starting from the first positional argument.
*
* @param args Arguments.
*
* @returns Parsed arguments.
*/
static std::vector<po::option>
stopAtFirstPositional(std::vector<std::string> &args)
{
std::vector<po::option> result;
const std::string &tok = args[0];
if (!tok.empty() && tok.front() != '-') {
for (unsigned int i = 0U; i < args.size(); ++i) {
po::option opt;
opt.value.push_back(args[i]);
opt.original_tokens.push_back(args[i]);
opt.position_key = std::numeric_limits<int>::max();
result.push_back(opt);
}
args.clear();
}
return result;
}
std::string
Invocation::getUsage() const
{
return "Usage: " + programName
+ " [--help|-h] [--version|-v] [repo] subcommand [args...]";
}
const std::string &
Invocation::getError() const
{
return error;
}
const std::string &
Invocation::getRepositoryPath() const
{
return repositoryPath;
}
const std::string &
Invocation::getSubcommandName() const
{
return subcommandName;
}
const std::vector<std::string> &
Invocation::getSubcommandArgs() const
{
return subcommandArgs;
}
bool
Invocation::shouldPrintHelp() const
{
return printHelp;
}
bool
Invocation::shouldPrintVersion() const
{
return printVersion;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "QmitkSliderLevelWindowWidget.h"
#include <qcursor.h>
#include <qtooltip.h>
#include <itkCommand.h>
/**
* Constructor
*/
QmitkSliderLevelWindowWidget::QmitkSliderLevelWindowWidget( QWidget * parent, const char * name, WFlags f )
: QWidget( parent, name, f )
{
m_Manager = mitk::LevelWindowManager::New();
itk::ReceptorMemberCommand<QmitkSliderLevelWindowWidget>::Pointer command = itk::ReceptorMemberCommand<QmitkSliderLevelWindowWidget>::New();
command->SetCallbackFunction(this, &QmitkSliderLevelWindowWidget::OnPropertyModified);
m_ObserverTag = m_Manager->AddObserver(itk::ModifiedEvent(), command);
m_IsObserverTagSet = true;
setMouseTracking(true);
m_Resize = false;
m_Bottom = false;
m_CtrlPressed = false;
m_MouseDown = false;
m_Font.setPointSize( 6 );
m_MoveHeight = height() - 25;
m_ScaleVisible = true;
m_Contextmenu = new QmitkLevelWindowWidgetContextMenu(this, "contextMenu", true);
setBackgroundMode( Qt::NoBackground );
this->hide();
update();
}
void QmitkSliderLevelWindowWidget::setLevelWindowManager(mitk::LevelWindowManager* levelWindowManager)
{
if ( m_IsObserverTagSet)
{
m_Manager->RemoveObserver(m_ObserverTag);
m_IsObserverTagSet = false;
}
m_Manager = levelWindowManager;
if ( m_Manager.IsNotNull() )
{
itk::ReceptorMemberCommand<QmitkSliderLevelWindowWidget>::Pointer command = itk::ReceptorMemberCommand<QmitkSliderLevelWindowWidget>::New();
command->SetCallbackFunction(this, &QmitkSliderLevelWindowWidget::OnPropertyModified);
m_ObserverTag = m_Manager->AddObserver(itk::ModifiedEvent(), command);
m_IsObserverTagSet = true;
}
}
void QmitkSliderLevelWindowWidget::OnPropertyModified(const itk::EventObject& )
{
try
{
m_LevelWindow = m_Manager->GetLevelWindow();
this->show();
update();
}
catch(...)
{
try
{
this->hide();
}
catch(...)
{
}
}
}
void QmitkSliderLevelWindowWidget::paintEvent( QPaintEvent* itkNotUsed(e) )
{
QPixmap pm(width(), height());
pm.fill( static_cast<QWidget*>(parent())->paletteBackgroundColor() );
QPainter painter(&pm);
painter.setFont( m_Font );
painter.setPen(static_cast<QWidget*>(parent())->paletteForegroundColor());
QColor c(93,144,169);
QColor cl = c.light();
QColor cd = c.dark();
painter.setBrush(c);
painter.drawRect(m_Rect);
float mr = m_LevelWindow.GetRange();
if ( mr < 1 )
mr = 1;
float fact = (float) m_MoveHeight / mr;
//begin draw scale
if (m_ScaleVisible)
{
int minRange = (int)m_LevelWindow.GetRangeMin();
int maxRange = (int)m_LevelWindow.GetRangeMax();
int yValue = m_MoveHeight + (int)(minRange*fact);
QString s = " 0";
if (minRange <= 0 && maxRange >= 0)
{
painter.drawLine( 5, yValue , 15, yValue);
painter.drawText( 21, yValue + 3, s );
}
int count = 1;
int k = 5;
bool enoughSpace = false;
bool enoughSpace2 = false;
for(int i = m_MoveHeight + (int)(minRange*fact); i < m_MoveHeight;)
{
if (-count*20 < minRange)
break;
yValue = m_MoveHeight + (int)((minRange + count*20)*fact);
s = QString::number(-count*20);
if (count % k && ((20*fact) > 2.5))
{
painter.drawLine( 8, yValue, 12, yValue);
enoughSpace = true;
}
else if (!(count % k))
{
if ((k*20*fact) > 7)
{
painter.drawLine( 5, yValue, 15, yValue);
painter.drawText( 21, yValue + 3, s );
enoughSpace2 = true;
}
else
{
k += 5;
}
}
if (enoughSpace)
{
i=yValue;
count++;
}
else if (enoughSpace2)
{
i=yValue;
count += k;
}
else
{
i=yValue;
count = k;
}
}
count = 1;
k = 5;
enoughSpace = false;
enoughSpace2 = false;
for(int i = m_MoveHeight + (int)(minRange*fact); i >= 0;)
{
if (count*20 > maxRange)
break;
yValue = m_MoveHeight + (int)((minRange - count*20)*fact);
s = QString::number(count*20);
if(count % k && ((20*fact) > 2.5))
{
if (!(minRange > 0 && (count*20) < minRange))
painter.drawLine( 8, yValue, 12, yValue);
enoughSpace = true;
}
else if (!(count % k))
{
if ((k*20*fact) > 7)
{
if (!(minRange > 0 && (count*20) < minRange))
{
painter.drawLine( 5, yValue, 15, yValue);
painter.drawText( 21, yValue + 3, s );
}
enoughSpace2 = true;
}
else
{
k += 5;
}
}
if (enoughSpace)
{
i=yValue;
count++;
}
else if (enoughSpace2)
{
i=yValue;
count += k;
}
else
{
i=yValue;
count = k;
}
}
}
//end draw scale
painter.setPen (cl);
painter.drawLine(m_Rect.topLeft(),m_Rect.topRight());
painter.drawLine(m_Rect.topLeft(),m_Rect.bottomLeft());
painter.setPen (cd);
painter.drawLine(m_Rect.topRight(),m_Rect.bottomRight());
painter.drawLine(m_Rect.bottomRight(),m_Rect.bottomLeft());
painter.end();
QPainter p (this);
p.drawPixmap(0, 0, pm);
}
/**
*
*/
void QmitkSliderLevelWindowWidget::mouseMoveEvent( QMouseEvent* mouseEvent ) {
if (!m_MouseDown)
{
if (((mouseEvent->pos().y() >= (m_Rect.topLeft().y() - 3) && mouseEvent->pos().y() <= (m_Rect.topLeft().y() + 3))
|| (mouseEvent->pos().y() >= (m_Rect.bottomLeft().y() - 3) && mouseEvent->pos().y() <= (m_Rect.bottomLeft().y() + 3)))
&& mouseEvent->pos().x() >= m_Rect.topLeft().x() && mouseEvent->pos().x() <= m_Rect.topRight().x())
{
setCursor(SizeVerCursor);
QToolTip::remove(this, m_UpperBound);
QToolTip::remove(this, m_LowerBound);
m_LowerBound.setRect(m_Rect.bottomLeft().x(), m_Rect.bottomLeft().y() - 3, 17, 7);
QToolTip::add(this, m_LowerBound, "Ctrl + left click to change only lower bound");
m_UpperBound.setRect(m_Rect.topLeft().x(), m_Rect.topLeft().y() - 3, 17, 7);
QToolTip::add(this, m_UpperBound, "Ctrl + left click to change only upper bound");
m_Resize = true;
if ((mouseEvent->pos().y() >= (m_Rect.bottomLeft().y() - 3) && mouseEvent->pos().y() <= (m_Rect.bottomLeft().y() + 3)))
m_Bottom = true;
}
else
{
QToolTip::remove(this, m_LowerBound);
QToolTip::remove(this, m_UpperBound);
setCursor(ArrowCursor);
m_Resize = false;
m_Bottom = false;
}
}
if ( m_MouseDown ) {
float fact = (float) m_MoveHeight / m_LevelWindow.GetRange();
if ( m_Leftbutton )
{
if (m_Resize && !m_CtrlPressed)
{
double diff = (mouseEvent->pos().y()) / fact;
diff -= (m_StartPos.y()) / fact;
m_StartPos = mouseEvent->pos();
if (diff == 0) return;
float value;
if (m_Bottom)
value = m_LevelWindow.GetWindow() + ( ( 2 * diff ) );
else
value = m_LevelWindow.GetWindow() - ( ( 2 * diff ) );
if ( value < 1 )
value = 1;
m_LevelWindow.SetLevelWindow( m_LevelWindow.GetLevel(), value );
}
else if(m_Resize && m_CtrlPressed)
{
if (!m_Bottom)
{
double diff = (mouseEvent->pos().y()) / fact;
diff -= (m_StartPos.y()) / fact;
m_StartPos = mouseEvent->pos();
if (diff == 0) return;
float value;
value = m_LevelWindow.GetWindow() - ( ( diff ) );
if ( value < 1 )
value = 1;
float oldWindow;
float oldLevel;
float newLevel;
oldWindow = m_LevelWindow.GetWindow();
oldLevel = m_LevelWindow.GetLevel();
newLevel = oldLevel + (value - oldWindow)/2;
if (!((newLevel + value/2) > m_LevelWindow.GetRangeMax()))
m_LevelWindow.SetLevelWindow( newLevel, value );
}
else
{
double diff = (mouseEvent->pos().y()) / fact;
diff -= (m_StartPos.y()) / fact;
m_StartPos = mouseEvent->pos();
if (diff == 0) return;
float value;
value = m_LevelWindow.GetWindow() + ( ( diff ) );
if ( value < 1 )
value = 1;
float oldWindow;
float oldLevel;
float newLevel;
oldWindow = m_LevelWindow.GetWindow();
oldLevel = m_LevelWindow.GetLevel();
newLevel = oldLevel - (value - oldWindow)/2;
if (!((newLevel - value/2) < m_LevelWindow.GetRangeMin()))
m_LevelWindow.SetLevelWindow( newLevel, value );
}
}
else
{
float maxv = m_LevelWindow.GetRangeMax();
float minv = m_LevelWindow.GetRangeMin();
float wh = m_LevelWindow.GetWindow() / 2;
float value = (m_MoveHeight - mouseEvent->pos().y()) / fact + minv;
if ( value - wh < minv )
m_LevelWindow.SetLevelWindow( m_LevelWindow.GetRangeMin() + wh, m_LevelWindow.GetLevel() );
else if ( value + wh > maxv )
m_LevelWindow.SetLevelWindow( m_LevelWindow.GetRangeMax() - wh, m_LevelWindow.GetLevel() );
else
m_LevelWindow.SetLevelWindow( value, m_LevelWindow.GetWindow() );
}
m_Manager->SetLevelWindow(m_LevelWindow);
}
}
}
/**
*
*/
void QmitkSliderLevelWindowWidget::mousePressEvent( QMouseEvent* mouseEvent ) {
m_MouseDown = true;
m_StartPos = mouseEvent->pos();
if ( mouseEvent->button() == QMouseEvent::LeftButton )
{
if (mouseEvent->state() == Qt::ControlButton || mouseEvent->state() == Qt::ShiftButton)
{
m_CtrlPressed = true;
}
else
{
m_CtrlPressed = false;
}
m_Leftbutton = true;
}
else
m_Leftbutton = false;
mouseMoveEvent( mouseEvent );
}
/**
*
*/
void QmitkSliderLevelWindowWidget::resizeEvent ( QResizeEvent * event ) {
m_MoveHeight = event->size().height() - 25;
update();
}
/**
*
*/
void QmitkSliderLevelWindowWidget::mouseReleaseEvent( QMouseEvent* )
{
m_MouseDown = false;
}
/**
*
*/
void QmitkSliderLevelWindowWidget::update() {
int rectWidth;
if(m_ScaleVisible)
{
rectWidth = 17;
setMinimumSize ( QSize( 50, 50 ) );
setMaximumSize ( QSize( 50, 2000 ) );
setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Expanding ) );
}
else
{
rectWidth = 26;
setMinimumSize ( QSize( 40, 50 ) );
setMaximumSize ( QSize( 50, 2000 ) );
setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Expanding ) );
}
float mr = m_LevelWindow.GetRange();
if ( mr < 1 )
mr = 1;
float fact = (float) m_MoveHeight / mr;
float rectHeight = m_LevelWindow.GetWindow() * fact;
if ( rectHeight < 15 )
rectHeight = 15;
if ( m_LevelWindow.GetMin() < 0 )
m_Rect.setRect( 2, (int) (m_MoveHeight - (m_LevelWindow.GetMax() - m_LevelWindow.GetRangeMin()) * fact) , rectWidth, (int) rectHeight );
else
m_Rect.setRect( 2, (int) (m_MoveHeight - (m_LevelWindow.GetMax() - m_LevelWindow.GetRangeMin()) * fact), rectWidth, (int) rectHeight );
QWidget::repaint();
}
void QmitkSliderLevelWindowWidget::contextMenuEvent( QContextMenuEvent * )
{
m_Contextmenu->setLevelWindowManager(m_Manager.GetPointer());
QPopupMenu *contextMenu = new QPopupMenu( this );
Q_CHECK_PTR( contextMenu );
if (m_ScaleVisible)
contextMenu->insertItem(tr("Hide Scale"), this, SLOT(hideScale()));
else
contextMenu->insertItem(tr("Show Scale"), this, SLOT(showScale()));
contextMenu->insertSeparator();
m_Contextmenu->getContextMenu(contextMenu);
}
void QmitkSliderLevelWindowWidget::hideScale()
{
m_ScaleVisible = false;
update();
}
void QmitkSliderLevelWindowWidget::showScale()
{
m_ScaleVisible = true;
update();
}
void QmitkSliderLevelWindowWidget::setDataTree(mitk::DataTree* tree)
{
m_Manager->SetDataTree(tree);
}
mitk::LevelWindowManager* QmitkSliderLevelWindowWidget::GetManager()
{
return m_Manager.GetPointer();
}
<commit_msg>Fixed: Bug when moving Slider<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "QmitkSliderLevelWindowWidget.h"
#include <qcursor.h>
#include <qtooltip.h>
#include <itkCommand.h>
/**
* Constructor
*/
QmitkSliderLevelWindowWidget::QmitkSliderLevelWindowWidget( QWidget * parent, const char * name, WFlags f )
: QWidget( parent, name, f )
{
m_Manager = mitk::LevelWindowManager::New();
itk::ReceptorMemberCommand<QmitkSliderLevelWindowWidget>::Pointer command = itk::ReceptorMemberCommand<QmitkSliderLevelWindowWidget>::New();
command->SetCallbackFunction(this, &QmitkSliderLevelWindowWidget::OnPropertyModified);
m_ObserverTag = m_Manager->AddObserver(itk::ModifiedEvent(), command);
m_IsObserverTagSet = true;
setMouseTracking(true);
m_Resize = false;
m_Bottom = false;
m_CtrlPressed = false;
m_MouseDown = false;
m_Font.setPointSize( 6 );
m_MoveHeight = height() - 25;
m_ScaleVisible = true;
m_Contextmenu = new QmitkLevelWindowWidgetContextMenu(this, "contextMenu", true);
setBackgroundMode( Qt::NoBackground );
this->hide();
update();
}
void QmitkSliderLevelWindowWidget::setLevelWindowManager(mitk::LevelWindowManager* levelWindowManager)
{
if ( m_IsObserverTagSet)
{
m_Manager->RemoveObserver(m_ObserverTag);
m_IsObserverTagSet = false;
}
m_Manager = levelWindowManager;
if ( m_Manager.IsNotNull() )
{
itk::ReceptorMemberCommand<QmitkSliderLevelWindowWidget>::Pointer command = itk::ReceptorMemberCommand<QmitkSliderLevelWindowWidget>::New();
command->SetCallbackFunction(this, &QmitkSliderLevelWindowWidget::OnPropertyModified);
m_ObserverTag = m_Manager->AddObserver(itk::ModifiedEvent(), command);
m_IsObserverTagSet = true;
}
}
void QmitkSliderLevelWindowWidget::OnPropertyModified(const itk::EventObject& )
{
try
{
m_LevelWindow = m_Manager->GetLevelWindow();
this->show();
update();
}
catch(...)
{
try
{
this->hide();
}
catch(...)
{
}
}
}
void QmitkSliderLevelWindowWidget::paintEvent( QPaintEvent* itkNotUsed(e) )
{
QPixmap pm(width(), height());
pm.fill( static_cast<QWidget*>(parent())->paletteBackgroundColor() );
QPainter painter(&pm);
painter.setFont( m_Font );
painter.setPen(static_cast<QWidget*>(parent())->paletteForegroundColor());
QColor c(93,144,169);
QColor cl = c.light();
QColor cd = c.dark();
painter.setBrush(c);
painter.drawRect(m_Rect);
float mr = m_LevelWindow.GetRange();
if ( mr < 1 )
mr = 1;
float fact = (float) m_MoveHeight / mr;
//begin draw scale
if (m_ScaleVisible)
{
int minRange = (int)m_LevelWindow.GetRangeMin();
int maxRange = (int)m_LevelWindow.GetRangeMax();
int yValue = m_MoveHeight + (int)(minRange*fact);
QString s = " 0";
if (minRange <= 0 && maxRange >= 0)
{
painter.drawLine( 5, yValue , 15, yValue);
painter.drawText( 21, yValue + 3, s );
}
int count = 1;
int k = 5;
bool enoughSpace = false;
bool enoughSpace2 = false;
for(int i = m_MoveHeight + (int)(minRange*fact); i < m_MoveHeight;)
{
if (-count*20 < minRange)
break;
yValue = m_MoveHeight + (int)((minRange + count*20)*fact);
s = QString::number(-count*20);
if (count % k && ((20*fact) > 2.5))
{
painter.drawLine( 8, yValue, 12, yValue);
enoughSpace = true;
}
else if (!(count % k))
{
if ((k*20*fact) > 7)
{
painter.drawLine( 5, yValue, 15, yValue);
painter.drawText( 21, yValue + 3, s );
enoughSpace2 = true;
}
else
{
k += 5;
}
}
if (enoughSpace)
{
i=yValue;
count++;
}
else if (enoughSpace2)
{
i=yValue;
count += k;
}
else
{
i=yValue;
count = k;
}
}
count = 1;
k = 5;
enoughSpace = false;
enoughSpace2 = false;
for(int i = m_MoveHeight + (int)(minRange*fact); i >= 0;)
{
if (count*20 > maxRange)
break;
yValue = m_MoveHeight + (int)((minRange - count*20)*fact);
s = QString::number(count*20);
if(count % k && ((20*fact) > 2.5))
{
if (!(minRange > 0 && (count*20) < minRange))
painter.drawLine( 8, yValue, 12, yValue);
enoughSpace = true;
}
else if (!(count % k))
{
if ((k*20*fact) > 7)
{
if (!(minRange > 0 && (count*20) < minRange))
{
painter.drawLine( 5, yValue, 15, yValue);
painter.drawText( 21, yValue + 3, s );
}
enoughSpace2 = true;
}
else
{
k += 5;
}
}
if (enoughSpace)
{
i=yValue;
count++;
}
else if (enoughSpace2)
{
i=yValue;
count += k;
}
else
{
i=yValue;
count = k;
}
}
}
//end draw scale
painter.setPen (cl);
painter.drawLine(m_Rect.topLeft(),m_Rect.topRight());
painter.drawLine(m_Rect.topLeft(),m_Rect.bottomLeft());
painter.setPen (cd);
painter.drawLine(m_Rect.topRight(),m_Rect.bottomRight());
painter.drawLine(m_Rect.bottomRight(),m_Rect.bottomLeft());
painter.end();
QPainter p (this);
p.drawPixmap(0, 0, pm);
}
/**
*
*/
void QmitkSliderLevelWindowWidget::mouseMoveEvent( QMouseEvent* mouseEvent ) {
if (!m_MouseDown)
{
if (((mouseEvent->pos().y() >= (m_Rect.topLeft().y() - 3) && mouseEvent->pos().y() <= (m_Rect.topLeft().y() + 3))
|| (mouseEvent->pos().y() >= (m_Rect.bottomLeft().y() - 3) && mouseEvent->pos().y() <= (m_Rect.bottomLeft().y() + 3)))
&& mouseEvent->pos().x() >= m_Rect.topLeft().x() && mouseEvent->pos().x() <= m_Rect.topRight().x())
{
setCursor(SizeVerCursor);
QToolTip::remove(this, m_UpperBound);
QToolTip::remove(this, m_LowerBound);
m_LowerBound.setRect(m_Rect.bottomLeft().x(), m_Rect.bottomLeft().y() - 3, 17, 7);
QToolTip::add(this, m_LowerBound, "Ctrl + left click to change only lower bound");
m_UpperBound.setRect(m_Rect.topLeft().x(), m_Rect.topLeft().y() - 3, 17, 7);
QToolTip::add(this, m_UpperBound, "Ctrl + left click to change only upper bound");
m_Resize = true;
if ((mouseEvent->pos().y() >= (m_Rect.bottomLeft().y() - 3) && mouseEvent->pos().y() <= (m_Rect.bottomLeft().y() + 3)))
m_Bottom = true;
}
else
{
QToolTip::remove(this, m_LowerBound);
QToolTip::remove(this, m_UpperBound);
setCursor(ArrowCursor);
m_Resize = false;
m_Bottom = false;
}
}
if ( m_MouseDown ) {
float fact = (float) m_MoveHeight / m_LevelWindow.GetRange();
if ( m_Leftbutton )
{
if (m_Resize && !m_CtrlPressed)
{
double diff = (mouseEvent->pos().y()) / fact;
diff -= (m_StartPos.y()) / fact;
m_StartPos = mouseEvent->pos();
if (diff == 0) return;
float value;
if (m_Bottom)
value = m_LevelWindow.GetWindow() + ( ( 2 * diff ) );
else
value = m_LevelWindow.GetWindow() - ( ( 2 * diff ) );
if ( value < 1 )
value = 1;
m_LevelWindow.SetLevelWindow( m_LevelWindow.GetLevel(), value );
}
else if(m_Resize && m_CtrlPressed)
{
if (!m_Bottom)
{
double diff = (mouseEvent->pos().y()) / fact;
diff -= (m_StartPos.y()) / fact;
m_StartPos = mouseEvent->pos();
if (diff == 0) return;
float value;
value = m_LevelWindow.GetWindow() - ( ( diff ) );
if ( value < 1 )
value = 1;
float oldWindow;
float oldLevel;
float newLevel;
oldWindow = m_LevelWindow.GetWindow();
oldLevel = m_LevelWindow.GetLevel();
newLevel = oldLevel + (value - oldWindow)/2;
if (!((newLevel + value/2) > m_LevelWindow.GetRangeMax()))
m_LevelWindow.SetLevelWindow( newLevel, value );
}
else
{
double diff = (mouseEvent->pos().y()) / fact;
diff -= (m_StartPos.y()) / fact;
m_StartPos = mouseEvent->pos();
if (diff == 0) return;
float value;
value = m_LevelWindow.GetWindow() + ( ( diff ) );
if ( value < 1 )
value = 1;
float oldWindow;
float oldLevel;
float newLevel;
oldWindow = m_LevelWindow.GetWindow();
oldLevel = m_LevelWindow.GetLevel();
newLevel = oldLevel - (value - oldWindow)/2;
if (!((newLevel - value/2) < m_LevelWindow.GetRangeMin()))
m_LevelWindow.SetLevelWindow( newLevel, value );
}
}
else
{
float maxv = m_LevelWindow.GetRangeMax();
float minv = m_LevelWindow.GetRangeMin();
float wh = m_LevelWindow.GetWindow() / 2;
float value = (m_MoveHeight - mouseEvent->pos().y()) / fact + minv;
if ( value - wh < minv )
m_LevelWindow.SetLevelWindow( m_LevelWindow.GetRangeMin() + wh, m_LevelWindow.GetWindow() );
else if ( value + wh > maxv )
m_LevelWindow.SetLevelWindow( m_LevelWindow.GetRangeMax() - wh, m_LevelWindow.GetWindow() );
else
m_LevelWindow.SetLevelWindow( value, m_LevelWindow.GetWindow() );
}
m_Manager->SetLevelWindow(m_LevelWindow);
}
}
}
/**
*
*/
void QmitkSliderLevelWindowWidget::mousePressEvent( QMouseEvent* mouseEvent ) {
m_MouseDown = true;
m_StartPos = mouseEvent->pos();
if ( mouseEvent->button() == QMouseEvent::LeftButton )
{
if (mouseEvent->state() == Qt::ControlButton || mouseEvent->state() == Qt::ShiftButton)
{
m_CtrlPressed = true;
}
else
{
m_CtrlPressed = false;
}
m_Leftbutton = true;
}
else
m_Leftbutton = false;
mouseMoveEvent( mouseEvent );
}
/**
*
*/
void QmitkSliderLevelWindowWidget::resizeEvent ( QResizeEvent * event ) {
m_MoveHeight = event->size().height() - 25;
update();
}
/**
*
*/
void QmitkSliderLevelWindowWidget::mouseReleaseEvent( QMouseEvent* )
{
m_MouseDown = false;
}
/**
*
*/
void QmitkSliderLevelWindowWidget::update() {
int rectWidth;
if(m_ScaleVisible)
{
rectWidth = 17;
setMinimumSize ( QSize( 50, 50 ) );
setMaximumSize ( QSize( 50, 2000 ) );
setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Expanding ) );
}
else
{
rectWidth = 26;
setMinimumSize ( QSize( 40, 50 ) );
setMaximumSize ( QSize( 50, 2000 ) );
setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Expanding ) );
}
float mr = m_LevelWindow.GetRange();
if ( mr < 1 )
mr = 1;
float fact = (float) m_MoveHeight / mr;
float rectHeight = m_LevelWindow.GetWindow() * fact;
if ( rectHeight < 15 )
rectHeight = 15;
if ( m_LevelWindow.GetMin() < 0 )
m_Rect.setRect( 2, (int) (m_MoveHeight - (m_LevelWindow.GetMax() - m_LevelWindow.GetRangeMin()) * fact) , rectWidth, (int) rectHeight );
else
m_Rect.setRect( 2, (int) (m_MoveHeight - (m_LevelWindow.GetMax() - m_LevelWindow.GetRangeMin()) * fact), rectWidth, (int) rectHeight );
QWidget::repaint();
}
void QmitkSliderLevelWindowWidget::contextMenuEvent( QContextMenuEvent * )
{
m_Contextmenu->setLevelWindowManager(m_Manager.GetPointer());
QPopupMenu *contextMenu = new QPopupMenu( this );
Q_CHECK_PTR( contextMenu );
if (m_ScaleVisible)
contextMenu->insertItem(tr("Hide Scale"), this, SLOT(hideScale()));
else
contextMenu->insertItem(tr("Show Scale"), this, SLOT(showScale()));
contextMenu->insertSeparator();
m_Contextmenu->getContextMenu(contextMenu);
}
void QmitkSliderLevelWindowWidget::hideScale()
{
m_ScaleVisible = false;
update();
}
void QmitkSliderLevelWindowWidget::showScale()
{
m_ScaleVisible = true;
update();
}
void QmitkSliderLevelWindowWidget::setDataTree(mitk::DataTree* tree)
{
m_Manager->SetDataTree(tree);
}
mitk::LevelWindowManager* QmitkSliderLevelWindowWidget::GetManager()
{
return m_Manager.GetPointer();
}
<|endoftext|> |
<commit_before>// Scintilla source code edit control
/** @file LineMarker.cxx
** Defines the look of a line marker in the margin .
**/
// Copyright 1998-2003 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <string.h>
#include "Platform.h"
#include "Scintilla.h"
#include "XPM.h"
#include "LineMarker.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
void LineMarker::RefreshColourPalette(Palette &pal, bool want) {
pal.WantFind(fore, want);
pal.WantFind(back, want);
if (pxpm) {
pxpm->RefreshColourPalette(pal, want);
}
}
void LineMarker::SetXPM(const char *textForm) {
delete pxpm;
pxpm = new XPM(textForm);
markType = SC_MARK_PIXMAP;
}
void LineMarker::SetXPM(const char * const *linesForm) {
delete pxpm;
pxpm = new XPM(linesForm);
markType = SC_MARK_PIXMAP;
}
static void DrawBox(Surface *surface, int centreX, int centreY, int armSize, ColourAllocated fore, ColourAllocated back) {
PRectangle rc;
rc.left = centreX - armSize;
rc.top = centreY - armSize;
rc.right = centreX + armSize + 1;
rc.bottom = centreY + armSize + 1;
surface->RectangleDraw(rc, back, fore);
}
static void DrawCircle(Surface *surface, int centreX, int centreY, int armSize, ColourAllocated fore, ColourAllocated back) {
PRectangle rcCircle;
rcCircle.left = centreX - armSize;
rcCircle.top = centreY - armSize;
rcCircle.right = centreX + armSize + 1;
rcCircle.bottom = centreY + armSize + 1;
surface->Ellipse(rcCircle, back, fore);
}
static void DrawPlus(Surface *surface, int centreX, int centreY, int armSize, ColourAllocated fore) {
PRectangle rcV(centreX, centreY - armSize + 2, centreX + 1, centreY + armSize - 2 + 1);
surface->FillRectangle(rcV, fore);
PRectangle rcH(centreX - armSize + 2, centreY, centreX + armSize - 2 + 1, centreY+1);
surface->FillRectangle(rcH, fore);
}
static void DrawMinus(Surface *surface, int centreX, int centreY, int armSize, ColourAllocated fore) {
PRectangle rcH(centreX - armSize + 2, centreY, centreX + armSize - 2 + 1, centreY+1);
surface->FillRectangle(rcH, fore);
}
void LineMarker::Draw(Surface *surface, PRectangle &rcWhole, Font &fontForCharacter) {
if ((markType == SC_MARK_PIXMAP) && (pxpm)) {
pxpm->Draw(surface, rcWhole);
return;
}
// Restrict most shapes a bit
PRectangle rc = rcWhole;
rc.top++;
rc.bottom--;
int minDim = Platform::Minimum(rc.Width(), rc.Height());
minDim--; // Ensure does not go beyond edge
int centreX = (rc.right + rc.left) / 2;
int centreY = (rc.bottom + rc.top) / 2;
int dimOn2 = minDim / 2;
int dimOn4 = minDim / 4;
int blobSize = dimOn2-1;
int armSize = dimOn2-2;
if (rc.Width() > (rc.Height() * 2)) {
// Wide column is line number so move to left to try to avoid overlapping number
centreX = rc.left + dimOn2 + 1;
}
if (markType == SC_MARK_ROUNDRECT) {
PRectangle rcRounded = rc;
rcRounded.left = rc.left + 1;
rcRounded.right = rc.right - 1;
surface->RoundedRectangle(rcRounded, fore.allocated, back.allocated);
} else if (markType == SC_MARK_CIRCLE) {
PRectangle rcCircle;
rcCircle.left = centreX - dimOn2;
rcCircle.top = centreY - dimOn2;
rcCircle.right = centreX + dimOn2;
rcCircle.bottom = centreY + dimOn2;
surface->Ellipse(rcCircle, fore.allocated, back.allocated);
} else if (markType == SC_MARK_ARROW) {
Point pts[] = {
Point(centreX - dimOn4, centreY - dimOn2),
Point(centreX - dimOn4, centreY + dimOn2),
Point(centreX + dimOn2 - dimOn4, centreY),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_ARROWDOWN) {
Point pts[] = {
Point(centreX - dimOn2, centreY - dimOn4),
Point(centreX + dimOn2, centreY - dimOn4),
Point(centreX, centreY + dimOn2 - dimOn4),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_PLUS) {
Point pts[] = {
Point(centreX - armSize, centreY - 1),
Point(centreX - 1, centreY - 1),
Point(centreX - 1, centreY - armSize),
Point(centreX + 1, centreY - armSize),
Point(centreX + 1, centreY - 1),
Point(centreX + armSize, centreY -1),
Point(centreX + armSize, centreY +1),
Point(centreX + 1, centreY + 1),
Point(centreX + 1, centreY + armSize),
Point(centreX - 1, centreY + armSize),
Point(centreX - 1, centreY + 1),
Point(centreX - armSize, centreY + 1),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_MINUS) {
Point pts[] = {
Point(centreX - armSize, centreY - 1),
Point(centreX + armSize, centreY -1),
Point(centreX + armSize, centreY +1),
Point(centreX - armSize, centreY + 1),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_SMALLRECT) {
PRectangle rcSmall;
rcSmall.left = rc.left + 1;
rcSmall.top = rc.top + 2;
rcSmall.right = rc.right - 1;
rcSmall.bottom = rc.bottom - 2;
surface->RectangleDraw(rcSmall, fore.allocated, back.allocated);
} else if (markType == SC_MARK_EMPTY || markType == SC_MARK_BACKGROUND || markType == SC_MARK_UNDERLINE) {
// An invisible marker so don't draw anything
} else if (markType == SC_MARK_VLINE) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rcWhole.bottom);
} else if (markType == SC_MARK_LCORNER) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rc.top + dimOn2);
surface->LineTo(rc.right - 2, rc.top + dimOn2);
} else if (markType == SC_MARK_TCORNER) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rc.top + dimOn2);
surface->LineTo(rc.right - 2, rc.top + dimOn2);
} else if (markType == SC_MARK_LCORNERCURVE) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rc.top + dimOn2-3);
surface->LineTo(centreX+3, rc.top + dimOn2);
surface->LineTo(rc.right - 1, rc.top + dimOn2);
} else if (markType == SC_MARK_TCORNERCURVE) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rc.top + dimOn2-3);
surface->LineTo(centreX+3, rc.top + dimOn2);
surface->LineTo(rc.right - 1, rc.top + dimOn2);
} else if (markType == SC_MARK_BOXPLUS) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
} else if (markType == SC_MARK_BOXPLUSCONNECTED) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType == SC_MARK_BOXMINUS) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
} else if (markType == SC_MARK_BOXMINUSCONNECTED) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType == SC_MARK_CIRCLEPLUS) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
} else if (markType == SC_MARK_CIRCLEPLUSCONNECTED) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType == SC_MARK_CIRCLEMINUS) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
} else if (markType == SC_MARK_CIRCLEMINUSCONNECTED) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType >= SC_MARK_CHARACTER) {
char character[1];
character[0] = static_cast<char>(markType - SC_MARK_CHARACTER);
int width = surface->WidthText(fontForCharacter, character, 1);
rc.left += (rc.Width() - width) / 2;
rc.right = rc.left + width;
surface->DrawTextClipped(rc, fontForCharacter, rc.bottom - 2,
character, 1, fore.allocated, back.allocated);
} else if (markType == SC_MARK_DOTDOTDOT) {
int right = centreX - 6;
for (int b=0; b<3; b++) {
PRectangle rcBlob(right, rc.bottom - 4, right + 2, rc.bottom-2);
surface->FillRectangle(rcBlob, fore.allocated);
right += 5;
}
} else if (markType == SC_MARK_ARROWS) {
surface->PenColour(fore.allocated);
int right = centreX - 2;
for (int b=0; b<3; b++) {
surface->MoveTo(right - 4, centreY - 4);
surface->LineTo(right, centreY);
surface->LineTo(right - 5, centreY + 5);
right += 4;
}
} else if (markType == SC_MARK_SHORTARROW) {
Point pts[] = {
Point(centreX, centreY + dimOn2),
Point(centreX + dimOn2, centreY),
Point(centreX, centreY - dimOn2),
Point(centreX, centreY - dimOn4),
Point(centreX - dimOn4, centreY - dimOn4),
Point(centreX - dimOn4, centreY + dimOn4),
Point(centreX, centreY + dimOn4),
Point(centreX, centreY + dimOn2),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_LEFTRECT) {
PRectangle rcLeft = rcWhole;
rcLeft.right = rcLeft.left + 4;
surface->FillRectangle(rcLeft, back.allocated);
} else { // SC_MARK_FULLRECT
surface->FillRectangle(rcWhole, back.allocated);
}
}
<commit_msg>Don't display SC_MARK_AVAILABLE markers.<commit_after>// Scintilla source code edit control
/** @file LineMarker.cxx
** Defines the look of a line marker in the margin .
**/
// Copyright 1998-2003 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <string.h>
#include "Platform.h"
#include "Scintilla.h"
#include "XPM.h"
#include "LineMarker.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
void LineMarker::RefreshColourPalette(Palette &pal, bool want) {
pal.WantFind(fore, want);
pal.WantFind(back, want);
if (pxpm) {
pxpm->RefreshColourPalette(pal, want);
}
}
void LineMarker::SetXPM(const char *textForm) {
delete pxpm;
pxpm = new XPM(textForm);
markType = SC_MARK_PIXMAP;
}
void LineMarker::SetXPM(const char * const *linesForm) {
delete pxpm;
pxpm = new XPM(linesForm);
markType = SC_MARK_PIXMAP;
}
static void DrawBox(Surface *surface, int centreX, int centreY, int armSize, ColourAllocated fore, ColourAllocated back) {
PRectangle rc;
rc.left = centreX - armSize;
rc.top = centreY - armSize;
rc.right = centreX + armSize + 1;
rc.bottom = centreY + armSize + 1;
surface->RectangleDraw(rc, back, fore);
}
static void DrawCircle(Surface *surface, int centreX, int centreY, int armSize, ColourAllocated fore, ColourAllocated back) {
PRectangle rcCircle;
rcCircle.left = centreX - armSize;
rcCircle.top = centreY - armSize;
rcCircle.right = centreX + armSize + 1;
rcCircle.bottom = centreY + armSize + 1;
surface->Ellipse(rcCircle, back, fore);
}
static void DrawPlus(Surface *surface, int centreX, int centreY, int armSize, ColourAllocated fore) {
PRectangle rcV(centreX, centreY - armSize + 2, centreX + 1, centreY + armSize - 2 + 1);
surface->FillRectangle(rcV, fore);
PRectangle rcH(centreX - armSize + 2, centreY, centreX + armSize - 2 + 1, centreY+1);
surface->FillRectangle(rcH, fore);
}
static void DrawMinus(Surface *surface, int centreX, int centreY, int armSize, ColourAllocated fore) {
PRectangle rcH(centreX - armSize + 2, centreY, centreX + armSize - 2 + 1, centreY+1);
surface->FillRectangle(rcH, fore);
}
void LineMarker::Draw(Surface *surface, PRectangle &rcWhole, Font &fontForCharacter) {
if ((markType == SC_MARK_PIXMAP) && (pxpm)) {
pxpm->Draw(surface, rcWhole);
return;
}
// Restrict most shapes a bit
PRectangle rc = rcWhole;
rc.top++;
rc.bottom--;
int minDim = Platform::Minimum(rc.Width(), rc.Height());
minDim--; // Ensure does not go beyond edge
int centreX = (rc.right + rc.left) / 2;
int centreY = (rc.bottom + rc.top) / 2;
int dimOn2 = minDim / 2;
int dimOn4 = minDim / 4;
int blobSize = dimOn2-1;
int armSize = dimOn2-2;
if (rc.Width() > (rc.Height() * 2)) {
// Wide column is line number so move to left to try to avoid overlapping number
centreX = rc.left + dimOn2 + 1;
}
if (markType == SC_MARK_ROUNDRECT) {
PRectangle rcRounded = rc;
rcRounded.left = rc.left + 1;
rcRounded.right = rc.right - 1;
surface->RoundedRectangle(rcRounded, fore.allocated, back.allocated);
} else if (markType == SC_MARK_CIRCLE) {
PRectangle rcCircle;
rcCircle.left = centreX - dimOn2;
rcCircle.top = centreY - dimOn2;
rcCircle.right = centreX + dimOn2;
rcCircle.bottom = centreY + dimOn2;
surface->Ellipse(rcCircle, fore.allocated, back.allocated);
} else if (markType == SC_MARK_ARROW) {
Point pts[] = {
Point(centreX - dimOn4, centreY - dimOn2),
Point(centreX - dimOn4, centreY + dimOn2),
Point(centreX + dimOn2 - dimOn4, centreY),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_ARROWDOWN) {
Point pts[] = {
Point(centreX - dimOn2, centreY - dimOn4),
Point(centreX + dimOn2, centreY - dimOn4),
Point(centreX, centreY + dimOn2 - dimOn4),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_PLUS) {
Point pts[] = {
Point(centreX - armSize, centreY - 1),
Point(centreX - 1, centreY - 1),
Point(centreX - 1, centreY - armSize),
Point(centreX + 1, centreY - armSize),
Point(centreX + 1, centreY - 1),
Point(centreX + armSize, centreY -1),
Point(centreX + armSize, centreY +1),
Point(centreX + 1, centreY + 1),
Point(centreX + 1, centreY + armSize),
Point(centreX - 1, centreY + armSize),
Point(centreX - 1, centreY + 1),
Point(centreX - armSize, centreY + 1),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_MINUS) {
Point pts[] = {
Point(centreX - armSize, centreY - 1),
Point(centreX + armSize, centreY -1),
Point(centreX + armSize, centreY +1),
Point(centreX - armSize, centreY + 1),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_SMALLRECT) {
PRectangle rcSmall;
rcSmall.left = rc.left + 1;
rcSmall.top = rc.top + 2;
rcSmall.right = rc.right - 1;
rcSmall.bottom = rc.bottom - 2;
surface->RectangleDraw(rcSmall, fore.allocated, back.allocated);
} else if (markType == SC_MARK_EMPTY || markType == SC_MARK_BACKGROUND ||
markType == SC_MARK_UNDERLINE || markType == SC_MARK_AVAILABLE) {
// An invisible marker so don't draw anything
} else if (markType == SC_MARK_VLINE) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rcWhole.bottom);
} else if (markType == SC_MARK_LCORNER) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rc.top + dimOn2);
surface->LineTo(rc.right - 2, rc.top + dimOn2);
} else if (markType == SC_MARK_TCORNER) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rc.top + dimOn2);
surface->LineTo(rc.right - 2, rc.top + dimOn2);
} else if (markType == SC_MARK_LCORNERCURVE) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rc.top + dimOn2-3);
surface->LineTo(centreX+3, rc.top + dimOn2);
surface->LineTo(rc.right - 1, rc.top + dimOn2);
} else if (markType == SC_MARK_TCORNERCURVE) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rc.top + dimOn2-3);
surface->LineTo(centreX+3, rc.top + dimOn2);
surface->LineTo(rc.right - 1, rc.top + dimOn2);
} else if (markType == SC_MARK_BOXPLUS) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
} else if (markType == SC_MARK_BOXPLUSCONNECTED) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType == SC_MARK_BOXMINUS) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
} else if (markType == SC_MARK_BOXMINUSCONNECTED) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType == SC_MARK_CIRCLEPLUS) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
} else if (markType == SC_MARK_CIRCLEPLUSCONNECTED) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType == SC_MARK_CIRCLEMINUS) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
} else if (markType == SC_MARK_CIRCLEMINUSCONNECTED) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType >= SC_MARK_CHARACTER) {
char character[1];
character[0] = static_cast<char>(markType - SC_MARK_CHARACTER);
int width = surface->WidthText(fontForCharacter, character, 1);
rc.left += (rc.Width() - width) / 2;
rc.right = rc.left + width;
surface->DrawTextClipped(rc, fontForCharacter, rc.bottom - 2,
character, 1, fore.allocated, back.allocated);
} else if (markType == SC_MARK_DOTDOTDOT) {
int right = centreX - 6;
for (int b=0; b<3; b++) {
PRectangle rcBlob(right, rc.bottom - 4, right + 2, rc.bottom-2);
surface->FillRectangle(rcBlob, fore.allocated);
right += 5;
}
} else if (markType == SC_MARK_ARROWS) {
surface->PenColour(fore.allocated);
int right = centreX - 2;
for (int b=0; b<3; b++) {
surface->MoveTo(right - 4, centreY - 4);
surface->LineTo(right, centreY);
surface->LineTo(right - 5, centreY + 5);
right += 4;
}
} else if (markType == SC_MARK_SHORTARROW) {
Point pts[] = {
Point(centreX, centreY + dimOn2),
Point(centreX + dimOn2, centreY),
Point(centreX, centreY - dimOn2),
Point(centreX, centreY - dimOn4),
Point(centreX - dimOn4, centreY - dimOn4),
Point(centreX - dimOn4, centreY + dimOn4),
Point(centreX, centreY + dimOn4),
Point(centreX, centreY + dimOn2),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_LEFTRECT) {
PRectangle rcLeft = rcWhole;
rcLeft.right = rcLeft.left + 4;
surface->FillRectangle(rcLeft, back.allocated);
} else { // SC_MARK_FULLRECT
surface->FillRectangle(rcWhole, back.allocated);
}
}
<|endoftext|> |
<commit_before>#include "MSA_Stream.hpp"
#include "file_io.hpp"
static void read_chunk( MSA_Stream::file_type::pointer fptr,
const size_t number,
MSA_Stream::container_type& prefetch_buffer,
const size_t max_read,
size_t& num_read)
{
prefetch_buffer.clear();
if (!fptr) {
throw std::runtime_error{"fptr was invalid!"};
}
int sites = 0;
int number_left = std::min(number, max_read - num_read);
if (number_left == 0) {
return;
}
char * sequence = nullptr;
char * header = nullptr;
long sequence_length;
long header_length;
long sequence_number;
while (number_left > 0 and pll_fasta_getnext( fptr,
&header,
&header_length,
&sequence,
&sequence_length,
&sequence_number))
{
if (sites and (sites != sequence_length)) {
throw std::runtime_error{"MSA file does not contain equal size sequences"};
}
if (!sites) sites = sequence_length;
for (long i = 0; i < sequence_length; ++i) {
sequence[i] = toupper(sequence[i]);
}
prefetch_buffer.append(header, sequence);
free(sequence);
free(header);
sites = sequence_length;
number_left--;
}
num_read += prefetch_buffer.size();
}
MSA_Stream::MSA_Stream( const std::string& msa_file,
const size_t initial_size,
const size_t offset,
const size_t max_read)
: fptr_(nullptr, fasta_close)
, max_read_(max_read)
{
fptr_ = file_type(pll_fasta_open(msa_file.c_str(), pll_map_fasta),
fasta_close);
if (!fptr_) {
throw std::runtime_error{std::string("Cannot open file: ") + msa_file};
}
if (offset) {
if (pll_fasta_fseek(fptr_.get(), offset, SEEK_SET)) {
throw std::runtime_error{"Unable to fseek on the fasta file."};
}
}
read_chunk(fptr_.get(), initial_size, prefetch_chunk_, max_read_, num_read_);
// prefetcher_ = std::thread(read_chunk, fptr_.get(), initial_size, std::ref(prefetch_chunk_));
}
size_t MSA_Stream::read_next( MSA_Stream::container_type& result,
const size_t number)
{
#ifdef __PREFETCH
// join prefetching thread to ensure new chunk exists
if (prefetcher_.joinable()) {
prefetcher_.join();
}
#endif
// perform pointer swap to data
std::swap(result, prefetch_chunk_);
if (!fptr_) {
throw std::runtime_error{"fptr was invalid during read_next!"};
}
// start request next chunk from prefetcher (async)
#ifdef __PREFETCH
prefetcher_ = std::thread(read_chunk,
fptr_.get(),
number,
std::ref(prefetch_chunk_),
max_read_,
std::ref(num_read_));
#else
read_chunk(fptr_.get(), initial_size, prefetch_chunk_, max_read_, num_read_);
#endif
// return size of current buffer
return result.size();
}
MSA_Stream::~MSA_Stream()
{
#ifdef __PREFETCH
// avoid dangling threads
if (prefetcher_.joinable()) {
prefetcher_.join();
}
#endif
}
<commit_msg>fixed compile error when not using prefetching<commit_after>#include "MSA_Stream.hpp"
#include "file_io.hpp"
static void read_chunk( MSA_Stream::file_type::pointer fptr,
const size_t number,
MSA_Stream::container_type& prefetch_buffer,
const size_t max_read,
size_t& num_read)
{
prefetch_buffer.clear();
if (!fptr) {
throw std::runtime_error{"fptr was invalid!"};
}
int sites = 0;
int number_left = std::min(number, max_read - num_read);
if (number_left == 0) {
return;
}
char * sequence = nullptr;
char * header = nullptr;
long sequence_length;
long header_length;
long sequence_number;
while (number_left > 0 and pll_fasta_getnext( fptr,
&header,
&header_length,
&sequence,
&sequence_length,
&sequence_number))
{
if (sites and (sites != sequence_length)) {
throw std::runtime_error{"MSA file does not contain equal size sequences"};
}
if (!sites) sites = sequence_length;
for (long i = 0; i < sequence_length; ++i) {
sequence[i] = toupper(sequence[i]);
}
prefetch_buffer.append(header, sequence);
free(sequence);
free(header);
sites = sequence_length;
number_left--;
}
num_read += prefetch_buffer.size();
}
MSA_Stream::MSA_Stream( const std::string& msa_file,
const size_t initial_size,
const size_t offset,
const size_t max_read)
: fptr_(nullptr, fasta_close)
, max_read_(max_read)
{
fptr_ = file_type(pll_fasta_open(msa_file.c_str(), pll_map_fasta),
fasta_close);
if (!fptr_) {
throw std::runtime_error{std::string("Cannot open file: ") + msa_file};
}
if (offset) {
if (pll_fasta_fseek(fptr_.get(), offset, SEEK_SET)) {
throw std::runtime_error{"Unable to fseek on the fasta file."};
}
}
read_chunk(fptr_.get(), initial_size, prefetch_chunk_, max_read_, num_read_);
// prefetcher_ = std::thread(read_chunk, fptr_.get(), initial_size, std::ref(prefetch_chunk_));
}
size_t MSA_Stream::read_next( MSA_Stream::container_type& result,
const size_t number)
{
#ifdef __PREFETCH
// join prefetching thread to ensure new chunk exists
if (prefetcher_.joinable()) {
prefetcher_.join();
}
#endif
// perform pointer swap to data
std::swap(result, prefetch_chunk_);
if (!fptr_) {
throw std::runtime_error{"fptr was invalid during read_next!"};
}
// start request next chunk from prefetcher (async)
#ifdef __PREFETCH
prefetcher_ = std::thread(read_chunk,
fptr_.get(),
number,
std::ref(prefetch_chunk_),
max_read_,
std::ref(num_read_));
#else
read_chunk(fptr_.get(), number, prefetch_chunk_, max_read_, num_read_);
#endif
// return size of current buffer
return result.size();
}
MSA_Stream::~MSA_Stream()
{
#ifdef __PREFETCH
// avoid dangling threads
if (prefetcher_.joinable()) {
prefetcher_.join();
}
#endif
}
<|endoftext|> |
<commit_before>#include "MainWindow.hpp"
#include "ui_MainWindow.h"
#include <algorithm>
#include <unordered_set>
#include <QProgressBar>
#include <QLabel>
#include <QSystemTrayIcon>
#include <QMessageBox>
#include <QDebug>
#include "matrix/Room.hpp"
#include "matrix/Session.hpp"
#include "sort.hpp"
#include "RoomView.hpp"
#include "ChatWindow.hpp"
#include "JoinDialog.hpp"
MainWindow::MainWindow(matrix::Session &session)
: ui(new Ui::MainWindow), session_(session),
progress_(new QProgressBar(this)), sync_label_(new QLabel(this)) {
ui->setupUi(this);
ui->status_bar->addPermanentWidget(sync_label_);
ui->status_bar->addPermanentWidget(progress_);
auto tray = new QSystemTrayIcon(QIcon::fromTheme("user-available"), this);
tray->setContextMenu(ui->menu_matrix);
connect(tray, &QSystemTrayIcon::activated, [this](QSystemTrayIcon::ActivationReason reason) {
if(reason == QSystemTrayIcon::Trigger) {
setVisible(!isVisible());
}
});
tray->show();
connect(ui->action_log_out, &QAction::triggered, this, &MainWindow::log_out);
connect(ui->action_join, &QAction::triggered, [this]() {
QPointer<JoinDialog> dialog(new JoinDialog);
dialog->setAttribute(Qt::WA_DeleteOnClose);
connect(dialog, &QDialog::accepted, [this, dialog]() {
const QString room = dialog->room();
auto reply = session_.join(room);
connect(reply, &matrix::JoinRequest::error, [room, dialog](const QString &msg) {
if(!dialog) return;
auto error = new QMessageBox(QMessageBox::Critical,
tr("Failed to join room"),
tr("Couldn't join %1: %2")
.arg(room)
.arg(msg),
QMessageBox::Close,
dialog);
error->open();
connect(error, &QDialog::finished, dialog, [dialog]() { if(dialog) dialog->setEnabled(true); });
});
connect(reply, &matrix::JoinRequest::success, dialog, &QWidget::close);
});
dialog->open();
});
connect(&session_, &matrix::Session::error, [this](QString msg) {
qDebug() << "Session error: " << msg;
});
connect(&session_, &matrix::Session::synced_changed, [this]() {
if(session_.synced()) {
sync_label_->hide();
} else {
sync_label_->setText(tr("Disconnected"));
sync_label_->show();
}
});
connect(&session_, &matrix::Session::sync_progress, this, &MainWindow::sync_progress);
connect(&session_, &matrix::Session::sync_complete, [this]() {
progress_->hide();
sync_label_->hide();
});
connect(&session_, &matrix::Session::joined, this, &MainWindow::joined);
ui->action_quit->setShortcuts(QKeySequence::Quit);
connect(ui->action_quit, &QAction::triggered, this, &MainWindow::quit);
connect(ui->room_list, &QListWidget::itemActivated, [this](QListWidgetItem *){
std::unordered_set<ChatWindow *> windows;
for(auto item : ui->room_list->selectedItems()) {
auto &room = *reinterpret_cast<matrix::Room *>(item->data(Qt::UserRole).value<void*>());
ChatWindow *window = nullptr;
auto &i = rooms_.at(room.id());
if(i.window) {
window = i.window; // Focus in existing window
} else if(last_focused_) {
window = last_focused_; // Add to most recently used window
} else {
// Select arbitrary window
for(auto &j : rooms_) {
if(j.second.window) {
window = j.second.window;
break;
}
}
if(!window) {
// Create first window
window = spawn_chat_window();
}
}
window->add_or_focus(room);
windows.insert(window);
}
for(auto window : windows) {
window->show();
window->activateWindow();
}
});
sync_progress(0, -1);
for(auto room : session_.rooms()) {
joined(*room);
}
}
MainWindow::~MainWindow() {
std::unordered_set<ChatWindow *> windows;
for(auto &room : rooms_) {
windows.insert(room.second.window);
}
for(auto window : windows) {
delete window;
}
delete ui;
}
void MainWindow::joined(matrix::Room &room) {
auto &i = rooms_.emplace(
std::piecewise_construct,
std::forward_as_tuple(room.id()),
std::forward_as_tuple()).first->second;
i.item = new QListWidgetItem;
i.item->setData(Qt::UserRole, QVariant::fromValue(reinterpret_cast<void*>(&room)));
// TODO: Sorting
ui->room_list->addItem(i.item);
i.display_name = room.pretty_name_highlights();
i.highlight_count = room.highlight_count() + room.notification_count();
i.has_unread = room.has_unread();
update_room(i);
connect(&room, &matrix::Room::highlight_count_changed, [this, &room](uint64_t old) {
update_room(room);
if(old <= room.highlight_count()) {
highlight(room.id());
}
});
connect(&room, &matrix::Room::notification_count_changed, [this, &room](uint64_t old) {
update_room(room);
if(old <= room.notification_count()) {
highlight(room.id());
}
});
auto &&just_update = [this, &room]() { update_room(room); };
connect(&room, &matrix::Room::name_changed, just_update);
connect(&room, &matrix::Room::canonical_alias_changed, just_update);
connect(&room, &matrix::Room::aliases_changed, just_update);
connect(&room, &matrix::Room::membership_changed, just_update);
connect(&room, &matrix::Room::receipts_changed, just_update);
connect(&room, &matrix::Room::message, [this, &room](const matrix::proto::Event &e) {
if(room.has_unread()) {
auto &i = rooms_.at(room.id());
i.has_unread = true;
update_room(i);
} else {
qDebug() << "new" << e.type << e.event_id << "on" << room.pretty_name() << "already read";
}
});
}
void MainWindow::highlight(const matrix::RoomID &room) {
QWidget *window = rooms_.at(room).window;
if(!window) {
window = this;
}
window->show();
QApplication::alert(window);
}
void MainWindow::update_room(matrix::Room &room) {
auto &i = rooms_.at(room.id());
i.display_name = room.pretty_name_highlights();
i.highlight_count = room.highlight_count() + room.notification_count();
i.has_unread = room.has_unread();
update_room(i);
}
void MainWindow::update_room(RoomInfo &info) {
info.item->setText(info.display_name);
auto f = font();
f.setBold(info.highlight_count != 0 || info.has_unread);
info.item->setFont(f);
}
void MainWindow::sync_progress(qint64 received, qint64 total) {
sync_label_->setText(tr("Synchronizing..."));
sync_label_->show();
progress_->show();
if(total == -1 || total == 0) {
progress_->setMaximum(0);
} else {
progress_->setMaximum(1000);
progress_->setValue(1000 * static_cast<float>(received)/static_cast<float>(total));
}
}
RoomWindowBridge::RoomWindowBridge(matrix::Room &room, ChatWindow &parent) : QObject(&parent), room_(room), window_(parent) {
connect(&room, &matrix::Room::highlight_count_changed, this, &RoomWindowBridge::display_changed);
connect(&room, &matrix::Room::notification_count_changed, this, &RoomWindowBridge::display_changed);
connect(&room, &matrix::Room::name_changed, this, &RoomWindowBridge::display_changed);
connect(&room, &matrix::Room::canonical_alias_changed, this, &RoomWindowBridge::display_changed);
connect(&room, &matrix::Room::aliases_changed, this, &RoomWindowBridge::display_changed);
connect(&room, &matrix::Room::membership_changed, this, &RoomWindowBridge::display_changed);
connect(&room, &matrix::Room::receipts_changed, this, &RoomWindowBridge::display_changed);
connect(&room, &matrix::Room::message, this, &RoomWindowBridge::display_changed);
connect(&parent, &ChatWindow::released, this, &RoomWindowBridge::check_release);
}
void RoomWindowBridge::display_changed() {
window_.room_display_changed(room_);
}
void RoomWindowBridge::check_release(const matrix::RoomID &room) {
if(room_.id() == room) deleteLater();
}
ChatWindow *MainWindow::spawn_chat_window() {
// We don't create these as children to prevent Qt from hinting to WMs that they should be floating
auto window = new ChatWindow;
connect(window, &ChatWindow::focused, [this, window](const matrix::RoomID &r) {
last_focused_ = window;
});
connect(window, &ChatWindow::claimed, [this, window](const matrix::RoomID &r) {
rooms_.at(r).window = window;
new RoomWindowBridge(*session_.room_from_id(r), *window);
});
connect(window, &ChatWindow::released, [this](const matrix::RoomID &rid) {
rooms_.at(rid).window = nullptr;
});
connect(window, &ChatWindow::pop_out, [this](const matrix::RoomID &r, RoomView *v) {
auto w = spawn_chat_window();
w->add(*session_.room_from_id(r), v);
w->show();
w->raise();
w->activateWindow();
});
return window;
}
<commit_msg>Remove unnecessary debug print<commit_after>#include "MainWindow.hpp"
#include "ui_MainWindow.h"
#include <algorithm>
#include <unordered_set>
#include <QProgressBar>
#include <QLabel>
#include <QSystemTrayIcon>
#include <QMessageBox>
#include <QDebug>
#include "matrix/Room.hpp"
#include "matrix/Session.hpp"
#include "sort.hpp"
#include "RoomView.hpp"
#include "ChatWindow.hpp"
#include "JoinDialog.hpp"
MainWindow::MainWindow(matrix::Session &session)
: ui(new Ui::MainWindow), session_(session),
progress_(new QProgressBar(this)), sync_label_(new QLabel(this)) {
ui->setupUi(this);
ui->status_bar->addPermanentWidget(sync_label_);
ui->status_bar->addPermanentWidget(progress_);
auto tray = new QSystemTrayIcon(QIcon::fromTheme("user-available"), this);
tray->setContextMenu(ui->menu_matrix);
connect(tray, &QSystemTrayIcon::activated, [this](QSystemTrayIcon::ActivationReason reason) {
if(reason == QSystemTrayIcon::Trigger) {
setVisible(!isVisible());
}
});
tray->show();
connect(ui->action_log_out, &QAction::triggered, this, &MainWindow::log_out);
connect(ui->action_join, &QAction::triggered, [this]() {
QPointer<JoinDialog> dialog(new JoinDialog);
dialog->setAttribute(Qt::WA_DeleteOnClose);
connect(dialog, &QDialog::accepted, [this, dialog]() {
const QString room = dialog->room();
auto reply = session_.join(room);
connect(reply, &matrix::JoinRequest::error, [room, dialog](const QString &msg) {
if(!dialog) return;
auto error = new QMessageBox(QMessageBox::Critical,
tr("Failed to join room"),
tr("Couldn't join %1: %2")
.arg(room)
.arg(msg),
QMessageBox::Close,
dialog);
error->open();
connect(error, &QDialog::finished, dialog, [dialog]() { if(dialog) dialog->setEnabled(true); });
});
connect(reply, &matrix::JoinRequest::success, dialog, &QWidget::close);
});
dialog->open();
});
connect(&session_, &matrix::Session::error, [this](QString msg) {
qDebug() << "Session error: " << msg;
});
connect(&session_, &matrix::Session::synced_changed, [this]() {
if(session_.synced()) {
sync_label_->hide();
} else {
sync_label_->setText(tr("Disconnected"));
sync_label_->show();
}
});
connect(&session_, &matrix::Session::sync_progress, this, &MainWindow::sync_progress);
connect(&session_, &matrix::Session::sync_complete, [this]() {
progress_->hide();
sync_label_->hide();
});
connect(&session_, &matrix::Session::joined, this, &MainWindow::joined);
ui->action_quit->setShortcuts(QKeySequence::Quit);
connect(ui->action_quit, &QAction::triggered, this, &MainWindow::quit);
connect(ui->room_list, &QListWidget::itemActivated, [this](QListWidgetItem *){
std::unordered_set<ChatWindow *> windows;
for(auto item : ui->room_list->selectedItems()) {
auto &room = *reinterpret_cast<matrix::Room *>(item->data(Qt::UserRole).value<void*>());
ChatWindow *window = nullptr;
auto &i = rooms_.at(room.id());
if(i.window) {
window = i.window; // Focus in existing window
} else if(last_focused_) {
window = last_focused_; // Add to most recently used window
} else {
// Select arbitrary window
for(auto &j : rooms_) {
if(j.second.window) {
window = j.second.window;
break;
}
}
if(!window) {
// Create first window
window = spawn_chat_window();
}
}
window->add_or_focus(room);
windows.insert(window);
}
for(auto window : windows) {
window->show();
window->activateWindow();
}
});
sync_progress(0, -1);
for(auto room : session_.rooms()) {
joined(*room);
}
}
MainWindow::~MainWindow() {
std::unordered_set<ChatWindow *> windows;
for(auto &room : rooms_) {
windows.insert(room.second.window);
}
for(auto window : windows) {
delete window;
}
delete ui;
}
void MainWindow::joined(matrix::Room &room) {
auto &i = rooms_.emplace(
std::piecewise_construct,
std::forward_as_tuple(room.id()),
std::forward_as_tuple()).first->second;
i.item = new QListWidgetItem;
i.item->setData(Qt::UserRole, QVariant::fromValue(reinterpret_cast<void*>(&room)));
// TODO: Sorting
ui->room_list->addItem(i.item);
i.display_name = room.pretty_name_highlights();
i.highlight_count = room.highlight_count() + room.notification_count();
i.has_unread = room.has_unread();
update_room(i);
connect(&room, &matrix::Room::highlight_count_changed, [this, &room](uint64_t old) {
update_room(room);
if(old <= room.highlight_count()) {
highlight(room.id());
}
});
connect(&room, &matrix::Room::notification_count_changed, [this, &room](uint64_t old) {
update_room(room);
if(old <= room.notification_count()) {
highlight(room.id());
}
});
auto &&just_update = [this, &room]() { update_room(room); };
connect(&room, &matrix::Room::name_changed, just_update);
connect(&room, &matrix::Room::canonical_alias_changed, just_update);
connect(&room, &matrix::Room::aliases_changed, just_update);
connect(&room, &matrix::Room::membership_changed, just_update);
connect(&room, &matrix::Room::receipts_changed, just_update);
connect(&room, &matrix::Room::message, [this, &room](const matrix::proto::Event &e) {
if(room.has_unread()) {
auto &i = rooms_.at(room.id());
i.has_unread = true;
update_room(i);
}
});
}
void MainWindow::highlight(const matrix::RoomID &room) {
QWidget *window = rooms_.at(room).window;
if(!window) {
window = this;
}
window->show();
QApplication::alert(window);
}
void MainWindow::update_room(matrix::Room &room) {
auto &i = rooms_.at(room.id());
i.display_name = room.pretty_name_highlights();
i.highlight_count = room.highlight_count() + room.notification_count();
i.has_unread = room.has_unread();
update_room(i);
}
void MainWindow::update_room(RoomInfo &info) {
info.item->setText(info.display_name);
auto f = font();
f.setBold(info.highlight_count != 0 || info.has_unread);
info.item->setFont(f);
}
void MainWindow::sync_progress(qint64 received, qint64 total) {
sync_label_->setText(tr("Synchronizing..."));
sync_label_->show();
progress_->show();
if(total == -1 || total == 0) {
progress_->setMaximum(0);
} else {
progress_->setMaximum(1000);
progress_->setValue(1000 * static_cast<float>(received)/static_cast<float>(total));
}
}
RoomWindowBridge::RoomWindowBridge(matrix::Room &room, ChatWindow &parent) : QObject(&parent), room_(room), window_(parent) {
connect(&room, &matrix::Room::highlight_count_changed, this, &RoomWindowBridge::display_changed);
connect(&room, &matrix::Room::notification_count_changed, this, &RoomWindowBridge::display_changed);
connect(&room, &matrix::Room::name_changed, this, &RoomWindowBridge::display_changed);
connect(&room, &matrix::Room::canonical_alias_changed, this, &RoomWindowBridge::display_changed);
connect(&room, &matrix::Room::aliases_changed, this, &RoomWindowBridge::display_changed);
connect(&room, &matrix::Room::membership_changed, this, &RoomWindowBridge::display_changed);
connect(&room, &matrix::Room::receipts_changed, this, &RoomWindowBridge::display_changed);
connect(&room, &matrix::Room::message, this, &RoomWindowBridge::display_changed);
connect(&parent, &ChatWindow::released, this, &RoomWindowBridge::check_release);
}
void RoomWindowBridge::display_changed() {
window_.room_display_changed(room_);
}
void RoomWindowBridge::check_release(const matrix::RoomID &room) {
if(room_.id() == room) deleteLater();
}
ChatWindow *MainWindow::spawn_chat_window() {
// We don't create these as children to prevent Qt from hinting to WMs that they should be floating
auto window = new ChatWindow;
connect(window, &ChatWindow::focused, [this, window](const matrix::RoomID &r) {
last_focused_ = window;
});
connect(window, &ChatWindow::claimed, [this, window](const matrix::RoomID &r) {
rooms_.at(r).window = window;
new RoomWindowBridge(*session_.room_from_id(r), *window);
});
connect(window, &ChatWindow::released, [this](const matrix::RoomID &rid) {
rooms_.at(rid).window = nullptr;
});
connect(window, &ChatWindow::pop_out, [this](const matrix::RoomID &r, RoomView *v) {
auto w = spawn_chat_window();
w->add(*session_.room_from_id(r), v);
w->show();
w->raise();
w->activateWindow();
});
return window;
}
<|endoftext|> |
<commit_before>#include "Mandelbrot.h"
Mandelbrot::Mandelbrot()
{
}
void Mandelbrot::Update(short *vals) const
{
int step = parallel_height / thread::hardware_concurrency();
vector<thread> threads;
for (int i = 0; i < parallel_height; i += step)
threads.push_back(thread(&Mandelbrot::Slice, *this, ref(vals), (parallel_pos * parallel_height) + i, min((parallel_pos * parallel_height) + i + step, (parallel_pos + 1) * parallel_height)));
for (auto &t : threads) t.join();
}
void Mandelbrot::Slice(short *vals, int minY, int maxY) const
{
long double real = 0L * zoom - width / 2.0L * zoom + offx;
long double imags = minY * zoom - parallel_height / 2.0L * zoom + offy;
for (int x = 0; x < width; x++, real += zoom)
{
long double imag = imags;
for (int y = minY; y < maxY; y++, imag += zoom)
vals[(y - (parallel_pos * parallel_height)) * width + x] = (short)(Calculate(real, imag) * 100);
}
}
double Mandelbrot::Calculate(long double r, long double i) const
{
long double zReal = r, zImag = i;
for (int c = 0; c < iter; c++)
{
long double r2 = zReal * zReal, i2 = zImag * zImag;
if (r2 + i2 > 4.0) return c + 1 - (log(log(r2 + i2) / 2) / log(2));
zImag = 2.0L * zReal * zImag + i;
zReal = r2 - i2 + r;
}
return -1;
}
<commit_msg>Render to the correct height of the portion of the fractal<commit_after>#include "Mandelbrot.h"
Mandelbrot::Mandelbrot()
{
}
void Mandelbrot::Update(short *vals) const
{
int step = parallel_height / thread::hardware_concurrency();
vector<thread> threads;
for (int i = 0; i < parallel_height; i += step)
threads.push_back(thread(&Mandelbrot::Slice, *this, ref(vals), (parallel_pos * parallel_height) + i, min((parallel_pos * parallel_height) + i + step, height)));
for (auto &t : threads) t.join();
}
void Mandelbrot::Slice(short *vals, int minY, int maxY) const
{
long double real = 0L * zoom - width / 2.0L * zoom + offx;
long double imags = minY * zoom - parallel_height / 2.0L * zoom + offy;
for (int x = 0; x < width; x++, real += zoom)
{
long double imag = imags;
for (int y = minY; y < maxY; y++, imag += zoom)
vals[(y - (parallel_pos * parallel_height)) * width + x] = (short)(Calculate(real, imag) * 100);
}
}
double Mandelbrot::Calculate(long double r, long double i) const
{
long double zReal = r, zImag = i;
for (int c = 0; c < iter; c++)
{
long double r2 = zReal * zReal, i2 = zImag * zImag;
if (r2 + i2 > 4.0) return c + 1 - (log(log(r2 + i2) / 2) / log(2));
zImag = 2.0L * zReal * zImag + i;
zReal = r2 - i2 + r;
}
return -1;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "allocators.h"
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
// This is used to attempt to keep keying material out of swap
// Note that VirtualLock does not provide this as a guarantee on Windows,
// but, in practice, memory that has been VirtualLock'd almost never gets written to
// the pagefile except in rare circumstances where memory is extremely low.
#else
#include <sys/mman.h>
#include <limits.h> // for PAGESIZE
#include <unistd.h> // for sysconf
#endif
LockedPageManager* LockedPageManager::_instance = NULL;
boost::once_flag LockedPageManager::init_flag = BOOST_ONCE_INIT;
/** Determine system page size in bytes */
static inline size_t GetSystemPageSize()
{
size_t page_size;
#if defined(WIN32)
SYSTEM_INFO sSysInfo;
GetSystemInfo(&sSysInfo);
page_size = sSysInfo.dwPageSize;
#elif defined(PAGESIZE) // defined in limits.h
page_size = PAGESIZE;
#else // assume some POSIX OS
page_size = sysconf(_SC_PAGESIZE);
#endif
return page_size;
}
bool MemoryPageLocker::Lock(const void* addr, size_t len)
{
#ifdef WIN32
return VirtualLock(const_cast<void*>(addr), len) != 0;
#else
return mlock(addr, len) == 0;
#endif
}
bool MemoryPageLocker::Unlock(const void* addr, size_t len)
{
#ifdef WIN32
return VirtualUnlock(const_cast<void*>(addr), len) != 0;
#else
return munlock(addr, len) == 0;
#endif
}
LockedPageManager::LockedPageManager() : LockedPageManagerBase<MemoryPageLocker>(GetSystemPageSize())
{
}
<commit_msg>Delete allocators.cpp<commit_after><|endoftext|> |
<commit_before>#include <float.h>
#include <QDateTime>
#include <QDebug>
#include "amqp_frame.h"
#include "amqp_table.h"
using namespace QAMQP;
/*
* field value types according to: https://www.rabbitmq.com/amqp-0-9-1-errata.html
t - Boolean
b - Signed 8-bit
Unsigned 8-bit
s - Signed 16-bit
Unsigned 16-bit
I - Signed 32-bit
Unsigned 32-bit
l - Signed 64-bit
Unsigned 64-bit
f - 32-bit float
d - 64-bit float
D - Decimal
S - Long string
A - Array
T - Timestamp (u64)
F - Nested Table
V - Void
x - Byte array
*/
ValueType valueTypeForOctet(qint8 octet)
{
switch (octet) {
case 't': return Boolean;
case 'b': return ShortShortInt;
case 's': return ShortInt;
case 'I': return LongInt;
case 'l': return LongLongInt;
case 'f': return Float;
case 'd': return Double;
case 'D': return Decimal;
case 'S': return LongString;
case 'A': return Array;
case 'T': return Timestamp;
case 'F': return Hash;
case 'V': return Void;
case 'x': return Bytes;
default:
qAmqpDebug() << Q_FUNC_INFO << "invalid octet received: " << char(octet);
}
return Invalid;
}
qint8 valueTypeToOctet(ValueType type)
{
switch (type) {
case Boolean: return 't';
case ShortShortInt: return 'b';
case ShortInt: return 's';
case LongInt: return 'I';
case LongLongInt: return 'l';
case Float: return 'f';
case Double: return 'd';
case Decimal: return 'D';
case LongString: return 'S';
case Array: return 'A';
case Timestamp: return 'T';
case Hash: return 'F';
case Void: return 'V';
case Bytes: return 'x';
default:
qAmqpDebug() << Q_FUNC_INFO << "invalid type received: " << char(type);
}
return 'V';
}
void Table::writeFieldValue(QDataStream &stream, const QVariant &value)
{
ValueType type;
switch (value.userType()) {
case QMetaType::Bool:
type = Boolean;
break;
case QMetaType::QByteArray:
type = Bytes;
break;
case QMetaType::Int:
{
int i = qAbs(value.toInt());
if (i <= qint8(UINT8_MAX)) {
type = ShortShortInt;
} else if (i <= qint16(UINT16_MAX)) {
type = ShortInt;
} else {
type = LongInt;
}
}
break;
case QMetaType::UShort:
type = ShortInt;
break;
case QMetaType::UInt:
{
int i = value.toInt();
if (i <= qint8(UINT8_MAX)) {
type = ShortShortInt;
} else if (i <= qint16(UINT16_MAX)) {
type = ShortInt;
} else {
type = LongInt;
}
}
break;
case QMetaType::LongLong:
case QMetaType::ULongLong:
type = LongLongInt;
break;
case QMetaType::QString:
type = LongString;
break;
case QMetaType::QDateTime:
type = Timestamp;
break;
case QMetaType::Double:
type = value.toDouble() > FLT_MAX ? Double : Float;
break;
case QMetaType::QVariantHash:
type = Hash;
break;
case QMetaType::QVariantList:
type = Array;
break;
case QMetaType::Void:
type = Void;
break;
default:
if (value.userType() == qMetaTypeId<Frame::decimal>()) {
type = Decimal;
break;
} else if (!value.isValid()) {
type = Void;
break;
}
qAmqpDebug() << Q_FUNC_INFO << "unhandled type: " << value.userType();
return;
}
// write the field value type, a requirement for field tables only
stream << valueTypeToOctet(type);
writeFieldValue(stream, type, value);
}
void Table::writeFieldValue(QDataStream &stream, ValueType type, const QVariant &value)
{
switch (type) {
case Boolean:
case ShortShortUint:
case ShortUint:
case LongUint:
case LongLongUint:
case ShortString:
case LongString:
case Timestamp:
case Hash:
return Frame::writeAmqpField(stream, type, value);
case ShortShortInt:
stream << qint8(value.toInt());
break;
case ShortInt:
stream << qint16(value.toInt());
break;
case LongInt:
stream << qint32(value.toInt());
break;
case LongLongInt:
stream << qlonglong(value.toLongLong());
break;
case Float:
{
float g = value.toFloat();
QDataStream::FloatingPointPrecision oldPrecision = stream.floatingPointPrecision();
stream.setFloatingPointPrecision(QDataStream::SinglePrecision);
stream << g;
stream.setFloatingPointPrecision(oldPrecision);
}
break;
case Double:
{
double g = value.toDouble();
QDataStream::FloatingPointPrecision oldPrecision = stream.floatingPointPrecision();
stream.setFloatingPointPrecision(QDataStream::DoublePrecision);
stream << g;
stream.setFloatingPointPrecision(oldPrecision);
}
break;
case Decimal:
{
Frame::decimal v(value.value<Frame::decimal>());
stream << v.scale;
stream << v.value;
}
break;
case Array:
{
QByteArray buffer;
QDataStream arrayStream(&buffer, QIODevice::WriteOnly);
QVariantList array(value.toList());
for (int i = 0; i < array.size(); ++i)
writeFieldValue(arrayStream, array.at(i));
if (buffer.isEmpty()) {
stream << qint32(0);
} else {
stream << buffer;
}
}
break;
case Bytes:
{
QByteArray ba = value.toByteArray();
stream << quint32(ba.length());
stream.writeRawData(ba.data(), ba.length());
}
break;
case Void:
stream << qint32(0);
break;
default:
qAmqpDebug() << Q_FUNC_INFO << "unhandled type: " << type;
}
}
QVariant Table::readFieldValue(QDataStream &stream, ValueType type)
{
switch (type) {
case Boolean:
case ShortShortUint:
case ShortUint:
case LongUint:
case LongLongUint:
case ShortString:
case LongString:
case Timestamp:
case Hash:
return Frame::readAmqpField(stream, type);
case ShortShortInt:
{
char octet;
stream.readRawData(&octet, sizeof(octet));
return QVariant::fromValue<int>(octet);
}
case ShortInt:
{
qint16 tmp_value = 0;
stream >> tmp_value;
return QVariant::fromValue<int>(tmp_value);
}
case LongInt:
{
qint32 tmp_value = 0;
stream >> tmp_value;
return QVariant::fromValue<int>(tmp_value);
}
case LongLongInt:
{
qlonglong v = 0 ;
stream >> v;
return v;
}
case Float:
{
float tmp_value;
QDataStream::FloatingPointPrecision precision = stream.floatingPointPrecision();
stream.setFloatingPointPrecision(QDataStream::SinglePrecision);
stream >> tmp_value;
stream.setFloatingPointPrecision(precision);
return QVariant::fromValue<float>(tmp_value);
}
case Double:
{
double tmp_value;
QDataStream::FloatingPointPrecision precision = stream.floatingPointPrecision();
stream.setFloatingPointPrecision(QDataStream::DoublePrecision);
stream >> tmp_value;
stream.setFloatingPointPrecision(precision);
return QVariant::fromValue<double>(tmp_value);
}
case Decimal:
{
Frame::decimal v;
stream >> v.scale;
stream >> v.value;
return QVariant::fromValue<Frame::decimal>(v);
}
case Array:
{
QByteArray data;
quint32 size = 0;
stream >> size;
data.resize(size);
stream.readRawData(data.data(), data.size());
qint8 type = 0;
QVariantList result;
QDataStream arrayStream(&data, QIODevice::ReadOnly);
while (!arrayStream.atEnd()) {
arrayStream >> type;
result.append(readFieldValue(arrayStream, valueTypeForOctet(type)));
}
return result;
}
case Bytes:
{
QByteArray bytes;
quint32 length = 0;
stream >> length;
bytes.resize(length);
stream.readRawData(bytes.data(), bytes.size());
return bytes;
}
case Void:
break;
default:
qAmqpDebug() << Q_FUNC_INFO << "unhandled type: " << type;
}
return QVariant();
}
QDataStream &operator<<(QDataStream &stream, const Table &table)
{
QByteArray data;
QDataStream s(&data, QIODevice::WriteOnly);
Table::ConstIterator it;
Table::ConstIterator itEnd = table.constEnd();
for (it = table.constBegin(); it != itEnd; ++it) {
Table::writeFieldValue(s, ShortString, it.key());
Table::writeFieldValue(s, it.value());
}
if (data.isEmpty()) {
stream << qint32(0);
} else {
stream << data;
}
return stream;
}
QDataStream &operator>>(QDataStream &stream, Table &table)
{
QByteArray data;
stream >> data;
QDataStream tableStream(&data, QIODevice::ReadOnly);
while (!tableStream.atEnd()) {
qint8 octet = 0;
QString field = Frame::readAmqpField(tableStream, ShortString).toString();
tableStream >> octet;
table[field] = Table::readFieldValue(tableStream, valueTypeForOctet(octet));
}
return stream;
}
<commit_msg>use compatible type max definitions<commit_after>#include <float.h>
#include <QDateTime>
#include <QDebug>
#include "amqp_frame.h"
#include "amqp_table.h"
using namespace QAMQP;
/*
* field value types according to: https://www.rabbitmq.com/amqp-0-9-1-errata.html
t - Boolean
b - Signed 8-bit
Unsigned 8-bit
s - Signed 16-bit
Unsigned 16-bit
I - Signed 32-bit
Unsigned 32-bit
l - Signed 64-bit
Unsigned 64-bit
f - 32-bit float
d - 64-bit float
D - Decimal
S - Long string
A - Array
T - Timestamp (u64)
F - Nested Table
V - Void
x - Byte array
*/
ValueType valueTypeForOctet(qint8 octet)
{
switch (octet) {
case 't': return Boolean;
case 'b': return ShortShortInt;
case 's': return ShortInt;
case 'I': return LongInt;
case 'l': return LongLongInt;
case 'f': return Float;
case 'd': return Double;
case 'D': return Decimal;
case 'S': return LongString;
case 'A': return Array;
case 'T': return Timestamp;
case 'F': return Hash;
case 'V': return Void;
case 'x': return Bytes;
default:
qAmqpDebug() << Q_FUNC_INFO << "invalid octet received: " << char(octet);
}
return Invalid;
}
qint8 valueTypeToOctet(ValueType type)
{
switch (type) {
case Boolean: return 't';
case ShortShortInt: return 'b';
case ShortInt: return 's';
case LongInt: return 'I';
case LongLongInt: return 'l';
case Float: return 'f';
case Double: return 'd';
case Decimal: return 'D';
case LongString: return 'S';
case Array: return 'A';
case Timestamp: return 'T';
case Hash: return 'F';
case Void: return 'V';
case Bytes: return 'x';
default:
qAmqpDebug() << Q_FUNC_INFO << "invalid type received: " << char(type);
}
return 'V';
}
void Table::writeFieldValue(QDataStream &stream, const QVariant &value)
{
ValueType type;
switch (value.userType()) {
case QMetaType::Bool:
type = Boolean;
break;
case QMetaType::QByteArray:
type = Bytes;
break;
case QMetaType::Int:
{
int i = qAbs(value.toInt());
if (i <= qint8(SCHAR_MAX)) {
type = ShortShortInt;
} else if (i <= qint16(SHRT_MAX)) {
type = ShortInt;
} else {
type = LongInt;
}
}
break;
case QMetaType::UShort:
type = ShortInt;
break;
case QMetaType::UInt:
{
int i = value.toInt();
if (i <= qint8(SCHAR_MAX)) {
type = ShortShortInt;
} else if (i <= qint16(SHRT_MAX)) {
type = ShortInt;
} else {
type = LongInt;
}
}
break;
case QMetaType::LongLong:
case QMetaType::ULongLong:
type = LongLongInt;
break;
case QMetaType::QString:
type = LongString;
break;
case QMetaType::QDateTime:
type = Timestamp;
break;
case QMetaType::Double:
type = value.toDouble() > FLT_MAX ? Double : Float;
break;
case QMetaType::QVariantHash:
type = Hash;
break;
case QMetaType::QVariantList:
type = Array;
break;
case QMetaType::Void:
type = Void;
break;
default:
if (value.userType() == qMetaTypeId<Frame::decimal>()) {
type = Decimal;
break;
} else if (!value.isValid()) {
type = Void;
break;
}
qAmqpDebug() << Q_FUNC_INFO << "unhandled type: " << value.userType();
return;
}
// write the field value type, a requirement for field tables only
stream << valueTypeToOctet(type);
writeFieldValue(stream, type, value);
}
void Table::writeFieldValue(QDataStream &stream, ValueType type, const QVariant &value)
{
switch (type) {
case Boolean:
case ShortShortUint:
case ShortUint:
case LongUint:
case LongLongUint:
case ShortString:
case LongString:
case Timestamp:
case Hash:
return Frame::writeAmqpField(stream, type, value);
case ShortShortInt:
stream << qint8(value.toInt());
break;
case ShortInt:
stream << qint16(value.toInt());
break;
case LongInt:
stream << qint32(value.toInt());
break;
case LongLongInt:
stream << qlonglong(value.toLongLong());
break;
case Float:
{
float g = value.toFloat();
QDataStream::FloatingPointPrecision oldPrecision = stream.floatingPointPrecision();
stream.setFloatingPointPrecision(QDataStream::SinglePrecision);
stream << g;
stream.setFloatingPointPrecision(oldPrecision);
}
break;
case Double:
{
double g = value.toDouble();
QDataStream::FloatingPointPrecision oldPrecision = stream.floatingPointPrecision();
stream.setFloatingPointPrecision(QDataStream::DoublePrecision);
stream << g;
stream.setFloatingPointPrecision(oldPrecision);
}
break;
case Decimal:
{
Frame::decimal v(value.value<Frame::decimal>());
stream << v.scale;
stream << v.value;
}
break;
case Array:
{
QByteArray buffer;
QDataStream arrayStream(&buffer, QIODevice::WriteOnly);
QVariantList array(value.toList());
for (int i = 0; i < array.size(); ++i)
writeFieldValue(arrayStream, array.at(i));
if (buffer.isEmpty()) {
stream << qint32(0);
} else {
stream << buffer;
}
}
break;
case Bytes:
{
QByteArray ba = value.toByteArray();
stream << quint32(ba.length());
stream.writeRawData(ba.data(), ba.length());
}
break;
case Void:
stream << qint32(0);
break;
default:
qAmqpDebug() << Q_FUNC_INFO << "unhandled type: " << type;
}
}
QVariant Table::readFieldValue(QDataStream &stream, ValueType type)
{
switch (type) {
case Boolean:
case ShortShortUint:
case ShortUint:
case LongUint:
case LongLongUint:
case ShortString:
case LongString:
case Timestamp:
case Hash:
return Frame::readAmqpField(stream, type);
case ShortShortInt:
{
char octet;
stream.readRawData(&octet, sizeof(octet));
return QVariant::fromValue<int>(octet);
}
case ShortInt:
{
qint16 tmp_value = 0;
stream >> tmp_value;
return QVariant::fromValue<int>(tmp_value);
}
case LongInt:
{
qint32 tmp_value = 0;
stream >> tmp_value;
return QVariant::fromValue<int>(tmp_value);
}
case LongLongInt:
{
qlonglong v = 0 ;
stream >> v;
return v;
}
case Float:
{
float tmp_value;
QDataStream::FloatingPointPrecision precision = stream.floatingPointPrecision();
stream.setFloatingPointPrecision(QDataStream::SinglePrecision);
stream >> tmp_value;
stream.setFloatingPointPrecision(precision);
return QVariant::fromValue<float>(tmp_value);
}
case Double:
{
double tmp_value;
QDataStream::FloatingPointPrecision precision = stream.floatingPointPrecision();
stream.setFloatingPointPrecision(QDataStream::DoublePrecision);
stream >> tmp_value;
stream.setFloatingPointPrecision(precision);
return QVariant::fromValue<double>(tmp_value);
}
case Decimal:
{
Frame::decimal v;
stream >> v.scale;
stream >> v.value;
return QVariant::fromValue<Frame::decimal>(v);
}
case Array:
{
QByteArray data;
quint32 size = 0;
stream >> size;
data.resize(size);
stream.readRawData(data.data(), data.size());
qint8 type = 0;
QVariantList result;
QDataStream arrayStream(&data, QIODevice::ReadOnly);
while (!arrayStream.atEnd()) {
arrayStream >> type;
result.append(readFieldValue(arrayStream, valueTypeForOctet(type)));
}
return result;
}
case Bytes:
{
QByteArray bytes;
quint32 length = 0;
stream >> length;
bytes.resize(length);
stream.readRawData(bytes.data(), bytes.size());
return bytes;
}
case Void:
break;
default:
qAmqpDebug() << Q_FUNC_INFO << "unhandled type: " << type;
}
return QVariant();
}
QDataStream &operator<<(QDataStream &stream, const Table &table)
{
QByteArray data;
QDataStream s(&data, QIODevice::WriteOnly);
Table::ConstIterator it;
Table::ConstIterator itEnd = table.constEnd();
for (it = table.constBegin(); it != itEnd; ++it) {
Table::writeFieldValue(s, ShortString, it.key());
Table::writeFieldValue(s, it.value());
}
if (data.isEmpty()) {
stream << qint32(0);
} else {
stream << data;
}
return stream;
}
QDataStream &operator>>(QDataStream &stream, Table &table)
{
QByteArray data;
stream >> data;
QDataStream tableStream(&data, QIODevice::ReadOnly);
while (!tableStream.atEnd()) {
qint8 octet = 0;
QString field = Frame::readAmqpField(tableStream, ShortString).toString();
tableStream >> octet;
table[field] = Table::readFieldValue(tableStream, valueTypeForOctet(octet));
}
return stream;
}
<|endoftext|> |
<commit_before>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <complex>
#include <af/defines.h>
#include <af/dim4.hpp>
#include <af/algorithm.h>
#include <err_common.hpp>
#include <handle.hpp>
#include <ops.hpp>
#include <scan.hpp>
#include <backend.hpp>
using af::dim4;
using namespace detail;
template<af_op_t op, typename Ti, typename To>
static inline af_array scan(const af_array in, const int dim, bool inclusive_scan = true)
{
return getHandle(scan<op,Ti,To>(getArray<Ti>(in), dim, inclusive_scan));
}
template<typename Ti, typename To>
static inline af_array scan_op(const af_array in, const int dim, af_binary_op op, bool inclusive_scan)
{
af_array out;
switch(op) {
case AF_ADD: out = scan<af_add_t, Ti, To>(in, dim, inclusive_scan); break;
case AF_SUB: out = scan<af_sub_t, Ti, To>(in, dim, inclusive_scan); break;
case AF_MUL: out = scan<af_mul_t, Ti, To>(in, dim, inclusive_scan); break;
case AF_DIV: out = scan<af_div_t, Ti, To>(in, dim, inclusive_scan); break;
case AF_MIN: out = scan<af_min_t, Ti, To>(in, dim, inclusive_scan); break;
case AF_MAX: out = scan<af_max_t, Ti, To>(in, dim, inclusive_scan); break;
//TODO Error for op in default case
}
return out;
}
af_err af_accum(af_array *out, const af_array in, const int dim)
{
ARG_ASSERT(2, dim >= 0);
ARG_ASSERT(2, dim < 4);
try {
const ArrayInfo& in_info = getInfo(in);
if (dim >= (int)in_info.ndims()) {
*out = retain(in);
return AF_SUCCESS;
}
af_dtype type = in_info.getType();
af_array res;
switch(type) {
case f32: res = scan<af_add_t, float , float >(in, dim); break;
case f64: res = scan<af_add_t, double , double >(in, dim); break;
case c32: res = scan<af_add_t, cfloat , cfloat >(in, dim); break;
case c64: res = scan<af_add_t, cdouble, cdouble>(in, dim); break;
case u32: res = scan<af_add_t, uint , uint >(in, dim); break;
case s32: res = scan<af_add_t, int , int >(in, dim); break;
case u64: res = scan<af_add_t, uintl , uintl >(in, dim); break;
case s64: res = scan<af_add_t, intl , intl >(in, dim); break;
case u16: res = scan<af_add_t, ushort , uint >(in, dim); break;
case s16: res = scan<af_add_t, short , int >(in, dim); break;
case u8: res = scan<af_add_t, uchar , uint >(in, dim); break;
// Make sure you are adding only "1" for every non zero value, even if op == af_add_t
case b8: res = scan<af_notzero_t, char , uint >(in, dim); break;
default:
TYPE_ERROR(1, type);
}
std::swap(*out, res);
}
CATCHALL;
return AF_SUCCESS;
}
af_err af_scan(af_array *out, const af_array in, const int dim, af_binary_op op, bool inclusive_scan)
{
ARG_ASSERT(2, dim >= 0);
ARG_ASSERT(2, dim < 4);
try {
const ArrayInfo& in_info = getInfo(in);
if (dim >= (int)in_info.ndims()) {
*out = retain(in);
return AF_SUCCESS;
}
af_dtype type = in_info.getType();
af_array res;
switch(type) {
case f32: res = scan_op<float , float >(in, dim, op, inclusive_scan); break;
case f64: res = scan_op<double , double >(in, dim, op, inclusive_scan); break;
case c32: res = scan_op<cfloat , cfloat >(in, dim, op, inclusive_scan); break;
case c64: res = scan_op<cdouble, cdouble>(in, dim, op, inclusive_scan); break;
case u32: res = scan_op<uint , uint >(in, dim, op, inclusive_scan); break;
case s32: res = scan_op<int , int >(in, dim, op, inclusive_scan); break;
case u64: res = scan_op<uintl , uintl >(in, dim, op, inclusive_scan); break;
case s64: res = scan_op<intl , intl >(in, dim, op, inclusive_scan); break;
case u16: res = scan_op<ushort , uint >(in, dim, op, inclusive_scan); break;
case s16: res = scan_op<short , int >(in, dim, op, inclusive_scan); break;
case u8: res = scan_op<uchar , uint >(in, dim, op, inclusive_scan); break;
case b8: res = scan_op<char , uint >(in, dim, op, inclusive_scan); break;
// Make sure you are adding only "1" for every non zero value, even if op == af_add_t
default:
TYPE_ERROR(1, type);
}
std::swap(*out, res);
}
CATCHALL;
return AF_SUCCESS;
}
<commit_msg>Removed unnecessary comments<commit_after>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <complex>
#include <af/defines.h>
#include <af/dim4.hpp>
#include <af/algorithm.h>
#include <err_common.hpp>
#include <handle.hpp>
#include <ops.hpp>
#include <scan.hpp>
#include <backend.hpp>
using af::dim4;
using namespace detail;
template<af_op_t op, typename Ti, typename To>
static inline af_array scan(const af_array in, const int dim, bool inclusive_scan = true)
{
return getHandle(scan<op,Ti,To>(getArray<Ti>(in), dim, inclusive_scan));
}
template<typename Ti, typename To>
static inline af_array scan_op(const af_array in, const int dim, af_binary_op op, bool inclusive_scan)
{
af_array out;
switch(op) {
case AF_ADD: out = scan<af_add_t, Ti, To>(in, dim, inclusive_scan); break;
case AF_SUB: out = scan<af_sub_t, Ti, To>(in, dim, inclusive_scan); break;
case AF_MUL: out = scan<af_mul_t, Ti, To>(in, dim, inclusive_scan); break;
case AF_DIV: out = scan<af_div_t, Ti, To>(in, dim, inclusive_scan); break;
case AF_MIN: out = scan<af_min_t, Ti, To>(in, dim, inclusive_scan); break;
case AF_MAX: out = scan<af_max_t, Ti, To>(in, dim, inclusive_scan); break;
//TODO Error for op in default case
}
return out;
}
af_err af_accum(af_array *out, const af_array in, const int dim)
{
ARG_ASSERT(2, dim >= 0);
ARG_ASSERT(2, dim < 4);
try {
const ArrayInfo& in_info = getInfo(in);
if (dim >= (int)in_info.ndims()) {
*out = retain(in);
return AF_SUCCESS;
}
af_dtype type = in_info.getType();
af_array res;
switch(type) {
case f32: res = scan<af_add_t, float , float >(in, dim); break;
case f64: res = scan<af_add_t, double , double >(in, dim); break;
case c32: res = scan<af_add_t, cfloat , cfloat >(in, dim); break;
case c64: res = scan<af_add_t, cdouble, cdouble>(in, dim); break;
case u32: res = scan<af_add_t, uint , uint >(in, dim); break;
case s32: res = scan<af_add_t, int , int >(in, dim); break;
case u64: res = scan<af_add_t, uintl , uintl >(in, dim); break;
case s64: res = scan<af_add_t, intl , intl >(in, dim); break;
case u16: res = scan<af_add_t, ushort , uint >(in, dim); break;
case s16: res = scan<af_add_t, short , int >(in, dim); break;
case u8: res = scan<af_add_t, uchar , uint >(in, dim); break;
// Make sure you are adding only "1" for every non zero value, even if op == af_add_t
case b8: res = scan<af_notzero_t, char , uint >(in, dim); break;
default:
TYPE_ERROR(1, type);
}
std::swap(*out, res);
}
CATCHALL;
return AF_SUCCESS;
}
af_err af_scan(af_array *out, const af_array in, const int dim, af_binary_op op, bool inclusive_scan)
{
ARG_ASSERT(2, dim >= 0);
ARG_ASSERT(2, dim < 4);
try {
const ArrayInfo& in_info = getInfo(in);
if (dim >= (int)in_info.ndims()) {
*out = retain(in);
return AF_SUCCESS;
}
af_dtype type = in_info.getType();
af_array res;
switch(type) {
case f32: res = scan_op<float , float >(in, dim, op, inclusive_scan); break;
case f64: res = scan_op<double , double >(in, dim, op, inclusive_scan); break;
case c32: res = scan_op<cfloat , cfloat >(in, dim, op, inclusive_scan); break;
case c64: res = scan_op<cdouble, cdouble>(in, dim, op, inclusive_scan); break;
case u32: res = scan_op<uint , uint >(in, dim, op, inclusive_scan); break;
case s32: res = scan_op<int , int >(in, dim, op, inclusive_scan); break;
case u64: res = scan_op<uintl , uintl >(in, dim, op, inclusive_scan); break;
case s64: res = scan_op<intl , intl >(in, dim, op, inclusive_scan); break;
case u16: res = scan_op<ushort , uint >(in, dim, op, inclusive_scan); break;
case s16: res = scan_op<short , int >(in, dim, op, inclusive_scan); break;
case u8: res = scan_op<uchar , uint >(in, dim, op, inclusive_scan); break;
case b8: res = scan_op<char , uint >(in, dim, op, inclusive_scan); break;
default:
TYPE_ERROR(1, type);
}
std::swap(*out, res);
}
CATCHALL;
return AF_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved
*/
// TEST Foundation::Containers::Stack
// STATUS PRELIMINARY
#include "Stroika/Foundation/StroikaPreComp.h"
#include <iostream>
#include <sstream>
#include "Stroika/Foundation/Containers/Stack.h"
#include "Stroika/Foundation/Containers/Concrete/Stack_LinkedList.h"
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Containers;
using Concrete::Stack_LinkedList;
namespace {
template <typename StackOfT>
void SimpleTest_1_ (StackOfT s)
{
StackOfT s2;
StackOfT s3 = s;
}
}
namespace {
template <typename StackOfT>
void SimpleTest_2_ (StackOfT s)
{
s.Push (1);
VerifyTestResult (s.size () == 1);
s.Push (1);
VerifyTestResult (s.size () == 2);
s.Pop ();
VerifyTestResult (s.size () == 1);
s.RemoveAll ();
VerifyTestResult (s.size () == 0);
}
}
namespace {
template <typename StackOfT>
void SimpleTest_3_Iteration_ (StackOfT s)
{
#if 0
m.Add (1, 2);
VerifyTestResult (m.size () == 1);
for (auto i : m) {
VerifyTestResult (i.first == 1);
VerifyTestResult (i.second == 2);
}
m.Add (1, 2);
VerifyTestResult (m.size () == 1);
for (auto i : m) {
VerifyTestResult (i.first == 1);
VerifyTestResult (i.second == 2);
}
m.Remove (1);
VerifyTestResult (m.size () == 0);
for (auto i : m) {
VerifyTestResult (false);
}
m.Add (1, 2);
m.Add (2, 3);
m.Add (3, 4);
unsigned int cnt = 0;
for (auto i : m) {
cnt++;
if (cnt == 1) {
VerifyTestResult (i.first == 1);
VerifyTestResult (i.second == 2);
}
if (cnt == 2) {
VerifyTestResult (i.first == 2);
VerifyTestResult (i.second == 3);
}
if (cnt == 3) {
VerifyTestResult (i.first == 3);
VerifyTestResult (i.second == 4);
}
}
VerifyTestResult (cnt == 3);
#endif
s.RemoveAll ();
VerifyTestResult (s.size () == 0);
}
}
namespace Test4_Equals {
template <typename USING_STACK_CONTAINER, typename EQUALS_COMPARER>
void DoAllTests_ ()
{
USING_STACK_CONTAINER s;
USING_STACK_CONTAINER s2 = s;
s.Push (1);
s.Push (2);
VerifyTestResult (s.size () == 2);
USING_STACK_CONTAINER s3 = s;
//VerifyTestResult (s == s3);
VerifyTestResult (s.template Equals<EQUALS_COMPARER> (s3));
//VerifyTestResult (not (s != s3));
//VerifyTestResult (s != s2);
VerifyTestResult (not s.template Equals<EQUALS_COMPARER> (s2));
//VerifyTestResult (not (s == s2));
}
}
namespace {
template <typename CONCRETE_STACK_TYPE, typename EQUALS_COMPARER>
void Tests_All_For_Type_WhichDontRequireComparer_For_Type_ ()
{
CONCRETE_STACK_TYPE s;
SimpleTest_1_<CONCRETE_STACK_TYPE> (s);
SimpleTest_2_<CONCRETE_STACK_TYPE> (s);
SimpleTest_3_Iteration_<CONCRETE_STACK_TYPE> (s);
}
template <typename CONCRETE_STACK_TYPE, typename EQUALS_COMPARER>
void Tests_All_For_Type_ ()
{
Tests_All_For_Type_WhichDontRequireComparer_For_Type_<CONCRETE_STACK_TYPE, EQUALS_COMPARER> ();
Test4_Equals::DoAllTests_<CONCRETE_STACK_TYPE, EQUALS_COMPARER> ();
}
}
namespace {
void DoRegressionTests_ ()
{
using COMPARE_SIZET = equal_to<size_t>;
using COMPARE_SimpleClass = equal_to<SimpleClass>;
struct COMPARE_SimpleClassWithoutComparisonOperators {
using value_type = SimpleClassWithoutComparisonOperators;
bool operator() (value_type v1, value_type v2) const
{
return v1.GetValue () == v2.GetValue ();
}
};
Tests_All_For_Type_<Stack<size_t>, COMPARE_SIZET> ();
Tests_All_For_Type_<Stack<SimpleClass>, COMPARE_SimpleClass> ();
Tests_All_For_Type_WhichDontRequireComparer_For_Type_<Stack<SimpleClassWithoutComparisonOperators>, COMPARE_SimpleClassWithoutComparisonOperators> ();
Tests_All_For_Type_<Stack<SimpleClassWithoutComparisonOperators>, COMPARE_SimpleClassWithoutComparisonOperators> ();
Tests_All_For_Type_<Stack_LinkedList<size_t>, COMPARE_SIZET> ();
Tests_All_For_Type_<Stack_LinkedList<SimpleClass>, COMPARE_SimpleClass> ();
Tests_All_For_Type_WhichDontRequireComparer_For_Type_<Stack_LinkedList<SimpleClassWithoutComparisonOperators>, COMPARE_SimpleClassWithoutComparisonOperators> ();
Tests_All_For_Type_<Stack_LinkedList<SimpleClassWithoutComparisonOperators>, COMPARE_SimpleClassWithoutComparisonOperators> ();
}
}
int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[])
{
Stroika::TestHarness::Setup ();
return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
<commit_msg>fixed recent checkins<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved
*/
// TEST Foundation::Containers::Stack
// STATUS PRELIMINARY
#include "Stroika/Foundation/StroikaPreComp.h"
#include <iostream>
#include <sstream>
#include "Stroika/Foundation/Containers/Stack.h"
#include "Stroika/Foundation/Containers/Concrete/Stack_LinkedList.h"
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Containers;
using Concrete::Stack_LinkedList;
namespace {
template <typename StackOfT>
void SimpleTest_1_ (StackOfT s)
{
StackOfT s2;
StackOfT s3 = s;
}
}
namespace {
template <typename StackOfT>
void SimpleTest_2_ (StackOfT s)
{
s.Push (1);
VerifyTestResult (s.size () == 1);
s.Push (1);
VerifyTestResult (s.size () == 2);
s.Pop ();
VerifyTestResult (s.size () == 1);
s.RemoveAll ();
VerifyTestResult (s.size () == 0);
}
}
namespace {
template <typename StackOfT>
void SimpleTest_3_Iteration_ (StackOfT s)
{
#if 0
m.Add (1, 2);
VerifyTestResult (m.size () == 1);
for (auto i : m) {
VerifyTestResult (i.first == 1);
VerifyTestResult (i.second == 2);
}
m.Add (1, 2);
VerifyTestResult (m.size () == 1);
for (auto i : m) {
VerifyTestResult (i.first == 1);
VerifyTestResult (i.second == 2);
}
m.Remove (1);
VerifyTestResult (m.size () == 0);
for (auto i : m) {
VerifyTestResult (false);
}
m.Add (1, 2);
m.Add (2, 3);
m.Add (3, 4);
unsigned int cnt = 0;
for (auto i : m) {
cnt++;
if (cnt == 1) {
VerifyTestResult (i.first == 1);
VerifyTestResult (i.second == 2);
}
if (cnt == 2) {
VerifyTestResult (i.first == 2);
VerifyTestResult (i.second == 3);
}
if (cnt == 3) {
VerifyTestResult (i.first == 3);
VerifyTestResult (i.second == 4);
}
}
VerifyTestResult (cnt == 3);
#endif
s.RemoveAll ();
VerifyTestResult (s.size () == 0);
}
}
namespace Test4_Equals {
template <typename USING_STACK_CONTAINER, typename EQUALS_COMPARER>
void DoAllTests_ ()
{
USING_STACK_CONTAINER s;
USING_STACK_CONTAINER s2 = s;
s.Push (1);
s.Push (2);
VerifyTestResult (s.size () == 2);
USING_STACK_CONTAINER s3 = s;
//VerifyTestResult (s == s3);
VerifyTestResult (USING_STACK_CONTAINER::EqualsComparer<EQUALS_COMPARER>{}(s, s3));
//VerifyTestResult (not (s != s3));
//VerifyTestResult (s != s2);
VerifyTestResult (not USING_STACK_CONTAINER::EqualsComparer<EQUALS_COMPARER>{}(s, s2));
//VerifyTestResult (not (s == s2));
}
}
namespace {
template <typename CONCRETE_STACK_TYPE, typename EQUALS_COMPARER>
void Tests_All_For_Type_WhichDontRequireComparer_For_Type_ ()
{
CONCRETE_STACK_TYPE s;
SimpleTest_1_<CONCRETE_STACK_TYPE> (s);
SimpleTest_2_<CONCRETE_STACK_TYPE> (s);
SimpleTest_3_Iteration_<CONCRETE_STACK_TYPE> (s);
}
template <typename CONCRETE_STACK_TYPE, typename EQUALS_COMPARER>
void Tests_All_For_Type_ ()
{
Tests_All_For_Type_WhichDontRequireComparer_For_Type_<CONCRETE_STACK_TYPE, EQUALS_COMPARER> ();
Test4_Equals::DoAllTests_<CONCRETE_STACK_TYPE, EQUALS_COMPARER> ();
}
}
namespace {
void DoRegressionTests_ ()
{
using COMPARE_SIZET = equal_to<size_t>;
using COMPARE_SimpleClass = equal_to<SimpleClass>;
struct COMPARE_SimpleClassWithoutComparisonOperators {
using value_type = SimpleClassWithoutComparisonOperators;
bool operator() (value_type v1, value_type v2) const
{
return v1.GetValue () == v2.GetValue ();
}
};
Tests_All_For_Type_<Stack<size_t>, COMPARE_SIZET> ();
Tests_All_For_Type_<Stack<SimpleClass>, COMPARE_SimpleClass> ();
Tests_All_For_Type_WhichDontRequireComparer_For_Type_<Stack<SimpleClassWithoutComparisonOperators>, COMPARE_SimpleClassWithoutComparisonOperators> ();
Tests_All_For_Type_<Stack<SimpleClassWithoutComparisonOperators>, COMPARE_SimpleClassWithoutComparisonOperators> ();
Tests_All_For_Type_<Stack_LinkedList<size_t>, COMPARE_SIZET> ();
Tests_All_For_Type_<Stack_LinkedList<SimpleClass>, COMPARE_SimpleClass> ();
Tests_All_For_Type_WhichDontRequireComparer_For_Type_<Stack_LinkedList<SimpleClassWithoutComparisonOperators>, COMPARE_SimpleClassWithoutComparisonOperators> ();
Tests_All_For_Type_<Stack_LinkedList<SimpleClassWithoutComparisonOperators>, COMPARE_SimpleClassWithoutComparisonOperators> ();
}
}
int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[])
{
Stroika::TestHarness::Setup ();
return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
// TEST Foundation::Execution::ThreadSafetyBuiltinObject
#include "Stroika/Foundation/StroikaPreComp.h"
#include <mutex>
#include "Stroika/Foundation/Characters/String.h"
#include "Stroika/Foundation/Containers/Collection.h"
#include "Stroika/Foundation/Containers/Sequence.h"
#include "Stroika/Foundation/Containers/Set.h"
#include "Stroika/Foundation/Containers/SortedSet.h"
#include "Stroika/Foundation/Execution/Thread.h"
#include "Stroika/Foundation/Math/Common.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika::Foundation;
using namespace Characters;
using namespace Containers;
using Execution::Thread;
using Execution::WaitableEvent;
namespace {
/*
* To REALLY this this code for thread-safety, use ExternallySynchronizedLock, but to verify it works
* without worrying about races, just use mutex.
*/
struct no_lock_ {
void lock () {}
void unlock () {}
};
}
namespace {
void RunThreads_ (const initializer_list<Thread>& threads)
{
for (Thread i : threads) {
i.Start ();
}
for (Thread i : threads) {
i.WaitForDone ();
}
}
}
namespace {
template <typename ITERABLE_TYPE, typename LOCK_TYPE>
Thread mkIterateOverThread_ (ITERABLE_TYPE* iterable, LOCK_TYPE* lock, unsigned int repeatCount)
{
using ElementType = typename ITERABLE_TYPE::ElementType;
return Thread ([iterable, lock, repeatCount] () {
for (unsigned int i = 0; i < repeatCount; ++i) {
lock_guard<decltype(*lock)> critSec (*lock);
for (ElementType e : *iterable) {
ElementType e2 = e; // do something
}
}
});
};
}
namespace {
template <typename ITERABLE_TYPE, typename LOCK_TYPE>
Thread mkOverwriteThread_ (ITERABLE_TYPE* oneToKeepOverwriting, ITERABLE_TYPE elt1, ITERABLE_TYPE elt2, LOCK_TYPE* lock, unsigned int repeatCount)
{
return Thread ([oneToKeepOverwriting, lock, repeatCount, elt1, elt2] () {
for (unsigned int i = 0; i < repeatCount; ++i) {
for (int ii = 0; ii <= 100; ++ii) {
if (Math::IsOdd (ii)) {
lock_guard<decltype(*lock)> critSec (*lock);
(*oneToKeepOverwriting) = elt1;
}
else {
lock_guard<decltype(*lock)> critSec (*lock);
(*oneToKeepOverwriting) = elt2;
}
}
}
});
};
}
namespace {
namespace AssignAndIterateAtSameTimeTest_1_ {
template <typename ITERABLE_TYPE>
void DoItOnce_ (ITERABLE_TYPE elt1, ITERABLE_TYPE elt2, unsigned int repeatCount)
{
no_lock_ lock ;
//mutex lock;
ITERABLE_TYPE oneToKeepOverwriting = elt1;
Thread iterateThread = mkIterateOverThread_ (&oneToKeepOverwriting, &lock, repeatCount);
Thread overwriteThread = mkOverwriteThread_ (&oneToKeepOverwriting, elt1, elt2, &lock, repeatCount);
RunThreads_ ({iterateThread, overwriteThread});
}
void DoIt ()
{
Debug::TraceContextBumper traceCtx (SDKSTR ("AssignAndIterateAtSameTimeTest_1_::DoIt ()"));
DoItOnce_<String> (String (L"123456789"), String (L"abcdedfghijkqlmopqrstuvwxyz"), 1000);
//DoItOnce_<Collection<int>> (Collection<int> ({1, 3, 4, 5, 6, 33, 12, 13}), Collection<int> ({4, 5, 6, 33, 12, 13, 1, 3, 99, 33, 4, 5}), 1000);
DoItOnce_<Sequence<int>> (Sequence<int> ({1, 3, 4, 5, 6, 33, 12, 13}), Sequence<int> ({4, 5, 6, 33, 12, 13, 1, 3, 99, 33, 4, 5}), 1000);
DoItOnce_<Set<int>> (Set<int> ({1, 3, 4, 5, 6, 33, 12, 13}), Set<int> ({4, 5, 6, 33, 12, 13, 34, 388, 3, 99, 33, 4, 5}), 1000);
DoItOnce_<SortedSet<int>> (SortedSet<int> ({1, 3, 4, 5, 6, 33, 12, 13}), SortedSet<int> ({4, 5, 6, 33, 12, 13, 34, 388, 3, 99, 33, 4, 5}), 1000);
}
}
}
namespace {
namespace IterateWhileMutatingContainer_Test_2_ {
template <typename ITERABLE_TYPE, typename LOCK, typename MUTATE_FUNCTION>
void DoItOnce_ (LOCK* lock, ITERABLE_TYPE elt1, unsigned int repeatCount, MUTATE_FUNCTION baseMutateFunction)
{
ITERABLE_TYPE oneToKeepOverwriting = elt1;
auto mutateFunction = [&oneToKeepOverwriting, lock, repeatCount, &baseMutateFunction] () {
for (unsigned int i = 0; i < repeatCount; ++i) {
baseMutateFunction (&oneToKeepOverwriting);
}
};
Thread iterateThread = mkIterateOverThread_ (&oneToKeepOverwriting, lock, repeatCount);
Thread mutateThread = mutateFunction;
RunThreads_ ({iterateThread, mutateThread});
}
void DoIt ()
{
// This test demonstrates the need for qStroika_Foundation_Traveral_IteratorHoldsSharedPtr_
Debug::TraceContextBumper traceCtx (SDKSTR ("IterateWhileMutatingContainer_Test_2_::DoIt ()"));
// @TODO - DEBUG!!!!
//no_lock_ lock;
mutex lock;
DoItOnce_<Set<int>> (
&lock,
Set<int> ({1, 3, 4, 5, 6, 33, 12, 13}),
1000,
[&lock] (Set<int>* oneToKeepOverwriting) {
for (int ii = 0; ii <= 100; ++ii) {
if (Math::IsOdd (ii)) {
lock_guard<decltype(lock)> critSec (lock);
(*oneToKeepOverwriting) = Set<int> {3, 5};
}
else {
lock_guard<decltype(lock)> critSec (lock);
(*oneToKeepOverwriting) = Set<int> {3, 5};
}
}
});
}
}
}
namespace {
void DoRegressionTests_ ()
{
AssignAndIterateAtSameTimeTest_1_::DoIt ();
IterateWhileMutatingContainer_Test_2_::DoIt ();
}
}
int main (int argc, const char* argv[])
{
Stroika::TestHarness::Setup ();
Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
return EXIT_SUCCESS;
}
<commit_msg>ThreadSafetyBuiltinObject cleanups<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
// TEST Foundation::Execution::ThreadSafetyBuiltinObject
#include "Stroika/Foundation/StroikaPreComp.h"
#include <mutex>
#include "Stroika/Foundation/Characters/String.h"
#include "Stroika/Foundation/Containers/Collection.h"
#include "Stroika/Foundation/Containers/Sequence.h"
#include "Stroika/Foundation/Containers/Set.h"
#include "Stroika/Foundation/Containers/SortedSet.h"
#include "Stroika/Foundation/Execution/Thread.h"
#include "Stroika/Foundation/Math/Common.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika::Foundation;
using namespace Characters;
using namespace Containers;
using Execution::Thread;
using Execution::WaitableEvent;
namespace {
/*
* To REALLY this this code for thread-safety, use ExternallySynchronizedLock, but to verify it works
* without worrying about races, just use mutex.
*/
struct no_lock_ {
void lock () {}
void unlock () {}
};
}
namespace {
void RunThreads_ (const initializer_list<Thread>& threads)
{
for (Thread i : threads) {
i.Start ();
}
for (Thread i : threads) {
i.WaitForDone ();
}
}
}
namespace {
template <typename ITERABLE_TYPE, typename LOCK_TYPE>
Thread mkIterateOverThread_ (ITERABLE_TYPE* iterable, LOCK_TYPE* lock, unsigned int repeatCount)
{
using ElementType = typename ITERABLE_TYPE::ElementType;
return Thread ([iterable, lock, repeatCount] () {
for (unsigned int i = 0; i < repeatCount; ++i) {
lock_guard<decltype(*lock)> critSec (*lock);
for (ElementType e : *iterable) {
ElementType e2 = e; // do something
}
}
});
};
}
namespace {
template <typename ITERABLE_TYPE, typename LOCK_TYPE>
Thread mkOverwriteThread_ (ITERABLE_TYPE* oneToKeepOverwriting, ITERABLE_TYPE elt1, ITERABLE_TYPE elt2, LOCK_TYPE* lock, unsigned int repeatCount)
{
return Thread ([oneToKeepOverwriting, lock, repeatCount, elt1, elt2] () {
for (unsigned int i = 0; i < repeatCount; ++i) {
for (int ii = 0; ii <= 100; ++ii) {
if (Math::IsOdd (ii)) {
lock_guard<decltype(*lock)> critSec (*lock);
(*oneToKeepOverwriting) = elt1;
}
else {
lock_guard<decltype(*lock)> critSec (*lock);
(*oneToKeepOverwriting) = elt2;
}
}
}
});
};
}
namespace {
namespace AssignAndIterateAtSameTimeTest_1_ {
template <typename ITERABLE_TYPE>
void DoItOnce_ (ITERABLE_TYPE elt1, ITERABLE_TYPE elt2, unsigned int repeatCount)
{
no_lock_ lock ;
//mutex lock;
ITERABLE_TYPE oneToKeepOverwriting = elt1;
Thread iterateThread = mkIterateOverThread_ (&oneToKeepOverwriting, &lock, repeatCount);
Thread overwriteThread = mkOverwriteThread_ (&oneToKeepOverwriting, elt1, elt2, &lock, repeatCount);
RunThreads_ ({iterateThread, overwriteThread});
}
void DoIt ()
{
Debug::TraceContextBumper traceCtx (SDKSTR ("AssignAndIterateAtSameTimeTest_1_::DoIt ()"));
DoItOnce_<String> (String (L"123456789"), String (L"abcdedfghijkqlmopqrstuvwxyz"), 1000);
DoItOnce_<Collection<int>> (Collection<int> ({1, 3, 4, 5, 6, 33, 12, 13}), Collection<int> ({4, 5, 6, 33, 12, 13, 1, 3, 99, 33, 4, 5}), 1000);
DoItOnce_<Sequence<int>> (Sequence<int> ({1, 3, 4, 5, 6, 33, 12, 13}), Sequence<int> ({4, 5, 6, 33, 12, 13, 1, 3, 99, 33, 4, 5}), 1000);
DoItOnce_<Set<int>> (Set<int> ({1, 3, 4, 5, 6, 33, 12, 13}), Set<int> ({4, 5, 6, 33, 12, 13, 34, 388, 3, 99, 33, 4, 5}), 1000);
DoItOnce_<SortedSet<int>> (SortedSet<int> ({1, 3, 4, 5, 6, 33, 12, 13}), SortedSet<int> ({4, 5, 6, 33, 12, 13, 34, 388, 3, 99, 33, 4, 5}), 1000);
}
}
}
namespace {
namespace IterateWhileMutatingContainer_Test_2_ {
template <typename ITERABLE_TYPE, typename LOCK, typename MUTATE_FUNCTION>
void DoItOnce_ (LOCK* lock, ITERABLE_TYPE elt1, unsigned int repeatCount, MUTATE_FUNCTION baseMutateFunction)
{
ITERABLE_TYPE oneToKeepOverwriting = elt1;
auto mutateFunction = [&oneToKeepOverwriting, lock, repeatCount, &baseMutateFunction] () {
for (unsigned int i = 0; i < repeatCount; ++i) {
baseMutateFunction (&oneToKeepOverwriting);
}
};
Thread iterateThread = mkIterateOverThread_ (&oneToKeepOverwriting, lock, repeatCount);
Thread mutateThread = mutateFunction;
RunThreads_ ({iterateThread, mutateThread});
}
void DoIt ()
{
// This test demonstrates the need for qStroika_Foundation_Traveral_IteratorHoldsSharedPtr_
Debug::TraceContextBumper traceCtx (SDKSTR ("IterateWhileMutatingContainer_Test_2_::DoIt ()"));
// @TODO - DEBUG!!!!
//no_lock_ lock;
mutex lock;
DoItOnce_<Set<int>> (
&lock,
Set<int> ({1, 3, 4, 5, 6, 33, 12, 13}),
1000,
[&lock] (Set<int>* oneToKeepOverwriting) {
for (int ii = 0; ii <= 100; ++ii) {
if (Math::IsOdd (ii)) {
lock_guard<decltype(lock)> critSec (lock);
(*oneToKeepOverwriting) = Set<int> {3, 5};
}
else {
lock_guard<decltype(lock)> critSec (lock);
(*oneToKeepOverwriting) = Set<int> {3, 5};
}
}
});
}
}
}
namespace {
void DoRegressionTests_ ()
{
AssignAndIterateAtSameTimeTest_1_::DoIt ();
IterateWhileMutatingContainer_Test_2_::DoIt ();
}
}
int main (int argc, const char* argv[])
{
Stroika::TestHarness::Setup ();
Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions Inc. 1990-2014. All rights reserved
*/
// TEST Foundation::Memory
#include "Stroika/Foundation/StroikaPreComp.h"
#include "Stroika/Foundation/Containers/Mapping.h"
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Memory/AnyVariantValue.h"
#include "Stroika/Foundation/Memory/Optional.h"
#include "Stroika/Foundation/Memory/SharedByValue.h"
#include "Stroika/Foundation/Memory/SharedPtr.h"
#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Memory;
//TODO: DOES IT EVEN NEED TO BE SAID? THese tests are a bit sparse ;-)
namespace {
void Test1_Optional ()
{
{
Optional<int> x;
VerifyTestResult (x.IsMissing ());
x = 1;
VerifyTestResult (not x.IsMissing ());
VerifyTestResult (x.IsPresent ());
VerifyTestResult (*x == 1);
}
{
// Careful about self-assignment
Optional<int> x;
x = 3;
x = max (*x, 1);
VerifyTestResult (x == 3);
}
auto testOptionalOfThingNotCopyable = [] () {
struct NotCopyable {
NotCopyable () {}
NotCopyable (const NotCopyable&&) {} // but is moveable!
NotCopyable (const NotCopyable&) = delete;
const NotCopyable& operator= (const NotCopyable&) = delete;
};
Optional<NotCopyable> n1;
VerifyTestResult (n1.IsMissing ());
Optional<NotCopyable> n2 (std::move (NotCopyable ())); // use r-value reference to move
VerifyTestResult (n2.IsPresent ());
};
testOptionalOfThingNotCopyable ();
}
void Test2_SharedByValue ()
{
}
void Test_4_Optional_Of_Mapping_Copy_Problem_ ()
{
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Foundation::Containers;
Mapping<int, float> ml1, ml2;
ml1 = ml2;
Optional<Mapping<int, float>> ol1, ol2;
if (ol2.IsPresent ()) {
ml1 = *ol2;
}
ol1 = ml1;
Optional<Mapping<int, float>> xxxx2 (ml1);
// fails to compile prior to 2013-09-09
Optional<Mapping<int, float>> xxxx1 (ol1);
// fails to compile prior to 2013-09-09
ol1 = ol2;
}
void Test_5_AnyVariantValue_ ()
{
{
VerifyTestResult (AnyVariantValue ().empty ());
VerifyTestResult (not AnyVariantValue (1).empty ());
VerifyTestResult (not AnyVariantValue ("1").empty ());
//VerifyTestResult (AnyVariantValue ("1").GetType () == typeid ("1")); // not sure why this fails but not worthy worrying about yet
VerifyTestResult (AnyVariantValue (1).As<int> () == 1);
}
{
AnyVariantValue v;
VerifyTestResult (v.empty ());
v = AnyVariantValue (1);
VerifyTestResult (not v.empty ());
VerifyTestResult (v.GetType () == typeid (1));
VerifyTestResult (v.As<int> () == 1);
v = AnyVariantValue (L"a");
//VerifyTestResult (v.GetType () == typeid (L"a")); // not sure why this fails but not worthy worrying about yet
VerifyTestResult (not v.empty ());
v.clear ();
VerifyTestResult (v.empty ());
VerifyTestResult (v.GetType () == typeid (void));
}
{
struct JIM {
int a;
};
AnyVariantValue v;
VerifyTestResult (v.empty ());
v = AnyVariantValue (JIM ());
VerifyTestResult (v.GetType () == typeid (JIM));
}
{
AnyVariantValue v;
VerifyTestResult (v.empty ());
v = AnyVariantValue (1);
v = v;
VerifyTestResult (v.GetType () == typeid (1));
VerifyTestResult (v.As<int> () == 1);
v = AnyVariantValue (v);
VerifyTestResult (v.GetType () == typeid (1));
VerifyTestResult (v.As<int> () == 1);
}
{
static int nCopies = 0;
struct Copyable {
Copyable ()
{
++nCopies;
}
Copyable (const Copyable&)
{
++nCopies;
}
~Copyable ()
{
--nCopies;
}
const Copyable& operator= (const Copyable&) = delete;
};
{
AnyVariantValue v;
VerifyTestResult (v.empty ());
v = AnyVariantValue (Copyable ());
v = v;
v = AnyVariantValue (AnyVariantValue (v));
v = AnyVariantValue (AnyVariantValue (Copyable ()));
VerifyTestResult (v.GetType () == typeid (Copyable));
}
VerifyTestResult (0 == nCopies);
}
}
void Test_6_SharedPtr ()
{
{
SharedPtr<int> p (new int (3));
VerifyTestResult (p.use_count () == 1);
VerifyTestResult (p.unique ());
VerifyTestResult (*p == 3);
}
}
}
namespace {
void DoRegressionTests_ ()
{
Test1_Optional ();
Test2_SharedByValue ();
Test_4_Optional_Of_Mapping_Copy_Problem_ ();
Test_5_AnyVariantValue_ ();
Test_6_SharedPtr ();
}
}
int main (int argc, const char* argv[])
{
Stroika::TestHarness::Setup ();
Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
return EXIT_SUCCESS;
}
<commit_msg>regression test cases for SharedPtr<><commit_after>/*
* Copyright(c) Sophist Solutions Inc. 1990-2014. All rights reserved
*/
// TEST Foundation::Memory
#include "Stroika/Foundation/StroikaPreComp.h"
#include "Stroika/Foundation/Containers/Mapping.h"
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Memory/AnyVariantValue.h"
#include "Stroika/Foundation/Memory/Optional.h"
#include "Stroika/Foundation/Memory/SharedByValue.h"
#include "Stroika/Foundation/Memory/SharedPtr.h"
#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Memory;
//TODO: DOES IT EVEN NEED TO BE SAID? THese tests are a bit sparse ;-)
namespace {
void Test1_Optional ()
{
{
Optional<int> x;
VerifyTestResult (x.IsMissing ());
x = 1;
VerifyTestResult (not x.IsMissing ());
VerifyTestResult (x.IsPresent ());
VerifyTestResult (*x == 1);
}
{
// Careful about self-assignment
Optional<int> x;
x = 3;
x = max (*x, 1);
VerifyTestResult (x == 3);
}
auto testOptionalOfThingNotCopyable = [] () {
struct NotCopyable {
NotCopyable () {}
NotCopyable (const NotCopyable&&) {} // but is moveable!
NotCopyable (const NotCopyable&) = delete;
const NotCopyable& operator= (const NotCopyable&) = delete;
};
Optional<NotCopyable> n1;
VerifyTestResult (n1.IsMissing ());
Optional<NotCopyable> n2 (std::move (NotCopyable ())); // use r-value reference to move
VerifyTestResult (n2.IsPresent ());
};
testOptionalOfThingNotCopyable ();
}
void Test2_SharedByValue ()
{
}
void Test_4_Optional_Of_Mapping_Copy_Problem_ ()
{
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Foundation::Containers;
Mapping<int, float> ml1, ml2;
ml1 = ml2;
Optional<Mapping<int, float>> ol1, ol2;
if (ol2.IsPresent ()) {
ml1 = *ol2;
}
ol1 = ml1;
Optional<Mapping<int, float>> xxxx2 (ml1);
// fails to compile prior to 2013-09-09
Optional<Mapping<int, float>> xxxx1 (ol1);
// fails to compile prior to 2013-09-09
ol1 = ol2;
}
void Test_5_AnyVariantValue_ ()
{
{
VerifyTestResult (AnyVariantValue ().empty ());
VerifyTestResult (not AnyVariantValue (1).empty ());
VerifyTestResult (not AnyVariantValue ("1").empty ());
//VerifyTestResult (AnyVariantValue ("1").GetType () == typeid ("1")); // not sure why this fails but not worthy worrying about yet
VerifyTestResult (AnyVariantValue (1).As<int> () == 1);
}
{
AnyVariantValue v;
VerifyTestResult (v.empty ());
v = AnyVariantValue (1);
VerifyTestResult (not v.empty ());
VerifyTestResult (v.GetType () == typeid (1));
VerifyTestResult (v.As<int> () == 1);
v = AnyVariantValue (L"a");
//VerifyTestResult (v.GetType () == typeid (L"a")); // not sure why this fails but not worthy worrying about yet
VerifyTestResult (not v.empty ());
v.clear ();
VerifyTestResult (v.empty ());
VerifyTestResult (v.GetType () == typeid (void));
}
{
struct JIM {
int a;
};
AnyVariantValue v;
VerifyTestResult (v.empty ());
v = AnyVariantValue (JIM ());
VerifyTestResult (v.GetType () == typeid (JIM));
}
{
AnyVariantValue v;
VerifyTestResult (v.empty ());
v = AnyVariantValue (1);
v = v;
VerifyTestResult (v.GetType () == typeid (1));
VerifyTestResult (v.As<int> () == 1);
v = AnyVariantValue (v);
VerifyTestResult (v.GetType () == typeid (1));
VerifyTestResult (v.As<int> () == 1);
}
{
static int nCopies = 0;
struct Copyable {
Copyable ()
{
++nCopies;
}
Copyable (const Copyable&)
{
++nCopies;
}
~Copyable ()
{
--nCopies;
}
const Copyable& operator= (const Copyable&) = delete;
};
{
AnyVariantValue v;
VerifyTestResult (v.empty ());
v = AnyVariantValue (Copyable ());
v = v;
v = AnyVariantValue (AnyVariantValue (v));
v = AnyVariantValue (AnyVariantValue (Copyable ()));
VerifyTestResult (v.GetType () == typeid (Copyable));
}
VerifyTestResult (0 == nCopies);
}
}
void Test_6_SharedPtr ()
{
{
SharedPtr<int> p (new int (3));
VerifyTestResult (p.use_count () == 1);
VerifyTestResult (p.unique ());
VerifyTestResult (*p == 3);
}
{
static int nCreates = 0;
static int nDestroys = 0;
struct COUNTED_OBJ {
COUNTED_OBJ ()
{
++nCreates;
}
COUNTED_OBJ (const COUNTED_OBJ&)
{
++nCreates;
}
~COUNTED_OBJ ()
{
++nDestroys;
}
const COUNTED_OBJ& operator= (const COUNTED_OBJ&) = delete;
};
struct CNT2 : COUNTED_OBJ {
};
{
SharedPtr<COUNTED_OBJ> p (new COUNTED_OBJ ());
}
VerifyTestResult (nCreates == nDestroys);
{
SharedPtr<COUNTED_OBJ> p (SharedPtr<CNT2> (new CNT2 ()));
VerifyTestResult (nCreates == nDestroys + 1);
}
VerifyTestResult (nCreates == nDestroys);
}
}
}
namespace {
void DoRegressionTests_ ()
{
Test1_Optional ();
Test2_SharedByValue ();
Test_4_Optional_Of_Mapping_Copy_Problem_ ();
Test_5_AnyVariantValue_ ();
Test_6_SharedPtr ();
}
}
int main (int argc, const char* argv[])
{
Stroika::TestHarness::Setup ();
Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "MoveSystem.h"
#include <iostream>
void MoveSystem::update(int currentStep)
{
const std::vector<int> &positionKeys = positionComponentList.uids();
const std::vector<int> &velocityKeys = velocityComponentList.uids();
for(int i = 0; i < positionKeys.size(); i++)
{
int uid = positionKeys[i];
PositionComponent &p = positionComponentList.get(uid);
std::cout << p.positionX;
}
}
<commit_msg>Add: movement node<commit_after>#include "MoveSystem.h"
#include <iostream>
void MoveSystem::update(int currentStep)
{
const std::vector<int> &uidList = movementNode.uids();
for(int i = 0; i < uidList.size(); i++)
{
MovementNode &n = movementNode.get(uidList.at(i));
PositionComponent &p = n.position;
std::cout << p.positionX;
}
}<|endoftext|> |
<commit_before>#include "Moves/Move.h"
#include <cassert>
#include <cctype>
#include <string>
#include "Game/Board.h"
#include "Game/Square.h"
#include "Game/Game_Result.h"
#include "Game/Piece.h"
Move::Move(Square start, Square end) noexcept :
origin(start),
destination(end)
{
assert(start.inside_board());
assert(end.inside_board());
assert(file_change() != 0 || rank_change() != 0);
}
void Move::side_effects(Board&) const noexcept
{
}
bool Move::is_legal(const Board& board) const noexcept
{
#ifndef NDEBUG
auto moving_piece = board.piece_on_square(start());
#endif
assert(moving_piece);
assert(moving_piece.color() == board.whose_turn());
assert(moving_piece.can_move(this));
if(auto attacked_piece = board.piece_on_square(end()))
{
if( ! can_capture() || board.whose_turn() == attacked_piece.color())
{
return false;
}
}
return move_specific_legal(board) && ! board.king_is_in_check_after_move(*this);
}
bool Move::move_specific_legal(const Board&) const noexcept
{
return true;
}
bool Move::can_capture() const noexcept
{
return able_to_capture;
}
Square Move::start() const noexcept
{
return origin;
}
Square Move::end() const noexcept
{
return destination;
}
Square_Difference Move::movement() const noexcept
{
return end() - start();
}
int Move::file_change() const noexcept
{
return end().file() - start().file();
}
int Move::rank_change() const noexcept
{
return end().rank() - start().rank();
}
std::string Move::algebraic(const Board& board) const noexcept
{
return algebraic_base(board) + result_mark(board);
}
std::string Move::algebraic_base(const Board& board) const noexcept
{
auto original_piece = board.piece_on_square(start());
std::string move_record = original_piece.pgn_symbol();
auto record_file = false;
auto record_rank = false;
for(auto other_square : Square::all_squares())
{
auto new_piece = board.piece_on_square(other_square);
if(original_piece == new_piece && board.is_legal(other_square, end()))
{
if(other_square.file() != start().file() && ! record_file)
{
record_file = true;
}
else if(other_square.rank() != start().rank())
{
record_rank = true;
}
}
}
if(record_file)
{
move_record += start().file();
}
if(record_rank)
{
move_record += std::to_string(start().rank());
}
if(board.piece_on_square(end()))
{
move_record += 'x';
}
move_record += end().string();
return move_record;
}
std::string Move::result_mark(Board board) const noexcept
{
auto result = board.submit_move(*this);
if(board.king_is_in_check())
{
if(result.winner() == Winner_Color::NONE)
{
return "+";
}
else
{
return "#";
}
}
else
{
return {};
}
}
std::string Move::coordinates() const noexcept
{
auto result = start().string() + end().string();
if(promotion_piece_symbol())
{
result += char(std::tolower(promotion_piece_symbol()));
}
return result;
}
bool Move::is_en_passant() const noexcept
{
return is_en_passant_move;
}
char Move::promotion_piece_symbol() const noexcept
{
return '\0';
}
void Move::adjust_end_file(int adjust) noexcept
{
destination += Square_Difference{adjust, 0};
}
void Move::adjust_end_rank(int adjust) noexcept
{
destination += Square_Difference{0, adjust};
}
size_t Move::attack_index() const noexcept
{
return attack_index(movement());
}
size_t Move::attack_index(const Square_Difference& move) noexcept
{
static constexpr auto xx = size_t(-1); // indicates invalid moves and should never be returned
static constexpr size_t array_width = 15;
// file change
// -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7
static constexpr size_t indices[] = { 0, xx, xx, xx, xx, xx, xx, 1, xx, xx, xx, xx, xx, xx, 2, // 7
xx, 0, xx, xx, xx, xx, xx, 1, xx, xx, xx, xx, xx, 2, xx, // 6
xx, xx, 0, xx, xx, xx, xx, 1, xx, xx, xx, xx, 2, xx, xx, // 5
xx, xx, xx, 0, xx, xx, xx, 1, xx, xx, xx, 2, xx, xx, xx, // 4
xx, xx, xx, xx, 0, xx, xx, 1, xx, xx, 2, xx, xx, xx, xx, // 3
xx, xx, xx, xx, xx, 0, 15, 1, 8, 2, xx, xx, xx, xx, xx, // 2
xx, xx, xx, xx, xx, 14, 0, 1, 2, 9, xx, xx, xx, xx, xx, // 1
3, 3, 3, 3, 3, 3, 3, xx, 4, 4, 4, 4, 4, 4, 4, // 0 rank change
xx, xx, xx, xx, xx, 13, 5, 6, 7, 10, xx, xx, xx, xx, xx, // -1
xx, xx, xx, xx, xx, 5, 12, 6, 11, 7, xx, xx, xx, xx, xx, // -2
xx, xx, xx, xx, 5, xx, xx, 6, xx, xx, 7, xx, xx, xx, xx, // -3
xx, xx, xx, 5, xx, xx, xx, 6, xx, xx, xx, 7, xx, xx, xx, // -4
xx, xx, 5, xx, xx, xx, xx, 6, xx, xx, xx, xx, 7, xx, xx, // -5
xx, 5, xx, xx, xx, xx, xx, 6, xx, xx, xx, xx, xx, 7, xx, // -6
5, xx, xx, xx, xx, xx, xx, 6, xx, xx, xx, xx, xx, xx, 7}; // -7
assert(-7 <= move.rank_change && move.rank_change <= 7);
assert(-7 <= move.file_change && move.file_change <= 7);
auto i = array_width*(7 - move.rank_change) + (move.file_change + 7);
assert(indices[i] < 16);
return indices[i];
}
Square_Difference Move::attack_direction_from_index(size_t index) noexcept
{
// index: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
static constexpr int dx[] = {-1, 0, 1, -1, 1, -1, 0, 1, 1, 2, 2, 1, -1, -2, -2, -1};
static constexpr int dy[] = { 1, 1, 1, 0, 0, -1, -1, -1, 2, 1, -1, -2, -2, -1, 1, 2};
return {dx[index], dy[index]};
}
void Move::disable_capturing() noexcept
{
able_to_capture = false;
}
void Move::enable_capturing() noexcept
{
able_to_capture = true;
}
void Move::mark_as_en_passant() noexcept
{
is_en_passant_move = true;
}
<commit_msg>Bit of cleanup<commit_after>#include "Moves/Move.h"
#include <cassert>
#include <cctype>
#include <string>
#include "Game/Board.h"
#include "Game/Square.h"
#include "Game/Game_Result.h"
#include "Game/Piece.h"
Move::Move(Square start, Square end) noexcept : origin(start), destination(end)
{
assert(start.inside_board());
assert(end.inside_board());
assert(file_change() != 0 || rank_change() != 0);
}
void Move::side_effects(Board&) const noexcept
{
}
bool Move::is_legal(const Board& board) const noexcept
{
assert(board.piece_on_square(start()));
assert(board.piece_on_square(start()).color() == board.whose_turn());
assert(board.piece_on_square(start()).can_move(this));
if(auto attacked_piece = board.piece_on_square(end()))
{
if( ! can_capture() || board.whose_turn() == attacked_piece.color())
{
return false;
}
}
return move_specific_legal(board) && ! board.king_is_in_check_after_move(*this);
}
bool Move::move_specific_legal(const Board&) const noexcept
{
return true;
}
bool Move::can_capture() const noexcept
{
return able_to_capture;
}
Square Move::start() const noexcept
{
return origin;
}
Square Move::end() const noexcept
{
return destination;
}
Square_Difference Move::movement() const noexcept
{
return end() - start();
}
int Move::file_change() const noexcept
{
return end().file() - start().file();
}
int Move::rank_change() const noexcept
{
return end().rank() - start().rank();
}
std::string Move::algebraic(const Board& board) const noexcept
{
return algebraic_base(board) + result_mark(board);
}
std::string Move::algebraic_base(const Board& board) const noexcept
{
auto original_piece = board.piece_on_square(start());
std::string move_record = original_piece.pgn_symbol();
auto record_file = false;
auto record_rank = false;
for(auto other_square : Square::all_squares())
{
auto new_piece = board.piece_on_square(other_square);
if(original_piece == new_piece && board.is_legal(other_square, end()))
{
if(other_square.file() != start().file() && ! record_file)
{
record_file = true;
}
else if(other_square.rank() != start().rank())
{
record_rank = true;
}
}
}
if(record_file)
{
move_record += start().file();
}
if(record_rank)
{
move_record += std::to_string(start().rank());
}
if(board.piece_on_square(end()))
{
move_record += 'x';
}
move_record += end().string();
return move_record;
}
std::string Move::result_mark(Board board) const noexcept
{
auto result = board.submit_move(*this);
if(board.king_is_in_check())
{
if(result.winner() == Winner_Color::NONE)
{
return "+";
}
else
{
return "#";
}
}
else
{
return {};
}
}
std::string Move::coordinates() const noexcept
{
auto result = start().string() + end().string();
if(promotion_piece_symbol())
{
result += char(std::tolower(promotion_piece_symbol()));
}
return result;
}
bool Move::is_en_passant() const noexcept
{
return is_en_passant_move;
}
char Move::promotion_piece_symbol() const noexcept
{
return '\0';
}
void Move::adjust_end_file(int adjust) noexcept
{
destination += Square_Difference{adjust, 0};
}
void Move::adjust_end_rank(int adjust) noexcept
{
destination += Square_Difference{0, adjust};
}
size_t Move::attack_index() const noexcept
{
return attack_index(movement());
}
size_t Move::attack_index(const Square_Difference& move) noexcept
{
static constexpr auto xx = size_t(-1); // indicates invalid moves and should never be returned
static constexpr size_t array_width = 15;
// file change
// -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7
static constexpr size_t indices[] = { 0, xx, xx, xx, xx, xx, xx, 1, xx, xx, xx, xx, xx, xx, 2, // 7
xx, 0, xx, xx, xx, xx, xx, 1, xx, xx, xx, xx, xx, 2, xx, // 6
xx, xx, 0, xx, xx, xx, xx, 1, xx, xx, xx, xx, 2, xx, xx, // 5
xx, xx, xx, 0, xx, xx, xx, 1, xx, xx, xx, 2, xx, xx, xx, // 4
xx, xx, xx, xx, 0, xx, xx, 1, xx, xx, 2, xx, xx, xx, xx, // 3
xx, xx, xx, xx, xx, 0, 15, 1, 8, 2, xx, xx, xx, xx, xx, // 2
xx, xx, xx, xx, xx, 14, 0, 1, 2, 9, xx, xx, xx, xx, xx, // 1
3, 3, 3, 3, 3, 3, 3, xx, 4, 4, 4, 4, 4, 4, 4, // 0 rank change
xx, xx, xx, xx, xx, 13, 5, 6, 7, 10, xx, xx, xx, xx, xx, // -1
xx, xx, xx, xx, xx, 5, 12, 6, 11, 7, xx, xx, xx, xx, xx, // -2
xx, xx, xx, xx, 5, xx, xx, 6, xx, xx, 7, xx, xx, xx, xx, // -3
xx, xx, xx, 5, xx, xx, xx, 6, xx, xx, xx, 7, xx, xx, xx, // -4
xx, xx, 5, xx, xx, xx, xx, 6, xx, xx, xx, xx, 7, xx, xx, // -5
xx, 5, xx, xx, xx, xx, xx, 6, xx, xx, xx, xx, xx, 7, xx, // -6
5, xx, xx, xx, xx, xx, xx, 6, xx, xx, xx, xx, xx, xx, 7}; // -7
assert(-7 <= move.rank_change && move.rank_change <= 7);
assert(-7 <= move.file_change && move.file_change <= 7);
auto i = array_width*(7 - move.rank_change) + (move.file_change + 7);
assert(indices[i] < 16);
return indices[i];
}
Square_Difference Move::attack_direction_from_index(size_t index) noexcept
{
// index: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
static constexpr int dx[] = {-1, 0, 1, -1, 1, -1, 0, 1, 1, 2, 2, 1, -1, -2, -2, -1};
static constexpr int dy[] = { 1, 1, 1, 0, 0, -1, -1, -1, 2, 1, -1, -2, -2, -1, 1, 2};
return {dx[index], dy[index]};
}
void Move::disable_capturing() noexcept
{
able_to_capture = false;
}
void Move::enable_capturing() noexcept
{
able_to_capture = true;
}
void Move::mark_as_en_passant() noexcept
{
is_en_passant_move = true;
}
<|endoftext|> |
<commit_before>// TimeFn.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
struct time {
int hour;
int minute;
int second;
};
class TimeClass {
private:
int _hour; // current hour of the day
int _minute; // current minute of the day
int _second; // current second of the day
time normalize_time(time input) {
// divide by 60 e.g. 75(s) / 60 = 1(int)
int next = input.second / 60;
// get divide remaining and set as current second
input.second = input.second % 60;
// add calculated minutes to the time minute
input.minute += next;
// divide by 60 e.g. 75(m) / 60 = 1(int)
next = input.minute / 60;
// get divide remaining and set as current minute
input.minute = input.minute % 60;
// add extra hours to current hour
input.hour += next;
// normalize hour
input.hour = input.hour % 24;
// return normalized value to the caller
return input;
}
public:
TimeClass() {
// reset hour
_hour = 0;
// reset minute
_minute = 0;
// reset second
_second = 0;
// set default time
set_time(0, 0, 0);
}
TimeClass(int hour, int minute, int second) {
// set time on construction
set_time(hour, minute, second);
}
TimeClass(time t) {
// set time on construction
set_time(t);
}
void set_time(time t) {
// normalize input time
t = normalize_time(t);
// assign hour
_hour = t.hour;
// assign minute
_minute = t.minute;
// assign second
_second = t.second;
}
void set_time(int hour, int minute, int second) {
// create new time variable
time t;
// assign hour
t.hour = hour;
// assign minute
t.minute = minute;
// assign second
t.second = second;
// call set_time with time struct
set_time(t);
}
time get_time() {
// create output variable
time output;
cout << "Hour: ";
// get hour
cin >> output.hour;
cout << "Minute: ";
// get minute
cin >> output.minute;
cout << "Second: ";
// get second
cin >> output.second;
// return output to caller
return output;
}
time subtract(time t1, time t2) {
// create output variable
time output;
// subtract hours
output.hour = t2.hour - t1.hour;
// subtract minutes
output.minute = t2.minute - t1.minute;
// subtract seconds
output.second = t2.second - t1.second;
while (output.hour < 0 || output.minute < 0 || output.second < 0) {
// if hour is negative
if (output.hour < 0) {
// fix negative hour
output.hour += 24;
}
if (output.minute < 0) {
// decrease hour
output.hour -= 1;
// add 60 minutes to current minute
output.minute += 60;
}
if (output.second < 0) {
// decrease minute
output.minute -= 1;
// add 60 seconds to current second
output.second += 60;
}
}
// return output to caller
return output;
}
time add(time t1, time t2) {
// create output variable
time output;
// add hours
output.hour = t1.hour + t2.hour;
// add minutes
output.minute = t1.minute + t2.minute;
// add seconds
output.second = t1.second + t2.second;
// normalize add result
output = normalize_time(output);
// return normalized time to the caller
return output;
}
void show_current_time() {
// show prompt
cout << "Current system time is: ";
// show time
show_time(_hour, _minute, _second);
}
void show_time(int hour, int minute, int second) {
// print time
cout << hour << ":" << minute << ":" << second;
}
};
int main()
{
// create new instance of time class
TimeClass timeEmpty;
// create new instance of time class with integer params
TimeClass timeWithIntParams(22, 65, 80);
// create time
time t;
// set hour
t.hour = 22;
// set minute
t.minute = 65;
// set second
t.second = 80;
// create new instance of time class with time param
TimeClass timeWithTimeParam(t);
// show prompt
cout << "Time is" << "\r\n\r\n";
// show prompt
cout << "\r\n" << "time class with default time constructor" << "\r\n";
// show crrent time of the timeEmpty instance
timeEmpty.show_current_time();
// show prompt
cout << "\r\n" << "time class with int parameters" << "\r\n";
// show current time of the timeWithIntParams instance
timeWithIntParams.show_current_time();
// show prompt
cout << "\r\n" << "time class with time parameters" << "\r\n";
// show current time of the timeWithTimeParam instance
timeWithTimeParam.show_current_time();
// Set time from code-behind
// set current time
timeEmpty.set_time(18, 35, 66);
// show prompt
cout << "\r\n" << "Time has been updated from code." << "\r\n\r\n" << "Time is: ";
// show current time
timeEmpty.show_current_time();
// Get time from user input and update time
// show prompt
cout << "\r\n\r\n" << "Trying to get time from user.\r\n";
// show prompt
cout << "Enter new time: \r\n";
// get time from user
time userTime = timeEmpty.get_time();
// show user entered values
cout << "\r\n" << "User entered: " << userTime.hour << ":" << userTime.minute << ":" << userTime.second;
// update time
timeEmpty.set_time(userTime);
cout << "\r\n" << "Time has been updated by the user. New time is: ";
// show updated time
timeEmpty.show_current_time();
// Add two times
cout << "\r\n\r\nAdd two times\r\n\r\n";
// shor prompt
cout << "Enter time 1: " << "\r\n";
// get time from user
time t1 = timeEmpty.get_time();
// show prompt
cout << "Enter time 2: " << "\r\n";
// get second time from user
time t2 = timeEmpty.get_time();
// add two times
time tResult = timeEmpty.add(t1, t2);
// show add result
cout << "\r\nAdd result: " << tResult.hour << ":" << tResult.minute << ":" << tResult.second;
// subtract two times
cout << "\r\n\r\nSubtract two times\r\n\r\n";
// shor prompt
cout << "Enter time 1: " << "\r\n";
// get time from user
t1 = timeEmpty.get_time();
// show prompt
cout << "Enter time 2: " << "\r\n";
// get second time from user
t2 = timeEmpty.get_time();
// subtract two times
tResult = timeEmpty.subtract(t1, t2);
// show add result
cout << "\r\nSubtract result: " << tResult.hour << ":" << tResult.minute << ":" << tResult.second;
getchar();
// show exit prompt
cout << "\r\nPress return to exit...";
// prevent auto close console window
cin.ignore();
return 0;
}<commit_msg>a fix on subtract function reported by Shaghayegh.kvn<commit_after>// TimeFn.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
struct time {
int hour;
int minute;
int second;
};
class TimeClass {
private:
int _hour; // current hour of the day
int _minute; // current minute of the day
int _second; // current second of the day
time normalize_time(time input) {
// divide by 60 e.g. 75(s) / 60 = 1(int)
int next = input.second / 60;
// get divide remaining and set as current second
input.second = input.second % 60;
// add calculated minutes to the time minute
input.minute += next;
// divide by 60 e.g. 75(m) / 60 = 1(int)
next = input.minute / 60;
// get divide remaining and set as current minute
input.minute = input.minute % 60;
// add extra hours to current hour
input.hour += next;
// normalize hour
input.hour = input.hour % 24;
// return normalized value to the caller
return input;
}
public:
TimeClass() {
// reset hour
_hour = 0;
// reset minute
_minute = 0;
// reset second
_second = 0;
// set default time
set_time(0, 0, 0);
}
TimeClass(int hour, int minute, int second) {
// set time on construction
set_time(hour, minute, second);
}
TimeClass(time t) {
// set time on construction
set_time(t);
}
void set_time(time t) {
// normalize input time
t = normalize_time(t);
// assign hour
_hour = t.hour;
// assign minute
_minute = t.minute;
// assign second
_second = t.second;
}
void set_time(int hour, int minute, int second) {
// create new time variable
time t;
// assign hour
t.hour = hour;
// assign minute
t.minute = minute;
// assign second
t.second = second;
// call set_time with time struct
set_time(t);
}
time get_time() {
// create output variable
time output;
cout << "Hour: ";
// get hour
cin >> output.hour;
cout << "Minute: ";
// get minute
cin >> output.minute;
cout << "Second: ";
// get second
cin >> output.second;
// return output to caller
return output;
}
time subtract(time t1, time t2) {
// create output variable
time output;
// subtract hours
output.hour = t2.hour - t1.hour;
// subtract minutes
output.minute = t2.minute - t1.minute;
// subtract seconds
output.second = t2.second - t1.second;
while (output.hour < 0 || output.minute < 0 || output.second < 0) {
// if hour is negative
if (output.hour < 0) {
// fix negative hour
output.hour += 24;
}
if (output.minute < 0) {
// decrease hour
output.hour -= 1;
// add 60 minutes to current minute
output.minute += 60;
}
if (output.second < 0) {
// decrease minute
output.minute -= 1;
// add 60 seconds to current second
output.second += 60;
}
}
// normalize time again
output = normalize_time(output);
// return output to caller
return output;
}
time add(time t1, time t2) {
// create output variable
time output;
// add hours
output.hour = t1.hour + t2.hour;
// add minutes
output.minute = t1.minute + t2.minute;
// add seconds
output.second = t1.second + t2.second;
// normalize add result
output = normalize_time(output);
// return normalized time to the caller
return output;
}
void show_current_time() {
// show prompt
cout << "Current system time is: ";
// show time
show_time(_hour, _minute, _second);
}
void show_time(int hour, int minute, int second) {
// print time
cout << hour << ":" << minute << ":" << second;
}
};
int main()
{
// create new instance of time class
TimeClass timeEmpty;
// create new instance of time class with integer params
TimeClass timeWithIntParams(22, 65, 80);
// create time
time t;
// set hour
t.hour = 22;
// set minute
t.minute = 65;
// set second
t.second = 80;
// create new instance of time class with time param
TimeClass timeWithTimeParam(t);
// show prompt
cout << "Time is" << "\r\n\r\n";
// show prompt
cout << "\r\n" << "time class with default time constructor" << "\r\n";
// show crrent time of the timeEmpty instance
timeEmpty.show_current_time();
// show prompt
cout << "\r\n" << "time class with int parameters" << "\r\n";
// show current time of the timeWithIntParams instance
timeWithIntParams.show_current_time();
// show prompt
cout << "\r\n" << "time class with time parameters" << "\r\n";
// show current time of the timeWithTimeParam instance
timeWithTimeParam.show_current_time();
// Set time from code-behind
// set current time
timeEmpty.set_time(18, 35, 66);
// show prompt
cout << "\r\n" << "Time has been updated from code." << "\r\n\r\n" << "Time is: ";
// show current time
timeEmpty.show_current_time();
// Get time from user input and update time
// show prompt
cout << "\r\n\r\n" << "Trying to get time from user.\r\n";
// show prompt
cout << "Enter new time: \r\n";
// get time from user
time userTime = timeEmpty.get_time();
// show user entered values
cout << "\r\n" << "User entered: " << userTime.hour << ":" << userTime.minute << ":" << userTime.second;
// update time
timeEmpty.set_time(userTime);
cout << "\r\n" << "Time has been updated by the user. New time is: ";
// show updated time
timeEmpty.show_current_time();
// Add two times
cout << "\r\n\r\nAdd two times\r\n\r\n";
// shor prompt
cout << "Enter time 1: " << "\r\n";
// get time from user
time t1 = timeEmpty.get_time();
// show prompt
cout << "Enter time 2: " << "\r\n";
// get second time from user
time t2 = timeEmpty.get_time();
// add two times
time tResult = timeEmpty.add(t1, t2);
// show add result
cout << "\r\nAdd result: " << tResult.hour << ":" << tResult.minute << ":" << tResult.second;
// subtract two times
cout << "\r\n\r\nSubtract two times\r\n\r\n";
// shor prompt
cout << "Enter time 1: " << "\r\n";
// get time from user
t1 = timeEmpty.get_time();
// show prompt
cout << "Enter time 2: " << "\r\n";
// get second time from user
t2 = timeEmpty.get_time();
// subtract two times
tResult = timeEmpty.subtract(t1, t2);
// show add result
cout << "\r\nSubtract result: " << tResult.hour << ":" << tResult.minute << ":" << tResult.second;
getchar();
// show exit prompt
cout << "\r\nPress return to exit...";
// prevent auto close console window
cin.ignore();
return 0;
}<|endoftext|> |
<commit_before>/*
This source file is part of pairOculus, a student project aiming at creating a
simple 3D multiplayer game for the Oculus Rift.
Repository can be found here : https://github.com/Target6/pairOculus
Copyright (c) 2013 Target6
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 "OgrePlayer.hpp"
OgrePlayer::OgrePlayer(
std::string name,
OgreBulletDynamics::DynamicsWorld *world,
BombManager* bombManager
):
Player(name),
mWorld(world),
mBody(0),
mBombManager(bombManager),
mEntity(0),
mAccelForward(0),
mAccelBack(0),
mAccelLeft(0),
mAccelRight(0),
mAccelUp(0),
mAccelDown(0),
mVelocity(Ogre::Vector3::ZERO),
mGraphicsSetUp(false),
mWasTeleported(false),
mYawCorrection(0),
mPitchCorrection(0),
mRollCorrection(0),
mPositionCorrection(Ogre::Vector3::ZERO),
mBombCooldown(1),
mBombCooldownLeft(0)
{
mTopSpeed = 10;
}
void OgrePlayer::injectPlayerInput(NetworkMessage::PlayerInput *message){
mYaw = message->getYaw();
mPitch = message->getPitch();
mRoll = message->getRoll();
mX = message->getX();
mY = message->getY();
mZ = message->getZ();
mGoingForward = message->getGoingForward();
mGoingBack = message->getGoingBack();
mGoingLeft = message->getGoingLeft();
mGoingRight = message->getGoingRight();
mGoingUp = message->getGoingUp();
mGoingDown = message->getGoingDown();
mPuttingBomb = message->getPuttingBomb();
resetCorrection();
mWasTeleported = true;
}
Ogre::Vector3 OgrePlayer::computeHitboxSize(){
if(mEntity){
Ogre::AxisAlignedBox boundingB = mEntity->getBoundingBox();
Ogre::Vector3 size = boundingB.getSize();
size /= 20;
size.x /= 2;
size.z /= 2;
return size;
}
return Ogre::Vector3::ZERO;
}
void OgrePlayer::generateHitbox(
Ogre::Vector3 size,
Ogre::SceneNode *bodyNode
){
using namespace OgreBulletCollisions;
using namespace Ogre;
BoxCollisionShape *boxShape = new BoxCollisionShape(size);
mBody = new OgreBulletDynamics::RigidBody(mNickname + "Box", mWorld);
Vector3 position(
mX,
mY,
mZ
);
mBody->setShape(
bodyNode,
boxShape,
0.6f,
0.0f,
50.0f,
position
);
mBody->disableDeactivation();
mBody->getBulletRigidBody()->setAngularFactor(btVector3(0, 0, 0));
mBody->getBulletRigidBody()->setGravity(btVector3(0, -98.1 * 2, 0));
}
void OgrePlayer::computeAcceleration(){
if(mGoingForward && mAccelForward < mTopAccel) mAccelForward += 1;
else if(!mGoingForward && mAccelForward > 0) mAccelForward -= 1;
if(mGoingLeft && mAccelLeft < mTopAccel) mAccelLeft += 1;
else if(!mGoingLeft && mAccelLeft > 0) mAccelLeft -= 1;
if(mGoingBack && mAccelBack < mTopAccel) mAccelBack += 1;
else if(!mGoingBack && mAccelBack > 0) mAccelBack -= 1;
if(mGoingRight && mAccelRight < mTopAccel) mAccelRight += 1;
else if(!mGoingRight && mAccelRight > 0) mAccelRight -= 1;
if(mGoingUp && mAccelUp < mTopAccel) mAccelUp += 1;
else if(!mGoingUp && mAccelUp > 0) mAccelUp -= 1;
if(mGoingDown && mAccelDown < mTopAccel) mAccelDown += 1;
else if(!mGoingDown && mAccelDown > 0) mAccelDown -= 1;
}
void OgrePlayer::computeVelocity(const Ogre::FrameEvent &evt){
mVelocity = Ogre::Vector3::ZERO;
if(mGoingForward || mAccelForward)
mVelocity += mAccelForward * getForwardDirection();
if(mGoingLeft || mAccelLeft)
mVelocity -= mAccelLeft * getRightDirection();
if(mGoingBack || mAccelBack)
mVelocity -= mAccelBack * getForwardDirection();
if(mGoingRight || mAccelRight)
mVelocity += mAccelRight * getRightDirection();
mVelocity.y = mBody->getLinearVelocity().y;
if(mGoingUp || mAccelUp)
mVelocity += mAccelUp * getUpDirection();
if(mGoingDown || mAccelDown)
mVelocity -= mAccelDown * getUpDirection();
}
void OgrePlayer::computeNodePosition(const Ogre::FrameEvent &evt){
if(mWasTeleported){
mWasTeleported = false;
}
else{
if(mGraphicsSetUp){
mX = mBody->getSceneNode()->getPosition().x;
mY = mBody->getSceneNode()->getPosition().y;
mZ = mBody->getSceneNode()->getPosition().z;
}
mX += mVelocity.x * evt.timeSinceLastFrame * mTopSpeed;
mY += mVelocity.y * evt.timeSinceLastFrame * mTopSpeed;
mZ += mVelocity.z * evt.timeSinceLastFrame * mTopSpeed;
mYaw += mYawCorrection.valueDegrees();
mPitch += mPitchCorrection.valueDegrees();
mRoll += mRollCorrection.valueDegrees();
mX += mPositionCorrection.x;
mY += mPositionCorrection.y;
mZ += mPositionCorrection.z;
}
if(mGraphicsSetUp){
mBody->getBulletRigidBody()->proceedToTransform(
btTransform(
btQuaternion(Ogre::Degree(mYaw + 180).valueRadians(), 0, 0),
btVector3(mX, mY, mZ)
)
);
Ogre::Vector3 physicsVelocity(Ogre::Vector3::ZERO);
//physicsVelocity.y = mBody->getLinearVelocity().y;
mBody->setLinearVelocity(physicsVelocity);
}
}
void OgrePlayer::handleBombCreation(const Ogre::FrameEvent &evt){
mBombCooldownLeft -= evt.timeSinceLastFrame;
if(mPuttingBomb && mBombCooldownLeft <= 0) {
mBombManager->add(mNickname + "bomb", Ogre::Vector3(getX() ,getY() ,getZ()) + getForwardDirection());
mBombCooldownLeft = mBombCooldown;
}
}
void OgrePlayer::resetCorrection(){
mYawCorrection = 0;
mPitchCorrection = 0;
mRollCorrection = 0;
mPositionCorrection = Ogre::Vector3::ZERO;
}
Ogre::Vector3 OgrePlayer::getForwardDirection(){
using namespace Ogre;
return Quaternion(Degree(mYaw), Vector3::UNIT_Y) * Vector3::UNIT_Z * -1;
}
Ogre::Vector3 OgrePlayer::getUpDirection(){
return Ogre::Vector3::UNIT_Y;
}
Ogre::Vector3 OgrePlayer::getRightDirection(){
using namespace Ogre;
return Quaternion(Degree(mYaw), Vector3::UNIT_Y) * Vector3::UNIT_X;
}
<commit_msg>fixed player gravity<commit_after>/*
This source file is part of pairOculus, a student project aiming at creating a
simple 3D multiplayer game for the Oculus Rift.
Repository can be found here : https://github.com/Target6/pairOculus
Copyright (c) 2013 Target6
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 "OgrePlayer.hpp"
OgrePlayer::OgrePlayer(
std::string name,
OgreBulletDynamics::DynamicsWorld *world,
BombManager* bombManager
):
Player(name),
mWorld(world),
mBody(0),
mBombManager(bombManager),
mEntity(0),
mAccelForward(0),
mAccelBack(0),
mAccelLeft(0),
mAccelRight(0),
mAccelUp(0),
mAccelDown(0),
mVelocity(Ogre::Vector3::ZERO),
mGraphicsSetUp(false),
mWasTeleported(false),
mYawCorrection(0),
mPitchCorrection(0),
mRollCorrection(0),
mPositionCorrection(Ogre::Vector3::ZERO),
mBombCooldown(1),
mBombCooldownLeft(0)
{
mTopSpeed = 10;
}
void OgrePlayer::injectPlayerInput(NetworkMessage::PlayerInput *message){
mYaw = message->getYaw();
mPitch = message->getPitch();
mRoll = message->getRoll();
mX = message->getX();
mY = message->getY();
mZ = message->getZ();
mGoingForward = message->getGoingForward();
mGoingBack = message->getGoingBack();
mGoingLeft = message->getGoingLeft();
mGoingRight = message->getGoingRight();
mGoingUp = message->getGoingUp();
mGoingDown = message->getGoingDown();
mPuttingBomb = message->getPuttingBomb();
resetCorrection();
mWasTeleported = true;
}
Ogre::Vector3 OgrePlayer::computeHitboxSize(){
if(mEntity){
Ogre::AxisAlignedBox boundingB = mEntity->getBoundingBox();
Ogre::Vector3 size = boundingB.getSize();
size /= 20;
size.x /= 2;
size.z /= 2;
return size;
}
return Ogre::Vector3::ZERO;
}
void OgrePlayer::generateHitbox(
Ogre::Vector3 size,
Ogre::SceneNode *bodyNode
){
using namespace OgreBulletCollisions;
using namespace Ogre;
BoxCollisionShape *boxShape = new BoxCollisionShape(size);
mBody = new OgreBulletDynamics::RigidBody(mNickname + "Box", mWorld);
Vector3 position(
mX,
mY,
mZ
);
mBody->setShape(
bodyNode,
boxShape,
0.6f,
0.0f,
50.0f,
position
);
mBody->disableDeactivation();
mBody->getBulletRigidBody()->setAngularFactor(btVector3(0, 0, 0));
mBody->getBulletRigidBody()->setGravity(btVector3(0, -98.1 * 2, 0));
}
void OgrePlayer::computeAcceleration(){
if(mGoingForward && mAccelForward < mTopAccel) mAccelForward += 1;
else if(!mGoingForward && mAccelForward > 0) mAccelForward -= 1;
if(mGoingLeft && mAccelLeft < mTopAccel) mAccelLeft += 1;
else if(!mGoingLeft && mAccelLeft > 0) mAccelLeft -= 1;
if(mGoingBack && mAccelBack < mTopAccel) mAccelBack += 1;
else if(!mGoingBack && mAccelBack > 0) mAccelBack -= 1;
if(mGoingRight && mAccelRight < mTopAccel) mAccelRight += 1;
else if(!mGoingRight && mAccelRight > 0) mAccelRight -= 1;
if(mGoingUp && mAccelUp < mTopAccel) mAccelUp += 1;
else if(!mGoingUp && mAccelUp > 0) mAccelUp -= 1;
if(mGoingDown && mAccelDown < mTopAccel) mAccelDown += 1;
else if(!mGoingDown && mAccelDown > 0) mAccelDown -= 1;
}
void OgrePlayer::computeVelocity(const Ogre::FrameEvent &evt){
mVelocity = Ogre::Vector3::ZERO;
if(mGoingForward || mAccelForward)
mVelocity += mAccelForward * getForwardDirection();
if(mGoingLeft || mAccelLeft)
mVelocity -= mAccelLeft * getRightDirection();
if(mGoingBack || mAccelBack)
mVelocity -= mAccelBack * getForwardDirection();
if(mGoingRight || mAccelRight)
mVelocity += mAccelRight * getRightDirection();
//mVelocity.y = mBody->getLinearVelocity().y;
if(mGoingUp || mAccelUp)
mVelocity += mAccelUp * getUpDirection();
if(mGoingDown || mAccelDown)
mVelocity -= mAccelDown * getUpDirection();
}
void OgrePlayer::computeNodePosition(const Ogre::FrameEvent &evt){
if(mWasTeleported){
mWasTeleported = false;
}
else{
if(mGraphicsSetUp){
mX = mBody->getSceneNode()->getPosition().x;
mY = mBody->getSceneNode()->getPosition().y;
mZ = mBody->getSceneNode()->getPosition().z;
}
mX += mVelocity.x * evt.timeSinceLastFrame * mTopSpeed;
mY += mVelocity.y * evt.timeSinceLastFrame * mTopSpeed;
mZ += mVelocity.z * evt.timeSinceLastFrame * mTopSpeed;
mYaw += mYawCorrection.valueDegrees();
mPitch += mPitchCorrection.valueDegrees();
mRoll += mRollCorrection.valueDegrees();
mX += mPositionCorrection.x;
mY += mPositionCorrection.y;
mZ += mPositionCorrection.z;
}
if(mGraphicsSetUp){
mBody->getBulletRigidBody()->proceedToTransform(
btTransform(
btQuaternion(Ogre::Degree(mYaw + 180).valueRadians(), 0, 0),
btVector3(mX, mY, mZ)
)
);
mBody->setLinearVelocity(Ogre::Vector3::ZERO);
}
}
void OgrePlayer::handleBombCreation(const Ogre::FrameEvent &evt){
mBombCooldownLeft -= evt.timeSinceLastFrame;
if(mPuttingBomb && mBombCooldownLeft <= 0) {
mBombManager->add(mNickname + "bomb", Ogre::Vector3(getX() ,getY() ,getZ()) + getForwardDirection());
mBombCooldownLeft = mBombCooldown;
}
}
void OgrePlayer::resetCorrection(){
mYawCorrection = 0;
mPitchCorrection = 0;
mRollCorrection = 0;
mPositionCorrection = Ogre::Vector3::ZERO;
}
Ogre::Vector3 OgrePlayer::getForwardDirection(){
using namespace Ogre;
return Quaternion(Degree(mYaw), Vector3::UNIT_Y) * Vector3::UNIT_Z * -1;
}
Ogre::Vector3 OgrePlayer::getUpDirection(){
return Ogre::Vector3::UNIT_Y;
}
Ogre::Vector3 OgrePlayer::getRightDirection(){
using namespace Ogre;
return Quaternion(Degree(mYaw), Vector3::UNIT_Y) * Vector3::UNIT_X;
}
<|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2019 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "libmesh/libmesh_config.h"
// C++ includes
#include <iostream>
#include <vector>
#include <string>
#ifdef LIBMESH_HAVE_GETOPT_H
// GCC 2.95.3 (and maybe others) do not include
// getopt.h in unistd.h... However IBM xlC has no
// getopt.h! This works around that.
#include <getopt.h>
#endif
#include <stdio.h>
#include <fstream>
// Local Includes
#include "libmesh/libmesh.h"
#include "libmesh/equation_systems.h"
#include "libmesh/mesh.h"
#include "libmesh/perfmon.h"
#include "libmesh/enum_xdr_mode.h"
using namespace libMesh;
/**
* how to use this, and command line processor
*/
void usage(const std::string & progName)
{
std::ostringstream helpList;
helpList << "usage:\n"
<< " "
<< progName
<< " [options] ...\n"
<< "\n"
<< "options:\n"
<< " -d <dim> <dim>-dimensional mesh\n"
<< " -m <string> Mesh file name\n"
<< " -l <string> Left Equation Systems file name\n"
<< " -r <string> Right Equation Systems file name\n"
<< " -t <float> threshold\n"
<< " -a ASCII format (default)\n"
<< " -b binary format\n"
<< " -v Verbose\n"
<< " -q really quiet\n"
<< " -h Print help menu\n"
<< "\n"
<< "\n"
<< " This program is used to compare equation systems to a user-specified\n"
<< " threshold. Equation systems are imported in the libMesh format\n"
<< " provided through the read and write methods in class EquationSystems.\n"
<< " \n"
<< " ./compare -d 3 -m grid.xda -l leftfile.dat -r rightfile.dat -b -t 1.e-8\n"
<< "\n"
<< " will read in the mesh grid.xda, the equation systems leftfile.dat and\n"
<< " rightfile.dat in binary format and compare systems, and especially the\n"
<< " floats stored in vectors. The comparison is said to be passed when the\n"
<< " floating point values agree up to the given threshold. When no threshold\n"
<< " is set the default libMesh tolerance is used. If neither -a or -b are set,\n"
<< " ASCII format is assumed.\n"
<< "\n";
libmesh_error_msg(helpList.str());
}
void process_cmd_line(int argc,
char ** argv,
std::vector<std::string> & names,
unsigned char & dim,
double & threshold,
XdrMODE & format,
bool & verbose,
bool & quiet)
{
char optionStr[] =
"d:m:l:r:t:abvq?h";
int opt;
bool format_set = false;
bool left_name_set = false;
if (argc < 3)
usage(std::string(argv[0]));
while ((opt = getopt(argc, argv, optionStr)) != -1)
{
switch (opt)
{
/**
* Get mesh file name
*/
case 'm':
{
if (names.empty())
names.push_back(optarg);
else
libmesh_error_msg("ERROR: Mesh file name must precede left file name!");
break;
}
/**
* Get the mesh dimension
*/
case 'd':
{
dim = cast_int<unsigned char>(atoi(optarg));
break;
}
/**
* Get left file name
*/
case 'l':
{
if (!left_name_set)
{
names.push_back(optarg);
left_name_set = true;
}
else
libmesh_error_msg("ERROR: Mesh file name must precede right file name!");
break;
}
/**
* Get right file name
*/
case 'r':
{
if ((!names.empty()) && (left_name_set))
names.push_back(optarg);
else
libmesh_error_msg("ERROR: Mesh file name and left file name must precede right file name!");
break;
}
/**
* Get the comparison threshold
*/
case 't':
{
threshold = atof(optarg);
break;
}
/**
* Use ascii format
*/
case 'a':
{
if (format_set)
libmesh_error_msg("ERROR: Equation system file format already set!");
else
{
format = READ;
format_set = true;
}
break;
}
/**
* Use binary format
*/
case 'b':
{
if (format_set)
libmesh_error_msg("ERROR: Equation system file format already set!");
else
{
format = DECODE;
format_set = true;
}
break;
}
/**
* Be verbose
*/
case 'v':
{
verbose = true;
break;
}
/**
* Be totally quiet, no matter what -v says
*/
case 'q':
{
quiet = true;
break;
}
case 'h':
case '?':
usage(argv[0]);
default:
return;
}
}
}
/**
* everything that is identical for the systems, and
* should _not_ go into EquationSystems::compare(),
* can go in this do_compare().
*/
bool do_compare (EquationSystems & les,
EquationSystems & res,
double threshold,
bool verbose)
{
if (verbose)
{
libMesh::out << "********* LEFT SYSTEM *********" << std::endl;
les.print_info ();
libMesh::out << "********* RIGHT SYSTEM *********" << std::endl;
res.print_info ();
libMesh::out << "********* COMPARISON PHASE *********" << std::endl
<< std::endl;
}
/**
* start comparing
*/
bool result = les.compare(res, threshold, verbose);
if (verbose)
{
libMesh::out << "********* FINISHED *********" << std::endl;
}
return result;
}
int main (int argc, char ** argv)
{
LibMeshInit init(argc, argv);
// these should not be contained in the following braces
bool quiet = false;
bool are_equal;
PerfMon perfmon(argv[0]);
// default values
std::vector<std::string> names;
unsigned char dim = static_cast<unsigned char>(-1);
double threshold = TOLERANCE;
XdrMODE format = READ;
bool verbose = false;
// get commands
process_cmd_line(argc, argv,
names,
dim,
threshold,
format,
verbose,
quiet);
if (dim == static_cast<unsigned char>(-1))
libmesh_error_msg("ERROR: you must specify the dimension on " \
<< "the command line!\n\n" \
<< argv[0] \
<< " -d 3 ... for example");
if (quiet)
verbose = false;
if (verbose)
{
libMesh::out << "Settings:" << std::endl
<< " dimensionality = " << +dim << std::endl
<< " mesh = " << names[0] << std::endl
<< " left system = " << names[1] << std::endl
<< " right system = " << names[2] << std::endl
<< " threshold = " << threshold << std::endl
<< " read format = " << format << std::endl
<< std::endl;
}
/**
* build the left and right mesh for left, init them
*/
Mesh left_mesh (init.comm(), dim);
Mesh right_mesh (init.comm(), dim);
if (!names.empty())
{
left_mesh.read (names[0]);
right_mesh.read (names[0]);
if (verbose)
left_mesh.print_info();
}
else
{
libMesh::out << "No input specified." << std::endl;
return 1;
}
/**
* build EquationSystems objects, read them
*/
EquationSystems left_system (left_mesh);
EquationSystems right_system (right_mesh);
if (names.size() == 3)
{
left_system.read (names[1], format);
right_system.read (names[2], format);
}
else
libmesh_error_msg("Bad input specified.");
are_equal = do_compare (left_system, right_system, threshold, verbose);
/**
* let's see what do_compare found out
*/
unsigned int our_result;
if (are_equal)
{
if (!quiet)
libMesh::out << std::endl
<< " Congrat's, up to the defined threshold, the two"
<< std::endl
<< " are identical."
<< std::endl;
our_result=0;
}
else
{
if (!quiet)
libMesh::out << std::endl
<< " Oops, differences occurred!"
<< std::endl
<< " Use -v to obtain more information where differences occurred."
<< std::endl;
our_result=1;
}
// return libMesh::close();
return our_result;
}
<commit_msg>Explicit conversion to double<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2019 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "libmesh/libmesh_config.h"
// C++ includes
#include <iostream>
#include <vector>
#include <string>
#ifdef LIBMESH_HAVE_GETOPT_H
// GCC 2.95.3 (and maybe others) do not include
// getopt.h in unistd.h... However IBM xlC has no
// getopt.h! This works around that.
#include <getopt.h>
#endif
#include <stdio.h>
#include <fstream>
// Local Includes
#include "libmesh/libmesh.h"
#include "libmesh/equation_systems.h"
#include "libmesh/mesh.h"
#include "libmesh/perfmon.h"
#include "libmesh/enum_xdr_mode.h"
using namespace libMesh;
/**
* how to use this, and command line processor
*/
void usage(const std::string & progName)
{
std::ostringstream helpList;
helpList << "usage:\n"
<< " "
<< progName
<< " [options] ...\n"
<< "\n"
<< "options:\n"
<< " -d <dim> <dim>-dimensional mesh\n"
<< " -m <string> Mesh file name\n"
<< " -l <string> Left Equation Systems file name\n"
<< " -r <string> Right Equation Systems file name\n"
<< " -t <float> threshold\n"
<< " -a ASCII format (default)\n"
<< " -b binary format\n"
<< " -v Verbose\n"
<< " -q really quiet\n"
<< " -h Print help menu\n"
<< "\n"
<< "\n"
<< " This program is used to compare equation systems to a user-specified\n"
<< " threshold. Equation systems are imported in the libMesh format\n"
<< " provided through the read and write methods in class EquationSystems.\n"
<< " \n"
<< " ./compare -d 3 -m grid.xda -l leftfile.dat -r rightfile.dat -b -t 1.e-8\n"
<< "\n"
<< " will read in the mesh grid.xda, the equation systems leftfile.dat and\n"
<< " rightfile.dat in binary format and compare systems, and especially the\n"
<< " floats stored in vectors. The comparison is said to be passed when the\n"
<< " floating point values agree up to the given threshold. When no threshold\n"
<< " is set the default libMesh tolerance is used. If neither -a or -b are set,\n"
<< " ASCII format is assumed.\n"
<< "\n";
libmesh_error_msg(helpList.str());
}
void process_cmd_line(int argc,
char ** argv,
std::vector<std::string> & names,
unsigned char & dim,
double & threshold,
XdrMODE & format,
bool & verbose,
bool & quiet)
{
char optionStr[] =
"d:m:l:r:t:abvq?h";
int opt;
bool format_set = false;
bool left_name_set = false;
if (argc < 3)
usage(std::string(argv[0]));
while ((opt = getopt(argc, argv, optionStr)) != -1)
{
switch (opt)
{
/**
* Get mesh file name
*/
case 'm':
{
if (names.empty())
names.push_back(optarg);
else
libmesh_error_msg("ERROR: Mesh file name must precede left file name!");
break;
}
/**
* Get the mesh dimension
*/
case 'd':
{
dim = cast_int<unsigned char>(atoi(optarg));
break;
}
/**
* Get left file name
*/
case 'l':
{
if (!left_name_set)
{
names.push_back(optarg);
left_name_set = true;
}
else
libmesh_error_msg("ERROR: Mesh file name must precede right file name!");
break;
}
/**
* Get right file name
*/
case 'r':
{
if ((!names.empty()) && (left_name_set))
names.push_back(optarg);
else
libmesh_error_msg("ERROR: Mesh file name and left file name must precede right file name!");
break;
}
/**
* Get the comparison threshold
*/
case 't':
{
threshold = atof(optarg);
break;
}
/**
* Use ascii format
*/
case 'a':
{
if (format_set)
libmesh_error_msg("ERROR: Equation system file format already set!");
else
{
format = READ;
format_set = true;
}
break;
}
/**
* Use binary format
*/
case 'b':
{
if (format_set)
libmesh_error_msg("ERROR: Equation system file format already set!");
else
{
format = DECODE;
format_set = true;
}
break;
}
/**
* Be verbose
*/
case 'v':
{
verbose = true;
break;
}
/**
* Be totally quiet, no matter what -v says
*/
case 'q':
{
quiet = true;
break;
}
case 'h':
case '?':
usage(argv[0]);
default:
return;
}
}
}
/**
* everything that is identical for the systems, and
* should _not_ go into EquationSystems::compare(),
* can go in this do_compare().
*/
bool do_compare (EquationSystems & les,
EquationSystems & res,
double threshold,
bool verbose)
{
if (verbose)
{
libMesh::out << "********* LEFT SYSTEM *********" << std::endl;
les.print_info ();
libMesh::out << "********* RIGHT SYSTEM *********" << std::endl;
res.print_info ();
libMesh::out << "********* COMPARISON PHASE *********" << std::endl
<< std::endl;
}
/**
* start comparing
*/
bool result = les.compare(res, threshold, verbose);
if (verbose)
{
libMesh::out << "********* FINISHED *********" << std::endl;
}
return result;
}
int main (int argc, char ** argv)
{
LibMeshInit init(argc, argv);
// these should not be contained in the following braces
bool quiet = false;
bool are_equal;
PerfMon perfmon(argv[0]);
// default values
std::vector<std::string> names;
unsigned char dim = static_cast<unsigned char>(-1);
double threshold = double(TOLERANCE);
XdrMODE format = READ;
bool verbose = false;
// get commands
process_cmd_line(argc, argv,
names,
dim,
threshold,
format,
verbose,
quiet);
if (dim == static_cast<unsigned char>(-1))
libmesh_error_msg("ERROR: you must specify the dimension on " \
<< "the command line!\n\n" \
<< argv[0] \
<< " -d 3 ... for example");
if (quiet)
verbose = false;
if (verbose)
{
libMesh::out << "Settings:" << std::endl
<< " dimensionality = " << +dim << std::endl
<< " mesh = " << names[0] << std::endl
<< " left system = " << names[1] << std::endl
<< " right system = " << names[2] << std::endl
<< " threshold = " << threshold << std::endl
<< " read format = " << format << std::endl
<< std::endl;
}
/**
* build the left and right mesh for left, init them
*/
Mesh left_mesh (init.comm(), dim);
Mesh right_mesh (init.comm(), dim);
if (!names.empty())
{
left_mesh.read (names[0]);
right_mesh.read (names[0]);
if (verbose)
left_mesh.print_info();
}
else
{
libMesh::out << "No input specified." << std::endl;
return 1;
}
/**
* build EquationSystems objects, read them
*/
EquationSystems left_system (left_mesh);
EquationSystems right_system (right_mesh);
if (names.size() == 3)
{
left_system.read (names[1], format);
right_system.read (names[2], format);
}
else
libmesh_error_msg("Bad input specified.");
are_equal = do_compare (left_system, right_system, threshold, verbose);
/**
* let's see what do_compare found out
*/
unsigned int our_result;
if (are_equal)
{
if (!quiet)
libMesh::out << std::endl
<< " Congrat's, up to the defined threshold, the two"
<< std::endl
<< " are identical."
<< std::endl;
our_result=0;
}
else
{
if (!quiet)
libMesh::out << std::endl
<< " Oops, differences occurred!"
<< std::endl
<< " Use -v to obtain more information where differences occurred."
<< std::endl;
our_result=1;
}
// return libMesh::close();
return our_result;
}
<|endoftext|> |
<commit_before>// Copyright 2006-2009 the V8 project authors. 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// CPU specific code for arm independent of OS goes here.
#ifdef __arm__
#include <sys/syscall.h> // for cache flushing.
#endif
#include "v8.h"
#if defined(V8_TARGET_ARCH_ARM)
#include "cpu.h"
#include "macro-assembler.h"
#include "simulator.h" // for cache flushing.
namespace v8 {
namespace internal {
void CPU::Setup() {
CpuFeatures::Probe(true);
if (!CpuFeatures::IsSupported(VFP3) || Serializer::enabled()) {
V8::DisableCrankshaft();
}
}
void CPU::FlushICache(void* start, size_t size) {
#if defined (USE_SIMULATOR)
// Not generating ARM instructions for C-code. This means that we are
// building an ARM emulator based target. We should notify the simulator
// that the Icache was flushed.
// None of this code ends up in the snapshot so there are no issues
// around whether or not to generate the code when building snapshots.
Simulator::FlushICache(start, size);
#else
// Ideally, we would call
// syscall(__ARM_NR_cacheflush, start,
// reinterpret_cast<intptr_t>(start) + size, 0);
// however, syscall(int, ...) is not supported on all platforms, especially
// not when using EABI, so we call the __ARM_NR_cacheflush syscall directly.
register uint32_t beg asm("a1") = reinterpret_cast<uint32_t>(start);
register uint32_t end asm("a2") =
reinterpret_cast<uint32_t>(start) + size;
register uint32_t flg asm("a3") = 0;
#ifdef __ARM_EABI__
#if defined (__arm__) && !defined(__thumb__)
// __arm__ may be defined in thumb mode.
register uint32_t scno asm("r7") = __ARM_NR_cacheflush;
asm volatile(
"svc 0x0"
: "=r" (beg)
: "0" (beg), "r" (end), "r" (flg), "r" (scno));
#else
// r7 is reserved by the EABI in thumb mode.
asm volatile(
"@ Enter ARM Mode \n\t"
"adr r3, 1f \n\t"
"bx r3 \n\t"
".ALIGN 4 \n\t"
".ARM \n"
"1: push {r7} \n\t"
"mov r7, %4 \n\t"
"svc 0x0 \n\t"
"pop {r7} \n\t"
"@ Enter THUMB Mode\n\t"
"adr r3, 2f+1 \n\t"
"bx r3 \n\t"
".THUMB \n"
"2: \n\t"
: "=r" (beg)
: "0" (beg), "r" (end), "r" (flg), "r" (__ARM_NR_cacheflush)
: "r3");
#endif
#else
#if defined (__arm__) && !defined(__thumb__)
// __arm__ may be defined in thumb mode.
asm volatile(
"svc %1"
: "=r" (beg)
: "i" (__ARM_NR_cacheflush), "0" (beg), "r" (end), "r" (flg));
#else
// Do not use the value of __ARM_NR_cacheflush in the inline assembly
// below, because the thumb mode value would be used, which would be
// wrong, since we switch to ARM mode before executing the svc instruction
asm volatile(
"@ Enter ARM Mode \n\t"
"adr r3, 1f \n\t"
"bx r3 \n\t"
".ALIGN 4 \n\t"
".ARM \n"
"1: svc 0x9f0002 \n"
"@ Enter THUMB Mode\n\t"
"adr r3, 2f+1 \n\t"
"bx r3 \n\t"
".THUMB \n"
"2: \n\t"
: "=r" (beg)
: "0" (beg), "r" (end), "r" (flg)
: "r3");
#endif
#endif
#endif
}
void CPU::DebugBreak() {
#if !defined (__arm__) || !defined(CAN_USE_ARMV5_INSTRUCTIONS)
UNIMPLEMENTED(); // when building ARM emulator target
#else
asm volatile("bkpt 0");
#endif
}
} } // namespace v8::internal
#endif // V8_TARGET_ARCH_ARM
<commit_msg>ARM: Don't try to flush the icache when there is nothing to flush<commit_after>// Copyright 2006-2009 the V8 project authors. 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// CPU specific code for arm independent of OS goes here.
#ifdef __arm__
#include <sys/syscall.h> // for cache flushing.
#endif
#include "v8.h"
#if defined(V8_TARGET_ARCH_ARM)
#include "cpu.h"
#include "macro-assembler.h"
#include "simulator.h" // for cache flushing.
namespace v8 {
namespace internal {
void CPU::Setup() {
CpuFeatures::Probe(true);
if (!CpuFeatures::IsSupported(VFP3) || Serializer::enabled()) {
V8::DisableCrankshaft();
}
}
void CPU::FlushICache(void* start, size_t size) {
// Nothing to do flushing no instructions.
if (size == 0) {
return;
}
#if defined (USE_SIMULATOR)
// Not generating ARM instructions for C-code. This means that we are
// building an ARM emulator based target. We should notify the simulator
// that the Icache was flushed.
// None of this code ends up in the snapshot so there are no issues
// around whether or not to generate the code when building snapshots.
Simulator::FlushICache(start, size);
#else
// Ideally, we would call
// syscall(__ARM_NR_cacheflush, start,
// reinterpret_cast<intptr_t>(start) + size, 0);
// however, syscall(int, ...) is not supported on all platforms, especially
// not when using EABI, so we call the __ARM_NR_cacheflush syscall directly.
register uint32_t beg asm("a1") = reinterpret_cast<uint32_t>(start);
register uint32_t end asm("a2") =
reinterpret_cast<uint32_t>(start) + size;
register uint32_t flg asm("a3") = 0;
#ifdef __ARM_EABI__
#if defined (__arm__) && !defined(__thumb__)
// __arm__ may be defined in thumb mode.
register uint32_t scno asm("r7") = __ARM_NR_cacheflush;
asm volatile(
"svc 0x0"
: "=r" (beg)
: "0" (beg), "r" (end), "r" (flg), "r" (scno));
#else
// r7 is reserved by the EABI in thumb mode.
asm volatile(
"@ Enter ARM Mode \n\t"
"adr r3, 1f \n\t"
"bx r3 \n\t"
".ALIGN 4 \n\t"
".ARM \n"
"1: push {r7} \n\t"
"mov r7, %4 \n\t"
"svc 0x0 \n\t"
"pop {r7} \n\t"
"@ Enter THUMB Mode\n\t"
"adr r3, 2f+1 \n\t"
"bx r3 \n\t"
".THUMB \n"
"2: \n\t"
: "=r" (beg)
: "0" (beg), "r" (end), "r" (flg), "r" (__ARM_NR_cacheflush)
: "r3");
#endif
#else
#if defined (__arm__) && !defined(__thumb__)
// __arm__ may be defined in thumb mode.
asm volatile(
"svc %1"
: "=r" (beg)
: "i" (__ARM_NR_cacheflush), "0" (beg), "r" (end), "r" (flg));
#else
// Do not use the value of __ARM_NR_cacheflush in the inline assembly
// below, because the thumb mode value would be used, which would be
// wrong, since we switch to ARM mode before executing the svc instruction
asm volatile(
"@ Enter ARM Mode \n\t"
"adr r3, 1f \n\t"
"bx r3 \n\t"
".ALIGN 4 \n\t"
".ARM \n"
"1: svc 0x9f0002 \n"
"@ Enter THUMB Mode\n\t"
"adr r3, 2f+1 \n\t"
"bx r3 \n\t"
".THUMB \n"
"2: \n\t"
: "=r" (beg)
: "0" (beg), "r" (end), "r" (flg)
: "r3");
#endif
#endif
#endif
}
void CPU::DebugBreak() {
#if !defined (__arm__) || !defined(CAN_USE_ARMV5_INSTRUCTIONS)
UNIMPLEMENTED(); // when building ARM emulator target
#else
asm volatile("bkpt 0");
#endif
}
} } // namespace v8::internal
#endif // V8_TARGET_ARCH_ARM
<|endoftext|> |
<commit_before>//
// Created by volundr on 7/6/16.
//
#include "UartInterface.h"
namespace bno055 {
/**
* Opens communications with the UART device found at location 'deviceFile'
* This code was taken from the 'Using the UART' tutorial page found at
* http://www.raspberry-projects.com/pi/programming-in-c/uart-serial-port/using-the-uart
*/
bool UartInterface::openPort(const char* deviceFile, tcflag_t baudRate) {
/*
* Close any existing serial communications
*/
closePort();
/*
* OPEN THE UART
* The flags (defined in fcntl.h):
* Access modes (use 1 of these):
* O_RDONLY - Open for reading only.
* O_RDWR - Open for reading and writing.
* O_WRONLY - Open for writing only.
*
* O_NDELAY / O_NONBLOCK (same function) -
* Enables nonblocking mode. When set read requests on the file can return immediately with a failure status
* if there is no input immediately available (instead of blocking). Likewise, sendData requests can also return
* immediately with a failure status if the output can't be written immediately.
*
* O_NOCTTY -
* When set and path identifies a terminal device, open() shall not cause the terminal device to become the
* controlling terminal for the process.
*/
// uartFile = open(deviceFile, O_RDWR | O_NOCTTY | O_SYNC); //Open in synchronous mode
uartFile = open(deviceFile, O_RDWR | O_NOCTTY | O_NONBLOCK); //Open in asynchronous mode
if (uartFile == -1) {
return false;
}
/*
* CONFIGURE THE UART
* The flags (defined in /usr/include/termios.h -
* see http://pubs.opengroup.org/onlinepubs/007908799/xsh/termios.h.html):
*
* Baud rate: B1200, B2400, B4800, B9600, B19200, B38400, B57600, B115200, B230400, B460800, B500000, B576000,
* B921600, B1000000, B1152000, B1500000, B2000000, B2500000, B3000000, B3500000, B4000000
* CSIZE : CS5, CS6, CS7, CS8
* CLOCAL : Ignore modem status lines
* CREAD : Enable receiver
* IGNPAR : Ignore characters with parity errors
* ICRNL : Map CR to NL on input (Use for ASCII comms where you want to auto correct end of line characters
* - don't use for bianry comms!)
* PARENB : Parity enable
* PARODD : Odd parity (else even)
*/
struct termios options;
tcgetattr(uartFile, &options);
options.c_cflag = baudRate | CS8 | CLOCAL | CREAD; //<Set baud rate
options.c_iflag = IGNPAR;
options.c_oflag = 0;
options.c_lflag = 0;
tcflush(uartFile, TCIOFLUSH);
tcsetattr(uartFile, TCSANOW, &options);
return true;
}
bool UartInterface::closePort() {
if (uartFile != -1) {
close(uartFile);
uartFile = -1;
return true;
}
return false;
}
UartInterface::~UartInterface() {
if (uartFile != -1) {
close(uartFile);
}
}
int64_t UartInterface::sendData(uint8_t* data, uint32_t length) {
if (uartFile == -1) {
return -1;
} else {
return (int64_t)write(uartFile, data, length);
}
}
int64_t UartInterface::recvData(uint8_t* empty, uint32_t maxLength) {
if (uartFile == -1) {
return -1;
} else {
return (int64_t)read(uartFile, (void*)empty, maxLength);
}
}
}
<commit_msg>trying synchronous serial<commit_after>//
// Created by volundr on 7/6/16.
//
#include "UartInterface.h"
namespace bno055 {
/**
* Opens communications with the UART device found at location 'deviceFile'
* This code was taken from the 'Using the UART' tutorial page found at
* http://www.raspberry-projects.com/pi/programming-in-c/uart-serial-port/using-the-uart
*/
bool UartInterface::openPort(const char* deviceFile, tcflag_t baudRate) {
/*
* Close any existing serial communications
*/
closePort();
/*
* OPEN THE UART
* The flags (defined in fcntl.h):
* Access modes (use 1 of these):
* O_RDONLY - Open for reading only.
* O_RDWR - Open for reading and writing.
* O_WRONLY - Open for writing only.
*
* O_NDELAY / O_NONBLOCK (same function) -
* Enables nonblocking mode. When set read requests on the file can return immediately with a failure status
* if there is no input immediately available (instead of blocking). Likewise, sendData requests can also return
* immediately with a failure status if the output can't be written immediately.
*
* O_NOCTTY -
* When set and path identifies a terminal device, open() shall not cause the terminal device to become the
* controlling terminal for the process.
*/
uartFile = open(deviceFile, O_RDWR | O_NOCTTY | O_SYNC); //Open in synchronous mode
// uartFile = open(deviceFile, O_RDWR | O_NOCTTY | O_NONBLOCK); //Open in asynchronous mode
if (uartFile == -1) {
return false;
}
/*
* CONFIGURE THE UART
* The flags (defined in /usr/include/termios.h -
* see http://pubs.opengroup.org/onlinepubs/007908799/xsh/termios.h.html):
*
* Baud rate: B1200, B2400, B4800, B9600, B19200, B38400, B57600, B115200, B230400, B460800, B500000, B576000,
* B921600, B1000000, B1152000, B1500000, B2000000, B2500000, B3000000, B3500000, B4000000
* CSIZE : CS5, CS6, CS7, CS8
* CLOCAL : Ignore modem status lines
* CREAD : Enable receiver
* IGNPAR : Ignore characters with parity errors
* ICRNL : Map CR to NL on input (Use for ASCII comms where you want to auto correct end of line characters
* - don't use for bianry comms!)
* PARENB : Parity enable
* PARODD : Odd parity (else even)
*/
struct termios options;
tcgetattr(uartFile, &options);
options.c_cflag = baudRate | CS8 | CLOCAL | CREAD; //<Set baud rate
options.c_iflag = IGNPAR;
options.c_oflag = 0;
options.c_lflag = 0;
tcflush(uartFile, TCIOFLUSH);
tcsetattr(uartFile, TCSANOW, &options);
return true;
}
bool UartInterface::closePort() {
if (uartFile != -1) {
close(uartFile);
uartFile = -1;
return true;
}
return false;
}
UartInterface::~UartInterface() {
if (uartFile != -1) {
close(uartFile);
}
}
int64_t UartInterface::sendData(uint8_t* data, uint32_t length) {
if (uartFile == -1) {
return -1;
} else {
return (int64_t)write(uartFile, data, length);
}
}
int64_t UartInterface::recvData(uint8_t* empty, uint32_t maxLength) {
if (uartFile == -1) {
return -1;
} else {
return (int64_t)read(uartFile, (void*)empty, maxLength);
}
}
}
<|endoftext|> |
<commit_before>/*
* C++ UDP socket server for live image upstreaming
* Modified from http://cs.ecs.baylor.edu/~donahoo/practical/CSockets/practical/UDPEchoServer.cpp
* Copyright (C) 2015
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "PracticalSocket.h" // For UDPSocket and SocketException
#include <iostream> // For cout and cerr
#include <cstdlib> // For atoi()
/* Added by CY */
#include <sys/poll.h> // http://beej.us/guide/bgnet/output/html/multipage/pollman.html
#include <ncurses.h> // sudo apt-get install libncurses-dev. For getch() getting pressed key.
#define BUF_LEN 65540 // Larger than maximum UDP packet size
#define TOTAL_PACK 30 // This value was dynamically configured in run-time with a range around 20 to 21 on my Surface. Set to 30 here to keep some room.
#include "opencv2/opencv.hpp"
using namespace cv;
#include "config.h"
timespec ts_diff(timespec start, timespec end);
int main(int argc, char * argv[]) {
if (argc != 4) { // Test for correct number of parameters
cerr << "Usage: " << argv[0] << " <IF#1 IP> <IF#2 IP> <Server Port> " << endl;
exit(1);
}
string if1Address = argv[1];
string if2Address = argv[2];
unsigned short servPort1 = atoi(argv[3]); // First arg: local port
unsigned short servPort2 = servPort1;
namedWindow("recv", CV_WINDOW_AUTOSIZE);
try {
UDPSocket sock1(if1Address, servPort1);
UDPSocket sock2(if2Address, servPort2);
//char buffer[BUF_LEN]; // Buffer for echo string
int recvMsgSize; // Size of received message
string sourceAddress; // Address of datagram source
unsigned short sourcePort; // Port of datagram source
struct timespec ts_last;
clock_gettime(CLOCK_MONOTONIC, &ts_last);
/* Variables for the primary interface */
int sock1State = 0;
int sock1TotoalPack = 0;
int sock1PackCount = 0;
char buffer1[BUF_LEN]; // Buffer for echo string
char * longbuf1 = new char[PACK_SIZE * TOTAL_PACK];
/* Variables for the secondary interface */
int sock2State = 0;
int sock2TotoalPack = 0;
int sock2PackCount = 0;
char buffer2[BUF_LEN]; // Buffer for echo string
char * longbuf2 = new char[PACK_SIZE * TOTAL_PACK];
/* Initialize getch() */
initscr();
clear();
noecho();
cbreak();
nodelay(stdscr, TRUE); // to make getch() non-blocking.
int key = 0;
while (1) {
key = getch();
if (key != ERR) {
cout << "key pressed.\r" << endl;
}
int rv;
struct pollfd ufds[2];
ufds[0].fd = sock1.getDescriptor();
ufds[0].events = POLLIN; // check for just normal data
ufds[1].fd = sock2.getDescriptor();
ufds[1].events = POLLIN; // check for just normal data
rv = poll(ufds, 2, 100); // The third parameter is timeout in minisecond.
if (rv == -1) {
perror("poll"); // error occurred in poll()
} else if (rv == 0) {
//printf("Timeout occurred! No data after 100 miniseconds.\n");
continue;
}
/* sock1State and sock2State:
* 0: Waiting for the initial packet (indicating the length of the frame packets) of a frame.
* 1: The initial packet has been received, in the process of receiving frame packets.
* 2: A complete frame has been received. This state is used for displaying the frame.
*/
// check for events on s1:
if (ufds[0].revents & POLLIN) {
if (sock1State == 0) {
recvMsgSize = sock1.recvFrom(buffer1, BUF_LEN, sourceAddress, sourcePort);
if (recvMsgSize > sizeof(int)) {
;
} else {
sock1TotoalPack = ((int * ) buffer1)[0];
sock1State = 1;
sock1PackCount = 0;
}
} else if (sock1State == 1) {
recvMsgSize = sock1.recvFrom(buffer1, BUF_LEN, sourceAddress, sourcePort);
if (recvMsgSize != PACK_SIZE) {
cerr << "Received unexpected size pack:" << recvMsgSize << endl;
//continue;
sock1State = 0; // Something wrong happens, so reset the state.
} else {
memcpy( & longbuf1[sock1PackCount * PACK_SIZE], buffer1, PACK_SIZE);
sock1PackCount++;
if (sock1PackCount == sock1TotoalPack) {
// One frame data is complete.
sock1State = 2;
}
}
}
}
// check for events on s2:
if (ufds[1].revents & POLLIN) {
if (sock2State == 0) {
recvMsgSize = sock2.recvFrom(buffer2, BUF_LEN, sourceAddress, sourcePort);
if (recvMsgSize > sizeof(int)) {
;
} else {
sock2TotoalPack = ((int * ) buffer2)[0];
sock2State = 1;
sock2PackCount = 0;
}
} else if (sock2State == 1) {
recvMsgSize = sock2.recvFrom(buffer2, BUF_LEN, sourceAddress, sourcePort);
if (recvMsgSize != PACK_SIZE) {
cerr << "Received unexpected size pack:" << recvMsgSize << endl;
//continue;
sock2State = 0; // Something wrong happens, so reset the state.
} else {
memcpy( & longbuf2[sock2PackCount * PACK_SIZE], buffer2, PACK_SIZE);
sock2PackCount++;
if (sock2PackCount == sock2TotoalPack) {
// One frame data is complete.
sock2State = 2;
}
}
}
}
/* If any of the interface has received a complete frame, go and display it. */
if ( (sock1State==2) || (sock2State==2) ) {
int total_pack;
Mat rawData;
if (sock1State == 2) {
/* sock1 has a frame. */
rawData = Mat(1, PACK_SIZE * sock1TotoalPack, CV_8UC1, longbuf1);
sock1State = 0;
total_pack = sock1TotoalPack;
if (sock2State == 2) {
/* Drop sock2's frame since we are using the frame from sock1. */
sock2State = 0;
}
cout << "Fram displayed from Main interface.\r" << endl;
} else if (sock2State == 2) {
/* sock2 has a frame while sock1 doesn't have one. */
rawData = Mat(1, PACK_SIZE * sock2TotoalPack, CV_8UC1, longbuf2);
sock2State = 0;
total_pack = sock2TotoalPack;
cout << "Fram displayed from Second interface.\r" << endl;
}
//Mat rawData = Mat(1, PACK_SIZE * total_pack, CV_8UC1, longbuf);
Mat frame = imdecode(rawData, CV_LOAD_IMAGE_COLOR);
if (frame.size().width == 0) {
cerr << "decode failure!" << endl;
continue;
}
imshow("recv", frame);
//free(longbuf);
waitKey(1);
struct timespec ts_next;
clock_gettime(CLOCK_MONOTONIC, &ts_next);
struct timespec ts_duration = ts_diff(ts_last, ts_next);
double duration = (ts_duration.tv_nsec)/1000000000.0;
cout << "\teffective FPS:" << (1 / duration) << " \tkbps:" << (PACK_SIZE * total_pack / duration / 1024 * 8) << "\r" << endl;
cout << "time period:" << duration << "\r" << endl;
ts_last.tv_nsec = ts_next.tv_nsec;
}
}
} catch (SocketException & e) {
cerr << e.what() << endl;
exit(1);
}
return 0;
}
timespec ts_diff(timespec start, timespec end)
{
timespec temp;
if ((end.tv_nsec-start.tv_nsec)<0) {
temp.tv_sec = end.tv_sec-start.tv_sec-1;
temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
} else {
temp.tv_sec = end.tv_sec-start.tv_sec;
temp.tv_nsec = end.tv_nsec-start.tv_nsec;
}
return temp;
}<commit_msg>Output log: <timestamp>,<Interface>,<FPS>,<kbps><commit_after>/*
* C++ UDP socket server for live image upstreaming
* Modified from http://cs.ecs.baylor.edu/~donahoo/practical/CSockets/practical/UDPEchoServer.cpp
* Copyright (C) 2015
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "PracticalSocket.h" // For UDPSocket and SocketException
#include <iostream> // For cout and cerr
#include <cstdlib> // For atoi()
/* Added by CY */
#include <sys/poll.h> // http://beej.us/guide/bgnet/output/html/multipage/pollman.html
#include <ncurses.h> // sudo apt-get install libncurses-dev. For getch() getting pressed key.
#define BUF_LEN 65540 // Larger than maximum UDP packet size
#define TOTAL_PACK 30 // This value was dynamically configured in run-time with a range around 20 to 21 on my Surface. Set to 30 here to keep some room.
#include "opencv2/opencv.hpp"
using namespace cv;
#include "config.h"
timespec ts_diff(timespec start, timespec end);
int main(int argc, char * argv[]) {
if (argc != 4) { // Test for correct number of parameters
cerr << "Usage: " << argv[0] << " <IF#1 IP> <IF#2 IP> <Server Port> " << endl;
exit(1);
}
string if1Address = argv[1];
string if2Address = argv[2];
unsigned short servPort1 = atoi(argv[3]); // First arg: local port
unsigned short servPort2 = servPort1;
namedWindow("recv", CV_WINDOW_AUTOSIZE);
try {
UDPSocket sock1(if1Address, servPort1);
UDPSocket sock2(if2Address, servPort2);
//char buffer[BUF_LEN]; // Buffer for echo string
int recvMsgSize; // Size of received message
string sourceAddress; // Address of datagram source
unsigned short sourcePort; // Port of datagram source
struct timespec ts_last;
struct timespec ts_last_if1;
struct timespec ts_last_if2;
clock_gettime(CLOCK_MONOTONIC, &ts_last);
clock_gettime(CLOCK_MONOTONIC, &ts_last_if1);
clock_gettime(CLOCK_MONOTONIC, &ts_last_if2);
/* Variables for the primary interface */
int sock1State = 0;
int sock1TotoalPack = 0;
int sock1PackCount = 0;
char buffer1[BUF_LEN]; // Buffer for echo string
char * longbuf1 = new char[PACK_SIZE * TOTAL_PACK];
/* Variables for the secondary interface */
int sock2State = 0;
int sock2TotoalPack = 0;
int sock2PackCount = 0;
char buffer2[BUF_LEN]; // Buffer for echo string
char * longbuf2 = new char[PACK_SIZE * TOTAL_PACK];
/* Initialize getch() */
initscr();
clear();
noecho();
cbreak();
nodelay(stdscr, TRUE); // to make getch() non-blocking.
int key = 0;
while (1) {
key = getch();
if (key != ERR) {
cout << "key pressed.\r" << endl;
}
int rv;
struct pollfd ufds[2];
ufds[0].fd = sock1.getDescriptor();
ufds[0].events = POLLIN; // check for just normal data
ufds[1].fd = sock2.getDescriptor();
ufds[1].events = POLLIN; // check for just normal data
rv = poll(ufds, 2, 100); // The third parameter is timeout in minisecond.
if (rv == -1) {
perror("poll"); // error occurred in poll()
} else if (rv == 0) {
//printf("Timeout occurred! No data after 100 miniseconds.\n");
continue;
}
/* sock1State and sock2State:
* 0: Waiting for the initial packet (indicating the length of the frame packets) of a frame.
* 1: The initial packet has been received, in the process of receiving frame packets.
* 2: A complete frame has been received. This state is used for displaying the frame.
*/
// check for events on s1:
if (ufds[0].revents & POLLIN) {
if (sock1State == 0) {
recvMsgSize = sock1.recvFrom(buffer1, BUF_LEN, sourceAddress, sourcePort);
if (recvMsgSize > sizeof(int)) {
;
} else {
sock1TotoalPack = ((int * ) buffer1)[0];
sock1State = 1;
sock1PackCount = 0;
}
} else if (sock1State == 1) {
recvMsgSize = sock1.recvFrom(buffer1, BUF_LEN, sourceAddress, sourcePort);
if (recvMsgSize != PACK_SIZE) {
cerr << "Received unexpected size pack:" << recvMsgSize << endl;
//continue;
sock1State = 0; // Something wrong happens, so reset the state.
} else {
memcpy( & longbuf1[sock1PackCount * PACK_SIZE], buffer1, PACK_SIZE);
sock1PackCount++;
if (sock1PackCount == sock1TotoalPack) {
// One frame data is complete.
sock1State = 2;
}
}
}
}
// check for events on s2:
if (ufds[1].revents & POLLIN) {
if (sock2State == 0) {
recvMsgSize = sock2.recvFrom(buffer2, BUF_LEN, sourceAddress, sourcePort);
if (recvMsgSize > sizeof(int)) {
;
} else {
sock2TotoalPack = ((int * ) buffer2)[0];
sock2State = 1;
sock2PackCount = 0;
}
} else if (sock2State == 1) {
recvMsgSize = sock2.recvFrom(buffer2, BUF_LEN, sourceAddress, sourcePort);
if (recvMsgSize != PACK_SIZE) {
cerr << "Received unexpected size pack:" << recvMsgSize << endl;
//continue;
sock2State = 0; // Something wrong happens, so reset the state.
} else {
memcpy( & longbuf2[sock2PackCount * PACK_SIZE], buffer2, PACK_SIZE);
sock2PackCount++;
if (sock2PackCount == sock2TotoalPack) {
// One frame data is complete.
sock2State = 2;
}
}
}
}
/* If any of the interface has received a complete frame, go and display it. */
if ( (sock1State==2) || (sock2State==2) ) {
struct timespec ts_next;
clock_gettime(CLOCK_MONOTONIC, &ts_next);
struct timespec ts_duration;
double duration;
int total_pack;
Mat rawData;
if (sock1State == 2) {
/* sock1 has a frame. */
rawData = Mat(1, PACK_SIZE * sock1TotoalPack, CV_8UC1, longbuf1);
sock1State = 0;
total_pack = sock1TotoalPack;
if (sock2State == 2) {
/* Drop sock2's frame since we are using the frame from sock1. */
sock2State = 0;
}
//cout << "Fram displayed from Main interface.\r" << endl;
ts_duration = ts_diff(ts_last_if1, ts_next);
duration = (ts_duration.tv_nsec)/1000000000.0;
ts_last_if1.tv_nsec = ts_next.tv_nsec;
cout << ts_next.tv_nsec << "," << "IF1," << (1 / duration) << "," << (PACK_SIZE * total_pack / duration / 1024 * 8) << "\r" << endl;
} else if (sock2State == 2) {
/* sock2 has a frame while sock1 doesn't have one. */
rawData = Mat(1, PACK_SIZE * sock2TotoalPack, CV_8UC1, longbuf2);
sock2State = 0;
total_pack = sock2TotoalPack;
//cout << "Fram displayed from Second interface.\r" << endl;
ts_duration = ts_diff(ts_last_if2, ts_next);
duration = (ts_duration.tv_nsec)/1000000000.0;
ts_last_if2.tv_nsec = ts_next.tv_nsec;
cout << ts_next.tv_nsec << "," << "IF2," << (1 / duration) << "," << (PACK_SIZE * total_pack / duration / 1024 * 8) << "\r" << endl;
}
//Mat rawData = Mat(1, PACK_SIZE * total_pack, CV_8UC1, longbuf);
Mat frame = imdecode(rawData, CV_LOAD_IMAGE_COLOR);
if (frame.size().width == 0) {
cerr << "decode failure!" << endl;
continue;
}
imshow("recv", frame);
//free(longbuf);
waitKey(1);
cout << ts_next.tv_nsec << "," << "all," << (1 / duration) << "," << (PACK_SIZE * total_pack / duration / 1024 * 8) << "\r" << endl;
}
}
} catch (SocketException & e) {
cerr << e.what() << endl;
exit(1);
}
return 0;
}
timespec ts_diff(timespec start, timespec end)
{
timespec temp;
if ((end.tv_nsec-start.tv_nsec)<0) {
temp.tv_sec = end.tv_sec-start.tv_sec-1;
temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
} else {
temp.tv_sec = end.tv_sec-start.tv_sec;
temp.tv_nsec = end.tv_nsec-start.tv_nsec;
}
return temp;
}<|endoftext|> |
<commit_before>/*
Greesound
Copyright (C) 2015 Grame
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Grame Centre national de création musicale
11, cours de Verdun Gensoul 69002 Lyon - France
*/
#include <QQuickItem>
#ifdef ANDROID
# include <QtAndroid>
# include <QAndroidJniObject>
#endif
#include "SensorAppl.h"
extern const char* kGreensoundsAddr;
extern const char* kButtonsAddr;
const float kVersion = 1.13f;
const char* kVersionStr = "1.13";
using namespace std;
//------------------------------------------------------------------------
OSCListener::OSCListener(SensorAppl* appl, int port)
: fSocket(IpEndpointName( IpEndpointName::ANY_ADDRESS, port ), this), fAppl(appl), fRunning(false) {}
OSCListener::~OSCListener() { fSocket.AsynchronousBreak(); }
//------------------------------------------------------------------------
void OSCListener::run()
{
fRunning = true;
try {
fSocket.Run();
}
catch (osc::Exception e) {
cerr << "osc error: " << e.what() << endl;
}
fRunning = false;
}
//------------------------------------------------------------------------
SensorAppl::~SensorAppl()
{
fSensors.send(kGreensoundsAddr, fSensors.ipstr(), "bye");
fListener.terminate();
}
#ifdef ANDROID
static void keepScreenOn(bool on)
{
QtAndroid::runOnAndroidThread([on]{
QAndroidJniObject activity = QtAndroid::androidActivity();
if (activity.isValid()) {
QAndroidJniObject window =
activity.callObjectMethod("getWindow", "()Landroid/view/Window;");
if (window.isValid()) {
const int FLAG_KEEP_SCREEN_ON = 128;
if (on) {
window.callMethod<void>("addFlags", "(I)V", FLAG_KEEP_SCREEN_ON);
} else {
window.callMethod<void>("clearFlags", "(I)V", FLAG_KEEP_SCREEN_ON);
}
}
}
// QAndroidJniEnvironment env;
// if (env->ExceptionCheck()) {
// env->ExceptionClear();
// }
});
}
#else
static void keepScreenOn(bool ) {}
#endif
//#define TESTMOTOE
//------------------------------------------------------------------------
void SensorAppl::start()
{
keepScreenOn(true);
fView.setSource(QUrl("qrc:/GSinit.qml"));
fView.rootContext()->setContextProperty("sensors", &fSensors);
fView.show();
#ifndef MACOS
bool ret = fSensors.initSensor();
if (!ret) {
fView.setSource(QUrl("qrc:/failsensor.qml"));
}
else {
// fView.setSource(QUrl("qrc:/GSinit.qml"));
// fView.rootContext()->setContextProperty("sensors", &fSensors);
// fView.show();
fTimerID = startTimer(1000);
fListener.start();
}
#else
fTimerID = startTimer(1000);
fListener.start();
#endif
connect((QObject*)fView.engine(), SIGNAL(quit()), this, SLOT(quit()));
connect((QObject*)this, SIGNAL(applicationStateChanged(Qt::ApplicationState)), this, SLOT(stateChanged(Qt::ApplicationState)));
}
//------------------------------------------------------------------------
void SensorAppl::stateChanged(Qt::ApplicationState )
{
#ifndef MACOS
if ((state == Qt::ApplicationSuspended) || ((state == Qt::ApplicationInactive))) {
quit();
}
#endif
}
//------------------------------------------------------------------------
void SensorAppl::greensound()
{
fView.setSource(QUrl("qrc:/GSwait.qml"));
fView.rootContext()->setContextProperty("sensors", &fSensors);
fSensors.start((QObject*)fView.rootObject());
fRunning = true;
}
//------------------------------------------------------------------------
void SensorAppl::wait()
{
fWait = true;
fUISwitch = true;
fSensors.stop();
}
//------------------------------------------------------------------------
void SensorAppl::play()
{
fWait = false;
fUISwitch = true;
fSensors.start();
fSensors.pmode(false);
}
//------------------------------------------------------------------------
void SensorAppl::setButtons(int b1, int b2, int b3)
{
fButtonsState[0] = b1;
fButtonsState[1] = b2;
fButtonsState[2] = b3;
fSetButtons = true;
}
//------------------------------------------------------------------------
void SensorAppl::timerEvent(QTimerEvent*)
{
static int ntry = 1;
if (fRunning) {
if (fUISwitch) {
if (fWait)
fView.setSource(QUrl("qrc:/GSwait.qml"));
else
fView.setSource(QUrl("qrc:/greensounds.qml"));
fUISwitch = false;
}
fSensors.send(kGreensoundsAddr, fSensors.ipstr(), fWait ? "wait" : "play");
if (fSetButtons) {
QQuickItem* root = fView.rootObject();
QObject *b = root->findChild<QObject*>("b1");
if (b) b->setProperty("visible", fButtonsState[0]);
b = root->findChild<QObject*>("b2");
if (b) b->setProperty("visible", fButtonsState[1]);
b = root->findChild<QObject*>("b3");
if (b) b->setProperty("visible", fButtonsState[2]);
fSetButtons = false;
}
}
else if (fSensors.connected() ) {
if (fSensors.network()) {
greensound();
}
else
fView.setSource(QUrl("qrc:/failnetwork.qml"));
}
else if (ntry < 5) {
fSensors.hello();
ntry++;
}
else if (fSensors.skip()) {
greensound();
}
else fView.setSource(QUrl("qrc:/failnetwork.qml"));
}
//------------------------------------------------------------------------
void OSCListener::ProcessMessage( const osc::ReceivedMessage& m, const IpEndpointName& src )
{
string address(m.AddressPattern());
try {
if (address == kGreensoundsAddr) {
osc::ReceivedMessageArgumentIterator i = m.ArgumentsBegin();
while (i != m.ArgumentsEnd()) {
if (i->IsString()) {
string msg(i->AsStringUnchecked());
if (msg == "hello") {
char buff[120];
src.AddressAsString(buff);
fAppl->connect_to(buff);
}
else if (msg == "version")
fAppl->sensors()->send (kGreensoundsAddr, "version", kVersion);
else if (msg == "wait")
fAppl->wait();
else if (msg == "play")
fAppl->play();
else if (msg == "quit")
fAppl->quit();
}
else if (i->IsInt32()) {
}
else if (i->IsFloat()) {
}
i++;
}
}
else if ((address == kButtonsAddr) && (m.ArgumentCount() == 3)) {
osc::ReceivedMessageArgumentStream args = m.ArgumentStream();
osc::int32 b1, b2, b3;
args >> b1 >> b2 >> b3;
fAppl->setButtons( b1, b2, b3);
}
}
catch(std::exception e) {}
}
<commit_msg>fix missing param name<commit_after>/*
Greesound
Copyright (C) 2015 Grame
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Grame Centre national de création musicale
11, cours de Verdun Gensoul 69002 Lyon - France
*/
#include <QQuickItem>
#ifdef ANDROID
# include <QtAndroid>
# include <QAndroidJniObject>
#endif
#include "SensorAppl.h"
extern const char* kGreensoundsAddr;
extern const char* kButtonsAddr;
const float kVersion = 1.13f;
const char* kVersionStr = "1.13";
using namespace std;
//------------------------------------------------------------------------
OSCListener::OSCListener(SensorAppl* appl, int port)
: fSocket(IpEndpointName( IpEndpointName::ANY_ADDRESS, port ), this), fAppl(appl), fRunning(false) {}
OSCListener::~OSCListener() { fSocket.AsynchronousBreak(); }
//------------------------------------------------------------------------
void OSCListener::run()
{
fRunning = true;
try {
fSocket.Run();
}
catch (osc::Exception e) {
cerr << "osc error: " << e.what() << endl;
}
fRunning = false;
}
//------------------------------------------------------------------------
SensorAppl::~SensorAppl()
{
fSensors.send(kGreensoundsAddr, fSensors.ipstr(), "bye");
fListener.terminate();
}
#ifdef ANDROID
static void keepScreenOn(bool on)
{
QtAndroid::runOnAndroidThread([on]{
QAndroidJniObject activity = QtAndroid::androidActivity();
if (activity.isValid()) {
QAndroidJniObject window =
activity.callObjectMethod("getWindow", "()Landroid/view/Window;");
if (window.isValid()) {
const int FLAG_KEEP_SCREEN_ON = 128;
if (on) {
window.callMethod<void>("addFlags", "(I)V", FLAG_KEEP_SCREEN_ON);
} else {
window.callMethod<void>("clearFlags", "(I)V", FLAG_KEEP_SCREEN_ON);
}
}
}
// QAndroidJniEnvironment env;
// if (env->ExceptionCheck()) {
// env->ExceptionClear();
// }
});
}
#else
static void keepScreenOn(bool ) {}
#endif
//#define TESTMOTOE
//------------------------------------------------------------------------
void SensorAppl::start()
{
keepScreenOn(true);
fView.setSource(QUrl("qrc:/GSinit.qml"));
fView.rootContext()->setContextProperty("sensors", &fSensors);
fView.show();
#ifndef MACOS
bool ret = fSensors.initSensor();
if (!ret) {
fView.setSource(QUrl("qrc:/failsensor.qml"));
}
else {
// fView.setSource(QUrl("qrc:/GSinit.qml"));
// fView.rootContext()->setContextProperty("sensors", &fSensors);
// fView.show();
fTimerID = startTimer(1000);
fListener.start();
}
#else
fTimerID = startTimer(1000);
fListener.start();
#endif
connect((QObject*)fView.engine(), SIGNAL(quit()), this, SLOT(quit()));
connect((QObject*)this, SIGNAL(applicationStateChanged(Qt::ApplicationState)), this, SLOT(stateChanged(Qt::ApplicationState)));
}
//------------------------------------------------------------------------
void SensorAppl::stateChanged(Qt::ApplicationState state)
{
#ifndef MACOS
if ((state == Qt::ApplicationSuspended) || ((state == Qt::ApplicationInactive))) {
quit();
}
#endif
}
//------------------------------------------------------------------------
void SensorAppl::greensound()
{
fView.setSource(QUrl("qrc:/GSwait.qml"));
fView.rootContext()->setContextProperty("sensors", &fSensors);
fSensors.start((QObject*)fView.rootObject());
fRunning = true;
}
//------------------------------------------------------------------------
void SensorAppl::wait()
{
fWait = true;
fUISwitch = true;
fSensors.stop();
}
//------------------------------------------------------------------------
void SensorAppl::play()
{
fWait = false;
fUISwitch = true;
fSensors.start();
fSensors.pmode(false);
}
//------------------------------------------------------------------------
void SensorAppl::setButtons(int b1, int b2, int b3)
{
fButtonsState[0] = b1;
fButtonsState[1] = b2;
fButtonsState[2] = b3;
fSetButtons = true;
}
//------------------------------------------------------------------------
void SensorAppl::timerEvent(QTimerEvent*)
{
static int ntry = 1;
if (fRunning) {
if (fUISwitch) {
if (fWait)
fView.setSource(QUrl("qrc:/GSwait.qml"));
else
fView.setSource(QUrl("qrc:/greensounds.qml"));
fUISwitch = false;
}
fSensors.send(kGreensoundsAddr, fSensors.ipstr(), fWait ? "wait" : "play");
if (fSetButtons) {
QQuickItem* root = fView.rootObject();
QObject *b = root->findChild<QObject*>("b1");
if (b) b->setProperty("visible", fButtonsState[0]);
b = root->findChild<QObject*>("b2");
if (b) b->setProperty("visible", fButtonsState[1]);
b = root->findChild<QObject*>("b3");
if (b) b->setProperty("visible", fButtonsState[2]);
fSetButtons = false;
}
}
else if (fSensors.connected() ) {
if (fSensors.network()) {
greensound();
}
else
fView.setSource(QUrl("qrc:/failnetwork.qml"));
}
else if (ntry < 5) {
fSensors.hello();
ntry++;
}
else if (fSensors.skip()) {
greensound();
}
else fView.setSource(QUrl("qrc:/failnetwork.qml"));
}
//------------------------------------------------------------------------
void OSCListener::ProcessMessage( const osc::ReceivedMessage& m, const IpEndpointName& src )
{
string address(m.AddressPattern());
try {
if (address == kGreensoundsAddr) {
osc::ReceivedMessageArgumentIterator i = m.ArgumentsBegin();
while (i != m.ArgumentsEnd()) {
if (i->IsString()) {
string msg(i->AsStringUnchecked());
if (msg == "hello") {
char buff[120];
src.AddressAsString(buff);
fAppl->connect_to(buff);
}
else if (msg == "version")
fAppl->sensors()->send (kGreensoundsAddr, "version", kVersion);
else if (msg == "wait")
fAppl->wait();
else if (msg == "play")
fAppl->play();
else if (msg == "quit")
fAppl->quit();
}
else if (i->IsInt32()) {
}
else if (i->IsFloat()) {
}
i++;
}
}
else if ((address == kButtonsAddr) && (m.ArgumentCount() == 3)) {
osc::ReceivedMessageArgumentStream args = m.ArgumentStream();
osc::int32 b1, b2, b3;
args >> b1 >> b2 >> b3;
fAppl->setButtons( b1, b2, b3);
}
}
catch(std::exception e) {}
}
<|endoftext|> |
<commit_before>/*
Copyright 2014 Justin White
See included LICENSE file for details.
*/
#define _ELPP_UNICODE
#define ELPP_NO_DEFAULT_LOG_FILE
#include <easylogging++.h>
INITIALIZE_EASYLOGGINGPP
#include <Game.h>
//system data
const int version = 0;
const int revision = 1;
const int width = 1280;
const int height = 720;
const std::string name = "SpaceFight";
int main(int argc, char *argv[]) {
std::string logFilename = name;
logFilename.append(".log");
// remove existing log file, easylogging++ doesn't currently support non-append logs
unlink(logFilename.c_str());
START_EASYLOGGINGPP(argc, argv);
el::Configurations logConf;
logConf.setToDefault();
logConf.setGlobally(el::ConfigurationType::Format, "%datetime{%H:%m:%s.%g} %level %msg");
logConf.setGlobally(el::ConfigurationType::Filename, logFilename);
logConf.setGlobally(el::ConfigurationType::Enabled, "true");
logConf.setGlobally(el::ConfigurationType::ToFile, "true");
logConf.setGlobally(el::ConfigurationType::ToStandardOutput, "true");
logConf.setGlobally(el::ConfigurationType::MillisecondsWidth, "3");
logConf.set(el::Level::Debug, el::ConfigurationType::Format, "%datetime{%H:%m:%s.%g} %level %loc %func %msg");
el::Loggers::reconfigureAllLoggers(logConf);
LOG(INFO) << name << " v" << version << "." << revision;
LOG(INFO) << "Built " << __DATE__ << __TIME__;
LOG(INFO) << "GCC " << __VERSION__;
LOG(INFO) << "SFML " << SFML_VERSION_MAJOR << "." << SFML_VERSION_MINOR;
Game *game = Game::getGame();
game->init(name, width, height);
game->run();
return EXIT_SUCCESS;
}
<commit_msg>Add header for unlink()<commit_after>/*
Copyright 2014 Justin White
See included LICENSE file for details.
*/
#include <unistd.h>
#define _ELPP_UNICODE
#define ELPP_NO_DEFAULT_LOG_FILE
#include <easylogging++.h>
INITIALIZE_EASYLOGGINGPP
#include <Game.h>
//system data
const int version = 0;
const int revision = 1;
const int width = 1280;
const int height = 720;
const std::string name = "SpaceFight";
int main(int argc, char *argv[]) {
std::string logFilename = name;
logFilename.append(".log");
// remove existing log file, easylogging++ doesn't currently support non-append logs
unlink(logFilename.c_str());
START_EASYLOGGINGPP(argc, argv);
el::Configurations logConf;
logConf.setToDefault();
logConf.setGlobally(el::ConfigurationType::Format, "%datetime{%H:%m:%s.%g} %level %msg");
logConf.setGlobally(el::ConfigurationType::Filename, logFilename);
logConf.setGlobally(el::ConfigurationType::Enabled, "true");
logConf.setGlobally(el::ConfigurationType::ToFile, "true");
logConf.setGlobally(el::ConfigurationType::ToStandardOutput, "true");
logConf.setGlobally(el::ConfigurationType::MillisecondsWidth, "3");
logConf.set(el::Level::Debug, el::ConfigurationType::Format, "%datetime{%H:%m:%s.%g} %level %loc %func %msg");
el::Loggers::reconfigureAllLoggers(logConf);
LOG(INFO) << name << " v" << version << "." << revision;
LOG(INFO) << "Built " << __DATE__ << __TIME__;
LOG(INFO) << "GCC " << __VERSION__;
LOG(INFO) << "SFML " << SFML_VERSION_MAJOR << "." << SFML_VERSION_MINOR;
Game *game = Game::getGame();
game->init(name, width, height);
game->run();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <nds.h>
#include "./background.h"
#include "./debug.h"
namespace FMAW {
//------------------------------------------------------------------------------
// Background class.
//------------------------------------------------------------------------------
background_id Background::nextEmptyBackground = 0;
//----------//------------------------------------------------------------------
//----------// Position.
//----------//------------------------------------------------------------------
bool Background::setCharacterBaseBlock( uint8 characterBaseBlock ) {
if ( characterBaseBlock > 15 || characterBaseBlock < 0 ) return false;
characterBaseBlock <<= 2;
*this->reg &= 0xFFC3;
*this->reg |= characterBaseBlock;
return true;
}
uint8 Background::getCharacterBaseBlock() {
return (*this->reg & 0x003C) >> 2;
}
bool Background::setScreenBaseBlock( uint8 newScreenBaseBlock ) {
if ( newScreenBaseBlock > 31 || newScreenBaseBlock < 0 ) return false;
newScreenBaseBlock <<= 8;
*this->reg &= 0xE0FF;
*this->reg |= newScreenBaseBlock;
return true;
}
uint8 Background::getScreenBaseBlock() {
return (*this->reg & 0x1F00) >> 8;
}
void Background::enableDisplayAreaOverflow() {
*this->reg |= 0x2000;
}
void Background::disableDisplayAreaOverflow() {
*this->reg &= 0xDFFF;
}
bool Background::displayAreaOverflowEnabled() {
return (*this->reg &= 0x2000) != 0;
}
bool Background::displayAreaOverflowDisabled() {
return !this->displayAreaOverflowEnabled();
}
//----------//------------------------------------------------------------------
//----------// Tile & palette settings.
//----------//------------------------------------------------------------------
bool Background::setTile( background_tile_id tile_id, uint16 tileIndex ) {
uint16 tileIndexCapped = tileIndex & 0x01FF;
if ( tileIndex != tileIndexCapped ) return false;
tiles[tile_id] |= 0x01FF;
tiles[tile_id] &= tileIndexCapped;
return true;
}
uint16 Background::getTile( background_tile_id tile_id ) {
TO_BE_IMPLEMENTED
return 0;
}
bool Background::setPalette( background_tile_id tile_id, uint8 paletteIndex ) {
TO_BE_IMPLEMENTED
return 0;
}
uint8 Background::getPalette( background_tile_id tile_id ) {
TO_BE_IMPLEMENTED
return 0;
}
//----------//------------------------------------------------------------------
//----------// Mosaic & color settings.
//----------//------------------------------------------------------------------
void Background::enableMosaic() {
*this->reg |= 0x0040;
}
void Background::disableMosaic() {
*this->reg &= 0xFFCF;
}
bool Background::mosaicIsEnabled() {
return (*this->reg & 0x0040) != 0;
}
bool Background::mosaicIsDisabled() {
return !this->mosaicIsEnabled();
}
void Background::use16BitColors() {
*this->reg &= 0xFF7F;
}
void Background::use256BitColors() {
*this->reg |= 0x0080;
}
bool Background::isUsing16BitColors() {
return (*this->reg & 0x0080) == 0;
}
bool Background::isUsing256BitColors() {
return !this->isUsing16BitColors();
}
//----------//------------------------------------------------------------------
//----------// Shape & size settings.
//----------//------------------------------------------------------------------
void Background::setSize( BackgroundSize newSize ) {
*this->reg &= 0x3FFF;
*this->reg |= newSize;
}
BackgroundSize Background::getSize() {
uint16 halfword = *this->reg | 0x3FFF;
switch ( halfword ) {
case size32x32:
return size32x32;
case size64x32:
return size64x32;
case size32x64:
return size32x64;
case size64x64:
// Default will not be triggered
default:
return size64x64;
}
}
//----------//------------------------------------------------------------------
//----------// Flip settings.
//----------//------------------------------------------------------------------
void Background::enableHorizontalFlip( background_tile_id tile_id ) {
TO_BE_IMPLEMENTED
}
void Background::disableHorizontalFlip( background_tile_id tile_id ) {
TO_BE_IMPLEMENTED
}
bool Background::horizontalFlipIsEnabled( background_tile_id tile_id ) {
TO_BE_IMPLEMENTED
return 0;
}
bool Background::horizontalFlipIsDisabled( background_tile_id tile_id ) {
TO_BE_IMPLEMENTED
return 0;
}
void Background::enableVerticalFlip( background_tile_id tile_id ) {
TO_BE_IMPLEMENTED
}
void Background::disableVerticalFlip( background_tile_id tile_id ) {
TO_BE_IMPLEMENTED
}
bool Background::verticalFlipIsEnabled( background_tile_id tile_id ) {
TO_BE_IMPLEMENTED
return 0;
}
bool Background::verticalFlipIsDisabled( background_tile_id tile_id ) {
TO_BE_IMPLEMENTED
return 0;
}
//----------//------------------------------------------------------------------
//----------// Priority settings.
//----------//------------------------------------------------------------------
void Background::setPriority( BackgroundPriority priority ) {
*this->reg |= 0x0003;
*this->reg &= priority;
}
BackgroundPriority Background::getPriority() {
switch ( (*this->reg & 0x0003) | 0xFFFC ) {
case bpHIGHEST:
return bpHIGHEST;
case bpHIGH:
return bpHIGH;
case bpLOW:
return bpLOW;
case bpLOWEST:
// Default won't be triggered.
default:
return bpLOWEST;
}
}
//----------//------------------------------------------------------------------
//----------// Other settings.
//----------//------------------------------------------------------------------
void Background::clear() {
*this->reg = 0x0000;
}
void Background::clearAllTiles() {
for ( int n = 0; n < 1024; n++ )
this->tiles[n] = 0x0000;
}
}<commit_msg>Added tile & palette settings<commit_after>#include <nds.h>
#include "./background.h"
#include "./debug.h"
namespace FMAW {
//------------------------------------------------------------------------------
// Background class.
//------------------------------------------------------------------------------
background_id Background::nextEmptyBackground = 0;
//----------//------------------------------------------------------------------
//----------// Position.
//----------//------------------------------------------------------------------
bool Background::setCharacterBaseBlock( uint8 characterBaseBlock ) {
if ( characterBaseBlock > 15 || characterBaseBlock < 0 ) return false;
characterBaseBlock <<= 2;
*this->reg &= 0xFFC3;
*this->reg |= characterBaseBlock;
return true;
}
uint8 Background::getCharacterBaseBlock() {
return (*this->reg & 0x003C) >> 2;
}
bool Background::setScreenBaseBlock( uint8 newScreenBaseBlock ) {
if ( newScreenBaseBlock > 31 || newScreenBaseBlock < 0 ) return false;
newScreenBaseBlock <<= 8;
*this->reg &= 0xE0FF;
*this->reg |= newScreenBaseBlock;
return true;
}
uint8 Background::getScreenBaseBlock() {
return (*this->reg & 0x1F00) >> 8;
}
void Background::enableDisplayAreaOverflow() {
*this->reg |= 0x2000;
}
void Background::disableDisplayAreaOverflow() {
*this->reg &= 0xDFFF;
}
bool Background::displayAreaOverflowEnabled() {
return (*this->reg &= 0x2000) != 0;
}
bool Background::displayAreaOverflowDisabled() {
return !this->displayAreaOverflowEnabled();
}
//----------//------------------------------------------------------------------
//----------// Tile & palette settings.
//----------//------------------------------------------------------------------
bool Background::setTile( background_tile_id tile_id, uint16 tileIndex ) {
uint16 tileIndexCapped = tileIndex & 0x01FF;
if ( tileIndex != tileIndexCapped ) return false;
this->tiles[tile_id] |= 0x01FF;
this->tiles[tile_id] &= tileIndexCapped;
return true;
}
uint16 Background::getTile( background_tile_id tile_id ) {
return this->tiles[tile_id] & 0x01FF;
}
bool Background::setPalette( background_tile_id tile_id, uint8 paletteIndex ) {
uint8 paletteIndexCapped = paletteIndex & 0x000F;
if ( paletteIndex != paletteIndexCapped ) return false;
// We first set tile bits to 1 so we can apply an AND later.
this->tiles[tile_id] |= 0xF000;
// We apply and AND to set the bits properly.
this->tiles[tile_id] &= paletteIndexCapped << 12;
return true;
}
uint8 Background::getPalette( background_tile_id tile_id ) {
return (this->tiles[tile_id] & 0xF000) >> 12;
}
//----------//------------------------------------------------------------------
//----------// Mosaic & color settings.
//----------//------------------------------------------------------------------
void Background::enableMosaic() {
*this->reg |= 0x0040;
}
void Background::disableMosaic() {
*this->reg &= 0xFFCF;
}
bool Background::mosaicIsEnabled() {
return (*this->reg & 0x0040) != 0;
}
bool Background::mosaicIsDisabled() {
return !this->mosaicIsEnabled();
}
void Background::use16BitColors() {
*this->reg &= 0xFF7F;
}
void Background::use256BitColors() {
*this->reg |= 0x0080;
}
bool Background::isUsing16BitColors() {
return (*this->reg & 0x0080) == 0;
}
bool Background::isUsing256BitColors() {
return !this->isUsing16BitColors();
}
//----------//------------------------------------------------------------------
//----------// Shape & size settings.
//----------//------------------------------------------------------------------
void Background::setSize( BackgroundSize newSize ) {
*this->reg &= 0x3FFF;
*this->reg |= newSize;
}
BackgroundSize Background::getSize() {
uint16 halfword = *this->reg | 0x3FFF;
switch ( halfword ) {
case size32x32:
return size32x32;
case size64x32:
return size64x32;
case size32x64:
return size32x64;
case size64x64:
// Default will not be triggered
default:
return size64x64;
}
}
//----------//------------------------------------------------------------------
//----------// Flip settings.
//----------//------------------------------------------------------------------
void Background::enableHorizontalFlip( background_tile_id tile_id ) {
TO_BE_IMPLEMENTED
}
void Background::disableHorizontalFlip( background_tile_id tile_id ) {
TO_BE_IMPLEMENTED
}
bool Background::horizontalFlipIsEnabled( background_tile_id tile_id ) {
TO_BE_IMPLEMENTED
return 0;
}
bool Background::horizontalFlipIsDisabled( background_tile_id tile_id ) {
TO_BE_IMPLEMENTED
return 0;
}
void Background::enableVerticalFlip( background_tile_id tile_id ) {
TO_BE_IMPLEMENTED
}
void Background::disableVerticalFlip( background_tile_id tile_id ) {
TO_BE_IMPLEMENTED
}
bool Background::verticalFlipIsEnabled( background_tile_id tile_id ) {
TO_BE_IMPLEMENTED
return 0;
}
bool Background::verticalFlipIsDisabled( background_tile_id tile_id ) {
TO_BE_IMPLEMENTED
return 0;
}
//----------//------------------------------------------------------------------
//----------// Priority settings.
//----------//------------------------------------------------------------------
void Background::setPriority( BackgroundPriority priority ) {
*this->reg |= 0x0003;
*this->reg &= priority;
}
BackgroundPriority Background::getPriority() {
switch ( (*this->reg & 0x0003) | 0xFFFC ) {
case bpHIGHEST:
return bpHIGHEST;
case bpHIGH:
return bpHIGH;
case bpLOW:
return bpLOW;
case bpLOWEST:
// Default won't be triggered.
default:
return bpLOWEST;
}
}
//----------//------------------------------------------------------------------
//----------// Other settings.
//----------//------------------------------------------------------------------
void Background::clear() {
*this->reg = 0x0000;
}
void Background::clearAllTiles() {
for ( int n = 0; n < 1024; n++ )
this->tiles[n] = 0x0000;
}
}<|endoftext|> |
<commit_before>// Time echo -e "1 1\n1 2\n2 3\n3 4\n4 5" |./bacon playedin.csv
// time echo -e "1 1\n1 2" |./bacon playedin.csv
/*
Some numbers:
Max ActorID: 1971696
NRows: 17316773-1
Max MovieID: 1151758
*/
#include <iostream>
#include <ios>
#include <fstream>
#include <vector>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <list>
#include <forward_list>
#include <thread>
//#include <mutex>
#include <chrono> // should allow high precision timing
using namespace std;
//static std::mutex barrier;
// BAD CODING!!! <3
//
int *actor_keys = new int[1971696];
int *act2mov_actors = new int[1971696];
int *act2mov_movies = new int[17316773-1];
int *mov2act_movies = new int[1151758];
int *mov2act_actors = new int[17316773-1]();
// Breadth-First Search
int BFS(
int *act2mov_actors,
int *act2mov_movies,
int *mov2act_movies,
int *mov2act_actors,
int actorid2,
forward_list<int> current_nodes,
bool *actor_visited,
bool *movie_visited
) {
// If BFS is called on an empty list of nodes return -1
if(current_nodes.empty()) {
return -1;
}
// Now we want to find all neighbours of each of the current nodes
forward_list<int> neighbours;
// For all current actors
for(int i : current_nodes) {
// Get all movies
for(int j = act2mov_actors[i-1]; j < act2mov_actors[i]; j++) {
int movie = act2mov_movies[j];
// For each movie find all actors
if(!movie_visited[movie])
{
movie_visited[movie] = 1;
for(int k=mov2act_movies[movie-1]; k<mov2act_movies[movie]; k++){
int new_actor = mov2act_actors[k];
// If he has not been inspected yet add him to neighbours
if(!actor_visited[new_actor]) {
// If it is the actor2 we are looking for return 1 as distance
if(new_actor==actorid2){
return 1;
}
actor_visited[new_actor] = 1;
neighbours.push_front(new_actor);
}
}
}
}
}
// Now perform BFS on the neighbours we just found
int count = BFS(
act2mov_actors, act2mov_movies,
mov2act_movies, mov2act_actors,
actorid2, neighbours, actor_visited, movie_visited);
// If BFS returns -1 we pass that forward
if(count == -1) {
return -1;
}
// If BFS returns a distance we have to increase that distance by 1
return ++count;
}
void BFSThread(int thread_a1, int thread_a2, int *dist_thread, int i){
if(thread_a1 == thread_a2){
dist_thread[i] = 0;
return;
}
bool *actor_visited = new bool[1971696+1]();
bool *movie_visited = new bool[1151758+1]();
// Boolean to save if actor i has been visited or not
// Nodes are the ones we are visiting right now - We'll want to find their neighbours with each iteration of BFS
forward_list<int> current_nodes;
// We start with only actorid1
current_nodes.push_front(actor_keys[thread_a1]);
int dist;
// Start Breadth-First-Search
dist = BFS(
act2mov_actors, act2mov_movies,
mov2act_movies, mov2act_actors,
actor_keys[thread_a2], current_nodes, actor_visited, movie_visited);
// Write on global dist variable
// std::lock_guard<std::mutex> block_threads_until_finish_this_job(barrier);
cout << "Process: " << i << " Distance: " << dist << endl;
dist_thread[i] = dist;
// delete unsused variable
delete[] actor_visited;
delete[] movie_visited;
}
int main(int argc, char** argv) {
// proper timing of actual code execution
auto start_time = chrono::high_resolution_clock::now();
// Movie to actor map - Will be replaced later
vector<vector<int>> M(1151758+1);
// Open file and figre out length
int handle = open(argv[1],O_RDONLY);
if (handle<0) return 1;
lseek(handle,0,SEEK_END);
long length = lseek(handle,0,SEEK_CUR);
// Map file into address space
auto data = static_cast<const char*>(mmap(nullptr,length,PROT_READ,MAP_SHARED,handle,0));
auto dataLimit = data + length;
/* Read file and create our datatypes
We store the actor to movie relation in a CSR and movie to actor in a map
*/
const char* line = data;
int actor_index = -1;
int m1_current = 0;
int last_actor = 0;
for (const char* current=data;current!=dataLimit;) {
const char* last=line;
unsigned column=0;
int actor=0;
int movie=0;
for (;current!=dataLimit;++current) {
char c=*current;
if (c==',') {
last=current+1;
++column;
}else if (c=='\n') {
// Insert entry into Movie->Actor Map
// M[movie].push_back(actor);
/* Check if the actor is different to the last one
If yes increase actor_index and add entry to actor_keys */
if(actor != last_actor){
++actor_index;
actor_keys[actor] = actor_index;
}
M[movie].push_back(actor_index);
act2mov_actors[actor_index] = m1_current+1;
// Insert movie to list
act2mov_movies[m1_current] = movie;
// Update index
++m1_current;
last_actor = actor;
++current;
break;
}else if (column==0) {
actor=10*actor+c-'0';
}else if (column==1) {
movie=10*movie+c-'0';
}
}
}
cout << "File eingelesen" << endl;
// Create CSR for movie to actor relation
int iterator = 0;
for(int movie_id=1; movie_id<=1151758; movie_id++){
for(int actor : M.at(movie_id)){
mov2act_actors[iterator] = actor;
++iterator;
}
mov2act_movies[movie_id] = iterator;
}
// While there is an input: read, store, compute
int actorid1;
int actorid2;
vector<int> actor1;
vector<int> actor2;
// // switch input
// // if there is a second argument read from this file
// // if not the use std::cin
// istream * input_stream = &cin;
// ifstream f;
// if(argc > 2)
// {
// f.open(argv[2]);
// input_stream = &f;
// cout << "Read from file: " << argv[2] << endl;
// }
// while( (*input_stream >> actorid1) && (*input_stream >> actorid2) )
// {
// cout << "Input " << actorid1 << " : " << actorid2 << endl;
// actor1.push_back(actorid1);
// actor2.push_back(actorid2);
// }
while((cin >> actorid1) && (cin >> actorid2)) {
actor1.push_back(actorid1);
actor2.push_back(actorid2);
}
int inputlen = actor1.size();
int *distance = new int[inputlen];
thread *thread_arr = new thread[inputlen];
for(int time_counter = 0; time_counter<1; ++time_counter){
for(int i=0; i < inputlen; i++){
thread_arr[i] = thread(BFSThread, actor1[i], actor2[i], distance, i);
}
cout << "Threading started" << endl;
for(int i=0; i < inputlen; i++){
thread_arr[i].join();
}
}
// timing
auto end_time = chrono::high_resolution_clock::now();
auto passed_usecs = chrono::duration_cast<chrono::microseconds>(end_time - start_time);
double elapsed_u = (double) passed_usecs.count();
double elapsed = elapsed_u / (1000.0 * 1000.0);
// cout << "Passed time: " << passed_usecs.count() << " microseconds" << endl << endl;
cout << endl << "Passed time: " << elapsed << " seconds" << endl << endl;
for(int j=0; j<inputlen; j++){
cout << distance[j] << endl;
}
return 0;
}
<commit_msg>my.cpp is a fast and working version<commit_after>// Time echo -e "1 1\n1 2\n2 3\n3 4\n4 5" |./bacon playedin.csv
// time echo -e "1 1\n1 2" |./bacon playedin.csv
/*
Some numbers:
Max ActorID: 1971696
NRows: 17316773-1
Max MovieID: 1151758
*/
#include <iostream>
#include <ios>
#include <fstream>
#include <vector>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <list>
#include <forward_list>
#include <thread>
//#include <mutex>
#include <chrono> // should allow high precision timing
using namespace std;
//static std::mutex barrier;
// BAD CODING!!! <3
//
int *actor_keys = new int[1971696];
int *act2mov_actors = new int[1971696];
int *act2mov_movies = new int[17316773-1];
int *mov2act_movies = new int[1151758];
int *mov2act_actors = new int[17316773-1]();
// Breadth-First Search
int BFS(
int *act2mov_actors,
int *act2mov_movies,
int *mov2act_movies,
int *mov2act_actors,
int actorid2,
forward_list<int> current_nodes,
bool *actor_visited,
bool *movie_visited
) {
// If BFS is called on an empty list of nodes return -1
if(current_nodes.empty()) {
return -1;
}
// Now we want to find all neighbours of each of the current nodes
forward_list<int> neighbours;
// For all current actors
for(int i : current_nodes) {
// Get all movies
for(int j = act2mov_actors[i-1]; j < act2mov_actors[i]; j++) {
int movie = act2mov_movies[j];
// For each movie find all actors
if(!movie_visited[movie]){
movie_visited[movie] = 1;
for(int k=mov2act_movies[movie-1]; k<mov2act_movies[movie]; k++){
int new_actor = mov2act_actors[k];
// If he has not been inspected yet add him to neighbours
if(!actor_visited[new_actor]) {
// If it is the actor2 we are looking for return 1 as distance
if(new_actor==actorid2){
return 1;
}
actor_visited[new_actor] = 1;
neighbours.push_front(new_actor);
}
}
}
}
}
// Now perform BFS on the neighbours we just found
int count = BFS(
act2mov_actors, act2mov_movies,
mov2act_movies, mov2act_actors,
actorid2, neighbours, actor_visited, movie_visited);
// If BFS returns -1 we pass that forward
if(count == -1) {
return -1;
}
// If BFS returns a distance we have to increase that distance by 1
return ++count;
}
void BFSThread(int thread_a1, int thread_a2, int *dist_thread, int i){
if(thread_a1 == thread_a2){
dist_thread[i] = 0;
return;
}
bool *actor_visited = new bool[1971696+1]();
bool *movie_visited = new bool[1151758+1]();
// Boolean to save if actor i has been visited or not
// Nodes are the ones we are visiting right now - We'll want to find their neighbours with each iteration of BFS
forward_list<int> current_nodes;
// We start with only actorid1
current_nodes.push_front(actor_keys[thread_a1]);
int dist;
// Start Breadth-First-Search
dist = BFS(
act2mov_actors, act2mov_movies,
mov2act_movies, mov2act_actors,
actor_keys[thread_a2], current_nodes, actor_visited, movie_visited);
// Write on global dist variable
// std::lock_guard<std::mutex> block_threads_until_finish_this_job(barrier);
cout << "Process: " << i << " Distance: " << dist << endl;
dist_thread[i] = dist;
// delete unsused variable
delete[] actor_visited;
delete[] movie_visited;
}
int main(int argc, char** argv) {
// proper timing of actual code execution
auto start_time = chrono::high_resolution_clock::now();
// Movie to actor map - Will be replaced later
vector<vector<int>> M(1151758+1);
// Open file and figre out length
int handle = open(argv[1],O_RDONLY);
if (handle<0) return 1;
lseek(handle,0,SEEK_END);
long length = lseek(handle,0,SEEK_CUR);
// Map file into address space
auto data = static_cast<const char*>(mmap(nullptr,length,PROT_READ,MAP_SHARED,handle,0));
auto dataLimit = data + length;
/* Read file and create our datatypes
We store the actor to movie relation in a CSR and movie to actor in a map
*/
const char* line = data;
int actor_index = -1;
int m1_current = 0;
int last_actor = 0;
for (const char* current=data;current!=dataLimit;) {
const char* last=line;
unsigned column=0;
int actor=0;
int movie=0;
for (;current!=dataLimit;++current) {
char c=*current;
if (c==',') {
last=current+1;
++column;
}else if (c=='\n') {
// Insert entry into Movie->Actor Map
// M[movie].push_back(actor);
/* Check if the actor is different to the last one
If yes increase actor_index and add entry to actor_keys */
if(actor != last_actor){
++actor_index;
actor_keys[actor] = actor_index;
}
M[movie].push_back(actor_index);
act2mov_actors[actor_index] = m1_current+1;
// Insert movie to list
act2mov_movies[m1_current] = movie;
// Update index
++m1_current;
last_actor = actor;
++current;
break;
}else if (column==0) {
actor=10*actor+c-'0';
}else if (column==1) {
movie=10*movie+c-'0';
}
}
}
cout << "File eingelesen" << endl;
// Create CSR for movie to actor relation
int iterator = 0;
for(int movie_id=1; movie_id<=1151758; movie_id++){
for(int actor : M.at(movie_id)){
mov2act_actors[iterator] = actor;
++iterator;
}
mov2act_movies[movie_id] = iterator;
}
// While there is an input: read, store, compute
int actorid1;
int actorid2;
vector<int> actor1;
vector<int> actor2;
while((cin >> actorid1) && (cin >> actorid2)) {
actor1.push_back(actorid1);
actor2.push_back(actorid2);
}
int inputlen = actor1.size();
int *distance = new int[inputlen];
thread *thread_arr = new thread[inputlen];
for(int time_counter = 0; time_counter<1; ++time_counter){
for(int i=0; i < inputlen; i++){
thread_arr[i] = thread(BFSThread, actor1[i], actor2[i], distance, i);
}
cout << "Threading started" << endl;
for(int i=0; i < inputlen; i++){
thread_arr[i].join();
}
}
// timing
auto end_time = chrono::high_resolution_clock::now();
auto passed_usecs = chrono::duration_cast<chrono::microseconds>(end_time - start_time);
double elapsed_u = (double) passed_usecs.count();
double elapsed = elapsed_u / (1000.0 * 1000.0);
// cout << "Passed time: " << passed_usecs.count() << " microseconds" << endl << endl;
cout << endl << "Passed time: " << elapsed << " seconds" << endl << endl;
for(int j=0; j<inputlen; j++){
cout << distance[j] << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>//Copyright (c) 2019 Ultimaker B.V.
#include "Statistics.h"
#include <sstream>
#include <fstream>
#include "utils/logoutput.h"
namespace arachne
{
void Statistics::analyse(Polygons& input, std::vector<std::vector<std::vector<ExtrusionJunction>>>& polygons_per_index, std::vector<std::vector<std::vector<ExtrusionJunction>>>& polylines_per_index, VoronoiQuadrangulation* vq)
{
this->input = &input;
this->vq = vq;
this->polygons_per_index = &polygons_per_index;
this->polylines_per_index = &polylines_per_index;
generateAllSegments(polygons_per_index, polylines_per_index);
for (coord_t segment_idx = 0; segment_idx < all_segments.size(); segment_idx++)
{
Segment s = all_segments[segment_idx];
Polygons covered = s.s.toPolygons(false);
area_covered.add(covered);
Polygons extruded = s.toPolygons();
overlaps.add(extruded);
}
area_covered = area_covered.execute(ClipperLib::pftNonZero);
overfills = overlaps;
for (PolygonRef poly : area_covered)
{
PolygonRef new_poly = overfills.newPoly();
for (coord_t point_idx = poly.size() - 1; point_idx >= 0; --point_idx)
{
new_poly.add(poly[point_idx]);
}
}
double_overfills = overfills;
for (PolygonRef poly : area_covered)
{
PolygonRef new_poly = double_overfills.newPoly();
for (coord_t point_idx = poly.size() - 1; point_idx >= 0; --point_idx)
{
new_poly.add(poly[point_idx]);
}
}
overfills = overfills.execute(ClipperLib::pftPositive);
overfills = overfills.unionPolygons(overlaps.xorPolygons(area_covered));
overfills = overfills.intersection(area_covered);
overfills = overfills.offset(-5);
overfills = overfills.offset(10);
overfills = overfills.offset(-5);
double_overfills = double_overfills.execute(ClipperLib::pftPositive);
double_overfills = double_overfills.offset(-5);
double_overfills = double_overfills.offset(10);
double_overfills = double_overfills.offset(-5);
double total_overfill_area = INT2MM2(overfills.area() + double_overfills.area());
logAlways("Total overfill area: %f mm²\n", total_overfill_area);
std::vector<PolygonsPart> overfill_areas = overfills.splitIntoParts();
logAlways("Average area: %f mm² over %d parts\n", total_overfill_area / overfill_areas.size(), overfill_areas.size());
underfills = input.difference(area_covered);
underfills = underfills.offset(5);
underfills = underfills.offset(-10);
underfills = underfills.offset(5);
double total_underfill_area = INT2MM2(underfills.area());
logAlways("Total underfill area: %f mm²\n", total_underfill_area);
std::vector<PolygonsPart> underfill_areas = underfills.splitIntoParts();
logAlways("Average area: %f mm² over %d parts\n", total_underfill_area / underfill_areas.size(), underfill_areas.size());
logAlways("Total target area: %f mm²\n", INT2MM2(input.area()));
// initialize paths
for (Segment& segment : all_segments)
{
PolygonRef poly = paths.newPoly();
poly.emplace_back(segment.s.from.p);
poly.emplace_back(segment.s.to.p);
}
}
void Statistics::generateAllSegments(std::vector<std::vector<std::vector<ExtrusionJunction>>>& polygons_per_index, std::vector<std::vector<std::vector<ExtrusionJunction>>>& polylines_per_index)
{
for (std::vector<std::vector<ExtrusionJunction>>& polygons : polygons_per_index)
{
for (std::vector<ExtrusionJunction>& polygon : polygons)
{
ExtrusionJunction last = polygon.back();
for (coord_t junction_idx = 0; junction_idx < polygon.size(); junction_idx++)
{
ExtrusionJunction& junction = polygon[junction_idx];
ExtrusionSegment segment(last, junction, false);
all_segments.emplace_back(segment, false);
last = junction;
}
}
}
for (std::vector<std::vector<ExtrusionJunction>>& polylines : polylines_per_index)
{
for (std::vector<ExtrusionJunction>& polyline : polylines)
{
ExtrusionJunction last = polyline.front();
for (coord_t junction_idx = 0; junction_idx < polyline.size(); junction_idx++)
{
ExtrusionJunction& junction = polyline[junction_idx];
ExtrusionSegment segment(last, junction, false);
all_segments.emplace_back(segment, junction_idx == polyline.size() - 1);
last = junction;
}
}
}
}
void Statistics::visualize()
{
AABB aabb(*input);
if (vq)
{
std::ostringstream ss;
ss << "output/" << output_prefix << "_" << filename_base << "_after.svg";
SVG svg(ss.str(), aabb);
vq->debugOutput(svg, false, false, true);
svg.writePolygons(paths, SVG::Color::BLACK, 2);
if (false)
for (auto polys : *polylines_per_index)
{
for (auto poly : polys)
{
Point prev = poly.front().p;
for (ExtrusionJunction& j : poly)
{
svg.writeLine(prev, j.p, SVG::Color::RED, 2);
prev = j.p;
}
}
}
for (auto polylines : *polylines_per_index)
{
for (std::vector<ExtrusionJunction>& polyline : polylines)
{
svg.writePoint(polyline.front().p, false, 2, SVG::Color::GREEN);
svg.writePoint(polyline.back().p, false, 2, SVG::Color::BLUE);
}
}
}
{
std::ostringstream ss;
ss << "output/" << output_prefix << "_" << filename_base << "_toolpaths.svg";
SVG svg(ss.str(), aabb);
svg.writeAreas(*input, SVG::Color::GRAY, SVG::Color::NONE, 2);
bool alternate = true;
for (PolygonRef poly : overlaps)
{
svg.writeAreas(poly, alternate? SVG::Color::BLUE : SVG::Color::MAGENTA, SVG::Color::NONE);
alternate = !alternate;
}
svg.writePolygons(paths, SVG::Color::BLACK, 2);
}
{
std::ostringstream ss;
ss << "output/" << output_prefix << "_" << filename_base << "_widths.svg";
SVG svg(ss.str(), aabb);
// svg.writeAreas(*input, SVG::Color::GRAY, SVG::Color::NONE, 2);
coord_t max_dev = 100;
// add legend
auto to_string = [](float v)
{
std::ostringstream ss;
ss << v;
return ss.str();
};
std::vector<Segment> all_segments_plus = all_segments;
AABB aabb(*input);
ExtrusionJunction legend_btm(Point(aabb.max.X + 400 + max_dev, aabb.max.Y), 400 - max_dev, 0);
ExtrusionJunction legend_top(Point(aabb.max.X + 400 + max_dev, aabb.min.Y), 400 + max_dev, 0);
ExtrusionJunction legend_mid((legend_top.p + legend_btm.p) / 2, (legend_top.w + legend_btm.w) / 2, 0);
all_segments_plus.emplace_back(ExtrusionSegment(legend_btm, legend_top, true), true);
Point legend_text_offset(400, 0);
svg.writeText(legend_top.p + legend_text_offset, to_string(INT2MM(legend_top.w)));
svg.writeText(legend_btm.p + legend_text_offset, to_string(INT2MM(legend_btm.w)));
svg.writeText(legend_mid.p + legend_text_offset, to_string(INT2MM(legend_mid.w)));
svg.writeLine(legend_top.p, legend_top.p + legend_text_offset);
svg.writeLine(legend_btm.p, legend_btm.p + legend_text_offset);
svg.writeLine(legend_mid.p, legend_mid.p + legend_text_offset);
for (const Segment& ss : all_segments_plus)
{
for (Segment s : discretize(ss, MM2INT(0.1)))
{
coord_t avg_w = (s.s.from.w + s.s.to.w) / 2;
Point3 gray(64,128,64);
Point3 red(255,0,0);
Point3 blue(0,0,255);
Point3 clr;
float color_ratio = std::min(1.0, std::abs(avg_w - 400.0) / max_dev);
color_ratio = sqrt(color_ratio);
if (avg_w > 400)
{
clr = red * color_ratio + gray * (1.0 - color_ratio );
}
else
{
clr = blue * color_ratio + gray * (1.0 - color_ratio );
}
s.s.from.w = std::max(static_cast<double>(0), 0.75 * (s.s.from.w + (s.s.from.w - 400) * 2.0));
s.s.to.w = std::max(static_cast<double>(0), 0.75 * (s.s.to.w + (s.s.to.w - 400) * 2.0));
Polygons covered = s.toPolygons();
svg.writeAreas(covered, SVG::ColorObject(clr.x, clr.y, clr.z), SVG::Color::NONE);
}
}
// svg.writePolygons(paths, SVG::Color::BLACK, 1);
}
{
std::ostringstream ss;
ss << "output/" << output_prefix << "_" << filename_base << "_accuracy.svg";
SVG svg(ss.str(), aabb);
svg.writeAreas(*input, SVG::Color::GRAY, SVG::Color::NONE, 3);
svg.writeAreas(overfills, SVG::Color::RED, SVG::Color::NONE);
svg.writeAreas(double_overfills, SVG::Color::ORANGE, SVG::Color::NONE);
svg.writeAreas(underfills, SVG::Color::BLUE, SVG::Color::NONE);
svg.writePolygons(paths, SVG::Color::BLACK, 1);
}
{
std::ostringstream ss;
ss << "output/" << output_prefix << "_" << filename_base << "_segments.csv";
std::ofstream csv(ss.str(), std::ofstream::out | std::ofstream::trunc);
csv << "from_x; from_y; from_width; to_x; to_y; to_width\n";
for (const Segment& segment : all_segments)
csv << segment.s.from.p.X << "; " << segment.s.from.p.Y << "; " << segment.s.from.w << "; " << segment.s.to.p.X << "; " << segment.s.to.p.Y << "; " << segment.s.to.w << '\n';
csv.close();
}
}
std::vector<Statistics::Segment> Statistics::discretize(const Segment& segment, coord_t step_size)
{
ExtrusionSegment extrusion_segment = segment.s;
Point a = extrusion_segment.from.p;
Point b = extrusion_segment.to.p;
Point ab = b - a;
coord_t ab_length = vSize(ab);
coord_t step_count = std::max(static_cast<coord_t>(1), (ab_length + step_size / 2) / step_size);
std::vector<Segment> discretized;
ExtrusionJunction from = extrusion_segment.from;
for (coord_t step = 0; step < step_count; step++)
{
ExtrusionJunction mid(a + ab * (step + 1) / step_count, extrusion_segment.from.w + (extrusion_segment.to.w - extrusion_segment.from.w) * (step + 1) / step_count, extrusion_segment.from.perimeter_index);
discretized.emplace_back(ExtrusionSegment(from, mid, segment.s.is_odd), false);
from = mid;
}
discretized.back().is_full = segment.is_full;
return discretized;
}
} // namespace arachne
<commit_msg>better colors for visualization of widths<commit_after>//Copyright (c) 2019 Ultimaker B.V.
#include "Statistics.h"
#include <sstream>
#include <fstream>
#include "utils/logoutput.h"
namespace arachne
{
void Statistics::analyse(Polygons& input, std::vector<std::vector<std::vector<ExtrusionJunction>>>& polygons_per_index, std::vector<std::vector<std::vector<ExtrusionJunction>>>& polylines_per_index, VoronoiQuadrangulation* vq)
{
this->input = &input;
this->vq = vq;
this->polygons_per_index = &polygons_per_index;
this->polylines_per_index = &polylines_per_index;
generateAllSegments(polygons_per_index, polylines_per_index);
for (coord_t segment_idx = 0; segment_idx < all_segments.size(); segment_idx++)
{
Segment s = all_segments[segment_idx];
Polygons covered = s.s.toPolygons(false);
area_covered.add(covered);
Polygons extruded = s.toPolygons();
overlaps.add(extruded);
}
area_covered = area_covered.execute(ClipperLib::pftNonZero);
overfills = overlaps;
for (PolygonRef poly : area_covered)
{
PolygonRef new_poly = overfills.newPoly();
for (coord_t point_idx = poly.size() - 1; point_idx >= 0; --point_idx)
{
new_poly.add(poly[point_idx]);
}
}
double_overfills = overfills;
for (PolygonRef poly : area_covered)
{
PolygonRef new_poly = double_overfills.newPoly();
for (coord_t point_idx = poly.size() - 1; point_idx >= 0; --point_idx)
{
new_poly.add(poly[point_idx]);
}
}
overfills = overfills.execute(ClipperLib::pftPositive);
overfills = overfills.unionPolygons(overlaps.xorPolygons(area_covered));
overfills = overfills.intersection(area_covered);
overfills = overfills.offset(-5);
overfills = overfills.offset(10);
overfills = overfills.offset(-5);
double_overfills = double_overfills.execute(ClipperLib::pftPositive);
double_overfills = double_overfills.offset(-5);
double_overfills = double_overfills.offset(10);
double_overfills = double_overfills.offset(-5);
double total_overfill_area = INT2MM2(overfills.area() + double_overfills.area());
logAlways("Total overfill area: %f mm²\n", total_overfill_area);
std::vector<PolygonsPart> overfill_areas = overfills.splitIntoParts();
logAlways("Average area: %f mm² over %d parts\n", total_overfill_area / overfill_areas.size(), overfill_areas.size());
underfills = input.difference(area_covered);
underfills = underfills.offset(5);
underfills = underfills.offset(-10);
underfills = underfills.offset(5);
double total_underfill_area = INT2MM2(underfills.area());
logAlways("Total underfill area: %f mm²\n", total_underfill_area);
std::vector<PolygonsPart> underfill_areas = underfills.splitIntoParts();
logAlways("Average area: %f mm² over %d parts\n", total_underfill_area / underfill_areas.size(), underfill_areas.size());
logAlways("Total target area: %f mm²\n", INT2MM2(input.area()));
// initialize paths
for (Segment& segment : all_segments)
{
PolygonRef poly = paths.newPoly();
poly.emplace_back(segment.s.from.p);
poly.emplace_back(segment.s.to.p);
}
}
void Statistics::generateAllSegments(std::vector<std::vector<std::vector<ExtrusionJunction>>>& polygons_per_index, std::vector<std::vector<std::vector<ExtrusionJunction>>>& polylines_per_index)
{
for (std::vector<std::vector<ExtrusionJunction>>& polygons : polygons_per_index)
{
for (std::vector<ExtrusionJunction>& polygon : polygons)
{
ExtrusionJunction last = polygon.back();
for (coord_t junction_idx = 0; junction_idx < polygon.size(); junction_idx++)
{
ExtrusionJunction& junction = polygon[junction_idx];
ExtrusionSegment segment(last, junction, false);
all_segments.emplace_back(segment, false);
last = junction;
}
}
}
for (std::vector<std::vector<ExtrusionJunction>>& polylines : polylines_per_index)
{
for (std::vector<ExtrusionJunction>& polyline : polylines)
{
ExtrusionJunction last = polyline.front();
for (coord_t junction_idx = 0; junction_idx < polyline.size(); junction_idx++)
{
ExtrusionJunction& junction = polyline[junction_idx];
ExtrusionSegment segment(last, junction, false);
all_segments.emplace_back(segment, junction_idx == polyline.size() - 1);
last = junction;
}
}
}
}
void Statistics::visualize()
{
AABB aabb(*input);
if (vq)
{
std::ostringstream ss;
ss << "output/" << output_prefix << "_" << filename_base << "_after.svg";
SVG svg(ss.str(), aabb);
vq->debugOutput(svg, false, false, true);
svg.writePolygons(paths, SVG::Color::BLACK, 2);
if (false)
for (auto polys : *polylines_per_index)
{
for (auto poly : polys)
{
Point prev = poly.front().p;
for (ExtrusionJunction& j : poly)
{
svg.writeLine(prev, j.p, SVG::Color::RED, 2);
prev = j.p;
}
}
}
for (auto polylines : *polylines_per_index)
{
for (std::vector<ExtrusionJunction>& polyline : polylines)
{
svg.writePoint(polyline.front().p, false, 2, SVG::Color::GREEN);
svg.writePoint(polyline.back().p, false, 2, SVG::Color::BLUE);
}
}
}
{
std::ostringstream ss;
ss << "output/" << output_prefix << "_" << filename_base << "_toolpaths.svg";
SVG svg(ss.str(), aabb);
svg.writeAreas(*input, SVG::Color::GRAY, SVG::Color::NONE, 2);
bool alternate = true;
for (PolygonRef poly : overlaps)
{
svg.writeAreas(poly, alternate? SVG::Color::BLUE : SVG::Color::MAGENTA, SVG::Color::NONE);
alternate = !alternate;
}
svg.writePolygons(paths, SVG::Color::BLACK, 2);
}
{
std::ostringstream ss;
ss << "output/" << output_prefix << "_" << filename_base << "_widths.svg";
SVG svg(ss.str(), aabb);
// svg.writeAreas(*input, SVG::Color::GRAY, SVG::Color::NONE, 2);
coord_t max_dev = 100;
// add legend
auto to_string = [](float v)
{
std::ostringstream ss;
ss << v;
return ss.str();
};
std::vector<Segment> all_segments_plus = all_segments;
AABB aabb(*input);
ExtrusionJunction legend_btm(Point(aabb.max.X + 400 + max_dev, aabb.max.Y), 400 - max_dev, 0);
ExtrusionJunction legend_top(Point(aabb.max.X + 400 + max_dev, aabb.min.Y), 400 + max_dev, 0);
ExtrusionJunction legend_mid((legend_top.p + legend_btm.p) / 2, (legend_top.w + legend_btm.w) / 2, 0);
all_segments_plus.emplace_back(ExtrusionSegment(legend_btm, legend_top, true), true);
Point legend_text_offset(400, 0);
svg.writeText(legend_top.p + legend_text_offset, to_string(INT2MM(legend_top.w)));
svg.writeText(legend_btm.p + legend_text_offset, to_string(INT2MM(legend_btm.w)));
svg.writeText(legend_mid.p + legend_text_offset, to_string(INT2MM(legend_mid.w)));
svg.writeLine(legend_top.p, legend_top.p + legend_text_offset);
svg.writeLine(legend_btm.p, legend_btm.p + legend_text_offset);
svg.writeLine(legend_mid.p, legend_mid.p + legend_text_offset);
Point3 green(0,255,0);
Point3 red(255,0,0);
Point3 blue(0,0,255);
for (const Segment& ss : all_segments_plus)
{
for (Segment s : discretize(ss, MM2INT(0.1)))
{
coord_t avg_w = (s.s.from.w + s.s.to.w) / 2;
Point3 clr;
float color_ratio = std::min(1.0, std::abs(avg_w - 400.0) / max_dev);
// color_ratio = sqrt(color_ratio);
if (avg_w > 400)
{
clr = red * color_ratio + green * (1.0 - color_ratio );
}
else
{
clr = blue * color_ratio + green * (1.0 - color_ratio );
}
coord_t clr_max = std::max(clr.x, std::max(clr.y, clr.z));
clr = clr * 255 / clr_max;
clr.y = clr.y * (255 - 92 * clr.dot(green) / green.vSize() / 255) / 255;
s.s.from.w = std::max(static_cast<double>(30), 0.75 * (s.s.from.w + (s.s.from.w - 400) * 2.0));
s.s.to.w = std::max(static_cast<double>(30), 0.75 * (s.s.to.w + (s.s.to.w - 400) * 2.0));
Polygons covered = s.toPolygons();
svg.writeAreas(covered, SVG::ColorObject(clr.x, clr.y, clr.z), SVG::Color::NONE);
}
}
// svg.writePolygons(paths, SVG::Color::BLACK, 1);
}
{
std::ostringstream ss;
ss << "output/" << output_prefix << "_" << filename_base << "_accuracy.svg";
SVG svg(ss.str(), aabb);
svg.writeAreas(*input, SVG::Color::GRAY, SVG::Color::NONE, 3);
svg.writeAreas(overfills, SVG::Color::RED, SVG::Color::NONE);
svg.writeAreas(double_overfills, SVG::Color::ORANGE, SVG::Color::NONE);
svg.writeAreas(underfills, SVG::Color::BLUE, SVG::Color::NONE);
svg.writePolygons(paths, SVG::Color::BLACK, 1);
}
{
std::ostringstream ss;
ss << "output/" << output_prefix << "_" << filename_base << "_segments.csv";
std::ofstream csv(ss.str(), std::ofstream::out | std::ofstream::trunc);
csv << "from_x; from_y; from_width; to_x; to_y; to_width\n";
for (const Segment& segment : all_segments)
csv << segment.s.from.p.X << "; " << segment.s.from.p.Y << "; " << segment.s.from.w << "; " << segment.s.to.p.X << "; " << segment.s.to.p.Y << "; " << segment.s.to.w << '\n';
csv.close();
}
}
std::vector<Statistics::Segment> Statistics::discretize(const Segment& segment, coord_t step_size)
{
ExtrusionSegment extrusion_segment = segment.s;
Point a = extrusion_segment.from.p;
Point b = extrusion_segment.to.p;
Point ab = b - a;
coord_t ab_length = vSize(ab);
coord_t step_count = std::max(static_cast<coord_t>(1), (ab_length + step_size / 2) / step_size);
std::vector<Segment> discretized;
ExtrusionJunction from = extrusion_segment.from;
for (coord_t step = 0; step < step_count; step++)
{
ExtrusionJunction mid(a + ab * (step + 1) / step_count, extrusion_segment.from.w + (extrusion_segment.to.w - extrusion_segment.from.w) * (step + 1) / step_count, extrusion_segment.from.perimeter_index);
discretized.emplace_back(ExtrusionSegment(from, mid, segment.s.is_odd), false);
from = mid;
}
discretized.back().is_full = segment.is_full;
return discretized;
}
} // namespace arachne
<|endoftext|> |
<commit_before>#include "TGATexture.h"
#include <fstream>
#include <vector>
#include <algorithm>
// all possible image types
// described in TGA format specification
enum class tga_image_type : uint8_t
{
none = 0, // no image data
colormap = 1, // uncompressed, colormap
bgr = 2, // uncompressed, bgr
mono = 3, // uncompressed, black-white image
colormap_rle = 9, // compressed, colormap
bgr_rle = 10, // compressed, bgr
mono_rle = 11 // compressed, black-white image
};
TGATexture::TGATexture()
:_texture(), _textureView()
{
memset(&_textureInfo, 0, sizeof(_textureInfo));
}
void TGATexture::load(const std::string& filename, ID3D11Device* device)
{
// in case if texture exists
// we need to release all resources
_texture.reset();
_textureView.reset();
std::ifstream stream(filename, std::ios_base::beg | std::ios_base::binary);
stream.exceptions(std::ios_base::failbit | std::ios_base::badbit | std::ios_base::eofbit);
// reading tga image header
struct
{
uint8_t data1[2];
tga_image_type tga_type;
uint8_t data2[5];
// 0,0 point for origin x,y
// is bottom left
uint16_t x_origin;
uint16_t y_origin;
uint16_t width;
uint16_t height;
uint8_t bpp;
uint8_t data3;
} img_header;
stream.read(reinterpret_cast<char*>(&img_header), sizeof(img_header));
if ((img_header.bpp != sizeof(uint32_t) * 8) || // image should be 32 bpp
(img_header.tga_type != tga_image_type::bgr)) // image shouldn't be compressed with RLE
{
stream.setstate(std::ios_base::failbit);
}
_textureInfo.width = img_header.width;
_textureInfo.height = img_header.height;
_textureInfo.bpp = img_header.bpp;
size_t imgSize = img_header.height * img_header.width;
std::vector<uint32_t> tmpData(imgSize);
tmpData.shrink_to_fit();
stream.read(reinterpret_cast<char*>(tmpData.data()), imgSize * sizeof(uint32_t));
stream.close();
// origin point is left-bottom
if (img_header.y_origin == 0)
{
for(auto fIter = tmpData.begin(), lIter = tmpData.end() - img_header.width;
fIter < lIter;
fIter += img_header.width, lIter -= img_header.width)
{
std::swap_ranges(fIter, fIter + img_header.width, lIter);
}
}
for(auto iter = tmpData.begin(); iter != tmpData.end(); ++iter)
{
uint8_t* bgra = reinterpret_cast<uint8_t*>(&(*iter));
// swap b and r components to get rgba from bgra
std::swap(bgra[0], bgra[2]);
}
D3D11_TEXTURE2D_DESC textureDesc;
textureDesc.ArraySize = 1;
textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
textureDesc.CPUAccessFlags = 0;
textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
textureDesc.Height = img_header.height;
textureDesc.MipLevels = 1;
textureDesc.MiscFlags = 0;
textureDesc.SampleDesc.Count = 1;
textureDesc.SampleDesc.Quality = 0;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.Width = img_header.width;
D3D11_SUBRESOURCE_DATA subData;
subData.pSysMem = tmpData.data();
subData.SysMemPitch = img_header.width * sizeof(uint32_t);
subData.SysMemSlicePitch = 0;
HRESULT hr = device->CreateTexture2D(&textureDesc, &subData, _texture.getpp());
D3D11_SHADER_RESOURCE_VIEW_DESC textureViewDesc;
memset(&textureViewDesc, 0, sizeof(textureViewDesc));
textureViewDesc.Format = textureDesc.Format;
textureViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
textureViewDesc.Texture2D.MipLevels = 1;
textureViewDesc.Texture2D.MostDetailedMip = 0;
hr = device->CreateShaderResourceView(_texture.getp(), &textureViewDesc, _textureView.getpp());
}<commit_msg>Targa RLE is now supported<commit_after>#include "TGATexture.h"
#include <fstream>
#include <vector>
#include <algorithm>
// all possible image types
// described in TGA format specification
enum class tga_image_type : uint8_t
{
none = 0, // no image data
colormap = 1, // uncompressed, colormap
bgr = 2, // uncompressed, bgr
mono = 3, // uncompressed, black-white image
colormap_rle = 9, // compressed, colormap
bgr_rle = 10, // compressed, bgr
mono_rle = 11 // compressed, black-white image
};
namespace ifstream_helpers
{
template<typename T>
inline void read(std::ifstream& stream, T* data, const size_t& count = 1)
{
stream.read(reinterpret_cast<char*>(data), sizeof(T) * count);
}
template<typename T>
inline void read(std::ifstream& stream, T& data, const size_t& count = 1)
{
stream.read(reinterpret_cast<char*>(&data), sizeof(T) * count);
}
}
// TGATexture class
TGATexture::TGATexture()
:_texture(), _textureView()
{
memset(&_textureInfo, 0, sizeof(_textureInfo));
}
void TGATexture::load(const std::string& filename, ID3D11Device* device)
{
// in case if texture exists
// we need to release all resources
_texture.reset();
_textureView.reset();
std::ifstream stream(filename, std::ios_base::beg | std::ios_base::binary);
stream.exceptions(std::ios_base::failbit | std::ios_base::badbit | std::ios_base::eofbit);
// reading tga image header
struct
{
uint8_t data1[2];
tga_image_type tga_type;
uint8_t data2[5];
// 0,0 point for origin x,y
// is bottom left
uint16_t x_origin;
uint16_t y_origin;
uint16_t width;
uint16_t height;
uint8_t bpp;
uint8_t data3;
} img_header;
ifstream_helpers::read(stream, img_header);
if (img_header.bpp != sizeof(uint32_t) * 8) // image should be 32 bpp
{
stream.setstate(std::ios_base::failbit);
}
_textureInfo.width = img_header.width;
_textureInfo.height = img_header.height;
_textureInfo.bpp = img_header.bpp;
size_t imgSize = img_header.height * img_header.width;
std::vector<uint32_t> tmpData(imgSize);
tmpData.shrink_to_fit();
if (img_header.tga_type == tga_image_type::bgr)
{
ifstream_helpers::read(stream, tmpData.data(), imgSize * sizeof(uint32_t));
}
else if (img_header.tga_type == tga_image_type::bgr_rle)
{
size_t loadedCount = 0;
uint8_t tmpByte;
while(loadedCount < tmpData.size())
{
ifstream_helpers::read(stream, tmpByte);
size_t pointCount = (tmpByte & ~0x80) + 1;
if (tmpByte & 0x80) // RLE packet
{
uint32_t tmpPacket;
ifstream_helpers::read(stream, tmpPacket);
std::fill_n(tmpData.begin() + loadedCount, pointCount, tmpPacket);
}
else // RAW packet
{
for(size_t i = 0; i < pointCount; ++i)
{
ifstream_helpers::read(stream, tmpData[loadedCount + i]);
}
}
loadedCount += pointCount;
}
}
else // unsupported format
{
stream.setstate(std::ios_base::failbit);
}
stream.close();
// origin point is left-bottom
if (img_header.y_origin == 0)
{
for(auto fIter = tmpData.begin(), lIter = tmpData.end() - img_header.width;
fIter < lIter;
fIter += img_header.width, lIter -= img_header.width)
{
std::swap_ranges(fIter, fIter + img_header.width, lIter);
}
}
for(auto iter = tmpData.begin(); iter != tmpData.end(); ++iter)
{
uint8_t* bgra = reinterpret_cast<uint8_t*>(&(*iter));
// swap b and r components to get rgba from bgra
std::swap(bgra[0], bgra[2]);
}
D3D11_TEXTURE2D_DESC textureDesc;
textureDesc.ArraySize = 1;
textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
textureDesc.CPUAccessFlags = 0;
textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
textureDesc.Height = img_header.height;
textureDesc.MipLevels = 1;
textureDesc.MiscFlags = 0;
textureDesc.SampleDesc.Count = 1;
textureDesc.SampleDesc.Quality = 0;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.Width = img_header.width;
D3D11_SUBRESOURCE_DATA subData;
subData.pSysMem = tmpData.data();
subData.SysMemPitch = img_header.width * sizeof(uint32_t);
subData.SysMemSlicePitch = 0;
HRESULT hr = device->CreateTexture2D(&textureDesc, &subData, _texture.getpp());
D3D11_SHADER_RESOURCE_VIEW_DESC textureViewDesc;
memset(&textureViewDesc, 0, sizeof(textureViewDesc));
textureViewDesc.Format = textureDesc.Format;
textureViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
textureViewDesc.Texture2D.MipLevels = 1;
textureViewDesc.Texture2D.MostDetailedMip = 0;
hr = device->CreateShaderResourceView(_texture.getp(), &textureViewDesc, _textureView.getpp());
}<|endoftext|> |
<commit_before>//Copyright (c) 2017 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "infill.h"
#include "LayerPlan.h"
#include "TopSurface.h"
namespace cura
{
TopSurface::TopSurface()
{
//Do nothing. Areas stays empty.
}
TopSurface::TopSurface(SliceMeshStorage& mesh, size_t layer_number, size_t part_number)
{
//The top surface is all parts of the mesh where there's no mesh above it, so find the layer above it first.
Polygons mesh_above;
if (layer_number < mesh.layers.size() - 1)
{
mesh_above = mesh.layers[layer_number].parts[part_number].print_outline;
} //If this is the top-most layer, mesh_above stays empty.
Polygons mesh_this = mesh.layers[layer_number].getOutlines();
areas = mesh_this.difference(mesh_above);
}
bool TopSurface::sand(const SettingsBaseVirtual* settings, const GCodePathConfig& line_config, LayerPlan& layer)
{
if (areas.empty())
{
return false; //Nothing to do.
}
Polygons sanding_areas = areas.offset(-settings->getSettingInMicrons("sanding_inset"));
if (sanding_areas.empty())
{
return false; //Now there's nothing to do.
}
//Generate the lines to cover the surface.
EFillMethod pattern = settings->getSettingAsFillMethod("sanding_pattern");
coord_t line_spacing = settings->getSettingInMicrons("sanding_line_spacing");
Infill infill_generator(pattern, sanding_areas, 0, 0, line_spacing, 0, 45.0, layer.z - 10, 0);
Polygons sand_polygons;
Polygons sand_lines;
infill_generator.generate(sand_polygons, sand_lines);
//Add the lines as travel moves to the layer plan.
bool added = false;
float sanding_flow = settings->getSettingAsRatio("sanding_flow");
if (!sand_polygons.empty())
{
layer.addPolygonsByOptimizer(sand_polygons, &line_config, nullptr, EZSeamType::SHORTEST, Point(0, 0), 0, false, sanding_flow);
added = true;
}
if (!sand_lines.empty())
{
layer.addLinesByOptimizer(sand_lines, &line_config, SpaceFillType::PolyLines, 0, sanding_flow);
added = true;
}
return added;
}
}<commit_msg>Use named parameters for infill constructor<commit_after>//Copyright (c) 2017 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "infill.h"
#include "LayerPlan.h"
#include "TopSurface.h"
namespace cura
{
TopSurface::TopSurface()
{
//Do nothing. Areas stays empty.
}
TopSurface::TopSurface(SliceMeshStorage& mesh, size_t layer_number, size_t part_number)
{
//The top surface is all parts of the mesh where there's no mesh above it, so find the layer above it first.
Polygons mesh_above;
if (layer_number < mesh.layers.size() - 1)
{
mesh_above = mesh.layers[layer_number].parts[part_number].print_outline;
} //If this is the top-most layer, mesh_above stays empty.
Polygons mesh_this = mesh.layers[layer_number].getOutlines();
areas = mesh_this.difference(mesh_above);
}
bool TopSurface::sand(const SettingsBaseVirtual* settings, const GCodePathConfig& line_config, LayerPlan& layer)
{
if (areas.empty())
{
return false; //Nothing to do.
}
Polygons sanding_areas = areas.offset(-settings->getSettingInMicrons("sanding_inset"));
if (sanding_areas.empty())
{
return false; //Now there's nothing to do.
}
//Generate the lines to cover the surface.
const EFillMethod pattern = settings->getSettingAsFillMethod("sanding_pattern");
const coord_t line_spacing = settings->getSettingInMicrons("sanding_line_spacing");
const coord_t outline_offset = 0;
const coord_t line_width = line_config.getLineWidth();
constexpr coord_t infill_overlap = 0;
constexpr double angle = 45.0;
constexpr coord_t shift = 0;
Infill infill_generator(pattern, areas, outline_offset, line_width, line_spacing, infill_overlap, angle, layer.z - 10, shift);
Polygons sand_polygons;
Polygons sand_lines;
infill_generator.generate(sand_polygons, sand_lines);
//Add the lines as travel moves to the layer plan.
bool added = false;
float sanding_flow = settings->getSettingAsRatio("sanding_flow");
if (!sand_polygons.empty())
{
layer.addPolygonsByOptimizer(sand_polygons, &line_config, nullptr, EZSeamType::SHORTEST, Point(0, 0), 0, false, sanding_flow);
added = true;
}
if (!sand_lines.empty())
{
layer.addLinesByOptimizer(sand_lines, &line_config, SpaceFillType::PolyLines, 0, sanding_flow);
added = true;
}
return added;
}
}<|endoftext|> |
<commit_before>#include "UserKernel.h"
extern "C" {
#include "lua.h"
#include "utils.h"
#include "luaT.h"
}
#include "EasyCL.h"
#include "THClKernels.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
static std::string getTensorInfoClSrc();
enum ClKernelDirection {
input,
output,
inout
};
class ClKernel;
class ClKernelArg {
public:
ClKernelDirection direction;
string name;
ClKernelArg(ClKernelDirection direction, string name) :
direction(direction),
name(name) {
}
virtual std::string asParameterString() const = 0;
virtual void writeToKernel(lua_State *L, ClKernel *clKernel,THClKernels *k) = 0;
virtual ~ClKernelArg() {
}
virtual std::string toString() const {
return "ClKernelArg{name=" + name + "}";
}
};
class ClKernelArgInt : public ClKernelArg {
public:
ClKernelArgInt(ClKernelDirection direction, string name) :
ClKernelArg(direction, name) {
if(direction != input) {
THError("ints can only be input parameters, not output, or inout");
}
}
virtual std::string asParameterString() const {
return "int " + name;
}
virtual void writeToKernel(lua_State *L, ClKernel *clKernel,THClKernels *k) {
luaT_getfieldchecknumber(L, -1, name.c_str());
int value = lua_tonumber(L, -1);
lua_pop(L, 1);
switch(direction) {
case input:
k->in(value);
break;
default:
THError("ints can only be input parameters, not output, or inout");
}
}
virtual std::string toString() const {
return "ClKernelArgInt{name=" + name + "}";
}
};
class ClKernelArgTensor : public ClKernelArg {
public:
ClKernelArgTensor(ClKernelDirection direction, string name) :
ClKernelArg(direction, name) {
}
virtual std::string asParameterString() const {
string res = "";
res += "global struct THClTensorInfoCl *" + name + "_info, ";
res += "global float * " + name + "_data";
return res;
}
virtual void writeToKernel(lua_State *L, ClKernel *clKernel,THClKernels *k) {
luaT_getfieldcheckudata(L, -1, name.c_str(), "torch.ClTensor");
THClTensor *value = (THClTensor *)luaT_checkudata(L, -1, "torch.ClTensor");
if(value == 0) {
THError("Tensor is null. this is odd actually, raise an issue");
}
if(value->storage == 0) {
if(direction != output){
THError("Output tensor has no data");
return;
} else {
// I guess we should resize here, somehow, in the future
THError("resize not implemented yet. It should be. Please remind me to add this, eg raise an issue");
return;
}
}
if(value->storage->wrapper == 0) {
THError("resize not implemented yet. It should be. Please remind me to add this, eg raise an issue");
return;
}
cout << "tensor value numElements " << value->storage->wrapper->size() << endl;
switch(direction) {
case input:
if(!value->storage->wrapper->isOnDevice()) {
value->storage->wrapper->copyToDevice();
}
k->inv2(value);
break;
case output:
if(!value->storage->wrapper->isOnDevice()) {
value->storage->wrapper->createOnDevice();
}
k->outv2(value);
break;
case inout:
if(!value->storage->wrapper->isOnDevice()) {
value->storage->wrapper->copyToDevice();
}
k->inoutv2(value);
break;
}
lua_pop(L, 1);
}
virtual std::string toString() const {
return "ClKernelArgTensor{name=" + name + "}";
}
};
class ClKernelArgFloat : public ClKernelArg {
public:
ClKernelArgFloat(ClKernelDirection direction, string name) :
ClKernelArg(direction, name) {
if(direction != input) {
THError("floats can only be input parameters, not output, or inout");
}
}
virtual std::string asParameterString() const {
return "float " + name;
}
virtual void writeToKernel(lua_State *L, ClKernel *clKernel,THClKernels *k) {
luaT_getfieldchecknumber(L, -1, name.c_str());
float value = lua_tonumber(L, -1);
lua_pop(L, 1);
cout << "float value: " << value << endl;
switch(direction) {
case input:
k->in(value);
break;
default:
THError("ints can only be input parameters, not output, or inout");
}
}
virtual std::string toString() const {
return "ClKernelArgFloat{name=" + name + "}";
}
};
int getNumElementsFromTensorArg(lua_State *L, ClKernelArgTensor *arg) {
THClState *state = cltorch_getstate(L);
luaT_getfieldcheckudata(L, -1, arg->name.c_str(), "torch.ClTensor");
THClTensor *tensor = (THClTensor *)luaT_checkudata(L, -1, "torch.ClTensor");
return THClTensor_nElement(state, tensor);
}
class ClKernel {
public:
int refCount;
string source;
string extraSource;
string kernelName;
string generatedSource;
CLKernel *kernel;
vector< ClKernelArg * >args;
ClKernel() {
kernel = 0;
kernelName = "user_kernel";
extraSource = "";
}
~ClKernel() {
for(int i = 0; i < (int)args.size(); i++) {
delete args[i];
}
args.clear();
}
};
static void ClKernel_rawInit(ClKernel *self) {
self->refCount = 1;
self->source = "";
}
static void printStack(string name, lua_State *L) {
int top = lua_gettop(L);
cout << name << " top: " << top << endl;
for(int i = 1; i <= top; i++ ) {
cout << " stack[" << i << "] type=" << lua_typename(L, lua_type(L, i)) << " " << lua_type(L, i) << endl;
}
}
static void loadParameters(lua_State *L, ClKernelDirection direction, ClKernel *self) {
// assume that stack top is a table iwth the parameters
// each parameter comprises name as key, and type as string value
// valid typenames: int, float, torch.ClTensor, maybe ClTensor as shorthand
// iterate this table...
lua_pushnil(L);
int argIndex = (int)self->args.size();
while(lua_next(L, -2) != 0) {
string name = lua_tostring(L, -2);
string paramType = lua_tostring(L, -1);
if(paramType == "float") {
ClKernelArg *arg = new ClKernelArgFloat(direction, name);
self->args.push_back(arg);
} else if(paramType == "int") {
ClKernelArg *arg = new ClKernelArgInt(direction, name);
self->args.push_back(arg);
} else if(paramType == "torch.ClTensor" || paramType == "ClTensor") {
ClKernelArg *arg = new ClKernelArgTensor(direction, name);
self->args.push_back(arg);
} else {
THError("Unrecognized typename %s", paramType.c_str());
}
lua_pop(L, 1);
}
}
static int ClKernel_new(lua_State *L) {
ClKernel *self = (ClKernel*)THAlloc(sizeof(ClKernel));
self = new(self) ClKernel();
ClKernel_rawInit(self);
if(lua_type(L, 1) == LUA_TTABLE) {
lua_pushnil(L);
while(lua_next(L, -2) != 0) {
string key = lua_tostring(L, -2);
if(key == "input") {
loadParameters(L, ClKernelDirection::input, self);
} else if( key == "output") {
loadParameters(L, ClKernelDirection::output, self);
} else if( key == "inout") {
loadParameters(L, ClKernelDirection::inout, self);
} else if( key == "name") {
self->kernelName = lua_tostring(L, -1); // probably should use luaT for this
} else if( key == "src") {
self->source = lua_tostring(L, -1);
} else if( key == "funcs") {
self->extraSource = lua_tostring(L, -1);
} else {
THError("Parameter %s not recognized", key.c_str());
}
lua_pop(L, 1);
}
if(self->source == "") {
THError("Missing parameter src, or was empty");
}
THClState *state = cltorch_getstate(L);
EasyCL *cl = THClState_getClv2(state, state->currentDevice);
string kernelName = "user_kernel"; // can override by param, in future
string generatedSource = "";
generatedSource += easycl::replaceGlobal(getTensorInfoClSrc(), "{{MAX_CLTORCH_DIMS}}", easycl::toString(MAX_CLTORCH_DIMS)) + "\n";
generatedSource += self->extraSource + "\n";
generatedSource += "kernel void " + kernelName + "(\n";
for(int i = 0; i < (int)self->args.size(); i++) {
if(i > 0) {
generatedSource += ",\n";
}
generatedSource += " " + self->args[i]->asParameterString();
}
generatedSource += "\n) {\n"; // probalby should use ostringstream for this really, for speed
generatedSource += self->source + "\n";
generatedSource += "}\n";
self->generatedSource = generatedSource;
self->kernelName = kernelName;
self->kernel = cl->buildKernelFromString(generatedSource, kernelName, "", "user_kernel");
} else {
THError("First parameter to torch.ClKernel should be a table");
}
luaT_pushudata(L, self, "torch.ClKernel");
return 1;
}
static int ClKernel_free(lua_State *L) {
ClKernel *self = (ClKernel*)THAlloc(sizeof(ClKernel));
if(!self) {
return 0;
}
if(THAtomicDecrementRef(&self->refCount))
{
delete self->kernel;
self->~ClKernel();
THFree(self);
}
return 0;
}
static int ClKernel_factory(lua_State *L) {
THError("ClKernel_factory not implemented");
return 0;
}
static int ClKernel_print(lua_State *L) {
ClKernel *self = (ClKernel *)luaT_checkudata(L, 1, "torch.ClKernel");
cout << "source=" << self->source << endl;
return 0;
}
static int ClKernel_run(lua_State *L) {
THClState *state = cltorch_getstate(L);
if(lua_type(L, 2) != LUA_TTABLE) {
THError("run method expects one parameter: a table, with named arg values in");
return 0;
}
// now we can assume we have a table :-)
ClKernel *self = (ClKernel *)luaT_checkudata(L, 1, "torch.ClKernel");
try {
THClKernels k(state, self->kernel);
int numElements = -1;
for(int i = 0; i < (int)self->args.size(); i++) {
// what we need to do here is:
// - loop through each parameter object
// - for each parameter object, get the value from the passed in parameters, which
// were hopefully passed into this method, as values in a table
// - and then write this value to the kernel
// presumably, we can get each arg to extract itself from the table, as long as
// the table is top of the stack
// we can ignore extra values in the table for now
// what we do is, throw error on missing values
self->args[i]->writeToKernel(L, self, &k);
if(numElements == -1 && self->args[i]->direction != input && dynamic_cast< ClKernelArgTensor *>( self->args[i] ) != 0) {
numElements = getNumElementsFromTensorArg(L, dynamic_cast< ClKernelArgTensor *>(self->args[i]));
}
}
if(numElements == -1) {
THError("Must provide at least one output, or inout, ClTensor");
}
int workgroupSize = 64; // should make this an option
int numWorkgroups = (numElements + workgroupSize - 1) / workgroupSize;
int globalSize = workgroupSize * numWorkgroups;
self->kernel->run_1d(globalSize, workgroupSize);
} catch(runtime_error &e) {
THError("Error: %s", e.what());
}
return 0;
}
static const struct luaL_Reg ClKernel_funcs [] = {
{"print", ClKernel_print},
{"run", ClKernel_run},
{0,0}
};
void cltorch_UserKernel_init(lua_State *L)
{
luaT_newmetatable(L, "torch.ClKernel", NULL,
ClKernel_new, ClKernel_free, ClKernel_factory);
luaL_setfuncs(L, ClKernel_funcs, 0);
lua_pop(L, 1);
}
static std::string getTensorInfoClSrc() {
// [[[cog
// import stringify
// stringify.write_kernel( "kernel", "src/lib/THClTensorInfoCl.cl" )
// ]]]
// generated using cog, from src/lib/THClTensorInfoCl.cl:
const char * kernelSource =
"typedef struct THClTensorInfoCl {\n"
" unsigned int sizes[{{MAX_CLTORCH_DIMS}}];\n"
" unsigned int strides[{{MAX_CLTORCH_DIMS}}];\n"
" int offset;\n"
" int dims;\n"
"} TensorInfoCl;\n"
"\n"
"";
// [[[end]]]
return kernelSource;
}
<commit_msg>remove more spam<commit_after>#include "UserKernel.h"
extern "C" {
#include "lua.h"
#include "utils.h"
#include "luaT.h"
}
#include "EasyCL.h"
#include "THClKernels.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
static std::string getTensorInfoClSrc();
enum ClKernelDirection {
input,
output,
inout
};
class ClKernel;
class ClKernelArg {
public:
ClKernelDirection direction;
string name;
ClKernelArg(ClKernelDirection direction, string name) :
direction(direction),
name(name) {
}
virtual std::string asParameterString() const = 0;
virtual void writeToKernel(lua_State *L, ClKernel *clKernel,THClKernels *k) = 0;
virtual ~ClKernelArg() {
}
virtual std::string toString() const {
return "ClKernelArg{name=" + name + "}";
}
};
class ClKernelArgInt : public ClKernelArg {
public:
ClKernelArgInt(ClKernelDirection direction, string name) :
ClKernelArg(direction, name) {
if(direction != input) {
THError("ints can only be input parameters, not output, or inout");
}
}
virtual std::string asParameterString() const {
return "int " + name;
}
virtual void writeToKernel(lua_State *L, ClKernel *clKernel,THClKernels *k) {
luaT_getfieldchecknumber(L, -1, name.c_str());
int value = lua_tonumber(L, -1);
lua_pop(L, 1);
switch(direction) {
case input:
k->in(value);
break;
default:
THError("ints can only be input parameters, not output, or inout");
}
}
virtual std::string toString() const {
return "ClKernelArgInt{name=" + name + "}";
}
};
class ClKernelArgTensor : public ClKernelArg {
public:
ClKernelArgTensor(ClKernelDirection direction, string name) :
ClKernelArg(direction, name) {
}
virtual std::string asParameterString() const {
string res = "";
res += "global struct THClTensorInfoCl *" + name + "_info, ";
res += "global float * " + name + "_data";
return res;
}
virtual void writeToKernel(lua_State *L, ClKernel *clKernel,THClKernels *k) {
luaT_getfieldcheckudata(L, -1, name.c_str(), "torch.ClTensor");
THClTensor *value = (THClTensor *)luaT_checkudata(L, -1, "torch.ClTensor");
if(value == 0) {
THError("Tensor is null. this is odd actually, raise an issue");
}
if(value->storage == 0) {
if(direction != output){
THError("Output tensor has no data");
return;
} else {
// I guess we should resize here, somehow, in the future
THError("resize not implemented yet. It should be. Please remind me to add this, eg raise an issue");
return;
}
}
if(value->storage->wrapper == 0) {
THError("resize not implemented yet. It should be. Please remind me to add this, eg raise an issue");
return;
}
switch(direction) {
case input:
if(!value->storage->wrapper->isOnDevice()) {
value->storage->wrapper->copyToDevice();
}
k->inv2(value);
break;
case output:
if(!value->storage->wrapper->isOnDevice()) {
value->storage->wrapper->createOnDevice();
}
k->outv2(value);
break;
case inout:
if(!value->storage->wrapper->isOnDevice()) {
value->storage->wrapper->copyToDevice();
}
k->inoutv2(value);
break;
}
lua_pop(L, 1);
}
virtual std::string toString() const {
return "ClKernelArgTensor{name=" + name + "}";
}
};
class ClKernelArgFloat : public ClKernelArg {
public:
ClKernelArgFloat(ClKernelDirection direction, string name) :
ClKernelArg(direction, name) {
if(direction != input) {
THError("floats can only be input parameters, not output, or inout");
}
}
virtual std::string asParameterString() const {
return "float " + name;
}
virtual void writeToKernel(lua_State *L, ClKernel *clKernel,THClKernels *k) {
luaT_getfieldchecknumber(L, -1, name.c_str());
float value = lua_tonumber(L, -1);
lua_pop(L, 1);
switch(direction) {
case input:
k->in(value);
break;
default:
THError("ints can only be input parameters, not output, or inout");
}
}
virtual std::string toString() const {
return "ClKernelArgFloat{name=" + name + "}";
}
};
int getNumElementsFromTensorArg(lua_State *L, ClKernelArgTensor *arg) {
THClState *state = cltorch_getstate(L);
luaT_getfieldcheckudata(L, -1, arg->name.c_str(), "torch.ClTensor");
THClTensor *tensor = (THClTensor *)luaT_checkudata(L, -1, "torch.ClTensor");
return THClTensor_nElement(state, tensor);
}
class ClKernel {
public:
int refCount;
string source;
string extraSource;
string kernelName;
string generatedSource;
CLKernel *kernel;
vector< ClKernelArg * >args;
ClKernel() {
kernel = 0;
kernelName = "user_kernel";
extraSource = "";
}
~ClKernel() {
for(int i = 0; i < (int)args.size(); i++) {
delete args[i];
}
args.clear();
}
};
static void ClKernel_rawInit(ClKernel *self) {
self->refCount = 1;
self->source = "";
}
static void printStack(string name, lua_State *L) {
int top = lua_gettop(L);
cout << name << " top: " << top << endl;
for(int i = 1; i <= top; i++ ) {
cout << " stack[" << i << "] type=" << lua_typename(L, lua_type(L, i)) << " " << lua_type(L, i) << endl;
}
}
static void loadParameters(lua_State *L, ClKernelDirection direction, ClKernel *self) {
// assume that stack top is a table iwth the parameters
// each parameter comprises name as key, and type as string value
// valid typenames: int, float, torch.ClTensor, maybe ClTensor as shorthand
// iterate this table...
lua_pushnil(L);
int argIndex = (int)self->args.size();
while(lua_next(L, -2) != 0) {
string name = lua_tostring(L, -2);
string paramType = lua_tostring(L, -1);
if(paramType == "float") {
ClKernelArg *arg = new ClKernelArgFloat(direction, name);
self->args.push_back(arg);
} else if(paramType == "int") {
ClKernelArg *arg = new ClKernelArgInt(direction, name);
self->args.push_back(arg);
} else if(paramType == "torch.ClTensor" || paramType == "ClTensor") {
ClKernelArg *arg = new ClKernelArgTensor(direction, name);
self->args.push_back(arg);
} else {
THError("Unrecognized typename %s", paramType.c_str());
}
lua_pop(L, 1);
}
}
static int ClKernel_new(lua_State *L) {
ClKernel *self = (ClKernel*)THAlloc(sizeof(ClKernel));
self = new(self) ClKernel();
ClKernel_rawInit(self);
if(lua_type(L, 1) == LUA_TTABLE) {
lua_pushnil(L);
while(lua_next(L, -2) != 0) {
string key = lua_tostring(L, -2);
if(key == "input") {
loadParameters(L, ClKernelDirection::input, self);
} else if( key == "output") {
loadParameters(L, ClKernelDirection::output, self);
} else if( key == "inout") {
loadParameters(L, ClKernelDirection::inout, self);
} else if( key == "name") {
self->kernelName = lua_tostring(L, -1); // probably should use luaT for this
} else if( key == "src") {
self->source = lua_tostring(L, -1);
} else if( key == "funcs") {
self->extraSource = lua_tostring(L, -1);
} else {
THError("Parameter %s not recognized", key.c_str());
}
lua_pop(L, 1);
}
if(self->source == "") {
THError("Missing parameter src, or was empty");
}
THClState *state = cltorch_getstate(L);
EasyCL *cl = THClState_getClv2(state, state->currentDevice);
string kernelName = "user_kernel"; // can override by param, in future
string generatedSource = "";
generatedSource += easycl::replaceGlobal(getTensorInfoClSrc(), "{{MAX_CLTORCH_DIMS}}", easycl::toString(MAX_CLTORCH_DIMS)) + "\n";
generatedSource += self->extraSource + "\n";
generatedSource += "kernel void " + kernelName + "(\n";
for(int i = 0; i < (int)self->args.size(); i++) {
if(i > 0) {
generatedSource += ",\n";
}
generatedSource += " " + self->args[i]->asParameterString();
}
generatedSource += "\n) {\n"; // probalby should use ostringstream for this really, for speed
generatedSource += self->source + "\n";
generatedSource += "}\n";
self->generatedSource = generatedSource;
self->kernelName = kernelName;
self->kernel = cl->buildKernelFromString(generatedSource, kernelName, "", "user_kernel");
} else {
THError("First parameter to torch.ClKernel should be a table");
}
luaT_pushudata(L, self, "torch.ClKernel");
return 1;
}
static int ClKernel_free(lua_State *L) {
ClKernel *self = (ClKernel*)THAlloc(sizeof(ClKernel));
if(!self) {
return 0;
}
if(THAtomicDecrementRef(&self->refCount))
{
delete self->kernel;
self->~ClKernel();
THFree(self);
}
return 0;
}
static int ClKernel_factory(lua_State *L) {
THError("ClKernel_factory not implemented");
return 0;
}
static int ClKernel_print(lua_State *L) {
ClKernel *self = (ClKernel *)luaT_checkudata(L, 1, "torch.ClKernel");
cout << "source=" << self->source << endl;
return 0;
}
static int ClKernel_run(lua_State *L) {
THClState *state = cltorch_getstate(L);
if(lua_type(L, 2) != LUA_TTABLE) {
THError("run method expects one parameter: a table, with named arg values in");
return 0;
}
// now we can assume we have a table :-)
ClKernel *self = (ClKernel *)luaT_checkudata(L, 1, "torch.ClKernel");
try {
THClKernels k(state, self->kernel);
int numElements = -1;
for(int i = 0; i < (int)self->args.size(); i++) {
// what we need to do here is:
// - loop through each parameter object
// - for each parameter object, get the value from the passed in parameters, which
// were hopefully passed into this method, as values in a table
// - and then write this value to the kernel
// presumably, we can get each arg to extract itself from the table, as long as
// the table is top of the stack
// we can ignore extra values in the table for now
// what we do is, throw error on missing values
self->args[i]->writeToKernel(L, self, &k);
if(numElements == -1 && self->args[i]->direction != input && dynamic_cast< ClKernelArgTensor *>( self->args[i] ) != 0) {
numElements = getNumElementsFromTensorArg(L, dynamic_cast< ClKernelArgTensor *>(self->args[i]));
}
}
if(numElements == -1) {
THError("Must provide at least one output, or inout, ClTensor");
}
int workgroupSize = 64; // should make this an option
int numWorkgroups = (numElements + workgroupSize - 1) / workgroupSize;
int globalSize = workgroupSize * numWorkgroups;
self->kernel->run_1d(globalSize, workgroupSize);
} catch(runtime_error &e) {
THError("Error: %s", e.what());
}
return 0;
}
static const struct luaL_Reg ClKernel_funcs [] = {
{"print", ClKernel_print},
{"run", ClKernel_run},
{0,0}
};
void cltorch_UserKernel_init(lua_State *L)
{
luaT_newmetatable(L, "torch.ClKernel", NULL,
ClKernel_new, ClKernel_free, ClKernel_factory);
luaL_setfuncs(L, ClKernel_funcs, 0);
lua_pop(L, 1);
}
static std::string getTensorInfoClSrc() {
// [[[cog
// import stringify
// stringify.write_kernel( "kernel", "src/lib/THClTensorInfoCl.cl" )
// ]]]
// generated using cog, from src/lib/THClTensorInfoCl.cl:
const char * kernelSource =
"typedef struct THClTensorInfoCl {\n"
" unsigned int sizes[{{MAX_CLTORCH_DIMS}}];\n"
" unsigned int strides[{{MAX_CLTORCH_DIMS}}];\n"
" int offset;\n"
" int dims;\n"
"} TensorInfoCl;\n"
"\n"
"";
// [[[end]]]
return kernelSource;
}
<|endoftext|> |
<commit_before>#include "bits2blocks.h"
#define MASK_5BIT 0x000001F
#define MASK_10BIT 0x00003FF
#define MASK_16BIT 0x000FFFF
#define MASK_26BIT 0x3FFFFFF
#define MASK_28BIT 0xFFFFFFF
#define MAX_ERR_LEN 3
namespace redsea {
namespace {
uint32_t rol10(uint32_t word, int k) {
uint32_t result = word;
uint32_t l;
for (int i=0; i<k; i++) {
l = (result & 0x200);
result = (result << 1) & 0x3FF;
result ^= l;
}
return result;
}
uint32_t calcSyndrome(uint32_t vec) {
uint32_t synd_reg = 0x000;
uint32_t bit,l;
for (int k=25; k>=0; k--) {
bit = (vec & (1 << k));
l = (synd_reg & 0x200); // Store lefmost bit of register
synd_reg = (synd_reg << 1) & 0x3FF; // Rotate register
synd_reg ^= (bit ? 0x31B : 0x00); // Premultiply input by x^325 mod g(x)
synd_reg ^= (l ? 0x1B9 : 0x00); // Division mod 2 by g(x)
}
return synd_reg;
}
uint32_t calcCheckBits(uint32_t dataWord) {
uint32_t generator = 0x1B9;
uint32_t result = 0;
for (unsigned k=0; k<16; k++) {
if ((dataWord >> k) & 0x01) {
result ^= rol10(generator, k);
}
}
return result;
}
}
BlockStream::BlockStream(int input_type) : bitcount_(0), left_to_read_(0),
wideblock_(0), expected_offset_(0), has_sync_for_(5), group_data_(4),
has_block_(5), block_has_errors_(50), dpsk_(), ascii_bits_(),
input_type_(input_type) {
offset_word_ = {0x0FC, 0x198, 0x168, 0x350, 0x1B4};
block_for_offset_ = {0, 1, 2, 2, 3};
for (uint32_t e=1; e < (1<<MAX_ERR_LEN); e++) {
for (unsigned shift=0; shift < 16; shift++) {
uint32_t errvec = ((e << shift) & MASK_16BIT) << 10;
uint32_t m = calcCheckBits(0x01);
uint32_t sy = calcSyndrome(((1<<10) + m) ^ errvec);
error_lookup_[sy] = errvec>>10;
}
}
}
int BlockStream::getNextBit() {
int result = 0;
if (input_type_ == INPUT_MPX) {
result = dpsk_.getNextBit();
} else if (input_type_ == INPUT_ASCIIBITS) {
result = ascii_bits_.getNextBit();
}
return result;
}
void BlockStream::uncorrectable() {
//printf(":offset %d: not received\n",expected_offset_);
data_length_ = 0;
// TODO: return partial group
/*if (has_block_[A]) {
has_whole_group_ = true;
data_length_ = 1;
if (has_block_[B]) {
data_length_ = 2;
if (has_block_[C] || has_block_[CI]) {
data_length_ = 3;
}
}
}*/
block_has_errors_[block_counter_ % block_has_errors_.size()] = true;
unsigned erroneous_blocks = 0;
for (bool e : block_has_errors_) {
if (e)
erroneous_blocks ++;
}
// Sync is lost when >45 out of last 50 blocks are erroneous (Section C.1.2)
if (is_in_sync_ && erroneous_blocks > 45) {
is_in_sync_ = false;
for (unsigned i=0; i<block_has_errors_.size(); i++)
block_has_errors_[i] = false;
pi_ = 0x0000;
//printf(":too many errors, sync lost\n");
}
for (int o : {A, B, C, CI, D})
has_block_[o] = false;
}
std::vector<uint16_t> BlockStream::getNextGroup() {
has_whole_group_ = false;
data_length_ = 0;
while (!(has_whole_group_ || isEOF())) {
// Compensate for clock slip corrections
bitcount_ += 26 - left_to_read_;
// Read from radio
for (unsigned i=0; i < (is_in_sync_ ? left_to_read_ : 1); i++,bitcount_++) {
wideblock_ = (wideblock_ << 1) + getNextBit();
}
left_to_read_ = 26;
wideblock_ &= MASK_28BIT;
uint32_t block = (wideblock_ >> 1) & MASK_26BIT;
// Find the offsets for which the calcSyndrome is zero
bool has_sync_for_any = false;
for (int o : {A, B, C, CI, D}) {
has_sync_for_[o] = (calcSyndrome(block ^ offset_word_[o]) == 0x000);
has_sync_for_any |= has_sync_for_[o];
}
// Acquire sync
if (!is_in_sync_) {
if (has_sync_for_any) {
for (int o : {A, B, C, CI, D}) {
if (has_sync_for_[o]) {
unsigned dist = bitcount_ - prevbitcount_;
if (dist % 26 == 0 && dist <= 156 &&
(block_for_offset_[prevsync_] + dist/26) % 4 ==
block_for_offset_[o]) {
is_in_sync_ = true;
expected_offset_ = o;
//printf(":sync!\n");
} else {
prevbitcount_ = bitcount_;
prevsync_ = o;
}
}
}
}
}
// Synchronous decoding
if (is_in_sync_) {
block_counter_ ++;
uint16_t message = block >> 10;
if (expected_offset_ == C && !has_sync_for_[C] && has_sync_for_[CI]) {
expected_offset_ = CI;
}
if ( !has_sync_for_[expected_offset_]) {
// If message is a correct PI, error was probably in check bits
if (expected_offset_ == A && message == pi_ && pi_ != 0) {
has_sync_for_[A] = true;
//printf(":offset 0: ignoring error in check bits\n");
} else if (expected_offset_ == C && message == pi_ && pi_ != 0) {
has_sync_for_[CI] = true;
//printf(":offset 0: ignoring error in check bits\n");
// Detect & correct clock slips (Section C.1.2)
} else if (expected_offset_ == A && pi_ != 0 &&
((wideblock_ >> 12) & MASK_16BIT) == pi_) {
message = pi_;
wideblock_ >>= 1;
has_sync_for_[A] = true;
//printf(":offset 0: clock slip corrected\n");
} else if (expected_offset_ == A && pi_ != 0 &&
((wideblock_ >> 10) & MASK_16BIT) == pi_) {
message = pi_;
wideblock_ = (wideblock_ << 1) + getNextBit();
has_sync_for_[A] = true;
left_to_read_ = 25;
//printf(":offset 0: clock slip corrected\n");
// Detect & correct burst errors (Section B.2.2)
} else {
uint16_t synd_reg =
calcSyndrome(block ^ offset_word_[expected_offset_]);
if (pi_ != 0 && expected_offset_ == A) {
//printf(":offset 0: expecting PI%04x, got %04x, xor %04x, "
// "syndrome %03x\n", pi_, block>>10, pi_ ^ (block>>10), synd_reg);
}
if (error_lookup_.find(synd_reg) != error_lookup_.end()) {
uint32_t corrected_block = (block ^ offset_word_[expected_offset_])
^ (error_lookup_[synd_reg] << 10);
if (calcSyndrome(corrected_block) == 0x000) {
message = (block >> 10) ^ error_lookup_[synd_reg];
has_sync_for_[expected_offset_] = true;
}
//printf(":offset %d: error corrected using vector %04x for "
// "syndrome %03x\n", expected_offset_, error_lookup_[synd_reg],
// synd_reg);
}
}
// Still no sync pulse
if ( !has_sync_for_[expected_offset_]) {
uncorrectable();
}
}
// Error-free block received
if (has_sync_for_[expected_offset_]) {
group_data_[block_for_offset_[expected_offset_]] = message;
has_block_[expected_offset_] = true;
if (expected_offset_ == A) {
pi_ = message;
}
// Complete group received
if (has_block_[A] && has_block_[B] && (has_block_[C] ||
has_block_[CI]) && has_block_[D]) {
has_whole_group_ = true;
data_length_ = 4;
}
}
expected_offset_ = (expected_offset_ == C ? D :
(expected_offset_ + 1) % 5);
if (expected_offset_ == A) {
for (int o : {A, B, C, CI, D})
has_block_[o] = false;
}
}
}
auto result = group_data_;
result.resize(data_length_);
return result;
}
bool BlockStream::isEOF() const {
if (input_type_ == INPUT_MPX)
return dpsk_.isEOF();
else
return ascii_bits_.isEOF();
}
} // namespace redsea
<commit_msg>unsigned->int<commit_after>#include "bits2blocks.h"
#define MASK_5BIT 0x000001F
#define MASK_10BIT 0x00003FF
#define MASK_16BIT 0x000FFFF
#define MASK_26BIT 0x3FFFFFF
#define MASK_28BIT 0xFFFFFFF
#define MAX_ERR_LEN 3
namespace redsea {
namespace {
uint32_t rol10(uint32_t word, int k) {
uint32_t result = word;
uint32_t l;
for (int i=0; i<k; i++) {
l = (result & 0x200);
result = (result << 1) & 0x3FF;
result ^= l;
}
return result;
}
uint32_t calcSyndrome(uint32_t vec) {
uint32_t synd_reg = 0x000;
uint32_t bit,l;
for (int k=25; k>=0; k--) {
bit = (vec & (1 << k));
l = (synd_reg & 0x200); // Store lefmost bit of register
synd_reg = (synd_reg << 1) & 0x3FF; // Rotate register
synd_reg ^= (bit ? 0x31B : 0x00); // Premultiply input by x^325 mod g(x)
synd_reg ^= (l ? 0x1B9 : 0x00); // Division mod 2 by g(x)
}
return synd_reg;
}
uint32_t calcCheckBits(uint32_t dataWord) {
uint32_t generator = 0x1B9;
uint32_t result = 0;
for (unsigned k=0; k<16; k++) {
if ((dataWord >> k) & 0x01) {
result ^= rol10(generator, k);
}
}
return result;
}
}
BlockStream::BlockStream(int input_type) : bitcount_(0), left_to_read_(0),
wideblock_(0), expected_offset_(0), has_sync_for_(5), group_data_(4),
has_block_(5), block_has_errors_(50), dpsk_(), ascii_bits_(),
input_type_(input_type) {
offset_word_ = {0x0FC, 0x198, 0x168, 0x350, 0x1B4};
block_for_offset_ = {0, 1, 2, 2, 3};
for (uint32_t e=1; e < (1<<MAX_ERR_LEN); e++) {
for (unsigned shift=0; shift < 16; shift++) {
uint32_t errvec = ((e << shift) & MASK_16BIT) << 10;
uint32_t m = calcCheckBits(0x01);
uint32_t sy = calcSyndrome(((1<<10) + m) ^ errvec);
error_lookup_[sy] = errvec>>10;
}
}
}
int BlockStream::getNextBit() {
int result = 0;
if (input_type_ == INPUT_MPX) {
result = dpsk_.getNextBit();
} else if (input_type_ == INPUT_ASCIIBITS) {
result = ascii_bits_.getNextBit();
}
return result;
}
void BlockStream::uncorrectable() {
//printf(":offset %d: not received\n",expected_offset_);
data_length_ = 0;
// TODO: return partial group
/*if (has_block_[A]) {
has_whole_group_ = true;
data_length_ = 1;
if (has_block_[B]) {
data_length_ = 2;
if (has_block_[C] || has_block_[CI]) {
data_length_ = 3;
}
}
}*/
block_has_errors_[block_counter_ % block_has_errors_.size()] = true;
unsigned erroneous_blocks = 0;
for (bool e : block_has_errors_) {
if (e)
erroneous_blocks ++;
}
// Sync is lost when >45 out of last 50 blocks are erroneous (Section C.1.2)
if (is_in_sync_ && erroneous_blocks > 45) {
is_in_sync_ = false;
for (unsigned i=0; i<block_has_errors_.size(); i++)
block_has_errors_[i] = false;
pi_ = 0x0000;
//printf(":too many errors, sync lost\n");
}
for (int o : {A, B, C, CI, D})
has_block_[o] = false;
}
std::vector<uint16_t> BlockStream::getNextGroup() {
has_whole_group_ = false;
data_length_ = 0;
while (!(has_whole_group_ || isEOF())) {
// Compensate for clock slip corrections
bitcount_ += 26 - left_to_read_;
// Read from radio
for (int i=0; i < (is_in_sync_ ? left_to_read_ : 1); i++,bitcount_++) {
wideblock_ = (wideblock_ << 1) + getNextBit();
}
left_to_read_ = 26;
wideblock_ &= MASK_28BIT;
uint32_t block = (wideblock_ >> 1) & MASK_26BIT;
// Find the offsets for which the calcSyndrome is zero
bool has_sync_for_any = false;
for (int o : {A, B, C, CI, D}) {
has_sync_for_[o] = (calcSyndrome(block ^ offset_word_[o]) == 0x000);
has_sync_for_any |= has_sync_for_[o];
}
// Acquire sync
if (!is_in_sync_) {
if (has_sync_for_any) {
for (int o : {A, B, C, CI, D}) {
if (has_sync_for_[o]) {
int dist = bitcount_ - prevbitcount_;
if (dist % 26 == 0 && dist <= 156 &&
(block_for_offset_[prevsync_] + dist/26) % 4 ==
block_for_offset_[o]) {
is_in_sync_ = true;
expected_offset_ = o;
//printf(":sync!\n");
} else {
prevbitcount_ = bitcount_;
prevsync_ = o;
}
}
}
}
}
// Synchronous decoding
if (is_in_sync_) {
block_counter_ ++;
uint16_t message = block >> 10;
if (expected_offset_ == C && !has_sync_for_[C] && has_sync_for_[CI]) {
expected_offset_ = CI;
}
if ( !has_sync_for_[expected_offset_]) {
// If message is a correct PI, error was probably in check bits
if (expected_offset_ == A && message == pi_ && pi_ != 0) {
has_sync_for_[A] = true;
//printf(":offset 0: ignoring error in check bits\n");
} else if (expected_offset_ == C && message == pi_ && pi_ != 0) {
has_sync_for_[CI] = true;
//printf(":offset 0: ignoring error in check bits\n");
// Detect & correct clock slips (Section C.1.2)
} else if (expected_offset_ == A && pi_ != 0 &&
((wideblock_ >> 12) & MASK_16BIT) == pi_) {
message = pi_;
wideblock_ >>= 1;
has_sync_for_[A] = true;
//printf(":offset 0: clock slip corrected\n");
} else if (expected_offset_ == A && pi_ != 0 &&
((wideblock_ >> 10) & MASK_16BIT) == pi_) {
message = pi_;
wideblock_ = (wideblock_ << 1) + getNextBit();
has_sync_for_[A] = true;
left_to_read_ = 25;
//printf(":offset 0: clock slip corrected\n");
// Detect & correct burst errors (Section B.2.2)
} else {
uint16_t synd_reg =
calcSyndrome(block ^ offset_word_[expected_offset_]);
if (pi_ != 0 && expected_offset_ == A) {
//printf(":offset 0: expecting PI%04x, got %04x, xor %04x, "
// "syndrome %03x\n", pi_, block>>10, pi_ ^ (block>>10), synd_reg);
}
if (error_lookup_.find(synd_reg) != error_lookup_.end()) {
uint32_t corrected_block = (block ^ offset_word_[expected_offset_])
^ (error_lookup_[synd_reg] << 10);
if (calcSyndrome(corrected_block) == 0x000) {
message = (block >> 10) ^ error_lookup_[synd_reg];
has_sync_for_[expected_offset_] = true;
}
//printf(":offset %d: error corrected using vector %04x for "
// "syndrome %03x\n", expected_offset_, error_lookup_[synd_reg],
// synd_reg);
}
}
// Still no sync pulse
if ( !has_sync_for_[expected_offset_]) {
uncorrectable();
}
}
// Error-free block received
if (has_sync_for_[expected_offset_]) {
group_data_[block_for_offset_[expected_offset_]] = message;
has_block_[expected_offset_] = true;
if (expected_offset_ == A) {
pi_ = message;
}
// Complete group received
if (has_block_[A] && has_block_[B] && (has_block_[C] ||
has_block_[CI]) && has_block_[D]) {
has_whole_group_ = true;
data_length_ = 4;
}
}
expected_offset_ = (expected_offset_ == C ? D :
(expected_offset_ + 1) % 5);
if (expected_offset_ == A) {
for (int o : {A, B, C, CI, D})
has_block_[o] = false;
}
}
}
auto result = group_data_;
result.resize(data_length_);
return result;
}
bool BlockStream::isEOF() const {
if (input_type_ == INPUT_MPX)
return dpsk_.isEOF();
else
return ascii_bits_.isEOF();
}
} // namespace redsea
<|endoftext|> |
<commit_before>/*
Author: Anfego
Date: 04/11/14
Class: CSCI 6430
Professor: Dr. Buttler
University: MTSU
Desciption:
This program is an implementation of a MPI tupple space
Support for:
PP_Init()
PP_Put()
PP_Get()
PP_Reserve()
PP_Finalize()
*/
#include <vector> // stack
#include <utility>
#include <pthread.h>
#include <iostream>
#include <stack>
#include "/nfshome/rbutler/public/courses/pp6430/mpich3i/include/mpi.h"
#include "pp.h"
#include "lindaStuff.h"
using namespace std;
/*<sumary>
int num_user_types;
Any valid integer can be a user type.
Wildcards will be described below.
int user_types[PP_MAX_USER_TYPES];
int server_flag; // I begin to execute server code if true
Discussion:
The user should do MPI_Init and MPI_Finalize.
</sumary>*/
int PP_Init(int num_user_types, int * user_types, int * am_server_flag)
{
MPI_Comm comm_world_dup;
MPI_Comm_dup(MPI_COMM_WORLD, &comm_world_dup);
// get user types
if(*am_server_flag == 0)
{
return PP_SUCCESS;
}
else
{
printf("I am a server %d\n",*am_server_flag);
vector<int> uTypes;
// create stack for user types
int done = 0;
int mpi_flag = 0;
MPI_Status status;
for (int i = 0; i < num_user_types; ++i)
{
}
while(!done)
{
MPI_Iprobe(MPI_ANY_SOURCE,MPI_ANY_TAG,comm_world_dup,&mpi_flag,&status);
if (mpi_flag == 1) // if true there is a message, PP_Finalize
{
MPI_Recv(&done,1,MPI_INT,MPI_ANY_SOURCE,MPI_ANY_TAG,comm_world_dup,&status);
}
}
}
return PP_SUCCESS;
}
int PP_Finalize()
{
MPI_Comm comm_linda;
//Send "To finish" signal
int finish = 1;
MPI_Send(&finish,1,MPI_INT,3,MPI_ANY_TAG,comm_linda);
return PP_SUCCESS;
}
int PP_Put()
{
return PP_SUCCESS;
}
int PP_Reserve()
{
return PP_SUCCESS;
}
int PP_Get()
{
return PP_SUCCESS;
}
int PP_Set_problem_done()
{
return PP_SUCCESS;
}
int PP_Abort()
{
return PP_SUCCESS;
}
<commit_msg>creating PP_Finalize<commit_after>/*
Author: Anfego
Date: 04/11/14
Class: CSCI 6430
Professor: Dr. Buttler
University: MTSU
Desciption:
This program is an implementation of a MPI tupple space
Support for:
PP_Init()
PP_Put()
PP_Get()
PP_Reserve()
PP_Finalize()
*/
#include <vector> // stack
#include <utility>
#include <pthread.h>
#include <iostream>
#include <stack>
#include "/nfshome/rbutler/public/courses/pp6430/mpich3i/include/mpi.h"
#include "pp.h"
#include "lindaStuff.h"
using namespace std;
/*<sumary>
int num_user_types;
Any valid integer can be a user type.
Wildcards will be described below.
int user_types[PP_MAX_USER_TYPES];
int server_flag; // I begin to execute server code if true
Discussion:
The user should do MPI_Init and MPI_Finalize.
</sumary>*/
int PP_Init(int num_user_types, int * user_types, int * am_server_flag)
{
MPI_Comm comm_world_dup;
MPI_Comm_dup(MPI_COMM_WORLD, &comm_world_dup);
// get user types
if(*am_server_flag == 0)
{
return PP_SUCCESS;
}
else
{
printf("I am a server %d\n",*am_server_flag);
vector<int> uTypes;
// create stack for user types
int done = 0;
int mpi_flag = 0;
MPI_Status status;
for (int i = 0; i < num_user_types; ++i)
{
}
while(!done)
{
MPI_Iprobe(MPI_ANY_SOURCE,MPI_ANY_TAG,comm_world_dup,&mpi_flag,&status);
if (mpi_flag == 1) // if true there is a message, PP_Finalize
{
MPI_Recv(&done,1,MPI_INT,MPI_ANY_SOURCE,MPI_ANY_TAG,comm_world_dup,&status);
printf("Server Exit\n");
}
}
}
return PP_SUCCESS;
}
int PP_Finalize()
{
MPI_Comm comm_linda;
//Send "To finish" signal
int finish = 1;
MPI_Send(&finish,1,MPI_INT,3,MPI_ANY_TAG,comm_linda);
return PP_SUCCESS;
}
int PP_Put()
{
return PP_SUCCESS;
}
int PP_Reserve()
{
return PP_SUCCESS;
}
int PP_Get()
{
return PP_SUCCESS;
}
int PP_Set_problem_done()
{
return PP_SUCCESS;
}
int PP_Abort()
{
return PP_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* Access logging.
*
* author: Max Kellermann <[email protected]>
*/
#ifndef BENG_PROXY_ACCESS_LOG_HXX
#define BENG_PROXY_ACCESS_LOG_HXX
#include <http/status.h>
#include <stdint.h>
struct http_server_request;
#ifndef NO_ACCESS_LOG
#include <daemon/log.h>
#endif
#ifdef NO_ACCESS_LOG
static inline void
access_log(gcc_unused struct http_server_request *request,
gcc_unused const char *site,
gcc_unused const char *referer,
gcc_unused const char *user_agent,
gcc_unused http_status_t status, gcc_unused off_t length,
gcc_unused uint64_t bytes_received,
gcc_unused uint64_t bytes_sent,
gcc_unused uint64_t duration)
{
}
#else
void
access_log(struct http_server_request *request, const char *site,
const char *referer, const char *user_agent,
http_status_t status, off_t length,
uint64_t bytes_received, uint64_t bytes_sent,
uint64_t duration);
#endif
#endif
<commit_msg>access_log: add missing include for off_t<commit_after>/*
* Access logging.
*
* author: Max Kellermann <[email protected]>
*/
#ifndef BENG_PROXY_ACCESS_LOG_HXX
#define BENG_PROXY_ACCESS_LOG_HXX
#include <http/status.h>
#include <stdint.h>
#include <sys/types.h>
struct http_server_request;
#ifndef NO_ACCESS_LOG
#include <daemon/log.h>
#endif
#ifdef NO_ACCESS_LOG
static inline void
access_log(gcc_unused struct http_server_request *request,
gcc_unused const char *site,
gcc_unused const char *referer,
gcc_unused const char *user_agent,
gcc_unused http_status_t status, gcc_unused off_t length,
gcc_unused uint64_t bytes_received,
gcc_unused uint64_t bytes_sent,
gcc_unused uint64_t duration)
{
}
#else
void
access_log(struct http_server_request *request, const char *site,
const char *referer, const char *user_agent,
http_status_t status, off_t length,
uint64_t bytes_received, uint64_t bytes_sent,
uint64_t duration);
#endif
#endif
<|endoftext|> |
<commit_before>#include "journal.h"
#include "qif.h"
#include "datetime.h"
#include "error.h"
#include "util.h"
#include <cstring>
#include <memory>
namespace ledger {
#define MAX_LINE 1024
static char line[MAX_LINE + 1];
static std::string path;
static unsigned int linenum;
static inline char * get_line(std::istream& in) {
in.getline(line, MAX_LINE);
int len = std::strlen(line);
if (line[len - 1] == '\r')
line[len - 1] = '\0';
linenum++;
return line;
}
bool qif_parser_t::test(std::istream& in) const
{
char magic[sizeof(unsigned int) + 1];
in.read(magic, sizeof(unsigned int));
magic[sizeof(unsigned int)] = '\0';
in.seekg(0, std::ios::beg);
return (std::strcmp(magic, "!Typ") == 0 ||
std::strcmp(magic, "\n!Ty") == 0 ||
std::strcmp(magic, "\r\n!T") == 0);
}
unsigned int qif_parser_t::parse(std::istream& in,
journal_t * journal,
account_t * master,
const std::string * original_file)
{
std::auto_ptr<entry_t> entry;
std::auto_ptr<amount_t> amount;
transaction_t * xact;
unsigned int count = 0;
account_t * misc = NULL;
commodity_t * def_commodity = NULL;
entry.reset(new entry_t);
xact = new transaction_t(master);
entry->add_transaction(xact);
path = journal->sources.back();
linenum = 1;
while (! in.eof()) {
char c;
in.get(c);
switch (c) {
case ' ':
case '\t':
if (peek_next_nonws(in) != '\n') {
get_line(in);
throw parse_error(path, linenum, "Line begins with whitespace");
}
// fall through...
case '\n':
linenum++;
case '\r': // skip blank lines
break;
case '!':
in >> line;
// jww (2004-08-19): these types are not supported yet
assert(std::strcmp(line, "Type:Invst") != 0 &&
std::strcmp(line, "Account") != 0 &&
std::strcmp(line, "Type:Cat") != 0 &&
std::strcmp(line, "Type:Class") != 0 &&
std::strcmp(line, "Type:Memorized") != 0);
get_line(in);
break;
case 'D':
in >> line;
if (! parse_date(line, &entry->date))
throw parse_error(path, linenum, "Failed to parse date");
break;
case 'T':
case '$':
in >> line;
xact->amount.parse(line);
if (! def_commodity)
def_commodity = commodity_t::find_commodity("$", true);
xact->amount.set_commodity(*def_commodity);
if (c == '$')
xact->amount.negate();
break;
case 'C':
if (in.peek() == '*') {
in.get(c);
entry->state = entry_t::CLEARED;
}
break;
case 'N':
if (std::isdigit(in.peek())) {
in >> line;
entry->code = line;
}
break;
case 'P':
case 'M':
case 'L':
case 'S':
case 'E': {
char b = c;
int len;
c = in.peek();
if (! std::isspace(c) && c != '\n') {
get_line(in);
switch (b) {
case 'P':
entry->payee = line;
break;
case 'S':
xact = new transaction_t(NULL);
entry->add_transaction(xact);
// fall through...
case 'L':
len = std::strlen(line);
if (line[len - 1] == ']')
line[len - 1] = '\0';
xact->account = journal->find_account(line[0] == '[' ?
line + 1 : line);
break;
case 'M':
case 'E':
xact->note = line;
break;
}
}
break;
}
case 'A':
// jww (2004-08-19): these are ignored right now
get_line(in);
break;
case '^':
if (xact->account == master) {
if (! misc)
misc = journal->find_account("Miscellaneous");
transaction_t * nxact = new transaction_t(misc);
entry->add_transaction(nxact);
nxact->amount.negate();
}
if (journal->add_entry(entry.get())) {
entry.release();
count++;
}
entry.reset(new entry_t);
xact = new transaction_t(master);
entry->add_transaction(xact);
break;
}
}
return count;
}
} // namespace ledger
#ifdef USE_BOOST_PYTHON
#include <boost/python.hpp>
using namespace boost::python;
using namespace ledger;
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(qif_parse_overloads,
qif_parser_t::parse, 2, 4)
void export_qif() {
class_< qif_parser_t, bases<parser_t> > ("QifParser")
.def("test", &qif_parser_t::test)
.def("parse", &qif_parser_t::parse, qif_parse_overloads())
;
}
#endif // USE_BOOST_PYTHON
<commit_msg>(qif_parser_t::parse): Propogate commodity flags when parsing amounts from a QIF file.<commit_after>#include "journal.h"
#include "qif.h"
#include "datetime.h"
#include "error.h"
#include "util.h"
#include <cstring>
#include <memory>
namespace ledger {
#define MAX_LINE 1024
static char line[MAX_LINE + 1];
static std::string path;
static unsigned int linenum;
static inline char * get_line(std::istream& in) {
in.getline(line, MAX_LINE);
int len = std::strlen(line);
if (line[len - 1] == '\r')
line[len - 1] = '\0';
linenum++;
return line;
}
bool qif_parser_t::test(std::istream& in) const
{
char magic[sizeof(unsigned int) + 1];
in.read(magic, sizeof(unsigned int));
magic[sizeof(unsigned int)] = '\0';
in.seekg(0, std::ios::beg);
return (std::strcmp(magic, "!Typ") == 0 ||
std::strcmp(magic, "\n!Ty") == 0 ||
std::strcmp(magic, "\r\n!T") == 0);
}
unsigned int qif_parser_t::parse(std::istream& in,
journal_t * journal,
account_t * master,
const std::string * original_file)
{
std::auto_ptr<entry_t> entry;
std::auto_ptr<amount_t> amount;
transaction_t * xact;
unsigned int count = 0;
account_t * misc = NULL;
commodity_t * def_commodity = NULL;
entry.reset(new entry_t);
xact = new transaction_t(master);
entry->add_transaction(xact);
path = journal->sources.back();
linenum = 1;
while (! in.eof()) {
char c;
in.get(c);
switch (c) {
case ' ':
case '\t':
if (peek_next_nonws(in) != '\n') {
get_line(in);
throw parse_error(path, linenum, "Line begins with whitespace");
}
// fall through...
case '\n':
linenum++;
case '\r': // skip blank lines
break;
case '!':
in >> line;
// jww (2004-08-19): these types are not supported yet
assert(std::strcmp(line, "Type:Invst") != 0 &&
std::strcmp(line, "Account") != 0 &&
std::strcmp(line, "Type:Cat") != 0 &&
std::strcmp(line, "Type:Class") != 0 &&
std::strcmp(line, "Type:Memorized") != 0);
get_line(in);
break;
case 'D':
in >> line;
if (! parse_date(line, &entry->date))
throw parse_error(path, linenum, "Failed to parse date");
break;
case 'T':
case '$': {
in >> line;
xact->amount.parse(line);
unsigned long flags = xact->amount.commodity().flags;
unsigned short prec = xact->amount.commodity().precision;
if (! def_commodity)
def_commodity = commodity_t::find_commodity("$", true);
xact->amount.set_commodity(*def_commodity);
def_commodity->flags |= flags;
if (prec > def_commodity->precision)
def_commodity->precision = prec;
if (c == '$')
xact->amount.negate();
break;
}
case 'C':
if (in.peek() == '*') {
in.get(c);
entry->state = entry_t::CLEARED;
}
break;
case 'N':
if (std::isdigit(in.peek())) {
in >> line;
entry->code = line;
}
break;
case 'P':
case 'M':
case 'L':
case 'S':
case 'E': {
char b = c;
int len;
c = in.peek();
if (! std::isspace(c) && c != '\n') {
get_line(in);
switch (b) {
case 'P':
entry->payee = line;
break;
case 'S':
xact = new transaction_t(NULL);
entry->add_transaction(xact);
// fall through...
case 'L':
len = std::strlen(line);
if (line[len - 1] == ']')
line[len - 1] = '\0';
xact->account = journal->find_account(line[0] == '[' ?
line + 1 : line);
break;
case 'M':
case 'E':
xact->note = line;
break;
}
}
break;
}
case 'A':
// jww (2004-08-19): these are ignored right now
get_line(in);
break;
case '^':
if (xact->account == master) {
if (! misc)
misc = journal->find_account("Miscellaneous");
transaction_t * nxact = new transaction_t(misc);
entry->add_transaction(nxact);
nxact->amount.negate();
}
if (journal->add_entry(entry.get())) {
entry.release();
count++;
}
entry.reset(new entry_t);
xact = new transaction_t(master);
entry->add_transaction(xact);
break;
}
}
return count;
}
} // namespace ledger
#ifdef USE_BOOST_PYTHON
#include <boost/python.hpp>
using namespace boost::python;
using namespace ledger;
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(qif_parse_overloads,
qif_parser_t::parse, 2, 4)
void export_qif() {
class_< qif_parser_t, bases<parser_t> > ("QifParser")
.def("test", &qif_parser_t::test)
.def("parse", &qif_parser_t::parse, qif_parse_overloads())
;
}
#endif // USE_BOOST_PYTHON
<|endoftext|> |
<commit_before>/// \file annotation.hpp
/// utilities for working with Struct-formatted annotations on Protobuf objects
#ifndef VG_ANNOTATION_HPP_INCLUDED
#define VG_ANNOTATION_HPP_INCLUDED
#include <vector>
#include <string>
#include <type_traits>
#include <google/protobuf/struct.pb.h>
namespace vg {
using namespace std;
////////////////////////////////////////////////////////////////////////
// Internal Types
////////////////////////////////////////////////////////////////////////
/// We define an adapter for things that are annotated to let us get at the annotation struct.
template<typename T>
struct Annotation {
/// Get the immutable annotations Struct
static const google::protobuf::Struct& get(const T& t);
/// Get the mutable annotations struct.
static google::protobuf::Struct* get_mutable(T* t);
/// Clear all annotations
void clear(T* t);
};
/// Cast a Protobuf generic Value to any type.
template <typename T, typename Enabled = void>
T value_cast(const google::protobuf::Value& value);
/// Cast any type to a generic Protobuf value.
template<typename T, typename Enabled = void>
google::protobuf::Value value_cast(const T& wrap);
////////////////////////////////////////////////////////////////////////
// API
////////////////////////////////////////////////////////////////////////
/// Get the annotation with the given name and return it.
/// If not present, returns the Protobuf default value for the annotation type.
/// The value may be a primitive type or an entire Protobuf object.
/// It is undefined behavior to read a value out into a different type than it was stored with.
template<typename AnnotationType, typename Annotated>
AnnotationType get_annotation(const Annotated& annotated, const string& name);
/// Set the annotation with the given name to the given value.
/// The value may be a primitive type or an entire Protobuf object.
template<typename AnnotationType, typename Annotated>
void set_annotation(Annotated* annotated, const string& name, const AnnotationType& annotation);
/// Clear the annotation with the given name.
template<typename Annotated>
void clear_annotation(Annotated* annotated, const string& name);
////////////////////////////////////////////////////////////////////////
// Implementation
////////////////////////////////////////////////////////////////////////
template<typename T>
const google::protobuf::Struct& Annotation<T>::get(const T& t) {
return t.annotation();
}
template<typename T>
google::protobuf::Struct* Annotation<T>::get_mutable(T* t) {
return t->mutable_annotation();
}
template<typename T>
void Annotation<T>::clear(T* t) {
t->clear_annotation();
}
template<>
bool value_cast<bool, void>(const google::protobuf::Value& value) {
assert(value.kind_case() == google::protobuf::Value::KindCase::kBoolValue);
return value.bool_value();
}
template<>
double value_cast<double, void>(const google::protobuf::Value& value) {
assert(value.kind_case() == google::protobuf::Value::KindCase::kNumberValue);
return value.number_value();
}
template<>
string value_cast<string, void>(const google::protobuf::Value& value) {
assert(value.kind_case() == google::protobuf::Value::KindCase::kStringValue);
return value.string_value();
}
template<>
google::protobuf::Value value_cast<bool, void>(const bool& wrap) {
google::protobuf::Value to_return;
to_return.set_bool_value(wrap);
return to_return;
}
template<>
google::protobuf::Value value_cast<double, void>(const double& wrap) {
google::protobuf::Value to_return;
to_return.set_number_value(wrap);
return to_return;
}
template<>
google::protobuf::Value value_cast<string, void>(const string& wrap) {
google::protobuf::Value to_return;
to_return.set_string_value(wrap);
return to_return;
}
// TODO: more value casts for e.g. vectors and ints and embedded messages.
template<typename AnnotationType, typename Annotated>
AnnotationType get_annotation(const Annotated& annotated, const string& name) {
// Grab the whole annotation struct
auto annotation_struct = Annotation<Annotated>::get(annotated);
if (!annotation_struct.fields().count(name)) {
// Nothing is there.
// Return the Proto default value, by value-initializing.
return AnnotationType();
}
// Get the Protobuf Value for this annotation name
auto value = annotation_struct.fields().at(name);
// Pull out the right type.
return value_cast<AnnotationType>(value);
}
template<typename AnnotationType, typename Annotated>
void set_annotation(Annotated* annotated, const string& name, const AnnotationType& annotation) {
// Get ahold of the struct
auto* annotation_struct = Annotation<Annotated>::get_mutable(annotated);
// Set the key to the wrapped value
(*annotation_struct->mutable_fields())[name] = value_cast(annotation);
}
template<typename Annotated>
void clear_annotation(Annotated* annotated, const string& name) {
Annotation<Annotated>::clear(annotated, name);
}
}
#endif
<commit_msg>Clear fields individually properly<commit_after>/// \file annotation.hpp
/// utilities for working with Struct-formatted annotations on Protobuf objects
#ifndef VG_ANNOTATION_HPP_INCLUDED
#define VG_ANNOTATION_HPP_INCLUDED
#include <vector>
#include <string>
#include <type_traits>
#include <google/protobuf/struct.pb.h>
namespace vg {
using namespace std;
////////////////////////////////////////////////////////////////////////
// Internal Types
////////////////////////////////////////////////////////////////////////
/// We define an adapter for things that are annotated to let us get at the annotation struct.
template<typename T>
struct Annotation {
/// Get the immutable annotations Struct
static const google::protobuf::Struct& get(const T& t);
/// Get the mutable annotations struct.
static google::protobuf::Struct* get_mutable(T* t);
/// Clear all annotations
void clear(T* t);
};
/// Cast a Protobuf generic Value to any type.
template <typename T, typename Enabled = void>
T value_cast(const google::protobuf::Value& value);
/// Cast any type to a generic Protobuf value.
template<typename T, typename Enabled = void>
google::protobuf::Value value_cast(const T& wrap);
////////////////////////////////////////////////////////////////////////
// API
////////////////////////////////////////////////////////////////////////
/// Get the annotation with the given name and return it.
/// If not present, returns the Protobuf default value for the annotation type.
/// The value may be a primitive type or an entire Protobuf object.
/// It is undefined behavior to read a value out into a different type than it was stored with.
template<typename AnnotationType, typename Annotated>
AnnotationType get_annotation(const Annotated& annotated, const string& name);
/// Set the annotation with the given name to the given value.
/// The value may be a primitive type or an entire Protobuf object.
template<typename AnnotationType, typename Annotated>
void set_annotation(Annotated* annotated, const string& name, const AnnotationType& annotation);
/// Clear the annotation with the given name.
template<typename Annotated>
void clear_annotation(Annotated* annotated, const string& name);
////////////////////////////////////////////////////////////////////////
// Implementation
////////////////////////////////////////////////////////////////////////
template<typename T>
const google::protobuf::Struct& Annotation<T>::get(const T& t) {
return t.annotation();
}
template<typename T>
google::protobuf::Struct* Annotation<T>::get_mutable(T* t) {
return t->mutable_annotation();
}
template<typename T>
void Annotation<T>::clear(T* t) {
t->clear_annotation();
}
template<>
bool value_cast<bool, void>(const google::protobuf::Value& value) {
assert(value.kind_case() == google::protobuf::Value::KindCase::kBoolValue);
return value.bool_value();
}
template<>
double value_cast<double, void>(const google::protobuf::Value& value) {
assert(value.kind_case() == google::protobuf::Value::KindCase::kNumberValue);
return value.number_value();
}
template<>
string value_cast<string, void>(const google::protobuf::Value& value) {
assert(value.kind_case() == google::protobuf::Value::KindCase::kStringValue);
return value.string_value();
}
template<>
google::protobuf::Value value_cast<bool, void>(const bool& wrap) {
google::protobuf::Value to_return;
to_return.set_bool_value(wrap);
return to_return;
}
template<>
google::protobuf::Value value_cast<double, void>(const double& wrap) {
google::protobuf::Value to_return;
to_return.set_number_value(wrap);
return to_return;
}
template<>
google::protobuf::Value value_cast<string, void>(const string& wrap) {
google::protobuf::Value to_return;
to_return.set_string_value(wrap);
return to_return;
}
// TODO: more value casts for e.g. vectors and ints and embedded messages.
template<typename AnnotationType, typename Annotated>
AnnotationType get_annotation(const Annotated& annotated, const string& name) {
// Grab the whole annotation struct
auto annotation_struct = Annotation<Annotated>::get(annotated);
if (!annotation_struct.fields().count(name)) {
// Nothing is there.
// Return the Proto default value, by value-initializing.
return AnnotationType();
}
// Get the Protobuf Value for this annotation name
auto value = annotation_struct.fields().at(name);
// Pull out the right type.
return value_cast<AnnotationType>(value);
}
template<typename AnnotationType, typename Annotated>
void set_annotation(Annotated* annotated, const string& name, const AnnotationType& annotation) {
// Get ahold of the struct
auto* annotation_struct = Annotation<Annotated>::get_mutable(annotated);
// Set the key to the wrapped value
(*annotation_struct->mutable_fields())[name] = value_cast(annotation);
}
template<typename Annotated>
void clear_annotation(Annotated* annotated, const string& name) {
// Get ahold of the struct
auto* annotation_struct = Annotation<Annotated>::get_mutable(annotated);
// Clear out that field
annotation_struct->mutable_fields()->clear(name);
}
}
#endif
<|endoftext|> |
<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2010, 2011, 2012, 2013, 2014
Raffaello D. Di Napoli
This file is part of Abaclade.
Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Abaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
Public License for more details.
You should have received a copy of the GNU General Public License along with Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#include <abaclade.hxx>
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::text::utf8_char_traits
namespace abc {
namespace text {
// Optimization 1: odd indices would have the same values as the preceding even ones, so the number
// of elements can be cut in half.
// Optimization 2: the maximum length is less than 0xf, so each value is encoded in a nibble instead
// of a full byte.
//
// In the end, the lead byte is treated like this:
//
// ┌─────────────┬──────────────┬────────┐
// │ 7 6 5 4 3 2 │ 1 │ 0 │
// ├─────────────┼──────────────┼────────┤
// │ byte index │ nibble index │ unused │
// └─────────────┴──────────────┴────────┘
//
// See utf8_char_traits::lead_char_to_codepoint_size() for the actual code accessing this array.
uint8_t const utf8_char_traits::smc_acbCpSizesByLeadChar[] = {
// 0xxxxxxx
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
// 10xxxxxx – invalid (cannot be start of a sequence), so just skip it.
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
// 110xxxxx
0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
// 1110xxxx
0x33, 0x33, 0x33, 0x33,
// 11110xxx
0x44, 0x44,
// These are either overlong (code points encoded using more bytes than necessary) or invalid
// (the resulting symbol would be out of Unicode code point range).
// 111110xx
0x55,
// 1111110x same as above, and 1111111x is invalid (not UTF-8), so just skip it.
0x16
};
uint8_t const utf8_char_traits::smc_acbitShiftMask[] = {
// 0xxxxxxx 110xxxxx 1110xxxx 11110xxx 111110xx 1111110x
0, 2, 3, 4, 5, 6
};
/*static*/ char8_t * utf8_char_traits::codepoint_to_chars(char32_t cp, char8_t * pchDstBegin) {
ABC_TRACE_FUNC(cp, pchDstBegin);
// Compute the length of the UTF-8 sequence for this code point.
unsigned cbSeq;
if (cp <= 0x00007f) {
// Encode xxx xxxx as 0xxxxxxx.
cbSeq = 1;
} else if (cp <= 0x0007ff) {
// Encode xxx xxyy yyyy as 110xxxxx 10yyyyyy.
cbSeq = 2;
} else if (cp <= 0x00ffff) {
// Encode xxxx yyyy yyzz zzzz as 1110xxxx 10yyyyyy 10zzzzzz.
cbSeq = 3;
} else /*if (cp <= 0x10ffff)*/ {
// Encode w wwxx xxxx yyyy yyzz zzzz as 11110www 10xxxxxx 10yyyyyy 10zzzzzz.
cbSeq = 4;
}
// Calculate where the sequence will end, and write each byte backwards from there.
char8_t * pchDstEnd(pchDstBegin + cbSeq);
--cbSeq;
char8_t iSeqIndicator(text::host_char_traits::cont_length_to_seq_indicator(cbSeq));
char8_t * pchDst(pchDstEnd);
while (cbSeq--) {
// Each trailing byte uses 6 bits.
*--pchDst = char8_t(0x80 | (cp & 0x3f));
cp >>= 6;
}
// The remaining code point bits (after >> 6 * (cbSeq - 1)) make up what goes in the lead byte.
*--pchDst = iSeqIndicator | char8_t(cp);
return pchDstEnd;
}
} //namespace text
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::text::utf16_char_traits
namespace abc {
namespace text {
/*static*/ char16_t * utf16_char_traits::codepoint_to_chars(char32_t cp, char16_t * pchDstBegin) {
ABC_TRACE_FUNC(cp, pchDstBegin);
char16_t * pchDst(pchDstBegin);
if (cp > 0x00ffff) {
// The code point requires two UTF-16 characters: generate a surrogate pair.
cp -= 0x10000;
*pchDst++ = char16_t(0xd800 | ((cp & 0x0ffc00) >> 10));
*pchDst++ = char16_t(0xdc00 | (cp & 0x0003ff) );
} else {
// The code point fits in a single UTF-16 character.
*pchDst++ = char16_t(cp);
}
return pchDst;
}
} //namespace text
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
<commit_msg>Don’t pull method from the wrong class<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2010, 2011, 2012, 2013, 2014
Raffaello D. Di Napoli
This file is part of Abaclade.
Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Abaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
Public License for more details.
You should have received a copy of the GNU General Public License along with Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#include <abaclade.hxx>
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::text::utf8_char_traits
namespace abc {
namespace text {
// Optimization 1: odd indices would have the same values as the preceding even ones, so the number
// of elements can be cut in half.
// Optimization 2: the maximum length is less than 0xf, so each value is encoded in a nibble instead
// of a full byte.
//
// In the end, the lead byte is treated like this:
//
// ┌─────────────┬──────────────┬────────┐
// │ 7 6 5 4 3 2 │ 1 │ 0 │
// ├─────────────┼──────────────┼────────┤
// │ byte index │ nibble index │ unused │
// └─────────────┴──────────────┴────────┘
//
// See utf8_char_traits::lead_char_to_codepoint_size() for the actual code accessing this array.
uint8_t const utf8_char_traits::smc_acbCpSizesByLeadChar[] = {
// 0xxxxxxx
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
// 10xxxxxx – invalid (cannot be start of a sequence), so just skip it.
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
// 110xxxxx
0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
// 1110xxxx
0x33, 0x33, 0x33, 0x33,
// 11110xxx
0x44, 0x44,
// These are either overlong (code points encoded using more bytes than necessary) or invalid
// (the resulting symbol would be out of Unicode code point range).
// 111110xx
0x55,
// 1111110x same as above, and 1111111x is invalid (not UTF-8), so just skip it.
0x16
};
uint8_t const utf8_char_traits::smc_acbitShiftMask[] = {
// 0xxxxxxx 110xxxxx 1110xxxx 11110xxx 111110xx 1111110x
0, 2, 3, 4, 5, 6
};
/*static*/ char8_t * utf8_char_traits::codepoint_to_chars(char32_t cp, char8_t * pchDstBegin) {
ABC_TRACE_FUNC(cp, pchDstBegin);
// Compute the length of the UTF-8 sequence for this code point.
unsigned cbSeq;
if (cp <= 0x00007f) {
// Encode xxx xxxx as 0xxxxxxx.
cbSeq = 1;
} else if (cp <= 0x0007ff) {
// Encode xxx xxyy yyyy as 110xxxxx 10yyyyyy.
cbSeq = 2;
} else if (cp <= 0x00ffff) {
// Encode xxxx yyyy yyzz zzzz as 1110xxxx 10yyyyyy 10zzzzzz.
cbSeq = 3;
} else /*if (cp <= 0x10ffff)*/ {
// Encode w wwxx xxxx yyyy yyzz zzzz as 11110www 10xxxxxx 10yyyyyy 10zzzzzz.
cbSeq = 4;
}
// Calculate where the sequence will end, and write each byte backwards from there.
char8_t * pchDstEnd(pchDstBegin + cbSeq);
--cbSeq;
char8_t iSeqIndicator(cont_length_to_seq_indicator(cbSeq));
char8_t * pchDst(pchDstEnd);
while (cbSeq--) {
// Each trailing byte uses 6 bits.
*--pchDst = char8_t(0x80 | (cp & 0x3f));
cp >>= 6;
}
// The remaining code point bits (after >> 6 * (cbSeq - 1)) make up what goes in the lead byte.
*--pchDst = iSeqIndicator | char8_t(cp);
return pchDstEnd;
}
} //namespace text
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::text::utf16_char_traits
namespace abc {
namespace text {
/*static*/ char16_t * utf16_char_traits::codepoint_to_chars(char32_t cp, char16_t * pchDstBegin) {
ABC_TRACE_FUNC(cp, pchDstBegin);
char16_t * pchDst(pchDstBegin);
if (cp > 0x00ffff) {
// The code point requires two UTF-16 characters: generate a surrogate pair.
cp -= 0x10000;
*pchDst++ = char16_t(0xd800 | ((cp & 0x0ffc00) >> 10));
*pchDst++ = char16_t(0xdc00 | (cp & 0x0003ff) );
} else {
// The code point fits in a single UTF-16 character.
*pchDst++ = char16_t(cp);
}
return pchDst;
}
} //namespace text
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>// Copyright (C) 2014 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
//// This library is free software; you can redistribute it and/or
//// modify it under the terms of the GNU Lesser General Public
//// License version 2.1 as published by the Free Software Foundation.
////
//// This library is distributed in the hope that it will be useful,
//// but WITHOUT ANY WARRANTY; without even the implied warranty of
//// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//// Lesser General Public License for more details.
////
//// You should have received a copy of the GNU Lesser General Public
//// License along with this library; if not, write to the Free Software
//// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
//USA
#ifndef JUBATUS_CORE_FRAMEWORK_MODEL_HPP_
#define JUBATUS_CORE_FRAMEWORK_MODEL_HPP_
#include "../common/version.hpp"
#include "packer.hpp"
namespace jubatus {
namespace core {
namespace framework {
// public interface for Jubatus users
class model {
public:
virtual ~model();
// TODO(unknown): Replace pack/unpack arguments
//virtual void save(packer&) const = 0;
//virtual void load(const msgpack::object&) = 0;
virtual void pack(msgpack::packer<msgpack::sbuffer>& packer) const = 0;
virtual void unpack(msgpack::object o) = 0;
virtual void clear();
};
} // namespace framework
} // namespace core
} // namespace jubatus
#endif // JUBATUS_CORE_FRAMEWORK_MODEL_HPP_
<commit_msg>Change framework::model::pack function interface<commit_after>// Copyright (C) 2014 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
//// This library is free software; you can redistribute it and/or
//// modify it under the terms of the GNU Lesser General Public
//// License version 2.1 as published by the Free Software Foundation.
////
//// This library is distributed in the hope that it will be useful,
//// but WITHOUT ANY WARRANTY; without even the implied warranty of
//// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//// Lesser General Public License for more details.
////
//// You should have received a copy of the GNU Lesser General Public
//// License along with this library; if not, write to the Free Software
//// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
//USA
#ifndef JUBATUS_CORE_FRAMEWORK_MODEL_HPP_
#define JUBATUS_CORE_FRAMEWORK_MODEL_HPP_
#include "../common/version.hpp"
#include "packer.hpp"
namespace jubatus {
namespace core {
namespace framework {
// public interface for Jubatus users
class model {
public:
virtual ~model();
virtual void pack(framework::packer& packer) const = 0;
virtual void unpack(msgpack::object o) = 0;
virtual void clear();
};
} // namespace framework
} // namespace core
} // namespace jubatus
#endif // JUBATUS_CORE_FRAMEWORK_MODEL_HPP_
<|endoftext|> |
<commit_before>/* Copyright (c) 2017 Hans-Kristian Arntzen
*
* 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 "shader.hpp"
#include "device.hpp"
#include "spirv_cross.hpp"
using namespace std;
using namespace spirv_cross;
using namespace Util;
namespace Vulkan
{
PipelineLayout::PipelineLayout(Device *device, const CombinedResourceLayout &layout)
: Cookie(device)
, device(device)
, layout(layout)
{
VkDescriptorSetLayout layouts[VULKAN_NUM_DESCRIPTOR_SETS] = {};
unsigned num_sets = 0;
for (unsigned i = 0; i < VULKAN_NUM_DESCRIPTOR_SETS; i++)
{
set_allocators[i] = device->request_descriptor_set_allocator(layout.sets[i]);
layouts[i] = set_allocators[i]->get_layout();
if (layout.descriptor_set_mask & (1u << i))
num_sets = i + 1;
}
unsigned num_ranges = 0;
VkPushConstantRange ranges[static_cast<unsigned>(ShaderStage::Count)];
for (auto &range : layout.ranges)
{
if (range.size != 0)
{
bool unique = true;
for (unsigned i = 0; i < num_ranges; i++)
{
// Try to merge equivalent ranges for multiple stages.
if (ranges[i].offset == range.offset && ranges[i].size == range.size)
{
unique = false;
ranges[i].stageFlags |= range.stageFlags;
break;
}
}
if (unique)
ranges[num_ranges++] = range;
}
}
memcpy(this->layout.ranges, ranges, num_ranges * sizeof(ranges[0]));
this->layout.num_ranges = num_ranges;
VkPipelineLayoutCreateInfo info = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO };
if (num_sets)
{
info.setLayoutCount = num_sets;
info.pSetLayouts = layouts;
}
if (num_ranges)
{
info.pushConstantRangeCount = num_ranges;
info.pPushConstantRanges = ranges;
}
if (vkCreatePipelineLayout(device->get_device(), &info, nullptr, &pipe_layout) != VK_SUCCESS)
LOGE("Failed to create pipeline layout.\n");
}
PipelineLayout::~PipelineLayout()
{
if (pipe_layout != VK_NULL_HANDLE)
vkDestroyPipelineLayout(device->get_device(), pipe_layout, nullptr);
}
Shader::Shader(VkDevice device, ShaderStage stage, const uint32_t *data, size_t size)
: device(device)
, stage(stage)
{
VkShaderModuleCreateInfo info = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO };
info.codeSize = size;
info.pCode = data;
if (vkCreateShaderModule(device, &info, nullptr, &module) != VK_SUCCESS)
LOGE("Failed to create shader module.\n");
vector<uint32_t> code(data, data + size / sizeof(uint32_t));
Compiler compiler(move(code));
auto resources = compiler.get_shader_resources();
for (auto &image : resources.sampled_images)
{
auto set = compiler.get_decoration(image.id, spv::DecorationDescriptorSet);
auto binding = compiler.get_decoration(image.id, spv::DecorationBinding);
auto &type = compiler.get_type(image.base_type_id);
if (type.image.dim == spv::DimBuffer)
layout.sets[set].sampled_buffer_mask |= 1u << binding;
else
layout.sets[set].sampled_image_mask |= 1u << binding;
layout.sets[set].stages |= 1u << static_cast<unsigned>(stage);
if (compiler.get_type(type.image.type).basetype == SPIRType::BaseType::Float)
layout.sets[set].fp_mask |= 1u << binding;
}
for (auto &image : resources.subpass_inputs)
{
auto set = compiler.get_decoration(image.id, spv::DecorationDescriptorSet);
auto binding = compiler.get_decoration(image.id, spv::DecorationBinding);
layout.sets[set].input_attachment_mask |= 1u << binding;
layout.sets[set].stages |= 1u << static_cast<unsigned>(stage);
auto &type = compiler.get_type(image.base_type_id);
if (compiler.get_type(type.image.type).basetype == SPIRType::BaseType::Float)
layout.sets[set].fp_mask |= 1u << binding;
}
for (auto &image : resources.storage_images)
{
auto set = compiler.get_decoration(image.id, spv::DecorationDescriptorSet);
auto binding = compiler.get_decoration(image.id, spv::DecorationBinding);
layout.sets[set].storage_image_mask |= 1u << binding;
layout.sets[set].stages |= 1u << static_cast<unsigned>(stage);
auto &type = compiler.get_type(image.base_type_id);
if (compiler.get_type(type.image.type).basetype == SPIRType::BaseType::Float)
layout.sets[set].fp_mask |= 1u << binding;
}
for (auto &buffer : resources.uniform_buffers)
{
auto set = compiler.get_decoration(buffer.id, spv::DecorationDescriptorSet);
auto binding = compiler.get_decoration(buffer.id, spv::DecorationBinding);
layout.sets[set].uniform_buffer_mask |= 1u << binding;
layout.sets[set].stages |= 1u << static_cast<unsigned>(stage);
}
for (auto &buffer : resources.storage_buffers)
{
auto set = compiler.get_decoration(buffer.id, spv::DecorationDescriptorSet);
auto binding = compiler.get_decoration(buffer.id, spv::DecorationBinding);
layout.sets[set].storage_buffer_mask |= 1u << binding;
layout.sets[set].stages |= 1u << static_cast<unsigned>(stage);
}
if (stage == ShaderStage::Vertex)
{
for (auto &attrib : resources.stage_inputs)
{
auto location = compiler.get_decoration(attrib.id, spv::DecorationLocation);
layout.attribute_mask |= 1u << location;
}
}
else if (stage == ShaderStage::Fragment)
{
for (auto &attrib : resources.stage_outputs)
{
auto location = compiler.get_decoration(attrib.id, spv::DecorationLocation);
layout.render_target_mask |= 1u << location;
}
}
if (!resources.push_constant_buffers.empty())
{
#ifdef VULKAN_DEBUG
// The validation layers are too conservative here, but this is just a performance pessimization.
size_t size =
compiler.get_declared_struct_size(compiler.get_type(resources.push_constant_buffers.front().base_type_id));
layout.push_constant_offset = 0;
layout.push_constant_range = size;
#else
auto ranges = compiler.get_active_buffer_ranges(resources.push_constant_buffers.front().id);
size_t minimum = ~0u;
size_t maximum = 0;
if (!ranges.empty())
{
for (auto &range : ranges)
{
minimum = min(minimum, range.offset);
maximum = max(maximum, range.offset + range.range);
}
layout.push_constant_offset = minimum;
layout.push_constant_range = maximum - minimum;
}
#endif
}
}
Shader::~Shader()
{
if (module)
vkDestroyShaderModule(device, module, nullptr);
}
void Program::set_shader(ShaderHandle handle)
{
shaders[static_cast<unsigned>(handle->get_stage())] = handle;
}
Program::Program(Device *device)
: Cookie(device)
, device(device)
{
}
VkPipeline Program::get_graphics_pipeline(Hash hash) const
{
auto itr = graphics_pipelines.find(hash);
if (itr != end(graphics_pipelines))
return itr->second;
else
return VK_NULL_HANDLE;
}
void Program::add_graphics_pipeline(Hash hash, VkPipeline pipeline)
{
VK_ASSERT(graphics_pipelines[hash] == VK_NULL_HANDLE);
graphics_pipelines[hash] = pipeline;
}
Program::~Program()
{
if (compute_pipeline != VK_NULL_HANDLE)
device->destroy_pipeline(compute_pipeline);
for (auto &pipe : graphics_pipelines)
device->destroy_pipeline(pipe.second);
}
}
<commit_msg>Always specify the declared push constant range.<commit_after>/* Copyright (c) 2017 Hans-Kristian Arntzen
*
* 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 "shader.hpp"
#include "device.hpp"
#include "spirv_cross.hpp"
using namespace std;
using namespace spirv_cross;
using namespace Util;
namespace Vulkan
{
PipelineLayout::PipelineLayout(Device *device, const CombinedResourceLayout &layout)
: Cookie(device)
, device(device)
, layout(layout)
{
VkDescriptorSetLayout layouts[VULKAN_NUM_DESCRIPTOR_SETS] = {};
unsigned num_sets = 0;
for (unsigned i = 0; i < VULKAN_NUM_DESCRIPTOR_SETS; i++)
{
set_allocators[i] = device->request_descriptor_set_allocator(layout.sets[i]);
layouts[i] = set_allocators[i]->get_layout();
if (layout.descriptor_set_mask & (1u << i))
num_sets = i + 1;
}
unsigned num_ranges = 0;
VkPushConstantRange ranges[static_cast<unsigned>(ShaderStage::Count)];
for (auto &range : layout.ranges)
{
if (range.size != 0)
{
bool unique = true;
for (unsigned i = 0; i < num_ranges; i++)
{
// Try to merge equivalent ranges for multiple stages.
if (ranges[i].offset == range.offset && ranges[i].size == range.size)
{
unique = false;
ranges[i].stageFlags |= range.stageFlags;
break;
}
}
if (unique)
ranges[num_ranges++] = range;
}
}
memcpy(this->layout.ranges, ranges, num_ranges * sizeof(ranges[0]));
this->layout.num_ranges = num_ranges;
VkPipelineLayoutCreateInfo info = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO };
if (num_sets)
{
info.setLayoutCount = num_sets;
info.pSetLayouts = layouts;
}
if (num_ranges)
{
info.pushConstantRangeCount = num_ranges;
info.pPushConstantRanges = ranges;
}
if (vkCreatePipelineLayout(device->get_device(), &info, nullptr, &pipe_layout) != VK_SUCCESS)
LOGE("Failed to create pipeline layout.\n");
}
PipelineLayout::~PipelineLayout()
{
if (pipe_layout != VK_NULL_HANDLE)
vkDestroyPipelineLayout(device->get_device(), pipe_layout, nullptr);
}
Shader::Shader(VkDevice device, ShaderStage stage, const uint32_t *data, size_t size)
: device(device)
, stage(stage)
{
VkShaderModuleCreateInfo info = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO };
info.codeSize = size;
info.pCode = data;
if (vkCreateShaderModule(device, &info, nullptr, &module) != VK_SUCCESS)
LOGE("Failed to create shader module.\n");
vector<uint32_t> code(data, data + size / sizeof(uint32_t));
Compiler compiler(move(code));
auto resources = compiler.get_shader_resources();
for (auto &image : resources.sampled_images)
{
auto set = compiler.get_decoration(image.id, spv::DecorationDescriptorSet);
auto binding = compiler.get_decoration(image.id, spv::DecorationBinding);
auto &type = compiler.get_type(image.base_type_id);
if (type.image.dim == spv::DimBuffer)
layout.sets[set].sampled_buffer_mask |= 1u << binding;
else
layout.sets[set].sampled_image_mask |= 1u << binding;
layout.sets[set].stages |= 1u << static_cast<unsigned>(stage);
if (compiler.get_type(type.image.type).basetype == SPIRType::BaseType::Float)
layout.sets[set].fp_mask |= 1u << binding;
}
for (auto &image : resources.subpass_inputs)
{
auto set = compiler.get_decoration(image.id, spv::DecorationDescriptorSet);
auto binding = compiler.get_decoration(image.id, spv::DecorationBinding);
layout.sets[set].input_attachment_mask |= 1u << binding;
layout.sets[set].stages |= 1u << static_cast<unsigned>(stage);
auto &type = compiler.get_type(image.base_type_id);
if (compiler.get_type(type.image.type).basetype == SPIRType::BaseType::Float)
layout.sets[set].fp_mask |= 1u << binding;
}
for (auto &image : resources.storage_images)
{
auto set = compiler.get_decoration(image.id, spv::DecorationDescriptorSet);
auto binding = compiler.get_decoration(image.id, spv::DecorationBinding);
layout.sets[set].storage_image_mask |= 1u << binding;
layout.sets[set].stages |= 1u << static_cast<unsigned>(stage);
auto &type = compiler.get_type(image.base_type_id);
if (compiler.get_type(type.image.type).basetype == SPIRType::BaseType::Float)
layout.sets[set].fp_mask |= 1u << binding;
}
for (auto &buffer : resources.uniform_buffers)
{
auto set = compiler.get_decoration(buffer.id, spv::DecorationDescriptorSet);
auto binding = compiler.get_decoration(buffer.id, spv::DecorationBinding);
layout.sets[set].uniform_buffer_mask |= 1u << binding;
layout.sets[set].stages |= 1u << static_cast<unsigned>(stage);
}
for (auto &buffer : resources.storage_buffers)
{
auto set = compiler.get_decoration(buffer.id, spv::DecorationDescriptorSet);
auto binding = compiler.get_decoration(buffer.id, spv::DecorationBinding);
layout.sets[set].storage_buffer_mask |= 1u << binding;
layout.sets[set].stages |= 1u << static_cast<unsigned>(stage);
}
if (stage == ShaderStage::Vertex)
{
for (auto &attrib : resources.stage_inputs)
{
auto location = compiler.get_decoration(attrib.id, spv::DecorationLocation);
layout.attribute_mask |= 1u << location;
}
}
else if (stage == ShaderStage::Fragment)
{
for (auto &attrib : resources.stage_outputs)
{
auto location = compiler.get_decoration(attrib.id, spv::DecorationLocation);
layout.render_target_mask |= 1u << location;
}
}
if (!resources.push_constant_buffers.empty())
{
// Need to declare the entire block.
size_t size =
compiler.get_declared_struct_size(compiler.get_type(resources.push_constant_buffers.front().base_type_id));
layout.push_constant_offset = 0;
layout.push_constant_range = size;
}
}
Shader::~Shader()
{
if (module)
vkDestroyShaderModule(device, module, nullptr);
}
void Program::set_shader(ShaderHandle handle)
{
shaders[static_cast<unsigned>(handle->get_stage())] = handle;
}
Program::Program(Device *device)
: Cookie(device)
, device(device)
{
}
VkPipeline Program::get_graphics_pipeline(Hash hash) const
{
auto itr = graphics_pipelines.find(hash);
if (itr != end(graphics_pipelines))
return itr->second;
else
return VK_NULL_HANDLE;
}
void Program::add_graphics_pipeline(Hash hash, VkPipeline pipeline)
{
VK_ASSERT(graphics_pipelines[hash] == VK_NULL_HANDLE);
graphics_pipelines[hash] = pipeline;
}
Program::~Program()
{
if (compute_pipeline != VK_NULL_HANDLE)
device->destroy_pipeline(compute_pipeline);
for (auto &pipe : graphics_pipelines)
device->destroy_pipeline(pipe.second);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2017, Franz Hollerer.
// SPDX-License-Identifier: MIT
#include <iostream>
#include <catch/catch.hpp>
#include <hodea/core/cstdint.hpp>
#include <hodea/core/cpu_endian.hpp>
using namespace hodea;
TEST_CASE("Cpu endian: is_cpu_le()", "[is_cpu_le]")
{
REQUIRE(is_cpu_le() == HONDEA_IS_CPU_LE);
}
TEST_CASE("Cpu endian: is_cpu_be()", "[is_cpu_be]")
{
REQUIRE(is_cpu_be() == HONDEA_IS_CPU_BE);
}
#if HONDEA_IS_CPU_LE == true
TEST_CASE("Cpu endian: cpu_to_le16()", "[cpu_to_le16]")
{
uint16_t x = 0x1234;
REQUIRE(cpu_to_le16(x) == x);
}
TEST_CASE("Cpu endian: cpu_to_le32()", "[cpu_to_le32]")
{
uint32_t x = 0x12345678;
REQUIRE(cpu_to_le32(x) == x);
}
TEST_CASE("Cpu endian: cpu_to_le64()", "[cpu_to_le64]")
{
uint64_t x = 0x123456789abcdefULL;
REQUIRE(cpu_to_le64(x) == x);
}
TEST_CASE("Cpu endian: cpu_to_be16()", "[cpu_to_be16]")
{
uint16_t x = 0x1234;
REQUIRE(cpu_to_be16(x) == uswap16(x));
}
TEST_CASE("Cpu endian: cpu_to_be32()", "[cpu_to_be32]")
{
uint32_t x = 0x12345678;
REQUIRE(cpu_to_be32(x) == uswap32(x));
}
TEST_CASE("Cpu endian: cpu_to_be64()", "[cpu_to_be64]")
{
uint64_t x = 0x123456789abcdefULL;
REQUIRE(cpu_to_be64(x) == uswap64(x));
}
#else
TEST_CASE("Cpu endian: cpu_to_le16()", "[cpu_to_le16]")
{
uint16_t x = 0x1234;
REQUIRE(cpu_to_le16(x) == uswap16(x));
}
TEST_CASE("Cpu endian: cpu_to_le32()", "[cpu_to_le32]")
{
uint32_t x = 0x12345678;
REQUIRE(cpu_to_le32(x) == uswap32(x));
}
TEST_CASE("Cpu endian: cpu_to_le64()", "[cpu_to_le64]")
{
uint64_t x = 0x123456789abcdefULL;
REQUIRE(cpu_to_le64(x) == uswap64(x));
}
TEST_CASE("Cpu endian: cpu_to_be16()", "[cpu_to_be16]")
{
uint16_t x = 0x1234;
REQUIRE(cpu_to_be16(x) == x);
}
TEST_CASE("Cpu endian: cpu_to_be32()", "[cpu_to_be32]")
{
uint32_t x = 0x12345678;
REQUIRE(cpu_to_be32(x) == x);
}
TEST_CASE("Cpu endian: cpu_to_be64()", "[cpu_to_be64]")
{
uint64_t x = 0x123456789abcdefULL;
REQUIRE(cpu_to_be64(x) == x);
}
#endif
TEST_CASE("Cpu endian: le16_to_cpu()", "[le16_to_cpu]")
{
uint16_t x = 0x1234;
REQUIRE(le16_to_cpu(cpu_to_le16(x)) == x);
}
TEST_CASE("Cpu endian: le32_to_cpu()", "[le32_to_cpu]")
{
uint32_t x = 0x12345678;
REQUIRE(le32_to_cpu(cpu_to_le32(x)) == x);
}
TEST_CASE("Cpu endian: le64_to_cpu()", "[le64_to_cpu]")
{
uint64_t x = 0x123456789abcdefULL;
REQUIRE(le64_to_cpu(cpu_to_le64(x)) == x);
}
TEST_CASE("Cpu endian: be16_to_cpu()", "[be16_to_cpu]")
{
uint16_t x = 0x1234;
REQUIRE(be16_to_cpu(cpu_to_be16(x)) == x);
}
TEST_CASE("Cpu endian: be32_to_cpu()", "[be32_to_cpu]")
{
uint32_t x = 0x12345678;
REQUIRE(be32_to_cpu(cpu_to_be32(x)) == x);
}
TEST_CASE("Cpu endian: be64_to_cpu()", "[be64_to_cpu]")
{
uint64_t x = 0x123456789abcdefULL;
REQUIRE(be64_to_cpu(cpu_to_be64(x)) == x);
}
<commit_msg>typo fixed<commit_after>// Copyright (c) 2017, Franz Hollerer.
// SPDX-License-Identifier: MIT
#include <iostream>
#include <catch/catch.hpp>
#include <hodea/core/cstdint.hpp>
#include <hodea/core/cpu_endian.hpp>
using namespace hodea;
TEST_CASE("Cpu endian: is_cpu_le()", "[is_cpu_le]")
{
REQUIRE(is_cpu_le() == HODEA_IS_CPU_LE);
}
TEST_CASE("Cpu endian: is_cpu_be()", "[is_cpu_be]")
{
REQUIRE(is_cpu_be() == HODEA_IS_CPU_BE);
}
#if HODEA_IS_CPU_LE == true
TEST_CASE("Cpu endian: cpu_to_le16()", "[cpu_to_le16]")
{
uint16_t x = 0x1234;
REQUIRE(cpu_to_le16(x) == x);
}
TEST_CASE("Cpu endian: cpu_to_le32()", "[cpu_to_le32]")
{
uint32_t x = 0x12345678;
REQUIRE(cpu_to_le32(x) == x);
}
TEST_CASE("Cpu endian: cpu_to_le64()", "[cpu_to_le64]")
{
uint64_t x = 0x123456789abcdefULL;
REQUIRE(cpu_to_le64(x) == x);
}
TEST_CASE("Cpu endian: cpu_to_be16()", "[cpu_to_be16]")
{
uint16_t x = 0x1234;
REQUIRE(cpu_to_be16(x) == uswap16(x));
}
TEST_CASE("Cpu endian: cpu_to_be32()", "[cpu_to_be32]")
{
uint32_t x = 0x12345678;
REQUIRE(cpu_to_be32(x) == uswap32(x));
}
TEST_CASE("Cpu endian: cpu_to_be64()", "[cpu_to_be64]")
{
uint64_t x = 0x123456789abcdefULL;
REQUIRE(cpu_to_be64(x) == uswap64(x));
}
#else
TEST_CASE("Cpu endian: cpu_to_le16()", "[cpu_to_le16]")
{
uint16_t x = 0x1234;
REQUIRE(cpu_to_le16(x) == uswap16(x));
}
TEST_CASE("Cpu endian: cpu_to_le32()", "[cpu_to_le32]")
{
uint32_t x = 0x12345678;
REQUIRE(cpu_to_le32(x) == uswap32(x));
}
TEST_CASE("Cpu endian: cpu_to_le64()", "[cpu_to_le64]")
{
uint64_t x = 0x123456789abcdefULL;
REQUIRE(cpu_to_le64(x) == uswap64(x));
}
TEST_CASE("Cpu endian: cpu_to_be16()", "[cpu_to_be16]")
{
uint16_t x = 0x1234;
REQUIRE(cpu_to_be16(x) == x);
}
TEST_CASE("Cpu endian: cpu_to_be32()", "[cpu_to_be32]")
{
uint32_t x = 0x12345678;
REQUIRE(cpu_to_be32(x) == x);
}
TEST_CASE("Cpu endian: cpu_to_be64()", "[cpu_to_be64]")
{
uint64_t x = 0x123456789abcdefULL;
REQUIRE(cpu_to_be64(x) == x);
}
#endif
TEST_CASE("Cpu endian: le16_to_cpu()", "[le16_to_cpu]")
{
uint16_t x = 0x1234;
REQUIRE(le16_to_cpu(cpu_to_le16(x)) == x);
}
TEST_CASE("Cpu endian: le32_to_cpu()", "[le32_to_cpu]")
{
uint32_t x = 0x12345678;
REQUIRE(le32_to_cpu(cpu_to_le32(x)) == x);
}
TEST_CASE("Cpu endian: le64_to_cpu()", "[le64_to_cpu]")
{
uint64_t x = 0x123456789abcdefULL;
REQUIRE(le64_to_cpu(cpu_to_le64(x)) == x);
}
TEST_CASE("Cpu endian: be16_to_cpu()", "[be16_to_cpu]")
{
uint16_t x = 0x1234;
REQUIRE(be16_to_cpu(cpu_to_be16(x)) == x);
}
TEST_CASE("Cpu endian: be32_to_cpu()", "[be32_to_cpu]")
{
uint32_t x = 0x12345678;
REQUIRE(be32_to_cpu(cpu_to_be32(x)) == x);
}
TEST_CASE("Cpu endian: be64_to_cpu()", "[be64_to_cpu]")
{
uint64_t x = 0x123456789abcdefULL;
REQUIRE(be64_to_cpu(cpu_to_be64(x)) == x);
}
<|endoftext|> |
<commit_before>#include <config.h>
// dune-multiscale
// Copyright Holders: Patrick Henning, Rene Milk
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#include "localoperator.hh"
#include <assert.h>
#include <boost/assert.hpp>
#include <dune/common/exceptions.hh>
#include <dune/multiscale/problems/selector.hh>
#include <dune/stuff/common/parameter/configcontainer.hh>
#include <dune/stuff/fem/matrix_object.hh>
#include <dune/stuff/fem/localmatrix_proxy.hh>
#include <dune/stuff/discretefunction/projection/heterogenous.hh>
#include <dune/stuff/fem/functions/integrals.hh>
#include <dune/multiscale/tools/misc.hh>
#include <dune/multiscale/msfem/localproblems/localproblemsolver.hh>
#include <dune/common/fmatrix.hh>
#include <dune/multiscale/common/traits.hh>
#include <dune/multiscale/msfem/localproblems/localproblemsolver.hh>
#include <dune/stuff/common/filesystem.hh>
#include <dune/stuff/fem/functions/checks.hh>
#include <dune/gdt/operators/projections.hh>
#include <dune/gdt/operators/prolongations.hh>
#include <dune/gdt/spaces/constraints.hh>
#include <dune/gdt/functionals/l2.hh>
namespace Dune {
namespace Multiscale {
namespace MsFEM {
LocalProblemOperator::LocalProblemOperator(const CoarseSpaceType& coarse_space,
const LocalGridDiscreteFunctionSpaceType& space,
const DiffusionOperatorType& diffusion_op)
: localSpace_(space)
, diffusion_operator_(diffusion_op)
, coarse_space_(coarse_space)
, system_matrix_(space.mapper().size(), space.mapper().size(),
EllipticOperatorType::pattern(space))
, system_assembler_(localSpace_)
, elliptic_operator_(diffusion_operator_, system_matrix_, localSpace_)
, constraints_(Problem::getModelData()->subBoundaryInfo(), space.mapper().maxNumDofs(), space.mapper().maxNumDofs())
{
assemble_matrix();
}
void LocalProblemOperator::assemble_matrix()
// x_T is the barycenter of the macro grid element T
{
system_assembler_.add(elliptic_operator_);
} // assemble_matrix
void LocalProblemOperator::assemble_all_local_rhs(const CoarseEntityType& coarseEntity,
MsFEMTraits::LocalSolutionVectorType& allLocalRHS) {
BOOST_ASSERT_MSG(allLocalRHS.size() > 0, "You need to preallocate the necessary space outside this function!");
//! @todo correct the error message below (+1 for simplecial, +2 for arbitrary), as there's no finespace any longer
// BOOST_ASSERT_MSG(
// (DSG::is_simplex_grid(coarse_space_) && allLocalRHS.size() == GridType::dimension + 1) ||
// (!(DSG::is_simplex_grid(coarse_space_)) &&
// static_cast<long long>(allLocalRHS.size()) ==
// static_cast<long long>(specifier.fineSpace().mapper().maxNumDofs() + 2)),
// "You need to allocate storage space for the correctors for all unit vector/all coarse basis functions"
// " and the dirichlet- and neuman corrector");
// build unit vectors (needed for cases where rhs is assembled for unit vectors instead of coarse
// base functions)
constexpr auto dimension = CommonTraits::GridType::dimension;
CommonTraits::JacobianRangeType unitVectors[dimension];
for (int i = 0; i < dimension; ++i) {
for (int j = 0; j < dimension; ++j) {
if (i == j) {
unitVectors[i][0][j] = 1.0;
} else {
unitVectors[i][0][j] = 0.0;
}
}
}
LocalGridDiscreteFunctionType dirichletExtension(localSpace_, "dirichletExtension");
CommonTraits::DiscreteFunctionType dirichletExtensionCoarse(coarse_space_, "Dirichlet Extension Coarse");
GDT::SystemAssembler<CommonTraits::DiscreteFunctionSpaceType> global_system_assembler_(coarse_space_);
GDT::Operators::DirichletProjectionLocalizable< CommonTraits::GridViewType, CommonTraits::DirichletDataType,
CommonTraits::DiscreteFunctionType >
coarse_dirichlet_projection_operator(*(coarse_space_.grid_view()),
DMP::getModelData()->boundaryInfo(),
*DMP::getDirichletData(),
dirichletExtensionCoarse);
global_system_assembler_.add(coarse_dirichlet_projection_operator, new GDT::ApplyOn::BoundaryEntities<CommonTraits::GridViewType>());
global_system_assembler_.assemble();
GDT::Operators::LagrangeProlongation<CommonTraits::GridViewType> projection(*coarse_space_.grid_view());
projection.apply(dirichletExtensionCoarse, dirichletExtension);
const bool is_simplex_grid = DSG::is_simplex_grid(coarse_space_);
const auto numBoundaryCorrectors = is_simplex_grid ? 1u : 2u;
const auto numInnerCorrectors = allLocalRHS.size() - numBoundaryCorrectors;
//!*********** anfang neu gdt
std::size_t coarseBaseFunc = 0;
for (; coarseBaseFunc < numInnerCorrectors; ++coarseBaseFunc)
{
if (is_simplex_grid) {
// diffusionsauswertung in unitVectors[coarseBaseFunc]
} else {
// diffusionsauswertung in
// const DomainType quadInCoarseLocal = coarseEntity.geometry().local(QuadraturPunkt);
// coarseBaseSet.jacobianAll(quadInCoarseLocal, coarseBaseFuncJacs);
}
// baseSet.jacobianAll(quadrature[quadraturePoint], gradient_phi);
// for (unsigned int i = 0; i < numBaseFunctions; ++i) {
// rhsLocalFunction[i] -= weight * (diffusions_auswertung * gradient_phi[i][0]);
// }
}
coarseBaseFunc++; // coarseBaseFunc == numInnerCorrectors
//neumann correktor
GDT::Functionals::L2Face< CommonTraits::NeumannDataType, CommonTraits::GdtVectorType, MsFEMTraits::LocalSpaceType >
neumann_functional(*Dune::Multiscale::Problem::getNeumannData(),
allLocalRHS[coarseBaseFunc]->vector(), localSpace_);
system_assembler_.add(neumann_functional);
coarseBaseFunc++;// coarseBaseFunc == 1 + numInnerCorrectors
//dirichlet correktor
{
// const auto dirichletLF = dirichletExtension.local_function(entity);
// dirichletLF.jacobian(local_point, dirichletJac);
// diffusion_operator_.diffusiveFlux(global_point, dirichletJac, diffusion);
// for (unsigned int i = 0; i < numBaseFunctions; ++i) {
// rhsLocalFunction[i] -= weight * (diffusion[0] * gradient_phi[i][0]);
// }
}
//dirichlet-0 for all rhs
typedef GDT::ApplyOn::BoundaryEntities< MsFEMTraits::LocalGridViewType > OnLocalBoundaryEntities;
LocalGridDiscreteFunctionType dirichlet_projection(localSpace_);
GDT::Operators::DirichletProjectionLocalizable< MsFEMTraits::LocalGridViewType, CommonTraits::DirichletDataType,
MsFEMTraits::LocalGridDiscreteFunctionType >
dirichlet_projection_operator(*(localSpace_.grid_view()),
allLocalDirichletInfo_,
dirichletZero_,
dirichlet_projection);
system_assembler_.add(dirichlet_projection_operator, new OnLocalBoundaryEntities());
system_assembler_.add(constraints_, system_matrix_, new OnLocalBoundaryEntities());
for (auto& rhs : allLocalRHS )
system_assembler_.add(constraints_, rhs->vector(), new OnLocalBoundaryEntities());
system_assembler_.assemble();
//!*********** ende neu gdt
#if 0 // alter dune-fem code
// get the base function set of the coarse space for the given coarse entity
const auto& coarseBaseSet = coarse_space_.basisFunctionSet(coarseEntity);
std::vector<CoarseBaseFunctionSetType::JacobianRangeType> coarseBaseFuncJacs(coarseBaseSet.size());
// gradient of micro scale base function:
std::vector<JacobianRangeType> gradient_phi(localSpace.blockMapper().maxNumDofs());
std::vector<RangeType> phi(localSpace.blockMapper().maxNumDofs());
for (auto& localGridCell : localSpace) {
const auto& geometry = localGridCell.geometry();
const bool hasBoundaryIntersection = localGridCell.hasBoundaryIntersections();
auto dirichletLF = dirichletExtension.localFunction(localGridCell);
JacobianRangeType dirichletJac(0.0);
for (std::size_t coarseBaseFunc = 0; coarseBaseFunc < allLocalRHS.size(); ++coarseBaseFunc) {
auto rhsLocalFunction = allLocalRHS[coarseBaseFunc]->localFunction(localGridCell);
const auto& baseSet = rhsLocalFunction.basisFunctionSet();
const auto numBaseFunctions = baseSet.size();
// correctors with index < numInnerCorrectors are for the basis functions, corrector at
// position numInnerCorrectors is for the neumann values, corrector at position numInnerCorrectors+1
// for the dirichlet values.
if (coarseBaseFunc < numInnerCorrectors || coarseBaseFunc == numInnerCorrectors + 1) {
const auto quadrature = DSFe::make_quadrature(localGridCell, localSpace);
const auto numQuadraturePoints = quadrature.nop();
for (size_t quadraturePoint = 0; quadraturePoint < numQuadraturePoints; ++quadraturePoint) {
const auto& local_point = quadrature.point(quadraturePoint);
// global point in the subgrid
const auto global_point = geometry.global(local_point);
const double weight = quadrature.weight(quadraturePoint) * geometry.integrationElement(local_point);
JacobianRangeType diffusion(0.0);
if (coarseBaseFunc < numInnerCorrectors) {
if (is_simplex_grid)
diffusion_operator_.diffusiveFlux(global_point, unitVectors[coarseBaseFunc], diffusion);
else {
const DomainType quadInCoarseLocal = coarseEntity.geometry().local(global_point);
coarseBaseSet.jacobianAll(quadInCoarseLocal, coarseBaseFuncJacs);
diffusion_operator_.diffusiveFlux(global_point, coarseBaseFuncJacs[coarseBaseFunc], diffusion);
}
} else {
dirichletLF.jacobian(local_point, dirichletJac);
diffusion_operator_.diffusiveFlux(global_point, dirichletJac, diffusion);
}
baseSet.jacobianAll(quadrature[quadraturePoint], gradient_phi);
for (unsigned int i = 0; i < numBaseFunctions; ++i) {
rhsLocalFunction[i] -= weight * (diffusion[0] * gradient_phi[i][0]);
}
}
}
// boundary integrals
if (coarseBaseFunc == numInnerCorrectors && hasBoundaryIntersection) {
const auto intEnd = localSpace.gridPart().iend(localGridCell);
for (auto iIt = localSpace.gridPart().ibegin(localGridCell); iIt != intEnd; ++iIt) {
const auto& intersection = *iIt;
if (DMP::is_neumann(intersection)) {
const auto orderOfIntegrand =
(CommonTraits::polynomial_order - 1) + 2 * (CommonTraits::polynomial_order + 1);
const auto quadOrder = std::ceil((orderOfIntegrand + 1) / 2);
const auto faceQuad = DSFe::make_quadrature(intersection, localSpace, quadOrder);
RangeType neumannValue(0.0);
const auto numQuadPoints = faceQuad.nop();
// loop over all quadrature points
for (unsigned int iqP = 0; iqP < numQuadPoints; ++iqP) {
// get local coordinate of quadrature point
const auto& xLocal = faceQuad.localPoint(iqP);
const auto& faceGeometry = intersection.geometry();
// the following does not work because subgrid does not implement geometryInInside()
// const auto& insideGeometry = intersection.geometryInInside();
// const typename FaceQuadratureType::CoordinateType& xInInside = insideGeometry.global(xLocal);
// therefore, we have to do stupid things:
const auto& xGlobal = faceGeometry.global(xLocal);
auto insidePtr = intersection.inside();
const auto& insideEntity = *insidePtr;
const auto& xInInside = insideEntity.geometry().local(xGlobal);
const double factor = faceGeometry.integrationElement(xLocal) * faceQuad.weight(iqP);
neumannData.evaluate(xGlobal, neumannValue);
baseSet.evaluateAll(xInInside, phi);
for (unsigned int i = 0; i < numBaseFunctions; ++i) {
rhsLocalFunction[i] -= factor * (neumannValue * phi[i]);
}
}
}
}
}
}
}
#endif
}
void LocalProblemOperator::apply_inverse(const MsFEMTraits::LocalGridDiscreteFunctionType ¤t_rhs, MsFEMTraits::LocalGridDiscreteFunctionType ¤t_solution)
{
if (!current_rhs.dofs_valid())
DUNE_THROW(Dune::InvalidStateException, "Local MsFEM Problem RHS invalid.");
const auto solver =
Dune::Multiscale::Problem::getModelData()->symmetricDiffusion() ? std::string("cg") : std::string("bcgs");
typedef BackendChooser<LocalGridDiscreteFunctionSpaceType>::InverseOperatorType LocalInverseOperatorType;
const auto localProblemSolver = DSC::make_unique<LocalInverseOperatorType>(system_matrix_, current_rhs.vector());
/*1e-8, 1e-8, 20000,
DSC_CONFIG_GET("msfem.localproblemsolver_verbose", false), solver,
DSC_CONFIG_GET("preconditioner_type", std::string("sor")), 1);*/
localProblemSolver->apply(current_rhs.vector(), current_solution.vector());
if (!current_solution.dofs_valid())
DUNE_THROW(Dune::InvalidStateException, "Current solution of the local msfem problem invalid!");
}
} // namespace MsFEM {
} // namespace Multiscale {
} // namespace Dune {
<commit_msg>removed more usages of stuff header<commit_after>#include <config.h>
// dune-multiscale
// Copyright Holders: Patrick Henning, Rene Milk
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#include "localoperator.hh"
#include <assert.h>
#include <boost/assert.hpp>
#include <dune/common/exceptions.hh>
#include <dune/multiscale/problems/selector.hh>
#include <dune/stuff/common/parameter/configcontainer.hh>
#include <dune/stuff/fem/localmatrix_proxy.hh>
#include <dune/stuff/discretefunction/projection/heterogenous.hh>
#include <dune/stuff/fem/functions/integrals.hh>
#include <dune/multiscale/tools/misc.hh>
#include <dune/multiscale/msfem/localproblems/localproblemsolver.hh>
#include <dune/common/fmatrix.hh>
#include <dune/multiscale/common/traits.hh>
#include <dune/multiscale/msfem/localproblems/localproblemsolver.hh>
#include <dune/stuff/common/filesystem.hh>
#include <dune/stuff/fem/functions/checks.hh>
#include <dune/gdt/operators/projections.hh>
#include <dune/gdt/operators/prolongations.hh>
#include <dune/gdt/spaces/constraints.hh>
#include <dune/gdt/functionals/l2.hh>
namespace Dune {
namespace Multiscale {
namespace MsFEM {
LocalProblemOperator::LocalProblemOperator(const CoarseSpaceType& coarse_space,
const LocalGridDiscreteFunctionSpaceType& space,
const DiffusionOperatorType& diffusion_op)
: localSpace_(space)
, diffusion_operator_(diffusion_op)
, coarse_space_(coarse_space)
, system_matrix_(space.mapper().size(), space.mapper().size(),
EllipticOperatorType::pattern(space))
, system_assembler_(localSpace_)
, elliptic_operator_(diffusion_operator_, system_matrix_, localSpace_)
, constraints_(Problem::getModelData()->subBoundaryInfo(), space.mapper().maxNumDofs(), space.mapper().maxNumDofs())
{
assemble_matrix();
}
void LocalProblemOperator::assemble_matrix()
// x_T is the barycenter of the macro grid element T
{
system_assembler_.add(elliptic_operator_);
} // assemble_matrix
void LocalProblemOperator::assemble_all_local_rhs(const CoarseEntityType& coarseEntity,
MsFEMTraits::LocalSolutionVectorType& allLocalRHS) {
BOOST_ASSERT_MSG(allLocalRHS.size() > 0, "You need to preallocate the necessary space outside this function!");
//! @todo correct the error message below (+1 for simplecial, +2 for arbitrary), as there's no finespace any longer
// BOOST_ASSERT_MSG(
// (DSG::is_simplex_grid(coarse_space_) && allLocalRHS.size() == GridType::dimension + 1) ||
// (!(DSG::is_simplex_grid(coarse_space_)) &&
// static_cast<long long>(allLocalRHS.size()) ==
// static_cast<long long>(specifier.fineSpace().mapper().maxNumDofs() + 2)),
// "You need to allocate storage space for the correctors for all unit vector/all coarse basis functions"
// " and the dirichlet- and neuman corrector");
// build unit vectors (needed for cases where rhs is assembled for unit vectors instead of coarse
// base functions)
constexpr auto dimension = CommonTraits::GridType::dimension;
CommonTraits::JacobianRangeType unitVectors[dimension];
for (int i = 0; i < dimension; ++i) {
for (int j = 0; j < dimension; ++j) {
if (i == j) {
unitVectors[i][0][j] = 1.0;
} else {
unitVectors[i][0][j] = 0.0;
}
}
}
LocalGridDiscreteFunctionType dirichletExtension(localSpace_, "dirichletExtension");
CommonTraits::DiscreteFunctionType dirichletExtensionCoarse(coarse_space_, "Dirichlet Extension Coarse");
GDT::SystemAssembler<CommonTraits::DiscreteFunctionSpaceType> global_system_assembler_(coarse_space_);
GDT::Operators::DirichletProjectionLocalizable< CommonTraits::GridViewType, CommonTraits::DirichletDataType,
CommonTraits::DiscreteFunctionType >
coarse_dirichlet_projection_operator(*(coarse_space_.grid_view()),
DMP::getModelData()->boundaryInfo(),
*DMP::getDirichletData(),
dirichletExtensionCoarse);
global_system_assembler_.add(coarse_dirichlet_projection_operator, new GDT::ApplyOn::BoundaryEntities<CommonTraits::GridViewType>());
global_system_assembler_.assemble();
GDT::Operators::LagrangeProlongation<CommonTraits::GridViewType> projection(*coarse_space_.grid_view());
projection.apply(dirichletExtensionCoarse, dirichletExtension);
const bool is_simplex_grid = DSG::is_simplex_grid(coarse_space_);
const auto numBoundaryCorrectors = is_simplex_grid ? 1u : 2u;
const auto numInnerCorrectors = allLocalRHS.size() - numBoundaryCorrectors;
//!*********** anfang neu gdt
std::size_t coarseBaseFunc = 0;
for (; coarseBaseFunc < numInnerCorrectors; ++coarseBaseFunc)
{
if (is_simplex_grid) {
// diffusionsauswertung in unitVectors[coarseBaseFunc]
} else {
// diffusionsauswertung in
// const DomainType quadInCoarseLocal = coarseEntity.geometry().local(QuadraturPunkt);
// coarseBaseSet.jacobianAll(quadInCoarseLocal, coarseBaseFuncJacs);
}
// baseSet.jacobianAll(quadrature[quadraturePoint], gradient_phi);
// for (unsigned int i = 0; i < numBaseFunctions; ++i) {
// rhsLocalFunction[i] -= weight * (diffusions_auswertung * gradient_phi[i][0]);
// }
}
coarseBaseFunc++; // coarseBaseFunc == numInnerCorrectors
//neumann correktor
GDT::Functionals::L2Face< CommonTraits::NeumannDataType, CommonTraits::GdtVectorType, MsFEMTraits::LocalSpaceType >
neumann_functional(*Dune::Multiscale::Problem::getNeumannData(),
allLocalRHS[coarseBaseFunc]->vector(), localSpace_);
system_assembler_.add(neumann_functional);
coarseBaseFunc++;// coarseBaseFunc == 1 + numInnerCorrectors
//dirichlet correktor
{
// const auto dirichletLF = dirichletExtension.local_function(entity);
// dirichletLF.jacobian(local_point, dirichletJac);
// diffusion_operator_.diffusiveFlux(global_point, dirichletJac, diffusion);
// for (unsigned int i = 0; i < numBaseFunctions; ++i) {
// rhsLocalFunction[i] -= weight * (diffusion[0] * gradient_phi[i][0]);
// }
}
//dirichlet-0 for all rhs
typedef GDT::ApplyOn::BoundaryEntities< MsFEMTraits::LocalGridViewType > OnLocalBoundaryEntities;
LocalGridDiscreteFunctionType dirichlet_projection(localSpace_);
GDT::Operators::DirichletProjectionLocalizable< MsFEMTraits::LocalGridViewType, CommonTraits::DirichletDataType,
MsFEMTraits::LocalGridDiscreteFunctionType >
dirichlet_projection_operator(*(localSpace_.grid_view()),
allLocalDirichletInfo_,
dirichletZero_,
dirichlet_projection);
system_assembler_.add(dirichlet_projection_operator, new OnLocalBoundaryEntities());
system_assembler_.add(constraints_, system_matrix_, new OnLocalBoundaryEntities());
for (auto& rhs : allLocalRHS )
system_assembler_.add(constraints_, rhs->vector(), new OnLocalBoundaryEntities());
system_assembler_.assemble();
//!*********** ende neu gdt
#if 0 // alter dune-fem code
// get the base function set of the coarse space for the given coarse entity
const auto& coarseBaseSet = coarse_space_.basisFunctionSet(coarseEntity);
std::vector<CoarseBaseFunctionSetType::JacobianRangeType> coarseBaseFuncJacs(coarseBaseSet.size());
// gradient of micro scale base function:
std::vector<JacobianRangeType> gradient_phi(localSpace.blockMapper().maxNumDofs());
std::vector<RangeType> phi(localSpace.blockMapper().maxNumDofs());
for (auto& localGridCell : localSpace) {
const auto& geometry = localGridCell.geometry();
const bool hasBoundaryIntersection = localGridCell.hasBoundaryIntersections();
auto dirichletLF = dirichletExtension.localFunction(localGridCell);
JacobianRangeType dirichletJac(0.0);
for (std::size_t coarseBaseFunc = 0; coarseBaseFunc < allLocalRHS.size(); ++coarseBaseFunc) {
auto rhsLocalFunction = allLocalRHS[coarseBaseFunc]->localFunction(localGridCell);
const auto& baseSet = rhsLocalFunction.basisFunctionSet();
const auto numBaseFunctions = baseSet.size();
// correctors with index < numInnerCorrectors are for the basis functions, corrector at
// position numInnerCorrectors is for the neumann values, corrector at position numInnerCorrectors+1
// for the dirichlet values.
if (coarseBaseFunc < numInnerCorrectors || coarseBaseFunc == numInnerCorrectors + 1) {
const auto quadrature = DSFe::make_quadrature(localGridCell, localSpace);
const auto numQuadraturePoints = quadrature.nop();
for (size_t quadraturePoint = 0; quadraturePoint < numQuadraturePoints; ++quadraturePoint) {
const auto& local_point = quadrature.point(quadraturePoint);
// global point in the subgrid
const auto global_point = geometry.global(local_point);
const double weight = quadrature.weight(quadraturePoint) * geometry.integrationElement(local_point);
JacobianRangeType diffusion(0.0);
if (coarseBaseFunc < numInnerCorrectors) {
if (is_simplex_grid)
diffusion_operator_.diffusiveFlux(global_point, unitVectors[coarseBaseFunc], diffusion);
else {
const DomainType quadInCoarseLocal = coarseEntity.geometry().local(global_point);
coarseBaseSet.jacobianAll(quadInCoarseLocal, coarseBaseFuncJacs);
diffusion_operator_.diffusiveFlux(global_point, coarseBaseFuncJacs[coarseBaseFunc], diffusion);
}
} else {
dirichletLF.jacobian(local_point, dirichletJac);
diffusion_operator_.diffusiveFlux(global_point, dirichletJac, diffusion);
}
baseSet.jacobianAll(quadrature[quadraturePoint], gradient_phi);
for (unsigned int i = 0; i < numBaseFunctions; ++i) {
rhsLocalFunction[i] -= weight * (diffusion[0] * gradient_phi[i][0]);
}
}
}
// boundary integrals
if (coarseBaseFunc == numInnerCorrectors && hasBoundaryIntersection) {
const auto intEnd = localSpace.gridPart().iend(localGridCell);
for (auto iIt = localSpace.gridPart().ibegin(localGridCell); iIt != intEnd; ++iIt) {
const auto& intersection = *iIt;
if (DMP::is_neumann(intersection)) {
const auto orderOfIntegrand =
(CommonTraits::polynomial_order - 1) + 2 * (CommonTraits::polynomial_order + 1);
const auto quadOrder = std::ceil((orderOfIntegrand + 1) / 2);
const auto faceQuad = DSFe::make_quadrature(intersection, localSpace, quadOrder);
RangeType neumannValue(0.0);
const auto numQuadPoints = faceQuad.nop();
// loop over all quadrature points
for (unsigned int iqP = 0; iqP < numQuadPoints; ++iqP) {
// get local coordinate of quadrature point
const auto& xLocal = faceQuad.localPoint(iqP);
const auto& faceGeometry = intersection.geometry();
// the following does not work because subgrid does not implement geometryInInside()
// const auto& insideGeometry = intersection.geometryInInside();
// const typename FaceQuadratureType::CoordinateType& xInInside = insideGeometry.global(xLocal);
// therefore, we have to do stupid things:
const auto& xGlobal = faceGeometry.global(xLocal);
auto insidePtr = intersection.inside();
const auto& insideEntity = *insidePtr;
const auto& xInInside = insideEntity.geometry().local(xGlobal);
const double factor = faceGeometry.integrationElement(xLocal) * faceQuad.weight(iqP);
neumannData.evaluate(xGlobal, neumannValue);
baseSet.evaluateAll(xInInside, phi);
for (unsigned int i = 0; i < numBaseFunctions; ++i) {
rhsLocalFunction[i] -= factor * (neumannValue * phi[i]);
}
}
}
}
}
}
}
#endif
}
void LocalProblemOperator::apply_inverse(const MsFEMTraits::LocalGridDiscreteFunctionType ¤t_rhs, MsFEMTraits::LocalGridDiscreteFunctionType ¤t_solution)
{
if (!current_rhs.dofs_valid())
DUNE_THROW(Dune::InvalidStateException, "Local MsFEM Problem RHS invalid.");
const auto solver =
Dune::Multiscale::Problem::getModelData()->symmetricDiffusion() ? std::string("cg") : std::string("bcgs");
typedef BackendChooser<LocalGridDiscreteFunctionSpaceType>::InverseOperatorType LocalInverseOperatorType;
const auto localProblemSolver = DSC::make_unique<LocalInverseOperatorType>(system_matrix_, current_rhs.vector());
/*1e-8, 1e-8, 20000,
DSC_CONFIG_GET("msfem.localproblemsolver_verbose", false), solver,
DSC_CONFIG_GET("preconditioner_type", std::string("sor")), 1);*/
localProblemSolver->apply(current_rhs.vector(), current_solution.vector());
if (!current_solution.dofs_valid())
DUNE_THROW(Dune::InvalidStateException, "Current solution of the local msfem problem invalid!");
}
} // namespace MsFEM {
} // namespace Multiscale {
} // namespace Dune {
<|endoftext|> |
<commit_before>//==============================================================================
// Single cell simulation view information solvers widget
//==============================================================================
#include "cellmlfileruntime.h"
#include "cellmlfilevariable.h"
#include "singlecellsimulationviewinformationsolverswidget.h"
#include "singlecellsimulationviewsimulation.h"
//==============================================================================
namespace OpenCOR {
namespace SingleCellSimulationView {
//==============================================================================
SingleCellSimulationViewInformationSolversWidgetData::SingleCellSimulationViewInformationSolversWidgetData(Core::Property *pSolversProperty,
Core::Property *pSolversListProperty,
const QMap<QString, Core::Properties> &pSolversProperties) :
mSolversProperty(pSolversProperty),
mSolversListProperty(pSolversListProperty),
mSolversProperties(pSolversProperties)
{
}
//==============================================================================
Core::Property * SingleCellSimulationViewInformationSolversWidgetData::solversProperty() const
{
// Return our solvers property
return mSolversProperty;
}
//==============================================================================
Core::Property * SingleCellSimulationViewInformationSolversWidgetData::solversListProperty() const
{
// Return our solvers list property
return mSolversListProperty;
}
//==============================================================================
QMap<QString, Core::Properties> SingleCellSimulationViewInformationSolversWidgetData::solversProperties() const
{
// Return our solvers properties
return mSolversProperties;
}
//==============================================================================
SingleCellSimulationViewInformationSolversWidget::SingleCellSimulationViewInformationSolversWidget(QWidget *pParent) :
PropertyEditorWidget(true, pParent),
mOdeSolverData(0),
mDaeSolverData(0),
mNlaSolverData(0),
mGuiStates(QMap<QString, Core::PropertyEditorWidgetGuiState *>()),
mDefaultGuiState(0)
{
}
//==============================================================================
SingleCellSimulationViewInformationSolversWidget::~SingleCellSimulationViewInformationSolversWidget()
{
// Delete some internal objects
delete mOdeSolverData;
delete mDaeSolverData;
delete mNlaSolverData;
resetAllGuiStates();
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::retranslateUi()
{
// Update our property names
if (mOdeSolverData) {
setStringPropertyItem(mOdeSolverData->solversProperty()->name(), tr("ODE solver"));
setStringPropertyItem(mOdeSolverData->solversListProperty()->name(), tr("Name"));
mOdeSolverData->solversListProperty()->value()->setEmptyListValue(tr("None available"));
}
if (mDaeSolverData) {
setStringPropertyItem(mDaeSolverData->solversProperty()->name(), tr("DAE solver"));
setStringPropertyItem(mDaeSolverData->solversListProperty()->name(), tr("Name"));
mDaeSolverData->solversListProperty()->value()->setEmptyListValue(tr("None available"));
}
if (mNlaSolverData) {
setStringPropertyItem(mNlaSolverData->solversProperty()->name(), tr("NLA solver"));
setStringPropertyItem(mNlaSolverData->solversListProperty()->name(), tr("Name"));
mNlaSolverData->solversListProperty()->value()->setEmptyListValue(tr("None available"));
}
// Default retranslation
// Note: we must do it last since we set the empty list value of some
// properties above...
PropertyEditorWidget::retranslateUi();
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::resetAllGuiStates()
{
// Reset all our GUI states including our default one
foreach (Core::PropertyEditorWidgetGuiState *guiState, mGuiStates)
delete guiState;
mGuiStates.clear();
delete mDefaultGuiState;
}
//==============================================================================
SingleCellSimulationViewInformationSolversWidgetData * SingleCellSimulationViewInformationSolversWidget::addSolverProperties(const SolverInterfaces &pSolverInterfaces,
const Solver::Type &pSolverType)
{
// Make sure that we have at least one solver interface
if (pSolverInterfaces.isEmpty())
return 0;
// Add our section property
Core::Property *solversProperty = addSectionProperty();
// Add our list property for the solvers
Core::Property *solversListProperty = addListProperty(solversProperty);
// Retrieve the name of the solvers which type is the one in whhich we are
// interested
QStringList solvers = QStringList();
QMap<QString, Core::Properties> solversProperties = QMap<QString, Core::Properties>();
foreach (SolverInterface *solverInterface, pSolverInterfaces)
if (solverInterface->type() == pSolverType) {
// Keep track of the solver's name
solvers << solverInterface->name();
// Add the solver's properties
Core::Property *property;
Core::Properties properties = Core::Properties();
foreach (const Solver::Property &solverInterfaceProperty,
solverInterface->properties()) {
// Add the solver's property
switch (solverInterfaceProperty.type()) {
case Solver::Double:
property = addDoubleProperty(true, false, solversProperty);
break;
default:
// Solver::Integer
property = addIntegerProperty(true, solversProperty);
}
// Set the solver's property's name
setStringPropertyItem(property->name(), solverInterfaceProperty.name());
// Set the solver's property's default value
switch (solverInterfaceProperty.type()) {
case Solver::Double:
setDoublePropertyItem(property->value(), solverInterfaceProperty.defaultValue().toDouble());
break;
default:
// Solver::Integer
setIntegerPropertyItem(property->value(), solverInterfaceProperty.defaultValue().toInt());
}
// Set the solver's property's 'unit', if needed
if (solverInterfaceProperty.hasVoiUnit())
setStringPropertyItem(property->unit(), "???");
// Note: to assign a non-empty string to our unit item is
// just a way for us to make sure that the property's
// will get initialised (see setPropertiesUnit())...
// Keep track of the solver's property
properties << property;
}
// Keep track of the solver's properties
solversProperties.insert(solverInterface->name(), properties);
}
// Add the list of solvers to our list property value item
solversListProperty->value()->setList(solvers);
// Keep track of changes to list properties
connect(this, SIGNAL(listPropertyChanged(const QString &)),
this, SLOT(listPropertyChanged(const QString &)));
// Return our solver data
return new SingleCellSimulationViewInformationSolversWidgetData(solversProperty,
solversListProperty,
solversProperties);
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::setSolverInterfaces(const SolverInterfaces &pSolverInterfaces)
{
// Remove all our properties
removeAllProperties();
// Add properties for our different solvers
delete mOdeSolverData;
delete mDaeSolverData;
delete mNlaSolverData;
mOdeSolverData = addSolverProperties(pSolverInterfaces, Solver::Ode);
mDaeSolverData = addSolverProperties(pSolverInterfaces, Solver::Dae);
mNlaSolverData = addSolverProperties(pSolverInterfaces, Solver::Nla);
// Show/hide the relevant properties
doListPropertyChanged(mOdeSolverData, mOdeSolverData->solversListProperty()->value()->text(), true);
doListPropertyChanged(mDaeSolverData, mDaeSolverData->solversListProperty()->value()->text(), true);
doListPropertyChanged(mNlaSolverData, mNlaSolverData->solversListProperty()->value()->text(), true);
// Expand all our properties
expandAll();
// Clear any track of previous GUI states and retrieve our default GUI state
resetAllGuiStates();
mDefaultGuiState = guiState();
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::setPropertiesUnit(SingleCellSimulationViewInformationSolversWidgetData *pSolverData,
const QString &pVoiUnit)
{
// Go through the solvers' properties and set the unit of the relevant ones
foreach (const Core::Properties &properties, pSolverData->solversProperties())
foreach (Core::Property *property, properties)
if (!property->unit()->text().isEmpty())
property->unit()->setText(pVoiUnit);
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::initialize(const QString &pFileName,
CellMLSupport::CellmlFileRuntime *pCellmlFileRuntime,
SingleCellSimulationViewSimulationData *pSimulationData)
{
// Make sure that we have a CellML file runtime
if (!pCellmlFileRuntime)
return;
// Retrieve and initialise our GUI state
setGuiState(mGuiStates.contains(pFileName)?
mGuiStates.value(pFileName):
mDefaultGuiState);
// Make sure that the CellML file runtime is valid
if (pCellmlFileRuntime->isValid()) {
// Show/hide the ODE/DAE solver information
setPropertyVisible(mOdeSolverData->solversProperty(), pCellmlFileRuntime->needOdeSolver());
setPropertyVisible(mDaeSolverData->solversProperty(), pCellmlFileRuntime->needDaeSolver());
// Show/hide the NLA solver information
setPropertyVisible(mNlaSolverData->solversProperty(), pCellmlFileRuntime->needNlaSolver());
// Retranslate ourselves so that the property names get properly set
retranslateUi();
}
// Set the unit of our different properties, if needed
QString voiUnit = pCellmlFileRuntime->variableOfIntegration()->unit();
setPropertiesUnit(mOdeSolverData, voiUnit);
setPropertiesUnit(mDaeSolverData, voiUnit);
setPropertiesUnit(mNlaSolverData, voiUnit);
// Initialise our simulation's NLA solver's properties, so that we can then
// properly reset our simulation the first time round
pSimulationData->setNlaSolverName(mNlaSolverData->solversListProperty()->value()->text(), false);
foreach (Core::Property *property, mNlaSolverData->solversProperties().value(pSimulationData->nlaSolverName()))
pSimulationData->addNlaSolverProperty(property->name()->text(),
(property->value()->type() == Core::PropertyItem::Integer)?
Core::PropertyEditorWidget::integerPropertyItem(property->value()):
Core::PropertyEditorWidget::doublePropertyItem(property->value()),
false);
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::finalize(const QString &pFileName)
{
// Keep track of our GUI state
mGuiStates.insert(pFileName, guiState());
}
//==============================================================================
QStringList SingleCellSimulationViewInformationSolversWidget::odeSolvers() const
{
// Return the available ODE solvers, if any
return mOdeSolverData?mOdeSolverData->solversListProperty()->value()->list():QStringList();
}
//==============================================================================
QStringList SingleCellSimulationViewInformationSolversWidget::daeSolvers() const
{
// Return the available DAE solvers, if any
return mDaeSolverData?mDaeSolverData->solversListProperty()->value()->list():QStringList();
}
//==============================================================================
QStringList SingleCellSimulationViewInformationSolversWidget::nlaSolvers() const
{
// Return the available NLA solvers, if any
return mNlaSolverData?mNlaSolverData->solversListProperty()->value()->list():QStringList();
}
//==============================================================================
SingleCellSimulationViewInformationSolversWidgetData * SingleCellSimulationViewInformationSolversWidget::odeSolverData() const
{
// Return our ODE solver data
return mOdeSolverData;
}
//==============================================================================
SingleCellSimulationViewInformationSolversWidgetData * SingleCellSimulationViewInformationSolversWidget::daeSolverData() const
{
// Return our DAE solver data
return mDaeSolverData;
}
//==============================================================================
SingleCellSimulationViewInformationSolversWidgetData * SingleCellSimulationViewInformationSolversWidget::nlaSolverData() const
{
// Return our NLA solver data
return mNlaSolverData;
}
//==============================================================================
bool SingleCellSimulationViewInformationSolversWidget::doListPropertyChanged(SingleCellSimulationViewInformationSolversWidgetData *pSolverData,
const QString &pSolverName,
const bool &pForceHandling)
{
// By default, we don't handle the change in the list property
bool res = false;
// Check whether the list property that got changed is the one we are after
if ( (pSolverData->solversListProperty() == currentProperty())
|| pForceHandling) {
// It is the list property we are after or we want to force the
// handling, so update our result
res = true;
// Go through the different properties for the given type of solver and
// show/hide whatever needs showing/hiding
QMap<QString, Core::Properties>::const_iterator iter = pSolverData->solversProperties().constBegin();
while (iter != pSolverData->solversProperties().constEnd()) {
bool propertyVisible = !iter.key().compare(pSolverName);
foreach (Core::Property *property, iter.value())
setPropertyVisible(property, propertyVisible);
++iter;
}
}
// Return our result
return res;
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::listPropertyChanged(const QString &pValue)
{
// Try, for the ODE, DAE and NLA solvers list property, to handle the change
// in the list property
if (!doListPropertyChanged(mOdeSolverData, pValue))
if (!doListPropertyChanged(mDaeSolverData, pValue))
doListPropertyChanged(mNlaSolverData, pValue);
}
//==============================================================================
} // namespace SingleCellSimulationView
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Fixed a minor issue with our solvers panel whereby a property with VOI unit wouldn't show the correct tooltip (#112).<commit_after>//==============================================================================
// Single cell simulation view information solvers widget
//==============================================================================
#include "cellmlfileruntime.h"
#include "cellmlfilevariable.h"
#include "singlecellsimulationviewinformationsolverswidget.h"
#include "singlecellsimulationviewsimulation.h"
//==============================================================================
namespace OpenCOR {
namespace SingleCellSimulationView {
//==============================================================================
SingleCellSimulationViewInformationSolversWidgetData::SingleCellSimulationViewInformationSolversWidgetData(Core::Property *pSolversProperty,
Core::Property *pSolversListProperty,
const QMap<QString, Core::Properties> &pSolversProperties) :
mSolversProperty(pSolversProperty),
mSolversListProperty(pSolversListProperty),
mSolversProperties(pSolversProperties)
{
}
//==============================================================================
Core::Property * SingleCellSimulationViewInformationSolversWidgetData::solversProperty() const
{
// Return our solvers property
return mSolversProperty;
}
//==============================================================================
Core::Property * SingleCellSimulationViewInformationSolversWidgetData::solversListProperty() const
{
// Return our solvers list property
return mSolversListProperty;
}
//==============================================================================
QMap<QString, Core::Properties> SingleCellSimulationViewInformationSolversWidgetData::solversProperties() const
{
// Return our solvers properties
return mSolversProperties;
}
//==============================================================================
SingleCellSimulationViewInformationSolversWidget::SingleCellSimulationViewInformationSolversWidget(QWidget *pParent) :
PropertyEditorWidget(true, pParent),
mOdeSolverData(0),
mDaeSolverData(0),
mNlaSolverData(0),
mGuiStates(QMap<QString, Core::PropertyEditorWidgetGuiState *>()),
mDefaultGuiState(0)
{
}
//==============================================================================
SingleCellSimulationViewInformationSolversWidget::~SingleCellSimulationViewInformationSolversWidget()
{
// Delete some internal objects
delete mOdeSolverData;
delete mDaeSolverData;
delete mNlaSolverData;
resetAllGuiStates();
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::retranslateUi()
{
// Update our property names
if (mOdeSolverData) {
setStringPropertyItem(mOdeSolverData->solversProperty()->name(), tr("ODE solver"));
setStringPropertyItem(mOdeSolverData->solversListProperty()->name(), tr("Name"));
mOdeSolverData->solversListProperty()->value()->setEmptyListValue(tr("None available"));
}
if (mDaeSolverData) {
setStringPropertyItem(mDaeSolverData->solversProperty()->name(), tr("DAE solver"));
setStringPropertyItem(mDaeSolverData->solversListProperty()->name(), tr("Name"));
mDaeSolverData->solversListProperty()->value()->setEmptyListValue(tr("None available"));
}
if (mNlaSolverData) {
setStringPropertyItem(mNlaSolverData->solversProperty()->name(), tr("NLA solver"));
setStringPropertyItem(mNlaSolverData->solversListProperty()->name(), tr("Name"));
mNlaSolverData->solversListProperty()->value()->setEmptyListValue(tr("None available"));
}
// Default retranslation
// Note: we must do it last since we set the empty list value of some
// properties above...
PropertyEditorWidget::retranslateUi();
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::resetAllGuiStates()
{
// Reset all our GUI states including our default one
foreach (Core::PropertyEditorWidgetGuiState *guiState, mGuiStates)
delete guiState;
mGuiStates.clear();
delete mDefaultGuiState;
}
//==============================================================================
SingleCellSimulationViewInformationSolversWidgetData * SingleCellSimulationViewInformationSolversWidget::addSolverProperties(const SolverInterfaces &pSolverInterfaces,
const Solver::Type &pSolverType)
{
// Make sure that we have at least one solver interface
if (pSolverInterfaces.isEmpty())
return 0;
// Add our section property
Core::Property *solversProperty = addSectionProperty();
// Add our list property for the solvers
Core::Property *solversListProperty = addListProperty(solversProperty);
// Retrieve the name of the solvers which type is the one in whhich we are
// interested
QStringList solvers = QStringList();
QMap<QString, Core::Properties> solversProperties = QMap<QString, Core::Properties>();
foreach (SolverInterface *solverInterface, pSolverInterfaces)
if (solverInterface->type() == pSolverType) {
// Keep track of the solver's name
solvers << solverInterface->name();
// Add the solver's properties
Core::Property *property;
Core::Properties properties = Core::Properties();
foreach (const Solver::Property &solverInterfaceProperty,
solverInterface->properties()) {
// Add the solver's property
switch (solverInterfaceProperty.type()) {
case Solver::Double:
property = addDoubleProperty(true, false, solversProperty);
break;
default:
// Solver::Integer
property = addIntegerProperty(true, solversProperty);
}
// Set the solver's property's name
setStringPropertyItem(property->name(), solverInterfaceProperty.name());
// Set the solver's property's default value
switch (solverInterfaceProperty.type()) {
case Solver::Double:
setDoublePropertyItem(property->value(), solverInterfaceProperty.defaultValue().toDouble());
break;
default:
// Solver::Integer
setIntegerPropertyItem(property->value(), solverInterfaceProperty.defaultValue().toInt());
}
// Set the solver's property's 'unit', if needed
if (solverInterfaceProperty.hasVoiUnit())
setStringPropertyItem(property->unit(), "???");
// Note: to assign a non-empty string to our unit item is
// just a way for us to make sure that the property's
// will get initialised (see setPropertiesUnit())...
// Keep track of the solver's property
properties << property;
}
// Keep track of the solver's properties
solversProperties.insert(solverInterface->name(), properties);
}
// Add the list of solvers to our list property value item
solversListProperty->value()->setList(solvers);
// Keep track of changes to list properties
connect(this, SIGNAL(listPropertyChanged(const QString &)),
this, SLOT(listPropertyChanged(const QString &)));
// Return our solver data
return new SingleCellSimulationViewInformationSolversWidgetData(solversProperty,
solversListProperty,
solversProperties);
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::setSolverInterfaces(const SolverInterfaces &pSolverInterfaces)
{
// Remove all our properties
removeAllProperties();
// Add properties for our different solvers
delete mOdeSolverData;
delete mDaeSolverData;
delete mNlaSolverData;
mOdeSolverData = addSolverProperties(pSolverInterfaces, Solver::Ode);
mDaeSolverData = addSolverProperties(pSolverInterfaces, Solver::Dae);
mNlaSolverData = addSolverProperties(pSolverInterfaces, Solver::Nla);
// Show/hide the relevant properties
doListPropertyChanged(mOdeSolverData, mOdeSolverData->solversListProperty()->value()->text(), true);
doListPropertyChanged(mDaeSolverData, mDaeSolverData->solversListProperty()->value()->text(), true);
doListPropertyChanged(mNlaSolverData, mNlaSolverData->solversListProperty()->value()->text(), true);
// Expand all our properties
expandAll();
// Clear any track of previous GUI states and retrieve our default GUI state
resetAllGuiStates();
mDefaultGuiState = guiState();
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::setPropertiesUnit(SingleCellSimulationViewInformationSolversWidgetData *pSolverData,
const QString &pVoiUnit)
{
// Go through the solvers' properties and set the unit of the relevant ones
foreach (const Core::Properties &properties, pSolverData->solversProperties())
foreach (Core::Property *property, properties)
if (!property->unit()->text().isEmpty())
setStringPropertyItem(property->unit(), pVoiUnit);
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::initialize(const QString &pFileName,
CellMLSupport::CellmlFileRuntime *pCellmlFileRuntime,
SingleCellSimulationViewSimulationData *pSimulationData)
{
// Make sure that we have a CellML file runtime
if (!pCellmlFileRuntime)
return;
// Retrieve and initialise our GUI state
setGuiState(mGuiStates.contains(pFileName)?
mGuiStates.value(pFileName):
mDefaultGuiState);
// Make sure that the CellML file runtime is valid
if (pCellmlFileRuntime->isValid()) {
// Show/hide the ODE/DAE solver information
setPropertyVisible(mOdeSolverData->solversProperty(), pCellmlFileRuntime->needOdeSolver());
setPropertyVisible(mDaeSolverData->solversProperty(), pCellmlFileRuntime->needDaeSolver());
// Show/hide the NLA solver information
setPropertyVisible(mNlaSolverData->solversProperty(), pCellmlFileRuntime->needNlaSolver());
// Retranslate ourselves so that the property names get properly set
retranslateUi();
}
// Set the unit of our different properties, if needed
QString voiUnit = pCellmlFileRuntime->variableOfIntegration()->unit();
setPropertiesUnit(mOdeSolverData, voiUnit);
setPropertiesUnit(mDaeSolverData, voiUnit);
setPropertiesUnit(mNlaSolverData, voiUnit);
// Initialise our simulation's NLA solver's properties, so that we can then
// properly reset our simulation the first time round
pSimulationData->setNlaSolverName(mNlaSolverData->solversListProperty()->value()->text(), false);
foreach (Core::Property *property, mNlaSolverData->solversProperties().value(pSimulationData->nlaSolverName()))
pSimulationData->addNlaSolverProperty(property->name()->text(),
(property->value()->type() == Core::PropertyItem::Integer)?
Core::PropertyEditorWidget::integerPropertyItem(property->value()):
Core::PropertyEditorWidget::doublePropertyItem(property->value()),
false);
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::finalize(const QString &pFileName)
{
// Keep track of our GUI state
mGuiStates.insert(pFileName, guiState());
}
//==============================================================================
QStringList SingleCellSimulationViewInformationSolversWidget::odeSolvers() const
{
// Return the available ODE solvers, if any
return mOdeSolverData?mOdeSolverData->solversListProperty()->value()->list():QStringList();
}
//==============================================================================
QStringList SingleCellSimulationViewInformationSolversWidget::daeSolvers() const
{
// Return the available DAE solvers, if any
return mDaeSolverData?mDaeSolverData->solversListProperty()->value()->list():QStringList();
}
//==============================================================================
QStringList SingleCellSimulationViewInformationSolversWidget::nlaSolvers() const
{
// Return the available NLA solvers, if any
return mNlaSolverData?mNlaSolverData->solversListProperty()->value()->list():QStringList();
}
//==============================================================================
SingleCellSimulationViewInformationSolversWidgetData * SingleCellSimulationViewInformationSolversWidget::odeSolverData() const
{
// Return our ODE solver data
return mOdeSolverData;
}
//==============================================================================
SingleCellSimulationViewInformationSolversWidgetData * SingleCellSimulationViewInformationSolversWidget::daeSolverData() const
{
// Return our DAE solver data
return mDaeSolverData;
}
//==============================================================================
SingleCellSimulationViewInformationSolversWidgetData * SingleCellSimulationViewInformationSolversWidget::nlaSolverData() const
{
// Return our NLA solver data
return mNlaSolverData;
}
//==============================================================================
bool SingleCellSimulationViewInformationSolversWidget::doListPropertyChanged(SingleCellSimulationViewInformationSolversWidgetData *pSolverData,
const QString &pSolverName,
const bool &pForceHandling)
{
// By default, we don't handle the change in the list property
bool res = false;
// Check whether the list property that got changed is the one we are after
if ( (pSolverData->solversListProperty() == currentProperty())
|| pForceHandling) {
// It is the list property we are after or we want to force the
// handling, so update our result
res = true;
// Go through the different properties for the given type of solver and
// show/hide whatever needs showing/hiding
QMap<QString, Core::Properties>::const_iterator iter = pSolverData->solversProperties().constBegin();
while (iter != pSolverData->solversProperties().constEnd()) {
bool propertyVisible = !iter.key().compare(pSolverName);
foreach (Core::Property *property, iter.value())
setPropertyVisible(property, propertyVisible);
++iter;
}
}
// Return our result
return res;
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::listPropertyChanged(const QString &pValue)
{
// Try, for the ODE, DAE and NLA solvers list property, to handle the change
// in the list property
if (!doListPropertyChanged(mOdeSolverData, pValue))
if (!doListPropertyChanged(mDaeSolverData, pValue))
doListPropertyChanged(mNlaSolverData, pValue);
}
//==============================================================================
} // namespace SingleCellSimulationView
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|> |
<commit_before>/*
This file is part of KMail.
Copyright (c) 2005 Cornelius Schumacher <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "distributionlistdialog.h"
#include <akonadi/collectiondialog.h>
#include <akonadi/contact/contactgroupsearchjob.h>
#include <akonadi/contact/contactsearchjob.h>
#include <akonadi/itemcreatejob.h>
#include <kpimutils/email.h>
#include <KLocale>
#include <KDebug>
#include <KLineEdit>
#include <KMessageBox>
#include <KInputDialog>
#include <QLabel>
#include <QTreeWidget>
#include <QTreeWidgetItem>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include "distributionlistdialog.moc"
class DistributionListItem : public QTreeWidgetItem
{
public:
DistributionListItem( QTreeWidget *tree )
: QTreeWidgetItem( tree )
{
setFlags( flags() | Qt::ItemIsUserCheckable );
}
void setAddressee( const KABC::Addressee &a, const QString &email )
{
mIsTransient = false;
init( a, email );
}
void setTransientAddressee( const KABC::Addressee &a, const QString &email )
{
mIsTransient = true;
init( a, email );
}
void init( const KABC::Addressee &a, const QString &email )
{
mAddressee = a;
mEmail = email;
setText( 0, mAddressee.realName() );
setText( 1, mEmail );
}
KABC::Addressee addressee() const
{
return mAddressee;
}
QString email() const
{
return mEmail;
}
bool isTransient() const
{
return mIsTransient;
}
private:
KABC::Addressee mAddressee;
QString mEmail;
bool mIsTransient;
};
DistributionListDialog::DistributionListDialog( QWidget *parent )
: KDialog( parent )
{
QFrame *topFrame = new QFrame( this );
setMainWidget( topFrame );
setCaption( i18nc("@title:window", "Save Distribution List") );
setButtons( User1 | Cancel );
setDefaultButton( User1 );
setModal( false );
setButtonText( User1, i18nc("@action:button","Save List") );
QBoxLayout *topLayout = new QVBoxLayout( topFrame );
topLayout->setSpacing( spacingHint() );
QBoxLayout *titleLayout = new QHBoxLayout();
titleLayout->setSpacing( spacingHint() );
topLayout->addItem( titleLayout );
QLabel *label = new QLabel(
i18nc("@label:textbox Name of the distribution list.", "&Name:"), topFrame );
titleLayout->addWidget( label );
mTitleEdit = new KLineEdit( topFrame );
titleLayout->addWidget( mTitleEdit );
mTitleEdit->setFocus();
mTitleEdit->setClearButtonShown( true );
label->setBuddy( mTitleEdit );
mRecipientsList = new QTreeWidget( topFrame );
mRecipientsList->setHeaderLabels(
QStringList() << i18nc( "@title:column Name of the recipient","Name" )
<< i18nc( "@title:column Email of the recipient", "Email" )
);
mRecipientsList->setRootIsDecorated( false );
topLayout->addWidget( mRecipientsList );
connect( this, SIGNAL( user1Clicked() ),
this, SLOT( slotUser1() ) );
}
void DistributionListDialog::setRecipients( const Recipient::List &recipients )
{
Recipient::List::ConstIterator it;
for( it = recipients.constBegin(); it != recipients.constEnd(); ++it ) {
QStringList emails = KPIMUtils::splitAddressList( (*it).email() );
QStringList::ConstIterator it2;
for( it2 = emails.constBegin(); it2 != emails.constEnd(); ++it2 ) {
QString name;
QString email;
KABC::Addressee::parseEmailAddress( *it2, name, email );
if ( !email.isEmpty() ) {
DistributionListItem *item = new DistributionListItem( mRecipientsList );
Akonadi::ContactSearchJob *job = new Akonadi::ContactSearchJob();
job->setQuery( Akonadi::ContactSearchJob::Email, email );
job->exec();
const KABC::Addressee::List contacts = job->contacts();
if ( contacts.isEmpty() ) {
if ( name.isEmpty() ) {
const int index = email.indexOf( QLatin1Char( '@' ) );
if ( index != -1 ) {
name = email.left( index );
} else {
name = email;
}
}
KABC::Addressee contact;
contact.setNameFromString( name );
contact.insertEmail( email );
item->setTransientAddressee( contact, email );
item->setCheckState( 0, Qt::Checked );
} else {
bool isFirst = true;
foreach ( const KABC::Addressee &contact, contacts ) {
item->setAddressee( contact, email );
if ( isFirst ) {
item->setCheckState( 0, Qt::Checked );
isFirst = false;
}
}
}
}
}
}
}
void DistributionListDialog::slotUser1()
{
bool isEmpty = true;
for (int i = 0; i < mRecipientsList->topLevelItemCount(); ++i) {
DistributionListItem *item = static_cast<DistributionListItem *>(
mRecipientsList->topLevelItem( i ));
if ( item && item->checkState( 0 ) == Qt::Checked ) {
isEmpty = false;
break;
}
}
if ( isEmpty ) {
KMessageBox::information( this,
i18nc("@info", "There are no recipients in your list. "
"First select some recipients, "
"then try again.") );
return;
}
QString name = mTitleEdit->text();
if ( name.isEmpty() ) {
bool ok = false;
name = KInputDialog::getText( i18nc("@title:window","New Distribution List"),
i18nc("@label:textbox","Please enter name:"), QString(), &ok, this );
if ( !ok || name.isEmpty() )
return;
}
Akonadi::ContactGroupSearchJob *job = new Akonadi::ContactGroupSearchJob();
job->setQuery( Akonadi::ContactGroupSearchJob::Name, name );
job->exec();
if ( !job->contactGroups().isEmpty() ) {
KMessageBox::information( this,
i18nc( "@info", "<para>Distribution list with the given name <resource>%1</resource> "
"already exists. Please select a different name.</para>", name ) );
return;
}
Akonadi::CollectionDialog dlg( this );
dlg.setMimeTypeFilter( QStringList() << KABC::Addressee::mimeType() << KABC::ContactGroup::mimeType() );
dlg.setAccessRightsFilter( Akonadi::Collection::CanCreateItem );
dlg.setDescription( i18n( "Select the address book folder to store the contact group in:" ) );
if ( !dlg.exec() )
return;
const Akonadi::Collection targetCollection = dlg.selectedCollection();
KABC::ContactGroup group( name );
for ( int i = 0; i < mRecipientsList->topLevelItemCount(); ++i ) {
DistributionListItem *item = static_cast<DistributionListItem *>( mRecipientsList->topLevelItem( i ) );
if ( item && item->checkState( 0 ) == Qt::Checked ) {
kDebug() << item->addressee().fullEmail() << item->addressee().uid();
if ( item->isTransient() ) {
Akonadi::Item contactItem( KABC::Addressee::mimeType() );
contactItem.setPayload<KABC::Addressee>( item->addressee() );
Akonadi::ItemCreateJob *job = new Akonadi::ItemCreateJob( contactItem, targetCollection );
job->exec();
group.append( KABC::ContactGroup::ContactReference( QString::number( job->item().id() ) ) );
} else {
group.append( KABC::ContactGroup::Data( item->addressee().realName(), item->email() ) );
}
}
}
Akonadi::Item groupItem( KABC::ContactGroup::mimeType() );
groupItem.setPayload<KABC::ContactGroup>( group );
new Akonadi::ItemCreateJob( groupItem, targetCollection );
close();
}
<commit_msg>Minor optimization<commit_after>/*
This file is part of KMail.
Copyright (c) 2005 Cornelius Schumacher <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "distributionlistdialog.h"
#include <akonadi/collectiondialog.h>
#include <akonadi/contact/contactgroupsearchjob.h>
#include <akonadi/contact/contactsearchjob.h>
#include <akonadi/itemcreatejob.h>
#include <kpimutils/email.h>
#include <KLocale>
#include <KDebug>
#include <KLineEdit>
#include <KMessageBox>
#include <KInputDialog>
#include <QLabel>
#include <QTreeWidget>
#include <QTreeWidgetItem>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include "distributionlistdialog.moc"
class DistributionListItem : public QTreeWidgetItem
{
public:
DistributionListItem( QTreeWidget *tree )
: QTreeWidgetItem( tree )
{
setFlags( flags() | Qt::ItemIsUserCheckable );
}
void setAddressee( const KABC::Addressee &a, const QString &email )
{
mIsTransient = false;
init( a, email );
}
void setTransientAddressee( const KABC::Addressee &a, const QString &email )
{
mIsTransient = true;
init( a, email );
}
void init( const KABC::Addressee &a, const QString &email )
{
mAddressee = a;
mEmail = email;
setText( 0, mAddressee.realName() );
setText( 1, mEmail );
}
KABC::Addressee addressee() const
{
return mAddressee;
}
QString email() const
{
return mEmail;
}
bool isTransient() const
{
return mIsTransient;
}
private:
KABC::Addressee mAddressee;
QString mEmail;
bool mIsTransient;
};
DistributionListDialog::DistributionListDialog( QWidget *parent )
: KDialog( parent )
{
QFrame *topFrame = new QFrame( this );
setMainWidget( topFrame );
setCaption( i18nc("@title:window", "Save Distribution List") );
setButtons( User1 | Cancel );
setDefaultButton( User1 );
setModal( false );
setButtonText( User1, i18nc("@action:button","Save List") );
QBoxLayout *topLayout = new QVBoxLayout( topFrame );
topLayout->setSpacing( spacingHint() );
QBoxLayout *titleLayout = new QHBoxLayout();
titleLayout->setSpacing( spacingHint() );
topLayout->addItem( titleLayout );
QLabel *label = new QLabel(
i18nc("@label:textbox Name of the distribution list.", "&Name:"), topFrame );
titleLayout->addWidget( label );
mTitleEdit = new KLineEdit( topFrame );
titleLayout->addWidget( mTitleEdit );
mTitleEdit->setFocus();
mTitleEdit->setClearButtonShown( true );
label->setBuddy( mTitleEdit );
mRecipientsList = new QTreeWidget( topFrame );
mRecipientsList->setHeaderLabels(
QStringList() << i18nc( "@title:column Name of the recipient","Name" )
<< i18nc( "@title:column Email of the recipient", "Email" )
);
mRecipientsList->setRootIsDecorated( false );
topLayout->addWidget( mRecipientsList );
connect( this, SIGNAL( user1Clicked() ),
this, SLOT( slotUser1() ) );
}
void DistributionListDialog::setRecipients( const Recipient::List &recipients )
{
Recipient::List::ConstIterator it;
for( it = recipients.constBegin(); it != recipients.constEnd(); ++it ) {
const QStringList emails = KPIMUtils::splitAddressList( (*it).email() );
QStringList::ConstIterator it2;
for( it2 = emails.constBegin(); it2 != emails.constEnd(); ++it2 ) {
QString name;
QString email;
KABC::Addressee::parseEmailAddress( *it2, name, email );
if ( !email.isEmpty() ) {
DistributionListItem *item = new DistributionListItem( mRecipientsList );
Akonadi::ContactSearchJob *job = new Akonadi::ContactSearchJob();
job->setQuery( Akonadi::ContactSearchJob::Email, email );
job->exec();
const KABC::Addressee::List contacts = job->contacts();
if ( contacts.isEmpty() ) {
if ( name.isEmpty() ) {
const int index = email.indexOf( QLatin1Char( '@' ) );
if ( index != -1 ) {
name = email.left( index );
} else {
name = email;
}
}
KABC::Addressee contact;
contact.setNameFromString( name );
contact.insertEmail( email );
item->setTransientAddressee( contact, email );
item->setCheckState( 0, Qt::Checked );
} else {
bool isFirst = true;
foreach ( const KABC::Addressee &contact, contacts ) {
item->setAddressee( contact, email );
if ( isFirst ) {
item->setCheckState( 0, Qt::Checked );
isFirst = false;
}
}
}
}
}
}
}
void DistributionListDialog::slotUser1()
{
bool isEmpty = true;
const int numberOfItems = mRecipientsList->topLevelItemCount();
for (int i = 0; i < numberOfItems; ++i) {
DistributionListItem *item = static_cast<DistributionListItem *>(
mRecipientsList->topLevelItem( i ));
if ( item && item->checkState( 0 ) == Qt::Checked ) {
isEmpty = false;
break;
}
}
if ( isEmpty ) {
KMessageBox::information( this,
i18nc("@info", "There are no recipients in your list. "
"First select some recipients, "
"then try again.") );
return;
}
QString name = mTitleEdit->text();
if ( name.isEmpty() ) {
bool ok = false;
name = KInputDialog::getText( i18nc("@title:window","New Distribution List"),
i18nc("@label:textbox","Please enter name:"), QString(), &ok, this );
if ( !ok || name.isEmpty() )
return;
}
Akonadi::ContactGroupSearchJob *job = new Akonadi::ContactGroupSearchJob();
job->setQuery( Akonadi::ContactGroupSearchJob::Name, name );
job->exec();
if ( !job->contactGroups().isEmpty() ) {
KMessageBox::information( this,
i18nc( "@info", "<para>Distribution list with the given name <resource>%1</resource> "
"already exists. Please select a different name.</para>", name ) );
return;
}
Akonadi::CollectionDialog dlg( this );
dlg.setMimeTypeFilter( QStringList() << KABC::Addressee::mimeType() << KABC::ContactGroup::mimeType() );
dlg.setAccessRightsFilter( Akonadi::Collection::CanCreateItem );
dlg.setDescription( i18n( "Select the address book folder to store the contact group in:" ) );
if ( !dlg.exec() )
return;
const Akonadi::Collection targetCollection = dlg.selectedCollection();
KABC::ContactGroup group( name );
const int numberOfTopLevelItems = mRecipientsList->topLevelItemCount();
for ( int i = 0; i < numberOfTopLevelItems; ++i ) {
DistributionListItem *item = static_cast<DistributionListItem *>( mRecipientsList->topLevelItem( i ) );
if ( item && item->checkState( 0 ) == Qt::Checked ) {
kDebug() << item->addressee().fullEmail() << item->addressee().uid();
if ( item->isTransient() ) {
Akonadi::Item contactItem( KABC::Addressee::mimeType() );
contactItem.setPayload<KABC::Addressee>( item->addressee() );
Akonadi::ItemCreateJob *job = new Akonadi::ItemCreateJob( contactItem, targetCollection );
job->exec();
group.append( KABC::ContactGroup::ContactReference( QString::number( job->item().id() ) ) );
} else {
group.append( KABC::ContactGroup::Data( item->addressee().realName(), item->email() ) );
}
}
}
Akonadi::Item groupItem( KABC::ContactGroup::mimeType() );
groupItem.setPayload<KABC::ContactGroup>( group );
new Akonadi::ItemCreateJob( groupItem, targetCollection );
close();
}
<|endoftext|> |
<commit_before>/***************************************************************************
* *
* Copyright (C) 2007-2013 by Johan De Taeye, frePPLe bvba *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Affero General Public License as published *
* by the Free Software Foundation; either version 3 of the License, or *
* (at your option) any later version. *
* *
* This 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 Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public *
* License along with this program. *
* If not, see <http://www.gnu.org/licenses/>. *
* *
***************************************************************************/
#define FREPPLE_CORE
#include "frepple/solver.h"
namespace frepple
{
DECLARE_EXPORT void SolverMRP::solve(const BufferProcure* b, void* v)
{
SolverMRPdata* data = static_cast<SolverMRPdata*>(v);
bool safetystock = (data->state->q_qty == -1.0);
// TODO create a more performant procurement solver. Instead of creating a list of operationplans
// moves and creations, we can create a custom command "updateProcurements". The commit of
// this command will update the operationplans.
// The solve method is only worried about getting a Yes/No reply. The reply is almost always yes,
// except a) when the request is inside max(current + the lead time, latest procurement + min time
// after locked procurement), or b) when the min time > 0 and max qty > 0
// TODO Procurement solver doesn't consider working days of the supplier.
// Call the user exit
if (userexit_buffer) userexit_buffer.call(b, PythonObject(data->constrainedPlanning));
// Message
if (data->getSolver()->getLogLevel()>1)
{
if (safetystock)
logger << indent(b->getLevel()) << " Buffer '" << b->getName()
<< "' replenishes for safety stock" << endl;
else
logger << indent(b->getLevel()) << " Procurement buffer '" << b->getName()
<< "' is asked: " << data->state->q_qty << " " << data->state->q_date << endl;
}
// Standard reply date
data->state->a_date = Date::infiniteFuture;
// Collect all reusable existing procurements in a vector data structure.
// Also find the latest locked procurement operation. It is used to know what
// the earliest date is for a new procurement.
int countProcurements = 0;
int indexProcurements = -1;
Date earliest_next;
Date latest_next = Date::infiniteFuture;
vector<OperationPlan*> procurements;
for (Buffer::flowplanlist::const_iterator c = b->getFlowPlans().begin();
c != b->getFlowPlans().end(); ++c)
{
if (c->getQuantity() <= 0 || c->getType() != 1)
continue;
const OperationPlan *o = reinterpret_cast<const FlowPlan*>(&*c)->getOperationPlan();
if (o->getLocked())
earliest_next = o->getDates().getEnd();
else
{
procurements.push_back(const_cast<OperationPlan*>(o));
++countProcurements;
}
}
Date latestlocked = earliest_next;
// Collect operation parameters
// Normally these are collected from fields on the buffer. Only when a
// producing operation has been explicitly specified do we use those instead.
TimePeriod leadtime = b->getLeadtime();
TimePeriod fence = b->getFence();
double size_minimum = b->getSizeMinimum();
Operation *oper;
if (b->getProducingOperation())
{
oper = b->getProducingOperation();
if (oper->getType() == *OperationAlternate::metadata)
{
if (oper->getSubOperations().empty())
throw DataException("Missing procurement alternate suboperations");
// Take the first suboperation.
oper = *(oper->getSubOperations().begin());
}
if (oper->getType() == *OperationFixedTime::metadata)
{
// Inherit on operation from the buffer
if (b->getSizeMinimum() != 1.0 && oper->getSizeMinimum() == 1.0)
oper->setSizeMinimum(b->getSizeMinimum());
if (b->getSizeMaximum() && !oper->getSizeMaximum())
oper->setSizeMaximum(b->getSizeMaximum());
if (b->getSizeMultiple() && !oper->getSizeMultiple())
oper->setSizeMultiple(b->getSizeMultiple());
// Values to use in this solver method
fence = oper->getFence();
leadtime = static_cast<OperationFixedTime*>(oper)->getDuration();
size_minimum = oper->getSizeMinimum();
}
else
throw DataException("Producing operation of a procurement buffer must be of type fixed_time or alternate");
}
else
oper = b->getOperation();
// Find constraints on earliest and latest date for the next procurement
if (earliest_next && b->getMaximumInterval())
latest_next = earliest_next + b->getMaximumInterval();
if (earliest_next && b->getMinimumInterval())
earliest_next += b->getMinimumInterval();
if (data->constrainedPlanning)
{
if (data->getSolver()->isLeadtimeConstrained() && data->getSolver()->isFenceConstrained()
&& earliest_next < Plan::instance().getCurrent() + leadtime + fence)
earliest_next = Plan::instance().getCurrent() + leadtime + fence;
else if (data->getSolver()->isLeadtimeConstrained()
&& earliest_next < Plan::instance().getCurrent() + leadtime)
earliest_next = Plan::instance().getCurrent() + leadtime;
else if (data->getSolver()->isFenceConstrained()
&& earliest_next < Plan::instance().getCurrent() + fence)
earliest_next = Plan::instance().getCurrent() + fence;
}
if (latest_next < earliest_next) latest_next = earliest_next;
// Loop through all flowplans
Date current_date;
double produced = 0.0;
double consumed = 0.0;
double current_inventory = 0.0;
const FlowPlan* current_flowplan = NULL;
for (Buffer::flowplanlist::const_iterator cur=b->getFlowPlans().begin();
latest_next != Date::infiniteFuture || earliest_next || cur != b->getFlowPlans().end(); )
{
if (cur==b->getFlowPlans().end())
{
current_date = earliest_next ? earliest_next : latest_next;
current_flowplan = NULL;
}
else if (latest_next != Date::infiniteFuture && latest_next < cur->getDate())
{
// Latest procument time is reached
current_date = latest_next;
current_flowplan = NULL;
}
else if (earliest_next && earliest_next < cur->getDate())
{
// Earliest procument time was reached
current_date = earliest_next;
current_flowplan = NULL;
}
else
{
// Date with flowplans found
if (current_date && current_date >= cur->getDate())
{
// When procurements are being moved, it happens that we revisit the
// same consuming flowplans twice. This check catches this case.
cur++;
continue;
}
current_date = cur->getDate();
do
{
if (cur->getType() != 1)
{
cur++;
continue;
}
current_flowplan = static_cast<const FlowPlan*>(&*(cur++));
if (current_flowplan->getQuantity() < 0)
consumed -= current_flowplan->getQuantity();
else if (current_flowplan->getOperationPlan()->getLocked())
produced += current_flowplan->getQuantity();
}
// Loop to pick up the last consuming flowplan on the given date
while (cur != b->getFlowPlans().end() && cur->getDate() == current_date);
}
// Compute current inventory. The actual onhand in the buffer may be
// different since we count only consumers and *locked* producers.
current_inventory = produced - consumed;
// Hard limit: respect minimum interval
if (current_date < earliest_next)
{
if (current_inventory < -ROUNDING_ERROR
&& current_date >= data->state->q_date
&& b->getMinimumInterval()
&& data->state->a_date > earliest_next
&& data->getSolver()->isMaterialConstrained()
&& data->constrainedPlanning)
// The inventory goes negative here and we can't procure more
// material because of the minimum interval...
data->state->a_date = earliest_next;
continue;
}
// Now the normal reorder check
if (current_inventory >= b->getMinimumInventory()
&& current_date < latest_next)
{
if (current_date == earliest_next) earliest_next = Date::infinitePast;
continue;
}
// When we are within the minimum interval, we may need to increase the
// size of the previous procurements.
//
// TODO We should not only resize the existing procurements, but also
// consider inserting additional ones. See "buffer 10" in "buffer_procure_1" testcase,
// where some possible purchasing intervals are not used.
if (current_date == earliest_next
&& current_inventory < b->getMinimumInventory() - ROUNDING_ERROR)
{
for (int cnt=indexProcurements;
cnt>=0 && current_inventory < b->getMinimumInventory() - ROUNDING_ERROR;
cnt--)
{
double origqty = procurements[cnt]->getQuantity();
procurements[cnt]->setQuantity(
procurements[cnt]->getQuantity()
+ b->getMinimumInventory() - current_inventory);
produced += procurements[cnt]->getQuantity() - origqty;
current_inventory = produced - consumed;
}
if (current_inventory < -ROUNDING_ERROR
&& data->state->a_date > earliest_next
&& earliest_next > data->state->q_date
&& data->getSolver()->isMaterialConstrained()
&& data->constrainedPlanning)
// Resizing didn't work, and we still have shortage (not only compared
// to the minimum, but also to 0.
data->state->a_date = earliest_next;
}
// At this point, we know we need to reorder...
earliest_next = Date::infinitePast;
double order_qty = b->getMaximumInventory() - current_inventory;
do
{
if (order_qty <= 0)
{
if (latest_next == current_date && size_minimum)
// Forced to buy the minumum quantity
order_qty = size_minimum;
else
break;
}
// Create a procurement or update an existing one
indexProcurements++;
if (indexProcurements >= countProcurements)
{
// No existing procurement can be reused. Create a new one.
CommandCreateOperationPlan *a =
new CommandCreateOperationPlan(oper, order_qty,
Date::infinitePast, current_date, data->state->curDemand);
a->getOperationPlan()->setMotive(data->state->motive);
a->getOperationPlan()->insertInOperationplanList(); // TODO Not very nice: unregistered opplan in the list!
produced += a->getOperationPlan()->getQuantity();
order_qty -= a->getOperationPlan()->getQuantity();
data->add(a);
procurements.push_back(a->getOperationPlan());
++countProcurements;
}
else if (procurements[indexProcurements]->getDates().getEnd() == current_date
&& procurements[indexProcurements]->getQuantity() == order_qty)
{
// Reuse existing procurement unchanged.
produced += order_qty;
order_qty = 0;
}
else
{
// Update an existing procurement to meet current needs
CommandMoveOperationPlan *a =
new CommandMoveOperationPlan(procurements[indexProcurements], Date::infinitePast, current_date, order_qty);
produced += procurements[indexProcurements]->getQuantity();
order_qty -= procurements[indexProcurements]->getQuantity();
data->add(a);
}
if (b->getMinimumInterval())
{
earliest_next = current_date + b->getMinimumInterval();
break; // Only 1 procurement allowed at this time...
}
}
while (order_qty > ROUNDING_ERROR && order_qty >= size_minimum);
if (b->getMaximumInterval())
{
current_inventory = produced - consumed;
if (current_inventory >= b->getMaximumInventory()
&& cur == b->getFlowPlans().end())
// Nothing happens any more further in the future.
// Abort procuring based on the max inteval
latest_next = Date::infiniteFuture;
else
latest_next = current_date + b->getMaximumInterval();
}
}
// Get rid of extra procurements that have become redundant
indexProcurements++;
while (indexProcurements < countProcurements)
data->add(new CommandDeleteOperationPlan(procurements[indexProcurements++]));
// Create the answer
if (safetystock)
data->state->a_qty = 1.0;
else if (data->constrainedPlanning && (data->getSolver()->isFenceConstrained()
|| data->getSolver()->isLeadtimeConstrained()
|| data->getSolver()->isMaterialConstrained()))
{
// Check if the inventory drops below zero somewhere
double shortage = 0;
Date startdate;
for (Buffer::flowplanlist::const_iterator cur = b->getFlowPlans().begin();
cur != b->getFlowPlans().end(); ++cur)
if (cur->getDate() >= data->state->q_date
&& cur->getOnhand() < -ROUNDING_ERROR
&& cur->getOnhand() < shortage)
{
shortage = cur->getOnhand();
if (-shortage >= data->state->q_qty) break;
if (startdate == Date::infinitePast) startdate = cur->getDate();
}
if (shortage < 0)
{
// Answer a shorted quantity
data->state->a_qty = data->state->q_qty + shortage;
// Log a constraint
if (data->logConstraints && data->planningDemand)
data->planningDemand->getConstraints().push(
ProblemMaterialShortage::metadata, b, startdate, Date::infiniteFuture, // @todo calculate a better end date
-shortage);
// Nothing to promise...
if (data->state->a_qty < 0) data->state->a_qty = 0;
// Check the reply date
if (data->constrainedPlanning)
{
if (data->getSolver()->isFenceConstrained()
&& data->state->q_date < Plan::instance().getCurrent() + fence
&& data->state->a_date > Plan::instance().getCurrent() + fence)
data->state->a_date = Plan::instance().getCurrent() + fence;
if (data->getSolver()->isLeadtimeConstrained()
&& data->state->q_date < Plan::instance().getCurrent() + leadtime
&& data->state->a_date > Plan::instance().getCurrent() + leadtime)
data->state->a_date = Plan::instance().getCurrent() + leadtime; // TODO Doesn't consider calendar of the procurement operation...
if (latestlocked
&& data->state->q_date < latestlocked
&& data->state->a_date > latestlocked)
data->state->a_date = latestlocked;
}
}
else
// Answer the full quantity
data->state->a_qty = data->state->q_qty;
}
else
// Answer the full quantity
data->state->a_qty = data->state->q_qty;
// Increment the cost
if (b->getItem() && data->state->a_qty > 0.0)
data->state->a_cost += data->state->a_qty * b->getItem()->getPrice();
// Message
if (data->getSolver()->getLogLevel()>1)
{
if (safetystock)
logger << indent(b->getLevel()) << " Buffer '" << b->getName()
<< "' solved for safety stock" << endl;
else
logger << indent(b->getLevel()) << " Procurement buffer '" << b
<< "' answers: " << data->state->a_qty << " " << data->state->a_date
<< " " << data->state->a_cost << " " << data->state->a_penalty << endl;
}
}
}
<commit_msg>Bug fix for infinite loop in the buffer_procurement solver<commit_after>/***************************************************************************
* *
* Copyright (C) 2007-2013 by Johan De Taeye, frePPLe bvba *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Affero General Public License as published *
* by the Free Software Foundation; either version 3 of the License, or *
* (at your option) any later version. *
* *
* This 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 Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public *
* License along with this program. *
* If not, see <http://www.gnu.org/licenses/>. *
* *
***************************************************************************/
#define FREPPLE_CORE
#include "frepple/solver.h"
namespace frepple
{
DECLARE_EXPORT void SolverMRP::solve(const BufferProcure* b, void* v)
{
SolverMRPdata* data = static_cast<SolverMRPdata*>(v);
bool safetystock = (data->state->q_qty == -1.0);
// TODO create a more performant procurement solver. Instead of creating a list of operationplans
// moves and creations, we can create a custom command "updateProcurements". The commit of
// this command will update the operationplans.
// The solve method is only worried about getting a Yes/No reply. The reply is almost always yes,
// except a) when the request is inside max(current + the lead time, latest procurement + min time
// after locked procurement), or b) when the min time > 0 and max qty > 0
// TODO Procurement solver doesn't consider working days of the supplier.
// Call the user exit
if (userexit_buffer) userexit_buffer.call(b, PythonObject(data->constrainedPlanning));
// Message
if (data->getSolver()->getLogLevel()>1)
{
if (safetystock)
logger << indent(b->getLevel()) << " Buffer '" << b->getName()
<< "' replenishes for safety stock" << endl;
else
logger << indent(b->getLevel()) << " Procurement buffer '" << b->getName()
<< "' is asked: " << data->state->q_qty << " " << data->state->q_date << endl;
}
// Standard reply date
data->state->a_date = Date::infiniteFuture;
// Collect all reusable existing procurements in a vector data structure.
// Also find the latest locked procurement operation. It is used to know what
// the earliest date is for a new procurement.
int countProcurements = 0;
int indexProcurements = -1;
Date earliest_next;
Date latest_next = Date::infiniteFuture;
vector<OperationPlan*> procurements;
for (Buffer::flowplanlist::const_iterator c = b->getFlowPlans().begin();
c != b->getFlowPlans().end(); ++c)
{
if (c->getQuantity() <= 0 || c->getType() != 1)
continue;
const OperationPlan *o = reinterpret_cast<const FlowPlan*>(&*c)->getOperationPlan();
if (o->getLocked())
earliest_next = o->getDates().getEnd();
else
{
procurements.push_back(const_cast<OperationPlan*>(o));
++countProcurements;
}
}
Date latestlocked = earliest_next;
// Collect operation parameters
// Normally these are collected from fields on the buffer. Only when a
// producing operation has been explicitly specified do we use those instead.
TimePeriod leadtime = b->getLeadtime();
TimePeriod fence = b->getFence();
double size_minimum = b->getSizeMinimum();
Operation *oper;
if (b->getProducingOperation())
{
oper = b->getProducingOperation();
if (oper->getType() == *OperationAlternate::metadata)
{
if (oper->getSubOperations().empty())
throw DataException("Missing procurement alternate suboperations");
// Take the first suboperation.
oper = *(oper->getSubOperations().begin());
}
if (oper->getType() == *OperationFixedTime::metadata)
{
// Inherit on operation from the buffer
if (b->getSizeMinimum() != 1.0 && oper->getSizeMinimum() == 1.0)
oper->setSizeMinimum(b->getSizeMinimum());
if (b->getSizeMaximum() && !oper->getSizeMaximum())
oper->setSizeMaximum(b->getSizeMaximum());
if (b->getSizeMultiple() && !oper->getSizeMultiple())
oper->setSizeMultiple(b->getSizeMultiple());
// Values to use in this solver method
fence = oper->getFence();
leadtime = static_cast<OperationFixedTime*>(oper)->getDuration();
size_minimum = oper->getSizeMinimum();
}
else
throw DataException("Producing operation of a procurement buffer must be of type fixed_time or alternate");
}
else
oper = b->getOperation();
// Find constraints on earliest and latest date for the next procurement
if (earliest_next && b->getMaximumInterval())
latest_next = earliest_next + b->getMaximumInterval();
if (earliest_next && b->getMinimumInterval())
earliest_next += b->getMinimumInterval();
if (data->constrainedPlanning)
{
if (data->getSolver()->isLeadtimeConstrained() && data->getSolver()->isFenceConstrained()
&& earliest_next < Plan::instance().getCurrent() + leadtime + fence)
earliest_next = Plan::instance().getCurrent() + leadtime + fence;
else if (data->getSolver()->isLeadtimeConstrained()
&& earliest_next < Plan::instance().getCurrent() + leadtime)
earliest_next = Plan::instance().getCurrent() + leadtime;
else if (data->getSolver()->isFenceConstrained()
&& earliest_next < Plan::instance().getCurrent() + fence)
earliest_next = Plan::instance().getCurrent() + fence;
}
if (latest_next < earliest_next) latest_next = earliest_next;
// Loop through all flowplans
Date current_date;
double produced = 0.0;
double consumed = 0.0;
double current_inventory = 0.0;
const FlowPlan* current_flowplan = NULL;
for (Buffer::flowplanlist::const_iterator cur=b->getFlowPlans().begin();
latest_next != Date::infiniteFuture || earliest_next || cur != b->getFlowPlans().end(); )
{
if (cur==b->getFlowPlans().end())
{
current_date = earliest_next ? earliest_next : latest_next;
current_flowplan = NULL;
}
else if (latest_next != Date::infiniteFuture && latest_next < cur->getDate())
{
// Latest procument time is reached
current_date = latest_next;
current_flowplan = NULL;
}
else if (earliest_next && earliest_next < cur->getDate())
{
// Earliest procument time was reached
current_date = earliest_next;
current_flowplan = NULL;
}
else
{
// Date with flowplans found
if (current_date && current_date >= cur->getDate())
{
// When procurements are being moved, it happens that we revisit the
// same consuming flowplans twice. This check catches this case.
cur++;
continue;
}
current_date = cur->getDate();
do
{
if (cur->getType() != 1)
{
cur++;
continue;
}
current_flowplan = static_cast<const FlowPlan*>(&*(cur++));
if (current_flowplan->getQuantity() < 0)
consumed -= current_flowplan->getQuantity();
else if (current_flowplan->getOperationPlan()->getLocked())
produced += current_flowplan->getQuantity();
}
// Loop to pick up the last consuming flowplan on the given date
while (cur != b->getFlowPlans().end() && cur->getDate() == current_date);
}
// Compute current inventory. The actual onhand in the buffer may be
// different since we count only consumers and *locked* producers.
current_inventory = produced - consumed;
// Hard limit: respect minimum interval
if (current_date < earliest_next)
{
if (current_inventory < -ROUNDING_ERROR
&& current_date >= data->state->q_date
&& b->getMinimumInterval()
&& data->state->a_date > earliest_next
&& data->getSolver()->isMaterialConstrained()
&& data->constrainedPlanning)
// The inventory goes negative here and we can't procure more
// material because of the minimum interval...
data->state->a_date = earliest_next;
continue;
}
// Now the normal reorder check
if (current_inventory > b->getMinimumInventory() - ROUNDING_ERROR
&& current_date < latest_next)
{
if (current_date == earliest_next)
earliest_next = Date::infinitePast;
continue;
}
// When we are within the minimum interval, we may need to increase the
// size of the previous procurements.
//
// TODO We should not only resize the existing procurements, but also
// consider inserting additional ones. See "buffer 10" in "buffer_procure_1" testcase,
// where some possible purchasing intervals are not used.
if (current_date == earliest_next
&& current_inventory < b->getMinimumInventory() - ROUNDING_ERROR)
{
for (int cnt=indexProcurements;
cnt>=0 && current_inventory < b->getMinimumInventory() - ROUNDING_ERROR;
cnt--)
{
double origqty = procurements[cnt]->getQuantity();
procurements[cnt]->setQuantity(
procurements[cnt]->getQuantity()
+ b->getMinimumInventory() - current_inventory);
produced += procurements[cnt]->getQuantity() - origqty;
current_inventory = produced - consumed;
}
if (current_inventory < -ROUNDING_ERROR
&& data->state->a_date > earliest_next
&& earliest_next > data->state->q_date
&& data->getSolver()->isMaterialConstrained()
&& data->constrainedPlanning)
// Resizing didn't work, and we still have shortage (not only compared
// to the minimum, but also to 0.
data->state->a_date = earliest_next;
}
// At this point, we know we need to reorder...
earliest_next = Date::infinitePast;
double order_qty = b->getMaximumInventory() - current_inventory;
do
{
if (order_qty <= 0)
{
if (latest_next == current_date && size_minimum)
// Forced to buy the minumum quantity
order_qty = size_minimum;
else
break;
}
// Create a procurement or update an existing one
indexProcurements++;
if (indexProcurements >= countProcurements)
{
// No existing procurement can be reused. Create a new one.
CommandCreateOperationPlan *a =
new CommandCreateOperationPlan(oper, order_qty,
Date::infinitePast, current_date, data->state->curDemand);
a->getOperationPlan()->setMotive(data->state->motive);
a->getOperationPlan()->insertInOperationplanList(); // TODO Not very nice: unregistered opplan in the list!
produced += a->getOperationPlan()->getQuantity();
order_qty -= a->getOperationPlan()->getQuantity();
data->add(a);
procurements.push_back(a->getOperationPlan());
++countProcurements;
}
else if (procurements[indexProcurements]->getDates().getEnd() == current_date
&& procurements[indexProcurements]->getQuantity() == order_qty)
{
// Reuse existing procurement unchanged.
produced += order_qty;
order_qty = 0;
}
else
{
// Update an existing procurement to meet current needs
CommandMoveOperationPlan *a =
new CommandMoveOperationPlan(procurements[indexProcurements], Date::infinitePast, current_date, order_qty);
produced += procurements[indexProcurements]->getQuantity();
order_qty -= procurements[indexProcurements]->getQuantity();
data->add(a);
}
if (b->getMinimumInterval())
{
earliest_next = current_date + b->getMinimumInterval();
break; // Only 1 procurement allowed at this time...
}
}
while (order_qty > ROUNDING_ERROR && order_qty >= size_minimum);
if (b->getMaximumInterval())
{
current_inventory = produced - consumed;
if (current_inventory >= b->getMaximumInventory()
&& cur == b->getFlowPlans().end())
// Nothing happens any more further in the future.
// Abort procuring based on the max inteval
latest_next = Date::infiniteFuture;
else
latest_next = current_date + b->getMaximumInterval();
}
}
// Get rid of extra procurements that have become redundant
indexProcurements++;
while (indexProcurements < countProcurements)
data->add(new CommandDeleteOperationPlan(procurements[indexProcurements++]));
// Create the answer
if (safetystock)
data->state->a_qty = 1.0;
else if (data->constrainedPlanning && (data->getSolver()->isFenceConstrained()
|| data->getSolver()->isLeadtimeConstrained()
|| data->getSolver()->isMaterialConstrained()))
{
// Check if the inventory drops below zero somewhere
double shortage = 0;
Date startdate;
for (Buffer::flowplanlist::const_iterator cur = b->getFlowPlans().begin();
cur != b->getFlowPlans().end(); ++cur)
if (cur->getDate() >= data->state->q_date
&& cur->getOnhand() < -ROUNDING_ERROR
&& cur->getOnhand() < shortage)
{
shortage = cur->getOnhand();
if (-shortage >= data->state->q_qty) break;
if (startdate == Date::infinitePast) startdate = cur->getDate();
}
if (shortage < 0)
{
// Answer a shorted quantity
data->state->a_qty = data->state->q_qty + shortage;
// Log a constraint
if (data->logConstraints && data->planningDemand)
data->planningDemand->getConstraints().push(
ProblemMaterialShortage::metadata, b, startdate, Date::infiniteFuture, // @todo calculate a better end date
-shortage);
// Nothing to promise...
if (data->state->a_qty < 0) data->state->a_qty = 0;
// Check the reply date
if (data->constrainedPlanning)
{
if (data->getSolver()->isFenceConstrained()
&& data->state->q_date < Plan::instance().getCurrent() + fence
&& data->state->a_date > Plan::instance().getCurrent() + fence)
data->state->a_date = Plan::instance().getCurrent() + fence;
if (data->getSolver()->isLeadtimeConstrained()
&& data->state->q_date < Plan::instance().getCurrent() + leadtime
&& data->state->a_date > Plan::instance().getCurrent() + leadtime)
data->state->a_date = Plan::instance().getCurrent() + leadtime; // TODO Doesn't consider calendar of the procurement operation...
if (latestlocked
&& data->state->q_date < latestlocked
&& data->state->a_date > latestlocked)
data->state->a_date = latestlocked;
}
}
else
// Answer the full quantity
data->state->a_qty = data->state->q_qty;
}
else
// Answer the full quantity
data->state->a_qty = data->state->q_qty;
// Increment the cost
if (b->getItem() && data->state->a_qty > 0.0)
data->state->a_cost += data->state->a_qty * b->getItem()->getPrice();
// Message
if (data->getSolver()->getLogLevel()>1)
{
if (safetystock)
logger << indent(b->getLevel()) << " Buffer '" << b->getName()
<< "' solved for safety stock" << endl;
else
logger << indent(b->getLevel()) << " Procurement buffer '" << b
<< "' answers: " << data->state->a_qty << " " << data->state->a_date
<< " " << data->state->a_cost << " " << data->state->a_penalty << endl;
}
}
}
<|endoftext|> |
<commit_before>// Copyright 2011 the V8 project authors. 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "../include/v8stdint.h"
#include "../include/v8-preparser.h"
#include "../src/preparse-data-format.h"
namespace i = v8::internal;
// This file is only used for testing the stand-alone preparser
// library.
// The first argument must be the path of a JavaScript source file, or
// the flags "-e" and the next argument is then the source of a JavaScript
// program.
// Optionally this can be followed by the word "throws" (case sensitive),
// which signals that the parsing is expected to throw - the default is
// to expect the parsing to not throw.
// The command line can further be followed by a message text (the
// *type* of the exception to throw), and even more optionally, the
// start and end position reported with the exception.
//
// This source file is preparsed and tested against the expectations, and if
// successful, the resulting preparser data is written to stdout.
// Diagnostic output is output on stderr.
// The source file must contain only ASCII characters (UTF-8 isn't supported).
// The file is read into memory, so it should have a reasonable size.
// Adapts an ASCII string to the UnicodeInputStream interface.
class AsciiInputStream : public v8::UnicodeInputStream {
public:
AsciiInputStream(const uint8_t* buffer, size_t length)
: buffer_(buffer),
end_offset_(static_cast<int>(length)),
offset_(0) { }
virtual ~AsciiInputStream() { }
virtual void PushBack(int32_t ch) {
offset_--;
#ifdef DEBUG
if (offset_ < 0 ||
(ch != ((offset_ >= end_offset_) ? -1 : buffer_[offset_]))) {
fprintf(stderr, "Invalid pushback: '%c' at offset %d.", ch, offset_);
exit(1);
}
#endif
}
virtual int32_t Next() {
if (offset_ >= end_offset_) {
offset_++; // Increment anyway to allow symmetric pushbacks.
return -1;
}
uint8_t next_char = buffer_[offset_];
#ifdef DEBUG
if (next_char > 0x7fu) {
fprintf(stderr, "Non-ASCII character in input: '%c'.", next_char);
exit(1);
}
#endif
offset_++;
return static_cast<int32_t>(next_char);
}
private:
const uint8_t* buffer_;
const int end_offset_;
int offset_;
};
bool ReadBuffer(FILE* source, void* buffer, size_t length) {
size_t actually_read = fread(buffer, 1, length, source);
return (actually_read == length);
}
bool WriteBuffer(FILE* dest, const void* buffer, size_t length) {
size_t actually_written = fwrite(buffer, 1, length, dest);
return (actually_written == length);
}
class PreparseDataInterpreter {
public:
PreparseDataInterpreter(const uint8_t* data, int length)
: data_(data), length_(length), message_(NULL) { }
~PreparseDataInterpreter() {
if (message_ != NULL) delete[] message_;
}
bool valid() {
int header_length =
i::PreparseDataConstants::kHeaderSize * sizeof(int); // NOLINT
return length_ >= header_length;
}
bool throws() {
return valid() &&
word(i::PreparseDataConstants::kHasErrorOffset) != 0;
}
const char* message() {
if (message_ != NULL) return message_;
if (!throws()) return NULL;
int text_pos = i::PreparseDataConstants::kHeaderSize +
i::PreparseDataConstants::kMessageTextPos;
int length = word(text_pos);
char* buffer = new char[length + 1];
for (int i = 1; i <= length; i++) {
int character = word(text_pos + i);
buffer[i - 1] = character;
}
buffer[length] = '\0';
message_ = buffer;
return buffer;
}
int beg_pos() {
if (!throws()) return -1;
return word(i::PreparseDataConstants::kHeaderSize +
i::PreparseDataConstants::kMessageStartPos);
}
int end_pos() {
if (!throws()) return -1;
return word(i::PreparseDataConstants::kHeaderSize +
i::PreparseDataConstants::kMessageEndPos);
}
private:
int word(int offset) {
const int* word_data = reinterpret_cast<const int*>(data_);
if (word_data + offset < reinterpret_cast<const int*>(data_ + length_)) {
return word_data[offset];
}
return -1;
}
const uint8_t* const data_;
const int length_;
const char* message_;
};
template <typename T>
class ScopedPointer {
public:
explicit ScopedPointer() : pointer_(NULL) {}
explicit ScopedPointer(T* pointer) : pointer_(pointer) {}
~ScopedPointer() { if (pointer_ != NULL) delete[] pointer_; }
T& operator[](int index) { return pointer_[index]; }
T* operator*() { return pointer_ ;}
T* operator=(T* new_value) {
if (pointer_ != NULL) delete[] pointer_;
pointer_ = new_value;
return new_value;
}
private:
T* pointer_;
};
void fail(v8::PreParserData* data, const char* message, ...) {
va_list args;
va_start(args, message);
vfprintf(stderr, message, args);
va_end(args);
fflush(stderr);
// Print preparser data to stdout.
uint32_t size = data->size();
fprintf(stderr, "LOG: data size: %u\n", size);
if (!WriteBuffer(stdout, data->data(), size)) {
perror("ERROR: Writing data");
fflush(stderr);
}
exit(EXIT_FAILURE);
}
bool IsFlag(const char* arg) {
// Anything starting with '-' is considered a flag.
// It's summarily ignored for now.
return arg[0] == '-';
}
struct ExceptionExpectation {
ExceptionExpectation()
: throws(false), type(NULL), beg_pos(-1), end_pos(-1) { }
bool throws;
const char* type;
int beg_pos;
int end_pos;
};
void CheckException(v8::PreParserData* data,
ExceptionExpectation* expects) {
PreparseDataInterpreter reader(data->data(), data->size());
if (expects->throws) {
if (!reader.throws()) {
if (expects->type == NULL) {
fail(data, "Didn't throw as expected\n");
} else {
fail(data, "Didn't throw \"%s\" as expected\n", expects->type);
}
}
if (expects->type != NULL) {
const char* actual_message = reader.message();
if (strcmp(expects->type, actual_message)) {
fail(data, "Wrong error message. Expected <%s>, found <%s> at %d..%d\n",
expects->type, actual_message, reader.beg_pos(), reader.end_pos());
}
}
if (expects->beg_pos >= 0) {
if (expects->beg_pos != reader.beg_pos()) {
fail(data, "Wrong error start position: Expected %i, found %i\n",
expects->beg_pos, reader.beg_pos());
}
}
if (expects->end_pos >= 0) {
if (expects->end_pos != reader.end_pos()) {
fail(data, "Wrong error end position: Expected %i, found %i\n",
expects->end_pos, reader.end_pos());
}
}
} else if (reader.throws()) {
const char* message = reader.message();
fail(data, "Throws unexpectedly with message: %s at location %d-%d\n",
message, reader.beg_pos(), reader.end_pos());
}
}
ExceptionExpectation ParseExpectation(int argc, const char* argv[]) {
ExceptionExpectation expects;
// Parse exception expectations from (the remainder of) the command line.
int arg_index = 0;
// Skip any flags.
while (argc > arg_index && IsFlag(argv[arg_index])) arg_index++;
if (argc > arg_index) {
if (strncmp("throws", argv[arg_index], 7)) {
// First argument after filename, if present, must be the verbatim
// "throws", marking that the preparsing should fail with an exception.
fail(NULL, "ERROR: Extra arguments not prefixed by \"throws\".\n");
}
expects.throws = true;
do {
arg_index++;
} while (argc > arg_index && IsFlag(argv[arg_index]));
if (argc > arg_index) {
// Next argument is the exception type identifier.
expects.type = argv[arg_index];
do {
arg_index++;
} while (argc > arg_index && IsFlag(argv[arg_index]));
if (argc > arg_index) {
expects.beg_pos = atoi(argv[arg_index]); // NOLINT
do {
arg_index++;
} while (argc > arg_index && IsFlag(argv[arg_index]));
if (argc > arg_index) {
expects.end_pos = atoi(argv[arg_index]); // NOLINT
}
}
}
}
return expects;
}
int main(int argc, const char* argv[]) {
// Parse command line.
// Format: preparser (<scriptfile> | -e "<source>")
// ["throws" [<exn-type> [<start> [<end>]]]]
// Any flags (except an initial -s) are ignored.
// Check for mandatory filename argument.
int arg_index = 1;
if (argc <= arg_index) {
fail(NULL, "ERROR: No filename on command line.\n");
}
const uint8_t* source = NULL;
const char* filename = argv[arg_index];
if (!strcmp(filename, "-e")) {
arg_index++;
if (argc <= arg_index) {
fail(NULL, "ERROR: No source after -e on command line.\n");
}
source = reinterpret_cast<const uint8_t*>(argv[arg_index]);
}
// Check remainder of command line for exception expectations.
arg_index++;
ExceptionExpectation expects =
ParseExpectation(argc - arg_index, argv + arg_index);
ScopedPointer<uint8_t> buffer;
size_t length;
if (source == NULL) {
// Open JS file.
FILE* input = fopen(filename, "rb");
if (input == NULL) {
perror("ERROR: Error opening file");
fflush(stderr);
return EXIT_FAILURE;
}
// Find length of JS file.
if (fseek(input, 0, SEEK_END) != 0) {
perror("ERROR: Error during seek");
fflush(stderr);
return EXIT_FAILURE;
}
length = static_cast<size_t>(ftell(input));
rewind(input);
// Read JS file into memory buffer.
buffer = new uint8_t[length];
if (!ReadBuffer(input, *buffer, length)) {
perror("ERROR: Reading file");
fflush(stderr);
return EXIT_FAILURE;
}
fclose(input);
source = *buffer;
} else {
length = strlen(reinterpret_cast<const char*>(source));
}
// Preparse input file.
AsciiInputStream input_buffer(source, length);
size_t kMaxStackSize = 64 * 1024 * sizeof(void*); // NOLINT
v8::PreParserData data = v8::Preparse(&input_buffer, kMaxStackSize);
// Fail if stack overflow.
if (data.stack_overflow()) {
fail(&data, "ERROR: Stack overflow\n");
}
// Check that the expected exception is thrown, if an exception is
// expected.
CheckException(&data, &expects);
return EXIT_SUCCESS;
}
<commit_msg>Ignore flags with arguments in preparser-process.<commit_after>// Copyright 2011 the V8 project authors. 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "../include/v8stdint.h"
#include "../include/v8-preparser.h"
#include "../src/preparse-data-format.h"
namespace i = v8::internal;
// This file is only used for testing the stand-alone preparser
// library.
// The first argument must be the path of a JavaScript source file, or
// the flags "-e" and the next argument is then the source of a JavaScript
// program.
// Optionally this can be followed by the word "throws" (case sensitive),
// which signals that the parsing is expected to throw - the default is
// to expect the parsing to not throw.
// The command line can further be followed by a message text (the
// *type* of the exception to throw), and even more optionally, the
// start and end position reported with the exception.
//
// This source file is preparsed and tested against the expectations, and if
// successful, the resulting preparser data is written to stdout.
// Diagnostic output is output on stderr.
// The source file must contain only ASCII characters (UTF-8 isn't supported).
// The file is read into memory, so it should have a reasonable size.
// Adapts an ASCII string to the UnicodeInputStream interface.
class AsciiInputStream : public v8::UnicodeInputStream {
public:
AsciiInputStream(const uint8_t* buffer, size_t length)
: buffer_(buffer),
end_offset_(static_cast<int>(length)),
offset_(0) { }
virtual ~AsciiInputStream() { }
virtual void PushBack(int32_t ch) {
offset_--;
#ifdef DEBUG
if (offset_ < 0 ||
(ch != ((offset_ >= end_offset_) ? -1 : buffer_[offset_]))) {
fprintf(stderr, "Invalid pushback: '%c' at offset %d.", ch, offset_);
exit(1);
}
#endif
}
virtual int32_t Next() {
if (offset_ >= end_offset_) {
offset_++; // Increment anyway to allow symmetric pushbacks.
return -1;
}
uint8_t next_char = buffer_[offset_];
#ifdef DEBUG
if (next_char > 0x7fu) {
fprintf(stderr, "Non-ASCII character in input: '%c'.", next_char);
exit(1);
}
#endif
offset_++;
return static_cast<int32_t>(next_char);
}
private:
const uint8_t* buffer_;
const int end_offset_;
int offset_;
};
bool ReadBuffer(FILE* source, void* buffer, size_t length) {
size_t actually_read = fread(buffer, 1, length, source);
return (actually_read == length);
}
bool WriteBuffer(FILE* dest, const void* buffer, size_t length) {
size_t actually_written = fwrite(buffer, 1, length, dest);
return (actually_written == length);
}
class PreparseDataInterpreter {
public:
PreparseDataInterpreter(const uint8_t* data, int length)
: data_(data), length_(length), message_(NULL) { }
~PreparseDataInterpreter() {
if (message_ != NULL) delete[] message_;
}
bool valid() {
int header_length =
i::PreparseDataConstants::kHeaderSize * sizeof(int); // NOLINT
return length_ >= header_length;
}
bool throws() {
return valid() &&
word(i::PreparseDataConstants::kHasErrorOffset) != 0;
}
const char* message() {
if (message_ != NULL) return message_;
if (!throws()) return NULL;
int text_pos = i::PreparseDataConstants::kHeaderSize +
i::PreparseDataConstants::kMessageTextPos;
int length = word(text_pos);
char* buffer = new char[length + 1];
for (int i = 1; i <= length; i++) {
int character = word(text_pos + i);
buffer[i - 1] = character;
}
buffer[length] = '\0';
message_ = buffer;
return buffer;
}
int beg_pos() {
if (!throws()) return -1;
return word(i::PreparseDataConstants::kHeaderSize +
i::PreparseDataConstants::kMessageStartPos);
}
int end_pos() {
if (!throws()) return -1;
return word(i::PreparseDataConstants::kHeaderSize +
i::PreparseDataConstants::kMessageEndPos);
}
private:
int word(int offset) {
const int* word_data = reinterpret_cast<const int*>(data_);
if (word_data + offset < reinterpret_cast<const int*>(data_ + length_)) {
return word_data[offset];
}
return -1;
}
const uint8_t* const data_;
const int length_;
const char* message_;
};
template <typename T>
class ScopedPointer {
public:
explicit ScopedPointer() : pointer_(NULL) {}
explicit ScopedPointer(T* pointer) : pointer_(pointer) {}
~ScopedPointer() { if (pointer_ != NULL) delete[] pointer_; }
T& operator[](int index) { return pointer_[index]; }
T* operator*() { return pointer_ ;}
T* operator=(T* new_value) {
if (pointer_ != NULL) delete[] pointer_;
pointer_ = new_value;
return new_value;
}
private:
T* pointer_;
};
void fail(v8::PreParserData* data, const char* message, ...) {
va_list args;
va_start(args, message);
vfprintf(stderr, message, args);
va_end(args);
fflush(stderr);
// Print preparser data to stdout.
uint32_t size = data->size();
fprintf(stderr, "LOG: data size: %u\n", size);
if (!WriteBuffer(stdout, data->data(), size)) {
perror("ERROR: Writing data");
fflush(stderr);
}
exit(EXIT_FAILURE);
}
bool IsFlag(const char* arg) {
// Anything starting with '-' is considered a flag.
// It's summarily ignored for now.
return arg[0] == '-';
}
struct ExceptionExpectation {
ExceptionExpectation()
: throws(false), type(NULL), beg_pos(-1), end_pos(-1) { }
bool throws;
const char* type;
int beg_pos;
int end_pos;
};
void CheckException(v8::PreParserData* data,
ExceptionExpectation* expects) {
PreparseDataInterpreter reader(data->data(), data->size());
if (expects->throws) {
if (!reader.throws()) {
if (expects->type == NULL) {
fail(data, "Didn't throw as expected\n");
} else {
fail(data, "Didn't throw \"%s\" as expected\n", expects->type);
}
}
if (expects->type != NULL) {
const char* actual_message = reader.message();
if (strcmp(expects->type, actual_message)) {
fail(data, "Wrong error message. Expected <%s>, found <%s> at %d..%d\n",
expects->type, actual_message, reader.beg_pos(), reader.end_pos());
}
}
if (expects->beg_pos >= 0) {
if (expects->beg_pos != reader.beg_pos()) {
fail(data, "Wrong error start position: Expected %i, found %i\n",
expects->beg_pos, reader.beg_pos());
}
}
if (expects->end_pos >= 0) {
if (expects->end_pos != reader.end_pos()) {
fail(data, "Wrong error end position: Expected %i, found %i\n",
expects->end_pos, reader.end_pos());
}
}
} else if (reader.throws()) {
const char* message = reader.message();
fail(data, "Throws unexpectedly with message: %s at location %d-%d\n",
message, reader.beg_pos(), reader.end_pos());
}
}
ExceptionExpectation ParseExpectation(int argc, const char* argv[]) {
// Parse ["throws" [<exn-type> [<start> [<end>]]]].
ExceptionExpectation expects;
int arg_index = 0;
while (argc > arg_index && strncmp("throws", argv[arg_index], 7)) {
arg_index++;
}
if (argc > arg_index) {
expects.throws = true;
arg_index++;
if (argc > arg_index && !IsFlag(argv[arg_index])) {
expects.type = argv[arg_index];
arg_index++;
if (argc > arg_index && !IsFlag(argv[arg_index])) {
expects.beg_pos = atoi(argv[arg_index]); // NOLINT
arg_index++;
if (argc > arg_index && !IsFlag(argv[arg_index])) {
expects.end_pos = atoi(argv[arg_index]); // NOLINT
}
}
}
}
return expects;
}
int main(int argc, const char* argv[]) {
// Parse command line.
// Format: preparser (<scriptfile> | -e "<source>")
// ["throws" [<exn-type> [<start> [<end>]]]]
// Any flags (except an initial -e) are ignored.
// Flags must not separate "throws" and its arguments.
// Check for mandatory filename argument.
int arg_index = 1;
if (argc <= arg_index) {
fail(NULL, "ERROR: No filename on command line.\n");
}
const uint8_t* source = NULL;
const char* filename = argv[arg_index];
if (!strcmp(filename, "-e")) {
arg_index++;
if (argc <= arg_index) {
fail(NULL, "ERROR: No source after -e on command line.\n");
}
source = reinterpret_cast<const uint8_t*>(argv[arg_index]);
}
// Check remainder of command line for exception expectations.
arg_index++;
ExceptionExpectation expects =
ParseExpectation(argc - arg_index, argv + arg_index);
ScopedPointer<uint8_t> buffer;
size_t length;
if (source == NULL) {
// Open JS file.
FILE* input = fopen(filename, "rb");
if (input == NULL) {
perror("ERROR: Error opening file");
fflush(stderr);
return EXIT_FAILURE;
}
// Find length of JS file.
if (fseek(input, 0, SEEK_END) != 0) {
perror("ERROR: Error during seek");
fflush(stderr);
return EXIT_FAILURE;
}
length = static_cast<size_t>(ftell(input));
rewind(input);
// Read JS file into memory buffer.
buffer = new uint8_t[length];
if (!ReadBuffer(input, *buffer, length)) {
perror("ERROR: Reading file");
fflush(stderr);
return EXIT_FAILURE;
}
fclose(input);
source = *buffer;
} else {
length = strlen(reinterpret_cast<const char*>(source));
}
// Preparse input file.
AsciiInputStream input_buffer(source, length);
size_t kMaxStackSize = 64 * 1024 * sizeof(void*); // NOLINT
v8::PreParserData data = v8::Preparse(&input_buffer, kMaxStackSize);
// Fail if stack overflow.
if (data.stack_overflow()) {
fail(&data, "ERROR: Stack overflow\n");
}
// Check that the expected exception is thrown, if an exception is
// expected.
CheckException(&data, &expects);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>//Author: Eddy Offermann
// This macro shows several ways to invert a matrix . Each method
// is a trade-off between accuracy of the inversion and speed.
// Which method to chose depends on "how well-behaved" the matrix is.
// This is best checked through a call to Condition(), available in each
// decomposition class. A second possibilty (less preferred) would be to
// check the determinant
//
// USAGE
// -----
// This macro can be execued via CINT or via ACLIC
// - via CINT, do
// root > .x invertMatrix.C
// - via ACLIC
// root > gSystem->Load("libMatrix");
// root > .x invertMatrix.C+
#ifndef __CINT__
#include "Riostream.h"
#include "TMath.h"
#include "TMatrixD.h"
#include "TMatrixDLazy.h"
#include "TVectorD.h"
#include "TDecompLU.h"
#include "TDecompSVD.h"
#endif
void invertMatrix(Int_t msize=6)
{
#ifdef __CINT__
gSystem->Load("libMatrix");
#endif
if (msize < 2 || msize > 10) {
cout << "2 <= msize <= 10" <<endl;
return;
}
cout << "--------------------------------------------------------" <<endl;
cout << "Inversion results for a ("<<msize<<","<<msize<<") matrix" <<endl;
cout << "For each inversion procedure we check the maxmimum size " <<endl;
cout << "of the off-diagonal elements of Inv(A) * A " <<endl;
cout << "--------------------------------------------------------" <<endl;
TMatrixT<double> H_square = THilbertMatrixD(msize,msize);
// 1. InvertFast(Double_t *det=0)
// It is identical to Invert() for sizes > 6 x 6 but for smaller sizes, the
// inversion is performed according to Cramer's rule by explicitly calculating
// all Jacobi's sub-determinants . For instance for a 6 x 6 matrix this means:
// # of 5 x 5 determinant : 36
// # of 4 x 4 determinant : 75
// # of 3 x 3 determinant : 80
// # of 2 x 2 determinant : 45 (see TMatrixD/FCramerInv.cxx)
//
// The only "quality" control in this process is to check whether the 6 x 6
// determinant is unequal 0 . But speed gains are significant compared to Invert() ,
// upto an order of magnitude for sizes <= 4 x 4
//
// The inversion is done "in place", so the original matrix will be overwritten
// If a pointer to a Double_t is supplied the determinant is calculated
//
cout << "1. Use .InvertFast(&det)" <<endl;
if (msize > 6)
cout << " for ("<<msize<<","<<msize<<") this is identical to .Invert(&det)" <<endl;
Double_t det1;
TMatrixD H1 = H_square;
H1.InvertFast(&det1);
// Get the maximum off-diagonal matrix value . One way to do this is to set the
// diagonal to zero .
TMatrixD U1(H1,TMatrixD::kMult,H_square);
TMatrixDDiag diag1(U1); diag1 = 0.0;
const Double_t U1_max_offdiag = (U1.Abs()).Max();
cout << " Maximum off-diagonal = " << U1_max_offdiag << endl;
cout << " Determinant = " << det1 <<endl;
// 2. Invert(Double_t *det=0)
// Again the inversion is performed in place .
// It consists out of a sequence of calls to the decomposition classes . For instance
// for the general dense matrix TMatrixD the LU decomposition is invoked:
// - The matrix is decomposed using a scheme according to Crout which involves
// "implicit partial pivoting", see for instance Num. Recip. (we have also available
// a decomposition scheme that does not the scaling and is therefore even slightly
// faster but less stable)
// With each decomposition, a tolerance has to be specified . If this tolerance
// requirement is not met, the matrix is regarded as being singular. The value
// passed to this decomposition, is the data member fTol of the matrix . Its
// default value is DBL_EPSILON, which is defined as the smallest nuber so that
// 1+DBL_EPSILON > 1
// - The last step is a standard forward/backward substitution .
//
// It is important to realize that both InvertFast() and Invert() are "one-shot" deals , speed
// comes at a price . If something goes wrong because the matrix is (near) singular, you have
// overwritten your original matrix and no factorization is available anymore to get more
// information like condition number or change the tolerance number .
//
// All other calls in the matrix classes involving inversion like the ones with the "smart"
// constructors (kInverted,kInvMult...) use this inversion method .
//
cout << "2. Use .Invert(&det)" <<endl;
Double_t det2;
TMatrixT<double> H2 = H_square;
H2.Invert(&det2);
TMatrixD U2(H2,TMatrixD::kMult,H_square);
TMatrixDDiag diag2(U2); diag2 = 0.0;
const Double_t U2_max_offdiag = (U2.Abs()).Max();
cout << " Maximum off-diagonal = " << U2_max_offdiag << endl;
cout << " Determinant = " << det2 <<endl;
// 3. Inversion through LU decomposition
// The (default) algorithms used are similar to 2. (Not identical because in 2, the whole
// calculation is done "in-place". Here the orginal matrix is copied (so more memory
// management => slower) and several operations can be performed without having to repeat
// the decomposition step .
// Inverting a matrix is nothing else than solving a set of equations where the rhs is given
// by the unit matrix, so the steps to take are identical to those solving a linear equation :
//
cout << "3. Use TDecompLU" <<endl;
TMatrixD H3 = H_square;
TDecompLU lu(H_square);
// Any operation that requires a decomposition will trigger it . The class keeps
// an internal state so that following operations will not perform the decomposition again
// unless the matrix is changed through SetMatrix(..)
// One might want to proceed more cautiously by invoking first Decompose() and check its
// return value before proceeding....
lu.Invert(H3);
Double_t d1_lu; Double_t d2_lu;
lu.Det(d1_lu,d2_lu);
Double_t det3 = d1_lu*TMath::Power(2.,d2_lu);
TMatrixD U3(H3,TMatrixD::kMult,H_square);
TMatrixDDiag diag3(U3); diag3 = 0.0;
const Double_t U3_max_offdiag = (U3.Abs()).Max();
cout << " Maximum off-diagonal = " << U3_max_offdiag << endl;
cout << " Determinant = " << det3 <<endl;
// 4. Inversion through SVD decomposition
// For SVD and QRH, the (n x m) matrix does only have to fulfill n >=m . In case n > m
// a pseudo-inverse is calculated
cout << "4. Use TDecompSVD on non-square matrix" <<endl;
TMatrixD H_nsquare = THilbertMatrixD(msize,msize-1);
TDecompSVD svd(H_nsquare);
TMatrixD H4 = svd.Invert();
Double_t d1_svd; Double_t d2_svd;
svd.Det(d1_svd,d2_svd);
Double_t det4 = d1_svd*TMath::Power(2.,d2_svd);
TMatrixD U4(H4,TMatrixD::kMult,H_nsquare);
TMatrixDDiag diag4(U4); diag4 = 0.0;
const Double_t U4_max_offdiag = (U4.Abs()).Max();
cout << " Maximum off-diagonal = " << U4_max_offdiag << endl;
cout << " Determinant = " << det4 <<endl;
}
<commit_msg>Remove debug statements<commit_after>//Author: Eddy Offermann
// This macro shows several ways to invert a matrix . Each method
// is a trade-off between accuracy of the inversion and speed.
// Which method to chose depends on "how well-behaved" the matrix is.
// This is best checked through a call to Condition(), available in each
// decomposition class. A second possibilty (less preferred) would be to
// check the determinant
//
// USAGE
// -----
// This macro can be execued via CINT or via ACLIC
// - via CINT, do
// root > .x invertMatrix.C
// - via ACLIC
// root > gSystem->Load("libMatrix");
// root > .x invertMatrix.C+
#ifndef __CINT__
#include "Riostream.h"
#include "TMath.h"
#include "TMatrixD.h"
#include "TMatrixDLazy.h"
#include "TVectorD.h"
#include "TDecompLU.h"
#include "TDecompSVD.h"
#endif
void invertMatrix(Int_t msize=6)
{
#ifdef __CINT__
gSystem->Load("libMatrix");
#endif
if (msize < 2 || msize > 10) {
cout << "2 <= msize <= 10" <<endl;
return;
}
cout << "--------------------------------------------------------" <<endl;
cout << "Inversion results for a ("<<msize<<","<<msize<<") matrix" <<endl;
cout << "For each inversion procedure we check the maxmimum size " <<endl;
cout << "of the off-diagonal elements of Inv(A) * A " <<endl;
cout << "--------------------------------------------------------" <<endl;
TMatrixD H_square = THilbertMatrixD(msize,msize);
// 1. InvertFast(Double_t *det=0)
// It is identical to Invert() for sizes > 6 x 6 but for smaller sizes, the
// inversion is performed according to Cramer's rule by explicitly calculating
// all Jacobi's sub-determinants . For instance for a 6 x 6 matrix this means:
// # of 5 x 5 determinant : 36
// # of 4 x 4 determinant : 75
// # of 3 x 3 determinant : 80
// # of 2 x 2 determinant : 45 (see TMatrixD/FCramerInv.cxx)
//
// The only "quality" control in this process is to check whether the 6 x 6
// determinant is unequal 0 . But speed gains are significant compared to Invert() ,
// upto an order of magnitude for sizes <= 4 x 4
//
// The inversion is done "in place", so the original matrix will be overwritten
// If a pointer to a Double_t is supplied the determinant is calculated
//
cout << "1. Use .InvertFast(&det)" <<endl;
if (msize > 6)
cout << " for ("<<msize<<","<<msize<<") this is identical to .Invert(&det)" <<endl;
Double_t det1;
TMatrixD H1 = H_square;
H1.InvertFast(&det1);
// Get the maximum off-diagonal matrix value . One way to do this is to set the
// diagonal to zero .
TMatrixD U1(H1,TMatrixD::kMult,H_square);
TMatrixDDiag diag1(U1); diag1 = 0.0;
const Double_t U1_max_offdiag = (U1.Abs()).Max();
cout << " Maximum off-diagonal = " << U1_max_offdiag << endl;
cout << " Determinant = " << det1 <<endl;
// 2. Invert(Double_t *det=0)
// Again the inversion is performed in place .
// It consists out of a sequence of calls to the decomposition classes . For instance
// for the general dense matrix TMatrixD the LU decomposition is invoked:
// - The matrix is decomposed using a scheme according to Crout which involves
// "implicit partial pivoting", see for instance Num. Recip. (we have also available
// a decomposition scheme that does not the scaling and is therefore even slightly
// faster but less stable)
// With each decomposition, a tolerance has to be specified . If this tolerance
// requirement is not met, the matrix is regarded as being singular. The value
// passed to this decomposition, is the data member fTol of the matrix . Its
// default value is DBL_EPSILON, which is defined as the smallest nuber so that
// 1+DBL_EPSILON > 1
// - The last step is a standard forward/backward substitution .
//
// It is important to realize that both InvertFast() and Invert() are "one-shot" deals , speed
// comes at a price . If something goes wrong because the matrix is (near) singular, you have
// overwritten your original matrix and no factorization is available anymore to get more
// information like condition number or change the tolerance number .
//
// All other calls in the matrix classes involving inversion like the ones with the "smart"
// constructors (kInverted,kInvMult...) use this inversion method .
//
cout << "2. Use .Invert(&det)" <<endl;
Double_t det2;
TMatrixD H2 = H_square;
H2.Invert(&det2);
TMatrixD U2(H2,TMatrixD::kMult,H_square);
TMatrixDDiag diag2(U2); diag2 = 0.0;
const Double_t U2_max_offdiag = (U2.Abs()).Max();
cout << " Maximum off-diagonal = " << U2_max_offdiag << endl;
cout << " Determinant = " << det2 <<endl;
// 3. Inversion through LU decomposition
// The (default) algorithms used are similar to 2. (Not identical because in 2, the whole
// calculation is done "in-place". Here the orginal matrix is copied (so more memory
// management => slower) and several operations can be performed without having to repeat
// the decomposition step .
// Inverting a matrix is nothing else than solving a set of equations where the rhs is given
// by the unit matrix, so the steps to take are identical to those solving a linear equation :
//
cout << "3. Use TDecompLU" <<endl;
TMatrixD H3 = H_square;
TDecompLU lu(H_square);
// Any operation that requires a decomposition will trigger it . The class keeps
// an internal state so that following operations will not perform the decomposition again
// unless the matrix is changed through SetMatrix(..)
// One might want to proceed more cautiously by invoking first Decompose() and check its
// return value before proceeding....
lu.Invert(H3);
Double_t d1_lu; Double_t d2_lu;
lu.Det(d1_lu,d2_lu);
Double_t det3 = d1_lu*TMath::Power(2.,d2_lu);
TMatrixD U3(H3,TMatrixD::kMult,H_square);
TMatrixDDiag diag3(U3); diag3 = 0.0;
const Double_t U3_max_offdiag = (U3.Abs()).Max();
cout << " Maximum off-diagonal = " << U3_max_offdiag << endl;
cout << " Determinant = " << det3 <<endl;
// 4. Inversion through SVD decomposition
// For SVD and QRH, the (n x m) matrix does only have to fulfill n >=m . In case n > m
// a pseudo-inverse is calculated
cout << "4. Use TDecompSVD on non-square matrix" <<endl;
TMatrixD H_nsquare = THilbertMatrixD(msize,msize-1);
TDecompSVD svd(H_nsquare);
TMatrixD H4 = svd.Invert();
Double_t d1_svd; Double_t d2_svd;
svd.Det(d1_svd,d2_svd);
Double_t det4 = d1_svd*TMath::Power(2.,d2_svd);
TMatrixD U4(H4,TMatrixD::kMult,H_nsquare);
TMatrixDDiag diag4(U4); diag4 = 0.0;
const Double_t U4_max_offdiag = (U4.Abs()).Max();
cout << " Maximum off-diagonal = " << U4_max_offdiag << endl;
cout << " Determinant = " << det4 <<endl;
}
<|endoftext|> |
<commit_before>// Copyright (C) 2010, Vaclav Haisman. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modifica-
// tion, 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 ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
// DING, 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 <log4cplus/helpers/stringhelper.h>
#include <log4cplus/helpers/loglog.h>
#ifdef LOG4CPLUS_HAVE_LIMITS_H
#include <limits.h>
#endif
#ifdef LOG4CPLUS_HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef LOG4CPLUS_HAVE_WCHAR_H
#include <wchar.h>
#endif
#include <cassert>
namespace log4cplus
{
namespace helpers
{
#if defined (UNICODE)
#if defined (LOG4CPLUS_WORKING_C_LOCALE)
static
void
tostring_internal (std::string & result, wchar_t const * src, std::size_t size)
{
std::size_t result_size = size + size / 3 + 1;
std::size_t ret;
result.resize (result_size);
while ((ret = wcstombs (&result[0], src, result_size)) == result_size)
{
result_size *= 2;
result.resize (result_size);
}
if (ret != static_cast<std::size_t>(-1))
result.resize (ret);
else
{
getLogLog ().error (LOG4CPLUS_TEXT ("tostring_internal: conversion error"));
result.clear ();
}
}
std::string
tostring (const std::wstring & src)
{
std::string ret;
tostring_internal (ret, src.c_str (), src.size ());
return ret;
}
std::string
tostring (wchar_t const * src)
{
assert (src);
std::string ret;
tostring_internal (ret, src, std::wcslen (src));
return ret;
}
static
void
towstring_internal (std::wstring & result, char const * src, std::size_t size)
{
std::size_t result_size = size + 1;
std::size_t ret;
result.resize (result_size);
while ((ret = mbstowcs (&result[0], src, result_size)) == result_size)
{
result_size *= 2;
result.resize (result_size);
}
if (ret != static_cast<std::size_t>(-1))
result.resize (ret);
else
{
getLogLog ().error (LOG4CPLUS_TEXT ("towstring_internal: conversion error"));
result.clear ();
}
}
std::wstring
towstring (const std::string& src)
{
std::wstring ret;
towstring_internal (ret, src.c_str (), src.size ());
return ret;
}
std::wstring
towstring (char const * src)
{
assert (src);
std::wstring ret;
towstring_internal (ret, src, std::strlen (src));
return ret;
}
#endif // LOG4CPLUS_WORKING_C_LOCALE
#endif // UNICODE
} // namespace helpers
} // namespace log4cplus
<commit_msg>stringhelper-clocale.cxx: Include <cwchar> for std::wcslen() and <cstring> for std::strlen().<commit_after>// Copyright (C) 2010, Vaclav Haisman. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modifica-
// tion, 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 ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
// DING, 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 <log4cplus/helpers/stringhelper.h>
#include <log4cplus/helpers/loglog.h>
#ifdef LOG4CPLUS_HAVE_LIMITS_H
#include <limits.h>
#endif
#ifdef LOG4CPLUS_HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef LOG4CPLUS_HAVE_WCHAR_H
#include <wchar.h>
#endif
#include <cstring>
#include <cwchar>
#include <cassert>
namespace log4cplus
{
namespace helpers
{
#if defined (UNICODE)
#if defined (LOG4CPLUS_WORKING_C_LOCALE)
static
void
tostring_internal (std::string & result, wchar_t const * src, std::size_t size)
{
std::size_t result_size = size + size / 3 + 1;
std::size_t ret;
result.resize (result_size);
while ((ret = wcstombs (&result[0], src, result_size)) == result_size)
{
result_size *= 2;
result.resize (result_size);
}
if (ret != static_cast<std::size_t>(-1))
result.resize (ret);
else
{
getLogLog ().error (LOG4CPLUS_TEXT ("tostring_internal: conversion error"));
result.clear ();
}
}
std::string
tostring (const std::wstring & src)
{
std::string ret;
tostring_internal (ret, src.c_str (), src.size ());
return ret;
}
std::string
tostring (wchar_t const * src)
{
assert (src);
std::string ret;
tostring_internal (ret, src, std::wcslen (src));
return ret;
}
static
void
towstring_internal (std::wstring & result, char const * src, std::size_t size)
{
std::size_t result_size = size + 1;
std::size_t ret;
result.resize (result_size);
while ((ret = mbstowcs (&result[0], src, result_size)) == result_size)
{
result_size *= 2;
result.resize (result_size);
}
if (ret != static_cast<std::size_t>(-1))
result.resize (ret);
else
{
getLogLog ().error (LOG4CPLUS_TEXT ("towstring_internal: conversion error"));
result.clear ();
}
}
std::wstring
towstring (const std::string& src)
{
std::wstring ret;
towstring_internal (ret, src.c_str (), src.size ());
return ret;
}
std::wstring
towstring (char const * src)
{
assert (src);
std::wstring ret;
towstring_internal (ret, src, std::strlen (src));
return ret;
}
#endif // LOG4CPLUS_WORKING_C_LOCALE
#endif // UNICODE
} // namespace helpers
} // namespace log4cplus
<|endoftext|> |
<commit_before>/*
qgpgmekeyformailboxjob.cpp
This file is part of qgpgme, the Qt API binding for gpgme
Copyright (c) 2016 by Bundesamt für Sicherheit in der Informationstechnik
Software engineering by Intevation GmbH
QGpgME 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.
QGpgME is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "qgpgmegpgcardjob.h"
#include <QStringList>
#include <QFileInfo>
#include <QDir>
#include <QProcess>
#include "util.h"
/* We cannot have a timeout because key generation can
* take ages. Well maybe 10 minutes. */
#define TIMEOUT_VALUE (600000)
#include <tuple>
using namespace GpgME;
using namespace QGpgME;
QGpgMEGpgCardJob::QGpgMEGpgCardJob()
: mixin_type(nullptr)
{
lateInitialization();
}
QGpgMEGpgCardJob::~QGpgMEGpgCardJob() {}
static QString getGpgCardPath()
{
auto bindir = QString::fromLocal8Bit(dirInfo("bindir"));
if (bindir.isEmpty()) {
return QString();
}
const QFileInfo fi(QDir(bindir).absoluteFilePath(QStringLiteral("gpg-card")));
if (fi.exists() && fi.isExecutable()) {
return fi.absoluteFilePath();
}
return QString();
}
static QGpgMEGpgCardJob::result_type do_work(const QStringList &cmds, const QString &path)
{
QStringList args;
args << QStringLiteral("--with-colons");
args += cmds;
QProcess proc;
proc.setProgram(path);
proc.setArguments(args);
proc.start();
if (!proc.waitForStarted()) {
return std::make_tuple (QString(), QString(), 1, QString(), Error());
}
if (!proc.waitForFinished(TIMEOUT_VALUE)) {
return std::make_tuple (QString(), QString(), 1, QString(), Error());
}
if (proc.exitStatus() == QProcess::NormalExit) {
return std::make_tuple (QString::fromUtf8(proc.readAllStandardOutput()),
QString::fromUtf8(proc.readAllStandardError()), proc.exitCode(),
QString(), Error());
}
return std::make_tuple (QString::fromUtf8(proc.readAllStandardOutput()),
QString::fromUtf8(proc.readAllStandardError()), 1,
QString(), Error());
}
Error QGpgMEGpgCardJob::start(const QStringList &cmds)
{
const auto cardpath = getGpgCardPath ();
if (cardpath.isEmpty()) {
return Error(make_error(GPG_ERR_NOT_SUPPORTED));
}
run(std::bind(&do_work, cmds, cardpath));
return Error();
}
Error QGpgMEGpgCardJob::exec(const QStringList &cmds, QString &std_out, QString &std_err, int &exitCode)
{
const auto cardpath = getGpgCardPath ();
if (cardpath.isEmpty()) {
return Error(make_error(GPG_ERR_NOT_SUPPORTED));
}
const result_type r = do_work(cmds, cardpath);
resultHook(r);
std_out = std::get<0>(r);
std_err = std::get<1>(r);
exitCode = std::get<2>(r);
return exitCode == 0 ? Error() : Error(make_error(GPG_ERR_GENERAL));
}
#include "qgpgmegpgcardjob.moc"
<commit_msg>qt: Add dummy context to make mixin happy<commit_after>/*
qgpgmekeyformailboxjob.cpp
This file is part of qgpgme, the Qt API binding for gpgme
Copyright (c) 2016 by Bundesamt für Sicherheit in der Informationstechnik
Software engineering by Intevation GmbH
QGpgME 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.
QGpgME is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "qgpgmegpgcardjob.h"
#include <QStringList>
#include <QFileInfo>
#include <QDir>
#include <QProcess>
#include "util.h"
/* We cannot have a timeout because key generation can
* take ages. Well maybe 10 minutes. */
#define TIMEOUT_VALUE (600000)
#include <tuple>
using namespace GpgME;
using namespace QGpgME;
QGpgMEGpgCardJob::QGpgMEGpgCardJob()
: mixin_type(/* needed for the mixer */
Context::createForEngine(GpgME::SpawnEngine).release())
{
lateInitialization();
}
QGpgMEGpgCardJob::~QGpgMEGpgCardJob() {}
static QString getGpgCardPath()
{
auto bindir = QString::fromLocal8Bit(dirInfo("bindir"));
if (bindir.isEmpty()) {
return QString();
}
const QFileInfo fi(QDir(bindir).absoluteFilePath(QStringLiteral("gpg-card")));
if (fi.exists() && fi.isExecutable()) {
return fi.absoluteFilePath();
}
return QString();
}
static QGpgMEGpgCardJob::result_type do_work(const QStringList &cmds, const QString &path)
{
QStringList args;
args << QStringLiteral("--with-colons");
args += cmds;
QProcess proc;
proc.setProgram(path);
proc.setArguments(args);
proc.start();
if (!proc.waitForStarted()) {
return std::make_tuple (QString(), QString(), 1, QString(), Error());
}
if (!proc.waitForFinished(TIMEOUT_VALUE)) {
return std::make_tuple (QString(), QString(), 1, QString(), Error());
}
if (proc.exitStatus() == QProcess::NormalExit) {
return std::make_tuple (QString::fromUtf8(proc.readAllStandardOutput()),
QString::fromUtf8(proc.readAllStandardError()), proc.exitCode(),
QString(), Error());
}
return std::make_tuple (QString::fromUtf8(proc.readAllStandardOutput()),
QString::fromUtf8(proc.readAllStandardError()), 1,
QString(), Error());
}
Error QGpgMEGpgCardJob::start(const QStringList &cmds)
{
const auto cardpath = getGpgCardPath ();
if (cardpath.isEmpty()) {
return Error(make_error(GPG_ERR_NOT_SUPPORTED));
}
run(std::bind(&do_work, cmds, cardpath));
return Error();
}
Error QGpgMEGpgCardJob::exec(const QStringList &cmds, QString &std_out, QString &std_err, int &exitCode)
{
const auto cardpath = getGpgCardPath ();
if (cardpath.isEmpty()) {
return Error(make_error(GPG_ERR_NOT_SUPPORTED));
}
const result_type r = do_work(cmds, cardpath);
resultHook(r);
std_out = std::get<0>(r);
std_err = std::get<1>(r);
exitCode = std::get<2>(r);
return exitCode == 0 ? Error() : Error(make_error(GPG_ERR_GENERAL));
}
#include "qgpgmegpgcardjob.moc"
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: document.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: obo $ $Date: 2008-02-26 14:48:32 $
*
* 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 _DOCUMENT_HXX
#define _DOCUMENT_HXX
#include <list>
#include <set>
#include <sal/types.h>
#include <cppuhelper/implbase5.hxx>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Exception.hpp>
#include <com/sun/star/beans/StringPair.hpp>
#include <com/sun/star/xml/dom/XNode.hpp>
#include <com/sun/star/xml/dom/XAttr.hpp>
#include <com/sun/star/xml/dom/XElement.hpp>
#include <com/sun/star/xml/dom/XDOMImplementation.hpp>
#include <com/sun/star/xml/dom/events/XDocumentEvent.hpp>
#include <com/sun/star/xml/dom/events/XEvent.hpp>
#include <com/sun/star/xml/sax/XSAXSerializable.hpp>
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#include <com/sun/star/io/XActiveDataSource.hpp>
#include <com/sun/star/io/XActiveDataControl.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XStreamListener.hpp>
#include "node.hxx"
#include <libxml/tree.h>
using namespace std;
using namespace rtl;
using namespace com::sun::star;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::xml::sax;
using namespace com::sun::star::io;
using namespace com::sun::star::xml::dom;
using namespace com::sun::star::xml::dom::events;
namespace DOM
{
class CDocument : public cppu::ImplInheritanceHelper5<
CNode, XDocument, XDocumentEvent,
XActiveDataControl, XActiveDataSource, XSAXSerializable>
{
friend class CNode;
typedef std::list< Reference< XNode >* > nodereflist_t;
typedef set< Reference< XStreamListener > > listenerlist_t;
private:
nodereflist_t m_aNodeRefList;
xmlDocPtr m_aDocPtr;
// datacontrol/source state
listenerlist_t m_streamListeners;
Reference< XOutputStream > m_rOutputStream;
protected:
CDocument(xmlDocPtr aDocPtr);
void addnode(xmlNodePtr aNode);
public:
virtual ~CDocument();
virtual void SAL_CALL saxify(
const Reference< XDocumentHandler >& i_xHandler);
/**
Creates an Attr of the given name.
*/
virtual Reference< XAttr > SAL_CALL createAttribute(const OUString& name)
throw (RuntimeException, DOMException);
/**
Creates an attribute of the given qualified name and namespace URI.
*/
virtual Reference< XAttr > SAL_CALL createAttributeNS(const OUString& namespaceURI, const OUString& qualifiedName)
throw (RuntimeException, DOMException);
/**
Creates a CDATASection node whose value is the specified string.
*/
virtual Reference< XCDATASection > SAL_CALL createCDATASection(const OUString& data)
throw (RuntimeException);
/**
Creates a Comment node given the specified string.
*/
virtual Reference< XComment > SAL_CALL createComment(const OUString& data)
throw (RuntimeException);
/**
Creates an empty DocumentFragment object.
*/
virtual Reference< XDocumentFragment > SAL_CALL createDocumentFragment()
throw (RuntimeException);
/**
Creates an element of the type specified.
*/
virtual Reference< XElement > SAL_CALL createElement(const OUString& tagName)
throw (RuntimeException, DOMException);
/**
Creates an element of the given qualified name and namespace URI.
*/
virtual Reference< XElement > SAL_CALL createElementNS(const OUString& namespaceURI, const OUString& qualifiedName)
throw (RuntimeException, DOMException);
/**
Creates an EntityReference object.
*/
virtual Reference< XEntityReference > SAL_CALL createEntityReference(const OUString& name)
throw (RuntimeException, DOMException);
/**
Creates a ProcessingInstruction node given the specified name and
data strings.
*/
virtual Reference< XProcessingInstruction > SAL_CALL createProcessingInstruction(
const OUString& target, const OUString& data)
throw (RuntimeException, DOMException);
/**
Creates a Text node given the specified string.
*/
virtual Reference< XText > SAL_CALL createTextNode(const OUString& data)
throw (RuntimeException);
/**
The Document Type Declaration (see DocumentType) associated with this
document.
*/
virtual Reference< XDocumentType > SAL_CALL getDoctype()
throw (RuntimeException);
/**
This is a convenience attribute that allows direct access to the child
node that is the root element of the document.
*/
virtual Reference< XElement > SAL_CALL getDocumentElement()
throw (RuntimeException);
/**
Returns the Element whose ID is given by elementId.
*/
virtual Reference< XElement > SAL_CALL getElementById(const OUString& elementId)
throw (RuntimeException);
/**
Returns a NodeList of all the Elements with a given tag name in the
order in which they are encountered in a preorder traversal of the
Document tree.
*/
virtual Reference< XNodeList > SAL_CALL getElementsByTagName(const OUString& tagname)
throw (RuntimeException);
/**
Returns a NodeList of all the Elements with a given local name and
namespace URI in the order in which they are encountered in a preorder
traversal of the Document tree.
*/
virtual Reference< XNodeList > SAL_CALL getElementsByTagNameNS(const OUString& namespaceURI, const OUString& localName)
throw (RuntimeException);
/**
The DOMImplementation object that handles this document.
*/
virtual Reference< XDOMImplementation > SAL_CALL getImplementation()
throw (RuntimeException);
/**
Imports a node from another document to this document.
*/
virtual Reference< XNode > SAL_CALL importNode(const Reference< XNode >& importedNode, sal_Bool deep)
throw (RuntimeException, DOMException);
// XDocumentEvent
virtual Reference< XEvent > SAL_CALL createEvent(const OUString& eventType) throw (RuntimeException);
// XActiveDataControl,
// see http://api.openoffice.org/docs/common/ref/com/sun/star/io/XActiveDataControl.html
virtual void SAL_CALL addListener(const Reference< XStreamListener >& aListener ) throw (RuntimeException);
virtual void SAL_CALL removeListener(const Reference< XStreamListener >& aListener ) throw (RuntimeException);
virtual void SAL_CALL start() throw (RuntimeException);
virtual void SAL_CALL terminate() throw (RuntimeException);
// XActiveDataSource
// see http://api.openoffice.org/docs/common/ref/com/sun/star/io/XActiveDataSource.html
virtual void SAL_CALL setOutputStream( const Reference< XOutputStream >& aStream ) throw (RuntimeException);
virtual Reference< XOutputStream > SAL_CALL getOutputStream() throw (RuntimeException);
// ---- resolve uno inheritance problems...
// overrides for XNode base
virtual OUString SAL_CALL getNodeName()
throw (RuntimeException);
virtual OUString SAL_CALL getNodeValue()
throw (RuntimeException);
// --- delegation for XNde base.
virtual Reference< XNode > SAL_CALL appendChild(const Reference< XNode >& newChild)
throw (RuntimeException, DOMException)
{
return CNode::appendChild(newChild);
}
virtual Reference< XNode > SAL_CALL cloneNode(sal_Bool deep)
throw (RuntimeException)
{
return CNode::cloneNode(deep);
}
virtual Reference< XNamedNodeMap > SAL_CALL getAttributes()
throw (RuntimeException)
{
return CNode::getAttributes();
}
virtual Reference< XNodeList > SAL_CALL getChildNodes()
throw (RuntimeException)
{
return CNode::getChildNodes();
}
virtual Reference< XNode > SAL_CALL getFirstChild()
throw (RuntimeException)
{
return CNode::getFirstChild();
}
virtual Reference< XNode > SAL_CALL getLastChild()
throw (RuntimeException)
{
return CNode::getLastChild();
}
virtual OUString SAL_CALL getLocalName()
throw (RuntimeException)
{
return CNode::getLocalName();
}
virtual OUString SAL_CALL getNamespaceURI()
throw (RuntimeException)
{
return CNode::getNamespaceURI();
}
virtual Reference< XNode > SAL_CALL getNextSibling()
throw (RuntimeException)
{
return CNode::getNextSibling();
}
virtual NodeType SAL_CALL getNodeType()
throw (RuntimeException)
{
return CNode::getNodeType();
}
virtual Reference< XDocument > SAL_CALL getOwnerDocument()
throw (RuntimeException)
{
return CNode::getOwnerDocument();
}
virtual Reference< XNode > SAL_CALL getParentNode()
throw (RuntimeException)
{
return CNode::getParentNode();
}
virtual OUString SAL_CALL getPrefix()
throw (RuntimeException)
{
return CNode::getPrefix();
}
virtual Reference< XNode > SAL_CALL getPreviousSibling()
throw (RuntimeException)
{
return CNode::getPreviousSibling();
}
virtual sal_Bool SAL_CALL hasAttributes()
throw (RuntimeException)
{
return CNode::hasAttributes();
}
virtual sal_Bool SAL_CALL hasChildNodes()
throw (RuntimeException)
{
return CNode::hasChildNodes();
}
virtual Reference< XNode > SAL_CALL insertBefore(
const Reference< XNode >& newChild, const Reference< XNode >& refChild)
throw (DOMException)
{
return CNode::insertBefore(newChild, refChild);
}
virtual sal_Bool SAL_CALL isSupported(const OUString& feature, const OUString& ver)
throw (RuntimeException)
{
return CNode::isSupported(feature, ver);
}
virtual void SAL_CALL normalize()
throw (RuntimeException)
{
CNode::normalize();
}
virtual Reference< XNode > SAL_CALL removeChild(const Reference< XNode >& oldChild)
throw (RuntimeException, DOMException)
{
return CNode::removeChild(oldChild);
}
virtual Reference< XNode > SAL_CALL replaceChild(
const Reference< XNode >& newChild, const Reference< XNode >& oldChild)
throw (RuntimeException, DOMException)
{
return CNode::replaceChild(newChild, oldChild);
}
virtual void SAL_CALL setNodeValue(const OUString& nodeValue)
throw (RuntimeException, DOMException)
{
return CNode::setNodeValue(nodeValue);
}
virtual void SAL_CALL setPrefix(const OUString& prefix)
throw (RuntimeException, DOMException)
{
return CNode::setPrefix(prefix);
}
// ::com::sun::star::xml::sax::XSAXSerializable
virtual void SAL_CALL serialize(
const Reference< XDocumentHandler >& i_xHandler,
const Sequence< beans::StringPair >& i_rNamespaces)
throw (RuntimeException, SAXException);
};
}
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.10.4); FILE MERGED 2008/03/31 13:38:57 rt 1.10.4.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: document.hxx,v $
* $Revision: 1.11 $
*
* 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 _DOCUMENT_HXX
#define _DOCUMENT_HXX
#include <list>
#include <set>
#include <sal/types.h>
#include <cppuhelper/implbase5.hxx>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Exception.hpp>
#include <com/sun/star/beans/StringPair.hpp>
#include <com/sun/star/xml/dom/XNode.hpp>
#include <com/sun/star/xml/dom/XAttr.hpp>
#include <com/sun/star/xml/dom/XElement.hpp>
#include <com/sun/star/xml/dom/XDOMImplementation.hpp>
#include <com/sun/star/xml/dom/events/XDocumentEvent.hpp>
#include <com/sun/star/xml/dom/events/XEvent.hpp>
#include <com/sun/star/xml/sax/XSAXSerializable.hpp>
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#include <com/sun/star/io/XActiveDataSource.hpp>
#include <com/sun/star/io/XActiveDataControl.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XStreamListener.hpp>
#include "node.hxx"
#include <libxml/tree.h>
using namespace std;
using namespace rtl;
using namespace com::sun::star;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::xml::sax;
using namespace com::sun::star::io;
using namespace com::sun::star::xml::dom;
using namespace com::sun::star::xml::dom::events;
namespace DOM
{
class CDocument : public cppu::ImplInheritanceHelper5<
CNode, XDocument, XDocumentEvent,
XActiveDataControl, XActiveDataSource, XSAXSerializable>
{
friend class CNode;
typedef std::list< Reference< XNode >* > nodereflist_t;
typedef set< Reference< XStreamListener > > listenerlist_t;
private:
nodereflist_t m_aNodeRefList;
xmlDocPtr m_aDocPtr;
// datacontrol/source state
listenerlist_t m_streamListeners;
Reference< XOutputStream > m_rOutputStream;
protected:
CDocument(xmlDocPtr aDocPtr);
void addnode(xmlNodePtr aNode);
public:
virtual ~CDocument();
virtual void SAL_CALL saxify(
const Reference< XDocumentHandler >& i_xHandler);
/**
Creates an Attr of the given name.
*/
virtual Reference< XAttr > SAL_CALL createAttribute(const OUString& name)
throw (RuntimeException, DOMException);
/**
Creates an attribute of the given qualified name and namespace URI.
*/
virtual Reference< XAttr > SAL_CALL createAttributeNS(const OUString& namespaceURI, const OUString& qualifiedName)
throw (RuntimeException, DOMException);
/**
Creates a CDATASection node whose value is the specified string.
*/
virtual Reference< XCDATASection > SAL_CALL createCDATASection(const OUString& data)
throw (RuntimeException);
/**
Creates a Comment node given the specified string.
*/
virtual Reference< XComment > SAL_CALL createComment(const OUString& data)
throw (RuntimeException);
/**
Creates an empty DocumentFragment object.
*/
virtual Reference< XDocumentFragment > SAL_CALL createDocumentFragment()
throw (RuntimeException);
/**
Creates an element of the type specified.
*/
virtual Reference< XElement > SAL_CALL createElement(const OUString& tagName)
throw (RuntimeException, DOMException);
/**
Creates an element of the given qualified name and namespace URI.
*/
virtual Reference< XElement > SAL_CALL createElementNS(const OUString& namespaceURI, const OUString& qualifiedName)
throw (RuntimeException, DOMException);
/**
Creates an EntityReference object.
*/
virtual Reference< XEntityReference > SAL_CALL createEntityReference(const OUString& name)
throw (RuntimeException, DOMException);
/**
Creates a ProcessingInstruction node given the specified name and
data strings.
*/
virtual Reference< XProcessingInstruction > SAL_CALL createProcessingInstruction(
const OUString& target, const OUString& data)
throw (RuntimeException, DOMException);
/**
Creates a Text node given the specified string.
*/
virtual Reference< XText > SAL_CALL createTextNode(const OUString& data)
throw (RuntimeException);
/**
The Document Type Declaration (see DocumentType) associated with this
document.
*/
virtual Reference< XDocumentType > SAL_CALL getDoctype()
throw (RuntimeException);
/**
This is a convenience attribute that allows direct access to the child
node that is the root element of the document.
*/
virtual Reference< XElement > SAL_CALL getDocumentElement()
throw (RuntimeException);
/**
Returns the Element whose ID is given by elementId.
*/
virtual Reference< XElement > SAL_CALL getElementById(const OUString& elementId)
throw (RuntimeException);
/**
Returns a NodeList of all the Elements with a given tag name in the
order in which they are encountered in a preorder traversal of the
Document tree.
*/
virtual Reference< XNodeList > SAL_CALL getElementsByTagName(const OUString& tagname)
throw (RuntimeException);
/**
Returns a NodeList of all the Elements with a given local name and
namespace URI in the order in which they are encountered in a preorder
traversal of the Document tree.
*/
virtual Reference< XNodeList > SAL_CALL getElementsByTagNameNS(const OUString& namespaceURI, const OUString& localName)
throw (RuntimeException);
/**
The DOMImplementation object that handles this document.
*/
virtual Reference< XDOMImplementation > SAL_CALL getImplementation()
throw (RuntimeException);
/**
Imports a node from another document to this document.
*/
virtual Reference< XNode > SAL_CALL importNode(const Reference< XNode >& importedNode, sal_Bool deep)
throw (RuntimeException, DOMException);
// XDocumentEvent
virtual Reference< XEvent > SAL_CALL createEvent(const OUString& eventType) throw (RuntimeException);
// XActiveDataControl,
// see http://api.openoffice.org/docs/common/ref/com/sun/star/io/XActiveDataControl.html
virtual void SAL_CALL addListener(const Reference< XStreamListener >& aListener ) throw (RuntimeException);
virtual void SAL_CALL removeListener(const Reference< XStreamListener >& aListener ) throw (RuntimeException);
virtual void SAL_CALL start() throw (RuntimeException);
virtual void SAL_CALL terminate() throw (RuntimeException);
// XActiveDataSource
// see http://api.openoffice.org/docs/common/ref/com/sun/star/io/XActiveDataSource.html
virtual void SAL_CALL setOutputStream( const Reference< XOutputStream >& aStream ) throw (RuntimeException);
virtual Reference< XOutputStream > SAL_CALL getOutputStream() throw (RuntimeException);
// ---- resolve uno inheritance problems...
// overrides for XNode base
virtual OUString SAL_CALL getNodeName()
throw (RuntimeException);
virtual OUString SAL_CALL getNodeValue()
throw (RuntimeException);
// --- delegation for XNde base.
virtual Reference< XNode > SAL_CALL appendChild(const Reference< XNode >& newChild)
throw (RuntimeException, DOMException)
{
return CNode::appendChild(newChild);
}
virtual Reference< XNode > SAL_CALL cloneNode(sal_Bool deep)
throw (RuntimeException)
{
return CNode::cloneNode(deep);
}
virtual Reference< XNamedNodeMap > SAL_CALL getAttributes()
throw (RuntimeException)
{
return CNode::getAttributes();
}
virtual Reference< XNodeList > SAL_CALL getChildNodes()
throw (RuntimeException)
{
return CNode::getChildNodes();
}
virtual Reference< XNode > SAL_CALL getFirstChild()
throw (RuntimeException)
{
return CNode::getFirstChild();
}
virtual Reference< XNode > SAL_CALL getLastChild()
throw (RuntimeException)
{
return CNode::getLastChild();
}
virtual OUString SAL_CALL getLocalName()
throw (RuntimeException)
{
return CNode::getLocalName();
}
virtual OUString SAL_CALL getNamespaceURI()
throw (RuntimeException)
{
return CNode::getNamespaceURI();
}
virtual Reference< XNode > SAL_CALL getNextSibling()
throw (RuntimeException)
{
return CNode::getNextSibling();
}
virtual NodeType SAL_CALL getNodeType()
throw (RuntimeException)
{
return CNode::getNodeType();
}
virtual Reference< XDocument > SAL_CALL getOwnerDocument()
throw (RuntimeException)
{
return CNode::getOwnerDocument();
}
virtual Reference< XNode > SAL_CALL getParentNode()
throw (RuntimeException)
{
return CNode::getParentNode();
}
virtual OUString SAL_CALL getPrefix()
throw (RuntimeException)
{
return CNode::getPrefix();
}
virtual Reference< XNode > SAL_CALL getPreviousSibling()
throw (RuntimeException)
{
return CNode::getPreviousSibling();
}
virtual sal_Bool SAL_CALL hasAttributes()
throw (RuntimeException)
{
return CNode::hasAttributes();
}
virtual sal_Bool SAL_CALL hasChildNodes()
throw (RuntimeException)
{
return CNode::hasChildNodes();
}
virtual Reference< XNode > SAL_CALL insertBefore(
const Reference< XNode >& newChild, const Reference< XNode >& refChild)
throw (DOMException)
{
return CNode::insertBefore(newChild, refChild);
}
virtual sal_Bool SAL_CALL isSupported(const OUString& feature, const OUString& ver)
throw (RuntimeException)
{
return CNode::isSupported(feature, ver);
}
virtual void SAL_CALL normalize()
throw (RuntimeException)
{
CNode::normalize();
}
virtual Reference< XNode > SAL_CALL removeChild(const Reference< XNode >& oldChild)
throw (RuntimeException, DOMException)
{
return CNode::removeChild(oldChild);
}
virtual Reference< XNode > SAL_CALL replaceChild(
const Reference< XNode >& newChild, const Reference< XNode >& oldChild)
throw (RuntimeException, DOMException)
{
return CNode::replaceChild(newChild, oldChild);
}
virtual void SAL_CALL setNodeValue(const OUString& nodeValue)
throw (RuntimeException, DOMException)
{
return CNode::setNodeValue(nodeValue);
}
virtual void SAL_CALL setPrefix(const OUString& prefix)
throw (RuntimeException, DOMException)
{
return CNode::setPrefix(prefix);
}
// ::com::sun::star::xml::sax::XSAXSerializable
virtual void SAL_CALL serialize(
const Reference< XDocumentHandler >& i_xHandler,
const Sequence< beans::StringPair >& i_rNamespaces)
throw (RuntimeException, SAXException);
};
}
#endif
<|endoftext|> |
<commit_before>/*
* Ascent MMORPG Server
* Copyright (C) 2005-2008 Ascent Team <http://www.ascentemu.com/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
void WorldSession::HandleSetVisibleRankOpcode(WorldPacket& recv_data)
{
CHECK_PACKET_SIZE(recv_data, 4);
uint32 ChosenRank;
recv_data >> ChosenRank;
if(ChosenRank == 0xFFFFFFFF)
_player->SetUInt32Value(PLAYER_CHOSEN_TITLE, 0);
else
_player->SetUInt32Value(PLAYER_CHOSEN_TITLE, ChosenRank);
}
void HonorHandler::AddHonorPointsToPlayer(Player *pPlayer, uint32 uAmount)
{
if( pPlayer->GetMapId() == 559 || pPlayer->GetMapId() == 562 || pPlayer->GetMapId() == 572)
return;
pPlayer->m_honorPoints += uAmount;
pPlayer->m_honorToday += uAmount;
pPlayer->HandleProc(PROC_ON_GAIN_EXPIERIENCE, pPlayer, NULL);
pPlayer->m_procCounter = 0;
RecalculateHonorFields(pPlayer);
}
int32 HonorHandler::CalculateHonorPointsForKill( Player *pPlayer, Unit* pVictim )
{
// this sucks.. ;p
if( pVictim == NULL )
{
int32 pts = rand() % 100 + 100;
return pts;
}
// Suicide lol
if( pVictim == pPlayer )
return 0;
if( pVictim->GetTypeId() != TYPEID_PLAYER )
return 0;
// How dishonorable, you fiend!
if( pVictim->HasActiveAura( PLAYER_HONORLESS_TARGET_SPELL ) )
return 0;
uint32 k_level = pPlayer->GetUInt32Value( UNIT_FIELD_LEVEL );
uint32 v_level = pVictim->GetUInt32Value( UNIT_FIELD_LEVEL );
int k_honor = pPlayer->m_honorPoints;
int v_honor = static_cast< Player* >( pVictim )->m_honorPoints;
uint32 k_grey = 0;
if( k_level > 5 && k_level < 40 )
{
k_grey = k_level - 5 - float2int32( floor( ((float)k_level) / 10.0f ) );
}
else
{
k_grey = k_level - 1 - float2int32( floor( ((float)k_level) / 5.0f ) );
}
if( k_honor == 0 )
k_honor = 1;
float diff_level = ((float)v_level - k_grey) / ((float)k_level - k_grey);
if( diff_level > 2 ) diff_level = 2.0f;
if( diff_level < 0 ) diff_level = 0.0f;
float diff_honor = ((float)v_honor) / ((float)k_honor);
if( diff_honor > 3 ) diff_honor = 3.0f;
if( diff_honor < 0 ) diff_honor = 0.0f;
float honor_points = diff_level * ( 150.0f + diff_honor * 60 );
honor_points *= ((float)k_level) / 70.0f;
honor_points *= World::getSingleton().getRate( RATE_HONOR );
return float2int32( honor_points );
}
void HonorHandler::OnPlayerKilledUnit( Player *pPlayer, Unit* pVictim )
{
if( pVictim == NULL || pPlayer == NULL )
return;
if( pPlayer->GetTypeId() != TYPEID_PLAYER || !pVictim->IsUnit() )
return;
if( !pVictim->IsPlayer() || static_cast< Player* >( pVictim )->m_honorless )
return;
if( pVictim->IsPlayer() )
{
if( pPlayer->m_bg )
{
if( static_cast< Player* >( pVictim )->m_bgTeam == pPlayer->m_bgTeam )
return;
// patch 2.4, players killed >50 times in battlegrounds won't be worth honor for the rest of that bg
if( static_cast<Player*>(pVictim)->m_bgScore.Deaths >= 50 )
return;
}
else
{
if( pPlayer->GetTeam() == static_cast< Player* >( pVictim )->GetTeam() )
return;
}
}
// Calculate points
int32 Points = CalculateHonorPointsForKill(pPlayer, pVictim);
if( Points > 0 )
{
if( pPlayer->m_bg )
{
// hackfix for battlegrounds (since the gorups there are disabled, we need to do this manually)
vector<Player*> toadd;
uint32 t = pPlayer->m_bgTeam;
toadd.reserve(15); // shouldnt have more than this
pPlayer->m_bg->Lock();
set<Player*> * s = &pPlayer->m_bg->m_players[t];
for(set<Player*>::iterator itr = s->begin(); itr != s->end(); ++itr)
{
if((*itr) == pPlayer || (*itr)->isInRange(pPlayer,100.0f))
toadd.push_back(*itr);
}
if( toadd.size() > 0 )
{
uint32 pts = Points / (uint32)toadd.size();
for(vector<Player*>::iterator vtr = toadd.begin(); vtr != toadd.end(); ++vtr)
{
AddHonorPointsToPlayer(*vtr, pts);
(*vtr)->m_killsToday++;
(*vtr)->m_killsLifetime++;
pPlayer->m_bg->HookOnHK(*vtr);
if(pVictim)
{
// Send PVP credit
WorldPacket data(SMSG_PVP_CREDIT, 12);
uint32 pvppoints = pts * 10;
data << pvppoints << pVictim->GetGUID() << uint32(static_cast< Player* >(pVictim)->GetPVPRank());
(*vtr)->GetSession()->SendPacket(&data);
}
}
}
pPlayer->m_bg->Unlock();
}
else
{
set<Player*> contributors;
// First loop: Get all the people in the attackermap.
for(std::set<Object*>::iterator itr = pVictim->GetInRangeOppFactsSetBegin(); itr != pVictim->GetInRangeOppFactsSetEnd(); itr++)
{
if(!(*itr)->IsPlayer())
continue;
Player * plr = (Player*)(*itr);
if(pVictim->CombatStatus.m_attackers.find(plr->GetGUID()) == pVictim->CombatStatus.m_attackers.end())
contributors.insert(plr);
if(plr->GetGroup())
{
Group * pGroup = plr->GetGroup();
uint32 groups = pGroup->GetSubGroupCount();
for(int i = 0; i < groups; i++)
{
SubGroup * sg = pGroup->GetSubGroup(i);
if(!sg) continue;
for(GroupMembersSet::iterator itr = sg->GetGroupMembersBegin(); itr != sg->GetGroupMembersEnd(); itr++)
{
PlayerInfo * pi = (*itr);
Player * gm = objmgr.GetPlayer(pi->guid);
if(!gm) continue;
if(gm->isInRange(pVictim, 100.0f))
contributors.insert(gm);
}
}
}
}
for(set<Player*>::iterator itr = contributors.begin(); itr != contributors.end(); itr++)
{
Player * pAffectedPlayer = (*itr);
if(!pAffectedPlayer) continue;
pAffectedPlayer->m_killsToday++;
pAffectedPlayer->m_killsLifetime++;
if(pAffectedPlayer->m_bg)
pAffectedPlayer->m_bg->HookOnHK(pAffectedPlayer);
int32 contributorpts = Points / contributors.size();
AddHonorPointsToPlayer(pAffectedPlayer, contributorpts);
if(pVictim->IsPlayer())
{
sHookInterface.OnHonorableKill(pAffectedPlayer, (Player*)pVictim);
WorldPacket data(SMSG_PVP_CREDIT, 12);
uint32 pvppoints = contributorpts * 10; // Why *10?
data << pvppoints << pVictim->GetGUID() << uint32(static_cast< Player* >(pVictim)->GetPVPRank());
pAffectedPlayer->GetSession()->SendPacket(&data);
}
if(pAffectedPlayer->GetZoneId() == 3518)
{
// Add Halaa Battle Token
SpellEntry * pvp_token_spell = dbcSpell.LookupEntry(pAffectedPlayer->GetTeam()? 33004 : 33005);
pAffectedPlayer->CastSpell(pAffectedPlayer, pvp_token_spell, true);
}
// If we are in Hellfire Peninsula
if(pAffectedPlayer->GetZoneId() == 3483)
{
// Add Mark of Thrallmar/Honor Hold
SpellEntry * pvp_token_spell = dbcSpell.LookupEntry(pAffectedPlayer->GetTeam()? 32158 : 32155);
pAffectedPlayer->CastSpell(pAffectedPlayer, pvp_token_spell, true);
}
}
}
}
}
void HonorHandler::RecalculateHonorFields(Player *pPlayer)
{
// Why are we multiplying by 10.. ho well
pPlayer->SetUInt32Value(PLAYER_FIELD_KILLS, pPlayer->m_killsToday);
pPlayer->SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, pPlayer->m_honorToday);
pPlayer->SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, pPlayer->m_killsYesterday | ( (pPlayer->m_honorYesterday * 10) << 16));
pPlayer->SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, pPlayer->m_killsLifetime);
pPlayer->SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, pPlayer->m_honorPoints);
pPlayer->SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, pPlayer->m_arenaPoints);
}
bool ChatHandler::HandleAddKillCommand(const char* args, WorldSession* m_session)
{
uint32 KillAmount = args ? atol(args) : 1;
Player *plr = getSelectedChar(m_session, true);
if(plr == 0)
return true;
BlueSystemMessage(m_session, "Adding %u kills to player %s.", KillAmount, plr->GetName());
GreenSystemMessage(plr->GetSession(), "You have had %u honor kills added to your character.", KillAmount);
for(uint32 i = 0; i < KillAmount; ++i)
HonorHandler::OnPlayerKilledUnit(plr, 0);
return true;
}
bool ChatHandler::HandleAddHonorCommand(const char* args, WorldSession* m_session)
{
uint32 HonorAmount = args ? atol(args) : 1;
Player *plr = getSelectedChar(m_session, true);
if(plr == 0)
return true;
BlueSystemMessage(m_session, "Adding %u honor to player %s.", HonorAmount, plr->GetName());
GreenSystemMessage(plr->GetSession(), "You have had %u honor points added to your character.", HonorAmount);
HonorHandler::AddHonorPointsToPlayer(plr, HonorAmount);
return true;
}
bool ChatHandler::HandlePVPCreditCommand(const char* args, WorldSession* m_session)
{
uint32 Rank, Points;
if(sscanf(args, "%u %u", (unsigned int*)&Rank, (unsigned int*)&Points) != 2)
{
RedSystemMessage(m_session, "Command must be in format <rank> <points>.");
return true;
}
Points *= 10;
uint64 Guid = m_session->GetPlayer()->GetSelection();
if(Guid == 0)
{
RedSystemMessage(m_session, "A selection of a unit or player is required.");
return true;
}
BlueSystemMessage(m_session, "Building packet with Rank %u, Points %u, GUID "I64FMT".",
Rank, Points, Guid);
WorldPacket data(SMSG_PVP_CREDIT, 12);
data << Points << Guid << Rank;
m_session->SendPacket(&data);
return true;
}
bool ChatHandler::HandleGlobalHonorDailyMaintenanceCommand(const char* args, WorldSession* m_session)
{
return false;
}
bool ChatHandler::HandleNextDayCommand(const char* args, WorldSession* m_session)
{
return false;
}
<commit_msg>. Epic typo!<commit_after>/*
* Ascent MMORPG Server
* Copyright (C) 2005-2008 Ascent Team <http://www.ascentemu.com/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
void WorldSession::HandleSetVisibleRankOpcode(WorldPacket& recv_data)
{
CHECK_PACKET_SIZE(recv_data, 4);
uint32 ChosenRank;
recv_data >> ChosenRank;
if(ChosenRank == 0xFFFFFFFF)
_player->SetUInt32Value(PLAYER_CHOSEN_TITLE, 0);
else
_player->SetUInt32Value(PLAYER_CHOSEN_TITLE, ChosenRank);
}
void HonorHandler::AddHonorPointsToPlayer(Player *pPlayer, uint32 uAmount)
{
if( pPlayer->GetMapId() == 559 || pPlayer->GetMapId() == 562 || pPlayer->GetMapId() == 572)
return;
pPlayer->m_honorPoints += uAmount;
pPlayer->m_honorToday += uAmount;
pPlayer->HandleProc(PROC_ON_GAIN_EXPIERIENCE, pPlayer, NULL);
pPlayer->m_procCounter = 0;
RecalculateHonorFields(pPlayer);
}
int32 HonorHandler::CalculateHonorPointsForKill( Player *pPlayer, Unit* pVictim )
{
// this sucks.. ;p
if( pVictim == NULL )
{
int32 pts = rand() % 100 + 100;
return pts;
}
// Suicide lol
if( pVictim == pPlayer )
return 0;
if( pVictim->GetTypeId() != TYPEID_PLAYER )
return 0;
// How dishonorable, you fiend!
if( pVictim->HasActiveAura( PLAYER_HONORLESS_TARGET_SPELL ) )
return 0;
uint32 k_level = pPlayer->GetUInt32Value( UNIT_FIELD_LEVEL );
uint32 v_level = pVictim->GetUInt32Value( UNIT_FIELD_LEVEL );
int k_honor = pPlayer->m_honorPoints;
int v_honor = static_cast< Player* >( pVictim )->m_honorPoints;
uint32 k_grey = 0;
if( k_level > 5 && k_level < 40 )
{
k_grey = k_level - 5 - float2int32( floor( ((float)k_level) / 10.0f ) );
}
else
{
k_grey = k_level - 1 - float2int32( floor( ((float)k_level) / 5.0f ) );
}
if( k_honor == 0 )
k_honor = 1;
float diff_level = ((float)v_level - k_grey) / ((float)k_level - k_grey);
if( diff_level > 2 ) diff_level = 2.0f;
if( diff_level < 0 ) diff_level = 0.0f;
float diff_honor = ((float)v_honor) / ((float)k_honor);
if( diff_honor > 3 ) diff_honor = 3.0f;
if( diff_honor < 0 ) diff_honor = 0.0f;
float honor_points = diff_level * ( 150.0f + diff_honor * 60 );
honor_points *= ((float)k_level) / 70.0f;
honor_points *= World::getSingleton().getRate( RATE_HONOR );
return float2int32( honor_points );
}
void HonorHandler::OnPlayerKilledUnit( Player *pPlayer, Unit* pVictim )
{
if( pVictim == NULL || pPlayer == NULL )
return;
if( pPlayer->GetTypeId() != TYPEID_PLAYER || !pVictim->IsUnit() )
return;
if( !pVictim->IsPlayer() || static_cast< Player* >( pVictim )->m_honorless )
return;
if( pVictim->IsPlayer() )
{
if( pPlayer->m_bg )
{
if( static_cast< Player* >( pVictim )->m_bgTeam == pPlayer->m_bgTeam )
return;
// patch 2.4, players killed >50 times in battlegrounds won't be worth honor for the rest of that bg
if( static_cast<Player*>(pVictim)->m_bgScore.Deaths >= 50 )
return;
}
else
{
if( pPlayer->GetTeam() == static_cast< Player* >( pVictim )->GetTeam() )
return;
}
}
// Calculate points
int32 Points = CalculateHonorPointsForKill(pPlayer, pVictim);
if( Points > 0 )
{
if( pPlayer->m_bg )
{
// hackfix for battlegrounds (since the gorups there are disabled, we need to do this manually)
vector<Player*> toadd;
uint32 t = pPlayer->m_bgTeam;
toadd.reserve(15); // shouldnt have more than this
pPlayer->m_bg->Lock();
set<Player*> * s = &pPlayer->m_bg->m_players[t];
for(set<Player*>::iterator itr = s->begin(); itr != s->end(); ++itr)
{
if((*itr) == pPlayer || (*itr)->isInRange(pPlayer,100.0f))
toadd.push_back(*itr);
}
if( toadd.size() > 0 )
{
uint32 pts = Points / (uint32)toadd.size();
for(vector<Player*>::iterator vtr = toadd.begin(); vtr != toadd.end(); ++vtr)
{
AddHonorPointsToPlayer(*vtr, pts);
(*vtr)->m_killsToday++;
(*vtr)->m_killsLifetime++;
pPlayer->m_bg->HookOnHK(*vtr);
if(pVictim)
{
// Send PVP credit
WorldPacket data(SMSG_PVP_CREDIT, 12);
uint32 pvppoints = pts * 10;
data << pvppoints << pVictim->GetGUID() << uint32(static_cast< Player* >(pVictim)->GetPVPRank());
(*vtr)->GetSession()->SendPacket(&data);
}
}
}
pPlayer->m_bg->Unlock();
}
else
{
set<Player*> contributors;
// First loop: Get all the people in the attackermap.
for(std::set<Object*>::iterator itr = pVictim->GetInRangeOppFactsSetBegin(); itr != pVictim->GetInRangeOppFactsSetEnd(); itr++)
{
if(!(*itr)->IsPlayer())
continue;
Player * plr = (Player*)(*itr);
if(pVictim->CombatStatus.m_attackers.find(plr->GetGUID()) != pVictim->CombatStatus.m_attackers.end())
contributors.insert(plr);
if(plr->GetGroup())
{
Group * pGroup = plr->GetGroup();
uint32 groups = pGroup->GetSubGroupCount();
for(int i = 0; i < groups; i++)
{
SubGroup * sg = pGroup->GetSubGroup(i);
if(!sg) continue;
for(GroupMembersSet::iterator itr = sg->GetGroupMembersBegin(); itr != sg->GetGroupMembersEnd(); itr++)
{
PlayerInfo * pi = (*itr);
Player * gm = objmgr.GetPlayer(pi->guid);
if(!gm) continue;
if(gm->isInRange(pVictim, 100.0f))
contributors.insert(gm);
}
}
}
}
for(set<Player*>::iterator itr = contributors.begin(); itr != contributors.end(); itr++)
{
Player * pAffectedPlayer = (*itr);
if(!pAffectedPlayer) continue;
pAffectedPlayer->m_killsToday++;
pAffectedPlayer->m_killsLifetime++;
if(pAffectedPlayer->m_bg)
pAffectedPlayer->m_bg->HookOnHK(pAffectedPlayer);
int32 contributorpts = Points / contributors.size();
AddHonorPointsToPlayer(pAffectedPlayer, contributorpts);
if(pVictim->IsPlayer())
{
sHookInterface.OnHonorableKill(pAffectedPlayer, (Player*)pVictim);
WorldPacket data(SMSG_PVP_CREDIT, 12);
uint32 pvppoints = contributorpts * 10; // Why *10?
data << pvppoints << pVictim->GetGUID() << uint32(static_cast< Player* >(pVictim)->GetPVPRank());
pAffectedPlayer->GetSession()->SendPacket(&data);
}
if(pAffectedPlayer->GetZoneId() == 3518)
{
// Add Halaa Battle Token
SpellEntry * pvp_token_spell = dbcSpell.LookupEntry(pAffectedPlayer->GetTeam()? 33004 : 33005);
pAffectedPlayer->CastSpell(pAffectedPlayer, pvp_token_spell, true);
}
// If we are in Hellfire Peninsula
if(pAffectedPlayer->GetZoneId() == 3483)
{
// Add Mark of Thrallmar/Honor Hold
SpellEntry * pvp_token_spell = dbcSpell.LookupEntry(pAffectedPlayer->GetTeam()? 32158 : 32155);
pAffectedPlayer->CastSpell(pAffectedPlayer, pvp_token_spell, true);
}
}
}
}
}
void HonorHandler::RecalculateHonorFields(Player *pPlayer)
{
// Why are we multiplying by 10.. ho well
pPlayer->SetUInt32Value(PLAYER_FIELD_KILLS, pPlayer->m_killsToday);
pPlayer->SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, pPlayer->m_honorToday);
pPlayer->SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, pPlayer->m_killsYesterday | ( (pPlayer->m_honorYesterday * 10) << 16));
pPlayer->SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, pPlayer->m_killsLifetime);
pPlayer->SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, pPlayer->m_honorPoints);
pPlayer->SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, pPlayer->m_arenaPoints);
}
bool ChatHandler::HandleAddKillCommand(const char* args, WorldSession* m_session)
{
uint32 KillAmount = args ? atol(args) : 1;
Player *plr = getSelectedChar(m_session, true);
if(plr == 0)
return true;
BlueSystemMessage(m_session, "Adding %u kills to player %s.", KillAmount, plr->GetName());
GreenSystemMessage(plr->GetSession(), "You have had %u honor kills added to your character.", KillAmount);
for(uint32 i = 0; i < KillAmount; ++i)
HonorHandler::OnPlayerKilledUnit(plr, 0);
return true;
}
bool ChatHandler::HandleAddHonorCommand(const char* args, WorldSession* m_session)
{
uint32 HonorAmount = args ? atol(args) : 1;
Player *plr = getSelectedChar(m_session, true);
if(plr == 0)
return true;
BlueSystemMessage(m_session, "Adding %u honor to player %s.", HonorAmount, plr->GetName());
GreenSystemMessage(plr->GetSession(), "You have had %u honor points added to your character.", HonorAmount);
HonorHandler::AddHonorPointsToPlayer(plr, HonorAmount);
return true;
}
bool ChatHandler::HandlePVPCreditCommand(const char* args, WorldSession* m_session)
{
uint32 Rank, Points;
if(sscanf(args, "%u %u", (unsigned int*)&Rank, (unsigned int*)&Points) != 2)
{
RedSystemMessage(m_session, "Command must be in format <rank> <points>.");
return true;
}
Points *= 10;
uint64 Guid = m_session->GetPlayer()->GetSelection();
if(Guid == 0)
{
RedSystemMessage(m_session, "A selection of a unit or player is required.");
return true;
}
BlueSystemMessage(m_session, "Building packet with Rank %u, Points %u, GUID "I64FMT".",
Rank, Points, Guid);
WorldPacket data(SMSG_PVP_CREDIT, 12);
data << Points << Guid << Rank;
m_session->SendPacket(&data);
return true;
}
bool ChatHandler::HandleGlobalHonorDailyMaintenanceCommand(const char* args, WorldSession* m_session)
{
return false;
}
bool ChatHandler::HandleNextDayCommand(const char* args, WorldSession* m_session)
{
return false;
}
<|endoftext|> |
<commit_before>#include <QtWidgets>
#include "GeometryWidget.hpp"
#include <Spirit/Geometry.h>
GeometryWidget::GeometryWidget(std::shared_ptr<State> state, SpinWidget * spinWidget)
{
this->state = state;
this->spinWidget = spinWidget;
// Setup User Interface
this->setupUi(this);
// We use a regular expression (regex) to filter the input into the lineEdits
QRegularExpression re("[+|-]?[\\d]*[\\.]?[\\d]*");
this->number_validator = new QRegularExpressionValidator(re);
QRegularExpression re2("[\\d]*[\\.]?[\\d]*");
this->number_validator_unsigned = new QRegularExpressionValidator(re2);
QRegularExpression re3("[+|-]?[\\d]*");
this->number_validator_int = new QRegularExpressionValidator(re3);
QRegularExpression re4("[\\d]*");
this->number_validator_int_unsigned = new QRegularExpressionValidator(re4);
// Setup the validators for the various input fields
this->Setup_Input_Validators();
// Load variables from SpinWidget and State
this->updateData();
// Connect signals and slots
this->Setup_Slots();
}
void GeometryWidget::updateData()
{
int n_cells[3];
Geometry_Get_N_Cells(this->state.get(), n_cells);
this->lineEdit_n_cells_a->setText(QString::number(n_cells[0]));
this->lineEdit_n_cells_b->setText(QString::number(n_cells[1]));
this->lineEdit_n_cells_c->setText(QString::number(n_cells[2]));
}
void GeometryWidget::setNCells()
{
// Get some reference values for the position filter of SpinWidget
auto x_range = this->spinWidget->xRangePosition();
auto y_range = this->spinWidget->yRangePosition();
auto z_range = this->spinWidget->zRangePosition();
float b_min[3], b_max[3], b_range[3];
Geometry_Get_Bounds(state.get(), b_min, b_max);
float pc_x = x_range.y;
float pc_y = y_range.y;
float pc_z = z_range.y;
if (std::abs(b_max[0]) > 0) pc_x /= b_max[0];
if (std::abs(b_max[1]) > 0) pc_y /= b_max[1];
if (std::abs(b_max[2]) > 0) pc_z /= b_max[2];
// Update the geometry in the core
int n_cells[3]{ this->lineEdit_n_cells_a->text().toFloat(), this->lineEdit_n_cells_b->text().toFloat(), this->lineEdit_n_cells_c->text().toFloat() };
Geometry_Set_N_Cells(this->state.get(), n_cells);
// Update geometry and arrays in SpinWidget
this->spinWidget->initializeGL();
this->spinWidget->updateData();
// Update the position filter of SpinWidget
float b_min_new[3], b_max_new[3], b_range_new[3];
Geometry_Get_Bounds(state.get(), b_min_new, b_max_new);
x_range.y = pc_x * b_max_new[0];
y_range.y = pc_y * b_max_new[1];
z_range.y = pc_z * b_max_new[2];
this->spinWidget->setOverallPositionRange(x_range, y_range, z_range);
// Update all widgets
emit updateNeeded();
}
void GeometryWidget::Setup_Input_Validators()
{
this->lineEdit_n_cells_a->setValidator(this->number_validator_unsigned);
this->lineEdit_n_cells_b->setValidator(this->number_validator_unsigned);
this->lineEdit_n_cells_c->setValidator(this->number_validator_unsigned);
}
void GeometryWidget::Setup_Slots()
{
connect(this->lineEdit_n_cells_a, SIGNAL(returnPressed()), this, SLOT(setNCells()));
connect(this->lineEdit_n_cells_b, SIGNAL(returnPressed()), this, SLOT(setNCells()));
connect(this->lineEdit_n_cells_c, SIGNAL(returnPressed()), this, SLOT(setNCells()));
}
<commit_msg>UI-CPP: Fixed clang error (narrowing conversion).<commit_after>#include <QtWidgets>
#include "GeometryWidget.hpp"
#include <Spirit/Geometry.h>
GeometryWidget::GeometryWidget(std::shared_ptr<State> state, SpinWidget * spinWidget)
{
this->state = state;
this->spinWidget = spinWidget;
// Setup User Interface
this->setupUi(this);
// We use a regular expression (regex) to filter the input into the lineEdits
QRegularExpression re("[+|-]?[\\d]*[\\.]?[\\d]*");
this->number_validator = new QRegularExpressionValidator(re);
QRegularExpression re2("[\\d]*[\\.]?[\\d]*");
this->number_validator_unsigned = new QRegularExpressionValidator(re2);
QRegularExpression re3("[+|-]?[\\d]*");
this->number_validator_int = new QRegularExpressionValidator(re3);
QRegularExpression re4("[\\d]*");
this->number_validator_int_unsigned = new QRegularExpressionValidator(re4);
// Setup the validators for the various input fields
this->Setup_Input_Validators();
// Load variables from SpinWidget and State
this->updateData();
// Connect signals and slots
this->Setup_Slots();
}
void GeometryWidget::updateData()
{
int n_cells[3];
Geometry_Get_N_Cells(this->state.get(), n_cells);
this->lineEdit_n_cells_a->setText(QString::number(n_cells[0]));
this->lineEdit_n_cells_b->setText(QString::number(n_cells[1]));
this->lineEdit_n_cells_c->setText(QString::number(n_cells[2]));
}
void GeometryWidget::setNCells()
{
// Get some reference values for the position filter of SpinWidget
auto x_range = this->spinWidget->xRangePosition();
auto y_range = this->spinWidget->yRangePosition();
auto z_range = this->spinWidget->zRangePosition();
float b_min[3], b_max[3], b_range[3];
Geometry_Get_Bounds(state.get(), b_min, b_max);
float pc_x = x_range.y;
float pc_y = y_range.y;
float pc_z = z_range.y;
if (std::abs(b_max[0]) > 0) pc_x /= b_max[0];
if (std::abs(b_max[1]) > 0) pc_y /= b_max[1];
if (std::abs(b_max[2]) > 0) pc_z /= b_max[2];
// Update the geometry in the core
int n_cells[3]{ this->lineEdit_n_cells_a->text().toInt(), this->lineEdit_n_cells_b->text().toInt(), this->lineEdit_n_cells_c->text().toInt() };
Geometry_Set_N_Cells(this->state.get(), n_cells);
// Update geometry and arrays in SpinWidget
this->spinWidget->initializeGL();
this->spinWidget->updateData();
// Update the position filter of SpinWidget
float b_min_new[3], b_max_new[3], b_range_new[3];
Geometry_Get_Bounds(state.get(), b_min_new, b_max_new);
x_range.y = pc_x * b_max_new[0];
y_range.y = pc_y * b_max_new[1];
z_range.y = pc_z * b_max_new[2];
this->spinWidget->setOverallPositionRange(x_range, y_range, z_range);
// Update all widgets
emit updateNeeded();
}
void GeometryWidget::Setup_Input_Validators()
{
this->lineEdit_n_cells_a->setValidator(this->number_validator_unsigned);
this->lineEdit_n_cells_b->setValidator(this->number_validator_unsigned);
this->lineEdit_n_cells_c->setValidator(this->number_validator_unsigned);
}
void GeometryWidget::Setup_Slots()
{
connect(this->lineEdit_n_cells_a, SIGNAL(returnPressed()), this, SLOT(setNCells()));
connect(this->lineEdit_n_cells_b, SIGNAL(returnPressed()), this, SLOT(setNCells()));
connect(this->lineEdit_n_cells_c, SIGNAL(returnPressed()), this, SLOT(setNCells()));
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2017 Maxim Teryokhin
This code is licensed under MIT. See LICENSE file for more details.
*/
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <set>
#include <map>
#include <string>
#include <vector>
using namespace std;
struct Flowerbed {
int id;
string shape;
set<string> flowers;
Flowerbed()
: flowers()
{
}
Flowerbed(int id, string shape, set<string> flowers)
: id(id)
, shape(shape)
, flowers(flowers)
{
}
friend istream& operator>>(istream& in, Flowerbed& a);
friend ostream& operator<<(ostream& out, const Flowerbed& a);
};
istream& operator>>(istream& in, Flowerbed& a)
{
a = Flowerbed();
string s;
in >> a.id;
in.ignore();
getline(in, a.shape, ',');
getline(in, s);
int prev_pos = 0, cur_pos = 0;
while ((cur_pos = s.find(",", prev_pos)) >= 0) {
a.flowers.insert(s.substr(prev_pos, cur_pos - prev_pos));
prev_pos = cur_pos + 1;
}
a.flowers.insert(s.substr(prev_pos, s.size()));
return in;
}
ostream& operator<<(ostream& out, const Flowerbed& a)
{
out << "{ " << a.id << " | " << a.shape << " |: ";
for (auto it = a.flowers.begin(); it != a.flowers.end(); it++)
out << *it << ", ";
out << "}";
return out;
}
int main()
{
ifstream fin("input.txt");
istream_iterator<Flowerbed> FB_in(fin);
istream_iterator<Flowerbed> end_in;
ostream_iterator<Flowerbed> FB_out(cout, "\n");
ostream_iterator<string> str_out(cout, "\n");
vector<Flowerbed> flowerbeds;
// TASK 1
copy(FB_in, end_in, back_inserter(flowerbeds));
// TASK 2
sort(flowerbeds.begin(), flowerbeds.end(), [](const Flowerbed& a, const Flowerbed& b) {
return a.id < b.id;
});
cout << "SORTED BY ID:\n";
copy(flowerbeds.begin(), flowerbeds.end(), FB_out);
sort(flowerbeds.begin(), flowerbeds.end(), [](const Flowerbed& a, const Flowerbed& b) {
return a.shape < b.shape;
});
cout << "\nSORTED BY SHAPE:\n";
copy(flowerbeds.begin(), flowerbeds.end(), FB_out);
//TASK 4
set<string> different_forms;
for_each(flowerbeds.begin(), flowerbeds.end(), [&different_forms](const Flowerbed& a) {
different_forms.insert(a.shape);
});
cout << "\nDIFFERENT SHAPES:\n";
copy(different_forms.begin(), different_forms.end(), str_out);
map<int,Flowerbed> flowerbeds_map;
for_each(flowerbeds.begin(), flowerbeds.end(), [&flowerbeds_map](const Flowerbed& a) {
flowerbeds_map.insert(make_pair(a.id, a));
});
int id;
cout << "\nEnter flowerbed id: ";
cin >> id;
cout << "Flowers from flowerbed #" << id << ":\n";
copy(flowerbeds_map[id].flowers.begin(), flowerbeds_map[id].flowers.end(), str_out);
set<string> different_flowers;
for_each(flowerbeds.begin(), flowerbeds.end(), [&different_flowers](const Flowerbed& a) {
different_flowers.insert(a.flowers.begin(), a.flowers.end());
});
cout << "\nLIST OF ALL DIFFERENT FLOWERS:\n";
copy(different_flowers.begin(), different_flowers.end(), str_out);
return 0;
}
<commit_msg>Week 2 comlete solution<commit_after>/*
Copyright (c) 2017 Maxim Teryokhin
This code is licensed under MIT. See LICENSE file for more details.
*/
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <map>
#include <set>
#include <string>
#include <vector>
using namespace std;
struct Flowerbed {
int id;
string shape;
set<string> flowers;
friend istream& operator>>(istream& in, Flowerbed& a);
friend ostream& operator<<(ostream& out, const Flowerbed& a);
};
istream& operator>>(istream& in, Flowerbed& a)
{
a = Flowerbed();
string s;
in >> a.id;
in.ignore();
getline(in, a.shape, ',');
getline(in, s);
int prev_pos = 0, cur_pos = 0;
while ((cur_pos = s.find(",", prev_pos)) >= 0) {
a.flowers.insert(s.substr(prev_pos, cur_pos - prev_pos));
prev_pos = cur_pos + 1;
}
a.flowers.insert(s.substr(prev_pos, s.size()));
return in;
}
ostream& operator<<(ostream& out, const Flowerbed& a)
{
out << "{ " << a.id << " | " << a.shape << " |: ";
for (auto it = a.flowers.begin(); it != a.flowers.end(); it++)
out << *it << ", ";
out << "}";
return out;
}
int main()
{
ifstream fin("input.txt");
istream_iterator<Flowerbed> FB_in(fin);
istream_iterator<Flowerbed> end_in;
ostream_iterator<Flowerbed> FB_out(cout, "\n\t");
ostream_iterator<string> str_out(cout, "\n\t");
vector<Flowerbed> flowerbeds;
// FLOWERBEDS INPUT
copy(FB_in, end_in, back_inserter(flowerbeds));
// FLOWERBEDS SORED BY ID
sort(flowerbeds.begin(), flowerbeds.end(), [](const Flowerbed& a, const Flowerbed& b) {
return a.id < b.id;
});
cout << "SORTED BY ID:\n\t";
copy(flowerbeds.begin(), flowerbeds.end(), FB_out);
// FLOWERBEDS SORED BY SHAPE
sort(flowerbeds.begin(), flowerbeds.end(), [](const Flowerbed& a, const Flowerbed& b) {
return a.shape < b.shape;
});
cout << "\nSORTED BY SHAPE:\n\t";
copy(flowerbeds.begin(), flowerbeds.end(), FB_out);
//DIFFERENT SHAPES
set<string> different_forms;
for_each(flowerbeds.begin(), flowerbeds.end(), [&different_forms](const Flowerbed& a) {
different_forms.insert(a.shape);
});
cout << "\nDIFFERENT SHAPES (" << different_forms.size() << "):\n\t";
copy(different_forms.begin(), different_forms.end(), str_out);
//FLOWERS FROM FLOWERBED ID, FLOWERBED BY FLOWER NAME
map<int, Flowerbed> flowerbeds_map;
multimap<string, int> FB_id_by_flower;
for_each(flowerbeds.begin(), flowerbeds.end(), [&FB_id_by_flower, &flowerbeds_map](const Flowerbed& a) {
flowerbeds_map.insert(make_pair(a.id, a));
for_each(a.flowers.begin(), a.flowers.end(), [&FB_id_by_flower, &a](const string& s) {
FB_id_by_flower.insert(make_pair(s, a.id));
});
});
int id;
cout << "\nEnter flowerbed id: ";
cin >> id;
cout << "Flowers from flowerbed #" << id << ":\n\t";
copy(flowerbeds_map[id].flowers.begin(), flowerbeds_map[id].flowers.end(), str_out);
string fl_name;
cout << "\nEnter flower name: ";
cin >> fl_name;
auto found = FB_id_by_flower.find(fl_name);
cout << "Flower \"" << fl_name << "\" found in flowerbed #" << found->second << ":\n\t";
cout << flowerbeds_map[found->second] << endl;
//LIST OF ALL DIFFERENT FLOWERS, FLOWERBED WITH MAXIMUM NUMBER OF FLOWERS
int max_flowers = 0, max_flowers_FB_id;
set<string> different_flowers;
for_each(flowerbeds.begin(), flowerbeds.end(), [&different_flowers, &max_flowers, &max_flowers_FB_id](const Flowerbed& a) {
if (a.flowers.size() > max_flowers) {
max_flowers = a.flowers.size();
max_flowers_FB_id = a.id;
}
different_flowers.insert(a.flowers.begin(), a.flowers.end());
});
cout << "\nLIST OF ALL DIFFERENT FLOWERS (" << different_flowers.size() << "):\n\t";
copy(different_flowers.begin(), different_flowers.end(), str_out);
cout << "\nFOLWERBED WITH MAXIMUM NUMBER OF FLOWERS (" << max_flowers << "):\n\t";
cout << flowerbeds_map[max_flowers_FB_id];
cout << endl
<< endl;
return 0;
}
<|endoftext|> |
<commit_before>#include "TEnum.h"
#include "TInterpreter.h"
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include <type_traits>
TEST(TEnum, UnderlyingType)
{
gInterpreter->Declare(R"CODE(
enum E0 { kE0One };
enum E1 { kE1One = LONG_MAX };
enum E2 { kE2One = ULONG_MAX };
enum E3: char { kE3One };
enum Eb: bool { kEbOne };
enum Euc: unsigned char { kEucOne };
enum Esc: signed char { kEscOne };
enum Eus: unsigned short { kEusOne };
enum Ess: signed short { kEssOne };
enum Eui: unsigned int { kEuiOne };
enum Esi: signed int { kEsiOne };
enum Eul: unsigned long { kEulOne };
enum Esl: signed long { kEslOne };
enum Eull: unsigned long long { kEullOne };
enum Esll: signed long long { kEsllOne };
enum Ecl: short;
enum class ECb: bool { kOne };
enum class ECuc: unsigned char { kOne };
enum class ECsc: signed char { kOne };
enum class ECus: unsigned short { kOne };
enum class ECss: signed short { kOne };
enum class ECui: unsigned int { kOne };
enum class ECsi: signed int { kOne };
enum class ECul: unsigned long { kOne };
enum class ECsl: signed long { kOne };
enum class ECull: unsigned long long { kOne };
enum class ECsll: signed long long { kOne };
enum class ECcl: short;
)CODE"
);
enum E0 { kE0One };
enum E1 { kE1One = LONG_MAX };
enum E2 { kE2One = ULONG_MAX };
EXPECT_EQ(TEnum::GetEnum("E0")->GetUnderlyingType(), TDataType::GetType(typeid(std::underlying_type<E0>::type)));
EXPECT_EQ(TEnum::GetEnum("E1")->GetUnderlyingType(), TDataType::GetType(typeid(std::underlying_type<E1>::type)));
EXPECT_EQ(TEnum::GetEnum("E2")->GetUnderlyingType(), TDataType::GetType(typeid(std::underlying_type<E2>::type)));
EXPECT_EQ(TEnum::GetEnum("E3")->GetUnderlyingType(), kChar_t);
EXPECT_EQ(TEnum::GetEnum("Eb")->GetUnderlyingType(), kBool_t);
EXPECT_EQ(TEnum::GetEnum("Euc")->GetUnderlyingType(), kUChar_t);
EXPECT_EQ(TEnum::GetEnum("Esc")->GetUnderlyingType(), kChar_t);
EXPECT_EQ(TEnum::GetEnum("Eus")->GetUnderlyingType(), kUShort_t);
EXPECT_EQ(TEnum::GetEnum("Ess")->GetUnderlyingType(), kShort_t);
EXPECT_EQ(TEnum::GetEnum("Eui")->GetUnderlyingType(), kUInt_t);
EXPECT_EQ(TEnum::GetEnum("Esi")->GetUnderlyingType(), kInt_t);
EXPECT_EQ(TEnum::GetEnum("Eul")->GetUnderlyingType(), kULong_t);
EXPECT_EQ(TEnum::GetEnum("Esl")->GetUnderlyingType(), kLong_t);
EXPECT_EQ(TEnum::GetEnum("Eull")->GetUnderlyingType(), kULong64_t);
EXPECT_EQ(TEnum::GetEnum("Esll")->GetUnderlyingType(), kLong64_t);
EXPECT_EQ(TEnum::GetEnum("Ecl")->GetUnderlyingType(), kShort_t);
}
TEST(TEnum, Scoped)
{
gInterpreter->Declare(R"CODE(
enum class EC { kOne };
enum class EC1: long { kOne };
enum ED { kEDOne };
)CODE"
);
EXPECT_EQ(TEnum::GetEnum("EC")->Property() & kIsScopedEnum, kIsScopedEnum);
EXPECT_EQ(TEnum::GetEnum("EC1")->Property() & kIsScopedEnum, kIsScopedEnum);
EXPECT_EQ(TEnum::GetEnum("ED")->Property() & kIsScopedEnum, 0);
}
<commit_msg>[meta] testTEnum underlying type needs to be specific about signedness:<commit_after>#include "TEnum.h"
#include "TInterpreter.h"
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include <type_traits>
TEST(TEnum, UnderlyingType)
{
gInterpreter->Declare(R"CODE(
enum E0 { kE0One };
enum E1 { kE1One = LONG_MAX };
enum E2 { kE2One = ULONG_MAX };
enum Eb: bool { kEbOne };
enum Euc: unsigned char { kEucOne };
enum Esc: signed char { kEscOne };
enum Eus: unsigned short { kEusOne };
enum Ess: signed short { kEssOne };
enum Eui: unsigned int { kEuiOne };
enum Esi: signed int { kEsiOne };
enum Eul: unsigned long { kEulOne };
enum Esl: signed long { kEslOne };
enum Eull: unsigned long long { kEullOne };
enum Esll: signed long long { kEsllOne };
enum Ecl: short;
enum class ECb: bool { kOne };
enum class ECuc: unsigned char { kOne };
enum class ECsc: signed char { kOne };
enum class ECus: unsigned short { kOne };
enum class ECss: signed short { kOne };
enum class ECui: unsigned int { kOne };
enum class ECsi: signed int { kOne };
enum class ECul: unsigned long { kOne };
enum class ECsl: signed long { kOne };
enum class ECull: unsigned long long { kOne };
enum class ECsll: signed long long { kOne };
enum class ECcl: short;
)CODE"
);
enum E0 { kE0One };
enum E1 { kE1One = LONG_MAX };
enum E2 { kE2One = ULONG_MAX };
EXPECT_EQ(TEnum::GetEnum("E0")->GetUnderlyingType(), TDataType::GetType(typeid(std::underlying_type<E0>::type)));
EXPECT_EQ(TEnum::GetEnum("E1")->GetUnderlyingType(), TDataType::GetType(typeid(std::underlying_type<E1>::type)));
EXPECT_EQ(TEnum::GetEnum("E2")->GetUnderlyingType(), TDataType::GetType(typeid(std::underlying_type<E2>::type)));
EXPECT_EQ(TEnum::GetEnum("Eb")->GetUnderlyingType(), kBool_t);
EXPECT_EQ(TEnum::GetEnum("Euc")->GetUnderlyingType(), kUChar_t);
EXPECT_EQ(TEnum::GetEnum("Esc")->GetUnderlyingType(), kChar_t);
EXPECT_EQ(TEnum::GetEnum("Eus")->GetUnderlyingType(), kUShort_t);
EXPECT_EQ(TEnum::GetEnum("Ess")->GetUnderlyingType(), kShort_t);
EXPECT_EQ(TEnum::GetEnum("Eui")->GetUnderlyingType(), kUInt_t);
EXPECT_EQ(TEnum::GetEnum("Esi")->GetUnderlyingType(), kInt_t);
EXPECT_EQ(TEnum::GetEnum("Eul")->GetUnderlyingType(), kULong_t);
EXPECT_EQ(TEnum::GetEnum("Esl")->GetUnderlyingType(), kLong_t);
EXPECT_EQ(TEnum::GetEnum("Eull")->GetUnderlyingType(), kULong64_t);
EXPECT_EQ(TEnum::GetEnum("Esll")->GetUnderlyingType(), kLong64_t);
EXPECT_EQ(TEnum::GetEnum("Ecl")->GetUnderlyingType(), kShort_t);
}
TEST(TEnum, Scoped)
{
gInterpreter->Declare(R"CODE(
enum class EC { kOne };
enum class EC1: long { kOne };
enum ED { kEDOne };
)CODE"
);
EXPECT_EQ(TEnum::GetEnum("EC")->Property() & kIsScopedEnum, kIsScopedEnum);
EXPECT_EQ(TEnum::GetEnum("EC1")->Property() & kIsScopedEnum, kIsScopedEnum);
EXPECT_EQ(TEnum::GetEnum("ED")->Property() & kIsScopedEnum, 0);
}
<|endoftext|> |
<commit_before>#include <cmath>
#include "unit-tests-common.h"
#include <librealsense2/hpp/rs_types.hpp>
#include <librealsense2/hpp/rs_frame.hpp>
#include <iostream>
#include <chrono>
#include <ctime>
#include <algorithm>
#include <librealsense2/rsutil.h>
#include <sys/wait.h>
#include <semaphore.h>
#include <fcntl.h>
using namespace rs2;
using namespace std::chrono;
bool stream(std::string serial_number, sem_t* sem2, bool do_query)
{
signal(SIGTERM, [](int signum) { std::cout << "SIGTERM: " << getpid() << std::endl; exit(1);});
rs2::context ctx;
if (do_query)
{
rs2::device_list list(ctx.query_devices());
bool found_sn(false);
for (auto&& dev : ctx.query_devices())
{
if (dev.get_info(RS2_CAMERA_INFO_SERIAL_NUMBER) == serial_number)
{
found_sn = true;
}
}
REQUIRE(found_sn);
}
rs2::pipeline pipe(ctx);
rs2::config cfg;
cfg.enable_device(serial_number);
std::cout << "pipe starting: " << serial_number << std::endl;
pipe.start(cfg);
std::cout << "pipe started: " << serial_number << std::endl;
double max_milli_between_frames(3000);
double last_frame_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
double crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
bool is_running(true);
int sem_value;
while (is_running && crnt_time-last_frame_time < max_milli_between_frames)
{
rs2::frameset fs;
if (pipe.poll_for_frames(&fs))
{
last_frame_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
}
crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
sem_getvalue(sem2, &sem_value);
is_running = (sem_value == 0);
}
pipe.stop();
}
void multiple_stream(std::string serial_number, sem_t* sem, bool do_query)
{
size_t max_iterations(10);
pid_t pid;
std::stringstream sem_name;
sem_name << "sem_" << serial_number << "_" << 0;
bool is_running(true);
int sem_value;
for (size_t counter=0; counter<10 && is_running; counter++)
{
sem_unlink(sem_name.str().c_str());
sem_t *sem2 = sem_open(sem_name.str().c_str(), O_CREAT|O_EXCL, S_IRWXU, 0);
CHECK_FALSE(sem2 == SEM_FAILED);
pid = fork();
if (pid == 0) // child process
{
std::cout << "Start streaming: " << serial_number << " : (" << counter+1 << "/" << max_iterations << ")" << std::endl;
stream(serial_number, sem2, do_query); //on normal behavior - should block
break;
}
else
{
std::this_thread::sleep_for(std::chrono::seconds(5));
int status;
pid_t w = waitpid(pid, &status, WNOHANG);
bool child_alive(w == 0);
if (child_alive) {
sem_post(sem2);
// Give 2 seconds to quit before kill:
double start_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
double crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
while (child_alive && (crnt_time - start_time < 2000))
{
std::this_thread::sleep_for(std::chrono::milliseconds(500));
pid_t w = waitpid(pid, &status, WNOHANG);
child_alive = (w == 0);
crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
}
if (child_alive)
{
std::cout << "Failed to start streaming: " << serial_number << std::endl;
int res = kill(pid,SIGTERM);
pid_t w = waitpid(pid, &status, 0);
exit(2);
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
else
{
std::cout << "Frames did not arrive: " << serial_number << std::endl;
exit(1);
}
}
sem_getvalue(sem, &sem_value);
is_running = (sem_value == 0);
}
if (pid != 0)
{
sem_unlink(sem_name.str().c_str());
}
exit(0);
}
TEST_CASE("multicam_streaming", "[code][live]")
{
// Test will start and stop streaming on 2 devices simultaneously for 10 times, thus testing the named_mutex mechnism.
rs2::context ctx;
std::vector<std::string> serials_numbers;
for (auto&& dev : ctx.query_devices())
{
std::string serial(dev.get_info(RS2_CAMERA_INFO_SERIAL_NUMBER));
std::string usb_type(dev.get_info(RS2_CAMERA_INFO_USB_TYPE_DESCRIPTOR));
if ( usb_type != "3.2")
{
std::cout << "Device " << serial << " with usb_type " << usb_type << " is skipped.";
continue;
}
serials_numbers.push_back(serial);
}
REQUIRE(serials_numbers.size() >= 2);
std::vector<pid_t> pids;
pid_t pid;
bool do_query(true);
std::vector<sem_t*> sems;
for (size_t idx = 0; idx < serials_numbers.size(); idx++)
{
std::stringstream sem_name;
sem_name << "sem_" << idx;
sem_unlink(sem_name.str().c_str());
sems.push_back(sem_open(sem_name.str().c_str(), O_CREAT|O_EXCL, S_IRWXU, 0));
CHECK_FALSE(sems[idx] == SEM_FAILED);
pid = fork();
if (pid == 0) // child
{
multiple_stream(serials_numbers[idx], sems[idx], do_query); //on normal behavior - should block
}
else
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
pids.push_back(pid);
}
}
if (pid != 0)
{
int status0;
pid_t pid = wait(&status0);
std::cout << "status0 = " << status0 << std::endl;
for (auto sem : sems)
{
sem_post(sem);
}
for (auto pid : pids)
{
int status;
pid_t w = waitpid(pid, &status, WNOHANG);
std::cout << "status: " << pid << " : " << status << std::endl;
bool child_alive(w == 0);
double start_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
double crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
while (child_alive && (crnt_time - start_time < 6000))
{
std::cout << "waiting for: " << pid << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
pid_t w = waitpid(pid, &status, WNOHANG);
child_alive = (w == 0);
crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
}
if (child_alive)
{
std::cout << "kill: " << pid << std::endl;
int res = kill(pid,SIGTERM);
pid_t w = waitpid(pid, &status, 0);
std::cout << "status: " << status << ", " << w << std::endl;
}
}
REQUIRE(status0 == 0);
}
}<commit_msg>unit-test flag [live] should appear first.<commit_after>#include <cmath>
#include "unit-tests-common.h"
#include <librealsense2/hpp/rs_types.hpp>
#include <librealsense2/hpp/rs_frame.hpp>
#include <iostream>
#include <chrono>
#include <ctime>
#include <algorithm>
#include <librealsense2/rsutil.h>
#include <sys/wait.h>
#include <semaphore.h>
#include <fcntl.h>
using namespace rs2;
using namespace std::chrono;
bool stream(std::string serial_number, sem_t* sem2, bool do_query)
{
signal(SIGTERM, [](int signum) { std::cout << "SIGTERM: " << getpid() << std::endl; exit(1);});
rs2::context ctx;
if (do_query)
{
rs2::device_list list(ctx.query_devices());
bool found_sn(false);
for (auto&& dev : ctx.query_devices())
{
if (dev.get_info(RS2_CAMERA_INFO_SERIAL_NUMBER) == serial_number)
{
found_sn = true;
}
}
REQUIRE(found_sn);
}
rs2::pipeline pipe(ctx);
rs2::config cfg;
cfg.enable_device(serial_number);
std::cout << "pipe starting: " << serial_number << std::endl;
pipe.start(cfg);
std::cout << "pipe started: " << serial_number << std::endl;
double max_milli_between_frames(3000);
double last_frame_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
double crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
bool is_running(true);
int sem_value;
while (is_running && crnt_time-last_frame_time < max_milli_between_frames)
{
rs2::frameset fs;
if (pipe.poll_for_frames(&fs))
{
last_frame_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
}
crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
sem_getvalue(sem2, &sem_value);
is_running = (sem_value == 0);
}
pipe.stop();
}
void multiple_stream(std::string serial_number, sem_t* sem, bool do_query)
{
size_t max_iterations(10);
pid_t pid;
std::stringstream sem_name;
sem_name << "sem_" << serial_number << "_" << 0;
bool is_running(true);
int sem_value;
for (size_t counter=0; counter<10 && is_running; counter++)
{
sem_unlink(sem_name.str().c_str());
sem_t *sem2 = sem_open(sem_name.str().c_str(), O_CREAT|O_EXCL, S_IRWXU, 0);
CHECK_FALSE(sem2 == SEM_FAILED);
pid = fork();
if (pid == 0) // child process
{
std::cout << "Start streaming: " << serial_number << " : (" << counter+1 << "/" << max_iterations << ")" << std::endl;
stream(serial_number, sem2, do_query); //on normal behavior - should block
break;
}
else
{
std::this_thread::sleep_for(std::chrono::seconds(5));
int status;
pid_t w = waitpid(pid, &status, WNOHANG);
bool child_alive(w == 0);
if (child_alive) {
sem_post(sem2);
// Give 2 seconds to quit before kill:
double start_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
double crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
while (child_alive && (crnt_time - start_time < 2000))
{
std::this_thread::sleep_for(std::chrono::milliseconds(500));
pid_t w = waitpid(pid, &status, WNOHANG);
child_alive = (w == 0);
crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
}
if (child_alive)
{
std::cout << "Failed to start streaming: " << serial_number << std::endl;
int res = kill(pid,SIGTERM);
pid_t w = waitpid(pid, &status, 0);
exit(2);
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
else
{
std::cout << "Frames did not arrive: " << serial_number << std::endl;
exit(1);
}
}
sem_getvalue(sem, &sem_value);
is_running = (sem_value == 0);
}
if (pid != 0)
{
sem_unlink(sem_name.str().c_str());
}
exit(0);
}
TEST_CASE("multicam_streaming", "[live][code]")
{
// Test will start and stop streaming on 2 devices simultaneously for 10 times, thus testing the named_mutex mechnism.
rs2::context ctx;
std::vector<std::string> serials_numbers;
for (auto&& dev : ctx.query_devices())
{
std::string serial(dev.get_info(RS2_CAMERA_INFO_SERIAL_NUMBER));
std::string usb_type(dev.get_info(RS2_CAMERA_INFO_USB_TYPE_DESCRIPTOR));
if ( usb_type != "3.2")
{
std::cout << "Device " << serial << " with usb_type " << usb_type << " is skipped.";
continue;
}
serials_numbers.push_back(serial);
}
REQUIRE(serials_numbers.size() >= 2);
std::vector<pid_t> pids;
pid_t pid;
bool do_query(true);
std::vector<sem_t*> sems;
for (size_t idx = 0; idx < serials_numbers.size(); idx++)
{
std::stringstream sem_name;
sem_name << "sem_" << idx;
sem_unlink(sem_name.str().c_str());
sems.push_back(sem_open(sem_name.str().c_str(), O_CREAT|O_EXCL, S_IRWXU, 0));
CHECK_FALSE(sems[idx] == SEM_FAILED);
pid = fork();
if (pid == 0) // child
{
multiple_stream(serials_numbers[idx], sems[idx], do_query); //on normal behavior - should block
}
else
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
pids.push_back(pid);
}
}
if (pid != 0)
{
int status0;
pid_t pid = wait(&status0);
std::cout << "status0 = " << status0 << std::endl;
for (auto sem : sems)
{
sem_post(sem);
}
for (auto pid : pids)
{
int status;
pid_t w = waitpid(pid, &status, WNOHANG);
std::cout << "status: " << pid << " : " << status << std::endl;
bool child_alive(w == 0);
double start_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
double crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
while (child_alive && (crnt_time - start_time < 6000))
{
std::cout << "waiting for: " << pid << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
pid_t w = waitpid(pid, &status, WNOHANG);
child_alive = (w == 0);
crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
}
if (child_alive)
{
std::cout << "kill: " << pid << std::endl;
int res = kill(pid,SIGTERM);
pid_t w = waitpid(pid, &status, 0);
std::cout << "status: " << status << ", " << w << std::endl;
}
}
REQUIRE(status0 == 0);
}
}<|endoftext|> |
<commit_before>#include "tileWorker.h"
#include "platform.h"
#include "data/dataSource.h"
#include "tile/tile.h"
#include "view/view.h"
#include "scene/scene.h"
#include "tile/tileID.h"
#include "tile/tileTask.h"
#include "tile/tileBuilder.h"
#include "tangram.h"
#include <algorithm>
#define WORKER_NICENESS 10
namespace Tangram {
TileWorker::TileWorker(int _num_worker) {
m_running = true;
m_pendingTiles = false;
for (int i = 0; i < _num_worker; i++) {
auto worker = std::make_unique<Worker>();
worker->thread = std::thread(&TileWorker::run, this, worker.get());
m_workers.push_back(std::move(worker));
}
}
TileWorker::~TileWorker(){
if (m_running) {
stop();
}
}
void disposeBuilder(std::unique_ptr<TileBuilder> _builder) {
if (_builder) {
// Bind _builder to a std::function that will run on the next mainloop
// iteration and does therefore dispose the TileBuilder, including it's
// Scene reference with OpenGL resources on the mainloop. This is done
// in order to ensure that no GL functions are called on
// the worker-thread.
auto disposer = std::bind([](auto builder){},
std::shared_ptr<TileBuilder>(std::move(_builder)));
Tangram::runOnMainLoop(disposer);
}
}
void TileWorker::run(Worker* instance) {
setCurrentThreadPriority(WORKER_NICENESS);
std::unique_ptr<TileBuilder> builder;
while (true) {
std::shared_ptr<TileTask> task;
{
std::unique_lock<std::mutex> lock(m_mutex);
m_condition.wait(lock, [&, this]{
return !m_running || !m_queue.empty();
});
if (instance->tileBuilder) {
disposeBuilder(std::move(builder));
builder = std::move(instance->tileBuilder);
LOG("Passed new TileBuilder to TileWorker");
}
// Check if thread should stop
if (!m_running) {
disposeBuilder(std::move(builder));
break;
}
if (!builder) {
LOGE("Missing Scene/StyleContext in TileWorker!");
continue;
}
// Remove all canceled tasks
auto removes = std::remove_if(m_queue.begin(), m_queue.end(),
[](const auto& a) { return a->isCanceled(); });
m_queue.erase(removes, m_queue.end());
if (m_queue.empty()) {
continue;
}
// Pop highest priority tile from queue
auto it = std::min_element(m_queue.begin(), m_queue.end(),
[](const auto& a, const auto& b) {
if (a->isProxy() != b->isProxy()) {
return !a->isProxy();
}
if (a->source().id() == b->source().id() &&
a->sourceGeneration() != b->sourceGeneration()) {
return a->sourceGeneration() < b->sourceGeneration();
}
return a->getPriority() < b->getPriority();
});
task = std::move(*it);
m_queue.erase(it);
}
if (task->isCanceled()) {
continue;
}
auto tileData = task->source().parse(*task, *builder->scene().mapProjection());
// const clock_t begin = clock();
if (tileData) {
auto raster = task->source().raster(*task);
auto tile = builder->build(task->tileId(), *tileData, task->source());
if (tile) { task->doneBuilding(); }
// float loadTime = (float(clock() - begin) / CLOCKS_PER_SEC) * 1000;
// LOG("loadTime %s - %f", task->tile()->getID().toString().c_str(), loadTime);
std::unique_lock<std::mutex> lock(m_mutex);
m_condition.wait(lock, [&]() {
if (!m_running) { return true; }
if (task->isCanceled()) { return true; }
for (auto& raster : task->rasterTasks()) {
if (!raster->hasData()) {
return false;
}
}
return true;
});
if (!m_running) {
if (builder) {
disposeBuilder(std::move(builder));
}
tile.reset();
m_queue.clear();
break;
}
if (task->isCanceled()) {
tile.reset();
continue;
}
// first set self texture, if it has one, then go to reference raster textures
if (raster.isValid()) {
tile->rasters().push_back(std::move(raster));
}
for (auto& rasterTask : task->rasterTasks()) {
auto rasterTex = rasterTask->source().raster(*rasterTask);
if (rasterTex.isValid()) {
tile->rasters().push_back(std::move(rasterTex));
}
}
// Mark task as ready
task->setTile(std::move(tile));
} else {
task->cancel();
}
m_pendingTiles = true;
requestRender();
}
}
void TileWorker::setScene(std::shared_ptr<Scene>& _scene) {
for (auto& worker : m_workers) {
auto tileBuilder = std::make_unique<TileBuilder>();
tileBuilder->setScene(_scene);
worker->tileBuilder = std::move(tileBuilder);
}
}
void TileWorker::enqueue(std::shared_ptr<TileTask>&& task) {
{
std::unique_lock<std::mutex> lock(m_mutex);
if (!m_running) {
return;
}
if (!task->isBuilt()) {
m_queue.push_back(std::move(task));
}
}
m_condition.notify_one();
}
void TileWorker::stop() {
{
std::unique_lock<std::mutex> lock(m_mutex);
m_running = false;
}
m_condition.notify_all();
for (auto& worker : m_workers) {
worker->thread.join();
}
}
}
<commit_msg>Remove extraneous tile and queue clears<commit_after>#include "tileWorker.h"
#include "platform.h"
#include "data/dataSource.h"
#include "tile/tile.h"
#include "view/view.h"
#include "scene/scene.h"
#include "tile/tileID.h"
#include "tile/tileTask.h"
#include "tile/tileBuilder.h"
#include "tangram.h"
#include <algorithm>
#define WORKER_NICENESS 10
namespace Tangram {
TileWorker::TileWorker(int _num_worker) {
m_running = true;
m_pendingTiles = false;
for (int i = 0; i < _num_worker; i++) {
auto worker = std::make_unique<Worker>();
worker->thread = std::thread(&TileWorker::run, this, worker.get());
m_workers.push_back(std::move(worker));
}
}
TileWorker::~TileWorker(){
if (m_running) {
stop();
}
}
void disposeBuilder(std::unique_ptr<TileBuilder> _builder) {
if (_builder) {
// Bind _builder to a std::function that will run on the next mainloop
// iteration and does therefore dispose the TileBuilder, including it's
// Scene reference with OpenGL resources on the mainloop. This is done
// in order to ensure that no GL functions are called on
// the worker-thread.
auto disposer = std::bind([](auto builder){},
std::shared_ptr<TileBuilder>(std::move(_builder)));
Tangram::runOnMainLoop(disposer);
}
}
void TileWorker::run(Worker* instance) {
setCurrentThreadPriority(WORKER_NICENESS);
std::unique_ptr<TileBuilder> builder;
while (true) {
std::shared_ptr<TileTask> task;
{
std::unique_lock<std::mutex> lock(m_mutex);
m_condition.wait(lock, [&, this]{
return !m_running || !m_queue.empty();
});
if (instance->tileBuilder) {
disposeBuilder(std::move(builder));
builder = std::move(instance->tileBuilder);
LOG("Passed new TileBuilder to TileWorker");
}
// Check if thread should stop
if (!m_running) {
disposeBuilder(std::move(builder));
break;
}
if (!builder) {
LOGE("Missing Scene/StyleContext in TileWorker!");
continue;
}
// Remove all canceled tasks
auto removes = std::remove_if(m_queue.begin(), m_queue.end(),
[](const auto& a) { return a->isCanceled(); });
m_queue.erase(removes, m_queue.end());
if (m_queue.empty()) {
continue;
}
// Pop highest priority tile from queue
auto it = std::min_element(m_queue.begin(), m_queue.end(),
[](const auto& a, const auto& b) {
if (a->isProxy() != b->isProxy()) {
return !a->isProxy();
}
if (a->source().id() == b->source().id() &&
a->sourceGeneration() != b->sourceGeneration()) {
return a->sourceGeneration() < b->sourceGeneration();
}
return a->getPriority() < b->getPriority();
});
task = std::move(*it);
m_queue.erase(it);
}
if (task->isCanceled()) {
continue;
}
auto tileData = task->source().parse(*task, *builder->scene().mapProjection());
// const clock_t begin = clock();
if (tileData) {
auto raster = task->source().raster(*task);
auto tile = builder->build(task->tileId(), *tileData, task->source());
if (tile) { task->doneBuilding(); }
// float loadTime = (float(clock() - begin) / CLOCKS_PER_SEC) * 1000;
// LOG("loadTime %s - %f", task->tile()->getID().toString().c_str(), loadTime);
std::unique_lock<std::mutex> lock(m_mutex);
m_condition.wait(lock, [&]() {
if (!m_running) { return true; }
if (task->isCanceled()) { return true; }
for (auto& raster : task->rasterTasks()) {
if (!raster->hasData()) {
return false;
}
}
return true;
});
if (!m_running) {
if (builder) {
disposeBuilder(std::move(builder));
}
break;
}
if (task->isCanceled()) {
continue;
}
// first set self texture, if it has one, then go to reference raster textures
if (raster.isValid()) {
tile->rasters().push_back(std::move(raster));
}
for (auto& rasterTask : task->rasterTasks()) {
auto rasterTex = rasterTask->source().raster(*rasterTask);
if (rasterTex.isValid()) {
tile->rasters().push_back(std::move(rasterTex));
}
}
// Mark task as ready
task->setTile(std::move(tile));
} else {
task->cancel();
}
m_pendingTiles = true;
requestRender();
}
}
void TileWorker::setScene(std::shared_ptr<Scene>& _scene) {
for (auto& worker : m_workers) {
auto tileBuilder = std::make_unique<TileBuilder>();
tileBuilder->setScene(_scene);
worker->tileBuilder = std::move(tileBuilder);
}
}
void TileWorker::enqueue(std::shared_ptr<TileTask>&& task) {
{
std::unique_lock<std::mutex> lock(m_mutex);
if (!m_running) {
return;
}
if (!task->isBuilt()) {
m_queue.push_back(std::move(task));
}
}
m_condition.notify_one();
}
void TileWorker::stop() {
{
std::unique_lock<std::mutex> lock(m_mutex);
m_running = false;
}
m_condition.notify_all();
for (auto& worker : m_workers) {
worker->thread.join();
}
}
}
<|endoftext|> |
<commit_before>// Copyright 2011-12 Bifrost Entertainment. All rights reserved.
#include "Common/Data.h"
#include "Common/RainbowAssert.h"
#ifdef RAINBOW_IOS
void Data::free(const void *const) { /* This is not needed */ }
const char* Data::get_path(const char *const file)
{
if (!file)
return [[[NSBundle mainBundle] bundlePath] UTF8String];
NSString *path = [NSString stringWithUTF8String:(file)];
return [[[NSBundle mainBundle] pathForResource:[path stringByDeletingPathExtension] ofType:[path pathExtension]] UTF8String];
}
Data::Data(const char *const file) : data(nil)
{
R_ASSERT(file, "No file to open");
NSError *err = nil;
NSString *path = [NSString stringWithUTF8String:file];
this->data = [[NSMutableData alloc] initWithContentsOfFile:path options:NSDataReadingUncached error:&err];
if (err != nil)
{
NSLog(@"[Rainbow] Data: Failed to read file");
this->data = nil;
}
}
Data::~Data() { }
void Data::copy(const void *const data, const size_t length)
{
R_ASSERT(false, "copy: Not implemented yet");
}
bool Data::save(const char *const file) const
{
if (!this->data)
return false;
R_ASSERT(false, "save: Not implemented yet");
return true;
}
#endif
<commit_msg>iOS: Implemented Data::copy().<commit_after>// Copyright 2011-12 Bifrost Entertainment. All rights reserved.
#include "Common/Data.h"
#include "Common/RainbowAssert.h"
#ifdef RAINBOW_IOS
void Data::free(const void *const) { /* This is not needed */ }
const char* Data::get_path(const char *const file)
{
if (!file)
return [[[NSBundle mainBundle] bundlePath] UTF8String];
NSString *path = [NSString stringWithUTF8String:(file)];
return [[[NSBundle mainBundle] pathForResource:[path stringByDeletingPathExtension] ofType:[path pathExtension]] UTF8String];
}
Data::Data(const char *const file) : data(nil)
{
R_ASSERT(file, "No file to open");
NSError *err = nil;
NSString *path = [NSString stringWithUTF8String:file];
this->data = [[NSMutableData alloc] initWithContentsOfFile:path options:NSDataReadingUncached error:&err];
if (err != nil)
{
NSLog(@"[Rainbow] Data: Failed to read file");
this->data = nil;
}
}
Data::~Data() { }
void Data::copy(const void *const data, const size_t length)
{
[this->data replaceBytesInRange:NSMakeRange(0, this->data.length) withBytes:data length:length];
}
bool Data::save(const char *const file) const
{
if (!this->data)
return false;
R_ASSERT(false, "save: Not implemented yet");
return true;
}
#endif
<|endoftext|> |
<commit_before>#include <Bindings/Bindings.hpp>
#include <Scene/Scene.hpp>
#include <Script/GameObject.hpp>
#include <Script/GlobalState.hpp>
#include <Script/ViliLuaBridge.hpp>
#include <System/Loaders.hpp>
#include <Transform/Units.hpp>
#include <Transform/UnitVector.hpp>
#include <Triggers/Trigger.hpp>
#include <Triggers/TriggerDatabase.hpp>
#define GAMEOBJECTENV ScriptEngine["__ENVIRONMENTS"][m_envIndex]
namespace obe
{
namespace Script
{
KAGUYA_MEMBER_FUNCTION_OVERLOADS_WITH_SIGNATURE(useExternalTriggerProxy, GameObject, useExternalTrigger, 3, 4,
void(GameObject::*)(std::string, std::string, std::string, std::string));
/*kaguya::LuaTable GameObject::access(kaguya::State* lua) const
{
return (*m_objectScript)["Object"];
}*/
unsigned GameObject::getEnvIndex() const
{
return m_envIndex;
}
kaguya::LuaTable GameObject::access() const
{
return GAMEOBJECTENV["Object"];
}
kaguya::LuaFunction GameObject::getConstructor() const
{
return GAMEOBJECTENV["ObjectInit"];
}
vili::ViliParser GameObjectDatabase::allDefinitions;
vili::ViliParser GameObjectDatabase::allRequires;
vili::ComplexNode* GameObjectDatabase::GetRequirementsForGameObject(const std::string& type)
{
if (!allRequires.root().contains(type))
{
vili::ViliParser getGameObjectFile;
System::Path("Data/GameObjects/").add(type).add(type + ".obj.vili").loadResource(&getGameObjectFile, System::Loaders::dataLoader);
if (getGameObjectFile->contains("Requires"))
{
vili::ComplexNode& requiresData = getGameObjectFile.at<vili::ComplexNode>("Requires");
getGameObjectFile->extractElement(&getGameObjectFile.at<vili::ComplexNode>("Requires"));
requiresData.setId(type);
allRequires->pushComplexNode(&requiresData);
return &requiresData;
}
return nullptr;
}
return &allRequires.at(type);
}
vili::ComplexNode* GameObjectDatabase::GetDefinitionForGameObject(const std::string& type)
{
if (!allDefinitions.root().contains(type))
{
vili::ViliParser getGameObjectFile;
System::Path("Data/GameObjects/").add(type).add(type + ".obj.vili").loadResource(&getGameObjectFile, System::Loaders::dataLoader);
if (getGameObjectFile->contains(type))
{
vili::ComplexNode& definitionData = getGameObjectFile.at<vili::ComplexNode>(type);
getGameObjectFile->extractElement(&getGameObjectFile.at<vili::ComplexNode>(type));
definitionData.setId(type);
allDefinitions->pushComplexNode(&definitionData);
return &definitionData;
}
aube::ErrorHandler::Raise("ObEngine.Script.GameObjectDatabase.ObjectDefinitionNotFound", { { "objectType", type } });
return nullptr;
}
return &allDefinitions.at(type);
}
void GameObjectDatabase::ApplyRequirements(GameObject* obj, vili::ComplexNode& requires)
{
for (const std::string& currentRequirement : requires.getAll())
{
kaguya::LuaTable requireTable = ScriptEngine["__ENVIRONMENTS"][obj->getEnvIndex()]["LuaCore"]["ObjectInitInjectionTable"];
DataBridge::dataToLua(requireTable, requires.get(currentRequirement));
}
}
//GameObject
std::vector<unsigned int> GameObject::AllEnvs;
GameObject::GameObject(const std::string& type, const std::string& id) : Identifiable(id), m_localTriggers(nullptr), m_objectNode(id)
{
m_type = type;
m_id = id;
}
void GameObject::initialize()
{
if (!m_initialised)
{
Debug::Log->debug("<GameObject> Initialising GameObject '{0}'", m_id);
m_initialised = true;
GAMEOBJECTENV["__OBJECT_INIT"] = true;
m_localTriggers->trigger("Init");
}
else
Debug::Log->warn("<GameObject> GameObject '{0}' has already been initialised", m_id);
}
GameObject::~GameObject()
{
Debug::Log->debug("<GameObject> Deleting GameObject {0}", m_id);
if (m_hasScriptEngine)
{
Triggers::TriggerDatabase::GetInstance()->removeNamespace(m_privateKey);
Triggers::TriggerDatabase::GetInstance()->removeNamespace(m_publicKey);
}
}
void GameObject::sendInitArgFromLua(const std::string& argName, kaguya::LuaRef value) const
{
Debug::Log->debug("<GameObject> Sending Local.Init argument {0} to GameObject {1} (From Lua)", argName, m_id);
m_localTriggers->pushParameterFromLua("Init", argName, value);
}
void GameObject::registerTrigger(Triggers::Trigger* trg, const std::string& callbackName)
{
m_registeredTriggers.emplace_back(trg, callbackName);
}
void GameObject::loadGameObject(Scene::Scene& world, vili::ComplexNode& obj)
{
Debug::Log->debug("<GameObject> Loading GameObject '{0}'", m_id);
//Script
if (obj.contains(vili::NodeType::DataNode, "permanent"))
{
m_permanent = obj.getDataNode("permanent").get<bool>();
}
if (obj.contains(vili::NodeType::ComplexNode, "Script"))
{
m_hasScriptEngine = true;
m_privateKey = Utils::String::getRandomKey(Utils::String::Alphabet + Utils::String::Numbers, 12);
m_publicKey = Utils::String::getRandomKey(Utils::String::Alphabet + Utils::String::Numbers, 12);
Triggers::TriggerDatabase::GetInstance()->createNamespace(m_privateKey);
Triggers::TriggerDatabase::GetInstance()->createNamespace(m_publicKey);
m_localTriggers = Triggers::TriggerDatabase::GetInstance()->createTriggerGroup(m_privateKey, "Local");
m_envIndex = ScriptEngine["CreateNewEnv"]();
AllEnvs.push_back(m_envIndex);
//std::cout << "Environment Index is : " << m_envIndex << std::endl;
//executeFile(m_envIndex, System::Path("Lib/Internal/ScriptInit.lua").find());
//loadScrGameObject(this, m_objectScript.get());
GAMEOBJECTENV["This"] = this;
m_localTriggers
->addTrigger("Init")
->addTrigger("Delete");
executeFile(m_envIndex, System::Path("Lib/Internal/ObjectInit.lua").find());
GAMEOBJECTENV["__OBJECT_TYPE"] = m_type;
GAMEOBJECTENV["__OBJECT_ID"] = m_id;
GAMEOBJECTENV["__OBJECT_INIT"] = false;
GAMEOBJECTENV["Private"] = m_privateKey;
GAMEOBJECTENV["Public"] = m_publicKey;
if (obj.at("Script").contains(vili::NodeType::DataNode, "source"))
{
std::string getScrName = obj.at("Script").getDataNode("source").get<std::string>();
executeFile(m_envIndex, System::Path(getScrName).find());
}
else if (obj.at("Script").contains(vili::NodeType::ArrayNode, "sources"))
{
int scriptListSize = obj.at("Script").getArrayNode("sources").size();
for (int i = 0; i < scriptListSize; i++)
{
std::string getScrName = obj.at("Script").getArrayNode("sources").get(i).get<std::string>();
executeFile(m_envIndex, System::Path(getScrName).find());
}
}
}
if (obj.contains(vili::NodeType::ComplexNode, "Animator"))
{
m_objectAnimator = std::make_unique<Animation::Animator>();
std::string animatorPath = obj.at("Animator").getDataNode("path").get<std::string>();
if (animatorPath != "")
{
m_objectAnimator->setPath(animatorPath);
m_objectAnimator->loadAnimator();
}
if (obj.at("Animator").contains(vili::NodeType::DataNode, "default"))
{
m_objectAnimator->setKey(obj.at("Animator").getDataNode("default").get<std::string>());
}
if (m_hasScriptEngine)
GAMEOBJECTENV["Object"]["Animation"] = m_objectAnimator.get();
m_hasAnimator = true;
}
//Collider
if (obj.contains(vili::NodeType::ComplexNode, "Collider"))
{
m_objectCollider = world.createCollider(m_id, false);
m_objectNode.addChild(m_objectCollider);
std::string pointsUnit = obj.at("Collider", "unit").getDataNode("unit").get<std::string>();
bool completePoint = true;
double pointBuffer = 0;
Transform::Units pBaseUnit = Transform::stringToUnits(pointsUnit);
for (vili::DataNode* colliderPoint : obj.at("Collider").getArrayNode("points"))
{
if ((completePoint = !completePoint))
{
Transform::UnitVector pVector2 = Transform::UnitVector(
pointBuffer,
colliderPoint->get<double>(),
pBaseUnit
).to<Transform::Units::WorldPixels>();
m_objectCollider->addPoint(pVector2);
}
else
pointBuffer = colliderPoint->get<double>();
}
if (obj.at("Collider").contains(vili::NodeType::DataNode, "tag"))
m_objectCollider->addTag(Collision::ColliderTagType::Tag, obj.at<vili::DataNode>("Collider", "tag").get<std::string>());
else if (obj.at("Collider").contains(vili::NodeType::ArrayNode, "tags"))
{
for (vili::DataNode* cTag : obj.at<vili::ArrayNode>("Collider", "tags"))
m_objectCollider->addTag(Collision::ColliderTagType::Tag, cTag->get<std::string>());
}
if (obj.at("Collider").contains(vili::NodeType::DataNode, "accept"))
m_objectCollider->addTag(Collision::ColliderTagType::Accepted, obj.at<vili::DataNode>("Collider", "accept").get<std::string>());
else if (obj.at("Collider").contains(vili::NodeType::ArrayNode, "accept"))
{
for (vili::DataNode* aTag : obj.at<vili::ArrayNode>("Collider", "accept"))
m_objectCollider->addTag(Collision::ColliderTagType::Accepted, aTag->get<std::string>());
}
if (obj.at("Collider").contains(vili::NodeType::DataNode, "reject"))
m_objectCollider->addTag(Collision::ColliderTagType::Rejected, obj.at<vili::DataNode>("Collider", "reject").get<std::string>());
else if (obj.at("Collider").contains(vili::NodeType::ArrayNode, "reject"))
{
for (vili::DataNode* rTag : obj.at<vili::ArrayNode>("Collider", "reject"))
m_objectCollider->addTag(Collision::ColliderTagType::Rejected, rTag->get<std::string>());
}
if (m_hasScriptEngine)
GAMEOBJECTENV["Object"]["Collider"] = m_objectCollider;
m_hasCollider = true;
}
//LevelSprite
if (obj.contains(vili::NodeType::ComplexNode, "LevelSprite"))
{
m_objectLevelSprite = world.createLevelSprite(m_id, false);
m_objectNode.addChild(m_objectLevelSprite);
m_objectLevelSprite->configure(obj.at("LevelSprite"));
if (m_hasScriptEngine)
GAMEOBJECTENV["Object"]["LevelSprite"] = m_objectLevelSprite;
m_hasLevelSprite = true;
world.reorganizeLayers();
}
}
void GameObject::update()
{
if (m_canUpdate)
{
if (m_initialised)
{
if (m_hasAnimator)
{
if (m_objectAnimator->getKey() != "")
m_objectAnimator->update();
if (m_hasLevelSprite)
{
m_objectLevelSprite->setTexture(m_objectAnimator->getTexture());
}
}
}
else
{
this->initialize();
}
}
}
std::string GameObject::getType() const
{
return m_type;
}
std::string GameObject::getPublicKey() const
{
return m_publicKey;
}
bool GameObject::doesHaveAnimator() const
{
return m_hasAnimator;
}
bool GameObject::doesHaveCollider() const
{
return m_hasCollider;
}
bool GameObject::doesHaveLevelSprite() const
{
return m_hasLevelSprite;
}
bool GameObject::doesHaveScriptEngine() const
{
return m_hasScriptEngine;
}
bool GameObject::getUpdateState() const
{
return m_canUpdate;
}
void GameObject::setUpdateState(bool state)
{
m_canUpdate = state;
}
Graphics::LevelSprite* GameObject::getLevelSprite()
{
if (m_hasLevelSprite)
return m_objectLevelSprite;
throw aube::ErrorHandler::Raise("ObEngine.Script.GameObject.NoLevelSprite", {{"id", m_id}});
}
Transform::SceneNode* GameObject::getSceneNode()
{
return &m_objectNode;
}
Collision::PolygonalCollider* GameObject::getCollider()
{
if (m_hasCollider)
return m_objectCollider;
throw aube::ErrorHandler::Raise("ObEngine.Script.GameObject.NoCollider", {{"id", m_id}});
}
Animation::Animator* GameObject::getAnimator()
{
if (m_hasAnimator)
return m_objectAnimator.get();
throw aube::ErrorHandler::Raise("ObEngine.Script.GameObject.NoAnimator", {{"id", m_id}});
}
Triggers::TriggerGroup* GameObject::getLocalTriggers() const
{
return m_localTriggers.operator->();
}
void GameObject::useLocalTrigger(const std::string& trName)
{
this->registerTrigger(Triggers::TriggerDatabase::GetInstance()->getTrigger(m_privateKey, "Local", trName), "Local." + trName);
Triggers::TriggerDatabase::GetInstance()->getTrigger(m_privateKey, "Local", trName)->registerEnvironment(m_envIndex, "Local." + trName);
}
void GameObject::useExternalTrigger(const std::string& trNsp, const std::string& trGrp, const std::string& trName, const std::string& callAlias)
{
if (trName == "*")
{
std::vector<std::string> allTrg = Triggers::TriggerDatabase::GetInstance()->getAllTriggersNameFromTriggerGroup(trNsp, trGrp);
for (int i = 0; i < allTrg.size(); i++)
{
this->useExternalTrigger(trNsp, trGrp, trName,
(Utils::String::occurencesInString(callAlias, "*")) ?
Utils::String::replace(callAlias, "*", allTrg[i]) :
"");
}
}
else
{
bool triggerNotFound = true;
for (auto& triggerPair : m_registeredTriggers)
{
if (triggerPair.first == Triggers::TriggerDatabase::GetInstance()->getTrigger(trNsp, trGrp, trName))
{
triggerNotFound = false;
}
}
if (triggerNotFound)
{
std::string callbackName = (callAlias.empty()) ? trNsp + "." + trGrp + "." + trName : callAlias;
this->registerTrigger(Triggers::TriggerDatabase::GetInstance()->getTrigger(trNsp, trGrp, trName), callbackName);
Triggers::TriggerDatabase::GetInstance()->getTrigger(trNsp, trGrp, trName)->registerEnvironment(m_envIndex, callbackName);
}
}
}
void GameObject::exec(const std::string& query) const
{
ScriptEngine["ExecuteStringOnEnv"](query, m_envIndex);
}
void GameObject::deleteObject()
{
Debug::Log->debug("GameObject::deleteObject called for {0}", m_id);
m_localTriggers->trigger("Delete");
this->deletable = true;
for (auto& trigger : m_registeredTriggers)
{
trigger.first->unregisterEnvironment(m_envIndex);
}
AllEnvs.erase(
std::remove_if(
AllEnvs.begin(),
AllEnvs.end(),
[this](const unsigned int& envIndex) { return envIndex == m_envIndex; }
),
AllEnvs.end()
);
//GAMEOBJECTENV = nullptr;
}
void GameObject::setPermanent(bool permanent)
{
m_permanent = permanent;
}
bool GameObject::isPermanent() const
{
return m_permanent;
}
}
}
<commit_msg>Added some GameObject Debug hints<commit_after>#include <Bindings/Bindings.hpp>
#include <Scene/Scene.hpp>
#include <Script/GameObject.hpp>
#include <Script/GlobalState.hpp>
#include <Script/ViliLuaBridge.hpp>
#include <System/Loaders.hpp>
#include <Transform/Units.hpp>
#include <Transform/UnitVector.hpp>
#include <Triggers/Trigger.hpp>
#include <Triggers/TriggerDatabase.hpp>
#define GAMEOBJECTENV ScriptEngine["__ENVIRONMENTS"][m_envIndex]
namespace obe
{
namespace Script
{
KAGUYA_MEMBER_FUNCTION_OVERLOADS_WITH_SIGNATURE(useExternalTriggerProxy, GameObject, useExternalTrigger, 3, 4,
void(GameObject::*)(std::string, std::string, std::string, std::string));
/*kaguya::LuaTable GameObject::access(kaguya::State* lua) const
{
return (*m_objectScript)["Object"];
}*/
unsigned GameObject::getEnvIndex() const
{
return m_envIndex;
}
kaguya::LuaTable GameObject::access() const
{
return GAMEOBJECTENV["Object"];
}
kaguya::LuaFunction GameObject::getConstructor() const
{
return GAMEOBJECTENV["ObjectInit"];
}
vili::ViliParser GameObjectDatabase::allDefinitions;
vili::ViliParser GameObjectDatabase::allRequires;
vili::ComplexNode* GameObjectDatabase::GetRequirementsForGameObject(const std::string& type)
{
if (!allRequires.root().contains(type))
{
vili::ViliParser getGameObjectFile;
System::Path("Data/GameObjects/").add(type).add(type + ".obj.vili").loadResource(&getGameObjectFile, System::Loaders::dataLoader);
if (getGameObjectFile->contains("Requires"))
{
vili::ComplexNode& requiresData = getGameObjectFile.at<vili::ComplexNode>("Requires");
getGameObjectFile->extractElement(&getGameObjectFile.at<vili::ComplexNode>("Requires"));
requiresData.setId(type);
allRequires->pushComplexNode(&requiresData);
return &requiresData;
}
return nullptr;
}
return &allRequires.at(type);
}
vili::ComplexNode* GameObjectDatabase::GetDefinitionForGameObject(const std::string& type)
{
if (!allDefinitions.root().contains(type))
{
vili::ViliParser getGameObjectFile;
System::Path("Data/GameObjects/").add(type).add(type + ".obj.vili").loadResource(&getGameObjectFile, System::Loaders::dataLoader);
if (getGameObjectFile->contains(type))
{
vili::ComplexNode& definitionData = getGameObjectFile.at<vili::ComplexNode>(type);
getGameObjectFile->extractElement(&getGameObjectFile.at<vili::ComplexNode>(type));
definitionData.setId(type);
allDefinitions->pushComplexNode(&definitionData);
return &definitionData;
}
aube::ErrorHandler::Raise("ObEngine.Script.GameObjectDatabase.ObjectDefinitionNotFound", { { "objectType", type } });
return nullptr;
}
return &allDefinitions.at(type);
}
void GameObjectDatabase::ApplyRequirements(GameObject* obj, vili::ComplexNode& requires)
{
for (const std::string& currentRequirement : requires.getAll())
{
kaguya::LuaTable requireTable = ScriptEngine["__ENVIRONMENTS"][obj->getEnvIndex()]["LuaCore"]["ObjectInitInjectionTable"];
DataBridge::dataToLua(requireTable, requires.get(currentRequirement));
}
}
//GameObject
std::vector<unsigned int> GameObject::AllEnvs;
GameObject::GameObject(const std::string& type, const std::string& id) : Identifiable(id), m_localTriggers(nullptr), m_objectNode(id)
{
m_type = type;
m_id = id;
}
void GameObject::initialize()
{
if (!m_initialised)
{
Debug::Log->debug("<GameObject> Initialising GameObject '{0}' ({1})", m_id, m_type);
m_initialised = true;
GAMEOBJECTENV["__OBJECT_INIT"] = true;
m_localTriggers->trigger("Init");
}
else
Debug::Log->warn("<GameObject> GameObject '{0}' ({1}) has already been initialised", m_id, m_type);
}
GameObject::~GameObject()
{
Debug::Log->debug("<GameObject> Deleting GameObject '{0}' ({1})", m_id, m_type);
if (m_hasScriptEngine)
{
Triggers::TriggerDatabase::GetInstance()->removeNamespace(m_privateKey);
Triggers::TriggerDatabase::GetInstance()->removeNamespace(m_publicKey);
}
}
void GameObject::sendInitArgFromLua(const std::string& argName, kaguya::LuaRef value) const
{
Debug::Log->debug("<GameObject> Sending Local.Init argument {0} to GameObject {1} ({2}) (From Lua)", argName, m_id, m_type);
m_localTriggers->pushParameterFromLua("Init", argName, value);
}
void GameObject::registerTrigger(Triggers::Trigger* trg, const std::string& callbackName)
{
m_registeredTriggers.emplace_back(trg, callbackName);
}
void GameObject::loadGameObject(Scene::Scene& world, vili::ComplexNode& obj)
{
Debug::Log->debug("<GameObject> Loading GameObject '{0}' ({1})", m_id, m_type);
//Script
if (obj.contains(vili::NodeType::DataNode, "permanent"))
{
m_permanent = obj.getDataNode("permanent").get<bool>();
}
if (obj.contains(vili::NodeType::ComplexNode, "Script"))
{
m_hasScriptEngine = true;
m_privateKey = Utils::String::getRandomKey(Utils::String::Alphabet + Utils::String::Numbers, 12);
m_publicKey = Utils::String::getRandomKey(Utils::String::Alphabet + Utils::String::Numbers, 12);
Triggers::TriggerDatabase::GetInstance()->createNamespace(m_privateKey);
Triggers::TriggerDatabase::GetInstance()->createNamespace(m_publicKey);
m_localTriggers = Triggers::TriggerDatabase::GetInstance()->createTriggerGroup(m_privateKey, "Local");
m_envIndex = ScriptEngine["CreateNewEnv"]();
AllEnvs.push_back(m_envIndex);
//std::cout << "Environment Index is : " << m_envIndex << std::endl;
//executeFile(m_envIndex, System::Path("Lib/Internal/ScriptInit.lua").find());
//loadScrGameObject(this, m_objectScript.get());
GAMEOBJECTENV["This"] = this;
m_localTriggers
->addTrigger("Init")
->addTrigger("Delete");
executeFile(m_envIndex, System::Path("Lib/Internal/ObjectInit.lua").find());
GAMEOBJECTENV["__OBJECT_TYPE"] = m_type;
GAMEOBJECTENV["__OBJECT_ID"] = m_id;
GAMEOBJECTENV["__OBJECT_INIT"] = false;
GAMEOBJECTENV["Private"] = m_privateKey;
GAMEOBJECTENV["Public"] = m_publicKey;
if (obj.at("Script").contains(vili::NodeType::DataNode, "source"))
{
std::string getScrName = obj.at("Script").getDataNode("source").get<std::string>();
executeFile(m_envIndex, System::Path(getScrName).find());
}
else if (obj.at("Script").contains(vili::NodeType::ArrayNode, "sources"))
{
int scriptListSize = obj.at("Script").getArrayNode("sources").size();
for (int i = 0; i < scriptListSize; i++)
{
std::string getScrName = obj.at("Script").getArrayNode("sources").get(i).get<std::string>();
executeFile(m_envIndex, System::Path(getScrName).find());
}
}
}
if (obj.contains(vili::NodeType::ComplexNode, "Animator"))
{
m_objectAnimator = std::make_unique<Animation::Animator>();
std::string animatorPath = obj.at("Animator").getDataNode("path").get<std::string>();
if (animatorPath != "")
{
m_objectAnimator->setPath(animatorPath);
m_objectAnimator->loadAnimator();
}
if (obj.at("Animator").contains(vili::NodeType::DataNode, "default"))
{
m_objectAnimator->setKey(obj.at("Animator").getDataNode("default").get<std::string>());
}
if (m_hasScriptEngine)
GAMEOBJECTENV["Object"]["Animation"] = m_objectAnimator.get();
m_hasAnimator = true;
}
//Collider
if (obj.contains(vili::NodeType::ComplexNode, "Collider"))
{
m_objectCollider = world.createCollider(m_id, false);
m_objectNode.addChild(m_objectCollider);
std::string pointsUnit = obj.at("Collider", "unit").getDataNode("unit").get<std::string>();
bool completePoint = true;
double pointBuffer = 0;
Transform::Units pBaseUnit = Transform::stringToUnits(pointsUnit);
for (vili::DataNode* colliderPoint : obj.at("Collider").getArrayNode("points"))
{
if ((completePoint = !completePoint))
{
Transform::UnitVector pVector2 = Transform::UnitVector(
pointBuffer,
colliderPoint->get<double>(),
pBaseUnit
).to<Transform::Units::WorldPixels>();
m_objectCollider->addPoint(pVector2);
}
else
pointBuffer = colliderPoint->get<double>();
}
if (obj.at("Collider").contains(vili::NodeType::DataNode, "tag"))
m_objectCollider->addTag(Collision::ColliderTagType::Tag, obj.at<vili::DataNode>("Collider", "tag").get<std::string>());
else if (obj.at("Collider").contains(vili::NodeType::ArrayNode, "tags"))
{
for (vili::DataNode* cTag : obj.at<vili::ArrayNode>("Collider", "tags"))
m_objectCollider->addTag(Collision::ColliderTagType::Tag, cTag->get<std::string>());
}
if (obj.at("Collider").contains(vili::NodeType::DataNode, "accept"))
m_objectCollider->addTag(Collision::ColliderTagType::Accepted, obj.at<vili::DataNode>("Collider", "accept").get<std::string>());
else if (obj.at("Collider").contains(vili::NodeType::ArrayNode, "accept"))
{
for (vili::DataNode* aTag : obj.at<vili::ArrayNode>("Collider", "accept"))
m_objectCollider->addTag(Collision::ColliderTagType::Accepted, aTag->get<std::string>());
}
if (obj.at("Collider").contains(vili::NodeType::DataNode, "reject"))
m_objectCollider->addTag(Collision::ColliderTagType::Rejected, obj.at<vili::DataNode>("Collider", "reject").get<std::string>());
else if (obj.at("Collider").contains(vili::NodeType::ArrayNode, "reject"))
{
for (vili::DataNode* rTag : obj.at<vili::ArrayNode>("Collider", "reject"))
m_objectCollider->addTag(Collision::ColliderTagType::Rejected, rTag->get<std::string>());
}
if (m_hasScriptEngine)
GAMEOBJECTENV["Object"]["Collider"] = m_objectCollider;
m_hasCollider = true;
}
//LevelSprite
if (obj.contains(vili::NodeType::ComplexNode, "LevelSprite"))
{
m_objectLevelSprite = world.createLevelSprite(m_id, false);
m_objectNode.addChild(m_objectLevelSprite);
m_objectLevelSprite->configure(obj.at("LevelSprite"));
if (m_hasScriptEngine)
GAMEOBJECTENV["Object"]["LevelSprite"] = m_objectLevelSprite;
m_hasLevelSprite = true;
world.reorganizeLayers();
}
}
void GameObject::update()
{
if (m_canUpdate)
{
if (m_initialised)
{
if (m_hasAnimator)
{
if (m_objectAnimator->getKey() != "")
m_objectAnimator->update();
if (m_hasLevelSprite)
{
m_objectLevelSprite->setTexture(m_objectAnimator->getTexture());
}
}
}
else
{
this->initialize();
}
}
}
std::string GameObject::getType() const
{
return m_type;
}
std::string GameObject::getPublicKey() const
{
return m_publicKey;
}
bool GameObject::doesHaveAnimator() const
{
return m_hasAnimator;
}
bool GameObject::doesHaveCollider() const
{
return m_hasCollider;
}
bool GameObject::doesHaveLevelSprite() const
{
return m_hasLevelSprite;
}
bool GameObject::doesHaveScriptEngine() const
{
return m_hasScriptEngine;
}
bool GameObject::getUpdateState() const
{
return m_canUpdate;
}
void GameObject::setUpdateState(bool state)
{
m_canUpdate = state;
}
Graphics::LevelSprite* GameObject::getLevelSprite()
{
if (m_hasLevelSprite)
return m_objectLevelSprite;
throw aube::ErrorHandler::Raise("ObEngine.Script.GameObject.NoLevelSprite", {{"id", m_id}});
}
Transform::SceneNode* GameObject::getSceneNode()
{
return &m_objectNode;
}
Collision::PolygonalCollider* GameObject::getCollider()
{
if (m_hasCollider)
return m_objectCollider;
throw aube::ErrorHandler::Raise("ObEngine.Script.GameObject.NoCollider", {{"id", m_id}});
}
Animation::Animator* GameObject::getAnimator()
{
if (m_hasAnimator)
return m_objectAnimator.get();
throw aube::ErrorHandler::Raise("ObEngine.Script.GameObject.NoAnimator", {{"id", m_id}});
}
Triggers::TriggerGroup* GameObject::getLocalTriggers() const
{
return m_localTriggers.operator->();
}
void GameObject::useLocalTrigger(const std::string& trName)
{
this->registerTrigger(Triggers::TriggerDatabase::GetInstance()->getTrigger(m_privateKey, "Local", trName), "Local." + trName);
Triggers::TriggerDatabase::GetInstance()->getTrigger(m_privateKey, "Local", trName)->registerEnvironment(m_envIndex, "Local." + trName);
}
void GameObject::useExternalTrigger(const std::string& trNsp, const std::string& trGrp, const std::string& trName, const std::string& callAlias)
{
if (trName == "*")
{
std::vector<std::string> allTrg = Triggers::TriggerDatabase::GetInstance()->getAllTriggersNameFromTriggerGroup(trNsp, trGrp);
for (int i = 0; i < allTrg.size(); i++)
{
this->useExternalTrigger(trNsp, trGrp, trName,
(Utils::String::occurencesInString(callAlias, "*")) ?
Utils::String::replace(callAlias, "*", allTrg[i]) :
"");
}
}
else
{
bool triggerNotFound = true;
for (auto& triggerPair : m_registeredTriggers)
{
if (triggerPair.first == Triggers::TriggerDatabase::GetInstance()->getTrigger(trNsp, trGrp, trName))
{
triggerNotFound = false;
}
}
if (triggerNotFound)
{
std::string callbackName = (callAlias.empty()) ? trNsp + "." + trGrp + "." + trName : callAlias;
this->registerTrigger(Triggers::TriggerDatabase::GetInstance()->getTrigger(trNsp, trGrp, trName), callbackName);
Triggers::TriggerDatabase::GetInstance()->getTrigger(trNsp, trGrp, trName)->registerEnvironment(m_envIndex, callbackName);
}
}
}
void GameObject::exec(const std::string& query) const
{
ScriptEngine["ExecuteStringOnEnv"](query, m_envIndex);
}
void GameObject::deleteObject()
{
Debug::Log->debug("GameObject::deleteObject called for '{0}' ({1})", m_id, m_type);
m_localTriggers->trigger("Delete");
this->deletable = true;
for (auto& trigger : m_registeredTriggers)
{
trigger.first->unregisterEnvironment(m_envIndex);
}
AllEnvs.erase(
std::remove_if(
AllEnvs.begin(),
AllEnvs.end(),
[this](const unsigned int& envIndex) { return envIndex == m_envIndex; }
),
AllEnvs.end()
);
//GAMEOBJECTENV = nullptr;
}
void GameObject::setPermanent(bool permanent)
{
m_permanent = permanent;
}
bool GameObject::isPermanent() const
{
return m_permanent;
}
}
}
<|endoftext|> |
<commit_before>#include "config.h"
#ifdef CONFIG_TASKBAR
#include "ylib.h"
#include "aworkspaces.h"
#include "wmtaskbar.h"
#include "prefs.h"
#include "wmmgr.h"
#include "wmapp.h"
#include "wmframe.h"
#include "yrect.h"
#include "yicon.h"
#include "intl.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include "base.h"
YColor * WorkspaceButton::normalButtonBg(NULL);
YColor * WorkspaceButton::normalButtonFg(NULL);
YColor * WorkspaceButton::activeButtonBg(NULL);
YColor * WorkspaceButton::activeButtonFg(NULL);
ref<YFont> WorkspaceButton::normalButtonFont;
ref<YFont> WorkspaceButton::activeButtonFont;
ref<YPixmap> workspacebuttonPixmap;
ref<YPixmap> workspacebuttonactivePixmap;
#ifdef CONFIG_GRADIENTS
ref<YPixbuf> workspacebuttonPixbuf;
ref<YPixbuf> workspacebuttonactivePixbuf;
#endif
WorkspaceButton::WorkspaceButton(long ws, YWindow *parent): ObjectButton(parent, (YAction *)0)
{
fWorkspace = ws;
//setDND(true);
}
void WorkspaceButton::handleClick(const XButtonEvent &/*up*/, int /*count*/) {
}
void WorkspaceButton::handleDNDEnter() {
if (fRaiseTimer == 0)
fRaiseTimer = new YTimer(autoRaiseDelay);
if (fRaiseTimer) {
fRaiseTimer->setTimerListener(this);
fRaiseTimer->startTimer();
}
repaint();
}
void WorkspaceButton::handleDNDLeave() {
if (fRaiseTimer && fRaiseTimer->getTimerListener() == this) {
fRaiseTimer->stopTimer();
fRaiseTimer->setTimerListener(0);
}
repaint();
}
bool WorkspaceButton::handleTimer(YTimer *t) {
if (t == fRaiseTimer) {
manager->activateWorkspace(fWorkspace);
}
return false;
}
void WorkspaceButton::actionPerformed(YAction */*action*/, unsigned int modifiers) {
if (modifiers & ShiftMask) {
manager->switchToWorkspace(fWorkspace, true);
} else if (modifiers & xapp->AltMask) {
if (manager->getFocus())
manager->getFocus()->wmOccupyWorkspace(fWorkspace);
} else {
manager->activateWorkspace(fWorkspace);
return;
}
}
WorkspacesPane::WorkspacesPane(YWindow *parent): YWindow(parent) {
long w;
if (workspaceCount > 0)
fWorkspaceButton = new WorkspaceButton *[workspaceCount];
else
fWorkspaceButton = 0;
if (fWorkspaceButton) {
YResourcePaths paths("", false);
int ht = 24;
int leftX = 0;
#warning "fixme"
/// ht = parent->height();
for (w = 0; w < workspaceCount; w++) {
WorkspaceButton *wk = new WorkspaceButton(w, this);
if (wk) {
ref<YIconImage> image
(paths.loadImage("workspace/", workspaceNames[w]));
if (image != null)
wk->setImage(image);
else
wk->setText(workspaceNames[w]);
char * wn(newstr(my_basename(workspaceNames[w])));
char * ext(strrchr(wn, '.'));
if (ext) *ext = '\0';
char * tt(strJoin(_("Workspace: "), wn, NULL));
delete[] wn;
wk->setToolTip(tt);
delete[] tt;
//if ((int)wk->height() + 1 > ht) ht = wk->height() + 1;
}
fWorkspaceButton[w] = wk;
}
for (w = 0; w < workspaceCount; w++) {
YButton *wk = fWorkspaceButton[w];
//leftX += 2;
if (wk) {
wk->setGeometry(YRect(leftX, 0, wk->width(), ht));
wk->show();
leftX += wk->width();
}
}
setSize(leftX, ht);
}
}
WorkspacesPane::~WorkspacesPane() {
if (fWorkspaceButton) {
for (long w = 0; w < workspaceCount; w++)
delete fWorkspaceButton[w];
delete [] fWorkspaceButton;
}
}
void WorkspacesPane::configure(const YRect &r, const bool resized) {
YWindow::configure(r, resized);
int ht = height();
int leftX = 0;
for (int w = 0; w < workspaceCount; w++) {
YButton *wk = fWorkspaceButton[w];
//leftX += 2;
if (wk) {
wk->setGeometry(YRect(leftX, 0, wk->width(), ht));
leftX += wk->width();
}
}
}
WorkspaceButton *WorkspacesPane::workspaceButton(long n) {
return (fWorkspaceButton ? fWorkspaceButton[n] : NULL);
}
ref<YFont> WorkspaceButton::getFont() {
return isPressed()
? *activeWorkspaceFontName
? activeButtonFont != null
? activeButtonFont
: activeButtonFont = YFont::getFont(XFA(activeWorkspaceFontName))
: YButton::getFont()
: *normalWorkspaceFontName
? normalButtonFont != null
? normalButtonFont
: normalButtonFont = YFont::getFont(XFA(normalWorkspaceFontName))
: YButton::getFont();
}
YColor * WorkspaceButton::getColor() {
return isPressed()
? *clrWorkspaceActiveButtonText
? activeButtonFg
? activeButtonFg
: activeButtonFg = new YColor(clrWorkspaceActiveButtonText)
: YButton::getColor()
: *clrWorkspaceNormalButtonText
? normalButtonFg
? normalButtonFg
: normalButtonFg = new YColor(clrWorkspaceNormalButtonText)
: YButton::getColor();
}
YSurface WorkspaceButton::getSurface() {
if (activeButtonBg == 0)
activeButtonBg = new YColor(*clrWorkspaceActiveButton
? clrWorkspaceActiveButton : clrActiveButton);
if (normalButtonBg == 0)
normalButtonBg = new YColor(*clrWorkspaceNormalButton
? clrWorkspaceNormalButton : clrNormalButton);
#ifdef CONFIG_GRADIENTS
return (isPressed() ? YSurface(activeButtonBg,
workspacebuttonactivePixmap,
workspacebuttonactivePixbuf)
: YSurface(normalButtonBg,
workspacebuttonPixmap,
workspacebuttonPixbuf));
#else
return (isPressed() ? YSurface(activeButtonBg, workspacebuttonactivePixmap)
: YSurface(normalButtonBg, workspacebuttonPixmap));
#endif
}
#endif
<commit_msg>fix fallback xft font<commit_after>#include "config.h"
#ifdef CONFIG_TASKBAR
#include "ylib.h"
#include "aworkspaces.h"
#include "wmtaskbar.h"
#include "prefs.h"
#include "wmmgr.h"
#include "wmapp.h"
#include "wmframe.h"
#include "yrect.h"
#include "yicon.h"
#include "intl.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include "base.h"
YColor * WorkspaceButton::normalButtonBg(NULL);
YColor * WorkspaceButton::normalButtonFg(NULL);
YColor * WorkspaceButton::activeButtonBg(NULL);
YColor * WorkspaceButton::activeButtonFg(NULL);
ref<YFont> WorkspaceButton::normalButtonFont;
ref<YFont> WorkspaceButton::activeButtonFont;
ref<YPixmap> workspacebuttonPixmap;
ref<YPixmap> workspacebuttonactivePixmap;
#ifdef CONFIG_GRADIENTS
ref<YPixbuf> workspacebuttonPixbuf;
ref<YPixbuf> workspacebuttonactivePixbuf;
#endif
WorkspaceButton::WorkspaceButton(long ws, YWindow *parent): ObjectButton(parent, (YAction *)0)
{
fWorkspace = ws;
//setDND(true);
}
void WorkspaceButton::handleClick(const XButtonEvent &/*up*/, int /*count*/) {
}
void WorkspaceButton::handleDNDEnter() {
if (fRaiseTimer == 0)
fRaiseTimer = new YTimer(autoRaiseDelay);
if (fRaiseTimer) {
fRaiseTimer->setTimerListener(this);
fRaiseTimer->startTimer();
}
repaint();
}
void WorkspaceButton::handleDNDLeave() {
if (fRaiseTimer && fRaiseTimer->getTimerListener() == this) {
fRaiseTimer->stopTimer();
fRaiseTimer->setTimerListener(0);
}
repaint();
}
bool WorkspaceButton::handleTimer(YTimer *t) {
if (t == fRaiseTimer) {
manager->activateWorkspace(fWorkspace);
}
return false;
}
void WorkspaceButton::actionPerformed(YAction */*action*/, unsigned int modifiers) {
if (modifiers & ShiftMask) {
manager->switchToWorkspace(fWorkspace, true);
} else if (modifiers & xapp->AltMask) {
if (manager->getFocus())
manager->getFocus()->wmOccupyWorkspace(fWorkspace);
} else {
manager->activateWorkspace(fWorkspace);
return;
}
}
WorkspacesPane::WorkspacesPane(YWindow *parent): YWindow(parent) {
long w;
if (workspaceCount > 0)
fWorkspaceButton = new WorkspaceButton *[workspaceCount];
else
fWorkspaceButton = 0;
if (fWorkspaceButton) {
YResourcePaths paths("", false);
int ht = 24;
int leftX = 0;
#warning "fixme"
/// ht = parent->height();
for (w = 0; w < workspaceCount; w++) {
WorkspaceButton *wk = new WorkspaceButton(w, this);
if (wk) {
ref<YIconImage> image
(paths.loadImage("workspace/", workspaceNames[w]));
if (image != null)
wk->setImage(image);
else
wk->setText(workspaceNames[w]);
char * wn(newstr(my_basename(workspaceNames[w])));
char * ext(strrchr(wn, '.'));
if (ext) *ext = '\0';
char * tt(strJoin(_("Workspace: "), wn, NULL));
delete[] wn;
wk->setToolTip(tt);
delete[] tt;
//if ((int)wk->height() + 1 > ht) ht = wk->height() + 1;
}
fWorkspaceButton[w] = wk;
}
for (w = 0; w < workspaceCount; w++) {
YButton *wk = fWorkspaceButton[w];
//leftX += 2;
if (wk) {
wk->setGeometry(YRect(leftX, 0, wk->width(), ht));
wk->show();
leftX += wk->width();
}
}
setSize(leftX, ht);
}
}
WorkspacesPane::~WorkspacesPane() {
if (fWorkspaceButton) {
for (long w = 0; w < workspaceCount; w++)
delete fWorkspaceButton[w];
delete [] fWorkspaceButton;
}
}
void WorkspacesPane::configure(const YRect &r, const bool resized) {
YWindow::configure(r, resized);
int ht = height();
int leftX = 0;
for (int w = 0; w < workspaceCount; w++) {
YButton *wk = fWorkspaceButton[w];
//leftX += 2;
if (wk) {
wk->setGeometry(YRect(leftX, 0, wk->width(), ht));
leftX += wk->width();
}
}
}
WorkspaceButton *WorkspacesPane::workspaceButton(long n) {
return (fWorkspaceButton ? fWorkspaceButton[n] : NULL);
}
ref<YFont> WorkspaceButton::getFont() {
return isPressed()
? (*activeWorkspaceFontName || *activeWorkspaceFontNameXft)
? activeButtonFont != null
? activeButtonFont
: activeButtonFont = YFont::getFont(XFA(activeWorkspaceFontName))
: YButton::getFont()
: (*normalWorkspaceFontName || *normalWorkspaceFontNameXft)
? normalButtonFont != null
? normalButtonFont
: normalButtonFont = YFont::getFont(XFA(normalWorkspaceFontName))
: YButton::getFont();
}
YColor * WorkspaceButton::getColor() {
return isPressed()
? *clrWorkspaceActiveButtonText
? activeButtonFg
? activeButtonFg
: activeButtonFg = new YColor(clrWorkspaceActiveButtonText)
: YButton::getColor()
: *clrWorkspaceNormalButtonText
? normalButtonFg
? normalButtonFg
: normalButtonFg = new YColor(clrWorkspaceNormalButtonText)
: YButton::getColor();
}
YSurface WorkspaceButton::getSurface() {
if (activeButtonBg == 0)
activeButtonBg = new YColor(*clrWorkspaceActiveButton
? clrWorkspaceActiveButton : clrActiveButton);
if (normalButtonBg == 0)
normalButtonBg = new YColor(*clrWorkspaceNormalButton
? clrWorkspaceNormalButton : clrNormalButton);
#ifdef CONFIG_GRADIENTS
return (isPressed() ? YSurface(activeButtonBg,
workspacebuttonactivePixmap,
workspacebuttonactivePixbuf)
: YSurface(normalButtonBg,
workspacebuttonPixmap,
workspacebuttonPixbuf));
#else
return (isPressed() ? YSurface(activeButtonBg, workspacebuttonactivePixmap)
: YSurface(normalButtonBg, workspacebuttonPixmap));
#endif
}
#endif
<|endoftext|> |
<commit_before>#ifndef STREAMS_HH
#define STREAMS_HH
#include <stddef.h>
#include <stdlib.h>
#include "Queue.hh"
class FormatBase
{
public:
enum class Base: uint8_t
{
// bcd = 0,
bin = 2,
oct = 8,
dec = 10,
hex = 16
};
FormatBase(): _width(6), _precision(4), _base(Base::dec) {}
inline void width(int8_t width)
{
_width = width;
}
inline int8_t width()
{
return _width;
}
inline void precision(int8_t precision)
{
_precision = precision;
}
inline int8_t precision()
{
return _precision;
}
inline void base(Base base)
{
_base = base;
}
inline Base base()
{
return _base;
}
protected:
const char* convert(int v)
{
char s[8 * sizeof(int) + 1];
return itoa(v, s, (uint8_t) _base);
}
const char* convert(unsigned int v)
{
char s[8 * sizeof(int) + 1];
return utoa(v, s, (uint8_t) _base);
}
const char* convert(long v)
{
char s[8 * sizeof(long) + 1];
return ltoa(v, s, (uint8_t) _base);
}
const char* convert(unsigned long v)
{
char s[8 * sizeof(long) + 1];
return ultoa(v, s, (uint8_t) _base);
}
const char* convert(double v)
{
char s[MAX_BUF_LEN];
return dtostrf(v, _width, _precision, s);
}
private:
static const uint8_t MAX_BUF_LEN = 64;
int8_t _width;
uint8_t _precision;
Base _base;
};
template<typename STREAM>
class FormattedOutput: public FormatBase
{
public:
FormattedOutput(STREAM& stream): _stream(stream) {}
void flush()
{
_stream.flush();
}
void put(char c, bool flush = true)
{
_stream.put(c, flush);
}
void put(const char* content, size_t size)
{
_stream.put(content, size);
}
void puts(const char* str)
{
_stream.puts(str);
}
// void puts_P();
//TODO others? eg void*, PSTR, Manipulator...
FormattedOutput<STREAM>& operator << (const char* s)
{
_stream.puts(s);
return *this;
}
FormattedOutput<STREAM>& operator << (int v)
{
_stream.puts(convert(v));
return *this;
}
FormattedOutput<STREAM>& operator << (unsigned int v)
{
_stream.puts(convert(v));
return *this;
}
FormattedOutput<STREAM>& operator << (long v)
{
_stream.puts(convert(v));
return *this;
}
FormattedOutput<STREAM>& operator << (unsigned long v)
{
_stream.puts(convert(v));
return *this;
}
FormattedOutput<STREAM>& operator << (double v)
{
_stream.puts(convert(v));
return *this;
}
typedef FormattedOutput<STREAM>& (*Manipulator)(FormattedOutput<STREAM>&);
FormattedOutput<STREAM>& operator << (Manipulator f)
{
return f(*this);
}
private:
STREAM& _stream;
friend FormattedOutput<STREAM>& bin(FormattedOutput<STREAM>&);
friend FormattedOutput<STREAM>& oct(FormattedOutput<STREAM>&);
friend FormattedOutput<STREAM>& dec(FormattedOutput<STREAM>&);
friend FormattedOutput<STREAM>& hex(FormattedOutput<STREAM>&);
//TODO other parameters here
friend FormattedOutput<STREAM>& flush(FormattedOutput<STREAM>&);
friend FormattedOutput<STREAM>& endl(FormattedOutput<STREAM>&);
};
template<typename STREAM>
inline FormattedOutput<STREAM>& bin(FormattedOutput<STREAM>& stream)
{
stream.base(FormatBase::Base::bin);
return stream;
}
template<typename STREAM>
inline FormattedOutput<STREAM>& oct(FormattedOutput<STREAM>& stream)
{
stream.base(FormatBase::Base::oct);
return stream;
}
template<typename STREAM>
inline FormattedOutput<STREAM>& dec(FormattedOutput<STREAM>& stream)
{
stream.base(FormatBase::Base::dec);
return stream;
}
template<typename STREAM>
inline FormattedOutput<STREAM>& hex(FormattedOutput<STREAM>& stream)
{
stream.base(FormatBase::Base::hex);
return stream;
}
template<typename STREAM>
inline FormattedOutput<STREAM>& flush(FormattedOutput<STREAM>& stream)
{
stream.flush();
return stream;
}
template<typename STREAM>
inline FormattedOutput<STREAM>& endl(FormattedOutput<STREAM>& stream)
{
stream.put('\n');
return stream;
}
class OutputBuffer:public Queue<char>
{
public:
template<uint8_t SIZE>
OutputBuffer(char (&buffer)[SIZE]): Queue<char>(buffer, SIZE)
{
static_assert(SIZE && !(SIZE & (SIZE - 1)), "SIZE must be a power of 2");
}
template<uint8_t SIZE>
static OutputBuffer create(char buffer[SIZE])
{
static_assert(SIZE && !(SIZE & (SIZE - 1)), "SIZE must be a power of 2");
return OutputBuffer(buffer, SIZE);
}
void flush()
{
on_flush();
}
void put(char c, bool flush = true)
{
if (!push(c)) on_overflow(c);
if (flush) on_flush();
}
void put(const char* content, size_t size)
{
while (size--) put(*content++, false);
on_flush();
}
void puts(const char* str)
{
while (*str) put(*str++, false);
on_flush();
}
// void puts_P();
protected:
OutputBuffer(char* buffer, uint8_t size): Queue<char>(buffer, size) {}
// Listeners of events on the buffer
virtual void on_overflow(__attribute__((unused)) char c) {}
virtual void on_flush() {}
};
//TODO Handle generic errors coming from UART RX (eg Parity...)
class InputBuffer: public Queue<char>
{
public:
static const int EOF = -1;
template<uint8_t SIZE>
InputBuffer(char (&buffer)[SIZE]): Queue<char>(buffer, SIZE)
{
static_assert(SIZE && !(SIZE & (SIZE - 1)), "SIZE must be a power of 2");
}
template<uint8_t SIZE>
static InputBuffer create(char buffer[SIZE])
{
static_assert(SIZE && !(SIZE & (SIZE - 1)), "SIZE must be a power of 2");
return InputBuffer(buffer, SIZE);
}
int available() const
{
return items();
}
int get()
{
char value;
if (pull(value)) return value;
return EOF;
}
//TODO
int gets(char* str, size_t max);
// InputBuffer& operator >> (bool& b);
// InputBuffer& operator >> (char& c);
// InputBuffer& operator >> (char* s);
// InputBuffer& operator >> (int& d);
// InputBuffer& operator >> (unsigned int& d);
// InputBuffer& operator >> (long& d);
// InputBuffer& operator >> (unsigned long& d);
// InputBuffer& operator >> (float& f);
// InputBuffer& operator >> (double& f);
protected:
InputBuffer(char* buffer, uint8_t size): Queue<char>(buffer, size) {}
// Listeners of events on the buffer
virtual void on_empty() {}
virtual void on_get(__attribute__((unused)) char c) {}
};
#endif /* STREAMS_HH */
<commit_msg>Work on implementation of Hardware UART (work in progress). Small reorganization of classes in header file.<commit_after>#ifndef STREAMS_HH
#define STREAMS_HH
#include <stddef.h>
#include <stdlib.h>
#include "Queue.hh"
class OutputBuffer:public Queue<char>
{
public:
template<uint8_t SIZE>
OutputBuffer(char (&buffer)[SIZE]): Queue<char>(buffer, SIZE)
{
static_assert(SIZE && !(SIZE & (SIZE - 1)), "SIZE must be a power of 2");
}
template<uint8_t SIZE>
static OutputBuffer create(char buffer[SIZE])
{
static_assert(SIZE && !(SIZE & (SIZE - 1)), "SIZE must be a power of 2");
return OutputBuffer(buffer, SIZE);
}
void flush()
{
on_flush();
}
void put(char c, bool flush = true)
{
if (!push(c)) on_overflow(c);
if (flush) on_flush();
}
void put(const char* content, size_t size)
{
while (size--) put(*content++, false);
on_flush();
}
void puts(const char* str)
{
while (*str) put(*str++, false);
on_flush();
}
// void puts_P();
protected:
OutputBuffer(char* buffer, uint8_t size): Queue<char>(buffer, size) {}
// Listeners of events on the buffer
virtual void on_overflow(__attribute__((unused)) char c) {}
virtual void on_flush() {}
};
//TODO Handle generic errors coming from UART RX (eg Parity...)
class InputBuffer: public Queue<char>
{
public:
static const int EOF = -1;
template<uint8_t SIZE>
InputBuffer(char (&buffer)[SIZE]): Queue<char>(buffer, SIZE)
{
static_assert(SIZE && !(SIZE & (SIZE - 1)), "SIZE must be a power of 2");
}
template<uint8_t SIZE>
static InputBuffer create(char buffer[SIZE])
{
static_assert(SIZE && !(SIZE & (SIZE - 1)), "SIZE must be a power of 2");
return InputBuffer(buffer, SIZE);
}
int available() const
{
return items();
}
int get()
{
char value;
if (pull(value)) return value;
return EOF;
}
//TODO
int gets(char* str, size_t max);
protected:
InputBuffer(char* buffer, uint8_t size): Queue<char>(buffer, size) {}
// Listeners of events on the buffer
virtual void on_empty() {}
virtual void on_get(__attribute__((unused)) char c) {}
};
class FormatBase
{
public:
enum class Base: uint8_t
{
// bcd = 0,
bin = 2,
oct = 8,
dec = 10,
hex = 16
};
FormatBase(): _width(6), _precision(4), _base(Base::dec) {}
inline void width(int8_t width)
{
_width = width;
}
inline int8_t width()
{
return _width;
}
inline void precision(int8_t precision)
{
_precision = precision;
}
inline int8_t precision()
{
return _precision;
}
inline void base(Base base)
{
_base = base;
}
inline Base base()
{
return _base;
}
protected:
//TODO inverted conversions (from string to value)
const char* convert(int v)
{
char s[8 * sizeof(int) + 1];
return itoa(v, s, (uint8_t) _base);
}
const char* convert(unsigned int v)
{
char s[8 * sizeof(int) + 1];
return utoa(v, s, (uint8_t) _base);
}
const char* convert(long v)
{
char s[8 * sizeof(long) + 1];
return ltoa(v, s, (uint8_t) _base);
}
const char* convert(unsigned long v)
{
char s[8 * sizeof(long) + 1];
return ultoa(v, s, (uint8_t) _base);
}
const char* convert(double v)
{
char s[MAX_BUF_LEN];
return dtostrf(v, _width, _precision, s);
}
private:
static const uint8_t MAX_BUF_LEN = 64;
int8_t _width;
uint8_t _precision;
Base _base;
};
template<typename STREAM>
class FormattedOutput: public FormatBase
{
public:
FormattedOutput(STREAM& stream): _stream(stream) {}
void flush()
{
_stream.flush();
}
void put(char c, bool flush = true)
{
_stream.put(c, flush);
}
void put(const char* content, size_t size)
{
_stream.put(content, size);
}
void puts(const char* str)
{
_stream.puts(str);
}
//TODO Handle PROGMEM strings output
// void puts_P();
//TODO others? eg void*, PSTR, Manipulator...
FormattedOutput<STREAM>& operator << (const char* s)
{
_stream.puts(s);
return *this;
}
FormattedOutput<STREAM>& operator << (int v)
{
_stream.puts(convert(v));
return *this;
}
FormattedOutput<STREAM>& operator << (unsigned int v)
{
_stream.puts(convert(v));
return *this;
}
FormattedOutput<STREAM>& operator << (long v)
{
_stream.puts(convert(v));
return *this;
}
FormattedOutput<STREAM>& operator << (unsigned long v)
{
_stream.puts(convert(v));
return *this;
}
FormattedOutput<STREAM>& operator << (double v)
{
_stream.puts(convert(v));
return *this;
}
typedef FormattedOutput<STREAM>& (*Manipulator)(FormattedOutput<STREAM>&);
FormattedOutput<STREAM>& operator << (Manipulator f)
{
return f(*this);
}
private:
STREAM& _stream;
template<typename FSTREAM> friend FSTREAM& bin(FSTREAM&);
template<typename FSTREAM> friend FSTREAM& oct(FSTREAM&);
template<typename FSTREAM> friend FSTREAM& dec(FSTREAM&);
template<typename FSTREAM> friend FSTREAM& hex(FSTREAM&);
//TODO other parameters here
template<typename FSTREAM> friend FSTREAM& flush(FSTREAM&);
template<typename FSTREAM> friend FSTREAM& endl(FSTREAM&);
};
template<typename STREAM>
class FormattedInput: public FormatBase
{
public:
FormattedInput(STREAM& stream): _stream(stream) {}
int available() const
{
return _stream.available();
}
int get()
{
return _stream.get();
}
int gets(char* str, size_t max)
{
return _stream.gets(str, max);
}
//TODO others? eg void*, PSTR, Manipulator...
FormattedInput<STREAM>& operator >> (char* s)
{
//TODO look for next token (until space)
return *this;
}
FormattedInput<STREAM>& operator >> (int& v)
{
return *this;
}
FormattedInput<STREAM>& operator >> (unsigned int& v)
{
return *this;
}
FormattedInput<STREAM>& operator >> (long& v)
{
return *this;
}
FormattedInput<STREAM>& operator >> (unsigned long& v)
{
return *this;
}
FormattedInput<STREAM>& operator >> (double& v)
{
return *this;
}
typedef FormattedInput<STREAM>& (*Manipulator)(FormattedInput<STREAM>&);
FormattedInput<STREAM>& operator >> (Manipulator f)
{
return f(*this);
}
private:
STREAM& _stream;
friend FormattedInput<STREAM>& bin(FormattedInput<STREAM>&);
friend FormattedInput<STREAM>& oct(FormattedInput<STREAM>&);
friend FormattedInput<STREAM>& dec(FormattedInput<STREAM>&);
friend FormattedInput<STREAM>& hex(FormattedInput<STREAM>&);
//TODO other parameters here
friend FormattedInput<STREAM>& flush(FormattedInput<STREAM>&);
friend FormattedInput<STREAM>& endl(FormattedInput<STREAM>&);
};
template<typename FSTREAM>
inline FSTREAM& bin(FSTREAM& stream)
{
stream.base(FormatBase::Base::bin);
return stream;
}
template<typename FSTREAM>
inline FSTREAM& oct(FSTREAM& stream)
{
stream.base(FormatBase::Base::oct);
return stream;
}
template<typename FSTREAM>
inline FSTREAM& dec(FSTREAM& stream)
{
stream.base(FormatBase::Base::dec);
return stream;
}
template<typename FSTREAM>
inline FSTREAM& hex(FSTREAM& stream)
{
stream.base(FormatBase::Base::hex);
return stream;
}
template<typename FSTREAM>
inline FSTREAM& flush(FSTREAM& stream)
{
stream.flush();
return stream;
}
template<typename FSTREAM>
inline FSTREAM& endl(FSTREAM& stream)
{
stream.put('\n');
return stream;
}
#endif /* STREAMS_HH */
<|endoftext|> |
<commit_before>/** \file control_number_filter.cc
* \brief A tool for filtering MARC-21 data sets based on patterns for control numbers.
* \author Dr. Johannes Ruscheinski
*/
/*
Copyright (C) 2015-2017, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <memory>
#include <cstdlib>
#include <cstring>
#include "MarcReader.h"
#include "MarcRecord.h"
#include "MarcWriter.h"
#include "RegexMatcher.h"
#include "util.h"
void Usage() {
std::cerr << "Usage: " << ::progname << "(--keep|--delete)] pattern marc_input marc_output\n";
std::cerr << " Removes records whose control numbers match \"pattern\" if \"--delete\" has been specified\n";
std::cerr << " or only keeps those records whose control numbers match \"pattern\" if \"--keep\" has\n";
std::cerr << " been specified. (\"pattern\" must be a PCRE.)\n";
std::exit(EXIT_FAILURE);
}
void FilterMarcRecords(const bool keep, const std::string ®ex_pattern, MarcReader * const marc_reader,
MarcWriter * const marc_writer)
{
std::string err_msg;
RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactory(regex_pattern, &err_msg));
if (matcher == nullptr)
logger->error("Failed to compile pattern \"" + regex_pattern + "\": " + err_msg);
unsigned count(0), kept_or_deleted_count(0);
while (MarcRecord record = marc_reader->read()) {
++count;
const bool matched(matcher->matched(record.getControlNumber(), &err_msg));
if (not err_msg.empty())
logger->error("regex matching error: " + err_msg);
if ((keep and matched) or (not keep and not matched)) {
++kept_or_deleted_count;
marc_writer->write(record);
}
}
if (not err_msg.empty())
logger->error(err_msg);
std::cerr << "Read " << count << " records.\n";
std::cerr << (keep ? "Kept " : "Deleted ") << kept_or_deleted_count << " record(s).\n";
}
int main(int argc, char **argv) {
::progname = argv[0];
if (argc != 5)
Usage();
if (std::strcmp(argv[1], "--keep") != 0 and std::strcmp(argv[1], "--delete") != 0)
Usage();
const bool keep(std::strcmp(argv[1], "--keep") == 0);
const std::string regex_pattern(argv[2]);
const std::string marc_input_filename(argv[3]);
const std::string marc_output_filename(argv[4]);
if (unlikely(marc_input_filename == marc_output_filename))
logger->error("Master input file name equals output file name!");
std::unique_ptr<MarcReader> marc_reader(MarcReader::Factory(marc_input_filename, MarcReader::BINARY));
std::unique_ptr<MarcWriter> marc_writer(MarcWriter::Factory(marc_output_filename, MarcWriter::BINARY));
FilterMarcRecords(keep, regex_pattern, marc_reader.get(), marc_writer.get());
}
<commit_msg>New API: control_number_filter<commit_after>/** \file control_number_filter.cc
* \brief A tool for filtering MARC-21 data sets based on patterns for control numbers.
* \author Dr. Johannes Ruscheinski
*/
/*
Copyright (C) 2015-2017, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <memory>
#include <cstdlib>
#include <cstring>
#include "MARC.h"
#include "RegexMatcher.h"
#include "util.h"
namespace {
[[noreturn]] void Usage() {
std::cerr << "Usage: " << ::progname << "(--keep|--delete)] pattern marc_input marc_output\n";
std::cerr << " Removes records whose control numbers match \"pattern\" if \"--delete\" has been specified\n";
std::cerr << " or only keeps those records whose control numbers match \"pattern\" if \"--keep\" has\n";
std::cerr << " been specified. (\"pattern\" must be a PCRE.)\n";
std::exit(EXIT_FAILURE);
}
void FilterMarcRecords(const bool keep, const std::string ®ex_pattern, MARC::Reader * const marc_reader,
MARC::Writer * const marc_writer)
{
std::string err_msg;
RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactory(regex_pattern, &err_msg));
if (matcher == nullptr)
LOG_ERROR("Failed to compile pattern \"" + regex_pattern + "\": " + err_msg);
unsigned count(0), kept_or_deleted_count(0);
while (MARC::Record record = marc_reader->read()) {
++count;
const bool matched(matcher->matched(record.getControlNumber(), &err_msg));
if (not err_msg.empty())
LOG_ERROR("regex matching error: " + err_msg);
if ((keep and matched) or (not keep and not matched)) {
++kept_or_deleted_count;
marc_writer->write(record);
}
}
if (not err_msg.empty())
LOG_ERROR(err_msg);
std::cerr << "Read " << count << " records.\n";
std::cerr << (keep ? "Kept " : "Deleted ") << kept_or_deleted_count << " record(s).\n";
}
} // unnamed namespace
int Main(int argc, char **argv) {
if (argc != 5)
Usage();
if (std::strcmp(argv[1], "--keep") != 0 and std::strcmp(argv[1], "--delete") != 0)
Usage();
const bool keep(std::strcmp(argv[1], "--keep") == 0);
const std::string regex_pattern(argv[2]);
const std::string marc_input_filename(argv[3]);
const std::string marc_output_filename(argv[4]);
if (unlikely(marc_input_filename == marc_output_filename))
LOG_ERROR("Master input file name equals output file name!");
auto marc_reader(MARC::Reader::Factory(marc_input_filename));
auto marc_writer(MARC::Writer::Factory(marc_output_filename));
FilterMarcRecords(keep, regex_pattern, marc_reader.get(), marc_writer.get());
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <glut.h>
int stage=1;//시작화면, 게임화면, 종료화면으로 나눔
int board[3][3]; // board for gameplay
int turn; // current move
int result; // Result of the game
bool over; // Is the game Over?
/*
Sets the board for Tic Tac Toe
*/
void Intialize()
{
turn=1;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
board[i][j]=0;
}
}
void start(int x,int y) //시작버튼
{
glColor3f(0,0,0);
glBegin(GL_LINES);
glVertex2f(10,20);
glVertex2f(60,20);
glVertex2f(10,20);
glVertex2f(10,90);
glVertex2f(10,90);
glVertex2f(60,90);
glVertex2f(60,90);
glVertex2f(60,160);
glVertex2f(60,160);
glVertex2f(10,160);
glEnd();
glBegin(GL_LINES);
glVertex2f(70,20);
glVertex2f(120,20);
glVertex2f(95,20);
glVertex2f(95,160);
glEnd();
glBegin(GL_LINES);
glVertex2f(130,20);
glVertex2f(130,160);
glVertex2f(130,20);
glVertex2f(175,20);
glVertex2f(175,20);
glVertex2f(175,160);
glVertex2f(130,90);
glVertex2f(175,90);
glEnd();
glBegin(GL_LINES);
glVertex2f(185,20);
glVertex2f(185,160);
glVertex2f(185,20);
glVertex2f(230,20);
glVertex2f(185,90);
glVertex2f(230,90);
glVertex2f(230,20);
glVertex2f(230,90);
glVertex2f(185,90);
glVertex2f(230,160);
glEnd();
glBegin(GL_LINES);
glVertex2f(240,20);
glVertex2f(290,20);
glVertex2f(265,20);
glVertex2f(265,160);
glEnd();
}
void select(int x,int y,int r) //말 선택 메뉴
{
glBegin(GL_LINES);
glColor3f(0,0,0);
glVertex2f(10,340);
glVertex2f(10,190);
glVertex2f(10,190);
glVertex2f(140,190);
glVertex2f(140,190);
glVertex2f(140,340);
glVertex2f(140,340);
glVertex2f(10,340);
glEnd();
}
void rule(int x,int y) //규칙 설명 메뉴
{
glBegin(GL_LINES);
glColor3f(0,0,0);
glVertex2f(160,340);
glVertex2f(160,190);
glVertex2f(160,190);
glVertex2f(290,190);
glVertex2f(290,190);
glVertex2f(290,340);
glVertex2f(290,340);
glVertex2f(160,340);
glEnd();
}
/*
Called when any key from keyboard is pressed
*/
void OnKeyPress(unsigned char key,int x,int y)
{
switch(key)
{
case 'y':
if(over==true)
{
over=false;
Intialize();
stage=2;
}
break;
case 'n':
if(over==true)
{
exit(0);
}
break;
default:
exit(0);
}
}
/*
Called when Mouse is clicked
*/
void OnMouseClick(int button,int state,int x,int y)
{
if(stage==1)
{
if(button==GLUT_LEFT_BUTTON && state==GLUT_DOWN && x>10 && x<290 && y>20 && y<160)
{
stage=2;
glutPostRedisplay();
}
}
else if(stage==2)
{
if(over==false && button==GLUT_LEFT_BUTTON && state==GLUT_DOWN)
{
if(turn==1)
{
if(board[(y-50)/100][x/100]==0)
{
board[(y-50)/100][x/100]=1;
turn=2;
}
}
else if(turn==2)
{
if(board[(y-50)/100][x/100]==0)
{
board[(y-50)/100][x/100]=2;
turn=1;
}
}
}
}
else if(stage==3)
{
}
}
/*
Utility function to draw string
*/
void DrawString(void *font,const char s[],float x,float y)
{
unsigned int i;
glRasterPos2f(x,y);
for(i=0;i<strlen(s);i++)
{
glutBitmapCharacter(font,s[i]);
}
}
/*
Function to draw up the horizontal and vertical lines
*/
void DrawLines()
{
glBegin(GL_LINES);
glColor3f(0,0,0);
glVertex2f(100,50);
glVertex2f(100,340);
glVertex2f(200,340);
glVertex2f(200,50);
glVertex2f(0,150);
glVertex2f(300,150);
glVertex2f(0,250);
glVertex2f(300,250);
glEnd();
}
/*
Utility function to draw the circle
*/
void DrawCircle(float cx, float cy, float r, int num_segments)
{
glBegin(GL_LINE_LOOP);
for (int i = 0; i < num_segments; i++)
{
float theta = 2.0f * 3.1415926f * float(i) / float(num_segments);//get the current angle
float x = r * cosf(theta);//calculate the x component
float y = r * sinf(theta);//calculate the y component
glVertex2f(x + cx, y + cy);//output vertex
}
glEnd();
}
/*
Function to draw the cross and circle of Tic Tac Toe
*/
void DrawXO()
{
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(board[i][j]==1)
{
glBegin(GL_LINES);
glVertex2f(50 + j * 100 - 25, 100 + i * 100 - 25);
glVertex2f(50 + j * 100 + 25, 100 + i * 100 + 25);
glVertex2f(50 + j * 100 - 25, 100 + i * 100 + 25);
glVertex2f(50 + j * 100 + 25, 100 + i * 100 - 25);
glEnd();
}
else if(board[i][j]==2)
{
DrawCircle(50 + j*100 , 100 + i*100 , 25 , 15);
}
}
}
}
/*
Function to check if there is any winner
*/
bool CheckWinner()
{
int i, j;
// horizontal check
for(i=0;i<3;i++)
{
for(j=1;j<3;j++)
{
if(board[i][0]!=0 && board[i][0]==board[i][j])
{
if(j==2)
{
return true;
}
}
else
break;
}
}
// vertical check
for(i=0;i<3;i++)
{
for(j=1;j<3;j++)
{
if(board[0][i]!=0 && board[0][i]==board[j][i])
{
if(j==2)
return true;
}
else
break;
}
}
// Diagonal check
if((board[0][0]!=0 && board[0][0]==board[1][1] && board[0][0]==board[2][2])
|| (board[2][0]!=0 && board[2][0]==board[1][1] && board[2][0]==board[0][2]))
return true;
return false;
}
/*
function to check if there is draw
*/
bool CheckIfDraw()
{
int i, j;
bool draw;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(board[i][j]==0)
return false;
}
}
return true;
}
/*
Function to display up everything
*/
void Display()
{
if(stage==1)
{
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(1,1,1,1);
select(0,0,0);
rule(0,0);
start(0,0);
}
else if(stage==2)
{
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(1, 1, 1, 1);
glColor3f(0, 0, 0);
if(turn == 1)
DrawString(GLUT_BITMAP_HELVETICA_18, "Player1's turn", 100, 30);
else
DrawString(GLUT_BITMAP_HELVETICA_18, "Player2's turn", 100, 30);
DrawLines();
DrawXO();
if(CheckWinner() == true)
{
if(turn == 1)
{
over = true;
result = 2;
}
else
{
over = true;
result = 1;
}
}
else if(CheckIfDraw() == true)
{
over = true;
result = 0;
}
if(over == true)
{
stage=3;
}
}
else if(stage==3)
{
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(1,1,1,1);
DrawString(GLUT_BITMAP_HELVETICA_18, "Game Over", 100, 160);
if(result == 0)
DrawString(GLUT_BITMAP_HELVETICA_18, "It's a draw", 110, 185);
if(result == 1)
DrawString(GLUT_BITMAP_HELVETICA_18, "Player1 wins", 95, 185);
if(result == 2)
DrawString(GLUT_BITMAP_HELVETICA_18, "Player2 wins", 95, 185);
DrawString(GLUT_BITMAP_HELVETICA_18, "Do you want to continue (y/n)", 40, 210);
}
glutSwapBuffers();
}
/*
Function to reshape
*/
void Reshape(int x, int y)
{
glViewport(0, 0, x, y);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, x, y, 0, 0, 1);
glMatrixMode(GL_MODELVIEW);
}
/*
Driver Function
*/
int main(int argc, char **argv)
{
Intialize();
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE);
glutInitWindowPosition(550,200);
glutInitWindowSize(300,350);
glutCreateWindow("Tic Tac Toe");
glutReshapeFunc(Reshape);
glutDisplayFunc(Display);
glutKeyboardFunc(OnKeyPress);
glutMouseFunc(OnMouseClick);
glutIdleFunc(Display);
glutMainLoop();
return 0;
}
<commit_msg>주석달기-1<commit_after>#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <glut.h>
int stage=1;// 시작화면(1), 게임화면(2), 종료화면(3)으로 나눔, 첫 화면은 시작화면이므로 1로 초기화
int board[3][3]; // 게임 보드판
int turn; // 현재의 턴(player1 or player2)
int result; // 게임의 결과
bool over; // 게임 종료 여부
/*
보드판을 초기화 함
*/
void Intialize()
{
turn=1;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
board[i][j]=0;
}
}
/*
START 버튼으로 누르면 게임이 시작되도록 함
*/
void start(int x,int y)
{
glColor3f(0,0,0);
glBegin(GL_LINES);
glVertex2f(10,20);
glVertex2f(60,20);
glVertex2f(10,20);
glVertex2f(10,90);
glVertex2f(10,90);
glVertex2f(60,90);
glVertex2f(60,90);
glVertex2f(60,160);
glVertex2f(60,160);
glVertex2f(10,160);
glEnd();
glBegin(GL_LINES);
glVertex2f(70,20);
glVertex2f(120,20);
glVertex2f(95,20);
glVertex2f(95,160);
glEnd();
glBegin(GL_LINES);
glVertex2f(130,20);
glVertex2f(130,160);
glVertex2f(130,20);
glVertex2f(175,20);
glVertex2f(175,20);
glVertex2f(175,160);
glVertex2f(130,90);
glVertex2f(175,90);
glEnd();
glBegin(GL_LINES);
glVertex2f(185,20);
glVertex2f(185,160);
glVertex2f(185,20);
glVertex2f(230,20);
glVertex2f(185,90);
glVertex2f(230,90);
glVertex2f(230,20);
glVertex2f(230,90);
glVertex2f(185,90);
glVertex2f(230,160);
glEnd();
glBegin(GL_LINES);
glVertex2f(240,20);
glVertex2f(290,20);
glVertex2f(265,20);
glVertex2f(265,160);
glEnd();
}
/*
말선택 메뉴 부분 자리를 만들어 놓음
*/
void select(int x,int y,int r)
{
glBegin(GL_LINES);
glColor3f(0,0,0);
glVertex2f(10,340);
glVertex2f(10,190);
glVertex2f(10,190);
glVertex2f(140,190);
glVertex2f(140,190);
glVertex2f(140,340);
glVertex2f(140,340);
glVertex2f(10,340);
glEnd();
}
/*
규칙설명 메뉴 부분 자리를 만들어 놓음
*/
void rule(int x,int y)
{
glBegin(GL_LINES);
glColor3f(0,0,0);
glVertex2f(160,340);
glVertex2f(160,190);
glVertex2f(160,190);
glVertex2f(290,190);
glVertex2f(290,190);
glVertex2f(290,340);
glVertex2f(290,340);
glVertex2f(160,340);
glEnd();
}
/*
키보드함수 : y를 누르면 게임 다시 시작, n을 누르면 게임 종료, 다른 버튼 누르면 게임 종료
*/
void OnKeyPress(unsigned char key,int x,int y)
{
switch(key)
{
case 'y':
if(over==true)
{
over=false;
Intialize();
stage=2;
}
break;
case 'n':
if(over==true)
{
exit(0);
}
break;
default:
exit(0);
}
}
/*
마우스함수 : stage가 1일때 start버튼을 누르면 게임 시작으로 stage가 2로 넘어감
stage가 2일때 player가 누른 자리에 아무 말도 놓여 있지 않을때 자신의 말을 놓고 turn을 넘겨줌
*/
void OnMouseClick(int button,int state,int x,int y)
{
if(stage==1)
{
if(button==GLUT_LEFT_BUTTON && state==GLUT_DOWN && x>10 && x<290 && y>20 && y<160)
{
stage=2;
glutPostRedisplay();
}
}
else if(stage==2)
{
if(over==false && button==GLUT_LEFT_BUTTON && state==GLUT_DOWN)
{
if(turn==1)
{
if(board[(y-50)/100][x/100]==0)
{
board[(y-50)/100][x/100]=1;
turn=2;
}
}
else if(turn==2)
{
if(board[(y-50)/100][x/100]==0)
{
board[(y-50)/100][x/100]=2;
turn=1;
}
}
}
}
}
/*
누구의 순서인지 알려주거나 누가 이겼는지 알려줌
*/
void DrawString(void *font,const char s[],float x,float y)
{
unsigned int i;
glRasterPos2f(x,y);
for(i=0;i<strlen(s);i++)
{
glutBitmapCharacter(font,s[i]);
}
}
/*
보드판 선을 그림
*/
void DrawLines()
{
glBegin(GL_LINES);
glColor3f(0,0,0);
glVertex2f(100,50);
glVertex2f(100,340);
glVertex2f(200,340);
glVertex2f(200,50);
glVertex2f(0,150);
glVertex2f(300,150);
glVertex2f(0,250);
glVertex2f(300,250);
glEnd();
}
/*
Player2 말 모양인 O를
*/
void DrawCircle(float cx, float cy, float r, int num_segments)
{
glBegin(GL_LINE_LOOP);
for (int i = 0; i < num_segments; i++)
{
float theta = 2.0f * 3.1415926f * float(i) / float(num_segments);//get the current angle
float x = r * cosf(theta);//calculate the x component
float y = r * sinf(theta);//calculate the y component
glVertex2f(x + cx, y + cy);//output vertex
}
glEnd();
}
/*
Function to draw the cross and circle of Tic Tac Toe
*/
void DrawXO()
{
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(board[i][j]==1)
{
glBegin(GL_LINES);
glVertex2f(50 + j * 100 - 25, 100 + i * 100 - 25);
glVertex2f(50 + j * 100 + 25, 100 + i * 100 + 25);
glVertex2f(50 + j * 100 - 25, 100 + i * 100 + 25);
glVertex2f(50 + j * 100 + 25, 100 + i * 100 - 25);
glEnd();
}
else if(board[i][j]==2)
{
DrawCircle(50 + j*100 , 100 + i*100 , 25 , 15);
}
}
}
}
/*
Function to check if there is any winner
*/
bool CheckWinner()
{
int i, j;
// horizontal check
for(i=0;i<3;i++)
{
for(j=1;j<3;j++)
{
if(board[i][0]!=0 && board[i][0]==board[i][j])
{
if(j==2)
{
return true;
}
}
else
break;
}
}
// vertical check
for(i=0;i<3;i++)
{
for(j=1;j<3;j++)
{
if(board[0][i]!=0 && board[0][i]==board[j][i])
{
if(j==2)
return true;
}
else
break;
}
}
// Diagonal check
if((board[0][0]!=0 && board[0][0]==board[1][1] && board[0][0]==board[2][2])
|| (board[2][0]!=0 && board[2][0]==board[1][1] && board[2][0]==board[0][2]))
return true;
return false;
}
/*
function to check if there is draw
*/
bool CheckIfDraw()
{
int i, j;
bool draw;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(board[i][j]==0)
return false;
}
}
return true;
}
/*
Function to display up everything
*/
void Display()
{
if(stage==1)
{
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(1,1,1,1);
select(0,0,0);
rule(0,0);
start(0,0);
}
else if(stage==2)
{
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(1, 1, 1, 1);
glColor3f(0, 0, 0);
if(turn == 1)
DrawString(GLUT_BITMAP_HELVETICA_18, "Player1's turn", 100, 30);
else
DrawString(GLUT_BITMAP_HELVETICA_18, "Player2's turn", 100, 30);
DrawLines();
DrawXO();
if(CheckWinner() == true)
{
if(turn == 1)
{
over = true;
result = 2;
}
else
{
over = true;
result = 1;
}
}
else if(CheckIfDraw() == true)
{
over = true;
result = 0;
}
if(over == true)
{
stage=3;
}
}
else if(stage==3)
{
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(1,1,1,1);
DrawString(GLUT_BITMAP_HELVETICA_18, "Game Over", 100, 160);
if(result == 0)
DrawString(GLUT_BITMAP_HELVETICA_18, "It's a draw", 110, 185);
if(result == 1)
DrawString(GLUT_BITMAP_HELVETICA_18, "Player1 wins", 95, 185);
if(result == 2)
DrawString(GLUT_BITMAP_HELVETICA_18, "Player2 wins", 95, 185);
DrawString(GLUT_BITMAP_HELVETICA_18, "Do you want to continue (y/n)", 40, 210);
}
glutSwapBuffers();
}
/*
Function to reshape
*/
void Reshape(int x, int y)
{
glViewport(0, 0, x, y);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, x, y, 0, 0, 1);
glMatrixMode(GL_MODELVIEW);
}
/*
Driver Function
*/
int main(int argc, char **argv)
{
Intialize();
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE);
glutInitWindowPosition(550,200);
glutInitWindowSize(300,350);
glutCreateWindow("Tic Tac Toe");
glutReshapeFunc(Reshape);
glutDisplayFunc(Display);
glutKeyboardFunc(OnKeyPress);
glutMouseFunc(OnMouseClick);
glutIdleFunc(Display);
glutMainLoop();
return 0;
}
<|endoftext|> |
<commit_before>//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// TObject to hold V0 configuration + results histogram
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#include "TList.h"
#include "TH3F.h"
#include "AliV0Result.h"
#include <iostream>
#include <TROOT.h>
using namespace std;
ClassImp(AliV0Result);
//________________________________________________________________
AliV0Result::AliV0Result() :
TNamed(),
fMassHypo(AliV0Result::kK0Short),
fCutV0Radius(5.0),
fCutDCANegToPV(0.1),
fCutDCAPosToPV(0.1),
fCutDCAV0Daughters(1.0),
fCutV0CosPA(0.998),
fCutProperLifetime(10),
fCutLeastNumberOfCrossedRows(70),
fCutLeastNumberOfCrossedRowsOverFindable(0.8),
fCutCompetingV0Rejection(-1),
fCutArmenteros(kTRUE),
fCutTPCdEdx(3.0)
{
// Dummy Constructor - not to be used!
//Main output histogram: Centrality, mass, transverse momentum
fHisto = new TH3F("fHisto","", 20,0,100, 200,0,2, 100,0,10);
}
//________________________________________________________________
AliV0Result::AliV0Result(const char * name, AliV0Result::EMassHypo lMassHypo, const char * title):
TNamed(name,title),
fMassHypo(lMassHypo),
fCutV0Radius(5.0),
fCutDCANegToPV(0.1),
fCutDCAPosToPV(0.1),
fCutDCAV0Daughters(1.0),
fCutV0CosPA(0.998),
fCutProperLifetime(10),
fCutLeastNumberOfCrossedRows(70),
fCutLeastNumberOfCrossedRowsOverFindable(0.8),
fCutCompetingV0Rejection(-1),
fCutArmenteros(kTRUE),
fCutTPCdEdx(3.0)
{
// Constructor
Double_t lThisMass = 0;
if( lMassHypo == AliV0Result::kK0Short ) lThisMass = 0.497;
if( lMassHypo == AliV0Result::kLambda ) lThisMass = 1.116;
if( lMassHypo == AliV0Result::kAntiLambda ) lThisMass = 1.116;
//Main output histogram: Centrality, mass, transverse momentum
fHisto = new TH3F(Form("fHisto_%s",this->GetName()),"", 20,0,100, 200,lThisMass-0.1,lThisMass+0.1, 100,0,10);
}
//________________________________________________________________
AliV0Result::AliV0Result(const AliV0Result& lCopyMe)
: TNamed(lCopyMe),
fMassHypo(lCopyMe.fMassHypo),
fCutV0Radius(lCopyMe.fCutV0Radius),
fCutDCANegToPV(lCopyMe.fCutDCANegToPV),
fCutDCAPosToPV(lCopyMe.fCutDCAPosToPV),
fCutDCAV0Daughters(lCopyMe.fCutDCAV0Daughters),
fCutV0CosPA(lCopyMe.fCutV0CosPA),
fCutProperLifetime(lCopyMe.fCutProperLifetime),
fCutLeastNumberOfCrossedRows(lCopyMe.fCutLeastNumberOfCrossedRows),
fCutLeastNumberOfCrossedRowsOverFindable(lCopyMe.fCutLeastNumberOfCrossedRowsOverFindable),
fCutCompetingV0Rejection(lCopyMe.fCutCompetingV0Rejection),
fCutArmenteros(lCopyMe.fCutArmenteros),
fCutTPCdEdx(lCopyMe.fCutTPCdEdx)
{
// Constructor
Double_t lThisMass = 0;
if( fMassHypo == AliV0Result::kK0Short ) lThisMass = 0.497;
if( fMassHypo == AliV0Result::kLambda ) lThisMass = 1.116;
if( fMassHypo == AliV0Result::kAntiLambda ) lThisMass = 1.116;
//Main output histogram: Centrality, mass, transverse momentum
fHisto = new TH3F("fHisto","", 20,0,100, 200,lThisMass-0.1,lThisMass+0.1, 100,0,10);
}
//________________________________________________________________
AliV0Result::AliV0Result(AliV0Result *lCopyMe)
: TNamed(*lCopyMe),
fHisto(0)
{
fMassHypo = lCopyMe->GetMassHypothesis();
fCutV0Radius = lCopyMe->GetCutV0Radius();
fCutDCANegToPV = lCopyMe->GetCutDCANegToPV();
fCutDCAPosToPV = lCopyMe->GetCutDCAPosToPV(),
fCutDCAV0Daughters = lCopyMe->GetCutDCAV0Daughters(),
fCutV0CosPA = lCopyMe->GetCutV0CosPA(),
fCutProperLifetime = lCopyMe->GetCutProperLifetime(),
fCutLeastNumberOfCrossedRows = lCopyMe->GetCutLeastNumberOfCrossedRows(),
fCutLeastNumberOfCrossedRowsOverFindable = lCopyMe->GetCutLeastNumberOfCrossedRowsOverFindable(),
fCutCompetingV0Rejection = lCopyMe->GetCutCompetingV0Rejection(),
fCutArmenteros = lCopyMe->GetCutArmenteros();
fCutTPCdEdx = lCopyMe->GetCutTPCdEdx();
// Constructor
Double_t lThisMass = 0;
if( fMassHypo == AliV0Result::kK0Short ) lThisMass = 0.497;
if( fMassHypo == AliV0Result::kLambda ) lThisMass = 1.116;
if( fMassHypo == AliV0Result::kAntiLambda ) lThisMass = 1.116;
//Main output histogram: Centrality, mass, transverse momentum
fHisto = new TH3F("fHisto","", 20,0,100, 200,lThisMass-0.1,lThisMass+0.1, 100,0,10);
}
//________________________________________________________________
AliV0Result::~AliV0Result(){
// destructor: clean stuff up
// Actual deletion of the objects causes corruption of event object
// - no idea why - on Proof(Lite). Hence it is disabled here.
//
//delete fEstimatorList;
//fEstimatorList=0x0;
}
//________________________________________________________________
AliV0Result& AliV0Result::operator=(const AliV0Result& lCopyMe)
{
if (&lCopyMe == this) return *this;
SetName(lCopyMe.GetName());
SetTitle(lCopyMe.GetTitle());
fMassHypo = lCopyMe.GetMassHypothesis();
fCutV0Radius = lCopyMe.GetCutV0Radius();
fCutDCANegToPV = lCopyMe.GetCutDCANegToPV();
fCutDCAPosToPV = lCopyMe.GetCutDCAPosToPV(),
fCutDCAV0Daughters = lCopyMe.GetCutDCAV0Daughters(),
fCutV0CosPA = lCopyMe.GetCutV0CosPA(),
fCutProperLifetime = lCopyMe.GetCutProperLifetime(),
fCutLeastNumberOfCrossedRows = lCopyMe.GetCutLeastNumberOfCrossedRows(),
fCutLeastNumberOfCrossedRowsOverFindable = lCopyMe.GetCutLeastNumberOfCrossedRowsOverFindable(),
fCutCompetingV0Rejection = lCopyMe.GetCutCompetingV0Rejection(),
fCutArmenteros = lCopyMe.GetCutArmenteros();
fCutTPCdEdx = lCopyMe.GetCutTPCdEdx();
if (fHisto) {
delete fHisto;
fHisto = 0;
}
// Constructor
Double_t lThisMass = 0;
if( fMassHypo == AliV0Result::kK0Short ) lThisMass = 0.497;
if( fMassHypo == AliV0Result::kLambda ) lThisMass = 1.116;
if( fMassHypo == AliV0Result::kAntiLambda ) lThisMass = 1.116;
//Main output histogram: Centrality, mass, transverse momentum
fHisto = new TH3F("fHisto","", 20,0,100, 200,lThisMass-0.1,lThisMass+0.1, 100,0,10);
return *this;
}<commit_msg>Adjusting constructors and histogram naming<commit_after>//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// TObject to hold V0 configuration + results histogram
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#include "TList.h"
#include "TH3F.h"
#include "AliV0Result.h"
#include <iostream>
#include <TROOT.h>
using namespace std;
ClassImp(AliV0Result);
//________________________________________________________________
AliV0Result::AliV0Result() :
TNamed(),
fMassHypo(AliV0Result::kK0Short),
fCutV0Radius(5.0),
fCutDCANegToPV(0.1),
fCutDCAPosToPV(0.1),
fCutDCAV0Daughters(1.0),
fCutV0CosPA(0.998),
fCutProperLifetime(10),
fCutLeastNumberOfCrossedRows(70),
fCutLeastNumberOfCrossedRowsOverFindable(0.8),
fCutCompetingV0Rejection(-1),
fCutArmenteros(kTRUE),
fCutTPCdEdx(3.0)
{
// Dummy Constructor - not to be used!
//Main output histogram: Centrality, mass, transverse momentum
fHisto = new TH3F("fHisto","", 20,0,100, 200,0,2, 100,0,10);
}
//________________________________________________________________
AliV0Result::AliV0Result(const char * name, AliV0Result::EMassHypo lMassHypo, const char * title):
TNamed(name,title),
fMassHypo(lMassHypo),
fCutV0Radius(5.0),
fCutDCANegToPV(0.1),
fCutDCAPosToPV(0.1),
fCutDCAV0Daughters(1.0),
fCutV0CosPA(0.998),
fCutProperLifetime(10),
fCutLeastNumberOfCrossedRows(70),
fCutLeastNumberOfCrossedRowsOverFindable(0.8),
fCutCompetingV0Rejection(-1),
fCutArmenteros(kTRUE),
fCutTPCdEdx(3.0)
{
// Constructor
Double_t lThisMass = 0;
if( lMassHypo == AliV0Result::kK0Short ) lThisMass = 0.497;
if( lMassHypo == AliV0Result::kLambda ) lThisMass = 1.116;
if( lMassHypo == AliV0Result::kAntiLambda ) lThisMass = 1.116;
//Main output histogram: Centrality, mass, transverse momentum
fHisto = new TH3F(Form("fHisto_%s",GetName()),"", 20,0,100, 200,lThisMass-0.1,lThisMass+0.1, 100,0,10);
}
//________________________________________________________________
AliV0Result::AliV0Result(const AliV0Result& lCopyMe)
: TNamed(lCopyMe),
fMassHypo(lCopyMe.fMassHypo),
fCutV0Radius(lCopyMe.fCutV0Radius),
fCutDCANegToPV(lCopyMe.fCutDCANegToPV),
fCutDCAPosToPV(lCopyMe.fCutDCAPosToPV),
fCutDCAV0Daughters(lCopyMe.fCutDCAV0Daughters),
fCutV0CosPA(lCopyMe.fCutV0CosPA),
fCutProperLifetime(lCopyMe.fCutProperLifetime),
fCutLeastNumberOfCrossedRows(lCopyMe.fCutLeastNumberOfCrossedRows),
fCutLeastNumberOfCrossedRowsOverFindable(lCopyMe.fCutLeastNumberOfCrossedRowsOverFindable),
fCutCompetingV0Rejection(lCopyMe.fCutCompetingV0Rejection),
fCutArmenteros(lCopyMe.fCutArmenteros),
fCutTPCdEdx(lCopyMe.fCutTPCdEdx)
{
// Constructor
Double_t lThisMass = 0;
if( fMassHypo == AliV0Result::kK0Short ) lThisMass = 0.497;
if( fMassHypo == AliV0Result::kLambda ) lThisMass = 1.116;
if( fMassHypo == AliV0Result::kAntiLambda ) lThisMass = 1.116;
//Main output histogram: Centrality, mass, transverse momentum
fHisto = new TH3F(Form("fHisto_%s",GetName()),"", 20,0,100, 200,lThisMass-0.1,lThisMass+0.1, 100,0,10);
}
//________________________________________________________________
AliV0Result::AliV0Result(AliV0Result *lCopyMe)
: TNamed(*lCopyMe),
fHisto(0)
{
fMassHypo = lCopyMe->GetMassHypothesis();
fCutV0Radius = lCopyMe->GetCutV0Radius();
fCutDCANegToPV = lCopyMe->GetCutDCANegToPV();
fCutDCAPosToPV = lCopyMe->GetCutDCAPosToPV(),
fCutDCAV0Daughters = lCopyMe->GetCutDCAV0Daughters(),
fCutV0CosPA = lCopyMe->GetCutV0CosPA(),
fCutProperLifetime = lCopyMe->GetCutProperLifetime(),
fCutLeastNumberOfCrossedRows = lCopyMe->GetCutLeastNumberOfCrossedRows(),
fCutLeastNumberOfCrossedRowsOverFindable = lCopyMe->GetCutLeastNumberOfCrossedRowsOverFindable(),
fCutCompetingV0Rejection = lCopyMe->GetCutCompetingV0Rejection(),
fCutArmenteros = lCopyMe->GetCutArmenteros();
fCutTPCdEdx = lCopyMe->GetCutTPCdEdx();
// Constructor
Double_t lThisMass = 0;
if( fMassHypo == AliV0Result::kK0Short ) lThisMass = 0.497;
if( fMassHypo == AliV0Result::kLambda ) lThisMass = 1.116;
if( fMassHypo == AliV0Result::kAntiLambda ) lThisMass = 1.116;
//Main output histogram: Centrality, mass, transverse momentum
fHisto = new TH3F(Form("fHisto_%s",GetName()),"", 20,0,100, 200,lThisMass-0.1,lThisMass+0.1, 100,0,10);
}
//________________________________________________________________
AliV0Result::~AliV0Result(){
// destructor: clean stuff up
// Actual deletion of the objects causes corruption of event object
// - no idea why - on Proof(Lite). Hence it is disabled here.
//
//delete fEstimatorList;
//fEstimatorList=0x0;
}
//________________________________________________________________
AliV0Result& AliV0Result::operator=(const AliV0Result& lCopyMe)
{
if (&lCopyMe == this) return *this;
SetName(lCopyMe.GetName());
SetTitle(lCopyMe.GetTitle());
fMassHypo = lCopyMe.GetMassHypothesis();
fCutV0Radius = lCopyMe.GetCutV0Radius();
fCutDCANegToPV = lCopyMe.GetCutDCANegToPV();
fCutDCAPosToPV = lCopyMe.GetCutDCAPosToPV(),
fCutDCAV0Daughters = lCopyMe.GetCutDCAV0Daughters(),
fCutV0CosPA = lCopyMe.GetCutV0CosPA(),
fCutProperLifetime = lCopyMe.GetCutProperLifetime(),
fCutLeastNumberOfCrossedRows = lCopyMe.GetCutLeastNumberOfCrossedRows(),
fCutLeastNumberOfCrossedRowsOverFindable = lCopyMe.GetCutLeastNumberOfCrossedRowsOverFindable(),
fCutCompetingV0Rejection = lCopyMe.GetCutCompetingV0Rejection(),
fCutArmenteros = lCopyMe.GetCutArmenteros();
fCutTPCdEdx = lCopyMe.GetCutTPCdEdx();
if (fHisto) {
delete fHisto;
fHisto = 0;
}
// Constructor
Double_t lThisMass = 0;
if( fMassHypo == AliV0Result::kK0Short ) lThisMass = 0.497;
if( fMassHypo == AliV0Result::kLambda ) lThisMass = 1.116;
if( fMassHypo == AliV0Result::kAntiLambda ) lThisMass = 1.116;
//Main output histogram: Centrality, mass, transverse momentum
fHisto = new TH3F(Form("fHisto_%s",GetName()),"", 20,0,100, 200,lThisMass-0.1,lThisMass+0.1, 100,0,10);
return *this;
}<|endoftext|> |
<commit_before>/******************************************************************************
* Birthstone is a programming language and interpreter written by *
* Robb Tolliver for his Senior Project at BYU-Idaho (Fall 2010). *
* *
* Copyright (C) 2010 by Robert Tolliver *
* [email protected] *
* *
* Birthstone 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. *
* *
* Birthstone 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 Birthstone. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "parser.h"
using namespace std;
int main(int argc, char **argv)
{
string filename;
bool interactive = true;
if (argc > 1)
{
ifstream input(argv[1]);
if (input.good())
Parser(input).run();
else
{
cerr << "error: could not read input file. " << endl;
}
input.close();
}
else // interactive mode
{
string str;
stringstream input;
Parser parser(input);
cout << "birthstone interactive interpreter" << endl;
do
{
cout << "bs> ";
getline(cin, str);
input.clear(); // clear flags including ios::eof
input.str(str);
} while (parser.run());
}
return 0;
}
<commit_msg>added build information to interactive interpreter header.<commit_after>/******************************************************************************
* Birthstone is a programming language and interpreter written by *
* Robb Tolliver for his Senior Project at BYU-Idaho (Fall 2010). *
* *
* Copyright (C) 2010 by Robert Tolliver *
* [email protected] *
* *
* Birthstone 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. *
* *
* Birthstone 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 Birthstone. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "parser.h"
using namespace std;
int main(int argc, char **argv)
{
string filename;
bool interactive = true;
if (argc > 1)
{
ifstream input(argv[1]);
if (input.good())
Parser(input).run();
else
{
cerr << "error: could not read input file. " << endl;
}
input.close();
}
else // interactive mode
{
string str;
stringstream input;
Parser parser(input);
cout << "Birthstone interactive interpreter" << endl;
cout << "(build " << __DATE__ << ' ' << __TIME__ ;
#ifdef BS_DEBUG
cout << " DEBUG";
#endif // BS_DEBUG
cout << ")"<< endl;
do
{
cout << "bs> ";
getline(cin, str);
input.clear(); // clear flags including ios::eof
input.str(str);
} while (parser.run());
}
return 0;
}
<|endoftext|> |
<commit_before>#include <chrono>
#include <iostream>
#include "image.h"
using namespace AhoViewer::Booru;
#include "browser.h"
Image::Image(const std::string &path, const std::string &url,
const std::string &thumbPath, const std::string &thumbUrl,
const std::string &postUrl,
std::set<std::string> tags, const Page &page)
: AhoViewer::Image(path),
m_Url(url),
m_ThumbnailUrl(thumbUrl),
m_PostUrl(postUrl),
m_Tags(tags),
m_Page(page),
m_Curler(m_Url),
m_ThumbnailCurler(m_ThumbnailUrl),
m_PixbufError(false)
{
m_ThumbnailPath = thumbPath;
if (!m_isWebM)
m_Curler.signal_write().connect(sigc::mem_fun(*this, &Image::on_write));
if (m_isWebM && !Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))
m_Loading = true;
m_Curler.set_referer(page.get_site()->get_url());
m_Curler.signal_progress().connect(sigc::mem_fun(*this, &Image::on_progress));
m_Curler.signal_finished().connect(sigc::mem_fun(*this, &Image::on_finished));
}
Image::~Image()
{
cancel_download();
if (m_Curler.is_active())
m_Page.get_image_fetcher().remove_handle(&m_Curler);
}
std::string Image::get_filename() const
{
return Glib::build_filename(m_Page.get_site()->get_name(), Glib::path_get_basename(m_Path));
}
const Glib::RefPtr<Gdk::Pixbuf>& Image::get_thumbnail()
{
if (!m_ThumbnailPixbuf)
{
m_ThumbnailLock.writer_lock();
if (m_ThumbnailCurler.perform())
{
m_ThumbnailCurler.save_file(m_ThumbnailPath);
try
{
m_ThumbnailPixbuf = create_pixbuf_at_size(m_ThumbnailPath, 128, 128);
}
catch (const Gdk::PixbufError &ex)
{
std::cerr << ex.what() << std::endl;
m_ThumbnailPixbuf = get_missing_pixbuf();
}
}
else
{
std::cerr << "Error while downloading thumbnail " << m_ThumbnailUrl
<< " " << std::endl << " " << m_ThumbnailCurler.get_error() << std::endl;
m_ThumbnailPixbuf = get_missing_pixbuf();
}
m_ThumbnailLock.writer_unlock();
}
return m_ThumbnailPixbuf;
}
void Image::load_pixbuf()
{
if (!m_Pixbuf && !m_PixbufError)
{
if (Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))
{
AhoViewer::Image::load_pixbuf();
}
else if (!start_download() && !m_isWebM && m_Loader->get_animation())
{
m_Pixbuf = m_Loader->get_animation();
}
}
}
void Image::reset_pixbuf()
{
if (m_Loading)
cancel_download();
AhoViewer::Image::reset_pixbuf();
}
void Image::save(const std::string &path)
{
if (!Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))
{
start_download();
Glib::Threads::Mutex::Lock lock(m_DownloadMutex);
while (!m_Curler.is_cancelled() && !Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))
m_DownloadCond.wait(m_DownloadMutex);
}
if (m_Curler.is_cancelled())
return;
Glib::RefPtr<Gio::File> src = Gio::File::create_for_path(m_Path),
dst = Gio::File::create_for_path(path);
src->copy(dst, Gio::FILE_COPY_OVERWRITE);
}
void Image::cancel_download()
{
Glib::Threads::Mutex::Lock lock(m_DownloadMutex);
m_Curler.cancel();
m_Curler.clear();
if (m_Loader)
{
try { m_Loader->close(); }
catch (...) { }
m_Loader.reset();
}
m_DownloadCond.signal();
}
/**
* Returns true if the download was started
**/
bool Image::start_download()
{
if (!m_Curler.is_active())
{
m_Page.get_image_fetcher().add_handle(&m_Curler);
m_Loading = true;
if (!m_isWebM)
{
m_Loader = Gdk::PixbufLoader::create();
m_Loader->signal_area_prepared().connect(sigc::mem_fun(*this, &Image::on_area_prepared));
m_Loader->signal_area_updated().connect(sigc::mem_fun(*this, &Image::on_area_updated));
}
return true;
}
return false;
}
void Image::on_write(const unsigned char *d, size_t l)
{
try
{
Glib::Threads::Mutex::Lock lock(m_DownloadMutex);
m_Loader->write(d, l);
}
catch (const Gdk::PixbufError &ex)
{
std::cerr << ex.what() << std::endl;
cancel_download();
m_PixbufError = true;
}
}
void Image::on_progress()
{
double c, t;
m_Curler.get_progress(c, t);
m_SignalProgress(c, t);
}
void Image::on_finished()
{
Glib::Threads::Mutex::Lock lock(m_DownloadMutex);
m_Curler.save_file(m_Path);
m_Curler.clear();
if (m_Loader)
{
m_Loader->close();
m_Loader.reset();
}
m_Loading = false;
m_SignalPixbufChanged();
m_DownloadCond.signal();
}
void Image::on_area_prepared()
{
m_ThumbnailLock.reader_lock();
if (m_ThumbnailPixbuf && m_ThumbnailPixbuf != get_missing_pixbuf())
{
Glib::RefPtr<Gdk::Pixbuf> pixbuf = m_Loader->get_pixbuf();
m_ThumbnailPixbuf->composite(pixbuf, 0, 0, pixbuf->get_width(), pixbuf->get_height(), 0, 0,
static_cast<double>(pixbuf->get_width()) / m_ThumbnailPixbuf->get_width(),
static_cast<double>(pixbuf->get_height()) / m_ThumbnailPixbuf->get_height(),
Gdk::INTERP_BILINEAR, 255);
}
m_ThumbnailLock.reader_unlock();
m_Pixbuf = m_Loader->get_animation();
if (!m_Curler.is_cancelled())
m_SignalPixbufChanged();
}
void Image::on_area_updated(int, int, int, int)
{
long since = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - m_LastDraw).count();
if (!m_Curler.is_cancelled() && since >= 100)
{
m_SignalPixbufChanged();
m_LastDraw = std::chrono::steady_clock::now();
}
}
<commit_msg>booru/image: Fix updating while downloading on Windows<commit_after>#include <chrono>
#include <iostream>
#include "image.h"
using namespace AhoViewer::Booru;
#include "browser.h"
Image::Image(const std::string &path, const std::string &url,
const std::string &thumbPath, const std::string &thumbUrl,
const std::string &postUrl,
std::set<std::string> tags, const Page &page)
: AhoViewer::Image(path),
m_Url(url),
m_ThumbnailUrl(thumbUrl),
m_PostUrl(postUrl),
m_Tags(tags),
m_Page(page),
m_Curler(m_Url),
m_ThumbnailCurler(m_ThumbnailUrl),
m_PixbufError(false)
{
m_ThumbnailPath = thumbPath;
if (!m_isWebM)
m_Curler.signal_write().connect(sigc::mem_fun(*this, &Image::on_write));
if (m_isWebM && !Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))
m_Loading = true;
m_Curler.set_referer(page.get_site()->get_url());
m_Curler.signal_progress().connect(sigc::mem_fun(*this, &Image::on_progress));
m_Curler.signal_finished().connect(sigc::mem_fun(*this, &Image::on_finished));
}
Image::~Image()
{
cancel_download();
if (m_Curler.is_active())
m_Page.get_image_fetcher().remove_handle(&m_Curler);
}
std::string Image::get_filename() const
{
return Glib::build_filename(m_Page.get_site()->get_name(), Glib::path_get_basename(m_Path));
}
const Glib::RefPtr<Gdk::Pixbuf>& Image::get_thumbnail()
{
if (!m_ThumbnailPixbuf)
{
m_ThumbnailLock.writer_lock();
if (m_ThumbnailCurler.perform())
{
m_ThumbnailCurler.save_file(m_ThumbnailPath);
try
{
m_ThumbnailPixbuf = create_pixbuf_at_size(m_ThumbnailPath, 128, 128);
}
catch (const Gdk::PixbufError &ex)
{
std::cerr << ex.what() << std::endl;
m_ThumbnailPixbuf = get_missing_pixbuf();
}
}
else
{
std::cerr << "Error while downloading thumbnail " << m_ThumbnailUrl
<< " " << std::endl << " " << m_ThumbnailCurler.get_error() << std::endl;
m_ThumbnailPixbuf = get_missing_pixbuf();
}
m_ThumbnailLock.writer_unlock();
}
return m_ThumbnailPixbuf;
}
void Image::load_pixbuf()
{
if (!m_Pixbuf && !m_PixbufError)
{
if (Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))
{
AhoViewer::Image::load_pixbuf();
}
else if (!start_download() && !m_isWebM && m_Loader->get_animation())
{
m_Pixbuf = m_Loader->get_animation();
}
}
}
void Image::reset_pixbuf()
{
if (m_Loading)
cancel_download();
AhoViewer::Image::reset_pixbuf();
}
void Image::save(const std::string &path)
{
if (!Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))
{
start_download();
Glib::Threads::Mutex::Lock lock(m_DownloadMutex);
while (!m_Curler.is_cancelled() && !Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))
m_DownloadCond.wait(m_DownloadMutex);
}
if (m_Curler.is_cancelled())
return;
Glib::RefPtr<Gio::File> src = Gio::File::create_for_path(m_Path),
dst = Gio::File::create_for_path(path);
src->copy(dst, Gio::FILE_COPY_OVERWRITE);
}
void Image::cancel_download()
{
Glib::Threads::Mutex::Lock lock(m_DownloadMutex);
m_Curler.cancel();
m_Curler.clear();
if (m_Loader)
{
try { m_Loader->close(); }
catch (...) { }
m_Loader.reset();
}
m_DownloadCond.signal();
}
/**
* Returns true if the download was started
**/
bool Image::start_download()
{
if (!m_Curler.is_active())
{
m_Page.get_image_fetcher().add_handle(&m_Curler);
m_Loading = true;
if (!m_isWebM)
{
m_Loader = Gdk::PixbufLoader::create();
m_Loader->signal_area_prepared().connect(sigc::mem_fun(*this, &Image::on_area_prepared));
m_Loader->signal_area_updated().connect(sigc::mem_fun(*this, &Image::on_area_updated));
}
return true;
}
return false;
}
void Image::on_write(const unsigned char *d, size_t l)
{
try
{
Glib::Threads::Mutex::Lock lock(m_DownloadMutex);
m_Loader->write(d, l);
}
catch (const Gdk::PixbufError &ex)
{
std::cerr << ex.what() << std::endl;
cancel_download();
m_PixbufError = true;
}
}
void Image::on_progress()
{
double c, t;
m_Curler.get_progress(c, t);
m_SignalProgress(c, t);
}
void Image::on_finished()
{
Glib::Threads::Mutex::Lock lock(m_DownloadMutex);
m_Curler.save_file(m_Path);
m_Curler.clear();
if (m_Loader)
{
m_Loader->close();
m_Loader.reset();
}
m_Loading = false;
m_SignalPixbufChanged();
m_DownloadCond.signal();
}
void Image::on_area_prepared()
{
m_ThumbnailLock.reader_lock();
if (m_ThumbnailPixbuf && m_ThumbnailPixbuf != get_missing_pixbuf())
{
Glib::RefPtr<Gdk::Pixbuf> pixbuf = m_Loader->get_pixbuf();
m_ThumbnailPixbuf->composite(pixbuf, 0, 0, pixbuf->get_width(), pixbuf->get_height(), 0, 0,
static_cast<double>(pixbuf->get_width()) / m_ThumbnailPixbuf->get_width(),
static_cast<double>(pixbuf->get_height()) / m_ThumbnailPixbuf->get_height(),
Gdk::INTERP_BILINEAR, 255);
}
m_ThumbnailLock.reader_unlock();
m_Pixbuf = m_Loader->get_animation();
if (!m_Curler.is_cancelled())
m_SignalPixbufChanged();
}
void Image::on_area_updated(int, int, int, int)
{
using namespace std::chrono;
if (!m_Curler.is_cancelled() && steady_clock::now() >= m_LastDraw + milliseconds(100))
{
m_SignalPixbufChanged();
m_LastDraw = steady_clock::now();
}
}
<|endoftext|> |
<commit_before>#include "bufferAgent.h"
#include "helpers/storageHelperFactory.h"
#include "glog/logging.h"
using boost::shared_ptr;
using boost::thread;
using boost::bind;
using std::string;
namespace veil {
namespace helpers {
BufferAgent::BufferAgent(write_fun w, read_fun r)
: m_agentActive(false),
doWrite(w),
doRead(r)
{
agentStart();
}
BufferAgent::~BufferAgent()
{
agentStop();
}
int BufferAgent::onOpen(std::string path, ffi_type ffi)
{
{
unique_lock guard(m_wrMutex);
m_wrCacheMap.erase(ffi->fh);
write_buffer_ptr lCache(new WriteCache());
lCache->fileName = path;
lCache->buffer = newFileCache(true);
lCache->ffi = *ffi;
m_wrCacheMap[ffi->fh] = lCache;
}
{
unique_lock guard(m_rdMutex);
read_cache_map_t::iterator it;
if(( it = m_rdCacheMap.find(path) ) != m_rdCacheMap.end()) {
it->second->openCount++;
} else {
read_buffer_ptr lCache(new ReadCache());
lCache->fileName = path;
lCache->openCount = 1;
lCache->ffi = *ffi;
lCache->buffer = newFileCache(false);
m_rdCacheMap[path] = lCache;
}
m_rdJobQueue.push_front(PrefetchJob(path, 0, 512));
m_rdCond.notify_one();
}
return 0;
}
int BufferAgent::onWrite(std::string path, const std::string &buf, size_t size, off_t offset, ffi_type ffi)
{
unique_lock guard(m_wrMutex);
write_buffer_ptr wrapper = m_wrCacheMap[ffi->fh];
guard.unlock();
{
if(wrapper->buffer->byteSize() > 1024 * 1024 * 64) {
if(int fRet = onFlush(path, ffi)) {
return fRet;
}
}
if(wrapper->buffer->byteSize() > 1024 * 1024 * 64) {
return doWrite(path, buf, size, offset, ffi);
}
wrapper->buffer->writeData(offset, buf);
}
unique_lock buffGuard(wrapper->mutex);
guard.lock();
if(!wrapper->opPending)
{
wrapper->opPending = true;
m_wrJobQueue.push_back(ffi->fh);
m_wrCond.notify_one();
}
return size;
}
int BufferAgent::onRead(std::string path, std::string &buf, size_t size, off_t offset, ffi_type ffi)
{
unique_lock guard(m_rdMutex);
read_buffer_ptr wrapper = m_rdCacheMap[path];
guard.unlock();
wrapper->buffer->readData(offset, size, buf);
LOG(INFO) << "Found: " << buf.size() << "bcount: " << wrapper->buffer->blockCount();
if(buf.size() < size) {
string buf2;
int ret = doRead(path, buf2, size - buf.size(), offset + buf.size(), &wrapper->ffi);
if(ret < 0)
return ret;
wrapper->buffer->writeData(offset + buf.size(), buf2);
buf += buf2;
//DLOG(INFO) << "doRead ret: " << ret << " bufSize: " << buf2.size() << " globalBufSize: " << buf.size() ;
guard.lock();
m_rdJobQueue.push_back(PrefetchJob(wrapper->fileName, offset + buf.size(), wrapper->blockSize));
guard.unlock();
} else {
string tmp;
size_t prefSize = std::max(2*size, wrapper->blockSize);
wrapper->buffer->readData(offset + size, prefSize, tmp);
if(tmp.size() != prefSize) {
guard.lock();
m_rdJobQueue.push_back(PrefetchJob(wrapper->fileName, offset + size + tmp.size(), wrapper->blockSize));
m_rdJobQueue.push_back(PrefetchJob(wrapper->fileName, offset + size + tmp.size() + wrapper->blockSize, wrapper->blockSize));
guard.unlock();
}
}
{
unique_lock buffGuard(wrapper->mutex);
wrapper->lastBlock = offset;
wrapper->blockSize = std::min((size_t) 1024 * 1024, (size_t) std::max(size, 2*wrapper->blockSize));
}
m_rdCond.notify_one();
return buf.size();
}
int BufferAgent::onFlush(std::string path, ffi_type ffi)
{
unique_lock guard(m_wrMutex);
write_buffer_ptr wrapper = m_wrCacheMap[ffi->fh];
guard.unlock();
unique_lock sendGuard(wrapper->sendMutex);
unique_lock buff_guard(wrapper->mutex);
while(wrapper->buffer->blockCount() > 0)
{
block_ptr block = wrapper->buffer->removeOldestBlock();
uint64_t start = utils::mtime<uint64_t>();
int res = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi);
uint64_t end = utils::mtime<uint64_t>();
//LOG(INFO) << "Roundtrip: " << (end - start) << " for " << block->data.size() << " bytes";
if(res < 0)
{
while(wrapper->buffer->blockCount() > 0)
{
(void) wrapper->buffer->removeOldestBlock();
}
return res;
}
}
guard.lock();
m_wrJobQueue.remove(ffi->fh);
return 0;
}
int BufferAgent::onRelease(std::string path, ffi_type ffi)
{
{
unique_lock guard(m_wrMutex);
m_wrCacheMap.erase(ffi->fh);
m_wrJobQueue.remove(ffi->fh);
}
{
unique_lock guard(m_rdMutex);
read_cache_map_t::iterator it;
if(( it = m_rdCacheMap.find(path) ) != m_rdCacheMap.end()) {
it->second->openCount--;
if(it->second->openCount <= 0) {
m_rdCacheMap.erase(it);
}
}
}
return 0;
}
void BufferAgent::agentStart(int worker_count)
{
m_workers.clear();
m_agentActive = true;
while(worker_count--)
{
m_workers.push_back(shared_ptr<thread>(new thread(bind(&BufferAgent::writerLoop, this))));
m_workers.push_back(shared_ptr<thread>(new thread(bind(&BufferAgent::readerLoop, this))));
}
}
void BufferAgent::agentStop()
{
m_agentActive = false;
m_wrCond.notify_all();
m_rdCond.notify_all();
while(m_workers.size() > 0)
{
m_workers.back()->join();
m_workers.pop_back();
}
}
void BufferAgent::readerLoop()
{
unique_lock guard(m_rdMutex);
while(m_agentActive)
{
while(m_rdJobQueue.empty() && m_agentActive)
m_rdCond.wait(guard);
if(!m_agentActive)
return;
PrefetchJob job = m_rdJobQueue.front();
read_buffer_ptr wrapper = m_rdCacheMap[job.fileName];
m_rdJobQueue.pop_front();
m_rdCond.notify_one();
if(!wrapper || wrapper->lastBlock >= job.offset)
continue;
guard.unlock();
{
string buff;
wrapper->buffer->readData(job.offset, job.size, buff);
if(buff.size() < job.size)
{
string tmp;
int ret = doRead(wrapper->fileName, tmp, job.size - buff.size(), job.offset + buff.size(), &wrapper->ffi);
if(ret > 0 && tmp.size() >= ret) {
wrapper->buffer->writeData(job.offset + buff.size(), tmp);
guard.lock();
m_rdJobQueue.push_back(PrefetchJob(job.fileName, job.offset + buff.size() + ret, wrapper->blockSize));
guard.unlock();
}
}
}
guard.lock();
}
}
void BufferAgent::writerLoop()
{
unique_lock guard(m_wrMutex);
while(m_agentActive)
{
while(m_wrJobQueue.empty() && m_agentActive)
m_wrCond.wait(guard);
if(!m_agentActive)
return;
fd_type file = m_wrJobQueue.front();
write_buffer_ptr wrapper = m_wrCacheMap[file];
m_wrJobQueue.pop_front();
m_wrCond.notify_one();
if(!wrapper)
continue;
guard.unlock();
{
unique_lock sendGuard(wrapper->sendMutex);
block_ptr block;
{
unique_lock buff_guard(wrapper->mutex);
block = wrapper->buffer->removeOldestBlock();
}
if(block)
{
uint64_t start = utils::mtime<uint64_t>();
int res = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi);
uint64_t end = utils::mtime<uint64_t>();
//LOG(INFO) << "Roundtrip: " << (end - start) << " for " << block->data.size() << " bytes";
wrapper->cond.notify_all();
}
{
unique_lock buff_guard(wrapper->mutex);
guard.lock();
if(wrapper->buffer->blockCount() > 0)
{
m_wrJobQueue.push_back(file);
}
else
{
wrapper->opPending = false;
}
}
}
wrapper->cond.notify_all();
}
}
boost::shared_ptr<FileCache> BufferAgent::newFileCache(bool isBuffer)
{
return boost::shared_ptr<FileCache>(new FileCache(10 * 1024 * 1024, isBuffer));
}
} // namespace helpers
} // namespace veil
<commit_msg>VFS-292: improve read speed<commit_after>#include "bufferAgent.h"
#include "helpers/storageHelperFactory.h"
#include "glog/logging.h"
using boost::shared_ptr;
using boost::thread;
using boost::bind;
using std::string;
namespace veil {
namespace helpers {
BufferAgent::BufferAgent(write_fun w, read_fun r)
: m_agentActive(false),
doWrite(w),
doRead(r)
{
agentStart();
}
BufferAgent::~BufferAgent()
{
agentStop();
}
int BufferAgent::onOpen(std::string path, ffi_type ffi)
{
{
unique_lock guard(m_wrMutex);
m_wrCacheMap.erase(ffi->fh);
write_buffer_ptr lCache(new WriteCache());
lCache->fileName = path;
lCache->buffer = newFileCache(true);
lCache->ffi = *ffi;
m_wrCacheMap[ffi->fh] = lCache;
}
{
unique_lock guard(m_rdMutex);
read_cache_map_t::iterator it;
if(( it = m_rdCacheMap.find(path) ) != m_rdCacheMap.end()) {
it->second->openCount++;
} else {
read_buffer_ptr lCache(new ReadCache());
lCache->fileName = path;
lCache->openCount = 1;
lCache->ffi = *ffi;
lCache->buffer = newFileCache(false);
m_rdCacheMap[path] = lCache;
}
m_rdJobQueue.push_front(PrefetchJob(path, 0, 10 * 1024 * 1024));
m_rdCond.notify_one();
}
return 0;
}
int BufferAgent::onWrite(std::string path, const std::string &buf, size_t size, off_t offset, ffi_type ffi)
{
unique_lock guard(m_wrMutex);
write_buffer_ptr wrapper = m_wrCacheMap[ffi->fh];
guard.unlock();
{
if(wrapper->buffer->byteSize() > 1024 * 1024 * 64) {
if(int fRet = onFlush(path, ffi)) {
return fRet;
}
}
if(wrapper->buffer->byteSize() > 1024 * 1024 * 64) {
return doWrite(path, buf, size, offset, ffi);
}
wrapper->buffer->writeData(offset, buf);
}
unique_lock buffGuard(wrapper->mutex);
guard.lock();
if(!wrapper->opPending)
{
wrapper->opPending = true;
m_wrJobQueue.push_back(ffi->fh);
m_wrCond.notify_one();
}
return size;
}
int BufferAgent::onRead(std::string path, std::string &buf, size_t size, off_t offset, ffi_type ffi)
{
unique_lock guard(m_rdMutex);
read_buffer_ptr wrapper = m_rdCacheMap[path];
guard.unlock();
wrapper->buffer->readData(offset, size, buf);
LOG(INFO) << "Found: " << buf.size() << "bcount: " << wrapper->buffer->blockCount();
if(buf.size() < size) {
string buf2;
int ret = doRead(path, buf2, size - buf.size(), offset + buf.size(), &wrapper->ffi);
if(ret < 0)
return ret;
wrapper->buffer->writeData(offset + buf.size(), buf2);
buf += buf2;
//DLOG(INFO) << "doRead ret: " << ret << " bufSize: " << buf2.size() << " globalBufSize: " << buf.size() ;
guard.lock();
m_rdJobQueue.push_back(PrefetchJob(wrapper->fileName, offset + buf.size(), wrapper->blockSize));
guard.unlock();
} else {
string tmp;
size_t prefSize = std::max(2*size, wrapper->blockSize);
wrapper->buffer->readData(offset + size, prefSize, tmp);
if(tmp.size() != prefSize) {
guard.lock();
m_rdJobQueue.push_back(PrefetchJob(wrapper->fileName, offset + size + tmp.size(), wrapper->blockSize));
m_rdJobQueue.push_back(PrefetchJob(wrapper->fileName, offset + size + tmp.size() + wrapper->blockSize, wrapper->blockSize));
guard.unlock();
}
}
{
unique_lock buffGuard(wrapper->mutex);
wrapper->lastBlock = offset;
wrapper->blockSize = std::min((size_t) 1024 * 1024, (size_t) std::max(size, 2*wrapper->blockSize));
}
m_rdCond.notify_one();
return buf.size();
}
int BufferAgent::onFlush(std::string path, ffi_type ffi)
{
unique_lock guard(m_wrMutex);
write_buffer_ptr wrapper = m_wrCacheMap[ffi->fh];
guard.unlock();
unique_lock sendGuard(wrapper->sendMutex);
unique_lock buff_guard(wrapper->mutex);
while(wrapper->buffer->blockCount() > 0)
{
block_ptr block = wrapper->buffer->removeOldestBlock();
uint64_t start = utils::mtime<uint64_t>();
int res = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi);
uint64_t end = utils::mtime<uint64_t>();
//LOG(INFO) << "Roundtrip: " << (end - start) << " for " << block->data.size() << " bytes";
if(res < 0)
{
while(wrapper->buffer->blockCount() > 0)
{
(void) wrapper->buffer->removeOldestBlock();
}
return res;
}
}
guard.lock();
m_wrJobQueue.remove(ffi->fh);
return 0;
}
int BufferAgent::onRelease(std::string path, ffi_type ffi)
{
{
unique_lock guard(m_wrMutex);
m_wrCacheMap.erase(ffi->fh);
m_wrJobQueue.remove(ffi->fh);
}
{
unique_lock guard(m_rdMutex);
read_cache_map_t::iterator it;
if(( it = m_rdCacheMap.find(path) ) != m_rdCacheMap.end()) {
it->second->openCount--;
if(it->second->openCount <= 0) {
m_rdCacheMap.erase(it);
}
}
}
return 0;
}
void BufferAgent::agentStart(int worker_count)
{
m_workers.clear();
m_agentActive = true;
while(worker_count--)
{
m_workers.push_back(shared_ptr<thread>(new thread(bind(&BufferAgent::writerLoop, this))));
m_workers.push_back(shared_ptr<thread>(new thread(bind(&BufferAgent::readerLoop, this))));
}
}
void BufferAgent::agentStop()
{
m_agentActive = false;
m_wrCond.notify_all();
m_rdCond.notify_all();
while(m_workers.size() > 0)
{
m_workers.back()->join();
m_workers.pop_back();
}
}
void BufferAgent::readerLoop()
{
unique_lock guard(m_rdMutex);
while(m_agentActive)
{
while(m_rdJobQueue.empty() && m_agentActive)
m_rdCond.wait(guard);
if(!m_agentActive)
return;
PrefetchJob job = m_rdJobQueue.front();
read_buffer_ptr wrapper = m_rdCacheMap[job.fileName];
m_rdJobQueue.pop_front();
m_rdCond.notify_one();
if(!wrapper || wrapper->lastBlock >= job.offset)
continue;
guard.unlock();
{
string buff;
wrapper->buffer->readData(job.offset, job.size, buff);
if(buff.size() < job.size)
{
string tmp;
int ret = doRead(wrapper->fileName, tmp, job.size - buff.size(), job.offset + buff.size(), &wrapper->ffi);
if(ret > 0 && tmp.size() >= ret) {
wrapper->buffer->writeData(job.offset + buff.size(), tmp);
guard.lock();
m_rdJobQueue.push_back(PrefetchJob(job.fileName, job.offset + buff.size() + ret, wrapper->blockSize));
guard.unlock();
}
}
}
guard.lock();
}
}
void BufferAgent::writerLoop()
{
unique_lock guard(m_wrMutex);
while(m_agentActive)
{
while(m_wrJobQueue.empty() && m_agentActive)
m_wrCond.wait(guard);
if(!m_agentActive)
return;
fd_type file = m_wrJobQueue.front();
write_buffer_ptr wrapper = m_wrCacheMap[file];
m_wrJobQueue.pop_front();
m_wrCond.notify_one();
if(!wrapper)
continue;
guard.unlock();
{
unique_lock sendGuard(wrapper->sendMutex);
block_ptr block;
{
unique_lock buff_guard(wrapper->mutex);
block = wrapper->buffer->removeOldestBlock();
}
if(block)
{
uint64_t start = utils::mtime<uint64_t>();
int res = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi);
uint64_t end = utils::mtime<uint64_t>();
//LOG(INFO) << "Roundtrip: " << (end - start) << " for " << block->data.size() << " bytes";
wrapper->cond.notify_all();
}
{
unique_lock buff_guard(wrapper->mutex);
guard.lock();
if(wrapper->buffer->blockCount() > 0)
{
m_wrJobQueue.push_back(file);
}
else
{
wrapper->opPending = false;
}
}
}
wrapper->cond.notify_all();
}
}
boost::shared_ptr<FileCache> BufferAgent::newFileCache(bool isBuffer)
{
return boost::shared_ptr<FileCache>(new FileCache(10 * 1024 * 1024, isBuffer));
}
} // namespace helpers
} // namespace veil
<|endoftext|> |
<commit_before>/*
Part of Scallop Transcript Assembler
(c) 2017 by Mingfu Shao, Carl Kingsford, and Carnegie Mellon University.
See LICENSE for licensing.
*/
#include <cassert>
#include <cstdio>
#include <cmath>
#include "bundle_base.h"
bundle_base::bundle_base()
{
tid = -1;
chrm = "";
lpos = INT32_MAX;
rpos = 0;
strand = '.';
num_long_reads = 0;
}
bundle_base::~bundle_base()
{}
int bundle_base::add_hit(const hit &ht)
{
if(ht.is_long_read == true) num_long_reads++;
// store new hit
hits.push_back(ht);
// calcuate the boundaries on reference
if(ht.pos < lpos) lpos = ht.pos;
if(ht.rpos > rpos) rpos = ht.rpos;
// set tid
if(tid == -1) tid = ht.tid;
assert(tid == ht.tid);
// set strand
if(hits.size() <= 1) strand = ht.strand;
assert(strand == ht.strand);
// DEBUG
/*
if(strand != ht.strand)
{
printf("strand = %c, ht.strand = %c, ht.xs = %c,\n", strand, ht.strand, ht.xs);
}
*/
// add intervals
vector<int64_t> vm;
vector<int64_t> vi;
vector<int64_t> vd;
ht.get_mid_intervals(vm, vi, vd);
//ht.print();
for(int k = 0; k < vm.size(); k++)
{
int32_t s = high32(vm[k]);
int32_t t = low32(vm[k]);
//printf(" add interval %d-%d\n", s, t);
mmap += make_pair(ROI(s, t), 1);
}
for(int k = 0; k < vi.size(); k++)
{
int32_t s = high32(vi[k]);
int32_t t = low32(vi[k]);
imap += make_pair(ROI(s, t), 1);
}
for(int k = 0; k < vd.size(); k++)
{
int32_t s = high32(vd[k]);
int32_t t = low32(vd[k]);
imap += make_pair(ROI(s, t), 1);
}
return 0;
}
bool bundle_base::overlap(const hit &ht) const
{
if(mmap.find(ROI(ht.pos, ht.pos + 1)) != mmap.end()) return true;
if(mmap.find(ROI(ht.rpos - 1, ht.rpos)) != mmap.end()) return true;
return false;
}
int bundle_base::clear()
{
tid = -1;
chrm = "";
lpos = INT32_MAX;
rpos = 0;
strand = '.';
hits.clear();
mmap.clear();
imap.clear();
num_long_reads = 0;
return 0;
}
<commit_msg>replace INT32_MAX with 1 << 30<commit_after>/*
Part of Scallop Transcript Assembler
(c) 2017 by Mingfu Shao, Carl Kingsford, and Carnegie Mellon University.
See LICENSE for licensing.
*/
#include <cassert>
#include <cstdio>
#include <cmath>
#include <climits>
#include "bundle_base.h"
bundle_base::bundle_base()
{
tid = -1;
chrm = "";
lpos = 1 << 30;
rpos = 0;
strand = '.';
num_long_reads = 0;
}
bundle_base::~bundle_base()
{}
int bundle_base::add_hit(const hit &ht)
{
if(ht.is_long_read == true) num_long_reads++;
// store new hit
hits.push_back(ht);
// calcuate the boundaries on reference
if(ht.pos < lpos) lpos = ht.pos;
if(ht.rpos > rpos) rpos = ht.rpos;
// set tid
if(tid == -1) tid = ht.tid;
assert(tid == ht.tid);
// set strand
if(hits.size() <= 1) strand = ht.strand;
assert(strand == ht.strand);
// DEBUG
/*
if(strand != ht.strand)
{
printf("strand = %c, ht.strand = %c, ht.xs = %c,\n", strand, ht.strand, ht.xs);
}
*/
// add intervals
vector<int64_t> vm;
vector<int64_t> vi;
vector<int64_t> vd;
ht.get_mid_intervals(vm, vi, vd);
//ht.print();
for(int k = 0; k < vm.size(); k++)
{
int32_t s = high32(vm[k]);
int32_t t = low32(vm[k]);
//printf(" add interval %d-%d\n", s, t);
mmap += make_pair(ROI(s, t), 1);
}
for(int k = 0; k < vi.size(); k++)
{
int32_t s = high32(vi[k]);
int32_t t = low32(vi[k]);
imap += make_pair(ROI(s, t), 1);
}
for(int k = 0; k < vd.size(); k++)
{
int32_t s = high32(vd[k]);
int32_t t = low32(vd[k]);
imap += make_pair(ROI(s, t), 1);
}
return 0;
}
bool bundle_base::overlap(const hit &ht) const
{
if(mmap.find(ROI(ht.pos, ht.pos + 1)) != mmap.end()) return true;
if(mmap.find(ROI(ht.rpos - 1, ht.rpos)) != mmap.end()) return true;
return false;
}
int bundle_base::clear()
{
tid = -1;
chrm = "";
lpos = 1 << 30;
rpos = 0;
strand = '.';
hits.clear();
mmap.clear();
imap.clear();
num_long_reads = 0;
return 0;
}
<|endoftext|> |
<commit_before>
/***************************************************************************
jabberaccountwidget.h - Account widget for Jabber
-------------------
begin : Mon Dec 9 2002
copyright : (C) 2002-2003 by Till Gerken <[email protected]>
Based on code by Olivier Goffart <[email protected]>
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include <kdebug.h>
#include <qlineedit.h>
#include <qcheckbox.h>
#include <qpushbutton.h>
#include <qspinbox.h>
#include <qcombobox.h>
#include <kmessagebox.h>
#include <klocale.h>
#include "jabbereditaccountwidget.h"
JabberEditAccountWidget::JabberEditAccountWidget (JabberProtocol * proto, JabberAccount * ident, QWidget * parent, const char *name)
: DlgJabberEditAccountWidget (parent, name), KopeteEditAccountWidget (ident)
{
m_protocol = proto;
connect (mID, SIGNAL (textChanged (const QString &)), this, SLOT (configChanged ()));
connect (mPass, SIGNAL (textChanged (const QString &)), this, SLOT (configChanged ()));
connect (mResource, SIGNAL (textChanged (const QString &)), this, SLOT (configChanged ()));
connect (mServer, SIGNAL (textChanged (const QString &)), this, SLOT (configChanged ()));
connect (mPort, SIGNAL (valueChanged (int)), this, SLOT (configChanged ()));
connect (mAutoConnect, SIGNAL (toggled (bool)), this, SLOT (configChanged ()));
connect (chkUseSSL, SIGNAL (toggled (bool)), this, SLOT (configChanged ()));
connect (chkRemPass, SIGNAL (toggled (bool)), this, SLOT (configChanged ()));
// Chat TAB
connect (cmbAuth, SIGNAL (activated (int)), this, SLOT (configChanged ()));
connect (cbProxyType, SIGNAL (activated (int)), this, SLOT (configChanged ()));
connect (leProxyName, SIGNAL (textChanged (const QString &)), this, SLOT (configChanged ()));
connect (spbProxyPort, SIGNAL (valueChanged (int)), this, SLOT (configChanged ()));
connect (cbProxyAuth, SIGNAL (toggled (bool)), this, SLOT (configChanged ()));
connect (leProxyUser, SIGNAL (textChanged (const QString &)), this, SLOT (configChanged ()));
connect (leProxyPass, SIGNAL (textChanged (const QString &)), this, SLOT (configChanged ()));
connect (mID, SIGNAL (textChanged (const QString &)), this, SLOT (setJIDValidation ()));
connect (mServer, SIGNAL (textChanged (const QString &)), this, SLOT (setJIDValidation ()));
connect (btnRegister, SIGNAL (clicked ()), this, SLOT (registerClicked ()));
connect (chkUseSSL, SIGNAL (toggled (bool)), this, SLOT (sslToggled (bool)));
if (account())
{
this->reopen ();
}
}
JabberEditAccountWidget::~JabberEditAccountWidget ()
{
}
void JabberEditAccountWidget::reopen ()
{
// FIXME: this is temporary until Kopete supports accound ID changes!
mID->setDisabled(true);
mID->setText (account()->accountId ());
mPass->setText (account()->password ());
mResource->setText (account()->pluginData (m_protocol, "Resource"));
mServer->setText (account()->pluginData (m_protocol, "Server"));
if (account()->pluginData (m_protocol, "UseSSL") == "true")
chkUseSSL->setChecked (true);
mPort->setValue (account()->pluginData (m_protocol, "Port").toInt ());
if (account()->pluginData (m_protocol, "RemPass") == "true")
chkRemPass->setChecked (true);
QString auth = account()->pluginData (m_protocol, "AuthType");
cmbAuth->setCurrentItem (0);
if (auth == QString ("plain"))
cmbAuth->setCurrentItem (1);
QString proxyType = account()->pluginData (m_protocol, "ProxyType");
cbProxyType->setCurrentItem (0);
if (proxyType == QString ("HTTPS"))
cbProxyType->setCurrentItem (1);
else if (proxyType == QString ("SOCKS4"))
cbProxyType->setCurrentItem (2);
else if (proxyType == QString ("SOCKS5"))
cbProxyType->setCurrentItem (3);
leProxyName->setText (account()->pluginData (m_protocol, "ProxyName"));
spbProxyPort->setValue (account()->pluginData (m_protocol, "ProxyPort").toInt ());
cbProxyAuth->setChecked (account()->pluginData (m_protocol, "ProxyAuth") == QString::fromLatin1 ("true"));
leProxyUser->setText (account()->pluginData (m_protocol, "ProxyUser"));
leProxyPass->setText (account()->pluginData (m_protocol, "ProxyPass"));
mAutoConnect->setChecked (account()->autoLogin());
revalidateJID = false;
}
KopeteAccount *JabberEditAccountWidget::apply ()
{
kdDebug (14180) << "JabberEditAccount::apply()" << endl;
if(revalidateJID)
validateJID();
if (!account())
{
setAccount(new JabberAccount (m_protocol, mID->text ()));
}
if(account()->isConnected())
{
KMessageBox::information(this,
i18n("The changes you just made will take effect next time you log in with Jabber."),
i18n("Jabber Changes During Online Jabber Session"));
}
this->writeConfig ();
return account();
}
void JabberEditAccountWidget::writeConfig ()
{
// FIXME: The call below represents a flaw in the current Kopete API.
// Once the API is cleaned up, this will most likely require a change.
//account()->setAccountId(mID->text());
account()->setPluginData (m_protocol, "Server", mServer->text ());
account()->setPluginData (m_protocol, "Resource", mResource->text ());
account()->setPluginData (m_protocol, "Port", QString::number (mPort->value ()));
if (chkUseSSL->isChecked ())
account()->setPluginData (m_protocol, "UseSSL", "true");
else
account()->setPluginData (m_protocol, "UseSSL", "false");
if (chkRemPass->isChecked ())
{
account()->setPluginData (m_protocol, "RemPass", "true");
account()->setPassword (mPass->text ());
}
else
{
account()->setPluginData (m_protocol, "RemPass", "false");
account()->setPassword (NULL);
}
account()->setAutoLogin(mAutoConnect->isChecked());
switch (cmbAuth->currentItem ())
{
case 0:
account()->setPluginData (m_protocol, "AuthType", "digest");
break;
case 1:
account()->setPluginData (m_protocol, "AuthType", "plain");
break;
default: // this case should never happen, just
// implemented for safety
account()->setPluginData (m_protocol, "AuthType", "digest");
break;
}
switch (cbProxyType->currentItem ())
{
case 0:
account()->setPluginData (m_protocol, "ProxyType", "None");
break;
case 1:
account()->setPluginData (m_protocol, "ProxyType", "HTTPS");
break;
case 2:
account()->setPluginData (m_protocol, "ProxyType", "SOCKS4");
break;
case 3:
account()->setPluginData (m_protocol, "ProxyType", "SOCKS5");
break;
default: // this case should never happen, just
// implemented for safety
account()->setPluginData (m_protocol, "ProxyType", "None");
break;
}
account()->setPluginData (m_protocol, "ProxyName", leProxyName->text ());
account()->setPluginData (m_protocol, "ProxyPort", QString::number (spbProxyPort->value ()));
if (cbProxyAuth->isChecked ())
account()->setPluginData (m_protocol, "ProxyAuth", "true");
else
account()->setPluginData (m_protocol, "ProxyAuth", "false");
account()->setPluginData (m_protocol, "ProxyUser", leProxyUser->text ());
account()->setPluginData (m_protocol, "ProxyPass", leProxyPass->text ());
//config->sync();
settings_changed = false;
}
bool JabberEditAccountWidget::validateData ()
{
if(!mID->text().contains('@'))
{
KMessageBox::sorry(this, i18n("The Jabber ID you have chosen is invalid. "
"Please make sure it is in the form [email protected]."),
i18n("Invalid Jabber ID"));
return false;
}
return true;
}
void JabberEditAccountWidget::validateJID ()
{
QString server = mID->text().section('@', 1);
if(mServer->text().isEmpty())
{
// the user didn't specify a server, automatically choose one
mServer->setText(server);
}
else
{
if(mServer->text() != server)
{
// the user has chosen a different server than his JID
// suggests, display a warning
int result = KMessageBox::warningYesNo (this, i18n("You have chosen a different Jabber server than your Jabber "
"ID suggests. Do you want me to change your server setting? Selecting \"Yes\" "
"will change your Jabber server to \"%1\" as indicated by your Jabber ID. "
"Selecting \"No\" leave your current settings.").arg(server),
i18n("Are you sure about your server name?"));
if(result == KMessageBox::Yes)
mServer->setText(server);
}
}
}
void JabberEditAccountWidget::configChanged ()
{
settings_changed = true;
}
void JabberEditAccountWidget::setJIDValidation ()
{
revalidateJID = true;
if((account() != 0L) && (account ()->pluginData(m_protocol, "Server") == mServer->text ()))
revalidateJID = false;
}
void JabberEditAccountWidget::registerClicked ()
{
if(!validateData())
return;
if (!account())
{
setAccount(new JabberAccount (m_protocol, mID->text ()));
}
this->writeConfig ();
static_cast < JabberAccount * >(account())->registerUser ();
}
void JabberEditAccountWidget::sslToggled (bool value)
{
if (value && (mPort->value() == 5222))
mPort->stepUp ();
else
if(!value && (mPort->value() == 5223))
mPort->stepDown ();
}
#include "jabbereditaccountwidget.moc"
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>Fix bug 69396 by rewording the last string.<commit_after>
/***************************************************************************
jabberaccountwidget.h - Account widget for Jabber
-------------------
begin : Mon Dec 9 2002
copyright : (C) 2002-2003 by Till Gerken <[email protected]>
Based on code by Olivier Goffart <[email protected]>
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include <kdebug.h>
#include <qlineedit.h>
#include <qcheckbox.h>
#include <qpushbutton.h>
#include <qspinbox.h>
#include <qcombobox.h>
#include <kmessagebox.h>
#include <klocale.h>
#include "jabbereditaccountwidget.h"
JabberEditAccountWidget::JabberEditAccountWidget (JabberProtocol * proto, JabberAccount * ident, QWidget * parent, const char *name)
: DlgJabberEditAccountWidget (parent, name), KopeteEditAccountWidget (ident)
{
m_protocol = proto;
connect (mID, SIGNAL (textChanged (const QString &)), this, SLOT (configChanged ()));
connect (mPass, SIGNAL (textChanged (const QString &)), this, SLOT (configChanged ()));
connect (mResource, SIGNAL (textChanged (const QString &)), this, SLOT (configChanged ()));
connect (mServer, SIGNAL (textChanged (const QString &)), this, SLOT (configChanged ()));
connect (mPort, SIGNAL (valueChanged (int)), this, SLOT (configChanged ()));
connect (mAutoConnect, SIGNAL (toggled (bool)), this, SLOT (configChanged ()));
connect (chkUseSSL, SIGNAL (toggled (bool)), this, SLOT (configChanged ()));
connect (chkRemPass, SIGNAL (toggled (bool)), this, SLOT (configChanged ()));
// Chat TAB
connect (cmbAuth, SIGNAL (activated (int)), this, SLOT (configChanged ()));
connect (cbProxyType, SIGNAL (activated (int)), this, SLOT (configChanged ()));
connect (leProxyName, SIGNAL (textChanged (const QString &)), this, SLOT (configChanged ()));
connect (spbProxyPort, SIGNAL (valueChanged (int)), this, SLOT (configChanged ()));
connect (cbProxyAuth, SIGNAL (toggled (bool)), this, SLOT (configChanged ()));
connect (leProxyUser, SIGNAL (textChanged (const QString &)), this, SLOT (configChanged ()));
connect (leProxyPass, SIGNAL (textChanged (const QString &)), this, SLOT (configChanged ()));
connect (mID, SIGNAL (textChanged (const QString &)), this, SLOT (setJIDValidation ()));
connect (mServer, SIGNAL (textChanged (const QString &)), this, SLOT (setJIDValidation ()));
connect (btnRegister, SIGNAL (clicked ()), this, SLOT (registerClicked ()));
connect (chkUseSSL, SIGNAL (toggled (bool)), this, SLOT (sslToggled (bool)));
if (account())
{
this->reopen ();
}
}
JabberEditAccountWidget::~JabberEditAccountWidget ()
{
}
void JabberEditAccountWidget::reopen ()
{
// FIXME: this is temporary until Kopete supports accound ID changes!
mID->setDisabled(true);
mID->setText (account()->accountId ());
mPass->setText (account()->password ());
mResource->setText (account()->pluginData (m_protocol, "Resource"));
mServer->setText (account()->pluginData (m_protocol, "Server"));
if (account()->pluginData (m_protocol, "UseSSL") == "true")
chkUseSSL->setChecked (true);
mPort->setValue (account()->pluginData (m_protocol, "Port").toInt ());
if (account()->pluginData (m_protocol, "RemPass") == "true")
chkRemPass->setChecked (true);
QString auth = account()->pluginData (m_protocol, "AuthType");
cmbAuth->setCurrentItem (0);
if (auth == QString ("plain"))
cmbAuth->setCurrentItem (1);
QString proxyType = account()->pluginData (m_protocol, "ProxyType");
cbProxyType->setCurrentItem (0);
if (proxyType == QString ("HTTPS"))
cbProxyType->setCurrentItem (1);
else if (proxyType == QString ("SOCKS4"))
cbProxyType->setCurrentItem (2);
else if (proxyType == QString ("SOCKS5"))
cbProxyType->setCurrentItem (3);
leProxyName->setText (account()->pluginData (m_protocol, "ProxyName"));
spbProxyPort->setValue (account()->pluginData (m_protocol, "ProxyPort").toInt ());
cbProxyAuth->setChecked (account()->pluginData (m_protocol, "ProxyAuth") == QString::fromLatin1 ("true"));
leProxyUser->setText (account()->pluginData (m_protocol, "ProxyUser"));
leProxyPass->setText (account()->pluginData (m_protocol, "ProxyPass"));
mAutoConnect->setChecked (account()->autoLogin());
revalidateJID = false;
}
KopeteAccount *JabberEditAccountWidget::apply ()
{
kdDebug (14180) << "JabberEditAccount::apply()" << endl;
if(revalidateJID)
validateJID();
if (!account())
{
setAccount(new JabberAccount (m_protocol, mID->text ()));
}
if(account()->isConnected())
{
KMessageBox::information(this,
i18n("The changes you just made will take effect next time you log in with Jabber."),
i18n("Jabber Changes During Online Jabber Session"));
}
this->writeConfig ();
return account();
}
void JabberEditAccountWidget::writeConfig ()
{
// FIXME: The call below represents a flaw in the current Kopete API.
// Once the API is cleaned up, this will most likely require a change.
//account()->setAccountId(mID->text());
account()->setPluginData (m_protocol, "Server", mServer->text ());
account()->setPluginData (m_protocol, "Resource", mResource->text ());
account()->setPluginData (m_protocol, "Port", QString::number (mPort->value ()));
if (chkUseSSL->isChecked ())
account()->setPluginData (m_protocol, "UseSSL", "true");
else
account()->setPluginData (m_protocol, "UseSSL", "false");
if (chkRemPass->isChecked ())
{
account()->setPluginData (m_protocol, "RemPass", "true");
account()->setPassword (mPass->text ());
}
else
{
account()->setPluginData (m_protocol, "RemPass", "false");
account()->setPassword (NULL);
}
account()->setAutoLogin(mAutoConnect->isChecked());
switch (cmbAuth->currentItem ())
{
case 0:
account()->setPluginData (m_protocol, "AuthType", "digest");
break;
case 1:
account()->setPluginData (m_protocol, "AuthType", "plain");
break;
default: // this case should never happen, just
// implemented for safety
account()->setPluginData (m_protocol, "AuthType", "digest");
break;
}
switch (cbProxyType->currentItem ())
{
case 0:
account()->setPluginData (m_protocol, "ProxyType", "None");
break;
case 1:
account()->setPluginData (m_protocol, "ProxyType", "HTTPS");
break;
case 2:
account()->setPluginData (m_protocol, "ProxyType", "SOCKS4");
break;
case 3:
account()->setPluginData (m_protocol, "ProxyType", "SOCKS5");
break;
default: // this case should never happen, just
// implemented for safety
account()->setPluginData (m_protocol, "ProxyType", "None");
break;
}
account()->setPluginData (m_protocol, "ProxyName", leProxyName->text ());
account()->setPluginData (m_protocol, "ProxyPort", QString::number (spbProxyPort->value ()));
if (cbProxyAuth->isChecked ())
account()->setPluginData (m_protocol, "ProxyAuth", "true");
else
account()->setPluginData (m_protocol, "ProxyAuth", "false");
account()->setPluginData (m_protocol, "ProxyUser", leProxyUser->text ());
account()->setPluginData (m_protocol, "ProxyPass", leProxyPass->text ());
//config->sync();
settings_changed = false;
}
bool JabberEditAccountWidget::validateData ()
{
if(!mID->text().contains('@'))
{
KMessageBox::sorry(this, i18n("The Jabber ID you have chosen is invalid. "
"Please make sure it is in the form [email protected]."),
i18n("Invalid Jabber ID"));
return false;
}
return true;
}
void JabberEditAccountWidget::validateJID ()
{
QString server = mID->text().section('@', 1);
if(mServer->text().isEmpty())
{
// the user didn't specify a server, automatically choose one
mServer->setText(server);
}
else
{
if(mServer->text() != server)
{
// the user has chosen a different server than his JID
// suggests, display a warning
int result = KMessageBox::warningYesNo (this, i18n("You have chosen a different Jabber server than your Jabber "
"ID suggests. Do you want me to change your server setting? Selecting \"Yes\" "
"will change your Jabber server to \"%1\" as indicated by your Jabber ID. "
"Selecting \"No\" will keep your current settings.").arg(server),
i18n("Are you sure about your server name?"));
if(result == KMessageBox::Yes)
mServer->setText(server);
}
}
}
void JabberEditAccountWidget::configChanged ()
{
settings_changed = true;
}
void JabberEditAccountWidget::setJIDValidation ()
{
revalidateJID = true;
if((account() != 0L) && (account ()->pluginData(m_protocol, "Server") == mServer->text ()))
revalidateJID = false;
}
void JabberEditAccountWidget::registerClicked ()
{
if(!validateData())
return;
if (!account())
{
setAccount(new JabberAccount (m_protocol, mID->text ()));
}
this->writeConfig ();
static_cast < JabberAccount * >(account())->registerUser ();
}
void JabberEditAccountWidget::sslToggled (bool value)
{
if (value && (mPort->value() == 5222))
mPort->stepUp ();
else
if(!value && (mPort->value() == 5223))
mPort->stepDown ();
}
#include "jabbereditaccountwidget.moc"
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: request.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 03:53:51 $
*
* 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 CONFIGMGR_BACKEND_REQUEST_HXX_
#define CONFIGMGR_BACKEND_REQUEST_HXX_
#ifndef CONFIGMGR_MISC_REQUESTOPTIONS_HXX_
#include "requestoptions.hxx"
#endif
#ifndef CONFIGMGR_BACKEND_REQUESTTYPES_HXX_
#include "requesttypes.hxx"
#endif
#ifndef CONFIGMGR_CONFIGPATH_HXX_
#include "configpath.hxx"
#endif
namespace configmgr
{
// ---------------------------------------------------------------------------
namespace backend
{
// ---------------------------------------------------------------------------
using configuration::AbsolutePath;
using configuration::Name;
// ---------------------------------------------------------------------------
class NodeRequest
{
AbsolutePath m_aNodePath;
RequestOptions m_aOptions;
public:
NodeRequest(AbsolutePath const& _aNodePath, RequestOptions const & _aOptions)
: m_aNodePath(_aNodePath)
, m_aOptions(_aOptions)
{
}
AbsolutePath const & getPath() const { return m_aNodePath; }
RequestOptions const & getOptions() const { return m_aOptions; }
};
// ---------------------------------------------------------------------------
class ComponentRequest
{
Name m_aComponentName;
RequestOptions m_aOptions;
bool m_bForcedReload;
public:
ComponentRequest(Name const& _aComponentName, RequestOptions const & _aOptions)
: m_aComponentName(_aComponentName)
, m_aOptions(_aOptions)
, m_bForcedReload(false)
{
}
Name const & getComponentName() const { return m_aComponentName; }
RequestOptions const & getOptions() const { return m_aOptions; }
bool isForcingReload() const { return m_bForcedReload; }
void forceReload(bool _bForce = true) { m_bForcedReload = _bForce; }
};
// ---------------------------------------------------------------------------
class TemplateRequest
{
Name m_aComponentName;
Name m_aTemplateName;
public:
static
TemplateRequest forComponent(Name const & _aComponentName)
{
return TemplateRequest( Name(), _aComponentName);
}
explicit
TemplateRequest(Name const & _aTemplateName, Name const & _aComponentName)
: m_aComponentName(_aComponentName)
, m_aTemplateName(_aTemplateName)
{}
bool isComponentRequest() const { return m_aTemplateName.isEmpty(); }
Name getTemplateName() const { return m_aTemplateName; }
Name getComponentName() const { return m_aComponentName; }
static RequestOptions getOptions()
{ return RequestOptions::forAllLocales(); }
};
inline ComponentRequest getComponentRequest(TemplateRequest const & _aTR)
{ return ComponentRequest(_aTR.getComponentName(), _aTR.getOptions()); }
// ---------------------------------------------------------------------------
class UpdateRequest
{
typedef rtl::OUString RequestId;
ConstUpdateInstance m_aUpdate;
RequestOptions m_aOptions;
RequestId m_aRQID;
public:
explicit
UpdateRequest( UpdateInstance const & _aUpdate,
RequestOptions const & _aOptions)
: m_aUpdate(_aUpdate)
, m_aOptions(_aOptions)
{}
explicit
UpdateRequest( ConstUpdateInstance const & _aUpdate,
RequestOptions const & _aOptions)
: m_aUpdate(_aUpdate)
, m_aOptions(_aOptions)
{}
explicit
UpdateRequest( ConstUpdateInstance::Data _aUpdateData,
AbsolutePath const & _aRootpath,
RequestOptions const & _aOptions)
: m_aUpdate(_aUpdateData, _aRootpath)
, m_aOptions(_aOptions)
{}
bool isSyncRequired() const { return !m_aOptions.isAsyncEnabled(); }
RequestOptions const & getOptions() const { return m_aOptions; }
NodePath const & getUpdateRoot() const { return m_aUpdate.root(); }
ConstUpdateInstance const & getUpdate() const { return m_aUpdate; }
ConstUpdateInstance::Data getUpdateData() const { return m_aUpdate.data(); }
void setRequestId(RequestId const & _aRQID) { m_aRQID = _aRQID; }
RequestId getRequestId() const { return m_aRQID; }
};
inline ComponentRequest getComponentRequest(UpdateRequest const & _aUR)
{ return ComponentRequest(_aUR.getUpdateRoot().getModuleName(), _aUR.getOptions()); }
// ---------------------------------------------------------------------------
} // namespace
// ---------------------------------------------------------------------------
} // namespace
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.5.130); FILE MERGED 2008/04/01 12:27:25 thb 1.5.130.2: #i85898# Stripping all external header guards 2008/03/31 12:22:44 rt 1.5.130.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: request.hxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef CONFIGMGR_BACKEND_REQUEST_HXX_
#define CONFIGMGR_BACKEND_REQUEST_HXX_
#include "requestoptions.hxx"
#include "requesttypes.hxx"
#include "configpath.hxx"
namespace configmgr
{
// ---------------------------------------------------------------------------
namespace backend
{
// ---------------------------------------------------------------------------
using configuration::AbsolutePath;
using configuration::Name;
// ---------------------------------------------------------------------------
class NodeRequest
{
AbsolutePath m_aNodePath;
RequestOptions m_aOptions;
public:
NodeRequest(AbsolutePath const& _aNodePath, RequestOptions const & _aOptions)
: m_aNodePath(_aNodePath)
, m_aOptions(_aOptions)
{
}
AbsolutePath const & getPath() const { return m_aNodePath; }
RequestOptions const & getOptions() const { return m_aOptions; }
};
// ---------------------------------------------------------------------------
class ComponentRequest
{
Name m_aComponentName;
RequestOptions m_aOptions;
bool m_bForcedReload;
public:
ComponentRequest(Name const& _aComponentName, RequestOptions const & _aOptions)
: m_aComponentName(_aComponentName)
, m_aOptions(_aOptions)
, m_bForcedReload(false)
{
}
Name const & getComponentName() const { return m_aComponentName; }
RequestOptions const & getOptions() const { return m_aOptions; }
bool isForcingReload() const { return m_bForcedReload; }
void forceReload(bool _bForce = true) { m_bForcedReload = _bForce; }
};
// ---------------------------------------------------------------------------
class TemplateRequest
{
Name m_aComponentName;
Name m_aTemplateName;
public:
static
TemplateRequest forComponent(Name const & _aComponentName)
{
return TemplateRequest( Name(), _aComponentName);
}
explicit
TemplateRequest(Name const & _aTemplateName, Name const & _aComponentName)
: m_aComponentName(_aComponentName)
, m_aTemplateName(_aTemplateName)
{}
bool isComponentRequest() const { return m_aTemplateName.isEmpty(); }
Name getTemplateName() const { return m_aTemplateName; }
Name getComponentName() const { return m_aComponentName; }
static RequestOptions getOptions()
{ return RequestOptions::forAllLocales(); }
};
inline ComponentRequest getComponentRequest(TemplateRequest const & _aTR)
{ return ComponentRequest(_aTR.getComponentName(), _aTR.getOptions()); }
// ---------------------------------------------------------------------------
class UpdateRequest
{
typedef rtl::OUString RequestId;
ConstUpdateInstance m_aUpdate;
RequestOptions m_aOptions;
RequestId m_aRQID;
public:
explicit
UpdateRequest( UpdateInstance const & _aUpdate,
RequestOptions const & _aOptions)
: m_aUpdate(_aUpdate)
, m_aOptions(_aOptions)
{}
explicit
UpdateRequest( ConstUpdateInstance const & _aUpdate,
RequestOptions const & _aOptions)
: m_aUpdate(_aUpdate)
, m_aOptions(_aOptions)
{}
explicit
UpdateRequest( ConstUpdateInstance::Data _aUpdateData,
AbsolutePath const & _aRootpath,
RequestOptions const & _aOptions)
: m_aUpdate(_aUpdateData, _aRootpath)
, m_aOptions(_aOptions)
{}
bool isSyncRequired() const { return !m_aOptions.isAsyncEnabled(); }
RequestOptions const & getOptions() const { return m_aOptions; }
NodePath const & getUpdateRoot() const { return m_aUpdate.root(); }
ConstUpdateInstance const & getUpdate() const { return m_aUpdate; }
ConstUpdateInstance::Data getUpdateData() const { return m_aUpdate.data(); }
void setRequestId(RequestId const & _aRQID) { m_aRQID = _aRQID; }
RequestId getRequestId() const { return m_aRQID; }
};
inline ComponentRequest getComponentRequest(UpdateRequest const & _aUR)
{ return ComponentRequest(_aUR.getUpdateRoot().getModuleName(), _aUR.getOptions()); }
// ---------------------------------------------------------------------------
} // namespace
// ---------------------------------------------------------------------------
} // namespace
#endif
<|endoftext|> |
<commit_before>/*
* Run a CGI script.
*
* author: Max Kellermann <[email protected]>
*/
#include "cgi_launch.hxx"
#include "cgi_address.hxx"
#include "istream.h"
#include "fork.h"
#include "strutil.h"
#include "strmap.h"
#include "sigutil.h"
#include "product.h"
#include "exec.hxx"
#include <daemon/log.h>
#include <sys/wait.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
static void gcc_noreturn
cgi_run(const struct jail_params *jail,
const char *interpreter, const char *action,
const char *path,
const char *const*args, unsigned n_args,
http_method_t method, const char *uri,
const char *script_name, const char *path_info,
const char *query_string,
const char *document_root,
const char *remote_addr,
struct strmap *headers,
off_t content_length,
const char *const env[], unsigned num_env)
{
const struct strmap_pair *pair;
const char *arg = nullptr;
assert(path != nullptr);
assert(http_method_is_valid(method));
assert(uri != nullptr);
if (script_name == nullptr)
script_name = "";
if (path_info == nullptr)
path_info = "";
if (query_string == nullptr)
query_string = "";
if (document_root == nullptr)
document_root = "/var/www";
clearenv();
for (unsigned j = 0; j < num_env; ++j) {
union {
const char *in;
char *out;
} u = {
.in = env[j],
};
putenv(u.out);
}
setenv("GATEWAY_INTERFACE", "CGI/1.1", 1);
setenv("SERVER_PROTOCOL", "HTTP/1.1", 1);
setenv("REQUEST_METHOD", http_method_to_string(method), 1);
setenv("SCRIPT_FILENAME", path, 1);
setenv("PATH_TRANSLATED", path, 1);
setenv("REQUEST_URI", uri, 1);
setenv("SCRIPT_NAME", script_name, 1);
setenv("PATH_INFO", path_info, 1);
setenv("QUERY_STRING", query_string, 1);
setenv("DOCUMENT_ROOT", document_root, 1);
setenv("SERVER_SOFTWARE", PRODUCT_TOKEN, 1);
if (remote_addr != nullptr)
setenv("REMOTE_ADDR", remote_addr, 1);
if (jail != nullptr && jail->enabled) {
setenv("JAILCGI_FILENAME", path, 1);
path = "/usr/lib/cm4all/jailcgi/bin/wrapper";
if (jail->home_directory != nullptr)
setenv("JETSERV_HOME", jail->home_directory, 1);
if (interpreter != nullptr)
setenv("JAILCGI_INTERPRETER", interpreter, 1);
if (action != nullptr)
setenv("JAILCGI_ACTION", action, 1);
} else {
if (action != nullptr)
path = action;
if (interpreter != nullptr) {
arg = path;
path = interpreter;
}
}
const char *content_type = nullptr;
if (headers != nullptr) {
strmap_rewind(headers);
while ((pair = strmap_next(headers)) != nullptr) {
if (strcmp(pair->key, "content-type") == 0) {
content_type = pair->value;
continue;
}
char buffer[512] = "HTTP_";
size_t i;
for (i = 0; 5 + i < sizeof(buffer) - 1 && pair->key[i] != 0; ++i) {
if (char_is_minuscule_letter(pair->key[i]))
buffer[5 + i] = (char)(pair->key[i] - 'a' + 'A');
else if (char_is_capital_letter(pair->key[i]) ||
char_is_digit(pair->key[i]))
buffer[5 + i] = pair->key[i];
else
buffer[5 + i] = '_';
}
buffer[5 + i] = 0;
setenv(buffer, pair->value, 1);
}
}
if (content_type != nullptr)
setenv("CONTENT_TYPE", content_type, 1);
if (content_length >= 0) {
char value[32];
snprintf(value, sizeof(value), "%llu",
(unsigned long long)content_length);
setenv("CONTENT_LENGTH", value, 1);
}
Exec e;
e.Append(path);
for (unsigned i = 0; i < n_args; ++i)
e.Append(args[i]);
if (arg != nullptr)
e.Append(arg);
e.DoExec();
}
struct cgi_ctx {
http_method_t method;
const struct cgi_address *address;
const char *uri;
off_t available;
const char *remote_addr;
struct strmap *headers;
sigset_t signals;
};
static int
cgi_fn(void *ctx)
{
struct cgi_ctx *c = (struct cgi_ctx *)ctx;
const struct cgi_address *address = c->address;
install_default_signal_handlers();
leave_signal_section(&c->signals);
address->options.SetupStderr();
namespace_options_setup(&address->options.ns);
rlimit_options_apply(&address->options.rlimits);
cgi_run(&address->options.jail,
address->interpreter, address->action,
address->path,
address->args.values, address->args.n,
c->method, c->uri,
address->script_name, address->path_info,
address->query_string, address->document_root,
c->remote_addr,
c->headers, c->available,
address->env.values, address->env.n);
}
static void
cgi_child_callback(int status, void *ctx gcc_unused)
{
int exit_status = WEXITSTATUS(status);
if (WIFSIGNALED(status)) {
int level = 1;
if (!WCOREDUMP(status) && WTERMSIG(status) == SIGTERM)
level = 4;
daemon_log(level, "CGI died from signal %d%s\n",
WTERMSIG(status),
WCOREDUMP(status) ? " (core dumped)" : "");
} else if (exit_status != 0)
daemon_log(1, "CGI exited with status %d\n",
exit_status);
}
static const char *
cgi_address_name(const struct cgi_address *address)
{
if (address->interpreter != nullptr)
return address->interpreter;
if (address->action != nullptr)
return address->action;
if (address->path != nullptr)
return address->path;
return "CGI";
}
struct istream *
cgi_launch(struct pool *pool, http_method_t method,
const struct cgi_address *address,
const char *remote_addr,
struct strmap *headers, struct istream *body,
GError **error_r)
{
struct cgi_ctx c = {
.method = method,
.address = address,
.uri = address->GetURI(pool),
.available = body != nullptr ? istream_available(body, false) : -1,
.remote_addr = remote_addr,
.headers = headers,
};
const int clone_flags =
namespace_options_clone_flags(&address->options.ns, SIGCHLD);
/* avoid race condition due to libevent signal handler in child
process */
enter_signal_section(&c.signals);
struct istream *input;
pid_t pid = beng_fork(pool, cgi_address_name(address), body, &input,
clone_flags,
cgi_fn, &c,
cgi_child_callback, nullptr, error_r);
if (pid < 0) {
leave_signal_section(&c.signals);
if (body != nullptr)
/* beng_fork() left the request body open - free this
resource, because our caller always assume that we have
consumed it */
istream_close_unused(body);
return nullptr;
}
leave_signal_section(&c.signals);
return input;
}
<commit_msg>cgi_launch: use ConstBuffer<commit_after>/*
* Run a CGI script.
*
* author: Max Kellermann <[email protected]>
*/
#include "cgi_launch.hxx"
#include "cgi_address.hxx"
#include "istream.h"
#include "fork.h"
#include "strutil.h"
#include "strmap.h"
#include "sigutil.h"
#include "product.h"
#include "exec.hxx"
#include "util/ConstBuffer.hxx"
#include <daemon/log.h>
#include <sys/wait.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
static void gcc_noreturn
cgi_run(const struct jail_params *jail,
const char *interpreter, const char *action,
const char *path,
ConstBuffer<const char *> args,
http_method_t method, const char *uri,
const char *script_name, const char *path_info,
const char *query_string,
const char *document_root,
const char *remote_addr,
struct strmap *headers,
off_t content_length,
ConstBuffer<const char *> env)
{
const struct strmap_pair *pair;
const char *arg = nullptr;
assert(path != nullptr);
assert(http_method_is_valid(method));
assert(uri != nullptr);
if (script_name == nullptr)
script_name = "";
if (path_info == nullptr)
path_info = "";
if (query_string == nullptr)
query_string = "";
if (document_root == nullptr)
document_root = "/var/www";
clearenv();
for (auto j : env) {
union {
const char *in;
char *out;
} u = {
.in = j,
};
putenv(u.out);
}
setenv("GATEWAY_INTERFACE", "CGI/1.1", 1);
setenv("SERVER_PROTOCOL", "HTTP/1.1", 1);
setenv("REQUEST_METHOD", http_method_to_string(method), 1);
setenv("SCRIPT_FILENAME", path, 1);
setenv("PATH_TRANSLATED", path, 1);
setenv("REQUEST_URI", uri, 1);
setenv("SCRIPT_NAME", script_name, 1);
setenv("PATH_INFO", path_info, 1);
setenv("QUERY_STRING", query_string, 1);
setenv("DOCUMENT_ROOT", document_root, 1);
setenv("SERVER_SOFTWARE", PRODUCT_TOKEN, 1);
if (remote_addr != nullptr)
setenv("REMOTE_ADDR", remote_addr, 1);
if (jail != nullptr && jail->enabled) {
setenv("JAILCGI_FILENAME", path, 1);
path = "/usr/lib/cm4all/jailcgi/bin/wrapper";
if (jail->home_directory != nullptr)
setenv("JETSERV_HOME", jail->home_directory, 1);
if (interpreter != nullptr)
setenv("JAILCGI_INTERPRETER", interpreter, 1);
if (action != nullptr)
setenv("JAILCGI_ACTION", action, 1);
} else {
if (action != nullptr)
path = action;
if (interpreter != nullptr) {
arg = path;
path = interpreter;
}
}
const char *content_type = nullptr;
if (headers != nullptr) {
strmap_rewind(headers);
while ((pair = strmap_next(headers)) != nullptr) {
if (strcmp(pair->key, "content-type") == 0) {
content_type = pair->value;
continue;
}
char buffer[512] = "HTTP_";
size_t i;
for (i = 0; 5 + i < sizeof(buffer) - 1 && pair->key[i] != 0; ++i) {
if (char_is_minuscule_letter(pair->key[i]))
buffer[5 + i] = (char)(pair->key[i] - 'a' + 'A');
else if (char_is_capital_letter(pair->key[i]) ||
char_is_digit(pair->key[i]))
buffer[5 + i] = pair->key[i];
else
buffer[5 + i] = '_';
}
buffer[5 + i] = 0;
setenv(buffer, pair->value, 1);
}
}
if (content_type != nullptr)
setenv("CONTENT_TYPE", content_type, 1);
if (content_length >= 0) {
char value[32];
snprintf(value, sizeof(value), "%llu",
(unsigned long long)content_length);
setenv("CONTENT_LENGTH", value, 1);
}
Exec e;
e.Append(path);
for (auto i : args)
e.Append(i);
if (arg != nullptr)
e.Append(arg);
e.DoExec();
}
struct cgi_ctx {
http_method_t method;
const struct cgi_address *address;
const char *uri;
off_t available;
const char *remote_addr;
struct strmap *headers;
sigset_t signals;
};
static int
cgi_fn(void *ctx)
{
struct cgi_ctx *c = (struct cgi_ctx *)ctx;
const struct cgi_address *address = c->address;
install_default_signal_handlers();
leave_signal_section(&c->signals);
address->options.SetupStderr();
namespace_options_setup(&address->options.ns);
rlimit_options_apply(&address->options.rlimits);
cgi_run(&address->options.jail,
address->interpreter, address->action,
address->path,
{ address->args.values, address->args.n },
c->method, c->uri,
address->script_name, address->path_info,
address->query_string, address->document_root,
c->remote_addr,
c->headers, c->available,
{ address->env.values, address->env.n });
}
static void
cgi_child_callback(int status, void *ctx gcc_unused)
{
int exit_status = WEXITSTATUS(status);
if (WIFSIGNALED(status)) {
int level = 1;
if (!WCOREDUMP(status) && WTERMSIG(status) == SIGTERM)
level = 4;
daemon_log(level, "CGI died from signal %d%s\n",
WTERMSIG(status),
WCOREDUMP(status) ? " (core dumped)" : "");
} else if (exit_status != 0)
daemon_log(1, "CGI exited with status %d\n",
exit_status);
}
static const char *
cgi_address_name(const struct cgi_address *address)
{
if (address->interpreter != nullptr)
return address->interpreter;
if (address->action != nullptr)
return address->action;
if (address->path != nullptr)
return address->path;
return "CGI";
}
struct istream *
cgi_launch(struct pool *pool, http_method_t method,
const struct cgi_address *address,
const char *remote_addr,
struct strmap *headers, struct istream *body,
GError **error_r)
{
struct cgi_ctx c = {
.method = method,
.address = address,
.uri = address->GetURI(pool),
.available = body != nullptr ? istream_available(body, false) : -1,
.remote_addr = remote_addr,
.headers = headers,
};
const int clone_flags =
namespace_options_clone_flags(&address->options.ns, SIGCHLD);
/* avoid race condition due to libevent signal handler in child
process */
enter_signal_section(&c.signals);
struct istream *input;
pid_t pid = beng_fork(pool, cgi_address_name(address), body, &input,
clone_flags,
cgi_fn, &c,
cgi_child_callback, nullptr, error_r);
if (pid < 0) {
leave_signal_section(&c.signals);
if (body != nullptr)
/* beng_fork() left the request body open - free this
resource, because our caller always assume that we have
consumed it */
istream_close_unused(body);
return nullptr;
}
leave_signal_section(&c.signals);
return input;
}
<|endoftext|> |
<commit_before>// Copyright 2010-2011 Google
// 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 "base/integral_types.h"
#include "base/logging.h"
#include "base/concise_iterator.h"
#include "base/map-util.h"
#include "constraint_solver/constraint_solveri.h"
#include "util/bitset.h"
namespace operations_research {
// ---------- SmallRevBitSet ----------
SmallRevBitSet::SmallRevBitSet(int64 size) : bits_(0LL), stamp_(0) {
DCHECK_GT(size, 0);
DCHECK_LE(size, 64);
}
void SmallRevBitSet::SetToOne(Solver* const s, int64 pos) {
DCHECK_GE(pos, 0);
const uint64 current_stamp = s->stamp();
if (stamp_ < current_stamp) {
stamp_ = current_stamp;
s->SaveValue(&bits_);
}
bits_ |= OneBit64(pos);
}
void SmallRevBitSet::SetToZero(Solver* const s, int64 pos) {
DCHECK_GE(pos, 0);
const uint64 current_stamp = s->stamp();
if (stamp_ < current_stamp) {
stamp_ = current_stamp;
s->SaveValue(&bits_);
}
bits_ &= ~OneBit64(pos);
}
int64 SmallRevBitSet::Cardinality() const {
return BitCount64(bits_);
}
int64 SmallRevBitSet::GetFirstOne() const {
return LeastSignificantBitPosition64(bits_);
}
// ---------- RevBitSet ----------
RevBitSet::RevBitSet(int64 size)
: rows_(1), columns_(size), length_(BitLength64(size)),
bits_(new uint64[length_]), stamps_(new uint64[length_]) {
DCHECK_GE(size, 1);
memset(bits_, 0, sizeof(*bits_) * length_);
memset(stamps_, 0, sizeof(*stamps_) * length_);
}
RevBitSet::RevBitSet(int64 rows, int64 columns)
: rows_(rows), columns_(columns), length_(BitLength64(rows * columns)),
bits_(new uint64[length_]), stamps_(new uint64[length_]) {
DCHECK_GE(rows, 1);
DCHECK_GE(columns, 1);
memset(bits_, 0, sizeof(*bits_) * length_);
memset(stamps_, 0, sizeof(*stamps_) * length_);
}
RevBitSet::~RevBitSet() {
delete [] bits_;
delete [] stamps_;
}
void RevBitSet::SetToOne(Solver* const solver, int64 index) {
DCHECK_GE(index, 0);
DCHECK_LT(index, columns_ * rows_);
const int64 offset = BitOffset64(index);
const int64 pos = BitPos64(index);
if (!(bits_[offset] & OneBit64(pos))) {
const uint64 current_stamp = solver->stamp();
if (current_stamp > stamps_[offset]) {
stamps_[offset] = current_stamp;
solver->SaveValue(&bits_[offset]);
}
bits_[offset] |= OneBit64(pos);
}
}
void RevBitSet::SetToOne(Solver* const solver, int64 row, int64 column) {
DCHECK_GE(row, 0);
DCHECK_LT(row, rows_);
DCHECK_GE(column, 0);
DCHECK_LT(column, columns_);
SetToOne(solver, row * columns_ + column);
}
void RevBitSet::SetToZero(Solver* const solver, int64 index) {
DCHECK_GE(index, 0);
DCHECK_LT(index, columns_ * rows_);
const int64 offset = BitOffset64(index);
const int64 pos = BitPos64(index);
if (bits_[offset] & OneBit64(pos)) {
const uint64 current_stamp = solver->stamp();
if (current_stamp > stamps_[offset]) {
stamps_[offset] = current_stamp;
solver->SaveValue(&bits_[offset]);
}
bits_[offset] &= ~OneBit64(pos);
}
}
void RevBitSet::SetToZero(Solver* const solver, int64 row, int64 column) {
DCHECK_GE(row, 0);
DCHECK_LT(row, rows_);
DCHECK_GE(column, 0);
DCHECK_LT(column, columns_);
SetToZero(solver, row * columns_ + column);
}
bool RevBitSet::IsSet(int64 index) const {
DCHECK_GE(index, 0);
DCHECK_LT(index, columns_ * rows_);
return IsBitSet64(bits_, index);
}
int64 RevBitSet::Cardinality() const {
int64 card = 0;
for (int i = 0; i < length_; ++i) {
card += BitCount64(bits_[i]);
}
return card;
}
bool RevBitSet::IsCardinalityZero() const {
for (int i = 0; i < length_; ++i) {
if (bits_[i]) {
return false;
}
}
return true;
}
bool RevBitSet::IsCardinalityOne() const {
bool found_one = false;
for (int i = 0; i < length_; ++i) {
const uint64 partial = bits_[i];
if (partial) {
if (!(partial & (partial - 1))) {
if (found_one) {
return false;
}
found_one = true;
}
}
}
return found_one;
}
int64 RevBitSet::GetFirstBit(int start) const {
const int end = rows_ * columns_ + columns_ - 1;
return LeastSignificantBitPosition64(bits_, start, end);
}
int64 RevBitSet::Cardinality(int row) const {
DCHECK_GE(row, 0);
DCHECK_LT(row, rows_);
const int start = row * columns_;
return BitCountRange64(bits_, start, start + columns_ - 1);
}
bool RevBitSet::IsCardinalityOne(int row) const {
// TODO(user) : Optimize this one.
return Cardinality(row) == 1;
}
bool RevBitSet::IsCardinalityZero(int row) const {
const int start = row * columns_;
return IsEmptyRange64(bits_, start, start + columns_ - 1);
}
int64 RevBitSet::GetFirstBit(int row, int start) const {
DCHECK_GE(start, 0);
DCHECK_GE(row, 0);
DCHECK_LT(row, rows_);
DCHECK_LT(start, columns_);
const int beginning = row * columns_;
const int end = beginning + columns_ - 1;
int64 position = LeastSignificantBitPosition64(bits_, beginning + start, end);
if (position == -1) {
return -1;
} else {
return position - beginning;
}
}
void RevBitSet::RevClearAll(Solver* const solver) {
const uint64 current_stamp = solver->stamp();
for (int offset = 0; offset < length_; ++offset) {
if (bits_[offset]) {
if (current_stamp > stamps_[offset]) {
stamps_[offset] = current_stamp;
solver->SaveValue(&bits_[offset]);
}
bits_[offset] = GG_ULONGLONG(0);
}
}
}
// ----- PrintModelVisitor -----
class PrintModelVisitor : public ModelVisitor {
public:
PrintModelVisitor() : indent_(0) {}
virtual ~PrintModelVisitor() {}
// Header/footers.
virtual void BeginVisitModel(const string& solver_name) {
LOG(INFO) << "Model " << solver_name << " {";
Increase();
}
virtual void EndVisitModel(const string& solver_name) {
LOG(INFO) << "}";
Decrease();
CHECK_EQ(0, indent_);
}
virtual void BeginVisitConstraint(const string& type_name,
const Constraint* const constraint) {
LOG(INFO) << Spaces() << type_name;
Increase();
}
virtual void EndVisitConstraint(const string& type_name,
const Constraint* const constraint) {
Decrease();
}
virtual void BeginVisitIntegerExpression(const string& type_name,
const IntExpr* const expr) {
LOG(INFO) << Spaces() << type_name;
Increase();
}
virtual void EndVisitIntegerExpression(const string& type_name,
const IntExpr* const expr) {
Decrease();
}
virtual void VisitIntegerVariable(const IntVar* const variable,
const IntExpr* const delegate) {
if (delegate != NULL) {
delegate->Accept(this);
} else {
if (variable->Bound() && variable->name().empty()) {
LOG(INFO) << Spaces() << variable->Min();
} else {
LOG(INFO) << Spaces() << variable->DebugString();
}
}
}
// Variables.
virtual void VisitIntegerArgument(const string& arg_name, int64 value) {
LOG(INFO) << Spaces() << arg_name << ": " << value;
}
virtual void VisitIntegerArrayArgument(const string& arg_name,
const int64* const values,
int size) {
string array = "[";
for (int i = 0; i < size; ++i) {
if (i != 0) {
array.append(", ");
}
StringAppendF(&array, "%lld", values[i]);
}
array.append("]");
LOG(INFO) << Spaces() << arg_name << ": " << array;
}
virtual void VisitIntegerExpressionArgument(
const string& arg_name,
const IntExpr* const argument) {
set_prefix(StringPrintf("%s: ", arg_name.c_str()));
Increase();
argument->Accept(this);
Decrease();
}
virtual void VisitIntegerVariableArrayArgument(
const string& arg_name,
const IntVar* const * arguments,
int size) {
LOG(INFO) << Spaces() << arg_name << ": [";
Increase();
for (int i = 0; i < size; ++i) {
arguments[i]->Accept(this);
}
Decrease();
LOG(INFO) << Spaces() << "]";
}
// Visit interval argument.
virtual void VisitIntervalArgument(const string& arg_name,
const IntervalVar* const argument) {
set_prefix(StringPrintf("%s: ", arg_name.c_str()));
Increase();
argument->Accept(this);
Decrease();
}
virtual void VisitIntervalArgumentArray(const string& arg_name,
const IntervalVar* const * arguments,
int size) {
LOG(INFO) << Spaces() << arg_name << ": [";
Increase();
for (int i = 0; i < size; ++i) {
arguments[i]->Accept(this);
}
Decrease();
LOG(INFO) << Spaces() << "]";
}
private:
void Increase() {
indent_ += 2;
}
void Decrease() {
indent_ -= 2;
}
string Spaces() {
string result;
for (int i = 0; i < indent_ - 2 * (!prefix_.empty()); ++i) {
result.append(" ");
}
if (!prefix_.empty()) {
result.append(prefix_);
prefix_ = "";
}
return result;
}
void set_prefix(const string& prefix) {
prefix_ = prefix;
}
int indent_;
string prefix_;
};
ModelVisitor* Solver::MakePrintModelVisitor() {
return RevAlloc(new PrintModelVisitor);
}
// ---------- ModelStatisticsVisitor -----------
class ModelStatisticsVisitor : public ModelVisitor {
public:
ModelStatisticsVisitor()
: num_constraints_(0),
num_variables_(0),
num_expressions_(0),
num_casts_(0),
num_intervals_(0) {}
virtual ~ModelStatisticsVisitor() {}
// Begin/End visit element.
virtual void BeginVisitModel(const string& solver_name) {
// Reset statistics.
num_constraints_ = 0;
num_variables_ = 0;
num_expressions_ = 0;
num_casts_ = 0;
num_intervals_ = 0;
already_visited_.clear();
}
virtual void EndVisitModel(const string& solver_name) {
// Display statistics.
LOG(INFO) << "Model has:";
LOG(INFO) << " - " << num_constraints_ << " constraints.";
for (ConstIter<hash_map<string, int> > it(constraint_types_);
!it.at_end();
++it) {
LOG(INFO) << " * " << it->second << " " << it->first;
}
LOG(INFO) << " - " << num_variables_ << " integer variables.";
LOG(INFO) << " - " << num_expressions_ << " integer expressions.";
for (ConstIter<hash_map<string, int> > it(expression_types_);
!it.at_end();
++it) {
LOG(INFO) << " * " << it->second << " " << it->first;
}
LOG(INFO) << " - " << num_casts_ << " expressions casted into variables.";
LOG(INFO) << " - " << num_intervals_ << " interval variables.";
}
virtual void BeginVisitConstraint(const string& type_name,
const Constraint* const constraint) {
num_constraints_++;
AddConstraintType(type_name);
}
virtual void BeginVisitIntegerExpression(const string& type_name,
const IntExpr* const expr) {
AddExpressionType(type_name);
num_expressions_++;
}
virtual void VisitIntegerVariable(const IntVar* const variable,
const IntExpr* const delegate) {
num_variables_++;
Register(variable);
if (delegate) {
num_casts_++;
VisitSubArgument(delegate);
}
}
virtual void VisitIntervalVariable(const IntervalVar* const variable,
const string operation,
const IntervalVar* const delegate) {
num_intervals_++;
// TODO(user): delegate.
}
// Visit integer expression argument.
virtual void VisitIntegerExpressionArgument(
const string& arg_name,
const IntExpr* const argument) {
VisitSubArgument(argument);
}
virtual void VisitIntegerVariableArrayArgument(
const string& arg_name,
const IntVar* const * arguments,
int size) {
for (int i = 0; i < size; ++i) {
VisitSubArgument(arguments[i]);
}
}
// Visit interval argument.
virtual void VisitIntervalArgument(const string& arg_name,
const IntervalVar* const argument) {
VisitSubArgument(argument);
}
virtual void VisitIntervalArrayArgument(const string& arg_name,
const IntervalVar* const * arguments,
int size) {
for (int i = 0; i < size; ++i) {
VisitSubArgument(arguments[i]);
}
}
private:
void Register(const BaseObject* const object) {
already_visited_.insert(object);
}
bool AlreadyVisited(const BaseObject* const object) {
return ContainsKey(already_visited_, object);
}
// T should derive from BaseObject
template<typename T> void VisitSubArgument(T* object) {
if (!AlreadyVisited(object)) {
Register(object);
object->Accept(this);
}
}
void AddConstraintType(const string& constraint_type) {
constraint_types_[constraint_type]++;
}
void AddExpressionType(const string& expression_type) {
expression_types_[expression_type]++;
}
hash_map<string, int> constraint_types_;
hash_map<string, int> expression_types_;
int num_constraints_;
int num_variables_;
int num_expressions_;
int num_casts_;
int num_intervals_;
hash_set<const BaseObject*> already_visited_;
};
ModelVisitor* Solver::MakeStatisticsModelVisitor() {
return RevAlloc(new ModelStatisticsVisitor);
}
} // namespace operations_research
<commit_msg>fix bug in rev bitset<commit_after>// Copyright 2010-2011 Google
// 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 "base/integral_types.h"
#include "base/logging.h"
#include "base/concise_iterator.h"
#include "base/map-util.h"
#include "constraint_solver/constraint_solveri.h"
#include "util/bitset.h"
namespace operations_research {
// ---------- SmallRevBitSet ----------
SmallRevBitSet::SmallRevBitSet(int64 size) : bits_(0LL), stamp_(0) {
DCHECK_GT(size, 0);
DCHECK_LE(size, 64);
}
void SmallRevBitSet::SetToOne(Solver* const s, int64 pos) {
DCHECK_GE(pos, 0);
const uint64 current_stamp = s->stamp();
if (stamp_ < current_stamp) {
stamp_ = current_stamp;
s->SaveValue(&bits_);
}
bits_ |= OneBit64(pos);
}
void SmallRevBitSet::SetToZero(Solver* const s, int64 pos) {
DCHECK_GE(pos, 0);
const uint64 current_stamp = s->stamp();
if (stamp_ < current_stamp) {
stamp_ = current_stamp;
s->SaveValue(&bits_);
}
bits_ &= ~OneBit64(pos);
}
int64 SmallRevBitSet::Cardinality() const {
return BitCount64(bits_);
}
int64 SmallRevBitSet::GetFirstOne() const {
return LeastSignificantBitPosition64(bits_);
}
// ---------- RevBitSet ----------
RevBitSet::RevBitSet(int64 size)
: rows_(1), columns_(size), length_(BitLength64(size)),
bits_(new uint64[length_]), stamps_(new uint64[length_]) {
DCHECK_GE(size, 1);
memset(bits_, 0, sizeof(*bits_) * length_);
memset(stamps_, 0, sizeof(*stamps_) * length_);
}
RevBitSet::RevBitSet(int64 rows, int64 columns)
: rows_(rows), columns_(columns), length_(BitLength64(rows * columns)),
bits_(new uint64[length_]), stamps_(new uint64[length_]) {
DCHECK_GE(rows, 1);
DCHECK_GE(columns, 1);
memset(bits_, 0, sizeof(*bits_) * length_);
memset(stamps_, 0, sizeof(*stamps_) * length_);
}
RevBitSet::~RevBitSet() {
delete [] bits_;
delete [] stamps_;
}
void RevBitSet::SetToOne(Solver* const solver, int64 index) {
DCHECK_GE(index, 0);
DCHECK_LT(index, columns_ * rows_);
const int64 offset = BitOffset64(index);
const int64 pos = BitPos64(index);
if (!(bits_[offset] & OneBit64(pos))) {
const uint64 current_stamp = solver->stamp();
if (current_stamp > stamps_[offset]) {
stamps_[offset] = current_stamp;
solver->SaveValue(&bits_[offset]);
}
bits_[offset] |= OneBit64(pos);
}
}
void RevBitSet::SetToOne(Solver* const solver, int64 row, int64 column) {
DCHECK_GE(row, 0);
DCHECK_LT(row, rows_);
DCHECK_GE(column, 0);
DCHECK_LT(column, columns_);
SetToOne(solver, row * columns_ + column);
}
void RevBitSet::SetToZero(Solver* const solver, int64 index) {
DCHECK_GE(index, 0);
DCHECK_LT(index, columns_ * rows_);
const int64 offset = BitOffset64(index);
const int64 pos = BitPos64(index);
if (bits_[offset] & OneBit64(pos)) {
const uint64 current_stamp = solver->stamp();
if (current_stamp > stamps_[offset]) {
stamps_[offset] = current_stamp;
solver->SaveValue(&bits_[offset]);
}
bits_[offset] &= ~OneBit64(pos);
}
}
void RevBitSet::SetToZero(Solver* const solver, int64 row, int64 column) {
DCHECK_GE(row, 0);
DCHECK_LT(row, rows_);
DCHECK_GE(column, 0);
DCHECK_LT(column, columns_);
SetToZero(solver, row * columns_ + column);
}
bool RevBitSet::IsSet(int64 index) const {
DCHECK_GE(index, 0);
DCHECK_LT(index, columns_ * rows_);
return IsBitSet64(bits_, index);
}
int64 RevBitSet::Cardinality() const {
int64 card = 0;
for (int i = 0; i < length_; ++i) {
card += BitCount64(bits_[i]);
}
return card;
}
bool RevBitSet::IsCardinalityZero() const {
for (int i = 0; i < length_; ++i) {
if (bits_[i]) {
return false;
}
}
return true;
}
bool RevBitSet::IsCardinalityOne() const {
bool found_one = false;
for (int i = 0; i < length_; ++i) {
const uint64 partial = bits_[i];
if (partial) {
if (!(partial & (partial - 1))) {
if (found_one) {
return false;
}
found_one = true;
} else {
return false;
}
}
}
return found_one;
}
int64 RevBitSet::GetFirstBit(int start) const {
const int end = rows_ * columns_ + columns_ - 1;
return LeastSignificantBitPosition64(bits_, start, end);
}
int64 RevBitSet::Cardinality(int row) const {
DCHECK_GE(row, 0);
DCHECK_LT(row, rows_);
const int start = row * columns_;
return BitCountRange64(bits_, start, start + columns_ - 1);
}
bool RevBitSet::IsCardinalityOne(int row) const {
// TODO(user) : Optimize this one.
return Cardinality(row) == 1;
}
bool RevBitSet::IsCardinalityZero(int row) const {
const int start = row * columns_;
return IsEmptyRange64(bits_, start, start + columns_ - 1);
}
int64 RevBitSet::GetFirstBit(int row, int start) const {
DCHECK_GE(start, 0);
DCHECK_GE(row, 0);
DCHECK_LT(row, rows_);
DCHECK_LT(start, columns_);
const int beginning = row * columns_;
const int end = beginning + columns_ - 1;
int64 position = LeastSignificantBitPosition64(bits_, beginning + start, end);
if (position == -1) {
return -1;
} else {
return position - beginning;
}
}
void RevBitSet::RevClearAll(Solver* const solver) {
const uint64 current_stamp = solver->stamp();
for (int offset = 0; offset < length_; ++offset) {
if (bits_[offset]) {
if (current_stamp > stamps_[offset]) {
stamps_[offset] = current_stamp;
solver->SaveValue(&bits_[offset]);
}
bits_[offset] = GG_ULONGLONG(0);
}
}
}
// ----- PrintModelVisitor -----
class PrintModelVisitor : public ModelVisitor {
public:
PrintModelVisitor() : indent_(0) {}
virtual ~PrintModelVisitor() {}
// Header/footers.
virtual void BeginVisitModel(const string& solver_name) {
LOG(INFO) << "Model " << solver_name << " {";
Increase();
}
virtual void EndVisitModel(const string& solver_name) {
LOG(INFO) << "}";
Decrease();
CHECK_EQ(0, indent_);
}
virtual void BeginVisitConstraint(const string& type_name,
const Constraint* const constraint) {
LOG(INFO) << Spaces() << type_name;
Increase();
}
virtual void EndVisitConstraint(const string& type_name,
const Constraint* const constraint) {
Decrease();
}
virtual void BeginVisitIntegerExpression(const string& type_name,
const IntExpr* const expr) {
LOG(INFO) << Spaces() << type_name;
Increase();
}
virtual void EndVisitIntegerExpression(const string& type_name,
const IntExpr* const expr) {
Decrease();
}
virtual void VisitIntegerVariable(const IntVar* const variable,
const IntExpr* const delegate) {
if (delegate != NULL) {
delegate->Accept(this);
} else {
if (variable->Bound() && variable->name().empty()) {
LOG(INFO) << Spaces() << variable->Min();
} else {
LOG(INFO) << Spaces() << variable->DebugString();
}
}
}
// Variables.
virtual void VisitIntegerArgument(const string& arg_name, int64 value) {
LOG(INFO) << Spaces() << arg_name << ": " << value;
}
virtual void VisitIntegerArrayArgument(const string& arg_name,
const int64* const values,
int size) {
string array = "[";
for (int i = 0; i < size; ++i) {
if (i != 0) {
array.append(", ");
}
StringAppendF(&array, "%lld", values[i]);
}
array.append("]");
LOG(INFO) << Spaces() << arg_name << ": " << array;
}
virtual void VisitIntegerExpressionArgument(
const string& arg_name,
const IntExpr* const argument) {
set_prefix(StringPrintf("%s: ", arg_name.c_str()));
Increase();
argument->Accept(this);
Decrease();
}
virtual void VisitIntegerVariableArrayArgument(
const string& arg_name,
const IntVar* const * arguments,
int size) {
LOG(INFO) << Spaces() << arg_name << ": [";
Increase();
for (int i = 0; i < size; ++i) {
arguments[i]->Accept(this);
}
Decrease();
LOG(INFO) << Spaces() << "]";
}
// Visit interval argument.
virtual void VisitIntervalArgument(const string& arg_name,
const IntervalVar* const argument) {
set_prefix(StringPrintf("%s: ", arg_name.c_str()));
Increase();
argument->Accept(this);
Decrease();
}
virtual void VisitIntervalArgumentArray(const string& arg_name,
const IntervalVar* const * arguments,
int size) {
LOG(INFO) << Spaces() << arg_name << ": [";
Increase();
for (int i = 0; i < size; ++i) {
arguments[i]->Accept(this);
}
Decrease();
LOG(INFO) << Spaces() << "]";
}
private:
void Increase() {
indent_ += 2;
}
void Decrease() {
indent_ -= 2;
}
string Spaces() {
string result;
for (int i = 0; i < indent_ - 2 * (!prefix_.empty()); ++i) {
result.append(" ");
}
if (!prefix_.empty()) {
result.append(prefix_);
prefix_ = "";
}
return result;
}
void set_prefix(const string& prefix) {
prefix_ = prefix;
}
int indent_;
string prefix_;
};
ModelVisitor* Solver::MakePrintModelVisitor() {
return RevAlloc(new PrintModelVisitor);
}
// ---------- ModelStatisticsVisitor -----------
class ModelStatisticsVisitor : public ModelVisitor {
public:
ModelStatisticsVisitor()
: num_constraints_(0),
num_variables_(0),
num_expressions_(0),
num_casts_(0),
num_intervals_(0) {}
virtual ~ModelStatisticsVisitor() {}
// Begin/End visit element.
virtual void BeginVisitModel(const string& solver_name) {
// Reset statistics.
num_constraints_ = 0;
num_variables_ = 0;
num_expressions_ = 0;
num_casts_ = 0;
num_intervals_ = 0;
already_visited_.clear();
}
virtual void EndVisitModel(const string& solver_name) {
// Display statistics.
LOG(INFO) << "Model has:";
LOG(INFO) << " - " << num_constraints_ << " constraints.";
for (ConstIter<hash_map<string, int> > it(constraint_types_);
!it.at_end();
++it) {
LOG(INFO) << " * " << it->second << " " << it->first;
}
LOG(INFO) << " - " << num_variables_ << " integer variables.";
LOG(INFO) << " - " << num_expressions_ << " integer expressions.";
for (ConstIter<hash_map<string, int> > it(expression_types_);
!it.at_end();
++it) {
LOG(INFO) << " * " << it->second << " " << it->first;
}
LOG(INFO) << " - " << num_casts_ << " expressions casted into variables.";
LOG(INFO) << " - " << num_intervals_ << " interval variables.";
}
virtual void BeginVisitConstraint(const string& type_name,
const Constraint* const constraint) {
num_constraints_++;
AddConstraintType(type_name);
}
virtual void BeginVisitIntegerExpression(const string& type_name,
const IntExpr* const expr) {
AddExpressionType(type_name);
num_expressions_++;
}
virtual void VisitIntegerVariable(const IntVar* const variable,
const IntExpr* const delegate) {
num_variables_++;
Register(variable);
if (delegate) {
num_casts_++;
VisitSubArgument(delegate);
}
}
virtual void VisitIntervalVariable(const IntervalVar* const variable,
const string operation,
const IntervalVar* const delegate) {
num_intervals_++;
// TODO(user): delegate.
}
// Visit integer expression argument.
virtual void VisitIntegerExpressionArgument(
const string& arg_name,
const IntExpr* const argument) {
VisitSubArgument(argument);
}
virtual void VisitIntegerVariableArrayArgument(
const string& arg_name,
const IntVar* const * arguments,
int size) {
for (int i = 0; i < size; ++i) {
VisitSubArgument(arguments[i]);
}
}
// Visit interval argument.
virtual void VisitIntervalArgument(const string& arg_name,
const IntervalVar* const argument) {
VisitSubArgument(argument);
}
virtual void VisitIntervalArrayArgument(const string& arg_name,
const IntervalVar* const * arguments,
int size) {
for (int i = 0; i < size; ++i) {
VisitSubArgument(arguments[i]);
}
}
private:
void Register(const BaseObject* const object) {
already_visited_.insert(object);
}
bool AlreadyVisited(const BaseObject* const object) {
return ContainsKey(already_visited_, object);
}
// T should derive from BaseObject
template<typename T> void VisitSubArgument(T* object) {
if (!AlreadyVisited(object)) {
Register(object);
object->Accept(this);
}
}
void AddConstraintType(const string& constraint_type) {
constraint_types_[constraint_type]++;
}
void AddExpressionType(const string& expression_type) {
expression_types_[expression_type]++;
}
hash_map<string, int> constraint_types_;
hash_map<string, int> expression_types_;
int num_constraints_;
int num_variables_;
int num_expressions_;
int num_casts_;
int num_intervals_;
hash_set<const BaseObject*> already_visited_;
};
ModelVisitor* Solver::MakeStatisticsModelVisitor() {
return RevAlloc(new ModelStatisticsVisitor);
}
} // namespace operations_research
<|endoftext|> |
<commit_before>// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include "CQPreferenceDialog.h"
#include "CQMessageBox.h"
#include "qtUtilities.h"
#include "commandline/CConfigurationFile.h"
#include "report/CCopasiRootContainer.h"
#define COL_NAME 0
#define COL_VALUE 1
/*
* Constructs a CQPreferenceDialog as a child of 'parent', with the
* name 'name' and widget flags set to 'f'.
*
* The dialog will by default be modeless, unless you set 'modal' to
* true to construct a modal dialog.
*/
CQPreferenceDialog::CQPreferenceDialog(QWidget* parent, const char* name, bool modal, Qt::WindowFlags fl)
: QDialog(parent, fl)
{
setObjectName(QString::fromUtf8(name));
setModal(modal);
setupUi(this);
init();
}
/*
* Destroys the object and frees any allocated resources
*/
CQPreferenceDialog::~CQPreferenceDialog()
{
// no need to delete child widgets, Qt does it all for us
}
void CQPreferenceDialog::init()
{
mpTreeWidget->setColumnWidth(COL_NAME, 150);
mpTreeWidget->setColumnWidth(COL_VALUE, 100);
CConfigurationFile * configFile = CCopasiRootContainer::getConfiguration();
CCopasiParameter * pParameter = configFile->getRecentFiles().getParameter("MaxFiles");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Max Last Visited Files");
Values.append(QString::number(pParameter->getValue< unsigned C_INT32 >()));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getRecentSBMLFiles().getParameter("MaxFiles");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Max Last Visited SBML Files");
Values.append(QString::number(pParameter->getValue< unsigned C_INT32 >()));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Application for opening URLs");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Application for opening URLs");
Values.append(FROM_UTF8(pParameter->getValue< std::string >()));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Validate Units");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Validate Units");
Values.append((pParameter->getValue< bool >() ? "YES" : "NO"));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Use OpenGL");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Use OpenGL");
Values.append((pParameter->getValue< bool >() ? "YES" : "NO"));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Use Advanced Sliders");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Use Advanced Sliders");
Values.append((pParameter->getValue< bool >() ? "YES" : "NO"));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Use Advanced Editing");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Use Advanced Editing");
Values.append((pParameter->getValue< bool >() ? "YES" : "NO"));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Normalize Weights per Experiment");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Normalize Weights per Experiment");
Values.append((pParameter->getValue< bool >() ? "YES" : "NO"));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Display Populations during Optimization");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Display Populations during Optimization");
Values.append((pParameter->getValue< bool >() ? "YES" : "NO"));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Allow Simultaneous Event Assignments");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Allow Simultaneous Event Assignments");
Values.append((pParameter->getValue< bool >() ? "YES" : "NO"));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Proxy Server");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Proxy Server");
Values.append(FROM_UTF8(pParameter->getValue< std::string >()));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Proxy Port");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Proxy Port");
Values.append(QString::number(pParameter->getValue< C_INT32 >()));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Proxy User");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Proxy User");
Values.append(FROM_UTF8(pParameter->getValue< std::string >()));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Proxy Password");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Proxy Password");
Values.append(FROM_UTF8(pParameter->getValue< std::string >()));
new QTreeWidgetItem(mpTreeWidget, Values);
}
// Adding current author information
pParameter = configFile->getParameter("Given Name");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Given Name");
Values.append(FROM_UTF8(pParameter->getValue< std::string >()));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Famliy Name");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Famliy Name");
Values.append(FROM_UTF8(pParameter->getValue< std::string >()));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Organization");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Organization");
Values.append(FROM_UTF8(pParameter->getValue< std::string >()));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Email");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Email");
Values.append(FROM_UTF8(pParameter->getValue< std::string >()));
new QTreeWidgetItem(mpTreeWidget, Values);
}
}
void CQPreferenceDialog::slotBtnOk()
{
// We need to commit the changes
unsigned C_INT32 newMaxFiles = 0;
CConfigurationFile * configFile = CCopasiRootContainer::getConfiguration();
QList< QTreeWidgetItem *> Items = mpTreeWidget->findItems("Max Last Visited Files", 0, 0);
CCopasiParameter * pParameter = configFile->getRecentFiles().getParameter("MaxFiles");
if (Items.size() > 0 &&
pParameter != NULL)
{
newMaxFiles = Items[0]->text(COL_VALUE).toUInt();
unsigned C_INT32 maxFiles = pParameter->getValue< unsigned C_INT32 >();
if (newMaxFiles > 0 && newMaxFiles <= 20)
pParameter->setValue(newMaxFiles);
else
{
CQMessageBox::critical(this, "Incorrect Setting",
"Max Last Visited Files should be a number between 1 and 20.",
QMessageBox::Ok, QMessageBox::Ok);
Items[0]->setText(COL_VALUE, QString::number(maxFiles));
return;
}
}
Items = mpTreeWidget->findItems("Max Last Visited SBML Files", 0, 0);
pParameter = configFile->getRecentSBMLFiles().getParameter("MaxFiles");
if (Items.size() > 0 &&
pParameter != NULL)
{
newMaxFiles = Items[0]->text(COL_VALUE).toUInt();
unsigned C_INT32 maxFiles = pParameter->getValue< unsigned C_INT32 >();
if (newMaxFiles > 0 && newMaxFiles <= 20)
pParameter->setValue(newMaxFiles);
else
{
CQMessageBox::critical(this, "Incorrect Setting", "Max Last Visited SBML Files should be a number between 1 and 20.",
QMessageBox::Ok, QMessageBox::Ok);
Items[0]->setText(COL_VALUE, QString::number(maxFiles));
return;
}
}
Items = mpTreeWidget->findItems("Application for opening URLs", 0, 0);
pParameter = configFile->getParameter("Application for opening URLs");
if (Items.size() > 0 &&
pParameter != NULL)
{
if (Items[0]->text(COL_VALUE) != FROM_UTF8(pParameter->getValue< std::string >()))
pParameter->setValue(std::string(TO_UTF8(Items[0]->text(COL_VALUE))));
}
Items = mpTreeWidget->findItems("Validate Units", 0, 0);
pParameter = configFile->getParameter("Validate Units");
if (Items.size() > 0 &&
pParameter != NULL)
{
pParameter->setValue(Items[0]->text(COL_VALUE).toUpper() == "YES");
}
Items = mpTreeWidget->findItems("Use OpenGL", 0, 0);
pParameter = configFile->getParameter("Use OpenGL");
if (Items.size() > 0 &&
pParameter != NULL)
{
pParameter->setValue(Items[0]->text(COL_VALUE).toUpper() == "YES");
}
Items = mpTreeWidget->findItems("Use Advanced Sliders", 0, 0);
pParameter = configFile->getParameter("Use Advanced Sliders");
if (Items.size() > 0 &&
pParameter != NULL)
{
pParameter->setValue(Items[0]->text(COL_VALUE).toUpper() == "YES");
}
Items = mpTreeWidget->findItems("Use Advanced Editing", 0, 0);
pParameter = configFile->getParameter("Use Advanced Editing");
if (Items.size() > 0 &&
pParameter != NULL)
{
pParameter->setValue(Items[0]->text(COL_VALUE).toUpper() == "YES");
}
Items = mpTreeWidget->findItems("Normalize Weights per Experiment", 0, 0);
pParameter = configFile->getParameter("Normalize Weights per Experiment");
if (Items.size() > 0 &&
pParameter != NULL)
{
pParameter->setValue(Items[0]->text(COL_VALUE).toUpper() == "YES");
}
Items = mpTreeWidget->findItems("Display Populations during Optimization", 0, 0);
pParameter = configFile->getParameter("Display Populations during Optimization");
if (Items.size() > 0 &&
pParameter != NULL)
{
pParameter->setValue(Items[0]->text(COL_VALUE).toUpper() == "YES");
}
Items = mpTreeWidget->findItems("Allow Simultaneous Event Assignments", 0, 0);
pParameter = configFile->getParameter("Allow Simultaneous Event Assignments");
if (Items.size() > 0 &&
pParameter != NULL)
{
pParameter->setValue(Items[0]->text(COL_VALUE).toUpper() == "YES");
}
Items = mpTreeWidget->findItems("Proxy Server", 0, 0);
pParameter = configFile->getParameter("Proxy Server");
if (Items.size() > 0 &&
pParameter != NULL)
{
if (Items[0]->text(COL_VALUE) != FROM_UTF8(pParameter->getValue< std::string >()))
pParameter->setValue(std::string(TO_UTF8(Items[0]->text(COL_VALUE))));
}
Items = mpTreeWidget->findItems("Proxy Port", 0, 0);
pParameter = configFile->getParameter("Proxy Port");
if (Items.size() > 0 &&
pParameter != NULL)
{
C_INT32 port = Items[0]->text(COL_VALUE).toInt();
pParameter->setValue(port);
}
Items = mpTreeWidget->findItems("Proxy User", 0, 0);
pParameter = configFile->getParameter("Proxy User");
if (Items.size() > 0 &&
pParameter != NULL)
{
if (Items[0]->text(COL_VALUE) != FROM_UTF8(pParameter->getValue< std::string >()))
pParameter->setValue(std::string(TO_UTF8(Items[0]->text(COL_VALUE))));
}
Items = mpTreeWidget->findItems("Proxy Password", 0, 0);
pParameter = configFile->getParameter("Proxy Password");
if (Items.size() > 0 &&
pParameter != NULL)
{
if (Items[0]->text(COL_VALUE) != FROM_UTF8(pParameter->getValue< std::string >()))
pParameter->setValue(std::string(TO_UTF8(Items[0]->text(COL_VALUE))));
}
Items = mpTreeWidget->findItems("Given Name", 0, 0);
pParameter = configFile->getParameter("Given Name");
if (Items.size() > 0 &&
pParameter != NULL)
{
if (Items[0]->text(COL_VALUE) != FROM_UTF8(pParameter->getValue< std::string >()))
pParameter->setValue(std::string(TO_UTF8(Items[0]->text(COL_VALUE))));
}
Items = mpTreeWidget->findItems("Famliy Name", 0, 0);
pParameter = configFile->getParameter("Famliy Name");
if (Items.size() > 0 &&
pParameter != NULL)
{
if (Items[0]->text(COL_VALUE) != FROM_UTF8(pParameter->getValue< std::string >()))
pParameter->setValue(std::string(TO_UTF8(Items[0]->text(COL_VALUE))));
}
Items = mpTreeWidget->findItems("Organization", 0, 0);
pParameter = configFile->getParameter("Organization");
if (Items.size() > 0 &&
pParameter != NULL)
{
if (Items[0]->text(COL_VALUE) != FROM_UTF8(pParameter->getValue< std::string >()))
pParameter->setValue(std::string(TO_UTF8(Items[0]->text(COL_VALUE))));
}
Items = mpTreeWidget->findItems("Email", 0, 0);
pParameter = configFile->getParameter("Email");
if (Items.size() > 0 &&
pParameter != NULL)
{
if (Items[0]->text(COL_VALUE) != FROM_UTF8(pParameter->getValue< std::string >()))
pParameter->setValue(std::string(TO_UTF8(Items[0]->text(COL_VALUE))));
}
done(1);
}
// virtual
void CQPreferenceDialog::slotBtnCancel()
{
done(0);
}
// virtual
void CQPreferenceDialog::slotItemDoubleClicked(QTreeWidgetItem* pItem, int column)
{
if (column == COL_VALUE)
{
Qt::ItemFlags Flags = pItem->flags();
pItem->setFlags(Flags | Qt::ItemIsEditable);
mpTreeWidget->editItem(pItem, column);
pItem->setFlags(Flags);
}
}
<commit_msg>- remove obsolete option "Allow Simultaneous Event Assignments"<commit_after>// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include "CQPreferenceDialog.h"
#include "CQMessageBox.h"
#include "qtUtilities.h"
#include "commandline/CConfigurationFile.h"
#include "report/CCopasiRootContainer.h"
#define COL_NAME 0
#define COL_VALUE 1
/*
* Constructs a CQPreferenceDialog as a child of 'parent', with the
* name 'name' and widget flags set to 'f'.
*
* The dialog will by default be modeless, unless you set 'modal' to
* true to construct a modal dialog.
*/
CQPreferenceDialog::CQPreferenceDialog(QWidget* parent, const char* name, bool modal, Qt::WindowFlags fl)
: QDialog(parent, fl)
{
setObjectName(QString::fromUtf8(name));
setModal(modal);
setupUi(this);
init();
}
/*
* Destroys the object and frees any allocated resources
*/
CQPreferenceDialog::~CQPreferenceDialog()
{
// no need to delete child widgets, Qt does it all for us
}
void CQPreferenceDialog::init()
{
mpTreeWidget->setColumnWidth(COL_NAME, 150);
mpTreeWidget->setColumnWidth(COL_VALUE, 100);
CConfigurationFile * configFile = CCopasiRootContainer::getConfiguration();
CCopasiParameter * pParameter = configFile->getRecentFiles().getParameter("MaxFiles");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Max Last Visited Files");
Values.append(QString::number(pParameter->getValue< unsigned C_INT32 >()));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getRecentSBMLFiles().getParameter("MaxFiles");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Max Last Visited SBML Files");
Values.append(QString::number(pParameter->getValue< unsigned C_INT32 >()));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Application for opening URLs");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Application for opening URLs");
Values.append(FROM_UTF8(pParameter->getValue< std::string >()));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Validate Units");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Validate Units");
Values.append((pParameter->getValue< bool >() ? "YES" : "NO"));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Use OpenGL");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Use OpenGL");
Values.append((pParameter->getValue< bool >() ? "YES" : "NO"));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Use Advanced Sliders");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Use Advanced Sliders");
Values.append((pParameter->getValue< bool >() ? "YES" : "NO"));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Use Advanced Editing");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Use Advanced Editing");
Values.append((pParameter->getValue< bool >() ? "YES" : "NO"));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Normalize Weights per Experiment");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Normalize Weights per Experiment");
Values.append((pParameter->getValue< bool >() ? "YES" : "NO"));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Display Populations during Optimization");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Display Populations during Optimization");
Values.append((pParameter->getValue< bool >() ? "YES" : "NO"));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Proxy Server");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Proxy Server");
Values.append(FROM_UTF8(pParameter->getValue< std::string >()));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Proxy Port");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Proxy Port");
Values.append(QString::number(pParameter->getValue< C_INT32 >()));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Proxy User");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Proxy User");
Values.append(FROM_UTF8(pParameter->getValue< std::string >()));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Proxy Password");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Proxy Password");
Values.append(FROM_UTF8(pParameter->getValue< std::string >()));
new QTreeWidgetItem(mpTreeWidget, Values);
}
// Adding current author information
pParameter = configFile->getParameter("Given Name");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Given Name");
Values.append(FROM_UTF8(pParameter->getValue< std::string >()));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Famliy Name");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Famliy Name");
Values.append(FROM_UTF8(pParameter->getValue< std::string >()));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Organization");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Organization");
Values.append(FROM_UTF8(pParameter->getValue< std::string >()));
new QTreeWidgetItem(mpTreeWidget, Values);
}
pParameter = configFile->getParameter("Email");
if (pParameter != NULL)
{
QStringList Values;
Values.append("Email");
Values.append(FROM_UTF8(pParameter->getValue< std::string >()));
new QTreeWidgetItem(mpTreeWidget, Values);
}
}
void CQPreferenceDialog::slotBtnOk()
{
// We need to commit the changes
unsigned C_INT32 newMaxFiles = 0;
CConfigurationFile * configFile = CCopasiRootContainer::getConfiguration();
QList< QTreeWidgetItem *> Items = mpTreeWidget->findItems("Max Last Visited Files", 0, 0);
CCopasiParameter * pParameter = configFile->getRecentFiles().getParameter("MaxFiles");
if (Items.size() > 0 &&
pParameter != NULL)
{
newMaxFiles = Items[0]->text(COL_VALUE).toUInt();
unsigned C_INT32 maxFiles = pParameter->getValue< unsigned C_INT32 >();
if (newMaxFiles > 0 && newMaxFiles <= 20)
pParameter->setValue(newMaxFiles);
else
{
CQMessageBox::critical(this, "Incorrect Setting",
"Max Last Visited Files should be a number between 1 and 20.",
QMessageBox::Ok, QMessageBox::Ok);
Items[0]->setText(COL_VALUE, QString::number(maxFiles));
return;
}
}
Items = mpTreeWidget->findItems("Max Last Visited SBML Files", 0, 0);
pParameter = configFile->getRecentSBMLFiles().getParameter("MaxFiles");
if (Items.size() > 0 &&
pParameter != NULL)
{
newMaxFiles = Items[0]->text(COL_VALUE).toUInt();
unsigned C_INT32 maxFiles = pParameter->getValue< unsigned C_INT32 >();
if (newMaxFiles > 0 && newMaxFiles <= 20)
pParameter->setValue(newMaxFiles);
else
{
CQMessageBox::critical(this, "Incorrect Setting", "Max Last Visited SBML Files should be a number between 1 and 20.",
QMessageBox::Ok, QMessageBox::Ok);
Items[0]->setText(COL_VALUE, QString::number(maxFiles));
return;
}
}
Items = mpTreeWidget->findItems("Application for opening URLs", 0, 0);
pParameter = configFile->getParameter("Application for opening URLs");
if (Items.size() > 0 &&
pParameter != NULL)
{
if (Items[0]->text(COL_VALUE) != FROM_UTF8(pParameter->getValue< std::string >()))
pParameter->setValue(std::string(TO_UTF8(Items[0]->text(COL_VALUE))));
}
Items = mpTreeWidget->findItems("Validate Units", 0, 0);
pParameter = configFile->getParameter("Validate Units");
if (Items.size() > 0 &&
pParameter != NULL)
{
pParameter->setValue(Items[0]->text(COL_VALUE).toUpper() == "YES");
}
Items = mpTreeWidget->findItems("Use OpenGL", 0, 0);
pParameter = configFile->getParameter("Use OpenGL");
if (Items.size() > 0 &&
pParameter != NULL)
{
pParameter->setValue(Items[0]->text(COL_VALUE).toUpper() == "YES");
}
Items = mpTreeWidget->findItems("Use Advanced Sliders", 0, 0);
pParameter = configFile->getParameter("Use Advanced Sliders");
if (Items.size() > 0 &&
pParameter != NULL)
{
pParameter->setValue(Items[0]->text(COL_VALUE).toUpper() == "YES");
}
Items = mpTreeWidget->findItems("Use Advanced Editing", 0, 0);
pParameter = configFile->getParameter("Use Advanced Editing");
if (Items.size() > 0 &&
pParameter != NULL)
{
pParameter->setValue(Items[0]->text(COL_VALUE).toUpper() == "YES");
}
Items = mpTreeWidget->findItems("Normalize Weights per Experiment", 0, 0);
pParameter = configFile->getParameter("Normalize Weights per Experiment");
if (Items.size() > 0 &&
pParameter != NULL)
{
pParameter->setValue(Items[0]->text(COL_VALUE).toUpper() == "YES");
}
Items = mpTreeWidget->findItems("Display Populations during Optimization", 0, 0);
pParameter = configFile->getParameter("Display Populations during Optimization");
if (Items.size() > 0 &&
pParameter != NULL)
{
pParameter->setValue(Items[0]->text(COL_VALUE).toUpper() == "YES");
}
Items = mpTreeWidget->findItems("Proxy Server", 0, 0);
pParameter = configFile->getParameter("Proxy Server");
if (Items.size() > 0 &&
pParameter != NULL)
{
if (Items[0]->text(COL_VALUE) != FROM_UTF8(pParameter->getValue< std::string >()))
pParameter->setValue(std::string(TO_UTF8(Items[0]->text(COL_VALUE))));
}
Items = mpTreeWidget->findItems("Proxy Port", 0, 0);
pParameter = configFile->getParameter("Proxy Port");
if (Items.size() > 0 &&
pParameter != NULL)
{
C_INT32 port = Items[0]->text(COL_VALUE).toInt();
pParameter->setValue(port);
}
Items = mpTreeWidget->findItems("Proxy User", 0, 0);
pParameter = configFile->getParameter("Proxy User");
if (Items.size() > 0 &&
pParameter != NULL)
{
if (Items[0]->text(COL_VALUE) != FROM_UTF8(pParameter->getValue< std::string >()))
pParameter->setValue(std::string(TO_UTF8(Items[0]->text(COL_VALUE))));
}
Items = mpTreeWidget->findItems("Proxy Password", 0, 0);
pParameter = configFile->getParameter("Proxy Password");
if (Items.size() > 0 &&
pParameter != NULL)
{
if (Items[0]->text(COL_VALUE) != FROM_UTF8(pParameter->getValue< std::string >()))
pParameter->setValue(std::string(TO_UTF8(Items[0]->text(COL_VALUE))));
}
Items = mpTreeWidget->findItems("Given Name", 0, 0);
pParameter = configFile->getParameter("Given Name");
if (Items.size() > 0 &&
pParameter != NULL)
{
if (Items[0]->text(COL_VALUE) != FROM_UTF8(pParameter->getValue< std::string >()))
pParameter->setValue(std::string(TO_UTF8(Items[0]->text(COL_VALUE))));
}
Items = mpTreeWidget->findItems("Famliy Name", 0, 0);
pParameter = configFile->getParameter("Famliy Name");
if (Items.size() > 0 &&
pParameter != NULL)
{
if (Items[0]->text(COL_VALUE) != FROM_UTF8(pParameter->getValue< std::string >()))
pParameter->setValue(std::string(TO_UTF8(Items[0]->text(COL_VALUE))));
}
Items = mpTreeWidget->findItems("Organization", 0, 0);
pParameter = configFile->getParameter("Organization");
if (Items.size() > 0 &&
pParameter != NULL)
{
if (Items[0]->text(COL_VALUE) != FROM_UTF8(pParameter->getValue< std::string >()))
pParameter->setValue(std::string(TO_UTF8(Items[0]->text(COL_VALUE))));
}
Items = mpTreeWidget->findItems("Email", 0, 0);
pParameter = configFile->getParameter("Email");
if (Items.size() > 0 &&
pParameter != NULL)
{
if (Items[0]->text(COL_VALUE) != FROM_UTF8(pParameter->getValue< std::string >()))
pParameter->setValue(std::string(TO_UTF8(Items[0]->text(COL_VALUE))));
}
done(1);
}
// virtual
void CQPreferenceDialog::slotBtnCancel()
{
done(0);
}
// virtual
void CQPreferenceDialog::slotItemDoubleClicked(QTreeWidgetItem* pItem, int column)
{
if (column == COL_VALUE)
{
Qt::ItemFlags Flags = pItem->flags();
pItem->setFlags(Flags | Qt::ItemIsEditable);
mpTreeWidget->editItem(pItem, column);
pItem->setFlags(Flags);
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.