text
stringlengths 54
60.6k
|
---|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// A general interface for filtering and only acting on classes in Chromium C++
// code.
#include "ChromeClassTester.h"
#include <sys/param.h>
#include "clang/Basic/FileManager.h"
using namespace clang;
namespace {
bool starts_with(const std::string& one, const std::string& two) {
return one.substr(0, two.size()) == two;
}
bool ends_with(const std::string& one, const std::string& two) {
if (two.size() > one.size())
return false;
return one.substr(one.size() - two.size(), two.size()) == two;
}
} // namespace
ChromeClassTester::ChromeClassTester(CompilerInstance& instance)
: instance_(instance),
diagnostic_(instance.getDiagnostics()) {
FigureOutSrcRoot();
BuildBannedLists();
}
void ChromeClassTester::FigureOutSrcRoot() {
char c_cwd[MAXPATHLEN];
if (getcwd(c_cwd, MAXPATHLEN) > 0) {
size_t pos = 1;
std::string cwd = c_cwd;
// Add a trailing '/' because the search below requires it.
if (cwd[cwd.size() - 1] != '/')
cwd += '/';
// Search the directory tree downwards until we find a path that contains
// "build/common.gypi" and assume that that is our srcroot.
size_t next_slash = cwd.find('/', pos);
while (next_slash != std::string::npos) {
next_slash++;
std::string candidate = cwd.substr(0, next_slash);
if (ends_with(candidate, "src/")) {
std::string common = candidate + "build/common.gypi";
if (access(common.c_str(), F_OK) != -1) {
src_root_ = candidate;
break;
}
}
pos = next_slash;
next_slash = cwd.find('/', pos);
}
}
if (src_root_.empty()) {
unsigned id = diagnostic().getCustomDiagID(
Diagnostic::Error,
"WARNING: Can't figure out srcroot!\n");
diagnostic().Report(id);
}
}
void ChromeClassTester::BuildBannedLists() {
banned_namespaces_.push_back("std");
banned_namespaces_.push_back("__gnu_cxx");
banned_directories_.push_back("third_party");
banned_directories_.push_back("native_client");
banned_directories_.push_back("breakpad");
banned_directories_.push_back("courgette");
banned_directories_.push_back("ppapi");
banned_directories_.push_back("/usr");
banned_directories_.push_back("testing");
banned_directories_.push_back("googleurl");
banned_directories_.push_back("v8");
banned_directories_.push_back("sdch");
// Don't check autogenerated headers.
banned_directories_.push_back("out");
banned_directories_.push_back("llvm");
banned_directories_.push_back("xcodebuild");
// You are standing in a mazy of twisty dependencies, all resolved by
// putting everything in the header.
banned_directories_.push_back("chrome/test/automation");
// Used in really low level threading code that probably shouldn't be out of
// lined.
ignored_record_names_.push_back("ThreadLocalBoolean");
// A complicated pickle derived struct that is all packed integers.
ignored_record_names_.push_back("Header");
// Part of the GPU system that uses multiple included header
// weirdness. Never getting this right.
ignored_record_names_.push_back("Validators");
// RAII class that's simple enough (media/base/callback.h).
ignored_record_names_.push_back("AutoTaskRunner");
ignored_record_names_.push_back("AutoCallbackRunner");
// Has a UNIT_TEST only constructor. Isn't *terribly* complex...
ignored_record_names_.push_back("AutocompleteController");
ignored_record_names_.push_back("HistoryURLProvider");
// Because of chrome frame
ignored_record_names_.push_back("ReliabilityTestSuite");
// Used over in the net unittests. A large enough bundle of integers with 1
// non-pod class member. Probably harmless.
ignored_record_names_.push_back("MockTransaction");
// Used heavily in app_unittests and once in views_unittests. Fixing this
// isn't worth the overhead of an additional library.
ignored_record_names_.push_back("TestAnimationDelegate");
// Part of our public interface that nacl and friends use. (Arguably, this
// should mean that this is a higher priority but fixing this looks hard.)
ignored_record_names_.push_back("PluginVersionInfo");
}
ChromeClassTester::~ChromeClassTester() {}
void ChromeClassTester::HandleTagDeclDefinition(TagDecl* tag) {
// We handle class types here where we have semantic information. We can only
// check structs/classes/enums here, but we get a bunch of nice semantic
// information instead of just parsing information.
if (CXXRecordDecl* record = dyn_cast<CXXRecordDecl>(tag)) {
// If this is a POD or a class template or a type dependent on a
// templated class, assume there's no ctor/dtor/virtual method
// optimization that we can do.
if (record->isPOD() ||
record->getDescribedClassTemplate() ||
record->getTemplateSpecializationKind() ||
record->isDependentType())
return;
if (InBannedNamespace(record))
return;
SourceLocation record_location = record->getInnerLocStart();
if (InBannedDirectory(record_location))
return;
// We sadly need to maintain a blacklist of types that violate these
// rules, but do so for good reason or due to limitations of this
// checker (i.e., we don't handle extern templates very well).
std::string base_name = record->getNameAsString();
if (IsIgnoredType(base_name))
return;
// We ignore all classes that end with "Matcher" because they're probably
// GMock artifacts.
if (ends_with(base_name, "Matcher"))
return;
CheckChromeClass(record_location, record);
}
}
void ChromeClassTester::HandleTranslationUnit(clang::ASTContext& ctx) {
RecursivelyCheckTopLevels(ctx.getTranslationUnitDecl());
}
void ChromeClassTester::RecursivelyCheckTopLevels(Decl* d) {
// Unlike HandleTagDeclDefinition, we can only rely on having parsing
// information here. We absoluetly shouldn't check that any semantic data
// here because we will assert.
Decl::Kind kind = d->getKind();
if (kind == Decl::UsingDirective) {
UsingDirectiveDecl* record = cast<UsingDirectiveDecl>(d);
SourceLocation record_location = record->getLocation();
if (!InBannedDirectory(record_location))
CheckChromeUsingDirective(record_location, record);
}
// If this is a DeclContext that isn't a function/method, recurse.
if (DeclContext* context = dyn_cast<DeclContext>(d)) {
if (context->isFileContext()) {
for (DeclContext::decl_iterator it = context->decls_begin();
it != context->decls_end(); ++it) {
RecursivelyCheckTopLevels(*it);
}
}
}
}
void ChromeClassTester::emitWarning(SourceLocation loc, const char* raw_error) {
FullSourceLoc full(loc, instance().getSourceManager());
std::string err;
err = "[chromium-style] ";
err += raw_error;
Diagnostic::Level level =
diagnostic().getWarningsAsErrors() ?
Diagnostic::Error :
Diagnostic::Warning;
unsigned id = diagnostic().getCustomDiagID(level, err);
DiagnosticBuilder B = diagnostic().Report(full, id);
}
bool ChromeClassTester::InTestingNamespace(Decl* record) {
return GetNamespace(record).find("testing") != std::string::npos;
}
bool ChromeClassTester::InBannedNamespace(Decl* record) {
std::string n = GetNamespace(record);
if (n != "") {
return std::find(banned_namespaces_.begin(), banned_namespaces_.end(), n)
!= banned_namespaces_.end();
}
return false;
}
std::string ChromeClassTester::GetNamespace(Decl* record) {
return GetNamespaceImpl(record->getDeclContext(), "");
}
std::string ChromeClassTester::GetNamespaceImpl(const DeclContext* context,
std::string candidate) {
switch (context->getDeclKind()) {
case Decl::TranslationUnit: {
return candidate;
}
case Decl::Namespace: {
const NamespaceDecl* decl = dyn_cast<NamespaceDecl>(context);
std::string name_str;
llvm::raw_string_ostream OS(name_str);
if (decl->isAnonymousNamespace())
OS << "<anonymous namespace>";
else
OS << decl;
return GetNamespaceImpl(context->getParent(),
OS.str());
}
default: {
return GetNamespaceImpl(context->getParent(), candidate);
}
}
}
bool ChromeClassTester::InBannedDirectory(SourceLocation loc) {
const SourceManager &SM = instance_.getSourceManager();
SourceLocation spelling_location = SM.getSpellingLoc(loc);
PresumedLoc ploc = SM.getPresumedLoc(spelling_location);
std::string buffer_name;
if (ploc.isInvalid()) {
// If we're in an invalid location, we're looking at things that aren't
// actually stated in the source; treat this as a banned location instead
// of going through our full lookup process.
return true;
} else {
std::string b = ploc.getFilename();
// We need to special case scratch space; which is where clang does its
// macro expansion. We explicitly want to allow people to do otherwise bad
// things through macros that were defined due to third party libraries.
if (b == "<scratch space>")
return true;
// Don't complain about these things in implementation files.
if (ends_with(b, ".cc") || ends_with(b, ".cpp") || ends_with(b, ".mm")) {
return true;
}
// Don't complain about autogenerated protobuf files.
if (ends_with(b, ".pb.h")) {
return true;
}
// We need to munge the paths so that they are relative to the repository
// srcroot. We first resolve the symlinktastic relative path and then
// remove our known srcroot from it if needed.
char resolvedPath[MAXPATHLEN];
if (realpath(b.c_str(), resolvedPath)) {
std::string resolved = resolvedPath;
if (starts_with(resolved, src_root_)) {
b = resolved.substr(src_root_.size());
}
}
for (std::vector<std::string>::const_iterator it =
banned_directories_.begin();
it != banned_directories_.end(); ++it) {
if (starts_with(b, *it)) {
return true;
}
}
}
return false;
}
bool ChromeClassTester::IsIgnoredType(const std::string& base_name) {
for (std::vector<std::string>::const_iterator it =
ignored_record_names_.begin();
it != ignored_record_names_.end(); ++it) {
if (base_name == *it)
return true;
}
return false;
}
<commit_msg>Fix clang bustage on Mac by blacklisting /Developer<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// A general interface for filtering and only acting on classes in Chromium C++
// code.
#include "ChromeClassTester.h"
#include <sys/param.h>
#include "clang/Basic/FileManager.h"
using namespace clang;
namespace {
bool starts_with(const std::string& one, const std::string& two) {
return one.substr(0, two.size()) == two;
}
bool ends_with(const std::string& one, const std::string& two) {
if (two.size() > one.size())
return false;
return one.substr(one.size() - two.size(), two.size()) == two;
}
} // namespace
ChromeClassTester::ChromeClassTester(CompilerInstance& instance)
: instance_(instance),
diagnostic_(instance.getDiagnostics()) {
FigureOutSrcRoot();
BuildBannedLists();
}
void ChromeClassTester::FigureOutSrcRoot() {
char c_cwd[MAXPATHLEN];
if (getcwd(c_cwd, MAXPATHLEN) > 0) {
size_t pos = 1;
std::string cwd = c_cwd;
// Add a trailing '/' because the search below requires it.
if (cwd[cwd.size() - 1] != '/')
cwd += '/';
// Search the directory tree downwards until we find a path that contains
// "build/common.gypi" and assume that that is our srcroot.
size_t next_slash = cwd.find('/', pos);
while (next_slash != std::string::npos) {
next_slash++;
std::string candidate = cwd.substr(0, next_slash);
if (ends_with(candidate, "src/")) {
std::string common = candidate + "build/common.gypi";
if (access(common.c_str(), F_OK) != -1) {
src_root_ = candidate;
break;
}
}
pos = next_slash;
next_slash = cwd.find('/', pos);
}
}
if (src_root_.empty()) {
unsigned id = diagnostic().getCustomDiagID(
Diagnostic::Error,
"WARNING: Can't figure out srcroot!\n");
diagnostic().Report(id);
}
}
void ChromeClassTester::BuildBannedLists() {
banned_namespaces_.push_back("std");
banned_namespaces_.push_back("__gnu_cxx");
banned_directories_.push_back("third_party");
banned_directories_.push_back("native_client");
banned_directories_.push_back("breakpad");
banned_directories_.push_back("courgette");
banned_directories_.push_back("ppapi");
banned_directories_.push_back("testing");
banned_directories_.push_back("googleurl");
banned_directories_.push_back("v8");
banned_directories_.push_back("sdch");
// Don't check autogenerated headers.
banned_directories_.push_back("out");
banned_directories_.push_back("llvm");
banned_directories_.push_back("xcodebuild");
// You are standing in a mazy of twisty dependencies, all resolved by
// putting everything in the header.
banned_directories_.push_back("chrome/test/automation");
// Don't check system headers.
banned_directories_.push_back("/usr");
banned_directories_.push_back("/Developer");
// Used in really low level threading code that probably shouldn't be out of
// lined.
ignored_record_names_.push_back("ThreadLocalBoolean");
// A complicated pickle derived struct that is all packed integers.
ignored_record_names_.push_back("Header");
// Part of the GPU system that uses multiple included header
// weirdness. Never getting this right.
ignored_record_names_.push_back("Validators");
// RAII class that's simple enough (media/base/callback.h).
ignored_record_names_.push_back("AutoTaskRunner");
ignored_record_names_.push_back("AutoCallbackRunner");
// Has a UNIT_TEST only constructor. Isn't *terribly* complex...
ignored_record_names_.push_back("AutocompleteController");
ignored_record_names_.push_back("HistoryURLProvider");
// Because of chrome frame
ignored_record_names_.push_back("ReliabilityTestSuite");
// Used over in the net unittests. A large enough bundle of integers with 1
// non-pod class member. Probably harmless.
ignored_record_names_.push_back("MockTransaction");
// Used heavily in app_unittests and once in views_unittests. Fixing this
// isn't worth the overhead of an additional library.
ignored_record_names_.push_back("TestAnimationDelegate");
// Part of our public interface that nacl and friends use. (Arguably, this
// should mean that this is a higher priority but fixing this looks hard.)
ignored_record_names_.push_back("PluginVersionInfo");
}
ChromeClassTester::~ChromeClassTester() {}
void ChromeClassTester::HandleTagDeclDefinition(TagDecl* tag) {
// We handle class types here where we have semantic information. We can only
// check structs/classes/enums here, but we get a bunch of nice semantic
// information instead of just parsing information.
if (CXXRecordDecl* record = dyn_cast<CXXRecordDecl>(tag)) {
// If this is a POD or a class template or a type dependent on a
// templated class, assume there's no ctor/dtor/virtual method
// optimization that we can do.
if (record->isPOD() ||
record->getDescribedClassTemplate() ||
record->getTemplateSpecializationKind() ||
record->isDependentType())
return;
if (InBannedNamespace(record))
return;
SourceLocation record_location = record->getInnerLocStart();
if (InBannedDirectory(record_location))
return;
// We sadly need to maintain a blacklist of types that violate these
// rules, but do so for good reason or due to limitations of this
// checker (i.e., we don't handle extern templates very well).
std::string base_name = record->getNameAsString();
if (IsIgnoredType(base_name))
return;
// We ignore all classes that end with "Matcher" because they're probably
// GMock artifacts.
if (ends_with(base_name, "Matcher"))
return;
CheckChromeClass(record_location, record);
}
}
void ChromeClassTester::HandleTranslationUnit(clang::ASTContext& ctx) {
RecursivelyCheckTopLevels(ctx.getTranslationUnitDecl());
}
void ChromeClassTester::RecursivelyCheckTopLevels(Decl* d) {
// Unlike HandleTagDeclDefinition, we can only rely on having parsing
// information here. We absoluetly shouldn't check that any semantic data
// here because we will assert.
Decl::Kind kind = d->getKind();
if (kind == Decl::UsingDirective) {
UsingDirectiveDecl* record = cast<UsingDirectiveDecl>(d);
SourceLocation record_location = record->getLocation();
if (!InBannedDirectory(record_location))
CheckChromeUsingDirective(record_location, record);
}
// If this is a DeclContext that isn't a function/method, recurse.
if (DeclContext* context = dyn_cast<DeclContext>(d)) {
if (context->isFileContext()) {
for (DeclContext::decl_iterator it = context->decls_begin();
it != context->decls_end(); ++it) {
RecursivelyCheckTopLevels(*it);
}
}
}
}
void ChromeClassTester::emitWarning(SourceLocation loc, const char* raw_error) {
FullSourceLoc full(loc, instance().getSourceManager());
std::string err;
err = "[chromium-style] ";
err += raw_error;
Diagnostic::Level level =
diagnostic().getWarningsAsErrors() ?
Diagnostic::Error :
Diagnostic::Warning;
unsigned id = diagnostic().getCustomDiagID(level, err);
DiagnosticBuilder B = diagnostic().Report(full, id);
}
bool ChromeClassTester::InTestingNamespace(Decl* record) {
return GetNamespace(record).find("testing") != std::string::npos;
}
bool ChromeClassTester::InBannedNamespace(Decl* record) {
std::string n = GetNamespace(record);
if (n != "") {
return std::find(banned_namespaces_.begin(), banned_namespaces_.end(), n)
!= banned_namespaces_.end();
}
return false;
}
std::string ChromeClassTester::GetNamespace(Decl* record) {
return GetNamespaceImpl(record->getDeclContext(), "");
}
std::string ChromeClassTester::GetNamespaceImpl(const DeclContext* context,
std::string candidate) {
switch (context->getDeclKind()) {
case Decl::TranslationUnit: {
return candidate;
}
case Decl::Namespace: {
const NamespaceDecl* decl = dyn_cast<NamespaceDecl>(context);
std::string name_str;
llvm::raw_string_ostream OS(name_str);
if (decl->isAnonymousNamespace())
OS << "<anonymous namespace>";
else
OS << decl;
return GetNamespaceImpl(context->getParent(),
OS.str());
}
default: {
return GetNamespaceImpl(context->getParent(), candidate);
}
}
}
bool ChromeClassTester::InBannedDirectory(SourceLocation loc) {
const SourceManager &SM = instance_.getSourceManager();
SourceLocation spelling_location = SM.getSpellingLoc(loc);
PresumedLoc ploc = SM.getPresumedLoc(spelling_location);
std::string buffer_name;
if (ploc.isInvalid()) {
// If we're in an invalid location, we're looking at things that aren't
// actually stated in the source; treat this as a banned location instead
// of going through our full lookup process.
return true;
} else {
std::string b = ploc.getFilename();
// We need to special case scratch space; which is where clang does its
// macro expansion. We explicitly want to allow people to do otherwise bad
// things through macros that were defined due to third party libraries.
if (b == "<scratch space>")
return true;
// Don't complain about these things in implementation files.
if (ends_with(b, ".cc") || ends_with(b, ".cpp") || ends_with(b, ".mm")) {
return true;
}
// Don't complain about autogenerated protobuf files.
if (ends_with(b, ".pb.h")) {
return true;
}
// We need to munge the paths so that they are relative to the repository
// srcroot. We first resolve the symlinktastic relative path and then
// remove our known srcroot from it if needed.
char resolvedPath[MAXPATHLEN];
if (realpath(b.c_str(), resolvedPath)) {
std::string resolved = resolvedPath;
if (starts_with(resolved, src_root_)) {
b = resolved.substr(src_root_.size());
}
}
for (std::vector<std::string>::const_iterator it =
banned_directories_.begin();
it != banned_directories_.end(); ++it) {
if (starts_with(b, *it)) {
return true;
}
}
}
return false;
}
bool ChromeClassTester::IsIgnoredType(const std::string& base_name) {
for (std::vector<std::string>::const_iterator it =
ignored_record_names_.begin();
it != ignored_record_names_.end(); ++it) {
if (base_name == *it)
return true;
}
return false;
}
<|endoftext|> |
<commit_before>// Copyright 2006-2012, 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.
//
// Modifications as part of cpp-ethereum under the following license:
//
// cpp-ethereum 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.
//
// cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
#include <map>
#include <libsolidity/parsing/Token.h>
#include <boost/range/iterator_range.hpp>
using namespace std;
namespace dev
{
namespace solidity
{
void ElementaryTypeNameToken::assertDetails(Token::Value _baseType, unsigned const& _first, unsigned const& _second)
{
solAssert(Token::isElementaryTypeName(_baseType), "");
if (_baseType == Token::BytesM)
{
solAssert(_second == 0, "There should not be a second size argument to type bytesM.");
solAssert(_first <= 32, "No elementary type bytes" + to_string(_first) + ".");
}
else if (_baseType == Token::UIntM || _baseType == Token::IntM)
{
solAssert(_second == 0, "There should not be a second size argument to type " + string(Token::toString(_baseType)) + ".");
solAssert(
_first <= 256 && _first % 8 == 0,
"No elementary type " + string(Token::toString(_baseType)) + to_string(_first) + "."
);
}
else if (_baseType == Token::UFixedMxN || _baseType == Token::FixedMxN)
{
solAssert(
_first + _second <= 256 && _first % 8 == 0 && _second % 8 == 0,
"No elementary type " + string(Token::toString(_baseType)) + to_string(_first) + "x" + to_string(_second) + "."
);
}
m_token = _baseType;
m_firstNumber = _first;
m_secondNumber = _second;
}
#define T(name, string, precedence) #name,
char const* const Token::m_name[NUM_TOKENS] =
{
TOKEN_LIST(T, T)
};
#undef T
#define T(name, string, precedence) string,
char const* const Token::m_string[NUM_TOKENS] =
{
TOKEN_LIST(T, T)
};
#undef T
#define T(name, string, precedence) precedence,
int8_t const Token::m_precedence[NUM_TOKENS] =
{
TOKEN_LIST(T, T)
};
#undef T
#define KT(a, b, c) 'T',
#define KK(a, b, c) 'K',
char const Token::m_tokenType[] =
{
TOKEN_LIST(KT, KK)
};
int Token::parseSize(string::const_iterator _begin, string::const_iterator _end)
{
try
{
unsigned int m = boost::lexical_cast<int>(boost::make_iterator_range(_begin, _end));
return m;
}
catch(boost::bad_lexical_cast const&)
{
return -1;
}
}
tuple<Token::Value, unsigned int, unsigned int> Token::fromIdentifierOrKeyword(string const& _literal)
{
auto positionM = find_if(_literal.begin(), _literal.end(), ::isdigit);
if (positionM != _literal.end())
{
string baseType(_literal.begin(), positionM);
auto positionX = find_if_not(positionM, _literal.end(), ::isdigit);
int m = parseSize(positionM, positionX);
Token::Value keyword = keywordByName(baseType);
if (keyword == Token::Bytes)
{
if (0 < m && m <= 32 && positionX == _literal.end())
return make_tuple(Token::BytesM, m, 0);
}
else if (keyword == Token::UInt || keyword == Token::Int)
{
if (0 < m && m <= 256 && m % 8 == 0 && positionX == _literal.end())
{
if (keyword == Token::UInt)
return make_tuple(Token::UIntM, m, 0);
else
return make_tuple(Token::IntM, m, 0);
}
}
else if (keyword == Token::UFixed || keyword == Token::Fixed)
{
if (
positionM < positionX &&
positionX < _literal.end() &&
*positionX == 'x' &&
all_of(positionX + 1, _literal.end(), ::isdigit)
) {
int n = parseSize(positionX + 1, _literal.end());
if (
m + n > 0 &&
m + n <= 256 &&
m % 8 == 0 &&
n % 8 == 0
) {
if (keyword == Token::UFixed)
return make_tuple(Token::UFixedMxN, m, n);
else
return make_tuple(Token::FixedMxN, m, n);
}
}
}
return make_tuple(Token::Identifier, 0, 0);
}
return make_tuple(keywordByName(_literal), 0, 0);
}
Token::Value Token::keywordByName(string const& _name)
{
// The following macros are used inside TOKEN_LIST and cause non-keyword tokens to be ignored
// and keywords to be put inside the keywords variable.
#define KEYWORD(name, string, precedence) {string, Token::name},
#define TOKEN(name, string, precedence)
static const map<string, Token::Value> keywords({TOKEN_LIST(TOKEN, KEYWORD)});
#undef KEYWORD
#undef TOKEN
auto it = keywords.find(_name);
return it == keywords.end() ? Token::Identifier : it->second;
}
#undef KT
#undef KK
}
}
<commit_msg>change lexical cast to unsigned int<commit_after>// Copyright 2006-2012, 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.
//
// Modifications as part of cpp-ethereum under the following license:
//
// cpp-ethereum 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.
//
// cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
#include <map>
#include <libsolidity/parsing/Token.h>
#include <boost/range/iterator_range.hpp>
using namespace std;
namespace dev
{
namespace solidity
{
void ElementaryTypeNameToken::assertDetails(Token::Value _baseType, unsigned const& _first, unsigned const& _second)
{
solAssert(Token::isElementaryTypeName(_baseType), "");
if (_baseType == Token::BytesM)
{
solAssert(_second == 0, "There should not be a second size argument to type bytesM.");
solAssert(_first <= 32, "No elementary type bytes" + to_string(_first) + ".");
}
else if (_baseType == Token::UIntM || _baseType == Token::IntM)
{
solAssert(_second == 0, "There should not be a second size argument to type " + string(Token::toString(_baseType)) + ".");
solAssert(
_first <= 256 && _first % 8 == 0,
"No elementary type " + string(Token::toString(_baseType)) + to_string(_first) + "."
);
}
else if (_baseType == Token::UFixedMxN || _baseType == Token::FixedMxN)
{
solAssert(
_first + _second <= 256 && _first % 8 == 0 && _second % 8 == 0,
"No elementary type " + string(Token::toString(_baseType)) + to_string(_first) + "x" + to_string(_second) + "."
);
}
m_token = _baseType;
m_firstNumber = _first;
m_secondNumber = _second;
}
#define T(name, string, precedence) #name,
char const* const Token::m_name[NUM_TOKENS] =
{
TOKEN_LIST(T, T)
};
#undef T
#define T(name, string, precedence) string,
char const* const Token::m_string[NUM_TOKENS] =
{
TOKEN_LIST(T, T)
};
#undef T
#define T(name, string, precedence) precedence,
int8_t const Token::m_precedence[NUM_TOKENS] =
{
TOKEN_LIST(T, T)
};
#undef T
#define KT(a, b, c) 'T',
#define KK(a, b, c) 'K',
char const Token::m_tokenType[] =
{
TOKEN_LIST(KT, KK)
};
int Token::parseSize(string::const_iterator _begin, string::const_iterator _end)
{
try
{
unsigned int m = boost::lexical_cast<unsigned int>(boost::make_iterator_range(_begin, _end));
return m;
}
catch(boost::bad_lexical_cast const&)
{
return -1;
}
}
tuple<Token::Value, unsigned int, unsigned int> Token::fromIdentifierOrKeyword(string const& _literal)
{
auto positionM = find_if(_literal.begin(), _literal.end(), ::isdigit);
if (positionM != _literal.end())
{
string baseType(_literal.begin(), positionM);
auto positionX = find_if_not(positionM, _literal.end(), ::isdigit);
int m = parseSize(positionM, positionX);
Token::Value keyword = keywordByName(baseType);
if (keyword == Token::Bytes)
{
if (0 < m && m <= 32 && positionX == _literal.end())
return make_tuple(Token::BytesM, m, 0);
}
else if (keyword == Token::UInt || keyword == Token::Int)
{
if (0 < m && m <= 256 && m % 8 == 0 && positionX == _literal.end())
{
if (keyword == Token::UInt)
return make_tuple(Token::UIntM, m, 0);
else
return make_tuple(Token::IntM, m, 0);
}
}
else if (keyword == Token::UFixed || keyword == Token::Fixed)
{
if (
positionM < positionX &&
positionX < _literal.end() &&
*positionX == 'x' &&
all_of(positionX + 1, _literal.end(), ::isdigit)
) {
int n = parseSize(positionX + 1, _literal.end());
if (
m + n > 0 &&
m + n <= 256 &&
m % 8 == 0 &&
n % 8 == 0
) {
if (keyword == Token::UFixed)
return make_tuple(Token::UFixedMxN, m, n);
else
return make_tuple(Token::FixedMxN, m, n);
}
}
}
return make_tuple(Token::Identifier, 0, 0);
}
return make_tuple(keywordByName(_literal), 0, 0);
}
Token::Value Token::keywordByName(string const& _name)
{
// The following macros are used inside TOKEN_LIST and cause non-keyword tokens to be ignored
// and keywords to be put inside the keywords variable.
#define KEYWORD(name, string, precedence) {string, Token::name},
#define TOKEN(name, string, precedence)
static const map<string, Token::Value> keywords({TOKEN_LIST(TOKEN, KEYWORD)});
#undef KEYWORD
#undef TOKEN
auto it = keywords.find(_name);
return it == keywords.end() ? Token::Identifier : it->second;
}
#undef KT
#undef KK
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <type_traits>
#include <boost/mpl/contains.hpp>
#include <boost/mpl/vector.hpp>
#include "value.hpp"
namespace blackhole {
namespace attribute {
/*!
* Helper metafunction that checks if the type `T` is compatible with attribute
* internal implementation, i.e. `attribute::value_t` variant can be constructed
* using type `T`.
* @note: This metafunction ignores implicit type conversion.
*/
template<typename T>
struct is_supported :
public boost::mpl::contains<
value_t::types,
typename std::decay<T>::type
>
{};
/*!
* Helper metafunction that checks if `attribute_value_t` can be constructed
* using type `T`.
*/
template<typename T>
struct is_constructible {
typedef boost::mpl::vector<
const char*, // Implicit literal to string conversion.
char,
unsigned char,
short,
unsigned short
> additional_types;
typedef typename std::conditional<
boost::mpl::contains<
additional_types,
typename std::decay<T>::type
>::value || is_supported<T>::value,
std::true_type,
std::false_type
>::type type;
static const bool value = type::value;
};
} // namespace attribute
} // namespace blackhole
<commit_msg>[Aux] Some notes added.<commit_after>#pragma once
#include <type_traits>
#include <boost/mpl/contains.hpp>
#include <boost/mpl/vector.hpp>
#include "value.hpp"
namespace blackhole {
namespace attribute {
/*!
* Helper metafunction that checks if the type `T` is compatible with attribute
* internal implementation, i.e. `attribute::value_t` variant can be constructed
* using type `T`.
* @note: This metafunction ignores implicit type conversion.
*/
template<typename T>
struct is_supported :
public boost::mpl::contains<
value_t::types,
typename std::decay<T>::type
>
{};
/*!
* Helper metafunction that checks if `attribute::value_t` can be constructed
* using type `T`.
* @todo: I don't like it.
*/
template<typename T>
struct is_constructible {
typedef boost::mpl::vector<
const char*, // Implicit literal to string conversion.
char,
unsigned char,
short,
unsigned short
> additional_types;
typedef typename std::conditional<
boost::mpl::contains<
additional_types,
typename std::decay<T>::type
>::value || is_supported<T>::value,
std::true_type,
std::false_type
>::type type;
static const bool value = type::value;
};
} // namespace attribute
} // namespace blackhole
<|endoftext|> |
<commit_before>// $Id: fe_hermite.C,v 1.6 2007-05-23 23:36:11 roystgnr Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson
// 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
// Local includes
#include "elem.h"
#include "fe.h"
#include "fe_macro.h"
// ------------------------------------------------------------
// Hierarchic-specific implementations
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::nodal_soln(const Elem* elem,
const Order order,
const std::vector<Number>& elem_soln,
std::vector<Number>& nodal_soln)
{
const unsigned int n_nodes = elem->n_nodes();
const ElemType type = elem->type();
nodal_soln.resize(n_nodes);
const Order totalorder = static_cast<Order>(order + elem->p_level());
const unsigned int n_sf =
FE<Dim,T>::n_shape_functions(type, totalorder);
for (unsigned int n=0; n<n_nodes; n++)
{
const Point mapped_point = FE<Dim,T>::inverse_map(elem,
elem->point(n));
assert (elem_soln.size() == n_sf);
// Zero before summation
nodal_soln[n] = 0;
// u_i = Sum (alpha_i phi_i)
for (unsigned int i=0; i<n_sf; i++)
nodal_soln[n] += elem_soln[i]*FE<Dim,T>::shape(elem,
order,
i,
mapped_point);
}
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs(const ElemType t, const Order o)
{
assert (o > 2);
// Piecewise (bi/tri)cubic C1 Hermite splines
switch (t)
{
case EDGE2:
assert (o < 4);
case EDGE3:
return (o+1);
case QUAD4:
case QUAD8:
assert (o < 4);
case QUAD9:
return ((o+1)*(o+1));
case HEX8:
case HEX20:
assert (o < 4);
case HEX27:
return ((o+1)*(o+1)*(o+1));
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
error();
return 0;
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs_at_node(const ElemType t,
const Order o,
const unsigned int n)
{
assert (o > 2);
// Piecewise (bi/tri)cubic C1 Hermite splines
switch (t)
{
case EDGE2:
case EDGE3:
{
switch (n)
{
case 0:
case 1:
return 2;
case 3:
// Interior DoFs are carried on Elems
// return (o-3);
return 0;
default:
error();
}
}
case QUAD4:
assert (o < 4);
case QUAD8:
case QUAD9:
{
switch (n)
{
// Vertices
case 0:
case 1:
case 2:
case 3:
return 4;
// Edges
case 4:
case 5:
case 6:
case 7:
return (2*(o-3));
case 8:
// Interior DoFs are carried on Elems
// return ((o-3)*(o-3));
return 0;
default:
error();
}
}
case HEX8:
case HEX20:
assert (o < 4);
case HEX27:
{
switch (n)
{
// Vertices
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
return 8;
// Edges
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
return (4*(o-3));
// Faces
case 20:
case 21:
case 22:
case 23:
case 24:
case 25:
return (2*(o-3)*(o-3));
case 26:
// Interior DoFs are carried on Elems
// return ((o-3)*(o-3)*(o-3));
return 0;
default:
error();
}
}
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
error();
return 0;
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs_per_elem(const ElemType t,
const Order o)
{
assert (o > 2);
switch (t)
{
case EDGE2:
case EDGE3:
return (o-3);
case QUAD4:
assert (o < 4);
case QUAD8:
case QUAD9:
return ((o-3)*(o-3));
case HEX8:
assert (o < 4);
case HEX20:
case HEX27:
return ((o-3)*(o-3)*(o-3));
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
// Will never get here...
error();
return 0;
}
template <unsigned int Dim, FEFamily T>
FEContinuity FE<Dim,T>::get_continuity() const
{
return C_ONE;
}
template <unsigned int Dim, FEFamily T>
bool FE<Dim,T>::is_hierarchic() const
{
return true;
}
#ifdef ENABLE_AMR
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::compute_constraints (DofConstraints &constraints,
DofMap &dof_map,
const unsigned int variable_number,
const Elem* elem)
{
compute_proj_constraints(constraints, dof_map, variable_number, elem);
}
#endif // #ifdef ENABLE_AMR
template <unsigned int Dim, FEFamily T>
bool FE<Dim,T>::shapes_need_reinit() const
{
return true;
}
//--------------------------------------------------------------
// Explicit instantiation of member functions
INSTANTIATE_MBRF(1,HERMITE);
INSTANTIATE_MBRF(2,HERMITE);
INSTANTIATE_MBRF(3,HERMITE);
#ifdef ENABLE_AMR
template void FE<2,HERMITE>::compute_constraints(DofConstraints&, DofMap&,
const unsigned int,
const Elem*);
template void FE<3,HERMITE>::compute_constraints(DofConstraints&, DofMap&,
const unsigned int,
const Elem*);
#endif // #ifdef ENABLE_AMR
<commit_msg>Bugfix for 1D Hermites<commit_after>// $Id: fe_hermite.C,v 1.7 2007-10-18 20:31:28 roystgnr Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson
// 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
// Local includes
#include "elem.h"
#include "fe.h"
#include "fe_macro.h"
// ------------------------------------------------------------
// Hierarchic-specific implementations
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::nodal_soln(const Elem* elem,
const Order order,
const std::vector<Number>& elem_soln,
std::vector<Number>& nodal_soln)
{
const unsigned int n_nodes = elem->n_nodes();
const ElemType type = elem->type();
nodal_soln.resize(n_nodes);
const Order totalorder = static_cast<Order>(order + elem->p_level());
const unsigned int n_sf =
FE<Dim,T>::n_shape_functions(type, totalorder);
for (unsigned int n=0; n<n_nodes; n++)
{
const Point mapped_point = FE<Dim,T>::inverse_map(elem,
elem->point(n));
assert (elem_soln.size() == n_sf);
// Zero before summation
nodal_soln[n] = 0;
// u_i = Sum (alpha_i phi_i)
for (unsigned int i=0; i<n_sf; i++)
nodal_soln[n] += elem_soln[i]*FE<Dim,T>::shape(elem,
order,
i,
mapped_point);
}
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs(const ElemType t, const Order o)
{
assert (o > 2);
// Piecewise (bi/tri)cubic C1 Hermite splines
switch (t)
{
case EDGE2:
assert (o < 4);
case EDGE3:
return (o+1);
case QUAD4:
case QUAD8:
assert (o < 4);
case QUAD9:
return ((o+1)*(o+1));
case HEX8:
case HEX20:
assert (o < 4);
case HEX27:
return ((o+1)*(o+1)*(o+1));
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
error();
return 0;
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs_at_node(const ElemType t,
const Order o,
const unsigned int n)
{
assert (o > 2);
// Piecewise (bi/tri)cubic C1 Hermite splines
switch (t)
{
case EDGE2:
case EDGE3:
{
switch (n)
{
case 0:
case 1:
return 2;
case 2:
// Interior DoFs are carried on Elems
// return (o-3);
return 0;
default:
error();
}
}
case QUAD4:
assert (o < 4);
case QUAD8:
case QUAD9:
{
switch (n)
{
// Vertices
case 0:
case 1:
case 2:
case 3:
return 4;
// Edges
case 4:
case 5:
case 6:
case 7:
return (2*(o-3));
case 8:
// Interior DoFs are carried on Elems
// return ((o-3)*(o-3));
return 0;
default:
error();
}
}
case HEX8:
case HEX20:
assert (o < 4);
case HEX27:
{
switch (n)
{
// Vertices
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
return 8;
// Edges
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
return (4*(o-3));
// Faces
case 20:
case 21:
case 22:
case 23:
case 24:
case 25:
return (2*(o-3)*(o-3));
case 26:
// Interior DoFs are carried on Elems
// return ((o-3)*(o-3)*(o-3));
return 0;
default:
error();
}
}
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
error();
return 0;
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs_per_elem(const ElemType t,
const Order o)
{
assert (o > 2);
switch (t)
{
case EDGE2:
case EDGE3:
return (o-3);
case QUAD4:
assert (o < 4);
case QUAD8:
case QUAD9:
return ((o-3)*(o-3));
case HEX8:
assert (o < 4);
case HEX20:
case HEX27:
return ((o-3)*(o-3)*(o-3));
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
// Will never get here...
error();
return 0;
}
template <unsigned int Dim, FEFamily T>
FEContinuity FE<Dim,T>::get_continuity() const
{
return C_ONE;
}
template <unsigned int Dim, FEFamily T>
bool FE<Dim,T>::is_hierarchic() const
{
return true;
}
#ifdef ENABLE_AMR
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::compute_constraints (DofConstraints &constraints,
DofMap &dof_map,
const unsigned int variable_number,
const Elem* elem)
{
compute_proj_constraints(constraints, dof_map, variable_number, elem);
}
#endif // #ifdef ENABLE_AMR
template <unsigned int Dim, FEFamily T>
bool FE<Dim,T>::shapes_need_reinit() const
{
return true;
}
//--------------------------------------------------------------
// Explicit instantiation of member functions
INSTANTIATE_MBRF(1,HERMITE);
INSTANTIATE_MBRF(2,HERMITE);
INSTANTIATE_MBRF(3,HERMITE);
#ifdef ENABLE_AMR
template void FE<2,HERMITE>::compute_constraints(DofConstraints&, DofMap&,
const unsigned int,
const Elem*);
template void FE<3,HERMITE>::compute_constraints(DofConstraints&, DofMap&,
const unsigned int,
const Elem*);
#endif // #ifdef ENABLE_AMR
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2003-2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY, TITLE, NONINFRINGEMENT 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 "base/util/utils.h"
#include "vocl/VConverter.h"
#include "vocl/VObjectFactory.h"
#include "base/util/WString.h"
#include "base/quoted-printable.h"
VObject* VConverter::parse(const WCHAR* buffer) {
WCHAR *objType = extractObjectType(buffer);
WCHAR *objVersion = extractObjectVersion(buffer);
if(!objType)
return NULL;
VObject* vo = VObjectFactory::createInstance(objType, objVersion);
VProperty *prop;
// Unfolding
WCHAR* buffCopy = unfolding(buffer);
while ( true ) {
prop = readFieldHeader(buffCopy);
if (!prop) {
break;
}
if ( readFieldBody(buffCopy, prop )) {
vo->addProperty(prop);
}
delete prop;
}
delete [] buffCopy; buffCopy = NULL;
return vo;
}
VProperty* VConverter::readFieldHeader(WCHAR* buffer) {
WCHAR* headerIndex = NULL;
WCHAR* quotaIndex = NULL;
quotaIndex = wcschr(buffer, '"');
headerIndex = wcschr(buffer, ':');
if(!headerIndex)
return NULL;
bool quota = false;
// If the header contains a quotation mark,
// then rescan it starting directly after the _quotation mark_
// (not after the end of the header, as in the original code)
// to find the real end of the header.
//
// The reason for this code apparently is that the simple search above
// might have found a headerIndex which points into the middle of
// the quoted string.
//
// A better solution would be to always scan the header properly.
if(quotaIndex && quotaIndex < headerIndex) {
quota = true;
int len = int(wcslen(buffer));
for(int i = int(quotaIndex - buffer) + 1; i < len; i++) {
if(buffer[i] == '"')
quota = !quota;
if(buffer[i] == ':' && !quota) {
headerIndex = &buffer[i];
break;
}
}
}
if(quota)
return NULL;
VProperty* prop = new VProperty(NULL);
WCHAR* header = new WCHAR[wcslen(buffer) + 1];
buffer[headerIndex - buffer] = '\0';
wcscpy(header, buffer);
// Shift the remaing string to the front of the buffer.
// Using wcscpy() for that is incorrect because the standard
// does not guarantee in which order bytes are moved!
// wcscpy(buffer, ++headerIndex);
++headerIndex;
memmove(buffer, headerIndex, (wcslen(headerIndex) + 1) * sizeof(*headerIndex));
//if the header is folded (in .ics files)
//we need to remove the folding
WCHAR* headerFolding = NULL;
if(headerFolding = wcsstr(header, TEXT("\n "))) {
header[headerFolding - header] = '\0';
}
WCHAR seps[] = TEXT(";");
WCHAR *token;
bool first = true;
token = wcstok( header, seps );
while( token != NULL ) {
if (first) {
WCHAR* group = new WCHAR[wcslen(token) + 1];
if(extractGroup(token, group))
prop->addParameter(TEXT("GROUP"), group);
else
delete [] group; group= NULL;
prop->setName(token);
first = false;
}
else {
WCHAR* paramIndex;
paramIndex = wcschr(token, '=');
if(paramIndex) {
WCHAR* paramName = new WCHAR[wcslen(token) + 1];
token[paramIndex - token] = '\0';
wcscpy(paramName, token);
++paramIndex;
memmove(token, paramIndex, (wcslen(paramIndex) + 1) * sizeof(*paramIndex));
WCHAR* paramVal = new WCHAR[wcslen(token) + 1];
wcscpy(paramVal, token);
prop->addParameter(paramName, paramVal);
delete [] paramName; paramName = NULL;
delete [] paramVal; paramVal = NULL;
}
else {
prop->addParameter(token,NULL);
}
}
token = wcstok( NULL, seps );
}
delete [] header; header = NULL;
delete token; token = NULL;
return prop;
}
bool VConverter::readFieldBody(WCHAR* buffer, VProperty* vprop) {
int i = 0;
int j = 0;
int len = 0;
int offset = 0;
bool ret = false;
WCHAR* value = NULL;
WCHAR* allValues = NULL;
WCHAR* c = NULL;
// Get length of all values
while (buffer[i] != '\0') {
if ((buffer[i] == '\r') || buffer[i] == '\n') {
// Get offset of next property
for (j=i+1; buffer[j] != '\0'; j++) {
if((buffer[j] != '\r') && (buffer[j] != '\n'))
break;
}
offset = j;
break;
}
i++;
}
len = i;
if (!len) {
// This field is empty, we MUST consider it adding an empty value
// so any value on client will be deleted.
vprop->addValue(TEXT(""));
ret = true;
goto finally;
}
// This is a string with all values for this property (to parse)
allValues = new WCHAR[len + 1];
wcsncpy(allValues, buffer, len);
allValues[len] = 0;
/* IT IS NOT POSSIBLE TO DECODE BASE64 PARAMETERS IN A WCHAR
AND TAKE THE LENGHT OF A BINARY!!
//
// If needed, decode QP string and copy to 'allValues'.
//
if(vprop->equalsEncoding(TEXT("QUOTED-PRINTABLE"))) {
char* buf = toMultibyte(allValues);
char* dec = qp_decode(buf);
len = strlen(dec);
delete [] buf;
if (dec) {
WCHAR* wdecoded = toWideChar(dec);
delete [] dec;
if (wdecoded) {
wcsncpy(allValues, wdecoded, len);
allValues[len] = 0;
delete [] wdecoded;
}
}
if (!len) {
goto finally;
}
}
//
// If needed, decode B64 string and copy to 'allValues'.
//
if(vprop->equalsEncoding(TEXT("BASE64")) ||
vprop->equalsEncoding(TEXT("B")) ||
vprop->equalsEncoding(TEXT("b")) ) {
char* buf = toMultibyte(allValues);
char* dec = new char[2*strlen(buf) + 1];
b64_decode(dec, buf);
len = strlen(dec);
delete [] buf;
if (dec) {
WCHAR* wdecoded = toWideChar(dec);
delete [] dec;
if (wdecoded) {
wcsncpy(allValues, wdecoded, len);
allValues[len] = 0;
delete [] wdecoded;
}
}
if (!len) {
goto finally;
}
}
*/
// This is a buffer for each single value
value = new WCHAR[len + 1];
wcscpy(value, TEXT(""));
//
// Extract values and add to Vproperty
//
j=0;
c = allValues;
for (i=0; i<len; i++) {
// End of value
if (c[i] == ';') {
vprop->addValue(value);
j = 0;
wcscpy(value, TEXT(""));
}
else {
// Manage escaped chars: jump back-slash
if (c[i] == '\\') {
if (c[i+1]=='n') {
// none: this is "\n" sequence (formatted line ending for 3.0)
}
else {
i++;
if (c[i] == '\0')
break;
}
}
value[j] = c[i];
j++;
value[j] = '\0';
}
}
vprop->addValue(value);
ret = true;
finally:
// Shift buffer for next property to parse
//wcscpy(buffer, buffer+offset);
memmove(buffer, buffer+offset, (wcslen(buffer+offset) + 1)*sizeof(*buffer));
if (value) {
delete [] value; value = NULL;
}
if (allValues) {
delete [] allValues; allValues = NULL;
}
return ret;
}
WCHAR* VConverter::extractObjectProperty(const WCHAR* buffer, const WCHAR *property,
WCHAR * &buffCopy, size_t &buffCopyLen) {
// Memory handling in extractObjectType() and
// extractObjectVersion() was broken:
// they allocated a buffer, then returned a pointer into
// parts of this buffer as result. The caller cannot
// free the result in this case. The functions were also
// duplicating the same code.
//
// This partial fix reuses previously allocated
// memory if the function is called a second time.
size_t len = wcslen(buffer) + 1;
if (buffCopyLen < len) {
if (buffCopy) {
delete [] buffCopy;
}
buffCopy = new WCHAR[len];
buffCopyLen = len;
}
wcscpy(buffCopy, buffer);
WCHAR seps[] = TEXT(":\n");
WCHAR *token;
token = wcstok( buffCopy, seps );
while (token != NULL) {
if(!wcscmp(token, property)) {
token = wcstok( NULL, seps );
WCHAR* index = wcschr(token,'\r');
if(index)
token[index-token] = '\0';
return token;
}
token = wcstok( NULL, seps );
}
return NULL;
}
WCHAR* VConverter::extractObjectType(const WCHAR* buffer) {
static WCHAR* buffCopy;
static size_t buffCopyLen;
return extractObjectProperty(buffer, TEXT("BEGIN"),
buffCopy, buffCopyLen);
}
WCHAR* VConverter::extractObjectVersion(const WCHAR* buffer) {
static WCHAR* buffCopy;
static size_t buffCopyLen;
return extractObjectProperty(buffer, TEXT("VERSION"),
buffCopy, buffCopyLen);
}
bool VConverter::extractGroup(WCHAR* propertyName, WCHAR* propertyGroup) {
WCHAR* groupIndex;
groupIndex = wcschr(propertyName, '.');
if(!groupIndex)
return false;
propertyName[groupIndex - propertyName] = '\0';
wcscpy(propertyGroup, propertyName);
wcscpy(propertyName, ++groupIndex);
return true;
}
<commit_msg>fixed Quoted Printable decoding of vobject<commit_after>/*
* Copyright (C) 2003-2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY, TITLE, NONINFRINGEMENT 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 "base/util/utils.h"
#include "vocl/VConverter.h"
#include "vocl/VObjectFactory.h"
#include "base/util/WString.h"
#include "base/quoted-printable.h"
VObject* VConverter::parse(const WCHAR* buffer) {
WCHAR *objType = extractObjectType(buffer);
WCHAR *objVersion = extractObjectVersion(buffer);
if(!objType)
return NULL;
VObject* vo = VObjectFactory::createInstance(objType, objVersion);
VProperty *prop;
// Unfolding
WCHAR* buffCopy = unfolding(buffer);
while ( true ) {
prop = readFieldHeader(buffCopy);
if (!prop) {
break;
}
if ( readFieldBody(buffCopy, prop )) {
vo->addProperty(prop);
}
delete prop;
}
delete [] buffCopy; buffCopy = NULL;
return vo;
}
VProperty* VConverter::readFieldHeader(WCHAR* buffer) {
WCHAR* headerIndex = NULL;
WCHAR* quotaIndex = NULL;
quotaIndex = wcschr(buffer, '"');
headerIndex = wcschr(buffer, ':');
if(!headerIndex)
return NULL;
bool quota = false;
// If the header contains a quotation mark,
// then rescan it starting directly after the _quotation mark_
// (not after the end of the header, as in the original code)
// to find the real end of the header.
//
// The reason for this code apparently is that the simple search above
// might have found a headerIndex which points into the middle of
// the quoted string.
//
// A better solution would be to always scan the header properly.
if(quotaIndex && quotaIndex < headerIndex) {
quota = true;
int len = int(wcslen(buffer));
for(int i = int(quotaIndex - buffer) + 1; i < len; i++) {
if(buffer[i] == '"')
quota = !quota;
if(buffer[i] == ':' && !quota) {
headerIndex = &buffer[i];
break;
}
}
}
if(quota)
return NULL;
VProperty* prop = new VProperty(NULL);
WCHAR* header = new WCHAR[wcslen(buffer) + 1];
buffer[headerIndex - buffer] = '\0';
wcscpy(header, buffer);
// Shift the remaing string to the front of the buffer.
// Using wcscpy() for that is incorrect because the standard
// does not guarantee in which order bytes are moved!
// wcscpy(buffer, ++headerIndex);
++headerIndex;
memmove(buffer, headerIndex, (wcslen(headerIndex) + 1) * sizeof(*headerIndex));
//if the header is folded (in .ics files)
//we need to remove the folding
WCHAR* headerFolding = NULL;
if(headerFolding = wcsstr(header, TEXT("\n "))) {
header[headerFolding - header] = '\0';
}
WCHAR seps[] = TEXT(";");
WCHAR *token;
bool first = true;
token = wcstok( header, seps );
while( token != NULL ) {
if (first) {
WCHAR* group = new WCHAR[wcslen(token) + 1];
if(extractGroup(token, group))
prop->addParameter(TEXT("GROUP"), group);
else
delete [] group; group= NULL;
prop->setName(token);
first = false;
}
else {
WCHAR* paramIndex;
paramIndex = wcschr(token, '=');
if(paramIndex) {
WCHAR* paramName = new WCHAR[wcslen(token) + 1];
token[paramIndex - token] = '\0';
wcscpy(paramName, token);
++paramIndex;
memmove(token, paramIndex, (wcslen(paramIndex) + 1) * sizeof(*paramIndex));
WCHAR* paramVal = new WCHAR[wcslen(token) + 1];
wcscpy(paramVal, token);
prop->addParameter(paramName, paramVal);
delete [] paramName; paramName = NULL;
delete [] paramVal; paramVal = NULL;
}
else {
prop->addParameter(token,NULL);
}
}
token = wcstok( NULL, seps );
}
delete [] header; header = NULL;
delete token; token = NULL;
return prop;
}
bool VConverter::readFieldBody(WCHAR* buffer, VProperty* vprop) {
int i = 0;
int j = 0;
int len = 0;
int offset = 0;
bool ret = false;
WCHAR* value = NULL;
WCHAR* allValues = NULL;
WCHAR* c = NULL;
// Get length of all values
while (buffer[i] != '\0') {
if ((buffer[i] == '\r') || buffer[i] == '\n') {
// Get offset of next property
for (j=i+1; buffer[j] != '\0'; j++) {
if((buffer[j] != '\r') && (buffer[j] != '\n'))
break;
}
offset = j;
break;
}
i++;
}
len = i;
if (!len) {
// This field is empty, we MUST consider it adding an empty value
// so any value on client will be deleted.
vprop->addValue(TEXT(""));
ret = true;
goto finally;
}
// This is a string with all values for this property (to parse)
allValues = new WCHAR[len + 1];
wcsncpy(allValues, buffer, len);
allValues[len] = 0;
//
// If needed, decode QP string and copy to 'allValues'.
//
if(vprop->equalsEncoding(TEXT("QUOTED-PRINTABLE"))) {
char* buf = toMultibyte(allValues);
char* dec = qp_decode(buf);
len = strlen(dec);
delete [] buf;
if (dec) {
WCHAR* wdecoded = toWideChar(dec);
delete [] dec;
if (wdecoded) {
wcsncpy(allValues, wdecoded, len);
allValues[len] = 0;
delete [] wdecoded;
}
}
if (!len) {
goto finally;
}
}
/*
--- base64 is not decoded ----
IT IS NOT POSSIBLE TO DECODE BASE64 PARAMETERS IN A WCHAR
AND TAKE THE LENGHT OF A BINARY!!
*/
// This is a buffer for each single value
value = new WCHAR[len + 1];
wcscpy(value, TEXT(""));
//
// Extract values and add to Vproperty
//
j=0;
c = allValues;
for (i=0; i<len; i++) {
// End of value
if (c[i] == ';') {
vprop->addValue(value);
j = 0;
wcscpy(value, TEXT(""));
}
else {
// Manage escaped chars: jump back-slash
if (c[i] == '\\') {
if (c[i+1]=='n') {
// none: this is "\n" sequence (formatted line ending for 3.0)
}
else {
i++;
if (c[i] == '\0')
break;
}
}
value[j] = c[i];
j++;
value[j] = '\0';
}
}
vprop->addValue(value);
ret = true;
finally:
// Shift buffer for next property to parse
//wcscpy(buffer, buffer+offset);
memmove(buffer, buffer+offset, (wcslen(buffer+offset) + 1)*sizeof(*buffer));
if (value) {
delete [] value; value = NULL;
}
if (allValues) {
delete [] allValues; allValues = NULL;
}
return ret;
}
WCHAR* VConverter::extractObjectProperty(const WCHAR* buffer, const WCHAR *property,
WCHAR * &buffCopy, size_t &buffCopyLen) {
// Memory handling in extractObjectType() and
// extractObjectVersion() was broken:
// they allocated a buffer, then returned a pointer into
// parts of this buffer as result. The caller cannot
// free the result in this case. The functions were also
// duplicating the same code.
//
// This partial fix reuses previously allocated
// memory if the function is called a second time.
size_t len = wcslen(buffer) + 1;
if (buffCopyLen < len) {
if (buffCopy) {
delete [] buffCopy;
}
buffCopy = new WCHAR[len];
buffCopyLen = len;
}
wcscpy(buffCopy, buffer);
WCHAR seps[] = TEXT(":\n");
WCHAR *token;
token = wcstok( buffCopy, seps );
while (token != NULL) {
if(!wcscmp(token, property)) {
token = wcstok( NULL, seps );
WCHAR* index = wcschr(token,'\r');
if(index)
token[index-token] = '\0';
return token;
}
token = wcstok( NULL, seps );
}
return NULL;
}
WCHAR* VConverter::extractObjectType(const WCHAR* buffer) {
static WCHAR* buffCopy;
static size_t buffCopyLen;
return extractObjectProperty(buffer, TEXT("BEGIN"),
buffCopy, buffCopyLen);
}
WCHAR* VConverter::extractObjectVersion(const WCHAR* buffer) {
static WCHAR* buffCopy;
static size_t buffCopyLen;
return extractObjectProperty(buffer, TEXT("VERSION"),
buffCopy, buffCopyLen);
}
bool VConverter::extractGroup(WCHAR* propertyName, WCHAR* propertyGroup) {
WCHAR* groupIndex;
groupIndex = wcschr(propertyName, '.');
if(!groupIndex)
return false;
propertyName[groupIndex - propertyName] = '\0';
wcscpy(propertyGroup, propertyName);
wcscpy(propertyName, ++groupIndex);
return true;
}
<|endoftext|> |
<commit_before>
#include "ttimer.h"
#include "texception.h"
#ifdef _WIN32
#include <windows.h>
//moto strano: se togliamo l'include della glut non linka
#include <GL/glut.h>
//------------------------------------------------------------------------------
namespace
{
void CALLBACK ElapsedTimeCB(UINT uID, UINT uMsg,
DWORD dwUser, DWORD dw1,
DWORD dw2);
};
//------------------------------------------------------------------------------
class TTimer::Imp
{
public:
Imp(std::string name, UINT timerRes, TTimer::Type type, TTimer *timer);
~Imp();
void start(UINT delay)
{
if (m_started)
throw TException("The timer is already started");
m_timerID = timeSetEvent(delay, m_timerRes,
(LPTIMECALLBACK)ElapsedTimeCB, (DWORD) this,
m_type | TIME_CALLBACK_FUNCTION);
m_delay = delay;
m_ticks = 0;
if (m_timerID == NULL)
throw TException("Unable to start timer");
m_started = true;
}
void stop()
{
if (m_started)
timeKillEvent(m_timerID);
m_started = false;
}
std::string getName() { return m_name; }
TUINT64 getTicks() { return m_ticks; }
UINT getDelay() { return m_delay; }
std::string m_name;
UINT m_timerRes;
UINT m_type;
TTimer *m_timer;
UINT m_timerID;
UINT m_delay;
TUINT64 m_ticks;
bool m_started;
TGenericTimerAction *m_action;
};
//------------------------------------------------------------------------------
TTimer::Imp::Imp(std::string name, UINT timerRes, TTimer::Type type, TTimer *timer)
: m_name(name), m_timerRes(timerRes), m_timer(timer), m_type(type), m_timerID(NULL), m_ticks(0), m_delay(0), m_started(false), m_action(0)
{
TIMECAPS tc;
if (timeGetDevCaps(&tc, sizeof(TIMECAPS)) != TIMERR_NOERROR) {
throw TException("Unable to create timer");
}
m_timerRes = tmin((int)tmax((int)tc.wPeriodMin, (int)m_timerRes), (int)tc.wPeriodMax);
timeBeginPeriod(m_timerRes);
switch (type) {
case TTimer::OneShot:
m_type = TIME_ONESHOT;
break;
case TTimer::Periodic:
m_type = TIME_PERIODIC;
break;
default:
throw TException("Unexpected timer type");
break;
}
}
//------------------------------------------------------------------------------
TTimer::Imp::~Imp()
{
stop();
timeEndPeriod(m_timerRes);
if (m_action)
delete m_action;
}
//------------------------------------------------------------------------------
namespace
{
void CALLBACK ElapsedTimeCB(UINT uID, UINT uMsg,
DWORD dwUser, DWORD dw1,
DWORD dw2)
{
TTimer::Imp *imp = reinterpret_cast<TTimer::Imp *>(dwUser);
imp->m_ticks++;
if (imp->m_action)
imp->m_action->sendCommand(imp->m_ticks);
}
};
#elif LINUX
#include <SDL/SDL_timer.h>
#include <SDL/SDL.h>
#include "tthread.h"
namespace
{
Uint32 ElapsedTimeCB(Uint32 interval, void *param);
}
class TTimer::Imp
{
public:
Imp(std::string name, UINT timerRes, TTimer::Type type, TTimer *timer)
: m_action(0), m_ticks(0)
{
}
~Imp() {}
void start(UINT delay)
{
static bool first = true;
if (first) {
SDL_Init(SDL_INIT_TIMER);
first = false;
}
m_timerID = SDL_AddTimer(delay, ElapsedTimeCB, this);
}
void stop()
{
SDL_RemoveTimer(m_timerID);
}
std::string getName() { return m_name; }
TUINT64 getTicks() { return m_ticks; }
UINT getDelay() { return m_delay; }
std::string m_name;
UINT m_timerRes;
UINT m_type;
TTimer *m_timer;
SDL_TimerID m_timerID;
UINT m_delay;
TUINT64 m_ticks;
bool m_started;
TGenericTimerAction *m_action;
};
class SendCommandMSG : public TThread::Msg
{
TTimer::Imp *m_ztimp;
public:
SendCommandMSG(TTimer::Imp *ztimp) : TThread::Msg(), m_ztimp(ztimp)
{
}
~SendCommandMSG() {}
TThread::Msg *clone() const { return new SendCommandMSG(*this); }
void onDeliver()
{
if (m_ztimp->m_action)
m_ztimp->m_action->sendCommand(m_ztimp->m_ticks);
}
};
namespace
{
Uint32 ElapsedTimeCB(Uint32 interval, void *param)
{
TTimer::Imp *imp = reinterpret_cast<TTimer::Imp *>(param);
imp->m_ticks++;
SendCommandMSG(imp).send();
return interval;
}
}
#elif __sgi
class TTimer::Imp
{
public:
Imp(std::string name, UINT timerRes, TTimer::Type type, TTimer *timer)
: m_action(0) {}
~Imp() {}
void start(UINT delay)
{
if (m_started)
throw TException("The timer is already started");
m_started = true;
}
void stop()
{
m_started = false;
}
std::string getName() { return m_name; }
TUINT64 getTicks() { return m_ticks; }
UINT getDelay() { return m_delay; }
std::string m_name;
UINT m_timerRes;
UINT m_type;
TTimer *m_timer;
UINT m_timerID;
UINT m_delay;
TUINT64 m_ticks;
bool m_started;
TGenericTimerAction *m_action;
};
#elif MACOSX
class TTimer::Imp
{
public:
Imp(std::string name, UINT timerRes, TTimer::Type type, TTimer *timer)
: m_action(0) {}
~Imp() {}
void start(UINT delay)
{
if (m_started)
throw TException("The timer is already started");
throw TException("The timer is not yet available under MAC :(");
m_started = true;
}
void stop()
{
m_started = false;
}
std::string getName() { return m_name; }
TUINT64 getTicks() { return m_ticks; }
UINT getDelay() { return m_delay; }
std::string m_name;
UINT m_timerRes;
UINT m_type;
TTimer *m_timer;
UINT m_timerID;
UINT m_delay;
TUINT64 m_ticks;
bool m_started;
TGenericTimerAction *m_action;
};
#endif
//===============================================================================
//
// TTimer
//
//===============================================================================
TTimer::TTimer(const std::string &name, UINT timerRes, Type type)
: m_imp(new TTimer::Imp(name, timerRes, type, this))
{
}
//--------------------------------------------------------------------------------
TTimer::~TTimer()
{
}
//--------------------------------------------------------------------------------
void TTimer::start(UINT delay)
{
m_imp->start(delay);
}
//--------------------------------------------------------------------------------
bool TTimer::isStarted() const
{
return m_imp->m_started;
}
//--------------------------------------------------------------------------------
void TTimer::stop()
{
m_imp->stop();
}
//--------------------------------------------------------------------------------
std::string TTimer::getName() const
{
return m_imp->getName();
}
//--------------------------------------------------------------------------------
TUINT64 TTimer::getTicks() const
{
return m_imp->getTicks();
}
//--------------------------------------------------------------------------------
UINT TTimer::getDelay() const
{
return m_imp->getDelay();
}
//--------------------------------------------------------------------------------
void TTimer::setAction(TGenericTimerAction *action)
{
if (m_imp->m_action)
delete m_imp->m_action;
m_imp->m_action = action;
}
<commit_msg>Correct class use with TTimer on Linux<commit_after>
#include "ttimer.h"
#include "tthreadmessage.h"
#include "texception.h"
#ifdef _WIN32
#include <windows.h>
//moto strano: se togliamo l'include della glut non linka
#include <GL/glut.h>
//------------------------------------------------------------------------------
namespace
{
void CALLBACK ElapsedTimeCB(UINT uID, UINT uMsg,
DWORD dwUser, DWORD dw1,
DWORD dw2);
};
//------------------------------------------------------------------------------
class TTimer::Imp
{
public:
Imp(std::string name, UINT timerRes, TTimer::Type type, TTimer *timer);
~Imp();
void start(UINT delay)
{
if (m_started)
throw TException("The timer is already started");
m_timerID = timeSetEvent(delay, m_timerRes,
(LPTIMECALLBACK)ElapsedTimeCB, (DWORD) this,
m_type | TIME_CALLBACK_FUNCTION);
m_delay = delay;
m_ticks = 0;
if (m_timerID == NULL)
throw TException("Unable to start timer");
m_started = true;
}
void stop()
{
if (m_started)
timeKillEvent(m_timerID);
m_started = false;
}
std::string getName() { return m_name; }
TUINT64 getTicks() { return m_ticks; }
UINT getDelay() { return m_delay; }
std::string m_name;
UINT m_timerRes;
UINT m_type;
TTimer *m_timer;
UINT m_timerID;
UINT m_delay;
TUINT64 m_ticks;
bool m_started;
TGenericTimerAction *m_action;
};
//------------------------------------------------------------------------------
TTimer::Imp::Imp(std::string name, UINT timerRes, TTimer::Type type, TTimer *timer)
: m_name(name), m_timerRes(timerRes), m_timer(timer), m_type(type), m_timerID(NULL), m_ticks(0), m_delay(0), m_started(false), m_action(0)
{
TIMECAPS tc;
if (timeGetDevCaps(&tc, sizeof(TIMECAPS)) != TIMERR_NOERROR) {
throw TException("Unable to create timer");
}
m_timerRes = tmin((int)tmax((int)tc.wPeriodMin, (int)m_timerRes), (int)tc.wPeriodMax);
timeBeginPeriod(m_timerRes);
switch (type) {
case TTimer::OneShot:
m_type = TIME_ONESHOT;
break;
case TTimer::Periodic:
m_type = TIME_PERIODIC;
break;
default:
throw TException("Unexpected timer type");
break;
}
}
//------------------------------------------------------------------------------
TTimer::Imp::~Imp()
{
stop();
timeEndPeriod(m_timerRes);
if (m_action)
delete m_action;
}
//------------------------------------------------------------------------------
namespace
{
void CALLBACK ElapsedTimeCB(UINT uID, UINT uMsg,
DWORD dwUser, DWORD dw1,
DWORD dw2)
{
TTimer::Imp *imp = reinterpret_cast<TTimer::Imp *>(dwUser);
imp->m_ticks++;
if (imp->m_action)
imp->m_action->sendCommand(imp->m_ticks);
}
};
#elif LINUX
#include <SDL/SDL_timer.h>
#include <SDL/SDL.h>
#include "tthread.h"
namespace
{
Uint32 ElapsedTimeCB(Uint32 interval, void *param);
}
class TTimer::Imp
{
public:
Imp(std::string name, UINT timerRes, TTimer::Type type, TTimer *timer)
: m_action(0), m_ticks(0)
{
}
~Imp() {}
void start(UINT delay)
{
static bool first = true;
if (first) {
SDL_Init(SDL_INIT_TIMER);
first = false;
}
m_timerID = SDL_AddTimer(delay, ElapsedTimeCB, this);
}
void stop()
{
SDL_RemoveTimer(m_timerID);
}
std::string getName() { return m_name; }
TUINT64 getTicks() { return m_ticks; }
UINT getDelay() { return m_delay; }
std::string m_name;
UINT m_timerRes;
UINT m_type;
TTimer *m_timer;
SDL_TimerID m_timerID;
UINT m_delay;
TUINT64 m_ticks;
bool m_started;
TGenericTimerAction *m_action;
};
class SendCommandMSG : public TThread::Message
{
TTimer::Imp *m_ztimp;
public:
SendCommandMSG(TTimer::Imp *ztimp) : TThread::Message(), m_ztimp(ztimp)
{
}
~SendCommandMSG() {}
TThread::Message *clone() const { return new SendCommandMSG(*this); }
void onDeliver()
{
if (m_ztimp->m_action)
m_ztimp->m_action->sendCommand(m_ztimp->m_ticks);
}
};
namespace
{
Uint32 ElapsedTimeCB(Uint32 interval, void *param)
{
TTimer::Imp *imp = reinterpret_cast<TTimer::Imp *>(param);
imp->m_ticks++;
SendCommandMSG(imp).send();
return interval;
}
}
#elif __sgi
class TTimer::Imp
{
public:
Imp(std::string name, UINT timerRes, TTimer::Type type, TTimer *timer)
: m_action(0) {}
~Imp() {}
void start(UINT delay)
{
if (m_started)
throw TException("The timer is already started");
m_started = true;
}
void stop()
{
m_started = false;
}
std::string getName() { return m_name; }
TUINT64 getTicks() { return m_ticks; }
UINT getDelay() { return m_delay; }
std::string m_name;
UINT m_timerRes;
UINT m_type;
TTimer *m_timer;
UINT m_timerID;
UINT m_delay;
TUINT64 m_ticks;
bool m_started;
TGenericTimerAction *m_action;
};
#elif MACOSX
class TTimer::Imp
{
public:
Imp(std::string name, UINT timerRes, TTimer::Type type, TTimer *timer)
: m_action(0) {}
~Imp() {}
void start(UINT delay)
{
if (m_started)
throw TException("The timer is already started");
throw TException("The timer is not yet available under MAC :(");
m_started = true;
}
void stop()
{
m_started = false;
}
std::string getName() { return m_name; }
TUINT64 getTicks() { return m_ticks; }
UINT getDelay() { return m_delay; }
std::string m_name;
UINT m_timerRes;
UINT m_type;
TTimer *m_timer;
UINT m_timerID;
UINT m_delay;
TUINT64 m_ticks;
bool m_started;
TGenericTimerAction *m_action;
};
#endif
//===============================================================================
//
// TTimer
//
//===============================================================================
TTimer::TTimer(const std::string &name, UINT timerRes, Type type)
: m_imp(new TTimer::Imp(name, timerRes, type, this))
{
}
//--------------------------------------------------------------------------------
TTimer::~TTimer()
{
}
//--------------------------------------------------------------------------------
void TTimer::start(UINT delay)
{
m_imp->start(delay);
}
//--------------------------------------------------------------------------------
bool TTimer::isStarted() const
{
return m_imp->m_started;
}
//--------------------------------------------------------------------------------
void TTimer::stop()
{
m_imp->stop();
}
//--------------------------------------------------------------------------------
std::string TTimer::getName() const
{
return m_imp->getName();
}
//--------------------------------------------------------------------------------
TUINT64 TTimer::getTicks() const
{
return m_imp->getTicks();
}
//--------------------------------------------------------------------------------
UINT TTimer::getDelay() const
{
return m_imp->getDelay();
}
//--------------------------------------------------------------------------------
void TTimer::setAction(TGenericTimerAction *action)
{
if (m_imp->m_action)
delete m_imp->m_action;
m_imp->m_action = action;
}
<|endoftext|> |
<commit_before>/*
*
* Copyright 2015 gRPC 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.
*
*/
// Generates Objective C gRPC service interface out of Protobuf IDL.
#include <memory>
#include "src/compiler/config.h"
#include "src/compiler/objective_c_generator.h"
#include "src/compiler/objective_c_generator_helpers.h"
#include <google/protobuf/compiler/objectivec/objectivec_helpers.h>
using ::google::protobuf::compiler::objectivec::
IsProtobufLibraryBundledProtoFile;
using ::google::protobuf::compiler::objectivec::ProtobufLibraryFrameworkName;
using ::grpc_objective_c_generator::FrameworkImport;
using ::grpc_objective_c_generator::LocalImport;
using ::grpc_objective_c_generator::PreprocIfElse;
using ::grpc_objective_c_generator::PreprocIfNot;
using ::grpc_objective_c_generator::SystemImport;
namespace {
inline ::grpc::string ImportProtoHeaders(
const grpc::protobuf::FileDescriptor* dep, const char* indent,
const ::grpc::string& framework) {
::grpc::string header = grpc_objective_c_generator::MessageHeaderName(dep);
if (!IsProtobufLibraryBundledProtoFile(dep)) {
if (framework.empty()) {
return indent + LocalImport(header);
} else {
return indent + FrameworkImport(header, framework);
}
}
::grpc::string base_name = header;
grpc_generator::StripPrefix(&base_name, "google/protobuf/");
// create the import code snippet
::grpc::string framework_header =
::grpc::string(ProtobufLibraryFrameworkName) + "/" + base_name;
static const ::grpc::string kFrameworkImportsCondition =
"GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS";
return PreprocIfElse(kFrameworkImportsCondition,
indent + SystemImport(framework_header),
indent + LocalImport(header));
}
} // namespace
class ObjectiveCGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator {
public:
ObjectiveCGrpcGenerator() {}
virtual ~ObjectiveCGrpcGenerator() {}
public:
virtual bool Generate(const grpc::protobuf::FileDescriptor* file,
const ::grpc::string& parameter,
grpc::protobuf::compiler::GeneratorContext* context,
::grpc::string* error) const {
if (file->service_count() == 0) {
// No services. Do nothing.
return true;
}
::grpc::string framework;
std::vector<::grpc::string> params_list =
grpc_generator::tokenize(parameter, ",");
for (auto param_str = params_list.begin(); param_str != params_list.end();
++param_str) {
std::vector<::grpc::string> param =
grpc_generator::tokenize(*param_str, "=");
if (param[0] == "generate_for_named_framework") {
if (param.size() != 2) {
*error =
grpc::string("Format: generate_for_named_framework=<Framework>");
return false;
} else if (param[1].empty()) {
*error = grpc::string(
"Name of framework cannot be empty for parameter: ") +
param[0];
return false;
}
framework = param[1];
}
}
static const ::grpc::string kNonNullBegin = "NS_ASSUME_NONNULL_BEGIN\n";
static const ::grpc::string kNonNullEnd = "NS_ASSUME_NONNULL_END\n";
static const ::grpc::string kProtocolOnly = "GPB_GRPC_PROTOCOL_ONLY";
static const ::grpc::string kForwardDeclare =
"GPB_GRPC_FORWARD_DECLARE_MESSAGE_PROTO";
::grpc::string file_name =
google::protobuf::compiler::objectivec::FilePath(file);
grpc_objective_c_generator::Parameters generator_params;
generator_params.no_v1_compatibility = false;
if (!parameter.empty()) {
std::vector<grpc::string> parameters_list =
grpc_generator::tokenize(parameter, ",");
for (auto parameter_string = parameters_list.begin();
parameter_string != parameters_list.end(); parameter_string++) {
std::vector<grpc::string> param =
grpc_generator::tokenize(*parameter_string, "=");
if (param[0] == "no_v1_compatibility") {
generator_params.no_v1_compatibility = true;
}
}
}
{
// Generate .pbrpc.h
::grpc::string imports;
if (framework.empty()) {
imports = LocalImport(file_name + ".pbobjc.h");
} else {
imports = FrameworkImport(file_name + ".pbobjc.h", framework);
}
::grpc::string system_imports =
SystemImport("ProtoRPC/ProtoService.h") +
(generator_params.no_v1_compatibility
? SystemImport("ProtoRPC/ProtoRPC.h")
: SystemImport("ProtoRPC/ProtoRPCLegacy.h"));
if (!generator_params.no_v1_compatibility) {
system_imports += SystemImport("RxLibrary/GRXWriteable.h") +
SystemImport("RxLibrary/GRXWriter.h");
}
::grpc::string forward_declarations =
"@class GRPCUnaryProtoCall;\n"
"@class GRPCStreamingProtoCall;\n"
"@class GRPCCallOptions;\n"
"@protocol GRPCProtoResponseHandler;\n";
if (!generator_params.no_v1_compatibility) {
forward_declarations += "@class GRPCProtoCall;\n";
}
forward_declarations += "\n";
::grpc::string class_declarations =
grpc_objective_c_generator::GetAllMessageClasses(file);
::grpc::string class_imports;
for (int i = 0; i < file->dependency_count(); i++) {
class_imports +=
ImportProtoHeaders(file->dependency(i), " ", framework);
}
::grpc::string ng_protocols;
for (int i = 0; i < file->service_count(); i++) {
const grpc::protobuf::ServiceDescriptor* service = file->service(i);
ng_protocols += grpc_objective_c_generator::GetV2Protocol(service);
}
::grpc::string protocols;
for (int i = 0; i < file->service_count(); i++) {
const grpc::protobuf::ServiceDescriptor* service = file->service(i);
protocols +=
grpc_objective_c_generator::GetProtocol(service, generator_params);
}
::grpc::string interfaces;
for (int i = 0; i < file->service_count(); i++) {
const grpc::protobuf::ServiceDescriptor* service = file->service(i);
interfaces +=
grpc_objective_c_generator::GetInterface(service, generator_params);
}
Write(context, file_name + ".pbrpc.h",
PreprocIfNot(kForwardDeclare, imports) + "\n" +
PreprocIfNot(kProtocolOnly, system_imports) + "\n" +
class_declarations + "\n" +
PreprocIfNot(kForwardDeclare, class_imports) + "\n" +
forward_declarations + "\n" + kNonNullBegin + "\n" +
ng_protocols + protocols + "\n" +
PreprocIfNot(kProtocolOnly, interfaces) + "\n" + kNonNullEnd +
"\n");
}
{
// Generate .pbrpc.m
::grpc::string imports;
if (framework.empty()) {
imports = LocalImport(file_name + ".pbrpc.h") +
LocalImport(file_name + ".pbobjc.h");
} else {
imports = FrameworkImport(file_name + ".pbrpc.h", framework) +
FrameworkImport(file_name + ".pbobjc.h", framework);
}
imports += (generator_params.no_v1_compatibility
? SystemImport("ProtoRPC/ProtoRPC.h")
: SystemImport("ProtoRPC/ProtoRPCLegacy.h"));
if (!generator_params.no_v1_compatibility) {
imports += SystemImport("RxLibrary/GRXWriter+Immediate.h");
}
::grpc::string class_imports;
for (int i = 0; i < file->dependency_count(); i++) {
class_imports += ImportProtoHeaders(file->dependency(i), "", framework);
}
::grpc::string definitions;
for (int i = 0; i < file->service_count(); i++) {
const grpc::protobuf::ServiceDescriptor* service = file->service(i);
definitions +=
grpc_objective_c_generator::GetSource(service, generator_params);
}
Write(context, file_name + ".pbrpc.m",
PreprocIfNot(kProtocolOnly,
imports + "\n" + class_imports + "\n" + definitions));
}
return true;
}
private:
// Write the given code into the given file.
void Write(grpc::protobuf::compiler::GeneratorContext* context,
const ::grpc::string& filename, const ::grpc::string& code) const {
std::unique_ptr<grpc::protobuf::io::ZeroCopyOutputStream> output(
context->Open(filename));
grpc::protobuf::io::CodedOutputStream coded_out(output.get());
coded_out.WriteRaw(code.data(), code.size());
}
};
int main(int argc, char* argv[]) {
ObjectiveCGrpcGenerator generator;
return grpc::protobuf::compiler::PluginMain(argc, argv, &generator);
}
<commit_msg>objc: add autogenerated header to generated files<commit_after>/*
*
* Copyright 2015 gRPC 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.
*
*/
// Generates Objective C gRPC service interface out of Protobuf IDL.
#include <memory>
#include "src/compiler/config.h"
#include "src/compiler/objective_c_generator.h"
#include "src/compiler/objective_c_generator_helpers.h"
#include <google/protobuf/compiler/objectivec/objectivec_helpers.h>
using ::google::protobuf::compiler::objectivec::
IsProtobufLibraryBundledProtoFile;
using ::google::protobuf::compiler::objectivec::ProtobufLibraryFrameworkName;
using ::grpc_objective_c_generator::FrameworkImport;
using ::grpc_objective_c_generator::LocalImport;
using ::grpc_objective_c_generator::PreprocIfElse;
using ::grpc_objective_c_generator::PreprocIfNot;
using ::grpc_objective_c_generator::SystemImport;
namespace {
inline ::grpc::string ImportProtoHeaders(
const grpc::protobuf::FileDescriptor* dep, const char* indent,
const ::grpc::string& framework) {
::grpc::string header = grpc_objective_c_generator::MessageHeaderName(dep);
if (!IsProtobufLibraryBundledProtoFile(dep)) {
if (framework.empty()) {
return indent + LocalImport(header);
} else {
return indent + FrameworkImport(header, framework);
}
}
::grpc::string base_name = header;
grpc_generator::StripPrefix(&base_name, "google/protobuf/");
// create the import code snippet
::grpc::string framework_header =
::grpc::string(ProtobufLibraryFrameworkName) + "/" + base_name;
static const ::grpc::string kFrameworkImportsCondition =
"GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS";
return PreprocIfElse(kFrameworkImportsCondition,
indent + SystemImport(framework_header),
indent + LocalImport(header));
}
} // namespace
class ObjectiveCGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator {
public:
ObjectiveCGrpcGenerator() {}
virtual ~ObjectiveCGrpcGenerator() {}
public:
virtual bool Generate(const grpc::protobuf::FileDescriptor* file,
const ::grpc::string& parameter,
grpc::protobuf::compiler::GeneratorContext* context,
::grpc::string* error) const {
if (file->service_count() == 0) {
// No services. Do nothing.
return true;
}
::grpc::string framework;
std::vector<::grpc::string> params_list =
grpc_generator::tokenize(parameter, ",");
for (auto param_str = params_list.begin(); param_str != params_list.end();
++param_str) {
std::vector<::grpc::string> param =
grpc_generator::tokenize(*param_str, "=");
if (param[0] == "generate_for_named_framework") {
if (param.size() != 2) {
*error =
grpc::string("Format: generate_for_named_framework=<Framework>");
return false;
} else if (param[1].empty()) {
*error = grpc::string(
"Name of framework cannot be empty for parameter: ") +
param[0];
return false;
}
framework = param[1];
}
}
static const ::grpc::string kNonNullBegin = "NS_ASSUME_NONNULL_BEGIN\n";
static const ::grpc::string kNonNullEnd = "NS_ASSUME_NONNULL_END\n";
static const ::grpc::string kProtocolOnly = "GPB_GRPC_PROTOCOL_ONLY";
static const ::grpc::string kForwardDeclare =
"GPB_GRPC_FORWARD_DECLARE_MESSAGE_PROTO";
::grpc::string file_name =
google::protobuf::compiler::objectivec::FilePath(file);
grpc_objective_c_generator::Parameters generator_params;
generator_params.no_v1_compatibility = false;
if (!parameter.empty()) {
std::vector<grpc::string> parameters_list =
grpc_generator::tokenize(parameter, ",");
for (auto parameter_string = parameters_list.begin();
parameter_string != parameters_list.end(); parameter_string++) {
std::vector<grpc::string> param =
grpc_generator::tokenize(*parameter_string, "=");
if (param[0] == "no_v1_compatibility") {
generator_params.no_v1_compatibility = true;
}
}
}
// Write out a file header.
::grpc::string file_header =
"// Code generated by gRPC proto compiler. DO NOT EDIT!\n"
"// source: " +
file->name() + "\n\n";
{
// Generate .pbrpc.h
::grpc::string imports;
if (framework.empty()) {
imports = LocalImport(file_name + ".pbobjc.h");
} else {
imports = FrameworkImport(file_name + ".pbobjc.h", framework);
}
::grpc::string system_imports =
SystemImport("ProtoRPC/ProtoService.h") +
(generator_params.no_v1_compatibility
? SystemImport("ProtoRPC/ProtoRPC.h")
: SystemImport("ProtoRPC/ProtoRPCLegacy.h"));
if (!generator_params.no_v1_compatibility) {
system_imports += SystemImport("RxLibrary/GRXWriteable.h") +
SystemImport("RxLibrary/GRXWriter.h");
}
::grpc::string forward_declarations =
"@class GRPCUnaryProtoCall;\n"
"@class GRPCStreamingProtoCall;\n"
"@class GRPCCallOptions;\n"
"@protocol GRPCProtoResponseHandler;\n";
if (!generator_params.no_v1_compatibility) {
forward_declarations += "@class GRPCProtoCall;\n";
}
forward_declarations += "\n";
::grpc::string class_declarations =
grpc_objective_c_generator::GetAllMessageClasses(file);
::grpc::string class_imports;
for (int i = 0; i < file->dependency_count(); i++) {
class_imports +=
ImportProtoHeaders(file->dependency(i), " ", framework);
}
::grpc::string ng_protocols;
for (int i = 0; i < file->service_count(); i++) {
const grpc::protobuf::ServiceDescriptor* service = file->service(i);
ng_protocols += grpc_objective_c_generator::GetV2Protocol(service);
}
::grpc::string protocols;
for (int i = 0; i < file->service_count(); i++) {
const grpc::protobuf::ServiceDescriptor* service = file->service(i);
protocols +=
grpc_objective_c_generator::GetProtocol(service, generator_params);
}
::grpc::string interfaces;
for (int i = 0; i < file->service_count(); i++) {
const grpc::protobuf::ServiceDescriptor* service = file->service(i);
interfaces +=
grpc_objective_c_generator::GetInterface(service, generator_params);
}
Write(context, file_name + ".pbrpc.h",
file_header + PreprocIfNot(kForwardDeclare, imports) + "\n" +
PreprocIfNot(kProtocolOnly, system_imports) + "\n" +
class_declarations + "\n" +
PreprocIfNot(kForwardDeclare, class_imports) + "\n" +
forward_declarations + "\n" + kNonNullBegin + "\n" +
ng_protocols + protocols + "\n" +
PreprocIfNot(kProtocolOnly, interfaces) + "\n" + kNonNullEnd +
"\n");
}
{
// Generate .pbrpc.m
::grpc::string imports;
if (framework.empty()) {
imports = LocalImport(file_name + ".pbrpc.h") +
LocalImport(file_name + ".pbobjc.h");
} else {
imports = FrameworkImport(file_name + ".pbrpc.h", framework) +
FrameworkImport(file_name + ".pbobjc.h", framework);
}
imports += (generator_params.no_v1_compatibility
? SystemImport("ProtoRPC/ProtoRPC.h")
: SystemImport("ProtoRPC/ProtoRPCLegacy.h"));
if (!generator_params.no_v1_compatibility) {
imports += SystemImport("RxLibrary/GRXWriter+Immediate.h");
}
::grpc::string class_imports;
for (int i = 0; i < file->dependency_count(); i++) {
class_imports += ImportProtoHeaders(file->dependency(i), "", framework);
}
::grpc::string definitions;
for (int i = 0; i < file->service_count(); i++) {
const grpc::protobuf::ServiceDescriptor* service = file->service(i);
definitions +=
grpc_objective_c_generator::GetSource(service, generator_params);
}
Write(context, file_name + ".pbrpc.m",
file_header +
PreprocIfNot(kProtocolOnly, imports + "\n" + class_imports +
"\n" + definitions));
}
return true;
}
private:
// Write the given code into the given file.
void Write(grpc::protobuf::compiler::GeneratorContext* context,
const ::grpc::string& filename, const ::grpc::string& code) const {
std::unique_ptr<grpc::protobuf::io::ZeroCopyOutputStream> output(
context->Open(filename));
grpc::protobuf::io::CodedOutputStream coded_out(output.get());
coded_out.WriteRaw(code.data(), code.size());
}
};
int main(int argc, char* argv[]) {
ObjectiveCGrpcGenerator generator;
return grpc::protobuf::compiler::PluginMain(argc, argv, &generator);
}
<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 3/14/2020, 9:03:01 PM
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint &operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint &operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator<=(const Mint &a) const { return x <= a.x; }
bool operator>(const Mint &a) const { return x > a.x; }
bool operator>=(const Mint &a) const { return x >= a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
bool operator!=(const Mint &a) const { return !(*this == a); }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- frequently used constexpr -----
constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- main() -----
int main()
{
double A, B, C;
cin >> A >> B >> C;
if (sqrt(A) + sqrt(B) + epsilon < sqrt(C))
{
Yes();
}
No();
}
<commit_msg>tried C.cpp to 'C'<commit_after>#define DEBUG 1
/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 3/14/2020, 9:03:01 PM
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint &operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint &operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator<=(const Mint &a) const { return x <= a.x; }
bool operator>(const Mint &a) const { return x > a.x; }
bool operator>=(const Mint &a) const { return x >= a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
bool operator!=(const Mint &a) const { return !(*this == a); }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- frequently used constexpr -----
constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- main() -----
int main()
{
ll A, B, C;
cin >> A >> B >> C;
if (A + B >= C)
{
No();
}
if (4 * A * B < (C - A + B) * (C - A + B))
{
Yes();
}
No();
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/common/lag_prediction.h"
#include <algorithm>
#include "modules/common/adapters/adapter_manager.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
using apollo::common::adapter::AdapterManager;
using apollo::perception::PerceptionObstacle;
using apollo::prediction::PredictionObstacle;
using apollo::prediction::PredictionObstacles;
LagPrediction::LagPrediction(uint32_t min_appear_num,
uint32_t max_disappear_num)
: min_appear_num_(min_appear_num), max_disappear_num_(max_disappear_num) {
if (AdapterManager::GetPredictionConfig().message_history_limit() <
static_cast<int32_t>(min_appear_num_)) {
AWARN << "Prediction adapter history limit is "
<< AdapterManager::GetPredictionConfig().message_history_limit()
<< ", but an obstacle need to be observed at least "
<< min_appear_num_ << " times";
return;
}
}
void LagPrediction::GetLaggedPrediction(PredictionObstacles* obstacles) const {
obstacles->mutable_prediction_obstacle()->Clear();
if (!AdapterManager::GetPrediction() ||
AdapterManager::GetPrediction()->Empty()) {
return;
}
const auto& prediction = *(AdapterManager::GetPrediction());
if (!AdapterManager::GetLocalization() ||
AdapterManager::GetLocalization()->Empty()) { // no localization
obstacles->CopyFrom(prediction.GetLatestObserved());
return;
}
const auto adc_position =
AdapterManager::GetLocalization()->GetLatestObserved().pose().position();
const auto latest_prediction = (*prediction.begin());
const double timestamp = latest_prediction->header().timestamp_sec();
std::unordered_set<int> protected_obstacles;
for (const auto& obstacle : latest_prediction->prediction_obstacle()) {
const auto& perception = obstacle.perception_obstacle();
if (perception.confidence() < FLAGS_perception_confidence_threshold &&
perception.type() != PerceptionObstacle::VEHICLE) {
continue;
}
double distance =
common::util::DistanceXY(perception.position(), adc_position);
if (distance < FLAGS_lag_prediction_protection_distance) {
protected_obstacles.insert(obstacle.perception_obstacle().id());
// add protected obstacle
AddObstacleToPrediction(0.0, obstacle, obstacles);
}
}
std::unordered_map<int, LagInfo> obstacle_lag_info;
int index = 0; // data in begin() is the most recent data
for (auto it = prediction.begin(); it != prediction.end(); ++it, ++index) {
for (const auto& obstacle : (*it)->prediction_obstacle()) {
const auto& perception = obstacle.perception_obstacle();
auto id = perception.id();
if (perception.confidence() < FLAGS_perception_confidence_threshold &&
perception.type() != PerceptionObstacle::VEHICLE) {
continue;
}
if (protected_obstacles.count(id) > 0) {
continue; // don't need to count the already added protected obstacle
}
auto& info = obstacle_lag_info[id];
++info.count;
if ((*it)->header().timestamp_sec() > info.last_observed_time) {
info.last_observed_time = (*it)->header().timestamp_sec();
info.last_observed_seq = index;
info.obstacle_ptr = &obstacle;
}
}
}
obstacles->mutable_header()->CopyFrom(latest_prediction->header());
obstacles->mutable_header()->set_module_name("lag_prediction");
obstacles->set_perception_error_code(
latest_prediction->perception_error_code());
obstacles->set_start_timestamp(latest_prediction->start_timestamp());
obstacles->set_end_timestamp(latest_prediction->end_timestamp());
bool apply_lag = std::distance(prediction.begin(), prediction.end()) >=
static_cast<int32_t>(min_appear_num_);
for (const auto& iter : obstacle_lag_info) {
if (apply_lag && iter.second.count < min_appear_num_) {
continue;
}
if (apply_lag && iter.second.last_observed_seq > max_disappear_num_) {
continue;
}
AddObstacleToPrediction(timestamp - iter.second.last_observed_time,
*(iter.second.obstacle_ptr), obstacles);
}
}
void LagPrediction::AddObstacleToPrediction(
double delay_sec, const prediction::PredictionObstacle& history_obstacle,
prediction::PredictionObstacles* obstacles) const {
auto* obstacle = obstacles->add_prediction_obstacle();
if (delay_sec <= 1e-6) {
obstacle->CopyFrom(history_obstacle);
return;
}
obstacle->mutable_perception_obstacle()->CopyFrom(
history_obstacle.perception_obstacle());
for (const auto& hist_trajectory : history_obstacle.trajectory()) {
auto* traj = obstacle->add_trajectory();
for (const auto& hist_point : hist_trajectory.trajectory_point()) {
if (hist_point.relative_time() < delay_sec) {
continue;
}
auto* point = traj->add_trajectory_point();
point->CopyFrom(hist_point);
point->set_relative_time(hist_point.relative_time() - delay_sec);
}
if (traj->trajectory_point_size() <= 0) {
obstacle->mutable_trajectory()->RemoveLast();
continue;
}
traj->set_probability(hist_trajectory.probability());
}
if (obstacle->trajectory_size() <= 0) {
obstacles->mutable_prediction_obstacle()->RemoveLast();
return;
}
obstacle->set_timestamp(history_obstacle.timestamp());
obstacle->set_predicted_period(history_obstacle.predicted_period());
}
} // namespace planning
} // namespace apollo
<commit_msg>bugfix for nullptr failure.<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/common/lag_prediction.h"
#include <algorithm>
#include "modules/common/adapters/adapter_manager.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
using apollo::common::adapter::AdapterManager;
using apollo::perception::PerceptionObstacle;
using apollo::prediction::PredictionObstacle;
using apollo::prediction::PredictionObstacles;
LagPrediction::LagPrediction(uint32_t min_appear_num,
uint32_t max_disappear_num)
: min_appear_num_(min_appear_num), max_disappear_num_(max_disappear_num) {
if (AdapterManager::GetPredictionConfig().message_history_limit() <
static_cast<int32_t>(min_appear_num_)) {
AWARN << "Prediction adapter history limit is "
<< AdapterManager::GetPredictionConfig().message_history_limit()
<< ", but an obstacle need to be observed at least "
<< min_appear_num_ << " times";
return;
}
}
void LagPrediction::GetLaggedPrediction(PredictionObstacles* obstacles) const {
obstacles->mutable_prediction_obstacle()->Clear();
if (!AdapterManager::GetPrediction() ||
AdapterManager::GetPrediction()->Empty()) {
return;
}
const auto& prediction = *(AdapterManager::GetPrediction());
if (!AdapterManager::GetLocalization() ||
AdapterManager::GetLocalization()->Empty()) { // no localization
obstacles->CopyFrom(prediction.GetLatestObserved());
return;
}
const auto adc_position =
AdapterManager::GetLocalization()->GetLatestObserved().pose().position();
const auto latest_prediction = (*prediction.begin());
const double timestamp = latest_prediction->header().timestamp_sec();
std::unordered_set<int> protected_obstacles;
for (const auto& obstacle : latest_prediction->prediction_obstacle()) {
const auto& perception = obstacle.perception_obstacle();
if (perception.confidence() < FLAGS_perception_confidence_threshold &&
perception.type() != PerceptionObstacle::VEHICLE) {
continue;
}
double distance =
common::util::DistanceXY(perception.position(), adc_position);
if (distance < FLAGS_lag_prediction_protection_distance) {
protected_obstacles.insert(obstacle.perception_obstacle().id());
// add protected obstacle
AddObstacleToPrediction(0.0, obstacle, obstacles);
}
}
std::unordered_map<int, LagInfo> obstacle_lag_info;
int index = 0; // data in begin() is the most recent data
for (auto it = prediction.begin(); it != prediction.end(); ++it, ++index) {
for (const auto& obstacle : (*it)->prediction_obstacle()) {
const auto& perception = obstacle.perception_obstacle();
auto id = perception.id();
if (perception.confidence() < FLAGS_perception_confidence_threshold &&
perception.type() != PerceptionObstacle::VEHICLE) {
continue;
}
if (protected_obstacles.count(id) > 0) {
continue; // don't need to count the already added protected obstacle
}
auto& info = obstacle_lag_info[id];
++info.count;
if ((*it)->header().timestamp_sec() > info.last_observed_time) {
info.last_observed_time = (*it)->header().timestamp_sec();
info.last_observed_seq = index;
info.obstacle_ptr = &obstacle;
}
}
}
obstacles->mutable_header()->CopyFrom(latest_prediction->header());
obstacles->mutable_header()->set_module_name("lag_prediction");
obstacles->set_perception_error_code(
latest_prediction->perception_error_code());
obstacles->set_start_timestamp(latest_prediction->start_timestamp());
obstacles->set_end_timestamp(latest_prediction->end_timestamp());
bool apply_lag = std::distance(prediction.begin(), prediction.end()) >=
static_cast<int32_t>(min_appear_num_);
for (const auto& iter : obstacle_lag_info) {
if (apply_lag && iter.second.count < min_appear_num_) {
continue;
}
if (apply_lag && iter.second.last_observed_seq > max_disappear_num_) {
continue;
}
AddObstacleToPrediction(timestamp - iter.second.last_observed_time,
*(iter.second.obstacle_ptr), obstacles);
}
}
void LagPrediction::AddObstacleToPrediction(
double delay_sec, const prediction::PredictionObstacle& history_obstacle,
prediction::PredictionObstacles* obstacles) const {
CHECK_NOTNULL(obstacles);
auto* obstacle = obstacles->add_prediction_obstacle();
if (obstacle == nullptr) {
AERROR << "obstalce is nullptr.";
return;
}
if (delay_sec <= 1e-6) {
obstacle->CopyFrom(history_obstacle);
return;
}
obstacle->mutable_perception_obstacle()->CopyFrom(
history_obstacle.perception_obstacle());
for (const auto& hist_trajectory : history_obstacle.trajectory()) {
auto* traj = obstacle->add_trajectory();
for (const auto& hist_point : hist_trajectory.trajectory_point()) {
if (hist_point.relative_time() < delay_sec) {
continue;
}
auto* point = traj->add_trajectory_point();
point->CopyFrom(hist_point);
point->set_relative_time(hist_point.relative_time() - delay_sec);
}
if (traj->trajectory_point_size() <= 0) {
obstacle->mutable_trajectory()->RemoveLast();
continue;
}
traj->set_probability(hist_trajectory.probability());
}
if (obstacle->trajectory_size() <= 0) {
obstacles->mutable_prediction_obstacle()->RemoveLast();
return;
}
obstacle->set_timestamp(history_obstacle.timestamp());
obstacle->set_predicted_period(history_obstacle.predicted_period());
}
} // namespace planning
} // namespace apollo
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/predictor/predictor.h"
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include "Eigen/Dense"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
namespace apollo {
namespace prediction {
using apollo::common::math::LineSegment2d;
using apollo::common::math::Vec2d;
using apollo::planning::ADCTrajectory;
const std::vector<Trajectory>& Predictor::trajectories() {
return trajectories_;
}
int Predictor::NumOfTrajectories() { return trajectories_.size(); }
Trajectory Predictor::GenerateTrajectory(
const std::vector<apollo::common::TrajectoryPoint>& points) {
Trajectory trajectory;
*trajectory.mutable_trajectory_point() = {points.begin(), points.end()};
return trajectory;
}
void Predictor::SetEqualProbability(double probability, int start_index) {
int num = NumOfTrajectories();
if (start_index >= 0 && num > start_index) {
probability /= static_cast<double>(num - start_index);
for (int i = start_index; i < num; ++i) {
trajectories_[i].set_probability(probability);
}
}
}
void Predictor::Clear() { trajectories_.clear(); }
void Predictor::TrimTrajectories(
const Obstacle* obstacle,
const ADCTrajectoryContainer* adc_trajectory_container) {
for (size_t i = 0; i < trajectories_.size(); ++i) {
TrimTrajectory(obstacle, adc_trajectory_container, &trajectories_[i]);
}
}
bool Predictor::TrimTrajectory(
const Obstacle* obstacle,
const ADCTrajectoryContainer* adc_trajectory_container,
Trajectory* trajectory) {
if (obstacle == nullptr || obstacle->history_size() == 0) {
AERROR << "Invalid obstacle.";
return false;
}
int num_point = trajectory->trajectory_point_size();
if (num_point == 0) {
return false;
}
const Feature& feature = obstacle->latest_feature();
double length = feature.length();
double heading = feature.theta();
double forward_length =
std::max(length / 2.0 - FLAGS_distance_beyond_junction, 0.0);
double start_x = trajectory->trajectory_point(0).path_point().x() +
forward_length * std::cos(heading);
double start_y = trajectory->trajectory_point(0).path_point().y() +
forward_length * std::sin(heading);
if (adc_trajectory_container->IsPointInJunction({start_x, start_y}) &&
PredictionMap::instance()->OnVirtualLane({start_x, start_y},
FLAGS_virtual_lane_radius)) {
return false;
}
int index = 0;
while (index < num_point) {
double x = trajectory->trajectory_point(index).path_point().x();
double y = trajectory->trajectory_point(index).path_point().y();
if (adc_trajectory_container->IsPointInJunction({x, y})) {
break;
}
if (!trajectory->trajectory_point(index).path_point().has_lane_id()) {
continue;
}
const std::string& lane_id =
trajectory->trajectory_point(index).path_point().lane_id();
if (PredictionMap::instance()->IsVirtualLane(lane_id)) {
break;
}
++index;
}
// if no intersect
if (index == num_point) {
return false;
}
for (int i = index; i < num_point; ++i) {
trajectory->mutable_trajectory_point()->RemoveLast();
}
return true;
}
} // namespace prediction
} // namespace apollo
<commit_msg>Prediction: fix a bug of infinite loop (#2119)<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/predictor/predictor.h"
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include "Eigen/Dense"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
namespace apollo {
namespace prediction {
using apollo::common::math::LineSegment2d;
using apollo::common::math::Vec2d;
using apollo::planning::ADCTrajectory;
const std::vector<Trajectory>& Predictor::trajectories() {
return trajectories_;
}
int Predictor::NumOfTrajectories() { return trajectories_.size(); }
Trajectory Predictor::GenerateTrajectory(
const std::vector<apollo::common::TrajectoryPoint>& points) {
Trajectory trajectory;
*trajectory.mutable_trajectory_point() = {points.begin(), points.end()};
return trajectory;
}
void Predictor::SetEqualProbability(double probability, int start_index) {
int num = NumOfTrajectories();
if (start_index >= 0 && num > start_index) {
probability /= static_cast<double>(num - start_index);
for (int i = start_index; i < num; ++i) {
trajectories_[i].set_probability(probability);
}
}
}
void Predictor::Clear() { trajectories_.clear(); }
void Predictor::TrimTrajectories(
const Obstacle* obstacle,
const ADCTrajectoryContainer* adc_trajectory_container) {
for (size_t i = 0; i < trajectories_.size(); ++i) {
TrimTrajectory(obstacle, adc_trajectory_container, &trajectories_[i]);
}
}
bool Predictor::TrimTrajectory(
const Obstacle* obstacle,
const ADCTrajectoryContainer* adc_trajectory_container,
Trajectory* trajectory) {
if (obstacle == nullptr || obstacle->history_size() == 0) {
AERROR << "Invalid obstacle.";
return false;
}
int num_point = trajectory->trajectory_point_size();
if (num_point == 0) {
return false;
}
const Feature& feature = obstacle->latest_feature();
double length = feature.length();
double heading = feature.theta();
double forward_length =
std::max(length / 2.0 - FLAGS_distance_beyond_junction, 0.0);
double start_x = trajectory->trajectory_point(0).path_point().x() +
forward_length * std::cos(heading);
double start_y = trajectory->trajectory_point(0).path_point().y() +
forward_length * std::sin(heading);
if (adc_trajectory_container->IsPointInJunction({start_x, start_y}) &&
PredictionMap::instance()->OnVirtualLane({start_x, start_y},
FLAGS_virtual_lane_radius)) {
return false;
}
int index = 0;
while (index < num_point) {
double x = trajectory->trajectory_point(index).path_point().x();
double y = trajectory->trajectory_point(index).path_point().y();
if (adc_trajectory_container->IsPointInJunction({x, y})) {
break;
}
if (!trajectory->trajectory_point(index).path_point().has_lane_id()) {
++index;
continue;
}
const std::string& lane_id =
trajectory->trajectory_point(index).path_point().lane_id();
if (PredictionMap::instance()->IsVirtualLane(lane_id)) {
break;
}
++index;
}
// if no intersect
if (index == num_point) {
return false;
}
for (int i = index; i < num_point; ++i) {
trajectory->mutable_trajectory_point()->RemoveLast();
}
return true;
}
} // namespace prediction
} // namespace apollo
<|endoftext|> |
<commit_before>#include "FlowJunction.h"
#include "Conversion.h"
#include "Simulation.h"
#include "Pipe.h"
#include "FEProblem.h"
#include "Factory.h"
#include <sstream>
template<>
InputParameters validParams<FlowJunction>()
{
InputParameters params = validParams<Junction>();
params.addRequiredParam<UserObjectName>("eos", "The name of equation of state object to use.");
params.addRequiredParam<Real>("junction_vol", "Volume of the junction");
params.addRequiredParam<Real>("junction_gravity", "Gravity in the junction");
params.addRequiredParam<Real>("junction_loss", "Loss in the junction");
params.addRequiredParam<Real>("junction_area", "Area of the junction");
params.addRequiredParam<Real>("initial_rho_junction", "Initial density in the junction");
params.addRequiredParam<Real>("initial_rhou_junction", "Initial momentum in the junction");
params.addRequiredParam<Real>("initial_rhoE_junction", "Initial total energy in the junction");
return params;
}
FlowJunction::FlowJunction(const std::string & name, InputParameters params) :
Junction(name, params),
_junction_rho_name(genName("junction_rho", _id, "")),
_junction_rhou_name(genName("junction_rhou", _id, "")),
_junction_rhoE_name(genName("junction_rhoE", _id, "")),
_p_name(genName("lm", _id, "p")),
_T_name(genName("lm", _id, "T")),
_junction_vol(getParam<Real>("junction_vol")),
_junction_gravity(getParam<Real>("junction_gravity")),
_junction_loss(getParam<Real>("junction_loss")),
_junction_area(getParam<Real>("junction_area")),
_initial_rho_junction(getParam<Real>("initial_rho_junction")),
_initial_rhou_junction(getParam<Real>("initial_rhou_junction")),
_initial_rhoE_junction(getParam<Real>("initial_rhoE_junction"))
{
}
FlowJunction::~FlowJunction()
{
}
void
FlowJunction::addVariables()
{
// add scalar variable (the conserved variables within the junction)
switch (_model_type)
{
case FlowModel::EQ_MODEL_3:
{
// Set initial conditions for the junction variables. Should somehow agree with
// the initial conditions in the pipes...
// Add three separate SCALAR junction variables with individual scaling factors
_sim.addVariable(true, _junction_rho_name, FEType(FIRST, SCALAR), 0, /*scale_factor=*/1.0);
_sim.addScalarInitialCondition(_junction_rho_name, _initial_rho_junction);
_sim.addVariable(true, _junction_rhou_name, FEType(FIRST, SCALAR), 0, /*scale_factor=*/1.e-4);
_sim.addScalarInitialCondition(_junction_rhou_name, _initial_rhou_junction);
_sim.addVariable(true, _junction_rhoE_name, FEType(FIRST, SCALAR), 0, /*scale_factor=*/1.e-6);
_sim.addScalarInitialCondition(_junction_rhoE_name, _initial_rhoE_junction);
// Add the SCALAR pressure aux variable and an initial condition.
_sim.addVariable(false, _p_name, FEType(FIRST, SCALAR), /*subdomain_id=*/0, /*scale_factor=*/1.);
_sim.addScalarInitialCondition(_p_name, _sim.getParam<Real>("global_init_P"));
// Add the SCALAR temperature aux variable and an initial condition.
_sim.addVariable(false, _T_name, FEType(FIRST, SCALAR), /*subdomain_id=*/0, /*scale_factor=*/1.);
_sim.addScalarInitialCondition(_T_name, _sim.getParam<Real>("global_init_T"));
break;
}
default:
mooseError("Not implemented yet.");
break;
}
}
void
FlowJunction::addMooseObjects()
{
std::vector<std::string> cv_u(1, FlowModel::VELOCITY);
std::vector<std::string> cv_pressure(1, FlowModel::PRESSURE);
std::vector<std::string> cv_rho(1, FlowModel::RHO);
std::vector<std::string> cv_rhou(1, FlowModel::RHOU);
std::vector<std::string> cv_rhoE(1, FlowModel::RHOE);
// Add NumericalFluxUserObject for use with FlowJunction - see
// HeatStructure.C for another example of adding a UserObject
{
InputParameters params = _factory.getValidParams("NumericalFluxUserObject");
_sim.addUserObject("NumericalFluxUserObject", "numerical_flux", params);
}
// add BC terms
const std::vector<unsigned int> & boundary_ids = getBoundaryIds();
for (unsigned int i = 0; i < boundary_ids.size(); ++i)
{
std::vector<unsigned int> bnd_id(1, boundary_ids[i]);
// mass
{
InputParameters params = _factory.getValidParams("OneDSpecifiedFluxBC");
params.set<NonlinearVariableName>("variable") = FlowModel::RHO;
params.set<std::vector<unsigned int> >("r7:boundary") = bnd_id;
params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");
params.set<std::string>("eqn_name") = "CONTINUITY";
params.set<std::vector<std::string> >("u") = cv_u;
params.set<std::vector<std::string> >("rho") = cv_rho;
params.set<std::vector<std::string> >("rhou") = cv_rhou;
params.set<std::vector<std::string> >("rhoE") = cv_rhoE;
params.set<std::vector<std::string> >("junction_rho") = std::vector<std::string>(1, _junction_rho_name);
params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);
params.set<UserObjectName>("numerical_flux") = "numerical_flux";
_sim.addBoundaryCondition("OneDSpecifiedFluxBC", genName("mass", _id, "_bc"), params);
}
// momentum
{
InputParameters params = _factory.getValidParams("OneDSpecifiedFluxBC");
params.set<NonlinearVariableName>("variable") = FlowModel::RHOU;
params.set<std::vector<unsigned int> >("r7:boundary") = bnd_id;
params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");
params.set<std::string>("eqn_name") = "MOMENTUM";
params.set<std::vector<std::string> >("u") = cv_u;
params.set<std::vector<std::string> >("rho") = cv_rho;
params.set<std::vector<std::string> >("rhou") = cv_rhou;
params.set<std::vector<std::string> >("rhoE") = cv_rhoE;
params.set<std::vector<std::string> >("junction_rho") = std::vector<std::string>(1, _junction_rho_name);
params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);
params.set<UserObjectName>("numerical_flux") = "numerical_flux";
_sim.addBoundaryCondition("OneDSpecifiedFluxBC", genName("mom", _id, "_bc"), params);
}
// energy
if (_model_type == FlowModel::EQ_MODEL_3)
{
InputParameters params = _factory.getValidParams("OneDSpecifiedFluxBC");
params.set<NonlinearVariableName>("variable") = FlowModel::RHOE;
params.set<std::vector<unsigned int> >("r7:boundary") = bnd_id;
params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");
params.set<std::string>("eqn_name") = "ENERGY";
params.set<std::vector<std::string> >("u") = cv_u;
params.set<std::vector<std::string> >("rho") = cv_rho;
params.set<std::vector<std::string> >("rhou") = cv_rhou;
params.set<std::vector<std::string> >("rhoE") = cv_rhoE;
params.set<std::vector<std::string> >("junction_rho") = std::vector<std::string>(1, _junction_rho_name);
params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);
params.set<UserObjectName>("numerical_flux") = "numerical_flux";
_sim.addBoundaryCondition("OneDSpecifiedFluxBC", genName("erg", _id, "_bc"), params);
}
}
// Add the constraints - add the same kernel three times,
// associating it with a different variable each time.
{
// Local variables to help with the loop...
std::vector<std::string> var_names(3), eqn_names(3), ker_names(3);
var_names[0] = _junction_rho_name; var_names[1] = _junction_rhou_name; var_names[2] = _junction_rhoE_name;
eqn_names[0] = "CONTINUITY"; eqn_names[1] = "MOMENTUM"; eqn_names[2] = "ENERGY";
ker_names[0] = "rho"; ker_names[1] = "rhou"; ker_names[2] = "rhoE";
for (unsigned v=0; v<3; ++v)
{
InputParameters params = _factory.getValidParams("FlowConstraint");
params.set<NonlinearVariableName>("variable") = var_names[v];
params.set<std::string>("eqn_name") = eqn_names[v];
params.set<FlowModel::EModelType>("model_type") = _model_type;
params.set<std::vector<unsigned int> >("nodes") = _nodes;
params.set<std::vector<Real> >("areas") = _Areas;
params.set<std::vector<Real> >("normals") = _normals;
params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");
params.set<UserObjectName>("numerical_flux") = "numerical_flux";
// coupling
params.set<std::vector<std::string> >("u") = cv_u;
params.set<std::vector<std::string> >("p") = cv_pressure;
params.set<std::vector<std::string> >("rho") = cv_rho;
params.set<std::vector<std::string> >("rhou") = cv_rhou;
params.set<std::vector<std::string> >("rhoE") = cv_rhoE;
params.set<std::vector<std::string> >("junction_rho") = std::vector<std::string>(1, _junction_rho_name);
params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);
// junction parameters
params.set<Real>("junction_vol") = _junction_vol;
params.set<Real>("junction_gravity") = _junction_gravity;
params.set<Real>("junction_loss") = _junction_loss;
params.set<Real>("junction_area") = _junction_area;
_sim.addScalarKernel("FlowConstraint", genName(ker_names[v], _id, "_c"), params);
}
}
// Add an AuxScalarKernel for the junction pressure.
{
InputParameters params = _factory.getValidParams("ScalarPressureAux");
// The variable associated with this kernel.
params.set<AuxVariableName>("variable") = _p_name;
params.set<std::vector<std::string> >("junction_rho") = std::vector<std::string>(1, _junction_rho_name);
params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);
// And the equation of state object that the AuxScalarKernel will use.
params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");
// Add this kernel to the Simulation object
_sim.addAuxScalarKernel("ScalarPressureAux", genName("flow", _id, "_p"), params);
}
// Add an AuxScalarKernel for the junction temperature.
{
InputParameters params = _factory.getValidParams("ScalarTemperatureAux");
// The variable associated with this kernel.
params.set<AuxVariableName>("variable") = _T_name;
params.set<std::vector<std::string> >("junction_rho") = std::vector<std::string>(1, _junction_rho_name);
params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);
// And the equation of state object that the AuxScalarKernel will use.
params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");
// Add this kernel to the Simulation object
_sim.addAuxScalarKernel("ScalarTemperatureAux", genName("flow", _id, "_T"), params);
}
// add PPS for visualization of scalar aux variables
MooseEnum execute_options(SetupInterface::getExecuteOptions());
execute_options = "timestep";
{
InputParameters params = _factory.getValidParams("PrintScalarVariable");
params.set<VariableName>("variable") = _p_name;
params.set<MooseEnum>("execute_on") = execute_options;
_sim.addPostprocessor("PrintScalarVariable", "p_junction", params);
}
{
InputParameters params = _factory.getValidParams("PrintScalarVariable");
params.set<VariableName>("variable") = _T_name;
params.set<MooseEnum>("execute_on") = execute_options;
_sim.addPostprocessor("PrintScalarVariable", "T_junction", params);
}
}
std::vector<unsigned int>
FlowJunction::getIDs(std::string /*piece*/)
{
mooseError("Not implemented yet");
return std::vector<unsigned int>();
}
std::string
FlowJunction::variableName(std::string /*piece*/)
{
mooseError("Not implemented yet");
return std::string();
}
<commit_msg>Output values of p and T from the FlowJunction only to a file and use a unique name, so multiple junctions will not get mixed together.<commit_after>#include "FlowJunction.h"
#include "Conversion.h"
#include "Simulation.h"
#include "Pipe.h"
#include "FEProblem.h"
#include "Factory.h"
#include <sstream>
template<>
InputParameters validParams<FlowJunction>()
{
InputParameters params = validParams<Junction>();
params.addRequiredParam<UserObjectName>("eos", "The name of equation of state object to use.");
params.addRequiredParam<Real>("junction_vol", "Volume of the junction");
params.addRequiredParam<Real>("junction_gravity", "Gravity in the junction");
params.addRequiredParam<Real>("junction_loss", "Loss in the junction");
params.addRequiredParam<Real>("junction_area", "Area of the junction");
params.addRequiredParam<Real>("initial_rho_junction", "Initial density in the junction");
params.addRequiredParam<Real>("initial_rhou_junction", "Initial momentum in the junction");
params.addRequiredParam<Real>("initial_rhoE_junction", "Initial total energy in the junction");
return params;
}
FlowJunction::FlowJunction(const std::string & name, InputParameters params) :
Junction(name, params),
_junction_rho_name(genName("junction_rho", _id, "")),
_junction_rhou_name(genName("junction_rhou", _id, "")),
_junction_rhoE_name(genName("junction_rhoE", _id, "")),
_p_name(genName("lm", _id, "p")),
_T_name(genName("lm", _id, "T")),
_junction_vol(getParam<Real>("junction_vol")),
_junction_gravity(getParam<Real>("junction_gravity")),
_junction_loss(getParam<Real>("junction_loss")),
_junction_area(getParam<Real>("junction_area")),
_initial_rho_junction(getParam<Real>("initial_rho_junction")),
_initial_rhou_junction(getParam<Real>("initial_rhou_junction")),
_initial_rhoE_junction(getParam<Real>("initial_rhoE_junction"))
{
}
FlowJunction::~FlowJunction()
{
}
void
FlowJunction::addVariables()
{
// add scalar variable (the conserved variables within the junction)
switch (_model_type)
{
case FlowModel::EQ_MODEL_3:
{
// Set initial conditions for the junction variables. Should somehow agree with
// the initial conditions in the pipes...
// Add three separate SCALAR junction variables with individual scaling factors
_sim.addVariable(true, _junction_rho_name, FEType(FIRST, SCALAR), 0, /*scale_factor=*/1.0);
_sim.addScalarInitialCondition(_junction_rho_name, _initial_rho_junction);
_sim.addVariable(true, _junction_rhou_name, FEType(FIRST, SCALAR), 0, /*scale_factor=*/1.e-4);
_sim.addScalarInitialCondition(_junction_rhou_name, _initial_rhou_junction);
_sim.addVariable(true, _junction_rhoE_name, FEType(FIRST, SCALAR), 0, /*scale_factor=*/1.e-6);
_sim.addScalarInitialCondition(_junction_rhoE_name, _initial_rhoE_junction);
// Add the SCALAR pressure aux variable and an initial condition.
_sim.addVariable(false, _p_name, FEType(FIRST, SCALAR), /*subdomain_id=*/0, /*scale_factor=*/1.);
_sim.addScalarInitialCondition(_p_name, _sim.getParam<Real>("global_init_P"));
// Add the SCALAR temperature aux variable and an initial condition.
_sim.addVariable(false, _T_name, FEType(FIRST, SCALAR), /*subdomain_id=*/0, /*scale_factor=*/1.);
_sim.addScalarInitialCondition(_T_name, _sim.getParam<Real>("global_init_T"));
break;
}
default:
mooseError("Not implemented yet.");
break;
}
}
void
FlowJunction::addMooseObjects()
{
std::vector<std::string> cv_u(1, FlowModel::VELOCITY);
std::vector<std::string> cv_pressure(1, FlowModel::PRESSURE);
std::vector<std::string> cv_rho(1, FlowModel::RHO);
std::vector<std::string> cv_rhou(1, FlowModel::RHOU);
std::vector<std::string> cv_rhoE(1, FlowModel::RHOE);
// Add NumericalFluxUserObject for use with FlowJunction - see
// HeatStructure.C for another example of adding a UserObject
{
InputParameters params = _factory.getValidParams("NumericalFluxUserObject");
_sim.addUserObject("NumericalFluxUserObject", "numerical_flux", params);
}
// add BC terms
const std::vector<unsigned int> & boundary_ids = getBoundaryIds();
for (unsigned int i = 0; i < boundary_ids.size(); ++i)
{
std::vector<unsigned int> bnd_id(1, boundary_ids[i]);
// mass
{
InputParameters params = _factory.getValidParams("OneDSpecifiedFluxBC");
params.set<NonlinearVariableName>("variable") = FlowModel::RHO;
params.set<std::vector<unsigned int> >("r7:boundary") = bnd_id;
params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");
params.set<std::string>("eqn_name") = "CONTINUITY";
params.set<std::vector<std::string> >("u") = cv_u;
params.set<std::vector<std::string> >("rho") = cv_rho;
params.set<std::vector<std::string> >("rhou") = cv_rhou;
params.set<std::vector<std::string> >("rhoE") = cv_rhoE;
params.set<std::vector<std::string> >("junction_rho") = std::vector<std::string>(1, _junction_rho_name);
params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);
params.set<UserObjectName>("numerical_flux") = "numerical_flux";
_sim.addBoundaryCondition("OneDSpecifiedFluxBC", genName("mass", _id, "_bc"), params);
}
// momentum
{
InputParameters params = _factory.getValidParams("OneDSpecifiedFluxBC");
params.set<NonlinearVariableName>("variable") = FlowModel::RHOU;
params.set<std::vector<unsigned int> >("r7:boundary") = bnd_id;
params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");
params.set<std::string>("eqn_name") = "MOMENTUM";
params.set<std::vector<std::string> >("u") = cv_u;
params.set<std::vector<std::string> >("rho") = cv_rho;
params.set<std::vector<std::string> >("rhou") = cv_rhou;
params.set<std::vector<std::string> >("rhoE") = cv_rhoE;
params.set<std::vector<std::string> >("junction_rho") = std::vector<std::string>(1, _junction_rho_name);
params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);
params.set<UserObjectName>("numerical_flux") = "numerical_flux";
_sim.addBoundaryCondition("OneDSpecifiedFluxBC", genName("mom", _id, "_bc"), params);
}
// energy
if (_model_type == FlowModel::EQ_MODEL_3)
{
InputParameters params = _factory.getValidParams("OneDSpecifiedFluxBC");
params.set<NonlinearVariableName>("variable") = FlowModel::RHOE;
params.set<std::vector<unsigned int> >("r7:boundary") = bnd_id;
params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");
params.set<std::string>("eqn_name") = "ENERGY";
params.set<std::vector<std::string> >("u") = cv_u;
params.set<std::vector<std::string> >("rho") = cv_rho;
params.set<std::vector<std::string> >("rhou") = cv_rhou;
params.set<std::vector<std::string> >("rhoE") = cv_rhoE;
params.set<std::vector<std::string> >("junction_rho") = std::vector<std::string>(1, _junction_rho_name);
params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);
params.set<UserObjectName>("numerical_flux") = "numerical_flux";
_sim.addBoundaryCondition("OneDSpecifiedFluxBC", genName("erg", _id, "_bc"), params);
}
}
// Add the constraints - add the same kernel three times,
// associating it with a different variable each time.
{
// Local variables to help with the loop...
std::vector<std::string> var_names(3), eqn_names(3), ker_names(3);
var_names[0] = _junction_rho_name; var_names[1] = _junction_rhou_name; var_names[2] = _junction_rhoE_name;
eqn_names[0] = "CONTINUITY"; eqn_names[1] = "MOMENTUM"; eqn_names[2] = "ENERGY";
ker_names[0] = "rho"; ker_names[1] = "rhou"; ker_names[2] = "rhoE";
for (unsigned v=0; v<3; ++v)
{
InputParameters params = _factory.getValidParams("FlowConstraint");
params.set<NonlinearVariableName>("variable") = var_names[v];
params.set<std::string>("eqn_name") = eqn_names[v];
params.set<FlowModel::EModelType>("model_type") = _model_type;
params.set<std::vector<unsigned int> >("nodes") = _nodes;
params.set<std::vector<Real> >("areas") = _Areas;
params.set<std::vector<Real> >("normals") = _normals;
params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");
params.set<UserObjectName>("numerical_flux") = "numerical_flux";
// coupling
params.set<std::vector<std::string> >("u") = cv_u;
params.set<std::vector<std::string> >("p") = cv_pressure;
params.set<std::vector<std::string> >("rho") = cv_rho;
params.set<std::vector<std::string> >("rhou") = cv_rhou;
params.set<std::vector<std::string> >("rhoE") = cv_rhoE;
params.set<std::vector<std::string> >("junction_rho") = std::vector<std::string>(1, _junction_rho_name);
params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);
// junction parameters
params.set<Real>("junction_vol") = _junction_vol;
params.set<Real>("junction_gravity") = _junction_gravity;
params.set<Real>("junction_loss") = _junction_loss;
params.set<Real>("junction_area") = _junction_area;
_sim.addScalarKernel("FlowConstraint", genName(ker_names[v], _id, "_c"), params);
}
}
// Add an AuxScalarKernel for the junction pressure.
{
InputParameters params = _factory.getValidParams("ScalarPressureAux");
// The variable associated with this kernel.
params.set<AuxVariableName>("variable") = _p_name;
params.set<std::vector<std::string> >("junction_rho") = std::vector<std::string>(1, _junction_rho_name);
params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);
// And the equation of state object that the AuxScalarKernel will use.
params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");
// Add this kernel to the Simulation object
_sim.addAuxScalarKernel("ScalarPressureAux", genName("flow", _id, "_p"), params);
}
// Add an AuxScalarKernel for the junction temperature.
{
InputParameters params = _factory.getValidParams("ScalarTemperatureAux");
// The variable associated with this kernel.
params.set<AuxVariableName>("variable") = _T_name;
params.set<std::vector<std::string> >("junction_rho") = std::vector<std::string>(1, _junction_rho_name);
params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);
// And the equation of state object that the AuxScalarKernel will use.
params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");
// Add this kernel to the Simulation object
_sim.addAuxScalarKernel("ScalarTemperatureAux", genName("flow", _id, "_T"), params);
}
// add PPS for visualization of scalar aux variables
MooseEnum execute_options(SetupInterface::getExecuteOptions());
execute_options = "timestep";
{
InputParameters params = _factory.getValidParams("PrintScalarVariable");
params.set<VariableName>("variable") = _p_name;
params.set<MooseEnum>("output") = "file";
params.set<MooseEnum>("execute_on") = execute_options;
_sim.addPostprocessor("PrintScalarVariable", genName(name(), "p"), params);
}
{
InputParameters params = _factory.getValidParams("PrintScalarVariable");
params.set<VariableName>("variable") = _T_name;
params.set<MooseEnum>("execute_on") = execute_options;
params.set<MooseEnum>("output") = "file";
_sim.addPostprocessor("PrintScalarVariable", genName(name(), "T"), params);
}
}
std::vector<unsigned int>
FlowJunction::getIDs(std::string /*piece*/)
{
mooseError("Not implemented yet");
return std::vector<unsigned int>();
}
std::string
FlowJunction::variableName(std::string /*piece*/)
{
mooseError("Not implemented yet");
return std::string();
}
<|endoftext|> |
<commit_before>// Time: O(logn * nlogx * logx) = O(1)
// Space: O(nlogx) = O(1)
class Solution {
public:
double myPow(double x, int n) {
double result = 1;
long long abs_n = abs(static_cast<long long>(n));
while (abs_n > 0) {
if (abs_n & 1) {
result *= x;
}
abs_n >>= 1;
x *= x;
}
return n < 0 ? 1 / result : result;
}
};
// Time: O(logn * nlogx * logx) = O(1)
// Space: O(nlogx) = O(1)
// Recursive solution.
class Solution2 {
public:
double myPow(double x, int n) {
if (n < 0 && n != -n) {
return 1.0 / myPow(x, -n);
}
if (n == 0) {
return 1;
}
double v = myPow(x, n / 2);
if (n % 2 == 0) {
return v * v;
} else {
return v * v * x;
}
}
};
<commit_msg>Update powx-n.cpp<commit_after>// Time: O(logn)
// Space: O(1)
class Solution {
public:
double myPow(double x, int n) {
double result = 1;
long long abs_n = abs(static_cast<long long>(n));
while (abs_n > 0) {
if (abs_n & 1) {
result *= x;
}
abs_n >>= 1;
x *= x;
}
return n < 0 ? 1 / result : result;
}
};
// Time: O(logn)
// Space: O(logn)
// Recursive solution.
class Solution2 {
public:
double myPow(double x, int n) {
if (n < 0 && n != -n) {
return 1.0 / myPow(x, -n);
}
if (n == 0) {
return 1;
}
double v = myPow(x, n / 2);
if (n % 2 == 0) {
return v * v;
} else {
return v * v * x;
}
}
};
<|endoftext|> |
<commit_before>/*
* RToolsInfo.cpp
*
* Copyright (C) 2009-19 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/Version.hpp>
#include <core/r_util/RToolsInfo.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <core/Log.hpp>
#include <core/http/URL.hpp>
#include <core/StringUtils.hpp>
#include <core/system/System.hpp>
#include <core/system/RegistryKey.hpp>
#ifndef KEY_WOW64_32KEY
#define KEY_WOW64_32KEY 0x0200
#endif
namespace rstudio {
namespace core {
namespace r_util {
namespace {
std::string asRBuildPath(const FilePath& filePath)
{
std::string path = filePath.getAbsolutePath();
boost::algorithm::replace_all(path, "\\", "/");
if (!boost::algorithm::ends_with(path, "/"))
path += "/";
return path;
}
std::vector<std::string> gcc463ClangArgs(const FilePath& installPath)
{
std::vector<std::string> clangArgs;
clangArgs.push_back("-I" + installPath.completeChildPath(
"gcc-4.6.3/i686-w64-mingw32/include").getAbsolutePath());
clangArgs.push_back("-I" + installPath.completeChildPath(
"gcc-4.6.3/include/c++/4.6.3").getAbsolutePath());
std::string bits = "-I" + installPath.completeChildPath(
"gcc-4.6.3/include/c++/4.6.3/i686-w64-mingw32").getAbsolutePath();
#ifdef _WIN64
bits += "/64";
#endif
clangArgs.push_back(bits);
return clangArgs;
}
void gcc463Configuration(const FilePath& installPath,
std::vector<std::string>* pRelativePathEntries,
std::vector<std::string>* pClangArgs)
{
pRelativePathEntries->push_back("bin");
pRelativePathEntries->push_back("gcc-4.6.3/bin");
*pClangArgs = gcc463ClangArgs(installPath);
}
} // anonymous namespace
RToolsInfo::RToolsInfo(const std::string& name,
const FilePath& installPath,
bool usingMingwGcc49)
: name_(name), installPath_(installPath)
{
std::string versionMin, versionMax;
std::vector<std::string> relativePathEntries;
std::vector<std::string> clangArgs;
std::vector<core::system::Option> environmentVars;
if (name == "2.11")
{
versionMin = "2.10.0";
versionMax = "2.11.1";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("perl/bin");
relativePathEntries.push_back("MinGW/bin");
}
else if (name == "2.12")
{
versionMin = "2.12.0";
versionMax = "2.12.2";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("perl/bin");
relativePathEntries.push_back("MinGW/bin");
relativePathEntries.push_back("MinGW64/bin");
}
else if (name == "2.13")
{
versionMin = "2.13.0";
versionMax = "2.13.2";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("MinGW/bin");
relativePathEntries.push_back("MinGW64/bin");
}
else if (name == "2.14")
{
versionMin = "2.13.0";
versionMax = "2.14.2";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("MinGW/bin");
relativePathEntries.push_back("MinGW64/bin");
}
else if (name == "2.15")
{
versionMin = "2.14.2";
versionMax = "2.15.1";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("gcc-4.6.3/bin");
clangArgs = gcc463ClangArgs(installPath);
}
else if (name == "2.16" || name == "3.0")
{
versionMin = "2.15.2";
versionMax = "3.0.99";
gcc463Configuration(installPath, &relativePathEntries, &clangArgs);
}
else if (name == "3.1")
{
versionMin = "3.0.0";
versionMax = "3.1.99";
gcc463Configuration(installPath, &relativePathEntries, &clangArgs);
}
else if (name == "3.2")
{
versionMin = "3.1.0";
versionMax = "3.2.0";
gcc463Configuration(installPath, &relativePathEntries, &clangArgs);
}
else if (name == "3.3")
{
versionMin = "3.2.0";
versionMax = "3.2.99";
gcc463Configuration(installPath, &relativePathEntries, &clangArgs);
}
else if (name == "3.4" || name == "3.5")
{
versionMin = "3.3.0";
if (name == "3.4")
versionMax = "3.5.99"; // Rtools 3.4
else
versionMax = "3.6.99"; // Rtools 3.5
relativePathEntries.push_back("bin");
// set environment variables
FilePath gccPath = installPath_.completeChildPath("mingw_$(WIN)/bin");
environmentVars.push_back(
std::make_pair("BINPREF", asRBuildPath(gccPath)));
// set clang args
#ifdef _WIN64
std::string baseDir = "mingw_64";
std::string arch = "x86_64";
#else
std::string baseDir = "mingw_32";
std::string arch = "i686";
#endif
boost::format mgwIncFmt("%1%/%2%-w64-mingw32/include");
std::string mgwInc = boost::str(mgwIncFmt % baseDir % arch);
clangArgs.push_back(
"-I" + installPath.completeChildPath(mgwInc).getAbsolutePath());
std::string cppInc = mgwInc + "/c++";
clangArgs.push_back(
"-I" + installPath.completeChildPath(cppInc).getAbsolutePath());
boost::format bitsIncFmt("%1%/%2%-w64-mingw32");
std::string bitsInc = boost::str(bitsIncFmt % cppInc % arch);
clangArgs.push_back(
"-I" + installPath.completeChildPath(bitsInc).getAbsolutePath());
}
else if (name == "4.0")
{
versionMin = "4.0.0";
versionMax = "5.0.0";
// PATH for utilities
relativePathEntries.push_back("usr/bin");
// set BINPREF
environmentVars.push_back({"BINPREF", "/mingw$(WIN)/bin/"});
// set clang args
#ifdef _WIN64
std::string baseDir = "mingw64";
std::string arch = "x86_64";
#else
std::string baseDir = "mingw32";
std::string arch = "i686";
#endif
// path to mingw includes
boost::format mgwIncFmt("%1%/%2%-w64-mingw32/include");
std::string mingwIncludeSuffix = boost::str(mgwIncFmt % baseDir % arch);
FilePath mingwIncludePath = installPath.completeChildPath(mingwIncludeSuffix);
clangArgs.push_back("-I" + mingwIncludePath.getAbsolutePath());
// path to C++ headers
std::string cppSuffix = "c++/8.3.0";
FilePath cppIncludePath = installPath.completeChildPath(cppSuffix);
clangArgs.push_back("-I" + cppIncludePath.getAbsolutePath());
}
else
{
LOG_DEBUG_MESSAGE("Unrecognized Rtools installation at path '" + installPath.getAbsolutePath() + "'");
}
// build version predicate and path list if we can
if (!versionMin.empty())
{
boost::format fmt("getRversion() >= \"%1%\" && getRversion() <= \"%2%\"");
versionPredicate_ = boost::str(fmt % versionMin % versionMax);
for (const std::string& relativePath : relativePathEntries)
{
pathEntries_.push_back(installPath_.completeChildPath(relativePath));
}
clangArgs_ = clangArgs;
environmentVars_ = environmentVars;
}
}
std::string RToolsInfo::url(const std::string& repos) const
{
std::string url;
if (name() == "4.0")
{
// TODO: Currently, Rtools 4.0 is only available from the 'testing'
// sub-directory. Update this URL once it's been promoted.
std::string arch = core::system::isWin64() ? "x86_64" : "i686";
std::string suffix = "bin/windows/testing/rtools40-" + arch + ".exe";
url = core::http::URL::complete(repos, suffix);
}
else
{
std::string version = boost::algorithm::replace_all_copy(name(), ".", "");
std::string suffix = "bin/windows/Rtools/Rtools" + version + ".exe";
url = core::http::URL::complete(repos, suffix);
}
return url;
}
std::ostream& operator<<(std::ostream& os, const RToolsInfo& info)
{
os << "Rtools " << info.name() << std::endl;
os << info.versionPredicate() << std::endl;
for (const FilePath& pathEntry : info.pathEntries())
{
os << pathEntry << std::endl;
}
for (const core::system::Option& var : info.environmentVars())
{
os << var.first << "=" << var.second << std::endl;
}
return os;
}
namespace {
Error scanEnvironmentForRTools(bool usingMingwGcc49,
const std::string& envvar,
std::vector<RToolsInfo>* pRTools)
{
// nothing to do if we have no envvar
if (envvar.empty())
return Success();
// read value
std::string envval = core::system::getenv(envvar);
if (envval.empty())
return Success();
// build info
FilePath installPath(envval);
RToolsInfo toolsInfo("4.0", installPath, usingMingwGcc49);
// check that recorded path is valid
bool ok =
toolsInfo.isStillInstalled() &&
toolsInfo.isRecognized();
// use it if all looks well
if (ok)
pRTools->push_back(toolsInfo);
return Success();
}
Error scanRegistryForRTools(HKEY key,
bool usingMingwGcc49,
std::vector<RToolsInfo>* pRTools)
{
core::system::RegistryKey regKey;
Error error = regKey.open(key,
"Software\\R-core\\Rtools",
KEY_READ | KEY_WOW64_32KEY);
if (error)
{
if (error != systemError(boost::system::errc::no_such_file_or_directory, ErrorLocation()))
return error;
else
return Success();
}
std::vector<std::string> keys = regKey.keyNames();
for (size_t i = 0; i < keys.size(); i++)
{
std::string name = keys.at(i);
core::system::RegistryKey verKey;
error = verKey.open(regKey.handle(),
name,
KEY_READ | KEY_WOW64_32KEY);
if (error)
{
LOG_ERROR(error);
continue;
}
std::string installPath = verKey.getStringValue("InstallPath", "");
if (!installPath.empty())
{
std::string utf8InstallPath = string_utils::systemToUtf8(installPath);
RToolsInfo toolsInfo(name, FilePath(utf8InstallPath), usingMingwGcc49);
if (toolsInfo.isStillInstalled())
{
if (toolsInfo.isRecognized())
pRTools->push_back(toolsInfo);
else
LOG_WARNING_MESSAGE("Unknown Rtools version: " + name);
}
}
}
return Success();
}
void scanRegistryForRTools(bool usingMingwGcc49,
std::vector<RToolsInfo>* pRTools)
{
// try HKLM first (backwards compatible with previous code)
Error error = scanRegistryForRTools(
HKEY_LOCAL_MACHINE,
usingMingwGcc49,
pRTools);
if (error)
LOG_ERROR(error);
// try HKCU as a fallback
if (pRTools->empty())
{
Error error = scanRegistryForRTools(
HKEY_CURRENT_USER,
usingMingwGcc49,
pRTools);
if (error)
LOG_ERROR(error);
}
}
void scanFoldersForRTools(bool usingMingwGcc49, std::vector<RToolsInfo>* pRTools)
{
// look for Rtools as installed by RStudio
std::string systemDrive = core::system::getenv("SYSTEMDRIVE");
FilePath buildDirRoot(systemDrive + "/RBuildTools");
// ensure it exists (may not exist if the user has not installed
// any copies of Rtools through RStudio yet)
if (!buildDirRoot.exists())
return;
// find sub-directories
std::vector<FilePath> buildDirs;
Error error = buildDirRoot.getChildren(buildDirs);
if (error)
LOG_ERROR(error);
// infer Rtools information from each directory
for (const FilePath& buildDir : buildDirs)
{
RToolsInfo toolsInfo(buildDir.getFilename(), buildDir, usingMingwGcc49);
if (toolsInfo.isRecognized())
pRTools->push_back(toolsInfo);
else
LOG_WARNING_MESSAGE("Unknown Rtools version: " + buildDir.getFilename());
}
}
} // end anonymous namespace
void scanForRTools(bool usingMingwGcc49,
const std::string& rtoolsHomeEnvVar,
std::vector<RToolsInfo>* pRTools)
{
std::vector<RToolsInfo> rtoolsInfo;
// scan for Rtools
scanEnvironmentForRTools(usingMingwGcc49, rtoolsHomeEnvVar, &rtoolsInfo);
scanRegistryForRTools(usingMingwGcc49, &rtoolsInfo);
scanFoldersForRTools(usingMingwGcc49, &rtoolsInfo);
// remove duplicates
std::set<FilePath> knownPaths;
for (const RToolsInfo& info : rtoolsInfo)
{
if (knownPaths.count(info.installPath()))
continue;
knownPaths.insert(info.installPath());
pRTools->push_back(info);
}
// ensure sorted by version
std::sort(
pRTools->begin(),
pRTools->end(),
[](const RToolsInfo& lhs, const RToolsInfo& rhs)
{
return Version(lhs.name()) < Version(rhs.name());
});
}
} // namespace r_util
} // namespace core
} // namespace rstudio
<commit_msg>update Rtools URL<commit_after>/*
* RToolsInfo.cpp
*
* Copyright (C) 2009-19 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/Version.hpp>
#include <core/r_util/RToolsInfo.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <core/Log.hpp>
#include <core/http/URL.hpp>
#include <core/StringUtils.hpp>
#include <core/system/System.hpp>
#include <core/system/RegistryKey.hpp>
#ifndef KEY_WOW64_32KEY
#define KEY_WOW64_32KEY 0x0200
#endif
namespace rstudio {
namespace core {
namespace r_util {
namespace {
std::string asRBuildPath(const FilePath& filePath)
{
std::string path = filePath.getAbsolutePath();
boost::algorithm::replace_all(path, "\\", "/");
if (!boost::algorithm::ends_with(path, "/"))
path += "/";
return path;
}
std::vector<std::string> gcc463ClangArgs(const FilePath& installPath)
{
std::vector<std::string> clangArgs;
clangArgs.push_back("-I" + installPath.completeChildPath(
"gcc-4.6.3/i686-w64-mingw32/include").getAbsolutePath());
clangArgs.push_back("-I" + installPath.completeChildPath(
"gcc-4.6.3/include/c++/4.6.3").getAbsolutePath());
std::string bits = "-I" + installPath.completeChildPath(
"gcc-4.6.3/include/c++/4.6.3/i686-w64-mingw32").getAbsolutePath();
#ifdef _WIN64
bits += "/64";
#endif
clangArgs.push_back(bits);
return clangArgs;
}
void gcc463Configuration(const FilePath& installPath,
std::vector<std::string>* pRelativePathEntries,
std::vector<std::string>* pClangArgs)
{
pRelativePathEntries->push_back("bin");
pRelativePathEntries->push_back("gcc-4.6.3/bin");
*pClangArgs = gcc463ClangArgs(installPath);
}
} // anonymous namespace
RToolsInfo::RToolsInfo(const std::string& name,
const FilePath& installPath,
bool usingMingwGcc49)
: name_(name), installPath_(installPath)
{
std::string versionMin, versionMax;
std::vector<std::string> relativePathEntries;
std::vector<std::string> clangArgs;
std::vector<core::system::Option> environmentVars;
if (name == "2.11")
{
versionMin = "2.10.0";
versionMax = "2.11.1";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("perl/bin");
relativePathEntries.push_back("MinGW/bin");
}
else if (name == "2.12")
{
versionMin = "2.12.0";
versionMax = "2.12.2";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("perl/bin");
relativePathEntries.push_back("MinGW/bin");
relativePathEntries.push_back("MinGW64/bin");
}
else if (name == "2.13")
{
versionMin = "2.13.0";
versionMax = "2.13.2";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("MinGW/bin");
relativePathEntries.push_back("MinGW64/bin");
}
else if (name == "2.14")
{
versionMin = "2.13.0";
versionMax = "2.14.2";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("MinGW/bin");
relativePathEntries.push_back("MinGW64/bin");
}
else if (name == "2.15")
{
versionMin = "2.14.2";
versionMax = "2.15.1";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("gcc-4.6.3/bin");
clangArgs = gcc463ClangArgs(installPath);
}
else if (name == "2.16" || name == "3.0")
{
versionMin = "2.15.2";
versionMax = "3.0.99";
gcc463Configuration(installPath, &relativePathEntries, &clangArgs);
}
else if (name == "3.1")
{
versionMin = "3.0.0";
versionMax = "3.1.99";
gcc463Configuration(installPath, &relativePathEntries, &clangArgs);
}
else if (name == "3.2")
{
versionMin = "3.1.0";
versionMax = "3.2.0";
gcc463Configuration(installPath, &relativePathEntries, &clangArgs);
}
else if (name == "3.3")
{
versionMin = "3.2.0";
versionMax = "3.2.99";
gcc463Configuration(installPath, &relativePathEntries, &clangArgs);
}
else if (name == "3.4" || name == "3.5")
{
versionMin = "3.3.0";
if (name == "3.4")
versionMax = "3.5.99"; // Rtools 3.4
else
versionMax = "3.6.99"; // Rtools 3.5
relativePathEntries.push_back("bin");
// set environment variables
FilePath gccPath = installPath_.completeChildPath("mingw_$(WIN)/bin");
environmentVars.push_back(
std::make_pair("BINPREF", asRBuildPath(gccPath)));
// set clang args
#ifdef _WIN64
std::string baseDir = "mingw_64";
std::string arch = "x86_64";
#else
std::string baseDir = "mingw_32";
std::string arch = "i686";
#endif
boost::format mgwIncFmt("%1%/%2%-w64-mingw32/include");
std::string mgwInc = boost::str(mgwIncFmt % baseDir % arch);
clangArgs.push_back(
"-I" + installPath.completeChildPath(mgwInc).getAbsolutePath());
std::string cppInc = mgwInc + "/c++";
clangArgs.push_back(
"-I" + installPath.completeChildPath(cppInc).getAbsolutePath());
boost::format bitsIncFmt("%1%/%2%-w64-mingw32");
std::string bitsInc = boost::str(bitsIncFmt % cppInc % arch);
clangArgs.push_back(
"-I" + installPath.completeChildPath(bitsInc).getAbsolutePath());
}
else if (name == "4.0")
{
versionMin = "4.0.0";
versionMax = "5.0.0";
// PATH for utilities
relativePathEntries.push_back("usr/bin");
// set BINPREF
environmentVars.push_back({"BINPREF", "/mingw$(WIN)/bin/"});
// set clang args
#ifdef _WIN64
std::string baseDir = "mingw64";
std::string arch = "x86_64";
#else
std::string baseDir = "mingw32";
std::string arch = "i686";
#endif
// path to mingw includes
boost::format mgwIncFmt("%1%/%2%-w64-mingw32/include");
std::string mingwIncludeSuffix = boost::str(mgwIncFmt % baseDir % arch);
FilePath mingwIncludePath = installPath.completeChildPath(mingwIncludeSuffix);
clangArgs.push_back("-I" + mingwIncludePath.getAbsolutePath());
// path to C++ headers
std::string cppSuffix = "c++/8.3.0";
FilePath cppIncludePath = installPath.completeChildPath(cppSuffix);
clangArgs.push_back("-I" + cppIncludePath.getAbsolutePath());
}
else
{
LOG_DEBUG_MESSAGE("Unrecognized Rtools installation at path '" + installPath.getAbsolutePath() + "'");
}
// build version predicate and path list if we can
if (!versionMin.empty())
{
boost::format fmt("getRversion() >= \"%1%\" && getRversion() <= \"%2%\"");
versionPredicate_ = boost::str(fmt % versionMin % versionMax);
for (const std::string& relativePath : relativePathEntries)
{
pathEntries_.push_back(installPath_.completeChildPath(relativePath));
}
clangArgs_ = clangArgs;
environmentVars_ = environmentVars;
}
}
std::string RToolsInfo::url(const std::string& repos) const
{
std::string url;
if (name() == "4.0")
{
std::string arch = core::system::isWin64() ? "x86_64" : "i686";
std::string suffix = "bin/windows/Rtools/rtools40-" + arch + ".exe";
url = core::http::URL::complete(repos, suffix);
}
else
{
std::string version = boost::algorithm::replace_all_copy(name(), ".", "");
std::string suffix = "bin/windows/Rtools/Rtools" + version + ".exe";
url = core::http::URL::complete(repos, suffix);
}
return url;
}
std::ostream& operator<<(std::ostream& os, const RToolsInfo& info)
{
os << "Rtools " << info.name() << std::endl;
os << info.versionPredicate() << std::endl;
for (const FilePath& pathEntry : info.pathEntries())
{
os << pathEntry << std::endl;
}
for (const core::system::Option& var : info.environmentVars())
{
os << var.first << "=" << var.second << std::endl;
}
return os;
}
namespace {
Error scanEnvironmentForRTools(bool usingMingwGcc49,
const std::string& envvar,
std::vector<RToolsInfo>* pRTools)
{
// nothing to do if we have no envvar
if (envvar.empty())
return Success();
// read value
std::string envval = core::system::getenv(envvar);
if (envval.empty())
return Success();
// build info
FilePath installPath(envval);
RToolsInfo toolsInfo("4.0", installPath, usingMingwGcc49);
// check that recorded path is valid
bool ok =
toolsInfo.isStillInstalled() &&
toolsInfo.isRecognized();
// use it if all looks well
if (ok)
pRTools->push_back(toolsInfo);
return Success();
}
Error scanRegistryForRTools(HKEY key,
bool usingMingwGcc49,
std::vector<RToolsInfo>* pRTools)
{
core::system::RegistryKey regKey;
Error error = regKey.open(key,
"Software\\R-core\\Rtools",
KEY_READ | KEY_WOW64_32KEY);
if (error)
{
if (error != systemError(boost::system::errc::no_such_file_or_directory, ErrorLocation()))
return error;
else
return Success();
}
std::vector<std::string> keys = regKey.keyNames();
for (size_t i = 0; i < keys.size(); i++)
{
std::string name = keys.at(i);
core::system::RegistryKey verKey;
error = verKey.open(regKey.handle(),
name,
KEY_READ | KEY_WOW64_32KEY);
if (error)
{
LOG_ERROR(error);
continue;
}
std::string installPath = verKey.getStringValue("InstallPath", "");
if (!installPath.empty())
{
std::string utf8InstallPath = string_utils::systemToUtf8(installPath);
RToolsInfo toolsInfo(name, FilePath(utf8InstallPath), usingMingwGcc49);
if (toolsInfo.isStillInstalled())
{
if (toolsInfo.isRecognized())
pRTools->push_back(toolsInfo);
else
LOG_WARNING_MESSAGE("Unknown Rtools version: " + name);
}
}
}
return Success();
}
void scanRegistryForRTools(bool usingMingwGcc49,
std::vector<RToolsInfo>* pRTools)
{
// try HKLM first (backwards compatible with previous code)
Error error = scanRegistryForRTools(
HKEY_LOCAL_MACHINE,
usingMingwGcc49,
pRTools);
if (error)
LOG_ERROR(error);
// try HKCU as a fallback
if (pRTools->empty())
{
Error error = scanRegistryForRTools(
HKEY_CURRENT_USER,
usingMingwGcc49,
pRTools);
if (error)
LOG_ERROR(error);
}
}
void scanFoldersForRTools(bool usingMingwGcc49, std::vector<RToolsInfo>* pRTools)
{
// look for Rtools as installed by RStudio
std::string systemDrive = core::system::getenv("SYSTEMDRIVE");
FilePath buildDirRoot(systemDrive + "/RBuildTools");
// ensure it exists (may not exist if the user has not installed
// any copies of Rtools through RStudio yet)
if (!buildDirRoot.exists())
return;
// find sub-directories
std::vector<FilePath> buildDirs;
Error error = buildDirRoot.getChildren(buildDirs);
if (error)
LOG_ERROR(error);
// infer Rtools information from each directory
for (const FilePath& buildDir : buildDirs)
{
RToolsInfo toolsInfo(buildDir.getFilename(), buildDir, usingMingwGcc49);
if (toolsInfo.isRecognized())
pRTools->push_back(toolsInfo);
else
LOG_WARNING_MESSAGE("Unknown Rtools version: " + buildDir.getFilename());
}
}
} // end anonymous namespace
void scanForRTools(bool usingMingwGcc49,
const std::string& rtoolsHomeEnvVar,
std::vector<RToolsInfo>* pRTools)
{
std::vector<RToolsInfo> rtoolsInfo;
// scan for Rtools
scanEnvironmentForRTools(usingMingwGcc49, rtoolsHomeEnvVar, &rtoolsInfo);
scanRegistryForRTools(usingMingwGcc49, &rtoolsInfo);
scanFoldersForRTools(usingMingwGcc49, &rtoolsInfo);
// remove duplicates
std::set<FilePath> knownPaths;
for (const RToolsInfo& info : rtoolsInfo)
{
if (knownPaths.count(info.installPath()))
continue;
knownPaths.insert(info.installPath());
pRTools->push_back(info);
}
// ensure sorted by version
std::sort(
pRTools->begin(),
pRTools->end(),
[](const RToolsInfo& lhs, const RToolsInfo& rhs)
{
return Version(lhs.name()) < Version(rhs.name());
});
}
} // namespace r_util
} // namespace core
} // namespace rstudio
<|endoftext|> |
<commit_before>/*
* RToolsInfo.cpp
*
* Copyright (C) 2009-18 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/r_util/RToolsInfo.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <core/Log.hpp>
#include <core/http/URL.hpp>
#include <core/StringUtils.hpp>
#include <core/system/Types.hpp>
#include <core/system/RegistryKey.hpp>
#ifndef KEY_WOW64_32KEY
#define KEY_WOW64_32KEY 0x0200
#endif
namespace rstudio {
namespace core {
namespace r_util {
namespace {
std::string asRBuildPath(const FilePath& filePath)
{
std::string path = filePath.absolutePath();
boost::algorithm::replace_all(path, "\\", "/");
if (!boost::algorithm::ends_with(path, "/"))
path += "/";
return path;
}
std::vector<std::string> gcc463ClangArgs(const FilePath& installPath)
{
std::vector<std::string> clangArgs;
clangArgs.push_back("-I" + installPath.childPath(
"gcc-4.6.3/i686-w64-mingw32/include").absolutePath());
clangArgs.push_back("-I" + installPath.childPath(
"gcc-4.6.3/include/c++/4.6.3").absolutePath());
std::string bits = "-I" + installPath.childPath(
"gcc-4.6.3/include/c++/4.6.3/i686-w64-mingw32").absolutePath();
#ifdef _WIN64
bits += "/64";
#endif
clangArgs.push_back(bits);
return clangArgs;
}
void gcc463Configuration(const FilePath& installPath,
std::vector<std::string>* pRelativePathEntries,
std::vector<std::string>* pClangArgs)
{
pRelativePathEntries->push_back("bin");
pRelativePathEntries->push_back("gcc-4.6.3/bin");
*pClangArgs = gcc463ClangArgs(installPath);
}
} // anonymous namespace
RToolsInfo::RToolsInfo(const std::string& name,
const FilePath& installPath,
bool usingMingwGcc49)
: name_(name), installPath_(installPath)
{
std::string versionMin, versionMax;
std::vector<std::string> relativePathEntries;
std::vector<std::string> clangArgs;
std::vector<core::system::Option> environmentVars;
if (name == "2.11")
{
versionMin = "2.10.0";
versionMax = "2.11.1";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("perl/bin");
relativePathEntries.push_back("MinGW/bin");
}
else if (name == "2.12")
{
versionMin = "2.12.0";
versionMax = "2.12.2";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("perl/bin");
relativePathEntries.push_back("MinGW/bin");
relativePathEntries.push_back("MinGW64/bin");
}
else if (name == "2.13")
{
versionMin = "2.13.0";
versionMax = "2.13.2";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("MinGW/bin");
relativePathEntries.push_back("MinGW64/bin");
}
else if (name == "2.14")
{
versionMin = "2.13.0";
versionMax = "2.14.2";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("MinGW/bin");
relativePathEntries.push_back("MinGW64/bin");
}
else if (name == "2.15")
{
versionMin = "2.14.2";
versionMax = "2.15.1";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("gcc-4.6.3/bin");
clangArgs = gcc463ClangArgs(installPath);
}
else if (name == "2.16" || name == "3.0")
{
versionMin = "2.15.2";
versionMax = "3.0.99";
gcc463Configuration(installPath, &relativePathEntries, &clangArgs);
}
else if (name == "3.1")
{
versionMin = "3.0.0";
versionMax = "3.1.99";
gcc463Configuration(installPath, &relativePathEntries, &clangArgs);
}
else if (name == "3.2")
{
versionMin = "3.1.0";
versionMax = "3.2.0";
gcc463Configuration(installPath, &relativePathEntries, &clangArgs);
}
else if (name == "3.3")
{
versionMin = "3.2.0";
versionMax = "3.2.99";
gcc463Configuration(installPath, &relativePathEntries, &clangArgs);
}
else if (name == "3.4" || name == "3.5")
{
versionMin = "3.3.0";
versionMax = "3.5.99";
relativePathEntries.push_back("bin");
// set environment variables
FilePath gccPath = installPath_.childPath("mingw_$(WIN)/bin");
environmentVars.push_back(
std::make_pair("BINPREF", asRBuildPath(gccPath)));
// set clang args
#ifdef _WIN64
std::string baseDir = "mingw_64";
std::string arch = "x86_64";
#else
std::string baseDir = "mingw_32";
std::string arch = "i686";
#endif
boost::format mgwIncFmt("%1%/%2%-w64-mingw32/include");
std::string mgwInc = boost::str(mgwIncFmt % baseDir % arch);
clangArgs.push_back(
"-I" + installPath.childPath(mgwInc).absolutePath());
std::string cppInc = mgwInc + "/c++";
clangArgs.push_back(
"-I" + installPath.childPath(cppInc).absolutePath());
boost::format bitsIncFmt("%1%/%2%-w64-mingw32");
std::string bitsInc = boost::str(bitsIncFmt % cppInc % arch);
clangArgs.push_back(
"-I" + installPath.childPath(bitsInc).absolutePath());
}
// build version predicate and path list if we can
if (!versionMin.empty())
{
boost::format fmt("getRversion() >= \"%1%\" && getRversion() <= \"%2%\"");
versionPredicate_ = boost::str(fmt % versionMin % versionMax);
BOOST_FOREACH(const std::string& relativePath, relativePathEntries)
{
pathEntries_.push_back(installPath_.childPath(relativePath));
}
clangArgs_ = clangArgs;
environmentVars_ = environmentVars;
}
}
std::string RToolsInfo::url(const std::string& repos) const
{
// strip period from name
std::string ver = boost::algorithm::replace_all_copy(name(), ".", "");
std::string url = core::http::URL::complete(
repos, "bin/windows/Rtools/Rtools" + ver + ".exe");
return url;
}
std::ostream& operator<<(std::ostream& os, const RToolsInfo& info)
{
os << "Rtools " << info.name() << std::endl;
os << info.versionPredicate() << std::endl;
BOOST_FOREACH(const FilePath& pathEntry, info.pathEntries())
{
os << pathEntry << std::endl;
}
BOOST_FOREACH(const core::system::Option& var, info.environmentVars())
{
os << var.first << "=" << var.second << std::endl;
}
return os;
}
Error scanRegistryForRTools(HKEY key,
bool usingMingwGcc49,
std::vector<RToolsInfo>* pRTools)
{
core::system::RegistryKey regKey;
Error error = regKey.open(key,
"Software\\R-core\\Rtools",
KEY_READ | KEY_WOW64_32KEY);
if (error)
{
if (error.code() != boost::system::errc::no_such_file_or_directory)
return error;
else
return Success();
}
std::vector<std::string> keys = regKey.keyNames();
for (size_t i = 0; i < keys.size(); i++)
{
std::string name = keys.at(i);
core::system::RegistryKey verKey;
error = verKey.open(regKey.handle(),
name,
KEY_READ | KEY_WOW64_32KEY);
if (error)
{
LOG_ERROR(error);
continue;
}
std::string installPath = verKey.getStringValue("InstallPath", "");
if (!installPath.empty())
{
std::string utf8InstallPath = string_utils::systemToUtf8(installPath);
RToolsInfo toolsInfo(name, FilePath(utf8InstallPath), usingMingwGcc49);
if (toolsInfo.isStillInstalled())
{
if (toolsInfo.isRecognized())
pRTools->push_back(toolsInfo);
else
LOG_WARNING_MESSAGE("Unknown Rtools version: " + name);
}
}
}
return Success();
}
Error scanRegistryForRTools(bool usingMingwGcc49,
std::vector<RToolsInfo>* pRTools)
{
// try HKLM first (backwards compatible with previous code)
Error error = scanRegistryForRTools(HKEY_LOCAL_MACHINE,
usingMingwGcc49,
pRTools);
if (error)
return error;
// try HKCU as a fallback
if (pRTools->empty())
return scanRegistryForRTools(HKEY_CURRENT_USER,
usingMingwGcc49,
pRTools);
else
return Success();
}
} // namespace r_util
} // namespace core
} // namespace rstudio
<commit_msg>allow use of Rtools 3.5 for R 3.6 (devel)<commit_after>/*
* RToolsInfo.cpp
*
* Copyright (C) 2009-18 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/r_util/RToolsInfo.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <core/Log.hpp>
#include <core/http/URL.hpp>
#include <core/StringUtils.hpp>
#include <core/system/Types.hpp>
#include <core/system/RegistryKey.hpp>
#ifndef KEY_WOW64_32KEY
#define KEY_WOW64_32KEY 0x0200
#endif
namespace rstudio {
namespace core {
namespace r_util {
namespace {
std::string asRBuildPath(const FilePath& filePath)
{
std::string path = filePath.absolutePath();
boost::algorithm::replace_all(path, "\\", "/");
if (!boost::algorithm::ends_with(path, "/"))
path += "/";
return path;
}
std::vector<std::string> gcc463ClangArgs(const FilePath& installPath)
{
std::vector<std::string> clangArgs;
clangArgs.push_back("-I" + installPath.childPath(
"gcc-4.6.3/i686-w64-mingw32/include").absolutePath());
clangArgs.push_back("-I" + installPath.childPath(
"gcc-4.6.3/include/c++/4.6.3").absolutePath());
std::string bits = "-I" + installPath.childPath(
"gcc-4.6.3/include/c++/4.6.3/i686-w64-mingw32").absolutePath();
#ifdef _WIN64
bits += "/64";
#endif
clangArgs.push_back(bits);
return clangArgs;
}
void gcc463Configuration(const FilePath& installPath,
std::vector<std::string>* pRelativePathEntries,
std::vector<std::string>* pClangArgs)
{
pRelativePathEntries->push_back("bin");
pRelativePathEntries->push_back("gcc-4.6.3/bin");
*pClangArgs = gcc463ClangArgs(installPath);
}
} // anonymous namespace
RToolsInfo::RToolsInfo(const std::string& name,
const FilePath& installPath,
bool usingMingwGcc49)
: name_(name), installPath_(installPath)
{
std::string versionMin, versionMax;
std::vector<std::string> relativePathEntries;
std::vector<std::string> clangArgs;
std::vector<core::system::Option> environmentVars;
if (name == "2.11")
{
versionMin = "2.10.0";
versionMax = "2.11.1";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("perl/bin");
relativePathEntries.push_back("MinGW/bin");
}
else if (name == "2.12")
{
versionMin = "2.12.0";
versionMax = "2.12.2";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("perl/bin");
relativePathEntries.push_back("MinGW/bin");
relativePathEntries.push_back("MinGW64/bin");
}
else if (name == "2.13")
{
versionMin = "2.13.0";
versionMax = "2.13.2";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("MinGW/bin");
relativePathEntries.push_back("MinGW64/bin");
}
else if (name == "2.14")
{
versionMin = "2.13.0";
versionMax = "2.14.2";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("MinGW/bin");
relativePathEntries.push_back("MinGW64/bin");
}
else if (name == "2.15")
{
versionMin = "2.14.2";
versionMax = "2.15.1";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("gcc-4.6.3/bin");
clangArgs = gcc463ClangArgs(installPath);
}
else if (name == "2.16" || name == "3.0")
{
versionMin = "2.15.2";
versionMax = "3.0.99";
gcc463Configuration(installPath, &relativePathEntries, &clangArgs);
}
else if (name == "3.1")
{
versionMin = "3.0.0";
versionMax = "3.1.99";
gcc463Configuration(installPath, &relativePathEntries, &clangArgs);
}
else if (name == "3.2")
{
versionMin = "3.1.0";
versionMax = "3.2.0";
gcc463Configuration(installPath, &relativePathEntries, &clangArgs);
}
else if (name == "3.3")
{
versionMin = "3.2.0";
versionMax = "3.2.99";
gcc463Configuration(installPath, &relativePathEntries, &clangArgs);
}
else if (name == "3.4" || name == "3.5")
{
versionMin = "3.3.0";
if (name == "3.4")
versionMax = "3.5.99"; // Rtools 3.4
else
versionMax = "3.6.99"; // Rtools 3.5
relativePathEntries.push_back("bin");
// set environment variables
FilePath gccPath = installPath_.childPath("mingw_$(WIN)/bin");
environmentVars.push_back(
std::make_pair("BINPREF", asRBuildPath(gccPath)));
// set clang args
#ifdef _WIN64
std::string baseDir = "mingw_64";
std::string arch = "x86_64";
#else
std::string baseDir = "mingw_32";
std::string arch = "i686";
#endif
boost::format mgwIncFmt("%1%/%2%-w64-mingw32/include");
std::string mgwInc = boost::str(mgwIncFmt % baseDir % arch);
clangArgs.push_back(
"-I" + installPath.childPath(mgwInc).absolutePath());
std::string cppInc = mgwInc + "/c++";
clangArgs.push_back(
"-I" + installPath.childPath(cppInc).absolutePath());
boost::format bitsIncFmt("%1%/%2%-w64-mingw32");
std::string bitsInc = boost::str(bitsIncFmt % cppInc % arch);
clangArgs.push_back(
"-I" + installPath.childPath(bitsInc).absolutePath());
}
// build version predicate and path list if we can
if (!versionMin.empty())
{
boost::format fmt("getRversion() >= \"%1%\" && getRversion() <= \"%2%\"");
versionPredicate_ = boost::str(fmt % versionMin % versionMax);
BOOST_FOREACH(const std::string& relativePath, relativePathEntries)
{
pathEntries_.push_back(installPath_.childPath(relativePath));
}
clangArgs_ = clangArgs;
environmentVars_ = environmentVars;
}
}
std::string RToolsInfo::url(const std::string& repos) const
{
// strip period from name
std::string ver = boost::algorithm::replace_all_copy(name(), ".", "");
std::string url = core::http::URL::complete(
repos, "bin/windows/Rtools/Rtools" + ver + ".exe");
return url;
}
std::ostream& operator<<(std::ostream& os, const RToolsInfo& info)
{
os << "Rtools " << info.name() << std::endl;
os << info.versionPredicate() << std::endl;
BOOST_FOREACH(const FilePath& pathEntry, info.pathEntries())
{
os << pathEntry << std::endl;
}
BOOST_FOREACH(const core::system::Option& var, info.environmentVars())
{
os << var.first << "=" << var.second << std::endl;
}
return os;
}
Error scanRegistryForRTools(HKEY key,
bool usingMingwGcc49,
std::vector<RToolsInfo>* pRTools)
{
core::system::RegistryKey regKey;
Error error = regKey.open(key,
"Software\\R-core\\Rtools",
KEY_READ | KEY_WOW64_32KEY);
if (error)
{
if (error.code() != boost::system::errc::no_such_file_or_directory)
return error;
else
return Success();
}
std::vector<std::string> keys = regKey.keyNames();
for (size_t i = 0; i < keys.size(); i++)
{
std::string name = keys.at(i);
core::system::RegistryKey verKey;
error = verKey.open(regKey.handle(),
name,
KEY_READ | KEY_WOW64_32KEY);
if (error)
{
LOG_ERROR(error);
continue;
}
std::string installPath = verKey.getStringValue("InstallPath", "");
if (!installPath.empty())
{
std::string utf8InstallPath = string_utils::systemToUtf8(installPath);
RToolsInfo toolsInfo(name, FilePath(utf8InstallPath), usingMingwGcc49);
if (toolsInfo.isStillInstalled())
{
if (toolsInfo.isRecognized())
pRTools->push_back(toolsInfo);
else
LOG_WARNING_MESSAGE("Unknown Rtools version: " + name);
}
}
}
return Success();
}
Error scanRegistryForRTools(bool usingMingwGcc49,
std::vector<RToolsInfo>* pRTools)
{
// try HKLM first (backwards compatible with previous code)
Error error = scanRegistryForRTools(HKEY_LOCAL_MACHINE,
usingMingwGcc49,
pRTools);
if (error)
return error;
// try HKCU as a fallback
if (pRTools->empty())
return scanRegistryForRTools(HKEY_CURRENT_USER,
usingMingwGcc49,
pRTools);
else
return Success();
}
} // namespace r_util
} // namespace core
} // namespace rstudio
<|endoftext|> |
<commit_before><commit_msg>fastuidraw/painter/stroked_caps_joins: bug fix<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sbxconv.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-10-12 14:32:25 $
*
* 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 _SBXCONV_HXX
#define _SBXCONV_HXX
#include "sbxdec.hxx"
// SBXSCAN.CXX
extern void ImpCvtNum( double nNum, short nPrec, String& rRes, BOOL bCoreString=FALSE );
extern SbxError ImpScan
( const String& rSrc, double& nVal, SbxDataType& rType, USHORT* pLen,
BOOL bAllowIntntl=FALSE, BOOL bOnlyIntntl=FALSE );
// mit erweiterter Auswertung (International, "TRUE"/"FALSE")
extern BOOL ImpConvStringExt( String& rSrc, SbxDataType eTargetType );
// SBXINT.CXX
double ImpRound( double );
INT16 ImpGetInteger( const SbxValues* );
void ImpPutInteger( SbxValues*, INT16 );
sal_Int64 ImpGetInt64( const SbxValues* );
void ImpPutInt64( SbxValues*, sal_Int64 );
sal_uInt64 ImpGetUInt64( const SbxValues* );
void ImpPutUInt64( SbxValues*, sal_uInt64 );
sal_Int64 ImpDoubleToSalInt64( double d );
sal_uInt64 ImpDoubleToSalUInt64( double d );
double ImpSalUInt64ToDouble( sal_uInt64 n );
// SBXLNG.CXX
INT32 ImpGetLong( const SbxValues* );
void ImpPutLong( SbxValues*, INT32 );
// SBXSNG.CXX
float ImpGetSingle( const SbxValues* );
void ImpPutSingle( SbxValues*, float );
// SBXDBL.CXX
double ImpGetDouble( const SbxValues* );
void ImpPutDouble( SbxValues*, double, BOOL bCoreString=FALSE );
#if FALSE
// SBX64.CXX
SbxINT64 ImpGetINT64( const SbxValues* );
void ImpPutINT64( SbxValues*, const SbxINT64& );
SbxUINT64 ImpGetUINT64( const SbxValues* );
void ImpPutUINT64( SbxValues*, const SbxUINT64& );
#endif
// SBXCURR.CXX
SbxUINT64 ImpDoubleToUINT64( double );
double ImpUINT64ToDouble( const SbxUINT64& );
SbxINT64 ImpDoubleToINT64( double );
double ImpINT64ToDouble( const SbxINT64& );
#if TRUE
INT32 ImpGetCurrLong( const SbxValues* );
void ImpPutCurrLong( SbxValues*, INT32 );
INT32 ImpDoubleToCurrLong( double );
double ImpCurrLongToDouble( INT32 );
#endif
SbxINT64 ImpGetCurrency( const SbxValues* );
void ImpPutCurrency( SbxValues*, const SbxINT64& );
inline
SbxINT64 ImpDoubleToCurrency( double d )
{ return ImpDoubleToINT64( d * CURRENCY_FACTOR ); }
inline
double ImpCurrencyToDouble( const SbxINT64 &r )
{ return ImpINT64ToDouble( r ) / CURRENCY_FACTOR; }
// SBXDEC.CXX
SbxDecimal* ImpCreateDecimal( SbxValues* p );
SbxDecimal* ImpGetDecimal( const SbxValues* p );
void ImpPutDecimal( SbxValues* p, SbxDecimal* pDec );
// SBXDATE.CXX
double ImpGetDate( const SbxValues* );
void ImpPutDate( SbxValues*, double );
// SBXSTR.CXX
String ImpGetString( const SbxValues* );
String ImpGetCoreString( const SbxValues* );
void ImpPutString( SbxValues*, const String* );
// SBXCHAR.CXX
sal_Unicode ImpGetChar( const SbxValues* );
void ImpPutChar( SbxValues*, sal_Unicode );
// SBXBYTE.CXX
BYTE ImpGetByte( const SbxValues* );
void ImpPutByte( SbxValues*, BYTE );
// SBXUINT.CXX
UINT16 ImpGetUShort( const SbxValues* );
void ImpPutUShort( SbxValues*, UINT16 );
// SBXULNG.CXX
UINT32 ImpGetULong( const SbxValues* );
void ImpPutULong( SbxValues*, UINT32 );
// SBXBOOL.CXX
enum SbxBOOL ImpGetBool( const SbxValues* );
void ImpPutBool( SbxValues*, INT16 );
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.154); FILE MERGED 2008/03/28 16:07:44 rt 1.4.154.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: sbxconv.hxx,v $
* $Revision: 1.5 $
*
* 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 _SBXCONV_HXX
#define _SBXCONV_HXX
#include "sbxdec.hxx"
// SBXSCAN.CXX
extern void ImpCvtNum( double nNum, short nPrec, String& rRes, BOOL bCoreString=FALSE );
extern SbxError ImpScan
( const String& rSrc, double& nVal, SbxDataType& rType, USHORT* pLen,
BOOL bAllowIntntl=FALSE, BOOL bOnlyIntntl=FALSE );
// mit erweiterter Auswertung (International, "TRUE"/"FALSE")
extern BOOL ImpConvStringExt( String& rSrc, SbxDataType eTargetType );
// SBXINT.CXX
double ImpRound( double );
INT16 ImpGetInteger( const SbxValues* );
void ImpPutInteger( SbxValues*, INT16 );
sal_Int64 ImpGetInt64( const SbxValues* );
void ImpPutInt64( SbxValues*, sal_Int64 );
sal_uInt64 ImpGetUInt64( const SbxValues* );
void ImpPutUInt64( SbxValues*, sal_uInt64 );
sal_Int64 ImpDoubleToSalInt64( double d );
sal_uInt64 ImpDoubleToSalUInt64( double d );
double ImpSalUInt64ToDouble( sal_uInt64 n );
// SBXLNG.CXX
INT32 ImpGetLong( const SbxValues* );
void ImpPutLong( SbxValues*, INT32 );
// SBXSNG.CXX
float ImpGetSingle( const SbxValues* );
void ImpPutSingle( SbxValues*, float );
// SBXDBL.CXX
double ImpGetDouble( const SbxValues* );
void ImpPutDouble( SbxValues*, double, BOOL bCoreString=FALSE );
#if FALSE
// SBX64.CXX
SbxINT64 ImpGetINT64( const SbxValues* );
void ImpPutINT64( SbxValues*, const SbxINT64& );
SbxUINT64 ImpGetUINT64( const SbxValues* );
void ImpPutUINT64( SbxValues*, const SbxUINT64& );
#endif
// SBXCURR.CXX
SbxUINT64 ImpDoubleToUINT64( double );
double ImpUINT64ToDouble( const SbxUINT64& );
SbxINT64 ImpDoubleToINT64( double );
double ImpINT64ToDouble( const SbxINT64& );
#if TRUE
INT32 ImpGetCurrLong( const SbxValues* );
void ImpPutCurrLong( SbxValues*, INT32 );
INT32 ImpDoubleToCurrLong( double );
double ImpCurrLongToDouble( INT32 );
#endif
SbxINT64 ImpGetCurrency( const SbxValues* );
void ImpPutCurrency( SbxValues*, const SbxINT64& );
inline
SbxINT64 ImpDoubleToCurrency( double d )
{ return ImpDoubleToINT64( d * CURRENCY_FACTOR ); }
inline
double ImpCurrencyToDouble( const SbxINT64 &r )
{ return ImpINT64ToDouble( r ) / CURRENCY_FACTOR; }
// SBXDEC.CXX
SbxDecimal* ImpCreateDecimal( SbxValues* p );
SbxDecimal* ImpGetDecimal( const SbxValues* p );
void ImpPutDecimal( SbxValues* p, SbxDecimal* pDec );
// SBXDATE.CXX
double ImpGetDate( const SbxValues* );
void ImpPutDate( SbxValues*, double );
// SBXSTR.CXX
String ImpGetString( const SbxValues* );
String ImpGetCoreString( const SbxValues* );
void ImpPutString( SbxValues*, const String* );
// SBXCHAR.CXX
sal_Unicode ImpGetChar( const SbxValues* );
void ImpPutChar( SbxValues*, sal_Unicode );
// SBXBYTE.CXX
BYTE ImpGetByte( const SbxValues* );
void ImpPutByte( SbxValues*, BYTE );
// SBXUINT.CXX
UINT16 ImpGetUShort( const SbxValues* );
void ImpPutUShort( SbxValues*, UINT16 );
// SBXULNG.CXX
UINT32 ImpGetULong( const SbxValues* );
void ImpPutULong( SbxValues*, UINT32 );
// SBXBOOL.CXX
enum SbxBOOL ImpGetBool( const SbxValues* );
void ImpPutBool( SbxValues*, INT16 );
#endif
<|endoftext|> |
<commit_before>#include "extlineedit.h"
#include <QPushButton>
#include <QIcon>
#include <QPropertyAnimation>
#include <QSignalTransition>
CExtLineEdit::CExtLineEdit(QWidget* parent)
: QLineEdit(parent)
, m_animated(true)
, m_animationDurationMS(500)
, m_clearButton(new QPushButton(this))
, m_textStateMachine(new QStateMachine(this))
, m_textNotEmptyState(new QState(m_textStateMachine))
, m_textEmptyState(new QState(m_textStateMachine))
, m_animHideClearButton(new QPropertyAnimation(m_clearButton, "pos"))
, m_animShowClearButton(new QPropertyAnimation(m_clearButton, "pos"))
{
QPixmap buttonImage(":/Icon/remove_16.png");
QIcon icon;
icon.addPixmap(buttonImage, QIcon::Normal, QIcon::Off);
m_clearButton->setFlat(true);
m_clearButton->setIcon(icon);
m_clearButton->setFocusPolicy(Qt::NoFocus);
m_clearButton->setCursor(Qt::ArrowCursor);
m_animHideClearButton->setDuration(m_animationDurationMS);
m_animHideClearButton->setEasingCurve(QEasingCurve::OutExpo);
m_animShowClearButton->setDuration(m_animationDurationMS);
m_animShowClearButton->setEasingCurve(QEasingCurve::OutBounce);
// Note on the StateMachine:
// Propertyassignment is added in CExtLineEdit::layoutClearButton()
// because we don't no the size of the button here.
// Starting of the the StateMachine is also done in CExtLineEdit::layoutClearButton().
QSignalTransition *transition;
transition = m_textNotEmptyState->addTransition(this, SIGNAL(textEmptyToggled()), m_textEmptyState);
transition->addAnimation(m_animHideClearButton);
transition = m_textEmptyState->addTransition(this, SIGNAL(textEmptyToggled()), m_textNotEmptyState);
transition->addAnimation(m_animShowClearButton);
connect(m_clearButton, SIGNAL(clicked()), this, SLOT(clear()));
connect(this, SIGNAL(textChanged(QString)), this, SLOT(onTextChanged(QString)));
}
bool CExtLineEdit::isAnimated()
{
return m_animated;
}
void CExtLineEdit::setAnimated(bool animate)
{
m_animated = animate;
if ( m_animated ) {
m_animHideClearButton->setDuration(m_animationDurationMS);
m_animShowClearButton->setDuration(m_animationDurationMS);
} else {
m_animHideClearButton->setDuration(0);
m_animShowClearButton->setDuration(0);
}
}
int CExtLineEdit::animationDuration() {
return m_animationDurationMS;
}
void CExtLineEdit::setAnimationDuration(int durationInMS) {
m_animationDurationMS = durationInMS;
if ( isAnimated() ) {
m_animHideClearButton->setDuration(m_animationDurationMS);
m_animShowClearButton->setDuration(m_animationDurationMS);
}
}
void CExtLineEdit::ensureStateMachineIsRunning()
{
if ( !m_textStateMachine->isRunning() ) {
if ( text().isEmpty() ) {
m_textStateMachine->setInitialState(m_textEmptyState);
} else {
m_textStateMachine->setInitialState(m_textNotEmptyState);
}
m_textStateMachine->start();
}
}
void CExtLineEdit::resizeEvent(QResizeEvent* event)
{
QLineEdit::resizeEvent(event);
layoutClearButton();
}
void CExtLineEdit::layoutClearButton()
{
ensurePolished();
// If the statemachine is not running we start it here with the correct state.
// This has to be done here because otherwise it is possible that someone calls
// setText on the LineEdit and then the statemachine would be in the wrong state.
ensureStateMachineIsRunning();
QSize buttonSize = m_clearButton->minimumSizeHint();
QPoint buttonVisiblePos(rect().right() - buttonSize.width(),(rect().height() - buttonSize.height() ) / 2);
QPoint buttonInvisiblePos(rect().right(), (rect().height() - buttonSize.height() ) / 2);
m_textNotEmptyState->assignProperty(m_clearButton, "pos", buttonVisiblePos);
m_textEmptyState->assignProperty(m_clearButton, "pos", buttonInvisiblePos);
if (m_textStateMachine->configuration().contains(m_textNotEmptyState)) {
m_clearButton->setProperty("pos", buttonVisiblePos);
} else {
m_clearButton->setProperty("pos", buttonInvisiblePos);
}
//maybe the size has changed so we better set the text margins again
int left, top, bottom;
this->getTextMargins (&left, &top, 0, &bottom );
this->setTextMargins(left, top, 2 + m_clearButton->minimumSizeHint().width() + 2, bottom);
}
void CExtLineEdit::onTextChanged(const QString &text)
{
if ( ( text.isEmpty() && m_textStateMachine->configuration().contains(m_textNotEmptyState))
|| (!text.isEmpty() && m_textStateMachine->configuration().contains(m_textEmptyState))
) {
emit textEmptyToggled();
}
}
<commit_msg>Fixed typo<commit_after>#include "extlineedit.h"
#include <QPushButton>
#include <QIcon>
#include <QPropertyAnimation>
#include <QSignalTransition>
CExtLineEdit::CExtLineEdit(QWidget* parent)
: QLineEdit(parent)
, m_animated(true)
, m_animationDurationMS(500)
, m_clearButton(new QPushButton(this))
, m_textStateMachine(new QStateMachine(this))
, m_textNotEmptyState(new QState(m_textStateMachine))
, m_textEmptyState(new QState(m_textStateMachine))
, m_animHideClearButton(new QPropertyAnimation(m_clearButton, "pos"))
, m_animShowClearButton(new QPropertyAnimation(m_clearButton, "pos"))
{
QPixmap buttonImage(":/Icon/remove_16.png");
QIcon icon;
icon.addPixmap(buttonImage, QIcon::Normal, QIcon::Off);
m_clearButton->setFlat(true);
m_clearButton->setIcon(icon);
m_clearButton->setFocusPolicy(Qt::NoFocus);
m_clearButton->setCursor(Qt::ArrowCursor);
m_animHideClearButton->setDuration(m_animationDurationMS);
m_animHideClearButton->setEasingCurve(QEasingCurve::OutExpo);
m_animShowClearButton->setDuration(m_animationDurationMS);
m_animShowClearButton->setEasingCurve(QEasingCurve::OutBounce);
// Note on the StateMachine:
// Propertyassignment is added in CExtLineEdit::layoutClearButton()
// because we don't know the size of the button here.
// Starting of the the StateMachine is also done in CExtLineEdit::layoutClearButton().
QSignalTransition *transition;
transition = m_textNotEmptyState->addTransition(this, SIGNAL(textEmptyToggled()), m_textEmptyState);
transition->addAnimation(m_animHideClearButton);
transition = m_textEmptyState->addTransition(this, SIGNAL(textEmptyToggled()), m_textNotEmptyState);
transition->addAnimation(m_animShowClearButton);
connect(m_clearButton, SIGNAL(clicked()), this, SLOT(clear()));
connect(this, SIGNAL(textChanged(QString)), this, SLOT(onTextChanged(QString)));
}
bool CExtLineEdit::isAnimated()
{
return m_animated;
}
void CExtLineEdit::setAnimated(bool animate)
{
m_animated = animate;
if ( m_animated ) {
m_animHideClearButton->setDuration(m_animationDurationMS);
m_animShowClearButton->setDuration(m_animationDurationMS);
} else {
m_animHideClearButton->setDuration(0);
m_animShowClearButton->setDuration(0);
}
}
int CExtLineEdit::animationDuration() {
return m_animationDurationMS;
}
void CExtLineEdit::setAnimationDuration(int durationInMS) {
m_animationDurationMS = durationInMS;
if ( isAnimated() ) {
m_animHideClearButton->setDuration(m_animationDurationMS);
m_animShowClearButton->setDuration(m_animationDurationMS);
}
}
void CExtLineEdit::ensureStateMachineIsRunning()
{
if ( !m_textStateMachine->isRunning() ) {
if ( text().isEmpty() ) {
m_textStateMachine->setInitialState(m_textEmptyState);
} else {
m_textStateMachine->setInitialState(m_textNotEmptyState);
}
m_textStateMachine->start();
}
}
void CExtLineEdit::resizeEvent(QResizeEvent* event)
{
QLineEdit::resizeEvent(event);
layoutClearButton();
}
void CExtLineEdit::layoutClearButton()
{
ensurePolished();
// If the statemachine is not running we start it here with the correct state.
// This has to be done here because otherwise it is possible that someone calls
// setText on the LineEdit and then the statemachine would be in the wrong state.
ensureStateMachineIsRunning();
QSize buttonSize = m_clearButton->minimumSizeHint();
QPoint buttonVisiblePos(rect().right() - buttonSize.width(),(rect().height() - buttonSize.height() ) / 2);
QPoint buttonInvisiblePos(rect().right(), (rect().height() - buttonSize.height() ) / 2);
m_textNotEmptyState->assignProperty(m_clearButton, "pos", buttonVisiblePos);
m_textEmptyState->assignProperty(m_clearButton, "pos", buttonInvisiblePos);
if (m_textStateMachine->configuration().contains(m_textNotEmptyState)) {
m_clearButton->setProperty("pos", buttonVisiblePos);
} else {
m_clearButton->setProperty("pos", buttonInvisiblePos);
}
//maybe the size has changed so we better set the text margins again
int left, top, bottom;
this->getTextMargins (&left, &top, 0, &bottom );
this->setTextMargins(left, top, 2 + m_clearButton->minimumSizeHint().width() + 2, bottom);
}
void CExtLineEdit::onTextChanged(const QString &text)
{
if ( ( text.isEmpty() && m_textStateMachine->configuration().contains(m_textNotEmptyState))
|| (!text.isEmpty() && m_textStateMachine->configuration().contains(m_textEmptyState))
) {
emit textEmptyToggled();
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "browser/url_request_context_getter.h"
#include <algorithm>
#include "browser/network_delegate.h"
#include "base/command_line.h"
#include "base/strings/string_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/threading/worker_pool.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/cookie_store_factory.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "net/base/host_mapping_rules.h"
#include "net/cert/cert_verifier.h"
#include "net/cookies/cookie_monster.h"
#include "net/dns/mapped_host_resolver.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_cache.h"
#include "net/http/http_server_properties_impl.h"
#include "net/proxy/dhcp_proxy_script_fetcher_factory.h"
#include "net/proxy/proxy_config_service.h"
#include "net/proxy/proxy_script_fetcher_impl.h"
#include "net/proxy/proxy_service.h"
#include "net/proxy/proxy_service_v8.h"
#include "net/ssl/default_server_bound_cert_store.h"
#include "net/ssl/server_bound_cert_service.h"
#include "net/ssl/ssl_config_service_defaults.h"
#include "net/url_request/data_protocol_handler.h"
#include "net/url_request/file_protocol_handler.h"
#include "net/url_request/protocol_intercept_job_factory.h"
#include "net/url_request/static_http_user_agent_settings.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_storage.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "webkit/browser/quota/special_storage_policy.h"
using content::BrowserThread;
namespace brightray {
namespace {
// Comma-separated list of rules that control how hostnames are mapped.
//
// For example:
// "MAP * 127.0.0.1" --> Forces all hostnames to be mapped to 127.0.0.1
// "MAP *.google.com proxy" --> Forces all google.com subdomains to be
// resolved to "proxy".
// "MAP test.com [::1]:77 --> Forces "test.com" to resolve to IPv6 loopback.
// Will also force the port of the resulting
// socket address to be 77.
// "MAP * baz, EXCLUDE www.google.com" --> Remaps everything to "baz",
// except for "www.google.com".
//
// These mappings apply to the endpoint host in a net::URLRequest (the TCP
// connect and host resolver in a direct connection, and the CONNECT in an http
// proxy connection, and the endpoint host in a SOCKS proxy connection).
const char kHostRules[] = "host-rules";
// Don't use a proxy server, always make direct connections. Overrides any
// other proxy server flags that are passed.
const char kNoProxyServer[] = "no-proxy-server";
} // namespace
URLRequestContextGetter::URLRequestContextGetter(
const base::FilePath& base_path,
base::MessageLoop* io_loop,
base::MessageLoop* file_loop,
base::Callback<scoped_ptr<NetworkDelegate>(void)> network_delegate_factory,
URLRequestJobFactoryFactory job_factory_factory,
content::ProtocolHandlerMap* protocol_handlers,
content::ProtocolHandlerScopedVector protocol_interceptors)
: base_path_(base_path),
io_loop_(io_loop),
file_loop_(file_loop),
network_delegate_factory_(network_delegate_factory),
job_factory_factory_(job_factory_factory),
protocol_interceptors_(protocol_interceptors.Pass()) {
// Must first be created on the UI thread.
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
std::swap(protocol_handlers_, *protocol_handlers);
proxy_config_service_.reset(net::ProxyService::CreateSystemProxyConfigService(
io_loop_->message_loop_proxy(), file_loop_));
}
URLRequestContextGetter::~URLRequestContextGetter() {
}
net::HostResolver* URLRequestContextGetter::host_resolver() {
return url_request_context_->host_resolver();
}
net::URLRequestContext* URLRequestContextGetter::GetURLRequestContext() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (!url_request_context_.get()) {
url_request_context_.reset(new net::URLRequestContext());
network_delegate_ = network_delegate_factory_.Run().Pass();
url_request_context_->set_network_delegate(network_delegate_.get());
storage_.reset(
new net::URLRequestContextStorage(url_request_context_.get()));
auto cookie_config = content::CookieStoreConfig(
base_path_.Append(FILE_PATH_LITERAL("Cookies")),
content::CookieStoreConfig::EPHEMERAL_SESSION_COOKIES,
nullptr,
nullptr);
storage_->set_cookie_store(content::CreateCookieStore(cookie_config));
storage_->set_server_bound_cert_service(new net::ServerBoundCertService(
new net::DefaultServerBoundCertStore(NULL),
base::WorkerPool::GetTaskRunner(true)));
storage_->set_http_user_agent_settings(
new net::StaticHttpUserAgentSettings(
"en-us,en", base::EmptyString()));
scoped_ptr<net::HostResolver> host_resolver(
net::HostResolver::CreateDefaultResolver(NULL));
// --host-resolver-rules
if (command_line.HasSwitch(switches::kHostResolverRules)) {
scoped_ptr<net::MappedHostResolver> remapped_resolver(
new net::MappedHostResolver(host_resolver.Pass()));
remapped_resolver->SetRulesFromString(
command_line.GetSwitchValueASCII(switches::kHostResolverRules));
host_resolver = remapped_resolver.PassAs<net::HostResolver>();
}
net::DhcpProxyScriptFetcherFactory dhcp_factory;
if (command_line.HasSwitch(kNoProxyServer))
storage_->set_proxy_service(net::ProxyService::CreateDirect());
else
storage_->set_proxy_service(
net::CreateProxyServiceUsingV8ProxyResolver(
proxy_config_service_.release(),
new net::ProxyScriptFetcherImpl(url_request_context_.get()),
dhcp_factory.Create(url_request_context_.get()),
host_resolver.get(),
NULL,
url_request_context_->network_delegate()));
storage_->set_cert_verifier(net::CertVerifier::CreateDefault());
storage_->set_transport_security_state(new net::TransportSecurityState);
storage_->set_ssl_config_service(new net::SSLConfigServiceDefaults);
storage_->set_http_auth_handler_factory(
net::HttpAuthHandlerFactory::CreateDefault(host_resolver.get()));
scoped_ptr<net::HttpServerProperties> server_properties(
new net::HttpServerPropertiesImpl);
storage_->set_http_server_properties(server_properties.Pass());
base::FilePath cache_path = base_path_.Append(FILE_PATH_LITERAL("Cache"));
net::HttpCache::DefaultBackend* main_backend =
new net::HttpCache::DefaultBackend(
net::DISK_CACHE,
net::CACHE_BACKEND_DEFAULT,
cache_path,
0,
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE));
net::HttpNetworkSession::Params network_session_params;
network_session_params.cert_verifier =
url_request_context_->cert_verifier();
network_session_params.transport_security_state =
url_request_context_->transport_security_state();
network_session_params.server_bound_cert_service =
url_request_context_->server_bound_cert_service();
network_session_params.proxy_service =
url_request_context_->proxy_service();
network_session_params.ssl_config_service =
url_request_context_->ssl_config_service();
network_session_params.http_auth_handler_factory =
url_request_context_->http_auth_handler_factory();
network_session_params.network_delegate =
url_request_context_->network_delegate();
network_session_params.http_server_properties =
url_request_context_->http_server_properties();
network_session_params.ignore_certificate_errors = false;
// --host-rules
if (command_line.HasSwitch(kHostRules)) {
host_mapping_rules_.reset(new net::HostMappingRules);
host_mapping_rules_->SetRulesFromString(command_line.GetSwitchValueASCII(kHostRules));
network_session_params.host_mapping_rules = host_mapping_rules_.get();
}
// Give |storage_| ownership at the end in case it's |mapped_host_resolver|.
storage_->set_host_resolver(host_resolver.Pass());
network_session_params.host_resolver =
url_request_context_->host_resolver();
net::HttpCache* main_cache = new net::HttpCache(
network_session_params, main_backend);
storage_->set_http_transaction_factory(main_cache);
// Give user a chance to create their own job factory.
scoped_ptr<net::URLRequestJobFactory> user_job_factory(
job_factory_factory_.Run(&protocol_handlers_, &protocol_interceptors_));
if (user_job_factory) {
storage_->set_job_factory(user_job_factory.release());
return url_request_context_.get();
}
scoped_ptr<net::URLRequestJobFactoryImpl> job_factory(
new net::URLRequestJobFactoryImpl());
for (auto it = protocol_handlers_.begin(),
end = protocol_handlers_.end(); it != end; ++it) {
bool set_protocol = job_factory->SetProtocolHandler(
it->first, it->second.release());
DCHECK(set_protocol);
(void)set_protocol; // silence unused-variable warning in Release builds on Windows
}
protocol_handlers_.clear();
job_factory->SetProtocolHandler(
content::kDataScheme, new net::DataProtocolHandler);
job_factory->SetProtocolHandler(
content::kFileScheme,
new net::FileProtocolHandler(
BrowserThread::GetBlockingPool()->
GetTaskRunnerWithShutdownBehavior(
base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
// Set up interceptors in the reverse order.
scoped_ptr<net::URLRequestJobFactory> top_job_factory =
job_factory.PassAs<net::URLRequestJobFactory>();
for (content::ProtocolHandlerScopedVector::reverse_iterator i =
protocol_interceptors_.rbegin();
i != protocol_interceptors_.rend();
++i) {
top_job_factory.reset(new net::ProtocolInterceptJobFactory(
top_job_factory.Pass(), make_scoped_ptr(*i)));
}
protocol_interceptors_.weak_clear();
storage_->set_job_factory(top_job_factory.release());
}
return url_request_context_.get();
}
scoped_refptr<base::SingleThreadTaskRunner>
URLRequestContextGetter::GetNetworkTaskRunner() const {
return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
}
} // namespace brightray
<commit_msg>Add --proxy-server switch.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "browser/url_request_context_getter.h"
#include <algorithm>
#include "browser/network_delegate.h"
#include "base/command_line.h"
#include "base/strings/string_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/threading/worker_pool.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/cookie_store_factory.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "net/base/host_mapping_rules.h"
#include "net/cert/cert_verifier.h"
#include "net/cookies/cookie_monster.h"
#include "net/dns/mapped_host_resolver.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_cache.h"
#include "net/http/http_server_properties_impl.h"
#include "net/proxy/dhcp_proxy_script_fetcher_factory.h"
#include "net/proxy/proxy_config_service.h"
#include "net/proxy/proxy_script_fetcher_impl.h"
#include "net/proxy/proxy_service.h"
#include "net/proxy/proxy_service_v8.h"
#include "net/ssl/default_server_bound_cert_store.h"
#include "net/ssl/server_bound_cert_service.h"
#include "net/ssl/ssl_config_service_defaults.h"
#include "net/url_request/data_protocol_handler.h"
#include "net/url_request/file_protocol_handler.h"
#include "net/url_request/protocol_intercept_job_factory.h"
#include "net/url_request/static_http_user_agent_settings.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_storage.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "webkit/browser/quota/special_storage_policy.h"
using content::BrowserThread;
namespace brightray {
namespace {
// Comma-separated list of rules that control how hostnames are mapped.
//
// For example:
// "MAP * 127.0.0.1" --> Forces all hostnames to be mapped to 127.0.0.1
// "MAP *.google.com proxy" --> Forces all google.com subdomains to be
// resolved to "proxy".
// "MAP test.com [::1]:77 --> Forces "test.com" to resolve to IPv6 loopback.
// Will also force the port of the resulting
// socket address to be 77.
// "MAP * baz, EXCLUDE www.google.com" --> Remaps everything to "baz",
// except for "www.google.com".
//
// These mappings apply to the endpoint host in a net::URLRequest (the TCP
// connect and host resolver in a direct connection, and the CONNECT in an http
// proxy connection, and the endpoint host in a SOCKS proxy connection).
const char kHostRules[] = "host-rules";
// Don't use a proxy server, always make direct connections. Overrides any
// other proxy server flags that are passed.
const char kNoProxyServer[] = "no-proxy-server";
// Uses a specified proxy server, overrides system settings. This switch only
// affects HTTP and HTTPS requests.
const char kProxyServer[] = "proxy-server";
} // namespace
URLRequestContextGetter::URLRequestContextGetter(
const base::FilePath& base_path,
base::MessageLoop* io_loop,
base::MessageLoop* file_loop,
base::Callback<scoped_ptr<NetworkDelegate>(void)> network_delegate_factory,
URLRequestJobFactoryFactory job_factory_factory,
content::ProtocolHandlerMap* protocol_handlers,
content::ProtocolHandlerScopedVector protocol_interceptors)
: base_path_(base_path),
io_loop_(io_loop),
file_loop_(file_loop),
network_delegate_factory_(network_delegate_factory),
job_factory_factory_(job_factory_factory),
protocol_interceptors_(protocol_interceptors.Pass()) {
// Must first be created on the UI thread.
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
std::swap(protocol_handlers_, *protocol_handlers);
proxy_config_service_.reset(net::ProxyService::CreateSystemProxyConfigService(
io_loop_->message_loop_proxy(), file_loop_));
}
URLRequestContextGetter::~URLRequestContextGetter() {
}
net::HostResolver* URLRequestContextGetter::host_resolver() {
return url_request_context_->host_resolver();
}
net::URLRequestContext* URLRequestContextGetter::GetURLRequestContext() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (!url_request_context_.get()) {
url_request_context_.reset(new net::URLRequestContext());
network_delegate_ = network_delegate_factory_.Run().Pass();
url_request_context_->set_network_delegate(network_delegate_.get());
storage_.reset(
new net::URLRequestContextStorage(url_request_context_.get()));
auto cookie_config = content::CookieStoreConfig(
base_path_.Append(FILE_PATH_LITERAL("Cookies")),
content::CookieStoreConfig::EPHEMERAL_SESSION_COOKIES,
nullptr,
nullptr);
storage_->set_cookie_store(content::CreateCookieStore(cookie_config));
storage_->set_server_bound_cert_service(new net::ServerBoundCertService(
new net::DefaultServerBoundCertStore(NULL),
base::WorkerPool::GetTaskRunner(true)));
storage_->set_http_user_agent_settings(
new net::StaticHttpUserAgentSettings(
"en-us,en", base::EmptyString()));
scoped_ptr<net::HostResolver> host_resolver(
net::HostResolver::CreateDefaultResolver(NULL));
// --host-resolver-rules
if (command_line.HasSwitch(switches::kHostResolverRules)) {
scoped_ptr<net::MappedHostResolver> remapped_resolver(
new net::MappedHostResolver(host_resolver.Pass()));
remapped_resolver->SetRulesFromString(
command_line.GetSwitchValueASCII(switches::kHostResolverRules));
host_resolver = remapped_resolver.PassAs<net::HostResolver>();
}
net::DhcpProxyScriptFetcherFactory dhcp_factory;
if (command_line.HasSwitch(kNoProxyServer))
storage_->set_proxy_service(net::ProxyService::CreateDirect());
else if (command_line.HasSwitch(kProxyServer))
storage_->set_proxy_service(net::ProxyService::CreateFixed(
command_line.GetSwitchValueASCII(kProxyServer)));
else
storage_->set_proxy_service(
net::CreateProxyServiceUsingV8ProxyResolver(
proxy_config_service_.release(),
new net::ProxyScriptFetcherImpl(url_request_context_.get()),
dhcp_factory.Create(url_request_context_.get()),
host_resolver.get(),
NULL,
url_request_context_->network_delegate()));
storage_->set_cert_verifier(net::CertVerifier::CreateDefault());
storage_->set_transport_security_state(new net::TransportSecurityState);
storage_->set_ssl_config_service(new net::SSLConfigServiceDefaults);
storage_->set_http_auth_handler_factory(
net::HttpAuthHandlerFactory::CreateDefault(host_resolver.get()));
scoped_ptr<net::HttpServerProperties> server_properties(
new net::HttpServerPropertiesImpl);
storage_->set_http_server_properties(server_properties.Pass());
base::FilePath cache_path = base_path_.Append(FILE_PATH_LITERAL("Cache"));
net::HttpCache::DefaultBackend* main_backend =
new net::HttpCache::DefaultBackend(
net::DISK_CACHE,
net::CACHE_BACKEND_DEFAULT,
cache_path,
0,
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE));
net::HttpNetworkSession::Params network_session_params;
network_session_params.cert_verifier =
url_request_context_->cert_verifier();
network_session_params.transport_security_state =
url_request_context_->transport_security_state();
network_session_params.server_bound_cert_service =
url_request_context_->server_bound_cert_service();
network_session_params.proxy_service =
url_request_context_->proxy_service();
network_session_params.ssl_config_service =
url_request_context_->ssl_config_service();
network_session_params.http_auth_handler_factory =
url_request_context_->http_auth_handler_factory();
network_session_params.network_delegate =
url_request_context_->network_delegate();
network_session_params.http_server_properties =
url_request_context_->http_server_properties();
network_session_params.ignore_certificate_errors = false;
// --host-rules
if (command_line.HasSwitch(kHostRules)) {
host_mapping_rules_.reset(new net::HostMappingRules);
host_mapping_rules_->SetRulesFromString(command_line.GetSwitchValueASCII(kHostRules));
network_session_params.host_mapping_rules = host_mapping_rules_.get();
}
// Give |storage_| ownership at the end in case it's |mapped_host_resolver|.
storage_->set_host_resolver(host_resolver.Pass());
network_session_params.host_resolver =
url_request_context_->host_resolver();
net::HttpCache* main_cache = new net::HttpCache(
network_session_params, main_backend);
storage_->set_http_transaction_factory(main_cache);
// Give user a chance to create their own job factory.
scoped_ptr<net::URLRequestJobFactory> user_job_factory(
job_factory_factory_.Run(&protocol_handlers_, &protocol_interceptors_));
if (user_job_factory) {
storage_->set_job_factory(user_job_factory.release());
return url_request_context_.get();
}
scoped_ptr<net::URLRequestJobFactoryImpl> job_factory(
new net::URLRequestJobFactoryImpl());
for (auto it = protocol_handlers_.begin(),
end = protocol_handlers_.end(); it != end; ++it) {
bool set_protocol = job_factory->SetProtocolHandler(
it->first, it->second.release());
DCHECK(set_protocol);
(void)set_protocol; // silence unused-variable warning in Release builds on Windows
}
protocol_handlers_.clear();
job_factory->SetProtocolHandler(
content::kDataScheme, new net::DataProtocolHandler);
job_factory->SetProtocolHandler(
content::kFileScheme,
new net::FileProtocolHandler(
BrowserThread::GetBlockingPool()->
GetTaskRunnerWithShutdownBehavior(
base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
// Set up interceptors in the reverse order.
scoped_ptr<net::URLRequestJobFactory> top_job_factory =
job_factory.PassAs<net::URLRequestJobFactory>();
for (content::ProtocolHandlerScopedVector::reverse_iterator i =
protocol_interceptors_.rbegin();
i != protocol_interceptors_.rend();
++i) {
top_job_factory.reset(new net::ProtocolInterceptJobFactory(
top_job_factory.Pass(), make_scoped_ptr(*i)));
}
protocol_interceptors_.weak_clear();
storage_->set_job_factory(top_job_factory.release());
}
return url_request_context_.get();
}
scoped_refptr<base::SingleThreadTaskRunner>
URLRequestContextGetter::GetNetworkTaskRunner() const {
return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
}
} // namespace brightray
<|endoftext|> |
<commit_before><commit_msg>Solution of prob 10<commit_after>#include <stdio.h>
int count(const int *numbers_a, const int *numbers_b, const int size_a, const int size_b, const int index_a, const int index_b)
{
/* base case */
if(index_a >= size_a || index_b >= size_b) return 0;
/* recursive case */
if(numbers_a[index_a] == numbers_b[index_b]) /* match */
return 1 + count(numbers_a, numbers_b, size_a, size_b, index_a + 1, index_b + 1);
else /* not match */
{
if(numbers_a[index_a] < numbers_b[index_b]) return count(numbers_a, numbers_b, size_a, size_b, index_a + 1, index_b);
if(numbers_a[index_a] > numbers_b[index_b]) return count(numbers_a, numbers_b, size_a, size_b, index_a, index_b + 1);
}
}
int count_of_two_sum(const int *numbers_a, const int *numbers_b, const int number_count_a, const int number_count_b)
{
count(numbers_a, numbers_b, number_count_a, number_count_b, 0, 0);
}
int main(void)
{
printf("count of two sum\n");
int size_of_array_a, size_of_array_b;
printf("Enter size_of_array_a= "); scanf("%d", &size_of_array_a);
int array_a[size_of_array_a];
printf("Enter in ascending order\n");
for(int i = 0; i < size_of_array_a; i++)
{
printf("Enter array_a[%d]= ", i); scanf("%d", &array_a[i]);
}
printf("Enter size_of_array_b= "); scanf("%d", &size_of_array_b);
int array_b[size_of_array_b];
printf("Enter in ascending order\n");
for(int i = 0; i < size_of_array_b; i++)
{
printf("Enter array_b[%d]= ", i); scanf("%d", &array_b[i]);
}
printf("Result is %d\n", count_of_two_sum(array_a, array_b, size_of_array_a, size_of_array_b));
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2013 midnightBITS
*
* 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 "pch.h"
#include <forms/vertical_renderer.hpp>
#include <fast_cgi.hpp>
#include "pages/reader_form.hpp"
#include <utils.hpp>
namespace FastCGI { namespace app { namespace reader { namespace errors {
class ErrorPageHandler : public ErrorHandler
{
protected:
virtual const char* pageTitle(int errorCode) { return nullptr; }
virtual const char* pageTitle(int errorCode, PageTranslation& tr) { return pageTitle(errorCode); }
std::string getTitle(int errorCode, Request& request, PageTranslation& tr, bool hasStrings)
{
std::string title = hasStrings ? tr(lng::LNG_GLOBAL_SITENAME) : "reedr";
const char* page = hasStrings ? pageTitle(errorCode, tr) : pageTitle(errorCode);
if (!page) return title;
title += " » ";
title += page;
return title;
}
virtual void header(int errorCode, const SessionPtr& session, Request& request, PageTranslation& tr, bool hasStrings)
{
request << "<!DOCTYPE html "
"PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" "
"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n"
"<html>\r\n"
" <head>\r\n"
" <title>" << getTitle(errorCode, request, tr, hasStrings) << "</title>\r\n"
" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>\r\n"
" <style type=\"text/css\">@import url(\"" << static_web << "css/site.css\");</style>\r\n"
" <style type=\"text/css\">@import url(\"" << static_web << "css/topbar.css\");</style>\r\n"
" <script type=\"text/javascript\" src=\"" << static_web << "code/jquery-1.9.1.js\"></script>\r\n"
" <script type=\"text/javascript\" src=\"" << static_web << "code/topbar.js\"></script>\r\n"
//" <style type=\"text/css\">@import url(\"" << static_web << "css/topbar_icons.css\");</style>\r\n"
" <meta name=\"viewport\" content=\"width=device-width, user-scalable=no\"/>\r\n";
#if DEBUG_CGI
request <<
" <style type=\"text/css\">@import url(\"" << static_web << "css/fd_icons.css\");</style>\r\n";
#endif
const char* description = hasStrings ? tr(lng::LNG_GLOBAL_DESCRIPTION) : "stay up to date";
request <<
" <style type=\"text/css\">@import url(\"" << static_web << "css/site-logo-big.css\");</style>\r\n"
" <style type=\"text/css\">@import url(\"" << static_web << "css/tabs.css\");</style>\r\n"
" <style type=\"text/css\">@import url(\"" << static_web << "css/forms-base.css\");</style>\r\n"
" <style type=\"text/css\" media=\"screen and (min-width: 490px)\">@import url(\"" << static_web << "css/forms-wide.css\");</style>\r\n"
" <script type=\"text/javascript\" src=\"" << static_web << "code/jquery-1.9.1.js\"></script>\r\n"
" <script type=\"text/javascript\" src=\"" << static_web << "code/jquery.pjax.js\"></script>\r\n"
" <script type=\"text/javascript\" src=\"" << static_web << "code/ajax_fragment.js\"></script>\r\n"
" </head>\r\n"
" <body>\r\n"
" <div class='site-logo'><div>\r\n"
" <div class='logo'><a href='/'><img src='" << static_web << "images/auth_logo.png' /></a></div>\r\n"
" <div class='site'><a href='/'>" << description << "</a></div>\r\n"
" </div></div>\r\n"
"\r\n"
" <div id=\"form-content\">\r\n";
}
virtual void footer(const SessionPtr& session, Request& request, PageTranslation& tr, bool hasStrings)
{
request << "\r\n"
" </div> <!-- form-content -->\r\n"
" </body>\r\n"
"</html\r\n";
}
virtual void contents(int errorCode, const SessionPtr& session, Request& request, PageTranslation& tr, bool hasStrings)
{
request <<
" <h1>" << errorCode << "</h1>\r\n"
" <p>A message</p>\r\n"
;
}
void onError(int errorCode, Request& request) override
{
auto session = request.getSession(false);
PageTranslation tr{};
bool hasStrings = tr.init(session, request);
header(errorCode, session, request, tr, hasStrings);
contents(errorCode, session, request, tr, hasStrings);
footer(session, request, tr, hasStrings);
}
};
void setErrorHandlers(Application& app)
{
app.setErrorHandler(0, std::make_shared<ErrorPageHandler>());
}
}}}} // FastCGI::app::reader::errors
<commit_msg>Handler for 400 and 404<commit_after>/*
* Copyright (C) 2013 midnightBITS
*
* 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 "pch.h"
#include <forms/vertical_renderer.hpp>
#include <fast_cgi.hpp>
#include "pages/reader_form.hpp"
#include <utils.hpp>
namespace FastCGI { namespace app { namespace reader { namespace errors {
struct String
{
lng::LNG lngId;
const char* fallback;
};
struct FallbackTranslation
{
PageTranslation tr;
bool hasStrings;
public:
void init(const SessionPtr& session, Request& request)
{
hasStrings = tr.init(session, request);
}
const char* operator()(const String& s)
{
return hasStrings ? tr(s.lngId) : s.fallback;
}
const char* operator()(lng::LNG id, const char* fallback)
{
return hasStrings ? tr(id) : fallback;
}
};
class ErrorPageHandler : public ErrorHandler
{
protected:
virtual const char* pageTitle(int errorCode, FallbackTranslation& tr) { return nullptr; }
std::string getTitle(int errorCode, Request& request, FallbackTranslation& tr)
{
std::string title = tr(lng::LNG_GLOBAL_SITENAME, "reedr");
const char* page = pageTitle(errorCode, tr);
if (!page) return title;
title += " » ";
title += page;
return title;
}
virtual void header(int errorCode, const SessionPtr& session, Request& request, FallbackTranslation& tr)
{
request << "<!DOCTYPE html "
"PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" "
"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n"
"<html>\r\n"
" <head>\r\n"
" <title>" << getTitle(errorCode, request, tr) << "</title>\r\n"
" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>\r\n"
" <style type=\"text/css\">@import url(\"" << static_web << "css/site.css\");</style>\r\n"
" <style type=\"text/css\">@import url(\"" << static_web << "css/topbar.css\");</style>\r\n"
" <script type=\"text/javascript\" src=\"" << static_web << "code/jquery-1.9.1.js\"></script>\r\n"
" <script type=\"text/javascript\" src=\"" << static_web << "code/topbar.js\"></script>\r\n"
//" <style type=\"text/css\">@import url(\"" << static_web << "css/topbar_icons.css\");</style>\r\n"
" <meta name=\"viewport\" content=\"width=device-width, user-scalable=no\"/>\r\n";
#if DEBUG_CGI
request <<
" <style type=\"text/css\">@import url(\"" << static_web << "css/fd_icons.css\");</style>\r\n";
#endif
const char* description = tr(lng::LNG_GLOBAL_DESCRIPTION, "stay up to date");
request <<
" <style type=\"text/css\">@import url(\"" << static_web << "css/site-logo-big.css\");</style>\r\n"
" <style type=\"text/css\">@import url(\"" << static_web << "css/tabs.css\");</style>\r\n"
" <style type=\"text/css\">@import url(\"" << static_web << "css/forms-base.css\");</style>\r\n"
" <style type=\"text/css\" media=\"screen and (min-width: 490px)\">@import url(\"" << static_web << "css/forms-wide.css\");</style>\r\n"
" <script type=\"text/javascript\" src=\"" << static_web << "code/jquery-1.9.1.js\"></script>\r\n"
" <script type=\"text/javascript\" src=\"" << static_web << "code/jquery.pjax.js\"></script>\r\n"
" <script type=\"text/javascript\" src=\"" << static_web << "code/ajax_fragment.js\"></script>\r\n"
" </head>\r\n"
" <body>\r\n"
" <div class='site-logo'><div>\r\n"
" <div class='logo'><a href='/'><img src='" << static_web << "images/auth_logo.png' /></a></div>\r\n"
" <div class='site'><a href='/'>" << description << "</a></div>\r\n"
" </div></div>\r\n"
"\r\n"
" <div id=\"form-content\">\r\n";
}
virtual void footer(const SessionPtr& session, Request& request, FallbackTranslation& tr)
{
request << "\r\n"
" </div> <!-- form-content -->\r\n"
" </body>\r\n"
"</html\r\n";
}
virtual void contents(int errorCode, const SessionPtr& session, Request& request, FallbackTranslation& tr)
{
request <<
" <h1>" << errorCode << "</h1>\r\n"
" <p>A message</p>\r\n"
;
}
void onError(int errorCode, Request& request) override
{
auto session = request.getSession(false);
FallbackTranslation tr{};
tr.init(session, request);
header(errorCode, session, request, tr);
contents(errorCode, session, request, tr);
footer(session, request, tr);
}
};
struct ErrorInfo
{
String title;
String oops;
String info;
};
static inline void error_contents(Request& request, FallbackTranslation& tr, const ErrorInfo& nfo)
{
request << "<h1>" << tr(nfo.title) << "</h1>\r\n"
"<p class='oops'>" << tr(nfo.oops) << "</p>\r\n"
"<p>" << tr(nfo.info) << "</p>\r\n";
}
class Error404 : public ErrorPageHandler
{
public:
void contents(int errorCode, const SessionPtr& session, Request& request, FallbackTranslation& tr) override
{
error_contents(request, tr, {
{ lng::LNG_ERROR_404_TITLE, "404<br/>FILE NOT FOUND" },
{ lng::LNG_ERROR_404_OOPS, "Well, that was not supposed to happen." },
{ lng::LNG_ERROR_404_INFO, "This link has nothing to show, maybe you mistyped the link or followed a bad one." }
});
}
};
class Error400 : public ErrorPageHandler
{
public:
void contents(int errorCode, const SessionPtr& session, Request& request, FallbackTranslation& tr) override
{
error_contents(request, tr, {
{ lng::LNG_ERROR_400_TITLE, "400<br/>BAD REQUEST" },
{ lng::LNG_ERROR_400_OOPS, "Hmm, this request looks mighty strange." },
{ lng::LNG_ERROR_400_INFO, "The request your browser made was not understood." }
});
}
};
void setErrorHandlers(Application& app)
{
app.setErrorHandler(0, std::make_shared<ErrorPageHandler>());
app.setErrorHandler(400, std::make_shared<Error400>());
app.setErrorHandler(404, std::make_shared<Error404>());
}
}}}} // FastCGI::app::reader::errors
<|endoftext|> |
<commit_before>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file JavascriptInstance.cpp
* @brief Javascript script instance used wit EC_Script.
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "MemoryLeakCheck.h"
#include "JavascriptInstance.h"
#include "JavascriptModule.h"
#include "ScriptMetaTypeDefines.h"
#include "ScriptCoreTypeDefines.h"
#include "EC_Script.h"
#include "ScriptAsset.h"
#include "IModule.h"
#include "AssetAPI.h"
#include "IAssetStorage.h"
#include "LoggingFunctions.h"
#include <QFile>
#include <sstream>
#include <QScriptClass>
Q_DECLARE_METATYPE(QScriptClass*)
//#ifndef QT_NO_SCRIPTTOOLS
//#include <QScriptEngineDebugger>
//#endif
#include "MemoryLeakCheck.h"
JavascriptInstance::JavascriptInstance(const QString &fileName, JavascriptModule *module) :
engine_(0),
sourceFile(fileName),
module_(module),
evaluated(false)
{
CreateEngine();
Load();
}
JavascriptInstance::JavascriptInstance(ScriptAssetPtr scriptRef, JavascriptModule *module) :
engine_(0),
module_(module),
evaluated(false)
{
// Make sure we do not push null or empty script assets as sources
if (scriptRef && !scriptRef->scriptContent.isEmpty())
scriptRefs_.push_back(scriptRef);
CreateEngine();
Load();
}
JavascriptInstance::JavascriptInstance(const std::vector<ScriptAssetPtr>& scriptRefs, JavascriptModule *module) :
engine_(0),
module_(module),
evaluated(false)
{
// Make sure we do not push null or empty script assets as sources
for (unsigned i = 0; i < scriptRefs.size(); ++i)
if (scriptRefs[i] && !scriptRefs[i]->scriptContent.isEmpty()) scriptRefs_.push_back(scriptRefs[i]);
CreateEngine();
Load();
}
JavascriptInstance::~JavascriptInstance()
{
DeleteEngine();
}
void JavascriptInstance::Load()
{
if (!engine_)
CreateEngine();
if (sourceFile.isEmpty() && scriptRefs_.empty())
{
LogError("JavascriptInstance::Load: No script content to load!");
return;
}
// Can't specify both a file source and an Asset API source.
if (!sourceFile.isEmpty() && !scriptRefs_.empty())
{
LogError("JavascriptInstance::Load: Cannot specify both an local input source file and a list of script refs to load!");
return;
}
bool useAssetAPI = !scriptRefs_.empty();
unsigned numScripts = useAssetAPI ? scriptRefs_.size() : 1;
// Determine based on code origin whether it can be trusted with system access or not
if (useAssetAPI)
{
trusted_ = true;
for(unsigned i = 0; i < scriptRefs_.size(); ++i)
{
AssetStoragePtr storage = scriptRefs_[i]->GetAssetStorage();
trusted_ = trusted_ && storage && storage->Trusted();
}
}
else // Local file: always trusted.
{
program_ = LoadScript(sourceFile);
trusted_ = true; // This is a file on the local filesystem. We are making an assumption nobody can inject untrusted code here.
// Actually, we are assuming the attacker does not know the absolute location of the asset cache locally here, since if he makes
// the client to load a script into local cache, he could use this code path to automatically load that unsafe script from cache, and make it trusted. -jj.
}
// Check the validity of the syntax in the input.
for (unsigned i = 0; i < numScripts; ++i)
{
QString scriptSourceFilename = (useAssetAPI ? scriptRefs_[i]->Name() : sourceFile);
QString &scriptContent = (useAssetAPI ? scriptRefs_[i]->scriptContent : program_);
QScriptSyntaxCheckResult syntaxResult = engine_->checkSyntax(scriptContent);
if (syntaxResult.state() != QScriptSyntaxCheckResult::Valid)
{
LogError("Syntax error in script " + scriptSourceFilename + "," + QString::number(syntaxResult.errorLineNumber()) +
": " + syntaxResult.errorMessage());
// Delete our loaded script content (if any exists).
program_ == "";
}
}
}
QString JavascriptInstance::LoadScript(const QString &fileName)
{
QString filename = fileName.trimmed();
// First check if the include was supposed to go through the Asset API.
if (module_)
{
ScriptAssetPtr asset = boost::dynamic_pointer_cast<ScriptAsset>(module_->GetFramework()->Asset()->GetAsset(fileName));
if (asset)
return asset->scriptContent;
}
// Otherwise, treat fileName as a local file to load up.
QFile scriptFile(filename);
if (!scriptFile.open(QIODevice::ReadOnly))
{
LogError("JavascriptInstance::LoadScript: Failed to load script from file " + filename + "!");
return "";
}
QString result = scriptFile.readAll();
scriptFile.close();
QString trimmedResult = result.trimmed();
if (trimmedResult.isEmpty())
{
LogWarning("JavascriptInstance::LoadScript: Warning Loaded script from file " + filename + ", but the content was empty.");
return "";
}
return result;
}
void JavascriptInstance::Unload()
{
DeleteEngine();
}
void JavascriptInstance::Run()
{
// Need to have either absolute file path source or an Asset API source.
if (scriptRefs_.empty() && program_.isEmpty())
{
LogError("JavascriptInstance::Run: Cannot run, no script reference loaded.");
return;
}
// Can't specify both a file source and an Asset API source.
assert(sourceFile.isEmpty() || scriptRefs_.empty());
// If we've already evaluated this script once before, create a new script engine to run it again, or otherwise
// the effects would stack (we'd possibly register into signals twice, or other odd side effects).
// We never allow a script to be run twice in this kind of "stacking" manner.
if (evaluated)
{
Unload();
Load();
}
if (!engine_)
{
LogError("JavascriptInstance::Run: Cannot run, script engine not loaded.");
return;
}
// If no script specified at all, we'll have to abort.
if (program_.isEmpty() && scriptRefs_.empty())
return;
bool useAssets = !scriptRefs_.empty();
unsigned numScripts = useAssets ? scriptRefs_.size() : 1;
includedFiles.clear();
for (unsigned i = 0; i < numScripts; ++i)
{
QString scriptSourceFilename = (useAssets ? scriptRefs_[i]->Name() : sourceFile);
QString &scriptContent = (useAssets ? scriptRefs_[i]->scriptContent : program_);
QScriptValue result = engine_->evaluate(scriptContent, scriptSourceFilename);
CheckAndPrintException("In run/evaluate: ", result);
}
evaluated = true;
emit ScriptEvaluated();
}
void JavascriptInstance::RegisterService(QObject *serviceObject, const QString &name)
{
if (!engine_)
{
LogError("JavascriptInstance::RegisterService: No Qt script engine created when trying to register service to js script instance.");
return;
}
if (!serviceObject)
{
LogError("JavascriptInstance::RegisterService: Trying to pass a null service object pointer to RegisterService!");
return;
}
QScriptValue scriptValue = engine_->newQObject(serviceObject);
engine_->globalObject().setProperty(name, scriptValue);
}
void JavascriptInstance::IncludeFile(const QString &path)
{
for(uint i = 0; i < includedFiles.size(); ++i)
if (includedFiles[i].toLower() == path.toLower())
{
LogDebug("JavascriptInstance::IncludeFile: Not including already included file " + path);
return;
}
QString script = LoadScript(path);
QScriptContext *context = engine_->currentContext();
assert(context);
if (!context)
{
LogError("JavascriptInstance::IncludeFile: QScriptEngine::currentContext() returned null!");
return;
}
QScriptContext *parent = context->parentContext();
if (!parent)
{
LogError("JavascriptInstance::IncludeFile: QScriptEngine::parentContext() returned null!");
return;
}
context->setActivationObject(context->parentContext()->activationObject());
context->setThisObject(context->parentContext()->thisObject());
QScriptSyntaxCheckResult syntaxResult = engine_->checkSyntax(script);
if(syntaxResult.state() != QScriptSyntaxCheckResult::Valid)
{
LogError("JavascriptInstance::IncludeFile: Syntax error in " + path + ". " + syntaxResult.errorMessage() +
" In line:" + QString::number(syntaxResult.errorLineNumber()));
return;
}
QScriptValue result = engine_->evaluate(script);
includedFiles.push_back(path);
if (engine_->hasUncaughtException())
LogError(result.toString());
}
void JavascriptInstance::ImportExtension(const QString &scriptExtensionName)
{
assert(engine_);
if (!engine_)
{
LogWarning("JavascriptInstance::ImportExtension(" + scriptExtensionName + ") failed, QScriptEngine == null!");
return;
}
QStringList qt_extension_whitelist;
QStringList qt_class_blacklist;
/// Allowed extension imports
qt_extension_whitelist << "qt.core" << "qt.gui" << "qt.xml" << "qt.xmlpatterns" << "qt.opengl" << "qt.webkit";
/// qt.core and qt.gui: Classes that may be harmful to your system from untrusted scripts
qt_class_blacklist << "QLibrary" << "QPluginLoader" << "QProcess" // process and library access
<< "QFile" << "QDir" << "QFileSystemModel" << "QDirModel" // file system access
<< "QFileDialog" << "QFileSystemWatcher" << "QFileInfo"
<< "QFileOpenEvent" << "QFileSystemModel"
<< "QClipboard" << "QDesktopServices"; // "system" access
/// qt.webkit: Initial blacklist, enabling some of these can be discussed.
/// Availble classes: QWebView, QGraphicsWebView, QWebPage, QWebFrame
qt_class_blacklist << "QWebDatabase" << "QWebElement" << "QWebElementCollection" << "QWebHistory" << "QWebHistoryInterface" << "QWebHistoryItem"
<< "QWebHitTestResult" << "QWebInspector" << "QWebPluginFactory" << "QWebSecurityOrigin" << "QWebSettings";
if (!trusted_ && !qt_extension_whitelist.contains(scriptExtensionName, Qt::CaseInsensitive))
{
LogWarning("JavascriptInstance::ImportExtension: refusing to load a QtScript plugin for an untrusted instance: " + scriptExtensionName);
return;
}
QScriptValue success = engine_->importExtension(scriptExtensionName);
if (!success.isUndefined()) // Yes, importExtension returns undefinedValue if the import succeeds. http://doc.qt.nokia.com/4.7/qscriptengine.html#importExtension
LogWarning("JavascriptInstance::ImportExtension: Failed to load " + scriptExtensionName + " plugin for QtScript!");
if (!trusted_)
{
QScriptValue exposed;
foreach (const QString &blacktype, qt_class_blacklist)
{
exposed = engine_->globalObject().property(blacktype);
if (exposed.isValid())
{
engine_->globalObject().setProperty(blacktype, QScriptValue()); //passing an invalid val removes the property, http://doc.qt.nokia.com/4.6/qscriptvalue.html#setProperty
//LogInfo("JavascriptInstance::ImportExtension: removed a type from the untrusted context: " + blacktype);
}
}
}
}
bool JavascriptInstance::CheckAndPrintException(const QString& message, const QScriptValue& result)
{
if (engine_->hasUncaughtException())
{
LogError(message + result.toString());
foreach(const QString &error, engine_->uncaughtExceptionBacktrace())
LogError(error);
LogError("Line " + QString::number(engine_->uncaughtExceptionLineNumber()) + ".");
engine_->clearExceptions();
return true;
}
return false;
}
void JavascriptInstance::CreateEngine()
{
if (engine_)
DeleteEngine();
engine_ = new QScriptEngine;
connect(engine_, SIGNAL(signalHandlerException(const QScriptValue &)), SLOT(OnSignalHandlerException(const QScriptValue &)));
//#ifndef QT_NO_SCRIPTTOOLS
// debugger_ = new QScriptEngineDebugger();
// debugger.attachTo(engine_);
//// debugger_->action(QScriptEngineDebugger::InterruptAction)->trigger();
//#endif
ExposeQtMetaTypes(engine_);
ExposeCoreTypes(engine_);
ExposeCoreApiMetaTypes(engine_);
EC_Script *ec = dynamic_cast<EC_Script *>(owner_.lock().get());
module_->PrepareScriptInstance(this, ec);
evaluated = false;
}
void JavascriptInstance::DeleteEngine()
{
if (!engine_)
return;
program_ = "";
engine_->abortEvaluation();
// As a convention, we call a function 'OnScriptDestroyed' for each JS script
// so that they can clean up their data before the script is removed from the object,
// or when the system is unloading.
emit ScriptUnloading();
QScriptValue destructor = engine_->globalObject().property("OnScriptDestroyed");
if (!destructor.isUndefined())
{
QScriptValue result = destructor.call();
CheckAndPrintException("In script destructor: ", result);
}
SAFE_DELETE(engine_);
//SAFE_DELETE(debugger_);
}
void JavascriptInstance::OnSignalHandlerException(const QScriptValue& exception)
{
LogError(exception.toString());
foreach(const QString &error, engine_->uncaughtExceptionBacktrace())
LogError(error);
LogError("Line " + QString::number(engine_->uncaughtExceptionLineNumber()) + ".");
}
<commit_msg>Added an error print to detect odd situations where script assets exist in Asset API without a source storage.<commit_after>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file JavascriptInstance.cpp
* @brief Javascript script instance used wit EC_Script.
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "MemoryLeakCheck.h"
#include "JavascriptInstance.h"
#include "JavascriptModule.h"
#include "ScriptMetaTypeDefines.h"
#include "ScriptCoreTypeDefines.h"
#include "EC_Script.h"
#include "ScriptAsset.h"
#include "IModule.h"
#include "AssetAPI.h"
#include "IAssetStorage.h"
#include "LoggingFunctions.h"
#include <QFile>
#include <sstream>
#include <QScriptClass>
Q_DECLARE_METATYPE(QScriptClass*)
//#ifndef QT_NO_SCRIPTTOOLS
//#include <QScriptEngineDebugger>
//#endif
#include "MemoryLeakCheck.h"
JavascriptInstance::JavascriptInstance(const QString &fileName, JavascriptModule *module) :
engine_(0),
sourceFile(fileName),
module_(module),
evaluated(false)
{
CreateEngine();
Load();
}
JavascriptInstance::JavascriptInstance(ScriptAssetPtr scriptRef, JavascriptModule *module) :
engine_(0),
module_(module),
evaluated(false)
{
// Make sure we do not push null or empty script assets as sources
if (scriptRef && !scriptRef->scriptContent.isEmpty())
scriptRefs_.push_back(scriptRef);
CreateEngine();
Load();
}
JavascriptInstance::JavascriptInstance(const std::vector<ScriptAssetPtr>& scriptRefs, JavascriptModule *module) :
engine_(0),
module_(module),
evaluated(false)
{
// Make sure we do not push null or empty script assets as sources
for (unsigned i = 0; i < scriptRefs.size(); ++i)
if (scriptRefs[i] && !scriptRefs[i]->scriptContent.isEmpty()) scriptRefs_.push_back(scriptRefs[i]);
CreateEngine();
Load();
}
JavascriptInstance::~JavascriptInstance()
{
DeleteEngine();
}
void JavascriptInstance::Load()
{
if (!engine_)
CreateEngine();
if (sourceFile.isEmpty() && scriptRefs_.empty())
{
LogError("JavascriptInstance::Load: No script content to load!");
return;
}
// Can't specify both a file source and an Asset API source.
if (!sourceFile.isEmpty() && !scriptRefs_.empty())
{
LogError("JavascriptInstance::Load: Cannot specify both an local input source file and a list of script refs to load!");
return;
}
bool useAssetAPI = !scriptRefs_.empty();
unsigned numScripts = useAssetAPI ? scriptRefs_.size() : 1;
// Determine based on code origin whether it can be trusted with system access or not
if (useAssetAPI)
{
trusted_ = true;
for(unsigned i = 0; i < scriptRefs_.size(); ++i)
{
AssetStoragePtr storage = scriptRefs_[i]->GetAssetStorage();
if (!storage)
LogError("Error: Script asset \"" + scriptRefs_[i]->Name() + "\" does not have a source asset storage!");
trusted_ = trusted_ && storage && storage->Trusted();
}
}
else // Local file: always trusted.
{
program_ = LoadScript(sourceFile);
trusted_ = true; // This is a file on the local filesystem. We are making an assumption nobody can inject untrusted code here.
// Actually, we are assuming the attacker does not know the absolute location of the asset cache locally here, since if he makes
// the client to load a script into local cache, he could use this code path to automatically load that unsafe script from cache, and make it trusted. -jj.
}
// Check the validity of the syntax in the input.
for (unsigned i = 0; i < numScripts; ++i)
{
QString scriptSourceFilename = (useAssetAPI ? scriptRefs_[i]->Name() : sourceFile);
QString &scriptContent = (useAssetAPI ? scriptRefs_[i]->scriptContent : program_);
QScriptSyntaxCheckResult syntaxResult = engine_->checkSyntax(scriptContent);
if (syntaxResult.state() != QScriptSyntaxCheckResult::Valid)
{
LogError("Syntax error in script " + scriptSourceFilename + "," + QString::number(syntaxResult.errorLineNumber()) +
": " + syntaxResult.errorMessage());
// Delete our loaded script content (if any exists).
program_ == "";
}
}
}
QString JavascriptInstance::LoadScript(const QString &fileName)
{
QString filename = fileName.trimmed();
// First check if the include was supposed to go through the Asset API.
if (module_)
{
ScriptAssetPtr asset = boost::dynamic_pointer_cast<ScriptAsset>(module_->GetFramework()->Asset()->GetAsset(fileName));
if (asset)
return asset->scriptContent;
}
// Otherwise, treat fileName as a local file to load up.
QFile scriptFile(filename);
if (!scriptFile.open(QIODevice::ReadOnly))
{
LogError("JavascriptInstance::LoadScript: Failed to load script from file " + filename + "!");
return "";
}
QString result = scriptFile.readAll();
scriptFile.close();
QString trimmedResult = result.trimmed();
if (trimmedResult.isEmpty())
{
LogWarning("JavascriptInstance::LoadScript: Warning Loaded script from file " + filename + ", but the content was empty.");
return "";
}
return result;
}
void JavascriptInstance::Unload()
{
DeleteEngine();
}
void JavascriptInstance::Run()
{
// Need to have either absolute file path source or an Asset API source.
if (scriptRefs_.empty() && program_.isEmpty())
{
LogError("JavascriptInstance::Run: Cannot run, no script reference loaded.");
return;
}
// Can't specify both a file source and an Asset API source.
assert(sourceFile.isEmpty() || scriptRefs_.empty());
// If we've already evaluated this script once before, create a new script engine to run it again, or otherwise
// the effects would stack (we'd possibly register into signals twice, or other odd side effects).
// We never allow a script to be run twice in this kind of "stacking" manner.
if (evaluated)
{
Unload();
Load();
}
if (!engine_)
{
LogError("JavascriptInstance::Run: Cannot run, script engine not loaded.");
return;
}
// If no script specified at all, we'll have to abort.
if (program_.isEmpty() && scriptRefs_.empty())
return;
bool useAssets = !scriptRefs_.empty();
unsigned numScripts = useAssets ? scriptRefs_.size() : 1;
includedFiles.clear();
for (unsigned i = 0; i < numScripts; ++i)
{
QString scriptSourceFilename = (useAssets ? scriptRefs_[i]->Name() : sourceFile);
QString &scriptContent = (useAssets ? scriptRefs_[i]->scriptContent : program_);
QScriptValue result = engine_->evaluate(scriptContent, scriptSourceFilename);
CheckAndPrintException("In run/evaluate: ", result);
}
evaluated = true;
emit ScriptEvaluated();
}
void JavascriptInstance::RegisterService(QObject *serviceObject, const QString &name)
{
if (!engine_)
{
LogError("JavascriptInstance::RegisterService: No Qt script engine created when trying to register service to js script instance.");
return;
}
if (!serviceObject)
{
LogError("JavascriptInstance::RegisterService: Trying to pass a null service object pointer to RegisterService!");
return;
}
QScriptValue scriptValue = engine_->newQObject(serviceObject);
engine_->globalObject().setProperty(name, scriptValue);
}
void JavascriptInstance::IncludeFile(const QString &path)
{
for(uint i = 0; i < includedFiles.size(); ++i)
if (includedFiles[i].toLower() == path.toLower())
{
LogDebug("JavascriptInstance::IncludeFile: Not including already included file " + path);
return;
}
QString script = LoadScript(path);
QScriptContext *context = engine_->currentContext();
assert(context);
if (!context)
{
LogError("JavascriptInstance::IncludeFile: QScriptEngine::currentContext() returned null!");
return;
}
QScriptContext *parent = context->parentContext();
if (!parent)
{
LogError("JavascriptInstance::IncludeFile: QScriptEngine::parentContext() returned null!");
return;
}
context->setActivationObject(context->parentContext()->activationObject());
context->setThisObject(context->parentContext()->thisObject());
QScriptSyntaxCheckResult syntaxResult = engine_->checkSyntax(script);
if(syntaxResult.state() != QScriptSyntaxCheckResult::Valid)
{
LogError("JavascriptInstance::IncludeFile: Syntax error in " + path + ". " + syntaxResult.errorMessage() +
" In line:" + QString::number(syntaxResult.errorLineNumber()));
return;
}
QScriptValue result = engine_->evaluate(script);
includedFiles.push_back(path);
if (engine_->hasUncaughtException())
LogError(result.toString());
}
void JavascriptInstance::ImportExtension(const QString &scriptExtensionName)
{
assert(engine_);
if (!engine_)
{
LogWarning("JavascriptInstance::ImportExtension(" + scriptExtensionName + ") failed, QScriptEngine == null!");
return;
}
QStringList qt_extension_whitelist;
QStringList qt_class_blacklist;
/// Allowed extension imports
qt_extension_whitelist << "qt.core" << "qt.gui" << "qt.xml" << "qt.xmlpatterns" << "qt.opengl" << "qt.webkit";
/// qt.core and qt.gui: Classes that may be harmful to your system from untrusted scripts
qt_class_blacklist << "QLibrary" << "QPluginLoader" << "QProcess" // process and library access
<< "QFile" << "QDir" << "QFileSystemModel" << "QDirModel" // file system access
<< "QFileDialog" << "QFileSystemWatcher" << "QFileInfo"
<< "QFileOpenEvent" << "QFileSystemModel"
<< "QClipboard" << "QDesktopServices"; // "system" access
/// qt.webkit: Initial blacklist, enabling some of these can be discussed.
/// Availble classes: QWebView, QGraphicsWebView, QWebPage, QWebFrame
qt_class_blacklist << "QWebDatabase" << "QWebElement" << "QWebElementCollection" << "QWebHistory" << "QWebHistoryInterface" << "QWebHistoryItem"
<< "QWebHitTestResult" << "QWebInspector" << "QWebPluginFactory" << "QWebSecurityOrigin" << "QWebSettings";
if (!trusted_ && !qt_extension_whitelist.contains(scriptExtensionName, Qt::CaseInsensitive))
{
LogWarning("JavascriptInstance::ImportExtension: refusing to load a QtScript plugin for an untrusted instance: " + scriptExtensionName);
return;
}
QScriptValue success = engine_->importExtension(scriptExtensionName);
if (!success.isUndefined()) // Yes, importExtension returns undefinedValue if the import succeeds. http://doc.qt.nokia.com/4.7/qscriptengine.html#importExtension
LogWarning("JavascriptInstance::ImportExtension: Failed to load " + scriptExtensionName + " plugin for QtScript!");
if (!trusted_)
{
QScriptValue exposed;
foreach (const QString &blacktype, qt_class_blacklist)
{
exposed = engine_->globalObject().property(blacktype);
if (exposed.isValid())
{
engine_->globalObject().setProperty(blacktype, QScriptValue()); //passing an invalid val removes the property, http://doc.qt.nokia.com/4.6/qscriptvalue.html#setProperty
//LogInfo("JavascriptInstance::ImportExtension: removed a type from the untrusted context: " + blacktype);
}
}
}
}
bool JavascriptInstance::CheckAndPrintException(const QString& message, const QScriptValue& result)
{
if (engine_->hasUncaughtException())
{
LogError(message + result.toString());
foreach(const QString &error, engine_->uncaughtExceptionBacktrace())
LogError(error);
LogError("Line " + QString::number(engine_->uncaughtExceptionLineNumber()) + ".");
engine_->clearExceptions();
return true;
}
return false;
}
void JavascriptInstance::CreateEngine()
{
if (engine_)
DeleteEngine();
engine_ = new QScriptEngine;
connect(engine_, SIGNAL(signalHandlerException(const QScriptValue &)), SLOT(OnSignalHandlerException(const QScriptValue &)));
//#ifndef QT_NO_SCRIPTTOOLS
// debugger_ = new QScriptEngineDebugger();
// debugger.attachTo(engine_);
//// debugger_->action(QScriptEngineDebugger::InterruptAction)->trigger();
//#endif
ExposeQtMetaTypes(engine_);
ExposeCoreTypes(engine_);
ExposeCoreApiMetaTypes(engine_);
EC_Script *ec = dynamic_cast<EC_Script *>(owner_.lock().get());
module_->PrepareScriptInstance(this, ec);
evaluated = false;
}
void JavascriptInstance::DeleteEngine()
{
if (!engine_)
return;
program_ = "";
engine_->abortEvaluation();
// As a convention, we call a function 'OnScriptDestroyed' for each JS script
// so that they can clean up their data before the script is removed from the object,
// or when the system is unloading.
emit ScriptUnloading();
QScriptValue destructor = engine_->globalObject().property("OnScriptDestroyed");
if (!destructor.isUndefined())
{
QScriptValue result = destructor.call();
CheckAndPrintException("In script destructor: ", result);
}
SAFE_DELETE(engine_);
//SAFE_DELETE(debugger_);
}
void JavascriptInstance::OnSignalHandlerException(const QScriptValue& exception)
{
LogError(exception.toString());
foreach(const QString &error, engine_->uncaughtExceptionBacktrace())
LogError(error);
LogError("Line " + QString::number(engine_->uncaughtExceptionLineNumber()) + ".");
}
<|endoftext|> |
<commit_before>/*
* Copyright 2010,
* François Bleibel,
* Olivier Stasse,
*
* CNRS/AIST
*
* This file is part of sot-dynamic.
* sot-dynamic is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
* sot-dynamic 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 sot-dynamic. If not, see <http://www.gnu.org/licenses/>.
*/
/** \mainpage
\section sec_intro Introduction
The sot-dynamic package is a bridge between the stack of tasks framework and the dynamicsJRLJapan library.
It provides an inverse dynamic model of the robot through dynamic-graph entities.
More precisely it wraps the newton euler algorithm implemented by the dynamicsJRLJapan library
to make it accessible for the stack of tasks controllers
(in the Stack of Tasks Framework as defined in \ref Mansard2007.)
This package depends on the following packages:
\li dynamicsJRLJapan
\li sot-core
\li dynamic-graph
Optional packages (for specific support of the hrp2-N robots)
\li hrp210optimized
\li hrp2-dynamics
See the JRL umi3218's page on github for instructions on how to download and
install these packages at https://github.com/jrl-umi3218.
\section overview API overview
As most packages based on the dynamic-graph framework (see https://github.com/jrl-umi3218/dynamic-graph),
the functionnality is exposed through entities. Hence .so or .dll (dynamic-link) libraries are
generated in the dynamic-graph plugins directory.
The following entities are created by this package:\n
(all entites are placed in the namespace sot::)
\li sot::ZmprefFromCom
\li sot::ForceCompensation
\li sot::IntegratorForceExact
\li sot::MassApparent
\li sot::IntegratorForceRk4
\li sot::IntegratorForce
\li sot::AngleEstimator
\li sot::WaistAttitudeFromSensor
\li sot::Dynamic - provides the inverse dynamics computations for of a humanoid robot
Optionally, if the packages in brackets are installed, the following entities
are made available:
\li sot::DynamicHrp2 - same as sot::Dynamic, but specialized for hrp2 robots [needs hrp2-dynamics]
\li sot::DynamicHrp2_10 - same as previous, optimized for the hrp2-10 robot [needs hrp210optimized]
\li sot::DynamicHrp2_10_old [needs hrp210optimized]
See each entity's documentation page for more information (when available).
\section References
\anchor Mansard2007
<b>"Task sequencing for sensor-based control"</b>,
<em>N. Mansard, F. Chaumette,</em>
IEEE Trans. on Robotics, 23(1):60-72, February 2007
**/
<commit_msg>Update doxygen main page and reference sphinx-documentation.<commit_after>/*
* Copyright 2010,
* François Bleibel,
* Olivier Stasse,
*
* CNRS/AIST
*
* This file is part of sot-dynamic.
* sot-dynamic is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
* sot-dynamic 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 sot-dynamic. If not, see <http://www.gnu.org/licenses/>.
*/
/** \mainpage
\section sot_dynamic_section_introduction Introduction
The sot-dynamic package is a bridge between the stack of tasks framework and the dynamicsJRLJapan library.
It provides an inverse dynamic model of the robot through dynamic-graph entities.
More precisely it wraps the newton euler algorithm implemented by the dynamicsJRLJapan library
to make it accessible for the stack of tasks controllers
(in the Stack of Tasks Framework as defined in \ref Mansard2007.)
This package depends on the following packages:
\li dynamicsJRLJapan
\li sot-core
\li dynamic-graph
\li dynamic-graph-python
Optional packages (for specific support of the hrp2-N robots)
\li hrp210optimized
\li hrp2-dynamics
See the JRL umi3218's page on github for instructions on how to download and
install these packages at https://github.com/jrl-umi3218.
\section python_bindings Python bindings
As most packages based on the dynamic-graph framework (see https://github.com/jrl-umi3218/dynamic-graph),
the functionnality is exposed through entities. Hence python sub-modules of dynamic_graph are generated. See <a href="../sphinx-html/index.html">sphinx documentation</a> for more details.
The following entities are created by this package:\n
(all entites are placed in the namespace sot::)
\li sot::ZmprefFromCom
\li sot::ForceCompensation
\li sot::IntegratorForceExact
\li sot::MassApparent
\li sot::IntegratorForceRk4
\li sot::IntegratorForce
\li sot::AngleEstimator
\li sot::WaistAttitudeFromSensor
\li sot::Dynamic - provides the inverse dynamics computations for of a humanoid robot
Optionally, if the packages in brackets are installed, the following entities
are made available:
\li sot::DynamicHrp2 - same as sot::Dynamic, but specialized for hrp2 robots [needs hrp2-dynamics]
\li sot::DynamicHrp2_10 - same as previous, optimized for the hrp2-10 robot [needs hrp210optimized]
\li sot::DynamicHrp2_10_old [needs hrp210optimized]
See each entity's documentation page for more information (when available).
\section References
\anchor Mansard2007
<b>"Task sequencing for sensor-based control"</b>,
<em>N. Mansard, F. Chaumette,</em>
IEEE Trans. on Robotics, 23(1):60-72, February 2007
**/
<|endoftext|> |
<commit_before>/// HEADER
#include <csapex/utility/subprocess.h>
#include <csapex/utility/assert.h>
/// SYSTEM
#include <iostream>
#include <boost/optional.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/interprocess/sync/interprocess_mutex.hpp>
#include <boost/interprocess/sync/interprocess_condition.hpp>
#include <unistd.h>
#include <fstream>
using namespace csapex;
namespace detail
{
Subprocess* g_sp_instance = nullptr;
void sp_signal_handler(int signal)
{
if(g_sp_instance) {
g_sp_instance->handleSignal(signal);
}
std::quick_exit(0);
}
}
Subprocess::Subprocess(const std::string& name_space)
: in(name_space + "_in", false, 65536),
out(name_space + "_out", false, 65536),
ctrl_in(name_space + "_ctrl", true, 1024),
ctrl_out(name_space + "_ctrl", true, 1024),
pid_(-1),
is_shutdown(false),
return_code(0)
{
if (pipe(pipe_in)) {
throw std::runtime_error("cannot create pipe for stdin");
}
if (pipe(pipe_out)) {
close(pipe_in[0]);
close(pipe_in[1]);
throw std::runtime_error("cannot create pipe for stdout");
}
if (pipe(pipe_err)) {
close(pipe_out[0]);
close(pipe_out[1]);
close(pipe_in[0]);
close(pipe_in[1]);
throw std::runtime_error("cannot create pipe for stderr");
}
active_ = true;
}
Subprocess::~Subprocess()
{
if(isParent()) {
while(ctrl_out.hasMessage()) {
readCtrlOut();
}
if(!isChildShutdown()) {
ctrl_in.write({SubprocessChannel::MessageType::SHUTDOWN, "shutdown"});
}
close(pipe_err[1]);
close(pipe_out[0]);
close(pipe_in[0]);
join();
}
}
bool Subprocess::isChild() const
{
return pid_ == 0;
}
bool Subprocess::isParent() const
{
return pid_ > 0;
}
void Subprocess::handleSignal(int signal)
{
if(active_) {
flush();
close(pipe_in[0]);
close(pipe_out[1]);
close(pipe_err[1]);
out.write({SubprocessChannel::MessageType::CHILD_SIGNAL, std::to_string(signal)});
ctrl_out.write({SubprocessChannel::MessageType::CHILD_SIGNAL, std::to_string(signal)});
}
}
pid_t Subprocess::fork(std::function<int()> child)
{
pid_ = ::fork();
if(pid_ == 0) {
close(pipe_in[1]);
close(pipe_out[0]);
close(pipe_err[0]);
// dup2(pipe_in[0], 0);
// dup2(pipe_out[1], 1);
// dup2(pipe_err[1], 2);
detail::g_sp_instance = this;
std::signal(SIGHUP , detail::sp_signal_handler);
std::signal(SIGINT , detail::sp_signal_handler);
std::signal(SIGQUIT , detail::sp_signal_handler);
std::signal(SIGILL , detail::sp_signal_handler);
std::signal(SIGTRAP , detail::sp_signal_handler);
std::signal(SIGABRT , detail::sp_signal_handler);
std::signal(SIGIOT , detail::sp_signal_handler);
std::signal(SIGBUS , detail::sp_signal_handler);
std::signal(SIGFPE , detail::sp_signal_handler);
std::signal(SIGKILL , detail::sp_signal_handler);
std::signal(SIGUSR1 , detail::sp_signal_handler);
std::signal(SIGSEGV , detail::sp_signal_handler);
std::signal(SIGUSR2 , detail::sp_signal_handler);
std::signal(SIGPIPE , detail::sp_signal_handler);
std::signal(SIGALRM , detail::sp_signal_handler);
std::signal(SIGTERM , detail::sp_signal_handler);
std::signal(SIGSTKFLT, detail::sp_signal_handler);
//std::signal(SIGCLD , detail::sp_signal_handler);
//std::signal(SIGCHLD , detail::sp_signal_handler);
//std::signal(SIGCONT , detail::sp_signal_handler);
//std::signal(SIGSTOP , detail::sp_signal_handler);
//std::signal(SIGTSTP , detail::sp_signal_handler);
//std::signal(SIGTTIN , detail::sp_signal_handler);
//std::signal(SIGTTOU , detail::sp_signal_handler);
//std::signal(SIGURG , detail::sp_signal_handler);
std::signal(SIGXCPU , detail::sp_signal_handler);
std::signal(SIGXFSZ , detail::sp_signal_handler);
std::signal(SIGVTALRM, detail::sp_signal_handler);
std::signal(SIGPROF , detail::sp_signal_handler);
//std::signal(SIGWINCH , detail::sp_signal_handler);
std::signal(SIGPOLL , detail::sp_signal_handler);
std::signal(SIGIO , detail::sp_signal_handler);
std::signal(SIGPWR , detail::sp_signal_handler);
std::signal(SIGSYS , detail::sp_signal_handler);
std::signal(SIGUNUSED, detail::sp_signal_handler);
subprocess_worker_ = std::thread([this](){
while(active_) {
try {
SubprocessChannel::Message m = ctrl_in.read();
switch(m.type)
{
case SubprocessChannel::MessageType::SHUTDOWN:
active_ = false;
in.shutdown();
out.shutdown();
break;
}
} catch(const SubprocessChannel::ShutdownException& e) {
active_ = false;
}
}
});
int return_code = 0;
try {
return_code = child();
} catch(const std::exception& e) {
if (active_) {
out.write({SubprocessChannel::MessageType::CHILD_ERROR, e.what()});
}
return_code = -1;
} catch(...) {
if (active_) {
out.write({SubprocessChannel::MessageType::CHILD_ERROR, "unknown error"});
}
return_code = -2;
}
active_ = false;
ctrl_in.shutdown();
subprocess_worker_.join();
close(pipe_in[0]);
close(pipe_out[1]);
close(pipe_err[1]);
// then send the end of program signal
ctrl_out.write({SubprocessChannel::MessageType::CHILD_EXIT, std::to_string(return_code)});
std::quick_exit(0);
} else {
close(pipe_in[0]);
close(pipe_out[1]);
close(pipe_err[1]);
const std::size_t N = 32;
// TODO: extract "pipe" class
parent_worker_cout_ = std::thread([&]() {
while(active_) {
char buf[N+1];
int r;
while((r = read(pipe_out[0], &buf, N)) > 0) {
buf[r] = 0;
child_cout << buf;
}
}
});
parent_worker_cerr_ = std::thread([&]() {
while(active_) {
char buf[N+1];
int r;
while((r = read(pipe_err[0], &buf, N)) > 0) {
buf[r] = 0;
child_cerr << buf;
}
}
});
}
return pid_;
}
void Subprocess::flush()
{
if(isChild()) {
fflush(stdout);
fflush(stderr);
} else {
apex_assert_hard(active_);
}
}
std::string Subprocess::getChildStdOut() const
{
return child_cout.str();
}
std::string Subprocess::getChildStdErr() const
{
return child_cerr.str();
}
bool Subprocess::isChildShutdown() const
{
return is_shutdown;
}
void Subprocess::readCtrlOut()
{
SubprocessChannel::Message message = ctrl_out.read();
switch(message.type) {
case SubprocessChannel::MessageType::CHILD_EXIT:
case SubprocessChannel::MessageType::CHILD_SIGNAL:
{
is_shutdown = true;
std::stringstream ss(message.toString());
ss >> return_code;
}
break;
case SubprocessChannel::MessageType::CHILD_ERROR:
is_shutdown = true;
return_code = 64;
break;
default:
std::cout << "read an unknown message: " << message.toString() << std::endl;
break;
}
}
int Subprocess::join()
{
apex_assert_hard(isParent());
while(!isChildShutdown()) {
readCtrlOut();
}
close(pipe_out[0]);
close(pipe_err[0]);
active_ = false;
if(parent_worker_cerr_.joinable()) {
parent_worker_cerr_.join();
}
if(parent_worker_cout_.joinable()) {
parent_worker_cout_.join();
}
return return_code;
}
bool Subprocess::isActive() const
{
return active_;
}
<commit_msg>Reenable subprocess output stream syphoning<commit_after>/// HEADER
#include <csapex/utility/subprocess.h>
#include <csapex/utility/assert.h>
/// SYSTEM
#include <iostream>
#include <boost/optional.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/interprocess/sync/interprocess_mutex.hpp>
#include <boost/interprocess/sync/interprocess_condition.hpp>
#include <unistd.h>
#include <fstream>
using namespace csapex;
namespace detail
{
Subprocess* g_sp_instance = nullptr;
void sp_signal_handler(int signal)
{
if(g_sp_instance) {
g_sp_instance->handleSignal(signal);
}
std::quick_exit(0);
}
}
Subprocess::Subprocess(const std::string& name_space)
: in(name_space + "_in", false, 65536),
out(name_space + "_out", false, 65536),
ctrl_in(name_space + "_ctrl", true, 1024),
ctrl_out(name_space + "_ctrl", true, 1024),
pid_(-1),
is_shutdown(false),
return_code(0)
{
if (pipe(pipe_in)) {
throw std::runtime_error("cannot create pipe for stdin");
}
if (pipe(pipe_out)) {
close(pipe_in[0]);
close(pipe_in[1]);
throw std::runtime_error("cannot create pipe for stdout");
}
if (pipe(pipe_err)) {
close(pipe_out[0]);
close(pipe_out[1]);
close(pipe_in[0]);
close(pipe_in[1]);
throw std::runtime_error("cannot create pipe for stderr");
}
active_ = true;
}
Subprocess::~Subprocess()
{
if(isParent()) {
while(ctrl_out.hasMessage()) {
readCtrlOut();
}
if(!isChildShutdown()) {
ctrl_in.write({SubprocessChannel::MessageType::SHUTDOWN, "shutdown"});
}
close(pipe_err[1]);
close(pipe_out[0]);
close(pipe_in[0]);
join();
}
}
bool Subprocess::isChild() const
{
return pid_ == 0;
}
bool Subprocess::isParent() const
{
return pid_ > 0;
}
void Subprocess::handleSignal(int signal)
{
if(active_) {
flush();
close(pipe_in[0]);
close(pipe_out[1]);
close(pipe_err[1]);
out.write({SubprocessChannel::MessageType::CHILD_SIGNAL, std::to_string(signal)});
ctrl_out.write({SubprocessChannel::MessageType::CHILD_SIGNAL, std::to_string(signal)});
}
}
pid_t Subprocess::fork(std::function<int()> child)
{
pid_ = ::fork();
if(pid_ == 0) {
close(pipe_in[1]);
close(pipe_out[0]);
close(pipe_err[0]);
dup2(pipe_in[0], 0);
dup2(pipe_out[1], 1);
dup2(pipe_err[1], 2);
detail::g_sp_instance = this;
std::signal(SIGHUP , detail::sp_signal_handler);
std::signal(SIGINT , detail::sp_signal_handler);
std::signal(SIGQUIT , detail::sp_signal_handler);
std::signal(SIGILL , detail::sp_signal_handler);
std::signal(SIGTRAP , detail::sp_signal_handler);
std::signal(SIGABRT , detail::sp_signal_handler);
std::signal(SIGIOT , detail::sp_signal_handler);
std::signal(SIGBUS , detail::sp_signal_handler);
std::signal(SIGFPE , detail::sp_signal_handler);
std::signal(SIGKILL , detail::sp_signal_handler);
std::signal(SIGUSR1 , detail::sp_signal_handler);
std::signal(SIGSEGV , detail::sp_signal_handler);
std::signal(SIGUSR2 , detail::sp_signal_handler);
std::signal(SIGPIPE , detail::sp_signal_handler);
std::signal(SIGALRM , detail::sp_signal_handler);
std::signal(SIGTERM , detail::sp_signal_handler);
std::signal(SIGSTKFLT, detail::sp_signal_handler);
//std::signal(SIGCLD , detail::sp_signal_handler);
//std::signal(SIGCHLD , detail::sp_signal_handler);
//std::signal(SIGCONT , detail::sp_signal_handler);
//std::signal(SIGSTOP , detail::sp_signal_handler);
//std::signal(SIGTSTP , detail::sp_signal_handler);
//std::signal(SIGTTIN , detail::sp_signal_handler);
//std::signal(SIGTTOU , detail::sp_signal_handler);
//std::signal(SIGURG , detail::sp_signal_handler);
std::signal(SIGXCPU , detail::sp_signal_handler);
std::signal(SIGXFSZ , detail::sp_signal_handler);
std::signal(SIGVTALRM, detail::sp_signal_handler);
std::signal(SIGPROF , detail::sp_signal_handler);
//std::signal(SIGWINCH , detail::sp_signal_handler);
std::signal(SIGPOLL , detail::sp_signal_handler);
std::signal(SIGIO , detail::sp_signal_handler);
std::signal(SIGPWR , detail::sp_signal_handler);
std::signal(SIGSYS , detail::sp_signal_handler);
std::signal(SIGUNUSED, detail::sp_signal_handler);
subprocess_worker_ = std::thread([this](){
while(active_) {
try {
SubprocessChannel::Message m = ctrl_in.read();
switch(m.type)
{
case SubprocessChannel::MessageType::SHUTDOWN:
active_ = false;
in.shutdown();
out.shutdown();
break;
}
} catch(const SubprocessChannel::ShutdownException& e) {
active_ = false;
}
}
});
int return_code = 0;
try {
return_code = child();
} catch(const std::exception& e) {
if (active_) {
out.write({SubprocessChannel::MessageType::CHILD_ERROR, e.what()});
}
return_code = -1;
} catch(...) {
if (active_) {
out.write({SubprocessChannel::MessageType::CHILD_ERROR, "unknown error"});
}
return_code = -2;
}
active_ = false;
ctrl_in.shutdown();
subprocess_worker_.join();
close(pipe_in[0]);
close(pipe_out[1]);
close(pipe_err[1]);
// then send the end of program signal
ctrl_out.write({SubprocessChannel::MessageType::CHILD_EXIT, std::to_string(return_code)});
std::quick_exit(0);
} else {
close(pipe_in[0]);
close(pipe_out[1]);
close(pipe_err[1]);
const std::size_t N = 32;
// TODO: extract "pipe" class
parent_worker_cout_ = std::thread([&]() {
while(active_) {
char buf[N+1];
int r;
while((r = read(pipe_out[0], &buf, N)) > 0) {
buf[r] = 0;
child_cout << buf;
}
}
});
parent_worker_cerr_ = std::thread([&]() {
while(active_) {
char buf[N+1];
int r;
while((r = read(pipe_err[0], &buf, N)) > 0) {
buf[r] = 0;
child_cerr << buf;
}
}
});
}
return pid_;
}
void Subprocess::flush()
{
if(isChild()) {
fflush(stdout);
fflush(stderr);
} else {
apex_assert_hard(active_);
}
}
std::string Subprocess::getChildStdOut() const
{
return child_cout.str();
}
std::string Subprocess::getChildStdErr() const
{
return child_cerr.str();
}
bool Subprocess::isChildShutdown() const
{
return is_shutdown;
}
void Subprocess::readCtrlOut()
{
SubprocessChannel::Message message = ctrl_out.read();
switch(message.type) {
case SubprocessChannel::MessageType::CHILD_EXIT:
case SubprocessChannel::MessageType::CHILD_SIGNAL:
{
is_shutdown = true;
std::stringstream ss(message.toString());
ss >> return_code;
}
break;
case SubprocessChannel::MessageType::CHILD_ERROR:
is_shutdown = true;
return_code = 64;
break;
default:
std::cout << "read an unknown message: " << message.toString() << std::endl;
break;
}
}
int Subprocess::join()
{
apex_assert_hard(isParent());
while(!isChildShutdown()) {
readCtrlOut();
}
close(pipe_out[0]);
close(pipe_err[0]);
active_ = false;
if(parent_worker_cerr_.joinable()) {
parent_worker_cerr_.join();
}
if(parent_worker_cout_.joinable()) {
parent_worker_cout_.join();
}
return return_code;
}
bool Subprocess::isActive() const
{
return active_;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <osrm/Coordinate.h>
#include "DouglasPeucker.h"
#include "../DataStructures/SegmentInformation.h"
#include <boost/assert.hpp>
#include <cmath>
#include <limits>
DouglasPeucker::DouglasPeucker()
: douglas_peucker_thresholds({262144., // z0
131072., // z1
65536., // z2
32768., // z3
16384., // z4
8192., // z5
4096., // z6
2048., // z7
960., // z8
480., // z9
240., // z10
90., // z11
50., // z12
25., // z13
15., // z14
5., // z15
.65, // z16
.5, // z17
.35 // z18
})
{
}
void DouglasPeucker::Run(std::vector<SegmentInformation> &input_geometry, const unsigned zoom_level)
{
BOOST_ASSERT_MSG(!input_geometry.empty(), "geometry invalid");
if (input_geometry.size() <= 2)
{
return;
}
{
BOOST_ASSERT_MSG(zoom_level < 19, "unsupported zoom level");
unsigned left_border = 0;
unsigned right_border = 1;
// Sweep over array and identify those ranges that need to be checked
do
{
BOOST_ASSERT_MSG(input_geometry[left_border].necessary,
"left border must be necessary");
BOOST_ASSERT_MSG(input_geometry.back().necessary, "right border must be necessary");
if (input_geometry[right_border].necessary)
{
recursion_stack.emplace(left_border, right_border);
left_border = right_border;
}
++right_border;
} while (right_border < input_geometry.size());
}
while (!recursion_stack.empty())
{
// pop next element
const GeometryRange pair = recursion_stack.top();
recursion_stack.pop();
BOOST_ASSERT_MSG(input_geometry[pair.first].necessary, "left border mus be necessary");
BOOST_ASSERT_MSG(input_geometry[pair.second].necessary, "right border must be necessary");
BOOST_ASSERT_MSG(pair.second < input_geometry.size(), "right border outside of geometry");
BOOST_ASSERT_MSG(pair.first < pair.second, "left border on the wrong side");
double max_distance = std::numeric_limits<double>::min();
unsigned farthest_element_index = pair.second;
// find index idx of element with max_distance
for (unsigned i = pair.first + 1; i < pair.second; ++i)
{
const double temp_dist = FixedPointCoordinate::ComputePerpendicularDistance(
input_geometry[i].location,
input_geometry[pair.first].location,
input_geometry[pair.second].location);
const double distance = std::abs(temp_dist);
if (distance > douglas_peucker_thresholds[zoom_level] && distance > max_distance)
{
farthest_element_index = i;
max_distance = distance;
}
}
if (max_distance > douglas_peucker_thresholds[zoom_level])
{
// mark idx as necessary
input_geometry[farthest_element_index].necessary = true;
if (1 < (farthest_element_index - pair.first))
{
recursion_stack.emplace(pair.first, farthest_element_index);
}
if (1 < (pair.second - farthest_element_index))
{
recursion_stack.emplace(farthest_element_index, pair.second);
}
}
}
}
<commit_msg>fix regression in debug build<commit_after>/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <osrm/Coordinate.h>
#include "DouglasPeucker.h"
#include "../DataStructures/SegmentInformation.h"
#include "../Util/SimpleLogger.h"
#include <boost/assert.hpp>
#include <cmath>
#include <limits>
DouglasPeucker::DouglasPeucker()
: douglas_peucker_thresholds({262144., // z0
131072., // z1
65536., // z2
32768., // z3
16384., // z4
8192., // z5
4096., // z6
2048., // z7
960., // z8
480., // z9
240., // z10
90., // z11
50., // z12
25., // z13
15., // z14
5., // z15
.65, // z16
.5, // z17
.35 // z18
})
{
}
void DouglasPeucker::Run(std::vector<SegmentInformation> &input_geometry, const unsigned zoom_level)
{
input_geometry.front().necessary = true;
input_geometry.back().necessary = true;
BOOST_ASSERT_MSG(!input_geometry.empty(), "geometry invalid");
if (input_geometry.size() < 2)
{
return;
}
SimpleLogger().Write() << "input_geometry.size()=" << input_geometry.size();
{
BOOST_ASSERT_MSG(zoom_level < 19, "unsupported zoom level");
unsigned left_border = 0;
unsigned right_border = 1;
// Sweep over array and identify those ranges that need to be checked
do
{
if (!input_geometry[left_border].necessary)
{
SimpleLogger().Write() << "broken interval [" << left_border << "," << right_border << "]";
}
BOOST_ASSERT_MSG(input_geometry[left_border].necessary,
"left border must be necessary");
BOOST_ASSERT_MSG(input_geometry.back().necessary, "right border must be necessary");
if (input_geometry[right_border].necessary)
{
recursion_stack.emplace(left_border, right_border);
left_border = right_border;
}
++right_border;
} while (right_border < input_geometry.size());
}
while (!recursion_stack.empty())
{
// pop next element
const GeometryRange pair = recursion_stack.top();
recursion_stack.pop();
BOOST_ASSERT_MSG(input_geometry[pair.first].necessary, "left border mus be necessary");
BOOST_ASSERT_MSG(input_geometry[pair.second].necessary, "right border must be necessary");
BOOST_ASSERT_MSG(pair.second < input_geometry.size(), "right border outside of geometry");
BOOST_ASSERT_MSG(pair.first < pair.second, "left border on the wrong side");
double max_distance = std::numeric_limits<double>::min();
unsigned farthest_element_index = pair.second;
// find index idx of element with max_distance
for (unsigned i = pair.first + 1; i < pair.second; ++i)
{
const double temp_dist = FixedPointCoordinate::ComputePerpendicularDistance(
input_geometry[i].location,
input_geometry[pair.first].location,
input_geometry[pair.second].location);
const double distance = std::abs(temp_dist);
if (distance > douglas_peucker_thresholds[zoom_level] && distance > max_distance)
{
farthest_element_index = i;
max_distance = distance;
}
}
if (max_distance > douglas_peucker_thresholds[zoom_level])
{
// mark idx as necessary
input_geometry[farthest_element_index].necessary = true;
if (1 < (farthest_element_index - pair.first))
{
recursion_stack.emplace(pair.first, farthest_element_index);
}
if (1 < (pair.second - farthest_element_index))
{
recursion_stack.emplace(farthest_element_index, pair.second);
}
}
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <Poco/Logger.h>
#include <Poco/Message.h>
#include <Poco/File.h>
#include <Poco/Util/Option.h>
#include <Poco/Util/OptionSet.h>
#include <Poco/Util/HelpFormatter.h>
#include <Poco/Util/ServerApplication.h>
#include "server/MongooseServer.h"
#include "di/DependencyInjector.h"
#include "UIServerModule.h"
using namespace std;
using namespace Poco;
using namespace Poco::Util;
using namespace BeeeOn;
#define DEFAULT_PORT 8000
#define LOCAL_CONFIG_FILE "logging.ini"
#define SYSTEM_CONFIG_FILE "/etc/beeeon/ui-server/logging.ini"
#define LOCAL_SERVICES_FILE "services.xml"
#define SYSTEM_SERVICES_FILE "/etc/beeeon/ui-server/services.xml"
static Option optServices("services", "s",
"services configuration file to be used (xml, ini, properties)",
false,
"<file>",
true);
static Option optLogging("logging", "l",
"logging configuration file to be used (xml, ini, properties)",
false,
"<file>",
true);
static Option optPort("port", "p",
"server port to listen on",
false,
"<port>",
true);
static Option optHelp("help", "h", "print help");
class Startup : public ServerApplication {
public:
Startup():
m_printHelp(false),
m_serverPort(DEFAULT_PORT)
{
}
protected:
void handleOption(const string &name, const string &value)
{
if (name == "services")
m_userServices = value;
if (name == "logging")
m_userLogging = value;
if (name == "help")
m_printHelp = true;
if (name == "port")
m_serverPort = stoi(value);
Application::handleOption(name, value);
}
void findAndLoadLogging()
{
File user(m_userLogging);
File local(LOCAL_CONFIG_FILE);
File system(SYSTEM_CONFIG_FILE);
if (!m_userLogging.empty() && user.exists())
loadConfiguration(user.path());
if (local.exists())
loadConfiguration(local.path());
else if (system.exists())
loadConfiguration(system.path());
}
void findAndLoadServices()
{
File user(m_userServices);
File local(LOCAL_SERVICES_FILE);
File system(SYSTEM_SERVICES_FILE);
if (!m_userServices.empty() && user.exists()) {
logger().notice(
"loading configuration from " + user.path(),
__FILE__, __LINE__);
loadConfiguration(user.path());
}
else if (local.exists()) {
logger().notice(
"loading configuration from " + local.path(),
__FILE__, __LINE__);
loadConfiguration(local.path());
}
else if (system.exists()) {
logger().notice(
"loading configuration from " + system.path(),
__FILE__, __LINE__);
loadConfiguration(system.path());
}
}
void initialize(Application &app)
{
Logger::root().setLevel(Logger::parseLevel("trace"));
findAndLoadLogging();
Application::initialize(app);
findAndLoadServices();
}
void defineOptions(OptionSet &options)
{
options.addOption(optServices);
options.addOption(optLogging);
options.addOption(optPort);
options.addOption(optHelp);
Application::defineOptions(options);
}
int printHelp()
{
HelpFormatter help(options());
help.setCommand(config().getString("application.baseName"));
help.setUnixStyle(true);
help.setWidth(80);
help.setUsage("[-h] ...");
help.format(cout);
return EXIT_OK;
}
int main(const std::vector <std::string> &args)
{
if (m_printHelp)
return printHelp();
if (logger().debug())
ManifestSingleton::reportInfo(logger());
DependencyInjector injector(config().createView("services"));
UIServerModule *module = injector
.create<UIServerModule>("main");
module->createServer(m_serverPort);
module->server().start();
waitForTerminationRequest();
module->server().stop();
return EXIT_OK;
}
private:
bool m_printHelp;
unsigned int m_serverPort;
string m_userLogging;
string m_userServices;
};
int main(int argc, char **argv)
{
Startup server;
server.setUnixOptions(true);
try {
return server.run(argc, argv);
} catch(Exception &e) {
cerr << e.displayText() << endl;
} catch(exception &e) {
cerr << e.what() << endl;
} catch(const char *s) {
cerr << s << endl;
}
}
<commit_msg>ui: fix default logging config file names<commit_after>#include <iostream>
#include <Poco/Logger.h>
#include <Poco/Message.h>
#include <Poco/File.h>
#include <Poco/Util/Option.h>
#include <Poco/Util/OptionSet.h>
#include <Poco/Util/HelpFormatter.h>
#include <Poco/Util/ServerApplication.h>
#include "server/MongooseServer.h"
#include "di/DependencyInjector.h"
#include "UIServerModule.h"
using namespace std;
using namespace Poco;
using namespace Poco::Util;
using namespace BeeeOn;
#define DEFAULT_PORT 8000
#define LOCAL_LOGGING_FILE "logging.ini"
#define SYSTEM_LOGGING_FILE "/etc/beeeon/ui-server/logging.ini"
#define LOCAL_SERVICES_FILE "services.xml"
#define SYSTEM_SERVICES_FILE "/etc/beeeon/ui-server/services.xml"
static Option optServices("services", "s",
"services configuration file to be used (xml, ini, properties)",
false,
"<file>",
true);
static Option optLogging("logging", "l",
"logging configuration file to be used (xml, ini, properties)",
false,
"<file>",
true);
static Option optPort("port", "p",
"server port to listen on",
false,
"<port>",
true);
static Option optHelp("help", "h", "print help");
class Startup : public ServerApplication {
public:
Startup():
m_printHelp(false),
m_serverPort(DEFAULT_PORT)
{
}
protected:
void handleOption(const string &name, const string &value)
{
if (name == "services")
m_userServices = value;
if (name == "logging")
m_userLogging = value;
if (name == "help")
m_printHelp = true;
if (name == "port")
m_serverPort = stoi(value);
Application::handleOption(name, value);
}
void findAndLoadLogging()
{
File user(m_userLogging);
File local(LOCAL_LOGGING_FILE);
File system(SYSTEM_LOGGING_FILE);
if (!m_userLogging.empty() && user.exists())
loadConfiguration(user.path());
if (local.exists())
loadConfiguration(local.path());
else if (system.exists())
loadConfiguration(system.path());
}
void findAndLoadServices()
{
File user(m_userServices);
File local(LOCAL_SERVICES_FILE);
File system(SYSTEM_SERVICES_FILE);
if (!m_userServices.empty() && user.exists()) {
logger().notice(
"loading configuration from " + user.path(),
__FILE__, __LINE__);
loadConfiguration(user.path());
}
else if (local.exists()) {
logger().notice(
"loading configuration from " + local.path(),
__FILE__, __LINE__);
loadConfiguration(local.path());
}
else if (system.exists()) {
logger().notice(
"loading configuration from " + system.path(),
__FILE__, __LINE__);
loadConfiguration(system.path());
}
}
void initialize(Application &app)
{
Logger::root().setLevel(Logger::parseLevel("trace"));
findAndLoadLogging();
Application::initialize(app);
findAndLoadServices();
}
void defineOptions(OptionSet &options)
{
options.addOption(optServices);
options.addOption(optLogging);
options.addOption(optPort);
options.addOption(optHelp);
Application::defineOptions(options);
}
int printHelp()
{
HelpFormatter help(options());
help.setCommand(config().getString("application.baseName"));
help.setUnixStyle(true);
help.setWidth(80);
help.setUsage("[-h] ...");
help.format(cout);
return EXIT_OK;
}
int main(const std::vector <std::string> &args)
{
if (m_printHelp)
return printHelp();
if (logger().debug())
ManifestSingleton::reportInfo(logger());
DependencyInjector injector(config().createView("services"));
UIServerModule *module = injector
.create<UIServerModule>("main");
module->createServer(m_serverPort);
module->server().start();
waitForTerminationRequest();
module->server().stop();
return EXIT_OK;
}
private:
bool m_printHelp;
unsigned int m_serverPort;
string m_userLogging;
string m_userServices;
};
int main(int argc, char **argv)
{
Startup server;
server.setUnixOptions(true);
try {
return server.run(argc, argv);
} catch(Exception &e) {
cerr << e.displayText() << endl;
} catch(exception &e) {
cerr << e.what() << endl;
} catch(const char *s) {
cerr << s << endl;
}
}
<|endoftext|> |
<commit_before>//=====================================================================//
/*! @file
@brief VS1063a を使った、オーディオプレイヤー @n
・P73/SO01 (26) ---> VS1063:SI (29) @n
・P74/SI01 (25) ---> VS1063:SO (30) @n
・P75/SCK01(24) ---> VS1063:SCLK (28) @n
・P52 (35) ---> VS1063:/xCS (23) @n
・P53 (36) ---> VS1063:/xDCS (13) @n
・P54 (37) ---> VS1063:/DREQ ( 8) @n
・/RESET ( 6) ---> VS1063:/xRESET( 3)
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include <cstdint>
#include "common/port_utils.hpp"
#include "common/tau_io.hpp"
#include "common/fifo.hpp"
#include "common/uart_io.hpp"
#include "common/itimer.hpp"
#include "common/format.hpp"
#include "common/delay.hpp"
#include "common/csi_io.hpp"
#include "common/sdc_io.hpp"
#include "common/command.hpp"
#include "chip/VS1063.hpp"
namespace {
// 送信、受信バッファの定義
typedef utils::fifo<uint8_t, 32> buffer;
// UART の定義(SAU02、SAU03)
device::uart_io<device::SAU02, device::SAU03, buffer, buffer> uart_;
// インターバル・タイマー
device::itimer<uint8_t> itm_;
// SDC CSI(SPI) の定義、CSI00 の通信では、「SAU00」を利用、0ユニット、チャネル0
typedef device::csi_io<device::SAU00> csi0;
csi0 csi0_;
// FatFS インターフェースの定義
typedef device::PORT<device::port_no::P0, device::bitpos::B0> card_select; ///< カード選択信号
typedef device::PORT<device::port_no::P0, device::bitpos::B1> card_power; ///< カード電源制御
typedef device::PORT<device::port_no::P14, device::bitpos::B6> card_detect; ///< カード検出
utils::sdc_io<csi0, card_select, card_power, card_detect> sdc_(csi0_);
utils::command<64> command_;
// VS1053 SPI の定義 CSI01「SAU01」
typedef device::csi_io<device::SAU01> csi1;
csi1 csi1_;
typedef device::PORT<device::port_no::P5, device::bitpos::B2> vs1063_sel; ///< VS1063 /CS
typedef device::PORT<device::port_no::P5, device::bitpos::B3> vs1063_dcs; ///< VS1063 /DCS
typedef device::PORT<device::port_no::P5, device::bitpos::B4> vs1063_req; ///< VS1063 DREQ
chip::VS1063<csi1, vs1063_sel, vs1063_dcs, vs1063_req> vs1063_(csi1_);
}
const void* ivec_[] __attribute__ ((section (".ivec"))) = {
/* 0 */ nullptr,
/* 1 */ nullptr,
/* 2 */ nullptr,
/* 3 */ nullptr,
/* 4 */ nullptr,
/* 5 */ nullptr,
/* 6 */ nullptr,
/* 7 */ nullptr,
/* 8 */ nullptr,
/* 9 */ nullptr,
/* 10 */ nullptr,
/* 11 */ nullptr,
/* 12 */ nullptr,
/* 13 */ nullptr,
/* 14 */ nullptr,
/* 15 */ nullptr,
/* 16 */ reinterpret_cast<void*>(uart_.send_task),
/* 17 */ reinterpret_cast<void*>(uart_.recv_task),
/* 18 */ reinterpret_cast<void*>(uart_.error_task),
/* 19 */ nullptr,
/* 20 */ nullptr,
/* 21 */ nullptr,
/* 22 */ nullptr,
/* 23 */ nullptr,
/* 24 */ nullptr,
/* 25 */ nullptr,
/* 26 */ reinterpret_cast<void*>(itm_.task),
};
extern "C" {
void sci_putch(char ch)
{
uart_.putch(ch);
}
void sci_puts(const char* str)
{
uart_.puts(str);
}
char sci_getch(void)
{
return uart_.getch();
}
uint16_t sci_length()
{
return uart_.recv_length();
}
DSTATUS disk_initialize(BYTE drv) {
return sdc_.at_mmc().disk_initialize(drv);
}
DSTATUS disk_status(BYTE drv) {
return sdc_.at_mmc().disk_status(drv);
}
DRESULT disk_read(BYTE drv, BYTE* buff, DWORD sector, UINT count) {
return sdc_.at_mmc().disk_read(drv, buff, sector, count);
}
DRESULT disk_write(BYTE drv, const BYTE* buff, DWORD sector, UINT count) {
return sdc_.at_mmc().disk_write(drv, buff, sector, count);
}
DRESULT disk_ioctl(BYTE drv, BYTE ctrl, void* buff) {
return sdc_.at_mmc().disk_ioctl(drv, ctrl, buff);
}
DWORD get_fattime(void) {
return 0;
}
};
namespace {
void play_(const char* fname)
{
if(!sdc_.get_mount()) {
utils::format("SD Card unmount.\n");
return;
}
utils::format("Play: '%s'\n") % fname;
FIL fil;
if(sdc_.open(&fil, fname, FA_READ) != FR_OK) {
utils::format("Can't open input file: '%s'\n") % fname;
return;
}
vs1063_.play(&fil);
}
void play_loop_(const char*);
void play_loop_func_(const char* name, const FILINFO* fi, bool dir)
{
if(dir) {
play_loop_(name);
} else {
play_(name);
}
}
void play_loop_(const char* root)
{
sdc_.dir_loop(root, play_loop_func_);
}
}
int main(int argc, char* argv[])
{
utils::port::pullup_all(); ///< 安全の為、全ての入力をプルアップ
device::PM4.B3 = 0; // output
// インターバル・タイマー開始
{
uint8_t intr_level = 1;
itm_.start(60, intr_level);
}
// UART 開始
{
uint8_t intr_level = 1;
uart_.start(115200, intr_level);
}
// SD カード・サービス開始
sdc_.initialize();
// VS1063 初期化
{
vs1063_.start();
}
uart_.puts("Start RL78/G13 VS1053 player sample\n");
command_.set_prompt("# ");
uint8_t n = 0;
FIL fil;
char tmp[64];
while(1) {
itm_.sync();
sdc_.service();
// コマンド入力と、コマンド解析
if(command_.service()) {
auto cmdn = command_.get_words();
if(cmdn >= 1) {
if(command_.cmp_word(0, "dir")) {
if(!sdc_.get_mount()) {
utils::format("SD Card unmount.\n");
} else {
if(cmdn >= 2) {
command_.get_word(1, sizeof(tmp), tmp);
sdc_.dir(tmp);
} else {
sdc_.dir("");
}
}
} else if(command_.cmp_word(0, "cd")) { // cd [xxx]
if(cmdn >= 2) {
command_.get_word(1, sizeof(tmp), tmp);
sdc_.cd(tmp);
} else {
sdc_.cd("/");
}
} else if(command_.cmp_word(0, "pwd")) { // pwd
utils::format("%s\n") % sdc_.get_current();
} else if(command_.cmp_word(0, "play")) { // play [xxx]
if(cmdn >= 2) {
command_.get_word(1, sizeof(tmp), tmp);
if(std::strcmp(tmp, "*") == 0) {
play_loop_("");
} else {
play_(tmp);
}
} else {
play_loop_("");
}
} else {
utils::format("dir ---> directory file\n");
utils::format("play file-name ---> play file\n");
utils::format("play * ---> play file all\n");
}
}
}
++n;
if(n >= 30) n = 0;
device::P4.B3 = n < 10 ? false : true;
}
}
<commit_msg>fix file open<commit_after>//=====================================================================//
/*! @file
@brief VS1063a を使った、オーディオプレイヤー @n
・P73/SO01 (26) ---> VS1063:SI (29) @n
・P74/SI01 (25) ---> VS1063:SO (30) @n
・P75/SCK01(24) ---> VS1063:SCLK (28) @n
・P52 (35) ---> VS1063:/xCS (23) @n
・P53 (36) ---> VS1063:/xDCS (13) @n
・P54 (37) ---> VS1063:/DREQ ( 8) @n
・/RESET ( 6) ---> VS1063:/xRESET( 3)
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include <cstdint>
#include "common/port_utils.hpp"
#include "common/tau_io.hpp"
#include "common/fifo.hpp"
#include "common/uart_io.hpp"
#include "common/itimer.hpp"
#include "common/format.hpp"
#include "common/delay.hpp"
#include "common/csi_io.hpp"
#include "common/sdc_io.hpp"
#include "common/command.hpp"
#include "chip/VS1063.hpp"
namespace {
// 送信、受信バッファの定義
typedef utils::fifo<uint8_t, 32> buffer;
// UART の定義(SAU02、SAU03)
device::uart_io<device::SAU02, device::SAU03, buffer, buffer> uart_;
// インターバル・タイマー
device::itimer<uint8_t> itm_;
// SDC CSI(SPI) の定義、CSI00 の通信では、「SAU00」を利用、0ユニット、チャネル0
typedef device::csi_io<device::SAU00> csi0;
csi0 csi0_;
// FatFS インターフェースの定義
typedef device::PORT<device::port_no::P0, device::bitpos::B0> card_select; ///< カード選択信号
typedef device::PORT<device::port_no::P0, device::bitpos::B1> card_power; ///< カード電源制御
typedef device::PORT<device::port_no::P14, device::bitpos::B6> card_detect; ///< カード検出
utils::sdc_io<csi0, card_select, card_power, card_detect> sdc_(csi0_);
utils::command<64> command_;
// VS1053 SPI の定義 CSI01「SAU01」
typedef device::csi_io<device::SAU01> csi1;
csi1 csi1_;
typedef device::PORT<device::port_no::P5, device::bitpos::B2> vs1063_sel; ///< VS1063 /CS
typedef device::PORT<device::port_no::P5, device::bitpos::B3> vs1063_dcs; ///< VS1063 /DCS
typedef device::PORT<device::port_no::P5, device::bitpos::B4> vs1063_req; ///< VS1063 DREQ
chip::VS1063<csi1, vs1063_sel, vs1063_dcs, vs1063_req> vs1063_(csi1_);
}
const void* ivec_[] __attribute__ ((section (".ivec"))) = {
/* 0 */ nullptr,
/* 1 */ nullptr,
/* 2 */ nullptr,
/* 3 */ nullptr,
/* 4 */ nullptr,
/* 5 */ nullptr,
/* 6 */ nullptr,
/* 7 */ nullptr,
/* 8 */ nullptr,
/* 9 */ nullptr,
/* 10 */ nullptr,
/* 11 */ nullptr,
/* 12 */ nullptr,
/* 13 */ nullptr,
/* 14 */ nullptr,
/* 15 */ nullptr,
/* 16 */ reinterpret_cast<void*>(uart_.send_task),
/* 17 */ reinterpret_cast<void*>(uart_.recv_task),
/* 18 */ reinterpret_cast<void*>(uart_.error_task),
/* 19 */ nullptr,
/* 20 */ nullptr,
/* 21 */ nullptr,
/* 22 */ nullptr,
/* 23 */ nullptr,
/* 24 */ nullptr,
/* 25 */ nullptr,
/* 26 */ reinterpret_cast<void*>(itm_.task),
};
extern "C" {
void sci_putch(char ch)
{
uart_.putch(ch);
}
void sci_puts(const char* str)
{
uart_.puts(str);
}
char sci_getch(void)
{
return uart_.getch();
}
uint16_t sci_length()
{
return uart_.recv_length();
}
DSTATUS disk_initialize(BYTE drv) {
return sdc_.at_mmc().disk_initialize(drv);
}
DSTATUS disk_status(BYTE drv) {
return sdc_.at_mmc().disk_status(drv);
}
DRESULT disk_read(BYTE drv, BYTE* buff, DWORD sector, UINT count) {
return sdc_.at_mmc().disk_read(drv, buff, sector, count);
}
DRESULT disk_write(BYTE drv, const BYTE* buff, DWORD sector, UINT count) {
return sdc_.at_mmc().disk_write(drv, buff, sector, count);
}
DRESULT disk_ioctl(BYTE drv, BYTE ctrl, void* buff) {
return sdc_.at_mmc().disk_ioctl(drv, ctrl, buff);
}
DWORD get_fattime(void) {
return 0;
}
};
namespace {
void play_(const char* fname)
{
if(!sdc_.get_mount()) {
utils::format("SD Card unmount.\n");
return;
}
utils::format("Play: '%s'\n") % fname;
FIL fil;
if(!sdc_.open(&fil, fname, FA_READ)) {
utils::format("Can't open input file: '%s'\n") % fname;
return;
}
vs1063_.play(&fil);
}
void play_loop_(const char*);
void play_loop_func_(const char* name, const FILINFO* fi, bool dir)
{
if(dir) {
play_loop_(name);
} else {
play_(name);
}
}
void play_loop_(const char* root)
{
sdc_.dir_loop(root, play_loop_func_);
}
}
int main(int argc, char* argv[])
{
utils::port::pullup_all(); ///< 安全の為、全ての入力をプルアップ
device::PM4.B3 = 0; // output
// インターバル・タイマー開始
{
uint8_t intr_level = 1;
itm_.start(60, intr_level);
}
// UART 開始
{
uint8_t intr_level = 1;
uart_.start(115200, intr_level);
}
// SD カード・サービス開始
sdc_.initialize();
// VS1063 初期化
{
vs1063_.start();
}
uart_.puts("Start RL78/G13 VS1053 player sample\n");
command_.set_prompt("# ");
uint8_t n = 0;
FIL fil;
char tmp[64];
while(1) {
itm_.sync();
sdc_.service();
// コマンド入力と、コマンド解析
if(command_.service()) {
auto cmdn = command_.get_words();
if(cmdn >= 1) {
if(command_.cmp_word(0, "dir")) {
if(!sdc_.get_mount()) {
utils::format("SD Card unmount.\n");
} else {
if(cmdn >= 2) {
command_.get_word(1, sizeof(tmp), tmp);
sdc_.dir(tmp);
} else {
sdc_.dir("");
}
}
} else if(command_.cmp_word(0, "cd")) { // cd [xxx]
if(cmdn >= 2) {
command_.get_word(1, sizeof(tmp), tmp);
sdc_.cd(tmp);
} else {
sdc_.cd("/");
}
} else if(command_.cmp_word(0, "pwd")) { // pwd
utils::format("%s\n") % sdc_.get_current();
} else if(command_.cmp_word(0, "play")) { // play [xxx]
if(cmdn >= 2) {
command_.get_word(1, sizeof(tmp), tmp);
if(std::strcmp(tmp, "*") == 0) {
play_loop_("");
} else {
play_(tmp);
}
} else {
play_loop_("");
}
} else {
utils::format("dir ---> directory file\n");
utils::format("play file-name ---> play file\n");
utils::format("play * ---> play file all\n");
}
}
}
++n;
if(n >= 30) n = 0;
device::P4.B3 = n < 10 ? false : true;
}
}
<|endoftext|> |
<commit_before>#include "ProcessEvent.h"
#include <specialized/eventbackend.h>
#if defined(__linux__)
#include <linux/version.h>
#elif !defined(KERNEL_VERSION)
#define LINUX_VERSION_CODE 0
#define KERNEL_VERSION(a, b, c) 0
#endif
#if defined(__linux__) && LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,15) /* Linux 2.6.15+ */
// Linux
#include <linux/netlink.h>
#include <linux/connector.h>
#include <linux/cn_proc.h>
// PUT
#include <cxxutils/posix_helpers.h>
#include <cxxutils/socket_helpers.h>
#include <cxxutils/vterm.h>
#include <specialized/procstat.h>
enum {
Read = 0,
Write = 1,
};
struct message_t
{
union {
ProcessEvent::Flags action;
uint32_t : 0;
};
pid_t pid;
};
static_assert(sizeof(message_t) == sizeof(uint64_t), "unexpected struct size");
// process flags
static constexpr uint8_t from_native_flags(const native_flags_t flags) noexcept
{
return
(flags & proc_event::PROC_EVENT_EXEC ? ProcessEvent::Exec : 0) |
(flags & proc_event::PROC_EVENT_EXIT ? ProcessEvent::Exit : 0) |
(flags & proc_event::PROC_EVENT_FORK ? ProcessEvent::Fork : 0) ;
}
/*
static constexpr native_flags_t to_native_flags(const uint8_t flags) noexcept
{
return
(flags & ProcessEvent::Exec ? native_flags_t(proc_event::PROC_EVENT_EXEC) : 0) | // Process called exec*()
(flags & ProcessEvent::Exit ? native_flags_t(proc_event::PROC_EVENT_EXIT) : 0) | // Process exited
(flags & ProcessEvent::Fork ? native_flags_t(proc_event::PROC_EVENT_FORK) : 0) ; // Process forked
}
*/
struct ProcessEvent::platform_dependant // process notification (process events connector)
{
posix::fd_t fd;
struct eventinfo_t
{
posix::fd_t fd[2]; // two fds for pipe based communication
ProcessEvent::Flags_t flags;
};
std::unordered_map<pid_t, eventinfo_t> events;
platform_dependant(void) noexcept
{
fd = posix::socket(EDomain::netlink, EType::datagram, EProtocol::connector);
flaw(fd == posix::invalid_descriptor,
terminal::warning,,,
"Unable to open a netlink socket for Process Events Connector: %s", std::strerror(errno))
sockaddr_nl sa_nl;
sa_nl.nl_family = PF_NETLINK;
sa_nl.nl_groups = CN_IDX_PROC;
sa_nl.nl_pid = uint32_t(getpid());
flaw(!posix::bind(fd, reinterpret_cast<struct sockaddr *>(&sa_nl), sizeof(sa_nl)),
terminal::warning,,,
"Process Events Connector requires root level access: %s", std::strerror(errno));
#pragma pack(push, 1)
struct alignas(NLMSG_ALIGNTO) procconn_t // 32-bit alignment
{
nlmsghdr header; // 16 bytes
cn_msg message;
proc_cn_mcast_op operation;
} procconn;
#pragma pack(pop)
static_assert(sizeof(nlmsghdr) + sizeof(cn_msg) + sizeof(proc_cn_mcast_op) == sizeof(procconn_t), "compiler needs to pack struct");
std::memset(&procconn, 0, sizeof(procconn));
procconn.header.nlmsg_len = sizeof(procconn);
procconn.header.nlmsg_pid = uint32_t(getpid());
procconn.header.nlmsg_type = NLMSG_DONE;
procconn.message.id.idx = CN_IDX_PROC;
procconn.message.id.val = CN_VAL_PROC;
procconn.message.len = sizeof(proc_cn_mcast_op);
procconn.operation = PROC_CN_MCAST_LISTEN;
flaw(posix::send(fd, &procconn, sizeof(procconn)) == posix::error_response,
terminal::warning,,,
"Failed to enable Process Events Connector notifications: %s", std::strerror(errno));
EventBackend::add(fd, EventBackend::SimplePollReadFlags,
[this](posix::fd_t lambda_fd, native_flags_t) noexcept { read(lambda_fd); });
std::fprintf(stderr, "%s%s\n", terminal::information, "Process Events Connector active");
}
~platform_dependant(void) noexcept
{
EventBackend::remove(fd, EventBackend::SimplePollReadFlags);
posix::close(fd);
fd = posix::invalid_descriptor;
}
posix::fd_t add(pid_t pid, ProcessEvent::Flags_t flags) noexcept
{
eventinfo_t event;
event.flags = flags;
if(!posix::pipe(event.fd))
return posix::invalid_descriptor;
auto iter = events.emplace(pid, event);
// add filter installation code here
return event.fd[Read];
}
bool remove(pid_t pid) noexcept
{
auto iter = events.find(pid);
if(iter == events.end())
return false;
// add filter removal code here
posix::close(iter->second.fd[Read]);
posix::close(iter->second.fd[Write]);
events.erase(iter);
return true;
}
void read(posix::fd_t procfd) noexcept
{
#pragma pack(push, 1)
struct alignas(NLMSG_ALIGNTO) procmsg_t // 32-bit alignment
{
nlmsghdr header; // 16 bytes
cn_msg message;
proc_event event;
} procmsg;
#pragma pack(pop)
static_assert(sizeof(nlmsghdr) + sizeof(cn_msg) + sizeof(proc_event) == sizeof(procmsg_t), "compiler needs to pack struct");
pollfd fds = { procfd, POLLIN, 0 };
while(posix::poll(&fds, 1, 0) > 0 && // while there are messages AND
posix::recv(procfd, reinterpret_cast<void*>(&procmsg), sizeof(procmsg_t), 0) > 0) // read process event message
{
auto iter = events.find(procmsg.event.event_data.id.process_pid); // find event info for this PID
if(iter != events.end()) // if found...
posix::write(iter->second.fd[Write], &procmsg.event, sizeof(procmsg.event)); // write process event info into the communications pipe
}
}
} ProcessEvent::s_platform;
ProcessEvent::ProcessEvent(pid_t _pid, Flags_t _flags) noexcept
: m_pid(_pid), m_flags(_flags), m_fd(posix::invalid_descriptor)
{
m_fd = s_platform.add(m_pid, m_flags); // add PID to monitor and return communications pipe
EventBackend::add(m_fd, EventBackend::SimplePollReadFlags, // connect communications pipe to a lambda function
[this](posix::fd_t lambda_fd, native_flags_t) noexcept
{
proc_event data;
pollfd fds = { lambda_fd, POLLIN, 0 };
while(posix::poll(&fds, 1, 0) > 0 && // while there is another event to be read
posix::read(lambda_fd, &data, sizeof(data)) > 0) // read the event
switch(from_native_flags(data.what)) // find the type of event
{
case Flags::Exec: // queue exec signal with PID
Object::enqueue(execed,
data.event_data.exec.process_pid);
break;
case Flags::Exit: // queue exit signal with PID and exit code
if(data.event_data.exit.exit_signal) // if killed by a signal
Object::enqueue(killed,
data.event_data.exit.process_pid,
*reinterpret_cast<posix::signal::EId*>(&data.event_data.exit.exit_signal));
else // else exited by itself
Object::enqueue(exited,
data.event_data.exit.process_pid,
*reinterpret_cast<posix::error_t*>(&data.event_data.exit.exit_code));
break;
case Flags::Fork: // queue fork signal with PID and child PID
Object::enqueue(forked,
data.event_data.fork.parent_pid,
data.event_data.fork.child_pid);
break;
}
});
}
ProcessEvent::~ProcessEvent(void) noexcept
{
EventBackend::remove(m_fd, EventBackend::SimplePollReadFlags);
s_platform.remove(m_pid);
}
#elif defined(__linux__)
//&& LINUX_VERSION_CODE >= KERNEL_VERSION(X,X,X) /* Linux X.X.X+ */
# error No process event backend code exists in PDTK for Linux before version 2.6.15! Please submit a patch!
#elif defined(__darwin__) /* Darwin 7+ */ || \
defined(__FreeBSD__) /* FreeBSD 4.1+ */ || \
defined(__DragonFly__) /* DragonFly BSD */ || \
defined(__OpenBSD__) /* OpenBSD 2.9+ */ || \
defined(__NetBSD__) /* NetBSD 2+ */
#include <sys/event.h> // kqueue
static constexpr native_flags_t composite_flag(uint16_t actions, int16_t filters, uint32_t flags) noexcept
{ return native_flags_t(actions) | (native_flags_t(uint16_t(filters)) << 16) | (native_flags_t(flags) << 32); }
static constexpr bool flag_subset(native_flags_t flags, native_flags_t subset)
{ return (flags & subset) == subset; }
static constexpr native_flags_t to_native_flags(const uint8_t flags) noexcept
{
return
(flags & ProcessEvent::Exec ? composite_flag(0, EVFILT_PROC, NOTE_EXEC) : 0) |
(flags & ProcessEvent::Exit ? composite_flag(0, EVFILT_PROC, NOTE_EXIT) : 0) |
(flags & ProcessEvent::Fork ? composite_flag(0, EVFILT_PROC, NOTE_FORK) : 0) ;
}
static constexpr ushort extract_filter(native_flags_t flags) noexcept
{ return (flags >> 16) & 0xFFFF; }
template<typename rtype>
static constexpr rtype extract_flags(native_flags_t flags) noexcept
{ return flags >> 32; }
ProcessEvent::ProcessEvent(pid_t _pid, Flags_t _flags) noexcept
: m_pid(_pid), m_flags(_flags), m_fd(posix::invalid_descriptor)
{
EventBackend::add(m_pid, to_native_flags(m_flags), // connect PID event to lambda function
[this](posix::fd_t lambda_fd, native_flags_t lambda_flags) noexcept
{
switch(extract_filter(lambda_fd)) // switch by filtered event type
{
case Flags::Exec: // queue exec signal with PID
Object::enqueue_copy(execed, m_pid);
break;
case Flags::Exit: // queue exit signal with PID and exit code
Object::enqueue_copy(exited, m_pid, extract_flags<posix::error_t>(lambda_fd));
break;
case Flags::Fork: // queue fork signal with PID and child PID
Object::enqueue_copy(forked, m_pid, extract_flags<pid_t>(lambda_fd));
break;
}
});
}
ProcessEvent::~ProcessEvent(void) noexcept
{
EventBackend::remove(m_pid, to_native_flags(m_flags)); // disconnect PID with flags
}
#elif defined(__solaris__) // Solaris / OpenSolaris / OpenIndiana / illumos
# error No process event backend code exists in PDTK for Solaris / OpenSolaris / OpenIndiana / illumos! Please submit a patch!
#elif defined(__minix) // MINIX
# error No process event backend code exists in PDTK for MINIX! Please submit a patch!
#elif defined(__QNX__) // QNX
// QNX docs: http://www.qnx.com/developers/docs/7.0.0/index.html#com.qnx.doc.neutrino.devctl/topic/about.html
# error No process event backend code exists in PDTK for QNX! Please submit a patch!
#elif defined(__hpux) // HP-UX
# error No process event backend code exists in PDTK for HP-UX! Please submit a patch!
#elif defined(_AIX) // IBM AIX
# error No process event backend code exists in PDTK for IBM AIX! Please submit a patch!
#elif defined(BSD)
# error Unrecognized BSD derivative!
#elif defined(__unix__)
# error Unrecognized UNIX variant!
#else
# error This platform is not supported.
#endif
<commit_msg>use lambda_flags and change PDTK to PUT<commit_after>#include "ProcessEvent.h"
#include <specialized/eventbackend.h>
#if defined(__linux__)
#include <linux/version.h>
#elif !defined(KERNEL_VERSION)
#define LINUX_VERSION_CODE 0
#define KERNEL_VERSION(a, b, c) 0
#endif
#if defined(__linux__) && LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,15) /* Linux 2.6.15+ */
// Linux
#include <linux/netlink.h>
#include <linux/connector.h>
#include <linux/cn_proc.h>
// PUT
#include <cxxutils/posix_helpers.h>
#include <cxxutils/socket_helpers.h>
#include <cxxutils/vterm.h>
#include <specialized/procstat.h>
enum {
Read = 0,
Write = 1,
};
struct message_t
{
union {
ProcessEvent::Flags action;
uint32_t : 0;
};
pid_t pid;
};
static_assert(sizeof(message_t) == sizeof(uint64_t), "unexpected struct size");
// process flags
static constexpr uint8_t from_native_flags(const native_flags_t flags) noexcept
{
return
(flags & proc_event::PROC_EVENT_EXEC ? ProcessEvent::Exec : 0) |
(flags & proc_event::PROC_EVENT_EXIT ? ProcessEvent::Exit : 0) |
(flags & proc_event::PROC_EVENT_FORK ? ProcessEvent::Fork : 0) ;
}
/*
static constexpr native_flags_t to_native_flags(const uint8_t flags) noexcept
{
return
(flags & ProcessEvent::Exec ? native_flags_t(proc_event::PROC_EVENT_EXEC) : 0) | // Process called exec*()
(flags & ProcessEvent::Exit ? native_flags_t(proc_event::PROC_EVENT_EXIT) : 0) | // Process exited
(flags & ProcessEvent::Fork ? native_flags_t(proc_event::PROC_EVENT_FORK) : 0) ; // Process forked
}
*/
struct ProcessEvent::platform_dependant // process notification (process events connector)
{
posix::fd_t fd;
struct eventinfo_t
{
posix::fd_t fd[2]; // two fds for pipe based communication
ProcessEvent::Flags_t flags;
};
std::unordered_map<pid_t, eventinfo_t> events;
platform_dependant(void) noexcept
{
fd = posix::socket(EDomain::netlink, EType::datagram, EProtocol::connector);
flaw(fd == posix::invalid_descriptor,
terminal::warning,,,
"Unable to open a netlink socket for Process Events Connector: %s", std::strerror(errno))
sockaddr_nl sa_nl;
sa_nl.nl_family = PF_NETLINK;
sa_nl.nl_groups = CN_IDX_PROC;
sa_nl.nl_pid = uint32_t(getpid());
flaw(!posix::bind(fd, reinterpret_cast<struct sockaddr *>(&sa_nl), sizeof(sa_nl)),
terminal::warning,,,
"Process Events Connector requires root level access: %s", std::strerror(errno));
#pragma pack(push, 1)
struct alignas(NLMSG_ALIGNTO) procconn_t // 32-bit alignment
{
nlmsghdr header; // 16 bytes
cn_msg message;
proc_cn_mcast_op operation;
} procconn;
#pragma pack(pop)
static_assert(sizeof(nlmsghdr) + sizeof(cn_msg) + sizeof(proc_cn_mcast_op) == sizeof(procconn_t), "compiler needs to pack struct");
std::memset(&procconn, 0, sizeof(procconn));
procconn.header.nlmsg_len = sizeof(procconn);
procconn.header.nlmsg_pid = uint32_t(getpid());
procconn.header.nlmsg_type = NLMSG_DONE;
procconn.message.id.idx = CN_IDX_PROC;
procconn.message.id.val = CN_VAL_PROC;
procconn.message.len = sizeof(proc_cn_mcast_op);
procconn.operation = PROC_CN_MCAST_LISTEN;
flaw(posix::send(fd, &procconn, sizeof(procconn)) == posix::error_response,
terminal::warning,,,
"Failed to enable Process Events Connector notifications: %s", std::strerror(errno));
EventBackend::add(fd, EventBackend::SimplePollReadFlags,
[this](posix::fd_t lambda_fd, native_flags_t) noexcept { read(lambda_fd); });
std::fprintf(stderr, "%s%s\n", terminal::information, "Process Events Connector active");
}
~platform_dependant(void) noexcept
{
EventBackend::remove(fd, EventBackend::SimplePollReadFlags);
posix::close(fd);
fd = posix::invalid_descriptor;
}
posix::fd_t add(pid_t pid, ProcessEvent::Flags_t flags) noexcept
{
eventinfo_t event;
event.flags = flags;
if(!posix::pipe(event.fd))
return posix::invalid_descriptor;
auto iter = events.emplace(pid, event);
// add filter installation code here
return event.fd[Read];
}
bool remove(pid_t pid) noexcept
{
auto iter = events.find(pid);
if(iter == events.end())
return false;
// add filter removal code here
posix::close(iter->second.fd[Read]);
posix::close(iter->second.fd[Write]);
events.erase(iter);
return true;
}
void read(posix::fd_t procfd) noexcept
{
#pragma pack(push, 1)
struct alignas(NLMSG_ALIGNTO) procmsg_t // 32-bit alignment
{
nlmsghdr header; // 16 bytes
cn_msg message;
proc_event event;
} procmsg;
#pragma pack(pop)
static_assert(sizeof(nlmsghdr) + sizeof(cn_msg) + sizeof(proc_event) == sizeof(procmsg_t), "compiler needs to pack struct");
pollfd fds = { procfd, POLLIN, 0 };
while(posix::poll(&fds, 1, 0) > 0 && // while there are messages AND
posix::recv(procfd, reinterpret_cast<void*>(&procmsg), sizeof(procmsg_t), 0) > 0) // read process event message
{
auto iter = events.find(procmsg.event.event_data.id.process_pid); // find event info for this PID
if(iter != events.end()) // if found...
posix::write(iter->second.fd[Write], &procmsg.event, sizeof(procmsg.event)); // write process event info into the communications pipe
}
}
} ProcessEvent::s_platform;
ProcessEvent::ProcessEvent(pid_t _pid, Flags_t _flags) noexcept
: m_pid(_pid), m_flags(_flags), m_fd(posix::invalid_descriptor)
{
m_fd = s_platform.add(m_pid, m_flags); // add PID to monitor and return communications pipe
EventBackend::add(m_fd, EventBackend::SimplePollReadFlags, // connect communications pipe to a lambda function
[this](posix::fd_t lambda_fd, native_flags_t) noexcept
{
proc_event data;
pollfd fds = { lambda_fd, POLLIN, 0 };
while(posix::poll(&fds, 1, 0) > 0 && // while there is another event to be read
posix::read(lambda_fd, &data, sizeof(data)) > 0) // read the event
switch(from_native_flags(data.what)) // find the type of event
{
case Flags::Exec: // queue exec signal with PID
Object::enqueue(execed,
data.event_data.exec.process_pid);
break;
case Flags::Exit: // queue exit signal with PID and exit code
if(data.event_data.exit.exit_signal) // if killed by a signal
Object::enqueue(killed,
data.event_data.exit.process_pid,
*reinterpret_cast<posix::signal::EId*>(&data.event_data.exit.exit_signal));
else // else exited by itself
Object::enqueue(exited,
data.event_data.exit.process_pid,
*reinterpret_cast<posix::error_t*>(&data.event_data.exit.exit_code));
break;
case Flags::Fork: // queue fork signal with PID and child PID
Object::enqueue(forked,
data.event_data.fork.parent_pid,
data.event_data.fork.child_pid);
break;
}
});
}
ProcessEvent::~ProcessEvent(void) noexcept
{
EventBackend::remove(m_fd, EventBackend::SimplePollReadFlags);
s_platform.remove(m_pid);
}
#elif defined(__linux__)
//&& LINUX_VERSION_CODE >= KERNEL_VERSION(X,X,X) /* Linux X.X.X+ */
# error No process event backend code exists in PUT for Linux before version 2.6.15! Please submit a patch!
#elif defined(__darwin__) /* Darwin 7+ */ || \
defined(__FreeBSD__) /* FreeBSD 4.1+ */ || \
defined(__DragonFly__) /* DragonFly BSD */ || \
defined(__OpenBSD__) /* OpenBSD 2.9+ */ || \
defined(__NetBSD__) /* NetBSD 2+ */
#include <sys/event.h> // kqueue
static constexpr native_flags_t composite_flag(uint16_t actions, int16_t filters, uint32_t flags) noexcept
{ return native_flags_t(actions) | (native_flags_t(uint16_t(filters)) << 16) | (native_flags_t(flags) << 32); }
static constexpr bool flag_subset(native_flags_t flags, native_flags_t subset)
{ return (flags & subset) == subset; }
static constexpr native_flags_t to_native_flags(const uint8_t flags) noexcept
{
return
(flags & ProcessEvent::Exec ? composite_flag(0, EVFILT_PROC, NOTE_EXEC) : 0) |
(flags & ProcessEvent::Exit ? composite_flag(0, EVFILT_PROC, NOTE_EXIT) : 0) |
(flags & ProcessEvent::Fork ? composite_flag(0, EVFILT_PROC, NOTE_FORK) : 0) ;
}
static constexpr ushort extract_filter(native_flags_t flags) noexcept
{ return (flags >> 16) & 0xFFFF; }
template<typename rtype>
static constexpr rtype extract_flags(native_flags_t flags) noexcept
{ return flags >> 32; }
ProcessEvent::ProcessEvent(pid_t _pid, Flags_t _flags) noexcept
: m_pid(_pid), m_flags(_flags), m_fd(posix::invalid_descriptor)
{
EventBackend::add(m_pid, to_native_flags(m_flags), // connect PID event to lambda function
[this](posix::fd_t lambda_fd, native_flags_t lambda_flags) noexcept
{
switch(extract_filter(lambda_flags)) // switch by filtered event type
{
case Flags::Exec: // queue exec signal with PID
Object::enqueue_copy(execed, m_pid);
break;
case Flags::Exit: // queue exit signal with PID and exit code
Object::enqueue_copy(exited, m_pid, extract_flags<posix::error_t>(lambda_flags));
break;
case Flags::Fork: // queue fork signal with PID and child PID
Object::enqueue_copy(forked, m_pid, extract_flags<pid_t>(lambda_flags));
break;
}
});
}
ProcessEvent::~ProcessEvent(void) noexcept
{
EventBackend::remove(m_pid, to_native_flags(m_flags)); // disconnect PID with flags
}
#elif defined(__solaris__) // Solaris / OpenSolaris / OpenIndiana / illumos
# error No process event backend code exists in PUT for Solaris / OpenSolaris / OpenIndiana / illumos! Please submit a patch!
#elif defined(__minix) // MINIX
# error No process event backend code exists in PUT for MINIX! Please submit a patch!
#elif defined(__QNX__) // QNX
// QNX docs: http://www.qnx.com/developers/docs/7.0.0/index.html#com.qnx.doc.neutrino.devctl/topic/about.html
# error No process event backend code exists in PUT for QNX! Please submit a patch!
#elif defined(__hpux) // HP-UX
# error No process event backend code exists in PUT for HP-UX! Please submit a patch!
#elif defined(_AIX) // IBM AIX
# error No process event backend code exists in PUT for IBM AIX! Please submit a patch!
#elif defined(BSD)
# error Unrecognized BSD derivative!
#elif defined(__unix__)
# error Unrecognized UNIX variant!
#else
# error This platform is not supported.
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/prefs/pref_service.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/net/prediction_options.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/translate/core/common/translate_pref_names.h"
#include "content/public/browser/notification_service.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/test_extension_registry_observer.h"
#include "extensions/test/extension_test_message_listener.h"
#include "extensions/test/result_catcher.h"
namespace {
void ReleaseBrowserProcessModule() {
g_browser_process->ReleaseModule();
}
} // namespace
class ExtensionPreferenceApiTest : public ExtensionApiTest {
protected:
ExtensionPreferenceApiTest() : profile_(NULL) {}
void CheckPreferencesSet() {
PrefService* prefs = profile_->GetPrefs();
const PrefService::Preference* pref = prefs->FindPreference(
prefs::kBlockThirdPartyCookies);
ASSERT_TRUE(pref);
EXPECT_TRUE(pref->IsExtensionControlled());
EXPECT_TRUE(prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled));
EXPECT_TRUE(prefs->GetBoolean(autofill::prefs::kAutofillEnabled));
EXPECT_FALSE(prefs->GetBoolean(prefs::kBlockThirdPartyCookies));
EXPECT_TRUE(prefs->GetBoolean(prefs::kEnableHyperlinkAuditing));
EXPECT_TRUE(prefs->GetBoolean(prefs::kEnableReferrers));
EXPECT_TRUE(prefs->GetBoolean(prefs::kEnableTranslate));
EXPECT_EQ(chrome_browser_net::NETWORK_PREDICTION_DEFAULT,
prefs->GetInteger(prefs::kNetworkPredictionOptions));
EXPECT_TRUE(prefs->GetBoolean(
password_manager::prefs::kPasswordManagerSavingEnabled));
EXPECT_TRUE(prefs->GetBoolean(prefs::kSafeBrowsingEnabled));
EXPECT_TRUE(prefs->GetBoolean(prefs::kSearchSuggestEnabled));
}
void CheckPreferencesCleared() {
PrefService* prefs = profile_->GetPrefs();
const PrefService::Preference* pref = prefs->FindPreference(
prefs::kBlockThirdPartyCookies);
ASSERT_TRUE(pref);
EXPECT_FALSE(pref->IsExtensionControlled());
EXPECT_FALSE(prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled));
EXPECT_FALSE(prefs->GetBoolean(autofill::prefs::kAutofillEnabled));
EXPECT_TRUE(prefs->GetBoolean(prefs::kBlockThirdPartyCookies));
EXPECT_FALSE(prefs->GetBoolean(prefs::kEnableHyperlinkAuditing));
EXPECT_FALSE(prefs->GetBoolean(prefs::kEnableReferrers));
EXPECT_FALSE(prefs->GetBoolean(prefs::kEnableTranslate));
EXPECT_EQ(chrome_browser_net::NETWORK_PREDICTION_NEVER,
prefs->GetInteger(prefs::kNetworkPredictionOptions));
EXPECT_FALSE(prefs->GetBoolean(
password_manager::prefs::kPasswordManagerSavingEnabled));
EXPECT_FALSE(prefs->GetBoolean(prefs::kSafeBrowsingEnabled));
EXPECT_FALSE(prefs->GetBoolean(prefs::kSearchSuggestEnabled));
}
void SetUpOnMainThread() override {
ExtensionApiTest::SetUpOnMainThread();
// The browser might get closed later (and therefore be destroyed), so we
// save the profile.
profile_ = browser()->profile();
// Closing the last browser window also releases a module reference. Make
// sure it's not the last one, so the message loop doesn't quit
// unexpectedly.
g_browser_process->AddRefModule();
}
void TearDownOnMainThread() override {
// ReleaseBrowserProcessModule() needs to be called in a message loop, so we
// post a task to do it, then run the message loop.
base::MessageLoop::current()->PostTask(
FROM_HERE, base::Bind(&ReleaseBrowserProcessModule));
content::RunAllPendingInMessageLoop();
ExtensionApiTest::TearDownOnMainThread();
}
Profile* profile_;
};
// http://crbug.com/177163
#if defined(OS_WIN) && !defined(NDEBUG)
#define MAYBE_Standard DISABLED_Standard
#else
#define MAYBE_Standard Standard
#endif
IN_PROC_BROWSER_TEST_F(ExtensionPreferenceApiTest, MAYBE_Standard) {
PrefService* prefs = profile_->GetPrefs();
prefs->SetBoolean(prefs::kAlternateErrorPagesEnabled, false);
prefs->SetBoolean(autofill::prefs::kAutofillEnabled, false);
prefs->SetBoolean(prefs::kBlockThirdPartyCookies, true);
prefs->SetBoolean(prefs::kEnableHyperlinkAuditing, false);
prefs->SetBoolean(prefs::kEnableReferrers, false);
prefs->SetBoolean(prefs::kEnableTranslate, false);
prefs->SetInteger(prefs::kNetworkPredictionOptions,
chrome_browser_net::NETWORK_PREDICTION_NEVER);
prefs->SetBoolean(password_manager::prefs::kPasswordManagerSavingEnabled,
false);
prefs->SetBoolean(prefs::kSafeBrowsingEnabled, false);
prefs->SetBoolean(prefs::kSearchSuggestEnabled, false);
#if defined(ENABLE_WEBRTC)
prefs->SetBoolean(prefs::kWebRTCMultipleRoutesEnabled, false);
#endif
const char kExtensionPath[] = "preference/standard";
EXPECT_TRUE(RunExtensionSubtest(kExtensionPath, "test.html")) << message_;
CheckPreferencesSet();
// The settings should not be reset when the extension is reloaded.
ReloadExtension(last_loaded_extension_id());
CheckPreferencesSet();
// Uninstalling and installing the extension (without running the test that
// calls the extension API) should clear the settings.
extensions::TestExtensionRegistryObserver observer(
extensions::ExtensionRegistry::Get(profile_), last_loaded_extension_id());
UninstallExtension(last_loaded_extension_id());
observer.WaitForExtensionUninstalled();
CheckPreferencesCleared();
LoadExtension(test_data_dir_.AppendASCII(kExtensionPath));
CheckPreferencesCleared();
}
IN_PROC_BROWSER_TEST_F(ExtensionPreferenceApiTest, PersistentIncognito) {
PrefService* prefs = profile_->GetPrefs();
prefs->SetBoolean(prefs::kBlockThirdPartyCookies, false);
EXPECT_TRUE(
RunExtensionTestIncognito("preference/persistent_incognito")) <<
message_;
// Setting an incognito preference should not create an incognito profile.
EXPECT_FALSE(profile_->HasOffTheRecordProfile());
PrefService* otr_prefs = profile_->GetOffTheRecordProfile()->GetPrefs();
const PrefService::Preference* pref =
otr_prefs->FindPreference(prefs::kBlockThirdPartyCookies);
ASSERT_TRUE(pref);
EXPECT_TRUE(pref->IsExtensionControlled());
EXPECT_TRUE(otr_prefs->GetBoolean(prefs::kBlockThirdPartyCookies));
pref = prefs->FindPreference(prefs::kBlockThirdPartyCookies);
ASSERT_TRUE(pref);
EXPECT_FALSE(pref->IsExtensionControlled());
EXPECT_FALSE(prefs->GetBoolean(prefs::kBlockThirdPartyCookies));
}
// Flakily times out: http://crbug.com/106144
IN_PROC_BROWSER_TEST_F(ExtensionPreferenceApiTest, DISABLED_IncognitoDisabled) {
EXPECT_FALSE(RunExtensionTest("preference/persistent_incognito"));
}
IN_PROC_BROWSER_TEST_F(ExtensionPreferenceApiTest, SessionOnlyIncognito) {
PrefService* prefs = profile_->GetPrefs();
prefs->SetBoolean(prefs::kBlockThirdPartyCookies, false);
EXPECT_TRUE(
RunExtensionTestIncognito("preference/session_only_incognito")) <<
message_;
EXPECT_TRUE(profile_->HasOffTheRecordProfile());
PrefService* otr_prefs = profile_->GetOffTheRecordProfile()->GetPrefs();
const PrefService::Preference* pref =
otr_prefs->FindPreference(prefs::kBlockThirdPartyCookies);
ASSERT_TRUE(pref);
EXPECT_TRUE(pref->IsExtensionControlled());
EXPECT_FALSE(otr_prefs->GetBoolean(prefs::kBlockThirdPartyCookies));
pref = prefs->FindPreference(prefs::kBlockThirdPartyCookies);
ASSERT_TRUE(pref);
EXPECT_FALSE(pref->IsExtensionControlled());
EXPECT_FALSE(prefs->GetBoolean(prefs::kBlockThirdPartyCookies));
}
IN_PROC_BROWSER_TEST_F(ExtensionPreferenceApiTest, Clear) {
PrefService* prefs = profile_->GetPrefs();
prefs->SetBoolean(prefs::kBlockThirdPartyCookies, true);
EXPECT_TRUE(RunExtensionTest("preference/clear")) << message_;
const PrefService::Preference* pref = prefs->FindPreference(
prefs::kBlockThirdPartyCookies);
ASSERT_TRUE(pref);
EXPECT_FALSE(pref->IsExtensionControlled());
EXPECT_EQ(true, prefs->GetBoolean(prefs::kBlockThirdPartyCookies));
}
IN_PROC_BROWSER_TEST_F(ExtensionPreferenceApiTest, OnChange) {
EXPECT_TRUE(RunExtensionTestIncognito("preference/onchange")) <<
message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionPreferenceApiTest, OnChangeSplit) {
extensions::ResultCatcher catcher;
catcher.RestrictToBrowserContext(profile_);
extensions::ResultCatcher catcher_incognito;
catcher_incognito.RestrictToBrowserContext(
profile_->GetOffTheRecordProfile());
// Open an incognito window.
ui_test_utils::OpenURLOffTheRecord(profile_, GURL("chrome://newtab/"));
// changeDefault listeners.
ExtensionTestMessageListener listener1("changeDefault regular ready", true);
ExtensionTestMessageListener listener_incognito1(
"changeDefault incognito ready", true);
// changeIncognitoOnly listeners.
ExtensionTestMessageListener listener2(
"changeIncognitoOnly regular ready", true);
ExtensionTestMessageListener listener_incognito2(
"changeIncognitoOnly incognito ready", true);
ExtensionTestMessageListener listener3(
"changeIncognitoOnly regular listening", true);
ExtensionTestMessageListener listener_incognito3(
"changeIncognitoOnly incognito pref set", false);
// changeDefaultOnly listeners.
ExtensionTestMessageListener listener4(
"changeDefaultOnly regular ready", true);
ExtensionTestMessageListener listener_incognito4(
"changeDefaultOnly incognito ready", true);
ExtensionTestMessageListener listener5(
"changeDefaultOnly regular pref set", false);
ExtensionTestMessageListener listener_incognito5(
"changeDefaultOnly incognito listening", true);
// changeIncognitoOnlyBack listeners.
ExtensionTestMessageListener listener6(
"changeIncognitoOnlyBack regular ready", true);
ExtensionTestMessageListener listener_incognito6(
"changeIncognitoOnlyBack incognito ready", true);
ExtensionTestMessageListener listener7(
"changeIncognitoOnlyBack regular listening", true);
ExtensionTestMessageListener listener_incognito7(
"changeIncognitoOnlyBack incognito pref set", false);
// clearIncognito listeners.
ExtensionTestMessageListener listener8(
"clearIncognito regular ready", true);
ExtensionTestMessageListener listener_incognito8(
"clearIncognito incognito ready", true);
ExtensionTestMessageListener listener9(
"clearIncognito regular listening", true);
ExtensionTestMessageListener listener_incognito9(
"clearIncognito incognito pref cleared", false);
// clearDefault listeners.
ExtensionTestMessageListener listener10(
"clearDefault regular ready", true);
ExtensionTestMessageListener listener_incognito10(
"clearDefault incognito ready", true);
base::FilePath extension_data_dir =
test_data_dir_.AppendASCII("preference").AppendASCII("onchange_split");
ASSERT_TRUE(LoadExtensionIncognito(extension_data_dir));
// Test 1 - changeDefault
EXPECT_TRUE(listener1.WaitUntilSatisfied()); // Regular ready
EXPECT_TRUE(listener_incognito1.WaitUntilSatisfied()); // Incognito ready
listener1.Reply("ok");
listener_incognito1.Reply("ok");
// Test 2 - changeIncognitoOnly
EXPECT_TRUE(listener2.WaitUntilSatisfied()); // Regular ready
EXPECT_TRUE(listener_incognito2.WaitUntilSatisfied()); // Incognito ready
EXPECT_TRUE(listener3.WaitUntilSatisfied()); // Regular listening
listener2.Reply("ok");
listener_incognito2.Reply("ok");
// Incognito preference set -- notify the regular listener
EXPECT_TRUE(listener_incognito3.WaitUntilSatisfied());
listener3.Reply("ok");
// Test 3 - changeDefaultOnly
EXPECT_TRUE(listener4.WaitUntilSatisfied()); // Regular ready
EXPECT_TRUE(listener_incognito4.WaitUntilSatisfied()); // Incognito ready
EXPECT_TRUE(listener_incognito5.WaitUntilSatisfied()); // Incognito listening
listener4.Reply("ok");
listener_incognito4.Reply("ok");
// Regular preference set - notify the incognito listener
EXPECT_TRUE(listener5.WaitUntilSatisfied());
listener_incognito5.Reply("ok");
// Test 4 - changeIncognitoOnlyBack
EXPECT_TRUE(listener6.WaitUntilSatisfied()); // Regular ready
EXPECT_TRUE(listener_incognito6.WaitUntilSatisfied()); // Incognito ready
EXPECT_TRUE(listener7.WaitUntilSatisfied()); // Regular listening
listener6.Reply("ok");
listener_incognito6.Reply("ok");
// Incognito preference set -- notify the regular listener
EXPECT_TRUE(listener_incognito7.WaitUntilSatisfied());
listener7.Reply("ok");
// Test 5 - clearIncognito
EXPECT_TRUE(listener8.WaitUntilSatisfied()); // Regular ready
EXPECT_TRUE(listener_incognito8.WaitUntilSatisfied()); // Incognito ready
EXPECT_TRUE(listener9.WaitUntilSatisfied()); // Regular listening
listener8.Reply("ok");
listener_incognito8.Reply("ok");
// Incognito preference cleared -- notify the regular listener
EXPECT_TRUE(listener_incognito9.WaitUntilSatisfied());
listener9.Reply("ok");
// Test 6 - clearDefault
EXPECT_TRUE(listener10.WaitUntilSatisfied()); // Regular ready
EXPECT_TRUE(listener_incognito10.WaitUntilSatisfied()); // Incognito ready
listener10.Reply("ok");
listener_incognito10.Reply("ok");
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();
}
IN_PROC_BROWSER_TEST_F(ExtensionPreferenceApiTest, DataReductionProxy) {
EXPECT_TRUE(RunExtensionTest("preference/data_reduction_proxy")) <<
message_;
}
<commit_msg>Disable flaky ExtensionPreferenceApiTest.DataReductionProxy on Windows.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/prefs/pref_service.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/net/prediction_options.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/translate/core/common/translate_pref_names.h"
#include "content/public/browser/notification_service.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/test_extension_registry_observer.h"
#include "extensions/test/extension_test_message_listener.h"
#include "extensions/test/result_catcher.h"
namespace {
void ReleaseBrowserProcessModule() {
g_browser_process->ReleaseModule();
}
} // namespace
class ExtensionPreferenceApiTest : public ExtensionApiTest {
protected:
ExtensionPreferenceApiTest() : profile_(NULL) {}
void CheckPreferencesSet() {
PrefService* prefs = profile_->GetPrefs();
const PrefService::Preference* pref = prefs->FindPreference(
prefs::kBlockThirdPartyCookies);
ASSERT_TRUE(pref);
EXPECT_TRUE(pref->IsExtensionControlled());
EXPECT_TRUE(prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled));
EXPECT_TRUE(prefs->GetBoolean(autofill::prefs::kAutofillEnabled));
EXPECT_FALSE(prefs->GetBoolean(prefs::kBlockThirdPartyCookies));
EXPECT_TRUE(prefs->GetBoolean(prefs::kEnableHyperlinkAuditing));
EXPECT_TRUE(prefs->GetBoolean(prefs::kEnableReferrers));
EXPECT_TRUE(prefs->GetBoolean(prefs::kEnableTranslate));
EXPECT_EQ(chrome_browser_net::NETWORK_PREDICTION_DEFAULT,
prefs->GetInteger(prefs::kNetworkPredictionOptions));
EXPECT_TRUE(prefs->GetBoolean(
password_manager::prefs::kPasswordManagerSavingEnabled));
EXPECT_TRUE(prefs->GetBoolean(prefs::kSafeBrowsingEnabled));
EXPECT_TRUE(prefs->GetBoolean(prefs::kSearchSuggestEnabled));
}
void CheckPreferencesCleared() {
PrefService* prefs = profile_->GetPrefs();
const PrefService::Preference* pref = prefs->FindPreference(
prefs::kBlockThirdPartyCookies);
ASSERT_TRUE(pref);
EXPECT_FALSE(pref->IsExtensionControlled());
EXPECT_FALSE(prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled));
EXPECT_FALSE(prefs->GetBoolean(autofill::prefs::kAutofillEnabled));
EXPECT_TRUE(prefs->GetBoolean(prefs::kBlockThirdPartyCookies));
EXPECT_FALSE(prefs->GetBoolean(prefs::kEnableHyperlinkAuditing));
EXPECT_FALSE(prefs->GetBoolean(prefs::kEnableReferrers));
EXPECT_FALSE(prefs->GetBoolean(prefs::kEnableTranslate));
EXPECT_EQ(chrome_browser_net::NETWORK_PREDICTION_NEVER,
prefs->GetInteger(prefs::kNetworkPredictionOptions));
EXPECT_FALSE(prefs->GetBoolean(
password_manager::prefs::kPasswordManagerSavingEnabled));
EXPECT_FALSE(prefs->GetBoolean(prefs::kSafeBrowsingEnabled));
EXPECT_FALSE(prefs->GetBoolean(prefs::kSearchSuggestEnabled));
}
void SetUpOnMainThread() override {
ExtensionApiTest::SetUpOnMainThread();
// The browser might get closed later (and therefore be destroyed), so we
// save the profile.
profile_ = browser()->profile();
// Closing the last browser window also releases a module reference. Make
// sure it's not the last one, so the message loop doesn't quit
// unexpectedly.
g_browser_process->AddRefModule();
}
void TearDownOnMainThread() override {
// ReleaseBrowserProcessModule() needs to be called in a message loop, so we
// post a task to do it, then run the message loop.
base::MessageLoop::current()->PostTask(
FROM_HERE, base::Bind(&ReleaseBrowserProcessModule));
content::RunAllPendingInMessageLoop();
ExtensionApiTest::TearDownOnMainThread();
}
Profile* profile_;
};
// http://crbug.com/177163
#if defined(OS_WIN) && !defined(NDEBUG)
#define MAYBE_Standard DISABLED_Standard
#else
#define MAYBE_Standard Standard
#endif
IN_PROC_BROWSER_TEST_F(ExtensionPreferenceApiTest, MAYBE_Standard) {
PrefService* prefs = profile_->GetPrefs();
prefs->SetBoolean(prefs::kAlternateErrorPagesEnabled, false);
prefs->SetBoolean(autofill::prefs::kAutofillEnabled, false);
prefs->SetBoolean(prefs::kBlockThirdPartyCookies, true);
prefs->SetBoolean(prefs::kEnableHyperlinkAuditing, false);
prefs->SetBoolean(prefs::kEnableReferrers, false);
prefs->SetBoolean(prefs::kEnableTranslate, false);
prefs->SetInteger(prefs::kNetworkPredictionOptions,
chrome_browser_net::NETWORK_PREDICTION_NEVER);
prefs->SetBoolean(password_manager::prefs::kPasswordManagerSavingEnabled,
false);
prefs->SetBoolean(prefs::kSafeBrowsingEnabled, false);
prefs->SetBoolean(prefs::kSearchSuggestEnabled, false);
#if defined(ENABLE_WEBRTC)
prefs->SetBoolean(prefs::kWebRTCMultipleRoutesEnabled, false);
#endif
const char kExtensionPath[] = "preference/standard";
EXPECT_TRUE(RunExtensionSubtest(kExtensionPath, "test.html")) << message_;
CheckPreferencesSet();
// The settings should not be reset when the extension is reloaded.
ReloadExtension(last_loaded_extension_id());
CheckPreferencesSet();
// Uninstalling and installing the extension (without running the test that
// calls the extension API) should clear the settings.
extensions::TestExtensionRegistryObserver observer(
extensions::ExtensionRegistry::Get(profile_), last_loaded_extension_id());
UninstallExtension(last_loaded_extension_id());
observer.WaitForExtensionUninstalled();
CheckPreferencesCleared();
LoadExtension(test_data_dir_.AppendASCII(kExtensionPath));
CheckPreferencesCleared();
}
IN_PROC_BROWSER_TEST_F(ExtensionPreferenceApiTest, PersistentIncognito) {
PrefService* prefs = profile_->GetPrefs();
prefs->SetBoolean(prefs::kBlockThirdPartyCookies, false);
EXPECT_TRUE(
RunExtensionTestIncognito("preference/persistent_incognito")) <<
message_;
// Setting an incognito preference should not create an incognito profile.
EXPECT_FALSE(profile_->HasOffTheRecordProfile());
PrefService* otr_prefs = profile_->GetOffTheRecordProfile()->GetPrefs();
const PrefService::Preference* pref =
otr_prefs->FindPreference(prefs::kBlockThirdPartyCookies);
ASSERT_TRUE(pref);
EXPECT_TRUE(pref->IsExtensionControlled());
EXPECT_TRUE(otr_prefs->GetBoolean(prefs::kBlockThirdPartyCookies));
pref = prefs->FindPreference(prefs::kBlockThirdPartyCookies);
ASSERT_TRUE(pref);
EXPECT_FALSE(pref->IsExtensionControlled());
EXPECT_FALSE(prefs->GetBoolean(prefs::kBlockThirdPartyCookies));
}
// Flakily times out: http://crbug.com/106144
IN_PROC_BROWSER_TEST_F(ExtensionPreferenceApiTest, DISABLED_IncognitoDisabled) {
EXPECT_FALSE(RunExtensionTest("preference/persistent_incognito"));
}
IN_PROC_BROWSER_TEST_F(ExtensionPreferenceApiTest, SessionOnlyIncognito) {
PrefService* prefs = profile_->GetPrefs();
prefs->SetBoolean(prefs::kBlockThirdPartyCookies, false);
EXPECT_TRUE(
RunExtensionTestIncognito("preference/session_only_incognito")) <<
message_;
EXPECT_TRUE(profile_->HasOffTheRecordProfile());
PrefService* otr_prefs = profile_->GetOffTheRecordProfile()->GetPrefs();
const PrefService::Preference* pref =
otr_prefs->FindPreference(prefs::kBlockThirdPartyCookies);
ASSERT_TRUE(pref);
EXPECT_TRUE(pref->IsExtensionControlled());
EXPECT_FALSE(otr_prefs->GetBoolean(prefs::kBlockThirdPartyCookies));
pref = prefs->FindPreference(prefs::kBlockThirdPartyCookies);
ASSERT_TRUE(pref);
EXPECT_FALSE(pref->IsExtensionControlled());
EXPECT_FALSE(prefs->GetBoolean(prefs::kBlockThirdPartyCookies));
}
IN_PROC_BROWSER_TEST_F(ExtensionPreferenceApiTest, Clear) {
PrefService* prefs = profile_->GetPrefs();
prefs->SetBoolean(prefs::kBlockThirdPartyCookies, true);
EXPECT_TRUE(RunExtensionTest("preference/clear")) << message_;
const PrefService::Preference* pref = prefs->FindPreference(
prefs::kBlockThirdPartyCookies);
ASSERT_TRUE(pref);
EXPECT_FALSE(pref->IsExtensionControlled());
EXPECT_EQ(true, prefs->GetBoolean(prefs::kBlockThirdPartyCookies));
}
IN_PROC_BROWSER_TEST_F(ExtensionPreferenceApiTest, OnChange) {
EXPECT_TRUE(RunExtensionTestIncognito("preference/onchange")) <<
message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionPreferenceApiTest, OnChangeSplit) {
extensions::ResultCatcher catcher;
catcher.RestrictToBrowserContext(profile_);
extensions::ResultCatcher catcher_incognito;
catcher_incognito.RestrictToBrowserContext(
profile_->GetOffTheRecordProfile());
// Open an incognito window.
ui_test_utils::OpenURLOffTheRecord(profile_, GURL("chrome://newtab/"));
// changeDefault listeners.
ExtensionTestMessageListener listener1("changeDefault regular ready", true);
ExtensionTestMessageListener listener_incognito1(
"changeDefault incognito ready", true);
// changeIncognitoOnly listeners.
ExtensionTestMessageListener listener2(
"changeIncognitoOnly regular ready", true);
ExtensionTestMessageListener listener_incognito2(
"changeIncognitoOnly incognito ready", true);
ExtensionTestMessageListener listener3(
"changeIncognitoOnly regular listening", true);
ExtensionTestMessageListener listener_incognito3(
"changeIncognitoOnly incognito pref set", false);
// changeDefaultOnly listeners.
ExtensionTestMessageListener listener4(
"changeDefaultOnly regular ready", true);
ExtensionTestMessageListener listener_incognito4(
"changeDefaultOnly incognito ready", true);
ExtensionTestMessageListener listener5(
"changeDefaultOnly regular pref set", false);
ExtensionTestMessageListener listener_incognito5(
"changeDefaultOnly incognito listening", true);
// changeIncognitoOnlyBack listeners.
ExtensionTestMessageListener listener6(
"changeIncognitoOnlyBack regular ready", true);
ExtensionTestMessageListener listener_incognito6(
"changeIncognitoOnlyBack incognito ready", true);
ExtensionTestMessageListener listener7(
"changeIncognitoOnlyBack regular listening", true);
ExtensionTestMessageListener listener_incognito7(
"changeIncognitoOnlyBack incognito pref set", false);
// clearIncognito listeners.
ExtensionTestMessageListener listener8(
"clearIncognito regular ready", true);
ExtensionTestMessageListener listener_incognito8(
"clearIncognito incognito ready", true);
ExtensionTestMessageListener listener9(
"clearIncognito regular listening", true);
ExtensionTestMessageListener listener_incognito9(
"clearIncognito incognito pref cleared", false);
// clearDefault listeners.
ExtensionTestMessageListener listener10(
"clearDefault regular ready", true);
ExtensionTestMessageListener listener_incognito10(
"clearDefault incognito ready", true);
base::FilePath extension_data_dir =
test_data_dir_.AppendASCII("preference").AppendASCII("onchange_split");
ASSERT_TRUE(LoadExtensionIncognito(extension_data_dir));
// Test 1 - changeDefault
EXPECT_TRUE(listener1.WaitUntilSatisfied()); // Regular ready
EXPECT_TRUE(listener_incognito1.WaitUntilSatisfied()); // Incognito ready
listener1.Reply("ok");
listener_incognito1.Reply("ok");
// Test 2 - changeIncognitoOnly
EXPECT_TRUE(listener2.WaitUntilSatisfied()); // Regular ready
EXPECT_TRUE(listener_incognito2.WaitUntilSatisfied()); // Incognito ready
EXPECT_TRUE(listener3.WaitUntilSatisfied()); // Regular listening
listener2.Reply("ok");
listener_incognito2.Reply("ok");
// Incognito preference set -- notify the regular listener
EXPECT_TRUE(listener_incognito3.WaitUntilSatisfied());
listener3.Reply("ok");
// Test 3 - changeDefaultOnly
EXPECT_TRUE(listener4.WaitUntilSatisfied()); // Regular ready
EXPECT_TRUE(listener_incognito4.WaitUntilSatisfied()); // Incognito ready
EXPECT_TRUE(listener_incognito5.WaitUntilSatisfied()); // Incognito listening
listener4.Reply("ok");
listener_incognito4.Reply("ok");
// Regular preference set - notify the incognito listener
EXPECT_TRUE(listener5.WaitUntilSatisfied());
listener_incognito5.Reply("ok");
// Test 4 - changeIncognitoOnlyBack
EXPECT_TRUE(listener6.WaitUntilSatisfied()); // Regular ready
EXPECT_TRUE(listener_incognito6.WaitUntilSatisfied()); // Incognito ready
EXPECT_TRUE(listener7.WaitUntilSatisfied()); // Regular listening
listener6.Reply("ok");
listener_incognito6.Reply("ok");
// Incognito preference set -- notify the regular listener
EXPECT_TRUE(listener_incognito7.WaitUntilSatisfied());
listener7.Reply("ok");
// Test 5 - clearIncognito
EXPECT_TRUE(listener8.WaitUntilSatisfied()); // Regular ready
EXPECT_TRUE(listener_incognito8.WaitUntilSatisfied()); // Incognito ready
EXPECT_TRUE(listener9.WaitUntilSatisfied()); // Regular listening
listener8.Reply("ok");
listener_incognito8.Reply("ok");
// Incognito preference cleared -- notify the regular listener
EXPECT_TRUE(listener_incognito9.WaitUntilSatisfied());
listener9.Reply("ok");
// Test 6 - clearDefault
EXPECT_TRUE(listener10.WaitUntilSatisfied()); // Regular ready
EXPECT_TRUE(listener_incognito10.WaitUntilSatisfied()); // Incognito ready
listener10.Reply("ok");
listener_incognito10.Reply("ok");
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();
}
#if defined(OS_WIN) // http://crbug.com/477844
#define MAYBE_DataReductionProxy DISABLED_DataReductionProxy
#else
#define MAYBE_DataReductionProxy DataReductionProxy
#endif
IN_PROC_BROWSER_TEST_F(ExtensionPreferenceApiTest, MAYBE_DataReductionProxy) {
EXPECT_TRUE(RunExtensionTest("preference/data_reduction_proxy")) <<
message_;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/frame/app_non_client_frame_view_ash.h"
#include "ash/wm/workspace/frame_maximize_button.h"
#include "base/debug/stack_trace.h"
#include "chrome/browser/ui/views/frame/browser_frame.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "grit/ash_resources.h"
#include "grit/generated_resources.h" // Accessibility names
#include "grit/theme_resources.h"
#include "ui/aura/window.h"
#include "ui/base/hit_test.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/theme_provider.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/point.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/size.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/non_client_view.h"
namespace {
// The number of pixels within the shadow to draw the buttons.
const int kShadowStart = 16;
// The size and close buttons are designed to overlap.
const int kButtonOverlap = 1;
// TODO(pkotwicz): Remove these constants once the IDR_AURA_FULLSCREEN_SHADOW
// resource is updated.
const int kShadowHeightStretch = -1;
}
class AppNonClientFrameViewAsh::ControlView
: public views::View, public views::ButtonListener {
public:
explicit ControlView(AppNonClientFrameViewAsh* owner) :
owner_(owner),
close_button_(new views::ImageButton(this)),
restore_button_(new ash::FrameMaximizeButton(this, owner_))
{
close_button_->SetAccessibleName(
l10n_util::GetStringUTF16(IDS_ACCNAME_CLOSE));
restore_button_->SetAccessibleName(
l10n_util::GetStringUTF16(IDS_ACCNAME_MAXIMIZE));
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
int control_base_resource_id = owner->browser_view()->IsOffTheRecord() ?
IDR_AURA_WINDOW_HEADER_BASE_INCOGNITO_ACTIVE :
IDR_AURA_WINDOW_HEADER_BASE_ACTIVE;
control_base_ = rb.GetImageNamed(control_base_resource_id).ToImageSkia();
shadow_ = rb.GetImageNamed(IDR_AURA_WINDOW_FULLSCREEN_SHADOW).ToImageSkia();
AddChildView(close_button_);
AddChildView(restore_button_);
}
virtual ~ControlView() {}
virtual void Layout() OVERRIDE {
restore_button_->SetPosition(gfx::Point(kShadowStart, 0));
close_button_->SetPosition(gfx::Point(kShadowStart +
restore_button_->width() - kButtonOverlap, 0));
}
virtual void ViewHierarchyChanged(bool is_add, View* parent,
View* child) OVERRIDE {
if (is_add && child == this) {
SetButtonImages(restore_button_,
IDR_AURA_WINDOW_FULLSCREEN_RESTORE,
IDR_AURA_WINDOW_FULLSCREEN_RESTORE_H,
IDR_AURA_WINDOW_FULLSCREEN_RESTORE_P);
restore_button_->SizeToPreferredSize();
SetButtonImages(close_button_,
IDR_AURA_WINDOW_FULLSCREEN_CLOSE,
IDR_AURA_WINDOW_FULLSCREEN_CLOSE_H,
IDR_AURA_WINDOW_FULLSCREEN_CLOSE_P);
close_button_->SizeToPreferredSize();
}
}
virtual gfx::Size GetPreferredSize() OVERRIDE {
return gfx::Size(shadow_->width(),
shadow_->height() + kShadowHeightStretch);
}
virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {
canvas->TileImageInt(*control_base_,
restore_button_->x(),
restore_button_->y(),
restore_button_->width() - kButtonOverlap + close_button_->width(),
restore_button_->height());
views::View::OnPaint(canvas);
canvas->DrawImageInt(*shadow_, 0, kShadowHeightStretch);
}
virtual void ButtonPressed(views::Button* sender,
const ui::Event& event) OVERRIDE {
if (sender == close_button_) {
owner_->frame()->Close();
} else if (sender == restore_button_) {
restore_button_->SetState(views::CustomButton::BS_NORMAL);
owner_->frame()->Restore();
}
}
private:
// Sets images whose ids are passed in for each of the respective states
// of |button|.
void SetButtonImages(views::ImageButton* button, int normal_image_id,
int hot_image_id, int pushed_image_id) {
ui::ThemeProvider* theme_provider = GetThemeProvider();
button->SetImage(views::CustomButton::BS_NORMAL,
theme_provider->GetImageSkiaNamed(normal_image_id));
button->SetImage(views::CustomButton::BS_HOT,
theme_provider->GetImageSkiaNamed(hot_image_id));
button->SetImage(views::CustomButton::BS_PUSHED,
theme_provider->GetImageSkiaNamed(pushed_image_id));
}
AppNonClientFrameViewAsh* owner_;
views::ImageButton* close_button_;
views::ImageButton* restore_button_;
const gfx::ImageSkia* control_base_;
const gfx::ImageSkia* shadow_;
DISALLOW_COPY_AND_ASSIGN(ControlView);
};
// Observer to detect when the browser frame widget closes so we can clean
// up our ControlView. Because we can be closed via a keyboard shortcut we
// are not guaranteed to run AppNonClientFrameView's Close() or Restore().
class AppNonClientFrameViewAsh::FrameObserver : public views::WidgetObserver {
public:
explicit FrameObserver(AppNonClientFrameViewAsh* owner) : owner_(owner) {}
virtual ~FrameObserver() {}
// views::WidgetObserver:
virtual void OnWidgetClosing(views::Widget* widget) OVERRIDE {
owner_->CloseControlWidget();
}
private:
AppNonClientFrameViewAsh* owner_;
DISALLOW_COPY_AND_ASSIGN(FrameObserver);
};
// static
const char AppNonClientFrameViewAsh::kViewClassName[] =
"AppNonClientFrameViewAsh";
// static
const char AppNonClientFrameViewAsh::kControlWindowName[] =
"AppNonClientFrameViewAshControls";
AppNonClientFrameViewAsh::AppNonClientFrameViewAsh(
BrowserFrame* frame, BrowserView* browser_view)
: BrowserNonClientFrameView(frame, browser_view),
control_view_(new ControlView(this)),
control_widget_(NULL),
frame_observer_(new FrameObserver(this)) {
// This FrameView is always maximized so we don't want the window to have
// resize borders.
frame->GetNativeView()->set_hit_test_bounds_override_inner(gfx::Insets());
// Watch for frame close so we can clean up the control widget.
frame->AddObserver(frame_observer_.get());
set_background(views::Background::CreateSolidBackground(SK_ColorBLACK));
// Create the controls.
control_widget_ = new views::Widget;
views::Widget::InitParams params(views::Widget::InitParams::TYPE_CONTROL);
params.parent = browser_view->GetNativeWindow();
params.transparent = true;
control_widget_->Init(params);
control_widget_->SetContentsView(control_view_);
aura::Window* window = control_widget_->GetNativeView();
window->SetName(kControlWindowName);
gfx::Rect control_bounds = GetControlBounds();
window->SetBounds(control_bounds);
control_widget_->Show();
}
AppNonClientFrameViewAsh::~AppNonClientFrameViewAsh() {
frame()->RemoveObserver(frame_observer_.get());
// This frame view can be replaced (and deleted) if the window is restored
// via a keyboard shortcut like Alt-[. Ensure we close the control widget.
CloseControlWidget();
}
gfx::Rect AppNonClientFrameViewAsh::GetBoundsForClientView() const {
return GetLocalBounds();
}
gfx::Rect AppNonClientFrameViewAsh::GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const {
return client_bounds;
}
int AppNonClientFrameViewAsh::NonClientHitTest(
const gfx::Point& point) {
return HTNOWHERE;
}
void AppNonClientFrameViewAsh::GetWindowMask(const gfx::Size& size,
gfx::Path* window_mask) {
}
void AppNonClientFrameViewAsh::ResetWindowControls() {
}
void AppNonClientFrameViewAsh::UpdateWindowIcon() {
}
void AppNonClientFrameViewAsh::UpdateWindowTitle() {
}
gfx::Rect AppNonClientFrameViewAsh::GetBoundsForTabStrip(
views::View* tabstrip) const {
return gfx::Rect();
}
BrowserNonClientFrameView::TabStripInsets
AppNonClientFrameViewAsh::GetTabStripInsets(bool restored) const {
return TabStripInsets();
}
int AppNonClientFrameViewAsh::GetThemeBackgroundXInset() const {
return 0;
}
void AppNonClientFrameViewAsh::UpdateThrobber(bool running) {
}
std::string AppNonClientFrameViewAsh::GetClassName() const {
return kViewClassName;
}
void AppNonClientFrameViewAsh::OnBoundsChanged(
const gfx::Rect& previous_bounds) {
if (control_widget_)
control_widget_->GetNativeView()->SetBounds(GetControlBounds());
}
gfx::Rect AppNonClientFrameViewAsh::GetControlBounds() const {
if (!control_view_)
return gfx::Rect();
gfx::Size preferred = control_view_->GetPreferredSize();
return gfx::Rect(
width() - preferred.width(), 0,
preferred.width(), preferred.height());
}
void AppNonClientFrameViewAsh::CloseControlWidget() {
if (control_widget_) {
control_widget_->Close();
control_widget_ = NULL;
}
}
<commit_msg>Fixed hit area problem with full screen controls<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/frame/app_non_client_frame_view_ash.h"
#include "ash/wm/workspace/frame_maximize_button.h"
#include "base/debug/stack_trace.h"
#include "chrome/browser/ui/views/frame/browser_frame.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "grit/ash_resources.h"
#include "grit/generated_resources.h" // Accessibility names
#include "grit/theme_resources.h"
#include "ui/aura/window.h"
#include "ui/base/hit_test.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/theme_provider.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/point.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/size.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/non_client_view.h"
namespace {
// The number of pixels within the shadow to draw the buttons.
const int kShadowStart = 16;
// The size and close buttons are designed to overlap.
const int kButtonOverlap = 1;
// TODO(pkotwicz): Remove these constants once the IDR_AURA_FULLSCREEN_SHADOW
// resource is updated.
const int kShadowHeightStretch = -1;
}
class AppNonClientFrameViewAsh::ControlView
: public views::View, public views::ButtonListener {
public:
explicit ControlView(AppNonClientFrameViewAsh* owner) :
owner_(owner),
close_button_(new views::ImageButton(this)),
restore_button_(new ash::FrameMaximizeButton(this, owner_))
{
close_button_->SetAccessibleName(
l10n_util::GetStringUTF16(IDS_ACCNAME_CLOSE));
restore_button_->SetAccessibleName(
l10n_util::GetStringUTF16(IDS_ACCNAME_MAXIMIZE));
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
int control_base_resource_id = owner->browser_view()->IsOffTheRecord() ?
IDR_AURA_WINDOW_HEADER_BASE_INCOGNITO_ACTIVE :
IDR_AURA_WINDOW_HEADER_BASE_ACTIVE;
control_base_ = rb.GetImageNamed(control_base_resource_id).ToImageSkia();
shadow_ = rb.GetImageNamed(IDR_AURA_WINDOW_FULLSCREEN_SHADOW).ToImageSkia();
AddChildView(close_button_);
AddChildView(restore_button_);
}
virtual ~ControlView() {}
virtual void Layout() OVERRIDE {
restore_button_->SetPosition(gfx::Point(kShadowStart, 0));
close_button_->SetPosition(gfx::Point(kShadowStart +
restore_button_->width() - kButtonOverlap, 0));
}
virtual void ViewHierarchyChanged(bool is_add, View* parent,
View* child) OVERRIDE {
if (is_add && child == this) {
SetButtonImages(restore_button_,
IDR_AURA_WINDOW_FULLSCREEN_RESTORE,
IDR_AURA_WINDOW_FULLSCREEN_RESTORE_H,
IDR_AURA_WINDOW_FULLSCREEN_RESTORE_P);
restore_button_->SizeToPreferredSize();
SetButtonImages(close_button_,
IDR_AURA_WINDOW_FULLSCREEN_CLOSE,
IDR_AURA_WINDOW_FULLSCREEN_CLOSE_H,
IDR_AURA_WINDOW_FULLSCREEN_CLOSE_P);
close_button_->SizeToPreferredSize();
}
}
virtual gfx::Size GetPreferredSize() OVERRIDE {
return gfx::Size(shadow_->width(),
shadow_->height() + kShadowHeightStretch);
}
virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {
canvas->TileImageInt(*control_base_,
restore_button_->x(),
restore_button_->y(),
restore_button_->width() - kButtonOverlap + close_button_->width(),
restore_button_->height());
views::View::OnPaint(canvas);
canvas->DrawImageInt(*shadow_, 0, kShadowHeightStretch);
}
virtual void ButtonPressed(views::Button* sender,
const ui::Event& event) OVERRIDE {
if (sender == close_button_) {
owner_->frame()->Close();
} else if (sender == restore_button_) {
restore_button_->SetState(views::CustomButton::BS_NORMAL);
owner_->frame()->Restore();
}
}
// Returns the insets of the control which are only covered by the shadow.
gfx::Insets GetShadowInsets() {
return gfx::Insets(
0,
shadow_->width() - close_button_->width() - restore_button_->width(),
shadow_->height() - close_button_->height(),
0);
}
private:
// Sets images whose ids are passed in for each of the respective states
// of |button|.
void SetButtonImages(views::ImageButton* button, int normal_image_id,
int hot_image_id, int pushed_image_id) {
ui::ThemeProvider* theme_provider = GetThemeProvider();
button->SetImage(views::CustomButton::BS_NORMAL,
theme_provider->GetImageSkiaNamed(normal_image_id));
button->SetImage(views::CustomButton::BS_HOT,
theme_provider->GetImageSkiaNamed(hot_image_id));
button->SetImage(views::CustomButton::BS_PUSHED,
theme_provider->GetImageSkiaNamed(pushed_image_id));
}
AppNonClientFrameViewAsh* owner_;
views::ImageButton* close_button_;
views::ImageButton* restore_button_;
const gfx::ImageSkia* control_base_;
const gfx::ImageSkia* shadow_;
DISALLOW_COPY_AND_ASSIGN(ControlView);
};
// Observer to detect when the browser frame widget closes so we can clean
// up our ControlView. Because we can be closed via a keyboard shortcut we
// are not guaranteed to run AppNonClientFrameView's Close() or Restore().
class AppNonClientFrameViewAsh::FrameObserver : public views::WidgetObserver {
public:
explicit FrameObserver(AppNonClientFrameViewAsh* owner) : owner_(owner) {}
virtual ~FrameObserver() {}
// views::WidgetObserver:
virtual void OnWidgetClosing(views::Widget* widget) OVERRIDE {
owner_->CloseControlWidget();
}
private:
AppNonClientFrameViewAsh* owner_;
DISALLOW_COPY_AND_ASSIGN(FrameObserver);
};
// static
const char AppNonClientFrameViewAsh::kViewClassName[] =
"AppNonClientFrameViewAsh";
// static
const char AppNonClientFrameViewAsh::kControlWindowName[] =
"AppNonClientFrameViewAshControls";
AppNonClientFrameViewAsh::AppNonClientFrameViewAsh(
BrowserFrame* frame, BrowserView* browser_view)
: BrowserNonClientFrameView(frame, browser_view),
control_view_(new ControlView(this)),
control_widget_(NULL),
frame_observer_(new FrameObserver(this)) {
// This FrameView is always maximized so we don't want the window to have
// resize borders.
frame->GetNativeView()->set_hit_test_bounds_override_inner(gfx::Insets());
// Watch for frame close so we can clean up the control widget.
frame->AddObserver(frame_observer_.get());
set_background(views::Background::CreateSolidBackground(SK_ColorBLACK));
// Create the controls.
control_widget_ = new views::Widget;
views::Widget::InitParams params(views::Widget::InitParams::TYPE_CONTROL);
params.parent = browser_view->GetNativeWindow();
params.transparent = true;
control_widget_->Init(params);
control_widget_->SetContentsView(control_view_);
aura::Window* window = control_widget_->GetNativeView();
window->SetName(kControlWindowName);
// Need to exclude the shadow from the active control area.
window->SetHitTestBoundsOverrideOuter(control_view_->GetShadowInsets(), 1);
gfx::Rect control_bounds = GetControlBounds();
window->SetBounds(control_bounds);
control_widget_->Show();
}
AppNonClientFrameViewAsh::~AppNonClientFrameViewAsh() {
frame()->RemoveObserver(frame_observer_.get());
// This frame view can be replaced (and deleted) if the window is restored
// via a keyboard shortcut like Alt-[. Ensure we close the control widget.
CloseControlWidget();
}
gfx::Rect AppNonClientFrameViewAsh::GetBoundsForClientView() const {
return GetLocalBounds();
}
gfx::Rect AppNonClientFrameViewAsh::GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const {
return client_bounds;
}
int AppNonClientFrameViewAsh::NonClientHitTest(
const gfx::Point& point) {
return HTNOWHERE;
}
void AppNonClientFrameViewAsh::GetWindowMask(const gfx::Size& size,
gfx::Path* window_mask) {
}
void AppNonClientFrameViewAsh::ResetWindowControls() {
}
void AppNonClientFrameViewAsh::UpdateWindowIcon() {
}
void AppNonClientFrameViewAsh::UpdateWindowTitle() {
}
gfx::Rect AppNonClientFrameViewAsh::GetBoundsForTabStrip(
views::View* tabstrip) const {
return gfx::Rect();
}
BrowserNonClientFrameView::TabStripInsets
AppNonClientFrameViewAsh::GetTabStripInsets(bool restored) const {
return TabStripInsets();
}
int AppNonClientFrameViewAsh::GetThemeBackgroundXInset() const {
return 0;
}
void AppNonClientFrameViewAsh::UpdateThrobber(bool running) {
}
std::string AppNonClientFrameViewAsh::GetClassName() const {
return kViewClassName;
}
void AppNonClientFrameViewAsh::OnBoundsChanged(
const gfx::Rect& previous_bounds) {
if (control_widget_)
control_widget_->GetNativeView()->SetBounds(GetControlBounds());
}
gfx::Rect AppNonClientFrameViewAsh::GetControlBounds() const {
if (!control_view_)
return gfx::Rect();
gfx::Size preferred = control_view_->GetPreferredSize();
return gfx::Rect(
width() - preferred.width(), 0,
preferred.width(), preferred.height());
}
void AppNonClientFrameViewAsh::CloseControlWidget() {
if (control_widget_) {
control_widget_->Close();
control_widget_ = NULL;
}
}
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2017 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 "Importer.h"
#include "common/sg/SceneGraph.h"
#include <memory>
/*! \file sg/module/Importer.cpp Defines the interface for writing
file importers for the ospray::sg */
namespace ospray {
namespace sg {
struct ColorMap
{
ColorMap(float lo, float hi)
: lo(lo), hi(hi)
{
assert(lo <= hi);
// TODO: need a better color map here ...
color.push_back(vec3f(0.f,0.f,0.f));
color.push_back(vec3f(0.f,0.f,1.f));
color.push_back(vec3f(0.f,1.f,0.f));
color.push_back(vec3f(1.f,0.f,0.f));
color.push_back(vec3f(1.f,1.f,0.f));
color.push_back(vec3f(0.f,1.f,1.f));
color.push_back(vec3f(1.f,0.f,1.f));
color.push_back(vec3f(1.f,1.f,1.f));
};
vec4f colorFor(float f)
{
if (f <= lo) return vec4f(color.front(),1.f);
if (f >= hi) return vec4f(color.back(),1.f);
float r = ((f-lo) * color.size()) / (hi-lo);
int idx = int(r);
if (idx < 0) idx = 0;
if (idx >= color.size()) idx = color.size()-1;
vec3f c = color[idx] + (r-idx)*(color[idx+1]-color[idx]);
return vec4f(c,1.f);
}
float lo, hi;
std::vector<vec3f> color;
};
bool readOne(FILE *file, float *f, int N, bool ascii)
{
if (!ascii)
return fread(f,sizeof(float),N,file) == N;
// ascii:
for (int i=0;i<N;i++) {
int rc = fscanf(file,"%f",f+i);
if (rc == 0) return (i == 0);
fscanf(file,"\n");
}
return true;
}
// for now, let's hardcode the importers - should be moved to a
// registry at some point ...
void importFileType_points(std::shared_ptr<World> &world,
const FileName &url)
{
std::cout << "--------------------------------------------" << std::endl;
std::cout << "#osp.sg: importer for 'points': " << url.str() << std::endl;
FormatURL fu(url.str());
PRINT(fu.fileName);
// const std::string portHeader = strstr(url.str().c_str(),"://")+3;
// const char *fileName = strstr(url.str().c_str(),"://")+3;
PRINT(fu.fileName);
FILE *file = fopen(fu.fileName.c_str(),"rb");
if (!file)
throw std::runtime_error("could not open file "+fu.fileName);
// read the data vector
PING;
std::shared_ptr<DataVectorT<Spheres::Sphere,OSP_RAW>> sphereData
= std::make_shared<DataVectorT<Spheres::Sphere,OSP_RAW>>();
float radius = .1f;
if (fu.hasArg("radius"))
radius = std::stof(fu["radius"]);
if (radius == 0.f)
throw std::runtime_error("#sg.importPoints: could not parse radius ...");
std::string format = "xyz";
if (fu.hasArg("format"))
format = fu["format"];
bool ascii = fu.hasArg("ascii");
/* for now, hard-coded sphere componetns to be in float format,
so the number of chars in the format string is the num components */
int numFloatsPerSphere = format.size();
size_t xPos = format.find("x");
size_t yPos = format.find("y");
size_t zPos = format.find("z");
size_t rPos = format.find("r");
size_t sPos = format.find("s");
if (xPos == std::string::npos)
throw std::runtime_error("invalid points format: no x component");
if (yPos == std::string::npos)
throw std::runtime_error("invalid points format: no y component");
if (zPos == std::string::npos)
throw std::runtime_error("invalid points format: no z component");
float f[numFloatsPerSphere];
box3f bounds;
std::vector<float> mappedScalarVector;
float mappedScalarMin = +std::numeric_limits<float>::infinity();
float mappedScalarMax = -std::numeric_limits<float>::infinity();
while (readOne(file,f,numFloatsPerSphere,ascii)) {
// read one more sphere ....
Spheres::Sphere s;
s.position.x = f[xPos];
s.position.y = f[yPos];
s.position.z = f[zPos];
s.radius
= (rPos == std::string::npos)
? radius
: f[rPos];
sphereData->v.push_back(s);
bounds.extend(s.position-s.radius);
bounds.extend(s.position+s.radius);
if (sPos != std::string::npos) {
mappedScalarVector.push_back(f[sPos]);
mappedScalarMin = std::min(mappedScalarMin,f[sPos]);
mappedScalarMax = std::max(mappedScalarMax,f[sPos]);
}
}
fclose(file);
// create the node
NodeHandle sphereObject = createNode("spheres","Spheres");
// iw - note that 'add' sounds wrong here, but that's the way
// the current scene graph works - 'adding' that node (which
// happens to have the right name) will essentially replace the
// old value of that node, and thereby assign the 'data' field
sphereData->setName("sphereData");
sphereObject->add(sphereData); //["data"]->setValue(data);
if (!mappedScalarVector.empty()) {
std::cout << "#osp.sg: creating color map for points data ..." << std::endl;
ColorMap cm(mappedScalarMin,mappedScalarMax);
std::shared_ptr<DataVectorT<vec4f,OSP_RAW>> colorData
= std::make_shared<DataVectorT<vec4f,OSP_RAW>>();
for (int i=0;i<mappedScalarVector.size();i++)
colorData->v.push_back(cm.colorFor(mappedScalarVector[i]));
colorData->setName("colorData");
sphereObject->add(colorData);
}
std::cout << "#osp.sg: imported " << prettyNumber(sphereData->v.size())
<< " points, bounds = " << bounds << std::endl;;
NodeHandle(world) += sphereObject;
}
}// ::ospray::sg
}// ::ospray
<commit_msg>- bugfix in color map code - better 'cool to warm' color map<commit_after>// ======================================================================== //
// Copyright 2009-2017 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 "Importer.h"
#include "common/sg/SceneGraph.h"
#include <memory>
/*! \file sg/module/Importer.cpp Defines the interface for writing
file importers for the ospray::sg */
namespace ospray {
namespace sg {
struct ColorMap
{
ColorMap(float lo, float hi)
: lo(lo), hi(hi)
{
assert(lo <= hi);
// TODO: need a better color map here ...
// color.push_back(vec3f(0.f,0.f,0.f));
// color.push_back(vec3f(0.f,0.f,1.f));
// color.push_back(vec3f(0.f,1.f,0.f));
// color.push_back(vec3f(1.f,0.f,0.f));
// color.push_back(vec3f(1.f,1.f,0.f));
// color.push_back(vec3f(0.f,1.f,1.f));
// color.push_back(vec3f(1.f,0.f,1.f));
// color.push_back(vec3f(1.f,1.f,1.f));
// from old qtivewre: "cool to warm"
color.push_back(ospcommon::vec3f(0.231373 , 0.298039 , 0.752941 ));
color.push_back(ospcommon::vec3f(0.865003 , 0.865003 , 0.865003 ));
color.push_back(ospcommon::vec3f(0.705882 , 0.0156863 , 0.14902 ));
};
vec4f colorFor(float f)
{
if (f <= lo) return vec4f(color.front(),1.f);
if (f >= hi) return vec4f(color.back(),1.f);
float r = ((f-lo) * (color.size()-1)) / (hi-lo);
int idx = int(r);
if (idx < 0) idx = 0;
if (idx >= color.size()) idx = color.size()-2;
vec3f c = color[idx] + (r-idx)*(color[idx+1]-color[idx]);
return vec4f(c,1.f);
}
float lo, hi;
std::vector<vec3f> color;
};
bool readOne(FILE *file, float *f, int N, bool ascii)
{
if (!ascii)
return fread(f,sizeof(float),N,file) == N;
// ascii:
for (int i=0;i<N;i++) {
int rc = fscanf(file,"%f",f+i);
if (rc == 0) return (i == 0);
fscanf(file,"\n");
}
return true;
}
// for now, let's hardcode the importers - should be moved to a
// registry at some point ...
void importFileType_points(std::shared_ptr<World> &world,
const FileName &url)
{
std::cout << "--------------------------------------------" << std::endl;
std::cout << "#osp.sg: importer for 'points': " << url.str() << std::endl;
FormatURL fu(url.str());
PRINT(fu.fileName);
// const std::string portHeader = strstr(url.str().c_str(),"://")+3;
// const char *fileName = strstr(url.str().c_str(),"://")+3;
PRINT(fu.fileName);
FILE *file = fopen(fu.fileName.c_str(),"rb");
if (!file)
throw std::runtime_error("could not open file "+fu.fileName);
// read the data vector
PING;
std::shared_ptr<DataVectorT<Spheres::Sphere,OSP_RAW>> sphereData
= std::make_shared<DataVectorT<Spheres::Sphere,OSP_RAW>>();
float radius = .1f;
if (fu.hasArg("radius"))
radius = std::stof(fu["radius"]);
if (radius == 0.f)
throw std::runtime_error("#sg.importPoints: could not parse radius ...");
std::string format = "xyz";
if (fu.hasArg("format"))
format = fu["format"];
bool ascii = fu.hasArg("ascii");
/* for now, hard-coded sphere componetns to be in float format,
so the number of chars in the format string is the num components */
int numFloatsPerSphere = format.size();
size_t xPos = format.find("x");
size_t yPos = format.find("y");
size_t zPos = format.find("z");
size_t rPos = format.find("r");
size_t sPos = format.find("s");
if (xPos == std::string::npos)
throw std::runtime_error("invalid points format: no x component");
if (yPos == std::string::npos)
throw std::runtime_error("invalid points format: no y component");
if (zPos == std::string::npos)
throw std::runtime_error("invalid points format: no z component");
float f[numFloatsPerSphere];
box3f bounds;
std::vector<float> mappedScalarVector;
float mappedScalarMin = +std::numeric_limits<float>::infinity();
float mappedScalarMax = -std::numeric_limits<float>::infinity();
while (readOne(file,f,numFloatsPerSphere,ascii)) {
// read one more sphere ....
Spheres::Sphere s;
s.position.x = f[xPos];
s.position.y = f[yPos];
s.position.z = f[zPos];
s.radius
= (rPos == std::string::npos)
? radius
: f[rPos];
sphereData->v.push_back(s);
bounds.extend(s.position-s.radius);
bounds.extend(s.position+s.radius);
if (sPos != std::string::npos) {
mappedScalarVector.push_back(f[sPos]);
mappedScalarMin = std::min(mappedScalarMin,f[sPos]);
mappedScalarMax = std::max(mappedScalarMax,f[sPos]);
}
}
fclose(file);
// create the node
NodeHandle sphereObject = createNode("spheres","Spheres");
// iw - note that 'add' sounds wrong here, but that's the way
// the current scene graph works - 'adding' that node (which
// happens to have the right name) will essentially replace the
// old value of that node, and thereby assign the 'data' field
sphereData->setName("sphereData");
sphereObject->add(sphereData); //["data"]->setValue(data);
if (!mappedScalarVector.empty()) {
std::cout << "#osp.sg: creating color map for points data ..." << std::endl;
ColorMap cm(mappedScalarMin,mappedScalarMax);
std::shared_ptr<DataVectorT<vec4f,OSP_RAW>> colorData
= std::make_shared<DataVectorT<vec4f,OSP_RAW>>();
for (int i=0;i<mappedScalarVector.size();i++)
colorData->v.push_back(cm.colorFor(mappedScalarVector[i]));
colorData->setName("colorData");
sphereObject->add(colorData);
}
std::cout << "#osp.sg: imported " << prettyNumber(sphereData->v.size())
<< " points, bounds = " << bounds << std::endl;;
NodeHandle(world) += sphereObject;
}
}// ::ospray::sg
}// ::ospray
<|endoftext|> |
<commit_before>/*
* Copyright 2019,
* Olivier Stasse,
*
* CNRS/AIST
*
*/
#include <iostream>
#include <sot/core/debug.hh>
#ifndef WIN32
#include <unistd.h>
#endif
using namespace std;
#include <boost/test/unit_test.hpp>
#include <dynamic-graph/entity.h>
#include <dynamic-graph/factory.h>
#include <sot/core/device.hh>
#include <sstream>
using namespace dynamicgraph;
using namespace dynamicgraph::sot;
class TestDevice : public dg::sot::Device {
public:
TestDevice(const std::string &RobotName) : Device(RobotName) {
timestep_ = 0.001;
}
~TestDevice() {}
};
BOOST_AUTO_TEST_CASE(test_device) {
TestDevice aDevice(std::string("simple_humanoid"));
/// Fix constant vector for the control entry in position
dg::Vector aStateVector(38);
dg::Vector aVelocityVector(38);
dg::Vector aLowerVelBound(38), anUpperVelBound(38);
dg::Vector aLowerBound(38), anUpperBound(38);
dg::Vector anAccelerationVector(38);
dg::Vector aControlVector(38);
for (unsigned int i = 0; i < 38; i++) {
// Specify lower velocity bound
aLowerVelBound[i] = -3.14;
// Specify lower position bound
aLowerBound[i]=-3.14;
// Specify state vector
aStateVector[i] = 0.1;
// Specify upper velocity bound
anUpperVelBound[i] = 3.14;
// Specify upper position bound
anUpperBound[i]=3.14;
// Specify control vector
aControlVector(i)= 0.1;
}
/// Specify state size
aDevice.setStateSize(38);
/// Specify state bounds
aDevice.setPositionBounds(aLowerBound,anUpperBound);
/// Specify velocity size
aDevice.setVelocitySize(38);
/// Specify velocity
aDevice.setVelocity(aStateVector);
/// Specify velocity bounds
aDevice.setVelocityBounds(aLowerVelBound, anUpperVelBound);
/// Specify current state value
aDevice.setState(aStateVector); // entry signal in position
/// Specify constant control value
aDevice.controlSIN.setConstant(aControlVector);
for (unsigned int i = 0; i < 2000; i++) {
double dt=0.001;
aDevice.increment(dt);
if (i == 0)
{
aDevice.stateSOUT.get(std::cout);
std::ostringstream anoss;
aDevice.stateSOUT.get(anoss);
for (unsigned int i = 0; i < 38; i++)
aControlVector[i]= 0.5;
}
if (i == 1)
{
aDevice.stateSOUT.get(std::cout);
std::ostringstream anoss;
aDevice.stateSOUT.get(anoss);
}
}
aDevice.display(std::cout);
aDevice.cmdDisplay();
}
<commit_msg>[unitTesting] Improve test_device<commit_after>/*
* Copyright 2019,
* Olivier Stasse,
*
* CNRS/AIST
*
*/
#include <pinocchio/multibody/liegroup/special-euclidean.hpp>
#include <iostream>
#include <sot/core/debug.hh>
#ifndef WIN32
#include <unistd.h>
#endif
using namespace std;
#include <boost/test/unit_test.hpp>
#include <dynamic-graph/entity.h>
#include <dynamic-graph/factory.h>
#include <sot/core/device.hh>
#include <sstream>
using namespace dynamicgraph;
using namespace dynamicgraph::sot;
class TestDevice : public dg::sot::Device {
public:
TestDevice(const std::string &RobotName) : Device(RobotName) {
timestep_ = 0.001;
}
~TestDevice() {}
};
BOOST_AUTO_TEST_CASE(test_device) {
TestDevice aDevice(std::string("simple_humanoid"));
/// Fix constant vector for the control entry in position
dg::Vector aStateVector(38);
dg::Vector aVelocityVector(38);
dg::Vector aLowerVelBound(38), anUpperVelBound(38);
dg::Vector aLowerBound(38), anUpperBound(38);
dg::Vector anAccelerationVector(38);
dg::Vector aControlVector(38);
for (unsigned int i = 0; i < 38; i++) {
// Specify lower velocity bound
aLowerVelBound[i] = -3.14;
// Specify lower position bound
aLowerBound[i]=-3.14;
// Specify state vector
aStateVector[i] = 0.1;
// Specify upper velocity bound
anUpperVelBound[i] = 3.14;
// Specify upper position bound
anUpperBound[i]=3.14;
// Specify control vector
aControlVector(i)= 0.1;
}
dg::Vector expected = aStateVector; // backup initial state vector
/// Specify state size
aDevice.setStateSize(38);
/// Specify state bounds
aDevice.setPositionBounds(aLowerBound,anUpperBound);
/// Specify velocity size
aDevice.setVelocitySize(38);
/// Specify velocity
aDevice.setVelocity(aStateVector);
/// Specify velocity bounds
aDevice.setVelocityBounds(aLowerVelBound, anUpperVelBound);
/// Specify current state value
aDevice.setState(aStateVector); // entry signal in position
/// Specify constant control value
aDevice.controlSIN.setConstant(aControlVector);
const double dt = 0.001;
const unsigned int N = 2000;
for (unsigned int i = 0; i < N; i++) {
aDevice.increment(dt);
if (i == 0)
{
aDevice.stateSOUT.get(std::cout);
std::ostringstream anoss;
aDevice.stateSOUT.get(anoss);
}
if (i == 1)
{
aDevice.stateSOUT.get(std::cout);
std::ostringstream anoss;
aDevice.stateSOUT.get(anoss);
}
}
aDevice.display(std::cout);
aDevice.cmdDisplay();
// verify correct integration
typedef pinocchio::SpecialEuclideanOperationTpl<3, double> SE3;
Eigen::Matrix<double, 7, 1> qin, qout;
qin.head<3>() = expected.head<3>();
Eigen::QuaternionMapd quat (qin.tail<4>().data());
quat = Eigen::AngleAxisd(expected(5), Eigen::Vector3d::UnitZ())
* Eigen::AngleAxisd(expected(4), Eigen::Vector3d::UnitY())
* Eigen::AngleAxisd(expected(3), Eigen::Vector3d::UnitX());
const double T = dt*N;
Eigen::Matrix<double, 6, 1> control = aControlVector.head<6>()*T;
SE3().integrate (qin, control, qout);
// Manual integration
expected.head<3>() = qout.head<3>();
expected.segment<3>(3) = Eigen::QuaternionMapd(qout.tail<4>().data()).toRotationMatrix().eulerAngles(2,1,0).reverse();
for(int i=6; i<expected.size(); i++)
expected[i] = 0.3;
std::cout << expected.transpose() << std::endl;
std::cout << aDevice.stateSOUT(N).transpose() << std::endl;
BOOST_CHECK(aDevice.stateSOUT(N).isApprox(expected));
}
<|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "AvatarModule.h"
#include "AvatarEditing/AvatarEditor.h"
#include "InputAPI.h"
#include "Scene.h"
#include "SceneAPI.h"
#include "AssetAPI.h"
#include "GenericAssetFactory.h"
#include "NullAssetFactory.h"
#include "AvatarDescAsset.h"
#include "ConsoleAPI.h"
#include "IComponentFactory.h"
#include "EntityComponent/EC_Avatar.h"
namespace Avatar
{
AvatarModule::AvatarModule()
:IModule("Avatar")
{
}
AvatarModule::~AvatarModule()
{
}
void AvatarModule::Load()
{
framework_->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_Avatar>));
///\todo This doesn't need to be loaded in headless server mode.
// Note: need to register in Initialize(), because in PostInitialize() AssetModule refreshes the local asset storages, and that
// would result in inability to create any avatar assets in unloaded state
if (!framework_->IsHeadless())
framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<AvatarDescAsset>("Avatar")));
else
framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new NullAssetFactory("Avatar")));
}
void AvatarModule::Initialize()
{
avatar_editor_ = AvatarEditorPtr(new AvatarEditor(this));
}
void AvatarModule::PostInitialize()
{
avatar_context_ = GetFramework()->Input()->RegisterInputContext("Avatar", 100);
if (avatar_context_)
{
connect(avatar_context_.get(), SIGNAL(KeyPressed(KeyEvent*)), SLOT(KeyPressed(KeyEvent*)));
connect(avatar_context_.get(), SIGNAL(KeyReleased(KeyEvent*)), SLOT(KeyReleased(KeyEvent*)));
}
framework_->Console()->RegisterCommand("editavatar",
"Edits the avatar in a specific entity. Usage: editavatar(entityname)",
this, SLOT(EditAvatar(const QString &)));
}
void AvatarModule::Uninitialize()
{
avatar_handler_.reset();
avatar_controllable_.reset();
avatar_editor_.reset();
}
void AvatarModule::Update(f64 frametime)
{
}
void AvatarModule::KeyPressed(KeyEvent *key)
{
}
void AvatarModule::KeyReleased(KeyEvent *key)
{
}
void AvatarModule::EditAvatar(const QString &entityName)
{
ScenePtr scene = framework_->Scene()->GetDefaultScene();
if (!scene)
return;// ConsoleResultFailure("No scene");
EntityPtr entity = scene->GetEntityByName(entityName);
if (!entity)
return;// ConsoleResultFailure("No such entity " + entityName.toStdString());
/// \todo Clone the avatar asset for editing
/// \todo Allow avatar asset editing without an avatar entity in the scene
avatar_editor_->SetEntityToEdit(entity);
if (avatar_editor_)
avatar_editor_->show();
}
}
extern "C"
{
__declspec(dllexport) void TundraPluginMain(Framework *fw)
{
Framework::SetInstance(fw); // Inside this DLL, remember the pointer to the global framework object.
IModule *module = new Avatar::AvatarModule();
fw->RegisterModule(module);
}
}
<commit_msg>Fixed previous avatarmodule refactors to build properly.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "AvatarModule.h"
#include "AvatarEditor.h"
#include "InputAPI.h"
#include "Scene.h"
#include "SceneAPI.h"
#include "AssetAPI.h"
#include "GenericAssetFactory.h"
#include "NullAssetFactory.h"
#include "AvatarDescAsset.h"
#include "ConsoleAPI.h"
#include "IComponentFactory.h"
#include "EC_Avatar.h"
namespace Avatar
{
AvatarModule::AvatarModule()
:IModule("Avatar")
{
}
AvatarModule::~AvatarModule()
{
}
void AvatarModule::Load()
{
framework_->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_Avatar>));
///\todo This doesn't need to be loaded in headless server mode.
// Note: need to register in Initialize(), because in PostInitialize() AssetModule refreshes the local asset storages, and that
// would result in inability to create any avatar assets in unloaded state
if (!framework_->IsHeadless())
framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<AvatarDescAsset>("Avatar")));
else
framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new NullAssetFactory("Avatar")));
}
void AvatarModule::Initialize()
{
avatar_editor_ = AvatarEditorPtr(new AvatarEditor(this));
}
void AvatarModule::PostInitialize()
{
avatar_context_ = GetFramework()->Input()->RegisterInputContext("Avatar", 100);
if (avatar_context_)
{
connect(avatar_context_.get(), SIGNAL(KeyPressed(KeyEvent*)), SLOT(KeyPressed(KeyEvent*)));
connect(avatar_context_.get(), SIGNAL(KeyReleased(KeyEvent*)), SLOT(KeyReleased(KeyEvent*)));
}
framework_->Console()->RegisterCommand("editavatar",
"Edits the avatar in a specific entity. Usage: editavatar(entityname)",
this, SLOT(EditAvatar(const QString &)));
}
void AvatarModule::Uninitialize()
{
avatar_handler_.reset();
avatar_controllable_.reset();
avatar_editor_.reset();
}
void AvatarModule::Update(f64 frametime)
{
}
void AvatarModule::KeyPressed(KeyEvent *key)
{
}
void AvatarModule::KeyReleased(KeyEvent *key)
{
}
void AvatarModule::EditAvatar(const QString &entityName)
{
ScenePtr scene = framework_->Scene()->GetDefaultScene();
if (!scene)
return;// ConsoleResultFailure("No scene");
EntityPtr entity = scene->GetEntityByName(entityName);
if (!entity)
return;// ConsoleResultFailure("No such entity " + entityName.toStdString());
/// \todo Clone the avatar asset for editing
/// \todo Allow avatar asset editing without an avatar entity in the scene
avatar_editor_->SetEntityToEdit(entity);
if (avatar_editor_)
avatar_editor_->show();
}
}
extern "C"
{
__declspec(dllexport) void TundraPluginMain(Framework *fw)
{
Framework::SetInstance(fw); // Inside this DLL, remember the pointer to the global framework object.
IModule *module = new Avatar::AvatarModule();
fw->RegisterModule(module);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2018 Universidad Carlos III de Madrid
*
* 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 <atomic>
#include <gtest/gtest.h>
#include <iostream>
#include "mapreduce.h"
#include "dyn/dynamic_execution.h"
#include "supported_executions.h"
using namespace std;
using namespace grppi;
template <typename T>
class map_reduce_test : public ::testing::Test {
public:
T execution_{};
dynamic_execution dyn_execution_{execution_};
// Variables
int output{};
// Vectors
vector<int> v{};
vector<int> v2{};
// Invocation counter
std::atomic<int> invocations_transformer{0};
template <typename E>
auto run_square_sum(const E & e) {
return grppi::map_reduce(e, v.begin(), v.end(), 0,
[this](int x) {
invocations_transformer++;
return x*x;
},
[](int x, int y) {
return x + y;
}
);
}
template <typename E>
auto run_square_sum_range(const E & e) {
return grppi::map_reduce(e, v, 0,
[this](int x) {
invocations_transformer++;
return x*x;
},
[](int x, int y) {
return x + y;
}
);
}
template <typename E>
auto run_scalar_product_tuple_iter(const E & e){
return grppi::map_reduce(e,
make_tuple(v.begin(),v2.begin()), v.end(), 0,
[this](int x1, int x2) {
invocations_transformer++;
return x1 * x2;
},
[](int x, int y){
return x + y;
}
);
}
template <typename E>
auto run_scalar_product_tuple_size(const E & e){
return grppi::map_reduce(e,
make_tuple(v.begin(),v2.begin()), v.size(), 0,
[this](int x1, int x2){
invocations_transformer++;
return x1 * x2;
},
[](int x, int y){
return x + y;
}
);
}
template <typename E>
auto run_scalar_product_tuple_range(const E & e){
return grppi::map_reduce(e,
grppi::zip(v,v2), 0,
[this](int x1, int x2) {
invocations_transformer++;
return x1 * x2;
},
[](int x, int y){
return x + y;
}
);
}
void setup_single() {
v = vector<int>{1};
output = 0;
}
void check_single() {
EXPECT_EQ(1, invocations_transformer);
EXPECT_EQ(1, this->output);
}
void setup_multiple() {
v = vector<int>{1,2,3,4,5};
output = 0;
}
void check_multiple() {
EXPECT_EQ(5, this->invocations_transformer);
EXPECT_EQ(55, this->output);
}
void setup_single_scalar_product() {
v = vector<int>{5};
v2 = vector<int>{6};
output = 0;
}
void check_single_scalar_product(){
EXPECT_EQ(1, this->invocations_transformer);
EXPECT_EQ(30, this->output);
}
void setup_multiple_scalar_product() {
v = vector<int>{1,2,3,4,5};
v2 = vector<int>{2,4,6,8,10};
output = 0;
}
void check_multiple_scalar_product() {
EXPECT_EQ(5, this->invocations_transformer);
EXPECT_EQ(110, this->output);
}
};
// Test for execution policies defined in supported_executions.h
TYPED_TEST_CASE(map_reduce_test, executions);
TYPED_TEST(map_reduce_test, static_single_square_sum)
{
this->setup_single();
this->output = this->run_square_sum(this->execution_);
this->check_single();
}
TYPED_TEST(map_reduce_test, static_single_square_sum_range)
{
this->setup_single();
this->output = this->run_square_sum_range(this->execution_);
this->check_single();
}
TYPED_TEST(map_reduce_test, dyn_single_square_sum)
{
this->setup_single();
this->output = this->run_square_sum(this->dyn_execution_);
this->check_single();
}
TYPED_TEST(map_reduce_test, dyn_single_square_sum_range)
{
this->setup_single();
this->output = this->run_square_sum_range(this->dyn_execution_);
this->check_single();
}
TYPED_TEST(map_reduce_test, static_multiple_square_sum)
{
this->setup_multiple();
this->output = this->run_square_sum(this->execution_);
this->check_multiple();
}
TYPED_TEST(map_reduce_test, static_multiple_square_sum_range)
{
this->setup_multiple();
this->output = this->run_square_sum_range(this->execution_);
this->check_multiple();
}
TYPED_TEST(map_reduce_test, dyn_multiple_square_sum)
{
this->setup_multiple();
this->output = this->run_square_sum(this->dyn_execution_);
this->check_multiple();
}
TYPED_TEST(map_reduce_test, dyn_multiple_square_sum_range)
{
this->setup_multiple();
this->output = this->run_square_sum_range(this->dyn_execution_);
this->check_multiple();
}
TYPED_TEST(map_reduce_test, static_single_scalar_product_tuple_iter)
{
this->setup_single_scalar_product();
this->output = this->run_scalar_product_tuple_iter(this->execution_);
this->check_single_scalar_product();
}
TYPED_TEST(map_reduce_test, static_single_scalar_product_tuple_size)
{
this->setup_single_scalar_product();
this->output = this->run_scalar_product_tuple_size(this->execution_);
this->check_single_scalar_product();
}
TYPED_TEST(map_reduce_test, static_single_scalar_product_tuple_range)
{
this->setup_single_scalar_product();
this->output = this->run_scalar_product_tuple_range(this->execution_);
this->check_single_scalar_product();
}
TYPED_TEST(map_reduce_test, dyn_single_scalar_product_tuple_iter)
{
this->setup_single_scalar_product();
this->output = this->run_scalar_product_tuple_iter(this->dyn_execution_);
this->check_single_scalar_product();
}
TYPED_TEST(map_reduce_test, dyn_single_scalar_product_tuple_size)
{
this->setup_single_scalar_product();
this->output = this->run_scalar_product_tuple_size(this->dyn_execution_);
this->check_single_scalar_product();
}
TYPED_TEST(map_reduce_test, dyn_single_scalar_product_tuple_range)
{
this->setup_single_scalar_product();
this->output = this->run_scalar_product_tuple_range(this->dyn_execution_);
this->check_single_scalar_product();
}
TYPED_TEST(map_reduce_test, static_multiple_scalar_product_tuple_iter)
{
this->setup_multiple_scalar_product();
this->output = this->run_scalar_product_tuple_iter(this->execution_);
this->check_multiple_scalar_product();
}
TYPED_TEST(map_reduce_test, static_multiple_scalar_product_tuple_size)
{
this->setup_multiple_scalar_product();
this->output = this->run_scalar_product_tuple_size(this->execution_);
this->check_multiple_scalar_product();
}
TYPED_TEST(map_reduce_test, static_multiple_scalar_product_tuple_range)
{
this->setup_multiple_scalar_product();
this->output = this->run_scalar_product_tuple_range(this->execution_);
this->check_multiple_scalar_product();
}
TYPED_TEST(map_reduce_test, dyn_multiple_scalar_product_tuple_iter)
{
this->setup_multiple_scalar_product();
this->output = this->run_scalar_product_tuple_iter(this->dyn_execution_);
this->check_multiple_scalar_product();
}
TYPED_TEST(map_reduce_test, dyn_multiple_scalar_product_tuple_size)
{
this->setup_multiple_scalar_product();
this->output = this->run_scalar_product_tuple_size(this->dyn_execution_);
this->check_multiple_scalar_product();
}
TYPED_TEST(map_reduce_test, dyn_multiple_scalar_product_tuple_size_range)
{
this->setup_multiple_scalar_product();
this->output = this->run_scalar_product_tuple_range(this->dyn_execution_);
this->check_multiple_scalar_product();
}
<commit_msg>Added missing test cases to map-reduce<commit_after>/*
* Copyright 2018 Universidad Carlos III de Madrid
*
* 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 <atomic>
#include <gtest/gtest.h>
#include <iostream>
#include "mapreduce.h"
#include "dyn/dynamic_execution.h"
#include "supported_executions.h"
using namespace std;
using namespace grppi;
template <typename T>
class map_reduce_test : public ::testing::Test {
public:
T execution_{};
dynamic_execution dyn_execution_{execution_};
// Variables
int output{};
// Vectors
vector<int> v{};
vector<int> v2{};
// Invocation counter
std::atomic<int> invocations_transformer{0};
template <typename E>
auto run_square_sum(const E & e) {
return grppi::map_reduce(e, v.begin(), v.end(), 0,
[this](int x) {
invocations_transformer++;
return x*x;
},
[](int x, int y) {
return x + y;
}
);
}
template <typename E>
auto run_square_sum_size(const E & e) {
return grppi::map_reduce(e, begin(v), v.size(), 0,
[this](int x) {
invocations_transformer++;
return x*x;
},
[](int x, int y) {
return x + y;
}
);
}
template <typename E>
auto run_square_sum_range(const E & e) {
return grppi::map_reduce(e, v, 0,
[this](int x) {
invocations_transformer++;
return x*x;
},
[](int x, int y) {
return x + y;
}
);
}
template <typename E>
auto run_scalar_product_tuple_iter(const E & e){
return grppi::map_reduce(e,
make_tuple(v.begin(),v2.begin()), v.end(), 0,
[this](int x1, int x2) {
invocations_transformer++;
return x1 * x2;
},
[](int x, int y){
return x + y;
}
);
}
template <typename E>
auto run_scalar_product_tuple_size(const E & e){
return grppi::map_reduce(e,
make_tuple(v.begin(),v2.begin()), v.size(), 0,
[this](int x1, int x2){
invocations_transformer++;
return x1 * x2;
},
[](int x, int y){
return x + y;
}
);
}
template <typename E>
auto run_scalar_product_tuple_range(const E & e){
return grppi::map_reduce(e,
grppi::zip(v,v2), 0,
[this](int x1, int x2) {
invocations_transformer++;
return x1 * x2;
},
[](int x, int y){
return x + y;
}
);
}
void setup_single() {
v = vector<int>{1};
output = 0;
}
void check_single() {
EXPECT_EQ(1, invocations_transformer);
EXPECT_EQ(1, this->output);
}
void setup_multiple() {
v = vector<int>{1,2,3,4,5};
output = 0;
}
void check_multiple() {
EXPECT_EQ(5, this->invocations_transformer);
EXPECT_EQ(55, this->output);
}
void setup_single_scalar_product() {
v = vector<int>{5};
v2 = vector<int>{6};
output = 0;
}
void check_single_scalar_product(){
EXPECT_EQ(1, this->invocations_transformer);
EXPECT_EQ(30, this->output);
}
void setup_multiple_scalar_product() {
v = vector<int>{1,2,3,4,5};
v2 = vector<int>{2,4,6,8,10};
output = 0;
}
void check_multiple_scalar_product() {
EXPECT_EQ(5, this->invocations_transformer);
EXPECT_EQ(110, this->output);
}
};
// Test for execution policies defined in supported_executions.h
TYPED_TEST_CASE(map_reduce_test, executions);
TYPED_TEST(map_reduce_test, static_single_square_sum)
{
this->setup_single();
this->output = this->run_square_sum(this->execution_);
this->check_single();
}
TYPED_TEST(map_reduce_test, static_single_square_sum_size)
{
this->setup_single();
this->output = this->run_square_sum_size(this->execution_);
this->check_single();
}
TYPED_TEST(map_reduce_test, static_single_square_sum_range)
{
this->setup_single();
this->output = this->run_square_sum_range(this->execution_);
this->check_single();
}
TYPED_TEST(map_reduce_test, dyn_single_square_sum)
{
this->setup_single();
this->output = this->run_square_sum(this->dyn_execution_);
this->check_single();
}
TYPED_TEST(map_reduce_test, dyn_single_square_sum_size)
{
this->setup_single();
this->output = this->run_square_sum_size(this->dyn_execution_);
this->check_single();
}
TYPED_TEST(map_reduce_test, dyn_single_square_sum_range)
{
this->setup_single();
this->output = this->run_square_sum_range(this->dyn_execution_);
this->check_single();
}
TYPED_TEST(map_reduce_test, static_multiple_square_sum)
{
this->setup_multiple();
this->output = this->run_square_sum(this->execution_);
this->check_multiple();
}
TYPED_TEST(map_reduce_test, static_multiple_square_sum_size)
{
this->setup_multiple();
this->output = this->run_square_sum_size(this->execution_);
this->check_multiple();
}
TYPED_TEST(map_reduce_test, static_multiple_square_sum_range)
{
this->setup_multiple();
this->output = this->run_square_sum_range(this->execution_);
this->check_multiple();
}
TYPED_TEST(map_reduce_test, dyn_multiple_square_sum)
{
this->setup_multiple();
this->output = this->run_square_sum(this->dyn_execution_);
this->check_multiple();
}
TYPED_TEST(map_reduce_test, dyn_multiple_square_sum_size)
{
this->setup_multiple();
this->output = this->run_square_sum_size(this->dyn_execution_);
this->check_multiple();
}
TYPED_TEST(map_reduce_test, dyn_multiple_square_sum_range)
{
this->setup_multiple();
this->output = this->run_square_sum_range(this->dyn_execution_);
this->check_multiple();
}
TYPED_TEST(map_reduce_test, static_single_scalar_product_tuple_iter)
{
this->setup_single_scalar_product();
this->output = this->run_scalar_product_tuple_iter(this->execution_);
this->check_single_scalar_product();
}
TYPED_TEST(map_reduce_test, static_single_scalar_product_tuple_size)
{
this->setup_single_scalar_product();
this->output = this->run_scalar_product_tuple_size(this->execution_);
this->check_single_scalar_product();
}
TYPED_TEST(map_reduce_test, static_single_scalar_product_tuple_range)
{
this->setup_single_scalar_product();
this->output = this->run_scalar_product_tuple_range(this->execution_);
this->check_single_scalar_product();
}
TYPED_TEST(map_reduce_test, dyn_single_scalar_product_tuple_iter)
{
this->setup_single_scalar_product();
this->output = this->run_scalar_product_tuple_iter(this->dyn_execution_);
this->check_single_scalar_product();
}
TYPED_TEST(map_reduce_test, dyn_single_scalar_product_tuple_size)
{
this->setup_single_scalar_product();
this->output = this->run_scalar_product_tuple_size(this->dyn_execution_);
this->check_single_scalar_product();
}
TYPED_TEST(map_reduce_test, dyn_single_scalar_product_tuple_range)
{
this->setup_single_scalar_product();
this->output = this->run_scalar_product_tuple_range(this->dyn_execution_);
this->check_single_scalar_product();
}
TYPED_TEST(map_reduce_test, static_multiple_scalar_product_tuple_iter)
{
this->setup_multiple_scalar_product();
this->output = this->run_scalar_product_tuple_iter(this->execution_);
this->check_multiple_scalar_product();
}
TYPED_TEST(map_reduce_test, static_multiple_scalar_product_tuple_size)
{
this->setup_multiple_scalar_product();
this->output = this->run_scalar_product_tuple_size(this->execution_);
this->check_multiple_scalar_product();
}
TYPED_TEST(map_reduce_test, static_multiple_scalar_product_tuple_range)
{
this->setup_multiple_scalar_product();
this->output = this->run_scalar_product_tuple_range(this->execution_);
this->check_multiple_scalar_product();
}
TYPED_TEST(map_reduce_test, dyn_multiple_scalar_product_tuple_iter)
{
this->setup_multiple_scalar_product();
this->output = this->run_scalar_product_tuple_iter(this->dyn_execution_);
this->check_multiple_scalar_product();
}
TYPED_TEST(map_reduce_test, dyn_multiple_scalar_product_tuple_size)
{
this->setup_multiple_scalar_product();
this->output = this->run_scalar_product_tuple_size(this->dyn_execution_);
this->check_multiple_scalar_product();
}
TYPED_TEST(map_reduce_test, dyn_multiple_scalar_product_tuple_size_range)
{
this->setup_multiple_scalar_product();
this->output = this->run_scalar_product_tuple_range(this->dyn_execution_);
this->check_multiple_scalar_product();
}
<|endoftext|> |
<commit_before><commit_msg>bustage fix - file moved<commit_after><|endoftext|> |
<commit_before>
#include "cmath" // For isnan(), when it's defined
#include "diff_system.h"
#include "equation_systems.h"
#include "libmesh_logging.h"
#include "linear_solver.h"
#include "newton_solver.h"
#include "numeric_vector.h"
#include "sparse_matrix.h"
#include "dof_map.h"
NewtonSolver::NewtonSolver (sys_type& s)
: Parent(s),
require_residual_reduction(true),
minsteplength(1e-5),
linear_tolerance_multiplier(1e-3),
linear_solver(LinearSolver<Number>::build())
{
}
NewtonSolver::~NewtonSolver ()
{
}
void NewtonSolver::reinit()
{
Parent::reinit();
linear_solver->clear();
}
void NewtonSolver::solve()
{
START_LOG("solve()", "NewtonSolver");
// NumericVector<Number> &newton_iterate =
// _system.get_vector("_nonlinear_solution");
NumericVector<Number> &newton_iterate = *(_system.solution);
// NumericVector<Number> &linear_solution = *(_system.solution);
AutoPtr<NumericVector<Number> > linear_solution_ptr = newton_iterate.clone();
NumericVector<Number> &linear_solution = *linear_solution_ptr;
newton_iterate.close();
linear_solution.close();
// solution = newton_iterate;
// _system.get_dof_map().enforce_constraints_exactly(_system);
// newton_iterate = solution;
_system.get_dof_map().enforce_constraints_exactly(_system);
NumericVector<Number> &rhs = *(_system.rhs);
SparseMatrix<Number> &matrix = *(_system.matrix);
// Prepare to take incomplete steps
Real last_residual=0.;
// Set starting linear tolerance
Real current_linear_tolerance = initial_linear_tolerance;
// Now we begin the nonlinear loop
for (unsigned int l=0; l<max_nonlinear_iterations; ++l)
{
if (!quiet)
std::cout << "Assembling System" << std::endl;
PAUSE_LOG("solve()", "NewtonSolver");
_system.assembly(true, true);
RESTART_LOG("solve()", "NewtonSolver");
rhs.close();
Real current_residual = rhs.l2_norm();
last_residual = current_residual;
// isnan() isn't standard C++ yet
#ifdef isnan
if (isnan(current_residual))
{
std::cout << " Nonlinear solver DIVERGED at step " << l
<< " with norm Not-a-Number"
<< std::endl;
error();
continue;
}
#endif // isnan
max_residual_norm = std::max (current_residual,
max_residual_norm);
// Compute the l2 norm of the whole solution
Real norm_total = newton_iterate.l2_norm();
max_solution_norm = std::max(max_solution_norm, norm_total);
if (!quiet)
std::cout << "Nonlinear Residual: "
<< current_residual << std::endl;
// Make sure our linear tolerance is low enough
current_linear_tolerance = std::min (current_linear_tolerance,
current_residual * linear_tolerance_multiplier);
// But don't let it be too small
if (current_linear_tolerance < minimum_linear_tolerance)
{
current_linear_tolerance = minimum_linear_tolerance;
}
// At this point newton_iterate is the current guess, and
// linear_solution is now about to become the NEGATIVE of the next
// Newton step.
// Our best initial guess for the linear_solution is zero!
linear_solution.zero();
if (!quiet)
std::cout << "Linear solve starting, tolerance "
<< current_linear_tolerance << std::endl;
PAUSE_LOG("solve()", "NewtonSolver");
// Solve the linear system. Two cases:
const std::pair<unsigned int, Real> rval =
(_system.have_matrix("Preconditioner")) ?
// 1.) User-supplied preconditioner
linear_solver->solve (matrix, _system.get_matrix("Preconditioner"),
linear_solution, rhs, current_linear_tolerance,
max_linear_iterations) :
// 2.) Use system matrix for the preconditioner
linear_solver->solve (matrix, linear_solution, rhs,
current_linear_tolerance,
max_linear_iterations);
// We may need to localize a parallel solution
_system.update ();
RESTART_LOG("solve()", "NewtonSolver");
// The linear solver may not have fit our constraints exactly
_system.get_dof_map().enforce_constraints_exactly(_system, &linear_solution);
const unsigned int linear_steps = rval.first;
assert(linear_steps <= max_linear_iterations);
const bool linear_solve_finished =
!(linear_steps == max_linear_iterations);
if (!quiet)
std::cout << "Linear solve finished, step " << linear_steps
<< ", residual " << rval.second
<< std::endl;
// Compute the l2 norm of the nonlinear update
Real norm_delta = linear_solution.l2_norm();
if (!quiet)
std::cout << "Trying full Newton step" << std::endl;
// Take a full Newton step
newton_iterate.add (-1., linear_solution);
newton_iterate.close();
// Check residual with full Newton step
Real steplength = 1.;
PAUSE_LOG("solve()", "NewtonSolver");
_system.assembly(true, false);
RESTART_LOG("solve()", "NewtonSolver");
rhs.close();
current_residual = rhs.l2_norm();
// A potential method for avoiding oversolving?
/*
Real predicted_absolute_error =
current_residual * norm_delta / last_residual;
Real predicted_relative_error =
predicted_absolute_error / max_solution_norm;
std::cout << "Predicted absolute error = " <<
predicted_absolute_error << std::endl;
std::cout << "Predicted relative error = " <<
predicted_relative_error << std::endl;
*/
// backtrack if necessary
if (require_residual_reduction)
{
// but don't fiddle around if we've already converged
if (test_convergence(current_residual, norm_delta,
linear_solve_finished))
{
if (!quiet)
print_convergence(l, current_residual, norm_delta,
linear_solve_finished);
break;
}
while (current_residual > last_residual)
{
// Reduce step size to 1/2, 1/4, etc.
steplength /= 2.;
norm_delta /= 2.;
if (!quiet)
std::cout << "Shrinking Newton step to "
<< steplength << std::endl;
newton_iterate.add (steplength, linear_solution);
newton_iterate.close();
// Check residual with fractional Newton step
PAUSE_LOG("solve()", "NewtonSolver");
_system.assembly (true, false);
RESTART_LOG("solve()", "NewtonSolver");
rhs.close();
current_residual = rhs.l2_norm();
if (!quiet)
std::cout << "Current Residual: "
<< current_residual << std::endl;
if (steplength/2. < minsteplength &&
current_residual > last_residual)
{
std::cout << "Inexact Newton step FAILED at step "
<< l << std::endl;
error();
}
}
}
// Compute the l2 norm of the whole solution
norm_total = newton_iterate.l2_norm();
max_solution_norm = std::max(max_solution_norm, norm_total);
// Print out information for the
// nonlinear iterations.
if (!quiet)
std::cout << " Nonlinear step: |du|/|u| = "
<< norm_delta / norm_total
<< ", |du| = " << norm_delta
<< std::endl;
// Terminate the solution iteration if the difference between
// this iteration and the last is sufficiently small.
if (!quiet)
print_convergence(l, current_residual,
norm_delta / steplength,
linear_solve_finished);
if (test_convergence(current_residual, norm_delta / steplength,
linear_solve_finished))
{
break;
}
if (l >= max_nonlinear_iterations - 1)
{
std::cout << " Nonlinear solver FAILED TO CONVERGE by step " << l
<< " with norm " << norm_total
<< std::endl;
if (continue_after_max_iterations)
std::cout << " Continuing anyway..." << std::endl;
else
error();
continue;
}
} // end nonlinear loop
// Copy the final nonlinear iterate into the current_solution,
// for other libMesh functions that expect it
// solution = newton_iterate;
// solution.close();
// The linear solver may not have fit our constraints exactly
_system.get_dof_map().enforce_constraints_exactly(_system);
// newton_iterate = solution;
// solution.close();
// We may need to localize a parallel solution
_system.update ();
STOP_LOG("solve()", "NewtonSolver");
}
bool NewtonSolver::test_convergence(Real current_residual,
Real step_norm,
bool linear_solve_finished)
{
// We haven't converged unless we pass a convergence test
bool has_converged = false;
// Is our absolute residual low enough?
if (current_residual < absolute_residual_tolerance)
has_converged = true;
// Is our relative residual low enough?
if ((current_residual / max_residual_norm) <
relative_residual_tolerance)
has_converged = true;
// For incomplete linear solves, it's not safe to test step sizes
if (!linear_solve_finished)
return has_converged;
// Is our absolute Newton step size small enough?
if (step_norm < absolute_step_tolerance)
has_converged = true;
// Is our relative Newton step size small enough?
if (step_norm / max_solution_norm <
relative_step_tolerance)
has_converged = true;
return has_converged;
}
void NewtonSolver::print_convergence(unsigned int step_num,
Real current_residual,
Real step_norm,
bool linear_solve_finished)
{
// Is our absolute residual low enough?
if (current_residual < absolute_residual_tolerance)
{
std::cout << " Nonlinear solver converged, step " << step_num
<< ", residual " << current_residual
<< std::endl;
}
else if (absolute_residual_tolerance)
{
std::cout << " Nonlinear solver current_residual "
<< current_residual << " > "
<< (absolute_residual_tolerance) << std::endl;
}
// Is our relative residual low enough?
if ((current_residual / max_residual_norm) <
relative_residual_tolerance)
{
std::cout << " Nonlinear solver converged, step " << step_num
<< ", residual reduction "
<< current_residual / max_residual_norm
<< " < " << relative_residual_tolerance
<< std::endl;
}
else if (relative_residual_tolerance)
{
if (!quiet)
std::cout << " Nonlinear solver relative residual "
<< (current_residual / max_residual_norm)
<< " > " << relative_residual_tolerance
<< std::endl;
}
// For incomplete linear solves, it's not safe to test step sizes
if (!linear_solve_finished)
return;
// Is our absolute Newton step size small enough?
if (step_norm < absolute_step_tolerance)
{
std::cout << " Nonlinear solver converged, step " << step_num
<< ", absolute step size "
<< step_norm
<< " < " << absolute_step_tolerance
<< std::endl;
}
else if (absolute_step_tolerance)
{
std::cout << " Nonlinear solver absolute step size "
<< step_norm
<< " > " << absolute_step_tolerance
<< std::endl;
}
// Is our relative Newton step size small enough?
if (step_norm / max_solution_norm <
relative_step_tolerance)
{
std::cout << " Nonlinear solver converged, step " << step_num
<< ", relative step size "
<< (step_norm / max_solution_norm)
<< " < " << relative_step_tolerance
<< std::endl;
}
else if (relative_step_tolerance)
{
std::cout << " Nonlinear solver relative step size "
<< (step_norm / max_solution_norm)
<< " > " << relative_step_tolerance
<< std::endl;
}
}
<commit_msg>Print post-Newton-step residuals when solver.quiet is off<commit_after>
#include "cmath" // For isnan(), when it's defined
#include "diff_system.h"
#include "equation_systems.h"
#include "libmesh_logging.h"
#include "linear_solver.h"
#include "newton_solver.h"
#include "numeric_vector.h"
#include "sparse_matrix.h"
#include "dof_map.h"
NewtonSolver::NewtonSolver (sys_type& s)
: Parent(s),
require_residual_reduction(true),
minsteplength(1e-5),
linear_tolerance_multiplier(1e-3),
linear_solver(LinearSolver<Number>::build())
{
}
NewtonSolver::~NewtonSolver ()
{
}
void NewtonSolver::reinit()
{
Parent::reinit();
linear_solver->clear();
}
void NewtonSolver::solve()
{
START_LOG("solve()", "NewtonSolver");
// NumericVector<Number> &newton_iterate =
// _system.get_vector("_nonlinear_solution");
NumericVector<Number> &newton_iterate = *(_system.solution);
// NumericVector<Number> &linear_solution = *(_system.solution);
AutoPtr<NumericVector<Number> > linear_solution_ptr = newton_iterate.clone();
NumericVector<Number> &linear_solution = *linear_solution_ptr;
newton_iterate.close();
linear_solution.close();
// solution = newton_iterate;
// _system.get_dof_map().enforce_constraints_exactly(_system);
// newton_iterate = solution;
_system.get_dof_map().enforce_constraints_exactly(_system);
NumericVector<Number> &rhs = *(_system.rhs);
SparseMatrix<Number> &matrix = *(_system.matrix);
// Prepare to take incomplete steps
Real last_residual=0.;
// Set starting linear tolerance
Real current_linear_tolerance = initial_linear_tolerance;
// Now we begin the nonlinear loop
for (unsigned int l=0; l<max_nonlinear_iterations; ++l)
{
if (!quiet)
std::cout << "Assembling System" << std::endl;
PAUSE_LOG("solve()", "NewtonSolver");
_system.assembly(true, true);
RESTART_LOG("solve()", "NewtonSolver");
rhs.close();
Real current_residual = rhs.l2_norm();
last_residual = current_residual;
// isnan() isn't standard C++ yet
#ifdef isnan
if (isnan(current_residual))
{
std::cout << " Nonlinear solver DIVERGED at step " << l
<< " with norm Not-a-Number"
<< std::endl;
error();
continue;
}
#endif // isnan
max_residual_norm = std::max (current_residual,
max_residual_norm);
// Compute the l2 norm of the whole solution
Real norm_total = newton_iterate.l2_norm();
max_solution_norm = std::max(max_solution_norm, norm_total);
if (!quiet)
std::cout << "Nonlinear Residual: "
<< current_residual << std::endl;
// Make sure our linear tolerance is low enough
current_linear_tolerance = std::min (current_linear_tolerance,
current_residual * linear_tolerance_multiplier);
// But don't let it be too small
if (current_linear_tolerance < minimum_linear_tolerance)
{
current_linear_tolerance = minimum_linear_tolerance;
}
// At this point newton_iterate is the current guess, and
// linear_solution is now about to become the NEGATIVE of the next
// Newton step.
// Our best initial guess for the linear_solution is zero!
linear_solution.zero();
if (!quiet)
std::cout << "Linear solve starting, tolerance "
<< current_linear_tolerance << std::endl;
PAUSE_LOG("solve()", "NewtonSolver");
// Solve the linear system. Two cases:
const std::pair<unsigned int, Real> rval =
(_system.have_matrix("Preconditioner")) ?
// 1.) User-supplied preconditioner
linear_solver->solve (matrix, _system.get_matrix("Preconditioner"),
linear_solution, rhs, current_linear_tolerance,
max_linear_iterations) :
// 2.) Use system matrix for the preconditioner
linear_solver->solve (matrix, linear_solution, rhs,
current_linear_tolerance,
max_linear_iterations);
// We may need to localize a parallel solution
_system.update ();
RESTART_LOG("solve()", "NewtonSolver");
// The linear solver may not have fit our constraints exactly
_system.get_dof_map().enforce_constraints_exactly(_system, &linear_solution);
const unsigned int linear_steps = rval.first;
assert(linear_steps <= max_linear_iterations);
const bool linear_solve_finished =
!(linear_steps == max_linear_iterations);
if (!quiet)
std::cout << "Linear solve finished, step " << linear_steps
<< ", residual " << rval.second
<< std::endl;
// Compute the l2 norm of the nonlinear update
Real norm_delta = linear_solution.l2_norm();
if (!quiet)
std::cout << "Trying full Newton step" << std::endl;
// Take a full Newton step
newton_iterate.add (-1., linear_solution);
newton_iterate.close();
// Check residual with full Newton step
Real steplength = 1.;
PAUSE_LOG("solve()", "NewtonSolver");
_system.assembly(true, false);
RESTART_LOG("solve()", "NewtonSolver");
rhs.close();
current_residual = rhs.l2_norm();
if (!quiet)
std::cout << " Current Residual: "
<< current_residual << std::endl;
// A potential method for avoiding oversolving?
/*
Real predicted_absolute_error =
current_residual * norm_delta / last_residual;
Real predicted_relative_error =
predicted_absolute_error / max_solution_norm;
std::cout << "Predicted absolute error = " <<
predicted_absolute_error << std::endl;
std::cout << "Predicted relative error = " <<
predicted_relative_error << std::endl;
*/
// backtrack if necessary
if (require_residual_reduction)
{
// but don't fiddle around if we've already converged
if (test_convergence(current_residual, norm_delta,
linear_solve_finished))
{
if (!quiet)
print_convergence(l, current_residual, norm_delta,
linear_solve_finished);
break;
}
while (current_residual > last_residual)
{
// Reduce step size to 1/2, 1/4, etc.
steplength /= 2.;
norm_delta /= 2.;
if (!quiet)
std::cout << " Shrinking Newton step to "
<< steplength << std::endl;
newton_iterate.add (steplength, linear_solution);
newton_iterate.close();
// Check residual with fractional Newton step
PAUSE_LOG("solve()", "NewtonSolver");
_system.assembly (true, false);
RESTART_LOG("solve()", "NewtonSolver");
rhs.close();
current_residual = rhs.l2_norm();
if (!quiet)
std::cout << " Current Residual: "
<< current_residual << std::endl;
if (steplength/2. < minsteplength &&
current_residual > last_residual)
{
std::cout << "Inexact Newton step FAILED at step "
<< l << std::endl;
error();
}
}
}
// Compute the l2 norm of the whole solution
norm_total = newton_iterate.l2_norm();
max_solution_norm = std::max(max_solution_norm, norm_total);
// Print out information for the
// nonlinear iterations.
if (!quiet)
std::cout << " Nonlinear step: |du|/|u| = "
<< norm_delta / norm_total
<< ", |du| = " << norm_delta
<< std::endl;
// Terminate the solution iteration if the difference between
// this iteration and the last is sufficiently small.
if (!quiet)
print_convergence(l, current_residual,
norm_delta / steplength,
linear_solve_finished);
if (test_convergence(current_residual, norm_delta / steplength,
linear_solve_finished))
{
break;
}
if (l >= max_nonlinear_iterations - 1)
{
std::cout << " Nonlinear solver FAILED TO CONVERGE by step " << l
<< " with norm " << norm_total
<< std::endl;
if (continue_after_max_iterations)
std::cout << " Continuing anyway..." << std::endl;
else
error();
continue;
}
} // end nonlinear loop
// Copy the final nonlinear iterate into the current_solution,
// for other libMesh functions that expect it
// solution = newton_iterate;
// solution.close();
// The linear solver may not have fit our constraints exactly
_system.get_dof_map().enforce_constraints_exactly(_system);
// newton_iterate = solution;
// solution.close();
// We may need to localize a parallel solution
_system.update ();
STOP_LOG("solve()", "NewtonSolver");
}
bool NewtonSolver::test_convergence(Real current_residual,
Real step_norm,
bool linear_solve_finished)
{
// We haven't converged unless we pass a convergence test
bool has_converged = false;
// Is our absolute residual low enough?
if (current_residual < absolute_residual_tolerance)
has_converged = true;
// Is our relative residual low enough?
if ((current_residual / max_residual_norm) <
relative_residual_tolerance)
has_converged = true;
// For incomplete linear solves, it's not safe to test step sizes
if (!linear_solve_finished)
return has_converged;
// Is our absolute Newton step size small enough?
if (step_norm < absolute_step_tolerance)
has_converged = true;
// Is our relative Newton step size small enough?
if (step_norm / max_solution_norm <
relative_step_tolerance)
has_converged = true;
return has_converged;
}
void NewtonSolver::print_convergence(unsigned int step_num,
Real current_residual,
Real step_norm,
bool linear_solve_finished)
{
// Is our absolute residual low enough?
if (current_residual < absolute_residual_tolerance)
{
std::cout << " Nonlinear solver converged, step " << step_num
<< ", residual " << current_residual
<< std::endl;
}
else if (absolute_residual_tolerance)
{
std::cout << " Nonlinear solver current_residual "
<< current_residual << " > "
<< (absolute_residual_tolerance) << std::endl;
}
// Is our relative residual low enough?
if ((current_residual / max_residual_norm) <
relative_residual_tolerance)
{
std::cout << " Nonlinear solver converged, step " << step_num
<< ", residual reduction "
<< current_residual / max_residual_norm
<< " < " << relative_residual_tolerance
<< std::endl;
}
else if (relative_residual_tolerance)
{
if (!quiet)
std::cout << " Nonlinear solver relative residual "
<< (current_residual / max_residual_norm)
<< " > " << relative_residual_tolerance
<< std::endl;
}
// For incomplete linear solves, it's not safe to test step sizes
if (!linear_solve_finished)
return;
// Is our absolute Newton step size small enough?
if (step_norm < absolute_step_tolerance)
{
std::cout << " Nonlinear solver converged, step " << step_num
<< ", absolute step size "
<< step_norm
<< " < " << absolute_step_tolerance
<< std::endl;
}
else if (absolute_step_tolerance)
{
std::cout << " Nonlinear solver absolute step size "
<< step_norm
<< " > " << absolute_step_tolerance
<< std::endl;
}
// Is our relative Newton step size small enough?
if (step_norm / max_solution_norm <
relative_step_tolerance)
{
std::cout << " Nonlinear solver converged, step " << step_num
<< ", relative step size "
<< (step_norm / max_solution_norm)
<< " < " << relative_step_tolerance
<< std::endl;
}
else if (relative_step_tolerance)
{
std::cout << " Nonlinear solver relative step size "
<< (step_norm / max_solution_norm)
<< " > " << relative_step_tolerance
<< std::endl;
}
}
<|endoftext|> |
<commit_before>
#include "diff_system.h"
#include "equation_systems.h"
#include "linear_solver.h"
#include "newton_solver.h"
#include "numeric_vector.h"
#include "sparse_matrix.h"
NewtonSolver::NewtonSolver (sys_type& s) :
Parent(s), linear_solver(LinearSolver<Number>::build())
{
}
NewtonSolver::~NewtonSolver ()
{
}
void NewtonSolver::solve()
{
// The number of steps and the stopping criterion
// for the nonlinear iterations.
const unsigned int max_nonlinear_steps = 100;
const unsigned int max_linear_iterations = 10000;
// Stopping criteria for nonlinear iterations
const Real nonlinear_abs_step_tolerance = 1.e-9;
const Real nonlinear_rel_step_tolerance = 1.e-6;
const Real nonlinear_abs_res_tolerance = 1.e-9;
const Real nonlinear_rel_res_tolerance = 1.e-6;
// Maximum amount by which to reduce Newton steps
const Real minsteplength = 0.1;
// Initial linear solver tolerance in main nonlinear solver
const Real linear_tolerance = 1.e-3;
// Amount by which nonlinear residual should exceed linear solver
// tolerance
const Real relative_tolerance = 1.e-3;
// We'll shut up eventually...
const bool verbose_convergence_chatter = true;
const bool require_residual_reduction = false;
EquationSystems &equation_systems = _system.get_equation_systems();
equation_systems.parameters.set<unsigned int>
("linear solver maximum iterations") =
max_linear_iterations;
NumericVector<Number> &solution = *(_system.solution);
NumericVector<Number> &newton_iterate =
_system.get_vector("_nonlinear_solution");
NumericVector<Number> &rhs = *(_system.rhs);
SparseMatrix<Number> &matrix = *(_system.matrix);
// Now we begin the nonlinear loop
newton_iterate.zero();
newton_iterate.close();
// Prepare to take incomplete steps
Real last_residual, first_residual;
// Set starting linear tolerance
Real current_linear_tolerance = linear_tolerance;
for (unsigned int l=0; l<max_nonlinear_steps; ++l)
{
_system.assembly(true, true);
rhs.close();
Real current_residual = rhs.l2_norm();
if (!l)
first_residual = current_residual;
last_residual = current_residual;
std::cout << "Nonlinear Residual: " << current_residual << std::endl;
// Make sure our linear tolerance is low enough
if (current_linear_tolerance > current_residual * relative_tolerance)
{
current_linear_tolerance = current_residual * relative_tolerance;
equation_systems.parameters.set<Real>
("linear solver tolerance") = current_linear_tolerance;
}
// At this point newton_iterate is the current guess, and
// solution is now about to become the NEGATIVE of the next
// Newton step
std::cout << "Linear solve starting" << std::endl;
// Solve the linear system. Two cases:
const std::pair<unsigned int, Real> rval =
(_system.have_matrix("Preconditioner")) ?
// 1.) User-supplied preconditioner
linear_solver->solve (matrix, _system.get_matrix("Preconditioner"),
solution, rhs, current_linear_tolerance,
max_linear_iterations) :
// 2.) Use system matrix for the preconditioner
linear_solver->solve (matrix, solution, rhs,
current_linear_tolerance,
max_linear_iterations);
std::cout << "Linear solve converged, step " << rval.first
<< ", residual " << rval.second
<< ", tolerance " << current_linear_tolerance << std::endl;
// Compute the l2 norm of the nonlinear update
Real norm_delta = solution.l2_norm();
std::cout << "Taking full Newton step" << std::endl;
// Take a full Newton step
newton_iterate.add (-1., solution);
newton_iterate.close();
// Check residual with full Newton step
Real steplength = 1.;
_system.assembly(true, false);
// backtrack if necessary
if (require_residual_reduction)
{
rhs.close();
current_residual = rhs.l2_norm();
while (current_residual > last_residual)
{
// Reduce step size to 1/2, 1/4, etc.
steplength /= 2.;
norm_delta /= 2.;
std::cout << "Shrinking Newton step to " << steplength << std::endl;
newton_iterate.add (steplength, solution);
newton_iterate.close();
// Check residual with fractional Newton step
std::cout << " Checking " << std::flush;
_system.assembly (true, false);
current_residual = rhs.l2_norm();
std::cout << "Current Residual: " << current_residual << std::endl;
if (steplength/2. < minsteplength &&
current_residual > last_residual)
{
std::cout << "Inexact Newton step FAILED at step " << l << std::endl;
error();
}
}
}
// Compute the l2 norm of the whole solution
const Real norm_total = newton_iterate.l2_norm();
// Print out information for the
// nonlinear iterations.
std::cout << " Nonlinear step: |du|/|u| = "
<< norm_delta / norm_total
<< ", |du| = "
<< norm_delta
<< std::endl;
// We haven't converged unless we pass a convergence test
bool has_converged = false;
// Is our absolute residual low enough?
if (current_residual < nonlinear_abs_res_tolerance)
{
std::cout << " Nonlinear solver converged, step "
<< l
<< ", residual "
<< current_residual
<< std::endl;
has_converged = true;
}
else if (verbose_convergence_chatter)
{
std::cout << " Nonlinear solver current_residual "
<< current_residual
<< " > "
<< (nonlinear_abs_res_tolerance)
<< std::endl;
}
// Is our relative residual low enough?
if ((current_residual / first_residual) < nonlinear_rel_res_tolerance)
{
std::cout << " Nonlinear solver converged, step "
<< l
<< ", residual reduction "
<< current_residual / first_residual
<< std::endl;
has_converged = true;
}
else if (verbose_convergence_chatter)
{
std::cout << " Nonlinear solver current/first residual "
<< (current_residual / first_residual)
<< " > "
<< nonlinear_rel_res_tolerance
<< std::endl;
}
// Is our absolute Newton step size small enough?
if (l != 0 && (norm_delta / steplength <
nonlinear_abs_step_tolerance))
{
std::cout << " Nonlinear solver converged, step "
<< l
<< ", absolute step size "
<< norm_delta / steplength
<< std::endl;
has_converged = true;
}
// Is our relative Newton step size small enough?
if (l != 0 && (norm_delta / steplength / norm_total <
nonlinear_rel_step_tolerance))
{
std::cout << " Nonlinear solver converged, step "
<< l
<< ", relative step size "
<< (norm_delta / steplength / norm_total)
<< std::endl;
has_converged = true;
}
// Terminate the solution iteration if the difference between
// this iteration and the last is sufficiently small.
if (has_converged)
{
break;
}
if (l >= max_nonlinear_steps - 1)
{
std::cout << " Nonlinear solver DIVERGED at step "
<< l
<< std::endl;
error();
continue;
}
} // end nonlinear loop
}
<commit_msg>Initialized variables to get rid of overzealous GCC warning.<commit_after>
#include "diff_system.h"
#include "equation_systems.h"
#include "linear_solver.h"
#include "newton_solver.h"
#include "numeric_vector.h"
#include "sparse_matrix.h"
NewtonSolver::NewtonSolver (sys_type& s) :
Parent(s), linear_solver(LinearSolver<Number>::build())
{
}
NewtonSolver::~NewtonSolver ()
{
}
void NewtonSolver::solve()
{
// The number of steps and the stopping criterion
// for the nonlinear iterations.
const unsigned int max_nonlinear_steps = 100;
const unsigned int max_linear_iterations = 10000;
// Stopping criteria for nonlinear iterations
const Real nonlinear_abs_step_tolerance = 1.e-9;
const Real nonlinear_rel_step_tolerance = 1.e-6;
const Real nonlinear_abs_res_tolerance = 1.e-9;
const Real nonlinear_rel_res_tolerance = 1.e-6;
// Maximum amount by which to reduce Newton steps
const Real minsteplength = 0.1;
// Initial linear solver tolerance in main nonlinear solver
const Real linear_tolerance = 1.e-3;
// Amount by which nonlinear residual should exceed linear solver
// tolerance
const Real relative_tolerance = 1.e-3;
// We'll shut up eventually...
const bool verbose_convergence_chatter = true;
const bool require_residual_reduction = false;
EquationSystems &equation_systems = _system.get_equation_systems();
equation_systems.parameters.set<unsigned int>
("linear solver maximum iterations") =
max_linear_iterations;
NumericVector<Number> &solution = *(_system.solution);
NumericVector<Number> &newton_iterate =
_system.get_vector("_nonlinear_solution");
NumericVector<Number> &rhs = *(_system.rhs);
SparseMatrix<Number> &matrix = *(_system.matrix);
// Now we begin the nonlinear loop
newton_iterate.zero();
newton_iterate.close();
// Prepare to take incomplete steps
Real last_residual=0., first_residual=0.;
// Set starting linear tolerance
Real current_linear_tolerance = linear_tolerance;
for (unsigned int l=0; l<max_nonlinear_steps; ++l)
{
_system.assembly(true, true);
rhs.close();
Real current_residual = rhs.l2_norm();
if (!l)
first_residual = current_residual;
last_residual = current_residual;
std::cout << "Nonlinear Residual: " << current_residual << std::endl;
// Make sure our linear tolerance is low enough
if (current_linear_tolerance > current_residual * relative_tolerance)
{
current_linear_tolerance = current_residual * relative_tolerance;
equation_systems.parameters.set<Real>
("linear solver tolerance") = current_linear_tolerance;
}
// At this point newton_iterate is the current guess, and
// solution is now about to become the NEGATIVE of the next
// Newton step
std::cout << "Linear solve starting" << std::endl;
// Solve the linear system. Two cases:
const std::pair<unsigned int, Real> rval =
(_system.have_matrix("Preconditioner")) ?
// 1.) User-supplied preconditioner
linear_solver->solve (matrix, _system.get_matrix("Preconditioner"),
solution, rhs, current_linear_tolerance,
max_linear_iterations) :
// 2.) Use system matrix for the preconditioner
linear_solver->solve (matrix, solution, rhs,
current_linear_tolerance,
max_linear_iterations);
std::cout << "Linear solve converged, step " << rval.first
<< ", residual " << rval.second
<< ", tolerance " << current_linear_tolerance << std::endl;
// Compute the l2 norm of the nonlinear update
Real norm_delta = solution.l2_norm();
std::cout << "Taking full Newton step" << std::endl;
// Take a full Newton step
newton_iterate.add (-1., solution);
newton_iterate.close();
// Check residual with full Newton step
Real steplength = 1.;
_system.assembly(true, false);
// backtrack if necessary
if (require_residual_reduction)
{
rhs.close();
current_residual = rhs.l2_norm();
while (current_residual > last_residual)
{
// Reduce step size to 1/2, 1/4, etc.
steplength /= 2.;
norm_delta /= 2.;
std::cout << "Shrinking Newton step to " << steplength << std::endl;
newton_iterate.add (steplength, solution);
newton_iterate.close();
// Check residual with fractional Newton step
std::cout << " Checking " << std::flush;
_system.assembly (true, false);
current_residual = rhs.l2_norm();
std::cout << "Current Residual: " << current_residual << std::endl;
if (steplength/2. < minsteplength &&
current_residual > last_residual)
{
std::cout << "Inexact Newton step FAILED at step " << l << std::endl;
error();
}
}
}
// Compute the l2 norm of the whole solution
const Real norm_total = newton_iterate.l2_norm();
// Print out information for the
// nonlinear iterations.
std::cout << " Nonlinear step: |du|/|u| = "
<< norm_delta / norm_total
<< ", |du| = "
<< norm_delta
<< std::endl;
// We haven't converged unless we pass a convergence test
bool has_converged = false;
// Is our absolute residual low enough?
if (current_residual < nonlinear_abs_res_tolerance)
{
std::cout << " Nonlinear solver converged, step "
<< l
<< ", residual "
<< current_residual
<< std::endl;
has_converged = true;
}
else if (verbose_convergence_chatter)
{
std::cout << " Nonlinear solver current_residual "
<< current_residual
<< " > "
<< (nonlinear_abs_res_tolerance)
<< std::endl;
}
// Is our relative residual low enough?
if ((current_residual / first_residual) < nonlinear_rel_res_tolerance)
{
std::cout << " Nonlinear solver converged, step "
<< l
<< ", residual reduction "
<< current_residual / first_residual
<< std::endl;
has_converged = true;
}
else if (verbose_convergence_chatter)
{
std::cout << " Nonlinear solver current/first residual "
<< (current_residual / first_residual)
<< " > "
<< nonlinear_rel_res_tolerance
<< std::endl;
}
// Is our absolute Newton step size small enough?
if (l != 0 && (norm_delta / steplength <
nonlinear_abs_step_tolerance))
{
std::cout << " Nonlinear solver converged, step "
<< l
<< ", absolute step size "
<< norm_delta / steplength
<< std::endl;
has_converged = true;
}
// Is our relative Newton step size small enough?
if (l != 0 && (norm_delta / steplength / norm_total <
nonlinear_rel_step_tolerance))
{
std::cout << " Nonlinear solver converged, step "
<< l
<< ", relative step size "
<< (norm_delta / steplength / norm_total)
<< std::endl;
has_converged = true;
}
// Terminate the solution iteration if the difference between
// this iteration and the last is sufficiently small.
if (has_converged)
{
break;
}
if (l >= max_nonlinear_steps - 1)
{
std::cout << " Nonlinear solver DIVERGED at step "
<< l
<< std::endl;
error();
continue;
}
} // end nonlinear loop
}
<|endoftext|> |
<commit_before>#include "shader.h"
#include "mesh.h"
#include "texture.h"
#include <glm/gtc/type_ptr.hpp>
#include <stdexcept>
#include <fstream>
namespace te
{
std::string getShaderLog(GLuint shader)
{
if (!glIsShader(shader))
{
throw std::runtime_error("Passed ID is not a shader.");
}
int infoLogLength = 0;
int maxLength = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
char* infoLog = new char[maxLength];
glGetShaderInfoLog(shader, maxLength, &infoLogLength, infoLog);
if (infoLogLength > 0)
{
std::string log{ infoLog };
delete[] infoLog;
return log;
}
else
{
return{ "" };
}
}
std::string getProgramLog(GLuint program)
{
if (!glIsProgram(program))
{
throw std::runtime_error("Passed ID is not a program.");
}
int infoLogLength = 0;
int maxLength = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength);
char* infoLog = new char[maxLength];
glGetProgramInfoLog(program, maxLength, &infoLogLength, infoLog);
if (infoLogLength > 0)
{
std::string log{ infoLog };
delete[] infoLog;
return log;
}
else
{
return{ "" };
}
}
GLuint loadShader(const std::string& path, GLenum shaderType)
{
GLuint shaderID = 0;
std::string shaderString;
std::ifstream srcFile(path.c_str());
if (!srcFile) { throw std::runtime_error("Unable to open file."); }
shaderString.assign(std::istreambuf_iterator<char>(srcFile), std::istreambuf_iterator<char>());
shaderID = glCreateShader(shaderType);
const GLchar* shaderSrc = shaderString.c_str();
glShaderSource(shaderID, 1, (const GLchar**)&shaderSrc, NULL);
glCompileShader(shaderID);
GLint shaderCompiled = GL_FALSE;
glGetShaderiv(shaderID, GL_COMPILE_STATUS, &shaderCompiled);
if (shaderCompiled != GL_TRUE)
{
std::string msg{ getShaderLog(shaderID) };
glDeleteShader(shaderID);
throw std::runtime_error(msg);
}
return shaderID;
}
GLuint loadProgram(const std::string& vertexShaderPath, const std::string& fragmentShaderPath)
{
GLuint program = glCreateProgram();
GLuint vertexShader = 0;
GLuint fragmentShader = 0;
try
{
vertexShader = loadShader(vertexShaderPath, GL_VERTEX_SHADER);
glAttachShader(program, vertexShader);
fragmentShader = loadShader(fragmentShaderPath, GL_FRAGMENT_SHADER);
glAttachShader(program, fragmentShader);
glLinkProgram(program);
GLint programSuccess = GL_TRUE;
glGetProgramiv(program, GL_LINK_STATUS, &programSuccess);
if (programSuccess != GL_TRUE)
{
throw std::runtime_error(getProgramLog(program));
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
}
catch (std::exception e)
{
glDeleteProgram(program);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
throw std::runtime_error(e.what());
}
return program;
}
Shader::Shader(const glm::mat4& projection, const glm::mat4& model)
: mProgram(loadProgram("shaders/basic.glvs", "shaders/basic.glfs"))
, mViewLocation(glGetUniformLocation(mProgram, "te_ViewMatrix"))
, mLastView()
, mModel(model)
{
glUseProgram(mProgram);
GLint projectionMatrixLocation = glGetUniformLocation(mProgram, "te_ProjectionMatrix");
if (projectionMatrixLocation == -1) { throw std::runtime_error("te_ProjectionMatrix: not a valid program variable."); }
glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, glm::value_ptr(projection));
if (mViewLocation == -1) { throw std::runtime_error{ "te_ViewMatrix: not a valid program variable." }; }
glUniformMatrix4fv(mViewLocation, 1, GL_FALSE, glm::value_ptr(mLastView));
GLint modelMatrixLocation = glGetUniformLocation(mProgram, "te_ModelMatrix");
if (modelMatrixLocation == -1) { throw std::runtime_error("te_ModelMatrix: not a valid program variable."); }
glUniformMatrix4fv(modelMatrixLocation, 1, GL_FALSE, glm::value_ptr(model));
}
void Shader::destroy()
{
glDeleteProgram(mProgram);
}
Shader::~Shader()
{
destroy();
}
Shader::Shader(Shader&& o)
: mProgram(o.mProgram)
, mLastView(o.mLastView)
{
o.mProgram = 0;
}
Shader& Shader::operator=(Shader&& o)
{
destroy();
mProgram = o.mProgram;
mLastView = o.mLastView;
o.mProgram = 0;
return *this;
}
glm::mat4 Shader::getModel() const
{
return mModel;
}
void Shader::draw(const glm::mat4& view, const Mesh& mesh)
{
glUseProgram(mProgram);
if (view != mLastView) {
glUniformMatrix4fv(mViewLocation, 1, GL_FALSE, glm::value_ptr(view));
mLastView = view;
}
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mesh.getTexture(0)->getID());
glBindVertexArray(mesh.getVAO());
glDrawElements(GL_TRIANGLES, mesh.getElementCount(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
glUseProgram(0);
}
}
<commit_msg>Add "assets/" to shader path<commit_after>#include "shader.h"
#include "mesh.h"
#include "texture.h"
#include <glm/gtc/type_ptr.hpp>
#include <stdexcept>
#include <fstream>
namespace te
{
std::string getShaderLog(GLuint shader)
{
if (!glIsShader(shader))
{
throw std::runtime_error("Passed ID is not a shader.");
}
int infoLogLength = 0;
int maxLength = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
char* infoLog = new char[maxLength];
glGetShaderInfoLog(shader, maxLength, &infoLogLength, infoLog);
if (infoLogLength > 0)
{
std::string log{ infoLog };
delete[] infoLog;
return log;
}
else
{
return{ "" };
}
}
std::string getProgramLog(GLuint program)
{
if (!glIsProgram(program))
{
throw std::runtime_error("Passed ID is not a program.");
}
int infoLogLength = 0;
int maxLength = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength);
char* infoLog = new char[maxLength];
glGetProgramInfoLog(program, maxLength, &infoLogLength, infoLog);
if (infoLogLength > 0)
{
std::string log{ infoLog };
delete[] infoLog;
return log;
}
else
{
return{ "" };
}
}
GLuint loadShader(const std::string& path, GLenum shaderType)
{
GLuint shaderID = 0;
std::string shaderString;
std::ifstream srcFile(path.c_str());
if (!srcFile) { throw std::runtime_error("Unable to open file."); }
shaderString.assign(std::istreambuf_iterator<char>(srcFile), std::istreambuf_iterator<char>());
shaderID = glCreateShader(shaderType);
const GLchar* shaderSrc = shaderString.c_str();
glShaderSource(shaderID, 1, (const GLchar**)&shaderSrc, NULL);
glCompileShader(shaderID);
GLint shaderCompiled = GL_FALSE;
glGetShaderiv(shaderID, GL_COMPILE_STATUS, &shaderCompiled);
if (shaderCompiled != GL_TRUE)
{
std::string msg{ getShaderLog(shaderID) };
glDeleteShader(shaderID);
throw std::runtime_error(msg);
}
return shaderID;
}
GLuint loadProgram(const std::string& vertexShaderPath, const std::string& fragmentShaderPath)
{
GLuint program = glCreateProgram();
GLuint vertexShader = 0;
GLuint fragmentShader = 0;
try
{
vertexShader = loadShader(vertexShaderPath, GL_VERTEX_SHADER);
glAttachShader(program, vertexShader);
fragmentShader = loadShader(fragmentShaderPath, GL_FRAGMENT_SHADER);
glAttachShader(program, fragmentShader);
glLinkProgram(program);
GLint programSuccess = GL_TRUE;
glGetProgramiv(program, GL_LINK_STATUS, &programSuccess);
if (programSuccess != GL_TRUE)
{
throw std::runtime_error(getProgramLog(program));
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
}
catch (std::exception e)
{
glDeleteProgram(program);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
throw std::runtime_error(e.what());
}
return program;
}
Shader::Shader(const glm::mat4& projection, const glm::mat4& model)
: mProgram(loadProgram("assets/shaders/basic.glvs", "assets/shaders/basic.glfs"))
, mViewLocation(glGetUniformLocation(mProgram, "te_ViewMatrix"))
, mLastView()
, mModel(model)
{
glUseProgram(mProgram);
GLint projectionMatrixLocation = glGetUniformLocation(mProgram, "te_ProjectionMatrix");
if (projectionMatrixLocation == -1) { throw std::runtime_error("te_ProjectionMatrix: not a valid program variable."); }
glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, glm::value_ptr(projection));
if (mViewLocation == -1) { throw std::runtime_error{ "te_ViewMatrix: not a valid program variable." }; }
glUniformMatrix4fv(mViewLocation, 1, GL_FALSE, glm::value_ptr(mLastView));
GLint modelMatrixLocation = glGetUniformLocation(mProgram, "te_ModelMatrix");
if (modelMatrixLocation == -1) { throw std::runtime_error("te_ModelMatrix: not a valid program variable."); }
glUniformMatrix4fv(modelMatrixLocation, 1, GL_FALSE, glm::value_ptr(model));
}
void Shader::destroy()
{
glDeleteProgram(mProgram);
}
Shader::~Shader()
{
destroy();
}
Shader::Shader(Shader&& o)
: mProgram(o.mProgram)
, mLastView(o.mLastView)
{
o.mProgram = 0;
}
Shader& Shader::operator=(Shader&& o)
{
destroy();
mProgram = o.mProgram;
mLastView = o.mLastView;
o.mProgram = 0;
return *this;
}
glm::mat4 Shader::getModel() const
{
return mModel;
}
void Shader::draw(const glm::mat4& view, const Mesh& mesh)
{
glUseProgram(mProgram);
if (view != mLastView) {
glUniformMatrix4fv(mViewLocation, 1, GL_FALSE, glm::value_ptr(view));
mLastView = view;
}
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mesh.getTexture(0)->getID());
glBindVertexArray(mesh.getVAO());
glDrawElements(GL_TRIANGLES, mesh.getElementCount(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
glUseProgram(0);
}
}
<|endoftext|> |
<commit_before>
// Camera.cpp
// InternetMap
//
#include "Camera.hpp"
#include <stdlib.h>
static const float MOVE_TIME = 1.0f;
static const float MIN_ZOOM = -10.0f;
//we need a bound on the max. zoom because on small nodes the calculated max puts the target behind the camera.
//this might be a bug in targeting...?
static const float MAX_MAX_ZOOM = -0.2f;
// TODO: better way to register this
void cameraMoveFinishedCallback(void);
Camera::Camera() :
_displayWidth(0.0f),
_displayHeight(0.0f),
_target(0.0f, 0.0f, 0.0f),
_isMovingToTarget(false),
_allowIdleAnimation(false),
_rotation(0.0f),
_zoom(-3.0f),
_maxZoom(MAX_MAX_ZOOM),
_targetMoveStartTime(MAXFLOAT),
_targetMoveStartPosition(0.0f, 0.0f, 0.0f),
_zoomStart(0.0f),
_zoomTarget(0.0f),
_zoomStartTime(0.0f),
_zoomDuration(0.0f),
_updateTime(0.0f),
_idleStartTime(0.0f),
_panEndTime(0.0f),
_zoomVelocity(0.0f),
_zoomEndTime(0.0f),
_rotationVelocity(0.0f),
_rotationEndTime(0.0f),
_rotationStartTime(0.0f),
_rotationDuration(0.0f),
_subregionX(0.0f),
_subregionY(0.0f),
_subregionWidth(1.0f),
_subregionHeight(1.0f)
{
_rotationMatrix = Matrix4::identity();
_panVelocity.x = 0.0f;
_panVelocity.y = 0.0f;
}
static const float NEAR_PLANE = 0.1f;
static const float FAR_PLANE = 100.0f;
void Camera::update(TimeInterval currentTime) {
TimeInterval delta = currentTime - _updateTime;
_updateTime = currentTime;
handleIdleMovement(delta);
handleMomentumPan(delta);
handleMomentumZoom(delta);
handleMomentumRotation(delta);
Vector3 currentTarget = calculateMoveTarget(delta);
handleAnimatedZoom(delta);
handleAnimatedRotation(delta);
float aspect = fabsf(_displayWidth / _displayHeight);
Matrix4 model = _rotationMatrix * Matrix4::translation(Vector3(-currentTarget.getX(), -currentTarget.getY(), -currentTarget.getZ()));
Matrix4 view = Matrix4::translation(Vector3(0.0f, 0.0f, _zoom));
Matrix4 modelView = view * model;
Matrix4 projectionMatrix;
if((_subregionX == 0.0f) && (_subregionY == 0.0f) && (_subregionWidth == 1.0f) && (_subregionHeight == 1.0f)) {
projectionMatrix = Matrix4::perspective(DegreesToRadians(65.0f), aspect, NEAR_PLANE, FAR_PLANE);
}
else {
float halfX = (float)tan( double( DegreesToRadians(65.0f) * 0.5 ) ) * NEAR_PLANE;
float halfY = halfX / aspect;
projectionMatrix = Matrix4::frustum(-halfX + (_subregionX * halfX * 2),
-halfX + (_subregionX * halfX * 2) + (_subregionWidth * halfX * 2),
-halfY + (_subregionY * halfY * 2),
-halfY + (_subregionY * halfY * 2) + (_subregionHeight * halfY * 2),
NEAR_PLANE, FAR_PLANE);
}
_projectionMatrix = projectionMatrix;
_modelViewMatrix = modelView;
_modelViewProjectionMatrix = projectionMatrix * modelView;
}
void Camera::handleIdleMovement(TimeInterval delta) {
// Rotate camera if idle
TimeInterval idleTime = _updateTime - _idleStartTime;
float idleDelay = 0.1;
if (_allowIdleAnimation && (idleTime > idleDelay)) {
// Ease in
float spinupFactor = fminf(1.0, (idleTime - idleDelay) / 2);
rotateRadiansX(0.0006 * spinupFactor);
rotateRadiansY(0.0001 * spinupFactor);
}
}
void Camera::handleMomentumPan(TimeInterval delta) {
//momentum panning
if (_panVelocity.x != 0 && _panVelocity.y != 0) {
TimeInterval rotationTime = _updateTime-_panEndTime;
static TimeInterval totalTime = 1.0;
float timeT = rotationTime / totalTime;
if(timeT > 1.0) {
_panVelocity.x = _panVelocity.y = 0.0f;
}
else {
//quadratic ease out
float positionT = 1+(timeT*timeT-2.0f*timeT);
rotateRadiansX(_panVelocity.x*delta*positionT);
rotateRadiansY(_panVelocity.y*delta*positionT);
}
}
}
void Camera::handleMomentumZoom(TimeInterval delta) {
//momentum zooming
if (_zoomVelocity != 0) {
static TimeInterval totalTime = 0.5;
TimeInterval zoomTime = _updateTime-_zoomEndTime;
float timeT = zoomTime / totalTime;
if(timeT > 1.0) {
_zoomVelocity = 0;
}
else {
//quadratic ease out
float positionT = 1+(timeT*timeT-2.0f*timeT);
zoomByScale(_zoomVelocity*delta*positionT);
}
}
}
void Camera::handleMomentumRotation(TimeInterval delta) {
//momentum rotation
if (_rotationVelocity != 0) {
TimeInterval rotationTime = _updateTime-_rotationEndTime;
static TimeInterval totalTime = 1.0;
float timeT = rotationTime / totalTime;
if(timeT > 1.0) {
_rotationVelocity = 0;
}
else {
//quadratic ease out
float positionT = 1+(timeT*timeT-2.0f*timeT);
rotateRadiansZ(_rotationVelocity*delta*positionT);
}
}
}
void Camera::handleAnimatedZoom(TimeInterval delta) {
//animated zoom
if(_zoomStartTime < _updateTime) {
float timeT = (_updateTime - _zoomStartTime) / _zoomDuration;
if(timeT > 1.0f) {
_zoomStartTime = MAXFLOAT;
}
else {
float positionT;
// Quadratic ease-in / ease-out
if (timeT < 0.5f)
{
positionT = timeT * timeT * 2;
}
else {
positionT = 1.0f - ((timeT - 1.0f) * (timeT - 1.0f) * 2.0f);
}
_zoom = _zoomStart + (_zoomTarget-_zoomStart)*positionT;
}
}
}
void Camera::handleAnimatedRotation(TimeInterval delta) {
//animated rotation
if (_rotationStartTime < _updateTime) {
float timeT = (_updateTime - _rotationStartTime) / _rotationDuration;
if(timeT > 1.0f) {
_rotationStartTime = MAXFLOAT;
}
else {
float positionT;
// Quadratic ease-in / ease-out
if (timeT < 0.5f)
{
positionT = timeT * timeT * 2;
}
else {
positionT = 1.0f - ((timeT - 1.0f) * (timeT - 1.0f) * 2.0f);
}
_rotationMatrix = Matrix4(Vectormath::Aos::slerp(positionT, _rotationStart , _rotationTarget), Vector3(0.0f, 0.0f, 0.0f));
}
}
}
Vector3 Camera::calculateMoveTarget(TimeInterval delta) {
Vector3 currentTarget;
//animated move to target
if(_targetMoveStartTime < _updateTime) {
float timeT = (_updateTime - _targetMoveStartTime) / MOVE_TIME;
if(timeT > 1.0f) {
currentTarget = _target;
_targetMoveStartTime = MAXFLOAT;
_isMovingToTarget = false;
cameraMoveFinishedCallback();
}
else {
float positionT;
// Quadratic ease-in / ease-out
if (timeT < 0.5f)
{
positionT = timeT * timeT * 2;
}
else {
positionT = 1.0f - ((timeT - 1.0f) * (timeT - 1.0f) * 2.0f);
}
currentTarget = _targetMoveStartPosition + ((_target - _targetMoveStartPosition) * positionT);
}
}
else {
currentTarget = _target;
}
return currentTarget;
}
void Camera::setRotationAndRenormalize(const Matrix4& matrix) {
_rotationMatrix = matrix;
// Becasue we are doing sucessive modification of the rotation matrix, error can accumulate
// Here we renormalize the matrix to make sure that the error doesn't grow
Vector3 zAxis = Vectormath::Aos::normalize(_rotationMatrix.getCol2().getXYZ());
_rotationMatrix.setCol0(Vector4(Vectormath::Aos::normalize(Vectormath::Aos::cross(_rotationMatrix.getCol1().getXYZ(), zAxis)), 0.0f));
_rotationMatrix.setCol1(Vector4(Vectormath::Aos::normalize(Vectormath::Aos::cross(zAxis, _rotationMatrix.getCol0().getXYZ())), 0.0f));
_rotationMatrix.setCol2(Vector4(zAxis, 0.0f));
}
float Camera::currentZoom(void) {
return _zoom;
}
Matrix4 Camera::currentModelViewProjection(void) {
return _modelViewProjectionMatrix;
}
Matrix4 Camera::currentModelView(void) {
return _modelViewMatrix;
}
Matrix4 Camera::currentProjection(void) {
return _projectionMatrix;
}
Vector3 Camera::cameraInObjectSpace(void) {
Matrix4 invertedModelViewMatrix = Vectormath::Aos::inverse(_modelViewMatrix);
return invertedModelViewMatrix.getTranslation();
}
Vector3 Camera::applyModelViewToPoint(Vector2 point) {
Vector4 vec4FromPoint(point.x, point.y, -0.1, 1);
Matrix4 invertedModelViewProjectionMatrix = Vectormath::Aos::inverse(_modelViewProjectionMatrix);
vec4FromPoint = invertedModelViewProjectionMatrix * vec4FromPoint;
vec4FromPoint = vec4FromPoint / vec4FromPoint.getW();
return Vector3(vec4FromPoint.getX(), vec4FromPoint.getY(), vec4FromPoint.getZ());
}
void Camera::rotateRadiansX(float rotate) {
setRotationAndRenormalize(Matrix4::rotation(rotate, Vector3(0.0f, 1.0f, 0.0f)) * _rotationMatrix);
}
void Camera::rotateRadiansY(float rotate) {
setRotationAndRenormalize(Matrix4::rotation(rotate, Vector3(1.0f, 0.0f, 0.0f)) * _rotationMatrix);
}
void Camera::rotateRadiansZ(float rotate) {
setRotationAndRenormalize(_rotationMatrix = Matrix4::rotation(rotate, Vector3(0.0f, 0.0f, 1.0f)) * _rotationMatrix);
}
void Camera::rotateAnimated(Matrix4 rotation, TimeInterval duration) {
_rotationStart = Quaternion(_rotationMatrix.getUpper3x3());
_rotationTarget = Quaternion(rotation.getUpper3x3());
_rotationStartTime = _updateTime;
_rotationDuration = duration;
}
void Camera::zoomByScale(float zoom) {
_zoom += zoom * -_zoom;
if(_zoom > _maxZoom) {
_zoom = _maxZoom;
}
if(_zoom < MIN_ZOOM) {
_zoom = MIN_ZOOM;
}
}
void Camera::zoomAnimated(float zoom, TimeInterval duration) {
if(zoom > _maxZoom) {
zoom = _maxZoom;
}
if(zoom < MIN_ZOOM) {
zoom = MIN_ZOOM;
}
_zoomStart = _zoom;
_zoomTarget = zoom;
_zoomStartTime = _updateTime;
_zoomDuration = duration;
}
void Camera::setTarget(const Target& target) {
_targetMoveStartPosition = _target;
_target = target.vector;
_targetMoveStartTime = _updateTime;
_isMovingToTarget = true;
_maxZoom = target.maxZoom;
if (_maxZoom > MAX_MAX_ZOOM) {
_maxZoom = MAX_MAX_ZOOM;
}
zoomAnimated(target.zoom, MOVE_TIME);
}
void Camera::startMomentumPanWithVelocity(Vector2 velocity) {
_panEndTime = _updateTime;
_panVelocity = velocity;
}
void Camera::stopMomentumPan(void) {
_panVelocity.x = _panVelocity.y = 0.0f;
}
void Camera::startMomentumZoomWithVelocity(float velocity) {
_zoomEndTime = _updateTime;
_zoomVelocity = velocity*0.5;
}
void Camera::stopMomentumZoom(void) {
_zoomVelocity = 0;
}
void Camera::startMomentumRotationWithVelocity(float velocity) {
_rotationVelocity = velocity;
_rotationEndTime = _updateTime;
}
void Camera::stopMomentumRotation(void) {
_rotationVelocity = 0;
}
void Camera::resetIdleTimer() {
_idleStartTime = _updateTime;
}
void Camera::setViewSubregion(float x, float y, float w, float h) {
_subregionX = x;
_subregionY = y;
_subregionWidth = w;
_subregionHeight = h;
}
float Camera::getSubregionScale(void) {
return 1.0f / _subregionWidth;
}
<commit_msg>Tweak near plane and zoom clamping to allow getting closer to small nodes. Fixes #93.<commit_after>
// Camera.cpp
// InternetMap
//
#include "Camera.hpp"
#include <stdlib.h>
static const float MOVE_TIME = 1.0f;
static const float MIN_ZOOM = -10.0f;
//we need a bound on the max. zoom because on small nodes the calculated max puts the target behind the camera.
//this might be a bug in targeting...?
static const float MAX_MAX_ZOOM = -0.06f;
// TODO: better way to register this
void cameraMoveFinishedCallback(void);
Camera::Camera() :
_displayWidth(0.0f),
_displayHeight(0.0f),
_target(0.0f, 0.0f, 0.0f),
_isMovingToTarget(false),
_allowIdleAnimation(false),
_rotation(0.0f),
_zoom(-3.0f),
_maxZoom(MAX_MAX_ZOOM),
_targetMoveStartTime(MAXFLOAT),
_targetMoveStartPosition(0.0f, 0.0f, 0.0f),
_zoomStart(0.0f),
_zoomTarget(0.0f),
_zoomStartTime(0.0f),
_zoomDuration(0.0f),
_updateTime(0.0f),
_idleStartTime(0.0f),
_panEndTime(0.0f),
_zoomVelocity(0.0f),
_zoomEndTime(0.0f),
_rotationVelocity(0.0f),
_rotationEndTime(0.0f),
_rotationStartTime(0.0f),
_rotationDuration(0.0f),
_subregionX(0.0f),
_subregionY(0.0f),
_subregionWidth(1.0f),
_subregionHeight(1.0f)
{
_rotationMatrix = Matrix4::identity();
_panVelocity.x = 0.0f;
_panVelocity.y = 0.0f;
}
static const float NEAR_PLANE = 0.05f;
static const float FAR_PLANE = 100.0f;
void Camera::update(TimeInterval currentTime) {
TimeInterval delta = currentTime - _updateTime;
_updateTime = currentTime;
handleIdleMovement(delta);
handleMomentumPan(delta);
handleMomentumZoom(delta);
handleMomentumRotation(delta);
Vector3 currentTarget = calculateMoveTarget(delta);
handleAnimatedZoom(delta);
handleAnimatedRotation(delta);
float aspect = fabsf(_displayWidth / _displayHeight);
Matrix4 model = _rotationMatrix * Matrix4::translation(Vector3(-currentTarget.getX(), -currentTarget.getY(), -currentTarget.getZ()));
Matrix4 view = Matrix4::translation(Vector3(0.0f, 0.0f, _zoom));
Matrix4 modelView = view * model;
Matrix4 projectionMatrix;
if((_subregionX == 0.0f) && (_subregionY == 0.0f) && (_subregionWidth == 1.0f) && (_subregionHeight == 1.0f)) {
projectionMatrix = Matrix4::perspective(DegreesToRadians(65.0f), aspect, NEAR_PLANE, FAR_PLANE);
}
else {
float halfX = (float)tan( double( DegreesToRadians(65.0f) * 0.5 ) ) * NEAR_PLANE;
float halfY = halfX / aspect;
projectionMatrix = Matrix4::frustum(-halfX + (_subregionX * halfX * 2),
-halfX + (_subregionX * halfX * 2) + (_subregionWidth * halfX * 2),
-halfY + (_subregionY * halfY * 2),
-halfY + (_subregionY * halfY * 2) + (_subregionHeight * halfY * 2),
NEAR_PLANE, FAR_PLANE);
}
_projectionMatrix = projectionMatrix;
_modelViewMatrix = modelView;
_modelViewProjectionMatrix = projectionMatrix * modelView;
}
void Camera::handleIdleMovement(TimeInterval delta) {
// Rotate camera if idle
TimeInterval idleTime = _updateTime - _idleStartTime;
float idleDelay = 0.1;
if (_allowIdleAnimation && (idleTime > idleDelay)) {
// Ease in
float spinupFactor = fminf(1.0, (idleTime - idleDelay) / 2);
rotateRadiansX(0.0006 * spinupFactor);
rotateRadiansY(0.0001 * spinupFactor);
}
}
void Camera::handleMomentumPan(TimeInterval delta) {
//momentum panning
if (_panVelocity.x != 0 && _panVelocity.y != 0) {
TimeInterval rotationTime = _updateTime-_panEndTime;
static TimeInterval totalTime = 1.0;
float timeT = rotationTime / totalTime;
if(timeT > 1.0) {
_panVelocity.x = _panVelocity.y = 0.0f;
}
else {
//quadratic ease out
float positionT = 1+(timeT*timeT-2.0f*timeT);
rotateRadiansX(_panVelocity.x*delta*positionT);
rotateRadiansY(_panVelocity.y*delta*positionT);
}
}
}
void Camera::handleMomentumZoom(TimeInterval delta) {
//momentum zooming
if (_zoomVelocity != 0) {
static TimeInterval totalTime = 0.5;
TimeInterval zoomTime = _updateTime-_zoomEndTime;
float timeT = zoomTime / totalTime;
if(timeT > 1.0) {
_zoomVelocity = 0;
}
else {
//quadratic ease out
float positionT = 1+(timeT*timeT-2.0f*timeT);
zoomByScale(_zoomVelocity*delta*positionT);
}
}
}
void Camera::handleMomentumRotation(TimeInterval delta) {
//momentum rotation
if (_rotationVelocity != 0) {
TimeInterval rotationTime = _updateTime-_rotationEndTime;
static TimeInterval totalTime = 1.0;
float timeT = rotationTime / totalTime;
if(timeT > 1.0) {
_rotationVelocity = 0;
}
else {
//quadratic ease out
float positionT = 1+(timeT*timeT-2.0f*timeT);
rotateRadiansZ(_rotationVelocity*delta*positionT);
}
}
}
void Camera::handleAnimatedZoom(TimeInterval delta) {
//animated zoom
if(_zoomStartTime < _updateTime) {
float timeT = (_updateTime - _zoomStartTime) / _zoomDuration;
if(timeT > 1.0f) {
_zoomStartTime = MAXFLOAT;
}
else {
float positionT;
// Quadratic ease-in / ease-out
if (timeT < 0.5f)
{
positionT = timeT * timeT * 2;
}
else {
positionT = 1.0f - ((timeT - 1.0f) * (timeT - 1.0f) * 2.0f);
}
_zoom = _zoomStart + (_zoomTarget-_zoomStart)*positionT;
}
}
}
void Camera::handleAnimatedRotation(TimeInterval delta) {
//animated rotation
if (_rotationStartTime < _updateTime) {
float timeT = (_updateTime - _rotationStartTime) / _rotationDuration;
if(timeT > 1.0f) {
_rotationStartTime = MAXFLOAT;
}
else {
float positionT;
// Quadratic ease-in / ease-out
if (timeT < 0.5f)
{
positionT = timeT * timeT * 2;
}
else {
positionT = 1.0f - ((timeT - 1.0f) * (timeT - 1.0f) * 2.0f);
}
_rotationMatrix = Matrix4(Vectormath::Aos::slerp(positionT, _rotationStart , _rotationTarget), Vector3(0.0f, 0.0f, 0.0f));
}
}
}
Vector3 Camera::calculateMoveTarget(TimeInterval delta) {
Vector3 currentTarget;
//animated move to target
if(_targetMoveStartTime < _updateTime) {
float timeT = (_updateTime - _targetMoveStartTime) / MOVE_TIME;
if(timeT > 1.0f) {
currentTarget = _target;
_targetMoveStartTime = MAXFLOAT;
_isMovingToTarget = false;
cameraMoveFinishedCallback();
}
else {
float positionT;
// Quadratic ease-in / ease-out
if (timeT < 0.5f)
{
positionT = timeT * timeT * 2;
}
else {
positionT = 1.0f - ((timeT - 1.0f) * (timeT - 1.0f) * 2.0f);
}
currentTarget = _targetMoveStartPosition + ((_target - _targetMoveStartPosition) * positionT);
}
}
else {
currentTarget = _target;
}
return currentTarget;
}
void Camera::setRotationAndRenormalize(const Matrix4& matrix) {
_rotationMatrix = matrix;
// Becasue we are doing sucessive modification of the rotation matrix, error can accumulate
// Here we renormalize the matrix to make sure that the error doesn't grow
Vector3 zAxis = Vectormath::Aos::normalize(_rotationMatrix.getCol2().getXYZ());
_rotationMatrix.setCol0(Vector4(Vectormath::Aos::normalize(Vectormath::Aos::cross(_rotationMatrix.getCol1().getXYZ(), zAxis)), 0.0f));
_rotationMatrix.setCol1(Vector4(Vectormath::Aos::normalize(Vectormath::Aos::cross(zAxis, _rotationMatrix.getCol0().getXYZ())), 0.0f));
_rotationMatrix.setCol2(Vector4(zAxis, 0.0f));
}
float Camera::currentZoom(void) {
return _zoom;
}
Matrix4 Camera::currentModelViewProjection(void) {
return _modelViewProjectionMatrix;
}
Matrix4 Camera::currentModelView(void) {
return _modelViewMatrix;
}
Matrix4 Camera::currentProjection(void) {
return _projectionMatrix;
}
Vector3 Camera::cameraInObjectSpace(void) {
Matrix4 invertedModelViewMatrix = Vectormath::Aos::inverse(_modelViewMatrix);
return invertedModelViewMatrix.getTranslation();
}
Vector3 Camera::applyModelViewToPoint(Vector2 point) {
Vector4 vec4FromPoint(point.x, point.y, -0.1, 1);
Matrix4 invertedModelViewProjectionMatrix = Vectormath::Aos::inverse(_modelViewProjectionMatrix);
vec4FromPoint = invertedModelViewProjectionMatrix * vec4FromPoint;
vec4FromPoint = vec4FromPoint / vec4FromPoint.getW();
return Vector3(vec4FromPoint.getX(), vec4FromPoint.getY(), vec4FromPoint.getZ());
}
void Camera::rotateRadiansX(float rotate) {
setRotationAndRenormalize(Matrix4::rotation(rotate, Vector3(0.0f, 1.0f, 0.0f)) * _rotationMatrix);
}
void Camera::rotateRadiansY(float rotate) {
setRotationAndRenormalize(Matrix4::rotation(rotate, Vector3(1.0f, 0.0f, 0.0f)) * _rotationMatrix);
}
void Camera::rotateRadiansZ(float rotate) {
setRotationAndRenormalize(_rotationMatrix = Matrix4::rotation(rotate, Vector3(0.0f, 0.0f, 1.0f)) * _rotationMatrix);
}
void Camera::rotateAnimated(Matrix4 rotation, TimeInterval duration) {
_rotationStart = Quaternion(_rotationMatrix.getUpper3x3());
_rotationTarget = Quaternion(rotation.getUpper3x3());
_rotationStartTime = _updateTime;
_rotationDuration = duration;
}
void Camera::zoomByScale(float zoom) {
_zoom += zoom * -_zoom;
if(_zoom > _maxZoom) {
_zoom = _maxZoom;
}
if(_zoom < MIN_ZOOM) {
_zoom = MIN_ZOOM;
}
}
void Camera::zoomAnimated(float zoom, TimeInterval duration) {
if(zoom > _maxZoom) {
zoom = _maxZoom;
}
if(zoom < MIN_ZOOM) {
zoom = MIN_ZOOM;
}
_zoomStart = _zoom;
_zoomTarget = zoom;
_zoomStartTime = _updateTime;
_zoomDuration = duration;
}
void Camera::setTarget(const Target& target) {
_targetMoveStartPosition = _target;
_target = target.vector;
_targetMoveStartTime = _updateTime;
_isMovingToTarget = true;
_maxZoom = target.maxZoom;
if (_maxZoom > MAX_MAX_ZOOM) {
_maxZoom = MAX_MAX_ZOOM;
}
zoomAnimated(target.zoom, MOVE_TIME);
}
void Camera::startMomentumPanWithVelocity(Vector2 velocity) {
_panEndTime = _updateTime;
_panVelocity = velocity;
}
void Camera::stopMomentumPan(void) {
_panVelocity.x = _panVelocity.y = 0.0f;
}
void Camera::startMomentumZoomWithVelocity(float velocity) {
_zoomEndTime = _updateTime;
_zoomVelocity = velocity*0.5;
}
void Camera::stopMomentumZoom(void) {
_zoomVelocity = 0;
}
void Camera::startMomentumRotationWithVelocity(float velocity) {
_rotationVelocity = velocity;
_rotationEndTime = _updateTime;
}
void Camera::stopMomentumRotation(void) {
_rotationVelocity = 0;
}
void Camera::resetIdleTimer() {
_idleStartTime = _updateTime;
}
void Camera::setViewSubregion(float x, float y, float w, float h) {
_subregionX = x;
_subregionY = y;
_subregionWidth = w;
_subregionHeight = h;
}
float Camera::getSubregionScale(void) {
return 1.0f / _subregionWidth;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkScalarsToColors.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 AUTHORS 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 <math.h>
#include "vtkScalarsToColors.h"
#include "vtkScalars.h"
// do not use SetMacro() because we do not the table to rebuild.
void vtkScalarsToColors::SetAlpha(float alpha)
{
this->Alpha = (alpha < 0.0 ? 0.0 : (alpha > 1.0 ? 1.0 : alpha));
}
vtkUnsignedCharArray *vtkScalarsToColors::MapScalars(vtkDataArray *scalars,
int colorMode, int comp)
{
vtkUnsignedCharArray *newColors;
vtkUnsignedCharArray *colors;
// map scalars through lookup table only if needed
if ( colorMode == VTK_COLOR_MODE_DEFAULT &&
(colors=vtkUnsignedCharArray::SafeDownCast(scalars)) != NULL )
{
newColors = this->
ConvertUnsignedCharToRGBA(colors, colors->GetNumberOfComponents(),
scalars->GetNumberOfTuples());
}
else
{
newColors = vtkUnsignedCharArray::New();
newColors->SetNumberOfComponents(4);
newColors->SetNumberOfTuples(scalars->GetNumberOfTuples());
newColors->Register(this);
this->
MapScalarsThroughTable2(scalars->GetVoidPointer(comp),
newColors->GetPointer(0),
scalars->GetDataType(),
scalars->GetNumberOfTuples(),
scalars->GetNumberOfComponents(),
VTK_RGBA);
}//need to map
return newColors;
}
// Map a set of scalar values through the table
void vtkScalarsToColors::MapScalarsThroughTable(vtkScalars *scalars,
unsigned char *output,
int outputFormat)
{
switch (outputFormat)
{
case VTK_RGBA:
case VTK_RGB:
case VTK_LUMINANCE_ALPHA:
case VTK_LUMINANCE:
break;
default:
vtkErrorMacro(<< "MapScalarsThroughTable: unrecognized color format");
break;
}
this->MapScalarsThroughTable2(scalars->GetVoidPointer(0),
output,
scalars->GetDataType(),
scalars->GetNumberOfScalars(),
scalars->GetNumberOfComponents(),
outputFormat);
}
vtkUnsignedCharArray *vtkScalarsToColors::ConvertUnsignedCharToRGBA(
vtkUnsignedCharArray *colors, int numComp, int numTuples)
{
unsigned char *cptr = colors->GetPointer(0);
vtkUnsignedCharArray *newColors = vtkUnsignedCharArray::New();
if ( numComp == 4 && this->Alpha >= 1.0 )
{
newColors->SetArray(cptr, numTuples, 0);
return newColors;
}
newColors->SetNumberOfComponents(4);
newColors->SetNumberOfTuples(numTuples);
unsigned char *nptr = newColors->GetPointer(0);
int i;
if ( this->Alpha >= 1.0 )
{
switch (numComp)
{
case 1:
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr;
*nptr++ = *cptr;
*nptr++ = *cptr++;
*nptr++ = 255;
}
break;
case 2:
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr;
*nptr++ = *cptr;
*nptr++ = *cptr++;
*nptr++ = *cptr++;
}
break;
case 3:
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = 255;
}
break;
default:
vtkErrorMacro(<<"Cannot convert colors");
return NULL;
}
}
else //blending required
{
unsigned char alpha;
switch (numComp)
{
case 1:
alpha = this->Alpha*255;
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr;
*nptr++ = *cptr;
*nptr++ = *cptr++;
*nptr++ = alpha;
}
break;
case 2:
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr;
*nptr++ = *cptr;
*nptr++ = *cptr++;
*nptr++ = (*cptr)*this->Alpha; cptr++;
}
break;
case 3:
alpha = this->Alpha*255;
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = alpha;
}
break;
case 4:
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = (*cptr)*this->Alpha; cptr++;
}
break;
default:
vtkErrorMacro(<<"Cannot convert colors");
return NULL;
}
}
return newColors;
}
<commit_msg>ERR:Fixed memory leak<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkScalarsToColors.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 AUTHORS 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 <math.h>
#include "vtkScalarsToColors.h"
#include "vtkScalars.h"
// do not use SetMacro() because we do not the table to rebuild.
void vtkScalarsToColors::SetAlpha(float alpha)
{
this->Alpha = (alpha < 0.0 ? 0.0 : (alpha > 1.0 ? 1.0 : alpha));
}
vtkUnsignedCharArray *vtkScalarsToColors::MapScalars(vtkDataArray *scalars,
int colorMode, int comp)
{
vtkUnsignedCharArray *newColors;
vtkUnsignedCharArray *colors;
// map scalars through lookup table only if needed
if ( colorMode == VTK_COLOR_MODE_DEFAULT &&
(colors=vtkUnsignedCharArray::SafeDownCast(scalars)) != NULL )
{
newColors = this->
ConvertUnsignedCharToRGBA(colors, colors->GetNumberOfComponents(),
scalars->GetNumberOfTuples());
}
else
{
newColors = vtkUnsignedCharArray::New();
newColors->SetNumberOfComponents(4);
newColors->SetNumberOfTuples(scalars->GetNumberOfTuples());
this->
MapScalarsThroughTable2(scalars->GetVoidPointer(comp),
newColors->GetPointer(0),
scalars->GetDataType(),
scalars->GetNumberOfTuples(),
scalars->GetNumberOfComponents(),
VTK_RGBA);
}//need to map
return newColors;
}
// Map a set of scalar values through the table
void vtkScalarsToColors::MapScalarsThroughTable(vtkScalars *scalars,
unsigned char *output,
int outputFormat)
{
switch (outputFormat)
{
case VTK_RGBA:
case VTK_RGB:
case VTK_LUMINANCE_ALPHA:
case VTK_LUMINANCE:
break;
default:
vtkErrorMacro(<< "MapScalarsThroughTable: unrecognized color format");
break;
}
this->MapScalarsThroughTable2(scalars->GetVoidPointer(0),
output,
scalars->GetDataType(),
scalars->GetNumberOfScalars(),
scalars->GetNumberOfComponents(),
outputFormat);
}
vtkUnsignedCharArray *vtkScalarsToColors::ConvertUnsignedCharToRGBA(
vtkUnsignedCharArray *colors, int numComp, int numTuples)
{
unsigned char *cptr = colors->GetPointer(0);
vtkUnsignedCharArray *newColors = vtkUnsignedCharArray::New();
if ( numComp == 4 && this->Alpha >= 1.0 )
{
newColors->SetArray(cptr, numTuples, 0);
return newColors;
}
newColors->SetNumberOfComponents(4);
newColors->SetNumberOfTuples(numTuples);
unsigned char *nptr = newColors->GetPointer(0);
int i;
if ( this->Alpha >= 1.0 )
{
switch (numComp)
{
case 1:
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr;
*nptr++ = *cptr;
*nptr++ = *cptr++;
*nptr++ = 255;
}
break;
case 2:
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr;
*nptr++ = *cptr;
*nptr++ = *cptr++;
*nptr++ = *cptr++;
}
break;
case 3:
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = 255;
}
break;
default:
vtkErrorMacro(<<"Cannot convert colors");
return NULL;
}
}
else //blending required
{
unsigned char alpha;
switch (numComp)
{
case 1:
alpha = this->Alpha*255;
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr;
*nptr++ = *cptr;
*nptr++ = *cptr++;
*nptr++ = alpha;
}
break;
case 2:
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr;
*nptr++ = *cptr;
*nptr++ = *cptr++;
*nptr++ = (*cptr)*this->Alpha; cptr++;
}
break;
case 3:
alpha = this->Alpha*255;
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = alpha;
}
break;
case 4:
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = (*cptr)*this->Alpha; cptr++;
}
break;
default:
vtkErrorMacro(<<"Cannot convert colors");
return NULL;
}
}
return newColors;
}
<|endoftext|> |
<commit_before>/**
* @file HOGDescriptor_.cpp
* @brief mex interface for HOGDescriptor
* @author Kota Yamaguchi
* @date 2012
*/
#include "mexopencv.hpp"
using namespace std;
using namespace cv;
namespace {
/// Last object id to allocate
int last_id = 0;
/// Object container
map<int,HOGDescriptor> obj_;
/** HistogramNormType map
*/
const ConstMap<std::string,int> HistogramNormType = ConstMap<std::string,int>
("L2Hys",HOGDescriptor::L2Hys);
/** HistogramNormType inverse map
*/
const ConstMap<int,std::string> InvHistogramNormType = ConstMap<int,std::string>
(HOGDescriptor::L2Hys,"L2Hys");
/// Alias for argument number check
inline void nargchk(bool cond)
{
if (!cond)
mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments");
}
}
/**
* Main entry called from Matlab
* @param nlhs number of left-hand-side arguments
* @param plhs pointers to mxArrays in the left-hand-side
* @param nrhs number of right-hand-side arguments
* @param prhs pointers to mxArrays in the right-hand-side
*/
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
nargchk(nrhs>=2 && nlhs<=2);
vector<MxArray> rhs(prhs,prhs+nrhs);
int id = rhs[0].toInt();
string method(rhs[1].toString());
// Constructor call
if (method == "new") {
nargchk(nlhs<=1);
if (nrhs==3 && rhs[2].isChar())
obj_[++last_id] = HOGDescriptor(rhs[2].toString());
else {
nargchk((nrhs%2)==0);
obj_[++last_id] = HOGDescriptor();
HOGDescriptor& obj = obj_[last_id];
for (int i=2; i<nrhs; i+=2) {
string key(rhs[i].toString());
if (key == "WinSize")
obj.winSize = rhs[i+1].toSize();
else if (key == "BlockSize")
obj.blockSize = rhs[i+1].toSize();
else if (key == "BlockStride")
obj.blockStride = rhs[i+1].toSize();
else if (key == "CellSize")
obj.cellSize = rhs[i+1].toSize();
else if (key == "NBins")
obj.nbins = rhs[i+1].toInt();
else if (key == "DerivAperture")
obj.derivAperture = rhs[i+1].toInt();
else if (key == "WinSigma")
obj.winSigma = rhs[i+1].toDouble();
else if (key == "HistogramNormType")
obj.histogramNormType = HistogramNormType[rhs[i+1].toString()];
else if (key == "L2HysThreshold")
obj.L2HysThreshold = rhs[i+1].toDouble();
else if (key == "GammaCorrection")
obj.gammaCorrection = rhs[i+1].toBool();
else if (key == "NLevels")
obj.nlevels = rhs[i+1].toInt();
else
mexErrMsgIdAndTxt("mexopencv:error","Unknown option %s",key.c_str());
}
}
plhs[0] = MxArray(last_id);
return;
}
// Big operation switch
HOGDescriptor& obj = obj_[id];
if (method == "delete") {
nargchk(nrhs==2 && nlhs==0);
obj_.erase(id);
}
else if (method == "getDescriptorSize") {
nargchk(nrhs==2 && nlhs<=1);
plhs[0] = MxArray(static_cast<int>(obj.getDescriptorSize()));
}
else if (method == "checkDetectorSize") {
nargchk(nrhs==2 && nlhs<=1);
plhs[0] = MxArray(obj.checkDetectorSize());
}
else if (method == "getWinSigma") {
nargchk(nrhs==2 && nlhs<=1);
plhs[0] = MxArray(obj.getWinSigma());
}
else if (method == "setSVMDetector") {
nargchk(nrhs==3 && nlhs==0);
if (rhs[2].isChar()) {
string key(rhs[2].toString());
if (key=="Default")
obj.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector());
else if (key=="Daimler")
obj.setSVMDetector(HOGDescriptor::getDaimlerPeopleDetector());
else
mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option %s", key.c_str());
}
else
obj.setSVMDetector(rhs[2].toVector<float>());
}
else if (method == "load") {
nargchk(nrhs==3 && nlhs<=1);
plhs[0] = MxArray(obj.load(rhs[2].toString()));
}
else if (method == "save") {
nargchk(nrhs==3 && nlhs==0);
obj.save(rhs[2].toString());
}
else if (method == "compute") {
nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs<=1);
Mat img(rhs[2].isUint8() ? rhs[2].toMat() : rhs[2].toMat(CV_32F));
Size winStride;
Size padding;
vector<Point> locations;
for (int i=3; i<nrhs; i+=2) {
string key = rhs[i].toString();
if (key=="WinStride")
winStride = rhs[i+1].toSize();
else if (key=="Padding")
padding = rhs[i+1].toSize();
else if (key=="Locations")
locations = rhs[i+1].toVector<Point>();
else
mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option %s", key.c_str());
}
// Run
vector<float> descriptors;
obj.compute(img,descriptors,winStride,padding,locations);
Mat m(descriptors);
plhs[0] = MxArray(m.reshape(0,m.total()/obj.getDescriptorSize()));
}
else if (method == "detect") {
nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs<=2);
Mat img(rhs[2].isUint8() ? rhs[2].toMat() : rhs[2].toMat(CV_32F));
double hitThreshold=0;
Size winStride;
Size padding;
vector<Point> searchLocations;
for (int i=3; i<nrhs; i+=2) {
string key = rhs[i].toString();
if (key=="HitThreshold")
hitThreshold = rhs[i+1].toDouble();
else if (key=="WinStride")
winStride = rhs[i+1].toSize();
else if (key=="Padding")
padding = rhs[i+1].toSize();
else if (key=="Locations")
searchLocations = rhs[i+1].toVector<Point>();
else
mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option %s", key.c_str());
}
// Run
vector<Point> foundLocations;
vector<double> weights;
obj.detect(img, foundLocations, hitThreshold, winStride,
padding, searchLocations);
plhs[0] = MxArray(foundLocations);
if (nlhs>1)
plhs[1] = MxArray(Mat(weights));
}
else if (method == "detectMultiScale") {
nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs<=2);
Mat img(rhs[2].isUint8() ? rhs[2].toMat() : rhs[2].toMat(CV_32F));
double hitThreshold=0;
Size winStride;
Size padding;
double scale=1.05;
double finalThreshold=2.0;
bool useMeanshiftGrouping = false;
for (int i=3; i<nrhs; i+=2) {
string key = rhs[i].toString();
if (key=="HitThreshold")
hitThreshold = rhs[i+1].toDouble();
else if (key=="WinStride")
winStride = rhs[i+1].toSize();
else if (key=="Padding")
padding = rhs[i+1].toSize();
else if (key=="Scale")
scale = rhs[i+1].toDouble();
else if (key=="FinalThreshold")
finalThreshold = rhs[i+1].toDouble();
else if (key=="UseMeanshiftGrouping")
useMeanshiftGrouping = rhs[i+1].toBool();
else
mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option %s", key.c_str());
}
// Run
vector<Rect> foundLocations;
vector<double> weights;
obj.detectMultiScale(img, foundLocations, weights, hitThreshold, winStride,
padding, scale, finalThreshold, useMeanshiftGrouping);
plhs[0] = MxArray(foundLocations);
if (nlhs>1)
plhs[1] = MxArray(Mat(weights));
}
else if (method == "computeGradient") {
nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs<=2);
Mat img(rhs[2].isUint8() ? rhs[2].toMat() : rhs[2].toMat(CV_32F));
Size paddingTL;
Size paddingBR;
for (int i=3; i<nrhs; i+=2) {
string key = rhs[i].toString();
if (key=="PaddingTR")
paddingTL = rhs[i+1].toSize();
else if (key=="PaddingBR")
paddingBR = rhs[i+1].toSize();
else
mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option %s", key.c_str());
}
// Run
Mat grad, angleOfs;
obj.computeGradient(img,grad,angleOfs,paddingTL,paddingBR);
plhs[0] = MxArray(grad);
if (nlhs>1)
plhs[1] = MxArray(angleOfs);
}
else if (method == "winSize") {
if (nlhs==1 && nrhs==2)
plhs[0] = MxArray(obj.winSize);
else if (nlhs==0 && nrhs==3)
obj.winSize = rhs[2].toSize();
else
nargchk(false);
}
else if (method == "blockSize") {
if (nlhs==1 && nrhs==2)
plhs[0] = MxArray(obj.blockSize);
else if (nlhs==0 && nrhs==3)
obj.blockSize = rhs[2].toSize();
else
nargchk(false);
}
else if (method == "blockStride") {
if (nlhs==1 && nrhs==2)
plhs[0] = MxArray(obj.blockStride);
else if (nlhs==0 && nrhs==3)
obj.blockStride = rhs[2].toSize();
else
nargchk(false);
}
else if (method == "cellSize") {
if (nlhs==1 && nrhs==2)
plhs[0] = MxArray(obj.cellSize);
else if (nlhs==0 && nrhs==3)
obj.cellSize = rhs[2].toSize();
else
nargchk(false);
}
else if (method == "nbins") {
if (nlhs==1 && nrhs==2)
plhs[0] = MxArray(obj.nbins);
else if (nlhs==0 && nrhs==3)
obj.nbins = rhs[2].toInt();
else
nargchk(false);
}
else if (method == "derivAperture") {
if (nlhs==1 && nrhs==2)
plhs[0] = MxArray(obj.derivAperture);
else if (nlhs==0 && nrhs==3)
obj.derivAperture = rhs[2].toInt();
else
nargchk(false);
}
else if (method == "winSigma") {
if (nlhs==1 && nrhs==2)
plhs[0] = MxArray(obj.winSigma);
else if (nlhs==0 && nrhs==3)
obj.winSigma = rhs[2].toDouble();
else
nargchk(false);
}
else if (method == "histogramNormType") {
if (nlhs==1 && nrhs==2)
plhs[0] = MxArray(InvHistogramNormType[obj.histogramNormType]);
else if (nlhs==0 && nrhs==3)
obj.histogramNormType = HistogramNormType[rhs[2].toString()];
else
nargchk(false);
}
else if (method == "L2HysThreshold") {
if (nlhs==1 && nrhs==2)
plhs[0] = MxArray(obj.L2HysThreshold);
else if (nlhs==0 && nrhs==3)
obj.L2HysThreshold = rhs[2].toDouble();
else
nargchk(false);
}
else if (method == "gammaCorrection") {
if (nlhs==1 && nrhs==2)
plhs[0] = MxArray(obj.gammaCorrection);
else if (nlhs==0 && nrhs==3)
obj.gammaCorrection = rhs[2].toBool();
else
nargchk(false);
}
else if (method == "nlevels") {
if (nlhs==1 && nrhs==2)
plhs[0] = MxArray(obj.nlevels);
else if (nlhs==0 && nrhs==3)
obj.nlevels = rhs[2].toInt();
else
nargchk(false);
}
else
mexErrMsgIdAndTxt("mexopencv:error","Unrecognized operation %s", method.c_str());
}
<commit_msg>missing weights argument in detect function<commit_after>/**
* @file HOGDescriptor_.cpp
* @brief mex interface for HOGDescriptor
* @author Kota Yamaguchi
* @date 2012
*/
#include "mexopencv.hpp"
using namespace std;
using namespace cv;
namespace {
/// Last object id to allocate
int last_id = 0;
/// Object container
map<int,HOGDescriptor> obj_;
/** HistogramNormType map
*/
const ConstMap<std::string,int> HistogramNormType = ConstMap<std::string,int>
("L2Hys",HOGDescriptor::L2Hys);
/** HistogramNormType inverse map
*/
const ConstMap<int,std::string> InvHistogramNormType = ConstMap<int,std::string>
(HOGDescriptor::L2Hys,"L2Hys");
/// Alias for argument number check
inline void nargchk(bool cond)
{
if (!cond)
mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments");
}
}
/**
* Main entry called from Matlab
* @param nlhs number of left-hand-side arguments
* @param plhs pointers to mxArrays in the left-hand-side
* @param nrhs number of right-hand-side arguments
* @param prhs pointers to mxArrays in the right-hand-side
*/
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
nargchk(nrhs>=2 && nlhs<=2);
vector<MxArray> rhs(prhs,prhs+nrhs);
int id = rhs[0].toInt();
string method(rhs[1].toString());
// Constructor call
if (method == "new") {
nargchk(nlhs<=1);
if (nrhs==3 && rhs[2].isChar())
obj_[++last_id] = HOGDescriptor(rhs[2].toString());
else {
nargchk((nrhs%2)==0);
obj_[++last_id] = HOGDescriptor();
HOGDescriptor& obj = obj_[last_id];
for (int i=2; i<nrhs; i+=2) {
string key(rhs[i].toString());
if (key == "WinSize")
obj.winSize = rhs[i+1].toSize();
else if (key == "BlockSize")
obj.blockSize = rhs[i+1].toSize();
else if (key == "BlockStride")
obj.blockStride = rhs[i+1].toSize();
else if (key == "CellSize")
obj.cellSize = rhs[i+1].toSize();
else if (key == "NBins")
obj.nbins = rhs[i+1].toInt();
else if (key == "DerivAperture")
obj.derivAperture = rhs[i+1].toInt();
else if (key == "WinSigma")
obj.winSigma = rhs[i+1].toDouble();
else if (key == "HistogramNormType")
obj.histogramNormType = HistogramNormType[rhs[i+1].toString()];
else if (key == "L2HysThreshold")
obj.L2HysThreshold = rhs[i+1].toDouble();
else if (key == "GammaCorrection")
obj.gammaCorrection = rhs[i+1].toBool();
else if (key == "NLevels")
obj.nlevels = rhs[i+1].toInt();
else
mexErrMsgIdAndTxt("mexopencv:error","Unknown option %s",key.c_str());
}
}
plhs[0] = MxArray(last_id);
return;
}
// Big operation switch
HOGDescriptor& obj = obj_[id];
if (method == "delete") {
nargchk(nrhs==2 && nlhs==0);
obj_.erase(id);
}
else if (method == "getDescriptorSize") {
nargchk(nrhs==2 && nlhs<=1);
plhs[0] = MxArray(static_cast<int>(obj.getDescriptorSize()));
}
else if (method == "checkDetectorSize") {
nargchk(nrhs==2 && nlhs<=1);
plhs[0] = MxArray(obj.checkDetectorSize());
}
else if (method == "getWinSigma") {
nargchk(nrhs==2 && nlhs<=1);
plhs[0] = MxArray(obj.getWinSigma());
}
else if (method == "setSVMDetector") {
nargchk(nrhs==3 && nlhs==0);
if (rhs[2].isChar()) {
string key(rhs[2].toString());
if (key=="Default")
obj.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector());
else if (key=="Daimler")
obj.setSVMDetector(HOGDescriptor::getDaimlerPeopleDetector());
else
mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option %s", key.c_str());
}
else
obj.setSVMDetector(rhs[2].toVector<float>());
}
else if (method == "load") {
nargchk(nrhs==3 && nlhs<=1);
plhs[0] = MxArray(obj.load(rhs[2].toString()));
}
else if (method == "save") {
nargchk(nrhs==3 && nlhs==0);
obj.save(rhs[2].toString());
}
else if (method == "compute") {
nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs<=1);
Mat img(rhs[2].isUint8() ? rhs[2].toMat() : rhs[2].toMat(CV_32F));
Size winStride;
Size padding;
vector<Point> locations;
for (int i=3; i<nrhs; i+=2) {
string key = rhs[i].toString();
if (key=="WinStride")
winStride = rhs[i+1].toSize();
else if (key=="Padding")
padding = rhs[i+1].toSize();
else if (key=="Locations")
locations = rhs[i+1].toVector<Point>();
else
mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option %s", key.c_str());
}
// Run
vector<float> descriptors;
obj.compute(img,descriptors,winStride,padding,locations);
Mat m(descriptors);
plhs[0] = MxArray(m.reshape(0,m.total()/obj.getDescriptorSize()));
}
else if (method == "detect") {
nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs<=2);
Mat img(rhs[2].isUint8() ? rhs[2].toMat() : rhs[2].toMat(CV_32F));
double hitThreshold=0;
Size winStride;
Size padding;
vector<Point> searchLocations;
for (int i=3; i<nrhs; i+=2) {
string key = rhs[i].toString();
if (key=="HitThreshold")
hitThreshold = rhs[i+1].toDouble();
else if (key=="WinStride")
winStride = rhs[i+1].toSize();
else if (key=="Padding")
padding = rhs[i+1].toSize();
else if (key=="Locations")
searchLocations = rhs[i+1].toVector<Point>();
else
mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option %s", key.c_str());
}
// Run
vector<Point> foundLocations;
vector<double> weights;
obj.detect(img, foundLocations, weights, hitThreshold, winStride,
padding, searchLocations);
plhs[0] = MxArray(foundLocations);
if (nlhs>1)
plhs[1] = MxArray(Mat(weights));
}
else if (method == "detectMultiScale") {
nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs<=2);
Mat img(rhs[2].isUint8() ? rhs[2].toMat() : rhs[2].toMat(CV_32F));
double hitThreshold=0;
Size winStride;
Size padding;
double scale=1.05;
double finalThreshold=2.0;
bool useMeanshiftGrouping = false;
for (int i=3; i<nrhs; i+=2) {
string key = rhs[i].toString();
if (key=="HitThreshold")
hitThreshold = rhs[i+1].toDouble();
else if (key=="WinStride")
winStride = rhs[i+1].toSize();
else if (key=="Padding")
padding = rhs[i+1].toSize();
else if (key=="Scale")
scale = rhs[i+1].toDouble();
else if (key=="FinalThreshold")
finalThreshold = rhs[i+1].toDouble();
else if (key=="UseMeanshiftGrouping")
useMeanshiftGrouping = rhs[i+1].toBool();
else
mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option %s", key.c_str());
}
// Run
vector<Rect> foundLocations;
vector<double> weights;
obj.detectMultiScale(img, foundLocations, weights, hitThreshold, winStride,
padding, scale, finalThreshold, useMeanshiftGrouping);
plhs[0] = MxArray(foundLocations);
if (nlhs>1)
plhs[1] = MxArray(Mat(weights));
}
else if (method == "computeGradient") {
nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs<=2);
Mat img(rhs[2].isUint8() ? rhs[2].toMat() : rhs[2].toMat(CV_32F));
Size paddingTL;
Size paddingBR;
for (int i=3; i<nrhs; i+=2) {
string key = rhs[i].toString();
if (key=="PaddingTR")
paddingTL = rhs[i+1].toSize();
else if (key=="PaddingBR")
paddingBR = rhs[i+1].toSize();
else
mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option %s", key.c_str());
}
// Run
Mat grad, angleOfs;
obj.computeGradient(img,grad,angleOfs,paddingTL,paddingBR);
plhs[0] = MxArray(grad);
if (nlhs>1)
plhs[1] = MxArray(angleOfs);
}
else if (method == "winSize") {
if (nlhs==1 && nrhs==2)
plhs[0] = MxArray(obj.winSize);
else if (nlhs==0 && nrhs==3)
obj.winSize = rhs[2].toSize();
else
nargchk(false);
}
else if (method == "blockSize") {
if (nlhs==1 && nrhs==2)
plhs[0] = MxArray(obj.blockSize);
else if (nlhs==0 && nrhs==3)
obj.blockSize = rhs[2].toSize();
else
nargchk(false);
}
else if (method == "blockStride") {
if (nlhs==1 && nrhs==2)
plhs[0] = MxArray(obj.blockStride);
else if (nlhs==0 && nrhs==3)
obj.blockStride = rhs[2].toSize();
else
nargchk(false);
}
else if (method == "cellSize") {
if (nlhs==1 && nrhs==2)
plhs[0] = MxArray(obj.cellSize);
else if (nlhs==0 && nrhs==3)
obj.cellSize = rhs[2].toSize();
else
nargchk(false);
}
else if (method == "nbins") {
if (nlhs==1 && nrhs==2)
plhs[0] = MxArray(obj.nbins);
else if (nlhs==0 && nrhs==3)
obj.nbins = rhs[2].toInt();
else
nargchk(false);
}
else if (method == "derivAperture") {
if (nlhs==1 && nrhs==2)
plhs[0] = MxArray(obj.derivAperture);
else if (nlhs==0 && nrhs==3)
obj.derivAperture = rhs[2].toInt();
else
nargchk(false);
}
else if (method == "winSigma") {
if (nlhs==1 && nrhs==2)
plhs[0] = MxArray(obj.winSigma);
else if (nlhs==0 && nrhs==3)
obj.winSigma = rhs[2].toDouble();
else
nargchk(false);
}
else if (method == "histogramNormType") {
if (nlhs==1 && nrhs==2)
plhs[0] = MxArray(InvHistogramNormType[obj.histogramNormType]);
else if (nlhs==0 && nrhs==3)
obj.histogramNormType = HistogramNormType[rhs[2].toString()];
else
nargchk(false);
}
else if (method == "L2HysThreshold") {
if (nlhs==1 && nrhs==2)
plhs[0] = MxArray(obj.L2HysThreshold);
else if (nlhs==0 && nrhs==3)
obj.L2HysThreshold = rhs[2].toDouble();
else
nargchk(false);
}
else if (method == "gammaCorrection") {
if (nlhs==1 && nrhs==2)
plhs[0] = MxArray(obj.gammaCorrection);
else if (nlhs==0 && nrhs==3)
obj.gammaCorrection = rhs[2].toBool();
else
nargchk(false);
}
else if (method == "nlevels") {
if (nlhs==1 && nrhs==2)
plhs[0] = MxArray(obj.nlevels);
else if (nlhs==0 && nrhs==3)
obj.nlevels = rhs[2].toInt();
else
nargchk(false);
}
else
mexErrMsgIdAndTxt("mexopencv:error","Unrecognized operation %s", method.c_str());
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: NeonHeadRequest.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: kz $ $Date: 2006-07-19 09:34:54 $
*
* 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 _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYSTATE_HPP_
#include <com/sun/star/beans/PropertyState.hpp>
#endif
#ifndef _NEONHEADREQUEST_HXX_
#include "NeonHeadRequest.hxx"
#endif
using namespace webdav_ucp;
using namespace com::sun::star;
#if NEON_VERSION >= 0250
static void process_headers(ne_request *req,
DAVResource &rResource,
const std::vector< ::rtl::OUString > &rHeaderNames)
{
void *cursor = NULL;
const char *name, *value;
while ((cursor = ne_response_header_iterate(req, cursor,
&name, &value)) != NULL) {
rtl::OUString aHeaderName( rtl::OUString::createFromAscii( name ) );
rtl::OUString aHeaderValue( rtl::OUString::createFromAscii( value ) );
// Note: Empty vector means that all headers are requested.
bool bIncludeIt = ( rHeaderNames.size() == 0 );
if ( !bIncludeIt )
{
// Check whether this header was requested.
std::vector< ::rtl::OUString >::const_iterator it(
rHeaderNames.begin() );
const std::vector< ::rtl::OUString >::const_iterator end(
rHeaderNames.end() );
while ( it != end )
{
if ( (*it) == aHeaderName )
break;
++it;
}
if ( it != end )
bIncludeIt = true;
}
if ( bIncludeIt )
{
// Create & set the PropertyValue
beans::PropertyValue thePropertyValue;
thePropertyValue.Handle = -1;
thePropertyValue.Name = aHeaderName;
thePropertyValue.State = beans::PropertyState_DIRECT_VALUE;
thePropertyValue.Value <<= aHeaderValue;
// Add the newly created PropertyValue
rResource.properties.push_back( thePropertyValue );
}
}
}
#else
struct NeonHeadRequestContext
{
DAVResource * pResource;
const std::vector< ::rtl::OUString > * pHeaderNames;
NeonHeadRequestContext( DAVResource * p,
const std::vector< ::rtl::OUString > * pHeaders )
: pResource( p ), pHeaderNames( pHeaders ) {}
};
extern "C" void NHR_ResponseHeaderCatcher( void * userdata,
const char * value )
{
rtl::OUString aHeader( rtl::OUString::createFromAscii( value ) );
sal_Int32 nPos = aHeader.indexOf( ':' );
if ( nPos != -1 )
{
rtl::OUString aHeaderName( aHeader.copy( 0, nPos ) );
NeonHeadRequestContext * pCtx
= static_cast< NeonHeadRequestContext * >( userdata );
// Note: Empty vector means that all headers are requested.
bool bIncludeIt = ( pCtx->pHeaderNames->size() == 0 );
if ( !bIncludeIt )
{
// Check whether this header was requested.
std::vector< ::rtl::OUString >::const_iterator it(
pCtx->pHeaderNames->begin() );
const std::vector< ::rtl::OUString >::const_iterator end(
pCtx->pHeaderNames->end() );
while ( it != end )
{
if ( (*it) == aHeaderName )
break;
++it;
}
if ( it != end )
bIncludeIt = true;
}
if ( bIncludeIt )
{
// Create & set the PropertyValue
beans::PropertyValue thePropertyValue;
thePropertyValue.Handle = -1;
thePropertyValue.Name = aHeaderName;
thePropertyValue.State = beans::PropertyState_DIRECT_VALUE;
if ( nPos < aHeader.getLength() )
thePropertyValue.Value <<= aHeader.copy( nPos + 1 ).trim();
// Add the newly created PropertyValue
pCtx->pResource->properties.push_back( thePropertyValue );
}
}
}
#endif
// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
NeonHeadRequest::NeonHeadRequest( HttpSession* inSession,
const rtl::OUString & inPath,
const std::vector< ::rtl::OUString > &
inHeaderNames,
DAVResource & ioResource,
int & nError )
{
ioResource.uri = inPath;
ioResource.properties.clear();
// Create and dispatch HEAD request. Install catcher for all response
// header fields.
ne_request * req = ne_request_create( inSession,
"HEAD",
rtl::OUStringToOString(
inPath,
RTL_TEXTENCODING_UTF8 ) );
#if NEON_VERSION < 0250
NeonHeadRequestContext aCtx( &ioResource, &inHeaderNames );
ne_add_response_header_catcher( req, NHR_ResponseHeaderCatcher, &aCtx );
#endif
nError = ne_request_dispatch( req );
#if NEON_VERSION >= 0250
process_headers(req, ioResource, inHeaderNames);
#endif
if ( nError == NE_OK && ne_get_status( req )->klass != 2 )
nError = NE_ERROR;
ne_request_destroy( req );
}
// -------------------------------------------------------------------
// Destructor
// -------------------------------------------------------------------
NeonHeadRequest::~NeonHeadRequest()
{
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.5.16); FILE MERGED 2006/09/01 17:55:54 kaib 1.5.16.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: NeonHeadRequest.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-17 14:06:12 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_ucb.hxx"
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYSTATE_HPP_
#include <com/sun/star/beans/PropertyState.hpp>
#endif
#ifndef _NEONHEADREQUEST_HXX_
#include "NeonHeadRequest.hxx"
#endif
using namespace webdav_ucp;
using namespace com::sun::star;
#if NEON_VERSION >= 0250
static void process_headers(ne_request *req,
DAVResource &rResource,
const std::vector< ::rtl::OUString > &rHeaderNames)
{
void *cursor = NULL;
const char *name, *value;
while ((cursor = ne_response_header_iterate(req, cursor,
&name, &value)) != NULL) {
rtl::OUString aHeaderName( rtl::OUString::createFromAscii( name ) );
rtl::OUString aHeaderValue( rtl::OUString::createFromAscii( value ) );
// Note: Empty vector means that all headers are requested.
bool bIncludeIt = ( rHeaderNames.size() == 0 );
if ( !bIncludeIt )
{
// Check whether this header was requested.
std::vector< ::rtl::OUString >::const_iterator it(
rHeaderNames.begin() );
const std::vector< ::rtl::OUString >::const_iterator end(
rHeaderNames.end() );
while ( it != end )
{
if ( (*it) == aHeaderName )
break;
++it;
}
if ( it != end )
bIncludeIt = true;
}
if ( bIncludeIt )
{
// Create & set the PropertyValue
beans::PropertyValue thePropertyValue;
thePropertyValue.Handle = -1;
thePropertyValue.Name = aHeaderName;
thePropertyValue.State = beans::PropertyState_DIRECT_VALUE;
thePropertyValue.Value <<= aHeaderValue;
// Add the newly created PropertyValue
rResource.properties.push_back( thePropertyValue );
}
}
}
#else
struct NeonHeadRequestContext
{
DAVResource * pResource;
const std::vector< ::rtl::OUString > * pHeaderNames;
NeonHeadRequestContext( DAVResource * p,
const std::vector< ::rtl::OUString > * pHeaders )
: pResource( p ), pHeaderNames( pHeaders ) {}
};
extern "C" void NHR_ResponseHeaderCatcher( void * userdata,
const char * value )
{
rtl::OUString aHeader( rtl::OUString::createFromAscii( value ) );
sal_Int32 nPos = aHeader.indexOf( ':' );
if ( nPos != -1 )
{
rtl::OUString aHeaderName( aHeader.copy( 0, nPos ) );
NeonHeadRequestContext * pCtx
= static_cast< NeonHeadRequestContext * >( userdata );
// Note: Empty vector means that all headers are requested.
bool bIncludeIt = ( pCtx->pHeaderNames->size() == 0 );
if ( !bIncludeIt )
{
// Check whether this header was requested.
std::vector< ::rtl::OUString >::const_iterator it(
pCtx->pHeaderNames->begin() );
const std::vector< ::rtl::OUString >::const_iterator end(
pCtx->pHeaderNames->end() );
while ( it != end )
{
if ( (*it) == aHeaderName )
break;
++it;
}
if ( it != end )
bIncludeIt = true;
}
if ( bIncludeIt )
{
// Create & set the PropertyValue
beans::PropertyValue thePropertyValue;
thePropertyValue.Handle = -1;
thePropertyValue.Name = aHeaderName;
thePropertyValue.State = beans::PropertyState_DIRECT_VALUE;
if ( nPos < aHeader.getLength() )
thePropertyValue.Value <<= aHeader.copy( nPos + 1 ).trim();
// Add the newly created PropertyValue
pCtx->pResource->properties.push_back( thePropertyValue );
}
}
}
#endif
// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
NeonHeadRequest::NeonHeadRequest( HttpSession* inSession,
const rtl::OUString & inPath,
const std::vector< ::rtl::OUString > &
inHeaderNames,
DAVResource & ioResource,
int & nError )
{
ioResource.uri = inPath;
ioResource.properties.clear();
// Create and dispatch HEAD request. Install catcher for all response
// header fields.
ne_request * req = ne_request_create( inSession,
"HEAD",
rtl::OUStringToOString(
inPath,
RTL_TEXTENCODING_UTF8 ) );
#if NEON_VERSION < 0250
NeonHeadRequestContext aCtx( &ioResource, &inHeaderNames );
ne_add_response_header_catcher( req, NHR_ResponseHeaderCatcher, &aCtx );
#endif
nError = ne_request_dispatch( req );
#if NEON_VERSION >= 0250
process_headers(req, ioResource, inHeaderNames);
#endif
if ( nError == NE_OK && ne_get_status( req )->klass != 2 )
nError = NE_ERROR;
ne_request_destroy( req );
}
// -------------------------------------------------------------------
// Destructor
// -------------------------------------------------------------------
NeonHeadRequest::~NeonHeadRequest()
{
}
<|endoftext|> |
<commit_before>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2016 Michael Fink
//
/// \file GPhoto2Common.cpp gPhoto2 - Common functions
//
// includes
#include "stdafx.h"
#include "GPhoto2Common.hpp"
#include "GPhoto2SourceInfoImpl.hpp"
#include "GPhoto2Include.hpp"
void GPhoto2::CheckError(const CString& cszFunction, int err, LPCSTR pszFile, UINT uiLine)
{
if (err >= GP_OK)
return;
const char* errorText = gp_result_as_string(err);
LOG_TRACE(_T("gPhoto2: error in function %s: %hs, return code %i\n"), cszFunction.GetString(), errorText, err);
throw CameraException(cszFunction, CString(errorText), static_cast<unsigned int>(err), pszFile, uiLine);
}
/// context error handler function
static void ctx_error_func(GPContext* context, const char* str, void* /*data*/)
{
LOG_TRACE(_T("gPhoto2 error: ctx=%p, text=%hs\n"), context, str);
}
/// context status handler function
static void ctx_status_func(GPContext* context, const char* str, void* /*data*/)
{
LOG_TRACE(_T("gPhoto2 status: ctx=%p, text=%hs\n"), context, str);
}
/// context message handler function
static void ctx_message_func(GPContext* context, const char* str, void* /*data*/)
{
LOG_TRACE(_T("gPhoto2 message: ctx=%p, text=%hs\n"), context, str);
}
GPhoto2::Ref::Ref()
{
GPContext* context = gp_context_new();
m_spContext.reset(context, gp_context_unref);
gp_context_set_error_func(context, ctx_error_func, nullptr);
gp_context_set_status_func(context, ctx_status_func, nullptr);
gp_context_set_message_func(context, ctx_message_func, nullptr);
}
GPhoto2::Ref::~Ref() throw()
{
}
void GPhoto2::Ref::AddVersionText(CString& cszVersionText) const
{
const char** ppVersion = gp_library_version(GP_VERSION_SHORT);
cszVersionText.AppendFormat(_T("gPhoto2 %hs\n"), ppVersion[0]);
}
void GPhoto2::Ref::EnumerateDevices(std::vector<std::shared_ptr<SourceInfo>>& vecSourceDevices) const
{
CameraList* cameraList = nullptr;
int ret = gp_list_new(&cameraList);
if (ret < GP_OK)
return;
std::shared_ptr<CameraList> spAutoFreeCameraList(cameraList, gp_list_free);
ret = gp_camera_autodetect(cameraList, m_spContext.get());
if (ret < GP_OK)
{
const char* errorText = gp_result_as_string(ret);
LOG_TRACE(_T("gPhoto2: no camera auto detected: %hs\n"), errorText);
return;
}
for (int index = 0, max = ret; index < max; index++)
{
const char* name = nullptr;
const char* port = nullptr;
gp_list_get_name(cameraList, index, &name);
gp_list_get_value(cameraList, index, &port);
LOG_TRACE(_T("gPhoto2 camera #%i: %hs (%hs)\n"), index, name, port);
vecSourceDevices.push_back(std::make_shared<GPhoto2::SourceInfoImpl>(m_spContext, name, port));
}
}
<commit_msg>added another newline after gPhoto version<commit_after>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2016 Michael Fink
//
/// \file GPhoto2Common.cpp gPhoto2 - Common functions
//
// includes
#include "stdafx.h"
#include "GPhoto2Common.hpp"
#include "GPhoto2SourceInfoImpl.hpp"
#include "GPhoto2Include.hpp"
void GPhoto2::CheckError(const CString& cszFunction, int err, LPCSTR pszFile, UINT uiLine)
{
if (err >= GP_OK)
return;
const char* errorText = gp_result_as_string(err);
LOG_TRACE(_T("gPhoto2: error in function %s: %hs, return code %i\n"), cszFunction.GetString(), errorText, err);
throw CameraException(cszFunction, CString(errorText), static_cast<unsigned int>(err), pszFile, uiLine);
}
/// context error handler function
static void ctx_error_func(GPContext* context, const char* str, void* /*data*/)
{
LOG_TRACE(_T("gPhoto2 error: ctx=%p, text=%hs\n"), context, str);
}
/// context status handler function
static void ctx_status_func(GPContext* context, const char* str, void* /*data*/)
{
LOG_TRACE(_T("gPhoto2 status: ctx=%p, text=%hs\n"), context, str);
}
/// context message handler function
static void ctx_message_func(GPContext* context, const char* str, void* /*data*/)
{
LOG_TRACE(_T("gPhoto2 message: ctx=%p, text=%hs\n"), context, str);
}
GPhoto2::Ref::Ref()
{
GPContext* context = gp_context_new();
m_spContext.reset(context, gp_context_unref);
gp_context_set_error_func(context, ctx_error_func, nullptr);
gp_context_set_status_func(context, ctx_status_func, nullptr);
gp_context_set_message_func(context, ctx_message_func, nullptr);
}
GPhoto2::Ref::~Ref() throw()
{
}
void GPhoto2::Ref::AddVersionText(CString& cszVersionText) const
{
const char** ppVersion = gp_library_version(GP_VERSION_SHORT);
cszVersionText.AppendFormat(_T("gPhoto2 %hs\n\n"), ppVersion[0]);
}
void GPhoto2::Ref::EnumerateDevices(std::vector<std::shared_ptr<SourceInfo>>& vecSourceDevices) const
{
CameraList* cameraList = nullptr;
int ret = gp_list_new(&cameraList);
if (ret < GP_OK)
return;
std::shared_ptr<CameraList> spAutoFreeCameraList(cameraList, gp_list_free);
ret = gp_camera_autodetect(cameraList, m_spContext.get());
if (ret < GP_OK)
{
const char* errorText = gp_result_as_string(ret);
LOG_TRACE(_T("gPhoto2: no camera auto detected: %hs\n"), errorText);
return;
}
for (int index = 0, max = ret; index < max; index++)
{
const char* name = nullptr;
const char* port = nullptr;
gp_list_get_name(cameraList, index, &name);
gp_list_get_value(cameraList, index, &port);
LOG_TRACE(_T("gPhoto2 camera #%i: %hs (%hs)\n"), index, name, port);
vecSourceDevices.push_back(std::make_shared<GPhoto2::SourceInfoImpl>(m_spContext, name, port));
}
}
<|endoftext|> |
<commit_before>/***********************************************************************************
** MIT License **
** **
** Copyright (c) 2017 Victor DENIS ([email protected]) **
** **
** Permission is hereby granted, free of charge, to any person obtaining a copy **
** of this software and associated documentation files (the "Software"), to deal **
** in the Software without restriction, including without limitation the rights **
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell **
** copies of the Software, and to permit persons to whom the Software is **
** furnished to do so, subject to the following conditions: **
** **
** The above copyright notice and this permission notice shall be included in all **
** copies or substantial portions of the Software. **
** **
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR **
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, **
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE **
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER **
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, **
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE **
** SOFTWARE. **
***********************************************************************************/
#include "Utils/Updater.hpp"
#include <QTimer>
#include <QMessageBox>
#include <QFile>
#include <QStandardPaths>
#include <QDesktopServices>
#include <QMessageBox>
#include <QNetworkRequest>
#include <QNetworkReply>
#include "Network/NetworkManager.hpp"
#include "BrowserWindow.hpp"
#include "Application.hpp"
namespace Sn {
Updater::Updater(BrowserWindow* window, QObject* parent) :
QObject(parent),
m_window(window)
{
QTimer::singleShot(10 * 1000, this, &Updater::start);
}
void Updater::downloadUpdateInfoCompleted()
{
if (!m_versionReply)
return;
QByteArray updateInfo = m_versionReply->readAll();
QTextStream in{&updateInfo};
QString newVersion{};
bool readLastVersion{true};
while (!in.atEnd()) {
QString line{in.readLine()};
QStringList versionInfo{line.split(QLatin1Char(','))};
if (newVersion.isEmpty())
newVersion = versionInfo[0];
if (versionInfo[0] == Application::currentVersion)
break;
std::string debug = line.toStdString();
for (int i{1}; i < versionInfo.count(); ++i) {
if (versionInfo[i] == "fullUpdate")
m_fullUpdate = true;
if (versionInfo[i] == "themeUpdate")
m_themeUpdate = true;
}
}
if (newVersion != Application::currentVersion) {
#if defined(Q_OS_WIN)
QMessageBox::information(m_window, tr("Update"), tr("A new version of Sielo will be download in background!"));
QString updaterName{};
if (m_fullUpdate)
updaterName = "sielo_full_update_setup.exe";
else if (m_themeUpdate)
updaterName = "sielo_theme_update_setup.exe";
else
updaterName = "sielo_update_setup.exe";
QUrl updaterUrl{QUrl("http://www.feldrise.com/Sielo/" + updaterName)};
startDownloadNewVersion(updaterUrl);
#elif defined(Q_OS_LINUX)
QMessageBox::information(m_window,
tr("Update"),
tr("A new version of Sielo is available (%1)! We advise you to download it.")
.arg(newVersion));
#endif
}
m_versionReply->deleteLater();
}
void Updater::downloadCompleted()
{
QString updaterLocation{QStandardPaths::writableLocation(QStandardPaths::TempLocation)};
QFile updater{updaterLocation + QLatin1String("/SieloUpdater.exe")};
if (!updater.open(QIODevice::WriteOnly)) {
QMessageBox::critical(m_window, tr("Update fail"), tr("Impossible to update Sielo... Please retry later"));
return;
}
updater.write(m_updaterReply->readAll());
updater.close();
QDesktopServices::openUrl(QUrl(updaterLocation + QLatin1String("/SieloUpdater.exe")));
m_updaterReply->deleteLater();
m_window->close();
}
void Updater::start()
{
QUrl newVersionUrl{QUrl("http://www.feldrise.com/Sielo/versions.txt")};
startDownloadingUpdateInfo(newVersionUrl);
}
void Updater::startDownloadNewVersion(const QUrl& url)
{
m_updaterReply = Application::instance()->networkManager()->get(QNetworkRequest(url));
connect(m_updaterReply, &QNetworkReply::finished, this, &Updater::downloadCompleted);
}
void Updater::startDownloadingUpdateInfo(const QUrl& url)
{
m_versionReply = Application::instance()->networkManager()->get(QNetworkRequest(url));
connect(m_versionReply, &QNetworkReply::finished, this, &Updater::downloadUpdateInfoCompleted);
}
}
<commit_msg>[Remove] useless variable<commit_after>/***********************************************************************************
** MIT License **
** **
** Copyright (c) 2017 Victor DENIS ([email protected]) **
** **
** Permission is hereby granted, free of charge, to any person obtaining a copy **
** of this software and associated documentation files (the "Software"), to deal **
** in the Software without restriction, including without limitation the rights **
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell **
** copies of the Software, and to permit persons to whom the Software is **
** furnished to do so, subject to the following conditions: **
** **
** The above copyright notice and this permission notice shall be included in all **
** copies or substantial portions of the Software. **
** **
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR **
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, **
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE **
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER **
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, **
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE **
** SOFTWARE. **
***********************************************************************************/
#include "Utils/Updater.hpp"
#include <QTimer>
#include <QMessageBox>
#include <QFile>
#include <QStandardPaths>
#include <QDesktopServices>
#include <QMessageBox>
#include <QNetworkRequest>
#include <QNetworkReply>
#include "Network/NetworkManager.hpp"
#include "BrowserWindow.hpp"
#include "Application.hpp"
namespace Sn {
Updater::Updater(BrowserWindow* window, QObject* parent) :
QObject(parent),
m_window(window)
{
QTimer::singleShot(10 * 1000, this, &Updater::start);
}
void Updater::downloadUpdateInfoCompleted()
{
if (!m_versionReply)
return;
QByteArray updateInfo = m_versionReply->readAll();
QTextStream in{&updateInfo};
QString newVersion{};
while (!in.atEnd()) {
QString line{in.readLine()};
QStringList versionInfo{line.split(QLatin1Char(','))};
if (newVersion.isEmpty())
newVersion = versionInfo[0];
if (versionInfo[0] == Application::currentVersion)
break;
for (int i{1}; i < versionInfo.count(); ++i) {
if (versionInfo[i] == "fullUpdate")
m_fullUpdate = true;
if (versionInfo[i] == "themeUpdate")
m_themeUpdate = true;
}
}
if (newVersion != Application::currentVersion) {
#if defined(Q_OS_WIN)
QMessageBox::information(m_window, tr("Update"), tr("A new version of Sielo will be download in background!"));
QString updaterName{};
if (m_fullUpdate)
updaterName = "sielo_full_update_setup.exe";
else if (m_themeUpdate)
updaterName = "sielo_theme_update_setup.exe";
else
updaterName = "sielo_update_setup.exe";
QUrl updaterUrl{QUrl("http://www.feldrise.com/Sielo/" + updaterName)};
startDownloadNewVersion(updaterUrl);
#elif defined(Q_OS_LINUX)
QMessageBox::information(m_window,
tr("Update"),
tr("A new version of Sielo is available (%1)! We advise you to download it.")
.arg(newVersion));
#endif
}
m_versionReply->deleteLater();
}
void Updater::downloadCompleted()
{
QString updaterLocation{QStandardPaths::writableLocation(QStandardPaths::TempLocation)};
QFile updater{updaterLocation + QLatin1String("/SieloUpdater.exe")};
if (!updater.open(QIODevice::WriteOnly)) {
QMessageBox::critical(m_window, tr("Update fail"), tr("Impossible to update Sielo... Please retry later"));
return;
}
updater.write(m_updaterReply->readAll());
updater.close();
QDesktopServices::openUrl(QUrl(updaterLocation + QLatin1String("/SieloUpdater.exe")));
m_updaterReply->deleteLater();
m_window->close();
}
void Updater::start()
{
QUrl newVersionUrl{QUrl("http://www.feldrise.com/Sielo/versions.txt")};
startDownloadingUpdateInfo(newVersionUrl);
}
void Updater::startDownloadNewVersion(const QUrl& url)
{
m_updaterReply = Application::instance()->networkManager()->get(QNetworkRequest(url));
connect(m_updaterReply, &QNetworkReply::finished, this, &Updater::downloadCompleted);
}
void Updater::startDownloadingUpdateInfo(const QUrl& url)
{
m_versionReply = Application::instance()->networkManager()->get(QNetworkRequest(url));
connect(m_versionReply, &QNetworkReply::finished, this, &Updater::downloadUpdateInfoCompleted);
}
}
<|endoftext|> |
<commit_before>#include <QList>
#include "Connection.hpp"
#include "ForwardingSender.hpp"
#include "RelayEdge.hpp"
#include "RelayForwarder.hpp"
namespace Dissent {
namespace Connections {
RelayForwarder::RelayForwarder(const Id &local_id, const ConnectionTable &ct,
RpcHandler &rpc) :
_local_id(local_id),
_base_been(local_id.ToString()),
_ct(ct),
_rpc(rpc),
_incoming_data(this, &RelayForwarder::IncomingData)
{
_rpc.Register(&_incoming_data, "RF::Data");
}
RelayForwarder::~RelayForwarder()
{
_rpc.Unregister("RF::Data");
}
RelayForwarder::ISender *RelayForwarder::GetSender(const Id &to)
{
return new ForwardingSender(this, to);
}
void RelayForwarder::Send(const QByteArray &data, const Id &to)
{
if(to == _local_id) {
_rpc.HandleData(data, new ForwardingSender(this, _local_id));
return;
}
Forward(data, to, _base_been);
}
void RelayForwarder::IncomingData(RpcRequest ¬ification)
{
const QVariantMap &msg = notification.GetMessage();
Id destination = Id(msg["to"].toString());
if(destination == Id::Zero()) {
qWarning() << "Received a forwarded message without a destination.";
return;
}
QStringList been = msg["been"].toStringList();
if(destination == _local_id) {
if(been.size() == 0) {
qWarning() << "Received a forwarded message without any history.";
return;
}
Id source = Id(been[0]);
if(source == Id::Zero()) {
qWarning() << "Received a forwarded message without a valid source.";
}
_rpc.HandleData(msg["data"].toByteArray(), new ForwardingSender(this, source));
return;
}
Forward(msg["data"].toByteArray(), destination, (been + _base_been));
}
void RelayForwarder::Forward(const QByteArray &data, const Id &to,
const QStringList &been)
{
QHash<int, bool> tested;
Connection *con = _ct.GetConnection(to);
if(con == 0 || (dynamic_cast<RelayEdge *>(con->GetEdge().data()) != 0)) {
const QList<Connection *> cons = _ct.GetConnections();
Dissent::Utils::Random &rand = Dissent::Utils::Random::GetInstance();
int idx = rand.GetInt(0, cons.size());
con = cons[idx];
tested[idx] = true;
RelayEdge *redge = dynamic_cast<RelayEdge *>(con->GetEdge().data());
while(been.contains(con->GetRemoteId().ToString()) || (redge != 0)) {
if(tested.size() == cons.size()) {
qWarning() << "Packet has been to all of our connections.";
return;
}
idx = rand.GetInt(0, cons.size());
con = cons[idx];
redge = dynamic_cast<RelayEdge *>(con->GetEdge().data());
tested[idx] = true;
}
}
qWarning() << _local_id.ToString() << con->GetRemoteId().ToString() << con->GetEdge()->ToString();
QVariantMap notification;
notification["method"] = "RF::Data";
notification["data"] = data;
notification["to"] = to.ToString();
notification["been"] = been + _base_been;
_rpc.SendNotification(notification, con);
}
}
}
<commit_msg>[Connections] debug cleanup<commit_after>#include <QList>
#include "Connection.hpp"
#include "ForwardingSender.hpp"
#include "RelayEdge.hpp"
#include "RelayForwarder.hpp"
namespace Dissent {
namespace Connections {
RelayForwarder::RelayForwarder(const Id &local_id, const ConnectionTable &ct,
RpcHandler &rpc) :
_local_id(local_id),
_base_been(local_id.ToString()),
_ct(ct),
_rpc(rpc),
_incoming_data(this, &RelayForwarder::IncomingData)
{
_rpc.Register(&_incoming_data, "RF::Data");
}
RelayForwarder::~RelayForwarder()
{
_rpc.Unregister("RF::Data");
}
RelayForwarder::ISender *RelayForwarder::GetSender(const Id &to)
{
return new ForwardingSender(this, to);
}
void RelayForwarder::Send(const QByteArray &data, const Id &to)
{
if(to == _local_id) {
_rpc.HandleData(data, new ForwardingSender(this, _local_id));
return;
}
Forward(data, to, _base_been);
}
void RelayForwarder::IncomingData(RpcRequest ¬ification)
{
const QVariantMap &msg = notification.GetMessage();
Id destination = Id(msg["to"].toString());
if(destination == Id::Zero()) {
qWarning() << "Received a forwarded message without a destination.";
return;
}
QStringList been = msg["been"].toStringList();
if(destination == _local_id) {
if(been.size() == 0) {
qWarning() << "Received a forwarded message without any history.";
return;
}
Id source = Id(been[0]);
if(source == Id::Zero()) {
qWarning() << "Received a forwarded message without a valid source.";
}
_rpc.HandleData(msg["data"].toByteArray(), new ForwardingSender(this, source));
return;
}
Forward(msg["data"].toByteArray(), destination, (been + _base_been));
}
void RelayForwarder::Forward(const QByteArray &data, const Id &to,
const QStringList &been)
{
QHash<int, bool> tested;
Connection *con = _ct.GetConnection(to);
if(con == 0 || (dynamic_cast<RelayEdge *>(con->GetEdge().data()) != 0)) {
const QList<Connection *> cons = _ct.GetConnections();
Dissent::Utils::Random &rand = Dissent::Utils::Random::GetInstance();
int idx = rand.GetInt(0, cons.size());
con = cons[idx];
tested[idx] = true;
RelayEdge *redge = dynamic_cast<RelayEdge *>(con->GetEdge().data());
while(been.contains(con->GetRemoteId().ToString()) || (redge != 0)) {
if(tested.size() == cons.size()) {
qWarning() << "Packet has been to all of our connections.";
return;
}
idx = rand.GetInt(0, cons.size());
con = cons[idx];
redge = dynamic_cast<RelayEdge *>(con->GetEdge().data());
tested[idx] = true;
}
}
QVariantMap notification;
notification["method"] = "RF::Data";
notification["data"] = data;
notification["to"] = to.ToString();
notification["been"] = been + _base_been;
_rpc.SendNotification(notification, con);
}
}
}
<|endoftext|> |
<commit_before>#include "TriangleMesh.hpp"
#include <Core/Geometry/TriangleOperation.hpp> // triangleArea
namespace Ra {
namespace Core {
namespace Geometry {
inline AttribArrayGeometry ::AttribArrayGeometry( const AttribArrayGeometry& other ) :
AbstractGeometry( other ) {
m_vertexAttribs.copyAllAttributes( other.m_vertexAttribs );
m_verticesHandle = other.m_verticesHandle;
m_normalsHandle = other.m_normalsHandle;
}
inline AttribArrayGeometry::AttribArrayGeometry( AttribArrayGeometry&& other ) :
m_vertexAttribs( std::move( other.m_vertexAttribs ) ),
m_verticesHandle( std::move( other.m_verticesHandle ) ),
m_normalsHandle( std::move( other.m_normalsHandle ) ) {}
inline AttribArrayGeometry& AttribArrayGeometry::operator=( const AttribArrayGeometry& other ) {
if ( this != &other )
{
m_vertexAttribs.clear();
m_vertexAttribs.copyAllAttributes( other.m_vertexAttribs );
m_verticesHandle = other.m_verticesHandle;
m_normalsHandle = other.m_normalsHandle;
}
return *this;
}
inline AttribArrayGeometry& AttribArrayGeometry::operator=( AttribArrayGeometry&& other ) {
if ( this != &other )
{
m_vertexAttribs = std::move( other.m_vertexAttribs );
m_verticesHandle = std::move( other.m_verticesHandle );
m_normalsHandle = std::move( other.m_normalsHandle );
}
return *this;
}
inline void AttribArrayGeometry::clear() {
m_vertexAttribs.clear();
// restore the default attribs (empty though)
initDefaultAttribs();
}
inline void AttribArrayGeometry::copyBaseGeometry( const AttribArrayGeometry& other ) {
clear();
m_vertexAttribs.copyAttributes(
other.m_vertexAttribs, other.m_verticesHandle, other.m_normalsHandle );
}
template <typename... Handles>
inline bool AttribArrayGeometry::copyAttributes( const AttribArrayGeometry& input,
Handles... attribs ) {
if ( vertices().size() != input.vertices().size() ) return false;
// copy attribs
m_vertexAttribs.copyAttributes( input.m_vertexAttribs, attribs... );
return true;
}
inline bool AttribArrayGeometry::copyAllAttributes( const AttribArrayGeometry& input ) {
if ( vertices().size() != input.vertices().size() ) return false;
// copy attribs
m_vertexAttribs.copyAllAttributes( input.m_vertexAttribs );
return true;
}
inline Aabb AttribArrayGeometry::computeAabb() const {
Aabb aabb;
for ( const auto& v : vertices() )
{
aabb.extend( v );
}
return aabb;
}
inline void AttribArrayGeometry::setVertices( PointAttribHandle::Container&& vertices ) {
m_vertexAttribs.setAttrib( m_verticesHandle, std::move( vertices ) );
}
inline void AttribArrayGeometry::setVertices( const PointAttribHandle::Container& vertices ) {
m_vertexAttribs.setAttrib<PointAttribHandle::value_type>( m_verticesHandle, vertices );
}
inline const AttribArrayGeometry::PointAttribHandle::Container&
AttribArrayGeometry::vertices() const {
return m_vertexAttribs.getAttrib( m_verticesHandle ).data();
}
inline void AttribArrayGeometry::setNormals( PointAttribHandle::Container&& normals ) {
m_vertexAttribs.setAttrib( m_normalsHandle, std::move( normals ) );
}
inline void AttribArrayGeometry::setNormals( const PointAttribHandle::Container& normals ) {
m_vertexAttribs.setAttrib( m_normalsHandle, normals );
}
inline const AttribArrayGeometry::NormalAttribHandle::Container&
AttribArrayGeometry::normals() const {
return m_vertexAttribs.getAttrib( m_normalsHandle ).data();
}
template <typename T>
inline Utils::AttribHandle<T>
AttribArrayGeometry::getAttribHandle( const std::string& name ) const {
return m_vertexAttribs.findAttrib<T>( name );
}
template <typename T>
inline bool AttribArrayGeometry::isValid( const Utils::AttribHandle<T>& h ) const {
return m_vertexAttribs.isValid( h );
}
template <typename T>
inline Utils::Attrib<T>& AttribArrayGeometry::getAttrib( const Utils::AttribHandle<T>& h ) {
return m_vertexAttribs.getAttrib( h );
}
template <typename T>
const Utils::Attrib<T>& AttribArrayGeometry::getAttrib( const Utils::AttribHandle<T>& h ) const {
return m_vertexAttribs.getAttrib( h );
}
inline Utils::AttribBase* AttribArrayGeometry::getAttribBase( const std::string& name ) {
return m_vertexAttribs.getAttribBase( name );
}
inline bool AttribArrayGeometry::hasAttrib( const std::string& name ) {
return m_vertexAttribs.contains( name );
}
template <typename T>
inline Utils::AttribHandle<T> AttribArrayGeometry::addAttrib( const std::string& name ) {
return m_vertexAttribs.addAttrib<T>( name );
}
template <typename T>
inline Utils::AttribHandle<T>
AttribArrayGeometry::addAttrib( const std::string& name,
const typename Core::VectorArray<T>& data ) {
auto handle = addAttrib<T>( name );
getAttrib( handle ).setData( data );
return handle;
}
template <typename T>
inline Utils::AttribHandle<T>
AttribArrayGeometry::addAttrib( const std::string& name,
const typename Utils::Attrib<T>::Container&& data ) {
auto handle = addAttrib<T>( name );
getAttrib( handle ).setData( std::move( data ) );
return handle;
}
template <typename T>
inline void AttribArrayGeometry::removeAttrib( Utils::AttribHandle<T>& h ) {
m_vertexAttribs.removeAttrib( h );
}
inline Utils::AttribManager& AttribArrayGeometry::vertexAttribs() {
return m_vertexAttribs;
}
inline const Utils::AttribManager& AttribArrayGeometry::vertexAttribs() const {
return m_vertexAttribs;
}
inline AttribArrayGeometry::PointAttribHandle::Container& AttribArrayGeometry::verticesWithLock() {
return m_vertexAttribs.getAttrib( m_verticesHandle ).getDataWithLock();
}
inline void AttribArrayGeometry::verticesUnlock() {
return m_vertexAttribs.getAttrib( m_verticesHandle ).unlock();
}
inline AttribArrayGeometry::NormalAttribHandle::Container& AttribArrayGeometry::normalsWithLock() {
return m_vertexAttribs.getAttrib( m_normalsHandle ).getDataWithLock();
}
inline void AttribArrayGeometry::normalsUnlock() {
return m_vertexAttribs.getAttrib( m_normalsHandle ).unlock();
}
inline void AttribArrayGeometry::initDefaultAttribs() {
m_verticesHandle = m_vertexAttribs.addAttrib<PointAttribHandle::value_type>( "in_position" );
m_normalsHandle = m_vertexAttribs.addAttrib<NormalAttribHandle::value_type>( "in_normal" );
}
template <typename T>
inline void AttribArrayGeometry::append_attrib( Utils::AttribBase* attr ) {
auto h = m_vertexAttribs.findAttrib<T>( attr->getName() );
auto& v0 = m_vertexAttribs.getAttrib( h ).getDataWithLock();
const auto& v1 = attr->cast<T>().data();
v0.insert( v0.end(), v1.cbegin(), v1.cend() );
m_vertexAttribs.getAttrib( h ).unlock();
}
/*** IndexedGeometry ***/
template <typename T>
inline IndexedGeometry<T>::IndexedGeometry( const IndexedGeometry<IndexType>& other ) :
AttribArrayGeometry( other ), m_indices( other.m_indices ) {}
template <typename T>
inline IndexedGeometry<T>::IndexedGeometry( IndexedGeometry<IndexType>&& other ) :
AttribArrayGeometry( std::move( other ) ), m_indices( std::move( other.m_indices ) ) {}
template <typename T>
inline IndexedGeometry<T>&
IndexedGeometry<T>::operator=( const IndexedGeometry<IndexType>& other ) {
AttribArrayGeometry::operator=( other );
m_indices = other.m_indices;
notify();
return *this;
}
template <typename T>
inline IndexedGeometry<T>& IndexedGeometry<T>::operator=( IndexedGeometry<IndexType>&& other ) {
AttribArrayGeometry::operator=( std::move( other ) );
m_indices = std::move( other.m_indices );
notify();
return *this;
}
template <typename T>
inline void IndexedGeometry<T>::clear() {
m_indices.clear();
AttribArrayGeometry::clear();
notify();
}
template <typename T>
inline void IndexedGeometry<T>::copy( const IndexedGeometry<IndexType>& other ) {
AttribArrayGeometry::copyBaseGeometry( other );
m_indices = other.m_indices;
notify();
}
template <typename T>
inline void IndexedGeometry<T>::checkConsistency() const {
#ifdef CORE_DEBUG
const auto nbVertices = vertices().size();
std::vector<bool> visited( nbVertices, false );
for ( uint t = 0; t < m_indices.size(); ++t )
{
const IndexType& face = m_indices[t];
for ( uint i = 0; i < IndexType::RowsAtCompileTime; ++i )
{
CORE_ASSERT( uint( face[i] ) < nbVertices,
"Vertex " << face[i] << " is out of bound, in face " << t << " (#" << i
<< ")" );
visited[face[i]] = true;
}
CORE_WARN_IF( IndexType::RowsAtCompileTime == 3 &&
!( Geometry::triangleArea( vertices()[face[0]],
vertices()[face[1]],
vertices()[face[2]] ) > 0.f ),
"triangle " << t << " is degenerate" );
}
for ( uint v = 0; v < nbVertices; ++v )
{
CORE_ASSERT( visited[v], "Vertex " << v << " does not belong to any triangle" );
}
// Always have the same number of vertex data and vertices
CORE_ASSERT( vertices().size() == normals().size(), "Inconsistent number of normals" );
#endif
}
template <typename T>
inline bool IndexedGeometry<T>::append( const IndexedGeometry<IndexType>& other ) {
const std::size_t verticesBefore = vertices().size();
const std::size_t trianglesBefore = m_indices.size();
// check same attributes through names
if ( !AttribArrayGeometry::append( other ) ) return false;
// now we can proceed topology
m_indices.insert( m_indices.end(), other.m_indices.cbegin(), other.m_indices.cend() );
// Offset the vertex indices in the triangles and faces
for ( size_t t = trianglesBefore; t < m_indices.size(); ++t )
{
for ( uint i = 0; i < IndexType::RowsAtCompileTime; ++i )
{
m_indices[t][i] += verticesBefore;
}
}
notify();
return true;
}
template <typename T>
const typename IndexedGeometry<T>::IndexContainerType& IndexedGeometry<T>::getIndices() const {
return m_indices;
}
template <typename T>
typename IndexedGeometry<T>::IndexContainerType& IndexedGeometry<T>::getIndicesWithLock() {
CORE_ASSERT( !m_isIndicesLocked, "try to get already locked indices" );
m_isIndicesLocked = true;
return m_indices;
}
template <typename T>
void IndexedGeometry<T>::indicesUnlock() {
CORE_ASSERT( !m_isIndicesLocked, "try unlock not locked indices" );
m_isIndicesLocked = false;
notify();
}
template <typename T>
void IndexedGeometry<T>::setIndices( IndexContainerType&& indices ) {
CORE_ASSERT( !m_isIndicesLocked, "try set already locked indices" );
m_indices = std::move( indices );
notify();
}
} // namespace Geometry
} // namespace Core
} // namespace Ra
<commit_msg>[Core] TriangleMesh: typo in assert.<commit_after>#include "TriangleMesh.hpp"
#include <Core/Geometry/TriangleOperation.hpp> // triangleArea
namespace Ra {
namespace Core {
namespace Geometry {
inline AttribArrayGeometry ::AttribArrayGeometry( const AttribArrayGeometry& other ) :
AbstractGeometry( other ) {
m_vertexAttribs.copyAllAttributes( other.m_vertexAttribs );
m_verticesHandle = other.m_verticesHandle;
m_normalsHandle = other.m_normalsHandle;
}
inline AttribArrayGeometry::AttribArrayGeometry( AttribArrayGeometry&& other ) :
m_vertexAttribs( std::move( other.m_vertexAttribs ) ),
m_verticesHandle( std::move( other.m_verticesHandle ) ),
m_normalsHandle( std::move( other.m_normalsHandle ) ) {}
inline AttribArrayGeometry& AttribArrayGeometry::operator=( const AttribArrayGeometry& other ) {
if ( this != &other )
{
m_vertexAttribs.clear();
m_vertexAttribs.copyAllAttributes( other.m_vertexAttribs );
m_verticesHandle = other.m_verticesHandle;
m_normalsHandle = other.m_normalsHandle;
}
return *this;
}
inline AttribArrayGeometry& AttribArrayGeometry::operator=( AttribArrayGeometry&& other ) {
if ( this != &other )
{
m_vertexAttribs = std::move( other.m_vertexAttribs );
m_verticesHandle = std::move( other.m_verticesHandle );
m_normalsHandle = std::move( other.m_normalsHandle );
}
return *this;
}
inline void AttribArrayGeometry::clear() {
m_vertexAttribs.clear();
// restore the default attribs (empty though)
initDefaultAttribs();
}
inline void AttribArrayGeometry::copyBaseGeometry( const AttribArrayGeometry& other ) {
clear();
m_vertexAttribs.copyAttributes(
other.m_vertexAttribs, other.m_verticesHandle, other.m_normalsHandle );
}
template <typename... Handles>
inline bool AttribArrayGeometry::copyAttributes( const AttribArrayGeometry& input,
Handles... attribs ) {
if ( vertices().size() != input.vertices().size() ) return false;
// copy attribs
m_vertexAttribs.copyAttributes( input.m_vertexAttribs, attribs... );
return true;
}
inline bool AttribArrayGeometry::copyAllAttributes( const AttribArrayGeometry& input ) {
if ( vertices().size() != input.vertices().size() ) return false;
// copy attribs
m_vertexAttribs.copyAllAttributes( input.m_vertexAttribs );
return true;
}
inline Aabb AttribArrayGeometry::computeAabb() const {
Aabb aabb;
for ( const auto& v : vertices() )
{
aabb.extend( v );
}
return aabb;
}
inline void AttribArrayGeometry::setVertices( PointAttribHandle::Container&& vertices ) {
m_vertexAttribs.setAttrib( m_verticesHandle, std::move( vertices ) );
}
inline void AttribArrayGeometry::setVertices( const PointAttribHandle::Container& vertices ) {
m_vertexAttribs.setAttrib<PointAttribHandle::value_type>( m_verticesHandle, vertices );
}
inline const AttribArrayGeometry::PointAttribHandle::Container&
AttribArrayGeometry::vertices() const {
return m_vertexAttribs.getAttrib( m_verticesHandle ).data();
}
inline void AttribArrayGeometry::setNormals( PointAttribHandle::Container&& normals ) {
m_vertexAttribs.setAttrib( m_normalsHandle, std::move( normals ) );
}
inline void AttribArrayGeometry::setNormals( const PointAttribHandle::Container& normals ) {
m_vertexAttribs.setAttrib( m_normalsHandle, normals );
}
inline const AttribArrayGeometry::NormalAttribHandle::Container&
AttribArrayGeometry::normals() const {
return m_vertexAttribs.getAttrib( m_normalsHandle ).data();
}
template <typename T>
inline Utils::AttribHandle<T>
AttribArrayGeometry::getAttribHandle( const std::string& name ) const {
return m_vertexAttribs.findAttrib<T>( name );
}
template <typename T>
inline bool AttribArrayGeometry::isValid( const Utils::AttribHandle<T>& h ) const {
return m_vertexAttribs.isValid( h );
}
template <typename T>
inline Utils::Attrib<T>& AttribArrayGeometry::getAttrib( const Utils::AttribHandle<T>& h ) {
return m_vertexAttribs.getAttrib( h );
}
template <typename T>
const Utils::Attrib<T>& AttribArrayGeometry::getAttrib( const Utils::AttribHandle<T>& h ) const {
return m_vertexAttribs.getAttrib( h );
}
inline Utils::AttribBase* AttribArrayGeometry::getAttribBase( const std::string& name ) {
return m_vertexAttribs.getAttribBase( name );
}
inline bool AttribArrayGeometry::hasAttrib( const std::string& name ) {
return m_vertexAttribs.contains( name );
}
template <typename T>
inline Utils::AttribHandle<T> AttribArrayGeometry::addAttrib( const std::string& name ) {
return m_vertexAttribs.addAttrib<T>( name );
}
template <typename T>
inline Utils::AttribHandle<T>
AttribArrayGeometry::addAttrib( const std::string& name,
const typename Core::VectorArray<T>& data ) {
auto handle = addAttrib<T>( name );
getAttrib( handle ).setData( data );
return handle;
}
template <typename T>
inline Utils::AttribHandle<T>
AttribArrayGeometry::addAttrib( const std::string& name,
const typename Utils::Attrib<T>::Container&& data ) {
auto handle = addAttrib<T>( name );
getAttrib( handle ).setData( std::move( data ) );
return handle;
}
template <typename T>
inline void AttribArrayGeometry::removeAttrib( Utils::AttribHandle<T>& h ) {
m_vertexAttribs.removeAttrib( h );
}
inline Utils::AttribManager& AttribArrayGeometry::vertexAttribs() {
return m_vertexAttribs;
}
inline const Utils::AttribManager& AttribArrayGeometry::vertexAttribs() const {
return m_vertexAttribs;
}
inline AttribArrayGeometry::PointAttribHandle::Container& AttribArrayGeometry::verticesWithLock() {
return m_vertexAttribs.getAttrib( m_verticesHandle ).getDataWithLock();
}
inline void AttribArrayGeometry::verticesUnlock() {
return m_vertexAttribs.getAttrib( m_verticesHandle ).unlock();
}
inline AttribArrayGeometry::NormalAttribHandle::Container& AttribArrayGeometry::normalsWithLock() {
return m_vertexAttribs.getAttrib( m_normalsHandle ).getDataWithLock();
}
inline void AttribArrayGeometry::normalsUnlock() {
return m_vertexAttribs.getAttrib( m_normalsHandle ).unlock();
}
inline void AttribArrayGeometry::initDefaultAttribs() {
m_verticesHandle = m_vertexAttribs.addAttrib<PointAttribHandle::value_type>( "in_position" );
m_normalsHandle = m_vertexAttribs.addAttrib<NormalAttribHandle::value_type>( "in_normal" );
}
template <typename T>
inline void AttribArrayGeometry::append_attrib( Utils::AttribBase* attr ) {
auto h = m_vertexAttribs.findAttrib<T>( attr->getName() );
auto& v0 = m_vertexAttribs.getAttrib( h ).getDataWithLock();
const auto& v1 = attr->cast<T>().data();
v0.insert( v0.end(), v1.cbegin(), v1.cend() );
m_vertexAttribs.getAttrib( h ).unlock();
}
/*** IndexedGeometry ***/
template <typename T>
inline IndexedGeometry<T>::IndexedGeometry( const IndexedGeometry<IndexType>& other ) :
AttribArrayGeometry( other ), m_indices( other.m_indices ) {}
template <typename T>
inline IndexedGeometry<T>::IndexedGeometry( IndexedGeometry<IndexType>&& other ) :
AttribArrayGeometry( std::move( other ) ), m_indices( std::move( other.m_indices ) ) {}
template <typename T>
inline IndexedGeometry<T>&
IndexedGeometry<T>::operator=( const IndexedGeometry<IndexType>& other ) {
AttribArrayGeometry::operator=( other );
m_indices = other.m_indices;
notify();
return *this;
}
template <typename T>
inline IndexedGeometry<T>& IndexedGeometry<T>::operator=( IndexedGeometry<IndexType>&& other ) {
AttribArrayGeometry::operator=( std::move( other ) );
m_indices = std::move( other.m_indices );
notify();
return *this;
}
template <typename T>
inline void IndexedGeometry<T>::clear() {
m_indices.clear();
AttribArrayGeometry::clear();
notify();
}
template <typename T>
inline void IndexedGeometry<T>::copy( const IndexedGeometry<IndexType>& other ) {
AttribArrayGeometry::copyBaseGeometry( other );
m_indices = other.m_indices;
notify();
}
template <typename T>
inline void IndexedGeometry<T>::checkConsistency() const {
#ifdef CORE_DEBUG
const auto nbVertices = vertices().size();
std::vector<bool> visited( nbVertices, false );
for ( uint t = 0; t < m_indices.size(); ++t )
{
const IndexType& face = m_indices[t];
for ( uint i = 0; i < IndexType::RowsAtCompileTime; ++i )
{
CORE_ASSERT( uint( face[i] ) < nbVertices,
"Vertex " << face[i] << " is out of bound, in face " << t << " (#" << i
<< ")" );
visited[face[i]] = true;
}
CORE_WARN_IF( IndexType::RowsAtCompileTime == 3 &&
!( Geometry::triangleArea( vertices()[face[0]],
vertices()[face[1]],
vertices()[face[2]] ) > 0.f ),
"triangle " << t << " is degenerate" );
}
for ( uint v = 0; v < nbVertices; ++v )
{
CORE_ASSERT( visited[v], "Vertex " << v << " does not belong to any triangle" );
}
// Always have the same number of vertex data and vertices
CORE_ASSERT( vertices().size() == normals().size(), "Inconsistent number of normals" );
#endif
}
template <typename T>
inline bool IndexedGeometry<T>::append( const IndexedGeometry<IndexType>& other ) {
const std::size_t verticesBefore = vertices().size();
const std::size_t trianglesBefore = m_indices.size();
// check same attributes through names
if ( !AttribArrayGeometry::append( other ) ) return false;
// now we can proceed topology
m_indices.insert( m_indices.end(), other.m_indices.cbegin(), other.m_indices.cend() );
// Offset the vertex indices in the triangles and faces
for ( size_t t = trianglesBefore; t < m_indices.size(); ++t )
{
for ( uint i = 0; i < IndexType::RowsAtCompileTime; ++i )
{
m_indices[t][i] += verticesBefore;
}
}
notify();
return true;
}
template <typename T>
const typename IndexedGeometry<T>::IndexContainerType& IndexedGeometry<T>::getIndices() const {
return m_indices;
}
template <typename T>
typename IndexedGeometry<T>::IndexContainerType& IndexedGeometry<T>::getIndicesWithLock() {
CORE_ASSERT( !m_isIndicesLocked, "try to get already locked indices" );
m_isIndicesLocked = true;
return m_indices;
}
template <typename T>
void IndexedGeometry<T>::indicesUnlock() {
CORE_ASSERT( m_isIndicesLocked, "try unlock not locked indices" );
m_isIndicesLocked = false;
notify();
}
template <typename T>
void IndexedGeometry<T>::setIndices( IndexContainerType&& indices ) {
CORE_ASSERT( !m_isIndicesLocked, "try set already locked indices" );
m_indices = std::move( indices );
notify();
}
} // namespace Geometry
} // namespace Core
} // namespace Ra
<|endoftext|> |
<commit_before>/***********************************************************************
created: Tue Feb 17 2009
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUI/RendererModules/Ogre/RenderTarget.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/RenderQueue.h"
#include "CEGUI/RendererModules/Ogre/GeometryBuffer.h"
#include <OgreRenderSystem.h>
#include <OgreCamera.h>
#include <OgreViewport.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
template <typename T>
const float OgreRenderTarget<T>::d_yfov_tan = 0.267949192431123f;
//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::OgreRenderTarget(OgreRenderer& owner,
Ogre::RenderSystem& rs) :
d_owner(owner),
d_renderSystem(rs),
d_area(0, 0, 0, 0),
d_renderTarget(0),
d_viewport(0),
d_ogreViewportDimensions(0, 0, 0, 0),
d_matrix(Ogre::Matrix4::IDENTITY),
d_matrixValid(false),
d_viewportValid(false),
d_viewDistance(0)
{
}
//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::~OgreRenderTarget()
{
delete d_viewport;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const GeometryBuffer& buffer)
{
buffer.draw();
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const RenderQueue& queue)
{
queue.draw();
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::setArea(const Rectf& area)
{
d_area = area;
setOgreViewportDimensions(area);
d_matrixValid = false;
RenderTargetEventArgs args(this);
T::fireEvent(RenderTarget::EventAreaChanged, args);
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::setOgreViewportDimensions(const Rectf& area)
{
d_ogreViewportDimensions = area;
if (d_viewport)
updateOgreViewportDimensions(d_viewport->getTarget());
d_viewportValid = false;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateOgreViewportDimensions(
const Ogre::RenderTarget* const rt)
{
if (rt)
{
if(d_viewport)
d_viewport->setDimensions(
d_ogreViewportDimensions.left() / rt->getWidth(),
d_ogreViewportDimensions.top() / rt->getHeight(),
d_ogreViewportDimensions.getWidth() / rt->getWidth(),
d_ogreViewportDimensions.getHeight() / rt->getHeight());
}
}
//----------------------------------------------------------------------------//
template <typename T>
const Rectf& OgreRenderTarget<T>::getArea() const
{
return d_area;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::activate()
{
if (!d_matrixValid)
updateMatrix();
if (!d_viewportValid)
updateViewport();
d_renderSystem._setViewport(d_viewport);
d_owner.setProjectionMatrix(d_matrix);
RenderTarget::activate();
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::deactivate()
{
// currently nothing to do in the basic case
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff,
const glm::vec2& p_in,
glm::vec2& p_out) const
{
if (!d_matrixValid)
updateMatrix();
const OgreGeometryBuffer& gb = static_cast<const OgreGeometryBuffer&>(buff);
const Ogre::Real midx = d_area.getWidth() * 0.5f;
const Ogre::Real midy = d_area.getHeight() * 0.5f;
// viewport matrix
const Ogre::Matrix4 vpmat(
midx, 0, 0, d_area.left() + midx,
0, -midy, 0, d_area.top() + midy,
0, 0, 1, 0,
0, 0, 0, 1
);
// matrices used for projecting and unprojecting points
const Ogre::Matrix4 proj(OgreRenderer::glmToOgreMatrix(gb.getModelMatrix()) * d_matrix * vpmat);
const Ogre::Matrix4 unproj(proj.inverse());
Ogre::Vector3 in;
// unproject the ends of the ray
in.x = midx;
in.y = midy;
in.z = -d_viewDistance;
const Ogre::Vector3 r1(unproj * in);
in.x = p_in.x;
in.y = p_in.y;
in.z = 0;
// calculate vector of picking ray
const Ogre::Vector3 rv(r1 - unproj * in);
// project points to orientate them with GeometryBuffer plane
in.x = 0.0;
in.y = 0.0;
const Ogre::Vector3 p1(proj * in);
in.x = 1.0;
in.y = 0.0;
const Ogre::Vector3 p2(proj * in);
in.x = 0.0;
in.y = 1.0;
const Ogre::Vector3 p3(proj * in);
// calculate the plane normal
const Ogre::Vector3 pn((p2 - p1).crossProduct(p3 - p1));
// calculate distance from origin
const Ogre::Real plen = pn.length();
const Ogre::Real dist = -(p1.x * (pn.x / plen) +
p1.y * (pn.y / plen) +
p1.z * (pn.z / plen));
// calculate intersection of ray and plane
const Ogre::Real pn_dot_rv = pn.dotProduct(rv);
const Ogre::Real tmp = pn_dot_rv != 0.0 ?
(pn.dotProduct(r1) + dist) / pn_dot_rv :
0.0f;
p_out.x = static_cast<float>(r1.x - rv.x * tmp);
p_out.y = static_cast<float>(r1.y - rv.y * tmp);
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateMatrix() const
{
const float w = d_area.getWidth();
const float h = d_area.getHeight();
// We need to check if width or height are zero and act accordingly to prevent running into issues
// with divisions by zero which would lead to undefined values, as well as faulty clipping planes
// This is mostly important for avoiding asserts
const bool widthAndHeightNotZero = ( w != 0.0f ) && ( h != 0.0f);
const float aspect = widthAndHeightNotZero ? w / h : 1.0f;
const float midx = widthAndHeightNotZero ? w * 0.5f : 0.5f;
const float midy = widthAndHeightNotZero ? h * 0.5f : 0.5f;
d_viewDistance = midx / (aspect * d_yfov_tan);
glm::vec3 eye = glm::vec3(midx, midy, -d_viewDistance);
glm::vec3 center = glm::vec3(midx, midy, 1);
glm::vec3 up = glm::vec3(0, -1, 0);
glm::mat4 projectionMatrix = glm::perspective(30.f, aspect, d_viewDistance * 0.5f, d_viewDistance * 2.0f);
// Projection matrix abuse!
glm::mat4 viewMatrix = glm::lookAt(eye, center, up);
glm::mat4 finalMatrix = projectionMatrix * viewMatrix;
Ogre::Matrix4 temp = OgreRenderer::glmToOgreMatrix(finalMatrix);
d_renderSystem._convertProjectionMatrix(temp, d_matrix, true);
d_matrixValid = true;
//! This will trigger the RenderTarget to notify all of its GeometryBuffers to regenerate their matrices
RenderTarget::d_activationCounter = -1;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateViewport()
{
if (!d_viewport)
{
#ifdef CEGUI_USE_OGRE_COMPOSITOR2
d_viewport = OGRE_NEW Ogre::Viewport(d_renderTarget, 0, 0, 1, 1);
#else
d_viewport = OGRE_NEW Ogre::Viewport(0, d_renderTarget, 0, 0, 1, 1, 0);
#endif // CEGUI_USE_OGRE_COMPOSITOR2
updateOgreViewportDimensions(d_renderTarget);
}
d_viewport->_updateDimensions();
d_viewportValid = true;
}
//----------------------------------------------------------------------------//
template <typename T>
Renderer& OgreRenderTarget<T>::getOwner()
{
return d_owner;
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<commit_msg>MOD: Removing matrix conversion<commit_after>/***********************************************************************
created: Tue Feb 17 2009
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUI/RendererModules/Ogre/RenderTarget.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/RenderQueue.h"
#include "CEGUI/RendererModules/Ogre/GeometryBuffer.h"
#include <OgreRenderSystem.h>
#include <OgreCamera.h>
#include <OgreViewport.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
template <typename T>
const float OgreRenderTarget<T>::d_yfov_tan = 0.267949192431123f;
//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::OgreRenderTarget(OgreRenderer& owner,
Ogre::RenderSystem& rs) :
d_owner(owner),
d_renderSystem(rs),
d_area(0, 0, 0, 0),
d_renderTarget(0),
d_viewport(0),
d_ogreViewportDimensions(0, 0, 0, 0),
d_matrix(Ogre::Matrix4::IDENTITY),
d_matrixValid(false),
d_viewportValid(false),
d_viewDistance(0)
{
}
//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::~OgreRenderTarget()
{
delete d_viewport;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const GeometryBuffer& buffer)
{
buffer.draw();
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const RenderQueue& queue)
{
queue.draw();
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::setArea(const Rectf& area)
{
d_area = area;
setOgreViewportDimensions(area);
d_matrixValid = false;
RenderTargetEventArgs args(this);
T::fireEvent(RenderTarget::EventAreaChanged, args);
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::setOgreViewportDimensions(const Rectf& area)
{
d_ogreViewportDimensions = area;
if (d_viewport)
updateOgreViewportDimensions(d_viewport->getTarget());
d_viewportValid = false;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateOgreViewportDimensions(
const Ogre::RenderTarget* const rt)
{
if (rt)
{
if(d_viewport)
d_viewport->setDimensions(
d_ogreViewportDimensions.left() / rt->getWidth(),
d_ogreViewportDimensions.top() / rt->getHeight(),
d_ogreViewportDimensions.getWidth() / rt->getWidth(),
d_ogreViewportDimensions.getHeight() / rt->getHeight());
}
}
//----------------------------------------------------------------------------//
template <typename T>
const Rectf& OgreRenderTarget<T>::getArea() const
{
return d_area;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::activate()
{
if (!d_matrixValid)
updateMatrix();
if (!d_viewportValid)
updateViewport();
d_renderSystem._setViewport(d_viewport);
d_owner.setProjectionMatrix(d_matrix);
RenderTarget::activate();
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::deactivate()
{
// currently nothing to do in the basic case
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff,
const glm::vec2& p_in,
glm::vec2& p_out) const
{
if (!d_matrixValid)
updateMatrix();
const OgreGeometryBuffer& gb = static_cast<const OgreGeometryBuffer&>(buff);
const Ogre::Real midx = d_area.getWidth() * 0.5f;
const Ogre::Real midy = d_area.getHeight() * 0.5f;
// viewport matrix
const Ogre::Matrix4 vpmat(
midx, 0, 0, d_area.left() + midx,
0, -midy, 0, d_area.top() + midy,
0, 0, 1, 0,
0, 0, 0, 1
);
// matrices used for projecting and unprojecting points
const Ogre::Matrix4 proj(OgreRenderer::glmToOgreMatrix(gb.getModelMatrix()) * d_matrix * vpmat);
const Ogre::Matrix4 unproj(proj.inverse());
Ogre::Vector3 in;
// unproject the ends of the ray
in.x = midx;
in.y = midy;
in.z = -d_viewDistance;
const Ogre::Vector3 r1(unproj * in);
in.x = p_in.x;
in.y = p_in.y;
in.z = 0;
// calculate vector of picking ray
const Ogre::Vector3 rv(r1 - unproj * in);
// project points to orientate them with GeometryBuffer plane
in.x = 0.0;
in.y = 0.0;
const Ogre::Vector3 p1(proj * in);
in.x = 1.0;
in.y = 0.0;
const Ogre::Vector3 p2(proj * in);
in.x = 0.0;
in.y = 1.0;
const Ogre::Vector3 p3(proj * in);
// calculate the plane normal
const Ogre::Vector3 pn((p2 - p1).crossProduct(p3 - p1));
// calculate distance from origin
const Ogre::Real plen = pn.length();
const Ogre::Real dist = -(p1.x * (pn.x / plen) +
p1.y * (pn.y / plen) +
p1.z * (pn.z / plen));
// calculate intersection of ray and plane
const Ogre::Real pn_dot_rv = pn.dotProduct(rv);
const Ogre::Real tmp = pn_dot_rv != 0.0 ?
(pn.dotProduct(r1) + dist) / pn_dot_rv :
0.0f;
p_out.x = static_cast<float>(r1.x - rv.x * tmp);
p_out.y = static_cast<float>(r1.y - rv.y * tmp);
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateMatrix() const
{
const float w = d_area.getWidth();
const float h = d_area.getHeight();
// We need to check if width or height are zero and act accordingly to prevent running into issues
// with divisions by zero which would lead to undefined values, as well as faulty clipping planes
// This is mostly important for avoiding asserts
const bool widthAndHeightNotZero = ( w != 0.0f ) && ( h != 0.0f);
const float aspect = widthAndHeightNotZero ? w / h : 1.0f;
const float midx = widthAndHeightNotZero ? w * 0.5f : 0.5f;
const float midy = widthAndHeightNotZero ? h * 0.5f : 0.5f;
d_viewDistance = midx / (aspect * d_yfov_tan);
glm::vec3 eye = glm::vec3(midx, midy, -d_viewDistance);
glm::vec3 center = glm::vec3(midx, midy, 1);
glm::vec3 up = glm::vec3(0, -1, 0);
glm::mat4 projectionMatrix = glm::perspective(30.f, aspect, d_viewDistance * 0.5f, d_viewDistance * 2.0f);
// Projection matrix abuse!
glm::mat4 viewMatrix = glm::lookAt(eye, center, up);
glm::mat4 finalMatrix = projectionMatrix * viewMatrix;
d_matrix = OgreRenderer::glmToOgreMatrix(finalMatrix);
d_matrixValid = true;
//! This will trigger the RenderTarget to notify all of its GeometryBuffers to regenerate their matrices
RenderTarget::d_activationCounter = -1;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateViewport()
{
if (!d_viewport)
{
#ifdef CEGUI_USE_OGRE_COMPOSITOR2
d_viewport = OGRE_NEW Ogre::Viewport(d_renderTarget, 0, 0, 1, 1);
#else
d_viewport = OGRE_NEW Ogre::Viewport(0, d_renderTarget, 0, 0, 1, 1, 0);
#endif // CEGUI_USE_OGRE_COMPOSITOR2
updateOgreViewportDimensions(d_renderTarget);
}
d_viewport->_updateDimensions();
d_viewportValid = true;
}
//----------------------------------------------------------------------------//
template <typename T>
Renderer& OgreRenderTarget<T>::getOwner()
{
return d_owner;
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>#include "RedBlackTree.h"
#include <algorithm>
#include <cassert>
#include <utility>
#define RED 'R'
#define BLACK 'B'
RbNode RBNIL = {BLACK, -1, &RBNIL, &RBNIL, &RBNIL};
#define is_nil(e) ((e) == &RBNIL)
#define not_nil(e) ((e) != &RBNIL)
#define set_nil(e) ((e) = &RBNIL)
#define is_leaf(e) (is_nil((e)->left) && is_nil((e)->right))
static RbNode *Previous(RbNode *e) {
while (not_nil(e->left))
e = e->left;
return e;
}
static RbNode *Next(RbNode *e) {
if (is_nil(e->right)) {
return &RBNIL;
}
RbNode *next = e->right;
while (not_nil(next->left)) {
next = next->left;
}
return next;
}
static RbNode *GrandFather(RbNode *e) {
if (is_nil(e))
return &RBNIL;
if (is_nil(e->father))
return &RBNIL;
return e->father->father;
}
static RbNode *Uncle(RbNode *e) {
if (is_nil(GrandFather(e)))
return &RBNIL;
if (GrandFather(e)->left == e)
return GrandFather(e)->right;
if (GrandFather(e)->right == e)
return GrandFather(e)->left;
return &RBNIL;
}
static bool IsLeft(RbNode *e) {
if (is_nil(e->father))
return false;
return e->father->left == e;
}
static bool IsRight(RbNode *e) {
if (is_nil(e->father))
return false;
return e->father->right == e;
}
static int ChildNumber(RbNode *e) {
return is_nil(e) ? 0
: ((is_nil(e->left) ? 0 : 1) + (is_nil(e->right) ? 0 : 1));
}
static RbNode *Brother(RbNode *e) {
if (is_nil(e))
return &RBNIL;
if (IsLeft(e)) {
return e->father->right;
}
if (IsRight(e)) {
return e->father->left;
}
return &RBNIL;
}
static void Free(RbNode *e) {
if (is_nil(e))
return;
Free(e->left);
Free(e->right);
delete e;
}
static void LeftRotate(RbNode *&father, RbNode *&e) {
RbNode *p_right = e->right;
e->right = p_right->left;
if (not_nil(e->right)) {
e->right->father = e;
}
p_right->father = e->father;
if (is_nil(e->father)) {
father = p_right;
} else if (e == e->father->left) {
e->father->left = p_right;
} else {
e->father->right = p_right;
}
p_right->left = e;
e->father = p_right;
}
static void RightRotate(RbNode *&father, RbNode *&e) {
RbNode *p_left = e->left;
e->left = p_left->right;
if (not_nil(e->left)) {
e->left->father = e;
}
p_left->father = e->father;
if (is_nil(e->father)) {
father = p_left;
} else if (e == e->father->left) {
e->father->left = p_left;
} else {
e->father->right = p_left;
}
p_left->right = e;
e->father = p_left;
}
void FixInsert(RbNode *&root, RbNode *&e) {
RbNode *e_father = &RBNIL;
RbNode *e_grand_father = &RBNIL;
while ((e != root) && (e->color != BLACK) && (e->father->color == RED)) {
e_father = e->father;
e_grand_father = e->father->father;
// case A
if (e_father == e_grand_father->left) {
RbNode *e_uncle = e_grand_father->right;
// case 1: Red Uncle
if (not_nil(e_uncle) && e_uncle->color == RED) {
e_grand_father->color = RED;
e_father->color = BLACK;
e_uncle->color = BLACK;
e = e_grand_father;
} else {
// case 2: Black Uncle, left-right-case
if (e == e_father->right) {
LeftRotate(root, e_father);
e = e_father;
e_father = e->father;
}
// case 3: Black Uncle, left-left-case
RightRotate(root, e_grand_father);
std::swap(e_father->color, e_grand_father->color);
e = e_father;
}
}
// case B
else {
RbNode *e_uncle = e_grand_father->right;
// case 1: Red Uncle
if (not_nil(e_uncle) && (e_uncle->color == RED)) {
e_grand_father->color = RED;
e_father->color = BLACK;
e_uncle->color = BLACK;
e = e_grand_father;
} else {
// case 4: Black Uncle, left-right-case
if (e == e_father->left) {
RightRotate(root, e_father);
e = e_father;
e_father = e->father;
}
// case 5: Black Uncle, right-right-case
LeftRotate(root, e_grand_father);
std::swap(e_father->color, e_grand_father->color);
e = e_father;
}
}
} // while
root->color = BLACK;
} // FixInsert
static RbNode *Replace(RbNode *e) {
if (not_nil(e->left) && not_nil(e->right)) {
return Previous(e->right);
}
if (is_nil(e->left) && is_nil(e->right)) {
return &RBNIL;
}
if (not_nil(e->left)) {
return e->left;
} else {
return e->right;
}
}
static void FixErase(RbNode *&root, RbNode *&e) {
if (e == root) {
e->color = BLACK;
return;
}
RbNode *e_father = e->father;
RbNode *e_grand_father = e_father->father;
RbNode *e_uncle = Uncle(e);
if (e_father->color != BLACK) {
if (not_nil(e_uncle) && e_uncle->color == RED) {
e_father->color = BLACK;
e_uncle->color = BLACK;
e_grand_father->color = RED;
e_grand_father->color = RED;
}
}
}
static void Erase(RbNode *&root, RbNode *&e) {
RbNode *p = Replace(e);
bool pe_black = ((is_nil(p) || p->color == BLACK) && (e->color == BLACK));
RbNode *e_father = e->father;
if (is_nil(p)) {
if (e == root) {
set_nil(root);
} else {
if (pe_black) {
FixErase(root, e);
} else {
if (not_nil(Uncle(e))) {
Uncle(e)->color = RED;
}
}
if (IsLeft(e)) {
set_nil(e_father->left);
} else {
set_nil(e_father->right);
}
}
delete e;
return;
} // if (is_nil(p))
if (is_nil(e->left) || is_nil(e->right)) {
if (e == root) {
e->value = p->value;
set_nil(e->left);
set_nil(e->right);
delete p;
} else {
if (IsLeft(e)) {
e_father->left = p;
} else {
e_father->right = p;
}
delete e;
p->father = e_father;
if (pe_black) {
FixErase(root, e);
} else {
p->color = BLACK;
}
}
return;
} // if (is_nil(e->left) || is_nil(e->right))
std::swap(p->color, e->color);
Erase(root, e);
} // Erase
static RbNode *Find(RbNode *e, int value) {
if (is_nil(e)) {
return &RBNIL;
}
//二分查找
if (e->value == value) {
return e;
} else if (e->value > value) {
return Find(e->left, value);
} else {
return Find(e->right, value);
}
}
static RbNode *Insert(RbNode *father, RbNode *e) {
assert(father);
assert(e);
if (is_nil(father)) {
return e;
}
//利用二分查找找到适合value插入的位置e
if (father->value > e->value) {
father->left = Insert(father->left, e);
father->left->father = father;
} else if (father->value < e->value) {
father->right = Insert(father->right, e);
father->right->father = father;
} else {
assert(father->value != e->value);
}
return father;
}
RedBlackTree *RedBlackTreeNew() {
RedBlackTree *t = new RedBlackTree();
if (!t)
return NULL;
t->root = &RBNIL;
return t;
}
void RedBlackTreeFree(RedBlackTree *t) {
assert(t);
Free(t->root);
delete t;
}
void RedBlackTreeInsert(RedBlackTree *t, int value) {
assert(t);
assert(value >= 0);
RbNode *e = new RbNode();
set_nil(e->left);
set_nil(e->right);
set_nil(e->father);
e->color = RED; // new node is red
e->value = value;
t->root = Insert(t->root, e);
FixInsert(t->root, e);
}
RbNode *RedBlackTreeFind(RedBlackTree *t, int value) {
return Find(t->root, value);
}
void RedBlackTreeErase(RedBlackTree *t, int value) {
RbNode *e = Find(t->root, value);
if (is_nil(e)) {
return;
}
Erase(t->root, e);
}
<commit_msg>save code<commit_after>#include "RedBlackTree.h"
#include <algorithm>
#include <cassert>
#include <utility>
#define RED 'R'
#define BLACK 'B'
RbNode RBNIL = {BLACK, -1, &RBNIL, &RBNIL, &RBNIL};
#define is_nil(e) ((e) == &RBNIL)
#define not_nil(e) ((e) != &RBNIL)
#define set_nil(e) ((e) = &RBNIL)
#define is_leaf(e) (is_nil((e)->left) && is_nil((e)->right))
static RbNode *Next(RbNode *e) {
if (is_nil(e->right)) {
return &RBNIL;
}
RbNode *next = e->right;
while (not_nil(next->left)) {
next = next->left;
}
return next;
}
static RbNode *GrandFather(RbNode *e) {
if (is_nil(e))
return &RBNIL;
if (is_nil(e->father))
return &RBNIL;
return e->father->father;
}
static RbNode *Uncle(RbNode *e) {
if (is_nil(GrandFather(e)))
return &RBNIL;
if (GrandFather(e)->left == e)
return GrandFather(e)->right;
if (GrandFather(e)->right == e)
return GrandFather(e)->left;
return &RBNIL;
}
static bool IsLeft(RbNode *e) {
if (is_nil(e->father))
return false;
return e->father->left == e;
}
static bool IsRight(RbNode *e) {
if (is_nil(e->father))
return false;
return e->father->right == e;
}
static RbNode *Brother(RbNode *e) {
if (is_nil(e))
return &RBNIL;
if (IsLeft(e)) {
return e->father->right;
}
if (IsRight(e)) {
return e->father->left;
}
return &RBNIL;
}
static void Free(RbNode *e) {
if (is_nil(e))
return;
Free(e->left);
Free(e->right);
delete e;
}
static void LeftRotate(RbNode *&father, RbNode *&e) {
RbNode *p_right = e->right;
e->right = p_right->left;
if (not_nil(e->right)) {
e->right->father = e;
}
p_right->father = e->father;
if (is_nil(e->father)) {
father = p_right;
} else if (e == e->father->left) {
e->father->left = p_right;
} else {
e->father->right = p_right;
}
p_right->left = e;
e->father = p_right;
}
static void RightRotate(RbNode *&father, RbNode *&e) {
RbNode *p_left = e->left;
e->left = p_left->right;
if (not_nil(e->left)) {
e->left->father = e;
}
p_left->father = e->father;
if (is_nil(e->father)) {
father = p_left;
} else if (e == e->father->left) {
e->father->left = p_left;
} else {
e->father->right = p_left;
}
p_left->right = e;
e->father = p_left;
}
void FixInsert(RbNode *&root, RbNode *&e) {
RbNode *e_father, *e_grand_father;
set_nil(e_father);
set_nil(e_grand_father);
while ((e != root) && (e->color != BLACK) && (e->father->color == RED)) {
e_father = e->father;
e_grand_father = e->father->father;
// case A
if (e_father == e_grand_father->left) {
RbNode *e_uncle = e_grand_father->right;
// case 1: Red Uncle
if (not_nil(e_uncle) && e_uncle->color == RED) {
e_grand_father->color = RED;
e_father->color = BLACK;
e_uncle->color = BLACK;
e = e_grand_father;
} else {
// case 2: Black Uncle, left-right-case
if (e == e_father->right) {
LeftRotate(root, e_father);
e = e_father;
e_father = e->father;
}
// case 3: Black Uncle, left-left-case
RightRotate(root, e_grand_father);
std::swap(e_father->color, e_grand_father->color);
e = e_father;
}
}
// case B
else {
RbNode *e_uncle = e_grand_father->right;
// case 1: Red Uncle
if (not_nil(e_uncle) && (e_uncle->color == RED)) {
e_grand_father->color = RED;
e_father->color = BLACK;
e_uncle->color = BLACK;
e = e_grand_father;
} else {
// case 4: Black Uncle, left-right-case
if (e == e_father->left) {
RightRotate(root, e_father);
e = e_father;
e_father = e->father;
}
// case 5: Black Uncle, right-right-case
LeftRotate(root, e_grand_father);
std::swap(e_father->color, e_grand_father->color);
e = e_father;
}
}
} // while
root->color = BLACK;
} // FixInsert
static RbNode *Replace(RbNode *e) {
if (not_nil(e->left) && not_nil(e->right)) {
return Next(e->right);
}
if (is_nil(e->left) && is_nil(e->right)) {
return &RBNIL;
}
if (not_nil(e->left)) {
return e->left;
} else {
return e->right;
}
}
static void FixErase(RbNode *&root, RbNode *&e) {
// reach root
if (e == root) {
return;
}
RbNode *e_brother = &RBNIL;
RbNode *e_father = &RBNIL;
while (true) {
e_brother = Brother(e);
e_father = e->father;
RbNode *e_brother = Brother(e);
RbNode *e_father = e->father;
if (is_nil(e_brother)) {
// no brother
// double black pushed up
FixErase(root, e_father);
} else {
if (e_brother->color == RED) {
// brother red
e_father->color = RED;
e_brother->color = BLACK;
if (IsLeft(e_brother)) {
// left case
RightRotate(root, e_father);
} else {
// right case
LeftRotate(root, e_father);
}
FixErase(root, e);
} else {
// brother black
if (e_brother->left->color == RED || e_brother->right->color == RED) {
// at least 1 red children
if (not_nil(e_brother->left) && e_brother->left->color == RED) {
if (IsLeft(e_brother)) {
// left left
e_brother->left->color = e_brother->color;
e_brother->color = e_father->color;
RightRotate(root, e_father);
} else {
// right left
e_brother->left->color = e_father->color;
RightRotate(root, e_brother);
LeftRotate(root, e_father);
}
} else {
if (IsLeft(e_brother)) {
// left right
e_brother->right->color = e_father->color;
LeftRotate(root, e_brother);
RightRotate(root, e_father);
} else {
// right right
e_brother->right->color = e_brother->color;
e_brother->color = e_father->color;
LeftRotate(root, e_father);
}
}
e_father->color = BLACK;
} else {
// 2 black children
e_brother->color = RED;
if (e_father->color == BLACK) {
FixErase(root, e_father);
} else {
e_father->color = BLACK;
}
}
}
}
} // while
} // FixErase
static void Erase(RbNode *&root, RbNode *&e) {
RbNode *p = Replace(e);
bool pe_black = ((is_nil(p) || p->color == BLACK) && (e->color == BLACK));
RbNode *e_father = e->father;
if (is_nil(p)) {
if (e == root) {
set_nil(root);
} else {
if (pe_black) {
FixErase(root, e);
} else {
if (not_nil(Uncle(e))) {
Uncle(e)->color = RED;
}
}
if (IsLeft(e)) {
set_nil(e_father->left);
} else {
set_nil(e_father->right);
}
}
delete e;
return;
} // if (is_nil(p))
if (is_nil(e->left) || is_nil(e->right)) {
if (e == root) {
e->value = p->value;
set_nil(e->left);
set_nil(e->right);
delete p;
} else {
if (IsLeft(e)) {
e_father->left = p;
} else {
e_father->right = p;
}
delete e;
p->father = e_father;
if (pe_black) {
FixErase(root, e);
} else {
p->color = BLACK;
}
}
return;
} // if (is_nil(e->left) || is_nil(e->right))
std::swap(p->color, e->color);
Erase(root, e);
} // Erase
static RbNode *Find(RbNode *e, int value) {
if (is_nil(e)) {
return &RBNIL;
}
//二分查找
if (e->value == value) {
return e;
} else if (e->value > value) {
return Find(e->left, value);
} else {
return Find(e->right, value);
}
}
static RbNode *Insert(RbNode *father, RbNode *e) {
assert(father);
assert(e);
if (is_nil(father)) {
return e;
}
//利用二分查找找到适合value插入的位置e
if (father->value > e->value) {
father->left = Insert(father->left, e);
father->left->father = father;
} else if (father->value < e->value) {
father->right = Insert(father->right, e);
father->right->father = father;
} else {
assert(father->value != e->value);
}
return father;
}
RedBlackTree *RedBlackTreeNew() {
RedBlackTree *t = new RedBlackTree();
if (!t)
return NULL;
t->root = &RBNIL;
return t;
}
void RedBlackTreeFree(RedBlackTree *t) {
assert(t);
Free(t->root);
delete t;
}
void RedBlackTreeInsert(RedBlackTree *t, int value) {
assert(t);
assert(value >= 0);
RbNode *e = new RbNode();
set_nil(e->left);
set_nil(e->right);
set_nil(e->father);
e->color = RED; // new node is red
e->value = value;
t->root = Insert(t->root, e);
FixInsert(t->root, e);
}
RbNode *RedBlackTreeFind(RedBlackTree *t, int value) {
return Find(t->root, value);
}
void RedBlackTreeErase(RedBlackTree *t, int value) {
RbNode *e = Find(t->root, value);
if (is_nil(e)) {
return;
}
Erase(t->root, e);
}
<|endoftext|> |
<commit_before>#include "GolfBall.hpp"
#include "../Resources.hpp"
#include "Default3D.vert.hpp"
#include "Default3D.geom.hpp"
#include "Default3D.frag.hpp"
#include "glm\gtc\constants.hpp"
GolfBall::GolfBall(BallType ballType) : Object() {
active = false;
modelGeometry = new Geometry::Model("Resources/Models/rock/Rock.bin");
std::string diffusePath = "Resources/Models/rock/diffuse.tga";
std::string normalPath = "Resources/Models/rock/normal.tga";
std::string specularPath = "Resources/Models/rock/specular.tga";
modelObject = new ModelObject(modelGeometry, diffusePath, normalPath, specularPath);
modelObject->SetPosition(2.f, 0.f, 0.f);
modelObject->SetScale(glm::vec3(0.01f, 0.01f, 0.01f));
/// @todo Mass based on explosive material.
mass = 0.0459f;
this->ballType = ballType;
SetRadius(0.0214f);
}
GolfBall::~GolfBall() {
delete modelObject;
delete modelGeometry;
}
void GolfBall::Update(double time, const glm::vec3& wind) {
if (active) {
modelObject->Move(static_cast<float>(time)* velocity);
float horizontal = static_cast<float>(time)*angularVelocity.x;
float vertical = static_cast<float>(time)*angularVelocity.y;
float tilt = static_cast<float>(time)*angularVelocity.z;
modelObject->Rotate(horizontal, vertical, tilt);
float v = velocity.length();
float w = angularVelocity.length();
float u = (velocity - wind).length();
float Cm = (sqrt(1.f + 0.31f*(v/w))-1.f)/20.f;
float Fm = 0.5f*Cm*1.23*area*u*u;
glm::vec3 eU = (velocity - wind) / u;
/// Calculate drive force.
float cD;
if (ballType == TWOPIECE) {
cD = v < 65.f ? -0.0051f * v + 0.53f : 0.21f;
} else {
cD = v < 60.f ? -0.0084f * v + 0.73f : 0.22f;
}
glm::vec3 driveForce = -0.5f * 1.23f * area * cD * u * u * eU;
glm::vec3 magnusForce = Fm*(cross(eU, (angularVelocity / w)));
// Calculate gravitational force.
glm::vec3 gravitationForce = glm::vec3(0.f, mass * -9.82f, 0.f);
glm::vec3 acceleration = (driveForce + magnusForce + gravitationForce) / mass;
velocity += acceleration * static_cast<float>(time);
}
}
void GolfBall::Render(Camera* camera, const glm::vec2& screenSize) const{
modelObject->Render(camera, screenSize);
}
void GolfBall::Strike() {
active = true;
/// @todo Calculate velocity based on club mass, loft and velocity.
velocity = glm::vec3(20.f, 5.f, 0.f);
angularVelocity = glm::vec3(0.f,0.f,-80.f);
}
void GolfBall::SetRadius(float radius) {
this->radius = radius;
SetScale(2.f * glm::vec3(radius, radius, radius));
area = glm::pi<float>() * radius * radius;
}
<commit_msg>Work on angular velocity.<commit_after>#include "GolfBall.hpp"
#include "../Resources.hpp"
#include "Default3D.vert.hpp"
#include "Default3D.geom.hpp"
#include "Default3D.frag.hpp"
#include "glm\gtc\constants.hpp"
GolfBall::GolfBall(BallType ballType) : Object() {
active = false;
modelGeometry = new Geometry::Model("Resources/Models/rock/Rock.bin");
std::string diffusePath = "Resources/Models/rock/diffuse.tga";
std::string normalPath = "Resources/Models/rock/normal.tga";
std::string specularPath = "Resources/Models/rock/specular.tga";
modelObject = new ModelObject(modelGeometry, diffusePath, normalPath, specularPath);
modelObject->SetPosition(2.f, 0.f, 0.f);
modelObject->SetScale(glm::vec3(0.01f, 0.01f, 0.01f));
/// @todo Mass based on explosive material.
mass = 0.0459f;
this->ballType = ballType;
SetRadius(0.0214f);
}
GolfBall::~GolfBall() {
delete modelObject;
delete modelGeometry;
}
void GolfBall::Update(double time, const glm::vec3& wind) {
if (active) {
modelObject->Move(static_cast<float>(time)* velocity);
float horizontal = static_cast<float>(time)*angularVelocity.x;
float vertical = static_cast<float>(time)*angularVelocity.y;
float tilt = -static_cast<float>(time)*angularVelocity.z;
modelObject->Rotate(horizontal, vertical, tilt);
float v = velocity.length();
float w = angularVelocity.length();
float u = (velocity - wind).length();
float Cm = (sqrt(1.f + 0.31f*(v/w))-1.f)/20.f;
float Fm = 0.5f*Cm*1.23*area*u*u;
glm::vec3 eU = (velocity - wind) / u;
/// Calculate drive force.
float cD;
if (ballType == TWOPIECE) {
cD = v < 65.f ? -0.0051f * v + 0.53f : 0.21f;
} else {
cD = v < 60.f ? -0.0084f * v + 0.73f : 0.22f;
}
glm::vec3 driveForce = -0.5f * 1.23f * area * cD * u * u * eU;
glm::vec3 magnusForce = Fm*(cross(eU, (angularVelocity / w)));
// Calculate gravitational force.
glm::vec3 gravitationForce = glm::vec3(0.f, mass * -9.82f, 0.f);
glm::vec3 acceleration = (driveForce + magnusForce + gravitationForce) / mass;
velocity += acceleration * static_cast<float>(time);
}
}
void GolfBall::Render(Camera* camera, const glm::vec2& screenSize) const{
modelObject->Render(camera, screenSize);
}
void GolfBall::Strike() {
active = true;
/// @todo Calculate velocity based on club mass, loft and velocity.
velocity = glm::vec3(20.f, 5.f, 0.f);
angularVelocity = glm::vec3(0.f,0.f,-800.f);
}
void GolfBall::SetRadius(float radius) {
this->radius = radius;
SetScale(2.f * glm::vec3(radius, radius, radius));
area = glm::pi<float>() * radius * radius;
}
<|endoftext|> |
<commit_before>#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <direct.h>
#else
#include <dirent.h>
#include <unistd.h>
#include <errno.h>
#endif
#include <cstring>
#include <string>
#include <set>
#include <algorithm>
#include <stdio.h>
#include <sys/stat.h>
#include <ctype.h>
#include "base/logging.h"
#include "base/basictypes.h"
#include "file/file_util.h"
#if defined(__FreeBSD__) || defined(__APPLE__) || defined(__SYMBIAN32__)
#define stat64 stat
#endif
// Hack
#ifdef __SYMBIAN32__
static inline int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result) {
struct dirent *readdir_entry;
readdir_entry = readdir(dirp);
if (readdir_entry == NULL) {
*result = NULL;
return errno;
}
*entry = *readdir_entry;
*result = entry;
return 0;
}
#endif
bool writeStringToFile(bool text_file, const std::string &str, const char *filename)
{
FILE *f = fopen(filename, text_file ? "w" : "wb");
if (!f)
return false;
size_t len = str.size();
if (len != fwrite(str.data(), 1, str.size(), f))
{
fclose(f);
return false;
}
fclose(f);
return true;
}
bool writeDataToFile(bool text_file, const void* data, const unsigned int size, const char *filename)
{
FILE *f = fopen(filename, text_file ? "w" : "wb");
if (!f)
return false;
size_t len = size;
if (len != fwrite(data, 1, len, f))
{
fclose(f);
return false;
}
fclose(f);
return true;
}
uint64_t GetSize(FILE *f)
{
// can't use off_t here because it can be 32-bit
uint64_t pos = ftell(f);
if (fseek(f, 0, SEEK_END) != 0) {
return 0;
}
uint64_t size = ftell(f);
// Reset the seek position to where it was when we started.
if ((size != pos) && (fseek(f, pos, SEEK_SET) != 0)) {
// Should error here
return 0;
}
return size;
}
bool ReadFileToString(bool text_file, const char *filename, std::string &str)
{
FILE *f = fopen(filename, text_file ? "r" : "rb");
if (!f)
return false;
size_t len = (size_t)GetSize(f);
char *buf = new char[len + 1];
buf[fread(buf, 1, len, f)] = 0;
str = std::string(buf, len);
fclose(f);
delete [] buf;
return true;
}
bool readDataFromFile(bool text_file, unsigned char* &data, const unsigned int size, const char *filename)
{
FILE *f = fopen(filename, text_file ? "r" : "rb");
if (!f)
return false;
size_t len = (size_t)GetSize(f);
if(len < size)
{
fclose(f);
return false;
}
data[fread(data, 1, size, f)] = 0;
fclose(f);
return true;
}
#define DIR_SEP "/"
#define DIR_SEP_CHR '\\'
#ifndef METRO
// Remove any ending forward slashes from directory paths
// Modifies argument.
static void stripTailDirSlashes(std::string &fname)
{
if (fname.length() > 1)
{
size_t i = fname.length() - 1;
while (fname[i] == DIR_SEP_CHR)
fname[i--] = '\0';
}
return;
}
// Returns true if file filename exists
bool exists(const std::string &filename)
{
#ifdef _WIN32
return GetFileAttributes(filename.c_str()) != 0xFFFFFFFF;
#else
struct stat64 file_info;
std::string copy(filename);
stripTailDirSlashes(copy);
int result = stat64(copy.c_str(), &file_info);
return (result == 0);
#endif
}
// Returns true if filename is a directory
bool isDirectory(const std::string &filename)
{
FileInfo info;
getFileInfo(filename.c_str(), &info);
return info.isDirectory;
}
bool getFileInfo(const char *path, FileInfo *fileInfo)
{
// TODO: Expand relative paths?
fileInfo->fullName = path;
#ifdef _WIN32
fileInfo->size = 0;
WIN32_FILE_ATTRIBUTE_DATA attrs;
if (GetFileAttributesExA(path, GetFileExInfoStandard, &attrs)) {
fileInfo->size = (uint64_t)attrs.nFileSizeLow | ((uint64_t)attrs.nFileSizeHigh << 32);
}
fileInfo->isDirectory = (attrs.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
fileInfo->isWritable = (attrs.dwFileAttributes & FILE_ATTRIBUTE_READONLY) == 0;
#else
struct stat64 file_info;
std::string copy(path);
stripTailDirSlashes(copy);
int result = stat64(copy.c_str(), &file_info);
if (result < 0) {
WLOG("IsDirectory: stat failed on %s", path);
return false;
}
fileInfo->isDirectory = S_ISDIR(file_info.st_mode);
fileInfo->isWritable = false;
fileInfo->size = file_info.st_size;
// HACK: approximation
if (file_info.st_mode & 0200)
fileInfo->isWritable = true;
#endif
return true;
}
std::string getFileExtension(const std::string &fn) {
int pos = fn.rfind(".");
if (pos < 0) return "";
std::string ext = fn.substr(pos+1);
for (size_t i = 0; i < ext.size(); i++) {
ext[i] = tolower(ext[i]);
}
return ext;
}
size_t getFilesInDir(const char *directory, std::vector<FileInfo> *files, const char *filter) {
size_t foundEntries = 0;
std::set<std::string> filters;
std::string tmp;
if (filter) {
while (*filter) {
if (*filter == ':') {
filters.insert(tmp);
tmp = "";
} else {
tmp.push_back(*filter);
}
filter++;
}
}
if (tmp.size())
filters.insert(tmp);
#ifdef _WIN32
// Find the first file in the directory.
WIN32_FIND_DATA ffd;
#ifdef UNICODE
HANDLE hFind = FindFirstFile((std::wstring(directory) + "\\*").c_str(), &ffd);
#else
HANDLE hFind = FindFirstFile((std::string(directory) + "\\*").c_str(), &ffd);
#endif
if (hFind == INVALID_HANDLE_VALUE) {
FindClose(hFind);
return 0;
}
// windows loop
do
{
const std::string virtualName(ffd.cFileName);
#else
struct dirent_large { struct dirent entry; char padding[FILENAME_MAX+1]; };
struct dirent_large diren;
struct dirent *result = NULL;
DIR *dirp = opendir(directory);
if (!dirp)
return 0;
// non windows loop
while (!readdir_r(dirp, (dirent*) &diren, &result) && result)
{
const std::string virtualName(result->d_name);
#endif
// check for "." and ".."
if (((virtualName[0] == '.') && (virtualName[1] == '\0')) ||
((virtualName[0] == '.') && (virtualName[1] == '.') &&
(virtualName[2] == '\0')))
continue;
// Remove dotfiles (should be made optional?)
if (virtualName[0] == '.')
continue;
FileInfo info;
info.name = virtualName;
info.fullName = std::string(directory) + "/" + virtualName;
info.isDirectory = isDirectory(info.fullName);
info.exists = true;
if (!info.isDirectory) {
std::string ext = getFileExtension(info.fullName);
if (filter) {
if (filters.find(ext) == filters.end())
continue;
}
}
files->push_back(info);
#ifdef _WIN32
} while (FindNextFile(hFind, &ffd) != 0);
FindClose(hFind);
#else
}
closedir(dirp);
#endif
std::sort(files->begin(), files->end());
return foundEntries;
}
void deleteFile(const char *file)
{
#ifdef _WIN32
if (!DeleteFile(file)) {
ELOG("Error deleting %s: %i", file, GetLastError());
}
#else
int err = unlink(file);
if (err) {
ELOG("Error unlinking %s: %i", file, err);
}
#endif
}
#endif
std::string getDir(const std::string &path)
{
if (path == "/")
return path;
int n = path.size() - 1;
while (n >= 0 && path[n] != '\\' && path[n] != '/')
n--;
std::string cutpath = n > 0 ? path.substr(0, n) : "";
for (size_t i = 0; i < cutpath.size(); i++)
{
if (cutpath[i] == '\\') cutpath[i] = '/';
}
#ifndef _WIN32
if (!cutpath.size()) {
return "/";
}
#endif
return cutpath;
}
void mkDir(const std::string &path)
{
#ifdef _WIN32
mkdir(path.c_str());
#else
mkdir(path.c_str(), 0777);
#endif
}
<commit_msg>Win32: Make getFileInfo() fail and label the path non-directory when GetFileAttributesExA fails<commit_after>#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <direct.h>
#else
#include <dirent.h>
#include <unistd.h>
#include <errno.h>
#endif
#include <cstring>
#include <string>
#include <set>
#include <algorithm>
#include <stdio.h>
#include <sys/stat.h>
#include <ctype.h>
#include "base/logging.h"
#include "base/basictypes.h"
#include "file/file_util.h"
#if defined(__FreeBSD__) || defined(__APPLE__) || defined(__SYMBIAN32__)
#define stat64 stat
#endif
// Hack
#ifdef __SYMBIAN32__
static inline int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result) {
struct dirent *readdir_entry;
readdir_entry = readdir(dirp);
if (readdir_entry == NULL) {
*result = NULL;
return errno;
}
*entry = *readdir_entry;
*result = entry;
return 0;
}
#endif
bool writeStringToFile(bool text_file, const std::string &str, const char *filename)
{
FILE *f = fopen(filename, text_file ? "w" : "wb");
if (!f)
return false;
size_t len = str.size();
if (len != fwrite(str.data(), 1, str.size(), f))
{
fclose(f);
return false;
}
fclose(f);
return true;
}
bool writeDataToFile(bool text_file, const void* data, const unsigned int size, const char *filename)
{
FILE *f = fopen(filename, text_file ? "w" : "wb");
if (!f)
return false;
size_t len = size;
if (len != fwrite(data, 1, len, f))
{
fclose(f);
return false;
}
fclose(f);
return true;
}
uint64_t GetSize(FILE *f)
{
// can't use off_t here because it can be 32-bit
uint64_t pos = ftell(f);
if (fseek(f, 0, SEEK_END) != 0) {
return 0;
}
uint64_t size = ftell(f);
// Reset the seek position to where it was when we started.
if ((size != pos) && (fseek(f, pos, SEEK_SET) != 0)) {
// Should error here
return 0;
}
return size;
}
bool ReadFileToString(bool text_file, const char *filename, std::string &str)
{
FILE *f = fopen(filename, text_file ? "r" : "rb");
if (!f)
return false;
size_t len = (size_t)GetSize(f);
char *buf = new char[len + 1];
buf[fread(buf, 1, len, f)] = 0;
str = std::string(buf, len);
fclose(f);
delete [] buf;
return true;
}
bool readDataFromFile(bool text_file, unsigned char* &data, const unsigned int size, const char *filename)
{
FILE *f = fopen(filename, text_file ? "r" : "rb");
if (!f)
return false;
size_t len = (size_t)GetSize(f);
if(len < size)
{
fclose(f);
return false;
}
data[fread(data, 1, size, f)] = 0;
fclose(f);
return true;
}
#define DIR_SEP "/"
#define DIR_SEP_CHR '\\'
#ifndef METRO
// Remove any ending forward slashes from directory paths
// Modifies argument.
static void stripTailDirSlashes(std::string &fname)
{
if (fname.length() > 1)
{
size_t i = fname.length() - 1;
while (fname[i] == DIR_SEP_CHR)
fname[i--] = '\0';
}
return;
}
// Returns true if file filename exists
bool exists(const std::string &filename)
{
#ifdef _WIN32
return GetFileAttributes(filename.c_str()) != 0xFFFFFFFF;
#else
struct stat64 file_info;
std::string copy(filename);
stripTailDirSlashes(copy);
int result = stat64(copy.c_str(), &file_info);
return (result == 0);
#endif
}
// Returns true if filename is a directory
bool isDirectory(const std::string &filename)
{
FileInfo info;
getFileInfo(filename.c_str(), &info);
return info.isDirectory;
}
bool getFileInfo(const char *path, FileInfo *fileInfo)
{
// TODO: Expand relative paths?
fileInfo->fullName = path;
#ifdef _WIN32
WIN32_FILE_ATTRIBUTE_DATA attrs;
if (!GetFileAttributesExA(path, GetFileExInfoStandard, &attrs)) {
fileInfo->size = 0;
fileInfo->isDirectory = false;
return false;
}
fileInfo->size = (uint64_t)attrs.nFileSizeLow | ((uint64_t)attrs.nFileSizeHigh << 32);
fileInfo->isDirectory = (attrs.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
fileInfo->isWritable = (attrs.dwFileAttributes & FILE_ATTRIBUTE_READONLY) == 0;
#else
struct stat64 file_info;
std::string copy(path);
stripTailDirSlashes(copy);
int result = stat64(copy.c_str(), &file_info);
if (result < 0) {
WLOG("IsDirectory: stat failed on %s", path);
return false;
}
fileInfo->isDirectory = S_ISDIR(file_info.st_mode);
fileInfo->isWritable = false;
fileInfo->size = file_info.st_size;
// HACK: approximation
if (file_info.st_mode & 0200)
fileInfo->isWritable = true;
#endif
return true;
}
std::string getFileExtension(const std::string &fn) {
int pos = fn.rfind(".");
if (pos < 0) return "";
std::string ext = fn.substr(pos+1);
for (size_t i = 0; i < ext.size(); i++) {
ext[i] = tolower(ext[i]);
}
return ext;
}
size_t getFilesInDir(const char *directory, std::vector<FileInfo> *files, const char *filter) {
size_t foundEntries = 0;
std::set<std::string> filters;
std::string tmp;
if (filter) {
while (*filter) {
if (*filter == ':') {
filters.insert(tmp);
tmp = "";
} else {
tmp.push_back(*filter);
}
filter++;
}
}
if (tmp.size())
filters.insert(tmp);
#ifdef _WIN32
// Find the first file in the directory.
WIN32_FIND_DATA ffd;
#ifdef UNICODE
HANDLE hFind = FindFirstFile((std::wstring(directory) + "\\*").c_str(), &ffd);
#else
HANDLE hFind = FindFirstFile((std::string(directory) + "\\*").c_str(), &ffd);
#endif
if (hFind == INVALID_HANDLE_VALUE) {
FindClose(hFind);
return 0;
}
// windows loop
do
{
const std::string virtualName(ffd.cFileName);
#else
struct dirent_large { struct dirent entry; char padding[FILENAME_MAX+1]; };
struct dirent_large diren;
struct dirent *result = NULL;
DIR *dirp = opendir(directory);
if (!dirp)
return 0;
// non windows loop
while (!readdir_r(dirp, (dirent*) &diren, &result) && result)
{
const std::string virtualName(result->d_name);
#endif
// check for "." and ".."
if (((virtualName[0] == '.') && (virtualName[1] == '\0')) ||
((virtualName[0] == '.') && (virtualName[1] == '.') &&
(virtualName[2] == '\0')))
continue;
// Remove dotfiles (should be made optional?)
if (virtualName[0] == '.')
continue;
FileInfo info;
info.name = virtualName;
info.fullName = std::string(directory) + "/" + virtualName;
info.isDirectory = isDirectory(info.fullName);
info.exists = true;
if (!info.isDirectory) {
std::string ext = getFileExtension(info.fullName);
if (filter) {
if (filters.find(ext) == filters.end())
continue;
}
}
files->push_back(info);
#ifdef _WIN32
} while (FindNextFile(hFind, &ffd) != 0);
FindClose(hFind);
#else
}
closedir(dirp);
#endif
std::sort(files->begin(), files->end());
return foundEntries;
}
void deleteFile(const char *file)
{
#ifdef _WIN32
if (!DeleteFile(file)) {
ELOG("Error deleting %s: %i", file, GetLastError());
}
#else
int err = unlink(file);
if (err) {
ELOG("Error unlinking %s: %i", file, err);
}
#endif
}
#endif
std::string getDir(const std::string &path)
{
if (path == "/")
return path;
int n = path.size() - 1;
while (n >= 0 && path[n] != '\\' && path[n] != '/')
n--;
std::string cutpath = n > 0 ? path.substr(0, n) : "";
for (size_t i = 0; i < cutpath.size(); i++)
{
if (cutpath[i] == '\\') cutpath[i] = '/';
}
#ifndef _WIN32
if (!cutpath.size()) {
return "/";
}
#endif
return cutpath;
}
void mkDir(const std::string &path)
{
#ifdef _WIN32
mkdir(path.c_str());
#else
mkdir(path.c_str(), 0777);
#endif
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <stdexcept>
#include <QClipboard>
#include <QMessageBox>
#include <QSettings>
#include <QSharedPointer>
#include <QWidget>
#include <QFile>
#include <CorpusWidget.hh>
#include <DactMacrosModel.hh>
#include <DactToolsMenu.hh>
#include <DactToolsModel.hh>
#include <DactTreeScene.hh>
#include <DactTreeView.hh>
#include <DependencyTreeWidget.hh>
#include <FilterModel.hh>
#include <ValidityColor.hh>
#include <XPathValidator.hh>
#include "ui_DependencyTreeWidget.h"
DependencyTreeWidget::DependencyTreeWidget(QWidget *parent) :
CorpusWidget(parent),
d_ui(QSharedPointer<Ui::DependencyTreeWidget>(new Ui::DependencyTreeWidget)),
d_macrosModel(QSharedPointer<DactMacrosModel>(new DactMacrosModel()))
{
d_ui->setupUi(this);
addConnections();
// Statistics are only shown after we have all entries, or when a
// query is executed...
d_ui->statisticsGroupBox->hide();
d_ui->hitsDescLabel->hide();
d_ui->hitsLabel->hide();
d_ui->statisticsLayout->setVerticalSpacing(0);
}
DependencyTreeWidget::~DependencyTreeWidget()
{
// Define a destructor here to make sure the qsharedpointers are implemented where all
// the proper header files are available (not just forward declarations)
}
void DependencyTreeWidget::addConnections()
{
connect(d_ui->highlightLineEdit, SIGNAL(textChanged(QString const &)),
SLOT(applyValidityColor(QString const &)));
connect(d_ui->highlightLineEdit, SIGNAL(returnPressed()),
SLOT(highlightChanged()));
connect(d_ui->treeGraphicsView, SIGNAL(sceneChanged(DactTreeScene*)),
SIGNAL(sceneChanged(DactTreeScene*)));
}
void DependencyTreeWidget::applyValidityColor(QString const &)
{
::applyValidityColor(sender());
}
BracketedSentenceWidget *DependencyTreeWidget::sentenceWidget()
{
return d_ui->sentenceWidget;
}
void DependencyTreeWidget::cancelQuery()
{
if (d_model)
d_model->cancelQuery();
}
void DependencyTreeWidget::saveAs()
{
std::cerr << "Dependency Tree Widget Save As" << std::endl;
}
bool DependencyTreeWidget::saveEnabled() const
{
return false;
}
void DependencyTreeWidget::copy()
{
if (!d_model)
return;
QStringList filenames;
QModelIndexList indices = d_ui->fileListWidget->selectionModel()->selectedIndexes();
for (QModelIndexList::const_iterator iter = indices.begin();
iter != indices.end(); ++iter)
{
QVariant v = d_model->data(*iter, Qt::DisplayRole);
if (v.type() == QVariant::String)
filenames.push_back(v.toString());
}
QApplication::clipboard()->setText(filenames.join("\n")); // XXX - Good enough for Windows?
}
void DependencyTreeWidget::nEntriesFound(int entries, int hits) {
d_ui->entriesLabel->setText(QString("%L1").arg(entries));
d_ui->hitsLabel->setText(QString("%L1").arg(hits));
if (!d_treeShown) {
d_ui->fileListWidget->selectionModel()->clear();
QModelIndex idx(d_model->index(0, 0));
d_ui->fileListWidget->selectionModel()->setCurrentIndex(idx,
QItemSelectionModel::ClearAndSelect);
d_treeShown = true;
}
}
void DependencyTreeWidget::entrySelected(QModelIndex const ¤t, QModelIndex const &prev)
{
Q_UNUSED(prev);
if (!current.isValid()) {
d_ui->treeGraphicsView->setScene(0);
d_ui->sentenceWidget->clear();
return;
}
showFile(current.data(Qt::UserRole).toString());
//focusFitTree();
focusFirstMatch();
}
void DependencyTreeWidget::fitTree()
{
d_ui->treeGraphicsView->fitTree();
}
void DependencyTreeWidget::focusFirstMatch()
{
if (d_ui->treeGraphicsView->scene() &&
d_ui->treeGraphicsView->scene()->activeNodes().length() > 0)
d_ui->treeGraphicsView->focusTreeNode(1);
}
void DependencyTreeWidget::focusFitTree()
{
if (d_ui->treeGraphicsView->scene()
&& d_ui->treeGraphicsView->scene()->activeNodes().length())
{
d_ui->treeGraphicsView->resetZoom();
d_ui->treeGraphicsView->focusTreeNode(1);
}
else
d_ui->treeGraphicsView->fitTree();
}
void DependencyTreeWidget::focusHighlight()
{
d_ui->highlightLineEdit->setFocus();
}
void DependencyTreeWidget::focusNextTreeNode()
{
d_ui->treeGraphicsView->focusNextTreeNode();
}
void DependencyTreeWidget::focusPreviousTreeNode()
{
d_ui->treeGraphicsView->focusPreviousTreeNode();
}
void DependencyTreeWidget::highlightChanged()
{
setHighlight(d_ui->highlightLineEdit->text().trimmed());
}
void DependencyTreeWidget::mapperStarted(int totalEntries)
{
d_ui->entriesLabel->setText(QString::number(0));
d_ui->hitsLabel->setText(QString::number(0));
if (!d_filter.isEmpty()) {
d_ui->filterProgressBar->setMinimum(0);
d_ui->filterProgressBar->setMaximum(totalEntries);
d_ui->filterProgressBar->setValue(0);
d_ui->filterProgressBar->setVisible(true);
}
}
void DependencyTreeWidget::mapperFailed(QString error)
{
d_ui->filterProgressBar->setVisible(false);
QMessageBox::critical(this, tr("Error processing query"),
tr("Could not process query: ") + error,
QMessageBox::Ok);
}
void DependencyTreeWidget::mapperFinished(int processedEntries, int totalEntries, bool cached)
{
if (cached) {
d_ui->fileListWidget->selectionModel()->clear();
QModelIndex idx(d_model->index(0, 0));
d_ui->fileListWidget->selectionModel()->setCurrentIndex(idx,
QItemSelectionModel::ClearAndSelect);
}
mapperStopped(processedEntries, totalEntries);
}
void DependencyTreeWidget::mapperStopped(int processedEntries, int totalEntries)
{
if (!d_filter.isEmpty())
d_ui->filterProgressBar->setVisible(false);
// Final counts. Doing this again is necessary, because the query may
// have been cached. If so, it doesn't emit a signal for every entry.
int entries = d_model->rowCount(QModelIndex());
int hits = d_model->hits();
d_ui->entriesLabel->setText(QString("%L1").arg(entries));
d_ui->hitsLabel->setText(QString("%L1").arg(hits));
if (!d_file.isNull())
{
QModelIndex current = d_model->indexOfFile(d_file);
d_ui->fileListWidget->setCurrentIndex(current);
}
}
/* Next- and prev entry buttons */
void DependencyTreeWidget::nextEntry(bool)
{
QModelIndex current(d_ui->fileListWidget->currentIndex());
QModelIndex next = current.sibling(current.row() + 1, current.column());
if (next.isValid())
d_ui->fileListWidget->setCurrentIndex(next);
}
void DependencyTreeWidget::previousEntry(bool)
{
QModelIndex current(d_ui->fileListWidget->currentIndex());
QModelIndex previous = current.sibling(current.row() - 1, current.column());
if (previous.isValid())
d_ui->fileListWidget->setCurrentIndex(previous);
}
void DependencyTreeWidget::progressChanged(int progress)
{
d_ui->filterProgressBar->setValue(progress);
}
void DependencyTreeWidget::readSettings()
{
QSettings settings;
// Splitter.
d_ui->splitter->restoreState(
settings.value("splitterSizes").toByteArray());
}
void DependencyTreeWidget::renderTree(QPainter *painter)
{
if (d_ui->treeGraphicsView->scene())
d_ui->treeGraphicsView->scene()->render(painter);
}
DactTreeScene *DependencyTreeWidget::scene()
{
return d_ui->treeGraphicsView->scene();
}
QItemSelectionModel *DependencyTreeWidget::selectionModel()
{
return d_ui->fileListWidget->selectionModel();
}
void DependencyTreeWidget::setFilter(QString const &filter, QString const &raw_filter)
{
d_filter = filter;
d_treeShown = false;
d_file = QString();
if (d_filter.isEmpty()) {
d_ui->statisticsGroupBox->hide();
d_ui->hitsDescLabel->hide();
d_ui->hitsLabel->hide();
d_ui->statisticsLayout->setVerticalSpacing(0);
} else {
d_ui->statisticsGroupBox->show();
d_ui->statisticsLayout->setVerticalSpacing(-1);
d_ui->hitsDescLabel->show();
d_ui->hitsLabel->show();
}
setHighlight(raw_filter);
if (d_model)
d_model->runQuery(d_filter);
}
void DependencyTreeWidget::setModel(FilterModel *model)
{
d_model = QSharedPointer<FilterModel>(model);
d_ui->fileListWidget->setModel(d_model.data());
connect(model, SIGNAL(queryFailed(QString)),
SLOT(mapperFailed(QString)));
connect(model, SIGNAL(queryStarted(int)),
SLOT(mapperStarted(int)));
connect(model, SIGNAL(queryStopped(int, int)),
SLOT(mapperStopped(int, int)));
connect(model, SIGNAL(queryFinished(int, int, bool)),
SLOT(mapperFinished(int, int, bool)));
connect(model, SIGNAL(nEntriesFound(int, int)),
SLOT(nEntriesFound(int, int)));
connect(model, SIGNAL(progressChanged(int)),
SLOT(progressChanged(int)));
connect(d_ui->fileListWidget->selectionModel(),
SIGNAL(currentChanged(QModelIndex,QModelIndex)),
SLOT(entrySelected(QModelIndex,QModelIndex)));
}
void DependencyTreeWidget::setMacrosModel(QSharedPointer<DactMacrosModel> macrosModel)
{
d_macrosModel = macrosModel;
d_xpathValidator = QSharedPointer<XPathValidator>(new XPathValidator(d_macrosModel));
d_ui->highlightLineEdit->setValidator(d_xpathValidator.data());
}
void DependencyTreeWidget::setHighlight(QString const &query)
{
d_highlight = query;
d_ui->highlightLineEdit->setText(query);
showFile(); // to force-reload the tree and bracketed sentence
}
void DependencyTreeWidget::showFile()
{
if (!d_file.isNull())
showFile(d_file);
}
void DependencyTreeWidget::showFile(QString const &entry)
{
// Read XML data.
if (d_corpusReader.isNull())
return;
try {
QString xml;
if (d_highlight.trimmed().isEmpty())
xml = QString::fromUtf8(d_corpusReader->read(entry.toUtf8().constData()).c_str());
else {
ac::CorpusReader::MarkerQuery query(d_macrosModel->expand(d_highlight).toUtf8().constData(),
"active", "1");
std::list<ac::CorpusReader::MarkerQuery> queries;
queries.push_back(query);
xml = QString::fromUtf8(d_corpusReader->read(entry.toUtf8().constData(), queries).c_str());
}
if (xml.size() == 0) {
qWarning() << "MainWindow::writeSettings: empty XML data!";
d_ui->treeGraphicsView->setScene(0);
return;
}
// Remember file for when we need to redraw the tree
d_file = entry;
// Parameters
QString valStr = d_highlight.trimmed().isEmpty() ? "'/..'" :
QString("'") + d_macrosModel->expand(d_highlight) + QString("'");
QHash<QString, QString> params;
params["expr"] = valStr;
try {
showTree(xml);
showSentence(entry, d_highlight);
// I try to find my file back in the file list to keep the list
// in sync with the treegraph since showFile can be called from
// the child dialogs.
QModelIndexList matches =
d_ui->fileListWidget->model()->match(
d_ui->fileListWidget->model()->index(0, 0),
Qt::DisplayRole, entry, 1,
Qt::MatchFixedString | Qt::MatchCaseSensitive);
if (matches.size() > 0) {
d_ui->fileListWidget->selectionModel()->select(matches.at(0),
QItemSelectionModel::ClearAndSelect);
d_ui->fileListWidget->scrollTo(matches.at(0));
}
} catch (std::runtime_error const &e) {
QMessageBox::critical(this, QString("Tranformation error"),
QString("A transformation error occured: %1\n\nCorpus data is probably corrupt.").arg(e.what()));
}
}
catch(std::runtime_error const &e)
{
QMessageBox::critical(this, QString("Read error"),
QString("An error occured while trying to read a corpus file: %1").arg(e.what()));
}
}
void DependencyTreeWidget::showSentence(QString const &entry, QString const &query)
{
d_ui->sentenceWidget->setEntry(entry, d_macrosModel->expand(query));
}
void DependencyTreeWidget::showTree(QString const &xml)
{
d_ui->treeGraphicsView->showTree(xml);
}
void DependencyTreeWidget::switchCorpus(QSharedPointer<alpinocorpus::CorpusReader> corpusReader)
{
d_corpusReader = corpusReader;
d_xpathValidator->setCorpusReader(d_corpusReader);
setModel(new FilterModel(d_corpusReader));
QString query = d_ui->highlightLineEdit->text();
d_ui->highlightLineEdit->clear();
d_ui->highlightLineEdit->insert(query);
d_model->runQuery(d_macrosModel->expand(d_filter));
d_ui->sentenceWidget->setCorpusReader(d_corpusReader);
}
void DependencyTreeWidget::writeSettings()
{
QSettings settings;
// Splitter
settings.setValue("splitterSizes", d_ui->splitter->saveState());
}
void DependencyTreeWidget::zoomIn()
{
d_ui->treeGraphicsView->zoomIn();
}
void DependencyTreeWidget::zoomOut()
{
d_ui->treeGraphicsView->zoomOut();
}
void DependencyTreeWidget::showToolMenu(QPoint const &position)
{
if (!d_ui->fileListWidget->model())
return;
QModelIndexList rows = d_ui->fileListWidget->selectionModel()->selectedRows();
QList<QString> selectedFiles;
if (rows.isEmpty())
return;
foreach (QModelIndex const &row, rows)
selectedFiles << row.data().toString();
DactToolsMenu::exec(
DactToolsModel::sharedInstance()->tools(QString::fromStdString(d_corpusReader->name())),
selectedFiles,
mapToGlobal(position),
d_ui->fileListWidget->actions());
}
<commit_msg>Remove a race condition.<commit_after>#include <iostream>
#include <stdexcept>
#include <QClipboard>
#include <QMessageBox>
#include <QSettings>
#include <QSharedPointer>
#include <QWidget>
#include <QFile>
#include <CorpusWidget.hh>
#include <DactMacrosModel.hh>
#include <DactToolsMenu.hh>
#include <DactToolsModel.hh>
#include <DactTreeScene.hh>
#include <DactTreeView.hh>
#include <DependencyTreeWidget.hh>
#include <FilterModel.hh>
#include <ValidityColor.hh>
#include <XPathValidator.hh>
#include "ui_DependencyTreeWidget.h"
// Note that there is a race in this class, when a new filter is set.
// d_model->runQuery may cancel an existing query, delivering a queryStopped()
// signal. However, at that point d_filter is already reset. Since queries
// run in a separate thread, we cannot connect signals directly.
//
// Consequence: don't rely on d_filter if the code path is treating stopping
// of an older query.
DependencyTreeWidget::DependencyTreeWidget(QWidget *parent) :
CorpusWidget(parent),
d_ui(QSharedPointer<Ui::DependencyTreeWidget>(new Ui::DependencyTreeWidget)),
d_macrosModel(QSharedPointer<DactMacrosModel>(new DactMacrosModel()))
{
d_ui->setupUi(this);
addConnections();
// Statistics are only shown after we have all entries, or when a
// query is executed...
d_ui->statisticsGroupBox->hide();
d_ui->hitsDescLabel->hide();
d_ui->hitsLabel->hide();
d_ui->statisticsLayout->setVerticalSpacing(0);
}
DependencyTreeWidget::~DependencyTreeWidget()
{
// Define a destructor here to make sure the qsharedpointers are implemented where all
// the proper header files are available (not just forward declarations)
}
void DependencyTreeWidget::addConnections()
{
connect(d_ui->highlightLineEdit, SIGNAL(textChanged(QString const &)),
SLOT(applyValidityColor(QString const &)));
connect(d_ui->highlightLineEdit, SIGNAL(returnPressed()),
SLOT(highlightChanged()));
connect(d_ui->treeGraphicsView, SIGNAL(sceneChanged(DactTreeScene*)),
SIGNAL(sceneChanged(DactTreeScene*)));
}
void DependencyTreeWidget::applyValidityColor(QString const &)
{
::applyValidityColor(sender());
}
BracketedSentenceWidget *DependencyTreeWidget::sentenceWidget()
{
return d_ui->sentenceWidget;
}
void DependencyTreeWidget::cancelQuery()
{
if (d_model)
d_model->cancelQuery();
}
void DependencyTreeWidget::saveAs()
{
std::cerr << "Dependency Tree Widget Save As" << std::endl;
}
bool DependencyTreeWidget::saveEnabled() const
{
return false;
}
void DependencyTreeWidget::copy()
{
if (!d_model)
return;
QStringList filenames;
QModelIndexList indices = d_ui->fileListWidget->selectionModel()->selectedIndexes();
for (QModelIndexList::const_iterator iter = indices.begin();
iter != indices.end(); ++iter)
{
QVariant v = d_model->data(*iter, Qt::DisplayRole);
if (v.type() == QVariant::String)
filenames.push_back(v.toString());
}
QApplication::clipboard()->setText(filenames.join("\n")); // XXX - Good enough for Windows?
}
void DependencyTreeWidget::nEntriesFound(int entries, int hits) {
d_ui->entriesLabel->setText(QString("%L1").arg(entries));
d_ui->hitsLabel->setText(QString("%L1").arg(hits));
if (!d_treeShown) {
d_ui->fileListWidget->selectionModel()->clear();
QModelIndex idx(d_model->index(0, 0));
d_ui->fileListWidget->selectionModel()->setCurrentIndex(idx,
QItemSelectionModel::ClearAndSelect);
d_treeShown = true;
}
}
void DependencyTreeWidget::entrySelected(QModelIndex const ¤t, QModelIndex const &prev)
{
Q_UNUSED(prev);
if (!current.isValid()) {
d_ui->treeGraphicsView->setScene(0);
d_ui->sentenceWidget->clear();
return;
}
showFile(current.data(Qt::UserRole).toString());
//focusFitTree();
focusFirstMatch();
}
void DependencyTreeWidget::fitTree()
{
d_ui->treeGraphicsView->fitTree();
}
void DependencyTreeWidget::focusFirstMatch()
{
if (d_ui->treeGraphicsView->scene() &&
d_ui->treeGraphicsView->scene()->activeNodes().length() > 0)
d_ui->treeGraphicsView->focusTreeNode(1);
}
void DependencyTreeWidget::focusFitTree()
{
if (d_ui->treeGraphicsView->scene()
&& d_ui->treeGraphicsView->scene()->activeNodes().length())
{
d_ui->treeGraphicsView->resetZoom();
d_ui->treeGraphicsView->focusTreeNode(1);
}
else
d_ui->treeGraphicsView->fitTree();
}
void DependencyTreeWidget::focusHighlight()
{
d_ui->highlightLineEdit->setFocus();
}
void DependencyTreeWidget::focusNextTreeNode()
{
d_ui->treeGraphicsView->focusNextTreeNode();
}
void DependencyTreeWidget::focusPreviousTreeNode()
{
d_ui->treeGraphicsView->focusPreviousTreeNode();
}
void DependencyTreeWidget::highlightChanged()
{
setHighlight(d_ui->highlightLineEdit->text().trimmed());
}
void DependencyTreeWidget::mapperStarted(int totalEntries)
{
d_ui->entriesLabel->setText(QString::number(0));
d_ui->hitsLabel->setText(QString::number(0));
if (!d_filter.isEmpty()) {
d_ui->filterProgressBar->setMinimum(0);
d_ui->filterProgressBar->setMaximum(totalEntries);
d_ui->filterProgressBar->setValue(0);
d_ui->filterProgressBar->setVisible(true);
}
}
void DependencyTreeWidget::mapperFailed(QString error)
{
d_ui->filterProgressBar->setVisible(false);
QMessageBox::critical(this, tr("Error processing query"),
tr("Could not process query: ") + error,
QMessageBox::Ok);
}
void DependencyTreeWidget::mapperFinished(int processedEntries, int totalEntries, bool cached)
{
if (cached) {
d_ui->fileListWidget->selectionModel()->clear();
QModelIndex idx(d_model->index(0, 0));
d_ui->fileListWidget->selectionModel()->setCurrentIndex(idx,
QItemSelectionModel::ClearAndSelect);
}
mapperStopped(processedEntries, totalEntries);
}
void DependencyTreeWidget::mapperStopped(int processedEntries, int totalEntries)
{
d_ui->filterProgressBar->setVisible(false);
// Final counts. Doing this again is necessary, because the query may
// have been cached. If so, it doesn't emit a signal for every entry.
int entries = d_model->rowCount(QModelIndex());
int hits = d_model->hits();
d_ui->entriesLabel->setText(QString("%L1").arg(entries));
d_ui->hitsLabel->setText(QString("%L1").arg(hits));
if (!d_file.isNull())
{
QModelIndex current = d_model->indexOfFile(d_file);
d_ui->fileListWidget->setCurrentIndex(current);
}
}
/* Next- and prev entry buttons */
void DependencyTreeWidget::nextEntry(bool)
{
QModelIndex current(d_ui->fileListWidget->currentIndex());
QModelIndex next = current.sibling(current.row() + 1, current.column());
if (next.isValid())
d_ui->fileListWidget->setCurrentIndex(next);
}
void DependencyTreeWidget::previousEntry(bool)
{
QModelIndex current(d_ui->fileListWidget->currentIndex());
QModelIndex previous = current.sibling(current.row() - 1, current.column());
if (previous.isValid())
d_ui->fileListWidget->setCurrentIndex(previous);
}
void DependencyTreeWidget::progressChanged(int progress)
{
d_ui->filterProgressBar->setValue(progress);
}
void DependencyTreeWidget::readSettings()
{
QSettings settings;
// Splitter.
d_ui->splitter->restoreState(
settings.value("splitterSizes").toByteArray());
}
void DependencyTreeWidget::renderTree(QPainter *painter)
{
if (d_ui->treeGraphicsView->scene())
d_ui->treeGraphicsView->scene()->render(painter);
}
DactTreeScene *DependencyTreeWidget::scene()
{
return d_ui->treeGraphicsView->scene();
}
QItemSelectionModel *DependencyTreeWidget::selectionModel()
{
return d_ui->fileListWidget->selectionModel();
}
void DependencyTreeWidget::setFilter(QString const &filter, QString const &raw_filter)
{
d_treeShown = false;
d_file = QString();
if (filter.isEmpty()) {
d_ui->statisticsGroupBox->hide();
d_ui->hitsDescLabel->hide();
d_ui->hitsLabel->hide();
d_ui->statisticsLayout->setVerticalSpacing(0);
} else {
d_ui->statisticsGroupBox->show();
d_ui->statisticsLayout->setVerticalSpacing(-1);
d_ui->hitsDescLabel->show();
d_ui->hitsLabel->show();
}
setHighlight(raw_filter);
if (d_model)
d_model->runQuery(filter);
d_filter = filter;
}
void DependencyTreeWidget::setModel(FilterModel *model)
{
d_model = QSharedPointer<FilterModel>(model);
d_ui->fileListWidget->setModel(d_model.data());
connect(model, SIGNAL(queryFailed(QString)),
SLOT(mapperFailed(QString)));
connect(model, SIGNAL(queryStarted(int)),
SLOT(mapperStarted(int)));
connect(model, SIGNAL(queryStopped(int, int)),
SLOT(mapperStopped(int, int)));
connect(model, SIGNAL(queryFinished(int, int, bool)),
SLOT(mapperFinished(int, int, bool)));
connect(model, SIGNAL(nEntriesFound(int, int)),
SLOT(nEntriesFound(int, int)));
connect(model, SIGNAL(progressChanged(int)),
SLOT(progressChanged(int)));
connect(d_ui->fileListWidget->selectionModel(),
SIGNAL(currentChanged(QModelIndex,QModelIndex)),
SLOT(entrySelected(QModelIndex,QModelIndex)));
}
void DependencyTreeWidget::setMacrosModel(QSharedPointer<DactMacrosModel> macrosModel)
{
d_macrosModel = macrosModel;
d_xpathValidator = QSharedPointer<XPathValidator>(new XPathValidator(d_macrosModel));
d_ui->highlightLineEdit->setValidator(d_xpathValidator.data());
}
void DependencyTreeWidget::setHighlight(QString const &query)
{
d_highlight = query;
d_ui->highlightLineEdit->setText(query);
showFile(); // to force-reload the tree and bracketed sentence
}
void DependencyTreeWidget::showFile()
{
if (!d_file.isNull())
showFile(d_file);
}
void DependencyTreeWidget::showFile(QString const &entry)
{
// Read XML data.
if (d_corpusReader.isNull())
return;
try {
QString xml;
if (d_highlight.trimmed().isEmpty())
xml = QString::fromUtf8(d_corpusReader->read(entry.toUtf8().constData()).c_str());
else {
ac::CorpusReader::MarkerQuery query(d_macrosModel->expand(d_highlight).toUtf8().constData(),
"active", "1");
std::list<ac::CorpusReader::MarkerQuery> queries;
queries.push_back(query);
xml = QString::fromUtf8(d_corpusReader->read(entry.toUtf8().constData(), queries).c_str());
}
if (xml.size() == 0) {
qWarning() << "MainWindow::writeSettings: empty XML data!";
d_ui->treeGraphicsView->setScene(0);
return;
}
// Remember file for when we need to redraw the tree
d_file = entry;
// Parameters
QString valStr = d_highlight.trimmed().isEmpty() ? "'/..'" :
QString("'") + d_macrosModel->expand(d_highlight) + QString("'");
QHash<QString, QString> params;
params["expr"] = valStr;
try {
showTree(xml);
showSentence(entry, d_highlight);
// I try to find my file back in the file list to keep the list
// in sync with the treegraph since showFile can be called from
// the child dialogs.
QModelIndexList matches =
d_ui->fileListWidget->model()->match(
d_ui->fileListWidget->model()->index(0, 0),
Qt::DisplayRole, entry, 1,
Qt::MatchFixedString | Qt::MatchCaseSensitive);
if (matches.size() > 0) {
d_ui->fileListWidget->selectionModel()->select(matches.at(0),
QItemSelectionModel::ClearAndSelect);
d_ui->fileListWidget->scrollTo(matches.at(0));
}
} catch (std::runtime_error const &e) {
QMessageBox::critical(this, QString("Tranformation error"),
QString("A transformation error occured: %1\n\nCorpus data is probably corrupt.").arg(e.what()));
}
}
catch(std::runtime_error const &e)
{
QMessageBox::critical(this, QString("Read error"),
QString("An error occured while trying to read a corpus file: %1").arg(e.what()));
}
}
void DependencyTreeWidget::showSentence(QString const &entry, QString const &query)
{
d_ui->sentenceWidget->setEntry(entry, d_macrosModel->expand(query));
}
void DependencyTreeWidget::showTree(QString const &xml)
{
d_ui->treeGraphicsView->showTree(xml);
}
void DependencyTreeWidget::switchCorpus(QSharedPointer<alpinocorpus::CorpusReader> corpusReader)
{
d_corpusReader = corpusReader;
d_xpathValidator->setCorpusReader(d_corpusReader);
setModel(new FilterModel(d_corpusReader));
QString query = d_ui->highlightLineEdit->text();
d_ui->highlightLineEdit->clear();
d_ui->highlightLineEdit->insert(query);
d_model->runQuery(d_macrosModel->expand(d_filter));
d_ui->sentenceWidget->setCorpusReader(d_corpusReader);
}
void DependencyTreeWidget::writeSettings()
{
QSettings settings;
// Splitter
settings.setValue("splitterSizes", d_ui->splitter->saveState());
}
void DependencyTreeWidget::zoomIn()
{
d_ui->treeGraphicsView->zoomIn();
}
void DependencyTreeWidget::zoomOut()
{
d_ui->treeGraphicsView->zoomOut();
}
void DependencyTreeWidget::showToolMenu(QPoint const &position)
{
if (!d_ui->fileListWidget->model())
return;
QModelIndexList rows = d_ui->fileListWidget->selectionModel()->selectedRows();
QList<QString> selectedFiles;
if (rows.isEmpty())
return;
foreach (QModelIndex const &row, rows)
selectedFiles << row.data().toString();
DactToolsMenu::exec(
DactToolsModel::sharedInstance()->tools(QString::fromStdString(d_corpusReader->name())),
selectedFiles,
mapToGlobal(position),
d_ui->fileListWidget->actions());
}
<|endoftext|> |
<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "TangentialMortarMechanicalContact.h"
registerADMooseObject("MooseApp", TangentialMortarMechanicalContact);
defineADValidParams(TangentialMortarMechanicalContact,
ADMortarConstraint,
MooseEnum component("x=0 y=1 z=2");
params.addRequiredParam<MooseEnum>(
"component",
component,
"The force component constraint that this object is supplying"););
template <ComputeStage compute_stage>
TangentialMortarMechanicalContact<compute_stage>::TangentialMortarMechanicalContact(
const InputParameters & parameters)
: ADMortarConstraint<compute_stage>(parameters), _component(adGetParam<MooseEnum>("component"))
{
}
template <ComputeStage compute_stage>
ADReal
TangentialMortarMechanicalContact<compute_stage>::computeQpResidual(Moose::MortarType type)
{
switch (type)
{
case Moose::MortarType::Slave:
// We have taken the convention the lagrange multiplier must have the same sign as the
// relative slip velocity of the slave face. So positive lambda indicates that force is being
// applied in the negative direction, so we want to decrease the momentum in the system, which
// means we want an outflow of momentum, which means we want the residual to be positive in
// that case. Negative lambda means force is being applied in the positive direction, so we
// want to increase momentum in the system, which means we want an inflow of momentum, which
// means we want the residual to be negative in that case. So the sign of this residual should
// be the same as the sign of lambda
return _test_slave[_i][_qp] * _lambda[_qp] *
std::abs(_tangents[_qp][0](_component) / _tangents[_qp][0].norm());
case Moose::MortarType::Master:
// Equal and opposite reactions so we put a negative sign here
return -_test_master[_i][_qp] * _lambda[_qp] *
std::abs(_tangents[_qp][0](_component) / _tangents[_qp][0].norm());
default:
return 0;
}
}
<commit_msg>Ensure that the tangential lagrange multiplier acts in the correct direction<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "TangentialMortarMechanicalContact.h"
registerADMooseObject("MooseApp", TangentialMortarMechanicalContact);
defineADValidParams(TangentialMortarMechanicalContact,
ADMortarConstraint,
MooseEnum component("x=0 y=1 z=2");
params.addRequiredParam<MooseEnum>(
"component",
component,
"The force component constraint that this object is supplying"););
template <ComputeStage compute_stage>
TangentialMortarMechanicalContact<compute_stage>::TangentialMortarMechanicalContact(
const InputParameters & parameters)
: ADMortarConstraint<compute_stage>(parameters), _component(adGetParam<MooseEnum>("component"))
{
}
template <ComputeStage compute_stage>
ADReal
TangentialMortarMechanicalContact<compute_stage>::computeQpResidual(Moose::MortarType type)
{
switch (type)
{
case Moose::MortarType::Slave:
// We have taken the convention the lagrange multiplier must have the same sign as the
// relative slip velocity of the slave face. So positive lambda indicates that force is being
// applied in the negative direction, so we want to decrease the momentum in the system, which
// means we want an outflow of momentum, which means we want the residual to be positive in
// that case. Negative lambda means force is being applied in the positive direction, so we
// want to increase momentum in the system, which means we want an inflow of momentum, which
// means we want the residual to be negative in that case. So the sign of this residual should
// be the same as the sign of lambda
return _test_slave[_i][_qp] * _lambda[_qp] * _tangents[_qp][0](_component) /
_tangents[_qp][0].norm();
case Moose::MortarType::Master:
// Equal and opposite reactions so we put a negative sign here
return -_test_master[_i][_qp] * _lambda[_qp] * _tangents[_qp][0](_component) /
_tangents[_qp][0].norm();
default:
return 0;
}
}
<|endoftext|> |
<commit_before>//
// File: MapGenerator.cpp
// Class MapGenerator
// Author Jonatan Rapp & Alexander Hederstaf
// All code is my own except where credited to others.
//
// Copyright © 2012 Catch22. All Rights Reserved.
//
// Date: Oct 9, 2012
//
//
#include "MapGenerator.hpp"
#include <algorithm>
#include <math.h>
#include <time.h>
#include <stdio.h>
#include "../../Helper/Logger.hpp"
// All possible GeneratedBlocks
const GeneratedBlock Ip2 = GeneratedBlock(2, INCLINE, 4);
const GeneratedBlock Hp2 = GeneratedBlock(2, HORIZONTAL, 4);
const GeneratedBlock Ip1 = GeneratedBlock(1, INCLINE, 4);
const GeneratedBlock Hp1 = GeneratedBlock(1, HORIZONTAL, 4);
const GeneratedBlock I0 = GeneratedBlock(0, INCLINE, 64);
const GeneratedBlock H0 = GeneratedBlock(0, HORIZONTAL, 244);
const GeneratedBlock D0 = GeneratedBlock(0, DECLINE, 64);
const GeneratedBlock Hn1 = GeneratedBlock(-1, HORIZONTAL, 4);
const GeneratedBlock Dn1 = GeneratedBlock(-1, DECLINE, 4);
const GeneratedBlock Hn2 = GeneratedBlock(-2, HORIZONTAL, 4);
// End of GeneratedBlocks
MapGenerator::~MapGenerator()
{
}
MapGenerator::MapGenerator()
{
recentlyUsedBuffer.resize(BUFFER_SIZE, H0);
bufferElementCounter.resize(11, 0);
bufferElementCounter[4] = 20; //20x Horizontal dy = 0 blocks
all.insert(Ip2);
all.insert(Hp2);
all.insert(Ip1);
all.insert(Hp1);
all.insert(I0);
all.insert(H0);
all.insert(D0);
all.insert(Hn1);
all.insert(Dn1);
all.insert(Hn2);
zeroIncline.insert(I0);
zeroDecline.insert(D0);
plusTwo.insert(Ip2);
plusTwo.insert(Hp2);
plusOne.insert(Ip1);
plusOne.insert(Hp1);
allZeroes.insert(I0);
allZeroes.insert(H0);
allZeroes.insert(D0);
allDeltaY.insert(Ip2);
allDeltaY.insert(Hp2);
allDeltaY.insert(Ip1);
allDeltaY.insert(Hp1);
allDeltaY.insert(Hn1);
allDeltaY.insert(Dn1);
allDeltaY.insert(Hn2);
}
set<GeneratedBlock> MapGenerator::getPossibleSet(GeneratedBlock* previousBlock)
{
set<GeneratedBlock> possibleSet = all;
if (!previousBlock) {
return possibleSet;
}
if (previousBlock->type == DECLINE) {
// remove zeroIncline
set<GeneratedBlock> tmp;
set_difference(possibleSet.begin(), possibleSet.end(), zeroIncline.begin(), zeroIncline.end(), inserter(tmp, tmp.end()));
possibleSet = tmp;
} else if (previousBlock->type == INCLINE) {
// remove zeroDecline
set<GeneratedBlock> tmp;
set_difference(possibleSet.begin(), possibleSet.end(), zeroDecline.begin(), zeroDecline.end(), inserter(tmp, tmp.end()));
possibleSet = tmp;
}
if (previousBlock->dy != 0) {
// remove allDeltaY
set<GeneratedBlock> tmp;
set_difference(possibleSet.begin(), possibleSet.end(), allDeltaY.begin(), allDeltaY.end(), inserter(tmp, tmp.end()));
possibleSet = tmp;
} else {
if (previousBlock->type != HORIZONTAL) {
// remove plusTwo
set<GeneratedBlock> tmp;
set_difference(possibleSet.begin(), possibleSet.end(), plusTwo.begin(), plusTwo.end(), inserter(tmp, tmp.end()));
possibleSet = tmp;
}
if (previousBlock->type == DECLINE) {
// remove plusOne
set<GeneratedBlock> tmp;
set_difference(possibleSet.begin(), possibleSet.end(), plusOne.begin(), plusOne.end(), inserter(tmp, tmp.end()));
possibleSet = tmp;
}
}
if (previousBlock->dy < 0) {
// remove zeroIncline
set<GeneratedBlock> tmp;
set_difference(possibleSet.begin(), possibleSet.end(), zeroIncline.begin(), zeroIncline.end(), inserter(tmp, tmp.end()));
possibleSet = tmp;
}
return possibleSet;
}
set<GeneratedBlock> MapGenerator::getAllowedSet(set<GeneratedBlock> possibleSet, Vector2d* startVector)
{
set<GeneratedBlock> allowedSet;
set<GeneratedBlock>::iterator it;
for (it = possibleSet.begin(); it != possibleSet.end(); it++) {
int dy = (*it).dy;
int t = (*it).type;
t = dy + (-1) * (t - 1); // t is now an int representing deltaY added by slope type.
if (((startVector->m_y + t) <= HEIGHT_MAX && (startVector->m_y + t) >= HEIGHT_MIN)
&& (startVector->m_y <= HEIGHT_MAX && startVector->m_y >= HEIGHT_MIN)) {
// Only keep GeneratedBlocks that stay within the allowed height margin
allowedSet.insert(*it);
}
}
return allowedSet;
}
void MapGenerator::addToBuffer(GeneratedBlock usedBlock)
{
vector<GeneratedBlock>::iterator it = recentlyUsedBuffer.begin();
recentlyUsedBuffer.erase(recentlyUsedBuffer.begin());
GeneratedBlock removed = *it;
int position = distance(all.begin(), all.find(removed));
bufferElementCounter[position]--;
recentlyUsedBuffer.push_back(usedBlock);
position = distance(all.begin(), all.find(usedBlock));
bufferElementCounter[position]++;
}
void MapGenerator::modifyChances(set<GeneratedBlock>& allowedSet, Vector2d* startVector)
{
set<GeneratedBlock>::iterator it;
for (it = allowedSet.begin(); it != allowedSet.end(); ++it) {
GeneratedBlock block = *it;
block.chance -= 2 * bufferElementCounter[distance(all.begin(), all.find(block))];
if ((block.dy + ((-1) * (block.type - 1)) < 0 && startVector->m_y < 4)
|| (block.dy + ((-1) * (block.type - 1)) > 0 && startVector->m_y > 4)) {
int z = abs((int) (startVector->m_y - 4));
if (z == 1) {
block.chance *= 3;
}
if (z == 2) {
block.chance *= 2;
}
block.chance /= 4;
}
allowedSet.erase(*it);
allowedSet.insert(block);
}
}
GeneratedBlock MapGenerator::selectBlock(set<GeneratedBlock> allowedSet)
{
set<GeneratedBlock>::iterator it;
int totalChance = 1;
for (it = allowedSet.begin(); it != allowedSet.end(); ++it) {
totalChance += (*it).chance;
}
int roll = (rand() % totalChance) + 1;
for (it = allowedSet.begin(); it != allowedSet.end(); ++it) {
if (roll <= (*it).chance) {
break;
} else {
roll-=(*it).chance;
}
}
return *it;
}
Platform* MapGenerator::generatePlatform(Vector2d* startVector)
{
// 1. get possible set
// 2. get allowed set
// 3. modify chance (using buffer & deltaY)
// 4. select GeneratedBlock
// 5. add platformblock to platform
// 6. add used GeneratedBlock to buffer
Platform* platform = new Platform();
set<GeneratedBlock> possibleSet = allZeroes;
set<GeneratedBlock> allowedSet = getAllowedSet(possibleSet, startVector);
modifyChances(allowedSet, startVector);
GeneratedBlock selectedBlock = selectBlock(allowedSet);
PlatformBlock* block = new PlatformBlock(selectedBlock.type, startVector);
platform->addPlatformBlock(block);
Vector2d* newStartVector = block->getEndVector();
addToBuffer(selectedBlock);
int length = (PLATFORM_LENGTH_MIN - 1) + (rand() % (2 + PLATFORM_LENGTH_MAX - PLATFORM_LENGTH_MIN));
for (int i = 0; i < length; i++) {
possibleSet = getPossibleSet(&selectedBlock);
allowedSet = getAllowedSet(possibleSet, newStartVector);
modifyChances(allowedSet, newStartVector);
selectedBlock = selectBlock(allowedSet);
*newStartVector+=Vector2d(0.f, selectedBlock.dy);
block = new PlatformBlock(selectedBlock.type, newStartVector);
platform->addPlatformBlock(block);
newStartVector = block->getEndVector();
addToBuffer(selectedBlock);
}
return platform;
}
Platform* MapGenerator::generateFlatPlatform(Vector2d* startVector, int length)
{
Platform* platform = new Platform();
for (int i = 0; i < length; i++) {
PlatformBlock* block = new PlatformBlock(HORIZONTAL, startVector);
platform->addPlatformBlock(block);
startVector = block->getEndVector();
}
return platform;
}
bool MapGenerator::testFunc()
{/*
printf("Size all = %i\n", (int)all.size());
set<GeneratedBlock> testSet = getPossibleSet(0);
printf("Size (input: 0) = %i\n", (int)testSet.size());
GeneratedBlock lastBlock = H0;
testSet = getPossibleSet(&lastBlock);
printf("Size (input: 0,H) = %i\n", (int)testSet.size());
testSet = getAllowedSet(testSet, new Vector2d(0, 5));
printf("Size (input: 0,H) V(0, 3) = %i\n", (int)testSet.size());
int nbr = testSet.size();
set<GeneratedBlock> printSet = testSet;
printf("allowedSet --------\n");
for (int i = 0; i < nbr; i++) {
set<GeneratedBlock>::iterator it = printSet.begin();
int y = (&*it)->dy;
int t = (&*it)->type;
int c = (&*it)->chance;
printf("Element #%i: dy: %i, type %i, chance %i\n", i, y, t, c);
printSet.erase(it);
}
modifyChances(testSet, new Vector2d(0, 5));
printf("After modifyChances()--------\n");
printSet = testSet;
for (int i = 0; i < nbr; i++) {
set<GeneratedBlock>::iterator it = printSet.begin();
int y = (&*it)->dy;
int t = (&*it)->type;
int c = (&*it)->chance;
printf("Element #%i: dy: %i, type %i, chance %i\n", i, y, t, c);
printSet.erase(it);
}
*/
GeneratedBlock lastBlock = H0;
Vector2d* startVector = new Vector2d(2,6);
int qwe = 6 + (rand() % 7);
for (int v = 0; v < qwe; v++) {
set<GeneratedBlock> possibleSet = getPossibleSet(&lastBlock);
set<GeneratedBlock> allowedSet = getAllowedSet(possibleSet, startVector);
modifyChances(allowedSet, startVector);
GeneratedBlock selBlock = selectBlock(allowedSet);
Vector2d* endVector = new Vector2d(2 + startVector->m_x, selBlock.dy + ((-1) * (selBlock.type - 1)) + startVector->m_y);
printf("----------------\n");
printf("GenBlock dY = %i", selBlock.dy);
printf("GenBlock type = %i", selBlock.type);
printf("StartVector = (%i, %i)\n", (int)startVector->m_x, (int)startVector->m_y);
printf("EndVector = (%i, %i)\n", (int)endVector->m_x, (int)endVector->m_y);
lastBlock = selBlock;
startVector = endVector;
}
/*
GeneratedBlock selBlock = selectBlock(testSet);
printf("Selected Block:\n");
printf("dY = %i\n", selBlock.dy);
printf("Type = %i\n", selBlock.type);
printf("Chance = %i\n", selBlock.chance);
*/
return true;
}
<commit_msg>Fixed random selectBlock function - baserandom number set to 0, was set to 1 as result of sonar test. - this causued division by zero but is now avoided with a check.<commit_after>//
// File: MapGenerator.cpp
// Class MapGenerator
// Author Jonatan Rapp & Alexander Hederstaf
// All code is my own except where credited to others.
//
// Copyright © 2012 Catch22. All Rights Reserved.
//
// Date: Oct 9, 2012
//
//
#include "MapGenerator.hpp"
#include <algorithm>
#include <math.h>
#include <time.h>
#include <stdio.h>
#include "../../Helper/Logger.hpp"
// All possible GeneratedBlocks
const GeneratedBlock Ip2 = GeneratedBlock(2, INCLINE, 4);
const GeneratedBlock Hp2 = GeneratedBlock(2, HORIZONTAL, 4);
const GeneratedBlock Ip1 = GeneratedBlock(1, INCLINE, 4);
const GeneratedBlock Hp1 = GeneratedBlock(1, HORIZONTAL, 4);
const GeneratedBlock I0 = GeneratedBlock(0, INCLINE, 64);
const GeneratedBlock H0 = GeneratedBlock(0, HORIZONTAL, 244);
const GeneratedBlock D0 = GeneratedBlock(0, DECLINE, 64);
const GeneratedBlock Hn1 = GeneratedBlock(-1, HORIZONTAL, 4);
const GeneratedBlock Dn1 = GeneratedBlock(-1, DECLINE, 4);
const GeneratedBlock Hn2 = GeneratedBlock(-2, HORIZONTAL, 4);
// End of GeneratedBlocks
MapGenerator::~MapGenerator()
{
}
MapGenerator::MapGenerator()
{
recentlyUsedBuffer.resize(BUFFER_SIZE, H0);
bufferElementCounter.resize(11, 0);
bufferElementCounter[4] = 20; //20x Horizontal dy = 0 blocks
all.insert(Ip2);
all.insert(Hp2);
all.insert(Ip1);
all.insert(Hp1);
all.insert(I0);
all.insert(H0);
all.insert(D0);
all.insert(Hn1);
all.insert(Dn1);
all.insert(Hn2);
zeroIncline.insert(I0);
zeroDecline.insert(D0);
plusTwo.insert(Ip2);
plusTwo.insert(Hp2);
plusOne.insert(Ip1);
plusOne.insert(Hp1);
allZeroes.insert(I0);
allZeroes.insert(H0);
allZeroes.insert(D0);
allDeltaY.insert(Ip2);
allDeltaY.insert(Hp2);
allDeltaY.insert(Ip1);
allDeltaY.insert(Hp1);
allDeltaY.insert(Hn1);
allDeltaY.insert(Dn1);
allDeltaY.insert(Hn2);
}
set<GeneratedBlock> MapGenerator::getPossibleSet(GeneratedBlock* previousBlock)
{
set<GeneratedBlock> possibleSet = all;
if (!previousBlock) {
return possibleSet;
}
if (previousBlock->type == DECLINE) {
// remove zeroIncline
set<GeneratedBlock> tmp;
set_difference(possibleSet.begin(), possibleSet.end(), zeroIncline.begin(), zeroIncline.end(), inserter(tmp, tmp.end()));
possibleSet = tmp;
} else if (previousBlock->type == INCLINE) {
// remove zeroDecline
set<GeneratedBlock> tmp;
set_difference(possibleSet.begin(), possibleSet.end(), zeroDecline.begin(), zeroDecline.end(), inserter(tmp, tmp.end()));
possibleSet = tmp;
}
if (previousBlock->dy != 0) {
// remove allDeltaY
set<GeneratedBlock> tmp;
set_difference(possibleSet.begin(), possibleSet.end(), allDeltaY.begin(), allDeltaY.end(), inserter(tmp, tmp.end()));
possibleSet = tmp;
} else {
if (previousBlock->type != HORIZONTAL) {
// remove plusTwo
set<GeneratedBlock> tmp;
set_difference(possibleSet.begin(), possibleSet.end(), plusTwo.begin(), plusTwo.end(), inserter(tmp, tmp.end()));
possibleSet = tmp;
}
if (previousBlock->type == DECLINE) {
// remove plusOne
set<GeneratedBlock> tmp;
set_difference(possibleSet.begin(), possibleSet.end(), plusOne.begin(), plusOne.end(), inserter(tmp, tmp.end()));
possibleSet = tmp;
}
}
if (previousBlock->dy < 0) {
// remove zeroIncline
set<GeneratedBlock> tmp;
set_difference(possibleSet.begin(), possibleSet.end(), zeroIncline.begin(), zeroIncline.end(), inserter(tmp, tmp.end()));
possibleSet = tmp;
}
return possibleSet;
}
set<GeneratedBlock> MapGenerator::getAllowedSet(set<GeneratedBlock> possibleSet, Vector2d* startVector)
{
set<GeneratedBlock> allowedSet;
set<GeneratedBlock>::iterator it;
for (it = possibleSet.begin(); it != possibleSet.end(); it++) {
int dy = (*it).dy;
int t = (*it).type;
t = dy + (-1) * (t - 1); // t is now an int representing deltaY added by slope type.
if (((startVector->m_y + t) <= HEIGHT_MAX && (startVector->m_y + t) >= HEIGHT_MIN)
&& (startVector->m_y <= HEIGHT_MAX && startVector->m_y >= HEIGHT_MIN)) {
// Only keep GeneratedBlocks that stay within the allowed height margin
allowedSet.insert(*it);
}
}
return allowedSet;
}
void MapGenerator::addToBuffer(GeneratedBlock usedBlock)
{
vector<GeneratedBlock>::iterator it = recentlyUsedBuffer.begin();
recentlyUsedBuffer.erase(recentlyUsedBuffer.begin());
GeneratedBlock removed = *it;
int position = distance(all.begin(), all.find(removed));
bufferElementCounter[position]--;
recentlyUsedBuffer.push_back(usedBlock);
position = distance(all.begin(), all.find(usedBlock));
bufferElementCounter[position]++;
}
void MapGenerator::modifyChances(set<GeneratedBlock>& allowedSet, Vector2d* startVector)
{
set<GeneratedBlock>::iterator it;
for (it = allowedSet.begin(); it != allowedSet.end(); ++it) {
GeneratedBlock block = *it;
block.chance -= 2 * bufferElementCounter[distance(all.begin(), all.find(block))];
if ((block.dy + ((-1) * (block.type - 1)) < 0 && startVector->m_y < 4)
|| (block.dy + ((-1) * (block.type - 1)) > 0 && startVector->m_y > 4)) {
int z = abs((int) (startVector->m_y - 4));
if (z == 1) {
block.chance *= 3;
}
if (z == 2) {
block.chance *= 2;
}
block.chance /= 4;
}
allowedSet.erase(*it);
allowedSet.insert(block);
}
}
GeneratedBlock* MapGenerator::selectBlock(set<GeneratedBlock> allowedSet)
{
set<GeneratedBlock>::iterator it;
int totalChance = 0;
for (it = allowedSet.begin(); it != allowedSet.end(); ++it) {
totalChance += (*it).chance;
}
if (totalChance == 0) {
// set is empty or sum of chance in all blocks are zero
return 0;
}
int roll = (rand() % totalChance) + 1;
for (it = allowedSet.begin(); it != allowedSet.end(); ++it) {
if (roll <= (*it).chance) {
break;
} else {
roll-=(*it).chance;
}
}
return *it;
}
Platform* MapGenerator::generatePlatform(Vector2d* startVector)
{
// 1. get possible set
// 2. get allowed set
// 3. modify chance (using buffer & deltaY)
// 4. select GeneratedBlock
// 5. add platformblock to platform
// 6. add used GeneratedBlock to buffer
Platform* platform = new Platform();
set<GeneratedBlock> possibleSet = allZeroes;
set<GeneratedBlock> allowedSet = getAllowedSet(possibleSet, startVector);
modifyChances(allowedSet, startVector);
GeneratedBlock selectedBlock = selectBlock(allowedSet);
PlatformBlock* block = new PlatformBlock(selectedBlock.type, startVector);
platform->addPlatformBlock(block);
Vector2d* newStartVector = block->getEndVector();
addToBuffer(selectedBlock);
int length = (PLATFORM_LENGTH_MIN - 1) + (rand() % (2 + PLATFORM_LENGTH_MAX - PLATFORM_LENGTH_MIN));
for (int i = 0; i < length; i++) {
possibleSet = getPossibleSet(&selectedBlock);
allowedSet = getAllowedSet(possibleSet, newStartVector);
modifyChances(allowedSet, newStartVector);
selectedBlock = selectBlock(allowedSet);
*newStartVector+=Vector2d(0.f, selectedBlock.dy);
block = new PlatformBlock(selectedBlock.type, newStartVector);
platform->addPlatformBlock(block);
newStartVector = block->getEndVector();
addToBuffer(selectedBlock);
}
return platform;
}
Platform* MapGenerator::generateFlatPlatform(Vector2d* startVector, int length)
{
Platform* platform = new Platform();
for (int i = 0; i < length; i++) {
PlatformBlock* block = new PlatformBlock(HORIZONTAL, startVector);
platform->addPlatformBlock(block);
startVector = block->getEndVector();
}
return platform;
}
bool MapGenerator::testFunc()
{/*
printf("Size all = %i\n", (int)all.size());
set<GeneratedBlock> testSet = getPossibleSet(0);
printf("Size (input: 0) = %i\n", (int)testSet.size());
GeneratedBlock lastBlock = H0;
testSet = getPossibleSet(&lastBlock);
printf("Size (input: 0,H) = %i\n", (int)testSet.size());
testSet = getAllowedSet(testSet, new Vector2d(0, 5));
printf("Size (input: 0,H) V(0, 3) = %i\n", (int)testSet.size());
int nbr = testSet.size();
set<GeneratedBlock> printSet = testSet;
printf("allowedSet --------\n");
for (int i = 0; i < nbr; i++) {
set<GeneratedBlock>::iterator it = printSet.begin();
int y = (&*it)->dy;
int t = (&*it)->type;
int c = (&*it)->chance;
printf("Element #%i: dy: %i, type %i, chance %i\n", i, y, t, c);
printSet.erase(it);
}
modifyChances(testSet, new Vector2d(0, 5));
printf("After modifyChances()--------\n");
printSet = testSet;
for (int i = 0; i < nbr; i++) {
set<GeneratedBlock>::iterator it = printSet.begin();
int y = (&*it)->dy;
int t = (&*it)->type;
int c = (&*it)->chance;
printf("Element #%i: dy: %i, type %i, chance %i\n", i, y, t, c);
printSet.erase(it);
}
*/
GeneratedBlock lastBlock = H0;
Vector2d* startVector = new Vector2d(2,6);
int qwe = 6 + (rand() % 7);
for (int v = 0; v < qwe; v++) {
set<GeneratedBlock> possibleSet = getPossibleSet(&lastBlock);
set<GeneratedBlock> allowedSet = getAllowedSet(possibleSet, startVector);
modifyChances(allowedSet, startVector);
GeneratedBlock selBlock = selectBlock(allowedSet);
Vector2d* endVector = new Vector2d(2 + startVector->m_x, selBlock.dy + ((-1) * (selBlock.type - 1)) + startVector->m_y);
printf("----------------\n");
printf("GenBlock dY = %i", selBlock.dy);
printf("GenBlock type = %i", selBlock.type);
printf("StartVector = (%i, %i)\n", (int)startVector->m_x, (int)startVector->m_y);
printf("EndVector = (%i, %i)\n", (int)endVector->m_x, (int)endVector->m_y);
lastBlock = selBlock;
startVector = endVector;
}
/*
GeneratedBlock selBlock = selectBlock(testSet);
printf("Selected Block:\n");
printf("dY = %i\n", selBlock.dy);
printf("Type = %i\n", selBlock.type);
printf("Chance = %i\n", selBlock.chance);
*/
return true;
}
<|endoftext|> |
<commit_before>#include "chainerx/cuda/cuda_device.h"
#include <cstddef>
#include <memory>
#include <cuda_runtime.h>
#include "chainerx/cuda/cuda_runtime.h"
#include "chainerx/cuda/cuda_set_device_scope.h"
#include "chainerx/cuda/memory_pool.h"
#include "chainerx/device.h"
#include "chainerx/error.h"
#include "chainerx/macro.h"
#include "chainerx/native/native_device.h"
namespace chainerx {
namespace cuda {
std::shared_ptr<void> CudaDevice::Allocate(size_t bytesize) {
void* ptr = device_memory_pool_->Malloc(bytesize);
return std::shared_ptr<void>{ptr, [weak_pool = std::weak_ptr<MemoryPool>{device_memory_pool_}](void* ptr) {
if (std::shared_ptr<MemoryPool> pool = weak_pool.lock()) {
pool->FreeNoExcept(ptr);
}
}};
}
std::shared_ptr<void> CudaDevice::AllocatePinnedMemory(size_t bytesize) {
void* ptr = pinned_memory_pool_->Malloc(bytesize);
return std::shared_ptr<void>{ptr, [weak_pool = std::weak_ptr<MemoryPool>{pinned_memory_pool_}](void* ptr) {
if (std::shared_ptr<MemoryPool> pool = weak_pool.lock()) {
pool->FreeNoExcept(ptr);
}
}};
}
void CudaDevice::MemoryCopyFromHostAsync(void* dst, const void* src, size_t bytesize) {
std::shared_ptr<void> pinned_src_ptr = AllocatePinnedMemory(bytesize);
CudaSetDeviceScope scope{index()};
// cudaMemcpyAsync is slightly faster than cudaMemcpy, although both should be synchronous involving not page-locked regions.
CheckCudaError(cudaMemcpyAsync(pinned_src_ptr.get(), src, bytesize, cudaMemcpyHostToHost));
CheckCudaError(cudaMemcpyAsync(dst, pinned_src_ptr.get(), bytesize, cudaMemcpyHostToDevice));
}
std::shared_ptr<void> CudaDevice::MakeDataFromForeignPointer(const std::shared_ptr<void>& data) {
if (data == nullptr) {
return data;
}
// check memory validity
void* ptr = data.get();
cudaPointerAttributes attr{};
cudaError_t status = cudaPointerGetAttributes(&attr, ptr);
switch (status) {
case cudaSuccess:
if (attr.device != index()) {
throw ChainerxError{"CUDA memory: ", ptr, " must reside on the device: ", index()};
}
break;
case cudaErrorInvalidValue:
throw ChainerxError{"Memory: ", ptr, " is not a CUDA memory"};
default:
Throw(status);
}
return data;
}
void CudaDevice::MemoryCopyFrom(void* dst, const void* src, size_t bytesize, Device& src_device) {
CHAINERX_ASSERT(bytesize == 0 || IsPointerCudaMemory(dst));
if (bytesize == 0) {
return;
}
CudaSetDeviceScope scope{index()};
if (&src_device == this || nullptr != dynamic_cast<CudaDevice*>(&src_device)) {
// Copy between CUDA devices
CheckCudaError(cudaMemcpyAsync(dst, src, bytesize, cudaMemcpyDeviceToDevice));
} else {
CHAINERX_ASSERT(
nullptr != dynamic_cast<native::NativeDevice*>(&src_device) &&
"CudaDevice only supports copy between cuda or native devices.");
// Copy from native device
MemoryCopyFromHostAsync(dst, src, bytesize);
}
}
void CudaDevice::MemoryCopyTo(void* dst, const void* src, size_t bytesize, Device& dst_device) {
CHAINERX_ASSERT(bytesize == 0 || src == nullptr || IsPointerCudaMemory(src));
if (bytesize == 0) {
return;
}
CudaSetDeviceScope scope{index()};
if (&dst_device == this || nullptr != dynamic_cast<CudaDevice*>(&dst_device)) {
// Copy between CUDA devices
CheckCudaError(cudaMemcpyAsync(dst, src, bytesize, cudaMemcpyDeviceToDevice));
} else {
CHAINERX_ASSERT(
nullptr != dynamic_cast<native::NativeDevice*>(&dst_device) &&
"CudaDevice only supports copy between cuda or native devices.");
// Copy to native device
CheckCudaError(cudaMemcpy(dst, src, bytesize, cudaMemcpyDeviceToHost));
}
}
std::shared_ptr<void> CudaDevice::TransferDataFrom(
Device& src_device, const std::shared_ptr<void>& src_ptr, size_t offset, size_t bytesize) {
std::shared_ptr<void> dst_ptr = Allocate(bytesize);
MemoryCopyFrom(dst_ptr.get(), &(static_cast<int8_t*>(src_ptr.get())[offset]), bytesize, src_device);
return dst_ptr;
}
std::shared_ptr<void> CudaDevice::TransferDataTo(Device& dst_device, const std::shared_ptr<void>& src_ptr, size_t offset, size_t bytesize) {
std::shared_ptr<void> dst_ptr = dst_device.Allocate(bytesize);
MemoryCopyTo(dst_ptr.get(), &(static_cast<int8_t*>(src_ptr.get())[offset]), bytesize, dst_device);
return dst_ptr;
}
std::shared_ptr<void> CudaDevice::FromHostMemory(const std::shared_ptr<void>& src_ptr, size_t bytesize) {
std::shared_ptr<void> dst_ptr = Allocate(bytesize);
MemoryCopyFromHostAsync(dst_ptr.get(), src_ptr.get(), bytesize);
return dst_ptr;
}
} // namespace cuda
} // namespace chainerx
<commit_msg>Fix for readability<commit_after>#include "chainerx/cuda/cuda_device.h"
#include <cstddef>
#include <memory>
#include <cuda_runtime.h>
#include "chainerx/cuda/cuda_runtime.h"
#include "chainerx/cuda/cuda_set_device_scope.h"
#include "chainerx/cuda/memory_pool.h"
#include "chainerx/device.h"
#include "chainerx/error.h"
#include "chainerx/macro.h"
#include "chainerx/native/native_device.h"
namespace chainerx {
namespace cuda {
std::shared_ptr<void> CudaDevice::Allocate(size_t bytesize) {
auto deleter = [weak_pool = std::weak_ptr<MemoryPool>{device_memory_pool_}](void* ptr) {
if (std::shared_ptr<MemoryPool> pool = weak_pool.lock()) {
pool->FreeNoExcept(ptr);
}
};
return std::shared_ptr<void>{device_memory_pool_->Malloc(bytesize), std::move(deleter)};
}
std::shared_ptr<void> CudaDevice::AllocatePinnedMemory(size_t bytesize) {
auto deleter = [weak_pool = std::weak_ptr<MemoryPool>{pinned_memory_pool_}](void* ptr) {
if (std::shared_ptr<MemoryPool> pool = weak_pool.lock()) {
pool->FreeNoExcept(ptr);
}
};
return std::shared_ptr<void>{pinned_memory_pool_->Malloc(bytesize), std::move(deleter)};
}
void CudaDevice::MemoryCopyFromHostAsync(void* dst, const void* src, size_t bytesize) {
std::shared_ptr<void> pinned_src_ptr = AllocatePinnedMemory(bytesize);
CudaSetDeviceScope scope{index()};
// cudaMemcpyAsync is slightly faster than cudaMemcpy, although both should be synchronous involving not page-locked regions.
CheckCudaError(cudaMemcpyAsync(pinned_src_ptr.get(), src, bytesize, cudaMemcpyHostToHost));
CheckCudaError(cudaMemcpyAsync(dst, pinned_src_ptr.get(), bytesize, cudaMemcpyHostToDevice));
}
std::shared_ptr<void> CudaDevice::MakeDataFromForeignPointer(const std::shared_ptr<void>& data) {
if (data == nullptr) {
return data;
}
// check memory validity
void* ptr = data.get();
cudaPointerAttributes attr{};
cudaError_t status = cudaPointerGetAttributes(&attr, ptr);
switch (status) {
case cudaSuccess:
if (attr.device != index()) {
throw ChainerxError{"CUDA memory: ", ptr, " must reside on the device: ", index()};
}
break;
case cudaErrorInvalidValue:
throw ChainerxError{"Memory: ", ptr, " is not a CUDA memory"};
default:
Throw(status);
}
return data;
}
void CudaDevice::MemoryCopyFrom(void* dst, const void* src, size_t bytesize, Device& src_device) {
CHAINERX_ASSERT(bytesize == 0 || IsPointerCudaMemory(dst));
if (bytesize == 0) {
return;
}
CudaSetDeviceScope scope{index()};
if (&src_device == this || nullptr != dynamic_cast<CudaDevice*>(&src_device)) {
// Copy between CUDA devices
CheckCudaError(cudaMemcpyAsync(dst, src, bytesize, cudaMemcpyDeviceToDevice));
} else {
CHAINERX_ASSERT(
nullptr != dynamic_cast<native::NativeDevice*>(&src_device) &&
"CudaDevice only supports copy between cuda or native devices.");
// Copy from native device
MemoryCopyFromHostAsync(dst, src, bytesize);
}
}
void CudaDevice::MemoryCopyTo(void* dst, const void* src, size_t bytesize, Device& dst_device) {
CHAINERX_ASSERT(bytesize == 0 || src == nullptr || IsPointerCudaMemory(src));
if (bytesize == 0) {
return;
}
CudaSetDeviceScope scope{index()};
if (&dst_device == this || nullptr != dynamic_cast<CudaDevice*>(&dst_device)) {
// Copy between CUDA devices
CheckCudaError(cudaMemcpyAsync(dst, src, bytesize, cudaMemcpyDeviceToDevice));
} else {
CHAINERX_ASSERT(
nullptr != dynamic_cast<native::NativeDevice*>(&dst_device) &&
"CudaDevice only supports copy between cuda or native devices.");
// Copy to native device
CheckCudaError(cudaMemcpy(dst, src, bytesize, cudaMemcpyDeviceToHost));
}
}
std::shared_ptr<void> CudaDevice::TransferDataFrom(
Device& src_device, const std::shared_ptr<void>& src_ptr, size_t offset, size_t bytesize) {
std::shared_ptr<void> dst_ptr = Allocate(bytesize);
MemoryCopyFrom(dst_ptr.get(), &(static_cast<int8_t*>(src_ptr.get())[offset]), bytesize, src_device);
return dst_ptr;
}
std::shared_ptr<void> CudaDevice::TransferDataTo(Device& dst_device, const std::shared_ptr<void>& src_ptr, size_t offset, size_t bytesize) {
std::shared_ptr<void> dst_ptr = dst_device.Allocate(bytesize);
MemoryCopyTo(dst_ptr.get(), &(static_cast<int8_t*>(src_ptr.get())[offset]), bytesize, dst_device);
return dst_ptr;
}
std::shared_ptr<void> CudaDevice::FromHostMemory(const std::shared_ptr<void>& src_ptr, size_t bytesize) {
std::shared_ptr<void> dst_ptr = Allocate(bytesize);
MemoryCopyFromHostAsync(dst_ptr.get(), src_ptr.get(), bytesize);
return dst_ptr;
}
} // namespace cuda
} // namespace chainerx
<|endoftext|> |
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/media/media_stream_audio_processor_options.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/metrics/field_trial.h"
#include "base/path_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "content/common/media/media_stream_options.h"
#include "content/renderer/media/media_stream_constraints_util.h"
#include "content/renderer/media/media_stream_source.h"
#include "content/renderer/media/rtc_media_constraints.h"
#include "media/audio/audio_parameters.h"
#include "third_party/webrtc/modules/audio_processing/include/audio_processing.h"
#include "third_party/webrtc/modules/audio_processing/typing_detection.h"
namespace content {
const char MediaAudioConstraints::kEchoCancellation[] = "echoCancellation";
const char MediaAudioConstraints::kGoogEchoCancellation[] =
"googEchoCancellation";
const char MediaAudioConstraints::kGoogExperimentalEchoCancellation[] =
"googEchoCancellation2";
const char MediaAudioConstraints::kGoogAutoGainControl[] =
"googAutoGainControl";
const char MediaAudioConstraints::kGoogExperimentalAutoGainControl[] =
"googAutoGainControl2";
const char MediaAudioConstraints::kGoogNoiseSuppression[] =
"googNoiseSuppression";
const char MediaAudioConstraints::kGoogExperimentalNoiseSuppression[] =
"googNoiseSuppression2";
const char MediaAudioConstraints::kGoogHighpassFilter[] = "googHighpassFilter";
const char MediaAudioConstraints::kGoogTypingNoiseDetection[] =
"googTypingNoiseDetection";
const char MediaAudioConstraints::kGoogAudioMirroring[] = "googAudioMirroring";
namespace {
// Constant constraint keys which enables default audio constraints on
// mediastreams with audio.
struct {
const char* key;
bool value;
} const kDefaultAudioConstraints[] = {
{ MediaAudioConstraints::kEchoCancellation, true },
{ MediaAudioConstraints::kGoogEchoCancellation, true },
#if defined(OS_ANDROID) || defined(OS_IOS)
{ MediaAudioConstraints::kGoogExperimentalEchoCancellation, false },
#else
// Enable the extended filter mode AEC on all non-mobile platforms.
{ MediaAudioConstraints::kGoogExperimentalEchoCancellation, true },
#endif
{ MediaAudioConstraints::kGoogAutoGainControl, true },
{ MediaAudioConstraints::kGoogExperimentalAutoGainControl, true },
{ MediaAudioConstraints::kGoogNoiseSuppression, true },
{ MediaAudioConstraints::kGoogHighpassFilter, true },
{ MediaAudioConstraints::kGoogTypingNoiseDetection, true },
{ MediaAudioConstraints::kGoogExperimentalNoiseSuppression, false },
#if defined(OS_WIN)
{ kMediaStreamAudioDucking, true },
#else
{ kMediaStreamAudioDucking, false },
#endif
};
bool IsAudioProcessingConstraint(const std::string& key) {
// |kMediaStreamAudioDucking| does not require audio processing.
return key != kMediaStreamAudioDucking;
}
} // namespace
// TODO(xians): Remove this method after the APM in WebRtc is deprecated.
void MediaAudioConstraints::ApplyFixedAudioConstraints(
RTCMediaConstraints* constraints) {
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kDefaultAudioConstraints); ++i) {
bool already_set_value;
if (!webrtc::FindConstraint(constraints, kDefaultAudioConstraints[i].key,
&already_set_value, NULL)) {
const std::string value = kDefaultAudioConstraints[i].value ?
webrtc::MediaConstraintsInterface::kValueTrue :
webrtc::MediaConstraintsInterface::kValueFalse;
constraints->AddOptional(kDefaultAudioConstraints[i].key, value, false);
} else {
DVLOG(1) << "Constraint " << kDefaultAudioConstraints[i].key
<< " already set to " << already_set_value;
}
}
}
MediaAudioConstraints::MediaAudioConstraints(
const blink::WebMediaConstraints& constraints, int effects)
: constraints_(constraints),
effects_(effects),
default_audio_processing_constraint_value_(true) {
// The default audio processing constraints are turned off when
// - gUM has a specific kMediaStreamSource, which is used by tab capture
// and screen capture.
// - |kEchoCancellation| is explicitly set to false.
std::string value_str;
bool value_bool = false;
if ((GetConstraintValueAsString(constraints, kMediaStreamSource,
&value_str)) ||
(GetConstraintValueAsBoolean(constraints_, kEchoCancellation,
&value_bool) && !value_bool)) {
default_audio_processing_constraint_value_ = false;
}
}
MediaAudioConstraints::~MediaAudioConstraints() {}
// TODO(xians): Remove this method after the APM in WebRtc is deprecated.
bool MediaAudioConstraints::NeedsAudioProcessing() {
if (GetEchoCancellationProperty())
return true;
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kDefaultAudioConstraints); ++i) {
// |kEchoCancellation| and |kGoogEchoCancellation| have been convered by
// GetEchoCancellationProperty().
if (kDefaultAudioConstraints[i].key != kEchoCancellation &&
kDefaultAudioConstraints[i].key != kGoogEchoCancellation &&
IsAudioProcessingConstraint(kDefaultAudioConstraints[i].key) &&
GetProperty(kDefaultAudioConstraints[i].key)) {
return true;
}
}
return false;
}
bool MediaAudioConstraints::GetProperty(const std::string& key) {
// Return the value if the constraint is specified in |constraints|,
// otherwise return the default value.
bool value = false;
if (!GetConstraintValueAsBoolean(constraints_, key, &value))
value = GetDefaultValueForConstraint(constraints_, key);
return value;
}
bool MediaAudioConstraints::GetEchoCancellationProperty() {
// If platform echo canceller is enabled, disable the software AEC.
if (effects_ & media::AudioParameters::ECHO_CANCELLER)
return false;
// If |kEchoCancellation| is specified in the constraints, it will
// override the value of |kGoogEchoCancellation|.
bool value = false;
if (GetConstraintValueAsBoolean(constraints_, kEchoCancellation, &value))
return value;
return GetProperty(kGoogEchoCancellation);
}
bool MediaAudioConstraints::IsValid() {
blink::WebVector<blink::WebMediaConstraint> mandatory;
constraints_.getMandatoryConstraints(mandatory);
for (size_t i = 0; i < mandatory.size(); ++i) {
const std::string key = mandatory[i].m_name.utf8();
if (key == kMediaStreamSource || key == kMediaStreamSourceId ||
key == MediaStreamSource::kSourceId) {
// Ignore Chrome specific Tab capture and |kSourceId| constraints.
continue;
}
bool valid = false;
for (size_t j = 0; j < ARRAYSIZE_UNSAFE(kDefaultAudioConstraints); ++j) {
if (key == kDefaultAudioConstraints[j].key) {
bool value = false;
valid = GetMandatoryConstraintValueAsBoolean(constraints_, key, &value);
break;
}
}
if (!valid) {
DLOG(ERROR) << "Invalid MediaStream constraint. Name: " << key;
return false;
}
}
return true;
}
bool MediaAudioConstraints::GetDefaultValueForConstraint(
const blink::WebMediaConstraints& constraints, const std::string& key) {
// |kMediaStreamAudioDucking| is not restricted by
// |default_audio_processing_constraint_value_| since it does not require
// audio processing.
if (!default_audio_processing_constraint_value_ &&
IsAudioProcessingConstraint(key))
return false;
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kDefaultAudioConstraints); ++i) {
if (kDefaultAudioConstraints[i].key == key)
return kDefaultAudioConstraints[i].value;
}
return false;
}
void EnableEchoCancellation(AudioProcessing* audio_processing) {
#if defined(OS_ANDROID) || defined(OS_IOS)
const std::string group_name =
base::FieldTrialList::FindFullName("ReplaceAECMWithAEC");
if (group_name.empty() || group_name != "Enabled") {
// Mobile devices are using AECM.
int err = audio_processing->echo_control_mobile()->set_routing_mode(
webrtc::EchoControlMobile::kSpeakerphone);
err |= audio_processing->echo_control_mobile()->Enable(true);
CHECK_EQ(err, 0);
return;
}
#endif
int err = audio_processing->echo_cancellation()->set_suppression_level(
webrtc::EchoCancellation::kHighSuppression);
// Enable the metrics for AEC.
err |= audio_processing->echo_cancellation()->enable_metrics(true);
err |= audio_processing->echo_cancellation()->enable_delay_logging(true);
err |= audio_processing->echo_cancellation()->Enable(true);
CHECK_EQ(err, 0);
}
void EnableNoiseSuppression(AudioProcessing* audio_processing) {
int err = audio_processing->noise_suppression()->set_level(
webrtc::NoiseSuppression::kHigh);
err |= audio_processing->noise_suppression()->Enable(true);
CHECK_EQ(err, 0);
}
void EnableExperimentalNoiseSuppression(AudioProcessing* audio_processing) {
CHECK_EQ(audio_processing->EnableExperimentalNs(true), 0);
}
void EnableHighPassFilter(AudioProcessing* audio_processing) {
CHECK_EQ(audio_processing->high_pass_filter()->Enable(true), 0);
}
void EnableTypingDetection(AudioProcessing* audio_processing,
webrtc::TypingDetection* typing_detector) {
int err = audio_processing->voice_detection()->Enable(true);
err |= audio_processing->voice_detection()->set_likelihood(
webrtc::VoiceDetection::kVeryLowLikelihood);
CHECK_EQ(err, 0);
// Configure the update period to 1s (100 * 10ms) in the typing detector.
typing_detector->SetParameters(0, 0, 0, 0, 0, 100);
}
void EnableExperimentalEchoCancellation(AudioProcessing* audio_processing) {
webrtc::Config config;
config.Set<webrtc::DelayCorrection>(new webrtc::DelayCorrection(true));
audio_processing->SetExtraOptions(config);
}
void StartEchoCancellationDump(AudioProcessing* audio_processing,
base::File aec_dump_file) {
DCHECK(aec_dump_file.IsValid());
FILE* stream = base::FileToFILE(aec_dump_file.Pass(), "w");
if (!stream) {
LOG(ERROR) << "Failed to open AEC dump file";
return;
}
if (audio_processing->StartDebugRecording(stream))
DLOG(ERROR) << "Fail to start AEC debug recording";
}
void StopEchoCancellationDump(AudioProcessing* audio_processing) {
if (audio_processing->StopDebugRecording())
DLOG(ERROR) << "Fail to stop AEC debug recording";
}
void EnableAutomaticGainControl(AudioProcessing* audio_processing) {
#if defined(OS_ANDROID) || defined(OS_IOS)
const webrtc::GainControl::Mode mode = webrtc::GainControl::kFixedDigital;
#else
const webrtc::GainControl::Mode mode = webrtc::GainControl::kAdaptiveAnalog;
#endif
int err = audio_processing->gain_control()->set_mode(mode);
err |= audio_processing->gain_control()->Enable(true);
CHECK_EQ(err, 0);
}
void GetAecStats(AudioProcessing* audio_processing,
webrtc::AudioProcessorInterface::AudioProcessorStats* stats) {
// These values can take on valid negative values, so use the lowest possible
// level as default rather than -1.
stats->echo_return_loss = -100;
stats->echo_return_loss_enhancement = -100;
// These values can also be negative, but in practice -1 is only used to
// signal insufficient data, since the resolution is limited to multiples
// of 4ms.
stats->echo_delay_median_ms = -1;
stats->echo_delay_std_ms = -1;
// TODO(ajm): Re-enable this metric once we have a reliable implementation.
stats->aec_quality_min = -1.0f;
if (!audio_processing->echo_cancellation()->are_metrics_enabled() ||
!audio_processing->echo_cancellation()->is_delay_logging_enabled() ||
!audio_processing->echo_cancellation()->is_enabled()) {
return;
}
// TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
// here, but it appears to be unsuitable currently. Revisit after this is
// investigated: http://b/issue?id=5666755
webrtc::EchoCancellation::Metrics echo_metrics;
if (!audio_processing->echo_cancellation()->GetMetrics(&echo_metrics)) {
stats->echo_return_loss = echo_metrics.echo_return_loss.instant;
stats->echo_return_loss_enhancement =
echo_metrics.echo_return_loss_enhancement.instant;
}
int median = 0, std = 0;
if (!audio_processing->echo_cancellation()->GetDelayMetrics(&median, &std)) {
stats->echo_delay_median_ms = median;
stats->echo_delay_std_ms = std;
}
}
} // namespace content
<commit_msg>Use Config to enable experimental noise suppression<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/media/media_stream_audio_processor_options.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/metrics/field_trial.h"
#include "base/path_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "content/common/media/media_stream_options.h"
#include "content/renderer/media/media_stream_constraints_util.h"
#include "content/renderer/media/media_stream_source.h"
#include "content/renderer/media/rtc_media_constraints.h"
#include "media/audio/audio_parameters.h"
#include "third_party/webrtc/modules/audio_processing/include/audio_processing.h"
#include "third_party/webrtc/modules/audio_processing/typing_detection.h"
namespace content {
const char MediaAudioConstraints::kEchoCancellation[] = "echoCancellation";
const char MediaAudioConstraints::kGoogEchoCancellation[] =
"googEchoCancellation";
const char MediaAudioConstraints::kGoogExperimentalEchoCancellation[] =
"googEchoCancellation2";
const char MediaAudioConstraints::kGoogAutoGainControl[] =
"googAutoGainControl";
const char MediaAudioConstraints::kGoogExperimentalAutoGainControl[] =
"googAutoGainControl2";
const char MediaAudioConstraints::kGoogNoiseSuppression[] =
"googNoiseSuppression";
const char MediaAudioConstraints::kGoogExperimentalNoiseSuppression[] =
"googNoiseSuppression2";
const char MediaAudioConstraints::kGoogHighpassFilter[] = "googHighpassFilter";
const char MediaAudioConstraints::kGoogTypingNoiseDetection[] =
"googTypingNoiseDetection";
const char MediaAudioConstraints::kGoogAudioMirroring[] = "googAudioMirroring";
namespace {
// Constant constraint keys which enables default audio constraints on
// mediastreams with audio.
struct {
const char* key;
bool value;
} const kDefaultAudioConstraints[] = {
{ MediaAudioConstraints::kEchoCancellation, true },
{ MediaAudioConstraints::kGoogEchoCancellation, true },
#if defined(OS_ANDROID) || defined(OS_IOS)
{ MediaAudioConstraints::kGoogExperimentalEchoCancellation, false },
#else
// Enable the extended filter mode AEC on all non-mobile platforms.
{ MediaAudioConstraints::kGoogExperimentalEchoCancellation, true },
#endif
{ MediaAudioConstraints::kGoogAutoGainControl, true },
{ MediaAudioConstraints::kGoogExperimentalAutoGainControl, true },
{ MediaAudioConstraints::kGoogNoiseSuppression, true },
{ MediaAudioConstraints::kGoogHighpassFilter, true },
{ MediaAudioConstraints::kGoogTypingNoiseDetection, true },
{ MediaAudioConstraints::kGoogExperimentalNoiseSuppression, false },
#if defined(OS_WIN)
{ kMediaStreamAudioDucking, true },
#else
{ kMediaStreamAudioDucking, false },
#endif
};
bool IsAudioProcessingConstraint(const std::string& key) {
// |kMediaStreamAudioDucking| does not require audio processing.
return key != kMediaStreamAudioDucking;
}
} // namespace
// TODO(xians): Remove this method after the APM in WebRtc is deprecated.
void MediaAudioConstraints::ApplyFixedAudioConstraints(
RTCMediaConstraints* constraints) {
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kDefaultAudioConstraints); ++i) {
bool already_set_value;
if (!webrtc::FindConstraint(constraints, kDefaultAudioConstraints[i].key,
&already_set_value, NULL)) {
const std::string value = kDefaultAudioConstraints[i].value ?
webrtc::MediaConstraintsInterface::kValueTrue :
webrtc::MediaConstraintsInterface::kValueFalse;
constraints->AddOptional(kDefaultAudioConstraints[i].key, value, false);
} else {
DVLOG(1) << "Constraint " << kDefaultAudioConstraints[i].key
<< " already set to " << already_set_value;
}
}
}
MediaAudioConstraints::MediaAudioConstraints(
const blink::WebMediaConstraints& constraints, int effects)
: constraints_(constraints),
effects_(effects),
default_audio_processing_constraint_value_(true) {
// The default audio processing constraints are turned off when
// - gUM has a specific kMediaStreamSource, which is used by tab capture
// and screen capture.
// - |kEchoCancellation| is explicitly set to false.
std::string value_str;
bool value_bool = false;
if ((GetConstraintValueAsString(constraints, kMediaStreamSource,
&value_str)) ||
(GetConstraintValueAsBoolean(constraints_, kEchoCancellation,
&value_bool) && !value_bool)) {
default_audio_processing_constraint_value_ = false;
}
}
MediaAudioConstraints::~MediaAudioConstraints() {}
// TODO(xians): Remove this method after the APM in WebRtc is deprecated.
bool MediaAudioConstraints::NeedsAudioProcessing() {
if (GetEchoCancellationProperty())
return true;
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kDefaultAudioConstraints); ++i) {
// |kEchoCancellation| and |kGoogEchoCancellation| have been convered by
// GetEchoCancellationProperty().
if (kDefaultAudioConstraints[i].key != kEchoCancellation &&
kDefaultAudioConstraints[i].key != kGoogEchoCancellation &&
IsAudioProcessingConstraint(kDefaultAudioConstraints[i].key) &&
GetProperty(kDefaultAudioConstraints[i].key)) {
return true;
}
}
return false;
}
bool MediaAudioConstraints::GetProperty(const std::string& key) {
// Return the value if the constraint is specified in |constraints|,
// otherwise return the default value.
bool value = false;
if (!GetConstraintValueAsBoolean(constraints_, key, &value))
value = GetDefaultValueForConstraint(constraints_, key);
return value;
}
bool MediaAudioConstraints::GetEchoCancellationProperty() {
// If platform echo canceller is enabled, disable the software AEC.
if (effects_ & media::AudioParameters::ECHO_CANCELLER)
return false;
// If |kEchoCancellation| is specified in the constraints, it will
// override the value of |kGoogEchoCancellation|.
bool value = false;
if (GetConstraintValueAsBoolean(constraints_, kEchoCancellation, &value))
return value;
return GetProperty(kGoogEchoCancellation);
}
bool MediaAudioConstraints::IsValid() {
blink::WebVector<blink::WebMediaConstraint> mandatory;
constraints_.getMandatoryConstraints(mandatory);
for (size_t i = 0; i < mandatory.size(); ++i) {
const std::string key = mandatory[i].m_name.utf8();
if (key == kMediaStreamSource || key == kMediaStreamSourceId ||
key == MediaStreamSource::kSourceId) {
// Ignore Chrome specific Tab capture and |kSourceId| constraints.
continue;
}
bool valid = false;
for (size_t j = 0; j < ARRAYSIZE_UNSAFE(kDefaultAudioConstraints); ++j) {
if (key == kDefaultAudioConstraints[j].key) {
bool value = false;
valid = GetMandatoryConstraintValueAsBoolean(constraints_, key, &value);
break;
}
}
if (!valid) {
DLOG(ERROR) << "Invalid MediaStream constraint. Name: " << key;
return false;
}
}
return true;
}
bool MediaAudioConstraints::GetDefaultValueForConstraint(
const blink::WebMediaConstraints& constraints, const std::string& key) {
// |kMediaStreamAudioDucking| is not restricted by
// |default_audio_processing_constraint_value_| since it does not require
// audio processing.
if (!default_audio_processing_constraint_value_ &&
IsAudioProcessingConstraint(key))
return false;
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kDefaultAudioConstraints); ++i) {
if (kDefaultAudioConstraints[i].key == key)
return kDefaultAudioConstraints[i].value;
}
return false;
}
void EnableEchoCancellation(AudioProcessing* audio_processing) {
#if defined(OS_ANDROID) || defined(OS_IOS)
const std::string group_name =
base::FieldTrialList::FindFullName("ReplaceAECMWithAEC");
if (group_name.empty() || group_name != "Enabled") {
// Mobile devices are using AECM.
int err = audio_processing->echo_control_mobile()->set_routing_mode(
webrtc::EchoControlMobile::kSpeakerphone);
err |= audio_processing->echo_control_mobile()->Enable(true);
CHECK_EQ(err, 0);
return;
}
#endif
int err = audio_processing->echo_cancellation()->set_suppression_level(
webrtc::EchoCancellation::kHighSuppression);
// Enable the metrics for AEC.
err |= audio_processing->echo_cancellation()->enable_metrics(true);
err |= audio_processing->echo_cancellation()->enable_delay_logging(true);
err |= audio_processing->echo_cancellation()->Enable(true);
CHECK_EQ(err, 0);
}
void EnableNoiseSuppression(AudioProcessing* audio_processing) {
int err = audio_processing->noise_suppression()->set_level(
webrtc::NoiseSuppression::kHigh);
err |= audio_processing->noise_suppression()->Enable(true);
CHECK_EQ(err, 0);
}
void EnableExperimentalNoiseSuppression(AudioProcessing* audio_processing) {
webrtc::Config config;
config.Set<webrtc::ExperimentalNs>(new webrtc::ExperimentalNs(true));
audio_processing->SetExtraOptions(config);
}
void EnableHighPassFilter(AudioProcessing* audio_processing) {
CHECK_EQ(audio_processing->high_pass_filter()->Enable(true), 0);
}
void EnableTypingDetection(AudioProcessing* audio_processing,
webrtc::TypingDetection* typing_detector) {
int err = audio_processing->voice_detection()->Enable(true);
err |= audio_processing->voice_detection()->set_likelihood(
webrtc::VoiceDetection::kVeryLowLikelihood);
CHECK_EQ(err, 0);
// Configure the update period to 1s (100 * 10ms) in the typing detector.
typing_detector->SetParameters(0, 0, 0, 0, 0, 100);
}
void EnableExperimentalEchoCancellation(AudioProcessing* audio_processing) {
webrtc::Config config;
config.Set<webrtc::DelayCorrection>(new webrtc::DelayCorrection(true));
audio_processing->SetExtraOptions(config);
}
void StartEchoCancellationDump(AudioProcessing* audio_processing,
base::File aec_dump_file) {
DCHECK(aec_dump_file.IsValid());
FILE* stream = base::FileToFILE(aec_dump_file.Pass(), "w");
if (!stream) {
LOG(ERROR) << "Failed to open AEC dump file";
return;
}
if (audio_processing->StartDebugRecording(stream))
DLOG(ERROR) << "Fail to start AEC debug recording";
}
void StopEchoCancellationDump(AudioProcessing* audio_processing) {
if (audio_processing->StopDebugRecording())
DLOG(ERROR) << "Fail to stop AEC debug recording";
}
void EnableAutomaticGainControl(AudioProcessing* audio_processing) {
#if defined(OS_ANDROID) || defined(OS_IOS)
const webrtc::GainControl::Mode mode = webrtc::GainControl::kFixedDigital;
#else
const webrtc::GainControl::Mode mode = webrtc::GainControl::kAdaptiveAnalog;
#endif
int err = audio_processing->gain_control()->set_mode(mode);
err |= audio_processing->gain_control()->Enable(true);
CHECK_EQ(err, 0);
}
void GetAecStats(AudioProcessing* audio_processing,
webrtc::AudioProcessorInterface::AudioProcessorStats* stats) {
// These values can take on valid negative values, so use the lowest possible
// level as default rather than -1.
stats->echo_return_loss = -100;
stats->echo_return_loss_enhancement = -100;
// These values can also be negative, but in practice -1 is only used to
// signal insufficient data, since the resolution is limited to multiples
// of 4ms.
stats->echo_delay_median_ms = -1;
stats->echo_delay_std_ms = -1;
// TODO(ajm): Re-enable this metric once we have a reliable implementation.
stats->aec_quality_min = -1.0f;
if (!audio_processing->echo_cancellation()->are_metrics_enabled() ||
!audio_processing->echo_cancellation()->is_delay_logging_enabled() ||
!audio_processing->echo_cancellation()->is_enabled()) {
return;
}
// TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
// here, but it appears to be unsuitable currently. Revisit after this is
// investigated: http://b/issue?id=5666755
webrtc::EchoCancellation::Metrics echo_metrics;
if (!audio_processing->echo_cancellation()->GetMetrics(&echo_metrics)) {
stats->echo_return_loss = echo_metrics.echo_return_loss.instant;
stats->echo_return_loss_enhancement =
echo_metrics.echo_return_loss_enhancement.instant;
}
int median = 0, std = 0;
if (!audio_processing->echo_cancellation()->GetDelayMetrics(&median, &std)) {
stats->echo_delay_median_ms = median;
stats->echo_delay_std_ms = std;
}
}
} // namespace content
<|endoftext|> |
<commit_before>// Implementations of various convex hull algorithms
// using the C++ Standard Library.
// For clarity, the implementations do not check for
// duplicate or collinear points.
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
struct point {
float x;
float y;
point(float xIn, float yIn) : x(xIn), y(yIn) { }
};
// The z-value of the cross product of segments
// (a, b) and (a, c). Positive means c is ccw
// from (a, b), negative cw. Zero means its collinear.
float ccw(const point& a, const point& b, const point& c) {
return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
}
// Returns true if a is lexicographically before b.
bool isLeftOf(const point& a, const point& b) {
return (a.x < b.x || (a.x == b.x && a.y < b.y));
}
// Used to sort points in ccw order about a pivot.
struct ccwSorter {
const point& pivot;
ccwSorter(const point& inPivot) : pivot(inPivot) { }
bool operator()(const point& a, const point& b) {
return ccw(pivot, a, b) < 0;
}
};
// The length of segment (a, b).
float len(const point& a, const point& b) {
return sqrt((b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - a.y));
}
// The unsigned distance of p from segment (a, b).
float dist(const point& a, const point& b, const point& p) {
return fabs((b.x - a.x) * (a.y - p.y) - (b.y - a.y) * (a.x - p.x)) / len(a, b);
}
// Returns the index of the farthest point from segment (a, b).
size_t getFarthest(const point& a, const point& b, const vector<point>& v) {
size_t idxMax = 0;
float distMax = dist(a, b, v[idxMax]);
for (size_t i = 1; i < v.size(); ++i) {
float distCurr = dist(a, b, v[i]);
if (distCurr > distMax) {
idxMax = i;
distMax = distCurr;
}
}
return idxMax;
}
// The gift-wrapping algorithm for convex hull.
// https://en.wikipedia.org/wiki/Gift_wrapping_algorithm
vector<point> giftWrapping(const vector<point>& v) {
// Start with the leftmost point.
size_t startIdx = min_element(v.begin(), v.end(), isLeftOf) - v.begin();
size_t hIdx = startIdx;
vector<point> hull;
do {
// Add our current point to the hull.
hull.push_back(v[hIdx]);
// Find the index of the input point that is farthest
// ccw from our last hull point.
ccwSorter isCcw(v[hIdx]);
size_t endIdx = 0;
for (size_t i = 1; i < v.size(); ++i) {
if ((endIdx == hIdx) || isCcw(v[endIdx], v[i])) {
endIdx = i;
}
}
// Make that our new
hIdx = endIdx;
} while (hIdx != startIdx);
return hull;
}
// The Graham scan algorithm for convex hull.
// https://en.wikipedia.org/wiki/Graham_scan
vector<point> GrahamScan(vector<point> v) {
// Put our leftmost point at index 0
swap(v[0], *min_element(v.begin(), v.end(), isLeftOf));
// Sort the rest of the points in counter-clockwise order
// from our leftmost point.
sort(v.begin() + 1, v.end(), ccwSorter(v[0]));
// Add our first three points to the hull.
vector<point> hull;
auto it = v.begin();
hull.push_back(*it++);
hull.push_back(*it++);
hull.push_back(*it++);
while (it != v.end()) {
// Pop off any points that make a convex angle with *it
while (ccw(*(hull.rbegin() + 1), *(hull.rbegin()), *it) >= 0) {
hull.pop_back();
}
hull.push_back(*it++);
}
return hull;
}
// The monotone chain algorithm for convex hull.
vector<point> monotoneChain(vector<point> v) {
// Sort our points in lexicographic order.
sort(v.begin(), v.end(), isLeftOf);
// Find the lower half of the convex hull.
vector<point> lower;
for (auto it = v.begin(); it != v.end(); ++it) {
// Pop off any points that make a convex angle with *it
while (lower.size() >= 2 && ccw(*(lower.rbegin() + 1), *(lower.rbegin()), *it) >= 0) {
lower.pop_back();
}
lower.push_back(*it);
}
// Find the upper half of the convex hull.
vector<point> upper;
for (auto it = v.rbegin(); it != v.rend(); ++it) {
// Pop off any points that make a convex angle with *it
while (upper.size() >= 2 && ccw(*(upper.rbegin() + 1), *(upper.rbegin()), *it) >= 0) {
upper.pop_back();
}
upper.push_back(*it);
}
vector<point> hull;
hull.insert(hull.end(), lower.begin(), lower.end());
// Both hulls include both endpoints, so leave them out when we
// append the upper hull.
hull.insert(hull.end(), upper.begin() + 1, upper.end() - 1);
return hull;
}
// Recursive call of the quickhull algorithm.
void quickHull(const vector<point>& v, const point& a, const point& b,
vector<point>& hull) {
if (v.empty()) {
return;
}
point f = v[getFarthest(a, b, v)];
// Collect points to the left of segment (a, f)
vector<point> left;
for (auto p : v) {
if (ccw(a, f, p) > 0) {
left.push_back(p);
}
}
quickHull(left, a, f, hull);
// Add f to the hull
hull.push_back(f);
// Collect points to the left of segment (f, b)
vector<point> right;
for (auto p : v) {
if (ccw(f, b, p) > 0) {
right.push_back(p);
}
}
quickHull(right, f, b, hull);
}
// QuickHull algorithm.
// https://en.wikipedia.org/wiki/QuickHull
vector<point> quickHull(const vector<point>& v) {
vector<point> hull;
// Start with the leftmost and rightmost points.
point a = *min_element(v.begin(), v.end(), isLeftOf);
point b = *max_element(v.begin(), v.end(), isLeftOf);
// Split the points on either side of segment (a, b)
vector<point> left, right;
for (auto p : v) {
ccw(a, b, p) > 0 ? left.push_back(p) : right.push_back(p);
}
// Be careful to add points to the hull
// in the correct order. Add our leftmost point.
hull.push_back(a);
// Add hull points from the left (top)
quickHull(left, a, b, hull);
// Add our rightmost point
hull.push_back(b);
// Add hull points from the right (bottom)
quickHull(right, b, a, hull);
return hull;
}
vector<point> getPoints() {
vector<point> v;
const float lo = -100.0;
const float hi = 100.0;
for (int i = 0; i < 100; ++i) {
float x = lo +
static_cast<float>(
rand()) / static_cast<float>(RAND_MAX / (hi - lo));
float y = lo +
static_cast<float>(
rand()) / static_cast<float>(RAND_MAX / (hi - lo));
v.push_back(point(x, y));
}
return v;
}
void print(const vector<point>& v) {
for (auto p : v) {
cout << p.x << ", " << p.y << endl;
}
}
int main() {
vector<point> v = getPoints();
vector<point> h = quickHull(v);
cout << "quickHull point count: " << h.size() << endl;
print(h);
h = giftWrapping(v);
cout << endl << "giftWrapping point count: " << h.size() << endl;
print(h);
h = monotoneChain(v);
cout << endl << "monotoneChain point count: " << h.size() << endl;
print(h);
h = GrahamScan(v);
cout << endl << "GrahamScan point count: " << h.size() << endl;
print(h);
return 0;
}
<commit_msg>simplify gift-wrapping algorithm<commit_after>// Implementations of various convex hull algorithms
// using the C++ Standard Library.
// For clarity, the implementations do not check for
// duplicate or collinear points.
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
struct point {
float x;
float y;
point(float xIn, float yIn) : x(xIn), y(yIn) { }
};
// The z-value of the cross product of segments
// (a, b) and (a, c). Positive means c is ccw
// from (a, b), negative cw. Zero means its collinear.
float ccw(const point& a, const point& b, const point& c) {
return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
}
// Returns true if a is lexicographically before b.
bool isLeftOf(const point& a, const point& b) {
return (a.x < b.x || (a.x == b.x && a.y < b.y));
}
// Used to sort points in ccw order about a pivot.
struct ccwSorter {
const point& pivot;
ccwSorter(const point& inPivot) : pivot(inPivot) { }
bool operator()(const point& a, const point& b) {
return ccw(pivot, a, b) < 0;
}
};
// The length of segment (a, b).
float len(const point& a, const point& b) {
return sqrt((b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - a.y));
}
// The unsigned distance of p from segment (a, b).
float dist(const point& a, const point& b, const point& p) {
return fabs((b.x - a.x) * (a.y - p.y) - (b.y - a.y) * (a.x - p.x)) / len(a, b);
}
// Returns the index of the farthest point from segment (a, b).
size_t getFarthest(const point& a, const point& b, const vector<point>& v) {
size_t idxMax = 0;
float distMax = dist(a, b, v[idxMax]);
for (size_t i = 1; i < v.size(); ++i) {
float distCurr = dist(a, b, v[i]);
if (distCurr > distMax) {
idxMax = i;
distMax = distCurr;
}
}
return idxMax;
}
// The gift-wrapping algorithm for convex hull.
// https://en.wikipedia.org/wiki/Gift_wrapping_algorithm
vector<point> giftWrapping(vector<point> v) {
// Move the leftmost point to the beginning of our vector.
// It will be the first point in our convext hull.
swap(v[0], *min_element(v.begin(), v.end(), isLeftOf));
vector<point> hull;
// Repeatedly find the first ccw point from our last hull point
// and put it at the front of our array.
// Stop when we see our first point again.
do {
hull.push_back(v[0]);
swap(v[0], *min_element(v.begin() + 1, v.end(), ccwSorter(v[0])));
} while (v[0].x != hull[0].x && v[0].y != hull[0].y);
return hull;
}
// The Graham scan algorithm for convex hull.
// https://en.wikipedia.org/wiki/Graham_scan
vector<point> GrahamScan(vector<point> v) {
// Put our leftmost point at index 0
swap(v[0], *min_element(v.begin(), v.end(), isLeftOf));
// Sort the rest of the points in counter-clockwise order
// from our leftmost point.
sort(v.begin() + 1, v.end(), ccwSorter(v[0]));
// Add our first three points to the hull.
vector<point> hull;
auto it = v.begin();
hull.push_back(*it++);
hull.push_back(*it++);
hull.push_back(*it++);
while (it != v.end()) {
// Pop off any points that make a convex angle with *it
while (ccw(*(hull.rbegin() + 1), *(hull.rbegin()), *it) >= 0) {
hull.pop_back();
}
hull.push_back(*it++);
}
return hull;
}
// The monotone chain algorithm for convex hull.
vector<point> monotoneChain(vector<point> v) {
// Sort our points in lexicographic order.
sort(v.begin(), v.end(), isLeftOf);
// Find the lower half of the convex hull.
vector<point> lower;
for (auto it = v.begin(); it != v.end(); ++it) {
// Pop off any points that make a convex angle with *it
while (lower.size() >= 2 && ccw(*(lower.rbegin() + 1), *(lower.rbegin()), *it) >= 0) {
lower.pop_back();
}
lower.push_back(*it);
}
// Find the upper half of the convex hull.
vector<point> upper;
for (auto it = v.rbegin(); it != v.rend(); ++it) {
// Pop off any points that make a convex angle with *it
while (upper.size() >= 2 && ccw(*(upper.rbegin() + 1), *(upper.rbegin()), *it) >= 0) {
upper.pop_back();
}
upper.push_back(*it);
}
vector<point> hull;
hull.insert(hull.end(), lower.begin(), lower.end());
// Both hulls include both endpoints, so leave them out when we
// append the upper hull.
hull.insert(hull.end(), upper.begin() + 1, upper.end() - 1);
return hull;
}
// Recursive call of the quickhull algorithm.
void quickHull(const vector<point>& v, const point& a, const point& b,
vector<point>& hull) {
if (v.empty()) {
return;
}
point f = v[getFarthest(a, b, v)];
// Collect points to the left of segment (a, f)
vector<point> left;
for (auto p : v) {
if (ccw(a, f, p) > 0) {
left.push_back(p);
}
}
quickHull(left, a, f, hull);
// Add f to the hull
hull.push_back(f);
// Collect points to the left of segment (f, b)
vector<point> right;
for (auto p : v) {
if (ccw(f, b, p) > 0) {
right.push_back(p);
}
}
quickHull(right, f, b, hull);
}
// QuickHull algorithm.
// https://en.wikipedia.org/wiki/QuickHull
vector<point> quickHull(const vector<point>& v) {
vector<point> hull;
// Start with the leftmost and rightmost points.
point a = *min_element(v.begin(), v.end(), isLeftOf);
point b = *max_element(v.begin(), v.end(), isLeftOf);
// Split the points on either side of segment (a, b)
vector<point> left, right;
for (auto p : v) {
ccw(a, b, p) > 0 ? left.push_back(p) : right.push_back(p);
}
// Be careful to add points to the hull
// in the correct order. Add our leftmost point.
hull.push_back(a);
// Add hull points from the left (top)
quickHull(left, a, b, hull);
// Add our rightmost point
hull.push_back(b);
// Add hull points from the right (bottom)
quickHull(right, b, a, hull);
return hull;
}
vector<point> getPoints() {
vector<point> v;
const float lo = -100.0;
const float hi = 100.0;
for (int i = 0; i < 100; ++i) {
float x = lo +
static_cast<float>(
rand()) / static_cast<float>(RAND_MAX / (hi - lo));
float y = lo +
static_cast<float>(
rand()) / static_cast<float>(RAND_MAX / (hi - lo));
v.push_back(point(x, y));
}
return v;
}
void print(const vector<point>& v) {
for (auto p : v) {
cout << p.x << ", " << p.y << endl;
}
}
int main() {
vector<point> v = getPoints();
vector<point> h = quickHull(v);
cout << "quickHull point count: " << h.size() << endl;
print(h);
h = giftWrapping(v);
cout << endl << "giftWrapping point count: " << h.size() << endl;
print(h);
h = monotoneChain(v);
cout << endl << "monotoneChain point count: " << h.size() << endl;
print(h);
h = GrahamScan(v);
cout << endl << "GrahamScan point count: " << h.size() << endl;
print(h);
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2015 Patrick Putnam
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef BERNOULLI_CLASSIFIER_GENERATOR_HPP_
#define BERNOULLI_CLASSIFIER_GENERATOR_HPP_
#include "clotho/utility/random_generator.hpp"
#include "clotho/classifiers/bernoulli_classifier.hpp"
namespace clotho {
namespace utility {
template < class URNG >
class random_generator< URNG, clotho::classifiers::bernoulli_classifier< URNG, double, bool > > {
public:
typedef random_generator< URNG, clotho::classifiers::bernoulli_classifier< URNG, double, bool > > self_type;
typedef clotho::classifiers::bernoulli_classifier< URNG, double, bool > result_type;
random_generator( URNG & rng, boost::property_tree::ptree & config ) :
m_rng( &rng )
, m_p( 0.5 ) {
parseConfig( config );
}
random_generator( URNG & rng, double p = 0.5 ) :
m_rng( &rng )
, m_p( p ) {
}
result_type operator()() {
return result_type( m_rng, m_p );
}
protected:
void parseConfig( boost::property_tree::ptree & config ) {
const string ppath = "classifiers.toolkit.bernoulli.p";
if( config.get_child_optional( ppath ) == boost::none ) {
config.put( ppath, m_p );
} else {
m_p = config.get< double >( ppath );
assert( 0. <= m_p <= 1.);
}
}
URNG * m_rng;
double m_p;
};
} // namespace utility {
} // namespace clotho {
#endif // BERNOULLI_CLASSIFIER_GENERATOR_HPP_
<commit_msg>Stupid error<commit_after>// Copyright 2015 Patrick Putnam
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef BERNOULLI_CLASSIFIER_GENERATOR_HPP_
#define BERNOULLI_CLASSIFIER_GENERATOR_HPP_
#include "clotho/utility/random_generator.hpp"
#include "clotho/classifiers/bernoulli_classifier.hpp"
namespace clotho {
namespace utility {
template < class URNG >
class random_generator< URNG, clotho::classifiers::bernoulli_classifier< URNG, double, bool > > {
public:
typedef random_generator< URNG, clotho::classifiers::bernoulli_classifier< URNG, double, bool > > self_type;
typedef clotho::classifiers::bernoulli_classifier< URNG, double, bool > result_type;
random_generator( URNG & rng, boost::property_tree::ptree & config ) :
m_rng( &rng )
, m_p( 0.5 ) {
parseConfig( config );
}
random_generator( URNG & rng, double p = 0.5 ) :
m_rng( &rng )
, m_p( p ) {
}
result_type operator()() {
return result_type( m_rng, m_p );
}
protected:
void parseConfig( boost::property_tree::ptree & config ) {
const string ppath = "classifiers.toolkit.bernoulli.p";
if( config.get_child_optional( ppath ) == boost::none ) {
config.put( ppath, m_p );
} else {
m_p = config.get< double >( ppath );
assert( 0. <= m_p && m_p <= 1.);
}
}
URNG * m_rng;
double m_p;
};
} // namespace utility {
} // namespace clotho {
#endif // BERNOULLI_CLASSIFIER_GENERATOR_HPP_
<|endoftext|> |
<commit_before>// The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// 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 <ostream>
#include <stack>
#include "BitFunnel/Configuration/Factories.h"
#include "BitFunnel/Configuration/IFileSystem.h"
#include "BitFunnel/Index/DocumentHandle.h"
#include "BitFunnel/Index/Factories.h"
#include "BitFunnel/Index/IDocument.h"
#include "BitFunnel/Index/IDocumentCache.h"
#include "BitFunnel/Index/IDocumentFrequencyTable.h"
#include "BitFunnel/Index/IIngestor.h"
#include "BitFunnel/Index/ISimpleIndex.h"
#include "BitFunnel/Index/RowIdSequence.h"
#include "CsvTsv/Csv.h"
#include "DocumentHandleInternal.h"
#include "LoggerInterfaces/Check.h"
#include "RowTableAnalyzer.h"
#include "RowTableDescriptor.h"
#include "Shard.h"
#include "TermToText.h"
namespace BitFunnel
{
void Factories::AnalyzeRowTables(ISimpleIndex const & index,
char const * outDir)
{
char const end = '\0'; // TODO: Workaround for issue #386.
CHECK_NE(*outDir, end)
<< "Output directory not set. ";
RowTableAnalyzer statistics(index);
statistics.AnalyzeColumns(outDir);
statistics.AnalyzeRows(outDir);
}
RowTableAnalyzer::RowTableAnalyzer(ISimpleIndex const & index)
: m_index(index)
{
}
//*************************************************************************
//
// Row Statistics
//
//*************************************************************************
class RowStatistics
{
public:
static void WriteHeader(std::ostream& out)
{
CsvTsv::CsvTableFormatter formatter(out);
formatter.WritePrologue(std::vector<char const *>{
"shard", "idfX10", "rank", "mean", "min", "max", "var", "count"});
}
void WriteSummary(std::ostream& out,
ShardId const & shardId,
Term::IdfX10 idfX10) const
{
for (Rank rank = 0; rank < c_maxRankValue; ++rank)
{
Accumulator const & accumulator = m_accumulators[rank];
if (accumulator.GetCount() == 0)
continue;
out << shardId << ","
<< static_cast<uint32_t>(idfX10) << ","
<< rank << ","
<< accumulator.GetMean() << ","
<< accumulator.GetMin() << ","
<< accumulator.GetMax() << ","
<< accumulator.GetVariance() << ","
<< accumulator.GetCount() << std::endl;
}
}
void RecordDensity(Rank rank, double density)
{
m_accumulators.at(rank).Record(density);
}
void Reset()
{
for (auto it = m_accumulators.begin(); it != m_accumulators.end(); ++it)
{
it->Reset();
}
}
private:
std::array<Accumulator, c_maxRankValue> m_accumulators;
};
//*************************************************************************
//
// Analyze rows
//
//*************************************************************************
void RowTableAnalyzer::AnalyzeRows(char const * outDir) const
{
//
// Gather row statistics for ingested documents.
// (documents need not be cached)
//
auto & fileManager = m_index.GetFileManager();
auto & ingestor = m_index.GetIngestor();
// Obtain data for converting a term hash to text, if file exists
std::unique_ptr<ITermToText> termToText;
try
{
// Will fail with exception if file does not exist or can't be read
// TODO: Create with factory?
termToText = Factories::CreateTermToText(*fileManager.TermToText().OpenForRead());
}
catch (RecoverableError e)
{
termToText = Factories::CreateTermToText();
}
auto fileSystem = Factories::CreateFileSystem();
auto outFileManager =
Factories::CreateFileManager(outDir,
outDir,
outDir,
*fileSystem);
auto summaryOut = outFileManager->RowDensitySummary().OpenForWrite();
RowStatistics::WriteHeader(*summaryOut);
for (ShardId shardId = 0; shardId < ingestor.GetShardCount(); ++shardId)
{
AnalyzeRowsInOneShard(shardId,
*termToText,
*outFileManager->RowDensities(shardId).OpenForWrite(),
*summaryOut);
}
}
void RowTableAnalyzer::AnalyzeRowsInOneShard(
ShardId const & shardId,
ITermToText const & termToText,
std::ostream& out,
std::ostream& summaryOut) const
{
auto & shard = m_index.GetIngestor().GetShard(shardId);
std::array<std::vector<double>, c_maxRankValue+1> densities;
for (Rank rank = 0; rank <= c_maxRankValue; ++rank)
{
densities[rank] = shard.GetDensities(rank);
}
RowStatistics statistics;
Term::IdfX10 curIdfX10 = 0;
// Use CsvTableFormatter to escape terms that contain commas and quotes.
CsvTsv::CsvTableFormatter formatter(out);
auto & fileManager = m_index.GetFileManager();
auto terms(Factories::CreateDocumentFrequencyTable(
*fileManager.DocFreqTable(shardId).OpenForRead()));
for (auto dfEntry : *terms)
{
Term term = dfEntry.GetTerm();
Term::IdfX10 idfX10 = Term::ComputeIdfX10(dfEntry.GetFrequency(), Term::c_maxIdfX10Value);
// When we cross an idfX10 bucket boundary, output statistics
// accumulated since previous idfX10 bucket. Then reset
// statistics accumulators for the next bucket.
if (idfX10 != curIdfX10)
{
curIdfX10 = idfX10;
statistics.WriteSummary(summaryOut, shardId, curIdfX10);
statistics.Reset();
}
RowIdSequence rows(term, m_index.GetTermTable(shardId));
std::string termName = termToText.Lookup(term.GetRawHash());
if (!termName.empty())
{
// Print out the term text if we have it.
formatter.WriteField(termName);
}
else
{
// Otherwise print out the term's hash.
formatter.SetHexMode(1);
formatter.WriteField(term.GetRawHash());
formatter.SetHexMode(0);
}
formatter.WriteField(dfEntry.GetFrequency());
std::stack<RowId> rowsReversed;
for (auto row : rows)
{
rowsReversed.push(row);
}
while (!rowsReversed.empty())
{
auto row = rowsReversed.top();
auto rank = row.GetRank();
auto index = row.GetIndex();
auto density = densities.at(rank).at(index);
statistics.RecordDensity(rank, density);
formatter.WriteField("r");
out << row.GetRank();
formatter.WriteField(index);
formatter.WriteField(density);
rowsReversed.pop();
}
formatter.WriteRowEnd();
}
statistics.WriteSummary(summaryOut, shardId, curIdfX10);
}
//*************************************************************************
//
// Analyze columns
//
//*************************************************************************
void RowTableAnalyzer::AnalyzeColumns(char const * outDir) const
{
auto & ingestor = m_index.GetIngestor();
auto fileSystem = Factories::CreateFileSystem();
auto outFileManager =
Factories::CreateFileManager(outDir,
outDir,
outDir,
*fileSystem);
auto summaryOut = outFileManager->ColumnDensitySummary().OpenForWrite();
// TODO: Consider using CsvTsv::CsvTableFormatter::WritePrologue() here.
*summaryOut << "shard,rank,mean,min,max,var,count" << std::endl;
std::array<Accumulator, c_maxRankValue+1> accumulators;
for (auto shardId = 0; shardId < ingestor.GetShardCount(); ++shardId)
{
IShard& shard = ingestor.GetShard(shardId);
// Write out each document's raw column data per shard.
// No need to use CsvTableFormatter for escaping because all values
// are numbers.
auto out = outFileManager->ColumnDensities(shardId).OpenForWrite();
Column::WriteHeader(*out);
auto itPtr = shard.GetIterator();
auto & it = *itPtr;
for (; !it.AtEnd(); ++it)
{
const DocumentHandleInternal handle(*it);
const DocId docId = handle.GetDocId();
Slice const & slice = handle.GetSlice();
// TODO: handle.GetPostingCount() instead of 0
Column column(docId, shardId, 0);
void const * buffer = slice.GetSliceBuffer();
const DocIndex docIndex = handle.GetIndex();
for (Rank rank = 0; rank <= c_maxRankValue; ++rank)
{
RowTableDescriptor rowTable = slice.GetRowTable(rank);
size_t bitCount = 0;
const size_t rowCount = rowTable.GetRowCount();
for (RowIndex row = 0; row < rowCount; ++row)
{
if (rowTable.GetBit(buffer, row, docIndex) != 0)
{
++bitCount;
}
}
column.SetCount(rank, bitCount);
double density =
(rowCount == 0) ? 0.0 : static_cast<double>(bitCount) / rowCount;
column.SetDensity(rank, density);
accumulators[rank].Record(density);
}
column.Write(*out);
}
//
// Generate document summary by rank for shard
//
for (Rank rank = 0; rank < c_maxRankValue; ++rank)
{
Accumulator accumulator = accumulators[rank];
if (accumulator.GetCount() == 0)
continue;
*summaryOut
<< shardId << ","
<< rank << ","
<< accumulator.GetMean() << ","
<< accumulator.GetMin() << ","
<< accumulator.GetMax() << ","
<< accumulator.GetVariance() << ","
<< accumulator.GetCount() << std::endl;
accumulators[rank].Reset();
}
}
}
RowTableAnalyzer::Column::Column(DocId id, ShardId shard, size_t postings)
: m_id(id),
m_postings(postings),
m_shard(shard),
m_bits{}
{
}
void RowTableAnalyzer::Column::SetCount(Rank rank, size_t count)
{
m_bits[rank] = count;
}
void RowTableAnalyzer::Column::SetDensity(Rank rank, double density)
{
m_densities[rank] = density;
}
void RowTableAnalyzer::Column::WriteHeader(std::ostream& out)
{
out << "id,postings,shard";
for (Rank rank = 0; rank <= c_maxRankValue; ++rank)
{
out << ",rank" << rank;
}
out << std::endl;
}
void RowTableAnalyzer::Column::Write(std::ostream& out)
{
out << m_id
<< "," << m_postings
<< "," << m_shard;
for (Rank rank = 0; rank <= c_maxRankValue; ++rank)
{
// TODO: Consider writing out or eliminating m_bits.
out << "," << m_densities[rank];
}
out << std::endl;
}
}
<commit_msg>Fix Linux signed/unsigned comparison mismatch<commit_after>// The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// 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 <ostream>
#include <stack>
#include "BitFunnel/Configuration/Factories.h"
#include "BitFunnel/Configuration/IFileSystem.h"
#include "BitFunnel/Index/DocumentHandle.h"
#include "BitFunnel/Index/Factories.h"
#include "BitFunnel/Index/IDocument.h"
#include "BitFunnel/Index/IDocumentCache.h"
#include "BitFunnel/Index/IDocumentFrequencyTable.h"
#include "BitFunnel/Index/IIngestor.h"
#include "BitFunnel/Index/ISimpleIndex.h"
#include "BitFunnel/Index/RowIdSequence.h"
#include "CsvTsv/Csv.h"
#include "DocumentHandleInternal.h"
#include "LoggerInterfaces/Check.h"
#include "RowTableAnalyzer.h"
#include "RowTableDescriptor.h"
#include "Shard.h"
#include "TermToText.h"
namespace BitFunnel
{
void Factories::AnalyzeRowTables(ISimpleIndex const & index,
char const * outDir)
{
char const end = '\0'; // TODO: Workaround for issue #386.
CHECK_NE(*outDir, end)
<< "Output directory not set. ";
RowTableAnalyzer statistics(index);
statistics.AnalyzeColumns(outDir);
statistics.AnalyzeRows(outDir);
}
RowTableAnalyzer::RowTableAnalyzer(ISimpleIndex const & index)
: m_index(index)
{
}
//*************************************************************************
//
// Row Statistics
//
//*************************************************************************
class RowStatistics
{
public:
static void WriteHeader(std::ostream& out)
{
CsvTsv::CsvTableFormatter formatter(out);
formatter.WritePrologue(std::vector<char const *>{
"shard", "idfX10", "rank", "mean", "min", "max", "var", "count"});
}
void WriteSummary(std::ostream& out,
ShardId const & shardId,
Term::IdfX10 idfX10) const
{
for (Rank rank = 0; rank < c_maxRankValue; ++rank)
{
Accumulator const & accumulator = m_accumulators[rank];
if (accumulator.GetCount() == 0)
continue;
out << shardId << ","
<< static_cast<uint32_t>(idfX10) << ","
<< rank << ","
<< accumulator.GetMean() << ","
<< accumulator.GetMin() << ","
<< accumulator.GetMax() << ","
<< accumulator.GetVariance() << ","
<< accumulator.GetCount() << std::endl;
}
}
void RecordDensity(Rank rank, double density)
{
m_accumulators.at(rank).Record(density);
}
void Reset()
{
for (auto it = m_accumulators.begin(); it != m_accumulators.end(); ++it)
{
it->Reset();
}
}
private:
std::array<Accumulator, c_maxRankValue> m_accumulators;
};
//*************************************************************************
//
// Analyze rows
//
//*************************************************************************
void RowTableAnalyzer::AnalyzeRows(char const * outDir) const
{
//
// Gather row statistics for ingested documents.
// (documents need not be cached)
//
auto & fileManager = m_index.GetFileManager();
auto & ingestor = m_index.GetIngestor();
// Obtain data for converting a term hash to text, if file exists
std::unique_ptr<ITermToText> termToText;
try
{
// Will fail with exception if file does not exist or can't be read
// TODO: Create with factory?
termToText = Factories::CreateTermToText(*fileManager.TermToText().OpenForRead());
}
catch (RecoverableError e)
{
termToText = Factories::CreateTermToText();
}
auto fileSystem = Factories::CreateFileSystem();
auto outFileManager =
Factories::CreateFileManager(outDir,
outDir,
outDir,
*fileSystem);
auto summaryOut = outFileManager->RowDensitySummary().OpenForWrite();
RowStatistics::WriteHeader(*summaryOut);
for (ShardId shardId = 0; shardId < ingestor.GetShardCount(); ++shardId)
{
AnalyzeRowsInOneShard(shardId,
*termToText,
*outFileManager->RowDensities(shardId).OpenForWrite(),
*summaryOut);
}
}
void RowTableAnalyzer::AnalyzeRowsInOneShard(
ShardId const & shardId,
ITermToText const & termToText,
std::ostream& out,
std::ostream& summaryOut) const
{
auto & shard = m_index.GetIngestor().GetShard(shardId);
std::array<std::vector<double>, c_maxRankValue+1> densities;
for (Rank rank = 0; rank <= c_maxRankValue; ++rank)
{
densities[rank] = shard.GetDensities(rank);
}
RowStatistics statistics;
Term::IdfX10 curIdfX10 = 0;
// Use CsvTableFormatter to escape terms that contain commas and quotes.
CsvTsv::CsvTableFormatter formatter(out);
auto & fileManager = m_index.GetFileManager();
auto terms(Factories::CreateDocumentFrequencyTable(
*fileManager.DocFreqTable(shardId).OpenForRead()));
for (auto dfEntry : *terms)
{
Term term = dfEntry.GetTerm();
Term::IdfX10 idfX10 = Term::ComputeIdfX10(dfEntry.GetFrequency(), Term::c_maxIdfX10Value);
// When we cross an idfX10 bucket boundary, output statistics
// accumulated since previous idfX10 bucket. Then reset
// statistics accumulators for the next bucket.
if (idfX10 != curIdfX10)
{
curIdfX10 = idfX10;
statistics.WriteSummary(summaryOut, shardId, curIdfX10);
statistics.Reset();
}
RowIdSequence rows(term, m_index.GetTermTable(shardId));
std::string termName = termToText.Lookup(term.GetRawHash());
if (!termName.empty())
{
// Print out the term text if we have it.
formatter.WriteField(termName);
}
else
{
// Otherwise print out the term's hash.
formatter.SetHexMode(1);
formatter.WriteField(term.GetRawHash());
formatter.SetHexMode(0);
}
formatter.WriteField(dfEntry.GetFrequency());
std::stack<RowId> rowsReversed;
for (auto row : rows)
{
rowsReversed.push(row);
}
while (!rowsReversed.empty())
{
auto row = rowsReversed.top();
auto rank = row.GetRank();
auto index = row.GetIndex();
auto density = densities.at(rank).at(index);
statistics.RecordDensity(rank, density);
formatter.WriteField("r");
out << row.GetRank();
formatter.WriteField(index);
formatter.WriteField(density);
rowsReversed.pop();
}
formatter.WriteRowEnd();
}
statistics.WriteSummary(summaryOut, shardId, curIdfX10);
}
//*************************************************************************
//
// Analyze columns
//
//*************************************************************************
void RowTableAnalyzer::AnalyzeColumns(char const * outDir) const
{
auto & ingestor = m_index.GetIngestor();
auto fileSystem = Factories::CreateFileSystem();
auto outFileManager =
Factories::CreateFileManager(outDir,
outDir,
outDir,
*fileSystem);
auto summaryOut = outFileManager->ColumnDensitySummary().OpenForWrite();
// TODO: Consider using CsvTsv::CsvTableFormatter::WritePrologue() here.
*summaryOut << "shard,rank,mean,min,max,var,count" << std::endl;
std::array<Accumulator, c_maxRankValue+1> accumulators;
for (ShardId shardId = 0; shardId < ingestor.GetShardCount(); ++shardId)
{
IShard& shard = ingestor.GetShard(shardId);
// Write out each document's raw column data per shard.
// No need to use CsvTableFormatter for escaping because all values
// are numbers.
auto out = outFileManager->ColumnDensities(shardId).OpenForWrite();
Column::WriteHeader(*out);
auto itPtr = shard.GetIterator();
auto & it = *itPtr;
for (; !it.AtEnd(); ++it)
{
const DocumentHandleInternal handle(*it);
const DocId docId = handle.GetDocId();
Slice const & slice = handle.GetSlice();
// TODO: handle.GetPostingCount() instead of 0
Column column(docId, shardId, 0);
void const * buffer = slice.GetSliceBuffer();
const DocIndex docIndex = handle.GetIndex();
for (Rank rank = 0; rank <= c_maxRankValue; ++rank)
{
RowTableDescriptor rowTable = slice.GetRowTable(rank);
size_t bitCount = 0;
const size_t rowCount = rowTable.GetRowCount();
for (RowIndex row = 0; row < rowCount; ++row)
{
if (rowTable.GetBit(buffer, row, docIndex) != 0)
{
++bitCount;
}
}
column.SetCount(rank, bitCount);
double density =
(rowCount == 0) ? 0.0 : static_cast<double>(bitCount) / rowCount;
column.SetDensity(rank, density);
accumulators[rank].Record(density);
}
column.Write(*out);
}
//
// Generate document summary by rank for shard
//
for (Rank rank = 0; rank < c_maxRankValue; ++rank)
{
Accumulator accumulator = accumulators[rank];
if (accumulator.GetCount() == 0)
continue;
*summaryOut
<< shardId << ","
<< rank << ","
<< accumulator.GetMean() << ","
<< accumulator.GetMin() << ","
<< accumulator.GetMax() << ","
<< accumulator.GetVariance() << ","
<< accumulator.GetCount() << std::endl;
accumulators[rank].Reset();
}
}
}
RowTableAnalyzer::Column::Column(DocId id, ShardId shard, size_t postings)
: m_id(id),
m_postings(postings),
m_shard(shard),
m_bits{}
{
}
void RowTableAnalyzer::Column::SetCount(Rank rank, size_t count)
{
m_bits[rank] = count;
}
void RowTableAnalyzer::Column::SetDensity(Rank rank, double density)
{
m_densities[rank] = density;
}
void RowTableAnalyzer::Column::WriteHeader(std::ostream& out)
{
out << "id,postings,shard";
for (Rank rank = 0; rank <= c_maxRankValue; ++rank)
{
out << ",rank" << rank;
}
out << std::endl;
}
void RowTableAnalyzer::Column::Write(std::ostream& out)
{
out << m_id
<< "," << m_postings
<< "," << m_shard;
for (Rank rank = 0; rank <= c_maxRankValue; ++rank)
{
// TODO: Consider writing out or eliminating m_bits.
out << "," << m_densities[rank];
}
out << std::endl;
}
}
<|endoftext|> |
<commit_before>// The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// 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 <ostream>
#include <stack>
#include "BitFunnel/Configuration/Factories.h"
#include "BitFunnel/Configuration/IFileSystem.h"
#include "BitFunnel/IFileManager.h"
#include "BitFunnel/Index/DocumentHandle.h"
#include "BitFunnel/Index/Factories.h"
#include "BitFunnel/Index/IDocument.h"
#include "BitFunnel/Index/IDocumentCache.h"
#include "BitFunnel/Index/IDocumentFrequencyTable.h"
#include "BitFunnel/Index/IIngestor.h"
#include "BitFunnel/Index/ISimpleIndex.h"
#include "BitFunnel/Index/RowIdSequence.h"
#include "BitFunnel/Index/Token.h"
#include "CsvTsv/Csv.h"
#include "DocumentHandleInternal.h"
#include "LoggerInterfaces/Check.h"
#include "RowTableAnalyzer.h"
#include "RowTableDescriptor.h"
#include "Shard.h"
#include "Slice.h"
#include "TermToText.h"
namespace BitFunnel
{
void Factories::AnalyzeRowTables(ISimpleIndex const & index,
char const * outDir)
{
CHECK_NE(*outDir, '\0')
<< "Output directory not set. ";
RowTableAnalyzer statistics(index);
statistics.AnalyzeColumns(outDir);
statistics.AnalyzeRows(outDir);
}
RowTableAnalyzer::RowTableAnalyzer(ISimpleIndex const & index)
: m_index(index)
{
}
//*************************************************************************
//
// Analyze rows
//
//*************************************************************************
void RowTableAnalyzer::AnalyzeRows(char const * outDir) const
{
//
// Gather row statistics for ingested documents.
// (documents need not be cached)
//
auto & fileManager = m_index.GetFileManager();
auto & ingestor = m_index.GetIngestor();
// TODO: Create with factory?
TermToText termToText(*fileManager.TermToText().OpenForRead());
for (ShardId shardId = 0; shardId < ingestor.GetShardCount(); ++shardId)
{
auto terms(Factories::CreateDocumentFrequencyTable(
*fileManager.DocFreqTable(shardId).OpenForRead()));
auto fileSystem = Factories::CreateFileSystem();
auto outFileManager =
Factories::CreateFileManager(outDir,
outDir,
outDir,
*fileSystem);
AnalyzeRowsInOneShard(shardId,
termToText,
*outFileManager->RowDensities(shardId).OpenForWrite());
}
}
void RowTableAnalyzer::AnalyzeRowsInOneShard(
ShardId const & shardId,
ITermToText const & termToText,
std::ostream& out) const
{
auto & fileManager = m_index.GetFileManager();
auto terms(Factories::CreateDocumentFrequencyTable(
*fileManager.DocFreqTable(shardId).OpenForRead()));
std::array<std::vector<double>, c_maxRankValue> densities;
for (Rank rank = 0; rank < c_maxRankValue; ++rank)
{
auto & shard = m_index.GetIngestor().GetShard(shardId);
densities[rank] = shard.GetDensities(rank);
}
// Use CsvTableFormatter to escape terms that contain commas and quotes.
CsvTsv::CsvTableFormatter formatter(out);
for (auto dfEntry : *terms)
{
Term term = dfEntry.GetTerm();
RowIdSequence rows(term, m_index.GetTermTable());
formatter.WriteField(termToText.Lookup(term.GetRawHash()));
formatter.WriteField(dfEntry.GetFrequency());
std::stack<RowId> rowsReversed;
for (auto row : rows)
{
rowsReversed.push(row);
}
while (!rowsReversed.empty())
{
auto row = rowsReversed.top();
formatter.WriteField("r");
out << row.GetRank();
formatter.WriteField(row.GetIndex());
formatter.WriteField(densities[row.GetRank()][row.GetIndex()]);
rowsReversed.pop();
}
formatter.WriteRowEnd();
}
}
//*************************************************************************
//
// Analyze columns
//
//*************************************************************************
void RowTableAnalyzer::AnalyzeColumns(char const * outDir) const
{
auto & ingestor = m_index.GetIngestor();
auto & cache = ingestor.GetDocumentCache();
std::vector<Column> columns;
for (auto doc : cache)
{
const DocumentHandleInternal
handle(ingestor.GetHandle(doc.second));
Slice const & slice = handle.GetSlice();
const ShardId shard = slice.GetShard().GetId();
columns.emplace_back(doc.second,
shard,
doc.first.GetPostingCount());
void const * buffer = slice.GetSliceBuffer();
const DocIndex column = handle.GetIndex();
for (Rank rank = 0; rank <= c_maxRankValue; ++rank)
{
RowTableDescriptor rowTable = slice.GetRowTable(rank);
size_t bitCount = 0;
const size_t rowCount = rowTable.GetRowCount();
for (RowIndex row = 0; row < rowCount; ++row)
{
bitCount +=
rowTable.GetBit(buffer, row, column);
}
columns.back().SetCount(rank, bitCount);
double density =
(rowCount == 0) ? 0.0 : static_cast<double>(bitCount) / rowCount;
columns.back().SetDensity(rank, density);
}
}
auto fileSystem = Factories::CreateFileSystem();
auto outFileManager =
Factories::CreateFileManager(outDir,
outDir,
outDir,
*fileSystem);
//
// Write out raw column data.
//
{
// No need to use CsvTableFormatter for escaping because all values
// are numbers.
auto out = outFileManager->ColumnDensities().OpenForWrite();
Column::WriteHeader(*out);
for (auto column : columns)
{
column.Write(*out);
}
}
//
// Generate summary.
//
{
auto out = outFileManager->ColumnDensitySummary().OpenForWrite();
*out << "Summary" << std::endl;
for (Rank rank = 0; rank <= c_maxRankValue; ++rank)
{
Accumulator accumulator;
for (auto column : columns)
{
accumulator.Record(column.m_densities[rank]);
}
*out << "Rank " << rank << std::endl
<< " column density: " << std::endl
<< " min: " << accumulator.GetMin() << std::endl
<< " max: " << accumulator.GetMax() << std::endl
<< " mean: " << accumulator.GetMean() << std::endl
<< " var: " << accumulator.GetVariance() << std::endl
<< " count: " << accumulator.GetCount() << std::endl;
}
}
}
RowTableAnalyzer::Column::Column(DocId id, ShardId shard, size_t postings)
: m_id(id),
m_postings(postings),
m_shard(shard),
m_bits{}
{
}
void RowTableAnalyzer::Column::SetCount(Rank rank, size_t count)
{
m_bits[rank] = count;
}
void RowTableAnalyzer::Column::SetDensity(Rank rank, double density)
{
m_densities[rank] = density;
}
void RowTableAnalyzer::Column::WriteHeader(std::ostream& out)
{
out << "id,postings,shard";
for (Rank rank = 0; rank <= c_maxRankValue; ++rank)
{
out << ",rank" << rank;
}
out << std::endl;
}
void RowTableAnalyzer::Column::Write(std::ostream& out)
{
out << m_id
<< "," << m_postings
<< "," << m_shard;
for (Rank rank = 0; rank <= c_maxRankValue; ++rank)
{
// TODO: Consider writing out or eliminating m_bits.
out << "," << m_densities[rank];
}
out << std::endl;
}
}
<commit_msg>Fix bug where analyzed column densities are too high.<commit_after>// The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// 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 <ostream>
#include <stack>
#include "BitFunnel/Configuration/Factories.h"
#include "BitFunnel/Configuration/IFileSystem.h"
#include "BitFunnel/IFileManager.h"
#include "BitFunnel/Index/DocumentHandle.h"
#include "BitFunnel/Index/Factories.h"
#include "BitFunnel/Index/IDocument.h"
#include "BitFunnel/Index/IDocumentCache.h"
#include "BitFunnel/Index/IDocumentFrequencyTable.h"
#include "BitFunnel/Index/IIngestor.h"
#include "BitFunnel/Index/ISimpleIndex.h"
#include "BitFunnel/Index/RowIdSequence.h"
#include "BitFunnel/Index/Token.h"
#include "CsvTsv/Csv.h"
#include "DocumentHandleInternal.h"
#include "LoggerInterfaces/Check.h"
#include "RowTableAnalyzer.h"
#include "RowTableDescriptor.h"
#include "Shard.h"
#include "Slice.h"
#include "TermToText.h"
namespace BitFunnel
{
void Factories::AnalyzeRowTables(ISimpleIndex const & index,
char const * outDir)
{
CHECK_NE(*outDir, '\0')
<< "Output directory not set. ";
RowTableAnalyzer statistics(index);
statistics.AnalyzeColumns(outDir);
statistics.AnalyzeRows(outDir);
}
RowTableAnalyzer::RowTableAnalyzer(ISimpleIndex const & index)
: m_index(index)
{
}
//*************************************************************************
//
// Analyze rows
//
//*************************************************************************
void RowTableAnalyzer::AnalyzeRows(char const * outDir) const
{
//
// Gather row statistics for ingested documents.
// (documents need not be cached)
//
auto & fileManager = m_index.GetFileManager();
auto & ingestor = m_index.GetIngestor();
// TODO: Create with factory?
TermToText termToText(*fileManager.TermToText().OpenForRead());
for (ShardId shardId = 0; shardId < ingestor.GetShardCount(); ++shardId)
{
auto terms(Factories::CreateDocumentFrequencyTable(
*fileManager.DocFreqTable(shardId).OpenForRead()));
auto fileSystem = Factories::CreateFileSystem();
auto outFileManager =
Factories::CreateFileManager(outDir,
outDir,
outDir,
*fileSystem);
AnalyzeRowsInOneShard(shardId,
termToText,
*outFileManager->RowDensities(shardId).OpenForWrite());
}
}
void RowTableAnalyzer::AnalyzeRowsInOneShard(
ShardId const & shardId,
ITermToText const & termToText,
std::ostream& out) const
{
auto & fileManager = m_index.GetFileManager();
auto terms(Factories::CreateDocumentFrequencyTable(
*fileManager.DocFreqTable(shardId).OpenForRead()));
std::array<std::vector<double>, c_maxRankValue> densities;
for (Rank rank = 0; rank < c_maxRankValue; ++rank)
{
auto & shard = m_index.GetIngestor().GetShard(shardId);
densities[rank] = shard.GetDensities(rank);
}
// Use CsvTableFormatter to escape terms that contain commas and quotes.
CsvTsv::CsvTableFormatter formatter(out);
for (auto dfEntry : *terms)
{
Term term = dfEntry.GetTerm();
RowIdSequence rows(term, m_index.GetTermTable());
formatter.WriteField(termToText.Lookup(term.GetRawHash()));
formatter.WriteField(dfEntry.GetFrequency());
std::stack<RowId> rowsReversed;
for (auto row : rows)
{
rowsReversed.push(row);
}
while (!rowsReversed.empty())
{
auto row = rowsReversed.top();
formatter.WriteField("r");
out << row.GetRank();
formatter.WriteField(row.GetIndex());
formatter.WriteField(densities[row.GetRank()][row.GetIndex()]);
rowsReversed.pop();
}
formatter.WriteRowEnd();
}
}
//*************************************************************************
//
// Analyze columns
//
//*************************************************************************
void RowTableAnalyzer::AnalyzeColumns(char const * outDir) const
{
auto & ingestor = m_index.GetIngestor();
auto & cache = ingestor.GetDocumentCache();
std::vector<Column> columns;
for (auto doc : cache)
{
const DocumentHandleInternal
handle(ingestor.GetHandle(doc.second));
Slice const & slice = handle.GetSlice();
const ShardId shard = slice.GetShard().GetId();
columns.emplace_back(doc.second,
shard,
doc.first.GetPostingCount());
void const * buffer = slice.GetSliceBuffer();
const DocIndex column = handle.GetIndex();
for (Rank rank = 0; rank <= c_maxRankValue; ++rank)
{
RowTableDescriptor rowTable = slice.GetRowTable(rank);
size_t bitCount = 0;
const size_t rowCount = rowTable.GetRowCount();
for (RowIndex row = 0; row < rowCount; ++row)
{
if (rowTable.GetBit(buffer, row, column) != 0)
{
++bitCount;
}
}
columns.back().SetCount(rank, bitCount);
double density =
(rowCount == 0) ? 0.0 : static_cast<double>(bitCount) / rowCount;
columns.back().SetDensity(rank, density);
}
}
auto fileSystem = Factories::CreateFileSystem();
auto outFileManager =
Factories::CreateFileManager(outDir,
outDir,
outDir,
*fileSystem);
//
// Write out raw column data.
//
{
// No need to use CsvTableFormatter for escaping because all values
// are numbers.
auto out = outFileManager->ColumnDensities().OpenForWrite();
Column::WriteHeader(*out);
for (auto column : columns)
{
column.Write(*out);
}
}
//
// Generate summary.
//
{
auto out = outFileManager->ColumnDensitySummary().OpenForWrite();
*out << "Summary" << std::endl;
for (Rank rank = 0; rank <= c_maxRankValue; ++rank)
{
Accumulator accumulator;
for (auto column : columns)
{
accumulator.Record(column.m_densities[rank]);
}
*out << "Rank " << rank << std::endl
<< " column density: " << std::endl
<< " min: " << accumulator.GetMin() << std::endl
<< " max: " << accumulator.GetMax() << std::endl
<< " mean: " << accumulator.GetMean() << std::endl
<< " var: " << accumulator.GetVariance() << std::endl
<< " count: " << accumulator.GetCount() << std::endl;
}
}
}
RowTableAnalyzer::Column::Column(DocId id, ShardId shard, size_t postings)
: m_id(id),
m_postings(postings),
m_shard(shard),
m_bits{}
{
}
void RowTableAnalyzer::Column::SetCount(Rank rank, size_t count)
{
m_bits[rank] = count;
}
void RowTableAnalyzer::Column::SetDensity(Rank rank, double density)
{
m_densities[rank] = density;
}
void RowTableAnalyzer::Column::WriteHeader(std::ostream& out)
{
out << "id,postings,shard";
for (Rank rank = 0; rank <= c_maxRankValue; ++rank)
{
out << ",rank" << rank;
}
out << std::endl;
}
void RowTableAnalyzer::Column::Write(std::ostream& out)
{
out << m_id
<< "," << m_postings
<< "," << m_shard;
for (Rank rank = 0; rank <= c_maxRankValue; ++rank)
{
// TODO: Consider writing out or eliminating m_bits.
out << "," << m_densities[rank];
}
out << std::endl;
}
}
<|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 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/diff_context.h"
#include "libmesh/diff_system.h"
namespace libMesh
{
DiffContext::DiffContext (const System& sys) :
time(sys.time),
system_time(sys.time),
elem_solution_derivative(1.),
fixed_solution_derivative(0.),
dof_indices_var(sys.n_vars()),
_deltat(NULL)
{
// Finally initialize solution/residual/jacobian data structures
unsigned int n_vars = sys.n_vars();
elem_subsolutions.reserve(n_vars);
elem_subresiduals.reserve(n_vars);
elem_subjacobians.resize(n_vars);
if (sys.use_fixed_solution)
elem_fixed_subsolutions.reserve(n_vars);
// If the user resizes sys.qoi, it will invalidate us
unsigned int n_qoi = sys.qoi.size();
elem_qoi.resize(n_qoi);
elem_qoi_derivative.resize(n_qoi);
elem_qoi_subderivatives.resize(n_qoi);
for (unsigned int q=0; q != n_qoi; ++q)
elem_qoi_subderivatives[q].reserve(n_vars);
for (unsigned int i=0; i != n_vars; ++i)
{
elem_subsolutions.push_back(new DenseSubVector<Number>(elem_solution));
elem_subresiduals.push_back(new DenseSubVector<Number>(elem_residual));
for (unsigned int q=0; q != n_qoi; ++q)
elem_qoi_subderivatives[q].push_back(new DenseSubVector<Number>(elem_qoi_derivative[q]));
elem_subjacobians[i].reserve(n_vars);
if (sys.use_fixed_solution)
elem_fixed_subsolutions.push_back
(new DenseSubVector<Number>(elem_fixed_solution));
for (unsigned int j=0; j != n_vars; ++j)
{
elem_subjacobians[i].push_back
(new DenseSubMatrix<Number>(elem_jacobian));
}
}
}
DiffContext::~DiffContext ()
{
for (unsigned int i=0; i != elem_subsolutions.size(); ++i)
{
delete elem_subsolutions[i];
delete elem_subresiduals[i];
for (unsigned int q=0; q != elem_qoi_subderivatives.size(); ++q)
delete elem_qoi_subderivatives[q][i];
if (!elem_fixed_subsolutions.empty())
delete elem_fixed_subsolutions[i];
for (unsigned int j=0; j != elem_subjacobians[i].size(); ++j)
delete elem_subjacobians[i][j];
}
}
void DiffContext::set_deltat_pointer(Real* dt)
{
// We may actually want to be able to set this pointer to NULL, so
// don't report an error for that.
_deltat = dt;
}
Real DiffContext::get_deltat_value()
{
libmesh_assert(_deltat);
return *_deltat;
}
} // namespace libMesh
<commit_msg>DiffContext should save (and have an accessor to) the System it was created for.<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 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/diff_context.h"
#include "libmesh/diff_system.h"
namespace libMesh
{
DiffContext::DiffContext (const System& sys) :
time(sys.time),
system_time(sys.time),
elem_solution_derivative(1.),
fixed_solution_derivative(0.),
dof_indices_var(sys.n_vars()),
_deltat(NULL),
_system(sys)
{
// Finally initialize solution/residual/jacobian data structures
unsigned int n_vars = sys.n_vars();
elem_subsolutions.reserve(n_vars);
elem_subresiduals.reserve(n_vars);
elem_subjacobians.resize(n_vars);
if (sys.use_fixed_solution)
elem_fixed_subsolutions.reserve(n_vars);
// If the user resizes sys.qoi, it will invalidate us
unsigned int n_qoi = sys.qoi.size();
elem_qoi.resize(n_qoi);
elem_qoi_derivative.resize(n_qoi);
elem_qoi_subderivatives.resize(n_qoi);
for (unsigned int q=0; q != n_qoi; ++q)
elem_qoi_subderivatives[q].reserve(n_vars);
for (unsigned int i=0; i != n_vars; ++i)
{
elem_subsolutions.push_back(new DenseSubVector<Number>(elem_solution));
elem_subresiduals.push_back(new DenseSubVector<Number>(elem_residual));
for (unsigned int q=0; q != n_qoi; ++q)
elem_qoi_subderivatives[q].push_back(new DenseSubVector<Number>(elem_qoi_derivative[q]));
elem_subjacobians[i].reserve(n_vars);
if (sys.use_fixed_solution)
elem_fixed_subsolutions.push_back
(new DenseSubVector<Number>(elem_fixed_solution));
for (unsigned int j=0; j != n_vars; ++j)
{
elem_subjacobians[i].push_back
(new DenseSubMatrix<Number>(elem_jacobian));
}
}
}
DiffContext::~DiffContext ()
{
for (unsigned int i=0; i != elem_subsolutions.size(); ++i)
{
delete elem_subsolutions[i];
delete elem_subresiduals[i];
for (unsigned int q=0; q != elem_qoi_subderivatives.size(); ++q)
delete elem_qoi_subderivatives[q][i];
if (!elem_fixed_subsolutions.empty())
delete elem_fixed_subsolutions[i];
for (unsigned int j=0; j != elem_subjacobians[i].size(); ++j)
delete elem_subjacobians[i][j];
}
}
void DiffContext::set_deltat_pointer(Real* dt)
{
// We may actually want to be able to set this pointer to NULL, so
// don't report an error for that.
_deltat = dt;
}
Real DiffContext::get_deltat_value()
{
libmesh_assert(_deltat);
return *_deltat;
}
} // namespace libMesh
<|endoftext|> |
<commit_before>// Copyright (C) 2015 Alexandre Janniaux
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/Posix/FileImpl.hpp>
#include <Nazara/Core/Error.hpp>
#include <cstdio>
#include <Nazara/Core/Debug.hpp>
namespace Nz
{
FileImpl::FileImpl(const File* parent) :
m_endOfFile(false),
m_endOfFileUpdated(true)
{
NazaraUnused(parent);
}
void FileImpl::Close()
{
if (m_fileDescriptor != -1)
close(m_fileDescriptor);
}
bool FileImpl::EndOfFile() const
{
if (!m_endOfFileUpdated)
{
struct stat64 fileSize;
if (fstat64(m_fileDescriptor, &fileSize) == -1)
fileSize.st_size = 0;
m_endOfFile = (GetCursorPos() >= static_cast<UInt64>(fileSize.st_size));
m_endOfFileUpdated = true;
}
return m_endOfFile;
}
void FileImpl::Flush()
{
if (fsync(m_fileDescriptor) == -1)
NazaraError("Unable to flush file: " + Error::GetLastSystemError());
}
UInt64 FileImpl::GetCursorPos() const
{
off64_t position = lseek64(m_fileDescriptor, 0, SEEK_CUR);
return static_cast<UInt64>(position);
}
bool FileImpl::Open(const String& filePath, OpenModeFlags mode)
{
int flags;
mode_t permissions = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
if ((mode & OpenMode_ReadWrite) == OpenMode_ReadWrite)
flags = O_CREAT | O_RDWR;
else if ((mode & OpenMode_ReadOnly) == OpenMode_ReadOnly)
flags = O_RDONLY;
else if ((mode & OpenMode_WriteOnly) == OpenMode_WriteOnly)
flags = O_CREAT | O_WRONLY;
else
return false;
if (mode & OpenMode_Append)
flags |= O_APPEND;
if (mode & OpenMode_MustExist)
flags &= ~O_CREAT;
if (mode & OpenMode_Truncate)
flags |= O_TRUNC;
///TODO: lock
//if ((mode & OpenMode_Lock) == 0)
// shareMode |= FILE_SHARE_WRITE;
m_fileDescriptor = open64(filePath.GetConstBuffer(), flags, permissions);
return m_fileDescriptor != -1;
}
std::size_t FileImpl::Read(void* buffer, std::size_t size)
{
ssize_t bytes;
if ((bytes = read(m_fileDescriptor, buffer, size)) != -1)
{
m_endOfFile = (static_cast<std::size_t>(bytes) != size);
m_endOfFileUpdated = true;
return static_cast<std::size_t>(bytes);
}
else
return 0;
}
bool FileImpl::SetCursorPos(CursorPosition pos, Int64 offset)
{
int moveMethod;
switch (pos)
{
case CursorPosition_AtBegin:
moveMethod = SEEK_SET;
break;
case CursorPosition_AtCurrent:
moveMethod = SEEK_CUR;
break;
case CursorPosition_AtEnd:
moveMethod = SEEK_END;
break;
default:
NazaraInternalError("Cursor position not handled (0x" + String::Number(pos, 16) + ')');
return false;
}
m_endOfFileUpdated = false;
return lseek64(m_fileDescriptor, offset, moveMethod) != -1;
}
bool FileImpl::SetSize(UInt64 size)
{
return ftruncate64(m_fileDescriptor, size) != 0;
}
std::size_t FileImpl::Write(const void* buffer, std::size_t size)
{
lockf64(m_fileDescriptor, F_LOCK, size);
ssize_t written = write(m_fileDescriptor, buffer, size);
lockf64(m_fileDescriptor, F_ULOCK, size);
m_endOfFileUpdated = false;
return written;
}
bool FileImpl::Copy(const String& sourcePath, const String& targetPath)
{
int fd1 = open64(sourcePath.GetConstBuffer(), O_RDONLY);
if (fd1 == -1)
{
NazaraError("Fail to open input file (" + sourcePath + "): " + Error::GetLastSystemError());
return false;
}
mode_t permissions;
struct stat sb;
if (fstat(fd1, &sb) == -1) // get permission from first file
{
NazaraWarning("Could not get permissions of source file");
permissions = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
}
else
{
permissions = sb.st_mode & ~S_IFMT; // S_IFMT: bit mask for the file type bit field -> ~S_IFMT: general permissions
}
int fd2 = open64(targetPath.GetConstBuffer(), O_WRONLY | O_TRUNC, permissions);
if (fd2 == -1)
{
NazaraError("Fail to open output file (" + targetPath + "): " + Error::GetLastSystemError()); // TODO: more info ?
close(fd1);
return false;
}
char buffer[512];
ssize_t bytes;
do
{
bytes = read(fd1,buffer,512);
if (bytes == -1)
{
close(fd1);
close(fd2);
NazaraError("An error occured from copy : " + Error::GetLastSystemError());
return false;
}
write(fd2,buffer,bytes);
}
while (bytes == 512);
close(fd1);
close(fd2);
return true;
}
bool FileImpl::Delete(const String& filePath)
{
bool success = unlink(filePath.GetConstBuffer()) != -1;
if (success)
return true;
else
{
NazaraError("Failed to delete file (" + filePath + "): " + Error::GetLastSystemError());
return false;
}
}
bool FileImpl::Exists(const String& filePath)
{
const char* path = filePath.GetConstBuffer();
if (access(path, F_OK) != -1)
return true;
return false;
}
time_t FileImpl::GetCreationTime(const String& filePath)
{
NazaraUnused(filePath);
NazaraWarning("Posix has no creation time information");
return 0;
}
time_t FileImpl::GetLastAccessTime(const String& filePath)
{
struct stat64 stats;
stat64(filePath.GetConstBuffer(), &stats);
return stats.st_atime;
}
time_t FileImpl::GetLastWriteTime(const String& filePath)
{
struct stat64 stats;
stat64(filePath.GetConstBuffer(), &stats);
return stats.st_mtime;
}
UInt64 FileImpl::GetSize(const String& filePath)
{
struct stat64 stats;
stat64(filePath.GetConstBuffer(), &stats);
return static_cast<UInt64>(stats.st_size);
}
bool FileImpl::Rename(const String& sourcePath, const String& targetPath)
{
bool success = std::rename(sourcePath.GetConstBuffer(), targetPath.GetConstBuffer()) != -1;
if (success)
return true;
else
{
NazaraError("Unable to rename file: " + Error::GetLastSystemError());
return false;
}
}
}
<commit_msg>Add lock file on Linux and the possibility to have two processes writing to the same one<commit_after>// Copyright (C) 2015 Alexandre Janniaux
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/Posix/FileImpl.hpp>
#include <Nazara/Core/Error.hpp>
#include <cstdio>
#include <sys/file.h>
#include <Nazara/Core/Debug.hpp>
namespace Nz
{
FileImpl::FileImpl(const File* parent) :
m_endOfFile(false),
m_endOfFileUpdated(true)
{
NazaraUnused(parent);
}
void FileImpl::Close()
{
if (m_fileDescriptor != -1)
close(m_fileDescriptor);
}
bool FileImpl::EndOfFile() const
{
if (!m_endOfFileUpdated)
{
struct stat64 fileSize;
if (fstat64(m_fileDescriptor, &fileSize) == -1)
fileSize.st_size = 0;
m_endOfFile = (GetCursorPos() >= static_cast<UInt64>(fileSize.st_size));
m_endOfFileUpdated = true;
}
return m_endOfFile;
}
void FileImpl::Flush()
{
if (fsync(m_fileDescriptor) == -1)
NazaraError("Unable to flush file: " + Error::GetLastSystemError());
}
UInt64 FileImpl::GetCursorPos() const
{
off64_t position = lseek64(m_fileDescriptor, 0, SEEK_CUR);
return static_cast<UInt64>(position);
}
bool FileImpl::Open(const String& filePath, OpenModeFlags mode)
{
int flags;
mode_t permissions = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
if ((mode & OpenMode_ReadWrite) == OpenMode_ReadWrite)
flags = O_CREAT | O_RDWR;
else if ((mode & OpenMode_ReadOnly) == OpenMode_ReadOnly)
flags = O_RDONLY;
else if ((mode & OpenMode_WriteOnly) == OpenMode_WriteOnly)
flags = O_CREAT | O_WRONLY;
else
return false;
if (mode & OpenMode_Append)
flags |= O_APPEND;
if (mode & OpenMode_MustExist)
flags &= ~O_CREAT;
if (mode & OpenMode_Truncate)
flags |= O_TRUNC;
m_fileDescriptor = open64(filePath.GetConstBuffer(), flags, permissions);
static struct flock lock;
auto initialize_flock = [](struct flock& fileLock)
{
fileLock.l_type = F_WRLCK;
fileLock.l_start = 0;
fileLock.l_whence = SEEK_SET;
fileLock.l_len = 0;
fileLock.l_pid = getpid();
};
initialize_flock(lock);
if (fcntl(m_fileDescriptor, F_GETLK, &lock) == -1)
{
Close();
NazaraError("Unable to detect presence of lock on the file");
return false;
}
if (lock.l_type != F_UNLCK)
{
Close();
NazaraError("A lock is present on the file");
return false;
}
if (mode & OpenMode_Lock)
{
initialize_flock(lock);
if (fcntl(m_fileDescriptor, F_SETLK, &lock) == -1)
{
Close();
NazaraError("Unable to place a lock on the file");
return false;
}
}
return m_fileDescriptor != -1;
}
std::size_t FileImpl::Read(void* buffer, std::size_t size)
{
ssize_t bytes;
if ((bytes = read(m_fileDescriptor, buffer, size)) != -1)
{
m_endOfFile = (static_cast<std::size_t>(bytes) != size);
m_endOfFileUpdated = true;
return static_cast<std::size_t>(bytes);
}
else
return 0;
}
bool FileImpl::SetCursorPos(CursorPosition pos, Int64 offset)
{
int moveMethod;
switch (pos)
{
case CursorPosition_AtBegin:
moveMethod = SEEK_SET;
break;
case CursorPosition_AtCurrent:
moveMethod = SEEK_CUR;
break;
case CursorPosition_AtEnd:
moveMethod = SEEK_END;
break;
default:
NazaraInternalError("Cursor position not handled (0x" + String::Number(pos, 16) + ')');
return false;
}
m_endOfFileUpdated = false;
return lseek64(m_fileDescriptor, offset, moveMethod) != -1;
}
bool FileImpl::SetSize(UInt64 size)
{
return ftruncate64(m_fileDescriptor, size) != 0;
}
std::size_t FileImpl::Write(const void* buffer, std::size_t size)
{
ssize_t written = write(m_fileDescriptor, buffer, size);
m_endOfFileUpdated = false;
return written;
}
bool FileImpl::Copy(const String& sourcePath, const String& targetPath)
{
int fd1 = open64(sourcePath.GetConstBuffer(), O_RDONLY);
if (fd1 == -1)
{
NazaraError("Fail to open input file (" + sourcePath + "): " + Error::GetLastSystemError());
return false;
}
mode_t permissions;
struct stat sb;
if (fstat(fd1, &sb) == -1) // get permission from first file
{
NazaraWarning("Could not get permissions of source file");
permissions = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
}
else
{
permissions = sb.st_mode & ~S_IFMT; // S_IFMT: bit mask for the file type bit field -> ~S_IFMT: general permissions
}
int fd2 = open64(targetPath.GetConstBuffer(), O_WRONLY | O_TRUNC, permissions);
if (fd2 == -1)
{
NazaraError("Fail to open output file (" + targetPath + "): " + Error::GetLastSystemError()); // TODO: more info ?
close(fd1);
return false;
}
char buffer[512];
ssize_t bytes;
do
{
bytes = read(fd1,buffer,512);
if (bytes == -1)
{
close(fd1);
close(fd2);
NazaraError("An error occured from copy : " + Error::GetLastSystemError());
return false;
}
write(fd2,buffer,bytes);
}
while (bytes == 512);
close(fd1);
close(fd2);
return true;
}
bool FileImpl::Delete(const String& filePath)
{
bool success = unlink(filePath.GetConstBuffer()) != -1;
if (success)
return true;
else
{
NazaraError("Failed to delete file (" + filePath + "): " + Error::GetLastSystemError());
return false;
}
}
bool FileImpl::Exists(const String& filePath)
{
const char* path = filePath.GetConstBuffer();
if (access(path, F_OK) != -1)
return true;
return false;
}
time_t FileImpl::GetCreationTime(const String& filePath)
{
NazaraUnused(filePath);
NazaraWarning("Posix has no creation time information");
return 0;
}
time_t FileImpl::GetLastAccessTime(const String& filePath)
{
struct stat64 stats;
stat64(filePath.GetConstBuffer(), &stats);
return stats.st_atime;
}
time_t FileImpl::GetLastWriteTime(const String& filePath)
{
struct stat64 stats;
stat64(filePath.GetConstBuffer(), &stats);
return stats.st_mtime;
}
UInt64 FileImpl::GetSize(const String& filePath)
{
struct stat64 stats;
stat64(filePath.GetConstBuffer(), &stats);
return static_cast<UInt64>(stats.st_size);
}
bool FileImpl::Rename(const String& sourcePath, const String& targetPath)
{
bool success = std::rename(sourcePath.GetConstBuffer(), targetPath.GetConstBuffer()) != -1;
if (success)
return true;
else
{
NazaraError("Unable to rename file: " + Error::GetLastSystemError());
return false;
}
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <vector>
#include "integrators/symplectic_integrator.hpp"
namespace principia {
namespace integrators {
class SPRKIntegrator : public SymplecticIntegrator {
public:
SPRKIntegrator();
~SPRKIntegrator() override = default;
std::vector<std::vector<double>> const& Order5Optimal() const;
void Initialize(Coefficients const& coefficients) override;
void Solve(RightHandSideComputation const compute_force,
AutonomousRightHandSideComputation const compute_velocity,
Parameters const& parameters,
Solution* solution) override;
private:
// The tableau.
int stages_;
std::vector<double> a_;
std::vector<double> b_;
std::vector<double> c_;
};
} // namespace integrators
} // namespace principia
#include "integrators/symplectic_partitioned_runge_kutta_integrator_body.hpp"
<commit_msg>After eggrobin's review.<commit_after>#pragma once
#include <vector>
#include "integrators/symplectic_integrator.hpp"
namespace principia {
namespace integrators {
class SPRKIntegrator : public SymplecticIntegrator {
public:
SPRKIntegrator();
~SPRKIntegrator() override = default;
std::vector<std::vector<double>> const& Order5Optimal() const;
void Initialize(Coefficients const& coefficients) override;
void Solve(RightHandSideComputation const compute_force,
AutonomousRightHandSideComputation const compute_velocity,
Parameters const& parameters,
Solution* solution) override;
private:
int stages_;
// The position and momentum nodes.
std::vector<double> a_;
std::vector<double> b_;
// The weights.
std::vector<double> c_;
};
} // namespace integrators
} // namespace principia
#include "integrators/symplectic_partitioned_runge_kutta_integrator_body.hpp"
<|endoftext|> |
<commit_before>/*
* jcom.receive
* External for Jamoma: receive messages from remote
* By Trond Lossius & Tim Place, Copyright � 2006
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "Jamoma.h"
/** Receive Object */
typedef struct _receive{
t_object ob; ///< REQUIRED: Our object
void *outlet; ///< Need one for each outlet
t_symbol *attr_name; ///< ATTRIBUTE: name
TTListPtr lk_nodes; ///< a pointer to a selection of nodes of the tree
TTListPtr lk_attr_observer; ///< a pointer to each created attribute observers
TTListPtr lk_life_observer; ///< a pointer to each created life cycle observers
t_receive_obex_callback callback; ///< Function pointer to call if we instantiated inside of another extern
void *baton; ///< Baton to hand back to the callee of the callback when it is called
} t_receive;
// Prototypes
void *receive_new(t_symbol *s, long argc, t_atom *argv);
void receive_free(t_receive *x);
void receive_assist(t_receive *x, void *b, long msg, long arg, char *dst);
t_max_err receive_setname(t_receive *x, void *attr, long argc, t_atom *argv);
void receive_setcallback(t_receive *x, void *callback, void *arg);
void receive_dispatch(t_receive *x, t_symbol *msg, long argc, t_atom *argv);
void receive_bind(t_receive *x);
void receive_remove(t_receive *x);
void receive_node_callback(t_receive *x, t_symbol *mess, long argc, t_atom *argv);
void receive_node_attribute_callback(t_receive *x, t_symbol *mess, long argc, t_atom *argv);
// experimental method to test the getter mecanism on a node
void receive_get(t_receive *x);
// Globals
static t_class *s_receive_class; // Required: Global pointer the jcom.receive class
//t_object *g_receivemaster_object = NULL; // An instance of the jcom.receivemaster class
/************************************************************************************/
void receive_initclass()
{
long attrflags = 0;
t_class *c;
t_object *attr;
// Define our class
c = class_new( "jcom.receive",
(method)receive_new,
(method)receive_free,
sizeof(t_receive),
(method)0L,
A_GIMME,
0);
// Make methods accessible for our class:
class_addmethod(c, (method)receive_dispatch, "dispatch", A_CANT, 0);
class_addmethod(c, (method)receive_node_callback, "receive_node_attribute_callback", A_CANT, 0);
class_addmethod(c, (method)receive_node_attribute_callback, "receive_node_attribute_callback", A_CANT, 0);
class_addmethod(c, (method)receive_setcallback, "setcallback", A_CANT, 0);
class_addmethod(c, (method)receive_assist, "assist", A_CANT, 0);
class_addmethod(c, (method)object_obex_dumpout, "dumpout", A_CANT, 0);
// experimental method to test the getter mecanism on a node
class_addmethod(c, (method)receive_get, "bang", 0);
// ATTRIBUTE: name
attr = attr_offset_new("name", _sym_symbol, attrflags,
(method)0, (method)receive_setname, calcoffset(t_receive, attr_name));
class_addattr(c, attr);
// Finalize our class
class_register(CLASS_BOX, c);
s_receive_class = c;
}
/************************************************************************************/
// Object Life
// Create
void *receive_new(t_symbol *s, long argc, t_atom *argv)
{
long attrstart = attr_args_offset(argc, argv); // support normal arguments
t_receive *x = (t_receive *)object_alloc(s_receive_class);
if(x){
object_obex_store((void *)x, _sym_dumpout, (object *)outlet_new(x, NULL));
x->outlet = outlet_new(x, NULL);
//if(!g_receivemaster_object)
// g_receivemaster_object = (t_object *)object_new_typed(CLASS_NOBOX, SymbolGen("jcom.receivemaster"), 0, NULL);
x->callback = NULL;
x->attr_name = NULL;
x->lk_nodes = new TTList();
x->lk_attr_observer = new TTList();
x->lk_life_observer = new TTList();
// attr_args_process(x, argc, argv); // handle attribute args
// If no name was specified as an attribute
if(x->attr_name == NULL){
if(attrstart > 0)
x->attr_name = atom_getsym(argv);
else
x->attr_name = SymbolGen("jcom.receive no arg specified");
receive_bind(x);
}
}
return x;
}
// Destroy
void receive_free(t_receive *x)
{
;
}
/************************************************************************************/
// Methods bound to input/inlets
// Method for Assistance Messages
void receive_assist(t_receive *x, void *b, long msg, long arg, char *dst)
{
if(msg==1) // Inlets
strcpy(dst, "(signal) input to the module");
else if(msg==2){ // Outlets
if(arg == 0)
strcpy(dst, "output from remote");
else
strcpy(dst, "dumpout");
}
}
// ATTRIBUTE: name
t_max_err receive_setname(t_receive *x, void *attr, long argc, t_atom *argv)
{
t_symbol *arg = atom_getsym(argv);
if(x->attr_name != arg){
receive_remove(x);
x->attr_name = arg;
x->lk_nodes = new TTList();
x->lk_attr_observer = new TTList();
x->lk_life_observer = new TTList();
receive_bind(x);
}
return MAX_ERR_NONE;
}
void receive_bind(t_receive *x)
{
TTObjectPtr newLifeCallback;
TTObjectPtr newAttrCallback;
TTList lk_selection;
TTNodePtr p_node;
TTErr err = kTTErrGeneric;
//if(!NOGOOD(g_receivemaster_object))
// object_method(g_receivemaster_object, jps_add, x->attr_name, x);
// if there isn't selection
if(x->lk_nodes->isEmpty()){
// look for the node(s) into the directory
if(x->attr_name->s_name[0] == C_SEPARATOR){
if(jamoma_directory){
err = jamoma_directory->Lookup(TT(x->attr_name->s_name), lk_selection, &p_node);
x->lk_nodes->merge(lk_selection);
}
if(err != kTTErrNone)
object_error((t_object*)x,"jcom.receive : %s doesn't exist", x->attr_name->s_name);
}
}
if(!x->lk_nodes->isEmpty()){
// for each node of the selection
for(x->lk_nodes->begin(); x->lk_nodes->end(); x->lk_nodes->next()){
// get a node from the selection
x->lk_nodes->current().get(0,(TTPtr*)&p_node);
// prepare the callback mecanism to
// be notified about changing value attribute
// TODO : observe other attribute (default value)
jamoma_node_attribute_observer_add(p_node, jps_value, (t_object*)x, gensym("receive_node_attribute_callback"), &newAttrCallback);
// prepare the callback mecanism to
// be notified about the destruction of the node
jamoma_node_observer_add(p_node, (t_object*)x, gensym("receive_node_callback"), &newLifeCallback);
x->lk_attr_observer->append(newAttrCallback);
x->lk_life_observer->append(newLifeCallback);
}
}
}
// experimental method to test the getter mecanism on a node
void receive_get(t_receive *x)
{
TTNodePtr p_node;
long argc;
t_atom *argv;
if(!x->lk_nodes->isEmpty()){
// for each node of the selection
for(x->lk_nodes->begin(); x->lk_nodes->end(); x->lk_nodes->next()){
// get a node from the selection
x->lk_nodes->current().get(0,(TTPtr*)&p_node);
// get the value of the node
jamoma_node_attribute_get(p_node, jps_value, &argc, &argv);
// get the OSCAddress of the node (in case we use * inside the x->attrname)
// and output data
outlet_anything(x->outlet, jamoma_node_OSC_address(p_node), argc, argv);
// free memory allocated inside the get property method
free(argv);
}
}
}
// This method his called by each observer attached to a node.
// Read the TTNode file to get info about life cycle observers mecanism
void receive_node_callback(t_receive *x, t_symbol *mess, long argc, t_atom *argv)
{
long flag = atom_getlong(&argv[0]);
post("node destruction : %s %d", mess->s_name, flag);
/*TTValue c(observingObject);
TTValue v;
TTErr err;
err = x->lk_nodes->findEquals(c, v);
*/
}
// This method his called by each observer attached to an attibute of the node.
// Read the TTNode file to get info about attribute observers mecanism
void receive_node_attribute_callback(t_receive *x, t_symbol *mess, long argc, t_atom *argv)
{
//object_post((t_object *)x, "jcom.receive : %s", mess->s_name);
if(!x->callback){
//object_post((t_object *)x, "external : %d", x);
outlet_anything(x->outlet, (t_symbol *)mess, argc, argv);
}
else
;//object_post((t_object *)x, "internal : %d", x);
}
void receive_remove(t_receive *x)
{
TTObjectPtr oldAttrCallback;
TTObjectPtr oldLifeCallback;
TTNodePtr p_node;
// if there is a selection, remove Observers
if(x->lk_nodes){
x->lk_attr_observer->begin();
x->lk_life_observer->begin();
for(x->lk_nodes->begin(); x->lk_nodes->end(); x->lk_nodes->next()){
// get a node of the selection
x->lk_nodes->current().get(0,(TTPtr*)&p_node);
// get the observer relative to this node
x->lk_attr_observer->current().get(0,(TTPtr*)&oldAttrCallback);
x->lk_life_observer->current().get(0,(TTPtr*)&oldLifeCallback);
// remove all the observers
// TODO : remove the other attribute observers
jamoma_node_attribute_observer_remove(p_node, jps_value, oldAttrCallback);
jamoma_node_observer_remove(p_node, oldLifeCallback);
x->lk_attr_observer->next();
x->lk_life_observer->next();
}
}
delete x->lk_nodes;
delete x->lk_attr_observer;
delete x->lk_life_observer;
//object_method(g_receivemaster_object, jps_remove, x->attr_name, x);
}
// This method is called by jcom.receivemaster
// In reponse, we figure out if we should send the data to our outlet
void receive_dispatch(t_receive *x, t_symbol *msg, long argc, t_atom *argv)
{
if(x->callback)
x->callback(x->baton, msg, argc, argv); // call the registered callback on the object that we're instantiated inside of
else
outlet_anything(x->outlet, msg, argc, argv);
}
// When we are inside of another external, we need a way to transmit messages
// to it. This function sets up another callback, which can call a function
// in that external to transmit the message.
void receive_setcallback(t_receive *x, void *callback, void *arg)
{
x->callback = (t_receive_obex_callback)callback;
x->baton = arg;
}<commit_msg>{ Adding : jcom.receive can observe the global node directory for creation or destruction notification}<commit_after>/*
* jcom.receive
* External for Jamoma: receive messages from remote
* By Trond Lossius & Tim Place, Copyright � 2006
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "Jamoma.h"
/** Receive Object */
typedef struct _receive{
t_object ob; ///< REQUIRED: Our object
void *address_out; ///< outlet used to output address of received data
void *data_out; ///< outlet used to output received data
t_symbol *attr_name; ///< ATTRIBUTE: the name of the jcom.receive (/address:attribute)
t_symbol *_address; ///< the address to bind
t_symbol *_attribute; ///< the attribute to bind (default : value)
bool enable; ///< if false, received data won't be output without unregistered attribute observers (default true).
TTListPtr lk_nodes; ///< a pointer to a selection of nodes of the tree
TTListPtr lk_attr_observer; ///< a pointer to each created attribute observers
TTObjectPtr life_observer; ///< a pointer to a life cycle observer
} t_receive;
// Prototypes
void *receive_new(t_symbol *s, long argc, t_atom *argv);
void receive_free(t_receive *x);
void receive_assist(t_receive *x, void *b, long msg, long arg, char *dst);
t_max_err receive_setname(t_receive *x, void *attr, long argc, t_atom *argv);
void receive_bind(t_receive *x);
void receive_remove(t_receive *x);
void receive_directory_callback(t_receive *x, t_symbol *mess, long argc, t_atom *argv);
void receive_node_attribute_callback(t_receive *x, t_symbol *mess, long argc, t_atom *argv);
// ask the value to the node
void receive_get(t_receive *x);
// enable/disable outputs without unregistered attributes observers
void receive_enable(t_receive *x, long e);
// Globals
static t_class *s_receive_class; // Required: Global pointer the jcom.receive class
/************************************************************************************/
void receive_initclass()
{
long attrflags = 0;
t_class *c;
t_object *attr;
// Define our class
c = class_new( "jcom.receive",
(method)receive_new,
(method)receive_free,
sizeof(t_receive),
(method)0L,
A_GIMME,
0);
// Make methods accessible for our class:
class_addmethod(c, (method)receive_directory_callback, "receive_directory_callback", A_CANT, 0);
class_addmethod(c, (method)receive_node_attribute_callback, "receive_node_attribute_callback", A_CANT, 0);
class_addmethod(c, (method)receive_assist, "assist", A_CANT, 0);
class_addmethod(c, (method)object_obex_dumpout, "dumpout", A_CANT, 0);
// ask the value to the node
class_addmethod(c, (method)receive_get, "bang", 0);
// enable/disable outputs without unregistered attributes observers
class_addmethod(c, (method)receive_enable, "int", A_LONG, 0);
// ATTRIBUTE: name
attr = attr_offset_new("name", _sym_symbol, attrflags,
(method)0, (method)receive_setname, calcoffset(t_receive, attr_name));
class_addattr(c, attr);
// Finalize our class
class_register(CLASS_BOX, c);
s_receive_class = c;
}
/************************************************************************************/
// Object Life
// Create
void *receive_new(t_symbol *s, long argc, t_atom *argv)
{
long attrstart = attr_args_offset(argc, argv); // support normal arguments
t_receive *x = (t_receive *)object_alloc(s_receive_class);
if(x){
x->address_out = outlet_new(x,NULL); // anything outlet
x->data_out = outlet_new(x, NULL); // anything outlet
x->attr_name = NULL;
x->_address = NULL;
x->_attribute = NULL;
x->enable = true;
x->lk_nodes = NULL;
x->lk_attr_observer = NULL;
//attr_args_process(x, argc, argv); // handle attribute args
// If no name was specified as an attribute
if(x->attr_name == NULL){
if(attrstart > 0)
x->attr_name = atom_getsym(argv);
else
x->attr_name = SymbolGen("jcom.receive no arg specified");
receive_bind(x);
}
}
return x;
}
// Destroy
void receive_free(t_receive *x)
{
;
}
/************************************************************************************/
// Methods bound to input/inlets
// Method for Assistance Messages
void receive_assist(t_receive *x, void *b, long msg, long arg, char *dst)
{
if(msg==1) // Inlets
strcpy(dst, "(signal) input to the module");
else if(msg==2){ // Outlets
if(arg == 0)
strcpy(dst, "output from remote");
else
strcpy(dst, "dumpout");
}
}
// ATTRIBUTE: name
t_max_err receive_setname(t_receive *x, void *attr, long argc, t_atom *argv)
{
t_symbol *arg = atom_getsym(argv);
if(x->attr_name != arg){
receive_remove(x);
x->attr_name = arg;
receive_bind(x);
}
return MAX_ERR_NONE;
}
void receive_bind(t_receive *x)
{
TTSymbolPtr oscAddress_parent, oscAddress_name, oscAddress_instance, oscAddress_attribute, oscAddress_noAttribute;
TTObjectPtr newAttrCallback;
TTList lk_selection;
TTNodePtr p_node;
TTErr err = kTTErrGeneric;
x->lk_nodes = new TTList();
x->lk_attr_observer = new TTList();
if(x->attr_name->s_name[0] == C_SEPARATOR){
if(jamoma_directory){
// 0. split the name in address part and attribute
splitOSCAddress(TT(x->attr_name->s_name), &oscAddress_parent, &oscAddress_name, &oscAddress_instance, &oscAddress_attribute);
mergeOSCAddress(&oscAddress_noAttribute, oscAddress_parent, oscAddress_name, oscAddress_instance, NO_ATTRIBUTE);
x->_address = SymbolGen((char*)oscAddress_noAttribute->getCString());
if(oscAddress_attribute != NO_ATTRIBUTE)
x->_attribute = SymbolGen((char*)oscAddress_attribute->getCString());
else
x->_attribute = jps_value;
// observe for node creation or destruction
if((x->_attribute == gensym("created")) || (x->_attribute == gensym("destroyed")))
{
jamoma_directory_observer_add(x->_address, (t_object*)x, gensym("receive_directory_callback"), &x->life_observer);
}
// observe for node attribute changes
else
{
// 1. look for node(s) into the directory
err = jamoma_directory->Lookup(TT(x->_address->s_name), lk_selection, &p_node);
// 2. start attribute observation on each existing node of the selection
if(!err){
x->lk_nodes->merge(lk_selection);
for(x->lk_nodes->begin(); x->lk_nodes->end(); x->lk_nodes->next())
{
// get a node from the selection
x->lk_nodes->current().get(0,(TTPtr*)&p_node);
// prepare the callback mecanism to
// be notified about changing value attribute
jamoma_node_attribute_observer_add(p_node, x->_attribute, (t_object*)x, gensym("receive_node_attribute_callback"), &newAttrCallback);
x->lk_attr_observer->append(new TTValue((TTPtr)newAttrCallback));
}
}
// 3. observe any creation or destruction below the attr_name address
jamoma_directory_observer_add(x->_address, (t_object*)x, gensym("receive_directory_callback"), &x->life_observer);
}
}
}
}
// ask the value to the node
void receive_get(t_receive *x)
{
TTNodePtr p_node;
TTString fullAddress;
long argc;
t_atom *argv;
if(!x->lk_nodes->isEmpty()){
// for each node of the selection
for(x->lk_nodes->begin(); x->lk_nodes->end(); x->lk_nodes->next()){
// get a node from the selection
x->lk_nodes->current().get(0,(TTPtr*)&p_node);
// get the value of the node
jamoma_node_attribute_get(p_node, x->_attribute, &argc, &argv);
// output the OSCAddress of the node (in case we use * inside the x->attrname)
fullAddress = jamoma_node_OSC_address(p_node)->s_name;
if(x->_attribute != jps_value){
fullAddress += C_PROPERTY;
fullAddress += x->_attribute->s_name;
}
outlet_anything(x->address_out, gensym((char*)fullAddress.data()), 0, NULL);
// then output data
outlet_anything(x->data_out, _sym_nothing, argc, argv);
// free memory allocated inside the get property method
sysmem_freeptr(argv);
}
}
}
// enable/disable outputs without unregistered attributes observers
void receive_enable(t_receive *x, long e)
{
x->enable = e > 0;
}
// This method his called the jcom.receive observer attached to the directory.
// Read the TTNodeDirectory file to get info about life cycle observers mecanism
void receive_directory_callback(t_receive *x, t_symbol *oscAddress, long argc, t_atom *argv)
{
TTObjectPtr newAttrCallback;
TTList lk_selection;
TTNodePtr p_node;
TTErr err = kTTErrGeneric;
long flag = atom_getlong(&argv[0]);
if(flag == kAddressCreated){
//post("jcom.receive %s observe a node creation at %s", x->attr_name->s_name, oscAddress->s_name);
// check the oscAddress into the directory to be sure that this node exist
if(oscAddress->s_name[0] == C_SEPARATOR)
if(jamoma_directory)
err = jamoma_directory->getTTNodeForOSC(TT(oscAddress->s_name), &p_node);
if(!err){
if(x->_attribute == gensym("created"))
{
// output the OSCAddress of the new node
outlet_anything(x->address_out, oscAddress, 0, NULL);
}
else
{
// add the node to the selection
x->lk_nodes->append(new TTValue((TTPtr)p_node));
// start attribute observation on the node
jamoma_node_attribute_observer_add(p_node, x->_attribute, (t_object*)x, gensym("receive_node_attribute_callback"), &newAttrCallback);
x->lk_attr_observer->append(new TTValue((TTPtr)newAttrCallback));
}
}
}
else{
//post("jcom.receive %s observe a node destruction at %s", x->attr_name->s_name, oscAddress->s_name);
if(x->_attribute == gensym("destroyed"))
{
// output the OSCAddress of the old node
outlet_anything(x->address_out, oscAddress, 0, NULL);
}
else
{
// remove the node from the selection
x->lk_nodes->remove(p_node);
}
}
}
// This method his called by each observer attached to an attribute of the node.
// Read the TTNode file to get info about attribute observers mecanism
void receive_node_attribute_callback(t_receive *x, t_symbol *mess, long argc, t_atom *argv)
{
if(x->enable){
// output the OSCAddress of the node (in case we use * inside the x->attrname)
outlet_anything(x->address_out, (t_symbol *)mess, 0, NULL);
// then output data
outlet_anything(x->data_out, _sym_nothing, argc, argv);
}
}
void receive_remove(t_receive *x)
{
TTObjectPtr oldAttrCallback;
TTNodePtr p_node;
// if there is a selection, remove Observers
if(x->lk_nodes){
x->lk_attr_observer->begin();
for(x->lk_nodes->begin(); x->lk_nodes->end(); x->lk_nodes->next()){
// get a node of the selection
x->lk_nodes->current().get(0,(TTPtr*)&p_node);
// get the observer relative to this node
x->lk_attr_observer->current().get(0,(TTPtr*)&oldAttrCallback);
// remove all the observers
jamoma_node_attribute_observer_remove(p_node, x->_attribute, oldAttrCallback);
x->lk_attr_observer->next();
}
}
delete x->lk_nodes;
delete x->lk_attr_observer;
jamoma_directory_observer_remove(x->attr_name, x->life_observer);
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015 SeNDA
*
* 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.
*
*/
/**
* FILE Bundle.cpp
* AUTHOR Blackcatn13
* DATE Jun 15, 2015
* VERSION 1
* This file contains the Bundle class implementation.
*/
#include "Bundle/Bundle.h"
#include <string>
#include <vector>
#include <utility>
#include <sstream>
#include "Bundle/PrimaryBlock.h"
#include "Bundle/CanonicalBlock.h"
#include "Bundle/MetadataExtensionBlock.h"
#include "Bundle/Block.h"
#include "Bundle/PayloadBlock.h"
#include "Utils/TimestampManager.h"
#include "Utils/SDNV.h"
#include "Utils/Logger.h"
Bundle::Bundle(const std::string &rawData)
: m_raw(rawData),
m_primaryBlock(nullptr),
m_payloadBlock(nullptr) {
/**
* A bundle is formed by a PrimaryBlock, and other blocks.
* In this other blocks one of it must be a PayloadBlock.
*/
LOG(35) << "New Bundle from raw Data";
// First generate a PrimaryBlock with the data.
LOG(35) << "Generating Primary Block";
try {
m_primaryBlock = std::shared_ptr<PrimaryBlock>(new PrimaryBlock(rawData));
m_blocks.push_back(m_primaryBlock);
// Skip the PrimaryBlock
std::string data = rawData.substr(m_primaryBlock->getLength());
// We now can start to generate the known blocks.
std::shared_ptr<Block> b;
while (data.size() != 0) {
switch (static_cast<BlockTypes>(data[0])) {
case BlockTypes::PAYLOAD_BLOCK: {
// Check if another payload block is present
if (m_payloadBlock == nullptr) {
LOG(35) << "Generating Payload Block";
b = std::shared_ptr<PayloadBlock>(new PayloadBlock(data, true));
m_payloadBlock = std::static_pointer_cast<PayloadBlock>(b);
} else {
throw BundleCreationException(
"[Bundle] More than one payload found");
}
break;
}
case BlockTypes::METADATA_EXTENSION_BLOCK: {
// This is an abstraction of the metadata block, so we need to create
// a derived block of it.
LOG(35) << "Generating Metadata Extension Block";
b = std::shared_ptr<MetadataExtensionBlock>(
new MetadataExtensionBlock(data));
break;
}
default: {
LOG(35) << "Generating Canonical Block";
b = std::shared_ptr<CanonicalBlock>(new CanonicalBlock(data));
break;
}
}
m_blocks.push_back(b);
size_t blockSize = b->getLength();
if (blockSize <= 0)
throw BundleCreationException("[Bundle] Bad raw format");
data = data.substr(blockSize);
}
std::vector<std::shared_ptr<Block>>::reverse_iterator finalBlock = m_blocks
.rbegin();
if (!std::static_pointer_cast<CanonicalBlock>(*finalBlock)->checkProcFlag(
BlockControlFlags::LAST_BLOCK)) {
throw BundleCreationException("[Bundle] Last block not marked as such");
}
} catch (const BlockConstructionException &e) {
throw BundleCreationException(e.what());
} catch (const std::exception &e) {
throw BundleCreationException("[Bundle] Bad raw format");
}
}
Bundle::Bundle(std::string origin, std::string destination, std::string payload)
: m_raw() {
LOG(34) << "Generating new bundle with parameters [Source: " << origin
<< "][Destination: " << destination << "][Payload: " << payload
<< "]";
TimestampManager *tm = TimestampManager::getInstance();
std::pair<uint64_t, uint64_t> timestampValue = tm->getTimestamp();
m_primaryBlock = std::shared_ptr<PrimaryBlock>(
new PrimaryBlock(origin, destination, timestampValue.first,
timestampValue.second));
m_payloadBlock = std::shared_ptr<PayloadBlock>(new PayloadBlock(payload));
m_blocks.push_back(m_primaryBlock);
m_blocks.push_back(m_payloadBlock);
}
Bundle::~Bundle() {
LOG(36) << "Deleting Bundle";
}
std::string Bundle::getRaw() {
return m_raw;
}
std::string Bundle::toRaw() {
LOG(36) << "Generating bundle in raw format";
std::string raw = m_raw;
if (raw == "") {
std::stringstream ss;
LOG(36) << "Getting the primary block in raw";
std::vector<std::shared_ptr<Block>>::reverse_iterator finalBlock = m_blocks
.rbegin();
std::static_pointer_cast<CanonicalBlock>(*finalBlock)->setProcFlag(
BlockControlFlags::LAST_BLOCK);
for (std::vector<std::shared_ptr<Block>>::iterator it = m_blocks.begin();
it != m_blocks.end(); ++it) {
LOG(36) << "Getting the next block in raw";
ss << (*it)->toRaw();
}
raw = ss.str();
}
return raw;
}
std::shared_ptr<PrimaryBlock> Bundle::getPrimaryBlock() {
return m_primaryBlock;
}
std::shared_ptr<PayloadBlock> Bundle::getPayloadBlock() {
return m_payloadBlock;
}
std::vector<std::shared_ptr<Block>> Bundle::getBlocks() {
return m_blocks;
}
void Bundle::addBlock(std::shared_ptr<CanonicalBlock> newBlock) {
// Check if the block type is a PayloadBlock
// only one can be present into a bundle.
LOG(37) << "Adding new Block to the bundle";
if (newBlock->getBlockType()
!= static_cast<uint8_t>(BlockTypes::PAYLOAD_BLOCK)) {
m_blocks.push_back(newBlock);
} else {
LOG(3) << "Some one is trying to add another Payload block";
throw BundleException("[Bundle] a paylod block is present");
}
}
std::string Bundle::getId() {
return m_primaryBlock->getSource() + m_primaryBlock->getCreationTimestamp()
+ m_primaryBlock->getCreationTimestampSeqNumber();
}
<commit_msg>Fixes Bundle getId implementation.<commit_after>/*
* Copyright (c) 2015 SeNDA
*
* 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.
*
*/
/**
* FILE Bundle.cpp
* AUTHOR Blackcatn13
* DATE Jun 15, 2015
* VERSION 1
* This file contains the Bundle class implementation.
*/
#include "Bundle/Bundle.h"
#include <string>
#include <vector>
#include <utility>
#include <sstream>
#include "Bundle/PrimaryBlock.h"
#include "Bundle/CanonicalBlock.h"
#include "Bundle/MetadataExtensionBlock.h"
#include "Bundle/Block.h"
#include "Bundle/PayloadBlock.h"
#include "Utils/TimestampManager.h"
#include "Utils/SDNV.h"
#include "Utils/Logger.h"
Bundle::Bundle(const std::string &rawData)
: m_raw(rawData),
m_primaryBlock(nullptr),
m_payloadBlock(nullptr) {
/**
* A bundle is formed by a PrimaryBlock, and other blocks.
* In this other blocks one of it must be a PayloadBlock.
*/
LOG(35) << "New Bundle from raw Data";
// First generate a PrimaryBlock with the data.
LOG(35) << "Generating Primary Block";
try {
m_primaryBlock = std::shared_ptr<PrimaryBlock>(new PrimaryBlock(rawData));
m_blocks.push_back(m_primaryBlock);
// Skip the PrimaryBlock
std::string data = rawData.substr(m_primaryBlock->getLength());
// We now can start to generate the known blocks.
std::shared_ptr<Block> b;
while (data.size() != 0) {
switch (static_cast<BlockTypes>(data[0])) {
case BlockTypes::PAYLOAD_BLOCK: {
// Check if another payload block is present
if (m_payloadBlock == nullptr) {
LOG(35) << "Generating Payload Block";
b = std::shared_ptr<PayloadBlock>(new PayloadBlock(data, true));
m_payloadBlock = std::static_pointer_cast<PayloadBlock>(b);
} else {
throw BundleCreationException(
"[Bundle] More than one payload found");
}
break;
}
case BlockTypes::METADATA_EXTENSION_BLOCK: {
// This is an abstraction of the metadata block, so we need to create
// a derived block of it.
LOG(35) << "Generating Metadata Extension Block";
b = std::shared_ptr<MetadataExtensionBlock>(
new MetadataExtensionBlock(data));
break;
}
default: {
LOG(35) << "Generating Canonical Block";
b = std::shared_ptr<CanonicalBlock>(new CanonicalBlock(data));
break;
}
}
m_blocks.push_back(b);
size_t blockSize = b->getLength();
if (blockSize <= 0)
throw BundleCreationException("[Bundle] Bad raw format");
data = data.substr(blockSize);
}
std::vector<std::shared_ptr<Block>>::reverse_iterator finalBlock = m_blocks
.rbegin();
if (!std::static_pointer_cast<CanonicalBlock>(*finalBlock)->checkProcFlag(
BlockControlFlags::LAST_BLOCK)) {
throw BundleCreationException("[Bundle] Last block not marked as such");
}
} catch (const BlockConstructionException &e) {
throw BundleCreationException(e.what());
} catch (const std::exception &e) {
throw BundleCreationException("[Bundle] Bad raw format");
}
}
Bundle::Bundle(std::string origin, std::string destination, std::string payload)
: m_raw() {
LOG(34) << "Generating new bundle with parameters [Source: " << origin
<< "][Destination: " << destination << "][Payload: " << payload
<< "]";
TimestampManager *tm = TimestampManager::getInstance();
std::pair<uint64_t, uint64_t> timestampValue = tm->getTimestamp();
m_primaryBlock = std::shared_ptr<PrimaryBlock>(
new PrimaryBlock(origin, destination, timestampValue.first,
timestampValue.second));
m_payloadBlock = std::shared_ptr<PayloadBlock>(new PayloadBlock(payload));
m_blocks.push_back(m_primaryBlock);
m_blocks.push_back(m_payloadBlock);
}
Bundle::~Bundle() {
LOG(36) << "Deleting Bundle";
}
std::string Bundle::getRaw() {
return m_raw;
}
std::string Bundle::toRaw() {
LOG(36) << "Generating bundle in raw format";
std::string raw = m_raw;
if (raw == "") {
std::stringstream ss;
LOG(36) << "Getting the primary block in raw";
std::vector<std::shared_ptr<Block>>::reverse_iterator finalBlock = m_blocks
.rbegin();
std::static_pointer_cast<CanonicalBlock>(*finalBlock)->setProcFlag(
BlockControlFlags::LAST_BLOCK);
for (std::vector<std::shared_ptr<Block>>::iterator it = m_blocks.begin();
it != m_blocks.end(); ++it) {
LOG(36) << "Getting the next block in raw";
ss << (*it)->toRaw();
}
raw = ss.str();
}
return raw;
}
std::shared_ptr<PrimaryBlock> Bundle::getPrimaryBlock() {
return m_primaryBlock;
}
std::shared_ptr<PayloadBlock> Bundle::getPayloadBlock() {
return m_payloadBlock;
}
std::vector<std::shared_ptr<Block>> Bundle::getBlocks() {
return m_blocks;
}
void Bundle::addBlock(std::shared_ptr<CanonicalBlock> newBlock) {
// Check if the block type is a PayloadBlock
// only one can be present into a bundle.
LOG(37) << "Adding new Block to the bundle";
if (newBlock->getBlockType()
!= static_cast<uint8_t>(BlockTypes::PAYLOAD_BLOCK)) {
m_blocks.push_back(newBlock);
} else {
LOG(3) << "Some one is trying to add another Payload block";
throw BundleException("[Bundle] a paylod block is present");
}
}
std::string Bundle::getId() {
std::stringstream ss;
ss << m_primaryBlock->getSource() << m_primaryBlock->getCreationTimestamp()
<< m_primaryBlock->getCreationTimestampSeqNumber();
return ss.str();
}
<|endoftext|> |
<commit_before>// Time: O(n)
// Space: O(n)
class Solution {
public:
/**
* @param expression: a vector of strings;
* @return: an integer
*/
int evaluateExpression(vector<string> &expression) {
if (expression.empty()) {
return 0;
}
vector<string> postfix;
infixToPostfix(expression, postfix);
return evalPostfixExpression(postfix);
}
// Convert Infix to Postfix Expression.
void infixToPostfix(vector<string>& infix, vector<string>& postfix) {
stack<string> s;
for (auto tok : infix) {
if (atoi(tok.c_str())) {
postfix.push_back(tok);
}
else if (tok == "(") {
s.push(tok);
}
else if (tok == ")") {
while (!s.empty()) {
tok = s.top();
s.pop();
if (tok == "(")
break;
postfix.push_back(tok);
}
} else {
while(!s.empty() && precedence(tok) <= precedence(s.top())) {
postfix.push_back(s.top());
s.pop();
}
s.push(tok);
}
}
while (!s.empty()) {
postfix.push_back(s.top());
s.pop();
}
}
int precedence(string x) {
if(x == "(") {
return 0;
}
else if(x == "+" || x == "-") {
return 1;
}
else if(x == "*" || x== "/") {
return 2;
}
return 3;
}
// Evaluate Postfix Expression.
int evalPostfixExpression(vector<string> &postfix) {
if (postfix.empty()) {
return 0;
}
stack<string> s;
for(auto& tok : postfix) {
if(!is_operator(tok)) {
s.push(tok);
}
else {
int y = stoi(s.top());
s.pop();
int x = stoi(s.top());
s.pop();
if(tok[0] == '+') {
x += y;
}
else if (tok[0] == '-') {
x -= y;
}
else if (tok[0] == '*') {
x *= y;
}
else {
x /= y;
}
s.push(to_string(x));
}
}
return stoi(s.top());
}
bool is_operator(const string &op) {
return op.length() == 1 && string("+-*/").find(op) != string::npos;
}
};<commit_msg>update<commit_after>// Time: O(n)
// Space: O(n)
class Solution {
public:
/**
* @param expression: a vector of strings;
* @return: an integer
*/
int evaluateExpression(vector<string> &expression) {
if (expression.empty()) {
return 0;
}
vector<string> postfix;
infixToPostfix(expression, postfix);
return evaluatePostfixExpression(postfix);
}
// Convert Infix to Postfix Expression.
void infixToPostfix(vector<string>& infix, vector<string>& postfix) {
stack<string> s;
for (auto tok : infix) {
if (atoi(tok.c_str())) {
postfix.push_back(tok);
}
else if (tok == "(") {
s.push(tok);
}
else if (tok == ")") {
while (!s.empty()) {
tok = s.top();
s.pop();
if (tok == "(")
break;
postfix.push_back(tok);
}
} else {
while(!s.empty() && precedence(tok) <= precedence(s.top())) {
postfix.push_back(s.top());
s.pop();
}
s.push(tok);
}
}
while (!s.empty()) {
postfix.push_back(s.top());
s.pop();
}
}
int precedence(string x) {
if(x == "(") {
return 0;
}
else if(x == "+" || x == "-") {
return 1;
}
else if(x == "*" || x== "/") {
return 2;
}
return 3;
}
// Evaluate Postfix Expression.
int evaluatePostfixExpression(vector<string> &postfix) {
if (postfix.empty()) {
return 0;
}
stack<string> s;
for(auto& tok : postfix) {
if(!is_operator(tok)) {
s.push(tok);
}
else {
int y = stoi(s.top());
s.pop();
int x = stoi(s.top());
s.pop();
if(tok[0] == '+') {
x += y;
}
else if (tok[0] == '-') {
x -= y;
}
else if (tok[0] == '*') {
x *= y;
}
else {
x /= y;
}
s.push(to_string(x));
}
}
return stoi(s.top());
}
bool is_operator(const string &op) {
return op.length() == 1 && string("+-*/").find(op) != string::npos;
}
};<|endoftext|> |
<commit_before>// Time: O(n)
// Space: O(n)
class Solution {
public:
/**
* @param expression: a vector of strings;
* @return: an integer
*/
int evaluateExpression(vector<string> &expression) {
if (expression.empty()) {
return 0;
}
vector<string> postfix;
infixToPostfix(expression, postfix);
return evaluatePostfixExpression(postfix);
}
// Convert Infix to Postfix Expression.
void infixToPostfix(vector<string>& infix, vector<string>& postfix) {
stack<string> s;
for (auto tok : infix) {
if (atoi(tok.c_str())) {
postfix.push_back(tok);
}
else if (tok == "(") {
s.push(tok);
}
else if (tok == ")") {
while (!s.empty()) {
tok = s.top();
s.pop();
if (tok == "(")
break;
postfix.push_back(tok);
}
} else {
while(!s.empty() && precedence(tok) <= precedence(s.top())) {
postfix.push_back(s.top());
s.pop();
}
s.push(tok);
}
}
while (!s.empty()) {
postfix.push_back(s.top());
s.pop();
}
}
int precedence(string x) {
if(x == "(") {
return 0;
}
else if(x == "+" || x == "-") {
return 1;
}
else if(x == "*" || x== "/") {
return 2;
}
return 3;
}
// Evaluate Postfix Expression.
int evaluatePostfixExpression(vector<string> &postfix) {
if (postfix.empty()) {
return 0;
}
stack<string> s;
for(auto& tok : postfix) {
if(!is_operator(tok)) {
s.push(tok);
}
else {
int y = stoi(s.top());
s.pop();
int x = stoi(s.top());
s.pop();
if(tok[0] == '+') {
x += y;
}
else if (tok[0] == '-') {
x -= y;
}
else if (tok[0] == '*') {
x *= y;
}
else {
x /= y;
}
s.push(to_string(x));
}
}
return stoi(s.top());
}
bool is_operator(const string &op) {
return op.length() == 1 && string("+-*/").find(op) != string::npos;
}
};<commit_msg>update<commit_after>// Time: O(n)
// Space: O(n)
class Solution {
public:
/**
* @param expression: a vector of strings;
* @return: an integer
*/
int evaluateExpression(vector<string> &expression) {
if (expression.empty()) {
return 0;
}
vector<string> postfix;
infixToPostfix(expression, postfix);
return evaluatePostfixExpression(postfix);
}
// Convert Infix to Postfix Expression.
void infixToPostfix(vector<string>& infix, vector<string>& postfix) {
stack<string> s;
for (auto tok : infix) {
if (atoi(tok.c_str())) {
postfix.push_back(tok);
}
else if (tok == "(") {
s.push(tok);
}
else if (tok == ")") {
while (!s.empty()) {
tok = s.top();
s.pop();
if (tok == "(") {
break;
}
postfix.push_back(tok);
}
} else {
while(!s.empty() && precedence(tok) <= precedence(s.top())) {
postfix.push_back(s.top());
s.pop();
}
s.push(tok);
}
}
while (!s.empty()) {
postfix.push_back(s.top());
s.pop();
}
}
int precedence(string x) {
if(x == "(") {
return 0;
}
else if(x == "+" || x == "-") {
return 1;
}
else if(x == "*" || x== "/") {
return 2;
}
return 3;
}
// Evaluate Postfix Expression.
int evaluatePostfixExpression(vector<string> &postfix) {
if (postfix.empty()) {
return 0;
}
stack<string> s;
for(auto& tok : postfix) {
if(!is_operator(tok)) {
s.push(tok);
}
else {
int y = stoi(s.top());
s.pop();
int x = stoi(s.top());
s.pop();
if(tok[0] == '+') {
x += y;
}
else if (tok[0] == '-') {
x -= y;
}
else if (tok[0] == '*') {
x *= y;
}
else {
x /= y;
}
s.push(to_string(x));
}
}
return stoi(s.top());
}
bool is_operator(const string &op) {
return op.length() == 1 && string("+-*/").find(op) != string::npos;
}
};<|endoftext|> |
<commit_before>#include <pybind11/pybind11.h>
#include <sirius.h>
#include <pybind11/stl.h>
#include <pybind11/operators.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <utility>
#include <memory>
#include "utils/json.hpp"
using namespace pybind11::literals; // to bring in the `_a` literal
namespace py = pybind11;
using namespace sirius;
using namespace geometry3d;
using json = nlohmann::json;
using nlohmann::basic_json;
//inspired by: https://github.com/mdcb/python-jsoncpp11/blob/master/extension.cpp
py::object pj_convert(json& node)
{
switch (node.type()) {
case json::value_t::null: {
return py::reinterpret_borrow<py::object>(Py_None);
}
case json::value_t::boolean: {
bool b(node);
return py::bool_(b);
}
case json::value_t::string: {
std::string s;
s = static_cast<std::string const&>(node);
return py::str(s);
}
case json::value_t::number_integer: {
int i(node);
return py::int_(i);
}
case json::value_t::number_unsigned: {
unsigned int u(node);
return py::int_(u);
}
case json::value_t::number_float: {
float f(node);
return py::float_(f);
}
case json::value_t::object: {
py::dict result;
for (auto it = node.begin(); it != node.end(); ++it) {
json my_key(it.key());
result[pj_convert(my_key)] = pj_convert(*it);
}
return result;
}
case json::value_t::array: {
py::list result;
for (auto it = node.begin(); it != node.end(); ++it) {
result.append(pj_convert(*it));
}
return result;
}
default: {
throw std::runtime_error("undefined json value");
/* make compiler happy */
return py::reinterpret_borrow<py::object>(Py_None);
}
}
}
std::string show_mat(const matrix3d<double>& mat)
{
std::string str = "[";
for (int i=0; i<2; ++i)
{str = str +"[" + std::to_string(mat(i,0)) + "," + std::to_string(mat(i,1)) + "," + std::to_string(mat(i,2)) + "]"+"\n";}
str = str + "[" + std::to_string(mat(2,0)) + "," + std::to_string(mat(2,1)) + "," + std::to_string(mat(2,2)) + "]"+ "]";
return str;
}
template<class T>
std::string show_vec(const vector3d<T>& vec)
{
std::string str = "[" + std::to_string(vec[0]) + "," + std::to_string(vec[1]) + "," + std::to_string(vec[2]) + "]";
return str;
}
PYBIND11_MODULE(py_sirius, m){
m.def("initialize", []()
{
sirius::initialize();
});
m.def("finalize", []()
{
sirius::finalize();
});
py::class_<Parameters_input>(m, "Parameters_input")
.def(py::init<>())
.def_readwrite("potential_tol_", &Parameters_input::potential_tol_)
.def_readwrite("energy_tol_", &Parameters_input::energy_tol_)
.def_readwrite("num_dft_iter_", &Parameters_input::num_dft_iter_);
py::class_<Simulation_parameters>(m, "Simulation_parameters")
.def(py::init<>())
.def("pw_cutoff", &Simulation_parameters::pw_cutoff)
.def("parameters_input", (Parameters_input& (Simulation_parameters::*)()) &Simulation_parameters::parameters_input,
py::return_value_policy::reference)
.def("num_spin_dims", &Simulation_parameters::num_spin_dims)
.def("num_mag_dims", &Simulation_parameters::num_mag_dims)
.def("set_gamma_point", &Simulation_parameters::set_gamma_point)
.def("set_pw_cutoff", &Simulation_parameters::set_pw_cutoff)
.def("set_iterative_solver_tolerance", &Simulation_parameters::set_iterative_solver_tolerance);
py::class_<Simulation_context_base, Simulation_parameters>(m, "Simulation_context_base");
py::class_<Simulation_context, Simulation_context_base>(m, "Simulation_context")
.def(py::init<>())
.def(py::init<std::string const&>())
.def("initialize", &Simulation_context::initialize)
.def("num_bands", py::overload_cast<>(&Simulation_context::num_bands, py::const_))
.def("num_bands", py::overload_cast<int>(&Simulation_context::num_bands))
.def("set_verbosity", &Simulation_context::set_verbosity)
.def("create_storage_file", &Simulation_context::create_storage_file)
.def("gvec", &Simulation_context::gvec)
.def("fft", &Simulation_context::fft)
.def("unit_cell", (Unit_cell& (Simulation_context::*)()) &Simulation_context::unit_cell, py::return_value_policy::reference);
py::class_<Unit_cell>(m, "Unit_cell")
.def("add_atom_type", static_cast<void (Unit_cell::*)(const std::string, const std::string)>(&Unit_cell::add_atom_type))
.def("add_atom", static_cast<void (Unit_cell::*)(const std::string, std::vector<double>)>(&Unit_cell::add_atom))
.def("atom_type", static_cast<Atom_type& (Unit_cell::*)(int)>(&Unit_cell::atom_type), py::return_value_policy::reference)
.def("set_lattice_vectors", static_cast<void (Unit_cell::*)(matrix3d<double>)>(&Unit_cell::set_lattice_vectors))
.def("get_symmetry", &Unit_cell::get_symmetry)
.def("reciprocal_lattice_vectors", &Unit_cell::reciprocal_lattice_vectors)
.def("generate_radial_functions", &Unit_cell::generate_radial_functions);
py::class_<z_column_descriptor> (m, "z_column_descriptor")
.def_readwrite("x", &z_column_descriptor::x)
.def_readwrite("y", &z_column_descriptor::y)
.def_readwrite("z", &z_column_descriptor::z)
.def(py::init<int, int , std::vector<int>>());
py::class_<Gvec>(m, "Gvec")
.def(py::init<matrix3d<double>, double, bool>())
.def("num_gvec", &sddk::Gvec::num_gvec)
.def("count", &sddk::Gvec::count)
.def("offset", &sddk::Gvec::offset)
.def("gvec", &sddk::Gvec::gvec)
.def("num_zcol", &sddk::Gvec::num_zcol)
.def("gvec_alt", [](Gvec &obj, int idx)
{
vector3d<int> vec(obj.gvec(idx));
std::vector<int> retr = {vec[0], vec[1], vec[2]};
return retr;
})
.def("index_by_gvec", [](Gvec &obj, std::vector<int> vec)
{
vector3d<int> vec3d(vec);
return obj.index_by_gvec(vec3d);
})
.def("zcol", [](Gvec &gvec, int idx)
{
z_column_descriptor obj(gvec.zcol(idx));
py::dict dict("x"_a = obj.x, "y"_a = obj.y, "z"_a = obj.z);
return dict;
})
.def("index_by_gvec", &Gvec::index_by_gvec);
py::class_<vector3d<int>>(m, "vector3d_int")
.def(py::init<std::vector<int>>())
.def("__call__", [](const vector3d<int> &obj, int x)
{
return obj[x];
})
.def("__repr__", [](const vector3d<int> &vec)
{
return show_vec(vec);
})
.def(py::init<vector3d<int>>());
py::class_<vector3d<double>>(m, "vector3d_double")
.def(py::init<std::vector<double>>())
.def("__call__", [](const vector3d<double> &obj, int x)
{
return obj[x];
})
.def("__repr__", [](const vector3d<double> &vec)
{
return show_vec(vec);
})
.def("length", &vector3d<double>::length)
.def(py::self - py::self)
.def(py::self * float())
.def(py::self + py::self)
.def(py::init<vector3d<double>>());
py::class_<matrix3d<double>>(m, "matrix3d")
.def(py::init<std::vector<std::vector<double>>>())
.def(py::init<>())
.def("__call__", [](const matrix3d<double> &obj, int x, int y)
{
return obj(x,y);
})
.def(py::self * py::self)
.def("__getitem__", [](const matrix3d<double> &obj, int x, int y)
{
return obj(x,y);
})
.def("__mul__", [](const matrix3d<double> & obj, vector3d<double> const& b)
{
vector3d<double> res = obj * b;
return res;
})
.def("__repr__", [](const matrix3d<double> &mat)
{
return show_mat(mat);
})
.def(py::init<matrix3d<double>>())
.def("det", &matrix3d<double>::det);
py::class_<Potential>(m, "Potential")
.def(py::init<Simulation_context&>())
.def("generate", &Potential::generate)
.def("allocate", &Potential::allocate)
.def("save", &Potential::save)
.def("load", &Potential::load);
py::class_<Density>(m, "Density")
.def(py::init<Simulation_context&>())
.def("initial_density", &Density::initial_density)
.def("allocate", &Density::allocate)
.def("save", &Density::save)
.def("load", &Density::load);
py::class_<Band>(m, "Band")
.def(py::init<Simulation_context&>())
.def("initialize_subspace", py::overload_cast<K_point_set&, Hamiltonian&>(&Band::initialize_subspace, py::const_))
.def("solve", &Band::solve);
py::class_<DFT_ground_state>(m, "DFT_ground_state")
.def(py::init<K_point_set&>())
.def("print_info", &DFT_ground_state::print_info)
.def("initial_state", &DFT_ground_state::initial_state)
.def("print_magnetic_moment", &DFT_ground_state::print_magnetic_moment)
.def("total_energy", &DFT_ground_state::total_energy)
.def("band", &DFT_ground_state::band)
.def("density", &DFT_ground_state::density, py::return_value_policy::reference)
.def("find", [](DFT_ground_state& dft, double potential_tol, double energy_tol, int num_dft_iter, bool write_state)
{
json js = dft.find(potential_tol, energy_tol, num_dft_iter, write_state);
return pj_convert(js);
})
.def("k_point_set", &DFT_ground_state::k_point_set, py::return_value_policy::reference_internal)
.def("hamiltonian", &DFT_ground_state::hamiltonian, py::return_value_policy::reference)
.def("potential", &DFT_ground_state::potential, py::return_value_policy::reference);
py::class_<K_point>(m, "K_point")
.def("band_energy", py::overload_cast<int, int>(&K_point::band_energy))
.def("vk", &K_point::vk, py::return_value_policy::reference);
py::class_<K_point_set>(m, "K_point_set")
.def(py::init<Simulation_context&>())
.def(py::init<Simulation_context&, std::vector<vector3d<double>>>())
.def(py::init<Simulation_context&, vector3d<int>, vector3d<int>, bool>())
.def(py::init<Simulation_context&, std::vector<int>, std::vector<int>, bool>())
.def("initialize", py::overload_cast<>(&K_point_set::initialize))
.def("num_kpoints", &K_point_set::num_kpoints)
.def("energy_fermi", &K_point_set::energy_fermi)
.def("get_band_energies", &K_point_set::get_band_energies, py::return_value_policy::reference)
.def("sync_band_energies", &K_point_set::sync_band_energies)
.def("__call__", &K_point_set::operator[], py::return_value_policy::reference)
.def("add_kpoint", [](K_point_set &ks, std::vector<double> &v, double weight)
{
vector3d<double> vec3d(v);
ks.add_kpoint(&vec3d[0], weight);
})
.def("add_kpoint", [](K_point_set &ks, vector3d<double> &v, double weight)
{
ks.add_kpoint(&v[0], weight);
});
py::class_<Hamiltonian>(m, "Hamiltonian")
.def(py::init<Simulation_context&, Potential&>());
py::class_<Stress>(m, "Stress")
//.def(py::init<Simulation_context&, K_point_set&, Density&, Potential&>())
.def("calc_stress_total", &Stress::calc_stress_total, py::return_value_policy::reference_internal)
.def("print_info", &Stress::print_info);
py::class_<Force>(m, "Force")
//.def(py::init<Simulation_context&, Density&, Potential&, Hamiltonian&, K_point_set&>())
.def("calc_forces_total", &Force::calc_forces_total, py::return_value_policy::reference_internal)
.def("print_info", &Force::print_info);
py::class_<Free_atom>(m, "Free_atom")
.def(py::init<Simulation_parameters&, std::string>())
.def(py::init<Simulation_parameters&, int>())
.def("ground_state", [](Free_atom& atom, double energy_tol, double charge_tol, bool rel)
{
json js = atom.ground_state(energy_tol, charge_tol, rel);
return pj_convert(js);
});
}
<commit_msg>python: call sirius::init/finalize internally on module import/exit<commit_after>#include <pybind11/pybind11.h>
#include <sirius.h>
#include <pybind11/stl.h>
#include <pybind11/operators.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <utility>
#include <memory>
#include "utils/json.hpp"
using namespace pybind11::literals; // to bring in the `_a` literal
namespace py = pybind11;
using namespace sirius;
using namespace geometry3d;
using json = nlohmann::json;
using nlohmann::basic_json;
//inspired by: https://github.com/mdcb/python-jsoncpp11/blob/master/extension.cpp
py::object pj_convert(json& node)
{
switch (node.type()) {
case json::value_t::null: {
return py::reinterpret_borrow<py::object>(Py_None);
}
case json::value_t::boolean: {
bool b(node);
return py::bool_(b);
}
case json::value_t::string: {
std::string s;
s = static_cast<std::string const&>(node);
return py::str(s);
}
case json::value_t::number_integer: {
int i(node);
return py::int_(i);
}
case json::value_t::number_unsigned: {
unsigned int u(node);
return py::int_(u);
}
case json::value_t::number_float: {
float f(node);
return py::float_(f);
}
case json::value_t::object: {
py::dict result;
for (auto it = node.begin(); it != node.end(); ++it) {
json my_key(it.key());
result[pj_convert(my_key)] = pj_convert(*it);
}
return result;
}
case json::value_t::array: {
py::list result;
for (auto it = node.begin(); it != node.end(); ++it) {
result.append(pj_convert(*it));
}
return result;
}
default: {
throw std::runtime_error("undefined json value");
/* make compiler happy */
return py::reinterpret_borrow<py::object>(Py_None);
}
}
}
std::string show_mat(const matrix3d<double>& mat)
{
std::string str = "[";
for (int i=0; i<2; ++i)
{str = str +"[" + std::to_string(mat(i,0)) + "," + std::to_string(mat(i,1)) + "," + std::to_string(mat(i,2)) + "]"+"\n";}
str = str + "[" + std::to_string(mat(2,0)) + "," + std::to_string(mat(2,1)) + "," + std::to_string(mat(2,2)) + "]"+ "]";
return str;
}
template<class T>
std::string show_vec(const vector3d<T>& vec)
{
std::string str = "[" + std::to_string(vec[0]) + "," + std::to_string(vec[1]) + "," + std::to_string(vec[2]) + "]";
return str;
}
PYBIND11_MODULE(py_sirius, m){
// MPI_Init/Finalize
sirius::initialize();
auto atexit = py::module::import("atexit");
atexit.attr("register")(py::cpp_function([](){ sirius::finalize(); }));
py::class_<Parameters_input>(m, "Parameters_input")
.def(py::init<>())
.def_readwrite("potential_tol_", &Parameters_input::potential_tol_)
.def_readwrite("energy_tol_", &Parameters_input::energy_tol_)
.def_readwrite("num_dft_iter_", &Parameters_input::num_dft_iter_);
py::class_<Simulation_parameters>(m, "Simulation_parameters")
.def(py::init<>())
.def("pw_cutoff", &Simulation_parameters::pw_cutoff)
.def("parameters_input", (Parameters_input& (Simulation_parameters::*)()) &Simulation_parameters::parameters_input,
py::return_value_policy::reference)
.def("num_spin_dims", &Simulation_parameters::num_spin_dims)
.def("num_mag_dims", &Simulation_parameters::num_mag_dims)
.def("set_gamma_point", &Simulation_parameters::set_gamma_point)
.def("set_pw_cutoff", &Simulation_parameters::set_pw_cutoff)
.def("set_iterative_solver_tolerance", &Simulation_parameters::set_iterative_solver_tolerance);
py::class_<Simulation_context_base, Simulation_parameters>(m, "Simulation_context_base");
py::class_<Simulation_context, Simulation_context_base>(m, "Simulation_context")
.def(py::init<>())
.def(py::init<std::string const&>())
.def("initialize", &Simulation_context::initialize)
.def("num_bands", py::overload_cast<>(&Simulation_context::num_bands, py::const_))
.def("num_bands", py::overload_cast<int>(&Simulation_context::num_bands))
.def("set_verbosity", &Simulation_context::set_verbosity)
.def("create_storage_file", &Simulation_context::create_storage_file)
.def("gvec", &Simulation_context::gvec)
.def("fft", &Simulation_context::fft)
.def("unit_cell", (Unit_cell& (Simulation_context::*)()) &Simulation_context::unit_cell, py::return_value_policy::reference);
py::class_<Unit_cell>(m, "Unit_cell")
.def("add_atom_type", static_cast<void (Unit_cell::*)(const std::string, const std::string)>(&Unit_cell::add_atom_type))
.def("add_atom", static_cast<void (Unit_cell::*)(const std::string, std::vector<double>)>(&Unit_cell::add_atom))
.def("atom_type", static_cast<Atom_type& (Unit_cell::*)(int)>(&Unit_cell::atom_type), py::return_value_policy::reference)
.def("set_lattice_vectors", static_cast<void (Unit_cell::*)(matrix3d<double>)>(&Unit_cell::set_lattice_vectors))
.def("get_symmetry", &Unit_cell::get_symmetry)
.def("reciprocal_lattice_vectors", &Unit_cell::reciprocal_lattice_vectors)
.def("generate_radial_functions", &Unit_cell::generate_radial_functions);
py::class_<z_column_descriptor> (m, "z_column_descriptor")
.def_readwrite("x", &z_column_descriptor::x)
.def_readwrite("y", &z_column_descriptor::y)
.def_readwrite("z", &z_column_descriptor::z)
.def(py::init<int, int , std::vector<int>>());
py::class_<Gvec>(m, "Gvec")
.def(py::init<matrix3d<double>, double, bool>())
.def("num_gvec", &sddk::Gvec::num_gvec)
.def("count", &sddk::Gvec::count)
.def("offset", &sddk::Gvec::offset)
.def("gvec", &sddk::Gvec::gvec)
.def("num_zcol", &sddk::Gvec::num_zcol)
.def("gvec_alt", [](Gvec &obj, int idx)
{
vector3d<int> vec(obj.gvec(idx));
std::vector<int> retr = {vec[0], vec[1], vec[2]};
return retr;
})
.def("index_by_gvec", [](Gvec &obj, std::vector<int> vec)
{
vector3d<int> vec3d(vec);
return obj.index_by_gvec(vec3d);
})
.def("zcol", [](Gvec &gvec, int idx)
{
z_column_descriptor obj(gvec.zcol(idx));
py::dict dict("x"_a = obj.x, "y"_a = obj.y, "z"_a = obj.z);
return dict;
})
.def("index_by_gvec", &Gvec::index_by_gvec);
py::class_<vector3d<int>>(m, "vector3d_int")
.def(py::init<std::vector<int>>())
.def("__call__", [](const vector3d<int> &obj, int x)
{
return obj[x];
})
.def("__repr__", [](const vector3d<int> &vec)
{
return show_vec(vec);
})
.def(py::init<vector3d<int>>());
py::class_<vector3d<double>>(m, "vector3d_double")
.def(py::init<std::vector<double>>())
.def("__call__", [](const vector3d<double> &obj, int x)
{
return obj[x];
})
.def("__repr__", [](const vector3d<double> &vec)
{
return show_vec(vec);
})
.def("length", &vector3d<double>::length)
.def(py::self - py::self)
.def(py::self * float())
.def(py::self + py::self)
.def(py::init<vector3d<double>>());
py::class_<matrix3d<double>>(m, "matrix3d")
.def(py::init<std::vector<std::vector<double>>>())
.def(py::init<>())
.def("__call__", [](const matrix3d<double> &obj, int x, int y)
{
return obj(x,y);
})
.def(py::self * py::self)
.def("__getitem__", [](const matrix3d<double> &obj, int x, int y)
{
return obj(x,y);
})
.def("__mul__", [](const matrix3d<double> & obj, vector3d<double> const& b)
{
vector3d<double> res = obj * b;
return res;
})
.def("__repr__", [](const matrix3d<double> &mat)
{
return show_mat(mat);
})
.def(py::init<matrix3d<double>>())
.def("det", &matrix3d<double>::det);
py::class_<Potential>(m, "Potential")
.def(py::init<Simulation_context&>())
.def("generate", &Potential::generate)
.def("allocate", &Potential::allocate)
.def("save", &Potential::save)
.def("load", &Potential::load);
py::class_<Density>(m, "Density")
.def(py::init<Simulation_context&>())
.def("initial_density", &Density::initial_density)
.def("allocate", &Density::allocate)
.def("save", &Density::save)
.def("load", &Density::load);
py::class_<Band>(m, "Band")
.def(py::init<Simulation_context&>())
.def("initialize_subspace", py::overload_cast<K_point_set&, Hamiltonian&>(&Band::initialize_subspace, py::const_))
.def("solve", &Band::solve);
py::class_<DFT_ground_state>(m, "DFT_ground_state")
.def(py::init<K_point_set&>())
.def("print_info", &DFT_ground_state::print_info)
.def("initial_state", &DFT_ground_state::initial_state)
.def("print_magnetic_moment", &DFT_ground_state::print_magnetic_moment)
.def("total_energy", &DFT_ground_state::total_energy)
.def("band", &DFT_ground_state::band)
.def("density", &DFT_ground_state::density, py::return_value_policy::reference)
.def("find", [](DFT_ground_state& dft, double potential_tol, double energy_tol, int num_dft_iter, bool write_state)
{
json js = dft.find(potential_tol, energy_tol, num_dft_iter, write_state);
return pj_convert(js);
})
.def("k_point_set", &DFT_ground_state::k_point_set, py::return_value_policy::reference_internal)
.def("hamiltonian", &DFT_ground_state::hamiltonian, py::return_value_policy::reference)
.def("potential", &DFT_ground_state::potential, py::return_value_policy::reference);
py::class_<K_point>(m, "K_point")
.def("band_energy", py::overload_cast<int, int>(&K_point::band_energy))
.def("vk", &K_point::vk, py::return_value_policy::reference);
py::class_<K_point_set>(m, "K_point_set")
.def(py::init<Simulation_context&>())
.def(py::init<Simulation_context&, std::vector<vector3d<double>>>())
.def(py::init<Simulation_context&, vector3d<int>, vector3d<int>, bool>())
.def(py::init<Simulation_context&, std::vector<int>, std::vector<int>, bool>())
.def("initialize", py::overload_cast<>(&K_point_set::initialize))
.def("num_kpoints", &K_point_set::num_kpoints)
.def("energy_fermi", &K_point_set::energy_fermi)
.def("get_band_energies", &K_point_set::get_band_energies, py::return_value_policy::reference)
.def("sync_band_energies", &K_point_set::sync_band_energies)
.def("__call__", &K_point_set::operator[], py::return_value_policy::reference)
.def("add_kpoint", [](K_point_set &ks, std::vector<double> &v, double weight)
{
vector3d<double> vec3d(v);
ks.add_kpoint(&vec3d[0], weight);
})
.def("add_kpoint", [](K_point_set &ks, vector3d<double> &v, double weight)
{
ks.add_kpoint(&v[0], weight);
});
py::class_<Hamiltonian>(m, "Hamiltonian")
.def(py::init<Simulation_context&, Potential&>());
py::class_<Stress>(m, "Stress")
//.def(py::init<Simulation_context&, K_point_set&, Density&, Potential&>())
.def("calc_stress_total", &Stress::calc_stress_total, py::return_value_policy::reference_internal)
.def("print_info", &Stress::print_info);
py::class_<Force>(m, "Force")
//.def(py::init<Simulation_context&, Density&, Potential&, Hamiltonian&, K_point_set&>())
.def("calc_forces_total", &Force::calc_forces_total, py::return_value_policy::reference_internal)
.def("print_info", &Force::print_info);
py::class_<Free_atom>(m, "Free_atom")
.def(py::init<Simulation_parameters&, std::string>())
.def(py::init<Simulation_parameters&, int>())
.def("ground_state", [](Free_atom& atom, double energy_tol, double charge_tol, bool rel)
{
json js = atom.ground_state(energy_tol, charge_tol, rel);
return pj_convert(js);
});
}
<|endoftext|> |
<commit_before><commit_msg>[basefunctionset.fem-localfunctions] update * use types from base * add static error message for wrong dimensions<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2011-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bench/bench.h>
#include <policy/policy.h>
#include <random.h>
#include <test/util/setup_common.h>
#include <txmempool.h>
#include <vector>
static void AddTx(const CTransactionRef &tx, CTxMemPool &pool)
EXCLUSIVE_LOCKS_REQUIRED(cs_main, pool.cs) {
int64_t nTime = 0;
unsigned int nHeight = 1;
bool spendsCoinbase = false;
unsigned int sigOpCost = 4;
LockPoints lp;
pool.addUnchecked(CTxMemPoolEntry(tx, 1000 * SATOSHI, nTime, nHeight,
spendsCoinbase, sigOpCost, lp));
}
struct Available {
CTransactionRef ref;
size_t vin_left{0};
size_t tx_count;
Available(CTransactionRef &_ref, size_t _tx_count)
: ref(_ref), tx_count(_tx_count) {}
};
static void ComplexMemPool(benchmark::Bench &bench) {
int childTxs = 800;
if (bench.complexityN() > 1) {
childTxs = static_cast<int>(bench.complexityN());
}
FastRandomContext det_rand{true};
std::vector<Available> available_coins;
std::vector<CTransactionRef> ordered_coins;
// Create some base transactions
size_t tx_counter = 1;
for (auto x = 0; x < 100; ++x) {
CMutableTransaction tx = CMutableTransaction();
tx.vin.resize(1);
tx.vin[0].scriptSig = CScript() << CScriptNum(tx_counter);
tx.vout.resize(det_rand.randrange(10) + 2);
for (auto &out : tx.vout) {
out.scriptPubKey = CScript() << CScriptNum(tx_counter) << OP_EQUAL;
out.nValue = 10 * COIN;
}
ordered_coins.emplace_back(MakeTransactionRef(tx));
available_coins.emplace_back(ordered_coins.back(), tx_counter++);
}
for (auto x = 0; x < childTxs && !available_coins.empty(); ++x) {
CMutableTransaction tx = CMutableTransaction();
size_t n_ancestors = det_rand.randrange(10) + 1;
for (size_t ancestor = 0;
ancestor < n_ancestors && !available_coins.empty(); ++ancestor) {
size_t idx = det_rand.randrange(available_coins.size());
Available coin = available_coins[idx];
TxId txid = coin.ref->GetId();
// biased towards taking just one ancestor, but maybe more
size_t n_to_take =
det_rand.randrange(2) == 0
? 1
: 1 + det_rand.randrange(coin.ref->vout.size() -
coin.vin_left);
for (size_t i = 0; i < n_to_take; ++i) {
tx.vin.emplace_back();
tx.vin.back().prevout = COutPoint(txid, coin.vin_left++);
tx.vin.back().scriptSig = CScript() << coin.tx_count;
}
if (coin.vin_left == coin.ref->vin.size()) {
coin = available_coins.back();
available_coins.pop_back();
}
tx.vout.resize(det_rand.randrange(10) + 2);
for (auto &out : tx.vout) {
out.scriptPubKey = CScript()
<< CScriptNum(tx_counter) << OP_EQUAL;
out.nValue = 10 * COIN;
}
}
ordered_coins.emplace_back(MakeTransactionRef(tx));
available_coins.emplace_back(ordered_coins.back(), tx_counter++);
}
TestingSetup test_setup;
CTxMemPool pool;
LOCK2(cs_main, pool.cs);
bench.run([&]() NO_THREAD_SAFETY_ANALYSIS {
for (auto &tx : ordered_coins) {
AddTx(tx, pool);
}
pool.TrimToSize(pool.DynamicMemoryUsage() * 3 / 4);
pool.TrimToSize(GetVirtualTransactionSize(*ordered_coins.front()));
});
}
BENCHMARK(ComplexMemPool);
<commit_msg>[bench] Benchmark CTxMemPool::check()<commit_after>// Copyright (c) 2011-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bench/bench.h>
#include <policy/policy.h>
#include <random.h>
#include <test/util/setup_common.h>
#include <txmempool.h>
#include <validation.h>
#include <vector>
static void AddTx(const CTransactionRef &tx, CTxMemPool &pool)
EXCLUSIVE_LOCKS_REQUIRED(cs_main, pool.cs) {
int64_t nTime = 0;
unsigned int nHeight = 1;
bool spendsCoinbase = false;
unsigned int sigOpCost = 4;
LockPoints lp;
pool.addUnchecked(CTxMemPoolEntry(tx, 1000 * SATOSHI, nTime, nHeight,
spendsCoinbase, sigOpCost, lp));
}
struct Available {
CTransactionRef ref;
size_t vin_left{0};
size_t tx_count;
Available(CTransactionRef &_ref, size_t _tx_count)
: ref(_ref), tx_count(_tx_count) {}
};
static std::vector<CTransactionRef>
CreateOrderedCoins(FastRandomContext &det_rand, int childTxs,
int min_ancestors) {
std::vector<Available> available_coins;
std::vector<CTransactionRef> ordered_coins;
// Create some base transactions
size_t tx_counter = 1;
for (auto x = 0; x < 100; ++x) {
CMutableTransaction tx = CMutableTransaction();
tx.vin.resize(1);
tx.vin[0].scriptSig = CScript() << CScriptNum(tx_counter);
tx.vout.resize(det_rand.randrange(10) + 2);
for (auto &out : tx.vout) {
out.scriptPubKey = CScript() << CScriptNum(tx_counter) << OP_EQUAL;
out.nValue = 10 * COIN;
}
ordered_coins.emplace_back(MakeTransactionRef(tx));
available_coins.emplace_back(ordered_coins.back(), tx_counter++);
}
for (auto x = 0; x < childTxs && !available_coins.empty(); ++x) {
CMutableTransaction tx = CMutableTransaction();
size_t n_ancestors = det_rand.randrange(10) + 1;
for (size_t ancestor = 0;
ancestor < n_ancestors && !available_coins.empty(); ++ancestor) {
size_t idx = det_rand.randrange(available_coins.size());
Available coin = available_coins[idx];
TxId txid = coin.ref->GetId();
// biased towards taking min_ancestors parents, but maybe more
size_t n_to_take =
det_rand.randrange(2) == 0
? min_ancestors
: min_ancestors + det_rand.randrange(coin.ref->vout.size() -
coin.vin_left);
for (size_t i = 0; i < n_to_take; ++i) {
tx.vin.emplace_back();
tx.vin.back().prevout = COutPoint(txid, coin.vin_left++);
tx.vin.back().scriptSig = CScript() << coin.tx_count;
}
if (coin.vin_left == coin.ref->vin.size()) {
coin = available_coins.back();
available_coins.pop_back();
}
tx.vout.resize(det_rand.randrange(10) + 2);
for (auto &out : tx.vout) {
out.scriptPubKey = CScript()
<< CScriptNum(tx_counter) << OP_EQUAL;
out.nValue = 10 * COIN;
}
}
ordered_coins.emplace_back(MakeTransactionRef(tx));
available_coins.emplace_back(ordered_coins.back(), tx_counter++);
}
return ordered_coins;
}
static void ComplexMemPool(benchmark::Bench &bench) {
FastRandomContext det_rand{true};
int childTxs = 800;
if (bench.complexityN() > 1) {
childTxs = static_cast<int>(bench.complexityN());
}
std::vector<CTransactionRef> ordered_coins =
CreateOrderedCoins(det_rand, childTxs, /* min_ancestors */ 1);
TestingSetup test_setup;
CTxMemPool pool;
LOCK2(cs_main, pool.cs);
bench.run([&]() NO_THREAD_SAFETY_ANALYSIS {
for (auto &tx : ordered_coins) {
AddTx(tx, pool);
}
pool.TrimToSize(pool.DynamicMemoryUsage() * 3 / 4);
pool.TrimToSize(GetVirtualTransactionSize(*ordered_coins.front()));
});
}
static void MempoolCheck(benchmark::Bench &bench) {
FastRandomContext det_rand{true};
const int childTxs =
bench.complexityN() > 1 ? static_cast<int>(bench.complexityN()) : 2000;
const std::vector<CTransactionRef> ordered_coins =
CreateOrderedCoins(det_rand, childTxs, /* min_ancestors */ 5);
const auto testing_setup =
TestingSetup(CBaseChainParams::MAIN, {"-checkmempool=1"});
CTxMemPool pool;
LOCK2(cs_main, pool.cs);
for (auto &tx : ordered_coins) {
AddTx(tx, pool);
}
bench.run([&]() NO_THREAD_SAFETY_ANALYSIS {
pool.check(testing_setup.m_node.chainman->ActiveChainstate());
});
}
BENCHMARK(ComplexMemPool);
BENCHMARK(MempoolCheck);
<|endoftext|> |
<commit_before>#include "MMDIkSolver.h"
#include <glm/gtc/matrix_transform.hpp>
namespace saba
{
MMDIkSolver::MMDIkSolver()
: m_ikNode(nullptr)
, m_ikTarget(nullptr)
, m_iterateCount(1)
, m_limitAngle(glm::pi<float>() * 2.0f)
, m_enable(true)
{
}
void MMDIkSolver::AddIKChain(MMDNode * node, bool isKnee)
{
IKChain chain;
chain.m_node = node;
chain.m_enableAxisLimit = isKnee;
if (isKnee)
{
chain.m_limitMin = glm::vec3(glm::radians(0.5f), 0, 0);
chain.m_limitMax = glm::vec3(glm::radians(180.0f), 0, 0);
}
m_chains.push_back(chain);
}
void MMDIkSolver::AddIKChain(
MMDNode * node,
bool axisLimit,
const glm::vec3 & limixMin,
const glm::vec3 & limitMax
)
{
IKChain chain;
chain.m_node = node;
chain.m_enableAxisLimit = axisLimit;
chain.m_limitMin = limixMin;
chain.m_limitMax = limitMax;
m_chains.push_back(chain);
}
void MMDIkSolver::Solve()
{
if (!m_enable)
{
return;
}
// Initialize IKChain
for (auto& chain : m_chains)
{
if (chain.m_enableAxisLimit)
{
//auto angle = (chain.m_limitMax - chain.m_limitMin) * 0.5f;
auto angle = chain.m_limitMax;
auto r = glm::rotate(glm::quat(), angle.x, glm::vec3(1, 0, 0));
r = glm::rotate(r, angle.y, glm::vec3(0, 1, 0));
r = glm::rotate(r, angle.z, glm::vec3(0, 0, 1));
chain.m_prevAngle = angle;
auto rm = glm::mat3_cast(r) * glm::inverse(glm::mat3_cast(chain.m_node->m_rotate));
chain.m_node->m_ikRotate = glm::quat_cast(rm);
}
else
{
chain.m_node->m_ikRotate = glm::quat();
}
chain.m_node->UpdateLocalMatrix();
chain.m_node->UpdateGlobalMatrix();
}
for (uint32_t i = 0; i < m_iterateCount; i++)
{
SolveCore();
}
}
namespace
{
float NormalizeAngle(float angle)
{
float ret = angle;
while (ret >= glm::two_pi<float>())
{
ret -= glm::two_pi<float>();
}
while (ret < 0)
{
ret += glm::two_pi<float>();
}
return ret;
}
float DiffAngle(float a, float b)
{
float diff = NormalizeAngle(a) - NormalizeAngle(b);
if (diff > glm::pi<float>())
{
return diff - glm::two_pi<float>();
}
else if (diff < -glm::pi<float>())
{
return diff + glm::two_pi<float>();
}
return diff;
}
float ClampAngle(float angle, float minAngle, float maxAngle)
{
if (minAngle == maxAngle)
{
return minAngle;
}
float ret = angle;
while (ret < minAngle)
{
ret += glm::two_pi<float>();
}
if (ret < maxAngle)
{
return ret;
}
while (ret > maxAngle)
{
ret -= glm::two_pi<float>();
}
if (ret > minAngle)
{
return ret;
}
float minDiff = std::abs(DiffAngle(minAngle, ret));
float maxDiff = std::abs(DiffAngle(maxAngle, ret));
if (minDiff < maxDiff)
{
return minAngle;
}
else
{
return maxAngle;
}
}
glm::vec3 Decompose(const glm::mat3& m, const glm::vec3& before)
{
glm::vec3 r;
float sy = -m[0][2];
const float e = 1.0e-6f;
if ((1.0f - std::abs(sy)) < e)
{
r.y = std::asin(sy);
// 180°に近いほうを探す
float sx = std::sin(before.x);
float sz = std::sin(before.z);
if (std::abs(sx) < std::abs(sz))
{
// Xのほうが0または180
float cx = std::cos(before.x);
if (cx > 0)
{
r.x = 0;
r.z = std::asin(-m[1][0]);
}
else
{
r.x = glm::pi<float>();
r.z = std::asin(m[1][0]);
}
}
else
{
float cz = std::cos(before.z);
if (cz > 0)
{
r.z = 0;
r.x = std::asin(-m[2][1]);
}
else
{
r.z = glm::pi<float>();
r.x = std::asin(m[2][1]);
}
}
}
else
{
r.x = std::atan2(m[1][2], m[2][2]);
r.y = std::asin(-m[0][2]);
r.z = std::atan2(m[0][1], m[0][0]);
}
const float pi = glm::pi<float>();
glm::vec3 tests[] =
{
{ r.x + pi, pi - r.y, r.z + pi },
{ r.x + pi, pi - r.y, r.z - pi },
{ r.x + pi, -pi - r.y, r.z + pi },
{ r.x + pi, -pi - r.y, r.z - pi },
{ r.x - pi, pi - r.y, r.z + pi },
{ r.x - pi, pi - r.y, r.z - pi },
{ r.x - pi, -pi - r.y, r.z + pi },
{ r.x - pi, -pi - r.y, r.z - pi },
};
float errX = std::abs(DiffAngle(r.x, before.x));
float errY = std::abs(DiffAngle(r.y, before.y));
float errZ = std::abs(DiffAngle(r.z, before.z));
float minErr = errX + errY + errZ;
for (const auto test : tests)
{
float err = std::abs(DiffAngle(test.x, before.x))
+ std::abs(DiffAngle(test.y, before.y))
+ std::abs(DiffAngle(test.z, before.z));
if (err < minErr)
{
minErr = err;
r = test;
}
}
return r;
}
}
void MMDIkSolver::SolveCore()
{
auto ikPos = glm::vec3(m_ikNode->m_global[3]);
for (auto& chain : m_chains)
{
MMDNode* chainNode = chain.m_node;
auto targetPos = glm::vec3(m_ikTarget->m_global[3]);
auto invChain = glm::inverse(chain.m_node->m_global);
auto chainIkPos = glm::vec3(invChain * glm::vec4(ikPos, 1));
auto chainTargetPos = glm::vec3(invChain * glm::vec4(targetPos, 1));
auto chainIkVec = glm::normalize(chainIkPos);
auto chainTargetVec = glm::normalize(chainTargetPos);
auto dot = glm::dot(chainTargetVec, chainIkVec);
if ((1.0f - dot) < std::numeric_limits<float>::epsilon())
{
continue;
}
float angle = std::acos(dot);
angle = glm::clamp(angle, -m_limitAngle, m_limitAngle);
auto cross = glm::cross(chainTargetVec, chainIkVec);
auto rot = glm::rotate(glm::quat(), angle, cross);
auto chainRotM = glm::mat3_cast(chainNode->m_ikRotate)
* glm::mat3_cast(chainNode->m_rotate)
* glm::mat3_cast(rot);
if (chain.m_enableAxisLimit)
{
auto rotXYZ = Decompose(chainRotM, chain.m_prevAngle);
glm::vec3 clampXYZ;
clampXYZ.x = ClampAngle(rotXYZ.x, chain.m_limitMin.x, chain.m_limitMax.x);
clampXYZ.y = ClampAngle(rotXYZ.y, chain.m_limitMin.y, chain.m_limitMax.y);
clampXYZ.z = ClampAngle(rotXYZ.z, chain.m_limitMin.z, chain.m_limitMax.z);
clampXYZ = glm::clamp(clampXYZ - chain.m_prevAngle, -m_limitAngle, m_limitAngle) + chain.m_prevAngle;
auto r = glm::rotate(glm::quat(), clampXYZ.x, glm::vec3(1, 0, 0));
r = glm::rotate(r, clampXYZ.y, glm::vec3(0, 1, 0));
r = glm::rotate(r, clampXYZ.z, glm::vec3(0, 0, 1));
chainRotM = glm::mat3_cast(r);
chain.m_prevAngle = clampXYZ;
}
auto ikRotM = chainRotM
* glm::inverse(glm::mat3_cast(chainNode->m_rotate));
chainNode->m_ikRotate = glm::quat_cast(ikRotM);
chainNode->UpdateLocalMatrix();
chainNode->UpdateGlobalMatrix();
}
}
}
<commit_msg>Limit を有効にした際の IKSolver で、回転の初期値を中間値にした 最大値、または最小値の場合、動かなくなってしまうため<commit_after>#include "MMDIkSolver.h"
#include <glm/gtc/matrix_transform.hpp>
namespace saba
{
MMDIkSolver::MMDIkSolver()
: m_ikNode(nullptr)
, m_ikTarget(nullptr)
, m_iterateCount(1)
, m_limitAngle(glm::pi<float>() * 2.0f)
, m_enable(true)
{
}
void MMDIkSolver::AddIKChain(MMDNode * node, bool isKnee)
{
IKChain chain;
chain.m_node = node;
chain.m_enableAxisLimit = isKnee;
if (isKnee)
{
chain.m_limitMin = glm::vec3(glm::radians(0.5f), 0, 0);
chain.m_limitMax = glm::vec3(glm::radians(180.0f), 0, 0);
}
m_chains.push_back(chain);
}
void MMDIkSolver::AddIKChain(
MMDNode * node,
bool axisLimit,
const glm::vec3 & limixMin,
const glm::vec3 & limitMax
)
{
IKChain chain;
chain.m_node = node;
chain.m_enableAxisLimit = axisLimit;
chain.m_limitMin = limixMin;
chain.m_limitMax = limitMax;
m_chains.push_back(chain);
}
void MMDIkSolver::Solve()
{
if (!m_enable)
{
return;
}
// Initialize IKChain
for (auto& chain : m_chains)
{
if (chain.m_enableAxisLimit)
{
auto angle = (chain.m_limitMax - chain.m_limitMin) * 0.5f;
auto r = glm::rotate(glm::quat(), angle.x, glm::vec3(1, 0, 0));
r = glm::rotate(r, angle.y, glm::vec3(0, 1, 0));
r = glm::rotate(r, angle.z, glm::vec3(0, 0, 1));
chain.m_prevAngle = angle;
auto rm = glm::mat3_cast(r) * glm::inverse(glm::mat3_cast(chain.m_node->m_rotate));
chain.m_node->m_ikRotate = glm::quat_cast(rm);
}
else
{
chain.m_node->m_ikRotate = glm::quat();
}
chain.m_node->UpdateLocalMatrix();
chain.m_node->UpdateGlobalMatrix();
}
for (uint32_t i = 0; i < m_iterateCount; i++)
{
SolveCore();
}
}
namespace
{
float NormalizeAngle(float angle)
{
float ret = angle;
while (ret >= glm::two_pi<float>())
{
ret -= glm::two_pi<float>();
}
while (ret < 0)
{
ret += glm::two_pi<float>();
}
return ret;
}
float DiffAngle(float a, float b)
{
float diff = NormalizeAngle(a) - NormalizeAngle(b);
if (diff > glm::pi<float>())
{
return diff - glm::two_pi<float>();
}
else if (diff < -glm::pi<float>())
{
return diff + glm::two_pi<float>();
}
return diff;
}
float ClampAngle(float angle, float minAngle, float maxAngle)
{
if (minAngle == maxAngle)
{
return minAngle;
}
float ret = angle;
while (ret < minAngle)
{
ret += glm::two_pi<float>();
}
if (ret < maxAngle)
{
return ret;
}
while (ret > maxAngle)
{
ret -= glm::two_pi<float>();
}
if (ret > minAngle)
{
return ret;
}
float minDiff = std::abs(DiffAngle(minAngle, ret));
float maxDiff = std::abs(DiffAngle(maxAngle, ret));
if (minDiff < maxDiff)
{
return minAngle;
}
else
{
return maxAngle;
}
}
glm::vec3 Decompose(const glm::mat3& m, const glm::vec3& before)
{
glm::vec3 r;
float sy = -m[0][2];
const float e = 1.0e-6f;
if ((1.0f - std::abs(sy)) < e)
{
r.y = std::asin(sy);
// 180°に近いほうを探す
float sx = std::sin(before.x);
float sz = std::sin(before.z);
if (std::abs(sx) < std::abs(sz))
{
// Xのほうが0または180
float cx = std::cos(before.x);
if (cx > 0)
{
r.x = 0;
r.z = std::asin(-m[1][0]);
}
else
{
r.x = glm::pi<float>();
r.z = std::asin(m[1][0]);
}
}
else
{
float cz = std::cos(before.z);
if (cz > 0)
{
r.z = 0;
r.x = std::asin(-m[2][1]);
}
else
{
r.z = glm::pi<float>();
r.x = std::asin(m[2][1]);
}
}
}
else
{
r.x = std::atan2(m[1][2], m[2][2]);
r.y = std::asin(-m[0][2]);
r.z = std::atan2(m[0][1], m[0][0]);
}
const float pi = glm::pi<float>();
glm::vec3 tests[] =
{
{ r.x + pi, pi - r.y, r.z + pi },
{ r.x + pi, pi - r.y, r.z - pi },
{ r.x + pi, -pi - r.y, r.z + pi },
{ r.x + pi, -pi - r.y, r.z - pi },
{ r.x - pi, pi - r.y, r.z + pi },
{ r.x - pi, pi - r.y, r.z - pi },
{ r.x - pi, -pi - r.y, r.z + pi },
{ r.x - pi, -pi - r.y, r.z - pi },
};
float errX = std::abs(DiffAngle(r.x, before.x));
float errY = std::abs(DiffAngle(r.y, before.y));
float errZ = std::abs(DiffAngle(r.z, before.z));
float minErr = errX + errY + errZ;
for (const auto test : tests)
{
float err = std::abs(DiffAngle(test.x, before.x))
+ std::abs(DiffAngle(test.y, before.y))
+ std::abs(DiffAngle(test.z, before.z));
if (err < minErr)
{
minErr = err;
r = test;
}
}
return r;
}
}
void MMDIkSolver::SolveCore()
{
auto ikPos = glm::vec3(m_ikNode->m_global[3]);
for (auto& chain : m_chains)
{
MMDNode* chainNode = chain.m_node;
auto targetPos = glm::vec3(m_ikTarget->m_global[3]);
auto invChain = glm::inverse(chain.m_node->m_global);
auto chainIkPos = glm::vec3(invChain * glm::vec4(ikPos, 1));
auto chainTargetPos = glm::vec3(invChain * glm::vec4(targetPos, 1));
auto chainIkVec = glm::normalize(chainIkPos);
auto chainTargetVec = glm::normalize(chainTargetPos);
auto dot = glm::dot(chainTargetVec, chainIkVec);
if ((1.0f - dot) < std::numeric_limits<float>::epsilon())
{
continue;
}
float angle = std::acos(dot);
angle = glm::clamp(angle, -m_limitAngle, m_limitAngle);
auto cross = glm::cross(chainTargetVec, chainIkVec);
auto rot = glm::rotate(glm::quat(), angle, cross);
auto chainRotM = glm::mat3_cast(chainNode->m_ikRotate)
* glm::mat3_cast(chainNode->m_rotate)
* glm::mat3_cast(rot);
if (chain.m_enableAxisLimit)
{
auto rotXYZ = Decompose(chainRotM, chain.m_prevAngle);
glm::vec3 clampXYZ;
clampXYZ.x = ClampAngle(rotXYZ.x, chain.m_limitMin.x, chain.m_limitMax.x);
clampXYZ.y = ClampAngle(rotXYZ.y, chain.m_limitMin.y, chain.m_limitMax.y);
clampXYZ.z = ClampAngle(rotXYZ.z, chain.m_limitMin.z, chain.m_limitMax.z);
clampXYZ = glm::clamp(clampXYZ - chain.m_prevAngle, -m_limitAngle, m_limitAngle) + chain.m_prevAngle;
auto r = glm::rotate(glm::quat(), clampXYZ.x, glm::vec3(1, 0, 0));
r = glm::rotate(r, clampXYZ.y, glm::vec3(0, 1, 0));
r = glm::rotate(r, clampXYZ.z, glm::vec3(0, 0, 1));
chainRotM = glm::mat3_cast(r);
chain.m_prevAngle = clampXYZ;
}
auto ikRotM = chainRotM
* glm::inverse(glm::mat3_cast(chainNode->m_rotate));
chainNode->m_ikRotate = glm::quat_cast(ikRotM);
chainNode->UpdateLocalMatrix();
chainNode->UpdateGlobalMatrix();
}
}
}
<|endoftext|> |
<commit_before>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <[email protected]>
*
* the hover data code is largely inspired from the gtk redmond engine
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or(at your option ) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "oxygenhoverdata.h"
#include "../oxygengtkutils.h"
#include "../config.h"
#include <gtk/gtk.h>
#include <iostream>
namespace Oxygen
{
//________________________________________________________________________________
void HoverData::connect( GtkWidget* widget )
{
#if OXYGEN_DEBUG
std::cout << "HoverData::connect - " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")" << std::endl;
#endif
// on connection, needs to check whether mouse pointer is in widget or not
// to have the proper initial value of the hover flag
gint xPointer,yPointer;
gdk_window_get_pointer(widget->window,&xPointer,&yPointer, 0L);
setHovered( widget, Gtk::gdk_rectangle_contains( &widget->allocation, xPointer, yPointer ) );
// register callbacks
_enterId = g_signal_connect( G_OBJECT(widget), "enter-notify-event", G_CALLBACK( enterNotifyEvent ), this );
_leaveId = g_signal_connect( G_OBJECT(widget), "leave-notify-event", G_CALLBACK( leaveNotifyEvent ), this );
}
//________________________________________________________________________________
void HoverData::disconnect( GtkWidget* widget )
{
#if OXYGEN_DEBUG
std::cout << "HoverData::disconnect - " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")" << std::endl;
#endif
g_signal_handler_disconnect( G_OBJECT(widget), _enterId );
g_signal_handler_disconnect( G_OBJECT(widget), _leaveId );
}
//________________________________________________________________________________
gboolean HoverData::enterNotifyEvent(GtkWidget* widget, GdkEventCrossing*, gpointer data )
{
#if OXYGEN_DEBUG
std::cout << "HoverData::enterNotifyEvent - " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")" << std::endl;
#endif
static_cast<HoverData*>( data )->setHovered( widget, true );
return FALSE;
}
//________________________________________________________________________________
gboolean HoverData::leaveNotifyEvent( GtkWidget* widget, GdkEventCrossing*, gpointer data )
{
#if OXYGEN_DEBUG
std::cout << "HoverData::leaveNotifyEvent - " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")" << std::endl;
#endif
static_cast<HoverData*>( data )->setHovered( widget, false );
return FALSE;
}
}
<commit_msg>Fixed comments. Properly initialize hover flag at creation.<commit_after>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <[email protected]>
*
* the hover data code is largely inspired from the gtk redmond engine
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or(at your option ) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "oxygenhoverdata.h"
#include "../oxygengtkutils.h"
#include "../config.h"
#include <gtk/gtk.h>
#include <iostream>
namespace Oxygen
{
//________________________________________________________________________________
void HoverData::connect( GtkWidget* widget )
{
#if OXYGEN_DEBUG
std::cout << "Oxygen::HoverData::connect - " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")" << std::endl;
#endif
// on connection, needs to check whether mouse pointer is in widget or not
// to have the proper initial value of the hover flag
gint xPointer,yPointer;
gdk_window_get_pointer(widget->window,&xPointer,&yPointer, 0L);
GdkRectangle rect = { 0, 0, widget->allocation.width, widget->allocation.height };
setHovered( widget, Gtk::gdk_rectangle_contains( &rect, xPointer, yPointer ) );
// register callbacks
_enterId = g_signal_connect( G_OBJECT(widget), "enter-notify-event", G_CALLBACK( enterNotifyEvent ), this );
_leaveId = g_signal_connect( G_OBJECT(widget), "leave-notify-event", G_CALLBACK( leaveNotifyEvent ), this );
}
//________________________________________________________________________________
void HoverData::disconnect( GtkWidget* widget )
{
#if OXYGEN_DEBUG
std::cout << "HoverData::disconnect - " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")" << std::endl;
#endif
g_signal_handler_disconnect( G_OBJECT(widget), _enterId );
g_signal_handler_disconnect( G_OBJECT(widget), _leaveId );
}
//________________________________________________________________________________
gboolean HoverData::enterNotifyEvent(GtkWidget* widget, GdkEventCrossing*, gpointer data )
{
#if OXYGEN_DEBUG
std::cout << "HoverData::enterNotifyEvent - " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")" << std::endl;
#endif
static_cast<HoverData*>( data )->setHovered( widget, true );
return FALSE;
}
//________________________________________________________________________________
gboolean HoverData::leaveNotifyEvent( GtkWidget* widget, GdkEventCrossing*, gpointer data )
{
#if OXYGEN_DEBUG
std::cout << "Oxygen::HoverData::leaveNotifyEvent - " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")" << std::endl;
#endif
static_cast<HoverData*>( data )->setHovered( widget, false );
return FALSE;
}
}
<|endoftext|> |
<commit_before>// Project specific
#include <Game.hpp>
#include <Utility/DynamicLoader/Include/DynamicLoader.hpp>
/// Engine
// Core
#include <DoremiEngine/Core/Include/DoremiEngine.hpp>
#include <DoremiEngine/Core/Include/Subsystem/EngineModuleEnum.hpp>
#include <DoremiEngine/Core/Include/SharedContext.hpp>
// Physics
#include <DoremiEngine/Physics/Include/CharacterControlManager.hpp>
#include <DoremiEngine/Physics/Include/PhysicsModule.hpp>
#include <DoremiEngine/Physics/Include/RigidBodyManager.hpp>
#include <DoremiEngine/Physics/Include/FluidManager.hpp>
// AI
#include <DoremiEngine/AI/Include/AIModule.hpp>
#include <DoremiEngine/AI/Include/Interface/SubModule/PotentialFieldSubModule.hpp>
#include <DoremiEngine/AI/Include/Interface/PotentialField/PotentialFieldActor.hpp>
// GRAPHICS
#include <DoremiEngine/Graphic/Include/GraphicModule.hpp>
#include <DoremiEngine/Graphic/Include/Interface/Manager/DirectXManager.hpp>
// Inputmodule
#include <DoremiEngine/Input/Include/InputModule.hpp>
/// Game
// handlers
#include <Doremi/Core/Include/InterpolationHandler.hpp>
#include <Doremi/Core/Include/EventHandler/EventHandlerClient.hpp>
#include <Doremi/Core/Include/PlayerHandlerClient.hpp>
#include <Doremi/Core/Include/EntityComponent/EntityHandlerClient.hpp>
#include <Doremi/Core/Include/AudioHandler.hpp>
#include <Doremi/Core/Include/InputHandlerClient.hpp>
#include <Doremi/Core/Include/MenuClasses/MainMenuHandler.hpp>
#include <Doremi/Core/Include/NetworkEventSender.hpp>
#include <Doremi/Core/Include/CameraHandler.hpp>
#include <Doremi/Core/Include/PositionCorrectionHandler.hpp>
#include <Doremi/Core/Include/Handler/StateHandler.hpp>
#include <Doremi/Core/Include/PlayerSpawnerHandler.hpp>
#include <Doremi/Core/Include/TimeHandler.hpp>
#include <Doremi/Core/Include/MenuClasses/ServerBrowserHandler.hpp>
#include <Doremi/Core/Include/SkeletalInformationHandler.hpp>
// Managers
#include <Doremi/Core/Include/Manager/GraphicManager.hpp>
#include <Doremi/Core/Include/Manager/SkeletalAnimationCoreManager.hpp>
#include <Doremi/Core/Include/Network/NetworkManagerClient.hpp>
#include <Doremi/Core/Include/Manager/MovementManagerClient.hpp>
#include <Doremi/Core/Include/Manager/AudioManager.hpp>
#include <Doremi/Core/Include/Manager/AI/AIPathManager.hpp>
#include <Doremi/Core/Include/Manager/CharacterControlSyncManager.hpp>
#include <Doremi/Core/Include/Manager/RigidTransformSyncManager.hpp>
#include <Doremi/Core/Include/Manager/JumpManager.hpp>
#include <Doremi/Core/Include/SkyBoxHandler.hpp>
#include <Doremi/Core/Include/Manager/GravityManager.hpp>
#include <Doremi/Core/Include/Manager/PressureParticleGraphicManager.hpp>
#include <Doremi/Core/Include/Manager/PressureParticleManager.hpp>
#include <Doremi/Core/Include/Manager/LightManager.hpp>
#include <Doremi/Core/Include/Manager/TriggerManager.hpp>
#include <Doremi/Core/Include/Manager/ExtraDrainSyncManager.hpp>
#include <Doremi/Core/Include/Manager/GroundEffectManagerClient.hpp>
// Components
#include <Doremi/Core/Include/EntityComponent/Components/PhysicsMaterialComponent.hpp>
#include <Doremi/Core/Include/EntityComponent/Components/RigidBodyComponent.hpp>
#include <Doremi/Core/Include/EntityComponent/Components/PotentialFieldComponent.hpp>
#include <Doremi/Core/Include/EntityComponent/Components/PlatformPatrolComponent.hpp>
// Events
#include <Doremi/Core/Include/EventHandler/Events/ChangeMenuState.hpp>
// Other stuff
#include <Doremi/Core/Include/TemplateCreator.hpp>
#include <Doremi/Core/Include/LevelLoaderClient.hpp>
#include <Doremi/Core/Include/EntityComponent/EntityFactory.hpp>
#include <Doremi/Core/Include/ScreenSpaceDrawer.hpp>
// Timer
#include <Doremi/Core/Include/Timing/TimerManager.hpp>
#include <Utility/Utilities/Include/Chrono/Timer.hpp>
// Third party
// Standard libraries
#include <exception>
#include <chrono>
#include <vector>
#include <iostream> //TODOLH remove once all the functionality is implemented in the menusystem
namespace Doremi
{
using namespace Core;
GameMain::GameMain() : m_sharedContext(nullptr), m_gameRunning(true) {}
GameMain::~GameMain()
{
for(auto& manager : m_managers)
{
delete manager;
}
m_managers.clear();
for(auto& manager : m_graphicalManagers)
{
delete manager;
}
m_graphicalManagers.clear();
}
void GameMain::Initialize()
{
TIME_FUNCTION_START
using namespace Core;
const DoremiEngine::Core::SharedContext& sharedContext = InitializeEngine(DoremiEngine::Core::EngineModuleEnum::ALL);
m_sharedContext = &sharedContext;
m_sharedContext->GetInputModule().SetExitFunction(std::bind(&GameMain::Stop, this));
/* This starts the physics handler. Should not be done here, but since this is the general
code dump, it'll work for now TODOJB*/
EventHandlerClient::StartupEventHandlerClient();
EntityHandlerClient::StartupEntityHandlerClient(sharedContext);
PlayerHandlerClient::StartPlayerHandlerClient(sharedContext);
InterpolationHandler::StartInterpolationHandler(sharedContext);
AudioHandler::StartAudioHandler(sharedContext); // Needs to be stareted after event handler
StateHandler::StartStateHandler(sharedContext);
CameraHandler::StartCameraHandler(sharedContext);
PositionCorrectionHandler::StartPositionCorrectionHandler(sharedContext);
EntityFactory::StartupEntityFactory(sharedContext);
PlayerSpawnerHandler::StartupPlayerSpawnerHandler(sharedContext);
SkyBoxHandler::StartupSkyBoxHandler(sharedContext);
ServerBrowserHandler::StartupServerBrowserHandler(sharedContext);
SkeletalInformationHandler::StartSkeletalInformationHandler(sharedContext);
// Initialize 2d drawer class
m_screenRes = m_sharedContext->GetGraphicModule().GetSubModuleManager().GetDirectXManager().GetScreenResolution();
m_screenSpaceDrawer = new ScreenSpaceDrawer(sharedContext, m_screenRes);
// Create manager & add manager to list of managers
AddToGraphicalManagerList(new PressureParticleGraphicManager(sharedContext));
AddToGraphicalManagerList(new GraphicManager(sharedContext));
AddToGraphicalManagerList(new SkeletalAnimationCoreManager(sharedContext));
AddToManagerList(new AudioManager(sharedContext));
NetworkManagerClient* t_netManager = new NetworkManagerClient(sharedContext);
AddToManagerList(t_netManager);
AddToServerBrowserList(t_netManager);
AddToManagerList(new RigidTransformSyncManager(sharedContext));
AddToManagerList(new PressureParticleManager(sharedContext));
AddToManagerList(new LightManager(sharedContext));
AddToManagerList(new JumpManager(sharedContext));
AddToManagerList(new GravityManager(sharedContext));
AddToManagerList(new MovementManagerClient(sharedContext)); // Must be after gravity/jump
AddToManagerList(new CharacterControlSyncManager(sharedContext)); // Must be after movement
AddToManagerList(new TriggerManager(sharedContext)); // TODOKO should only be needed on server
AddToManagerList(new ExtraDrainSyncManager(sharedContext));
AddToGraphicalManagerList(new GroundEffectManagerClient(sharedContext));
MainMenuHandler::StartMainMenuHandler(sharedContext, m_screenRes);
MainMenuHandler::GetInstance()->Initialize();
TemplateCreator::GetInstance()->CreateTemplatesForClient(sharedContext);
// BuildWorld(sharedContext);
AudioHandler::GetInstance()->SetupContinuousRecording();
AudioHandler::GetInstance()->StartContinuousRecording();
AudioHandler::GetInstance()->SetupRepeatableRecording();
TIME_FUNCTION_STOP
}
void GameMain::AddToManagerList(Manager* p_manager) { m_managers.push_back(p_manager); }
void GameMain::AddToServerBrowserList(Manager* p_manager) { m_serverBrowserManagers.push_back(p_manager); }
void GameMain::AddToGraphicalManagerList(Manager* p_manager) { m_graphicalManagers.push_back(p_manager); }
void GameMain::BuildWorld(const DoremiEngine::Core::SharedContext& sharedContext)
{
// TIME_FUNCTION_START
// Core::EntityFactory& t_entityFactory = *Core::EntityFactory::GetInstance();
// Core::LevelLoaderClient t_levelLoader(sharedContext);
// t_levelLoader.LoadLevel("Levels/IntroScene.drm");
////// Create platforms
////for(size_t i = 0; i < 1; i++)
////{
//// int entityID = t_entityFactory.CreateEntity(Blueprints::PlatformEntity, DirectX::XMFLOAT3(-165.75f, 4.6f, -103.74f), XMFLOAT4(0, 0, 0,
/// 1));
//// DirectX::XMFLOAT3 position = DirectX::XMFLOAT3(-165.75f, 4.6f, -103.74f); // why not pass as parameter in above method?
//// DirectX::XMFLOAT4 orientation = XMFLOAT4(0, 0, 0, 1);
//// Core::PlatformPatrolComponent* t_platformPatrolComponent =
//// Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PlatformPatrolComponent>(entityID);
//// t_platformPatrolComponent->startPosition = position;
//// t_platformPatrolComponent->endPosition = DirectX::XMFLOAT3(position.x, position.y + 140, position.z);
////}
//// Create an enemy spawner (only necessary to keep entityIDs aligned with server)
// TIME_FUNCTION_STOP
}
void GameMain::Run()
{
TIME_FUNCTION_START
// TODOCM remove for better timer
// GameLoop is not currently set
TimeHandler* t_timeHandler = TimeHandler::GetInstance();
t_timeHandler->PreviousClock = std::chrono::high_resolution_clock::now();
while(m_gameRunning)
{
// Tick time
t_timeHandler->Tick();
// Loop as many update-steps we will take this frame
while(m_gameRunning && t_timeHandler->ShouldUpdateFrame())
{
// Update game based on state
Update(t_timeHandler->UpdateStepLen);
// Update interpolation transforms from snapshots
Core::InterpolationHandler::GetInstance()->UpdateInterpolationTransforms();
// Deliver events
static_cast<Core::EventHandlerClient*>(Core::EventHandler::GetInstance())->DeliverEvents();
// Update accumulator and gametime
t_timeHandler->UpdateAccumulatorAndGameTime();
}
// Update alpha usd for inteprolation
double alpha = t_timeHandler->GetFrameAlpha();
// Interpolate the frames here
Core::InterpolationHandler::GetInstance()->InterpolateFrame(alpha);
// Update camera after we update positions
CameraHandler::GetInstance()->UpdateDraw();
Draw(t_timeHandler->Frame);
}
TIME_FUNCTION_STOP
}
void GameMain::UpdateGame(double p_deltaTime)
{
TIME_FUNCTION_START
size_t length = m_managers.size();
PlayerHandler::GetInstance()->Update(p_deltaTime);
// AudioHandler::GetInstance()->Update(p_deltaTime);
// Have all managers update
for(size_t i = 0; i < length; i++)
{
Doremi::Core::TimerManager::GetInstance().StartTimer(m_managers.at(i)->GetName());
m_managers.at(i)->Update(p_deltaTime);
Doremi::Core::TimerManager::GetInstance().StopTimer(m_managers.at(i)->GetName());
}
CameraHandler::GetInstance()->UpdateInput(p_deltaTime);
// PlayerHandler::GetInstance()->UpdateAddRemoveObjects();
TIME_FUNCTION_STOP
}
void GameMain::UpdateServerBrowser(double p_deltaTime)
{
TIME_FUNCTION_START
size_t length = m_serverBrowserManagers.size();
PlayerHandler::GetInstance()->Update(p_deltaTime);
// Have all managers update
for(size_t i = 0; i < length; i++)
{
Doremi::Core::TimerManager::GetInstance().StartTimer(m_managers.at(i)->GetName());
m_serverBrowserManagers.at(i)->Update(p_deltaTime);
Doremi::Core::TimerManager::GetInstance().StopTimer(m_managers.at(i)->GetName());
}
TIME_FUNCTION_STOP
}
void GameMain::Update(double p_deltaTime)
{
TIME_FUNCTION_START
static_cast<PlayerHandlerClient*>(Core::PlayerHandler::GetInstance())->UpdatePlayerInputs();
AudioHandler::GetInstance()->Update(p_deltaTime);
Core::DoremiGameStates t_state = Core::StateHandler::GetInstance()->GetState();
switch(t_state)
{
case Core::DoremiGameStates::MAINMENU:
{
// Update Menu Logic
MainMenuHandler::GetInstance()->Update(p_deltaTime);
break;
}
case Core::DoremiGameStates::SERVER_BROWSER:
{
// TODOCM maybe only run network manager
UpdateServerBrowser(p_deltaTime);
ServerBrowserHandler::GetInstance()->Update(p_deltaTime);
break;
}
case Core::DoremiGameStates::OPTIONS:
{
std::cout << "You clicked options button. It has no effect. State changed back to MAINMENU" << std::endl;
// State is changed with events TODOXX should be removed from here once options is implemented
Core::ChangeMenuState* menuEvent = new Core::ChangeMenuState();
menuEvent->state = Core::DoremiGameStates::MAINMENU;
Core::EventHandler::GetInstance()->BroadcastEvent(menuEvent);
break;
}
case Core::DoremiGameStates::RUNGAME:
{
// Update Game logic
UpdateGame(p_deltaTime);
break;
}
case Core::DoremiGameStates::PAUSE:
{
// Update Pause Screen
break;
}
case Core::DoremiGameStates::EXIT:
{
m_gameRunning = false;
break;
}
default:
{
break;
}
}
TIME_FUNCTION_STOP
}
void GameMain::DrawGame(double p_deltaTime)
{
TIME_FUNCTION_START
const size_t length = m_graphicalManagers.size();
for(size_t i = 0; i < length; i++)
{
Doremi::Core::TimerManager::GetInstance().StartTimer(m_graphicalManagers.at(i)->GetName());
m_graphicalManagers.at(i)->Update(p_deltaTime);
Doremi::Core::TimerManager::GetInstance().StopTimer(m_graphicalManagers.at(i)->GetName());
}
SkyBoxHandler::GetInstance()->Draw();
TIME_FUNCTION_STOP
}
void GameMain::Draw(double p_deltaTime)
{
TIME_FUNCTION_START
/** TODOLH Detta ska flyttas till en function som i updaten*/
Core::DoremiGameStates t_state = Core::StateHandler::GetInstance()->GetState();
m_sharedContext->GetGraphicModule().GetSubModuleManager().GetDirectXManager().BeginDraw();
switch(t_state)
{
case Core::DoremiGameStates::RUNGAME:
// Draw Game
DrawGame(p_deltaTime);
break;
default:
break;
}
// WE always draw 2d stuff
m_screenSpaceDrawer->Draw();
m_sharedContext->GetGraphicModule().GetSubModuleManager().GetDirectXManager().EndDraw();
TIME_FUNCTION_STOP
}
void GameMain::Start()
{
try
{
TIME_FUNCTION_START
Initialize();
Run();
TIME_FUNCTION_STOP
}
catch(...)
{
printf("Gamemain start exception.\n");
}
Doremi::Core::TimerManager::GetInstance().DumpData(*m_sharedContext);
}
void GameMain::Stop()
{
Core::ChangeMenuState* menuEvent = new Core::ChangeMenuState();
menuEvent->state = Core::DoremiGameStates::EXIT;
Core::EventHandler::GetInstance()->BroadcastEvent(menuEvent);
}
}<commit_msg>Fixed copy paste error for managertiming<commit_after>// Project specific
#include <Game.hpp>
#include <Utility/DynamicLoader/Include/DynamicLoader.hpp>
/// Engine
// Core
#include <DoremiEngine/Core/Include/DoremiEngine.hpp>
#include <DoremiEngine/Core/Include/Subsystem/EngineModuleEnum.hpp>
#include <DoremiEngine/Core/Include/SharedContext.hpp>
// Physics
#include <DoremiEngine/Physics/Include/CharacterControlManager.hpp>
#include <DoremiEngine/Physics/Include/PhysicsModule.hpp>
#include <DoremiEngine/Physics/Include/RigidBodyManager.hpp>
#include <DoremiEngine/Physics/Include/FluidManager.hpp>
// AI
#include <DoremiEngine/AI/Include/AIModule.hpp>
#include <DoremiEngine/AI/Include/Interface/SubModule/PotentialFieldSubModule.hpp>
#include <DoremiEngine/AI/Include/Interface/PotentialField/PotentialFieldActor.hpp>
// GRAPHICS
#include <DoremiEngine/Graphic/Include/GraphicModule.hpp>
#include <DoremiEngine/Graphic/Include/Interface/Manager/DirectXManager.hpp>
// Inputmodule
#include <DoremiEngine/Input/Include/InputModule.hpp>
/// Game
// handlers
#include <Doremi/Core/Include/InterpolationHandler.hpp>
#include <Doremi/Core/Include/EventHandler/EventHandlerClient.hpp>
#include <Doremi/Core/Include/PlayerHandlerClient.hpp>
#include <Doremi/Core/Include/EntityComponent/EntityHandlerClient.hpp>
#include <Doremi/Core/Include/AudioHandler.hpp>
#include <Doremi/Core/Include/InputHandlerClient.hpp>
#include <Doremi/Core/Include/MenuClasses/MainMenuHandler.hpp>
#include <Doremi/Core/Include/NetworkEventSender.hpp>
#include <Doremi/Core/Include/CameraHandler.hpp>
#include <Doremi/Core/Include/PositionCorrectionHandler.hpp>
#include <Doremi/Core/Include/Handler/StateHandler.hpp>
#include <Doremi/Core/Include/PlayerSpawnerHandler.hpp>
#include <Doremi/Core/Include/TimeHandler.hpp>
#include <Doremi/Core/Include/MenuClasses/ServerBrowserHandler.hpp>
#include <Doremi/Core/Include/SkeletalInformationHandler.hpp>
// Managers
#include <Doremi/Core/Include/Manager/GraphicManager.hpp>
#include <Doremi/Core/Include/Manager/SkeletalAnimationCoreManager.hpp>
#include <Doremi/Core/Include/Network/NetworkManagerClient.hpp>
#include <Doremi/Core/Include/Manager/MovementManagerClient.hpp>
#include <Doremi/Core/Include/Manager/AudioManager.hpp>
#include <Doremi/Core/Include/Manager/AI/AIPathManager.hpp>
#include <Doremi/Core/Include/Manager/CharacterControlSyncManager.hpp>
#include <Doremi/Core/Include/Manager/RigidTransformSyncManager.hpp>
#include <Doremi/Core/Include/Manager/JumpManager.hpp>
#include <Doremi/Core/Include/SkyBoxHandler.hpp>
#include <Doremi/Core/Include/Manager/GravityManager.hpp>
#include <Doremi/Core/Include/Manager/PressureParticleGraphicManager.hpp>
#include <Doremi/Core/Include/Manager/PressureParticleManager.hpp>
#include <Doremi/Core/Include/Manager/LightManager.hpp>
#include <Doremi/Core/Include/Manager/TriggerManager.hpp>
#include <Doremi/Core/Include/Manager/ExtraDrainSyncManager.hpp>
#include <Doremi/Core/Include/Manager/GroundEffectManagerClient.hpp>
// Components
#include <Doremi/Core/Include/EntityComponent/Components/PhysicsMaterialComponent.hpp>
#include <Doremi/Core/Include/EntityComponent/Components/RigidBodyComponent.hpp>
#include <Doremi/Core/Include/EntityComponent/Components/PotentialFieldComponent.hpp>
#include <Doremi/Core/Include/EntityComponent/Components/PlatformPatrolComponent.hpp>
// Events
#include <Doremi/Core/Include/EventHandler/Events/ChangeMenuState.hpp>
// Other stuff
#include <Doremi/Core/Include/TemplateCreator.hpp>
#include <Doremi/Core/Include/LevelLoaderClient.hpp>
#include <Doremi/Core/Include/EntityComponent/EntityFactory.hpp>
#include <Doremi/Core/Include/ScreenSpaceDrawer.hpp>
// Timer
#include <Doremi/Core/Include/Timing/TimerManager.hpp>
#include <Utility/Utilities/Include/Chrono/Timer.hpp>
// Third party
// Standard libraries
#include <exception>
#include <chrono>
#include <vector>
#include <iostream> //TODOLH remove once all the functionality is implemented in the menusystem
namespace Doremi
{
using namespace Core;
GameMain::GameMain() : m_sharedContext(nullptr), m_gameRunning(true) {}
GameMain::~GameMain()
{
for(auto& manager : m_managers)
{
delete manager;
}
m_managers.clear();
for(auto& manager : m_graphicalManagers)
{
delete manager;
}
m_graphicalManagers.clear();
}
void GameMain::Initialize()
{
TIME_FUNCTION_START
using namespace Core;
const DoremiEngine::Core::SharedContext& sharedContext = InitializeEngine(DoremiEngine::Core::EngineModuleEnum::ALL);
m_sharedContext = &sharedContext;
m_sharedContext->GetInputModule().SetExitFunction(std::bind(&GameMain::Stop, this));
/* This starts the physics handler. Should not be done here, but since this is the general
code dump, it'll work for now TODOJB*/
EventHandlerClient::StartupEventHandlerClient();
EntityHandlerClient::StartupEntityHandlerClient(sharedContext);
PlayerHandlerClient::StartPlayerHandlerClient(sharedContext);
InterpolationHandler::StartInterpolationHandler(sharedContext);
AudioHandler::StartAudioHandler(sharedContext); // Needs to be stareted after event handler
StateHandler::StartStateHandler(sharedContext);
CameraHandler::StartCameraHandler(sharedContext);
PositionCorrectionHandler::StartPositionCorrectionHandler(sharedContext);
EntityFactory::StartupEntityFactory(sharedContext);
PlayerSpawnerHandler::StartupPlayerSpawnerHandler(sharedContext);
SkyBoxHandler::StartupSkyBoxHandler(sharedContext);
ServerBrowserHandler::StartupServerBrowserHandler(sharedContext);
SkeletalInformationHandler::StartSkeletalInformationHandler(sharedContext);
// Initialize 2d drawer class
m_screenRes = m_sharedContext->GetGraphicModule().GetSubModuleManager().GetDirectXManager().GetScreenResolution();
m_screenSpaceDrawer = new ScreenSpaceDrawer(sharedContext, m_screenRes);
// Create manager & add manager to list of managers
AddToGraphicalManagerList(new PressureParticleGraphicManager(sharedContext));
AddToGraphicalManagerList(new GraphicManager(sharedContext));
AddToGraphicalManagerList(new SkeletalAnimationCoreManager(sharedContext));
AddToManagerList(new AudioManager(sharedContext));
NetworkManagerClient* t_netManager = new NetworkManagerClient(sharedContext);
AddToManagerList(t_netManager);
AddToServerBrowserList(t_netManager);
AddToManagerList(new RigidTransformSyncManager(sharedContext));
AddToManagerList(new PressureParticleManager(sharedContext));
AddToManagerList(new LightManager(sharedContext));
AddToManagerList(new JumpManager(sharedContext));
AddToManagerList(new GravityManager(sharedContext));
AddToManagerList(new MovementManagerClient(sharedContext)); // Must be after gravity/jump
AddToManagerList(new CharacterControlSyncManager(sharedContext)); // Must be after movement
AddToManagerList(new TriggerManager(sharedContext)); // TODOKO should only be needed on server
AddToManagerList(new ExtraDrainSyncManager(sharedContext));
AddToGraphicalManagerList(new GroundEffectManagerClient(sharedContext));
MainMenuHandler::StartMainMenuHandler(sharedContext, m_screenRes);
MainMenuHandler::GetInstance()->Initialize();
TemplateCreator::GetInstance()->CreateTemplatesForClient(sharedContext);
// BuildWorld(sharedContext);
AudioHandler::GetInstance()->SetupContinuousRecording();
AudioHandler::GetInstance()->StartContinuousRecording();
AudioHandler::GetInstance()->SetupRepeatableRecording();
TIME_FUNCTION_STOP
}
void GameMain::AddToManagerList(Manager* p_manager) { m_managers.push_back(p_manager); }
void GameMain::AddToServerBrowserList(Manager* p_manager) { m_serverBrowserManagers.push_back(p_manager); }
void GameMain::AddToGraphicalManagerList(Manager* p_manager) { m_graphicalManagers.push_back(p_manager); }
void GameMain::BuildWorld(const DoremiEngine::Core::SharedContext& sharedContext)
{
// TIME_FUNCTION_START
// Core::EntityFactory& t_entityFactory = *Core::EntityFactory::GetInstance();
// Core::LevelLoaderClient t_levelLoader(sharedContext);
// t_levelLoader.LoadLevel("Levels/IntroScene.drm");
////// Create platforms
////for(size_t i = 0; i < 1; i++)
////{
//// int entityID = t_entityFactory.CreateEntity(Blueprints::PlatformEntity, DirectX::XMFLOAT3(-165.75f, 4.6f, -103.74f), XMFLOAT4(0, 0, 0,
/// 1));
//// DirectX::XMFLOAT3 position = DirectX::XMFLOAT3(-165.75f, 4.6f, -103.74f); // why not pass as parameter in above method?
//// DirectX::XMFLOAT4 orientation = XMFLOAT4(0, 0, 0, 1);
//// Core::PlatformPatrolComponent* t_platformPatrolComponent =
//// Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PlatformPatrolComponent>(entityID);
//// t_platformPatrolComponent->startPosition = position;
//// t_platformPatrolComponent->endPosition = DirectX::XMFLOAT3(position.x, position.y + 140, position.z);
////}
//// Create an enemy spawner (only necessary to keep entityIDs aligned with server)
// TIME_FUNCTION_STOP
}
void GameMain::Run()
{
TIME_FUNCTION_START
// TODOCM remove for better timer
// GameLoop is not currently set
TimeHandler* t_timeHandler = TimeHandler::GetInstance();
t_timeHandler->PreviousClock = std::chrono::high_resolution_clock::now();
while(m_gameRunning)
{
// Tick time
t_timeHandler->Tick();
// Loop as many update-steps we will take this frame
while(m_gameRunning && t_timeHandler->ShouldUpdateFrame())
{
// Update game based on state
Update(t_timeHandler->UpdateStepLen);
// Update interpolation transforms from snapshots
Core::InterpolationHandler::GetInstance()->UpdateInterpolationTransforms();
// Deliver events
static_cast<Core::EventHandlerClient*>(Core::EventHandler::GetInstance())->DeliverEvents();
// Update accumulator and gametime
t_timeHandler->UpdateAccumulatorAndGameTime();
}
// Update alpha usd for inteprolation
double alpha = t_timeHandler->GetFrameAlpha();
// Interpolate the frames here
Core::InterpolationHandler::GetInstance()->InterpolateFrame(alpha);
// Update camera after we update positions
CameraHandler::GetInstance()->UpdateDraw();
Draw(t_timeHandler->Frame);
}
TIME_FUNCTION_STOP
}
void GameMain::UpdateGame(double p_deltaTime)
{
TIME_FUNCTION_START
size_t length = m_managers.size();
PlayerHandler::GetInstance()->Update(p_deltaTime);
// AudioHandler::GetInstance()->Update(p_deltaTime);
// Have all managers update
for(size_t i = 0; i < length; i++)
{
Doremi::Core::TimerManager::GetInstance().StartTimer(m_managers.at(i)->GetName());
m_managers.at(i)->Update(p_deltaTime);
Doremi::Core::TimerManager::GetInstance().StopTimer(m_managers.at(i)->GetName());
}
CameraHandler::GetInstance()->UpdateInput(p_deltaTime);
// PlayerHandler::GetInstance()->UpdateAddRemoveObjects();
TIME_FUNCTION_STOP
}
void GameMain::UpdateServerBrowser(double p_deltaTime)
{
TIME_FUNCTION_START
size_t length = m_serverBrowserManagers.size();
PlayerHandler::GetInstance()->Update(p_deltaTime);
// Have all managers update
for(size_t i = 0; i < length; i++)
{
Doremi::Core::TimerManager::GetInstance().StartTimer(m_serverBrowserManagers.at(i)->GetName());
m_serverBrowserManagers.at(i)->Update(p_deltaTime);
Doremi::Core::TimerManager::GetInstance().StopTimer(m_serverBrowserManagers.at(i)->GetName());
}
TIME_FUNCTION_STOP
}
void GameMain::Update(double p_deltaTime)
{
TIME_FUNCTION_START
static_cast<PlayerHandlerClient*>(Core::PlayerHandler::GetInstance())->UpdatePlayerInputs();
AudioHandler::GetInstance()->Update(p_deltaTime);
Core::DoremiGameStates t_state = Core::StateHandler::GetInstance()->GetState();
switch(t_state)
{
case Core::DoremiGameStates::MAINMENU:
{
// Update Menu Logic
MainMenuHandler::GetInstance()->Update(p_deltaTime);
break;
}
case Core::DoremiGameStates::SERVER_BROWSER:
{
// TODOCM maybe only run network manager
UpdateServerBrowser(p_deltaTime);
ServerBrowserHandler::GetInstance()->Update(p_deltaTime);
break;
}
case Core::DoremiGameStates::OPTIONS:
{
std::cout << "You clicked options button. It has no effect. State changed back to MAINMENU" << std::endl;
// State is changed with events TODOXX should be removed from here once options is implemented
Core::ChangeMenuState* menuEvent = new Core::ChangeMenuState();
menuEvent->state = Core::DoremiGameStates::MAINMENU;
Core::EventHandler::GetInstance()->BroadcastEvent(menuEvent);
break;
}
case Core::DoremiGameStates::RUNGAME:
{
// Update Game logic
UpdateGame(p_deltaTime);
break;
}
case Core::DoremiGameStates::PAUSE:
{
// Update Pause Screen
break;
}
case Core::DoremiGameStates::EXIT:
{
m_gameRunning = false;
break;
}
default:
{
break;
}
}
TIME_FUNCTION_STOP
}
void GameMain::DrawGame(double p_deltaTime)
{
TIME_FUNCTION_START
const size_t length = m_graphicalManagers.size();
for(size_t i = 0; i < length; i++)
{
Doremi::Core::TimerManager::GetInstance().StartTimer(m_graphicalManagers.at(i)->GetName());
m_graphicalManagers.at(i)->Update(p_deltaTime);
Doremi::Core::TimerManager::GetInstance().StopTimer(m_graphicalManagers.at(i)->GetName());
}
SkyBoxHandler::GetInstance()->Draw();
TIME_FUNCTION_STOP
}
void GameMain::Draw(double p_deltaTime)
{
TIME_FUNCTION_START
/** TODOLH Detta ska flyttas till en function som i updaten*/
Core::DoremiGameStates t_state = Core::StateHandler::GetInstance()->GetState();
m_sharedContext->GetGraphicModule().GetSubModuleManager().GetDirectXManager().BeginDraw();
switch(t_state)
{
case Core::DoremiGameStates::RUNGAME:
// Draw Game
DrawGame(p_deltaTime);
break;
default:
break;
}
// WE always draw 2d stuff
m_screenSpaceDrawer->Draw();
m_sharedContext->GetGraphicModule().GetSubModuleManager().GetDirectXManager().EndDraw();
TIME_FUNCTION_STOP
}
void GameMain::Start()
{
try
{
TIME_FUNCTION_START
Initialize();
Run();
TIME_FUNCTION_STOP
}
catch(...)
{
printf("Gamemain start exception.\n");
}
Doremi::Core::TimerManager::GetInstance().DumpData(*m_sharedContext);
}
void GameMain::Stop()
{
Core::ChangeMenuState* menuEvent = new Core::ChangeMenuState();
menuEvent->state = Core::DoremiGameStates::EXIT;
Core::EventHandler::GetInstance()->BroadcastEvent(menuEvent);
}
}<|endoftext|> |
<commit_before>#include "inmost.h"
using namespace INMOST;
//todo: want to separate all faces into those that share edges
//see todo: inside text
int main(int argc, char ** argv)
{
if (argc < 2)
{
std::cout << "Usage: " << argv[0] << " mesh clusters [clusters=10] [max_iterations=10] [mesh_out=grid.vtk]" << std::endl;
return -1;
}
int K = 10;
if( argc > 2 ) K = atoi(argv[2]);
int max_iterations = 10;
if( argc > 3 ) max_iterations = atoi(argv[3]);
if( K == 0 )
std::cout << "Problem with number of clusters argument " << argv[2] << std::endl;
if( max_iterations == 0 )
std::cout << "Problem with max iterations argument " << argv[3] << std::endl;
std::string grid_out = "grid.vtk";
if (argc > 4) grid_out = std::string(argv[4]);
Mesh m;
m.Load(argv[1]);
std::cout << "Start:" << std::endl;
std::cout << "Cells: " << m.NumberOfCells() << std::endl;
std::cout << "Faces: " << m.NumberOfFaces() << std::endl;
std::cout << "Edges: " << m.NumberOfEdges() << std::endl;
double tt = Timer();
//There seems to be a problem with the mesh
/*
int fixed = 0;
for (Mesh::iteratorFace f = m.BeginFace(); f != m.EndFace(); ++f)
{
if (f->FixNormalOrientation())
fixed++;
}
std::cout << "Time to fix normals: " << Timer() - tt << std::endl;
std::cout << "Total face normals fixed: " << fixed << std::endl;
*/
int total_points = 0
#if defined(USE_OMP)
#pragma omp parallel for reduction(+:total_points)
#endif
for(int q = 0; q < m.CellLastLocalID(); ++q) if( m.isValidCell(q) )
{
Cell n = m.CellByLocalID(q);
if( n->GetStatus() != Element::Ghost ) total_points++;
}
std::vector< double > points_center(total_points*3);
std::vector< int > points_node(total_points);
std::vector< int > points_cluster(total_points,-1);
std::vector< double > cluster_center(K*3);
std::vector< int > cluster_npoints(K);
#if defined(USE_MPI)
std::vector< double > cluster_center_tmp(K*3);
std::vector< int > cluster_npoints_tmp(K);
#endif
int k = 0;
for(int q = 0; q < m.CellLastLocalID(); ++q) if( m.isValidCell(q) )
{
Cell n = m.CellByLocalID(q);
if( n->GetStatus() != Element::Ghost ) points_node[k++] = n->LocalID();
}
#if defined(USE_OMP)
#pragma omp paralell for
#endif
for(int q = 0; q < total_points; ++q)
{
Cell n = m.CellByLocalID(points_node[q]);
double cnt[3];
n->Centroid(cnt);
points_center[q*3+0] = cnt[0];
points_center[q*3+1] = cnt[1];
points_center[q*3+2] = cnt[2];
}
// choose K distinct values for the centers of the clusters
{
std::vector<int> prohibited_indexes;
int Kpart = (int)ceil((double)K/(double)m.GetProessorsNumber());
int Kstart = Kpart * m.GetProcessorRank();
int Kend = Kstart + Kpart;
if( Kend > K ) Kend = K;
for(int i = Kstart; i < Kend; i++)
{
while(true)
{
int index_point = rand() % total_points;
if(find(prohibited_indexes.begin(), prohibited_indexes.end(),
index_point) == prohibited_indexes.end())
{
prohibited_indexes.push_back(index_point);
cluster_center[i*3+0] = points_center[index_point*3+0];
cluster_center[i*3+1] = points_center[index_point*3+1];
cluster_center[i*3+2] = points_center[index_point*3+2];
points_cluster[index_point] = i;
break;
}
}
}
//guter cluster centers over all processes
#if defined(USE_MPI)
{
std::vector<int> recvcounts(m.GetProcessorNumber()), displs(m.GetProcessorNumber());
displs[0] = 0;
recvcounts[0] = Kpart*3;
for(int i = 1; i < (int)m.GetProcessorNumber(); ++i)
{
displs[i] = displs[i-1] + recvcounts[i-1];
recvcounts[i] = Kpart*3;
}
recvcounts.back() = K - displs.back();
MPI_Allgatherv(MPI_IN_PLACE,0,MPI_DATATYPE_NULL,&cluster_center[0],&recvcounts[0],&displs[0],MPI_DOUBLE,MPI_COMM_WORLD);
}
#endif
}
int iter = 1;
double t = Timer();
while(true)
{
int changed = 0;
// associates each point to the nearest center
#if defined(USE_OMP)
#pragma omp parallel for reduction(+:changed)
#endif
for(int i = 0; i < total_points; i++)
{
int id_old_cluster = points_cluster[i];
int id_nearest_center = -1;
double lmin = 1.0e+100;
for(int j = 0; j < K; ++j)
{
double v[3];
v[0] = (points_center[i*3+0] - cluster_center[j*3+0]);
v[1] = (points_center[i*3+1] - cluster_center[j*3+1]);
v[2] = (points_center[i*3+2] - cluster_center[j*3+2]);
double l = v[0]*v[0] + v[1]*v[1] + v[2]*v[2];
if( l < lmin )
{
lmin = l;
id_nearest_center = j;
}
}
if(id_old_cluster != id_nearest_center)
{
points_cluster[i] = id_nearest_center;
changed++;
}
}
#if defined(USE_MPI)
int tmp = changed;
MPI_Allreduce(&tmp,&changed,1,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
#endif
if(changed == 0 || iter >= max_iterations)
{
std::cout << "Break in iteration " << iter << std::endl;
break;
}
for(int i = 0; i < K; i++)
{
cluster_center[i*3+0] = 0;
cluster_center[i*3+1] = 0;
cluster_center[i*3+2] = 0;
cluster_npoints[i] = 0;
}
// recalculating the center of each cluster
#if defined(USE_OMP)
#pragma omp parallel
#endif
{
std::vector< double > local_sum(K*3,0.0);
std::vector< int > local_npoints(K,0);
for(int j = 0; j < total_points; ++j)
{
local_sum[points_cluster[j]*3+0] += points_center[j*3+0];
local_sum[points_cluster[j]*3+1] += points_center[j*3+1];
local_sum[points_cluster[j]*3+2] += points_center[j*3+2];
local_npoints[points_cluster[j]]++;
}
#if defined(USE_OMP)
#pragma omp critical
#endif
{
for(int i = 0; i < K; ++i)
{
cluster_center[i*3+0] += local_sum[i*3+0];
cluster_center[i*3+1] += local_sum[i*3+1];
cluster_center[i*3+2] += local_sum[i*3+2];
cluster_npoints[i] += local_npoints[i];
}
}
}
#if defined(USE_MPI)
MPI_Allreduce(&cluster_center[0],&cluster_center_tmp[0],K*3,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
MPI_Allreduce(&cluster_npoints[0],&cluster_npoints_tmp[0],K,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
cluster_center.swap(cluster_center_tmp);
cluster_npoints.swap(cluster_npoints_tmp);
#endif
for(int i = 0; i < K; i++)
{
cluster_center[i*3+0] /= (double) cluster_npoints[i];
cluster_center[i*3+1] /= (double) cluster_npoints[i];
cluster_center[i*3+2] /= (double) cluster_npoints[i];
}
std::cout << "Iteration " << iter << std::endl;
iter++;
}
std::cout << "Clustering in " << Timer() - t << " secs " << std::endl;
// shows elements of clusters
TagInteger mat = m.CreateTag("MATERIAL",DATA_INTEGER,CELL,NONE,1);
#if defined(USE_OMP)
#pragma omp parallel for
#endif
for(int j = 0; j < total_points; ++j)
mat[m.CellByLocalID(points_node[j])] = points_cluster[j]+1;
m.ExchangeData(mat,CELL,0);
m.Save(grid_out);
return 0;
}
<commit_msg>Fixes for parallel MPI-clustering<commit_after>#include "inmost.h"
using namespace INMOST;
//todo: want to separate all faces into those that share edges
//see todo: inside text
int main(int argc, char ** argv)
{
if (argc < 2)
{
std::cout << "Usage: " << argv[0] << " mesh clusters [clusters=10] [max_iterations=10] [mesh_out=grid.vtk]" << std::endl;
return -1;
}
Mesh::Initialize(&argc,&argv);
int K = 10;
if( argc > 2 ) K = atoi(argv[2]);
int max_iterations = 10;
if( argc > 3 ) max_iterations = atoi(argv[3]);
if( K == 0 )
std::cout << "Problem with number of clusters argument " << argv[2] << std::endl;
if( max_iterations == 0 )
std::cout << "Problem with max iterations argument " << argv[3] << std::endl;
std::string grid_out = "grid.vtk";
if (argc > 4) grid_out = std::string(argv[4]);
Mesh m;
m.SetCommunicator(INMOST_MPI_COMM_WORLD);
m.Load(argv[1]);
std::cout << "Start:" << std::endl;
std::cout << "Cells: " << m.NumberOfCells() << std::endl;
std::cout << "Faces: " << m.NumberOfFaces() << std::endl;
std::cout << "Edges: " << m.NumberOfEdges() << std::endl;
double tt = Timer();
//There seems to be a problem with the mesh
/*
int fixed = 0;
for (Mesh::iteratorFace f = m.BeginFace(); f != m.EndFace(); ++f)
{
if (f->FixNormalOrientation())
fixed++;
}
std::cout << "Time to fix normals: " << Timer() - tt << std::endl;
std::cout << "Total face normals fixed: " << fixed << std::endl;
*/
int total_points = 0, total_global_points = 0;
#if defined(USE_OMP)
#pragma omp parallel for reduction(+:total_points)
#endif
for(int q = 0; q < m.CellLastLocalID(); ++q) if( m.isValidCell(q) )
{
Cell n = m.CellByLocalID(q);
if( n->GetStatus() != Element::Ghost ) total_points++;
}
#if defined(USE_MPI)
MPI_Allreduce(&total_global_points,&total,points,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD)
#else
total_global_points = total_points;
#endif
std::vector< double > points_center(total_points*3);
std::vector< int > points_node(total_points);
std::vector< int > points_cluster(total_points,-1);
std::vector< double > cluster_center(K*3);
std::vector< int > cluster_npoints(K);
#if defined(USE_MPI)
std::vector< double > cluster_center_tmp(K*3);
std::vector< int > cluster_npoints_tmp(K);
#endif
int k = 0;
for(int q = 0; q < m.CellLastLocalID(); ++q) if( m.isValidCell(q) )
{
Cell n = m.CellByLocalID(q);
if( n->GetStatus() != Element::Ghost ) points_node[k++] = n->LocalID();
}
#if defined(USE_OMP)
#pragma omp paralell for
#endif
for(int q = 0; q < total_points; ++q)
{
Cell n = m.CellByLocalID(points_node[q]);
double cnt[3];
n->Centroid(cnt);
points_center[q*3+0] = cnt[0];
points_center[q*3+1] = cnt[1];
points_center[q*3+2] = cnt[2];
}
std::cout << m.GetProcessorRank() << " init clusters" << std::endl;
// choose K distinct values for the centers of the clusters
{
std::vector<int> prohibited_indexes;
int Kpart = (int)ceil((double)K/(double)m.GetProcessorsNumber());
int Kstart = Kpart * m.GetProcessorRank();
int Kend = Kstart + Kpart;
if( Kend > K ) Kend = K;
for(int i = Kstart; i < Kend; i++)
{
while(true)
{
int index_point = rand() % total_points;
if(find(prohibited_indexes.begin(), prohibited_indexes.end(),
index_point) == prohibited_indexes.end())
{
prohibited_indexes.push_back(index_point);
cluster_center[i*3+0] = points_center[index_point*3+0];
cluster_center[i*3+1] = points_center[index_point*3+1];
cluster_center[i*3+2] = points_center[index_point*3+2];
points_cluster[index_point] = i;
break;
}
}
}
//guter cluster centers over all processes
#if defined(USE_MPI)
{
std::vector<int> recvcounts(m.GetProcessorsNumber()), displs(m.GetProcessorsNumber());
displs[0] = 0;
recvcounts[0] = Kpart*3;
for(int i = 1; i < (int)m.GetProcessorsNumber(); ++i)
{
displs[i] = displs[i-1] + recvcounts[i-1];
recvcounts[i] = Kpart*3;
}
recvcounts.back() = K*3 - displs.back();
std::cout << m.GetProcessorRank() << " " << Kstart << " " << Kend << std::endl;
for(int i = 0; i < (int)m.GetProcessorsNumber(); ++i)
{
std::cout << m.GetProcessorRank() << " " << i << " " << displs[i] << " " << recvcounts[i] << std::endl;
}
for(int i = Kstart; i < Kend; ++i)
{
cluster_center_tmp[i*3+0] = cluster_center[i*3+0];
cluster_center_tmp[i*3+1] = cluster_center[i*3+1];
cluster_center_tmp[i*3+2] = cluster_center[i*3+2];
}
MPI_Allgatherv(&cluster_center_tmp[Kstart*3],(Kend-Kstart)*3,MPI_DOUBLE,&cluster_center[0],&recvcounts[0],&displs[0],MPI_DOUBLE,MPI_COMM_WORLD);
}
#endif
}
std::cout << m.GetProcessorRank() << " start clustering" << std::endl;
int iter = 1;
double t = Timer();
while(true)
{
int changed = 0;
// associates each point to the nearest center
#if defined(USE_OMP)
#pragma omp parallel for reduction(+:changed)
#endif
for(int i = 0; i < total_points; i++)
{
int id_old_cluster = points_cluster[i];
int id_nearest_center = -1;
double lmin = 1.0e+100;
for(int j = 0; j < K; ++j)
{
double v[3];
v[0] = (points_center[i*3+0] - cluster_center[j*3+0]);
v[1] = (points_center[i*3+1] - cluster_center[j*3+1]);
v[2] = (points_center[i*3+2] - cluster_center[j*3+2]);
double l = v[0]*v[0] + v[1]*v[1] + v[2]*v[2];
if( l < lmin )
{
lmin = l;
id_nearest_center = j;
}
}
if(id_old_cluster != id_nearest_center)
{
points_cluster[i] = id_nearest_center;
changed++;
}
}
#if defined(USE_MPI)
int tmp = changed;
MPI_Allreduce(&tmp,&changed,1,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
#endif
if(changed == 0 || iter >= max_iterations)
{
std::cout << m.GetProcessorRank() << " break in iteration " << iter << std::endl;
break;
}
for(int i = 0; i < K; i++)
{
cluster_center[i*3+0] = 0;
cluster_center[i*3+1] = 0;
cluster_center[i*3+2] = 0;
cluster_npoints[i] = 0;
}
// recalculating the center of each cluster
#if defined(USE_OMP)
#pragma omp parallel
#endif
{
std::vector< double > local_sum(K*3,0.0);
std::vector< int > local_npoints(K,0);
for(int j = 0; j < total_points; ++j)
{
local_sum[points_cluster[j]*3+0] += points_center[j*3+0];
local_sum[points_cluster[j]*3+1] += points_center[j*3+1];
local_sum[points_cluster[j]*3+2] += points_center[j*3+2];
local_npoints[points_cluster[j]]++;
}
#if defined(USE_OMP)
#pragma omp critical
#endif
{
for(int i = 0; i < K; ++i)
{
cluster_center[i*3+0] += local_sum[i*3+0];
cluster_center[i*3+1] += local_sum[i*3+1];
cluster_center[i*3+2] += local_sum[i*3+2];
cluster_npoints[i] += local_npoints[i];
}
}
}
#if defined(USE_MPI)
MPI_Allreduce(&cluster_center[0],&cluster_center_tmp[0],K*3,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
MPI_Allreduce(&cluster_npoints[0],&cluster_npoints_tmp[0],K,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
cluster_center.swap(cluster_center_tmp);
cluster_npoints.swap(cluster_npoints_tmp);
#endif
for(int i = 0; i < K; i++)
{
cluster_center[i*3+0] /= (double) cluster_npoints[i];
cluster_center[i*3+1] /= (double) cluster_npoints[i];
cluster_center[i*3+2] /= (double) cluster_npoints[i];
}
std::cout << "Iteration " << iter << std::endl;
iter++;
}
std::cout << "Clustering in " << Timer() - t << " secs " << std::endl;
// shows elements of clusters
TagInteger mat = m.CreateTag("MATERIAL",DATA_INTEGER,CELL,NONE,1);
#if defined(USE_OMP)
#pragma omp parallel for
#endif
for(int j = 0; j < total_points; ++j)
mat[m.CellByLocalID(points_node[j])] = points_cluster[j]+1;
m.ExchangeData(mat,CELL,0);
m.Save(grid_out);
Mesh::Finalize();
return 0;
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "CppUnitTest.h"
#include "Property.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace std;
using namespace FTL;
namespace FTLTest
{
class TestClass
{
public:
// Value
Property<TestClass, int, false, false, PropertyType::AutoGen> defaultProp;
Property<TestClass, int, true, true, PropertyType::Manual> prop1{ [this]() { return innerI1; }, [this](int val) { innerI1 = val * val; } };
Property<TestClass, int, false, true, PropertyType::Manual> prop2{ [this]() { return innerI2; }, [this](int val) { innerI2 = val * val; } };
Property<TestClass, int, true, false, PropertyType::Manual> prop3{ [this]() { return innerI3; }, [this](int val) { innerI3 = val * val; } };
Property<TestClass, int, false, false, PropertyType::Manual> prop4{ [this]() { return innerI4; }, [this](int val) { innerI4 = val * val; } };
int innerI1, innerI2, innerI3, innerI4;
int *pD, *p1, *p2, *p3, *p4;
int pID, pI1, pI2, pI3, pI4;
Property<TestClass, int*, false, false, PropertyType::AutoGen> pDefaultProp{ pD };
Property<TestClass, int*, true, true, PropertyType::Manual> pProp1{ [this]() { return p1; }, [this](int* val) { p1 = val; } };
Property<TestClass, int*, false, true, PropertyType::Manual> pProp2{ [this]() { return p2; }, [this](int* val) { p2 = val; } };
Property<TestClass, int*, true, false, PropertyType::Manual> pProp3{ [this]() { return p3; }, [this](int* val) { p3 = val; } };
Property<TestClass, int*, false, false, PropertyType::Manual> pProp4{ [this]() { return p4; }, [this](int* val) { p4 = val; } };
// Pointer
Property<TestClass, int*, false, false, PropertyType::AutoGen> ptrProp;
// Smart Pointer
Property<TestClass, shared_ptr<int>, false, false, PropertyType::AutoGen> smptrProp;
// Getter only
int goInnerValue;
Property <TestClass, int, false, false, PropertyType::GetterOnly> go{ [this]() { return goInnerValue; } };
// Setter only
int soInnerValue;
Property <TestClass, int, false, false, PropertyType::SetterOnly> so{ [this](int value) { soInnerValue = value; } };
void Test()
{
defaultProp = 0;
prop1 = 1;
prop2 = 2;
prop3 = 3;
prop4 = 4;
pDefaultProp = &pID;
pProp1 = &pI1;
pProp2 = &pI2;
pProp3 = &pI3;
pProp4 = &pI4;
*pDefaultProp = 0;
*pProp1 = 1;
*pProp2 = 2;
*pProp3 = 3;
*pProp4 = 4;
}
};
TEST_CLASS(PropertyTest)
{
public:
TEST_METHOD(PropertyTest1)
{
FTLTest::TestClass cls;
cls.Test();
// Getter privateness
Assert::AreEqual(false, IsGetterPrivate(cls.defaultProp, nullptr));
Assert::AreEqual(true, IsGetterPrivate(cls.prop1, nullptr));
Assert::AreEqual(false, IsGetterPrivate(cls.prop2, nullptr));
Assert::AreEqual(true, IsGetterPrivate(cls.prop3, nullptr));
Assert::AreEqual(false, IsGetterPrivate(cls.prop4, nullptr));
Assert::AreEqual(false, IsGetterPrivate(cls.pDefaultProp, nullptr));
Assert::AreEqual(true, IsGetterPrivate(cls.pProp1, nullptr));
Assert::AreEqual(false, IsGetterPrivate(cls.pProp2, nullptr));
Assert::AreEqual(true, IsGetterPrivate(cls.pProp3, nullptr));
Assert::AreEqual(false, IsGetterPrivate(cls.pProp4, nullptr));
// Setter privateness
Assert::AreEqual(false, IsSetterPrivate(cls.defaultProp, nullptr));
Assert::AreEqual(true, IsSetterPrivate(cls.prop1, nullptr));
Assert::AreEqual(true, IsSetterPrivate(cls.prop2, nullptr));
Assert::AreEqual(false, IsSetterPrivate(cls.prop3, nullptr));
Assert::AreEqual(false, IsSetterPrivate(cls.prop4, nullptr));
Assert::AreEqual(false, IsSetterPrivate(cls.pDefaultProp, nullptr));
Assert::AreEqual(true, IsSetterPrivate(cls.pProp1, nullptr));
Assert::AreEqual(true, IsSetterPrivate(cls.pProp2, nullptr));
Assert::AreEqual(false, IsSetterPrivate(cls.pProp3, nullptr));
Assert::AreEqual(false, IsSetterPrivate(cls.pProp4, nullptr));
}
TEST_METHOD(PropertyTest2)
{
FTLTest::TestClass cls;
cls.Test();
// Getter value
Assert::AreEqual(0, static_cast<int>(cls.defaultProp));
// Assert::AreEqual(1 * 1, static_cast<int>(cls.prop1)); // Compile error
Assert::AreEqual(2 * 2, static_cast<int>(cls.prop2));
// Assert::AreEqual(3 * 3, static_cast<int>(cls.prop3)); // Compile error
Assert::AreEqual(4 * 4, static_cast<int>(cls.prop4));
// Setter value
Assert::AreEqual(1, static_cast<int>(cls.defaultProp = 1));
// Assert::AreEqual(2 * 2, static_cast<int>(cls.prop1 = 2)); // Compile error
// Assert::AreEqual(3 * 3, static_cast<int>(cls.prop2 = 3)); // Compile error
Assert::AreEqual(4, static_cast<int>(cls.prop3 = 4));
Assert::AreEqual(5, static_cast<int>(cls.prop4 = 5));
// After set
Assert::AreEqual(1 * 1, static_cast<int>(cls.defaultProp));
// Assert::AreEqual(2 * 2, static_cast<int>(cls.prop1)); // Setter private, compile error
// Assert::AreEqual(3 * 3, static_cast<int>(cls.prop2)); // Setter private
// Assert::AreEqual(4 * 4, static_cast<int>(cls.prop3)); // Compile error
Assert::AreEqual(5 * 5, static_cast<int>(cls.prop4));
}
TEST_METHOD(PropertyTest3)
{
FTLTest::TestClass cls;
int dummyInt = 5555;
int dummyInt1 = 6666;
int dummyInt2 = 7777;
int dummyInt3 = 8888;
int dummyInt4 = 9999;
Assert::AreEqual(&dummyInt, static_cast<int*>(cls.pDefaultProp = &dummyInt));
// Assert::AreEqual(&dummyInt1, static_cast<int*>(cls.pProp1 = &dummyInt1)); // Compile error
// Assert::AreEqual(&dummyInt2, static_cast<int*>(cls.pProp2 = &dummyInt2)); // Compile error
Assert::AreEqual(&dummyInt3, static_cast<int*>(cls.pProp3 = &dummyInt3));
Assert::AreEqual(&dummyInt4, static_cast<int*>(cls.pProp4 = &dummyInt4));
}
TEST_METHOD(PropertyTest4)
{
FTLTest::TestClass cls;
cls.Test();
// Pointer dereference(getter)
Assert::AreEqual(0, static_cast<int>(*cls.pDefaultProp));
// Assert::AreEqual(1, static_cast<int>(*cls.pProp1)); // Compile error
Assert::AreEqual(2, static_cast<int>(*cls.pProp2));
// Assert::AreEqual(3, static_cast<int>(*cls.pProp3)); // Compile error
Assert::AreEqual(4, static_cast<int>(*cls.pProp4));
// Pointer deference(setter)
*cls.pDefaultProp = 10;
// *cls.pProp1 = 11; // Compile error
*cls.pProp2 = 12;
// *cls.pProp3 = 13; // Compile error
*cls.pProp4 = 14;
Assert::AreEqual(10, static_cast<int>(*cls.pDefaultProp));
// Assert::AreEqual(11, static_cast<int>(*cls.pProp1)); // Compile error
Assert::AreEqual(12, static_cast<int>(*cls.pProp2));
// Assert::AreEqual(13, static_cast<int>(*cls.pProp3)); // Compile error
Assert::AreEqual(14, static_cast<int>(*cls.pProp4));
}
TEST_METHOD(PropertyTest5)
{
FTLTest::TestClass cls;
cls.Test();
// Getter only
cls.goInnerValue = 3;
// cls.go = 4; // Compile error
Assert::AreEqual(3, cls.go.get());
// Setter only
cls.so = 6;
Assert::AreEqual(6, cls.soInnerValue);
// Assert::AreEqual(6, cls.so.get()); // Compile error
}
TEST_METHOD(PropertyTest6)
{
FTLTest::TestClass cls;
cls.Test();
Assert::AreEqual(false, cls.defaultProp.isPointer);
Assert::AreEqual(false, cls.prop1.isPointer);
Assert::AreEqual(false, cls.prop2.isPointer);
Assert::AreEqual(false, cls.prop3.isPointer);
Assert::AreEqual(false, cls.prop4.isPointer);
Assert::AreEqual(true, cls.pDefaultProp.isPointer);
Assert::AreEqual(true, cls.pProp1.isPointer);
Assert::AreEqual(true, cls.pProp2.isPointer);
Assert::AreEqual(true, cls.pProp3.isPointer);
Assert::AreEqual(true, cls.pProp4.isPointer);
Assert::AreEqual(true, cls.smptrProp.isPointer);
}
private:
template <class T>
constexpr bool IsGetterPrivate(const T&, ...) const
{
return true;
}
template <class T>
constexpr bool IsGetterPrivate(const T&, decltype(typename declval<T>().operator T::InterfaceType())* ptr) const
{
return false;
}
template <class T>
constexpr bool IsSetterPrivate(T&, ...) const
{
return true;
}
template <class T>
constexpr bool IsSetterPrivate(T& val, decltype(val = typename T::InterfaceType())* ptr) const
{
return false;
}
// Sealed due to Visual Studio C++ compiler's bug. Works well on clang.
/*
template <class T, class = void>
class IsGetterPrivate : public true_type {};
template <class T>
class IsGetterPrivate<T, VoidTemplate<decltype(typename declval<T>().operator T::Type())>> : public false_type {};
*/
};
}<commit_msg>TMP bug fix<commit_after>#include "stdafx.h"
#include "CppUnitTest.h"
#include "Property.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace std;
using namespace FTL;
namespace FTLTest
{
class TestClass
{
public:
// Value
Property<TestClass, int, false, false, PropertyType::AutoGen> defaultProp;
Property<TestClass, int, true, true, PropertyType::Manual> prop1{ [this]() { return innerI1; }, [this](int val) { innerI1 = val * val; } };
Property<TestClass, int, false, true, PropertyType::Manual> prop2{ [this]() { return innerI2; }, [this](int val) { innerI2 = val * val; } };
Property<TestClass, int, true, false, PropertyType::Manual> prop3{ [this]() { return innerI3; }, [this](int val) { innerI3 = val * val; } };
Property<TestClass, int, false, false, PropertyType::Manual> prop4{ [this]() { return innerI4; }, [this](int val) { innerI4 = val * val; } };
int innerI1, innerI2, innerI3, innerI4;
int *pD, *p1, *p2, *p3, *p4;
int pID, pI1, pI2, pI3, pI4;
Property<TestClass, int*, false, false, PropertyType::AutoGen> pDefaultProp{ pD };
Property<TestClass, int*, true, true, PropertyType::Manual> pProp1{ [this]() { return p1; }, [this](int* val) { p1 = val; } };
Property<TestClass, int*, false, true, PropertyType::Manual> pProp2{ [this]() { return p2; }, [this](int* val) { p2 = val; } };
Property<TestClass, int*, true, false, PropertyType::Manual> pProp3{ [this]() { return p3; }, [this](int* val) { p3 = val; } };
Property<TestClass, int*, false, false, PropertyType::Manual> pProp4{ [this]() { return p4; }, [this](int* val) { p4 = val; } };
// Pointer
Property<TestClass, int*, false, false, PropertyType::AutoGen> ptrProp;
// Smart Pointer
Property<TestClass, shared_ptr<int>, false, false, PropertyType::AutoGen> smptrProp;
// Getter only
int goInnerValue;
Property <TestClass, int, false, false, PropertyType::GetterOnly> go{ [this]() { return goInnerValue; } };
// Setter only
int soInnerValue;
Property <TestClass, int, false, false, PropertyType::SetterOnly> so{ [this](int value) { soInnerValue = value; } };
void Test()
{
defaultProp = 0;
prop1 = 1;
prop2 = 2;
prop3 = 3;
prop4 = 4;
pDefaultProp = &pID;
pProp1 = &pI1;
pProp2 = &pI2;
pProp3 = &pI3;
pProp4 = &pI4;
*pDefaultProp = 0;
*pProp1 = 1;
*pProp2 = 2;
*pProp3 = 3;
*pProp4 = 4;
}
};
TEST_CLASS(PropertyTest)
{
public:
TEST_METHOD(PropertyTest1)
{
FTLTest::TestClass cls;
cls.Test();
// Getter privateness
Assert::AreEqual(false, IsGetterPrivate(cls.defaultProp, nullptr));
Assert::AreEqual(true, IsGetterPrivate(cls.prop1, nullptr));
Assert::AreEqual(false, IsGetterPrivate(cls.prop2, nullptr));
Assert::AreEqual(true, IsGetterPrivate(cls.prop3, nullptr));
Assert::AreEqual(false, IsGetterPrivate(cls.prop4, nullptr));
Assert::AreEqual(false, IsGetterPrivate(cls.pDefaultProp, nullptr));
Assert::AreEqual(true, IsGetterPrivate(cls.pProp1, nullptr));
Assert::AreEqual(false, IsGetterPrivate(cls.pProp2, nullptr));
Assert::AreEqual(true, IsGetterPrivate(cls.pProp3, nullptr));
Assert::AreEqual(false, IsGetterPrivate(cls.pProp4, nullptr));
// Setter privateness
Assert::AreEqual(false, IsSetterPrivate(cls.defaultProp, nullptr));
Assert::AreEqual(true, IsSetterPrivate(cls.prop1, nullptr));
Assert::AreEqual(true, IsSetterPrivate(cls.prop2, nullptr));
Assert::AreEqual(false, IsSetterPrivate(cls.prop3, nullptr));
Assert::AreEqual(false, IsSetterPrivate(cls.prop4, nullptr));
Assert::AreEqual(false, IsSetterPrivate(cls.pDefaultProp, nullptr));
Assert::AreEqual(true, IsSetterPrivate(cls.pProp1, nullptr));
Assert::AreEqual(true, IsSetterPrivate(cls.pProp2, nullptr));
Assert::AreEqual(false, IsSetterPrivate(cls.pProp3, nullptr));
Assert::AreEqual(false, IsSetterPrivate(cls.pProp4, nullptr));
}
TEST_METHOD(PropertyTest2)
{
FTLTest::TestClass cls;
cls.Test();
// Getter value
Assert::AreEqual(0, static_cast<int>(cls.defaultProp));
// Assert::AreEqual(1 * 1, static_cast<int>(cls.prop1)); // Compile error
Assert::AreEqual(2 * 2, static_cast<int>(cls.prop2));
// Assert::AreEqual(3 * 3, static_cast<int>(cls.prop3)); // Compile error
Assert::AreEqual(4 * 4, static_cast<int>(cls.prop4));
// Setter value
Assert::AreEqual(1, static_cast<int>(cls.defaultProp = 1));
// Assert::AreEqual(2 * 2, static_cast<int>(cls.prop1 = 2)); // Compile error
// Assert::AreEqual(3 * 3, static_cast<int>(cls.prop2 = 3)); // Compile error
Assert::AreEqual(4, static_cast<int>(cls.prop3 = 4));
Assert::AreEqual(5, static_cast<int>(cls.prop4 = 5));
// After set
Assert::AreEqual(1 * 1, static_cast<int>(cls.defaultProp));
// Assert::AreEqual(2 * 2, static_cast<int>(cls.prop1)); // Setter private, compile error
// Assert::AreEqual(3 * 3, static_cast<int>(cls.prop2)); // Setter private
// Assert::AreEqual(4 * 4, static_cast<int>(cls.prop3)); // Compile error
Assert::AreEqual(5 * 5, static_cast<int>(cls.prop4));
}
TEST_METHOD(PropertyTest3)
{
FTLTest::TestClass cls;
int dummyInt = 5555;
int dummyInt1 = 6666;
int dummyInt2 = 7777;
int dummyInt3 = 8888;
int dummyInt4 = 9999;
Assert::AreEqual(&dummyInt, static_cast<int*>(cls.pDefaultProp = &dummyInt));
// Assert::AreEqual(&dummyInt1, static_cast<int*>(cls.pProp1 = &dummyInt1)); // Compile error
// Assert::AreEqual(&dummyInt2, static_cast<int*>(cls.pProp2 = &dummyInt2)); // Compile error
Assert::AreEqual(&dummyInt3, static_cast<int*>(cls.pProp3 = &dummyInt3));
Assert::AreEqual(&dummyInt4, static_cast<int*>(cls.pProp4 = &dummyInt4));
}
TEST_METHOD(PropertyTest4)
{
FTLTest::TestClass cls;
cls.Test();
// Pointer dereference(getter)
Assert::AreEqual(0, static_cast<int>(*cls.pDefaultProp));
// Assert::AreEqual(1, static_cast<int>(*cls.pProp1)); // Compile error
Assert::AreEqual(2, static_cast<int>(*cls.pProp2));
// Assert::AreEqual(3, static_cast<int>(*cls.pProp3)); // Compile error
Assert::AreEqual(4, static_cast<int>(*cls.pProp4));
// Pointer deference(setter)
*cls.pDefaultProp = 10;
// *cls.pProp1 = 11; // Compile error
*cls.pProp2 = 12;
// *cls.pProp3 = 13; // Compile error
*cls.pProp4 = 14;
Assert::AreEqual(10, static_cast<int>(*cls.pDefaultProp));
// Assert::AreEqual(11, static_cast<int>(*cls.pProp1)); // Compile error
Assert::AreEqual(12, static_cast<int>(*cls.pProp2));
// Assert::AreEqual(13, static_cast<int>(*cls.pProp3)); // Compile error
Assert::AreEqual(14, static_cast<int>(*cls.pProp4));
}
TEST_METHOD(PropertyTest5)
{
FTLTest::TestClass cls;
cls.Test();
// Getter only
cls.goInnerValue = 3;
// cls.go = 4; // Compile error
Assert::AreEqual(3, cls.go.get());
// Setter only
cls.so = 6;
Assert::AreEqual(6, cls.soInnerValue);
// Assert::AreEqual(6, cls.so.get()); // Compile error
}
TEST_METHOD(PropertyTest6)
{
FTLTest::TestClass cls;
cls.Test();
Assert::AreEqual(false, cls.defaultProp.isPointer);
Assert::AreEqual(false, cls.prop1.isPointer);
Assert::AreEqual(false, cls.prop2.isPointer);
Assert::AreEqual(false, cls.prop3.isPointer);
Assert::AreEqual(false, cls.prop4.isPointer);
Assert::AreEqual(true, cls.pDefaultProp.isPointer);
Assert::AreEqual(true, cls.pProp1.isPointer);
Assert::AreEqual(true, cls.pProp2.isPointer);
Assert::AreEqual(true, cls.pProp3.isPointer);
Assert::AreEqual(true, cls.pProp4.isPointer);
Assert::AreEqual(true, cls.smptrProp.isPointer);
}
private:
template <class T>
constexpr bool IsGetterPrivate(const T&, ...) const
{
return true;
}
template <class T>
constexpr bool IsGetterPrivate(const T&, decltype(declval<T>().operator typename T::InterfaceType())* ptr) const
{
return false;
}
template <class T>
constexpr bool IsSetterPrivate(T&, ...) const
{
return true;
}
template <class T>
constexpr bool IsSetterPrivate(T& val, decltype(val = typename T::InterfaceType())* ptr) const
{
return false;
}
// Sealed due to Visual Studio C++ compiler's bug. Works well on clang.
/*
template <class T, class = void>
class IsGetterPrivate : public true_type {};
template <class T>
class IsGetterPrivate<T, VoidTemplate<decltype(typename declval<T>().operator T::Type())>> : public false_type {};
*/
};
}<|endoftext|> |
<commit_before>#include "ship_instance.h"
#include "weapon_instance.h"
ShipCarrier::ShipCarrier(int id, std::vector<float> d) : Ship(id, 1000, 400, d, 9.5, 1000, 1, 1) {
this->add_weapon(new WeaponStandardGun());
this->add_weapon(new WeaponStandardCannon());
}
ShipScout::ShipScout(int id, std::vector<float> d) : Ship(id, 200, 100, d, .2, 500, .5, .5) {
this->add_weapon(new WeaponStandardGun());
}
ShipFighter::ShipFighter(int id, std::vector<float> d) : Ship(id, 400, 200, d, .4, 200, .5, .5) {
this->add_weapon(new WeaponStandardGun());
this->add_weapon(new WeaponStandardCannon());
}
<commit_msg>changed rotation speeds<commit_after>#include "ship_instance.h"
#include "weapon_instance.h"
ShipCarrier::ShipCarrier(int id, std::vector<float> d) : Ship(id, 1000, 400, d, 9.5, 1000, 1.5, 1.5) {
this->add_weapon(new WeaponStandardGun());
this->add_weapon(new WeaponStandardCannon());
}
ShipScout::ShipScout(int id, std::vector<float> d) : Ship(id, 200, 100, d, .2, 500, 1.5,1.5) {
this->add_weapon(new WeaponStandardGun());
}
ShipFighter::ShipFighter(int id, std::vector<float> d) : Ship(id, 400, 200, d, .4, 200, 1.5, 1.5) {
this->add_weapon(new WeaponStandardGun());
this->add_weapon(new WeaponStandardCannon());
}
<|endoftext|> |
<commit_before>/*****************************************************************************
// * This source file is part of ArkGameFrame *
// * For the latest info, see https://github.com/ArkGame *
// * *
// * Copyright(c) 2013 - 2017 ArkGame 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. *
// * *
// * *
// * @file AFPlatform.h *
// * @author Ark Game Tech *
// * @date 2015-12-15 *
// * @brief AFPlatform *
*****************************************************************************/
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <math.h>
#include <assert.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <cstring>
#include <vector>
#include <map>
#include <list>
#include <set>
#include <deque>
#include <limits>
#include <algorithm>
#include <utility>
#include <functional>
#include <cctype>
#include <iterator>
#include <unordered_map>
#include <stdint.h>
#include <functional>
#include <memory>
#include <signal.h>
#include <chrono>
#include <sstream>
#include <random>
#include <thread>
#if defined(__WIN32__) || defined(WIN32) || defined(_WIN32) || defined(__WIN64__) || defined(WIN64) || defined(_WIN64)
// only windows include
#include <io.h>
#include <time.h>
#ifndef WIN32_LEAN_AND_MEAN
#include <WinSock2.h>
#include <MSWSock.h>
#define WIN32_LEAN_AND_MEAN
#endif // WIN32_LEAN_AND_MEAN
#include <windows.h>
#define _SCL_SECURE_NO_WARNINGS
#define SIGHUP 1
#define SIGINT 2
#define SIGQUIT 3
#define SIGUSR1 10
#define SIGPIPE 13
#define SIGCHLD 17
#define SIGSYS 32
#else
// only other unix/linux include
#include <sys/socket.h>
#endif
#define ARK_LITTLE_ENDIAN
#define ARK_BIG_ENDIAN
#if !defined(ARK_ENDIAN)
# if defined(USE_BIG_ENDIAN)
# define ARK_ENDIAN ARK_BIG_ENDIAN
# else
# define ARK_ENDIAN ARK_LITTLE_ENDIAN
# endif
#endif // !defined(ARK_ENDIAN)
#define PLATFORM_WIN 0
#define PLATFORM_UNIX 1
#define PLATFORM_APPLE 2
#define UNIX_FLAVOUR_LINUX 1
#define UNIX_FLAVOUR_BSD 2
#define UNIX_FLAVOUR_OTHER 3
#define UNIX_FLAVOUR_OSX 4
#if defined(__WIN32__) || defined(WIN32) || defined(_WIN32) || defined(__WIN64__) || defined(WIN64) || defined(_WIN64)
# define ARK_PLATFORM PLATFORM_WIN
#elif defined(__APPLE_CC__)
# define ARK_PLATFORM PLATFORM_APPLE
#else
# define ARK_PLATFORM PLATFORM_UNIX
#endif
#define COMPILER_MICROSOFT 0
#define COMPILER_GNU 1
#define COMPILER_BORLAND 2
#define COMPILER_INTEL 3
#define COMPILER_CLANG 4
#define GOOGLE_STRIP_LOG 2
#ifdef _MSC_VER
# define ARK_COMPILER COMPILER_MICROSOFT
#elif defined(__INTEL_COMPILER)
# define ARK_COMPILER COMPILER_INTEL
#elif defined(__BORLANDC__)
# define ARK_COMPILER COMPILER_BORLAND
#elif defined(__GNUC__)
# define ARK_COMPILER COMPILER_GNU
#elif defined( __clang__ )
# define ARK_COMPILER COMPILER_CLANG
#else
# pragma error "FATAL ERROR: Unknown compiler."
#endif
#if ARK_PLATFORM == PLATFORM_UNIX || ARK_PLATFORM == PLATFORM_APPLE
# if defined(HAVE_DARWIN)
# define ARK_PLATFORM_NAME "MacOSX"
# define UNIX_FLAVOUR UNIX_FLAVOUR_OSX
# elif defined(USE_KQUEUE)
# define ARK_PLATFORM_NAME "FreeBSD"
# define UNIX_FLAVOUR UNIX_FLAVOUR_BSD
# elif defined(USE_KQUEUE_DFLY)
# define ARK_PLATFORM_NAME "DragonFlyBSD"
# define UNIX_FLAVOUR UNIX_FLAVOUR_BSD
# else
# define ARK_PLATFORM_NAME "Linux"
# define UNIX_FLAVOUR UNIX_FLAVOUR_LINUX
# endif
#elif ARK_PLATFORM == PLATFORM_WIN
# define ARK_PLATFORM_NAME "Windows"
#else
# pragma error "FATAL ERROR: Unknown platform."
#endif
#define ARK_RUN_MODE_DEBUG 0
#define ARK_RUN_MODE_RELEASE 1
#ifndef ARK_RUN_MODE
# if defined(DEBUG) || defined(_DEBUG)
# define ARK_RUN_MODE ARK_RUN_MODE_DEBUG
# define ARK_RUN_MODE_NAME "Debug"
# else
# define ARK_RUN_MODE ARK_RUN_MODE_RELEASE
# define ARK_RUN_MODE_NAME "Release"
# endif // DEBUG
#endif
#ifndef X64
# if defined(_WIN64) || defined(__x86_64__) || defined(__amd64) || defined(__LP64__)
# define X64
# endif
#endif
#ifdef X64
# define ARK_ARCH_NAME "X64"
#else
# define ARK_ARCH_NAME "X86"
#endif // X64
#define ARK_LITTLE_ENDIAN
#ifndef ARK_DYNAMIC_PLUGIN
#define ARK_DYNAMIC_PLUGIN
#endif
<commit_msg>remove netmodule log<commit_after>/*****************************************************************************
// * This source file is part of ArkGameFrame *
// * For the latest info, see https://github.com/ArkGame *
// * *
// * Copyright(c) 2013 - 2017 ArkGame 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. *
// * *
// * *
// * @file AFPlatform.h *
// * @author Ark Game Tech *
// * @date 2015-12-15 *
// * @brief AFPlatform *
*****************************************************************************/
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <math.h>
#include <assert.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <cstring>
#include <vector>
#include <map>
#include <list>
#include <set>
#include <deque>
#include <limits>
#include <algorithm>
#include <utility>
#include <functional>
#include <cctype>
#include <iterator>
#include <unordered_map>
#include <stdint.h>
#include <functional>
#include <memory>
#include <signal.h>
#include <chrono>
#include <sstream>
#include <random>
#include <thread>
#if defined(__WIN32__) || defined(WIN32) || defined(_WIN32) || defined(__WIN64__) || defined(WIN64) || defined(_WIN64)
// only windows include
#include <io.h>
#include <time.h>
#ifndef WIN32_LEAN_AND_MEAN
#include <WinSock2.h>
#include <MSWSock.h>
#define WIN32_LEAN_AND_MEAN
#endif // WIN32_LEAN_AND_MEAN
#include <windows.h>
#define _SCL_SECURE_NO_WARNINGS
#define SIGHUP 1
#define SIGINT 2
#define SIGQUIT 3
#define SIGUSR1 10
#define SIGPIPE 13
#define SIGCHLD 17
#define SIGSYS 32
#else
// only other unix/linux include
#include <sys/socket.h>
#endif
#define ARK_LITTLE_ENDIAN
#define ARK_BIG_ENDIAN
#if !defined(ARK_ENDIAN)
# if defined(USE_BIG_ENDIAN)
# define ARK_ENDIAN ARK_BIG_ENDIAN
# else
# define ARK_ENDIAN ARK_LITTLE_ENDIAN
# endif
#endif // !defined(ARK_ENDIAN)
#define PLATFORM_WIN 0
#define PLATFORM_UNIX 1
#define PLATFORM_APPLE 2
#define UNIX_FLAVOUR_LINUX 1
#define UNIX_FLAVOUR_BSD 2
#define UNIX_FLAVOUR_OTHER 3
#define UNIX_FLAVOUR_OSX 4
#if defined(__WIN32__) || defined(WIN32) || defined(_WIN32) || defined(__WIN64__) || defined(WIN64) || defined(_WIN64)
# define ARK_PLATFORM PLATFORM_WIN
#elif defined(__APPLE_CC__)
# define ARK_PLATFORM PLATFORM_APPLE
#else
# define ARK_PLATFORM PLATFORM_UNIX
#endif
#define COMPILER_MICROSOFT 0
#define COMPILER_GNU 1
#define COMPILER_BORLAND 2
#define COMPILER_INTEL 3
#define COMPILER_CLANG 4
#ifdef _MSC_VER
# define ARK_COMPILER COMPILER_MICROSOFT
#elif defined(__INTEL_COMPILER)
# define ARK_COMPILER COMPILER_INTEL
#elif defined(__BORLANDC__)
# define ARK_COMPILER COMPILER_BORLAND
#elif defined(__GNUC__)
# define ARK_COMPILER COMPILER_GNU
#elif defined( __clang__ )
# define ARK_COMPILER COMPILER_CLANG
#else
# pragma error "FATAL ERROR: Unknown compiler."
#endif
#if ARK_PLATFORM == PLATFORM_UNIX || ARK_PLATFORM == PLATFORM_APPLE
# if defined(HAVE_DARWIN)
# define ARK_PLATFORM_NAME "MacOSX"
# define UNIX_FLAVOUR UNIX_FLAVOUR_OSX
# elif defined(USE_KQUEUE)
# define ARK_PLATFORM_NAME "FreeBSD"
# define UNIX_FLAVOUR UNIX_FLAVOUR_BSD
# elif defined(USE_KQUEUE_DFLY)
# define ARK_PLATFORM_NAME "DragonFlyBSD"
# define UNIX_FLAVOUR UNIX_FLAVOUR_BSD
# else
# define ARK_PLATFORM_NAME "Linux"
# define UNIX_FLAVOUR UNIX_FLAVOUR_LINUX
# endif
#elif ARK_PLATFORM == PLATFORM_WIN
# define ARK_PLATFORM_NAME "Windows"
#else
# pragma error "FATAL ERROR: Unknown platform."
#endif
#define ARK_RUN_MODE_DEBUG 0
#define ARK_RUN_MODE_RELEASE 1
#ifndef ARK_RUN_MODE
# if defined(DEBUG) || defined(_DEBUG)
# define ARK_RUN_MODE ARK_RUN_MODE_DEBUG
# define ARK_RUN_MODE_NAME "Debug"
# else
# define ARK_RUN_MODE ARK_RUN_MODE_RELEASE
# define ARK_RUN_MODE_NAME "Release"
# endif // DEBUG
#endif
#ifndef X64
# if defined(_WIN64) || defined(__x86_64__) || defined(__amd64) || defined(__LP64__)
# define X64
# endif
#endif
#ifdef X64
# define ARK_ARCH_NAME "X64"
#else
# define ARK_ARCH_NAME "X86"
#endif // X64
#define ARK_LITTLE_ENDIAN
#ifndef ARK_DYNAMIC_PLUGIN
#define ARK_DYNAMIC_PLUGIN
#endif
<|endoftext|> |
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2020, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_config.h"
#include "match_prefix.h"
#include <termios.h>
#include <unistd.h>
#include <grp.h>
#include <signal.h>
#include <algorithm>
// condor_nsenter
//
// This is a replacement for the linux nsenter command to launch a
// shell inside a container. We need this when running
// condor_ssh_to_job to a job that has been launched inside singularity
// Docker jobs use docker exec to enter the container, but there is no
// equivalent in singularity. Standard nsenter isn't sufficient, as it
// does not create a pty for the shell, and we need different command
// line arguments to enter a non-setuid singularity container. This
// is harder because the starter can't tell if singularity is setuid easily.
//
// The architecture for ssh-to-job to a contained job is to land in an sshd
// the starter forks *outside* the container. This is important because we
// never want to assume anything about the container, even that there is an sshd
// inside it. After the sshd starts, a script runs which runs condor_docker_enter
// (even for singularity), which connects to a Unix Domain Socket, passes
// stdin/out/err to the starter, which passes those to condor_nsenter, which
// is runs as root. Rootly privilege is required to enter a setuid namespace
// so this is how we acquire.
//
// condor_nsenter enters the namespace, taking care to try to enter the user
// namespace, which is only set up for non-setuid singularity, and drops
// privileges to the uid and gid passed on the command line. It sets up
// a pty for the shell to use, so all interactive processses will work.
//
// A final problem is environment variables. Singularity, especially when
// managing GPUs, sets some nvidia-related environment variables that the
// condor starter doesn't know about. So, condor_nsenter extracts the environment
// variables from the contained job process, and sets them in the shell
// it spawns.
void
usage( char *cmd )
{
fprintf(stderr,"Usage: %s [options] condor_* ....\n",cmd);
fprintf(stderr,"Where options are:\n");
fprintf(stderr,"-t target_pid:\n");
fprintf(stderr,"-S user_id:\n");
fprintf(stderr,"-G group_id:\n");
fprintf(stderr," -help Display options\n");
}
#if (__GLIBC__ == 2) && (__GLIBC_MINOR__ < 15)
// el6 doesn't have setns. What are we going to do?
// what can we do? Just not enter the container
int setns(int , int) {
return 0;
}
#endif
// Before we exit, we need to reset the pty back to normal
// if we put it in raw mode
bool pty_is_raw = false;
struct termios old_tio;
void reset_pty_and_exit(int signo) {
if (pty_is_raw)
tcsetattr(0, TCSAFLUSH, &old_tio);
exit(signo);
}
int main( int argc, char *argv[] )
{
std::string condor_prefix;
pid_t pid = 0;
uid_t uid = 0;
gid_t gid = 0;
// parse command line args
for( int i=1; i<argc; i++ ) {
if(is_arg_prefix(argv[i],"-help")) {
usage(argv[0]);
exit(1);
}
// target pid to enter
if(is_arg_prefix(argv[i],"-t")) {
pid = atoi(argv[i + 1]);
i++;
}
// uid to switch to
if(is_arg_prefix(argv[i],"-S")) {
uid = atoi(argv[i + 1]);
i++;
}
// gid to switch to
if(is_arg_prefix(argv[i],"-G")) {
gid = atoi(argv[i + 1]);
i++;
}
}
if (pid < 1) {
fprintf(stderr, "missing -t argument > 1\n");
exit(1);
}
if (uid == 0) {
fprintf(stderr, "missing -S argument > 1\n");
exit(1);
}
if (gid == 0) {
fprintf(stderr, "missing -G argument > 1\n");
exit(1);
}
// slurp the enviroment out of our victim
std::string env;
std::string envfile;
formatstr(envfile, "/proc/%d/environ", pid);
int e = open(envfile.c_str(), O_RDONLY);
if (e < 0) {
fprintf(stderr, "Can't open %s %s\n", envfile.c_str(), strerror(errno));
exit(1);
}
char buf[512];
int bytesRead;
while ((bytesRead = read(e, &buf, 512)) > 0) {
env.append(buf, bytesRead);
}
close(e);
// make a vector to hold all the pointers to env entries
std::vector<const char *> envp;
// the first one
envp.push_back(env.c_str());
auto it = env.begin();
while (env.end() != (it = std::find(it, env.end(), '\0'))) {
// skip past null terminator
it++;
if (& (*it) != 0) {
envp.push_back(& (*it));
}
}
envp.push_back(0);
envp.push_back(0);
// grab the fd for the cwd -- need to get this outside
// but chdir inside the container
std::string cwdPath;
formatstr(cwdPath, "/proc/%d/cwd", pid);
int rootFd = open(cwdPath.c_str(), O_RDONLY);
if (rootFd < 0) {
fprintf(stderr, "Can't open %s\n", cwdPath.c_str());
}
std::string filename;
// start changing namespaces. Note that once we do this, things
// get funny in this process
formatstr(filename, "/proc/%d/ns/uts", pid);
int fd = open(filename.c_str(), O_RDONLY);
if (fd < 0) {
fprintf(stderr, "Can't open uts namespace: %d %s\n", errno, strerror(errno));
exit(1);
}
int r = setns(fd, 0);
close(fd);
if (r < 0) {
// This means an unprivileged singularity, most likely
// need to set user namespace instead.
formatstr(filename, "/proc/%d/ns/user", pid);
fd = open(filename.c_str(), O_RDONLY);
if (fd < 0) {
fprintf(stderr, "Can't open user namespace: %d %s\n", errno, strerror(errno));
exit(1);
}
r = setns(fd, 0);
close(fd);
if (r < 0) {
fprintf(stderr, "Can't setns to user namespace: %s\n", strerror(errno));
exit(1);
}
}
// now the pid namespace
formatstr(filename, "/proc/%d/ns/pid", pid);
fd = open(filename.c_str(), O_RDONLY);
if (fd < 0) {
fprintf(stderr, "Can't open pid namespace: %s\n", strerror(errno));
exit(1);
}
r = setns(fd, 0);
close(fd);
if (r < 0) {
fprintf(stderr, "Can't setns to pid namespace: %s\n", strerror(errno));
exit(1);
}
// finally the mnt namespace
formatstr(filename, "/proc/%d/ns/mnt", pid);
fd = open(filename.c_str(), O_RDONLY);
if (fd < 0) {
fprintf(stderr, "Can't open mnt namespace: %s\n", strerror(errno));
exit(1);
}
r = setns(fd, 0);
close(fd);
if (r < 0) {
fprintf(stderr, "Can't setns to mnt namespace: %s\n", strerror(errno));
exit(1);
}
setgroups(0, 0);
// order matters!
r = setgid(gid);
if (r < 0) {
fprintf(stderr, "Can't setgid to %d\n", gid);
exit(1);
}
r = setuid(uid);
if (r < 0) {
fprintf(stderr, "Can't setuid to %d\n", uid);
exit(1);
}
// now the pty handling
int masterPty = -1;
int workerPty = -1;
masterPty = open("/dev/ptmx", O_RDWR);
unlockpt(masterPty);
if (masterPty < 0) {
fprintf(stderr, "Can't open master pty %s\n", strerror(errno));
exit(1);
} else {
workerPty = open(ptsname(masterPty), O_RDWR);
if (workerPty < 0) {
fprintf(stderr, "Can't open worker pty %s\n", strerror(errno));
exit(1);
}
}
int childpid = fork();
if (childpid == 0) {
// in the child --
close(0);
close(1);
close(2);
close(masterPty);
dup2(workerPty, 0);
dup2(workerPty, 1);
dup2(workerPty, 2);
// chdir to existing cwd
int ret = fchdir(rootFd);
if (ret < 0) {
fprintf(stderr, "Can't open %s\n", cwdPath.c_str());
}
close(rootFd);
// make this process group leader so shell job control works
setsid();
execle("/bin/sh", "/bin/sh", "-i", 0, envp.data());
// Only get here if exec fails
fprintf(stderr, "exec failed %d\n", errno);
exit(errno);
} else {
// the parent
fd_set readfds, writefds, exceptfds;
bool keepGoing = true;
// put the pty in raw mode
struct termios tio;
tcgetattr(0, &tio);
pty_is_raw = true;
old_tio = tio;
tio.c_oflag &= ~(OPOST);
tio.c_cflag |= (CS8);
tio.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
tio.c_cc[VMIN] = 1;
tio.c_cc[VTIME] = 0;
tcsetattr(0, TCSAFLUSH, &tio);
struct sigaction handler;
struct sigaction oldhandler;
handler.sa_handler = reset_pty_and_exit;
sigaction(SIGCHLD, &handler, &oldhandler);
while (keepGoing) {
FD_ZERO(&readfds);
FD_ZERO(&writefds);
FD_ZERO(&exceptfds);
FD_SET(0, &readfds);
FD_SET(masterPty, &readfds);
select(masterPty + 1, &readfds, &writefds, &exceptfds, 0);
if (FD_ISSET(masterPty, &readfds)) {
char buf;
int r = read(masterPty, &buf, 1);
if (r > 0) {
int ret = write(1, &buf, 1);
if (ret < 0) {
reset_pty_and_exit(0);
}
} else {
keepGoing = false;
}
}
if (FD_ISSET(0, &readfds)) {
char buf;
int r = read(0, &buf, 1);
if (r > 0) {
int ret = write(masterPty, &buf, 1);
if (ret < 0) {
reset_pty_and_exit(0);
}
} else {
keepGoing = false;
}
}
}
int status;
waitpid(childpid, &status, 0);
}
return 0;
}
<commit_msg>Make nsenter work with dash #7666<commit_after>/***************************************************************
*
* Copyright (C) 1990-2020, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_config.h"
#include "match_prefix.h"
#include <termios.h>
#include <unistd.h>
#include <grp.h>
#include <signal.h>
#include <algorithm>
// condor_nsenter
//
// This is a replacement for the linux nsenter command to launch a
// shell inside a container. We need this when running
// condor_ssh_to_job to a job that has been launched inside singularity
// Docker jobs use docker exec to enter the container, but there is no
// equivalent in singularity. Standard nsenter isn't sufficient, as it
// does not create a pty for the shell, and we need different command
// line arguments to enter a non-setuid singularity container. This
// is harder because the starter can't tell if singularity is setuid easily.
//
// The architecture for ssh-to-job to a contained job is to land in an sshd
// the starter forks *outside* the container. This is important because we
// never want to assume anything about the container, even that there is an sshd
// inside it. After the sshd starts, a script runs which runs condor_docker_enter
// (even for singularity), which connects to a Unix Domain Socket, passes
// stdin/out/err to the starter, which passes those to condor_nsenter, which
// is runs as root. Rootly privilege is required to enter a setuid namespace
// so this is how we acquire.
//
// condor_nsenter enters the namespace, taking care to try to enter the user
// namespace, which is only set up for non-setuid singularity, and drops
// privileges to the uid and gid passed on the command line. It sets up
// a pty for the shell to use, so all interactive processses will work.
//
// A final problem is environment variables. Singularity, especially when
// managing GPUs, sets some nvidia-related environment variables that the
// condor starter doesn't know about. So, condor_nsenter extracts the environment
// variables from the contained job process, and sets them in the shell
// it spawns.
void
usage( char *cmd )
{
fprintf(stderr,"Usage: %s [options] condor_* ....\n",cmd);
fprintf(stderr,"Where options are:\n");
fprintf(stderr,"-t target_pid:\n");
fprintf(stderr,"-S user_id:\n");
fprintf(stderr,"-G group_id:\n");
fprintf(stderr," -help Display options\n");
}
#if (__GLIBC__ == 2) && (__GLIBC_MINOR__ < 15)
// el6 doesn't have setns. What are we going to do?
// what can we do? Just not enter the container
int setns(int , int) {
return 0;
}
#endif
// Before we exit, we need to reset the pty back to normal
// if we put it in raw mode
bool pty_is_raw = false;
struct termios old_tio;
void reset_pty_and_exit(int signo) {
if (pty_is_raw)
tcsetattr(0, TCSAFLUSH, &old_tio);
exit(signo);
}
int main( int argc, char *argv[] )
{
std::string condor_prefix;
pid_t pid = 0;
uid_t uid = 0;
gid_t gid = 0;
// parse command line args
for( int i=1; i<argc; i++ ) {
if(is_arg_prefix(argv[i],"-help")) {
usage(argv[0]);
exit(1);
}
// target pid to enter
if(is_arg_prefix(argv[i],"-t")) {
pid = atoi(argv[i + 1]);
i++;
}
// uid to switch to
if(is_arg_prefix(argv[i],"-S")) {
uid = atoi(argv[i + 1]);
i++;
}
// gid to switch to
if(is_arg_prefix(argv[i],"-G")) {
gid = atoi(argv[i + 1]);
i++;
}
}
if (pid < 1) {
fprintf(stderr, "missing -t argument > 1\n");
exit(1);
}
if (uid == 0) {
fprintf(stderr, "missing -S argument > 1\n");
exit(1);
}
if (gid == 0) {
fprintf(stderr, "missing -G argument > 1\n");
exit(1);
}
// slurp the enviroment out of our victim
std::string env;
std::string envfile;
formatstr(envfile, "/proc/%d/environ", pid);
int e = open(envfile.c_str(), O_RDONLY);
if (e < 0) {
fprintf(stderr, "Can't open %s %s\n", envfile.c_str(), strerror(errno));
exit(1);
}
char buf[512];
int bytesRead;
while ((bytesRead = read(e, &buf, 512)) > 0) {
env.append(buf, bytesRead);
}
close(e);
// make a vector to hold all the pointers to env entries
std::vector<const char *> envp;
// the first one
envp.push_back(env.c_str());
auto it = env.begin();
while (env.end() != (it = std::find(it, env.end(), '\0'))) {
// skip past null terminator
it++;
if (& (*it) != 0) {
envp.push_back(& (*it));
}
}
envp.push_back(0);
envp.push_back(0);
// grab the fd for the cwd -- need to get this outside
// but chdir inside the container
std::string cwdPath;
formatstr(cwdPath, "/proc/%d/cwd", pid);
int rootFd = open(cwdPath.c_str(), O_RDONLY);
if (rootFd < 0) {
fprintf(stderr, "Can't open %s\n", cwdPath.c_str());
}
std::string filename;
// start changing namespaces. Note that once we do this, things
// get funny in this process
formatstr(filename, "/proc/%d/ns/uts", pid);
int fd = open(filename.c_str(), O_RDONLY);
if (fd < 0) {
fprintf(stderr, "Can't open uts namespace: %d %s\n", errno, strerror(errno));
exit(1);
}
int r = setns(fd, 0);
close(fd);
if (r < 0) {
// This means an unprivileged singularity, most likely
// need to set user namespace instead.
formatstr(filename, "/proc/%d/ns/user", pid);
fd = open(filename.c_str(), O_RDONLY);
if (fd < 0) {
fprintf(stderr, "Can't open user namespace: %d %s\n", errno, strerror(errno));
exit(1);
}
r = setns(fd, 0);
close(fd);
if (r < 0) {
fprintf(stderr, "Can't setns to user namespace: %s\n", strerror(errno));
exit(1);
}
}
// now the pid namespace
formatstr(filename, "/proc/%d/ns/pid", pid);
fd = open(filename.c_str(), O_RDONLY);
if (fd < 0) {
fprintf(stderr, "Can't open pid namespace: %s\n", strerror(errno));
exit(1);
}
r = setns(fd, 0);
close(fd);
if (r < 0) {
fprintf(stderr, "Can't setns to pid namespace: %s\n", strerror(errno));
exit(1);
}
// finally the mnt namespace
formatstr(filename, "/proc/%d/ns/mnt", pid);
fd = open(filename.c_str(), O_RDONLY);
if (fd < 0) {
fprintf(stderr, "Can't open mnt namespace: %s\n", strerror(errno));
exit(1);
}
r = setns(fd, 0);
close(fd);
if (r < 0) {
fprintf(stderr, "Can't setns to mnt namespace: %s\n", strerror(errno));
exit(1);
}
setgroups(0, 0);
// order matters!
r = setgid(gid);
if (r < 0) {
fprintf(stderr, "Can't setgid to %d\n", gid);
exit(1);
}
r = setuid(uid);
if (r < 0) {
fprintf(stderr, "Can't setuid to %d\n", uid);
exit(1);
}
struct winsize win;
ioctl(0, TIOCGWINSZ, &win);
// now the pty handling
int masterPty = -1;
int workerPty = -1;
masterPty = open("/dev/ptmx", O_RDWR);
unlockpt(masterPty);
if (masterPty < 0) {
fprintf(stderr, "Can't open master pty %s\n", strerror(errno));
exit(1);
} else {
workerPty = open(ptsname(masterPty), O_RDWR);
if (workerPty < 0) {
fprintf(stderr, "Can't open worker pty %s\n", strerror(errno));
exit(1);
}
}
int childpid = fork();
if (childpid == 0) {
// in the child --
close(0);
close(1);
close(2);
close(masterPty);
dup2(workerPty, 0);
dup2(workerPty, 1);
dup2(workerPty, 2);
// chdir to existing cwd
int ret = fchdir(rootFd);
if (ret < 0) {
fprintf(stderr, "Can't open %s\n", cwdPath.c_str());
}
close(rootFd);
// make this process group leader so shell job control works
setsid();
// Make the pty the controlling terminal
ioctl(workerPty, TIOCSCTTY, 0);
// and make it the process group leader
tcsetpgrp(workerPty, getpid());
// and set the window size properly
ioctl(0, TIOCSWINSZ, &win);
// Finally, launch the shell
execle("/bin/sh", "/bin/sh", "-l", "-i", nullptr, envp.data());
// Only get here if exec fails
fprintf(stderr, "exec failed %d\n", errno);
exit(errno);
} else {
// the parent
fd_set readfds, writefds, exceptfds;
bool keepGoing = true;
// put the pty in raw mode
struct termios tio;
tcgetattr(0, &tio);
pty_is_raw = true;
old_tio = tio;
tio.c_oflag &= ~(OPOST);
tio.c_cflag |= (CS8);
tio.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
tio.c_cc[VMIN] = 1;
tio.c_cc[VTIME] = 0;
tcsetattr(0, TCSAFLUSH, &tio);
struct sigaction handler;
struct sigaction oldhandler;
handler.sa_handler = reset_pty_and_exit;
handler.sa_flags = 0;
sigaction(SIGCHLD, &handler, &oldhandler);
while (keepGoing) {
FD_ZERO(&readfds);
FD_ZERO(&writefds);
FD_ZERO(&exceptfds);
FD_SET(0, &readfds);
FD_SET(masterPty, &readfds);
select(masterPty + 1, &readfds, &writefds, &exceptfds, 0);
if (FD_ISSET(masterPty, &readfds)) {
char buf;
int r = read(masterPty, &buf, 1);
if (r > 0) {
int ret = write(1, &buf, 1);
if (ret < 0) {
reset_pty_and_exit(0);
}
} else {
keepGoing = false;
}
}
if (FD_ISSET(0, &readfds)) {
char buf;
int r = read(0, &buf, 1);
if (r > 0) {
int ret = write(masterPty, &buf, 1);
if (ret < 0) {
reset_pty_and_exit(0);
}
} else {
keepGoing = false;
}
}
}
int status;
waitpid(childpid, &status, 0);
}
return 0;
}
<|endoftext|> |
<commit_before>/// This is where the magic happens; program your plug-in's core behavior here.
#include "game_hooks.h"
#include <graphics/graphics.h>
#include <SCBW/api.h>
#include <SCBW/scbwdata.h>
#include <SCBW/ExtendSightLimit.h>
#include "psi_field.h"
#include <cstdio>
namespace hooks {
/// This hook is called every frame; most of your plugin's logic goes here.
bool nextFrame() {
if (!scbw::isGamePaused()) { //If the game is not paused
graphics::resetAllGraphics();
hooks::updatePsiFieldProviders();
if (*elapsedTimeFrames == 0) {
scbw::printText("Hello, world!");
}
// Loop through all visible units in the game.
for (CUnit *unit = *firstVisibleUnit; unit; unit = unit->link.next) {
//Write your code here
}
// Loop through all bullets in the game
//for (BULLET* bullet = *firstBullet; bullet; bullet = bullet->next) {
// //Write your code here
//}
}
return true;
}
bool gameOn() {
return true;
}
bool gameEnd() {
return true;
}
} //hooks
<commit_msg>GPTP: Cleanup game_hooks.cpp<commit_after>/// This is where the magic happens; program your plug-in's core behavior here.
#include "game_hooks.h"
#include <graphics/graphics.h>
#include <SCBW/api.h>
#include <SCBW/scbwdata.h>
#include <SCBW/ExtendSightLimit.h>
#include "psi_field.h"
#include <cstdio>
namespace hooks {
/// This hook is called every frame; most of your plugin's logic goes here.
bool nextFrame() {
if (!scbw::isGamePaused()) { //If the game is not paused
graphics::resetAllGraphics();
hooks::updatePsiFieldProviders();
//This block is executed once every game.
if (*elapsedTimeFrames == 0) {
//Write your code here
scbw::printText(PLUGIN_NAME ": Hello, world!");
}
//Loop through all visible units in the game.
for (CUnit *unit = *firstVisibleUnit; unit; unit = unit->link.next) {
//Write your code here
}
}
return true;
}
bool gameOn() {
return true;
}
bool gameEnd() {
return true;
}
} //hooks
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
#include <TROOT.h>
#include <TSystem.h>
#include <TInterpreter.h>
#include <TChain.h>
#include <TFile.h>
#include <TList.h>
#include "AliAnalysisTaskJets.h"
#include "AliAnalysisManager.h"
#include "AliJetFinder.h"
#include "AliJetHistos.h"
#include "AliESDEvent.h"
#include "AliESD.h"
#include "AliAODEvent.h"
#include "AliAODHandler.h"
#include "AliMCEventHandler.h"
#include "AliESDInputHandler.h"
#include "AliMCEvent.h"
#include "AliStack.h"
ClassImp(AliAnalysisTaskJets)
////////////////////////////////////////////////////////////////////////
AliAnalysisTaskJets::AliAnalysisTaskJets():
fDebug(0),
fJetFinder(0x0),
fTree(0x0),
fESD(0x0),
fAOD(0x0),
fTreeA(0x0),
fHistos(0x0),
fListOfHistos(0x0)
{
// Default constructor
}
AliAnalysisTaskJets::AliAnalysisTaskJets(const char* name):
AliAnalysisTask(name, "AnalysisTaskJets"),
fDebug(0),
fJetFinder(0x0),
fTree(0x0),
fESD(0x0),
fAOD(0x0),
fTreeA(0x0),
fHistos(0x0),
fListOfHistos(0x0)
{
// Default constructor
DefineInput (0, TChain::Class());
DefineOutput(0, TTree::Class());
DefineOutput(1, TList::Class());
}
void AliAnalysisTaskJets::CreateOutputObjects()
{
// Create the output container
//
// Default AOD
if (fDebug > 1) printf("AnalysisTaskJets::CreateOutPutData() \n");
AliAODHandler* handler = (AliAODHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler());
fAOD = handler->GetAOD();
fTreeA = handler->GetTree();
fJetFinder->ConnectAOD(fAOD);
//
// Histograms
OpenFile(1);
fListOfHistos = new TList();
fHistos = new AliJetHistos();
fHistos->AddHistosToList(fListOfHistos);
}
void AliAnalysisTaskJets::Init()
{
// Initialization
if (fDebug > 1) printf("AnalysisTaskJets::Init() \n");
// Call configuration file
gROOT->LoadMacro("ConfigJetAnalysis.C");
fJetFinder = (AliJetFinder*) gInterpreter->ProcessLine("ConfigJetAnalysis()");
// Initialise Jet Analysis
fJetFinder->Init();
// Write header information to local file
fJetFinder->WriteHeaders();
}
void AliAnalysisTaskJets::ConnectInputData(Option_t */*option*/)
{
// Connect the input data
if (fDebug > 1) printf("AnalysisTaskJets::ConnectInputData() \n");
AliESDInputHandler* esdH = (AliESDInputHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetInputEventHandler());
AliESDEvent* fESD = esdH->GetEvent();
fTree = esdH->GetTree();
AliMCEventHandler* mcTruth = (AliMCEventHandler*)
((AliAnalysisManager::GetAnalysisManager())->GetMCtruthEventHandler());
fJetFinder->GetReader()->SetInputEvent(fESD, fAOD, mcTruth);
}
void AliAnalysisTaskJets::Exec(Option_t */*option*/)
{
// Execute analysis for current event
//
AliMCEventHandler* mctruth = (AliMCEventHandler*)
((AliAnalysisManager::GetAnalysisManager())->GetMCtruthEventHandler());
if (mctruth) {
AliStack* stack = mctruth->MCEvent()->Stack();
//printf("AliAnalysisTaskJets: Number of tracks on stack %5d\n", stack->GetNtrack());
}
Long64_t ientry = fTree->GetReadEntry();
if (fDebug > 1) printf("Analysing event # %5d\n", (Int_t) ientry);
fJetFinder->ProcessEvent(ientry);
// Fill control histos
fHistos->FillHistos(fAOD->GetJets());
// Post the data
PostData(0, fTreeA);
PostData(1, fListOfHistos);
}
void AliAnalysisTaskJets::Terminate(Option_t */*option*/)
{
// Terminate analysis
//
if (fDebug > 1) printf("AnalysisJets: Terminate() \n");
// if (fJetFinder) fJetFinder->FinishRun();
}
<commit_msg>Double declaration removed.<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
#include <TROOT.h>
#include <TSystem.h>
#include <TInterpreter.h>
#include <TChain.h>
#include <TFile.h>
#include <TList.h>
#include "AliAnalysisTaskJets.h"
#include "AliAnalysisManager.h"
#include "AliJetFinder.h"
#include "AliJetHistos.h"
#include "AliESDEvent.h"
#include "AliESD.h"
#include "AliAODEvent.h"
#include "AliAODHandler.h"
#include "AliMCEventHandler.h"
#include "AliESDInputHandler.h"
#include "AliMCEvent.h"
#include "AliStack.h"
ClassImp(AliAnalysisTaskJets)
////////////////////////////////////////////////////////////////////////
AliAnalysisTaskJets::AliAnalysisTaskJets():
fDebug(0),
fJetFinder(0x0),
fTree(0x0),
fESD(0x0),
fAOD(0x0),
fTreeA(0x0),
fHistos(0x0),
fListOfHistos(0x0)
{
// Default constructor
}
AliAnalysisTaskJets::AliAnalysisTaskJets(const char* name):
AliAnalysisTask(name, "AnalysisTaskJets"),
fDebug(0),
fJetFinder(0x0),
fTree(0x0),
fESD(0x0),
fAOD(0x0),
fTreeA(0x0),
fHistos(0x0),
fListOfHistos(0x0)
{
// Default constructor
DefineInput (0, TChain::Class());
DefineOutput(0, TTree::Class());
DefineOutput(1, TList::Class());
}
void AliAnalysisTaskJets::CreateOutputObjects()
{
// Create the output container
//
// Default AOD
if (fDebug > 1) printf("AnalysisTaskJets::CreateOutPutData() \n");
AliAODHandler* handler = (AliAODHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler());
fAOD = handler->GetAOD();
fTreeA = handler->GetTree();
fJetFinder->ConnectAOD(fAOD);
//
// Histograms
OpenFile(1);
fListOfHistos = new TList();
fHistos = new AliJetHistos();
fHistos->AddHistosToList(fListOfHistos);
}
void AliAnalysisTaskJets::Init()
{
// Initialization
if (fDebug > 1) printf("AnalysisTaskJets::Init() \n");
// Call configuration file
gROOT->LoadMacro("ConfigJetAnalysis.C");
fJetFinder = (AliJetFinder*) gInterpreter->ProcessLine("ConfigJetAnalysis()");
// Initialise Jet Analysis
fJetFinder->Init();
// Write header information to local file
fJetFinder->WriteHeaders();
}
void AliAnalysisTaskJets::ConnectInputData(Option_t */*option*/)
{
// Connect the input data
if (fDebug > 1) printf("AnalysisTaskJets::ConnectInputData() \n");
AliESDInputHandler* esdH = (AliESDInputHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetInputEventHandler());
fESD = esdH->GetEvent();
fTree = esdH->GetTree();
AliMCEventHandler* mcTruth = (AliMCEventHandler*)
((AliAnalysisManager::GetAnalysisManager())->GetMCtruthEventHandler());
fJetFinder->GetReader()->SetInputEvent(fESD, fAOD, mcTruth);
}
void AliAnalysisTaskJets::Exec(Option_t */*option*/)
{
// Execute analysis for current event
//
AliMCEventHandler* mctruth = (AliMCEventHandler*)
((AliAnalysisManager::GetAnalysisManager())->GetMCtruthEventHandler());
if (mctruth) {
AliStack* stack = mctruth->MCEvent()->Stack();
//printf("AliAnalysisTaskJets: Number of tracks on stack %5d\n", stack->GetNtrack());
}
Long64_t ientry = fTree->GetReadEntry();
if (fDebug > 1) printf("Analysing event # %5d\n", (Int_t) ientry);
fJetFinder->ProcessEvent(ientry);
// Fill control histos
fHistos->FillHistos(fAOD->GetJets());
// Post the data
PostData(0, fTreeA);
PostData(1, fListOfHistos);
}
void AliAnalysisTaskJets::Terminate(Option_t */*option*/)
{
// Terminate analysis
//
if (fDebug > 1) printf("AnalysisJets: Terminate() \n");
// if (fJetFinder) fJetFinder->FinishRun();
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2012 Lasath Fernando <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "filters.h"
#include <QtGui/QTextDocument> //needed for Qt::escape
EscapeFilter::EscapeFilter(QObject *parent)
: AbstractMessageFilter(parent)
{
}
void EscapeFilter::filterMessage(Message& message)
{
QString escapedMessage = Qt::escape(message.mainMessagePart());
escapedMessage.replace(QLatin1String("\n "), QLatin1String("<br/> ")); //keep leading whitespaces
escapedMessage.replace(QLatin1Char('\n'), QLatin1String("<br/>"));
escapedMessage.replace(QLatin1Char('\t'), QLatin1String(" ")); // replace tabs by 4 spaces
escapedMessage.replace(QLatin1String(" "), QLatin1String(" ")); // keep multiple whitespaces
escapedMessage.replace(QLatin1Char('\\'), QLatin1String("\\\\")); //replace a single backslash with two backslashes.
message.setMainMessagePart(escapedMessage);
}<commit_msg>Move replacement not needed by appendScript to escapeFilter<commit_after>/*
Copyright (C) 2012 Lasath Fernando <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "filters.h"
#include <QtGui/QTextDocument> //needed for Qt::escape
EscapeFilter::EscapeFilter(QObject *parent)
: AbstractMessageFilter(parent)
{
}
void EscapeFilter::filterMessage(Message& message)
{
QString escapedMessage = Qt::escape(message.mainMessagePart());
escapedMessage.replace(QLatin1String("\n "), QLatin1String("<br/> ")); //keep leading whitespaces
escapedMessage.replace(QLatin1Char('\n'), QLatin1String("<br/>"));
escapedMessage.replace(QLatin1Char('\r'), QLatin1String("<br/>"));
escapedMessage.replace(QLatin1Char('\t'), QLatin1String(" ")); // replace tabs by 4 spaces
escapedMessage.replace(QLatin1String(" "), QLatin1String(" ")); // keep multiple whitespaces
escapedMessage.replace(QLatin1Char('\\'), QLatin1String("\\\\")); //replace a single backslash with two backslashes.
message.setMainMessagePart(escapedMessage);
}<|endoftext|> |
<commit_before>// AntAppSkeleton.cpp
#include "AntAppSkeleton.h"
AntAppSkeleton::AntAppSkeleton()
: m_bar(NULL)
{
}
AntAppSkeleton::~AntAppSkeleton()
{
///@todo Delete this before glfw
//delete m_bar;
}
void AntAppSkeleton::_InitializeBar()
{
// Create a tweak bar
m_bar = TwNewBar("TweakBar");
TwDefine(" GLOBAL help='This example shows how to integrate AntTweakBar with GLFW and OpenGL.' "); // Message added to the help bar.
TwAddVarRW(m_bar, "rotation x", TW_TYPE_FLOAT, &g_rotation.x,
" label='Rot x' min=0 max=360 step=1.0 keyIncr=a keyDecr=A help='Rotation x' ");
TwAddVarRW(m_bar, "rotation y", TW_TYPE_FLOAT, &g_rotation.y,
" label='Rot y' min=0 max=360 step=1.0 keyIncr=s keyDecr=S help='Rotation y' ");
TwAddVarRW(m_bar, "rotation z", TW_TYPE_FLOAT, &g_rotation.z,
" label='Rot z' min=0 max=360 step=1.0 keyIncr=d keyDecr=D help='Rotation z' ");
}
bool AntAppSkeleton::initGL(int argc, char **argv)
{
TwInit(TW_OPENGL, NULL);
_InitializeBar();
return TriAppSkeleton::initGL(argc, argv);
}
void AntAppSkeleton::display() const
{
TriAppSkeleton::display();
TwDraw(); ///@todo Should this go first? Will it write to a depth buffer?
}
void AntAppSkeleton::mouseDown(int button, int state, int x, int y)
{
TwEventMouseButtonGLFW(button, state);
}
void AntAppSkeleton::mouseMove(int x, int y)
{
TwEventMousePosGLFW(x, y);
}
void AntAppSkeleton::mouseWheel(int x, int y)
{
TwEventMouseWheelGLFW(x);
}
void AntAppSkeleton::keyboard(int key, int x, int y)
{
TwEventKeyGLFW(key, 0);
}
void AntAppSkeleton::charkey(unsigned int key)
{
TwEventCharGLFW(key, 0);
}<commit_msg>Plugged in callback fallthroughs, key action still broken in Ant.<commit_after>// AntAppSkeleton.cpp
#include "AntAppSkeleton.h"
AntAppSkeleton::AntAppSkeleton()
: m_bar(NULL)
{
}
AntAppSkeleton::~AntAppSkeleton()
{
///@todo Delete this before glfw
//delete m_bar;
}
void AntAppSkeleton::_InitializeBar()
{
// Create a tweak bar
m_bar = TwNewBar("TweakBar");
TwDefine(" GLOBAL help='This example shows how to integrate AntTweakBar with GLFW and OpenGL.' "); // Message added to the help bar.
TwAddVarRW(m_bar, "rotation x", TW_TYPE_FLOAT, &g_rotation.x,
" label='Rot x' min=0 max=360 step=1.0 keyIncr=a keyDecr=A help='Rotation x' ");
TwAddVarRW(m_bar, "rotation y", TW_TYPE_FLOAT, &g_rotation.y,
" label='Rot y' min=0 max=360 step=1.0 keyIncr=s keyDecr=S help='Rotation y' ");
TwAddVarRW(m_bar, "rotation z", TW_TYPE_FLOAT, &g_rotation.z,
" label='Rot z' min=0 max=360 step=1.0 keyIncr=d keyDecr=D help='Rotation z' ");
}
bool AntAppSkeleton::initGL(int argc, char **argv)
{
TwInit(TW_OPENGL, NULL);
_InitializeBar();
return TriAppSkeleton::initGL(argc, argv);
}
void AntAppSkeleton::display() const
{
TriAppSkeleton::display();
TwDraw(); ///@todo Should this go first? Will it write to a depth buffer?
}
void AntAppSkeleton::mouseDown(int button, int state, int x, int y)
{
int ant = TwEventMouseButtonGLFW(button, state);
if (ant != 0)
return;
TriAppSkeleton::mouseDown(button, state, x, y);
}
void AntAppSkeleton::mouseMove(int x, int y)
{
TwEventMousePosGLFW(x, y);
TriAppSkeleton::mouseMove(x, y);
}
void AntAppSkeleton::mouseWheel(int x, int y)
{
TwEventMouseWheelGLFW(x);
//TriAppSkeleton::mouseWheel(x, y);
}
void AntAppSkeleton::keyboard(int key, int x, int y)
{
int ant = TwEventKeyGLFW(key, 0);
if (ant != 0)
return;
TriAppSkeleton::keyboard(key, x, y);
}
void AntAppSkeleton::charkey(unsigned int key)
{
int ant = TwEventCharGLFW(key, 0);
if (ant != 0)
return;
TriAppSkeleton::keyboard(key, 0, 0);
}
<|endoftext|> |
<commit_before>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <vw/BundleAdjustment/ControlNetwork.h>
#include <vw/BundleAdjustment/CameraRelation.h>
#include <vw/Cartography.h>
using namespace vw;
using namespace vw::ba;
using namespace vw::camera;
#include <boost/algorithm/string.hpp>
#include <boost/program_options.hpp>
#include <boost/foreach.hpp>
#include <boost/filesystem/path.hpp>
namespace po = boost::program_options;
namespace fs = boost::filesystem;
#include <asp/IsisIO/IsisCameraModel.h>
#include <asp/Core/Macros.h>
int find_destination_index( int const& source_idx,
std::map<int,std::string> const& src_map,
std::map<std::string,int> & dst_map,
int & dst_max_idx ) {
std::map<std::string,int>::iterator search =
dst_map.find( src_map.find(source_idx)->second );
int dst_index;
if ( search == dst_map.end() ) {
dst_max_idx++;
dst_index = dst_max_idx;
std::string serial = src_map.find(source_idx)->second;
vw_out() << " Adding camera w/ serial: " << serial << "\n";
dst_map[ serial ] = dst_index;
} else {
dst_index = search->second;
}
return dst_index;
}
void print_cnet_statistics( ControlNetwork const& cnet ) {
int cmeasure_size = 0;
BOOST_FOREACH( ControlPoint const& cp, cnet ) {
cmeasure_size+=cp.size();
}
vw_out() << " CP : " << cnet.size() << " CM : " << cmeasure_size << "\n";
}
struct ContainsEqualMeasure {
Vector2 m_position;
ContainsEqualMeasure( Vector2 const& pos ) : m_position(pos) {}
bool operator()( boost::shared_ptr<IPFeature> in ) {
if ( m_position[0] == in->m_ip.x &&
m_position[1] == in->m_ip.y )
return true;
return false;
}
};
struct ContainsCloseMeasure {
Vector2 m_position;
double m_close;
ContainsCloseMeasure( Vector2 const& pos, double const& close ) : m_position(pos), m_close(close) {}
bool operator()( boost::shared_ptr<IPFeature> in ) {
if ( norm_2( Vector2(in->m_ip.x, in->m_ip.y) - m_position ) <= m_close )
return true;
return false;
}
};
struct Options {
// Input
std::string destination_cnet;
std::vector<std::string> source_cnets;
double close;
// Output
std::string output_prefix;
};
void handle_arguments( int argc, char *argv[], Options& opt ) {
po::options_description general_options("");
general_options.add_options()
("output-prefix,o", po::value(&opt.output_prefix)->default_value("merged"),
"Output prefix for merge control network.")
("close-px", po::value(&opt.close)->default_value(-1),
"Merge measurements are that are this pixel close. Leave -1 to only merge exact measurements." )
("help,h", "Display this help message");
po::options_description positional("");
positional.add_options()
("dest-cnet", po::value(&opt.destination_cnet) )
("source-cnets", po::value(&opt.source_cnets) );
po::positional_options_description positional_desc;
positional_desc.add("dest-cnet", 1 );
positional_desc.add("source-cnets", -1 );
po::options_description all_options;
all_options.add(general_options).add(positional);
po::variables_map vm;
try {
po::store( po::command_line_parser( argc, argv ).options(all_options).positional(positional_desc).run(), vm );
po::notify( vm );
} catch (po::error &e) {
vw_throw( ArgumentErr() << "Error parsing input:\n\t"
<< e.what() << general_options );
}
std::ostringstream usage;
usage << "Usage: " << argv[0] << " [options] <dest> <source1> ... <sourceN>\n";
if ( vm.count("help") )
vw_throw( ArgumentErr() << usage.str() << general_options );
if ( opt.destination_cnet.empty() )
vw_throw( ArgumentErr() << "Missing destination cnets.\n"
<< usage.str() << general_options );
if ( opt.source_cnets.empty() )
vw_throw( ArgumentErr() << "Missing source cnets.\n"
<< usage.str() << general_options );
}
int main( int argc, char** argv ) {
Options opt;
try {
handle_arguments( argc, argv, opt );
ControlNetwork dst_cnet("destination");
dst_cnet.read_binary( opt.destination_cnet );
vw_out() << "Destination Control Network:\n";
print_cnet_statistics( dst_cnet );
std::map<std::string,int> dst_serial_to_cam_idx;
int dst_max_cam_idx = -1;
{
float inc_amt = 1.0/float(dst_cnet.size());
TerminalProgressCallback tpc("","Destination Idx:");
BOOST_FOREACH( ControlPoint const& cp, dst_cnet ) {
tpc.report_incremental_progress( inc_amt );
BOOST_FOREACH( ControlMeasure const& cm, cp ) {
if ( dst_serial_to_cam_idx.find( cm.serial() ) ==
dst_serial_to_cam_idx.end() ) {
dst_serial_to_cam_idx[cm.serial()] = cm.image_id();
if ( cm.image_id() > dst_max_cam_idx )
dst_max_cam_idx = cm.image_id();
}
}
}
tpc.report_finished();
}
vw_out() << "Input Control Network has " << dst_max_cam_idx+1 << " cameras.\n";
CameraRelationNetwork<IPFeature> dst_crn;
dst_crn.read_controlnetwork( dst_cnet );
BOOST_FOREACH( std::string const& source_cnet, opt.source_cnets ) {
ControlNetwork src_cnet("source");
src_cnet.read_binary( source_cnet );
vw_out() << "Input " << source_cnet << ":\n";
print_cnet_statistics( src_cnet );
typedef std::map<int,std::string> src_map_type;
src_map_type src_cam_idx_to_serial;
float inc_amt = 1.0/float(src_cnet.size());
{
TerminalProgressCallback tpc("cnet",source_cnet+" Idx:");
BOOST_FOREACH( ControlPoint const& cp, src_cnet ) {
tpc.report_incremental_progress( inc_amt );
BOOST_FOREACH( ControlMeasure const& cm, cp ) {
if ( src_cam_idx_to_serial.find( cm.image_id() ) ==
src_cam_idx_to_serial.end() )
src_cam_idx_to_serial[cm.image_id()] = cm.serial();
}
}
tpc.report_finished();
}
{
TerminalProgressCallback tpc("cnet",source_cnet+" Merge:");
BOOST_FOREACH( ControlPoint const& cp, src_cnet ) {
tpc.report_incremental_progress(inc_amt );
typedef boost::shared_ptr<IPFeature> f_ptr;
typedef std::list<f_ptr>::iterator f_itr;
ControlPoint::const_iterator cm1, cm2;
cm1 = cm2 = cp.begin();
cm2++;
int dst_index1 =
find_destination_index( cm1->image_id(),
src_cam_idx_to_serial,
dst_serial_to_cam_idx,
dst_max_cam_idx );
f_itr dst_feature1;
if ( opt.close < 0 ) {
dst_feature1 = std::find_if( dst_crn[dst_index1].begin(),
dst_crn[dst_index1].end(),
ContainsEqualMeasure(cm1->position()));
} else {
dst_feature1 = std::find_if( dst_crn[dst_index1].begin(),
dst_crn[dst_index1].end(),
ContainsCloseMeasure(cm1->position(),opt.close));
}
if ( dst_feature1 == dst_crn[dst_index1].end() ) {
dst_crn[dst_index1].relations.push_front( f_ptr( new IPFeature(*cm1,0, dst_index1) ));
dst_feature1 = dst_crn[dst_index1].begin();
}
while ( cm2 != cp.end() ) {
int dst_index2 =
find_destination_index( cm2->image_id(),
src_cam_idx_to_serial,
dst_serial_to_cam_idx,
dst_max_cam_idx );
f_itr dst_feature2;
if ( opt.close < 0 ) {
dst_feature2 = std::find_if( dst_crn[dst_index2].begin(),
dst_crn[dst_index2].end(),
ContainsEqualMeasure(cm2->position()));
} else {
dst_feature2 = std::find_if( dst_crn[dst_index2].begin(),
dst_crn[dst_index2].end(),
ContainsCloseMeasure(cm2->position(),opt.close));
}
if ( dst_feature2 == dst_crn[dst_index2].end() ) {
dst_crn[dst_index2].relations.push_front( f_ptr( new IPFeature( *cm2, 0, dst_index2 )));
dst_feature2 = dst_crn[dst_index2].begin();
}
// Doubly linking
(*dst_feature1)->connection( *dst_feature2, true );
(*dst_feature2)->connection( *dst_feature1, true );
dst_index1 = dst_index2;
dst_feature1 = dst_feature2;
cm1++; cm2++;
}
}
tpc.report_finished();
}
}
dst_crn.write_controlnetwork( dst_cnet );
vw_out() << "Output Control Network:\n";
print_cnet_statistics( dst_cnet );
// Re apply serial
std::map<int,std::string> reverse_dst;
for ( std::map<std::string,int>::iterator it = dst_serial_to_cam_idx.begin();
it != dst_serial_to_cam_idx.end(); it++ ) {
reverse_dst[it->second] = it->first;
}
BOOST_FOREACH( ControlPoint & cp, dst_cnet ) {
BOOST_FOREACH( ControlMeasure & cm, cp ) {
cm.set_serial( reverse_dst[cm.image_id()] );
}
}
dst_cnet.write_binary(opt.output_prefix);
} ASP_STANDARD_CATCHES;
}
<commit_msg>Allow cnet_merge to add cameras<commit_after>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <vw/BundleAdjustment/ControlNetwork.h>
#include <vw/BundleAdjustment/CameraRelation.h>
#include <vw/Cartography.h>
using namespace vw;
using namespace vw::ba;
using namespace vw::camera;
#include <boost/algorithm/string.hpp>
#include <boost/program_options.hpp>
#include <boost/foreach.hpp>
#include <boost/filesystem/path.hpp>
namespace po = boost::program_options;
namespace fs = boost::filesystem;
#include <asp/IsisIO/IsisCameraModel.h>
#include <asp/Core/Macros.h>
int find_destination_index( int const& source_idx,
std::map<int,std::string> const& src_map,
std::map<std::string,int> & dst_map,
int & dst_max_idx ) {
std::map<std::string,int>::iterator search =
dst_map.find( src_map.find(source_idx)->second );
int dst_index;
if ( search == dst_map.end() ) {
dst_max_idx++;
dst_index = dst_max_idx;
std::string serial = src_map.find(source_idx)->second;
vw_out() << " Adding camera w/ serial: " << serial << "\n";
dst_map[ serial ] = dst_index;
} else {
dst_index = search->second;
}
return dst_index;
}
void print_cnet_statistics( ControlNetwork const& cnet ) {
int cmeasure_size = 0;
BOOST_FOREACH( ControlPoint const& cp, cnet ) {
cmeasure_size+=cp.size();
}
vw_out() << " CP : " << cnet.size() << " CM : " << cmeasure_size << "\n";
}
struct ContainsEqualMeasure {
Vector2 m_position;
ContainsEqualMeasure( Vector2 const& pos ) : m_position(pos) {}
bool operator()( boost::shared_ptr<IPFeature> in ) {
if ( m_position[0] == in->m_ip.x &&
m_position[1] == in->m_ip.y )
return true;
return false;
}
};
struct ContainsCloseMeasure {
Vector2 m_position;
double m_close;
ContainsCloseMeasure( Vector2 const& pos, double const& close ) : m_position(pos), m_close(close) {}
bool operator()( boost::shared_ptr<IPFeature> in ) {
if ( norm_2( Vector2(in->m_ip.x, in->m_ip.y) - m_position ) <= m_close )
return true;
return false;
}
};
struct Options {
// Input
std::string destination_cnet;
std::vector<std::string> source_cnets;
double close;
// Output
std::string output_prefix;
};
void handle_arguments( int argc, char *argv[], Options& opt ) {
po::options_description general_options("");
general_options.add_options()
("output-prefix,o", po::value(&opt.output_prefix)->default_value("merged"),
"Output prefix for merge control network.")
("close-px", po::value(&opt.close)->default_value(-1),
"Merge measurements are that are this pixel close. Leave -1 to only merge exact measurements." )
("help,h", "Display this help message");
po::options_description positional("");
positional.add_options()
("dest-cnet", po::value(&opt.destination_cnet) )
("source-cnets", po::value(&opt.source_cnets) );
po::positional_options_description positional_desc;
positional_desc.add("dest-cnet", 1 );
positional_desc.add("source-cnets", -1 );
po::options_description all_options;
all_options.add(general_options).add(positional);
po::variables_map vm;
try {
po::store( po::command_line_parser( argc, argv ).options(all_options).positional(positional_desc).run(), vm );
po::notify( vm );
} catch (po::error &e) {
vw_throw( ArgumentErr() << "Error parsing input:\n\t"
<< e.what() << general_options );
}
std::ostringstream usage;
usage << "Usage: " << argv[0] << " [options] <dest> <source1> ... <sourceN>\n";
if ( vm.count("help") )
vw_throw( ArgumentErr() << usage.str() << general_options );
if ( opt.destination_cnet.empty() )
vw_throw( ArgumentErr() << "Missing destination cnets.\n"
<< usage.str() << general_options );
if ( opt.source_cnets.empty() )
vw_throw( ArgumentErr() << "Missing source cnets.\n"
<< usage.str() << general_options );
}
int main( int argc, char** argv ) {
Options opt;
try {
handle_arguments( argc, argv, opt );
ControlNetwork dst_cnet("destination");
dst_cnet.read_binary( opt.destination_cnet );
vw_out() << "Destination Control Network:\n";
print_cnet_statistics( dst_cnet );
std::map<std::string,int> dst_serial_to_cam_idx;
int dst_max_cam_idx = -1;
{
float inc_amt = 1.0/float(dst_cnet.size());
TerminalProgressCallback tpc("","Destination Idx:");
BOOST_FOREACH( ControlPoint const& cp, dst_cnet ) {
tpc.report_incremental_progress( inc_amt );
BOOST_FOREACH( ControlMeasure const& cm, cp ) {
if ( dst_serial_to_cam_idx.find( cm.serial() ) ==
dst_serial_to_cam_idx.end() ) {
dst_serial_to_cam_idx[cm.serial()] = cm.image_id();
if ( cm.image_id() > dst_max_cam_idx )
dst_max_cam_idx = cm.image_id();
}
}
}
tpc.report_finished();
}
vw_out() << "Input Control Network has " << dst_max_cam_idx+1 << " cameras.\n";
CameraRelationNetwork<IPFeature> dst_crn;
dst_crn.read_controlnetwork( dst_cnet );
BOOST_FOREACH( std::string const& source_cnet, opt.source_cnets ) {
ControlNetwork src_cnet("source");
src_cnet.read_binary( source_cnet );
vw_out() << "Input " << source_cnet << ":\n";
print_cnet_statistics( src_cnet );
typedef std::map<int,std::string> src_map_type;
src_map_type src_cam_idx_to_serial;
float inc_amt = 1.0/float(src_cnet.size());
{
TerminalProgressCallback tpc("cnet",source_cnet+" Idx:");
BOOST_FOREACH( ControlPoint const& cp, src_cnet ) {
tpc.report_incremental_progress( inc_amt );
BOOST_FOREACH( ControlMeasure const& cm, cp ) {
if ( src_cam_idx_to_serial.find( cm.image_id() ) ==
src_cam_idx_to_serial.end() )
src_cam_idx_to_serial[cm.image_id()] = cm.serial();
}
}
tpc.report_finished();
}
{
TerminalProgressCallback tpc("cnet",source_cnet+" Merge:");
BOOST_FOREACH( ControlPoint const& cp, src_cnet ) {
tpc.report_incremental_progress(inc_amt );
typedef boost::shared_ptr<IPFeature> f_ptr;
typedef std::list<f_ptr>::iterator f_itr;
ControlPoint::const_iterator cm1, cm2;
cm1 = cm2 = cp.begin();
cm2++;
int dst_index1 =
find_destination_index( cm1->image_id(),
src_cam_idx_to_serial,
dst_serial_to_cam_idx,
dst_max_cam_idx );
if ( dst_index1 == dst_crn.size() )
dst_crn.add_node( CameraNode<IPFeature>(dst_index1,"") );
f_itr dst_feature1;
if ( opt.close < 0 ) {
dst_feature1 = std::find_if( dst_crn[dst_index1].begin(),
dst_crn[dst_index1].end(),
ContainsEqualMeasure(cm1->position()));
} else {
dst_feature1 = std::find_if( dst_crn[dst_index1].begin(),
dst_crn[dst_index1].end(),
ContainsCloseMeasure(cm1->position(),opt.close));
}
if ( dst_feature1 == dst_crn[dst_index1].end() ) {
dst_crn[dst_index1].relations.push_front( f_ptr( new IPFeature(*cm1,0, dst_index1) ));
dst_feature1 = dst_crn[dst_index1].begin();
}
while ( cm2 != cp.end() ) {
int dst_index2 =
find_destination_index( cm2->image_id(),
src_cam_idx_to_serial,
dst_serial_to_cam_idx,
dst_max_cam_idx );
if ( dst_index2 == dst_crn.size() )
dst_crn.add_node( CameraNode<IPFeature>(dst_index2,"") );
f_itr dst_feature2;
if ( opt.close < 0 ) {
dst_feature2 = std::find_if( dst_crn[dst_index2].begin(),
dst_crn[dst_index2].end(),
ContainsEqualMeasure(cm2->position()));
} else {
dst_feature2 = std::find_if( dst_crn[dst_index2].begin(),
dst_crn[dst_index2].end(),
ContainsCloseMeasure(cm2->position(),opt.close));
}
if ( dst_feature2 == dst_crn[dst_index2].end() ) {
dst_crn[dst_index2].relations.push_front( f_ptr( new IPFeature( *cm2, 0, dst_index2 )));
dst_feature2 = dst_crn[dst_index2].begin();
}
// Doubly linking
(*dst_feature1)->connection( *dst_feature2, true );
(*dst_feature2)->connection( *dst_feature1, true );
dst_index1 = dst_index2;
dst_feature1 = dst_feature2;
cm1++; cm2++;
}
}
tpc.report_finished();
}
}
dst_crn.write_controlnetwork( dst_cnet );
vw_out() << "Output Control Network:\n";
print_cnet_statistics( dst_cnet );
// Re apply serial
std::map<int,std::string> reverse_dst;
for ( std::map<std::string,int>::iterator it = dst_serial_to_cam_idx.begin();
it != dst_serial_to_cam_idx.end(); it++ ) {
reverse_dst[it->second] = it->first;
}
BOOST_FOREACH( ControlPoint & cp, dst_cnet ) {
BOOST_FOREACH( ControlMeasure & cm, cp ) {
cm.set_serial( reverse_dst[cm.image_id()] );
}
}
dst_cnet.write_binary(opt.output_prefix);
} ASP_STANDARD_CATCHES;
}
<|endoftext|> |
<commit_before>//===- MinGW.cpp ----------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "MinGW.h"
#include "Error.h"
#include "llvm/Object/COFF.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
using namespace lld;
using namespace lld::coff;
using namespace llvm;
using namespace llvm::COFF;
AutoExporter::AutoExporter() {
if (Config->Machine == I386)
ExcludeSymbols = {
"__NULL_IMPORT_DESCRIPTOR",
"__pei386_runtime_relocator",
"_do_pseudo_reloc",
"_impure_ptr",
"__impure_ptr",
"__fmode",
"_environ",
"___dso_handle",
// These are the MinGW names that differ from the standard
// ones (lacking an extra underscore).
"_DllMain@12",
"_DllEntryPoint@12",
"_DllMainCRTStartup@12",
};
else
ExcludeSymbols = {
"_NULL_IMPORT_DESCRIPTOR",
"_pei386_runtime_relocator",
"do_pseudo_reloc",
"impure_ptr",
"_impure_ptr",
"_fmode",
"environ",
"__dso_handle",
// These are the MinGW names that differ from the standard
// ones (lacking an extra underscore).
"DllMain",
"DllEntryPoint",
"DllMainCRTStartup",
};
ExcludeLibs = {
"libgcc",
"libgcc_s",
"libstdc++",
"libmingw32",
"libmingwex",
"libg2c",
"libsupc++",
"libobjc",
"libgcj",
"libclang_rt.builtins-aarch64",
"libclang_rt.builtins-arm",
"libclang_rt.builtins-i386",
"libclang_rt.builtins-x86_64",
};
ExcludeObjects = {
"crt0.o",
"crt1.o",
"crt1u.o",
"crt2.o",
"crt2u.o",
"dllcrt1.o",
"dllcrt2.o",
"gcrt0.o",
"gcrt1.o",
"gcrt2.o",
"crtbegin.o",
"crtend.o",
};
}
bool AutoExporter::shouldExport(Defined *Sym) const {
if (!Sym || !Sym->isLive() || !Sym->getChunk())
return false;
if (ExcludeSymbols.count(Sym->getName()))
return false;
StringRef LibName = sys::path::filename(Sym->getFile()->ParentName);
// Drop the file extension.
LibName = LibName.substr(0, LibName.rfind('.'));
if (ExcludeLibs.count(LibName))
return false;
StringRef FileName = sys::path::filename(Sym->getFile()->getName());
if (LibName.empty() && ExcludeObjects.count(FileName))
return false;
return true;
}
void coff::writeDefFile(StringRef Name) {
std::error_code EC;
raw_fd_ostream OS(Name, EC, sys::fs::F_None);
if (EC)
fatal("cannot open " + Name + ": " + EC.message());
OS << "EXPORTS\n";
for (Export &E : Config->Exports) {
OS << " " << E.ExportName << " "
<< "@" << E.Ordinal;
if (auto *Def = dyn_cast_or_null<Defined>(E.Sym)) {
if (Def && Def->getChunk() &&
!(Def->getChunk()->getPermissions() & IMAGE_SCN_MEM_EXECUTE))
OS << " DATA";
}
OS << "\n";
}
}
<commit_msg>[MinGW] Omit libc++/libc++abi/libunwind from autoexporting<commit_after>//===- MinGW.cpp ----------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "MinGW.h"
#include "Error.h"
#include "llvm/Object/COFF.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
using namespace lld;
using namespace lld::coff;
using namespace llvm;
using namespace llvm::COFF;
AutoExporter::AutoExporter() {
if (Config->Machine == I386)
ExcludeSymbols = {
"__NULL_IMPORT_DESCRIPTOR",
"__pei386_runtime_relocator",
"_do_pseudo_reloc",
"_impure_ptr",
"__impure_ptr",
"__fmode",
"_environ",
"___dso_handle",
// These are the MinGW names that differ from the standard
// ones (lacking an extra underscore).
"_DllMain@12",
"_DllEntryPoint@12",
"_DllMainCRTStartup@12",
};
else
ExcludeSymbols = {
"_NULL_IMPORT_DESCRIPTOR",
"_pei386_runtime_relocator",
"do_pseudo_reloc",
"impure_ptr",
"_impure_ptr",
"_fmode",
"environ",
"__dso_handle",
// These are the MinGW names that differ from the standard
// ones (lacking an extra underscore).
"DllMain",
"DllEntryPoint",
"DllMainCRTStartup",
};
ExcludeLibs = {
"libgcc",
"libgcc_s",
"libstdc++",
"libmingw32",
"libmingwex",
"libg2c",
"libsupc++",
"libobjc",
"libgcj",
"libclang_rt.builtins-aarch64",
"libclang_rt.builtins-arm",
"libclang_rt.builtins-i386",
"libclang_rt.builtins-x86_64",
"libc++",
"libc++abi",
"libunwind",
};
ExcludeObjects = {
"crt0.o",
"crt1.o",
"crt1u.o",
"crt2.o",
"crt2u.o",
"dllcrt1.o",
"dllcrt2.o",
"gcrt0.o",
"gcrt1.o",
"gcrt2.o",
"crtbegin.o",
"crtend.o",
};
}
bool AutoExporter::shouldExport(Defined *Sym) const {
if (!Sym || !Sym->isLive() || !Sym->getChunk())
return false;
if (ExcludeSymbols.count(Sym->getName()))
return false;
StringRef LibName = sys::path::filename(Sym->getFile()->ParentName);
// Drop the file extension.
LibName = LibName.substr(0, LibName.rfind('.'));
if (ExcludeLibs.count(LibName))
return false;
StringRef FileName = sys::path::filename(Sym->getFile()->getName());
if (LibName.empty() && ExcludeObjects.count(FileName))
return false;
return true;
}
void coff::writeDefFile(StringRef Name) {
std::error_code EC;
raw_fd_ostream OS(Name, EC, sys::fs::F_None);
if (EC)
fatal("cannot open " + Name + ": " + EC.message());
OS << "EXPORTS\n";
for (Export &E : Config->Exports) {
OS << " " << E.ExportName << " "
<< "@" << E.Ordinal;
if (auto *Def = dyn_cast_or_null<Defined>(E.Sym)) {
if (Def && Def->getChunk() &&
!(Def->getChunk()->getPermissions() & IMAGE_SCN_MEM_EXECUTE))
OS << " DATA";
}
OS << "\n";
}
}
<|endoftext|> |
<commit_before>/*
// License Agreement (3-clause BSD License)
// Copyright (c) 2015, Klaus Haag, all rights reserved.
// Third party copyrights and patents are property of their respective owners.
//
// 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 names of the copyright holders nor the names of the 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 copyright holders or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
*/
#ifndef HELPER_H_
#define HELPER_H_
#include <opencv2/core/core.hpp>
#include "cv_ext.hpp"
#include "mat_consts.hpp"
namespace cf_tracking
{
void dftCcs(const cv::Mat& input, cv::Mat& out, int flags = 0);
void dftNoCcs(const cv::Mat& input, cv::Mat& out, int flags = 0);
int mod(int dividend, int divisor);
void depResize(const cv::Mat& source, cv::Mat& dst, const cv::Size& dsize);
template<typename T>
cv::Size_<T> sizeFloor(cv::Size_<T> size)
{
return cv::Size_<T>(floor(size.width), floor(size.height));
}
template <typename T>
cv::Mat numberToRowVector(int n)
{
cv::Mat_<T> rowVec(n, 1);
for (int i = 0; i < n; ++i)
rowVec.template at<T>(i, 0) = static_cast<T>(i + 1);
return rowVec;
}
template <typename T>
cv::Mat numberToColVector(int n)
{
cv::Mat_<T> colVec(1, n);
for (int i = 0; i < n; ++i)
colVec.template at<T>(0, i) = static_cast<T>(i + 1);
return colVec;
}
// http://home.isr.uc.pt/~henriques/circulant/
template <typename T>
T subPixelPeak(T* p)
{
T delta = mat_consts::constants<T>::c0_5 * (p[2] - p[0]) / (2 * p[1] - p[2] - p[0]);
if (!std::isfinite(delta))
return 0;
return delta;
}
// http://home.isr.uc.pt/~henriques/circulant/
template <typename T>
cv::Point_<T> subPixelDelta(const cv::Mat& response, const cv::Point2i& delta)
{
cv::Point_<T> subDelta(static_cast<float>(delta.x), static_cast<float>(delta.y));
T vNeighbors[3] = {};
T hNeighbors[3] = {};
for (int i = -1; i < 2; ++i)
{
vNeighbors[i + 1] = response.template at<T>(mod(delta.y + i, response.rows), delta.x);
hNeighbors[i + 1] = response.template at<T>(delta.y, mod(delta.x + i, response.cols));
}
subDelta.y += subPixelPeak(vNeighbors);
subDelta.x += subPixelPeak(hNeighbors);
return subDelta;
}
// http://home.isr.uc.pt/~henriques/circulant/
template <typename T>
cv::Mat gaussianShapedLabels2D(T sigma, const cv::Size_<T>& size)
{
int width = static_cast<int>(size.width);
int height = static_cast<int>(size.height);
cv::Mat_<T> rs(height, width);
CV_Assert(rs.isContinuous());
T lowerBoundX = static_cast<T>(-floor(width * 0.5) + 1);
T lowerBoundY = static_cast<T>(-floor(height * 0.5) + 1);
T* colValues = new T[width];
T* rsd = rs.template ptr<T>(0, 0);
T rowValue = 0;
T sigmaMult = static_cast<T>(-0.5 / (sigma*sigma));
for (int i = 0; i < width; ++i)
colValues[i] = (i + lowerBoundX) * (i + lowerBoundX);
for (int row = 0; row < height; ++row)
{
rowValue = (row + lowerBoundY) * (row + lowerBoundY);
for (int col = 0; col < width; ++col)
{
rsd[row*width + col] = exp((colValues[col] + rowValue) * sigmaMult);
}
}
delete[] colValues;
return rs;
}
// http://home.isr.uc.pt/~henriques/circulant/
template <typename T>
cv::Mat gaussianShapedLabelsShifted2D(T sigma, const cv::Size_<T>& size)
{
cv::Mat y = gaussianShapedLabels2D(sigma, size);
cv::Point2f delta(static_cast<float>(1 - floor(size.width * 0.5)),
static_cast<float>(1 - floor(size.height * 0.5)));
shift(y, y, delta, cv::BORDER_WRAP);
CV_Assert(y.at<T>(0, 0) == 1.0);
return y;
}
template <typename BT, typename ET>
cv::Mat pow(BT base_, const cv::Mat_<ET>& exponent)
{
cv::Mat dst = cv::Mat(exponent.rows, exponent.cols, exponent.type());
int widthChannels = exponent.cols * exponent.channels();
int height = exponent.rows;
// http://docs.opencv.org/doc/tutorials/core/how_to_scan_images/how_to_scan_images.html#the-efficient-way
if (exponent.isContinuous())
{
widthChannels *= height;
height = 1;
}
int row = 0, col = 0;
const ET* exponentd = 0;
ET* dstd = 0;
for (row = 0; row < height; ++row)
{
exponentd = exponent.template ptr<ET>(row);
dstd = dst.template ptr<ET>(row);
for (col = 0; col < widthChannels; ++col)
{
dstd[col] = std::pow(base_, exponentd[col]);
}
}
return dst;
}
// http://en.wikipedia.org/wiki/Hann_function
template<typename T>
cv::Mat hanningWindow(int n)
{
CV_Assert(n > 0);
cv::Mat_<T> w = cv::Mat_<T>(n, 1);
if (n == 1)
{
w.template at<T>(0, 0) = 1;
return w;
}
for (int i = 0; i < n; ++i)
w.template at<T>(i, 0) = static_cast<T>(0.5 * (1.0 - cos(2.0 * 3.14159265358979323846 * i / (n - 1))));
return w;
}
template <typename T>
void divideSpectrumsNoCcs(const cv::Mat& numerator, const cv::Mat& denominator, cv::Mat& dst)
{
// http://mathworld.wolfram.com/ComplexDivision.html
// (a,b) / (c,d) = ((ac+bd)/v , (bc-ad)/v)
// with v = (c^2 + d^2)
// Performance wise implemented according to
// http://docs.opencv.org/doc/tutorials/core/how_to_scan_images/how_to_scan_images.html#howtoscanimagesopencv
// TODO: this is still very slow => vectorize (note that mulSpectrums is not vectorized either...)
int type = numerator.type();
int channels = numerator.channels();
CV_Assert(type == denominator.type()
&& numerator.size() == denominator.size()
&& channels == denominator.channels() && channels == 2);
CV_Assert(type == CV_32FC1 || type == CV_32FC2 || type == CV_64FC1 || type == CV_64FC2);
dst = cv::Mat(numerator.rows, numerator.cols, type);
int widthChannels = numerator.cols * channels;
int height = numerator.rows;
if (numerator.isContinuous() && denominator.isContinuous())
{
widthChannels *= height;
height = 1;
}
int row = 0, col = 0;
const T* numd, *denomd;
T* dstd;
T a, b, c, d, v;
for (row = 0; row < height; ++row)
{
numd = numerator.ptr<T>(row);
denomd = denominator.ptr<T>(row);
dstd = dst.ptr<T>(row);
for (col = 0; col < widthChannels; col += 2)
{
a = numd[col]; // real part
b = numd[col + 1]; // imag part
c = denomd[col]; // real part
d = denomd[col + 1]; // imag part
v = (c * c) + (d * d);
dstd[col] = (a * c + b * d) / v;
dstd[col + 1] = (b * c - a * d) / v;
}
}
}
// http://home.isr.uc.pt/~henriques/circulant/
template<typename T>
bool getSubWindow(const cv::Mat& image, cv::Mat& patch, const cv::Size_<T>& size,
const cv::Point_<T>& pos, cv::Point_<T>* posInSubWindow = 0)
{
int width = static_cast<int>(size.width);
int height = static_cast<int>(size.height);
int xs = static_cast<int>(std::floor(pos.x) - std::floor(width / 2.0)) + 1;
int ys = static_cast<int>(std::floor(pos.y) - std::floor(height / 2.0)) + 1;
T posInSubWindowX = pos.x - xs;
T posInSubWindowY = pos.y - ys;
int diffTopX = -xs;
int diffTopY = -ys;
int diffBottomX = image.cols - xs - width;
int diffBottomY = image.rows - ys - height;
cv::Rect imageRect(0, 0, image.cols, image.rows);
cv::Rect subRect(xs, ys, width, height);
subRect &= imageRect;
cv::Mat subWindow = image(subRect);
if (subWindow.cols == 0 || subWindow.rows == 0)
return false;
if (diffTopX > 0 || diffTopY > 0
|| diffBottomX < 0 || diffBottomY < 0)
{
diffTopX = std::max(0, diffTopX);
diffTopY = std::max(0, diffTopY);
diffBottomX = std::min(0, diffBottomX);
diffBottomY = std::min(0, diffBottomY);
copyMakeBorder(subWindow, subWindow, diffTopY, -diffBottomY,
diffTopX, -diffBottomX, cv::BORDER_REPLICATE);
posInSubWindowX += diffTopX;
posInSubWindowY += diffTopY;
}
// this if can be true if the sub window
// is completely outside the image
if (width != subWindow.cols ||
height != subWindow.rows)
return false;
if (posInSubWindow != 0)
{
posInSubWindow->x = posInSubWindowX;
posInSubWindow->y = posInSubWindowY;
}
patch = subWindow;
return true;
}
}
#endif
<commit_msg>Fix scale estimator patch extraction<commit_after>/*
// License Agreement (3-clause BSD License)
// Copyright (c) 2015, Klaus Haag, all rights reserved.
// Third party copyrights and patents are property of their respective owners.
//
// 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 names of the copyright holders nor the names of the 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 copyright holders or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
*/
#ifndef HELPER_H_
#define HELPER_H_
#include <opencv2/core/core.hpp>
#include "cv_ext.hpp"
#include "mat_consts.hpp"
namespace cf_tracking
{
void dftCcs(const cv::Mat& input, cv::Mat& out, int flags = 0);
void dftNoCcs(const cv::Mat& input, cv::Mat& out, int flags = 0);
int mod(int dividend, int divisor);
void depResize(const cv::Mat& source, cv::Mat& dst, const cv::Size& dsize);
template<typename T>
cv::Size_<T> sizeFloor(cv::Size_<T> size)
{
return cv::Size_<T>(floor(size.width), floor(size.height));
}
template <typename T>
cv::Mat numberToRowVector(int n)
{
cv::Mat_<T> rowVec(n, 1);
for (int i = 0; i < n; ++i)
rowVec.template at<T>(i, 0) = static_cast<T>(i + 1);
return rowVec;
}
template <typename T>
cv::Mat numberToColVector(int n)
{
cv::Mat_<T> colVec(1, n);
for (int i = 0; i < n; ++i)
colVec.template at<T>(0, i) = static_cast<T>(i + 1);
return colVec;
}
// http://home.isr.uc.pt/~henriques/circulant/
template <typename T>
T subPixelPeak(T* p)
{
T delta = mat_consts::constants<T>::c0_5 * (p[2] - p[0]) / (2 * p[1] - p[2] - p[0]);
if (!std::isfinite(delta))
return 0;
return delta;
}
// http://home.isr.uc.pt/~henriques/circulant/
template <typename T>
cv::Point_<T> subPixelDelta(const cv::Mat& response, const cv::Point2i& delta)
{
cv::Point_<T> subDelta(static_cast<float>(delta.x), static_cast<float>(delta.y));
T vNeighbors[3] = {};
T hNeighbors[3] = {};
for (int i = -1; i < 2; ++i)
{
vNeighbors[i + 1] = response.template at<T>(mod(delta.y + i, response.rows), delta.x);
hNeighbors[i + 1] = response.template at<T>(delta.y, mod(delta.x + i, response.cols));
}
subDelta.y += subPixelPeak(vNeighbors);
subDelta.x += subPixelPeak(hNeighbors);
return subDelta;
}
// http://home.isr.uc.pt/~henriques/circulant/
template <typename T>
cv::Mat gaussianShapedLabels2D(T sigma, const cv::Size_<T>& size)
{
int width = static_cast<int>(size.width);
int height = static_cast<int>(size.height);
cv::Mat_<T> rs(height, width);
CV_Assert(rs.isContinuous());
T lowerBoundX = static_cast<T>(-floor(width * 0.5) + 1);
T lowerBoundY = static_cast<T>(-floor(height * 0.5) + 1);
T* colValues = new T[width];
T* rsd = rs.template ptr<T>(0, 0);
T rowValue = 0;
T sigmaMult = static_cast<T>(-0.5 / (sigma*sigma));
for (int i = 0; i < width; ++i)
colValues[i] = (i + lowerBoundX) * (i + lowerBoundX);
for (int row = 0; row < height; ++row)
{
rowValue = (row + lowerBoundY) * (row + lowerBoundY);
for (int col = 0; col < width; ++col)
{
rsd[row*width + col] = exp((colValues[col] + rowValue) * sigmaMult);
}
}
delete[] colValues;
return rs;
}
// http://home.isr.uc.pt/~henriques/circulant/
template <typename T>
cv::Mat gaussianShapedLabelsShifted2D(T sigma, const cv::Size_<T>& size)
{
cv::Mat y = gaussianShapedLabels2D(sigma, size);
cv::Point2f delta(static_cast<float>(1 - floor(size.width * 0.5)),
static_cast<float>(1 - floor(size.height * 0.5)));
shift(y, y, delta, cv::BORDER_WRAP);
CV_Assert(y.at<T>(0, 0) == 1.0);
return y;
}
template <typename BT, typename ET>
cv::Mat pow(BT base_, const cv::Mat_<ET>& exponent)
{
cv::Mat dst = cv::Mat(exponent.rows, exponent.cols, exponent.type());
int widthChannels = exponent.cols * exponent.channels();
int height = exponent.rows;
// http://docs.opencv.org/doc/tutorials/core/how_to_scan_images/how_to_scan_images.html#the-efficient-way
if (exponent.isContinuous())
{
widthChannels *= height;
height = 1;
}
int row = 0, col = 0;
const ET* exponentd = 0;
ET* dstd = 0;
for (row = 0; row < height; ++row)
{
exponentd = exponent.template ptr<ET>(row);
dstd = dst.template ptr<ET>(row);
for (col = 0; col < widthChannels; ++col)
{
dstd[col] = std::pow(base_, exponentd[col]);
}
}
return dst;
}
// http://en.wikipedia.org/wiki/Hann_function
template<typename T>
cv::Mat hanningWindow(int n)
{
CV_Assert(n > 0);
cv::Mat_<T> w = cv::Mat_<T>(n, 1);
if (n == 1)
{
w.template at<T>(0, 0) = 1;
return w;
}
for (int i = 0; i < n; ++i)
w.template at<T>(i, 0) = static_cast<T>(0.5 * (1.0 - cos(2.0 * 3.14159265358979323846 * i / (n - 1))));
return w;
}
template <typename T>
void divideSpectrumsNoCcs(const cv::Mat& numerator, const cv::Mat& denominator, cv::Mat& dst)
{
// http://mathworld.wolfram.com/ComplexDivision.html
// (a,b) / (c,d) = ((ac+bd)/v , (bc-ad)/v)
// with v = (c^2 + d^2)
// Performance wise implemented according to
// http://docs.opencv.org/doc/tutorials/core/how_to_scan_images/how_to_scan_images.html#howtoscanimagesopencv
// TODO: this is still very slow => vectorize (note that mulSpectrums is not vectorized either...)
int type = numerator.type();
int channels = numerator.channels();
CV_Assert(type == denominator.type()
&& numerator.size() == denominator.size()
&& channels == denominator.channels() && channels == 2);
CV_Assert(type == CV_32FC1 || type == CV_32FC2 || type == CV_64FC1 || type == CV_64FC2);
dst = cv::Mat(numerator.rows, numerator.cols, type);
int widthChannels = numerator.cols * channels;
int height = numerator.rows;
if (numerator.isContinuous() && denominator.isContinuous())
{
widthChannels *= height;
height = 1;
}
int row = 0, col = 0;
const T* numd, *denomd;
T* dstd;
T a, b, c, d, v;
for (row = 0; row < height; ++row)
{
numd = numerator.ptr<T>(row);
denomd = denominator.ptr<T>(row);
dstd = dst.ptr<T>(row);
for (col = 0; col < widthChannels; col += 2)
{
a = numd[col]; // real part
b = numd[col + 1]; // imag part
c = denomd[col]; // real part
d = denomd[col + 1]; // imag part
v = (c * c) + (d * d);
dstd[col] = (a * c + b * d) / v;
dstd[col + 1] = (b * c - a * d) / v;
}
}
}
// http://home.isr.uc.pt/~henriques/circulant/
template<typename T>
bool getSubWindow(const cv::Mat& image, cv::Mat& patch, const cv::Size_<T>& size,
const cv::Point_<T>& pos, cv::Point_<T>* posInSubWindow = 0)
{
int width = static_cast<int>(size.width);
int height = static_cast<int>(size.height);
int xs = static_cast<int>(std::floor(pos.x) - std::floor(width / 2.0)) + 1;
int ys = static_cast<int>(std::floor(pos.y) - std::floor(height / 2.0)) + 1;
T posInSubWindowX = pos.x - xs;
T posInSubWindowY = pos.y - ys;
int diffTopX = -xs;
int diffTopY = -ys;
int diffBottomX = image.cols - xs - width;
int diffBottomY = image.rows - ys - height;
cv::Rect imageRect(0, 0, image.cols, image.rows);
cv::Rect subRect(xs, ys, width, height);
subRect &= imageRect;
cv::Mat subWindow = image(subRect);
if (subWindow.cols == 0 || subWindow.rows == 0)
return false;
if (diffTopX > 0 || diffTopY > 0
|| diffBottomX < 0 || diffBottomY < 0)
{
diffTopX = std::max(0, diffTopX);
diffTopY = std::max(0, diffTopY);
diffBottomX = std::min(0, diffBottomX);
diffBottomY = std::min(0, diffBottomY);
copyMakeBorder(subWindow, subWindow, diffTopY, -diffBottomY,
diffTopX, -diffBottomX, cv::BORDER_REPLICATE);
}
// this if can be true if the sub window
// is completely outside the image
if (width != subWindow.cols ||
height != subWindow.rows)
return false;
if (posInSubWindow != 0)
{
posInSubWindow->x = posInSubWindowX;
posInSubWindow->y = posInSubWindowY;
}
patch = subWindow;
return true;
}
}
#endif
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <algorithm>
#include <cmath>
#include <iostream>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "modules/planning/proto/dp_poly_path_config.pb.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/log.h"
#include "modules/common/util/file.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/integration_tests/planning_test_base.h"
#include "modules/planning/optimizer/dp_poly_path/dp_road_graph.h"
namespace apollo {
namespace planning {
using common::adapter::AdapterManager;
class DpRoadGraphTest : public PlanningTestBase {
public:
void SetInitPoint() {
init_point_.mutable_path_point()->set_x(pose_.position().x());
init_point_.mutable_path_point()->set_y(pose_.position().y());
const auto& velocity = pose_.linear_velocity();
init_point_.set_v(std::hypot(velocity.x(), velocity.y()));
const auto& acc = pose_.linear_acceleration();
init_point_.set_a(std::hypot(acc.x(), acc.y()));
init_point_.set_relative_time(0.0);
}
void SetSpeedDataWithConstVeolocity(const double velocity) {
// speed point params: s, time, v, a, da
double t = 0.0;
const double delta_s = 1.0;
if (velocity > 0.0) {
for (double s = 0.0; s < 100.0; s += delta_s) {
speed_data_.add_speed_point(s, t, velocity, 0.0, 0.0);
t += delta_s / velocity;
}
} else { // when velocity = 0, stand still
for (double t = 0.0; t < 10.0; t += 0.1) {
speed_data_.add_speed_point(0.0, t, 0.0, 0.0, 0.0);
}
}
}
virtual void SetUp() {
google::InitGoogleLogging("DpRoadGraphTest");
PlanningTestBase::SetUp();
SetInitPoint();
SetSpeedDataWithConstVeolocity(10.0);
const auto* frame = planning_.GetFrame();
ASSERT_TRUE(frame != nullptr);
reference_line_ = &(frame->reference_line());
}
protected:
const ReferenceLine* reference_line_ = nullptr;
DecisionData decision_data_;
common::TrajectoryPoint init_point_;
SpeedData speed_data_; // input
PathData path_data_; // output
};
TEST_F(DpRoadGraphTest, speed_road_graph) {
DPRoadGraph road_graph(dp_poly_path_config_, init_point_, speed_data_);
ASSERT_TRUE(reference_line_ != nullptr);
bool result =
road_graph.FindPathTunnel(*reference_line_, &decision_data_, &path_data_);
EXPECT_TRUE(result);
EXPECT_EQ(648, path_data_.discretized_path().num_of_points());
EXPECT_EQ(648, path_data_.frenet_frame_path().number_of_points());
EXPECT_FLOAT_EQ(70.253212,
path_data_.frenet_frame_path().points().back().s());
EXPECT_FLOAT_EQ(0.0, path_data_.frenet_frame_path().points().back().l());
// export_path_data(path_data_, "/tmp/path.txt");
}
} // namespace planning
} // namespace apollo
<commit_msg>fix dp_road_graph_test.<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <algorithm>
#include <cmath>
#include <iostream>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "modules/planning/proto/dp_poly_path_config.pb.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/log.h"
#include "modules/common/util/file.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/integration_tests/planning_test_base.h"
#include "modules/planning/optimizer/dp_poly_path/dp_road_graph.h"
namespace apollo {
namespace planning {
using common::adapter::AdapterManager;
class DpRoadGraphTest : public PlanningTestBase {
public:
void SetInitPoint() {
init_point_.mutable_path_point()->set_x(pose_.position().x());
init_point_.mutable_path_point()->set_y(pose_.position().y());
const auto& velocity = pose_.linear_velocity();
init_point_.set_v(std::hypot(velocity.x(), velocity.y()));
const auto& acc = pose_.linear_acceleration();
init_point_.set_a(std::hypot(acc.x(), acc.y()));
init_point_.set_relative_time(0.0);
}
void SetSpeedDataWithConstVeolocity(const double velocity) {
// speed point params: s, time, v, a, da
double t = 0.0;
const double delta_s = 1.0;
if (velocity > 0.0) {
for (double s = 0.0; s < 100.0; s += delta_s) {
speed_data_.add_speed_point(s, t, velocity, 0.0, 0.0);
t += delta_s / velocity;
}
} else { // when velocity = 0, stand still
for (double t = 0.0; t < 10.0; t += 0.1) {
speed_data_.add_speed_point(0.0, t, 0.0, 0.0, 0.0);
}
}
}
virtual void SetUp() {
google::InitGoogleLogging("DpRoadGraphTest");
PlanningTestBase::SetUp();
SetInitPoint();
SetSpeedDataWithConstVeolocity(10.0);
const auto* frame = planning_.GetFrame();
ASSERT_TRUE(frame != nullptr);
reference_line_ = &(frame->reference_line());
}
protected:
const ReferenceLine* reference_line_ = nullptr;
DecisionData decision_data_;
common::TrajectoryPoint init_point_;
SpeedData speed_data_; // input
PathData path_data_; // output
};
TEST_F(DpRoadGraphTest, speed_road_graph) {
DPRoadGraph road_graph(dp_poly_path_config_, init_point_, speed_data_);
ASSERT_TRUE(reference_line_ != nullptr);
bool result =
road_graph.FindPathTunnel(*reference_line_, &decision_data_, &path_data_);
EXPECT_TRUE(result);
EXPECT_EQ(648, path_data_.discretized_path().num_of_points());
EXPECT_EQ(648, path_data_.frenet_frame_path().number_of_points());
EXPECT_FLOAT_EQ(72.00795,
path_data_.frenet_frame_path().points().back().s());
EXPECT_FLOAT_EQ(0.0, path_data_.frenet_frame_path().points().back().l());
// export_path_data(path_data_, "/tmp/path.txt");
}
} // namespace planning
} // namespace apollo
<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *
* *
* 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. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#ifndef SOFA_COMPONENT_FORCEFIELD_INTERPOLATIONCONTROLLER_INL
#define SOFA_COMPONENT_FORCEFIELD_INTERPOLATIONCONTROLLER_INL
#include "InterpolationController.h"
#include <sofa/core/behavior/ForceField.inl>
#include <sofa/simulation/common/AnimateBeginEvent.h>
#include <sofa/simulation/common/Simulation.h>
#include <sofa/core/visual/VisualParams.h>
namespace sofa
{
namespace component
{
namespace controller
{
using core::behavior::MechanicalState;
using sofa::defaulttype::Vector3;
template<class DataTypes>
InterpolationController<DataTypes>::InterpolationController()
: fromModel(initLink("original", "Original mesh"))
, toModel(initLink("objective", "Objective mesh"))
//, interpModel(initLink("interpolated", "Objective mesh"))
, f_alphaMax( initData(&f_alphaMax, float(1.0), "alphaMax", "bound defining the max interpolation between the origina (alpha=0) and the objectiv (alpha=1) meshes"))
, f_alpha0( initData(&f_alpha0, float(0.0), "alpha0", "alpha value at t=0. (0 < alpha0 < 1)"))
, f_evolution( initData(&f_evolution, (int)STABLE , "evolution", "O for fixity, 1 for inflation, 2 for deflation"))
, f_period( initData(&f_period, double(1.0), "period", "time to cover all the interpolation positions between original mesh and alpha*(objective mesh), in seconds "))
, f_interpValues(initData(&f_interpValues, "interpValues", "values or the interpolation"))
{
}
template<class DataTypes>
void InterpolationController<DataTypes>::bwdInit() {
if (!fromModel || !toModel ) //|| !interpModel)
{
serr << "One or more MechanicalStates are missing";
return;
}
fromXs = fromModel->getX();
toXs = toModel->getX();
if (fromXs->size() != toXs->size())
{
serr << "<InterpolationController> Different number of nodes between the two meshes (original and objective)";
}
if (f_alpha0.getValue()>=0.0 && f_alpha0.getValue()<=f_alphaMax.getValue())
{
alpha = f_alpha0.getValue();
}
else
{
serr << "<InterpolationController> Wrong value for alpha0";
alpha=0;
}
sofa::helper::WriteAccessor< DataVecCoord > interpValues = f_interpValues;
interpValues.resize(fromXs[0].size());
interpolation(); //interpXs);
}
template<class DataTypes>
void InterpolationController<DataTypes>::interpolation() { //VecCoord &interpXs) {
sofa::helper::WriteAccessor< DataVecCoord > interpValues = f_interpValues;
// interpValues.resize(fromXs[0].size());
for (size_t ptIter=0; ptIter < fromXs[0].size(); ptIter++)
{
for (size_t i=0; i< interpValues[0].size(); i++) //interpXs[0].size(); i++)
{
//interpXs[ptIter][i] = (fromXs[0][ptIter][i] + alpha*(toXs[0][ptIter][i] - fromXs[0][ptIter][i]) );
interpValues[ptIter][i] = (fromXs[0][ptIter][i] + alpha*(toXs[0][ptIter][i] - fromXs[0][ptIter][i]) );
}
}
}
template<class DataTypes>
void InterpolationController<DataTypes>::handleEvent(core::objectmodel::Event *event) {
if (dynamic_cast<sofa::simulation::AnimateBeginEvent *>(event))
{
if (f_evolution.getValue() != STABLE)
{
//helper::WriteAccessor<Data<VecCoord> > interpXData = *interpModel->write(sofa::core::VecCoordId::position());
//VecCoord& interpXs = interpXData.wref();
//dAlpha computation(period,dt)
dAlpha = 1.0 / (f_period.getValue() / this->getContext()->getDt());
//alpha computation(evolution,alpha,alphaMax,dAlpha)
switch (static_cast<Evolution_Type>(f_evolution.getValue()))
{
case INFLATING:
alpha = (alpha <= f_alphaMax.getValue()-dAlpha)? alpha+dAlpha : alpha;
break;
case DEFLATING:
alpha = (alpha >= dAlpha)? alpha-dAlpha : alpha;
break;
default:
break;
}
//interpolation computation(alpha)
interpolation();//interpXs);
if(alpha<dAlpha || alpha>(f_alphaMax.getValue()-dAlpha))
{
f_evolution.setValue(STABLE);
}
}
}
}
template<class DataTypes>
void InterpolationController<DataTypes>::draw(const core::visual::VisualParams* vparams)
{
if ((!vparams->displayFlags().getShowVisualModels()) || f_evolution.getValue()==STABLE) return;
sofa::helper::ReadAccessor< DataVecCoord > interpValues = f_interpValues;
if(interpValues.size() != this->fromXs[0].size()) return;
//const VecCoord *interpXs = interpModel->getX();
defaulttype::Vec<4,float> color;
switch (static_cast<Evolution_Type>(f_evolution.getValue()))
{
case INFLATING:
color = defaulttype::Vec<4,float>(1.0f,0.4f,0.4f,1.0f);
break;
case DEFLATING:
color = defaulttype::Vec<4,float>(0.4f,0.4f,1.0f,1.0f);
break;
default:
break;
}
float norm = Vector3(this->toXs[0][0][0] - this->fromXs[0][0][0], this->toXs[0][0][1] - this->fromXs[0][0][1], this->toXs[0][0][2] - this->fromXs[0][0][2]).norm()/10.0;
for (unsigned ptIter = 0; ptIter < fromXs[0].size(); ptIter += fromXs[0].size()/80)
{
Vector3 p1(interpValues[ptIter][0],interpValues[ptIter][1],interpValues[ptIter][2]), p2;
//Vector3 p1(interpXs[0][ptIter][0],interpXs[0][ptIter][1],interpXs[0][ptIter][2]), p2;
switch (static_cast<Evolution_Type>(f_evolution.getValue()))
{
case INFLATING:
p2 = Vector3(this->toXs[0][ptIter][0],this->toXs[0][ptIter][1],this->toXs[0][ptIter][2]) ;
break;
case DEFLATING:
p2 = Vector3(this->fromXs[0][ptIter][0],this->fromXs[0][ptIter][1],this->fromXs[0][ptIter][2]);
break;
default:
break;
}
vparams->drawTool()->drawArrow(p1,p2, norm, color);
}
}
} // namespace forcefield
} // namespace component
} // namespace sofa
#endif // SOFA_COMPONENT_FORCEFIELD_INTERPOLATIONCONTROLLER_INL
<commit_msg>r10661/sofa : fixing warnings<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *
* *
* 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. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#ifndef SOFA_COMPONENT_FORCEFIELD_INTERPOLATIONCONTROLLER_INL
#define SOFA_COMPONENT_FORCEFIELD_INTERPOLATIONCONTROLLER_INL
#include "InterpolationController.h"
#include <sofa/core/behavior/ForceField.inl>
#include <sofa/simulation/common/AnimateBeginEvent.h>
#include <sofa/simulation/common/Simulation.h>
#include <sofa/core/visual/VisualParams.h>
namespace sofa
{
namespace component
{
namespace controller
{
using core::behavior::MechanicalState;
using sofa::defaulttype::Vector3;
template<class DataTypes>
InterpolationController<DataTypes>::InterpolationController()
: f_evolution( initData(&f_evolution, (int)STABLE , "evolution", "O for fixity, 1 for inflation, 2 for deflation"))
, f_period( initData(&f_period, double(1.0), "period", "time to cover all the interpolation positions between original mesh and alpha*(objective mesh), in seconds "))
, f_alphaMax( initData(&f_alphaMax, float(1.0), "alphaMax", "bound defining the max interpolation between the origina (alpha=0) and the objectiv (alpha=1) meshes"))
, f_alpha0( initData(&f_alpha0, float(0.0), "alpha0", "alpha value at t=0. (0 < alpha0 < 1)"))
, f_interpValues(initData(&f_interpValues, "interpValues", "values or the interpolation"))
, fromModel(initLink("original", "Original mesh"))
, toModel(initLink("objective", "Objective mesh"))
{
}
template<class DataTypes>
void InterpolationController<DataTypes>::bwdInit() {
if (!fromModel || !toModel ) //|| !interpModel)
{
serr << "One or more MechanicalStates are missing";
return;
}
fromXs = fromModel->getX();
toXs = toModel->getX();
if (fromXs->size() != toXs->size())
{
serr << "<InterpolationController> Different number of nodes between the two meshes (original and objective)";
}
if (f_alpha0.getValue()>=0.0 && f_alpha0.getValue()<=f_alphaMax.getValue())
{
alpha = f_alpha0.getValue();
}
else
{
serr << "<InterpolationController> Wrong value for alpha0";
alpha=0;
}
sofa::helper::WriteAccessor< DataVecCoord > interpValues = f_interpValues;
interpValues.resize(fromXs[0].size());
interpolation(); //interpXs);
}
template<class DataTypes>
void InterpolationController<DataTypes>::interpolation() { //VecCoord &interpXs) {
sofa::helper::WriteAccessor< DataVecCoord > interpValues = f_interpValues;
// interpValues.resize(fromXs[0].size());
for (size_t ptIter=0; ptIter < fromXs[0].size(); ptIter++)
{
for (size_t i=0; i< interpValues[0].size(); i++) //interpXs[0].size(); i++)
{
//interpXs[ptIter][i] = (fromXs[0][ptIter][i] + alpha*(toXs[0][ptIter][i] - fromXs[0][ptIter][i]) );
interpValues[ptIter][i] = (fromXs[0][ptIter][i] + alpha*(toXs[0][ptIter][i] - fromXs[0][ptIter][i]) );
}
}
}
template<class DataTypes>
void InterpolationController<DataTypes>::handleEvent(core::objectmodel::Event *event) {
if (dynamic_cast<sofa::simulation::AnimateBeginEvent *>(event))
{
if (f_evolution.getValue() != STABLE)
{
//helper::WriteAccessor<Data<VecCoord> > interpXData = *interpModel->write(sofa::core::VecCoordId::position());
//VecCoord& interpXs = interpXData.wref();
//dAlpha computation(period,dt)
dAlpha = 1.0 / (f_period.getValue() / this->getContext()->getDt());
//alpha computation(evolution,alpha,alphaMax,dAlpha)
switch (static_cast<Evolution_Type>(f_evolution.getValue()))
{
case INFLATING:
alpha = (alpha <= f_alphaMax.getValue()-dAlpha)? alpha+dAlpha : alpha;
break;
case DEFLATING:
alpha = (alpha >= dAlpha)? alpha-dAlpha : alpha;
break;
default:
break;
}
//interpolation computation(alpha)
interpolation();//interpXs);
if(alpha<dAlpha || alpha>(f_alphaMax.getValue()-dAlpha))
{
f_evolution.setValue(STABLE);
}
}
}
}
template<class DataTypes>
void InterpolationController<DataTypes>::draw(const core::visual::VisualParams* vparams)
{
if ((!vparams->displayFlags().getShowVisualModels()) || f_evolution.getValue()==STABLE) return;
sofa::helper::ReadAccessor< DataVecCoord > interpValues = f_interpValues;
if(interpValues.size() != this->fromXs[0].size()) return;
//const VecCoord *interpXs = interpModel->getX();
defaulttype::Vec<4,float> color;
switch (static_cast<Evolution_Type>(f_evolution.getValue()))
{
case INFLATING:
color = defaulttype::Vec<4,float>(1.0f,0.4f,0.4f,1.0f);
break;
case DEFLATING:
color = defaulttype::Vec<4,float>(0.4f,0.4f,1.0f,1.0f);
break;
default:
break;
}
float norm = Vector3(this->toXs[0][0][0] - this->fromXs[0][0][0], this->toXs[0][0][1] - this->fromXs[0][0][1], this->toXs[0][0][2] - this->fromXs[0][0][2]).norm()/10.0;
for (unsigned ptIter = 0; ptIter < fromXs[0].size(); ptIter += fromXs[0].size()/80)
{
Vector3 p1(interpValues[ptIter][0],interpValues[ptIter][1],interpValues[ptIter][2]), p2;
//Vector3 p1(interpXs[0][ptIter][0],interpXs[0][ptIter][1],interpXs[0][ptIter][2]), p2;
switch (static_cast<Evolution_Type>(f_evolution.getValue()))
{
case INFLATING:
p2 = Vector3(this->toXs[0][ptIter][0],this->toXs[0][ptIter][1],this->toXs[0][ptIter][2]) ;
break;
case DEFLATING:
p2 = Vector3(this->fromXs[0][ptIter][0],this->fromXs[0][ptIter][1],this->fromXs[0][ptIter][2]);
break;
default:
break;
}
vparams->drawTool()->drawArrow(p1,p2, norm, color);
}
}
} // namespace forcefield
} // namespace component
} // namespace sofa
#endif // SOFA_COMPONENT_FORCEFIELD_INTERPOLATIONCONTROLLER_INL
<|endoftext|> |
<commit_before>/* Copyright (C) 2005, 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"
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()));
}
Connection::~Connection() {
}
void Connection::socketRead() {
int iAvailable;
while (1) {
iAvailable = qtsSocket->bytesAvailable();
if (iPacketLength == -1) {
if (iAvailable < 2)
return;
unsigned char a_ucBuffer[2];
qtsSocket->read(reinterpret_cast<char *>(a_ucBuffer), 2);
iPacketLength = ((a_ucBuffer[0] << 8) & 0xff00) + a_ucBuffer[1];
iAvailable -= 2;
}
if ((iPacketLength != -1) && (iAvailable >= iPacketLength)) {
QByteArray qbaBuffer = qtsSocket->read(iPacketLength);
emit message(qbaBuffer);
iPacketLength = -1;
} 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(Message *mMsg) {
QByteArray qbaBuffer;
mMsg->messageToNetwork(qbaBuffer);
sendMessage(qbaBuffer);
}
void Connection::sendMessage(QByteArray &qbaMsg) {
unsigned char a_ucBuffer[2];
if (qtsSocket->state() != QAbstractSocket::ConnectedState)
return;
if (qbaMsg.size() > 0xffff) {
qFatal("Connection: Oversized message (%d bytes)", qbaMsg.size());
}
a_ucBuffer[0]=(qbaMsg.size() >> 8) & 0xff;
a_ucBuffer[1]=(qbaMsg.size() & 0xff);
qtsSocket->write(reinterpret_cast<const char *>(a_ucBuffer), 2);
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>UNIX murmur compile fixes<commit_after>/* Copyright (C) 2005, 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"
#ifdef Q_OS_UNIX
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/tcp.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()));
}
Connection::~Connection() {
}
void Connection::socketRead() {
int iAvailable;
while (1) {
iAvailable = qtsSocket->bytesAvailable();
if (iPacketLength == -1) {
if (iAvailable < 2)
return;
unsigned char a_ucBuffer[2];
qtsSocket->read(reinterpret_cast<char *>(a_ucBuffer), 2);
iPacketLength = ((a_ucBuffer[0] << 8) & 0xff00) + a_ucBuffer[1];
iAvailable -= 2;
}
if ((iPacketLength != -1) && (iAvailable >= iPacketLength)) {
QByteArray qbaBuffer = qtsSocket->read(iPacketLength);
emit message(qbaBuffer);
iPacketLength = -1;
} 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(Message *mMsg) {
QByteArray qbaBuffer;
mMsg->messageToNetwork(qbaBuffer);
sendMessage(qbaBuffer);
}
void Connection::sendMessage(QByteArray &qbaMsg) {
unsigned char a_ucBuffer[2];
if (qtsSocket->state() != QAbstractSocket::ConnectedState)
return;
if (qbaMsg.size() > 0xffff) {
qFatal("Connection: Oversized message (%d bytes)", qbaMsg.size());
}
a_ucBuffer[0]=(qbaMsg.size() >> 8) & 0xff;
a_ucBuffer[1]=(qbaMsg.size() & 0xff);
qtsSocket->write(reinterpret_cast<const char *>(a_ucBuffer), 2);
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 "lutin.h"
using namespace lutinCompiler;
//implementation of the State5 class methods
State5 :: State5(const char* name) : State(name)
{
}
void State5 ::print()
{
State::print();
}
bool State5 ::transition(Automat &automat, Symbol *s)
{
switch(*s)
{
case ID_TOKEN: automat.shift(s,new State8("Etat 8"));
break;
default : errorDiagnostic(s);
}
return false;
}
void State5::errorDiagnostic(Symbol *s)
{
}
//implementation of the State8 class methods
State8 :: State8(const char* name) : State(name)
{
}
void State8 ::print()
{
State::print();
}
bool State8 ::transition(Automat &automat, Symbol *s)
{
switch(*s)
{
case EQ_TOKEN: automat.shift(s,new State9("Etat 9"));
break;
default : errorDiagnostic(s);
}
return false;
}
void State8::errorDiagnostic(Symbol *s)
{
}
//implementation of the State9 class methods
State9 :: State9(const char* name) : State(name)
{
}
void State9 ::print()
{
}
bool State9 ::transition(Automat &automat, Symbol *s)
{
switch(*s)
{
case NUM_TOKEN: automat.shift(s,new State20("Etat 20"));
break;
default : errorDiagnostic(s);
}
return false;
}
void State9::errorDiagnostic(Symbol *s)
{
}
//implementation of the State20 class methods
State20 :: State20(const char* name) : State(name)
{
}
void State20 ::print()
{
}
bool State20 ::transition(Automat &automat, Symbol *s)
{
switch(*s)
{
case SEM_TOKEN: //automat.reduce(new NoTerminalSymbolConstDec(),0);
break;
case COM_TOKEN: //automat.reduce(new NoTerminalSymbolConstDec(),0);
break;
default : errorDiagnostic(s);
}
return false;
}
void State20::errorDiagnostic(Symbol *s)
{
}
//implementation of the State21 class methods
State21 :: State21(const char* name) : State(name)
{
}
void State21 ::print()
{
}
bool State21 ::transition(Automat &automat, Symbol *s)
{
switch(*s)
{
case SEM_TOKEN: automat.shift(s,new State22("Etat 22"));
break;
case COM_TOKEN: automat.shift(s,new State49("Etat 49"));
break;
default : errorDiagnostic(s);
}
return false;
}
void State21::errorDiagnostic(Symbol *s)
{
}
//implementation of the State22 class methods
State22 :: State22(const char* name) : State(name)
{
}
void State22 ::print()
{
}
bool State22 ::transition(Automat &automat, Symbol *s)
{
switch(*s)
{
case VAR_TOKEN: automat.shift(s,new State4("Etat 4"));
break;
case CONST_TOKEN: automat.shift(s,new State5("Etat 5"));
break;
case WRITE_TOKEN: //automat.reduce(new NoTerminalSymbolDec(),0);
break;
case READ_TOKEN: //automat.reduce(new NoTerminalSymbolDec(),0);
break;
case ID_TOKEN: //automat.reduce(new NoTerminalSymbolDec(),0);
break;
case EOF_TOKEN: //automat.reduce(new NoTerminalSymbolDec(),0);
break;
case TOKEN_DEC: automat.shift(s,new State23("Etat 23"));
break;
case TOKEN_VAR: automat.shift(s,new State2("Etat 2"));
break;
case TOKEN_CONST: automat.shift(s,new State3("Etat 3"));
break;
default : errorDiagnostic(s);
}
return false;
}
void State22::errorDiagnostic(Symbol *s)
{
}
//implementation of the State23 class methods
State23 :: State23(const char* name) : State(name)
{
}
void State23 ::print()
{
}
bool State23 ::transition(Automat &automat, Symbol *s)
{
switch(*s)
{
case WRITE_TOKEN: //automat.reduce(new NoTerminalSymbolConst(),7);
break;
case READ_TOKEN: //automat.reduce(new NoTerminalSymbolConst(),7);
break;
case ID_TOKEN: //automat.reduce(new NoTerminalSymbolConst(),7);
break;
case EOF_TOKEN: //automat.reduce(new NoTerminalSymbolConst(),7);
break;
default : errorDiagnostic(s);
}
return false;
}
void State23::errorDiagnostic(Symbol *s)
{
}
//implementation of the State24 class methods
State24 :: State24(const char* name) : State(name)
{
}
void State24 ::print()
{
}
bool State24 ::transition(Automat &automat, Symbol *s)
{
switch(*s)
{
case EQ_TOKEN: automat.shift(s,new State25("Etat 25"));
break;
default : errorDiagnostic(s);
}
return false;
}
void State24::errorDiagnostic(Symbol *s)
{
}
//implementation of the State25 class methods
State25 :: State25(const char* name) : State(name)
{
}
void State25 ::print()
{
}
bool State25 ::transition(Automat &automat, Symbol *s)
{
switch(*s)
{
case NUM_TOKEN: automat.shift(s,new State26("Etat 26"));
break;
default : errorDiagnostic(s);
}
return false;
}
void State25::errorDiagnostic(Symbol *s)
{
}
//implementation of the State26 class methods
State26 :: State26(const char* name) : State(name)
{
}
void State26 ::print()
{
}
bool State26 ::transition(Automat &automat, Symbol *s)
{
switch(*s)
{
case COM_TOKEN: //automat.reduce(new NoTerminalSymbolConstDec(),5);
break;
case SEM_TOKEN: //automat.reduce(new NoTerminalSymbolConstDec(),5);
break;
default : errorDiagnostic(s);
}
return false;
}
void State26::errorDiagnostic(Symbol *s)
{
}
//implementation of the State26 class methods
State49 :: State49(const char* name) : State(name)
{
}
void State49 ::print()
{
}
bool State49 ::transition(Automat &automat, Symbol *s)
{
switch(*s)
{
case SEM_TOKEN: automat.shift(s,new State24("Etat24"));
break;
default : errorDiagnostic(s);
}
return false;
}
void State49::errorDiagnostic(Symbol *s)
{
}<commit_msg>Modification on ConstCPP<commit_after>#include "lutin.h"
using namespace lutinCompiler;
//implementation of the State5 class methods
State5 :: State5(const char* name) : State(name)
{
}
void State5 ::print()
{
State::print();
}
bool State5 ::transition(Automat &automat, Symbol *s)
{
switch(*s)
{
case ID_TOKEN: automat.shift(s,new State8("Etat 8"));
break;
default : errorDiagnostic(s);
}
return false;
}
void State5::errorDiagnostic(Symbol *s)
{
}
//implementation of the State8 class methods
State8 :: State8(const char* name) : State(name)
{
}
void State8 ::print()
{
State::print();
}
bool State8 ::transition(Automat &automat, Symbol *s)
{
switch(*s)
{
case EQ_TOKEN: automat.shift(s,new State9("Etat 9"));
break;
default : errorDiagnostic(s);
}
return false;
}
void State8::errorDiagnostic(Symbol *s)
{
}
//implementation of the State9 class methods
State9 :: State9(const char* name) : State(name)
{
}
void State9 ::print()
{
State::print();
}
bool State9 ::transition(Automat &automat, Symbol *s)
{
switch(*s)
{
case NUM_TOKEN: automat.shift(s,new State20("Etat 20"));
break;
default : errorDiagnostic(s);
}
return false;
}
void State9::errorDiagnostic(Symbol *s)
{
}
//implementation of the State20 class methods
State20 :: State20(const char* name) : State(name)
{
}
void State20 ::print()
{
State::print();
}
bool State20 ::transition(Automat &automat, Symbol *s)
{
switch(*s)
{
case SEM_TOKEN: //automat.reduce(new NoTerminalSymbolConstDec(),0);
break;
case COM_TOKEN: //automat.reduce(new NoTerminalSymbolConstDec(),0);
break;
default : errorDiagnostic(s);
}
return false;
}
void State20::errorDiagnostic(Symbol *s)
{
}
//implementation of the State21 class methods
State21 :: State21(const char* name) : State(name)
{
}
void State21 ::print()
{
State::print();
}
bool State21 ::transition(Automat &automat, Symbol *s)
{
switch(*s)
{
case SEM_TOKEN: automat.shift(s,new State22("Etat 22"));
break;
case COM_TOKEN: automat.shift(s,new State49("Etat 49"));
break;
default : errorDiagnostic(s);
}
return false;
}
void State21::errorDiagnostic(Symbol *s)
{
}
//implementation of the State22 class methods
State22 :: State22(const char* name) : State(name)
{
}
void State22 ::print()
{
State::print();
}
bool State22 ::transition(Automat &automat, Symbol *s)
{
switch(*s)
{
case VAR_TOKEN: automat.shift(s,new State4("Etat 4"));
break;
case CONST_TOKEN: automat.shift(s,new State5("Etat 5"));
break;
case WRITE_TOKEN: //automat.reduce(new NoTerminalSymbolDec(),0);
break;
case READ_TOKEN: //automat.reduce(new NoTerminalSymbolDec(),0);
break;
case ID_TOKEN: //automat.reduce(new NoTerminalSymbolDec(),0);
break;
case EOF_TOKEN: //automat.reduce(new NoTerminalSymbolDec(),0);
break;
case TOKEN_DEC: automat.shift(s,new State23("Etat 23"));
break;
case TOKEN_VAR: automat.shift(s,new State2("Etat 2"));
break;
case TOKEN_CONST: automat.shift(s,new State3("Etat 3"));
break;
default : errorDiagnostic(s);
}
return false;
}
void State22::errorDiagnostic(Symbol *s)
{
}
//implementation of the State23 class methods
State23 :: State23(const char* name) : State(name)
{
}
void State23 ::print()
{
State::print();
}
bool State23 ::transition(Automat &automat, Symbol *s)
{
switch(*s)
{
case WRITE_TOKEN: //automat.reduce(new NoTerminalSymbolConst(),7);
break;
case READ_TOKEN: //automat.reduce(new NoTerminalSymbolConst(),7);
break;
case ID_TOKEN: //automat.reduce(new NoTerminalSymbolConst(),7);
break;
case EOF_TOKEN: //automat.reduce(new NoTerminalSymbolConst(),7);
break;
default : errorDiagnostic(s);
}
return false;
}
void State23::errorDiagnostic(Symbol *s)
{
}
//implementation of the State24 class methods
State24 :: State24(const char* name) : State(name)
{
}
void State24 ::print()
{
State::print();
}
bool State24 ::transition(Automat &automat, Symbol *s)
{
switch(*s)
{
case EQ_TOKEN: automat.shift(s,new State25("Etat 25"));
break;
default : errorDiagnostic(s);
}
return false;
}
void State24::errorDiagnostic(Symbol *s)
{
}
//implementation of the State25 class methods
State25 :: State25(const char* name) : State(name)
{
}
void State25 ::print()
{
State::print();
}
bool State25 ::transition(Automat &automat, Symbol *s)
{
switch(*s)
{
case NUM_TOKEN: automat.shift(s,new State26("Etat 26"));
break;
default : errorDiagnostic(s);
}
return false;
}
void State25::errorDiagnostic(Symbol *s)
{
}
//implementation of the State26 class methods
State26 :: State26(const char* name) : State(name)
{
}
void State26 ::print()
{
State::print();
}
bool State26 ::transition(Automat &automat, Symbol *s)
{
switch(*s)
{
case COM_TOKEN: //automat.reduce(new NoTerminalSymbolConstDec(),5);
break;
case SEM_TOKEN: //automat.reduce(new NoTerminalSymbolConstDec(),5);
break;
default : errorDiagnostic(s);
}
return false;
}
void State26::errorDiagnostic(Symbol *s)
{
}
//implementation of the State26 class methods
State49 :: State49(const char* name) : State(name)
{
}
void State49 ::print()
{
State::print();
}
bool State49 ::transition(Automat &automat, Symbol *s)
{
switch(*s)
{
case SEM_TOKEN: automat.shift(s,new State24("Etat24"));
break;
default : errorDiagnostic(s);
}
return false;
}
void State49::errorDiagnostic(Symbol *s)
{
}<|endoftext|> |
<commit_before>
// -*- mode: c++; c-basic-offset:4 -*-
// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.
// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <[email protected]>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
// (c) COPYRIGHT URI/MIT 1995-1999
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
// jhrg,jimg James Gallagher <[email protected]>
#ifdef _GNUG_
// #pragma implementation
#endif
#include "config_dap.h"
#include <string>
#include <algorithm>
#ifdef WIN32
#include <functional>
#endif
#include "Constructor.h"
#include "BTIterAdapter.h"
#include "debug.h"
#include "escaping.h"
#include "Error.h"
#include "InternalErr.h"
#ifdef TRACE_NEW
#include "trace_new.h"
#endif
using namespace std;
// Private member functions
void
Constructor::_duplicate(const Constructor &s)
{
}
// Public member functions
Constructor::Constructor(const string &n, const Type &t)
: BaseType(n, t)
{
}
Constructor::Constructor(const Constructor &rhs) : BaseType(rhs)
{
}
Constructor::~Constructor()
{
}
Constructor &
Constructor::operator=(const Constructor &rhs)
{
if (this == &rhs)
return *this;
dynamic_cast<BaseType &>(*this) = rhs; // run BaseType=
_duplicate(rhs);
return *this;
}
/** @name Pix interface; deprecated */
//@{
/** @brief Returns an index to the first variable in a Constructor instance.
For a Structure, this returns the first variable, for a Sequence, it is
the template of the variable in the first column.
*/
Pix
Constructor::first_var()
{
if (_vars.empty())
return 0;
BTIterAdapter *i = new BTIterAdapter( _vars ) ;
i->first() ;
return i ;
}
/** @brief Increments the Constructor instance.
This returns a pointer to the
next ``column'' in the Constructor, not the next row. */
void
Constructor::next_var(Pix p)
{
p.next() ;
}
/** @brief Returns a pointer to a Constructor member.
This may be another Constructor. */
BaseType *
Constructor::var(Pix p)
{
BTIterAdapter *i = (BTIterAdapter *)p.getIterator() ;
if( i ) {
return i->entry() ;
}
return 0 ;
}
//@}
/** Returns an iterator referencing the first structure element. */
Constructor::Vars_iter
Constructor::var_begin()
{
return _vars.begin() ;
}
/** Returns an iterator referencing the end of the list of structure
elements. Does not reference the last structure element. */
Constructor::Vars_iter
Constructor::var_end()
{
return _vars.end() ;
}
/** Return the iterator for the \i ith variable.
@param i the index
@return The corresponding Vars_iter */
Constructor::Vars_iter
Constructor::get_vars_iter(int i)
{
return _vars.begin() + i;
}
void
Constructor::print_decl(ostream &os, string space, bool print_semi,
bool constraint_info, bool constrained)
{
if (constrained && !send_p())
return;
os << space << type_name() << " {" << endl;
for (Vars_iter i = _vars.begin(); i != _vars.end(); i++)
{
(*i)->print_decl(os, space + " ", true,
constraint_info, constrained);
}
os << space << "} " << id2www(name());
if (constraint_info) { // Used by test drivers only.
if (send_p())
cout << ": Send True";
else
cout << ": Send False";
}
if (print_semi)
os << ";" << endl;
}
void
Constructor::print_decl(FILE *out, string space, bool print_semi,
bool constraint_info, bool constrained)
{
if (constrained && !send_p())
return;
fprintf( out, "%s%s {\n", space.c_str(), type_name().c_str() ) ;
for (Vars_citer i = _vars.begin(); i != _vars.end(); i++)
{
(*i)->print_decl(out, space + " ", true,
constraint_info, constrained);
}
fprintf( out, "%s} %s", space.c_str(), id2www( name() ).c_str() ) ;
if (constraint_info) { // Used by test drivers only.
if (send_p())
cout << ": Send True";
else
cout << ": Send False";
}
if (print_semi)
fprintf( out, ";\n" ) ;
}
class PrintField : public unary_function<BaseType *, void> {
FILE *d_out;
string d_space;
bool d_constrained;
public:
PrintField(FILE *o, string s, bool c)
: d_out(o), d_space(s), d_constrained(c) {}
void operator()(BaseType *btp) {
btp->print_xml(d_out, d_space, d_constrained);
}
};
void
Constructor::print_xml(FILE *out, string space, bool constrained)
{
bool has_attributes = false; // *** fix me
bool has_variables = (var_begin() != var_end());
fprintf(out, "%s<%s", space.c_str(), type_name().c_str());
if (!name().empty())
fprintf(out, " name=\"%s\"", id2xml(name()).c_str());
if (has_attributes || has_variables) {
fprintf(out, ">\n");
get_attr_table().print_xml(out, space + " ", constrained);
for_each(var_begin(), var_end(),
PrintField(out, space + " ", constrained));
fprintf(out, "%s<%s/>\n", space.c_str(), type_name().c_str());
}
else {
fprintf(out, "/>\n");
}
}
/** True if the instance can be flattened and printed as a single table
of values. For Arrays and Grids this is always false. For Structures
and Sequences the conditions are more complex. The implementation
provided by this class always returns false. Other classes should
override this implementation.
@todo Change the name to is_flattenable or something like that. 05/16/03
jhrg
@brief Check to see whether this variable can be printed simply.
@return True if the instance can be printed as a single table of
values, false otherwise. */
bool
Constructor::is_linear()
{
return false;
}
// $Log: Constructor.cc,v $
// Revision 1.13 2004/07/19 07:25:42 rmorris
// #include <functional> for "unary_function" under win32.
//
// Revision 1.12 2004/07/07 21:08:47 jimg
// Merged with release-3-4-8FCS
//
// Revision 1.8.2.3 2004/07/02 20:41:51 jimg
// Removed (commented) the pragma interface/implementation lines. See
// the ChangeLog for more details. This fixes a build problem on HP/UX.
//
// Revision 1.11 2003/12/10 21:11:57 jimg
// Merge with 3.4. Some of the files contains erros (some tests fail). See
// the ChangeLog for information about fixes.
//
// Revision 1.10 2003/12/08 18:02:29 edavis
// Merge release-3-4 into trunk
//
// Revision 1.8.2.2 2003/09/06 22:37:50 jimg
// Updated the documentation.
//
// Revision 1.8.2.1 2003/06/05 20:15:25 jimg
// Removed many uses of strstream and replaced them with stringstream.
//
// Revision 1.9 2003/05/23 03:24:57 jimg
// Changes that add support for the DDX response. I've based this on Nathan
// Potter's work in the Java DAP software. At this point the code can
// produce a DDX from a DDS and it can merge attributes from a DAS into a
// DDS to produce a DDX fully loaded with attributes. Attribute aliases
// are not supported yet. I've also removed all traces of strstream in
// favor of stringstream. This code should no longer generate warnings
// about the use of deprecated headers.
//
// Revision 1.8 2003/04/22 19:40:27 jimg
// Merged with 3.3.1.
//
// Revision 1.7 2003/02/21 00:14:24 jimg
// Repaired copyright.
//
// Revision 1.6.2.1 2003/02/21 00:10:07 jimg
// Repaired copyright.
//
// Revision 1.6 2003/01/23 00:22:24 jimg
// Updated the copyright notice; this implementation of the DAP is
// copyrighted by OPeNDAP, Inc.
//
// Revision 1.5 2003/01/10 19:46:40 jimg
// Merged with code tagged release-3-2-10 on the release-3-2 branch. In many
// cases files were added on that branch (so they appear on the trunk for
// the first time).
//
// Revision 1.1.2.3 2002/08/08 06:54:56 jimg
// Changes for thread-safety. In many cases I found ugly places at the
// tops of files while looking for globals, et c., and I fixed them up
// (hopefully making them easier to read, ...). Only the files RCReader.cc
// and usage.cc actually use pthreads synchronization functions. In other
// cases I removed static objects where they were used for supposed
// improvements in efficiency which had never actually been verifiied (and
// which looked dubious).
//
// Revision 1.4 2002/06/18 15:36:24 tom
// Moved comments and edited to accommodate doxygen documentation-generator.
//
// Revision 1.3 2001/09/28 17:50:07 jimg
// Merged with 3.2.7.
//
// Revision 1.1.2.2 2001/09/25 20:35:28 jimg
// Added a default definition for is_linear().
//
// Revision 1.2 2001/06/15 23:49:01 jimg
// Merged with release-3-2-4.
//
// Revision 1.1.2.1 2001/06/05 16:04:39 jimg
// Created.
//
<commit_msg>Added accessors for the new reverse iterators. Also added a new method to access variables using an integer index.<commit_after>
// -*- mode: c++; c-basic-offset:4 -*-
// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.
// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <[email protected]>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
// (c) COPYRIGHT URI/MIT 1995-1999
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
// jhrg,jimg James Gallagher <[email protected]>
#ifdef _GNUG_
// #pragma implementation
#endif
#include "config_dap.h"
#include <string>
#include <algorithm>
#ifdef WIN32
#include <functional>
#endif
#include "Constructor.h"
#include "BTIterAdapter.h"
#include "debug.h"
#include "escaping.h"
#include "Error.h"
#include "InternalErr.h"
#ifdef TRACE_NEW
#include "trace_new.h"
#endif
using namespace std;
// Private member functions
void
Constructor::_duplicate(const Constructor &s)
{
}
// Public member functions
Constructor::Constructor(const string &n, const Type &t)
: BaseType(n, t)
{
}
Constructor::Constructor(const Constructor &rhs) : BaseType(rhs)
{
}
Constructor::~Constructor()
{
}
Constructor &
Constructor::operator=(const Constructor &rhs)
{
if (this == &rhs)
return *this;
dynamic_cast<BaseType &>(*this) = rhs; // run BaseType=
_duplicate(rhs);
return *this;
}
/** @name Pix interface; deprecated */
//@{
/** @brief Returns an index to the first variable in a Constructor instance.
For a Structure, this returns the first variable, for a Sequence, it is
the template of the variable in the first column.
*/
Pix
Constructor::first_var()
{
if (_vars.empty())
return 0;
BTIterAdapter *i = new BTIterAdapter( _vars ) ;
i->first() ;
return i ;
}
/** @brief Increments the Constructor instance.
This returns a pointer to the
next ``column'' in the Constructor, not the next row. */
void
Constructor::next_var(Pix p)
{
p.next() ;
}
/** @brief Returns a pointer to a Constructor member.
This may be another Constructor. */
BaseType *
Constructor::var(Pix p)
{
BTIterAdapter *i = (BTIterAdapter *)p.getIterator() ;
if( i ) {
return i->entry() ;
}
return 0 ;
}
//@}
/** Returns an iterator referencing the first structure element. */
Constructor::Vars_iter
Constructor::var_begin()
{
return _vars.begin() ;
}
/** Returns an iterator referencing the end of the list of structure
elements. Does not reference the last structure element. */
Constructor::Vars_iter
Constructor::var_end()
{
return _vars.end() ;
}
/** Return a reverse iterator that references the last element. */
Constructor::Vars_riter
Constructor::var_rbegin()
{
return _vars.rbegin();
}
/** Return a reverse iterator that references a point 'before' the first
element. */
Constructor::Vars_riter
Constructor::var_rend()
{
return _vars.rend();
}
/** Return the iterator for the \i ith variable.
@param i the index
@return The corresponding Vars_iter */
Constructor::Vars_iter
Constructor::get_vars_iter(int i)
{
return _vars.begin() + i;
}
/** Return the BaseType pointer for the \e ith variable.
@param i This index
@return The corresponding BaseType*. */
BaseType *
Constructor::get_var_index(int i)
{
return *(_vars.begin() + i);
}
void
Constructor::print_decl(ostream &os, string space, bool print_semi,
bool constraint_info, bool constrained)
{
if (constrained && !send_p())
return;
os << space << type_name() << " {" << endl;
for (Vars_iter i = _vars.begin(); i != _vars.end(); i++)
{
(*i)->print_decl(os, space + " ", true,
constraint_info, constrained);
}
os << space << "} " << id2www(name());
if (constraint_info) { // Used by test drivers only.
if (send_p())
cout << ": Send True";
else
cout << ": Send False";
}
if (print_semi)
os << ";" << endl;
}
void
Constructor::print_decl(FILE *out, string space, bool print_semi,
bool constraint_info, bool constrained)
{
if (constrained && !send_p())
return;
fprintf( out, "%s%s {\n", space.c_str(), type_name().c_str() ) ;
for (Vars_citer i = _vars.begin(); i != _vars.end(); i++)
{
(*i)->print_decl(out, space + " ", true,
constraint_info, constrained);
}
fprintf( out, "%s} %s", space.c_str(), id2www( name() ).c_str() ) ;
if (constraint_info) { // Used by test drivers only.
if (send_p())
cout << ": Send True";
else
cout << ": Send False";
}
if (print_semi)
fprintf( out, ";\n" ) ;
}
class PrintField : public unary_function<BaseType *, void> {
FILE *d_out;
string d_space;
bool d_constrained;
public:
PrintField(FILE *o, string s, bool c)
: d_out(o), d_space(s), d_constrained(c) {}
void operator()(BaseType *btp) {
btp->print_xml(d_out, d_space, d_constrained);
}
};
void
Constructor::print_xml(FILE *out, string space, bool constrained)
{
bool has_attributes = false; // *** fix me
bool has_variables = (var_begin() != var_end());
fprintf(out, "%s<%s", space.c_str(), type_name().c_str());
if (!name().empty())
fprintf(out, " name=\"%s\"", id2xml(name()).c_str());
if (has_attributes || has_variables) {
fprintf(out, ">\n");
get_attr_table().print_xml(out, space + " ", constrained);
for_each(var_begin(), var_end(),
PrintField(out, space + " ", constrained));
fprintf(out, "%s<%s/>\n", space.c_str(), type_name().c_str());
}
else {
fprintf(out, "/>\n");
}
}
/** True if the instance can be flattened and printed as a single table
of values. For Arrays and Grids this is always false. For Structures
and Sequences the conditions are more complex. The implementation
provided by this class always returns false. Other classes should
override this implementation.
@todo Change the name to is_flattenable or something like that. 05/16/03
jhrg
@brief Check to see whether this variable can be printed simply.
@return True if the instance can be printed as a single table of
values, false otherwise. */
bool
Constructor::is_linear()
{
return false;
}
// $Log: Constructor.cc,v $
// Revision 1.14 2004/11/16 17:56:05 jimg
// Added accessors for the new reverse iterators. Also added a new method
// to access variables using an integer index.
//
// Revision 1.13 2004/07/19 07:25:42 rmorris
// #include <functional> for "unary_function" under win32.
//
// Revision 1.12 2004/07/07 21:08:47 jimg
// Merged with release-3-4-8FCS
//
// Revision 1.8.2.3 2004/07/02 20:41:51 jimg
// Removed (commented) the pragma interface/implementation lines. See
// the ChangeLog for more details. This fixes a build problem on HP/UX.
//
// Revision 1.11 2003/12/10 21:11:57 jimg
// Merge with 3.4. Some of the files contains erros (some tests fail). See
// the ChangeLog for information about fixes.
//
// Revision 1.10 2003/12/08 18:02:29 edavis
// Merge release-3-4 into trunk
//
// Revision 1.8.2.2 2003/09/06 22:37:50 jimg
// Updated the documentation.
//
// Revision 1.8.2.1 2003/06/05 20:15:25 jimg
// Removed many uses of strstream and replaced them with stringstream.
//
// Revision 1.9 2003/05/23 03:24:57 jimg
// Changes that add support for the DDX response. I've based this on Nathan
// Potter's work in the Java DAP software. At this point the code can
// produce a DDX from a DDS and it can merge attributes from a DAS into a
// DDS to produce a DDX fully loaded with attributes. Attribute aliases
// are not supported yet. I've also removed all traces of strstream in
// favor of stringstream. This code should no longer generate warnings
// about the use of deprecated headers.
//
// Revision 1.8 2003/04/22 19:40:27 jimg
// Merged with 3.3.1.
//
// Revision 1.7 2003/02/21 00:14:24 jimg
// Repaired copyright.
//
// Revision 1.6.2.1 2003/02/21 00:10:07 jimg
// Repaired copyright.
//
// Revision 1.6 2003/01/23 00:22:24 jimg
// Updated the copyright notice; this implementation of the DAP is
// copyrighted by OPeNDAP, Inc.
//
// Revision 1.5 2003/01/10 19:46:40 jimg
// Merged with code tagged release-3-2-10 on the release-3-2 branch. In many
// cases files were added on that branch (so they appear on the trunk for
// the first time).
//
// Revision 1.1.2.3 2002/08/08 06:54:56 jimg
// Changes for thread-safety. In many cases I found ugly places at the
// tops of files while looking for globals, et c., and I fixed them up
// (hopefully making them easier to read, ...). Only the files RCReader.cc
// and usage.cc actually use pthreads synchronization functions. In other
// cases I removed static objects where they were used for supposed
// improvements in efficiency which had never actually been verifiied (and
// which looked dubious).
//
// Revision 1.4 2002/06/18 15:36:24 tom
// Moved comments and edited to accommodate doxygen documentation-generator.
//
// Revision 1.3 2001/09/28 17:50:07 jimg
// Merged with 3.2.7.
//
// Revision 1.1.2.2 2001/09/25 20:35:28 jimg
// Added a default definition for is_linear().
//
// Revision 1.2 2001/06/15 23:49:01 jimg
// Merged with release-3-2-4.
//
// Revision 1.1.2.1 2001/06/05 16:04:39 jimg
// Created.
//
<|endoftext|> |
<commit_before>
// -*- mode: c++; c-basic-offset:4 -*-
// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.
// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <[email protected]>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
// (c) COPYRIGHT URI/MIT 1995-1999
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
// jhrg,jimg James Gallagher <[email protected]>
#include "config.h"
#include <string>
#include <algorithm>
#include <functional>
#include "Constructor.h"
//#include "BTIterAdapter.h"
#include "debug.h"
#include "escaping.h"
#include "Error.h"
#include "InternalErr.h"
using namespace std;
// Private member functions
void
Constructor::_duplicate(const Constructor &)
{
}
// Public member functions
Constructor::Constructor(const string &n, const Type &t)
: BaseType(n, t)
{
}
Constructor::Constructor(const Constructor &rhs) : BaseType(rhs)
{
}
Constructor::~Constructor()
{
}
Constructor &
Constructor::operator=(const Constructor &rhs)
{
if (this == &rhs)
return *this;
dynamic_cast<BaseType &>(*this) = rhs; // run BaseType=
_duplicate(rhs);
return *this;
}
/** Returns an iterator referencing the first structure element. */
Constructor::Vars_iter
Constructor::var_begin()
{
return _vars.begin() ;
}
/** Returns an iterator referencing the end of the list of structure
elements. Does not reference the last structure element. */
Constructor::Vars_iter
Constructor::var_end()
{
return _vars.end() ;
}
/** Return a reverse iterator that references the last element. */
Constructor::Vars_riter
Constructor::var_rbegin()
{
return _vars.rbegin();
}
/** Return a reverse iterator that references a point 'before' the first
element. */
Constructor::Vars_riter
Constructor::var_rend()
{
return _vars.rend();
}
/** Return the iterator for the \e ith variable.
@param i the index
@return The corresponding Vars_iter */
Constructor::Vars_iter
Constructor::get_vars_iter(int i)
{
return _vars.begin() + i;
}
/** Return the BaseType pointer for the \e ith variable.
@param i This index
@return The corresponding BaseType*. */
BaseType *
Constructor::get_var_index(int i)
{
return *(_vars.begin() + i);
}
void
Constructor::print_decl(FILE *out, string space, bool print_semi,
bool constraint_info, bool constrained)
{
if (constrained && !send_p())
return;
fprintf( out, "%s%s {\n", space.c_str(), type_name().c_str() ) ;
for (Vars_citer i = _vars.begin(); i != _vars.end(); i++)
{
(*i)->print_decl(out, space + " ", true,
constraint_info, constrained);
}
fprintf( out, "%s} %s", space.c_str(), id2www( name() ).c_str() ) ;
if (constraint_info) { // Used by test drivers only.
if (send_p())
cout << ": Send True";
else
cout << ": Send False";
}
if (print_semi)
fprintf( out, ";\n" ) ;
}
class PrintField : public unary_function<BaseType *, void> {
FILE *d_out;
string d_space;
bool d_constrained;
public:
PrintField(FILE *o, string s, bool c)
: d_out(o), d_space(s), d_constrained(c) {}
void operator()(BaseType *btp) {
btp->print_xml(d_out, d_space, d_constrained);
}
};
void
Constructor::print_xml(FILE *out, string space, bool constrained)
{
if (constrained && !send_p())
return;
bool has_attributes = false; // *** fix me
bool has_variables = (var_begin() != var_end());
fprintf(out, "%s<%s", space.c_str(), type_name().c_str());
if (!name().empty())
fprintf(out, " name=\"%s\"", id2xml(name()).c_str());
if (has_attributes || has_variables) {
fprintf(out, ">\n");
get_attr_table().print_xml(out, space + " ", constrained);
for_each(var_begin(), var_end(),
PrintField(out, space + " ", constrained));
fprintf(out, "%s</%s>\n", space.c_str(), type_name().c_str());
}
else {
fprintf(out, "/>\n");
}
}
/** True if the instance can be flattened and printed as a single table
of values. For Arrays and Grids this is always false. For Structures
and Sequences the conditions are more complex. The implementation
provided by this class always returns false. Other classes should
override this implementation.
@todo Change the name to is_flattenable or something like that. 05/16/03
jhrg
@brief Check to see whether this variable can be printed simply.
@return True if the instance can be printed as a single table of
values, false otherwise. */
bool
Constructor::is_linear()
{
return false;
}
<commit_msg>Constructor: Added code to merge attributes into a constructor. This method is called from DDS.<commit_after>
// -*- mode: c++; c-basic-offset:4 -*-
// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.
// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <[email protected]>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
// (c) COPYRIGHT URI/MIT 1995-1999
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
// jhrg,jimg James Gallagher <[email protected]>
#include "config.h"
#include <string>
#include <algorithm>
#include <functional>
#define DODS_DEBUG
#include "Constructor.h"
#include "Grid.h"
//#include "BTIterAdapter.h"
#include "debug.h"
#include "escaping.h"
#include "Error.h"
#include "InternalErr.h"
using namespace std;
// Private member functions
void
Constructor::_duplicate(const Constructor &)
{
}
// Public member functions
Constructor::Constructor(const string &n, const Type &t)
: BaseType(n, t)
{
}
Constructor::Constructor(const Constructor &rhs) : BaseType(rhs)
{
}
Constructor::~Constructor()
{
}
Constructor &
Constructor::operator=(const Constructor &rhs)
{
if (this == &rhs)
return *this;
dynamic_cast<BaseType &>(*this) = rhs; // run BaseType=
_duplicate(rhs);
return *this;
}
/** Returns an iterator referencing the first structure element. */
Constructor::Vars_iter
Constructor::var_begin()
{
return _vars.begin() ;
}
/** @brief Look for the parent of an HDF4 dimension attribute
If this attribute container's name ends in the '_dim_?' suffix, look
for the variable to which it's attributes should be bound: For an array,
they should be held in a sub-table of the array; for a Structure or
Sequence, I don't think the HDF4 handler ever makes these (since those
types don't have 'dimension' in hdf-land); and for a Grid, the attributes
belong with the map variables.
@note This method does check that the \e source really is an hdf4 dimension
attribute.
@param source The attribute container, an AttrTable::entry instance.
@return the BaseType to which these attributes belong or null if none
was found. */
BaseType *
Constructor::find_hdf4_dimension_attribute_home(AttrTable::entry *source)
{
BaseType *btp;
string::size_type i = source->name.find("_dim_");
if (i != string::npos && (btp = var(source->name.substr(0, i)))) {
if (btp->is_vector_type()) {
return btp;
}
else if (btp->type() == dods_grid_c) {
// For a Grid, the hdf4 handler uses _dim_n for the n-th Map
// i+5 points to the character holding 'n'
int n = atoi(source->name.substr(i+5).c_str());
DBG(cerr << "Found a Grid (" << btp->name() << ") and "
<< source->name.substr(i) << ", extracted n: " << n << endl);
return *(dynamic_cast<Grid&>(*btp).map_begin() + n);
}
}
return 0;
}
/** Given an attribute container from a table, find or make a destination
for its contents in the current constructor variable. */
AttrTable *
Constructor::find_matching_container(AttrTable::entry *source,
BaseType **dest_variable)
{
// The attribute entry 'source' must be a container
if (source->type != Attr_container)
throw InternalErr(__FILE__, __LINE__, "Constructor::find_matching_container");
// Use the name of the attribute container 'source' to figure out where
// to put its contents.
BaseType *btp;
if ((btp = var(source->name))) {
// ... matches a variable name? Use var's table
*dest_variable = btp;
return &btp->get_attr_table();
}
// As more special-case attribute containers come to light, add clauses
// here.
else if ((btp = find_hdf4_dimension_attribute_home(source))) {
// ... hdf4 dimension attribute? Make a sub table and use that.
// btp can only be an Array or a Grid Map (which is an array)
if (btp->get_parent()->type() == dods_grid_c) {
DBG(cerr << "Found a Grid" << endl);
*dest_variable = btp;
return &btp->get_attr_table();
}
else { // must ba a plain Array
string::size_type i = source->name.find("_dim_");
string ext = source->name.substr(i+1);
*dest_variable = btp;
return btp->get_attr_table().append_container(ext);
}
}
else {
// ... otherwise assume it's a global attribute.
AttrTable *at = get_attr_table().find_container(source->name);
if (!at) {
at = new AttrTable(); // Make a new global table if needed
get_attr_table().append_container(at, source->name);
}
*dest_variable = 0;
return at;
}
}
/** Given an Attribute entry, scavenge attributes from it and load them into
this object and the variables it contains. Assume that the caller has
determined the table holds attributes pertinent to only this variable.
@note This method is technically \e unnecessary because a server (or
client) can easily add attributes directly using the DDS::get_attr_table
or BaseType::get_attr_table methods and then poke values in using any
of the methods AttrTable provides. This method exists to ease the
transition to DDS objects which contain attribute information for the
existing servers (Since they all make DAS objects separately from the
DDS). They could be modified to use the same AttrTable methods but
operate on the AttrTable instances in a DDS/BaseType instead of those in
a DAS.
@param at Get attribute information from this Attribute table. */
void
Constructor::transfer_attributes(AttrTable::entry * entry)
{
DBG(cerr << "Constructor::transfer_attributes, variable: " << name() <<
endl);
DBG(cerr << "Working on the '" << entry->
name << "' container." << endl);
if (entry->type != Attr_container)
throw InternalErr(__FILE__, __LINE__,
"Constructor::transfer_attributes");
AttrTable *source = entry->attributes;
BaseType *dest_variable = 0;
AttrTable *dest = find_matching_container(entry, &dest_variable);
// foreach source attribute in the das_i container
AttrTable::Attr_iter source_p = source->attr_begin();
while (source_p != source->attr_end()) {
DBG(cerr << "Working on the '" << (*source_p)->
name << "' attribute" << endl);
if ((*source_p)->type == Attr_container) {
if (dest_variable && dest_variable->is_constructor_type()) {
dynamic_cast <Constructor & >(*dest_variable).transfer_attributes(*source_p);
}
else {
dest->append_container(new AttrTable(*(*source_p)->attributes),
(*source_p)->name);
}
} else {
dest->append_attr(source->get_name(source_p),
source->get_type(source_p),
source->get_attr_vector(source_p));
}
++source_p;
}
}
/** Returns an iterator referencing the end of the list of structure
elements. Does not reference the last structure element. */
Constructor::Vars_iter
Constructor::var_end()
{
return _vars.end() ;
}
/** Return a reverse iterator that references the last element. */
Constructor::Vars_riter
Constructor::var_rbegin()
{
return _vars.rbegin();
}
/** Return a reverse iterator that references a point 'before' the first
element. */
Constructor::Vars_riter
Constructor::var_rend()
{
return _vars.rend();
}
/** Return the iterator for the \e ith variable.
@param i the index
@return The corresponding Vars_iter */
Constructor::Vars_iter
Constructor::get_vars_iter(int i)
{
return _vars.begin() + i;
}
/** Return the BaseType pointer for the \e ith variable.
@param i This index
@return The corresponding BaseType*. */
BaseType *
Constructor::get_var_index(int i)
{
return *(_vars.begin() + i);
}
void
Constructor::print_decl(FILE *out, string space, bool print_semi,
bool constraint_info, bool constrained)
{
if (constrained && !send_p())
return;
fprintf( out, "%s%s {\n", space.c_str(), type_name().c_str() ) ;
for (Vars_citer i = _vars.begin(); i != _vars.end(); i++)
{
(*i)->print_decl(out, space + " ", true,
constraint_info, constrained);
}
fprintf( out, "%s} %s", space.c_str(), id2www( name() ).c_str() ) ;
if (constraint_info) { // Used by test drivers only.
if (send_p())
cout << ": Send True";
else
cout << ": Send False";
}
if (print_semi)
fprintf( out, ";\n" ) ;
}
class PrintField : public unary_function<BaseType *, void> {
FILE *d_out;
string d_space;
bool d_constrained;
public:
PrintField(FILE *o, string s, bool c)
: d_out(o), d_space(s), d_constrained(c) {}
void operator()(BaseType *btp) {
btp->print_xml(d_out, d_space, d_constrained);
}
};
void
Constructor::print_xml(FILE *out, string space, bool constrained)
{
if (constrained && !send_p())
return;
bool has_attributes = false; // *** fix me
bool has_variables = (var_begin() != var_end());
fprintf(out, "%s<%s", space.c_str(), type_name().c_str());
if (!name().empty())
fprintf(out, " name=\"%s\"", id2xml(name()).c_str());
if (has_attributes || has_variables) {
fprintf(out, ">\n");
get_attr_table().print_xml(out, space + " ", constrained);
for_each(var_begin(), var_end(),
PrintField(out, space + " ", constrained));
fprintf(out, "%s</%s>\n", space.c_str(), type_name().c_str());
}
else {
fprintf(out, "/>\n");
}
}
/** True if the instance can be flattened and printed as a single table
of values. For Arrays and Grids this is always false. For Structures
and Sequences the conditions are more complex. The implementation
provided by this class always returns false. Other classes should
override this implementation.
@todo Change the name to is_flattenable or something like that. 05/16/03
jhrg
@brief Check to see whether this variable can be printed simply.
@return True if the instance can be printed as a single table of
values, false otherwise. */
bool
Constructor::is_linear()
{
return false;
}
<|endoftext|> |
<commit_before>// includes files
#include <gl\glew.h> ///< always include glew before glfw
#include "Window.h" ///< include after glew, never before. that include glfw too
#include "EasyErrors.h"
#include "InputManager.h"
#include "GLProgram.h"
#include "Camera3D.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm\gtx\rotate_vector.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <chrono>
#include "FpsCounter.h"
#include "DrawBatch.h"
#include "Block.h"
int main()
{
auto t_start = std::chrono::high_resolution_clock::now();
const int width = 1600;
const int height = 1200;
if (!glfwInit())
{
Debug_Log("Failed to initialize GLFW\n");
}
// create a window
Window m_window;
m_window.init(width, height, "Doxel");
// Set up glew
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
{
Debug_Log("Failed to initialize GLEW\n");
}
// Set up the Input Manager
InputManager m_inputManager;
m_inputManager.init(m_window.getGlfwWindow());
glm::vec3 cPos = glm::vec3(0);
Camera3D m_camera;
m_camera.init(cPos, 45.0f,m_window.getAspectRatio(),1.0, 10000);
glEnable(GL_DEPTH_TEST);
DrawBatch m_drawBatch;
m_drawBatch.init(&m_camera);
// compile shaders, add attribes and all that
GLProgram m_glProgram;
m_glProgram.loadShaders("Shaders/shader.vert", "Shaders/shader.frag");
glm::mat4 model, projection, view;
glm::vec3 mPos(0, 0, 0);
projection = m_camera.getProjectionMatrix();
m_glProgram.uploadUniformMatrix("projection", 1, projection, GL_FALSE);
FpsCounter m_fpsCounter;
glm::vec3 lightPos(0, 100, 100);
//ChunkStuff
ChunkManager m_chunkManager;
m_chunkManager.init();
m_fpsCounter.start();
Color8 colors[8] {Color8(255, 255, 255, 255), Color8(255, 0, 0, 255), Color8(255, 255, 0, 255), Color8(255, 0, 255, 255), Color8(0, 255, 0, 255), Color8(125, 255, 0, 255), Color8(255, 50, 120, 255), Color8(0, 255, 120, 255) };
// This is the game loop
while (!m_window.shouldWindowClose())
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
m_inputManager.update();
m_camera.update();
// update input
// handle input from user
if (m_inputManager.isKeyPressed(KEYS::ESC))
{
m_window.setWindowClose();
}
if (m_inputManager.isKeyPressed(KEYS::W) || m_inputManager.isKeyHeldDown(KEYS::W)) ///< FORWARD
{
m_camera.applyMovement(cMove::Forward);
}
if (m_inputManager.isKeyPressed(KEYS::S) || m_inputManager.isKeyHeldDown(KEYS::S)) ///< BACKWARD
{
m_camera.applyMovement(cMove::Backward);
}
if (m_inputManager.isKeyPressed(KEYS::A) || m_inputManager.isKeyHeldDown(KEYS::A)) ///< LEFT
{
m_camera.applyMovement(cMove::Left);
}
if (m_inputManager.isKeyPressed(KEYS::D) || m_inputManager.isKeyHeldDown(KEYS::D)) ///< RIGHT
{
m_camera.applyMovement(cMove::Right);
}
if (m_inputManager.isKeyPressed(KEYS::Z) || m_inputManager.isKeyHeldDown(KEYS::Z)) ///<UP
{
m_camera.applyMovement(cMove::Up);
}
if (m_inputManager.isKeyPressed(KEYS::X) || m_inputManager.isKeyHeldDown(KEYS::X))///< DOWN
{
m_camera.applyMovement(cMove::Down);
}
if (m_inputManager.isKeyPressed(KEYS::Q) || m_inputManager.isKeyHeldDown(KEYS::Q))///< rotate left
{
m_camera.applyMovement(cMove::Rotate_Left);
}
if (m_inputManager.isKeyPressed(KEYS::E) || m_inputManager.isKeyHeldDown(KEYS::E))///< rotate left
{
m_camera.applyMovement(cMove::Rotate_Right);
}
if (m_inputManager.isKeyPressed(KEYS::F) || m_inputManager.isKeyHeldDown(KEYS::F))///< rotate left
{
m_camera.applyMovement(cMove::Roll_Left);
}
if (m_inputManager.isKeyPressed(KEYS::G) || m_inputManager.isKeyHeldDown(KEYS::G))///< rotate left
{
m_camera.applyMovement(cMove::Roll_Right);
}
if (m_inputManager.isKeyPressed(KEYS::C) || m_inputManager.isKeyHeldDown(KEYS::C))///< rotate left
{
m_camera.applyMovement(cMove::Pitch_Up);
}
if (m_inputManager.isKeyPressed(KEYS::V) || m_inputManager.isKeyHeldDown(KEYS::V))///< rotate left
{
m_camera.applyMovement(cMove::Pitch_Down);
}
if (m_inputManager.isKeyPressed(KEYS::UP) || m_inputManager.isKeyHeldDown(KEYS::UP))
{
m_camera.increaseSpeed();
}
if (m_inputManager.isKeyPressed(KEYS::DOWN) || m_inputManager.isKeyHeldDown(KEYS::DOWN))
{
m_camera.decreaseSpeed();
}
if (m_inputManager.isKeyPressed(KEYS::SPACE))
{
m_camera.setPosition(glm::vec3(0));
m_camera.setDirection(glm::vec3(1, 1, 0));
m_camera.setUpDir(glm::vec3(0, 0, 1));
m_camera.setSpeed(0.1f);
}
if (m_inputManager.isKeyPressed(KEYS::T))
{
m_chunkManager.setGenMethod(GEN_METHOD::SPHERE);
}
if (m_inputManager.isKeyPressed(KEYS::R))
{
m_chunkManager.setGenMethod(GEN_METHOD::RANDOM);
}
if (m_inputManager.isKeyPressed(KEYS::Y))
{
m_chunkManager.setGenMethod(GEN_METHOD::ALL);
}
auto t_now = std::chrono::high_resolution_clock::now();
float time = std::chrono::duration_cast<std::chrono::duration<float>>(t_now - t_start).count();
// Use the glProgram
// m_glProgram.use();
// UPLOAD THE CAMERA MATRIX AFTER YOU CALLED THE PROGRAM.
// m_glProgram.uploadUnifromMatrix("view", 1, view, GL_FALSE);
// m_glProgram.uploadUnifromMatrix("model", 1, model, GL_FALSE);
glm::mat4 view = m_camera.getViewMatrix();
glm::mat4 mvp = projection * view * model;
glm::vec3 lightPos = glm::vec3(cosf(time / 2)* 100,0,sinf(time / 2)* 100);
// glm::vec3 lightPos = m_camera.getPosition() + glm::vec3(0, 0, 50);
m_glProgram.uploadUniformMatrix("mvp", 1, mvp, GL_FALSE);
m_glProgram.uploadUniformMatrix("m", 1, model, GL_FALSE);
m_glProgram.uploadUniformMatrix("v", 1, view, GL_FALSE);
m_glProgram.uploadUniformVector3("lightPosition_worldSpace", 1, lightPos);
m_chunkManager.update(m_camera.getPosition());
m_drawBatch.start();
m_chunkManager.draw(&m_drawBatch);
m_drawBatch.draw(glm::vec3(0, 0, -0.1), glm::vec3(CHUNK_SIZE * NUM_CHUNKS, CHUNK_SIZE * NUM_CHUNKS, EPSILON), Color8(255, 255, 255, 255), true);
m_drawBatch.draw(lightPos, glm::vec3(10, 10, 10), Color8(255, 255, 255, 255));
m_drawBatch.end();
m_drawBatch.renderBatch();
// m_glProgram.unuse();
// update the window
m_window.update();
m_fpsCounter.end();
}
//m_debugRenderer.dispose();
//m_chunkManager.dispose();
m_glProgram.deleteProgram();
m_drawBatch.dispose();
//Close the window
m_chunkManager.dispose();
m_window.dispose();
glfwTerminate();
return 0;
}
<commit_msg>removed some colors that do nothing<commit_after>// includes files
#include <gl\glew.h> ///< always include glew before glfw
#include "Window.h" ///< include after glew, never before. that include glfw too
#include "EasyErrors.h"
#include "InputManager.h"
#include "GLProgram.h"
#include "Camera3D.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm\gtx\rotate_vector.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <chrono>
#include "FpsCounter.h"
#include "DrawBatch.h"
#include "Block.h"
int main()
{
auto t_start = std::chrono::high_resolution_clock::now();
const int width = 1600;
const int height = 1200;
if (!glfwInit())
{
Debug_Log("Failed to initialize GLFW\n");
}
// create a window
Window m_window;
m_window.init(width, height, "Doxel");
// Set up glew
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
{
Debug_Log("Failed to initialize GLEW\n");
}
// Set up the Input Manager
InputManager m_inputManager;
m_inputManager.init(m_window.getGlfwWindow());
glm::vec3 cPos = glm::vec3(0);
Camera3D m_camera;
m_camera.init(cPos, 45.0f,m_window.getAspectRatio(),1.0, 10000);
glEnable(GL_DEPTH_TEST);
DrawBatch m_drawBatch;
m_drawBatch.init(&m_camera);
// compile shaders, add attribes and all that
GLProgram m_glProgram;
m_glProgram.loadShaders("Shaders/shader.vert", "Shaders/shader.frag");
glm::mat4 model, projection, view;
glm::vec3 mPos(0, 0, 0);
projection = m_camera.getProjectionMatrix();
m_glProgram.uploadUniformMatrix("projection", 1, projection, GL_FALSE);
FpsCounter m_fpsCounter;
glm::vec3 lightPos(0, 100, 100);
//ChunkStuff
ChunkManager m_chunkManager;
m_chunkManager.init();
m_fpsCounter.start();
// This is the game loop
while (!m_window.shouldWindowClose())
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
m_inputManager.update();
m_camera.update();
// update input
// handle input from user
if (m_inputManager.isKeyPressed(KEYS::ESC))
{
m_window.setWindowClose();
}
if (m_inputManager.isKeyPressed(KEYS::W) || m_inputManager.isKeyHeldDown(KEYS::W)) ///< FORWARD
{
m_camera.applyMovement(cMove::Forward);
}
if (m_inputManager.isKeyPressed(KEYS::S) || m_inputManager.isKeyHeldDown(KEYS::S)) ///< BACKWARD
{
m_camera.applyMovement(cMove::Backward);
}
if (m_inputManager.isKeyPressed(KEYS::A) || m_inputManager.isKeyHeldDown(KEYS::A)) ///< LEFT
{
m_camera.applyMovement(cMove::Left);
}
if (m_inputManager.isKeyPressed(KEYS::D) || m_inputManager.isKeyHeldDown(KEYS::D)) ///< RIGHT
{
m_camera.applyMovement(cMove::Right);
}
if (m_inputManager.isKeyPressed(KEYS::Z) || m_inputManager.isKeyHeldDown(KEYS::Z)) ///<UP
{
m_camera.applyMovement(cMove::Up);
}
if (m_inputManager.isKeyPressed(KEYS::X) || m_inputManager.isKeyHeldDown(KEYS::X))///< DOWN
{
m_camera.applyMovement(cMove::Down);
}
if (m_inputManager.isKeyPressed(KEYS::Q) || m_inputManager.isKeyHeldDown(KEYS::Q))///< rotate left
{
m_camera.applyMovement(cMove::Rotate_Left);
}
if (m_inputManager.isKeyPressed(KEYS::E) || m_inputManager.isKeyHeldDown(KEYS::E))///< rotate left
{
m_camera.applyMovement(cMove::Rotate_Right);
}
if (m_inputManager.isKeyPressed(KEYS::F) || m_inputManager.isKeyHeldDown(KEYS::F))///< rotate left
{
m_camera.applyMovement(cMove::Roll_Left);
}
if (m_inputManager.isKeyPressed(KEYS::G) || m_inputManager.isKeyHeldDown(KEYS::G))///< rotate left
{
m_camera.applyMovement(cMove::Roll_Right);
}
if (m_inputManager.isKeyPressed(KEYS::C) || m_inputManager.isKeyHeldDown(KEYS::C))///< rotate left
{
m_camera.applyMovement(cMove::Pitch_Up);
}
if (m_inputManager.isKeyPressed(KEYS::V) || m_inputManager.isKeyHeldDown(KEYS::V))///< rotate left
{
m_camera.applyMovement(cMove::Pitch_Down);
}
if (m_inputManager.isKeyPressed(KEYS::UP) || m_inputManager.isKeyHeldDown(KEYS::UP))
{
m_camera.increaseSpeed();
}
if (m_inputManager.isKeyPressed(KEYS::DOWN) || m_inputManager.isKeyHeldDown(KEYS::DOWN))
{
m_camera.decreaseSpeed();
}
if (m_inputManager.isKeyPressed(KEYS::SPACE))
{
m_camera.setPosition(glm::vec3(0));
m_camera.setDirection(glm::vec3(1, 1, 0));
m_camera.setUpDir(glm::vec3(0, 0, 1));
m_camera.setSpeed(0.1f);
}
if (m_inputManager.isKeyPressed(KEYS::T))
{
m_chunkManager.setGenMethod(GEN_METHOD::SPHERE);
}
if (m_inputManager.isKeyPressed(KEYS::R))
{
m_chunkManager.setGenMethod(GEN_METHOD::RANDOM);
}
if (m_inputManager.isKeyPressed(KEYS::Y))
{
m_chunkManager.setGenMethod(GEN_METHOD::ALL);
}
auto t_now = std::chrono::high_resolution_clock::now();
float time = std::chrono::duration_cast<std::chrono::duration<float>>(t_now - t_start).count();
// Use the glProgram
// m_glProgram.use();
// UPLOAD THE CAMERA MATRIX AFTER YOU CALLED THE PROGRAM.
// m_glProgram.uploadUnifromMatrix("view", 1, view, GL_FALSE);
// m_glProgram.uploadUnifromMatrix("model", 1, model, GL_FALSE);
glm::mat4 view = m_camera.getViewMatrix();
glm::mat4 mvp = projection * view * model;
glm::vec3 lightPos = glm::vec3(cosf(time / 2)* 100,0,sinf(time / 2)* 100);
// glm::vec3 lightPos = m_camera.getPosition() + glm::vec3(0, 0, 50);
m_glProgram.uploadUniformMatrix("mvp", 1, mvp, GL_FALSE);
m_glProgram.uploadUniformMatrix("m", 1, model, GL_FALSE);
m_glProgram.uploadUniformMatrix("v", 1, view, GL_FALSE);
m_glProgram.uploadUniformVector3("lightPosition_worldSpace", 1, lightPos);
m_chunkManager.update(m_camera.getPosition());
m_drawBatch.start();
m_chunkManager.draw(&m_drawBatch);
m_drawBatch.draw(glm::vec3(0, 0, -0.1), glm::vec3(CHUNK_SIZE * NUM_CHUNKS, CHUNK_SIZE * NUM_CHUNKS, EPSILON), Color8(255, 255, 255, 255), true);
m_drawBatch.draw(lightPos, glm::vec3(10, 10, 10), Color8(255, 255, 255, 255));
m_drawBatch.end();
m_drawBatch.renderBatch();
// m_glProgram.unuse();
// update the window
m_window.update();
m_fpsCounter.end();
}
//m_debugRenderer.dispose();
//m_chunkManager.dispose();
m_glProgram.deleteProgram();
m_drawBatch.dispose();
//Close the window
m_chunkManager.dispose();
m_window.dispose();
glfwTerminate();
return 0;
}
<|endoftext|> |
<commit_before>#include <cucumber-cpp/internal/connectors/wire/WireServer.hpp>
namespace cucumber {
namespace internal {
SocketServer::SocketServer(const ProtocolHandler *protocolHandler) :
ios(),
acceptor(ios),
protocolHandler(protocolHandler) {
}
void SocketServer::listen(const port_type port) {
tcp::endpoint endpoint(tcp::v4(), port);
acceptor.open(endpoint.protocol());
acceptor.set_option(tcp::acceptor::reuse_address(true));
acceptor.bind(endpoint);
acceptor.listen(1);
}
void SocketServer::acceptOnce() {
tcp::iostream stream;
acceptor.accept(*stream.rdbuf());
processStream(stream);
}
void SocketServer::processStream(tcp::iostream &stream) {
std::string request;
while (getline(stream, request)) {
stream << protocolHandler->handle(request) << std::endl << std::flush;
}
}
}
}
<commit_msg>Fix compiler warning about member initializer order<commit_after>#include <cucumber-cpp/internal/connectors/wire/WireServer.hpp>
namespace cucumber {
namespace internal {
SocketServer::SocketServer(const ProtocolHandler *protocolHandler) :
protocolHandler(protocolHandler),
ios(),
acceptor(ios) {
}
void SocketServer::listen(const port_type port) {
tcp::endpoint endpoint(tcp::v4(), port);
acceptor.open(endpoint.protocol());
acceptor.set_option(tcp::acceptor::reuse_address(true));
acceptor.bind(endpoint);
acceptor.listen(1);
}
void SocketServer::acceptOnce() {
tcp::iostream stream;
acceptor.accept(*stream.rdbuf());
processStream(stream);
}
void SocketServer::processStream(tcp::iostream &stream) {
std::string request;
while (getline(stream, request)) {
stream << protocolHandler->handle(request) << std::endl << std::flush;
}
}
}
}
<|endoftext|> |
<commit_before>/*
* RInterface.hpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef R_INTERFACE_HPP
#define R_INTERFACE_HPP
#include <string>
#include <setjmp.h>
#ifdef _WIN32
#include <R_ext/Boolean.h>
#include <R_ext/RStartup.h>
extern "C" void R_RestoreGlobalEnvFromFile(const char *, Rboolean);
extern "C" void R_SaveGlobalEnvToFile(const char *);
extern "C" void R_Suicide(const char *);
extern "C" char *R_HomeDir(void);
extern "C" void Rf_jump_to_toplevel(void);
extern "C" void Rf_onintr(void);
#define R_ClearerrConsole void
extern "C" void R_FlushConsole();
extern "C" int R_SignalHandlers;
extern "C" void run_Rmainloop();
extern "C" void Rf_mainloop(void);
extern "C" void* R_GlobalContext;
typedef struct SEXPREC *SEXP;
#else
#define R_INTERFACE_PTRS 1
#include <Rinterface.h>
#endif
#ifdef _WIN32
// on Windows platforms, use a manual definition of sigjmp_buf that corresponds
// to how R lays out the structure in memory
typedef struct
{
jmp_buf buf;
int sigmask;
int savedmask;
}
sigjmp_buf[1];
#endif
typedef struct RCNTXT {
struct RCNTXT *nextcontext;
int callflag;
sigjmp_buf cjmpbuf;
int cstacktop;
int evaldepth;
SEXP promargs;
SEXP callfun;
SEXP sysparent;
SEXP call;
SEXP cloenv;
SEXP conexit;
void (*cend)(void *);
void *cenddata;
void *vmax;
int intsusp;
SEXP handlerstack;
SEXP restartstack;
struct RPRSTACK *prstack;
SEXP *nodestack;
#ifdef BC_INT_STACK
IStackval *intstack;
#endif
SEXP srcref;
} RCNTXT, *context;
enum {
CTXT_TOPLEVEL = 0,
CTXT_NEXT = 1,
CTXT_BREAK = 2,
CTXT_LOOP = 3,
CTXT_FUNCTION = 4,
CTXT_CCODE = 8,
CTXT_RETURN = 12,
CTXT_BROWSER = 16,
CTXT_GENERIC = 20,
CTXT_RESTART = 32,
CTXT_BUILTIN = 64
};
namespace r {
inline RCNTXT* getGlobalContext()
{
return static_cast<RCNTXT*>(R_GlobalContext);
}
} // namespace r
#endif // R_INTERFACE_HPP
<commit_msg>put debugger types in anonymous namespace (prevent gcc 4.9 warning)<commit_after>/*
* RInterface.hpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef R_INTERFACE_HPP
#define R_INTERFACE_HPP
#include <string>
#include <setjmp.h>
#ifdef _WIN32
#include <R_ext/Boolean.h>
#include <R_ext/RStartup.h>
extern "C" void R_RestoreGlobalEnvFromFile(const char *, Rboolean);
extern "C" void R_SaveGlobalEnvToFile(const char *);
extern "C" void R_Suicide(const char *);
extern "C" char *R_HomeDir(void);
extern "C" void Rf_jump_to_toplevel(void);
extern "C" void Rf_onintr(void);
#define R_ClearerrConsole void
extern "C" void R_FlushConsole();
extern "C" int R_SignalHandlers;
extern "C" void run_Rmainloop();
extern "C" void Rf_mainloop(void);
extern "C" void* R_GlobalContext;
typedef struct SEXPREC *SEXP;
#else
#define R_INTERFACE_PTRS 1
#include <Rinterface.h>
#endif
#ifdef _WIN32
// on Windows platforms, use a manual definition of sigjmp_buf that corresponds
// to how R lays out the structure in memory
namespace {
typedef struct
{
jmp_buf buf;
int sigmask;
int savedmask;
}
sigjmp_buf[1];
#endif
typedef struct RCNTXT {
struct RCNTXT *nextcontext;
int callflag;
sigjmp_buf cjmpbuf;
int cstacktop;
int evaldepth;
SEXP promargs;
SEXP callfun;
SEXP sysparent;
SEXP call;
SEXP cloenv;
SEXP conexit;
void (*cend)(void *);
void *cenddata;
void *vmax;
int intsusp;
SEXP handlerstack;
SEXP restartstack;
struct RPRSTACK *prstack;
SEXP *nodestack;
#ifdef BC_INT_STACK
IStackval *intstack;
#endif
SEXP srcref;
} RCNTXT, *context;
enum {
CTXT_TOPLEVEL = 0,
CTXT_NEXT = 1,
CTXT_BREAK = 2,
CTXT_LOOP = 3,
CTXT_FUNCTION = 4,
CTXT_CCODE = 8,
CTXT_RETURN = 12,
CTXT_BROWSER = 16,
CTXT_GENERIC = 20,
CTXT_RESTART = 32,
CTXT_BUILTIN = 64
};
} // anonymous namespace
namespace r {
inline RCNTXT* getGlobalContext()
{
return static_cast<RCNTXT*>(R_GlobalContext);
}
} // namespace r
#endif // R_INTERFACE_HPP
<|endoftext|> |
<commit_before>#include "SkColorPriv.h"
#include "SkTableColorFilter.h"
#include "SkUnPreMultiply.h"
class SkTable_ColorFilter : public SkColorFilter {
public:
SkTable_ColorFilter(const uint8_t tableA[], const uint8_t tableR[],
const uint8_t tableG[], const uint8_t tableB[]) {
fFlags = 0;
uint8_t* dst = fStorage;
if (tableA) {
memcpy(dst, tableA, 256);
dst += 256;
fFlags |= kA_Flag;
}
if (tableR) {
memcpy(dst, tableR, 256);
dst += 256;
fFlags |= kR_Flag;
}
if (tableG) {
memcpy(dst, tableG, 256);
dst += 256;
fFlags |= kG_Flag;
}
if (tableB) {
memcpy(dst, tableB, 256);
fFlags |= kB_Flag;
}
}
virtual void filterSpan(const SkPMColor src[], int count,
SkPMColor dst[]) SK_OVERRIDE;
virtual void flatten(SkFlattenableWriteBuffer&) SK_OVERRIDE;
virtual Factory getFactory() SK_OVERRIDE;
static SkFlattenable* CreateProc(SkFlattenableReadBuffer& buffer) {
return SkNEW_ARGS(SkTable_ColorFilter, (buffer));
}
protected:
SkTable_ColorFilter(SkFlattenableReadBuffer& buffer);
private:
enum {
kA_Flag = 1 << 0,
kR_Flag = 1 << 1,
kG_Flag = 1 << 2,
kB_Flag = 1 << 3,
};
uint8_t fStorage[256 * 4];
unsigned fFlags;
typedef SkColorFilter INHERITED;
};
static const uint8_t gIdentityTable[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F,
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F,
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F,
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F,
0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,
0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF,
0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7,
0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF,
0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7,
0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF,
0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7,
0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF,
0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7,
0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF,
0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7,
0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF
};
void SkTable_ColorFilter::filterSpan(const SkPMColor src[], int count,
SkPMColor dst[]) {
const uint8_t* table = fStorage;
const uint8_t* tableA = gIdentityTable;
const uint8_t* tableR = gIdentityTable;
const uint8_t* tableG = gIdentityTable;
const uint8_t* tableB = gIdentityTable;
if (fFlags & kA_Flag) {
tableA = table; table += 256;
}
if (fFlags & kR_Flag) {
tableR = table; table += 256;
}
if (fFlags & kG_Flag) {
tableG = table; table += 256;
}
if (fFlags & kB_Flag) {
tableB = table;
}
const SkUnPreMultiply::Scale* scaleTable = SkUnPreMultiply::GetScaleTable();
for (int i = 0; i < count; ++i) {
SkPMColor c = src[i];
unsigned a, r, g, b;
if (0 == c) {
a = r = g = b = 0;
} else {
a = SkGetPackedA32(c);
r = SkGetPackedR32(c);
g = SkGetPackedG32(c);
b = SkGetPackedB32(c);
if (a < 255) {
SkUnPreMultiply::Scale scale = scaleTable[a];
r = SkUnPreMultiply::ApplyScale(scale, r);
g = SkUnPreMultiply::ApplyScale(scale, g);
b = SkUnPreMultiply::ApplyScale(scale, b);
}
}
dst[i] = SkPremultiplyARGBInline(tableA[a], tableR[r],
tableG[g], tableB[b]);
}
}
SkFlattenable::Factory SkTable_ColorFilter::getFactory() {
return CreateProc;
}
static const uint8_t gCountNibBits[] = {
0, 1, 1, 2,
1, 2, 2, 3,
1, 2, 2, 3,
2, 3, 3, 4
};
#include "SkPackBits.h"
void SkTable_ColorFilter::flatten(SkFlattenableWriteBuffer& buffer) {
this->INHERITED::flatten(buffer);
uint8_t storage[5*256];
int count = gCountNibBits[fFlags & 0xF];
size_t size = SkPackBits::Pack8(fStorage, count * 256, storage);
SkASSERT(size <= sizeof(storage));
// SkDebugf("raw %d packed %d\n", count * 256, size);
buffer.writeInt(fFlags);
buffer.writeInt(size);
buffer.write(storage, size);
}
SkTable_ColorFilter::SkTable_ColorFilter(SkFlattenableReadBuffer& buffer) : INHERITED(buffer) {
uint8_t storage[5*256];
fFlags = buffer.readInt();
size_t size = buffer.readInt();
buffer.read(storage, size);
size_t raw = SkPackBits::Unpack8(storage, size, fStorage);
SkASSERT(raw <= sizeof(fStorage));
size_t count = gCountNibBits[fFlags & 0xF];
SkASSERT(raw == count * 256);
}
///////////////////////////////////////////////////////////////////////////////
#ifdef SK_CPU_BENDIAN
#else
#define SK_A32_INDEX (3 - (SK_A32_SHIFT >> 3))
#define SK_R32_INDEX (3 - (SK_R32_SHIFT >> 3))
#define SK_G32_INDEX (3 - (SK_G32_SHIFT >> 3))
#define SK_B32_INDEX (3 - (SK_B32_SHIFT >> 3))
#endif
///////////////////////////////////////////////////////////////////////////////
SkColorFilter* SkTableColorFilter::Create(const uint8_t table[256]) {
return SkNEW_ARGS(SkTable_ColorFilter, (table, table, table, table));
}
SkColorFilter* SkTableColorFilter::CreateARGB(const uint8_t tableA[256],
const uint8_t tableR[256],
const uint8_t tableG[256],
const uint8_t tableB[256]) {
return SkNEW_ARGS(SkTable_ColorFilter, (tableA, tableR, tableG, tableB));
}
<commit_msg>override asComponentTable()<commit_after>#include "SkColorPriv.h"
#include "SkTableColorFilter.h"
#include "SkUnPreMultiply.h"
class SkTable_ColorFilter : public SkColorFilter {
public:
SkTable_ColorFilter(const uint8_t tableA[], const uint8_t tableR[],
const uint8_t tableG[], const uint8_t tableB[]) {
fBitmap = NULL;
fFlags = 0;
uint8_t* dst = fStorage;
if (tableA) {
memcpy(dst, tableA, 256);
dst += 256;
fFlags |= kA_Flag;
}
if (tableR) {
memcpy(dst, tableR, 256);
dst += 256;
fFlags |= kR_Flag;
}
if (tableG) {
memcpy(dst, tableG, 256);
dst += 256;
fFlags |= kG_Flag;
}
if (tableB) {
memcpy(dst, tableB, 256);
fFlags |= kB_Flag;
}
}
virtual bool asComponentTable(SkBitmap* table) SK_OVERRIDE;
virtual void filterSpan(const SkPMColor src[], int count,
SkPMColor dst[]) SK_OVERRIDE;
virtual void flatten(SkFlattenableWriteBuffer&) SK_OVERRIDE;
virtual Factory getFactory() SK_OVERRIDE;
static SkFlattenable* CreateProc(SkFlattenableReadBuffer& buffer) {
return SkNEW_ARGS(SkTable_ColorFilter, (buffer));
}
protected:
SkTable_ColorFilter(SkFlattenableReadBuffer& buffer);
private:
SkBitmap* fBitmap;
enum {
kA_Flag = 1 << 0,
kR_Flag = 1 << 1,
kG_Flag = 1 << 2,
kB_Flag = 1 << 3,
};
uint8_t fStorage[256 * 4];
unsigned fFlags;
typedef SkColorFilter INHERITED;
};
static const uint8_t gIdentityTable[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F,
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F,
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F,
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F,
0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,
0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF,
0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7,
0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF,
0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7,
0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF,
0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7,
0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF,
0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7,
0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF,
0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7,
0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF
};
void SkTable_ColorFilter::filterSpan(const SkPMColor src[], int count,
SkPMColor dst[]) {
const uint8_t* table = fStorage;
const uint8_t* tableA = gIdentityTable;
const uint8_t* tableR = gIdentityTable;
const uint8_t* tableG = gIdentityTable;
const uint8_t* tableB = gIdentityTable;
if (fFlags & kA_Flag) {
tableA = table; table += 256;
}
if (fFlags & kR_Flag) {
tableR = table; table += 256;
}
if (fFlags & kG_Flag) {
tableG = table; table += 256;
}
if (fFlags & kB_Flag) {
tableB = table;
}
const SkUnPreMultiply::Scale* scaleTable = SkUnPreMultiply::GetScaleTable();
for (int i = 0; i < count; ++i) {
SkPMColor c = src[i];
unsigned a, r, g, b;
if (0 == c) {
a = r = g = b = 0;
} else {
a = SkGetPackedA32(c);
r = SkGetPackedR32(c);
g = SkGetPackedG32(c);
b = SkGetPackedB32(c);
if (a < 255) {
SkUnPreMultiply::Scale scale = scaleTable[a];
r = SkUnPreMultiply::ApplyScale(scale, r);
g = SkUnPreMultiply::ApplyScale(scale, g);
b = SkUnPreMultiply::ApplyScale(scale, b);
}
}
dst[i] = SkPremultiplyARGBInline(tableA[a], tableR[r],
tableG[g], tableB[b]);
}
}
SkFlattenable::Factory SkTable_ColorFilter::getFactory() {
return CreateProc;
}
static const uint8_t gCountNibBits[] = {
0, 1, 1, 2,
1, 2, 2, 3,
1, 2, 2, 3,
2, 3, 3, 4
};
#include "SkPackBits.h"
void SkTable_ColorFilter::flatten(SkFlattenableWriteBuffer& buffer) {
this->INHERITED::flatten(buffer);
uint8_t storage[5*256];
int count = gCountNibBits[fFlags & 0xF];
size_t size = SkPackBits::Pack8(fStorage, count * 256, storage);
SkASSERT(size <= sizeof(storage));
// SkDebugf("raw %d packed %d\n", count * 256, size);
buffer.writeInt(fFlags);
buffer.writeInt(size);
buffer.write(storage, size);
}
SkTable_ColorFilter::SkTable_ColorFilter(SkFlattenableReadBuffer& buffer) : INHERITED(buffer) {
fBitmap = NULL;
uint8_t storage[5*256];
fFlags = buffer.readInt();
size_t size = buffer.readInt();
buffer.read(storage, size);
size_t raw = SkPackBits::Unpack8(storage, size, fStorage);
SkASSERT(raw <= sizeof(fStorage));
size_t count = gCountNibBits[fFlags & 0xF];
SkASSERT(raw == count * 256);
}
bool SkTable_ColorFilter::asComponentTable(SkBitmap* table) {
if (table) {
if (NULL == fBitmap) {
fBitmap = new SkBitmap;
fBitmap->setConfig(SkBitmap::kA8_Config, 256, 4, 256);
fBitmap->allocPixels();
memcpy(fBitmap->getAddr8(0, 0), fStorage, 256 * 4);
}
*table = *fBitmap;
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
#ifdef SK_CPU_BENDIAN
#else
#define SK_A32_INDEX (3 - (SK_A32_SHIFT >> 3))
#define SK_R32_INDEX (3 - (SK_R32_SHIFT >> 3))
#define SK_G32_INDEX (3 - (SK_G32_SHIFT >> 3))
#define SK_B32_INDEX (3 - (SK_B32_SHIFT >> 3))
#endif
///////////////////////////////////////////////////////////////////////////////
SkColorFilter* SkTableColorFilter::Create(const uint8_t table[256]) {
return SkNEW_ARGS(SkTable_ColorFilter, (table, table, table, table));
}
SkColorFilter* SkTableColorFilter::CreateARGB(const uint8_t tableA[256],
const uint8_t tableR[256],
const uint8_t tableG[256],
const uint8_t tableB[256]) {
return SkNEW_ARGS(SkTable_ColorFilter, (tableA, tableR, tableG, tableB));
}
<|endoftext|> |
<commit_before>#ifdef EMSCRIPTEN
#include <emscripten.h>
#endif
#include <iostream>
#include <SDL/SDL.h>
using namespace std;
// Native GBC display info
const int NATIVE_WIDTH = 160;
const int NATIVE_HEIGHT = 144;
int game_w;
int game_h;
int pixel_size_w = 5;
int pixel_size_h = 5;
bool keep_ratio = true;
// Map
Uint32 pixels_map[NATIVE_WIDTH][NATIVE_HEIGHT] = { { 0 } };
Uint32 pixels_map_actual[NATIVE_WIDTH][NATIVE_HEIGHT] = { { 1 } };
// SDL Variables
int bpp = 32;
int flags = SDL_HWSURFACE | SDL_RESIZABLE | SDL_DOUBLEBUF;
SDL_Surface* screen;
SDL_Surface* window;
/**
* Update game dimensions
*/
void resize(int w, int h) {
game_w = w;
game_h = h;
int new_pixel_size_w = game_w / NATIVE_WIDTH;
int new_pixel_size_h = game_h / NATIVE_HEIGHT;
if (!keep_ratio) {
pixel_size_w = new_pixel_size_w;
pixel_size_h = new_pixel_size_h;
}
else {
pixel_size_w = min(new_pixel_size_w, new_pixel_size_h);
pixel_size_h = pixel_size_w;
}
}
/**
* Draw a big pixel
*/
void drawPixel(int x, int y, Uint32 color)
{
int container_width = game_w;
int contained_width = NATIVE_WIDTH * pixel_size_w;
int container_height = game_h;
int contained_height = NATIVE_HEIGHT * pixel_size_h;
int offset_x = (int)(((float)container_width / 2) - ((float)contained_width / 2));
int offset_y = (int)(((float)container_height / 2) - ((float)contained_height / 2));
x = x * pixel_size_w + offset_x;
y = y * pixel_size_h + offset_y;
SDL_Rect rect = { x, y, pixel_size_w, pixel_size_h };
SDL_FillRect(window, &rect, color);
}
/**
* Draw next frame
*/
void drawScreen(bool force = false)
{
//TODO: control FPS with emscripten
SDL_Flip(window);
for (size_t i = 0; i < NATIVE_WIDTH; i++) {
for (size_t j = 0; j < NATIVE_HEIGHT; j++) {
if (pixels_map[i][j] != pixels_map_actual[i][j] || force) {
pixels_map_actual[i][j] = pixels_map[i][j];
drawPixel(i, j, pixels_map[i][j]);
}
}
}
}
void processEvents()
{
SDL_Event event;
while(SDL_PollEvent(&event)) {
switch(event.type) {
case SDL_QUIT:
exit(EXIT_SUCCESS);
break;
case SDL_VIDEORESIZE:
SDL_FreeSurface(screen);
screen = SDL_SetVideoMode(event.resize.w, event.resize.h, bpp,
flags);
resize(event.resize.w, event.resize.h);
drawScreen(true);
}
}
}
/**
* One iteration of the main loop
*/
void oneIteration()
{
processEvents();
drawScreen();
}
/**
* Entry point
*/
int main(int argc, char** argv)
{
#ifndef EMSCRIPTEN
atexit(SDL_Quit);
#endif
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
cout << "Video initialization failed: " << SDL_GetError() << endl;
exit(EXIT_FAILURE);
}
const SDL_VideoInfo* screen_info = SDL_GetVideoInfo();
int screen_width = screen_info->current_w / 2;
int screen_height = screen_info->current_h / 2;
#ifdef EMSCRIPTEN
screen_width = screen_info->current_w;
screen_height = screen_info->current_h;
#endif
screen = SDL_SetVideoMode(screen_width, screen_height, bpp, flags);
if (screen == NULL) {
cout << "Video mode set failed: " << SDL_GetError() << endl;
exit(EXIT_SUCCESS);
}
SDL_WM_SetCaption("gbcEmulator", NULL);
window = SDL_GetVideoSurface();
resize(window->w, window->h);
// Generate pixels
srand (time(NULL));
for (size_t i = 0; i < NATIVE_WIDTH; i++) {
for (size_t j = 0; j < NATIVE_HEIGHT; j++) {
pixels_map[i][j] = SDL_MapRGB(window->format, rand() % 256, rand() % 256, rand() % 256);
}
}
#ifdef EMSCRIPTEN
emscripten_set_main_loop(oneIteration, 0, 1);
#else
while(1) {
oneIteration();
//60 FPS
SDL_Delay(16);
}
SDL_Quit();
#endif
return EXIT_SUCCESS;
}
<commit_msg>Change drawscreen routine<commit_after>#ifdef EMSCRIPTEN
#include <emscripten.h>
#endif
#include <iostream>
#include <SDL/SDL.h>
using namespace std;
// Native GBC display info
const int NATIVE_WIDTH = 160;
const int NATIVE_HEIGHT = 144;
int game_w;
int game_h;
int pixel_size_w = 5;
int pixel_size_h = 5;
bool keep_ratio = true;
// Map
Uint32 pixels_map[NATIVE_WIDTH][NATIVE_HEIGHT] = { { 0 } };
Uint32 pixels_map_actual[NATIVE_WIDTH][NATIVE_HEIGHT] = { { 1 } };
// SDL Variables
int bpp = 32;
int flags = SDL_HWSURFACE | SDL_RESIZABLE | SDL_DOUBLEBUF;
SDL_Surface* screen;
SDL_Surface* window;
/**
* Update game dimensions
*/
void resize(int w, int h) {
game_w = w;
game_h = h;
int new_pixel_size_w = game_w / NATIVE_WIDTH;
int new_pixel_size_h = game_h / NATIVE_HEIGHT;
if (!keep_ratio) {
pixel_size_w = new_pixel_size_w;
pixel_size_h = new_pixel_size_h;
}
else {
pixel_size_w = min(new_pixel_size_w, new_pixel_size_h);
pixel_size_h = pixel_size_w;
}
}
/**
* Draw a big pixel
*/
void drawPixel(int x, int y, Uint32 color)
{
int container_width = game_w;
int contained_width = NATIVE_WIDTH * pixel_size_w;
int container_height = game_h;
int contained_height = NATIVE_HEIGHT * pixel_size_h;
int offset_x = (int)(((float)container_width / 2) - ((float)contained_width / 2));
int offset_y = (int)(((float)container_height / 2) - ((float)contained_height / 2));
x = x * pixel_size_w + offset_x;
y = y * pixel_size_h + offset_y;
SDL_Rect rect = { x, y, pixel_size_w, pixel_size_h };
SDL_FillRect(window, &rect, color);
}
/**
* Draw next frame
*/
void drawScreen()
{
for (size_t i = 0; i < NATIVE_WIDTH; i++) {
for (size_t j = 0; j < NATIVE_HEIGHT; j++) {
pixels_map_actual[i][j] = pixels_map[i][j];
drawPixel(i, j, pixels_map[i][j]);
}
}
}
void processEvents()
{
SDL_Event event;
while(SDL_PollEvent(&event)) {
switch(event.type) {
case SDL_QUIT:
exit(EXIT_SUCCESS);
break;
case SDL_VIDEORESIZE:
SDL_FreeSurface(screen);
screen = SDL_SetVideoMode(event.resize.w, event.resize.h, bpp,
flags);
resize(event.resize.w, event.resize.h);
drawScreen();
}
}
}
/**
* One iteration of the main loop
*/
void oneIteration()
{
processEvents();
SDL_Flip(window);
}
/**
* Entry point
*/
int main(int argc, char** argv)
{
#ifndef EMSCRIPTEN
atexit(SDL_Quit);
#endif
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
cout << "Video initialization failed: " << SDL_GetError() << endl;
exit(EXIT_FAILURE);
}
const SDL_VideoInfo* screen_info = SDL_GetVideoInfo();
int screen_width = screen_info->current_w / 2;
int screen_height = screen_info->current_h / 2;
#ifdef EMSCRIPTEN
screen_width = screen_info->current_w;
screen_height = screen_info->current_h;
#endif
screen = SDL_SetVideoMode(screen_width, screen_height, bpp, flags);
if (screen == NULL) {
cout << "Video mode set failed: " << SDL_GetError() << endl;
exit(EXIT_SUCCESS);
}
SDL_WM_SetCaption("gbcEmulator", NULL);
window = SDL_GetVideoSurface();
resize(window->w, window->h);
// Generate pixels
srand (time(NULL));
for (size_t i = 0; i < NATIVE_WIDTH; i++) {
for (size_t j = 0; j < NATIVE_HEIGHT; j++) {
Uint32 color = rand() % 0xFFFFFFFF;
pixels_map[i][j] = color;
drawPixel(i, j, color);
}
}
#ifdef EMSCRIPTEN
emscripten_set_main_loop(oneIteration, 0, 1);
#else
while(1) {
oneIteration();
//60 FPS
SDL_Delay(16);
}
SDL_Quit();
#endif
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <common/list.h>
#include <gdb/location.h>
#include <stdlib.h>
#include <string.h>
#include <common/log.h>
gdb_location_t::gdb_location_t(){
fullname = 0;
filename = 0;
}
gdb_location_t::~gdb_location_t(){
delete fullname;
delete filename;
}
int conv_location(gdb_result_t* result, void** loc){
gdb_result_t* r;
if(*loc == 0)
*loc = new gdb_location_t;
list_for_each(result, r){
switch(r->var_id){
case V_LINE:
((gdb_location_t*)*loc)->line = atoi((char*)r->value);
break;
case V_FILE:
((gdb_location_t*)*loc)->filename = new char[strlen((const char*)r->value->value) + 1];
strcpy(((gdb_location_t*)*loc)->filename, (const char*)r->value->value);
break;
case V_FULLNAME:
((gdb_location_t*)*loc)->fullname = new char[strlen((const char*)r->value->value) + 1];
strcpy(((gdb_location_t*)*loc)->fullname, (const char*)r->value->value);
break;
default:
break;
};
}
return 0;
}
<commit_msg>[fix gdb location conversion]<commit_after>#include <common/list.h>
#include <gdb/location.h>
#include <stdlib.h>
#include <string.h>
#include <common/log.h>
gdb_location_t::gdb_location_t(){
fullname = 0;
filename = 0;
}
gdb_location_t::~gdb_location_t(){
delete fullname;
delete filename;
}
int conv_location(gdb_result_t* result, void** loc){
gdb_result_t* r;
if(*loc == 0)
*loc = new gdb_location_t;
list_for_each(result, r){
switch(r->var_id){
case V_LINE:
((gdb_location_t*)*loc)->line = atoi((char*)r->value->value);
break;
case V_FILE:
((gdb_location_t*)*loc)->filename = new char[strlen((const char*)r->value->value) + 1];
strcpy(((gdb_location_t*)*loc)->filename, (const char*)r->value->value);
break;
case V_FULLNAME:
((gdb_location_t*)*loc)->fullname = new char[strlen((const char*)r->value->value) + 1];
strcpy(((gdb_location_t*)*loc)->fullname, (const char*)r->value->value);
break;
default:
break;
};
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <tr1/memory>
#include <queue>
#include <boost/functional.hpp>
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>
#include "corpus_tools.h"
#include "m.h"
#include "tdict.h"
#include "sampler.h"
#include "ccrp.h"
// A not very memory-efficient implementation of an N-gram LM based on PYPs
// as described in Y.-W. Teh. (2006) A Hierarchical Bayesian Language Model
// based on Pitman-Yor Processes. In Proc. ACL.
// I use templates to handle the recursive formalation of the prior, so
// the order of the model has to be specified here, at compile time:
#define kORDER 3
using namespace std;
using namespace tr1;
namespace po = boost::program_options;
shared_ptr<MT19937> prng;
void InitCommandLine(int argc, char** argv, po::variables_map* conf) {
po::options_description opts("Configuration options");
opts.add_options()
("samples,s",po::value<unsigned>()->default_value(300),"Number of samples")
("train,i",po::value<string>(),"Training data file")
("test,T",po::value<string>(),"Test data file")
("discount_prior_a,a",po::value<double>()->default_value(1.0), "discount ~ Beta(a,b): a=this")
("discount_prior_b,b",po::value<double>()->default_value(1.0), "discount ~ Beta(a,b): b=this")
("strength_prior_s,s",po::value<double>()->default_value(1.0), "strength ~ Gamma(s,r): s=this")
("strength_prior_r,r",po::value<double>()->default_value(1.0), "strength ~ Gamma(s,r): r=this")
("random_seed,S",po::value<uint32_t>(), "Random seed");
po::options_description clo("Command line options");
clo.add_options()
("config", po::value<string>(), "Configuration file")
("help", "Print this help message and exit");
po::options_description dconfig_options, dcmdline_options;
dconfig_options.add(opts);
dcmdline_options.add(opts).add(clo);
po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
if (conf->count("config")) {
ifstream config((*conf)["config"].as<string>().c_str());
po::store(po::parse_config_file(config, dconfig_options), *conf);
}
po::notify(*conf);
if (conf->count("help") || (conf->count("train") == 0)) {
cerr << dcmdline_options << endl;
exit(1);
}
}
template <unsigned N> struct PYPLM;
// uniform base distribution (0-gram model)
template<> struct PYPLM<0> {
PYPLM(unsigned vs, double, double, double, double) : p0(1.0 / vs), draws() {}
void increment(WordID, const vector<WordID>&, MT19937*) { ++draws; }
void decrement(WordID, const vector<WordID>&, MT19937*) { --draws; assert(draws >= 0); }
double prob(WordID, const vector<WordID>&) const { return p0; }
void resample_hyperparameters(MT19937*, const unsigned, const unsigned) {}
double log_likelihood() const { return draws * log(p0); }
const double p0;
int draws;
};
// represents an N-gram LM
template <unsigned N> struct PYPLM {
PYPLM(unsigned vs, double da, double db, double ss, double sr) :
backoff(vs, da, db, ss, sr),
discount_a(da), discount_b(db),
strength_s(ss), strength_r(sr),
d(0.8), alpha(1.0), lookup(N-1) {}
void increment(WordID w, const vector<WordID>& context, MT19937* rng) {
const double bo = backoff.prob(w, context);
for (unsigned i = 0; i < N-1; ++i)
lookup[i] = context[context.size() - 1 - i];
typename unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > >::iterator it = p.find(lookup);
if (it == p.end())
it = p.insert(make_pair(lookup, CCRP<WordID>(d,alpha))).first;
if (it->second.increment(w, bo, rng))
backoff.increment(w, context, rng);
}
void decrement(WordID w, const vector<WordID>& context, MT19937* rng) {
for (unsigned i = 0; i < N-1; ++i)
lookup[i] = context[context.size() - 1 - i];
typename unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > >::iterator it = p.find(lookup);
assert(it != p.end());
if (it->second.decrement(w, rng))
backoff.decrement(w, context, rng);
}
double prob(WordID w, const vector<WordID>& context) const {
const double bo = backoff.prob(w, context);
for (unsigned i = 0; i < N-1; ++i)
lookup[i] = context[context.size() - 1 - i];
typename unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > >::const_iterator it = p.find(lookup);
if (it == p.end()) return bo;
return it->second.prob(w, bo);
}
double log_likelihood() const {
return log_likelihood(d, alpha) + backoff.log_likelihood();
}
double log_likelihood(const double& dd, const double& aa) const {
if (aa <= -dd) return -std::numeric_limits<double>::infinity();
//double llh = Md::log_beta_density(dd, 10, 3) + Md::log_gamma_density(aa, 1, 1);
double llh = Md::log_beta_density(dd, discount_a, discount_b) +
Md::log_gamma_density(aa, strength_s, strength_r);
typename unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > >::const_iterator it;
for (it = p.begin(); it != p.end(); ++it)
llh += it->second.log_crp_prob(dd, aa);
return llh;
}
struct DiscountResampler {
DiscountResampler(const PYPLM& m) : m_(m) {}
const PYPLM& m_;
double operator()(const double& proposed_discount) const {
return m_.log_likelihood(proposed_discount, m_.alpha);
}
};
struct AlphaResampler {
AlphaResampler(const PYPLM& m) : m_(m) {}
const PYPLM& m_;
double operator()(const double& proposed_alpha) const {
return m_.log_likelihood(m_.d, proposed_alpha);
}
};
void resample_hyperparameters(MT19937* rng, const unsigned nloop = 5, const unsigned niterations = 10) {
DiscountResampler dr(*this);
AlphaResampler ar(*this);
for (int iter = 0; iter < nloop; ++iter) {
alpha = slice_sampler1d(ar, alpha, *rng, 0.0,
std::numeric_limits<double>::infinity(), 0.0, niterations, 100*niterations);
d = slice_sampler1d(dr, d, *rng, std::numeric_limits<double>::min(),
1.0, 0.0, niterations, 100*niterations);
}
alpha = slice_sampler1d(ar, alpha, *rng, 0.0,
std::numeric_limits<double>::infinity(), 0.0, niterations, 100*niterations);
typename unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > >::iterator it;
cerr << "PYPLM<" << N << ">(d=" << d << ",a=" << alpha << ") = " << log_likelihood(d, alpha) << endl;
for (it = p.begin(); it != p.end(); ++it) {
it->second.set_discount(d);
it->second.set_alpha(alpha);
}
backoff.resample_hyperparameters(rng, nloop, niterations);
}
PYPLM<N-1> backoff;
double discount_a, discount_b, strength_s, strength_r;
double d, alpha;
mutable vector<WordID> lookup; // thread-local
unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > > p;
};
int main(int argc, char** argv) {
po::variables_map conf;
InitCommandLine(argc, argv, &conf);
const unsigned samples = conf["samples"].as<unsigned>();
if (conf.count("random_seed"))
prng.reset(new MT19937(conf["random_seed"].as<uint32_t>()));
else
prng.reset(new MT19937);
MT19937& rng = *prng;
vector<vector<WordID> > corpuse;
set<WordID> vocabe;
const WordID kEOS = TD::Convert("</s>");
cerr << "Reading corpus...\n";
CorpusTools::ReadFromFile(conf["train"].as<string>(), &corpuse, &vocabe);
cerr << "E-corpus size: " << corpuse.size() << " sentences\t (" << vocabe.size() << " word types)\n";
vector<vector<WordID> > test;
if (conf.count("test"))
CorpusTools::ReadFromFile(conf["test"].as<string>(), &test);
else
test = corpuse;
PYPLM<kORDER> lm(vocabe.size(),
conf["discount_prior_a"].as<double>(),
conf["discount_prior_b"].as<double>(),
conf["strength_prior_s"].as<double>(),
conf["strength_prior_r"].as<double>());
vector<WordID> ctx(kORDER - 1, TD::Convert("<s>"));
for (int SS=0; SS < samples; ++SS) {
for (int ci = 0; ci < corpuse.size(); ++ci) {
ctx.resize(kORDER - 1);
const vector<WordID>& s = corpuse[ci];
for (int i = 0; i <= s.size(); ++i) {
WordID w = (i < s.size() ? s[i] : kEOS);
if (SS > 0) lm.decrement(w, ctx, &rng);
lm.increment(w, ctx, &rng);
ctx.push_back(w);
}
if (SS > 0) lm.decrement(kEOS, ctx, &rng);
lm.increment(kEOS, ctx, &rng);
}
if (SS % 10 == 9) {
cerr << " [LLH=" << lm.log_likelihood() << "]" << endl;
if (SS % 20 == 19) lm.resample_hyperparameters(&rng);
} else { cerr << '.' << flush; }
}
double llh = 0;
unsigned cnt = 0;
unsigned oovs = 0;
for (int ci = 0; ci < test.size(); ++ci) {
ctx.resize(kORDER - 1);
const vector<WordID>& s = test[ci];
for (int i = 0; i <= s.size(); ++i) {
WordID w = (i < s.size() ? s[i] : kEOS);
double lp = log(lm.prob(w, ctx)) / log(2);
if (i < s.size() && vocabe.count(w) == 0) {
cerr << "**OOV ";
++oovs;
lp = 0;
}
cerr << "p(" << TD::Convert(w) << " |";
for (int j = ctx.size() + 1 - kORDER; j < ctx.size(); ++j)
cerr << ' ' << TD::Convert(ctx[j]);
cerr << ") = " << lp << endl;
ctx.push_back(w);
llh -= lp;
cnt++;
}
}
cerr << " Log_10 prob: " << (-llh * log(2) / log(10)) << endl;
cerr << " Count: " << cnt << endl;
cerr << " OOVs: " << oovs << endl;
cerr << "Cross-entropy: " << (llh / cnt) << endl;
cerr << " Perplexity: " << pow(2, llh / cnt) << endl;
return 0;
}
<commit_msg>fix parameter name clash<commit_after>#include <iostream>
#include <tr1/memory>
#include <queue>
#include <boost/functional.hpp>
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>
#include "corpus_tools.h"
#include "m.h"
#include "tdict.h"
#include "sampler.h"
#include "ccrp.h"
// A not very memory-efficient implementation of an N-gram LM based on PYPs
// as described in Y.-W. Teh. (2006) A Hierarchical Bayesian Language Model
// based on Pitman-Yor Processes. In Proc. ACL.
// I use templates to handle the recursive formalation of the prior, so
// the order of the model has to be specified here, at compile time:
#define kORDER 3
using namespace std;
using namespace tr1;
namespace po = boost::program_options;
shared_ptr<MT19937> prng;
void InitCommandLine(int argc, char** argv, po::variables_map* conf) {
po::options_description opts("Configuration options");
opts.add_options()
("samples,n",po::value<unsigned>()->default_value(300),"Number of samples")
("train,i",po::value<string>(),"Training data file")
("test,T",po::value<string>(),"Test data file")
("discount_prior_a,a",po::value<double>()->default_value(1.0), "discount ~ Beta(a,b): a=this")
("discount_prior_b,b",po::value<double>()->default_value(1.0), "discount ~ Beta(a,b): b=this")
("strength_prior_s,s",po::value<double>()->default_value(1.0), "strength ~ Gamma(s,r): s=this")
("strength_prior_r,r",po::value<double>()->default_value(1.0), "strength ~ Gamma(s,r): r=this")
("random_seed,S",po::value<uint32_t>(), "Random seed");
po::options_description clo("Command line options");
clo.add_options()
("config", po::value<string>(), "Configuration file")
("help", "Print this help message and exit");
po::options_description dconfig_options, dcmdline_options;
dconfig_options.add(opts);
dcmdline_options.add(opts).add(clo);
po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
if (conf->count("config")) {
ifstream config((*conf)["config"].as<string>().c_str());
po::store(po::parse_config_file(config, dconfig_options), *conf);
}
po::notify(*conf);
if (conf->count("help") || (conf->count("train") == 0)) {
cerr << dcmdline_options << endl;
exit(1);
}
}
template <unsigned N> struct PYPLM;
// uniform base distribution (0-gram model)
template<> struct PYPLM<0> {
PYPLM(unsigned vs, double, double, double, double) : p0(1.0 / vs), draws() {}
void increment(WordID, const vector<WordID>&, MT19937*) { ++draws; }
void decrement(WordID, const vector<WordID>&, MT19937*) { --draws; assert(draws >= 0); }
double prob(WordID, const vector<WordID>&) const { return p0; }
void resample_hyperparameters(MT19937*, const unsigned, const unsigned) {}
double log_likelihood() const { return draws * log(p0); }
const double p0;
int draws;
};
// represents an N-gram LM
template <unsigned N> struct PYPLM {
PYPLM(unsigned vs, double da, double db, double ss, double sr) :
backoff(vs, da, db, ss, sr),
discount_a(da), discount_b(db),
strength_s(ss), strength_r(sr),
d(0.8), alpha(1.0), lookup(N-1) {}
void increment(WordID w, const vector<WordID>& context, MT19937* rng) {
const double bo = backoff.prob(w, context);
for (unsigned i = 0; i < N-1; ++i)
lookup[i] = context[context.size() - 1 - i];
typename unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > >::iterator it = p.find(lookup);
if (it == p.end())
it = p.insert(make_pair(lookup, CCRP<WordID>(d,alpha))).first;
if (it->second.increment(w, bo, rng))
backoff.increment(w, context, rng);
}
void decrement(WordID w, const vector<WordID>& context, MT19937* rng) {
for (unsigned i = 0; i < N-1; ++i)
lookup[i] = context[context.size() - 1 - i];
typename unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > >::iterator it = p.find(lookup);
assert(it != p.end());
if (it->second.decrement(w, rng))
backoff.decrement(w, context, rng);
}
double prob(WordID w, const vector<WordID>& context) const {
const double bo = backoff.prob(w, context);
for (unsigned i = 0; i < N-1; ++i)
lookup[i] = context[context.size() - 1 - i];
typename unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > >::const_iterator it = p.find(lookup);
if (it == p.end()) return bo;
return it->second.prob(w, bo);
}
double log_likelihood() const {
return log_likelihood(d, alpha) + backoff.log_likelihood();
}
double log_likelihood(const double& dd, const double& aa) const {
if (aa <= -dd) return -std::numeric_limits<double>::infinity();
//double llh = Md::log_beta_density(dd, 10, 3) + Md::log_gamma_density(aa, 1, 1);
double llh = Md::log_beta_density(dd, discount_a, discount_b) +
Md::log_gamma_density(aa, strength_s, strength_r);
typename unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > >::const_iterator it;
for (it = p.begin(); it != p.end(); ++it)
llh += it->second.log_crp_prob(dd, aa);
return llh;
}
struct DiscountResampler {
DiscountResampler(const PYPLM& m) : m_(m) {}
const PYPLM& m_;
double operator()(const double& proposed_discount) const {
return m_.log_likelihood(proposed_discount, m_.alpha);
}
};
struct AlphaResampler {
AlphaResampler(const PYPLM& m) : m_(m) {}
const PYPLM& m_;
double operator()(const double& proposed_alpha) const {
return m_.log_likelihood(m_.d, proposed_alpha);
}
};
void resample_hyperparameters(MT19937* rng, const unsigned nloop = 5, const unsigned niterations = 10) {
DiscountResampler dr(*this);
AlphaResampler ar(*this);
for (int iter = 0; iter < nloop; ++iter) {
alpha = slice_sampler1d(ar, alpha, *rng, 0.0,
std::numeric_limits<double>::infinity(), 0.0, niterations, 100*niterations);
d = slice_sampler1d(dr, d, *rng, std::numeric_limits<double>::min(),
1.0, 0.0, niterations, 100*niterations);
}
alpha = slice_sampler1d(ar, alpha, *rng, 0.0,
std::numeric_limits<double>::infinity(), 0.0, niterations, 100*niterations);
typename unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > >::iterator it;
cerr << "PYPLM<" << N << ">(d=" << d << ",a=" << alpha << ") = " << log_likelihood(d, alpha) << endl;
for (it = p.begin(); it != p.end(); ++it) {
it->second.set_discount(d);
it->second.set_alpha(alpha);
}
backoff.resample_hyperparameters(rng, nloop, niterations);
}
PYPLM<N-1> backoff;
double discount_a, discount_b, strength_s, strength_r;
double d, alpha;
mutable vector<WordID> lookup; // thread-local
unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > > p;
};
int main(int argc, char** argv) {
po::variables_map conf;
InitCommandLine(argc, argv, &conf);
const unsigned samples = conf["samples"].as<unsigned>();
if (conf.count("random_seed"))
prng.reset(new MT19937(conf["random_seed"].as<uint32_t>()));
else
prng.reset(new MT19937);
MT19937& rng = *prng;
vector<vector<WordID> > corpuse;
set<WordID> vocabe;
const WordID kEOS = TD::Convert("</s>");
cerr << "Reading corpus...\n";
CorpusTools::ReadFromFile(conf["train"].as<string>(), &corpuse, &vocabe);
cerr << "E-corpus size: " << corpuse.size() << " sentences\t (" << vocabe.size() << " word types)\n";
vector<vector<WordID> > test;
if (conf.count("test"))
CorpusTools::ReadFromFile(conf["test"].as<string>(), &test);
else
test = corpuse;
PYPLM<kORDER> lm(vocabe.size(),
conf["discount_prior_a"].as<double>(),
conf["discount_prior_b"].as<double>(),
conf["strength_prior_s"].as<double>(),
conf["strength_prior_r"].as<double>());
vector<WordID> ctx(kORDER - 1, TD::Convert("<s>"));
for (int SS=0; SS < samples; ++SS) {
for (int ci = 0; ci < corpuse.size(); ++ci) {
ctx.resize(kORDER - 1);
const vector<WordID>& s = corpuse[ci];
for (int i = 0; i <= s.size(); ++i) {
WordID w = (i < s.size() ? s[i] : kEOS);
if (SS > 0) lm.decrement(w, ctx, &rng);
lm.increment(w, ctx, &rng);
ctx.push_back(w);
}
if (SS > 0) lm.decrement(kEOS, ctx, &rng);
lm.increment(kEOS, ctx, &rng);
}
if (SS % 10 == 9) {
cerr << " [LLH=" << lm.log_likelihood() << "]" << endl;
if (SS % 20 == 19) lm.resample_hyperparameters(&rng);
} else { cerr << '.' << flush; }
}
double llh = 0;
unsigned cnt = 0;
unsigned oovs = 0;
for (int ci = 0; ci < test.size(); ++ci) {
ctx.resize(kORDER - 1);
const vector<WordID>& s = test[ci];
for (int i = 0; i <= s.size(); ++i) {
WordID w = (i < s.size() ? s[i] : kEOS);
double lp = log(lm.prob(w, ctx)) / log(2);
if (i < s.size() && vocabe.count(w) == 0) {
cerr << "**OOV ";
++oovs;
lp = 0;
}
cerr << "p(" << TD::Convert(w) << " |";
for (int j = ctx.size() + 1 - kORDER; j < ctx.size(); ++j)
cerr << ' ' << TD::Convert(ctx[j]);
cerr << ") = " << lp << endl;
ctx.push_back(w);
llh -= lp;
cnt++;
}
}
cerr << " Log_10 prob: " << (-llh * log(2) / log(10)) << endl;
cerr << " Count: " << cnt << endl;
cerr << " OOVs: " << oovs << endl;
cerr << "Cross-entropy: " << (llh / cnt) << endl;
cerr << " Perplexity: " << pow(2, llh / cnt) << endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkPath.h"
#include "SkRandom.h"
#include "SkTArray.h"
namespace skiagm {
// This GM tests a grab-bag of convex and concave polygons. They are triangles,
// trapezoid, diamond, polygons with lots of edges, several concave polygons...
// But rectangles are excluded.
class PolygonsGM: public GM {
public:
PolygonsGM() {}
protected:
virtual SkString onShortName() SK_OVERRIDE {
return SkString("polygons");
}
virtual SkISize onISize() SK_OVERRIDE {
size_t width = kNumPolygons * kCellSize + 40;
size_t height = (kNumJoins * kNumStrokeWidths + kNumExtraStyles) * kCellSize + 40;
return SkISize::Make(width, height);
}
// Construct all polygons
virtual void onOnceBeforeDraw() SK_OVERRIDE {
SkPoint p0[] = {{0, 0}, {60, 0}, {90, 40}}; // triangle
SkPoint p1[] = {{0, 0}, {0, 40}, {60, 40}, {40, 0}}; // trapezoid
SkPoint p2[] = {{0, 0}, {40, 40}, {80, 40}, {40, 0}}; // diamond
SkPoint p3[] = {{10, 0}, {50, 0}, {60, 10}, {60, 30}, {50, 40},
{10, 40}, {0, 30}, {0, 10}}; // octagon
SkPoint p4[32]; // circle-like polygons with 32-edges.
SkPoint p5[] = {{0, 0}, {20, 20}, {0, 40}, {60, 20}}; // concave polygon with 4 edges
SkPoint p6[] = {{0, 40}, {0, 30}, {15, 30}, {15, 20}, {30, 20},
{30, 10}, {45, 10}, {45, 0}, {60, 0}, {60, 40}}; // stairs-like polygon
SkPoint p7[] = {{0, 20}, {20, 20}, {30, 0}, {40, 20}, {60, 20},
{45, 30}, {55, 50}, {30, 40}, {5, 50}, {15, 30}}; // five-point stars
for (size_t i = 0; i < SK_ARRAY_COUNT(p4); ++i) {
SkScalar angle = 2 * SK_ScalarPI * i / SK_ARRAY_COUNT(p4);
p4[i].set(20 * cos(angle) + 20, 20 * sin(angle) + 20);
}
struct Polygons {
SkPoint* fPoints;
size_t fPointNum;
} pgs[] = {
{ p0, SK_ARRAY_COUNT(p0) },
{ p1, SK_ARRAY_COUNT(p1) },
{ p2, SK_ARRAY_COUNT(p2) },
{ p3, SK_ARRAY_COUNT(p3) },
{ p4, SK_ARRAY_COUNT(p4) },
{ p5, SK_ARRAY_COUNT(p5) },
{ p6, SK_ARRAY_COUNT(p6) },
{ p7, SK_ARRAY_COUNT(p7) }
};
SkASSERT(SK_ARRAY_COUNT(pgs) == kNumPolygons);
for (size_t pgIndex = 0; pgIndex < SK_ARRAY_COUNT(pgs); ++pgIndex) {
fPolygons.push_back().moveTo(pgs[pgIndex].fPoints[0].fX,
pgs[pgIndex].fPoints[0].fY);
for (size_t ptIndex = 1; ptIndex < pgs[pgIndex].fPointNum; ++ptIndex) {
fPolygons.back().lineTo(pgs[pgIndex].fPoints[ptIndex].fX,
pgs[pgIndex].fPoints[ptIndex].fY);
}
fPolygons.back().close();
}
}
// Set the location for the current test on the canvas
static void SetLocation(SkCanvas* canvas, int counter, int lineNum) {
SkScalar x = SK_Scalar1 * kCellSize * (counter % lineNum) + 30 + SK_Scalar1 / 4;
SkScalar y = SK_Scalar1 * kCellSize * (counter / lineNum) + 30 + 3 * SK_Scalar1 / 4;
canvas->translate(x, y);
}
static void SetColorAndAlpha(SkPaint* paint, SkLCGRandom* rand) {
SkColor color = rand->nextU();
color |= 0xff000000;
paint->setColor(color);
if (40 == paint->getStrokeWidth()) {
paint->setAlpha(0xA0);
}
}
virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
// Stroke widths are:
// 0(may use hairline rendering), 10(common case for stroke-style)
// 40(>= geometry width/height, make the contour filled in fact)
static const int kStrokeWidths[] = {0, 10, 40};
SkASSERT(kNumStrokeWidths == SK_ARRAY_COUNT(kStrokeWidths));
static const SkPaint::Join kJoins[] = {
SkPaint::kMiter_Join, SkPaint::kRound_Join, SkPaint::kBevel_Join
};
SkASSERT(kNumJoins == SK_ARRAY_COUNT(kJoins));
int counter = 0;
SkPaint paint;
paint.setAntiAlias(true);
SkLCGRandom rand;
// For stroke style painter
paint.setStyle(SkPaint::kStroke_Style);
for (int join = 0; join < kNumJoins; ++join) {
for (int width = 0; width < kNumStrokeWidths; ++width) {
for (int i = 0; i < fPolygons.count(); ++i) {
canvas->save();
SetLocation(canvas, counter, fPolygons.count());
SetColorAndAlpha(&paint, &rand);
paint.setStrokeJoin(kJoins[join]);
paint.setStrokeWidth(SkIntToScalar(kStrokeWidths[width]));
canvas->drawPath(fPolygons[i], paint);
canvas->restore();
++counter;
}
}
}
// For stroke-and-fill style painter and fill style painter
static const SkPaint::Style kStyles[] = {
SkPaint::kStrokeAndFill_Style, SkPaint::kFill_Style
};
SkASSERT(kNumExtraStyles == SK_ARRAY_COUNT(kStyles));
paint.setStrokeJoin(SkPaint::kMiter_Join);
paint.setStrokeWidth(SkIntToScalar(20));
for (int style = 0; style < kNumExtraStyles; ++style) {
paint.setStyle(kStyles[style]);
for (int i = 0; i < fPolygons.count(); ++i) {
canvas->save();
SetLocation(canvas, counter, fPolygons.count());
SetColorAndAlpha(&paint, &rand);
canvas->drawPath(fPolygons[i], paint);
canvas->restore();
++counter;
}
}
}
private:
static const int kNumPolygons = 8;
static const int kCellSize = 100;
static const int kNumExtraStyles = 2;
static const int kNumStrokeWidths = 3;
static const int kNumJoins = 3;
SkTArray<SkPath> fPolygons;
typedef GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
DEF_GM(return new PolygonsGM;)
}
<commit_msg>Fix warning as error on Mac for implicit narrowing conversion from r12413.<commit_after>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkPath.h"
#include "SkRandom.h"
#include "SkScalar.h"
#include "SkTArray.h"
namespace skiagm {
// This GM tests a grab-bag of convex and concave polygons. They are triangles,
// trapezoid, diamond, polygons with lots of edges, several concave polygons...
// But rectangles are excluded.
class PolygonsGM: public GM {
public:
PolygonsGM() {}
protected:
virtual SkString onShortName() SK_OVERRIDE {
return SkString("polygons");
}
virtual SkISize onISize() SK_OVERRIDE {
size_t width = kNumPolygons * kCellSize + 40;
size_t height = (kNumJoins * kNumStrokeWidths + kNumExtraStyles) * kCellSize + 40;
return SkISize::Make(width, height);
}
// Construct all polygons
virtual void onOnceBeforeDraw() SK_OVERRIDE {
SkPoint p0[] = {{0, 0}, {60, 0}, {90, 40}}; // triangle
SkPoint p1[] = {{0, 0}, {0, 40}, {60, 40}, {40, 0}}; // trapezoid
SkPoint p2[] = {{0, 0}, {40, 40}, {80, 40}, {40, 0}}; // diamond
SkPoint p3[] = {{10, 0}, {50, 0}, {60, 10}, {60, 30}, {50, 40},
{10, 40}, {0, 30}, {0, 10}}; // octagon
SkPoint p4[32]; // circle-like polygons with 32-edges.
SkPoint p5[] = {{0, 0}, {20, 20}, {0, 40}, {60, 20}}; // concave polygon with 4 edges
SkPoint p6[] = {{0, 40}, {0, 30}, {15, 30}, {15, 20}, {30, 20},
{30, 10}, {45, 10}, {45, 0}, {60, 0}, {60, 40}}; // stairs-like polygon
SkPoint p7[] = {{0, 20}, {20, 20}, {30, 0}, {40, 20}, {60, 20},
{45, 30}, {55, 50}, {30, 40}, {5, 50}, {15, 30}}; // five-point stars
for (size_t i = 0; i < SK_ARRAY_COUNT(p4); ++i) {
SkScalar angle = 2 * SK_ScalarPI * i / SK_ARRAY_COUNT(p4);
p4[i].set(20 * SkScalarCos(angle) + 20, 20 * SkScalarSin(angle) + 20);
}
struct Polygons {
SkPoint* fPoints;
size_t fPointNum;
} pgs[] = {
{ p0, SK_ARRAY_COUNT(p0) },
{ p1, SK_ARRAY_COUNT(p1) },
{ p2, SK_ARRAY_COUNT(p2) },
{ p3, SK_ARRAY_COUNT(p3) },
{ p4, SK_ARRAY_COUNT(p4) },
{ p5, SK_ARRAY_COUNT(p5) },
{ p6, SK_ARRAY_COUNT(p6) },
{ p7, SK_ARRAY_COUNT(p7) }
};
SkASSERT(SK_ARRAY_COUNT(pgs) == kNumPolygons);
for (size_t pgIndex = 0; pgIndex < SK_ARRAY_COUNT(pgs); ++pgIndex) {
fPolygons.push_back().moveTo(pgs[pgIndex].fPoints[0].fX,
pgs[pgIndex].fPoints[0].fY);
for (size_t ptIndex = 1; ptIndex < pgs[pgIndex].fPointNum; ++ptIndex) {
fPolygons.back().lineTo(pgs[pgIndex].fPoints[ptIndex].fX,
pgs[pgIndex].fPoints[ptIndex].fY);
}
fPolygons.back().close();
}
}
// Set the location for the current test on the canvas
static void SetLocation(SkCanvas* canvas, int counter, int lineNum) {
SkScalar x = SK_Scalar1 * kCellSize * (counter % lineNum) + 30 + SK_Scalar1 / 4;
SkScalar y = SK_Scalar1 * kCellSize * (counter / lineNum) + 30 + 3 * SK_Scalar1 / 4;
canvas->translate(x, y);
}
static void SetColorAndAlpha(SkPaint* paint, SkLCGRandom* rand) {
SkColor color = rand->nextU();
color |= 0xff000000;
paint->setColor(color);
if (40 == paint->getStrokeWidth()) {
paint->setAlpha(0xA0);
}
}
virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
// Stroke widths are:
// 0(may use hairline rendering), 10(common case for stroke-style)
// 40(>= geometry width/height, make the contour filled in fact)
static const int kStrokeWidths[] = {0, 10, 40};
SkASSERT(kNumStrokeWidths == SK_ARRAY_COUNT(kStrokeWidths));
static const SkPaint::Join kJoins[] = {
SkPaint::kMiter_Join, SkPaint::kRound_Join, SkPaint::kBevel_Join
};
SkASSERT(kNumJoins == SK_ARRAY_COUNT(kJoins));
int counter = 0;
SkPaint paint;
paint.setAntiAlias(true);
SkLCGRandom rand;
// For stroke style painter
paint.setStyle(SkPaint::kStroke_Style);
for (int join = 0; join < kNumJoins; ++join) {
for (int width = 0; width < kNumStrokeWidths; ++width) {
for (int i = 0; i < fPolygons.count(); ++i) {
canvas->save();
SetLocation(canvas, counter, fPolygons.count());
SetColorAndAlpha(&paint, &rand);
paint.setStrokeJoin(kJoins[join]);
paint.setStrokeWidth(SkIntToScalar(kStrokeWidths[width]));
canvas->drawPath(fPolygons[i], paint);
canvas->restore();
++counter;
}
}
}
// For stroke-and-fill style painter and fill style painter
static const SkPaint::Style kStyles[] = {
SkPaint::kStrokeAndFill_Style, SkPaint::kFill_Style
};
SkASSERT(kNumExtraStyles == SK_ARRAY_COUNT(kStyles));
paint.setStrokeJoin(SkPaint::kMiter_Join);
paint.setStrokeWidth(SkIntToScalar(20));
for (int style = 0; style < kNumExtraStyles; ++style) {
paint.setStyle(kStyles[style]);
for (int i = 0; i < fPolygons.count(); ++i) {
canvas->save();
SetLocation(canvas, counter, fPolygons.count());
SetColorAndAlpha(&paint, &rand);
canvas->drawPath(fPolygons[i], paint);
canvas->restore();
++counter;
}
}
}
private:
static const int kNumPolygons = 8;
static const int kCellSize = 100;
static const int kNumExtraStyles = 2;
static const int kNumStrokeWidths = 3;
static const int kNumJoins = 3;
SkTArray<SkPath> fPolygons;
typedef GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
DEF_GM(return new PolygonsGM;)
}
<|endoftext|> |
<commit_before>#include "MainWindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent),
currentState(NotConnected),
sshProcess(NULL),
sshAskPassFile(NULL),
timer(NULL)
{
setWindowTitle(qApp->applicationName());
layout = new QFormLayout();
sshServerLayout = new QHBoxLayout();
sshServerAddrEdit = new QLineEdit();
sshServerLayout->addWidget(sshServerAddrEdit);
sshServerColon = new QLabel(":");
sshServerLayout->addWidget(sshServerColon);
sshServerPortEdit = new QLineEdit();
sshServerPortEdit->setMaxLength(5);
sshServerPortEdit->setFixedWidth(50);
sshServerLayout->addWidget(sshServerPortEdit);
layout->addRow(tr("SSH Server:"), sshServerLayout);
usernameEdit = new QLineEdit();
layout->addRow(tr("Username:"), usernameEdit);
passwordLayout = new QHBoxLayout();
passwordEdit = new QLineEdit();
passwordEdit->setEchoMode(QLineEdit::Password);
passwordLayout->addWidget(passwordEdit);
remberPasswordCheckBox = new QCheckBox(tr("Rember"));
passwordLayout->addWidget(remberPasswordCheckBox);
layout->addRow(tr("Password:"), passwordLayout);
socksServerLayout = new QHBoxLayout();
socksServerAddrEdit = new QLineEdit();
socksServerLayout->addWidget(socksServerAddrEdit);
socksServerColon = new QLabel(":");
socksServerLayout->addWidget(socksServerColon);
socksServerPortEdit = new QLineEdit();
socksServerPortEdit->setMaxLength(5);
socksServerPortEdit->setFixedWidth(50);
socksServerLayout->addWidget(socksServerPortEdit);
layout->addRow(tr("SOCKS Server:"), socksServerLayout);
statusLabel = new QLabel();
layout->addRow(tr("Status:"), statusLabel);
connectBtn = new QPushButton();
connect(connectBtn, SIGNAL(clicked()), this, SLOT(connectBtnClicked()));
layout->addRow(connectBtn);
QWidget *widget = new QWidget(this);
widget->setLayout(layout);
setCentralWidget(widget);
prepareMenuBar();
prepareTrayIcon();
loadSettings();
setCurrentState(NotConnected);
}
MainWindow::~MainWindow()
{
}
void
MainWindow::connectBtnClicked()
{
if (!this->validateForm()) {
return;
}
connectBtn->setDisabled(true);
if (currentState == NotConnected) {
connectSSH();
} else {
disconnectSSH();
}
}
void
MainWindow::operationActionTriggered()
{
if (!this->validateForm()) {
return;
}
if (currentState == NotConnected) {
connectSSH();
} else if (currentState == Connected) {
disconnectSSH();
}
}
void
MainWindow::sshReadyReadStdout()
{
QString data(sshProcess->readAllStandardOutput());
qDebug() << "stdout:" << data;
}
void
MainWindow::sshReadyReadStderr()
{
QString data(sshProcess->readAllStandardError());
qDebug() << "stderr:" << data;
if (data.contains("Permission denied")) {
/* Connect failed, maybe incorrect username or password */
setCurrentState(NotConnected);
statusLabel->setText(tr("Connect failed (permission denied)"));
if (sshAskPassFile != NULL) {
delete sshAskPassFile;
sshAskPassFile = NULL;
}
} else if (data.contains("Operation timed out")) {
/* Connect failed, maybe incorrect IP/port */
setCurrentState(NotConnected);
statusLabel->setText(tr("Connect failed (Operation timed out)"));
} else if (data.contains("Entering interactive session.")) {
/* Connect success */
setCurrentState(Connected);
} else {
/* If output is not key information, then return, don't remove
* sshAskPassFile */
return;
}
if (sshAskPassFile != NULL) {
delete sshAskPassFile;
sshAskPassFile = NULL;
}
}
void
MainWindow::updateTime()
{
QTime t(0, 0, 0);
t = t.addMSecs(elapsedTimer.elapsed());
QString status = tr("Connected (%1)").arg(t.toString("hh:mm:ss"));
statusLabel->setText(status);
statusAction->setText(status);
}
void
MainWindow::closeEvent(QCloseEvent *event)
{
settings.setValue("ssh_server/addr", sshServerAddrEdit->text());
settings.setValue("ssh_server/port", sshServerPortEdit->text());
settings.setValue("username", usernameEdit->text());
if (remberPasswordCheckBox->isChecked()) {
settings.setValue("password/value", passwordEdit->text());
settings.setValue("password/rember",
remberPasswordCheckBox->isChecked());
} else {
settings.remove("password");
}
settings.setValue("socks_server/addr", socksServerAddrEdit->text());
settings.setValue("socks_server/port", socksServerPortEdit->text());
event->accept();
}
void
MainWindow::prepareMenuBar()
{
}
void
MainWindow::prepareTrayIcon()
{
trayIcon = new QSystemTrayIcon(QIcon(":/images/images/[email protected]"),
this);
trayMenu = new QMenu(this);
/* Add status and operation action */
statusAction = new QAction(this);
statusAction->setDisabled(true);
trayMenu->addAction(statusAction);
operationAction = new QAction(this);
connect(operationAction, SIGNAL(triggered()),
this, SLOT(operationActionTriggered()));
trayMenu->addAction(operationAction);
/* Separator */
trayMenu->addSeparator();
/* Quit action */
trayMenu->addAction(tr("Quit %1").arg(qApp->applicationName()),
qApp, SLOT(quit()));
trayIcon->setContextMenu(trayMenu);
trayIcon->show();
}
void
MainWindow::loadSettings()
{
sshServerAddrEdit->setText(settings.value("ssh_server/addr").toString());
sshServerPortEdit->setText(settings.value("ssh_server/port",
"22").toString());
usernameEdit->setText(settings.value("username").toString());
passwordEdit->setText(settings.value("password/value").toString());
remberPasswordCheckBox->setChecked(settings.value("password/rember",
false).toBool());
socksServerAddrEdit->setText(settings.value("socks_server/addr",
"127.0.0.1").toString());
socksServerPortEdit->setText(settings.value("socks_server/port",
"7070").toString());
}
bool
MainWindow::validateForm()
{
if (sshServerAddrEdit->text().length() == 0) {
QMessageBox::warning(this, tr("Warning"),
tr("Invalid SSH server address"));
return false;
}
if (sshServerPortEdit->text().length() == 0) {
QMessageBox::warning(this, tr("Warning"),
tr("Invalid SSH server address"));
return false;
}
if (usernameEdit->text().length() == 0) {
QMessageBox::warning(this, tr("Warning"),
tr("Invalid SSH username"));
return false;
}
if (passwordEdit->text().length() == 0) {
QMessageBox::warning(this, tr("Warning"),
tr("Invalid SSH password"));
return false;
}
if (socksServerAddrEdit->text().length() == 0) {
QMessageBox::warning(this, tr("Warning"),
tr("Invalid SOCKS server address"));
return false;
}
if (socksServerPortEdit->text().length() == 0) {
QMessageBox::warning(this, tr("Warning"),
tr("Invalid SOCKS server address"));
return false;
}
return true;
}
void
MainWindow::connectSSH()
{
setCurrentState(Connecting);
/* Create SSH process object */
sshProcess = new QProcess(this);
connect(sshProcess, SIGNAL(readyReadStandardOutput()),
this, SLOT(sshReadyReadStdout()));
connect(sshProcess, SIGNAL(readyReadStandardError()),
this, SLOT(sshReadyReadStderr()));
/* Generate SSH_ASKPASS file with right permission and content */
sshAskPassFile = new QTemporaryFile();
if (!sshAskPassFile->open()) {
setCurrentState(NotConnected);
statusLabel->setText(tr("Connect failed (SSH_ASKPASS error)"));
return;
}
QFile::Permissions perm = sshAskPassFile->permissions();
qDebug() << sshAskPassFile->fileName();
perm |= QFile::ExeOwner | QFile::ExeUser;
sshAskPassFile->setPermissions(perm);
QTextStream out(sshAskPassFile);
out << "#!/usr/bin/env bash\n";
out << "echo '" << passwordEdit->text() << "'\n";
sshAskPassFile->close();
/* Set SSH_ASKPASS enviroment variable */
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
env.insert("SSH_ASKPASS", sshAskPassFile->fileName());
sshProcess->setProcessEnvironment(env);
/* Assemble arguments and start SSH process */
QStringList arguments;
arguments << "-qTnN";
arguments << "-v";
arguments << "-D" << QString("%1:%2").arg(socksServerAddrEdit->text(),
socksServerPortEdit->text());
arguments << "-p" << sshServerPortEdit->text();
arguments << "-o" << "ConnectTimeout=10";
arguments << QString("%1@%2").arg(usernameEdit->text(),
sshServerAddrEdit->text());
sshProcess->start("ssh", arguments);
if (!sshProcess->waitForStarted(1000)) {
setCurrentState(NotConnected);
statusLabel->setText(tr("SSH start failed"));
return;
}
}
void
MainWindow::disconnectSSH()
{
setCurrentState(Disconnecting);
sshProcess->kill();
delete sshProcess;
sshProcess = NULL;
setCurrentState(NotConnected);
}
void
MainWindow::setCurrentState(CurrentState state)
{
currentState = state;
if (currentState != Connected && timer != NULL) {
delete timer;
timer = NULL;
}
if (currentState == NotConnected) {
statusLabel->setText(tr("Not connected"));
connectBtn->setText(tr("Connect"));
connectBtn->setEnabled(true);
statusAction->setText(tr("Not connected"));
operationAction->setText(tr("Connect"));
operationAction->setVisible(true);
} else if (currentState == Connecting) {
statusLabel->setText(tr("Connecting..."));
connectBtn->setEnabled(false);
statusAction->setText(tr("Connecting..."));
operationAction->setVisible(false);
} else if (currentState == Connected) {
/* Start timer to update elapsed time in status label */
elapsedTimer.restart();
updateTime();
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateTime()));
timer->start(1000);
connectBtn->setText(tr("Disconnect"));
connectBtn->setEnabled(true);
operationAction->setText(tr("Disconnect"));
operationAction->setVisible(true);
} else if (currentState == Disconnecting) {
statusLabel->setText(tr("Disconnecting..."));
connectBtn->setEnabled(false);
statusAction->setText(tr("Disconnecting..."));
operationAction->setVisible(false);
}
}
<commit_msg>add disable user input area when connecting<commit_after>#include "MainWindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent),
currentState(NotConnected),
sshProcess(NULL),
sshAskPassFile(NULL),
timer(NULL)
{
setWindowTitle(qApp->applicationName());
layout = new QFormLayout();
sshServerLayout = new QHBoxLayout();
sshServerAddrEdit = new QLineEdit();
sshServerLayout->addWidget(sshServerAddrEdit);
sshServerColon = new QLabel(":");
sshServerLayout->addWidget(sshServerColon);
sshServerPortEdit = new QLineEdit();
sshServerPortEdit->setMaxLength(5);
sshServerPortEdit->setFixedWidth(50);
sshServerLayout->addWidget(sshServerPortEdit);
layout->addRow(tr("SSH Server:"), sshServerLayout);
usernameEdit = new QLineEdit();
layout->addRow(tr("Username:"), usernameEdit);
passwordLayout = new QHBoxLayout();
passwordEdit = new QLineEdit();
passwordEdit->setEchoMode(QLineEdit::Password);
passwordLayout->addWidget(passwordEdit);
remberPasswordCheckBox = new QCheckBox(tr("Rember"));
passwordLayout->addWidget(remberPasswordCheckBox);
layout->addRow(tr("Password:"), passwordLayout);
socksServerLayout = new QHBoxLayout();
socksServerAddrEdit = new QLineEdit();
socksServerLayout->addWidget(socksServerAddrEdit);
socksServerColon = new QLabel(":");
socksServerLayout->addWidget(socksServerColon);
socksServerPortEdit = new QLineEdit();
socksServerPortEdit->setMaxLength(5);
socksServerPortEdit->setFixedWidth(50);
socksServerLayout->addWidget(socksServerPortEdit);
layout->addRow(tr("SOCKS Server:"), socksServerLayout);
statusLabel = new QLabel();
layout->addRow(tr("Status:"), statusLabel);
connectBtn = new QPushButton();
connect(connectBtn, SIGNAL(clicked()), this, SLOT(connectBtnClicked()));
layout->addRow(connectBtn);
QWidget *widget = new QWidget(this);
widget->setLayout(layout);
setCentralWidget(widget);
prepareMenuBar();
prepareTrayIcon();
loadSettings();
setCurrentState(NotConnected);
}
MainWindow::~MainWindow()
{
}
void
MainWindow::connectBtnClicked()
{
if (!this->validateForm()) {
return;
}
connectBtn->setDisabled(true);
if (currentState == NotConnected) {
connectSSH();
} else {
disconnectSSH();
}
}
void
MainWindow::operationActionTriggered()
{
if (!this->validateForm()) {
return;
}
if (currentState == NotConnected) {
connectSSH();
} else if (currentState == Connected) {
disconnectSSH();
}
}
void
MainWindow::sshReadyReadStdout()
{
QString data(sshProcess->readAllStandardOutput());
qDebug() << "stdout:" << data;
}
void
MainWindow::sshReadyReadStderr()
{
QString data(sshProcess->readAllStandardError());
qDebug() << "stderr:" << data;
if (data.contains("Permission denied")) {
/* Connect failed, maybe incorrect username or password */
setCurrentState(NotConnected);
statusLabel->setText(tr("Connect failed (permission denied)"));
if (sshAskPassFile != NULL) {
delete sshAskPassFile;
sshAskPassFile = NULL;
}
} else if (data.contains("Operation timed out")) {
/* Connect failed, maybe incorrect IP/port */
setCurrentState(NotConnected);
statusLabel->setText(tr("Connect failed (Operation timed out)"));
} else if (data.contains("Entering interactive session.")) {
/* Connect success */
setCurrentState(Connected);
} else {
/* If output is not key information, then return, don't remove
* sshAskPassFile */
return;
}
if (sshAskPassFile != NULL) {
delete sshAskPassFile;
sshAskPassFile = NULL;
}
}
void
MainWindow::updateTime()
{
QTime t(0, 0, 0);
t = t.addMSecs(elapsedTimer.elapsed());
QString status = tr("Connected (%1)").arg(t.toString("hh:mm:ss"));
statusLabel->setText(status);
statusAction->setText(status);
}
void
MainWindow::closeEvent(QCloseEvent *event)
{
settings.setValue("ssh_server/addr", sshServerAddrEdit->text());
settings.setValue("ssh_server/port", sshServerPortEdit->text());
settings.setValue("username", usernameEdit->text());
if (remberPasswordCheckBox->isChecked()) {
settings.setValue("password/value", passwordEdit->text());
settings.setValue("password/rember",
remberPasswordCheckBox->isChecked());
} else {
settings.remove("password");
}
settings.setValue("socks_server/addr", socksServerAddrEdit->text());
settings.setValue("socks_server/port", socksServerPortEdit->text());
event->accept();
}
void
MainWindow::prepareMenuBar()
{
}
void
MainWindow::prepareTrayIcon()
{
trayIcon = new QSystemTrayIcon(QIcon(":/images/images/[email protected]"),
this);
trayMenu = new QMenu(this);
/* Add status and operation action */
statusAction = new QAction(this);
statusAction->setDisabled(true);
trayMenu->addAction(statusAction);
operationAction = new QAction(this);
connect(operationAction, SIGNAL(triggered()),
this, SLOT(operationActionTriggered()));
trayMenu->addAction(operationAction);
/* Separator */
trayMenu->addSeparator();
/* Quit action */
trayMenu->addAction(tr("Quit %1").arg(qApp->applicationName()),
qApp, SLOT(quit()));
trayIcon->setContextMenu(trayMenu);
trayIcon->show();
}
void
MainWindow::loadSettings()
{
sshServerAddrEdit->setText(settings.value("ssh_server/addr").toString());
sshServerPortEdit->setText(settings.value("ssh_server/port",
"22").toString());
usernameEdit->setText(settings.value("username").toString());
passwordEdit->setText(settings.value("password/value").toString());
remberPasswordCheckBox->setChecked(settings.value("password/rember",
false).toBool());
socksServerAddrEdit->setText(settings.value("socks_server/addr",
"127.0.0.1").toString());
socksServerPortEdit->setText(settings.value("socks_server/port",
"7070").toString());
}
bool
MainWindow::validateForm()
{
if (sshServerAddrEdit->text().length() == 0) {
QMessageBox::warning(this, tr("Warning"),
tr("Invalid SSH server address"));
return false;
}
if (sshServerPortEdit->text().length() == 0) {
QMessageBox::warning(this, tr("Warning"),
tr("Invalid SSH server address"));
return false;
}
if (usernameEdit->text().length() == 0) {
QMessageBox::warning(this, tr("Warning"),
tr("Invalid SSH username"));
return false;
}
if (passwordEdit->text().length() == 0) {
QMessageBox::warning(this, tr("Warning"),
tr("Invalid SSH password"));
return false;
}
if (socksServerAddrEdit->text().length() == 0) {
QMessageBox::warning(this, tr("Warning"),
tr("Invalid SOCKS server address"));
return false;
}
if (socksServerPortEdit->text().length() == 0) {
QMessageBox::warning(this, tr("Warning"),
tr("Invalid SOCKS server address"));
return false;
}
return true;
}
void
MainWindow::connectSSH()
{
setCurrentState(Connecting);
/* Create SSH process object */
sshProcess = new QProcess(this);
connect(sshProcess, SIGNAL(readyReadStandardOutput()),
this, SLOT(sshReadyReadStdout()));
connect(sshProcess, SIGNAL(readyReadStandardError()),
this, SLOT(sshReadyReadStderr()));
/* Generate SSH_ASKPASS file with right permission and content */
sshAskPassFile = new QTemporaryFile();
if (!sshAskPassFile->open()) {
setCurrentState(NotConnected);
statusLabel->setText(tr("Connect failed (SSH_ASKPASS error)"));
return;
}
QFile::Permissions perm = sshAskPassFile->permissions();
qDebug() << sshAskPassFile->fileName();
perm |= QFile::ExeOwner | QFile::ExeUser;
sshAskPassFile->setPermissions(perm);
QTextStream out(sshAskPassFile);
out << "#!/usr/bin/env bash\n";
out << "echo '" << passwordEdit->text() << "'\n";
sshAskPassFile->close();
/* Set SSH_ASKPASS enviroment variable */
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
env.insert("SSH_ASKPASS", sshAskPassFile->fileName());
sshProcess->setProcessEnvironment(env);
/* Assemble arguments and start SSH process */
QStringList arguments;
arguments << "-qTnN";
arguments << "-v";
arguments << "-D" << QString("%1:%2").arg(socksServerAddrEdit->text(),
socksServerPortEdit->text());
arguments << "-p" << sshServerPortEdit->text();
arguments << "-o" << "ConnectTimeout=10";
arguments << QString("%1@%2").arg(usernameEdit->text(),
sshServerAddrEdit->text());
sshProcess->start("ssh", arguments);
if (!sshProcess->waitForStarted(1000)) {
setCurrentState(NotConnected);
statusLabel->setText(tr("SSH start failed"));
return;
}
}
void
MainWindow::disconnectSSH()
{
setCurrentState(Disconnecting);
sshProcess->kill();
delete sshProcess;
sshProcess = NULL;
setCurrentState(NotConnected);
}
void
MainWindow::setCurrentState(CurrentState state)
{
currentState = state;
if (currentState != Connected && timer != NULL) {
delete timer;
timer = NULL;
}
if (currentState == NotConnected) {
/* Enable user input area */
sshServerAddrEdit->setEnabled(true);
sshServerPortEdit->setEnabled(true);
usernameEdit->setEnabled(true);
passwordEdit->setEnabled(true);
remberPasswordCheckBox->setEnabled(true);
socksServerAddrEdit->setEnabled(true);
socksServerPortEdit->setEnabled(true);
statusLabel->setText(tr("Not connected"));
connectBtn->setText(tr("Connect"));
connectBtn->setEnabled(true);
statusAction->setText(tr("Not connected"));
operationAction->setText(tr("Connect"));
operationAction->setVisible(true);
} else if (currentState == Connecting) {
/* Disable user input area */
sshServerAddrEdit->setDisabled(true);
sshServerPortEdit->setDisabled(true);
usernameEdit->setDisabled(true);
passwordEdit->setDisabled(true);
remberPasswordCheckBox->setDisabled(true);
socksServerAddrEdit->setDisabled(true);
socksServerPortEdit->setDisabled(true);
statusLabel->setText(tr("Connecting..."));
connectBtn->setEnabled(false);
statusAction->setText(tr("Connecting..."));
operationAction->setVisible(false);
} else if (currentState == Connected) {
/* Start timer to update elapsed time in status label */
elapsedTimer.restart();
updateTime();
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateTime()));
timer->start(1000);
connectBtn->setText(tr("Disconnect"));
connectBtn->setEnabled(true);
operationAction->setText(tr("Disconnect"));
operationAction->setVisible(true);
} else if (currentState == Disconnecting) {
statusLabel->setText(tr("Disconnecting..."));
connectBtn->setEnabled(false);
statusAction->setText(tr("Disconnecting..."));
operationAction->setVisible(false);
}
}
<|endoftext|> |
<commit_before>/////////////////////////////////////////////////////////////////
/*
* Template of a read routine
*/
/////////////////////////////////////////////////////////////////
#include <NrrdIO/NrrdIOAPI.h>
#include <hxfield/HxUniformScalarField3.h>
#include <Amira/HxMessage.h>
#include <teem/nrrd.h>
NRRDIO_API
int NrrdReader(const char* filename)
{
Nrrd *nrrd = nrrdNew();
if ( nrrdLoad( nrrd, filename, NULL ) )
throw biffGetDone(NRRD);
if ( nrrd->dim > 3 )
{
theMsg->printf("ERROR: for now, nrrd input can only handle data with dimension 3 or less.");
return 0;
}
const int dims[3] =
{
(nrrd->dim > 0) ? nrrd->axis[0].size : 1,
(nrrd->dim > 1) ? nrrd->axis[1].size : 1,
(nrrd->dim > 2) ? nrrd->axis[2].size : 1
};
if(nrrd->type != nrrdTypeUChar)
{
theMsg->printf("ERROR: for now, nrrd input can only uchar data.");
return 0;
}
// Create a new scalar field (assume byte for now)
HxUniformScalarField3* field =
new HxUniformScalarField3(dims,McPrimType::mc_uint8,nrrd->data);
// Shouldn't need to check for data loading
HxData::registerData(field, filename);
return 1;
}
<commit_msg>Whitespace<commit_after>/////////////////////////////////////////////////////////////////
/*
* Template of a read routine
*/
/////////////////////////////////////////////////////////////////
#include <NrrdIO/NrrdIOAPI.h>
#include <hxfield/HxUniformScalarField3.h>
#include <Amira/HxMessage.h>
#include <teem/nrrd.h>
NRRDIO_API
int NrrdReader(const char* filename)
{
Nrrd *nrrd = nrrdNew();
if ( nrrdLoad( nrrd, filename, NULL ) )
throw biffGetDone(NRRD);
if ( nrrd->dim > 3 )
{
theMsg->printf("ERROR: for now, nrrd input can only handle data with dimension 3 or less.");
return 0;
}
const int dims[3] =
{
(nrrd->dim > 0) ? nrrd->axis[0].size : 1,
(nrrd->dim > 1) ? nrrd->axis[1].size : 1,
(nrrd->dim > 2) ? nrrd->axis[2].size : 1
};
if(nrrd->type != nrrdTypeUChar)
{
theMsg->printf("ERROR: for now, nrrd input can only uchar data.");
return 0;
}
// Create a new scalar field (assume byte for now)
HxUniformScalarField3* field =
new HxUniformScalarField3(dims,McPrimType::mc_uint8,nrrd->data);
// Shouldn't need to check for data loading
HxData::registerData(field, filename);
return 1;
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
///////////////////////////////////////////////////////////////////////////////
//
// //
// Photon Multiplicity Detector //
// This class contains the basic functions for the Photon Multiplicity //
// Detector. Functions specific to one particular geometry are //
// contained in the derived classes //
// //
//Begin_Html
/*
<img src="picts/AliPMDClass.gif">
</pre>
<br clear=left>
<font size=+2 color=red>
<p>The responsible person for this module is
<a href="mailto:[email protected]">Subhasis Chattopadhyay</a>.
</font>
<pre>
*/
//End_Html
// //
///////////////////////////////////////////////////////////////////////////////
#include <TBRIK.h>
#include <TClonesArray.h>
#include <TGeometry.h>
#include <TNode.h>
#include <TTree.h>
#include <TVirtualMC.h>
#include "AliLog.h"
#include "AliLoader.h"
#include "AliPMDLoader.h"
#include "AliPMD.h"
#include "AliRun.h"
#include "AliMC.h"
#include "AliPMDDigitizer.h"
#include "AliPMDhit.h"
#include "AliPMDDDLRawData.h"
ClassImp(AliPMD)
//_____________________________________________________________________________
AliPMD::AliPMD()
{
//
// Default constructor
//
fIshunt = 0;
}
//_____________________________________________________________________________
AliPMD::AliPMD(const char *name, const char *title)
: AliDetector(name,title)
{
//
// Default constructor
//
//
// Allocate the array of hits
fHits = new TClonesArray("AliPMDhit", 405);
gAlice->GetMCApp()->AddHitList(fHits);
fIshunt = 0;
fPar[0] = 1;
fPar[1] = 1;
fPar[2] = 0.8;
fPar[3] = 0.02;
fIn[0] = 6;
fIn[1] = 20;
fIn[2] = 600;
fIn[3] = 27;
fIn[4] = 27;
fGeo[0] = 0;
fGeo[1] = 0.2;
fGeo[2] = 4;
fPadSize[0] = 0.8;
fPadSize[1] = 1.0;
fPadSize[2] = 1.2;
fPadSize[3] = 1.5;
}
AliLoader* AliPMD::MakeLoader(const char* topfoldername)
{
// Makes PMD Loader
fLoader = new AliPMDLoader(GetName(),topfoldername);
if (fLoader)
{
AliDebug(100,"Success");
}
else
{
AliError("Failure");
}
return fLoader;
}
AliPMD::~AliPMD()
{
//
// Destructor
//
}
//_____________________________________________________________________________
void AliPMD::AddHit(Int_t track, Int_t *vol, Float_t *hits)
{
//
// Add a PMD hit
//
TClonesArray &lhits = *fHits;
AliPMDhit *newcell, *curcell;
// printf("PMD++ Adding energy %f, prim %d, vol %d %d %d %d %d %d %d %d\n",
// hits[3],gAlice->GetPrimary(track-1),vol[0],vol[1],vol[2],vol[3],
// vol[4],vol[5],vol[6],vol[7]);
newcell = new AliPMDhit(fIshunt, track, vol, hits);
Int_t i;
for (i=0; i<fNhits; i++) {
//
// See if this cell has already been hit
curcell=(AliPMDhit*) lhits[i];
if (*curcell==*newcell) {
// printf("Cell with same numbers found\n") ; curcell->Print();
*curcell = *curcell+*newcell;
// printf("Cell after addition\n") ; curcell->Print();
delete newcell;
return;
}
}
new(lhits[fNhits++]) AliPMDhit(newcell);
delete newcell;
}
//_____________________________________________________________________________
void AliPMD::BuildGeometry()
{
//
// Build simple ROOT TNode geometry for event display
//
TNode *node, *top;
const int kColorPMD = kRed;
//
top=gAlice->GetGeometry()->GetNode("alice");
// PMD
new TBRIK("S_PMD","PMD box","void",300,300,5);
top->cd();
node = new TNode("PMD","PMD","S_PMD",0,0,-600,"");
node->SetLineColor(kColorPMD);
fNodes->Add(node);
}
//_____________________________________________________________________________
void AliPMD::SetPAR(Float_t p1, Float_t p2, Float_t p3,Float_t p4)
{
//
// Set PMD parameters
//
fPar[0] = p1;
fPar[1] = p2;
fPar[2] = p3;
fPar[3] = p4;
}
//_____________________________________________________________________________
void AliPMD::SetIN(Float_t p1, Float_t p2, Float_t p3,Float_t p4,Float_t p5)
{
//
// Set PMD parameters
//
fIn[0] = p1;
fIn[1] = p2;
fIn[2] = p3;
fIn[3] = p4;
fIn[4] = p5;
}
//_____________________________________________________________________________
void AliPMD::SetGEO(Float_t p1, Float_t p2, Float_t p3)
{
//
// Set geometry parameters
//
fGeo[0] = p1;
fGeo[1] = p2;
fGeo[2] = p3;
}
//_____________________________________________________________________________
void AliPMD::SetPadSize(Float_t p1, Float_t p2, Float_t p3,Float_t p4)
{
//
// Set pad size
//
fPadSize[0] = p1;
fPadSize[1] = p2;
fPadSize[2] = p3;
fPadSize[3] = p4;
}
//_____________________________________________________________________________
void AliPMD::StepManager()
{
//
// Called at every step in PMD
//
}
void AliPMD::MakeBranch(Option_t* option)
{
// Create Tree branches for the PMD
const char *cH = strstr(option,"H");
if (cH && fLoader->TreeH() && (fHits == 0x0))
fHits = new TClonesArray("AliPMDhit", 405);
AliDetector::MakeBranch(option);
}
void AliPMD::SetTreeAddress()
{
// Set branch address
if (fLoader->TreeH() && fHits==0x0)
fHits = new TClonesArray("AliPMDhit", 405);
AliDetector::SetTreeAddress();
}
//____________________________________________________________________________
void AliPMD::Hits2SDigits()
{
// create summable digits
AliRunLoader* runLoader = fLoader->GetRunLoader();
AliPMDDigitizer* pmdDigitizer = new AliPMDDigitizer;
pmdDigitizer->OpengAliceFile(fLoader->GetRunLoader()->GetFileName().Data(),
"HS");
pmdDigitizer->SetZPosition(361.5);
for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
pmdDigitizer->Hits2SDigits(iEvent);
}
fLoader->UnloadHits();
fLoader->UnloadSDigits();
delete pmdDigitizer;
}
//____________________________________________________________________________
void AliPMD::SDigits2Digits()
{
// creates sdigits to digits
}
//____________________________________________________________________________
void AliPMD::Hits2Digits()
{
// create digits
AliRunLoader* runLoader = fLoader->GetRunLoader();
AliPMDDigitizer* pmdDigitizer = new AliPMDDigitizer;
pmdDigitizer->OpengAliceFile(fLoader->GetRunLoader()->GetFileName().Data(),
"HD");
pmdDigitizer->SetZPosition(361.5);
for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
pmdDigitizer->Hits2Digits(iEvent);
}
fLoader->UnloadHits();
fLoader->UnloadDigits();
delete pmdDigitizer;
}
// ---------------------------------------------------------------------------
AliDigitizer* AliPMD::CreateDigitizer(AliRunDigitizer* manager) const
{
return new AliPMDDigitizer(manager);
}
// ---------------------------------------------------------------------------
void AliPMD::Digits2Raw()
{
// convert digits of the current event to raw data
fLoader->LoadDigits();
TTree* digits = fLoader->TreeD();
if (!digits) {
AliError("No digits tree");
return;
}
AliPMDDDLRawData rawWriter;
rawWriter.WritePMDRawData(digits);
fLoader->UnloadDigits();
}
Bool_t AliPMD::Raw2SDigits()
{
}
<commit_msg>Dummy return<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
///////////////////////////////////////////////////////////////////////////////
//
// //
// Photon Multiplicity Detector //
// This class contains the basic functions for the Photon Multiplicity //
// Detector. Functions specific to one particular geometry are //
// contained in the derived classes //
// //
//Begin_Html
/*
<img src="picts/AliPMDClass.gif">
</pre>
<br clear=left>
<font size=+2 color=red>
<p>The responsible person for this module is
<a href="mailto:[email protected]">Subhasis Chattopadhyay</a>.
</font>
<pre>
*/
//End_Html
// //
///////////////////////////////////////////////////////////////////////////////
#include <TBRIK.h>
#include <TClonesArray.h>
#include <TGeometry.h>
#include <TNode.h>
#include <TTree.h>
#include <TVirtualMC.h>
#include "AliLog.h"
#include "AliLoader.h"
#include "AliPMDLoader.h"
#include "AliPMD.h"
#include "AliRun.h"
#include "AliMC.h"
#include "AliPMDDigitizer.h"
#include "AliPMDhit.h"
#include "AliPMDDDLRawData.h"
ClassImp(AliPMD)
//_____________________________________________________________________________
AliPMD::AliPMD()
{
//
// Default constructor
//
fIshunt = 0;
}
//_____________________________________________________________________________
AliPMD::AliPMD(const char *name, const char *title)
: AliDetector(name,title)
{
//
// Default constructor
//
//
// Allocate the array of hits
fHits = new TClonesArray("AliPMDhit", 405);
gAlice->GetMCApp()->AddHitList(fHits);
fIshunt = 0;
fPar[0] = 1;
fPar[1] = 1;
fPar[2] = 0.8;
fPar[3] = 0.02;
fIn[0] = 6;
fIn[1] = 20;
fIn[2] = 600;
fIn[3] = 27;
fIn[4] = 27;
fGeo[0] = 0;
fGeo[1] = 0.2;
fGeo[2] = 4;
fPadSize[0] = 0.8;
fPadSize[1] = 1.0;
fPadSize[2] = 1.2;
fPadSize[3] = 1.5;
}
AliLoader* AliPMD::MakeLoader(const char* topfoldername)
{
// Makes PMD Loader
fLoader = new AliPMDLoader(GetName(),topfoldername);
if (fLoader)
{
AliDebug(100,"Success");
}
else
{
AliError("Failure");
}
return fLoader;
}
AliPMD::~AliPMD()
{
//
// Destructor
//
}
//_____________________________________________________________________________
void AliPMD::AddHit(Int_t track, Int_t *vol, Float_t *hits)
{
//
// Add a PMD hit
//
TClonesArray &lhits = *fHits;
AliPMDhit *newcell, *curcell;
// printf("PMD++ Adding energy %f, prim %d, vol %d %d %d %d %d %d %d %d\n",
// hits[3],gAlice->GetPrimary(track-1),vol[0],vol[1],vol[2],vol[3],
// vol[4],vol[5],vol[6],vol[7]);
newcell = new AliPMDhit(fIshunt, track, vol, hits);
Int_t i;
for (i=0; i<fNhits; i++) {
//
// See if this cell has already been hit
curcell=(AliPMDhit*) lhits[i];
if (*curcell==*newcell) {
// printf("Cell with same numbers found\n") ; curcell->Print();
*curcell = *curcell+*newcell;
// printf("Cell after addition\n") ; curcell->Print();
delete newcell;
return;
}
}
new(lhits[fNhits++]) AliPMDhit(newcell);
delete newcell;
}
//_____________________________________________________________________________
void AliPMD::BuildGeometry()
{
//
// Build simple ROOT TNode geometry for event display
//
TNode *node, *top;
const int kColorPMD = kRed;
//
top=gAlice->GetGeometry()->GetNode("alice");
// PMD
new TBRIK("S_PMD","PMD box","void",300,300,5);
top->cd();
node = new TNode("PMD","PMD","S_PMD",0,0,-600,"");
node->SetLineColor(kColorPMD);
fNodes->Add(node);
}
//_____________________________________________________________________________
void AliPMD::SetPAR(Float_t p1, Float_t p2, Float_t p3,Float_t p4)
{
//
// Set PMD parameters
//
fPar[0] = p1;
fPar[1] = p2;
fPar[2] = p3;
fPar[3] = p4;
}
//_____________________________________________________________________________
void AliPMD::SetIN(Float_t p1, Float_t p2, Float_t p3,Float_t p4,Float_t p5)
{
//
// Set PMD parameters
//
fIn[0] = p1;
fIn[1] = p2;
fIn[2] = p3;
fIn[3] = p4;
fIn[4] = p5;
}
//_____________________________________________________________________________
void AliPMD::SetGEO(Float_t p1, Float_t p2, Float_t p3)
{
//
// Set geometry parameters
//
fGeo[0] = p1;
fGeo[1] = p2;
fGeo[2] = p3;
}
//_____________________________________________________________________________
void AliPMD::SetPadSize(Float_t p1, Float_t p2, Float_t p3,Float_t p4)
{
//
// Set pad size
//
fPadSize[0] = p1;
fPadSize[1] = p2;
fPadSize[2] = p3;
fPadSize[3] = p4;
}
//_____________________________________________________________________________
void AliPMD::StepManager()
{
//
// Called at every step in PMD
//
}
void AliPMD::MakeBranch(Option_t* option)
{
// Create Tree branches for the PMD
const char *cH = strstr(option,"H");
if (cH && fLoader->TreeH() && (fHits == 0x0))
fHits = new TClonesArray("AliPMDhit", 405);
AliDetector::MakeBranch(option);
}
void AliPMD::SetTreeAddress()
{
// Set branch address
if (fLoader->TreeH() && fHits==0x0)
fHits = new TClonesArray("AliPMDhit", 405);
AliDetector::SetTreeAddress();
}
//____________________________________________________________________________
void AliPMD::Hits2SDigits()
{
// create summable digits
AliRunLoader* runLoader = fLoader->GetRunLoader();
AliPMDDigitizer* pmdDigitizer = new AliPMDDigitizer;
pmdDigitizer->OpengAliceFile(fLoader->GetRunLoader()->GetFileName().Data(),
"HS");
pmdDigitizer->SetZPosition(361.5);
for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
pmdDigitizer->Hits2SDigits(iEvent);
}
fLoader->UnloadHits();
fLoader->UnloadSDigits();
delete pmdDigitizer;
}
//____________________________________________________________________________
void AliPMD::SDigits2Digits()
{
// creates sdigits to digits
}
//____________________________________________________________________________
void AliPMD::Hits2Digits()
{
// create digits
AliRunLoader* runLoader = fLoader->GetRunLoader();
AliPMDDigitizer* pmdDigitizer = new AliPMDDigitizer;
pmdDigitizer->OpengAliceFile(fLoader->GetRunLoader()->GetFileName().Data(),
"HD");
pmdDigitizer->SetZPosition(361.5);
for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
pmdDigitizer->Hits2Digits(iEvent);
}
fLoader->UnloadHits();
fLoader->UnloadDigits();
delete pmdDigitizer;
}
// ---------------------------------------------------------------------------
AliDigitizer* AliPMD::CreateDigitizer(AliRunDigitizer* manager) const
{
return new AliPMDDigitizer(manager);
}
// ---------------------------------------------------------------------------
void AliPMD::Digits2Raw()
{
// convert digits of the current event to raw data
fLoader->LoadDigits();
TTree* digits = fLoader->TreeD();
if (!digits) {
AliError("No digits tree");
return;
}
AliPMDDDLRawData rawWriter;
rawWriter.WritePMDRawData(digits);
fLoader->UnloadDigits();
}
Bool_t AliPMD::Raw2SDigits()
{
return kTRUE;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.