text
stringlengths
54
60.6k
<commit_before>/* libscratch - Multipurpose objective C++ library. Copyright (c) 2013 - 2016 Angelo Geels <spansjh@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "Common.h" SCRATCH_NAMESPACE_BEGIN; namespace Internal { template<typename Result, typename ...Args> struct abstract_function { virtual Result operator()(Args... args) = 0; virtual abstract_function *clone() const = 0; virtual ~abstract_function() {} }; template<typename Func, typename Result, typename ...Args> class concrete_function : public abstract_function<Result, Args...> { private: Func m_func; public: concrete_function(const Func &x) : m_func(x) { } virtual Result operator()(Args... args) { return m_func(args...); } virtual concrete_function* clone() const { return new concrete_function(m_func); } }; template<typename Func> struct func_filter { typedef Func type; }; template<typename Result, typename ...Args> struct func_filter<Result(Args...)> { typedef Result(*type)(Args...); }; } template<typename signature> class Function; template<typename Result, typename ...Args> class Function<Result(Args...)> { private: Internal::abstract_function<Result, Args...>* m_func; public: Function() { m_func = nullptr; } template<typename Func> Function(const Func &x) { m_func = new Internal::concrete_function<typename Internal::func_filter<Func>::type, Result, Args...>(x); } Function(const Function &rhs) { m_func = nullptr; if (rhs.m_func != nullptr) { m_func = rhs.m_func->clone(); } } Function(decltype(nullptr)) { m_func = nullptr; } ~Function() { if (m_func != nullptr) { delete m_func; } } Function &operator=(const Function &rhs) { if (&rhs != this && rhs.m_func != nullptr) { auto temp = rhs.m_func->clone(); if (m_func != nullptr) { delete m_func; } m_func = temp; } return *this; } Function &operator=(decltype(nullptr)) { m_func = nullptr; return *this; } template<typename Func> Function &operator=(const Func &x) { auto temp = new Internal::concrete_function<typename Internal::func_filter<Func>::type, Result, Args...>(x); if (m_func != nullptr) { delete m_func; } m_func = temp; return *this; } bool operator==(decltype(nullptr)) { return m_func == nullptr; } bool operator!=(decltype(nullptr)) { return m_func != nullptr; } Result operator()(Args... args) const { if (m_func == nullptr) { return Result(); } return (*m_func)(args...); } }; SCRATCH_NAMESPACE_END; <commit_msg>Fuction nullptr check can be on const object<commit_after>/* libscratch - Multipurpose objective C++ library. Copyright (c) 2013 - 2016 Angelo Geels <spansjh@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "Common.h" SCRATCH_NAMESPACE_BEGIN; namespace Internal { template<typename Result, typename ...Args> struct abstract_function { virtual Result operator()(Args... args) = 0; virtual abstract_function *clone() const = 0; virtual ~abstract_function() {} }; template<typename Func, typename Result, typename ...Args> class concrete_function : public abstract_function<Result, Args...> { private: Func m_func; public: concrete_function(const Func &x) : m_func(x) { } virtual Result operator()(Args... args) { return m_func(args...); } virtual concrete_function* clone() const { return new concrete_function(m_func); } }; template<typename Func> struct func_filter { typedef Func type; }; template<typename Result, typename ...Args> struct func_filter<Result(Args...)> { typedef Result(*type)(Args...); }; } template<typename signature> class Function; template<typename Result, typename ...Args> class Function<Result(Args...)> { private: Internal::abstract_function<Result, Args...>* m_func; public: Function() { m_func = nullptr; } template<typename Func> Function(const Func &x) { m_func = new Internal::concrete_function<typename Internal::func_filter<Func>::type, Result, Args...>(x); } Function(const Function &rhs) { m_func = nullptr; if (rhs.m_func != nullptr) { m_func = rhs.m_func->clone(); } } Function(decltype(nullptr)) { m_func = nullptr; } ~Function() { if (m_func != nullptr) { delete m_func; } } Function &operator=(const Function &rhs) { if (&rhs != this && rhs.m_func != nullptr) { auto temp = rhs.m_func->clone(); if (m_func != nullptr) { delete m_func; } m_func = temp; } return *this; } Function &operator=(decltype(nullptr)) { m_func = nullptr; return *this; } template<typename Func> Function &operator=(const Func &x) { auto temp = new Internal::concrete_function<typename Internal::func_filter<Func>::type, Result, Args...>(x); if (m_func != nullptr) { delete m_func; } m_func = temp; return *this; } bool operator==(decltype(nullptr)) const { return m_func == nullptr; } bool operator!=(decltype(nullptr)) const { return m_func != nullptr; } Result operator()(Args... args) const { if (m_func == nullptr) { return Result(); } return (*m_func)(args...); } }; SCRATCH_NAMESPACE_END; <|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) 2005 OPeNDAP, Inc. // Author: James Gallagher <jgallagher@opendap.org> // // 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 // // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112. #include <cppunit/TextTestRunner.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/extensions/HelperMacros.h> #include <cstring> #include <string> #include "GNURegex.h" #include "Array.h" #include "Int16.h" #include "Str.h" #include "Structure.h" #include "debug.h" #include "GetOpt.h" using namespace CppUnit; using namespace std; static bool debug = false; namespace libdap { class ArrayTest: public TestFixture { private: Array *d_cardinal, *d_string, *d_structure; Int16 *d_int16; Str *d_str; Structure *d_struct; string svalues[4]; public: ArrayTest() { svalues[0] = "0 String"; svalues[1] = "1 String"; svalues[2] = "2 String"; svalues[3] = "3 String"; } ~ArrayTest() { } void setUp() { d_int16 = new Int16("Int16"); DBG(cerr << "d_int16: " << d_int16 << endl); d_cardinal = new Array("Array_of_Int16", d_int16); d_cardinal->append_dim(4, "dimension"); dods_int16 buffer[4] = { 0, 1, 2, 3 }; d_cardinal->val2buf(buffer); #ifdef DODS_DEBUG for (int i = 0; i < 4; ++i) cerr << "buffer[" << i << "]: " << buffer[i] << endl; #endif d_str = new Str("Str"); d_string = new Array("Array_of_String", d_str); d_string->append_dim(4, "dimension"); string sbuffer[4] = { "0 String", "1 String", "2 String", "3 String" }; d_string->val2buf(sbuffer); #ifdef DODS_DEBUG for (int i = 0; i < 4; ++i) cerr << "sbuffer[" << i << "]: " << sbuffer[i] << endl; #endif d_struct = new Structure("Structure"); d_struct->add_var(d_int16); d_structure = new Array("Array_of_Strctures", d_struct); d_structure->append_dim(4, "dimension"); ostringstream oss; for (int i = 0; i < 4; ++i) { oss.str(""); oss << "field" << i; Int16 *n = new Int16(oss.str()); DBG(cerr << "n " << i << ": " << n << endl); oss.str(""); oss << "element" << i; Structure *s = new Structure(oss.str()); s->add_var(n); d_structure->set_vec(i, s); delete n; n = 0; delete s; s = 0; } delete d_int16; d_int16 = 0; delete d_str; d_str = 0; delete d_struct; d_struct = 0; } void tearDown() { delete d_cardinal; delete d_string; delete d_structure; } bool re_match(Regex &r, const char *s) { int match_position = r.match(s, strlen(s)); DBG(cerr << "match position: " << match_position << " string length: " << (int)strlen(s) << endl); return match_position == (int) strlen(s); } CPPUNIT_TEST_SUITE (ArrayTest); CPPUNIT_TEST (duplicate_cardinal_test); CPPUNIT_TEST (duplicate_string_test); CPPUNIT_TEST (duplicate_structure_test); CPPUNIT_TEST_SUITE_END(); void duplicate_structure_test() { Array::Dim_iter i = d_structure->dim_begin(); CPPUNIT_ASSERT(d_structure->dimension_size(i) == 4); #ifdef DODS_DEBUG for (int i = 0; i < 4; ++i) { Structure *s = dynamic_cast<Structure*>(d_structure->var(i)); DBG(cerr << "s: " << s << endl); if (s) s->print_decl(cerr); } #endif Array *a = new Array(*d_structure); // a = *d_structure; I test operator= in duplicate_cardinal_test(). i = a->dim_begin(); CPPUNIT_ASSERT(a->dimension_size(i) == 4); for (int i = 0; i < 4; ++i) { // The point of this test is to ensure that the const ctor // performs a deep copy; first test to make sure the pointers // to BaseType instnaces are different in the two objects. Structure *src = dynamic_cast<Structure*>(d_structure->var(i)); Structure *dest = dynamic_cast<Structure*>(a->var(i)); CPPUNIT_ASSERT(src != dest); // However, for the deep copy to be correct, the two arrays must // have equivalent elements. We know there's only one field... CPPUNIT_ASSERT(src->type() == dods_structure_c && dest->type() == dods_structure_c); Constructor::Vars_iter s = src->var_begin(); Constructor::Vars_iter d = dest->var_begin(); CPPUNIT_ASSERT((*s)->type() == dods_int16_c && (*d)->type() == dods_int16_c); CPPUNIT_ASSERT((*s)->name() == (*d)->name()); } delete a; a = 0; } void duplicate_string_test() { Array::Dim_iter i = d_string->dim_begin(); CPPUNIT_ASSERT(d_string->dimension_size(i) == 4); string *s = new string[4]; d_string->buf2val((void**) &s); for (int i = 0; i < 4; ++i) { CPPUNIT_ASSERT(s[i] == svalues[i]); DBG(cerr << "s[" << i << "]: " << s[i] << endl); } Array a = *d_string; i = a.dim_begin(); CPPUNIT_ASSERT(a.dimension_size(i) == 4); string *s2 = new string[4]; d_string->buf2val((void**) &s2); for (int i = 0; i < 4; ++i) { CPPUNIT_ASSERT(s2[i] == svalues[i]); DBG(cerr << "s2[" << i << "]: " << s2[i] << endl); } delete[] s; s = 0; delete[] s2; s2 = 0; } void duplicate_cardinal_test() { Array::Dim_iter i = d_cardinal->dim_begin(); CPPUNIT_ASSERT(d_cardinal->dimension_size(i) == 4); dods_int16 *b = new dods_int16[4]; d_cardinal->buf2val((void**) &b); for (int i = 0; i < 4; ++i) { CPPUNIT_ASSERT(b[i] == i); DBG(cerr << "b[" << i << "]: " << b[i] << endl); } delete[] b; b = 0; Array a = *d_cardinal; i = a.dim_begin(); CPPUNIT_ASSERT(a.dimension_size(i) == 4); dods_int16 *b2 = new dods_int16[4]; d_cardinal->buf2val((void**) &b2); for (int i = 0; i < 4; ++i) { CPPUNIT_ASSERT(b2[i] == i); DBG(cerr << "b2[" << i << "]: " << b2[i] << endl); } delete[] b2; b2 = 0; } }; CPPUNIT_TEST_SUITE_REGISTRATION (ArrayTest); } // namespace libdap int main(int argc, char *argv[]) { GetOpt getopt(argc, argv, "dh"); int option_char; while ((option_char = getopt()) != -1) switch (option_char) { case 'd': debug = 1; // debug is a static global break; case 'h': { // help - show test names cerr << "Usage: ArrayTest has the following tests:" << endl; const std::vector<Test*> &tests = libdap::ArrayTest::suite()->getTests(); unsigned int prefix_len = libdap::ArrayTest::suite()->getName().append("::").length(); for (std::vector<Test*>::const_iterator i = tests.begin(), e = tests.end(); i != e; ++i) { cerr << (*i)->getName().replace(0, prefix_len, "") << endl; } break; } default: break; } CppUnit::TextTestRunner runner; runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest()); bool wasSuccessful = true; string test = ""; int i = getopt.optind; if (i == argc) { // run them all wasSuccessful = runner.run(""); } else { for (; i < argc; ++i) { if (debug) cerr << "Running " << argv[i] << endl; test = libdap::ArrayTest::suite()->getName().append("::").append(argv[i]); wasSuccessful = wasSuccessful && runner.run(test); } } return wasSuccessful ? 0 : 1; } <commit_msg>more testing<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) 2005,2018 OPeNDAP, Inc. // Author: James Gallagher <jgallagher@opendap.org> // // 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 // // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112. #include <cppunit/TextTestRunner.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/extensions/HelperMacros.h> #include <cstring> #include <string> #include "GNURegex.h" #include "Array.h" #include "Int16.h" #include "Str.h" #include "Structure.h" #include "D4Dimensions.h" #include "debug.h" #include "GetOpt.h" using namespace CppUnit; using namespace std; static bool debug = false; namespace libdap { class ArrayTest: public TestFixture { private: Array *d_cardinal, *d_string, *d_structure; Int16 *d_int16; Str *d_str; Structure *d_struct; string svalues[4]; char a[1024]; public: ArrayTest() { svalues[0] = "0 String"; svalues[1] = "1 String"; svalues[2] = "2 String"; svalues[3] = "3 String"; } ~ArrayTest() { } void setUp() { d_int16 = new Int16("Int16"); DBG(cerr << "d_int16: " << d_int16 << endl); d_cardinal = new Array("Array_of_Int16", d_int16); d_cardinal->append_dim(4, "dimension"); dods_int16 buffer[4] = { 0, 1, 2, 3 }; d_cardinal->val2buf(buffer); #ifdef DODS_DEBUG for (int i = 0; i < 4; ++i) cerr << "buffer[" << i << "]: " << buffer[i] << endl; #endif d_str = new Str("Str"); d_string = new Array("Array_of_String", d_str); d_string->append_dim(4, "dimension"); string sbuffer[4] = { "0 String", "1 String", "2 String", "3 String" }; d_string->val2buf(sbuffer); #ifdef DODS_DEBUG for (int i = 0; i < 4; ++i) cerr << "sbuffer[" << i << "]: " << sbuffer[i] << endl; #endif d_struct = new Structure("Structure"); d_struct->add_var(d_int16); d_structure = new Array("Array_of_Strctures", d_struct); d_structure->append_dim(4, "dimension"); ostringstream oss; for (int i = 0; i < 4; ++i) { oss.str(""); oss << "field" << i; Int16 *n = new Int16(oss.str()); DBG(cerr << "n " << i << ": " << n << endl); oss.str(""); oss << "element" << i; Structure *s = new Structure(oss.str()); s->add_var(n); d_structure->set_vec(i, s); delete n; n = 0; delete s; s = 0; } delete d_int16; d_int16 = 0; delete d_str; d_str = 0; delete d_struct; d_struct = 0; } void tearDown() { delete d_cardinal; delete d_string; delete d_structure; } bool re_match(Regex &r, const char *s) { int match_position = r.match(s, strlen(s)); DBG(cerr << "match position: " << match_position << " string length: " << (int)strlen(s) << endl); return match_position == (int) strlen(s); } CPPUNIT_TEST_SUITE (ArrayTest); CPPUNIT_TEST (cons_test); CPPUNIT_TEST (equals_test); CPPUNIT_TEST (prepend_dim_test); CPPUNIT_TEST (prepend_dim_2_test); CPPUNIT_TEST (clear_dims_test); CPPUNIT_TEST (error_handling_test); CPPUNIT_TEST (error_handling_2_test); CPPUNIT_TEST (print_test); CPPUNIT_TEST (duplicate_cardinal_test); CPPUNIT_TEST (duplicate_string_test); CPPUNIT_TEST (duplicate_structure_test); CPPUNIT_TEST_SUITE_END(); void cons_test() { Array a1 = Array("a", "b", d_int16, true); CPPUNIT_ASSERT(a1.name() == "a"); } void equals_test() { Array a1 = Array("a", d_int16); a1 = *d_cardinal; Array::Dim_iter i = a1.dim_begin(); CPPUNIT_ASSERT(a1.dimension_size(i) == 4); a1 = a1; i = a1.dim_begin(); CPPUNIT_ASSERT(a1.dimension_size(i) == 4); } void prepend_dim_test() { Array a1 = Array("a", d_int16); Array::Dim_iter i = a1.dim_begin(); CPPUNIT_ASSERT(a1.dimension_size(i) == 0); a1.prepend_dim(2, "dim_a"); i = a1.dim_begin(); CPPUNIT_ASSERT(a1.dimension_size(i) == 2); a1.prepend_dim(3, "dim_b"); } void prepend_dim_2_test() { Array a1 = Array("a", d_int16); string expected_name[2] = {"dim_b", "dim_a"}; int j = 0; D4Dimensions *dims = new D4Dimensions(); D4Dimension *d = new D4Dimension("dim_b", 2, dims); a1.prepend_dim(2, "dim_a"); a1.prepend_dim(d); for (Array::Dim_iter i = a1.dim_begin(); i != a1.dim_end(); i++, j++) { CPPUNIT_ASSERT(a1.dimension_name(i) == expected_name[j]); } } void clear_dims_test() { Array a1 = Array("a", d_int16); a1.prepend_dim(2, "dim_a"); a1.prepend_dim(3, "dim_b"); a1.clear_all_dims(); Array::Dim_iter i = a1.dim_begin(); CPPUNIT_ASSERT(a1.dimension_size(i) == 0); } void error_handling_test() { Array a1 = Array("a", d_int16); Array::Dim_iter i = a1.dim_begin(); string msg; CPPUNIT_ASSERT_THROW(a1.dimension_name(i), InternalErr); CPPUNIT_ASSERT(!a1.check_semantics(msg)); } void error_handling_2_test() { Array a1 = Array("a", d_int16); a1.append_dim(2, "dim_a"); Array::Dim_iter i = a1.dim_begin(); CPPUNIT_ASSERT(a1.dimension_size(i) == 2); CPPUNIT_ASSERT_THROW(a1.add_constraint(i, 2, 1, 1), Error); CPPUNIT_ASSERT_THROW(a1.add_constraint(i, 0, 1, 2), Error); CPPUNIT_ASSERT_THROW(a1.add_constraint(i, 0, 3, 1), Error); } void print_test() { Array a1 = Array("a", d_int16); FILE *fp; a1.append_dim(2, "dim_a"); CPPUNIT_ASSERT(fp = fopen("ArrayTest.output", "w")); a1.print_xml(fp, " ", true); fclose(fp); ifstream ifs("ArrayTest.output"); while(!ifs.eof()) ifs >> a; ifs.close(); cout<<a; CPPUNIT_ASSERT(!strcmp(a, "22;")); } void duplicate_structure_test() { Array::Dim_iter i = d_structure->dim_begin(); CPPUNIT_ASSERT(d_structure->dimension_size(i) == 4); #ifdef DODS_DEBUG for (int i = 0; i < 4; ++i) { Structure *s = dynamic_cast<Structure*>(d_structure->var(i)); DBG(cerr << "s: " << s << endl); if (s) s->print_decl(cerr); } #endif Array *a = new Array(*d_structure); // a = *d_structure; I test operator= in duplicate_cardinal_test(). i = a->dim_begin(); CPPUNIT_ASSERT(a->dimension_size(i) == 4); for (int i = 0; i < 4; ++i) { // The point of this test is to ensure that the const ctor // performs a deep copy; first test to make sure the pointers // to BaseType instnaces are different in the two objects. Structure *src = dynamic_cast<Structure*>(d_structure->var(i)); Structure *dest = dynamic_cast<Structure*>(a->var(i)); CPPUNIT_ASSERT(src != dest); // However, for the deep copy to be correct, the two arrays must // have equivalent elements. We know there's only one field... CPPUNIT_ASSERT(src->type() == dods_structure_c && dest->type() == dods_structure_c); Constructor::Vars_iter s = src->var_begin(); Constructor::Vars_iter d = dest->var_begin(); CPPUNIT_ASSERT((*s)->type() == dods_int16_c && (*d)->type() == dods_int16_c); CPPUNIT_ASSERT((*s)->name() == (*d)->name()); } delete a; a = 0; } void duplicate_string_test() { Array::Dim_iter i = d_string->dim_begin(); CPPUNIT_ASSERT(d_string->dimension_size(i) == 4); string *s = new string[4]; d_string->buf2val((void**) &s); for (int i = 0; i < 4; ++i) { CPPUNIT_ASSERT(s[i] == svalues[i]); DBG(cerr << "s[" << i << "]: " << s[i] << endl); } Array a = *d_string; i = a.dim_begin(); CPPUNIT_ASSERT(a.dimension_size(i) == 4); string *s2 = new string[4]; d_string->buf2val((void**) &s2); for (int i = 0; i < 4; ++i) { CPPUNIT_ASSERT(s2[i] == svalues[i]); DBG(cerr << "s2[" << i << "]: " << s2[i] << endl); } delete[] s; s = 0; delete[] s2; s2 = 0; } void duplicate_cardinal_test() { Array::Dim_iter i = d_cardinal->dim_begin(); CPPUNIT_ASSERT(d_cardinal->dimension_size(i) == 4); dods_int16 *b = new dods_int16[4]; d_cardinal->buf2val((void**) &b); for (int i = 0; i < 4; ++i) { CPPUNIT_ASSERT(b[i] == i); DBG(cerr << "b[" << i << "]: " << b[i] << endl); } delete[] b; b = 0; Array a = *d_cardinal; i = a.dim_begin(); CPPUNIT_ASSERT(a.dimension_size(i) == 4); dods_int16 *b2 = new dods_int16[4]; d_cardinal->buf2val((void**) &b2); for (int i = 0; i < 4; ++i) { CPPUNIT_ASSERT(b2[i] == i); DBG(cerr << "b2[" << i << "]: " << b2[i] << endl); } delete[] b2; b2 = 0; } }; CPPUNIT_TEST_SUITE_REGISTRATION (ArrayTest); } // namespace libdap int main(int argc, char *argv[]) { GetOpt getopt(argc, argv, "dh"); int option_char; while ((option_char = getopt()) != -1) switch (option_char) { case 'd': debug = 1; // debug is a static global break; case 'h': { // help - show test names cerr << "Usage: ArrayTest has the following tests:" << endl; const std::vector<Test*> &tests = libdap::ArrayTest::suite()->getTests(); unsigned int prefix_len = libdap::ArrayTest::suite()->getName().append("::").length(); for (std::vector<Test*>::const_iterator i = tests.begin(), e = tests.end(); i != e; ++i) { cerr << (*i)->getName().replace(0, prefix_len, "") << endl; } break; } default: break; } CppUnit::TextTestRunner runner; runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest()); bool wasSuccessful = true; string test = ""; int i = getopt.optind; if (i == argc) { // run them all wasSuccessful = runner.run(""); } else { for (; i < argc; ++i) { if (debug) cerr << "Running " << argv[i] << endl; test = libdap::ArrayTest::suite()->getName().append("::").append(argv[i]); wasSuccessful = wasSuccessful && runner.run(test); } } return wasSuccessful ? 0 : 1; } <|endoftext|>
<commit_before><commit_msg>Initialize NSS with databases.<commit_after><|endoftext|>
<commit_before>// $Id: sample.cpp 793 2008-08-17 14:33:30Z glandrum $ // // Copyright (C) 2009 Greg Landrum // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include <GraphMol/RDKitBase.h> #include <GraphMol/SmilesParse/SmilesParse.h> #include <GraphMol/Depictor/RDDepictor.h> #include <Demos/RDKit/Draw/MolDrawing.h> #include <RDGeneral/RDLog.h> #include <vector> using namespace RDKit; void DrawDemo(){ RWMol *mol=SmilesToMol("Clc1c(C#N)cc(C(=O)NCc2sccc2)cc1"); //RWMol *mol=SmilesToMol("c1ncncn1"); RDKit::MolOps::Kekulize(*mol); // generate the 2D coordinates: RDDepict::compute2DCoords(*mol); std::vector<int> drawing=RDKit::Drawing::DrawMol(*mol); std::cout<<"var codes=["; std::copy(drawing.begin(),drawing.end(),std::ostream_iterator<int>(std::cout,",")); std::cout<<"];"<<std::endl; delete mol; } int main(int argc, char *argv[]) { RDLog::InitLogs(); DrawDemo(); } <commit_msg>initial pass at very crude svg translation<commit_after>// $Id: sample.cpp 793 2008-08-17 14:33:30Z glandrum $ // // Copyright (C) 2009 Greg Landrum // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include <GraphMol/RDKitBase.h> #include <GraphMol/SmilesParse/SmilesParse.h> #include <GraphMol/Depictor/RDDepictor.h> #include <Demos/RDKit/Draw/MolDrawing.h> #include <RDGeneral/RDLog.h> #include <vector> #include <sstream> using namespace RDKit; std::string getColor(int atNum){ static std::map<int,std::string> colors; if(colors.empty()){ colors[7]="#0000FF"; colors[8]="#FF0000"; colors[9]="#33CCCC"; colors[15]="#FF7F00"; colors[16]="#CCCC00"; colors[16]="#00CC00"; colors[35]="#7F4C19"; colors[0]="#7F7F7F"; } std::string res="#000000"; if(colors.find(atNum)!=colors.end()) res= colors[atNum]; return res; } void drawLine(std::vector<int>::const_iterator &pos,std::ostringstream &sstr){ pos+=4; sstr<<"<svg:path "; sstr<<"d='M "<<*pos<<","<<*(pos+1)<<" "<<*(pos+2)<<","<<*(pos+3)<<"' "; pos+=4; sstr<<"style='fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:3px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1'"; sstr<<" />\n"; } void drawAtom(std::vector<int>::const_iterator &pos,std::ostringstream &sstr){ int atNum=*pos++; int xp=*pos++; int yp=*pos++; int slen=*pos++; std::string label=""; for(unsigned int i=0;i<slen;++i){ label+=(char)*pos++; } sstr<<"<svg:text x='"<<xp<<"' y='"<<yp<<"'"; sstr<<" style='font-size:40px;font-style:normal;font-weight:normal;line-height:125%;letter-spacing:0px;word-spacing:0px;fill-opacity:1;stroke:none;font-family:Sans;text-anchor:middle;baseline-shift:sub"<<";fill:"<<getColor(atNum)<<"'"; sstr<<">"; sstr<<"<svg:tspan x='"<<xp<<"' y='"<<yp<<"'>"; sstr<<label<<"</svg:tspan>"; sstr<<"</svg:text>\n"; } std::string ToSVG(const std::vector<int> &drawing){ std::ostringstream sstr; sstr<<"<?xml version='1.0' encoding='iso-8859-1'?>\n"; int width=300,height=300; std::vector<int>::const_iterator pos=drawing.begin()+2; TEST_ASSERT(*pos==Drawing::BOUNDS); pos+=3; width = *pos++; height = *pos++; sstr << "<svg:svg version='1.1' baseProfile='full'\n \ xmlns:svg='http://www.w3.org/2000/svg'\n \ xmlns:xlink='http://www.w3.org/1999/xlink'\n \ xml:space='preserve'\n"; sstr<<"width='"<<width<<"px' height='"<<height<<"px' >\n"; sstr<<"<svg:g transform='translate("<<width*.05<<","<<height*.05<<") scale(.9,.9)'>"; while(pos!=drawing.end()){ int token=*pos++; switch(token){ case Drawing::LINE: drawLine(pos,sstr); break; case Drawing::ATOM: drawAtom(pos,sstr); break; default: std::cerr<<"unrecognized token: "<<token<<std::endl; } } sstr<<"</svg:g></svg:svg>"; return sstr.str(); } void DrawDemo(){ RWMol *mol=SmilesToMol("Clc1c(C#N)cc(C(=O)NCc2sccc2)cc1"); //RWMol *mol=SmilesToMol("c1ncncn1"); RDKit::MolOps::Kekulize(*mol); // generate the 2D coordinates: RDDepict::compute2DCoords(*mol); std::vector<int> drawing=RDKit::Drawing::DrawMol(*mol); std::cerr<<"var codes=["; std::copy(drawing.begin(),drawing.end(),std::ostream_iterator<int>(std::cerr,",")); std::cerr<<"];"<<std::endl; std::string svg=ToSVG(drawing); std::cout<<svg<<std::endl; delete mol; } int main(int argc, char *argv[]) { RDLog::InitLogs(); DrawDemo(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sb.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2007-06-27 14:10:46 $ * * 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 _SB_HXX #define _SB_HXX #ifndef _SBERRORS_HXX #include <basic/sberrors.hxx> #endif #include <basic/sbdef.hxx> #include <basic/sbmeth.hxx> #include <basic/sbmod.hxx> #include <basic/sbprop.hxx> #include <basic/sbstar.hxx> #endif <commit_msg>INTEGRATION: CWS changefileheader (1.3.88); FILE MERGED 2008/03/28 16:06:55 rt 1.3.88.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: sb.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SB_HXX #define _SB_HXX #ifndef _SBERRORS_HXX #include <basic/sberrors.hxx> #endif #include <basic/sbdef.hxx> #include <basic/sbmeth.hxx> #include <basic/sbmod.hxx> #include <basic/sbprop.hxx> #include <basic/sbstar.hxx> #endif <|endoftext|>
<commit_before>// // Copyright (C) 2013-2018 University of Amsterdam // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public // License along with this program. If not, see // <http://www.gnu.org/licenses/>. // #include "rowcontrols.h" #include "analysis/analysisform.h" #include "analysis/jaspcontrol.h" #include "jasplistcontrol.h" #include "log.h" #include <QQmlContext> RowControls::RowControls(ListModel* parent , QQmlComponent* component , const QMap<QString, Json::Value>& rowValues) : QObject(parent), _parentModel(parent), _rowComponent(component), _rowValues(rowValues) { } // Cannot do this code in the constructor: the Component create function (comp->create(context)) will call the addJASPControl method in JASPControl (or ListView), // So this RowControls instance needs to exist already. void RowControls::init(int row, const Term& key, bool isNew) { JASPListControl* listView = _parentModel->listView(); QQmlContext* context = new QQmlContext(qmlContext(listView), listView); context->setContextProperty("isDynamic", true); context->setContextProperty("form", listView->form()); context->setContextProperty("listView", listView); context->setContextProperty("isNew", isNew); context->setContextProperty("rowIndex", row); context->setContextProperty("rowValue", key.asQString()); _rowObject = qobject_cast<QQuickItem*>(_rowComponent->create(context)); _context = context; if (_rowObject) _setupControls(); else Log::log() << "Could not create control in ListView " << listView->name() << std::endl; } void RowControls::_setupControls(bool reuseBoundValue) { // The controls (when created or reused) may need to be bound with some values: // either with the initial values (in _rowValues), new values (by calling createJson) // And if a control depends on a source, its values must be refreshed by this source. QList<JASPControl*> controls = _rowJASPControlMap.values(); AnalysisForm* form = _parentModel->listView()->form(); if (form) { form->sortControls(controls); form->blockValueChangeSignal(true); } for (JASPControl* control : controls) { bool hasInitialValues = _rowValues.contains(control->name()); BoundControl* boundItem = control->boundControl(); if (boundItem) { if (!reuseBoundValue || boundItem->boundValue().isNull()) boundItem->bindTo(hasInitialValues ? (_rowValues[control->name()]) : boundItem->createJson()); } if (!boundItem || !hasInitialValues || reuseBoundValue) { JASPListControl* listView = dynamic_cast<JASPListControl*>(control); // If a ListView depends on a source, it has to be initialized by this source // For this just call the sourceTermsChanged handler. if (listView && listView->hasSource()) listView->model()->sourceTermsReset(); } } if (form) form->blockValueChangeSignal(false, false); } void RowControls::setContext(int row, const QString &key) { // Cannot use qmlContext(item) : setContextProperty would generate: 'Cannot set property on internal context.' error _context->setContextProperty("rowIndex", row); _context->setContextProperty("rowValue", key); _context->setContextProperty("isNew", false); _rowObject->setParentItem(nullptr); _setupControls(true); } bool RowControls::addJASPControl(JASPControl *control) { bool success = false; JASPListControl* listView = _parentModel->listView(); if (control->isBound() && control->name().isEmpty()) listView->addControlError(tr("A row component in %1 does not have a name").arg(listView->name())); else if (_rowJASPControlMap.contains(control->name())) listView->addControlError(tr("2 row components in %1 have the same name").arg(listView->name()).arg(control->name())); else success = true; if (!control->name().isEmpty() && success) _rowJASPControlMap[control->name()] = control; return success; } <commit_msg>Adding a row in a ComponentList does not signal a analysis change<commit_after>// // Copyright (C) 2013-2018 University of Amsterdam // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public // License along with this program. If not, see // <http://www.gnu.org/licenses/>. // #include "rowcontrols.h" #include "analysis/analysisform.h" #include "analysis/jaspcontrol.h" #include "jasplistcontrol.h" #include "log.h" #include <QQmlContext> RowControls::RowControls(ListModel* parent , QQmlComponent* component , const QMap<QString, Json::Value>& rowValues) : QObject(parent), _parentModel(parent), _rowComponent(component), _rowValues(rowValues) { } // Cannot do this code in the constructor: the Component create function (comp->create(context)) will call the addJASPControl method in JASPControl (or ListView), // So this RowControls instance needs to exist already. void RowControls::init(int row, const Term& key, bool isNew) { JASPListControl* listView = _parentModel->listView(); QQmlContext* context = new QQmlContext(qmlContext(listView), listView); context->setContextProperty("isDynamic", true); context->setContextProperty("form", listView->form()); context->setContextProperty("listView", listView); context->setContextProperty("isNew", isNew); context->setContextProperty("rowIndex", row); context->setContextProperty("rowValue", key.asQString()); _rowObject = qobject_cast<QQuickItem*>(_rowComponent->create(context)); _context = context; if (_rowObject) _setupControls(); else Log::log() << "Could not create control in ListView " << listView->name() << std::endl; } void RowControls::_setupControls(bool reuseBoundValue) { // The controls (when created or reused) may need to be bound with some values: // either with the initial values (in _rowValues), new values (by calling createJson) // And if a control depends on a source, its values must be refreshed by this source. QList<JASPControl*> controls = _rowJASPControlMap.values(); AnalysisForm* form = _parentModel->listView()->form(); if (form) { form->sortControls(controls); form->blockValueChangeSignal(true); } for (JASPControl* control : controls) { bool hasInitialValues = _rowValues.contains(control->name()); BoundControl* boundItem = control->boundControl(); if (boundItem) { if (!reuseBoundValue || boundItem->boundValue().isNull()) boundItem->bindTo(hasInitialValues ? (_rowValues[control->name()]) : boundItem->createJson()); } if (!boundItem || !hasInitialValues || reuseBoundValue) { JASPListControl* listView = dynamic_cast<JASPListControl*>(control); // If a ListView depends on a source, it has to be initialized by this source // For this just call the sourceTermsChanged handler. if (listView && listView->hasSource()) listView->model()->sourceTermsReset(); } } if (form) form->blockValueChangeSignal(false); } void RowControls::setContext(int row, const QString &key) { // Cannot use qmlContext(item) : setContextProperty would generate: 'Cannot set property on internal context.' error _context->setContextProperty("rowIndex", row); _context->setContextProperty("rowValue", key); _context->setContextProperty("isNew", false); _rowObject->setParentItem(nullptr); _setupControls(true); } bool RowControls::addJASPControl(JASPControl *control) { bool success = false; JASPListControl* listView = _parentModel->listView(); if (control->isBound() && control->name().isEmpty()) listView->addControlError(tr("A row component in %1 does not have a name").arg(listView->name())); else if (_rowJASPControlMap.contains(control->name())) listView->addControlError(tr("2 row components in %1 have the same name").arg(listView->name()).arg(control->name())); else success = true; if (!control->name().isEmpty() && success) _rowJASPControlMap[control->name()] = control; return success; } <|endoftext|>
<commit_before>/* * FileSystem.cc * Apto * * Created by David on 12/7/05. * Copyright 2005-2011 David Michael Bryson. All rights reserved. * http://programerror.com/software/apto * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * 3. Neither the name of David Michael Bryson, nor the names of contributors may be used to endorse or promote * products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY DAVID MICHAEL BRYSON 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 DAVID MICHAEL BRYSON 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. * * Authors: David M. Bryson <david@programerror.com> * */ #include "apto/core/FileSystem.h" #include "apto/platform/Platform.h" #include "apto/platform/FileSystem.h" #include <cerrno> #include <sys/stat.h> #include <cstdio> #include <fstream> // mkdir undefined in ms windows #if APTO_PLATFORM(WINDOWS) # include <direct.h> # ifndef ACCESSPERMS # define ACCESSPERMS 0 # endif # ifndef mkdir # define mkdir(path, ignored_mode) _mkdir(path) # endif # ifndef mode_t # define mode_t unsigned int # endif #endif #if APTO_PLATFORM(WINDOWS) # include <direct.h> #else # include <unistd.h> #endif namespace Apto { namespace FileSystem { String GetCWD() { String cwd_str; char* dirbuf = new char[MAXIMUM_DIRECTORY_LENGTH]; #if APTO_PLATFORM(WINDOWS) char* cwd = _getcwd(dirbuf, MAXIMUM_DIRECTORY_LENGTH); #else char* cwd = getcwd(dirbuf, MAXIMUM_DIRECTORY_LENGTH); #endif if (cwd != NULL) cwd_str = cwd; delete [] dirbuf; return cwd_str; } String GetAbsolutePath(const String& path, const String& working_dir) { if (path.GetSize() == 0) return working_dir; #if APTO_PLATFORM(WINDOWS) if (!(path.IsLetter(0) && path[1] == ':' && path[2] =='\\')) return PathAppend(working_dir, path); #else if (path[0] != '/' && path[0] != '\\') return PathAppend(working_dir, path); #endif return path; } bool IsDir(const String& path) { struct stat st; if (stat(path, &st) == 0 && st.st_mode & S_IFDIR) return true; return false; } bool IsFile(const String& path) { struct stat st; if (stat(path, &st) == 0 && st.st_mode & S_IFREG) return true; return false; } bool CpDir(const String& src, const String& dest) { if (!IsDir(src)) return false; MkDir(dest); // Collect entries in directory Array<String, Smart> direntries; ReadDir(src, direntries); // Process all entries, removing them as appropriate for (int i = 0; i < direntries.GetSize(); i++) { // Do not copy current or parent directory entries if (direntries[i] == "." || direntries[i] == "..") continue; Apto::String src_path = PathAppend(src, direntries[i]); Apto::String dest_path = PathAppend(dest, direntries[i]); struct stat st; if (stat(src_path, &st) != 0) continue; if (st.st_mode & S_IFDIR) { // Recursively copy subdirectory if (!CpDir(src_path, dest_path)) return false; } else if (st.st_mode & S_IFREG) { // Cop regular file if (!CpFile(src_path, dest_path)) return false; } } return true; } bool MkDir(const String& dirname) { FILE* fp = 0; #if APTO_PLATFORM(WINDOWS) if (fopen_s(&fp, dirname, "r") == 0) { #else fp = fopen(dirname, "r"); if (fp == 0) { #endif if (errno == ENOENT) { // not found, creating... if (mkdir(dirname, (S_IRWXU | S_IRWXG | S_IRWXO))) return false; return true; } return false; } fclose(fp); // found return true; } bool RmDir(const String& dirname, bool recursive) { if (!IsDir(dirname)) return false; if (recursive) { // Collect entries in directory Array<String, Smart> direntries; ReadDir(dirname, direntries); // Process all entries, removing them as appropriate for (int i = 0; i < direntries.GetSize(); i++) { // Do not remove current or parent directory entries if (direntries[i] == "." || direntries[i] == "..") continue; Apto::String path = PathAppend(dirname, direntries[i]); struct stat st; if (stat(path, &st) != 0) continue; if (st.st_mode & S_IFDIR) { // Recursively remove subdirectory if (!RmDir(path)) return false; } else { // Remove regular (or other) file if (remove(path) != 0) return false; } } } // Attempt to remove the directory itself #if APTO_PLATFORM(WINDOWS) return (_rmdir(dirname) == 0); #else return (rmdir(dirname) == 0); #endif } bool ReadDir(const String& path, Array<String, Smart>& entries) { DIR* dp; struct dirent* dirp; if ((dp = opendir(path)) == NULL) return false; while ((dirp = readdir(dp)) != NULL) entries.Push(dirp->d_name); closedir(dp); return true; } bool CpFile(const String& src, const String& dest) { std::ifstream ifs(src, std::ios::binary); std::ofstream ofs(dest, std::ios::binary); if (!ifs.is_open() || !ofs.is_open()) return false; ofs << ifs.rdbuf(); ifs.close(); ofs.close(); return true; } bool RmFile(const String& path) { return (remove(path) == 0); } }; }; <commit_msg>Fix create folder support on windows.<commit_after>/* * FileSystem.cc * Apto * * Created by David on 12/7/05. * Copyright 2005-2011 David Michael Bryson. All rights reserved. * http://programerror.com/software/apto * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * 3. Neither the name of David Michael Bryson, nor the names of contributors may be used to endorse or promote * products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY DAVID MICHAEL BRYSON 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 DAVID MICHAEL BRYSON 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. * * Authors: David M. Bryson <david@programerror.com> * */ #include "apto/core/FileSystem.h" #include "apto/platform/Platform.h" #include "apto/platform/FileSystem.h" #include <cerrno> #include <sys/stat.h> #include <cstdio> #include <fstream> // mkdir undefined in ms windows #if APTO_PLATFORM(WINDOWS) # include <direct.h> # ifndef ACCESSPERMS # define ACCESSPERMS 0 # endif # ifndef mkdir # define mkdir(path, ignored_mode) _mkdir(path) # endif # ifndef mode_t # define mode_t unsigned int # endif #endif #if APTO_PLATFORM(WINDOWS) # include <direct.h> #else # include <unistd.h> #endif namespace Apto { namespace FileSystem { String GetCWD() { String cwd_str; char* dirbuf = new char[MAXIMUM_DIRECTORY_LENGTH]; #if APTO_PLATFORM(WINDOWS) char* cwd = _getcwd(dirbuf, MAXIMUM_DIRECTORY_LENGTH); #else char* cwd = getcwd(dirbuf, MAXIMUM_DIRECTORY_LENGTH); #endif if (cwd != NULL) cwd_str = cwd; delete [] dirbuf; return cwd_str; } String GetAbsolutePath(const String& path, const String& working_dir) { if (path.GetSize() == 0) return working_dir; #if APTO_PLATFORM(WINDOWS) if (!(path.IsLetter(0) && path[1] == ':' && path[2] =='\\')) return PathAppend(working_dir, path); #else if (path[0] != '/' && path[0] != '\\') return PathAppend(working_dir, path); #endif return path; } bool IsDir(const String& path) { struct stat st; if (stat(path, &st) == 0 && st.st_mode & S_IFDIR) return true; return false; } bool IsFile(const String& path) { struct stat st; if (stat(path, &st) == 0 && st.st_mode & S_IFREG) return true; return false; } bool CpDir(const String& src, const String& dest) { if (!IsDir(src)) return false; MkDir(dest); // Collect entries in directory Array<String, Smart> direntries; ReadDir(src, direntries); // Process all entries, removing them as appropriate for (int i = 0; i < direntries.GetSize(); i++) { // Do not copy current or parent directory entries if (direntries[i] == "." || direntries[i] == "..") continue; Apto::String src_path = PathAppend(src, direntries[i]); Apto::String dest_path = PathAppend(dest, direntries[i]); struct stat st; if (stat(src_path, &st) != 0) continue; if (st.st_mode & S_IFDIR) { // Recursively copy subdirectory if (!CpDir(src_path, dest_path)) return false; } else if (st.st_mode & S_IFREG) { // Cop regular file if (!CpFile(src_path, dest_path)) return false; } } return true; } bool MkDir(const String& dirname) { FILE* fp = 0; #if APTO_PLATFORM(WINDOWS) fopen_s(&fp, dirname, "r"); if (fp == 0) { #else fp = fopen(dirname, "r"); if (fp == 0) { #endif if (errno == ENOENT) { // not found, creating... if (mkdir(dirname, (S_IRWXU | S_IRWXG | S_IRWXO))) return false; return true; } return false; } fclose(fp); // found return true; } bool RmDir(const String& dirname, bool recursive) { if (!IsDir(dirname)) return false; if (recursive) { // Collect entries in directory Array<String, Smart> direntries; ReadDir(dirname, direntries); // Process all entries, removing them as appropriate for (int i = 0; i < direntries.GetSize(); i++) { // Do not remove current or parent directory entries if (direntries[i] == "." || direntries[i] == "..") continue; Apto::String path = PathAppend(dirname, direntries[i]); struct stat st; if (stat(path, &st) != 0) continue; if (st.st_mode & S_IFDIR) { // Recursively remove subdirectory if (!RmDir(path)) return false; } else { // Remove regular (or other) file if (remove(path) != 0) return false; } } } // Attempt to remove the directory itself #if APTO_PLATFORM(WINDOWS) return (_rmdir(dirname) == 0); #else return (rmdir(dirname) == 0); #endif } bool ReadDir(const String& path, Array<String, Smart>& entries) { DIR* dp; struct dirent* dirp; if ((dp = opendir(path)) == NULL) return false; while ((dirp = readdir(dp)) != NULL) entries.Push(dirp->d_name); closedir(dp); return true; } bool CpFile(const String& src, const String& dest) { std::ifstream ifs(src, std::ios::binary); std::ofstream ofs(dest, std::ios::binary); if (!ifs.is_open() || !ofs.is_open()) return false; ofs << ifs.rdbuf(); ifs.close(); ofs.close(); return true; } bool RmFile(const String& path) { return (remove(path) == 0); } }; }; <|endoftext|>
<commit_before>//================================================================== // ָOfferԹپͱ⡷ // ߣκ //================================================================== // 14 // ĿһΪnӣӼmΣmnn>1m1 // ÿεӵijȼΪk[0]k[1]k[m]k[0]*k[1]**k[m]ܵ // Ƕ٣統ӵij8ʱǰɳȷֱΪ233Σ // ʱõij˻18 #include <iostream> #include <cmath> int maxProductAfterCutting_solution1(int length) { if(length < 2) return 0; if(length == 2) return 1; if(length == 3) return 2; int* products = new int[length + 1]; products[0] = 0; products[1] = 1; products[2] = 2; products[3] = 3; int max = 0; for(int i = 4; i <= length; ++i) { max = 0; for(int j = 1; j <= i / 2; ++j) { int product = products[j] * products[i - j]; if(max < product) max = product; products[i] = max; } } max = products[length]; delete[] products; return max; } int maxProductAfterCutting_solution2(int length) { if(length < 2) return 0; if(length == 2) return 1; if(length == 3) return 2; int timesOf3 = length / 3; if((length - timesOf3 * 3) % 2 == 1) timesOf3 -= 1; int timesOf2 = (length - timesOf3 * 3) / 2; return (int) (pow(3, timesOf3)) * (int) (pow(2, timesOf2)); } // ====================Դ==================== void test(const char* testName, int length, int expected) { int result1 = maxProductAfterCutting_solution1(length); if(result1 == expected) std::cout << "Solution1 for " << testName << " passed." << std::endl; else std::cout << "Solution1 for " << testName << " FAILED." << std::endl; int result2 = maxProductAfterCutting_solution2(length); if(result2 == expected) std::cout << "Solution2 for " << testName << " passed." << std::endl; else std::cout << "Solution2 for " << testName << " FAILED." << std::endl; } void test1() { int length = 1; int expected = 0; test("test1", length, expected); } void test2() { int length = 2; int expected = 1; test("test2", length, expected); } void test3() { int length = 3; int expected = 2; test("test3", length, expected); } void test4() { int length = 4; int expected = 4; test("test4", length, expected); } void test5() { int length = 5; int expected = 6; test("test5", length, expected); } void test6() { int length = 6; int expected = 9; test("test6", length, expected); } void test7() { int length = 7; int expected = 12; test("test7", length, expected); } void test8() { int length = 8; int expected = 18; test("test8", length, expected); } void test9() { int length = 9; int expected = 27; test("test9", length, expected); } void test10() { int length = 10; int expected = 36; test("test10", length, expected); } void test11() { int length = 50; int expected = 86093442; test("test11", length, expected); } int main(int agrc, char* argv[]) { test1(); test2(); test3(); test4(); test5(); test6(); test7(); test8(); test9(); test10(); test11(); } <commit_msg>Changes for question 14<commit_after>//================================================================== // ָOfferԹپͱ⡷ // ߣκ //================================================================== // 14 // ĿһΪnӣӼmΣmnn>1m1 // ÿεӵijȼΪk[0]k[1]k[m]k[0]*k[1]**k[m]ܵ // Ƕ٣統ӵij8ʱǰɳȷֱΪ233Σ // ʱõij˻18 #include <iostream> #include <cmath> // ====================̬滮==================== int maxProductAfterCutting_solution1(int length) { if(length < 2) return 0; if(length == 2) return 1; if(length == 3) return 2; int* products = new int[length + 1]; products[0] = 0; products[1] = 1; products[2] = 2; products[3] = 3; int max = 0; for(int i = 4; i <= length; ++i) { max = 0; for(int j = 1; j <= i / 2; ++j) { int product = products[j] * products[i - j]; if(max < product) max = product; products[i] = max; } } max = products[length]; delete[] products; return max; } // ====================̰㷨==================== int maxProductAfterCutting_solution2(int length) { if(length < 2) return 0; if(length == 2) return 1; if(length == 3) return 2; // ܶؼȥΪ3Ӷ int timesOf3 = length / 3; // ʣµijΪ4ʱ򣬲ټȥΪ3ӶΡ // ʱõķǰӼɳΪ2ΣΪ2*2 > 3*1 if(length - timesOf3 * 3 == 1) timesOf3 -= 1; int timesOf2 = (length - timesOf3 * 3) / 2; return (int) (pow(3, timesOf3)) * (int) (pow(2, timesOf2)); } // ====================Դ==================== void test(const char* testName, int length, int expected) { int result1 = maxProductAfterCutting_solution1(length); if(result1 == expected) std::cout << "Solution1 for " << testName << " passed." << std::endl; else std::cout << "Solution1 for " << testName << " FAILED." << std::endl; int result2 = maxProductAfterCutting_solution2(length); if(result2 == expected) std::cout << "Solution2 for " << testName << " passed." << std::endl; else std::cout << "Solution2 for " << testName << " FAILED." << std::endl; } void test1() { int length = 1; int expected = 0; test("test1", length, expected); } void test2() { int length = 2; int expected = 1; test("test2", length, expected); } void test3() { int length = 3; int expected = 2; test("test3", length, expected); } void test4() { int length = 4; int expected = 4; test("test4", length, expected); } void test5() { int length = 5; int expected = 6; test("test5", length, expected); } void test6() { int length = 6; int expected = 9; test("test6", length, expected); } void test7() { int length = 7; int expected = 12; test("test7", length, expected); } void test8() { int length = 8; int expected = 18; test("test8", length, expected); } void test9() { int length = 9; int expected = 27; test("test9", length, expected); } void test10() { int length = 10; int expected = 36; test("test10", length, expected); } void test11() { int length = 50; int expected = 86093442; test("test11", length, expected); } int main(int agrc, char* argv[]) { test1(); test2(); test3(); test4(); test5(); test6(); test7(); test8(); test9(); test10(); test11(); return 0; } <|endoftext|>
<commit_before>/** Copyright (C) 2016 Ultimaker - Released under terms of the AGPLv3 License */ #include "SettingRegistry.h" #include <sstream> #include <iostream> // debug IO #include <libgen.h> // dirname #include <string> #include <cstring> // strtok (split string using delimiters) strcpy #include <fstream> // ifstream (to see if file exists) #include "rapidjson/rapidjson.h" #include "rapidjson/document.h" #include "rapidjson/error/en.h" #include "rapidjson/filereadstream.h" #include "../utils/logoutput.h" namespace cura { SettingRegistry SettingRegistry::instance; // define settingRegistry std::string SettingRegistry::toString(rapidjson::Type type) { switch (type) { case rapidjson::Type::kNullType: return "null"; case rapidjson::Type::kFalseType: return "false"; case rapidjson::Type::kTrueType: return "true"; case rapidjson::Type::kObjectType: return "object"; case rapidjson::Type::kArrayType: return "array"; case rapidjson::Type::kStringType: return "string"; case rapidjson::Type::kNumberType: return "number"; default: return "Unknown"; } } SettingConfig::SettingConfig(std::string key, std::string label) : SettingContainer(key, label) { // std::cerr << key << std::endl; // debug output to show all frontend registered settings... } bool SettingRegistry::settingExists(std::string key) const { return setting_key_to_config.find(key) != setting_key_to_config.end(); } SettingConfig* SettingRegistry::getSettingConfig(std::string key) const { auto it = setting_key_to_config.find(key); if (it == setting_key_to_config.end()) return nullptr; return it->second; } SettingRegistry::SettingRegistry() : setting_definitions("settings", "Settings") { // load search paths from environment variable CURA_ENGINE_SEARCH_PATH char* paths = getenv("CURA_ENGINE_SEARCH_PATH"); if (paths) { #if defined(__linux__) || (defined(__APPLE__) && defined(__MACH__)) char delims[] = ":"; // colon #else char delims[] = ";"; // semicolon #endif char* path = strtok(paths, delims); // search for next path delimited by any of the characters in delims while (path != NULL) { search_paths.emplace(path); path = strtok(NULL, ";:,"); // continue searching in last call to strtok } } } int SettingRegistry::loadJSON(std::string filename, rapidjson::Document& json_document) { FILE* f = fopen(filename.c_str(), "rb"); if (!f) { cura::logError("Couldn't open JSON file.\n"); return 1; } char read_buffer[4096]; rapidjson::FileReadStream reader_stream(f, read_buffer, sizeof(read_buffer)); json_document.ParseStream(reader_stream); fclose(f); if (json_document.HasParseError()) { cura::logError("Error parsing JSON(offset %u): %s\n", (unsigned)json_document.GetErrorOffset(), GetParseError_En(json_document.GetParseError())); return 2; } return 0; } /*! * Check whether a file exists. * from https://techoverflow.net/blog/2013/01/11/cpp-check-if-file-exists/ * * \param filename The path to a filename to check if it exists * \return Whether the file exists. */ bool fexists(const char *filename) { std::ifstream ifile(filename); return (bool)ifile; } bool SettingRegistry::getDefinitionFile(const std::string machine_id, std::string& result) { for (const std::string& search_path : search_paths) { result = search_path + std::string("/") + machine_id + std::string(".def.json"); if (fexists(result.c_str())) { return true; } } return false; } int SettingRegistry::loadExtruderJSONsettings(unsigned int extruder_nr, SettingsBase* settings_base) { if (extruder_train_ids.empty()) { logError("Couldn't find any extruder trains!\n"); return -1; } if (extruder_nr >= extruder_train_ids.size()) { logWarning("Couldn't load extruder.def.json file for extruder %i. Index out of bounds.\n Loading first extruder definition instead.\n", extruder_nr); extruder_nr = 0; } std::string definition_file; bool found = getDefinitionFile(extruder_train_ids[extruder_nr], definition_file); if (!found) { logError("Couldn't find extruder.def.json file for extruder %i.\n", extruder_nr); return -1; } bool warn_base_file_duplicates = false; return loadJSONsettings(definition_file, settings_base, warn_base_file_duplicates); } int SettingRegistry::loadJSONsettings(std::string filename, SettingsBase* settings_base, bool warn_base_file_duplicates) { rapidjson::Document json_document; log("Loading %s...\n", filename.c_str()); int err = loadJSON(filename, json_document); if (err) { return err; } { // add parent folder to search paths char filename_cstr[filename.size()]; std::strcpy(filename_cstr, filename.c_str()); // copy the string because dirname(.) changes the input string!!! std::string folder_name = std::string(dirname(filename_cstr)); search_paths.emplace(folder_name); } if (json_document.HasMember("inherits") && json_document["inherits"].IsString()) { std::string child_filename; bool found = getDefinitionFile(json_document["inherits"].GetString(), child_filename); if (!found) { cura::logError("Inherited JSON file \"%s\" not found\n", json_document["inherits"].GetString()); return -1; } err = loadJSONsettings(child_filename, settings_base, warn_base_file_duplicates); // load child first if (err) { return err; } err = loadJSONsettingsFromDoc(json_document, settings_base, false); } else { err = loadJSONsettingsFromDoc(json_document, settings_base, warn_base_file_duplicates); } if (json_document.HasMember("metadata") && json_document["metadata"].IsObject()) { const rapidjson::Value& json_metadata = json_document["metadata"]; if (json_metadata.HasMember("machine_extruder_trains") && json_metadata["machine_extruder_trains"].IsObject()) { const rapidjson::Value& json_machine_extruder_trains = json_metadata["machine_extruder_trains"]; for (rapidjson::Value::ConstMemberIterator extr_train_iterator = json_machine_extruder_trains.MemberBegin(); extr_train_iterator != json_machine_extruder_trains.MemberEnd(); ++extr_train_iterator) { int extruder_train_nr = atoi(extr_train_iterator->name.GetString()); if (extruder_train_nr < 0) { continue; } const rapidjson::Value& json_id = extr_train_iterator->value; if (!json_id.IsString()) { continue; } const char* id = json_id.GetString(); if (extruder_train_nr >= (int) extruder_train_ids.size()) { extruder_train_ids.resize(extruder_train_nr + 1); } extruder_train_ids[extruder_train_nr] = std::string(id); } } } return err; } int SettingRegistry::loadJSONsettingsFromDoc(rapidjson::Document& json_document, SettingsBase* settings_base, bool warn_duplicates) { if (!json_document.IsObject()) { cura::logError("JSON file is not an object.\n"); return 3; } if (json_document.HasMember("settings")) { handleChildren(json_document["settings"], settings_base, warn_duplicates); } if (json_document.HasMember("overrides")) { const rapidjson::Value& json_object_container = json_document["overrides"]; for (rapidjson::Value::ConstMemberIterator override_iterator = json_object_container.MemberBegin(); override_iterator != json_object_container.MemberEnd(); ++override_iterator) { std::string setting = override_iterator->name.GetString(); SettingConfig* conf = getSettingConfig(setting); if (!conf) //Setting could not be found. { logWarning("Trying to override unknown setting %s.\n", setting.c_str()); continue; } _loadSettingValues(conf, override_iterator, settings_base); } } return 0; } void SettingRegistry::handleChildren(const rapidjson::Value& settings_list, SettingsBase* settings_base, bool warn_duplicates) { if (!settings_list.IsObject()) { logError("json settings list is not an object!\n"); return; } for (rapidjson::Value::ConstMemberIterator setting_iterator = settings_list.MemberBegin(); setting_iterator != settings_list.MemberEnd(); ++setting_iterator) { handleSetting(setting_iterator, settings_base, warn_duplicates); if (setting_iterator->value.HasMember("children")) { handleChildren(setting_iterator->value["children"], settings_base, warn_duplicates); } } } bool SettingRegistry::settingIsUsedByEngine(const rapidjson::Value& setting) { if (setting.HasMember("children")) { return false; } else { return true; } } void SettingRegistry::handleSetting(const rapidjson::Value::ConstMemberIterator& json_setting_it, SettingsBase* settings_base, bool warn_duplicates) { const rapidjson::Value& json_setting = json_setting_it->value; if (!json_setting.IsObject()) { logError("json setting is not an object!\n"); return; } std::string name = json_setting_it->name.GetString(); if (json_setting.HasMember("type") && json_setting["type"].IsString() && json_setting["type"].GetString() == std::string("category")) { // skip category objects setting_key_to_config[name] = nullptr; // add the category name to the mapping, but don't instantiate a setting config for it. return; } if (settingIsUsedByEngine(json_setting)) { if (!json_setting.HasMember("label") || !json_setting["label"].IsString()) { logError("json setting \"%s\" has no label!\n", name.c_str()); return; } std::string label = json_setting["label"].GetString(); SettingConfig* setting = getSettingConfig(name); if (warn_duplicates && setting) { cura::logWarning("Duplicate definition of setting: %s a.k.a. \"%s\" was already claimed by \"%s\"\n", name.c_str(), label.c_str(), getSettingConfig(name)->getLabel().c_str()); } if (!setting) { setting = &addSetting(name, label); } _loadSettingValues(setting, json_setting_it, settings_base); } else { setting_key_to_config[name] = nullptr; // add the setting name to the mapping, but don't instantiate a setting config for it. } } SettingConfig& SettingRegistry::addSetting(std::string name, std::string label) { SettingConfig* config = setting_definitions.addChild(name, label); setting_key_to_config[name] = config; return *config; } void SettingRegistry::loadDefault(const rapidjson::GenericValue< rapidjson::UTF8< char > >::ConstMemberIterator& json_object_it, SettingConfig* config) { const rapidjson::Value& setting_content = json_object_it->value; if (setting_content.HasMember("default_value")) { const rapidjson::Value& dflt = setting_content["default_value"]; if (dflt.IsString()) { config->setDefault(dflt.GetString()); } else if (dflt.IsTrue()) { config->setDefault("true"); } else if (dflt.IsFalse()) { config->setDefault("false"); } else if (dflt.IsNumber()) { std::ostringstream ss; ss << dflt.GetDouble(); config->setDefault(ss.str()); } // arrays are ignored because machine_extruder_trains needs to be handled separately else { logWarning("WARNING: Unrecognized data type in JSON: %s has type %s\n", json_object_it->name.GetString(), toString(dflt.GetType()).c_str()); } } } void SettingRegistry::_loadSettingValues(SettingConfig* config, const rapidjson::GenericValue< rapidjson::UTF8< char > >::ConstMemberIterator& json_object_it, SettingsBase* settings_base) { const rapidjson::Value& data = json_object_it->value; /// Fill the setting config object with data we have in the json file. if (data.HasMember("type") && data["type"].IsString()) { config->setType(data["type"].GetString()); } if (config->getType() == std::string("polygon") || config->getType() == std::string("polygons")) { // skip polygon settings : not implemented yet and not used yet (TODO) // logWarning("WARNING: Loading polygon setting %s not implemented...\n", json_object_it->name.GetString()); return; } loadDefault(json_object_it, config); if (data.HasMember("unit") && data["unit"].IsString()) { config->setUnit(data["unit"].GetString()); } settings_base->_setSetting(config->getKey(), config->getDefaultValue()); } }//namespace cura <commit_msg>Remove the duplicate SettingConfig definition.<commit_after>/** Copyright (C) 2016 Ultimaker - Released under terms of the AGPLv3 License */ #include "SettingRegistry.h" #include <sstream> #include <iostream> // debug IO #include <libgen.h> // dirname #include <string> #include <cstring> // strtok (split string using delimiters) strcpy #include <fstream> // ifstream (to see if file exists) #include "rapidjson/rapidjson.h" #include "rapidjson/document.h" #include "rapidjson/error/en.h" #include "rapidjson/filereadstream.h" #include "../utils/logoutput.h" namespace cura { SettingRegistry SettingRegistry::instance; // define settingRegistry std::string SettingRegistry::toString(rapidjson::Type type) { switch (type) { case rapidjson::Type::kNullType: return "null"; case rapidjson::Type::kFalseType: return "false"; case rapidjson::Type::kTrueType: return "true"; case rapidjson::Type::kObjectType: return "object"; case rapidjson::Type::kArrayType: return "array"; case rapidjson::Type::kStringType: return "string"; case rapidjson::Type::kNumberType: return "number"; default: return "Unknown"; } } bool SettingRegistry::settingExists(std::string key) const { return setting_key_to_config.find(key) != setting_key_to_config.end(); } SettingConfig* SettingRegistry::getSettingConfig(std::string key) const { auto it = setting_key_to_config.find(key); if (it == setting_key_to_config.end()) return nullptr; return it->second; } SettingRegistry::SettingRegistry() : setting_definitions("settings", "Settings") { // load search paths from environment variable CURA_ENGINE_SEARCH_PATH char* paths = getenv("CURA_ENGINE_SEARCH_PATH"); if (paths) { #if defined(__linux__) || (defined(__APPLE__) && defined(__MACH__)) char delims[] = ":"; // colon #else char delims[] = ";"; // semicolon #endif char* path = strtok(paths, delims); // search for next path delimited by any of the characters in delims while (path != NULL) { search_paths.emplace(path); path = strtok(NULL, ";:,"); // continue searching in last call to strtok } } } int SettingRegistry::loadJSON(std::string filename, rapidjson::Document& json_document) { FILE* f = fopen(filename.c_str(), "rb"); if (!f) { cura::logError("Couldn't open JSON file.\n"); return 1; } char read_buffer[4096]; rapidjson::FileReadStream reader_stream(f, read_buffer, sizeof(read_buffer)); json_document.ParseStream(reader_stream); fclose(f); if (json_document.HasParseError()) { cura::logError("Error parsing JSON(offset %u): %s\n", (unsigned)json_document.GetErrorOffset(), GetParseError_En(json_document.GetParseError())); return 2; } return 0; } /*! * Check whether a file exists. * from https://techoverflow.net/blog/2013/01/11/cpp-check-if-file-exists/ * * \param filename The path to a filename to check if it exists * \return Whether the file exists. */ bool fexists(const char *filename) { std::ifstream ifile(filename); return (bool)ifile; } bool SettingRegistry::getDefinitionFile(const std::string machine_id, std::string& result) { for (const std::string& search_path : search_paths) { result = search_path + std::string("/") + machine_id + std::string(".def.json"); if (fexists(result.c_str())) { return true; } } return false; } int SettingRegistry::loadExtruderJSONsettings(unsigned int extruder_nr, SettingsBase* settings_base) { if (extruder_train_ids.empty()) { logError("Couldn't find any extruder trains!\n"); return -1; } if (extruder_nr >= extruder_train_ids.size()) { logWarning("Couldn't load extruder.def.json file for extruder %i. Index out of bounds.\n Loading first extruder definition instead.\n", extruder_nr); extruder_nr = 0; } std::string definition_file; bool found = getDefinitionFile(extruder_train_ids[extruder_nr], definition_file); if (!found) { logError("Couldn't find extruder.def.json file for extruder %i.\n", extruder_nr); return -1; } bool warn_base_file_duplicates = false; return loadJSONsettings(definition_file, settings_base, warn_base_file_duplicates); } int SettingRegistry::loadJSONsettings(std::string filename, SettingsBase* settings_base, bool warn_base_file_duplicates) { rapidjson::Document json_document; log("Loading %s...\n", filename.c_str()); int err = loadJSON(filename, json_document); if (err) { return err; } { // add parent folder to search paths char filename_cstr[filename.size()]; std::strcpy(filename_cstr, filename.c_str()); // copy the string because dirname(.) changes the input string!!! std::string folder_name = std::string(dirname(filename_cstr)); search_paths.emplace(folder_name); } if (json_document.HasMember("inherits") && json_document["inherits"].IsString()) { std::string child_filename; bool found = getDefinitionFile(json_document["inherits"].GetString(), child_filename); if (!found) { cura::logError("Inherited JSON file \"%s\" not found\n", json_document["inherits"].GetString()); return -1; } err = loadJSONsettings(child_filename, settings_base, warn_base_file_duplicates); // load child first if (err) { return err; } err = loadJSONsettingsFromDoc(json_document, settings_base, false); } else { err = loadJSONsettingsFromDoc(json_document, settings_base, warn_base_file_duplicates); } if (json_document.HasMember("metadata") && json_document["metadata"].IsObject()) { const rapidjson::Value& json_metadata = json_document["metadata"]; if (json_metadata.HasMember("machine_extruder_trains") && json_metadata["machine_extruder_trains"].IsObject()) { const rapidjson::Value& json_machine_extruder_trains = json_metadata["machine_extruder_trains"]; for (rapidjson::Value::ConstMemberIterator extr_train_iterator = json_machine_extruder_trains.MemberBegin(); extr_train_iterator != json_machine_extruder_trains.MemberEnd(); ++extr_train_iterator) { int extruder_train_nr = atoi(extr_train_iterator->name.GetString()); if (extruder_train_nr < 0) { continue; } const rapidjson::Value& json_id = extr_train_iterator->value; if (!json_id.IsString()) { continue; } const char* id = json_id.GetString(); if (extruder_train_nr >= (int) extruder_train_ids.size()) { extruder_train_ids.resize(extruder_train_nr + 1); } extruder_train_ids[extruder_train_nr] = std::string(id); } } } return err; } int SettingRegistry::loadJSONsettingsFromDoc(rapidjson::Document& json_document, SettingsBase* settings_base, bool warn_duplicates) { if (!json_document.IsObject()) { cura::logError("JSON file is not an object.\n"); return 3; } if (json_document.HasMember("settings")) { handleChildren(json_document["settings"], settings_base, warn_duplicates); } if (json_document.HasMember("overrides")) { const rapidjson::Value& json_object_container = json_document["overrides"]; for (rapidjson::Value::ConstMemberIterator override_iterator = json_object_container.MemberBegin(); override_iterator != json_object_container.MemberEnd(); ++override_iterator) { std::string setting = override_iterator->name.GetString(); SettingConfig* conf = getSettingConfig(setting); if (!conf) //Setting could not be found. { logWarning("Trying to override unknown setting %s.\n", setting.c_str()); continue; } _loadSettingValues(conf, override_iterator, settings_base); } } return 0; } void SettingRegistry::handleChildren(const rapidjson::Value& settings_list, SettingsBase* settings_base, bool warn_duplicates) { if (!settings_list.IsObject()) { logError("json settings list is not an object!\n"); return; } for (rapidjson::Value::ConstMemberIterator setting_iterator = settings_list.MemberBegin(); setting_iterator != settings_list.MemberEnd(); ++setting_iterator) { handleSetting(setting_iterator, settings_base, warn_duplicates); if (setting_iterator->value.HasMember("children")) { handleChildren(setting_iterator->value["children"], settings_base, warn_duplicates); } } } bool SettingRegistry::settingIsUsedByEngine(const rapidjson::Value& setting) { if (setting.HasMember("children")) { return false; } else { return true; } } void SettingRegistry::handleSetting(const rapidjson::Value::ConstMemberIterator& json_setting_it, SettingsBase* settings_base, bool warn_duplicates) { const rapidjson::Value& json_setting = json_setting_it->value; if (!json_setting.IsObject()) { logError("json setting is not an object!\n"); return; } std::string name = json_setting_it->name.GetString(); if (json_setting.HasMember("type") && json_setting["type"].IsString() && json_setting["type"].GetString() == std::string("category")) { // skip category objects setting_key_to_config[name] = nullptr; // add the category name to the mapping, but don't instantiate a setting config for it. return; } if (settingIsUsedByEngine(json_setting)) { if (!json_setting.HasMember("label") || !json_setting["label"].IsString()) { logError("json setting \"%s\" has no label!\n", name.c_str()); return; } std::string label = json_setting["label"].GetString(); SettingConfig* setting = getSettingConfig(name); if (warn_duplicates && setting) { cura::logWarning("Duplicate definition of setting: %s a.k.a. \"%s\" was already claimed by \"%s\"\n", name.c_str(), label.c_str(), getSettingConfig(name)->getLabel().c_str()); } if (!setting) { setting = &addSetting(name, label); } _loadSettingValues(setting, json_setting_it, settings_base); } else { setting_key_to_config[name] = nullptr; // add the setting name to the mapping, but don't instantiate a setting config for it. } } SettingConfig& SettingRegistry::addSetting(std::string name, std::string label) { SettingConfig* config = setting_definitions.addChild(name, label); setting_key_to_config[name] = config; return *config; } void SettingRegistry::loadDefault(const rapidjson::GenericValue< rapidjson::UTF8< char > >::ConstMemberIterator& json_object_it, SettingConfig* config) { const rapidjson::Value& setting_content = json_object_it->value; if (setting_content.HasMember("default_value")) { const rapidjson::Value& dflt = setting_content["default_value"]; if (dflt.IsString()) { config->setDefault(dflt.GetString()); } else if (dflt.IsTrue()) { config->setDefault("true"); } else if (dflt.IsFalse()) { config->setDefault("false"); } else if (dflt.IsNumber()) { std::ostringstream ss; ss << dflt.GetDouble(); config->setDefault(ss.str()); } // arrays are ignored because machine_extruder_trains needs to be handled separately else { logWarning("WARNING: Unrecognized data type in JSON: %s has type %s\n", json_object_it->name.GetString(), toString(dflt.GetType()).c_str()); } } } void SettingRegistry::_loadSettingValues(SettingConfig* config, const rapidjson::GenericValue< rapidjson::UTF8< char > >::ConstMemberIterator& json_object_it, SettingsBase* settings_base) { const rapidjson::Value& data = json_object_it->value; /// Fill the setting config object with data we have in the json file. if (data.HasMember("type") && data["type"].IsString()) { config->setType(data["type"].GetString()); } if (config->getType() == std::string("polygon") || config->getType() == std::string("polygons")) { // skip polygon settings : not implemented yet and not used yet (TODO) // logWarning("WARNING: Loading polygon setting %s not implemented...\n", json_object_it->name.GetString()); return; } loadDefault(json_object_it, config); if (data.HasMember("unit") && data["unit"].IsString()) { config->setUnit(data["unit"].GetString()); } settings_base->_setSetting(config->getKey(), config->getDefaultValue()); } }//namespace cura <|endoftext|>
<commit_before>#include "mitkPointSetWriter.h" #include <iostream> #include <fstream> // // Initialization of the xml tags. // const char* mitk::PointSetWriter::XML_POINT_SET_FILE = "point_set_file" ; const char* mitk::PointSetWriter::XML_FILE_VERSION = "file_version" ; const char* mitk::PointSetWriter::XML_POINT_SET = "point_set" ; const char* mitk::PointSetWriter::XML_POINT = "point" ; const char* mitk::PointSetWriter::XML_ID = "id" ; const char* mitk::PointSetWriter::XML_X = "x" ; const char* mitk::PointSetWriter::XML_Y = "y" ; const char* mitk::PointSetWriter::XML_Z = "z" ; const char* mitk::PointSetWriter::VERSION_STRING = "0.1" ; mitk::PointSetWriter::PointSetWriter() { this->SetNumberOfRequiredInputs( 1 ); this->SetNumberOfOutputs( 1 ); this->SetNthOutput( 0, mitk::PointSet::New().GetPointer() ); m_Indent = 2; m_IndentDepth = 0; } mitk::PointSetWriter::~PointSetWriter() {} void mitk::PointSetWriter::GenerateData() { m_IndentDepth = 0; // // Opening the file to write to // if ( m_FileName == "" ) { itkWarningMacro( << "Sorry, filename has not been set!" ); return ; } std::ofstream out( m_FileName.c_str() ); if ( !out.good() ) { itkWarningMacro( << "Sorry, file " << m_FileName << " could not be opened!" ); out.close(); return ; } // // Here the actual xml writing begins // WriteXMLHeader( out ); WriteStartElement( XML_POINT_SET_FILE, out ); WriteStartElement( XML_FILE_VERSION, out ); WriteCharacterData( VERSION_STRING, out ); WriteEndElement( XML_FILE_VERSION, out, false ); // // for each input object write its xml representation to // the stream // for ( unsigned int i = 0 ; i < this->GetNumberOfInputs(); ++i ) { InputType::Pointer pointSet = this->GetInput( i ); assert( pointSet.IsNotNull() ); WriteXML( pointSet.GetPointer(), out ); } WriteEndElement( XML_POINT_SET_FILE, out ); out.close(); } void mitk::PointSetWriter::WriteXML( mitk::PointSet* pointSet, std::ofstream& out ) { WriteStartElement( XML_POINT_SET, out ); mitk::PointSet::PointsContainer* pointsContainer = pointSet->GetPointSet()->GetPoints(); mitk::PointSet::PointsContainer::Iterator it, end; for ( it = pointsContainer->Begin(); it != pointsContainer->End(); ++it ) { WriteStartElement( XML_POINT, out ); WriteStartElement( XML_ID, out ); WriteCharacterData( ConvertToString<int>( it->Index() ).c_str() , out ); WriteEndElement( XML_ID, out, false ); mitk::PointSet::PointType point = it->Value(); WriteStartElement( XML_X, out ); WriteCharacterData( ConvertToString<mitk::ScalarType>( point[ 0 ] ).c_str(), out ); WriteEndElement( XML_X, out, false ); WriteStartElement( XML_Y, out ); WriteCharacterData( ConvertToString<mitk::ScalarType>( point[ 1 ] ).c_str(), out ); WriteEndElement( XML_Y, out, false ); WriteStartElement( XML_Z, out ); WriteCharacterData( ConvertToString<mitk::ScalarType>( point[ 2 ] ).c_str(), out ); WriteEndElement( XML_Z, out, false ); WriteEndElement( XML_POINT, out ); } WriteEndElement( XML_POINT_SET, out ); } void mitk::PointSetWriter::ResizeInputs( const unsigned int& num ) { unsigned int prevNum = this->GetNumberOfInputs(); this->SetNumberOfInputs( num ); for ( unsigned int i = prevNum; i < num; ++i ) { this->SetNthInput( i, mitk::PointSet::New().GetPointer() ); } } void mitk::PointSetWriter::SetInput( InputType* pointSet ) { this->ProcessObject::SetNthInput( 0, pointSet ); } void mitk::PointSetWriter::SetInput( const unsigned int& id, InputType* pointSet ) { if ( id >= this->GetNumberOfInputs() ) this->ResizeInputs( id + 1 ); this->ProcessObject::SetNthInput( id, pointSet ); } mitk::PointSet* mitk::PointSetWriter::GetInput() { if ( this->GetNumberOfInputs() < 1 ) { return 0; } else { return dynamic_cast<InputType*> ( this->GetInput( 0 ) ); } } mitk::PointSet* mitk::PointSetWriter::GetInput( const unsigned int& num ) { return dynamic_cast<InputType*> ( this->ProcessObject::GetInput( num ) ); } template < typename T> std::string mitk::PointSetWriter::ConvertToString( T value ) { std::ostringstream o; if ( o << value ) return o.str(); else return "conversion error"; } void mitk::PointSetWriter::WriteXMLHeader( std::ofstream &file ) { file << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>"; } void mitk::PointSetWriter::WriteStartElement( const char *const tag, std::ofstream &file ) { file << std::endl; WriteIndent( file ); file << '<' << tag << '>'; m_IndentDepth++; } void mitk::PointSetWriter::WriteEndElement( const char *const tag, std::ofstream &file, const bool& indent ) { m_IndentDepth--; if ( indent ) { file << std::endl; WriteIndent( file ); } file << '<' << '/' << tag << '>'; } void mitk::PointSetWriter::WriteCharacterData( const char *const data, std::ofstream &file ) { file << data; } void mitk::PointSetWriter::WriteStartElement( std::string &tag, std::ofstream &file ) { WriteStartElement( tag.c_str(), file ); } void mitk::PointSetWriter::WriteEndElement( std::string &tag, std::ofstream &file, const bool& indent ) { WriteEndElement( tag.c_str(), file, indent ); } void mitk::PointSetWriter::WriteCharacterData( std::string &data, std::ofstream &file ) { WriteCharacterData( data.c_str(), file ); } void mitk::PointSetWriter::WriteIndent( std::ofstream& file ) { std::string spaces( m_IndentDepth * m_Indent, ' ' ); file << spaces.c_str(); } <commit_msg>Added missing newline at end of file.<commit_after>#include "mitkPointSetWriter.h" #include <iostream> #include <fstream> // // Initialization of the xml tags. // const char* mitk::PointSetWriter::XML_POINT_SET_FILE = "point_set_file" ; const char* mitk::PointSetWriter::XML_FILE_VERSION = "file_version" ; const char* mitk::PointSetWriter::XML_POINT_SET = "point_set" ; const char* mitk::PointSetWriter::XML_POINT = "point" ; const char* mitk::PointSetWriter::XML_ID = "id" ; const char* mitk::PointSetWriter::XML_X = "x" ; const char* mitk::PointSetWriter::XML_Y = "y" ; const char* mitk::PointSetWriter::XML_Z = "z" ; const char* mitk::PointSetWriter::VERSION_STRING = "0.1" ; mitk::PointSetWriter::PointSetWriter() { this->SetNumberOfRequiredInputs( 1 ); this->SetNumberOfOutputs( 1 ); this->SetNthOutput( 0, mitk::PointSet::New().GetPointer() ); m_Indent = 2; m_IndentDepth = 0; } mitk::PointSetWriter::~PointSetWriter() {} void mitk::PointSetWriter::GenerateData() { m_IndentDepth = 0; // // Opening the file to write to // if ( m_FileName == "" ) { itkWarningMacro( << "Sorry, filename has not been set!" ); return ; } std::ofstream out( m_FileName.c_str() ); if ( !out.good() ) { itkWarningMacro( << "Sorry, file " << m_FileName << " could not be opened!" ); out.close(); return ; } // // Here the actual xml writing begins // WriteXMLHeader( out ); WriteStartElement( XML_POINT_SET_FILE, out ); WriteStartElement( XML_FILE_VERSION, out ); WriteCharacterData( VERSION_STRING, out ); WriteEndElement( XML_FILE_VERSION, out, false ); // // for each input object write its xml representation to // the stream // for ( unsigned int i = 0 ; i < this->GetNumberOfInputs(); ++i ) { InputType::Pointer pointSet = this->GetInput( i ); assert( pointSet.IsNotNull() ); WriteXML( pointSet.GetPointer(), out ); } WriteEndElement( XML_POINT_SET_FILE, out ); out.close(); } void mitk::PointSetWriter::WriteXML( mitk::PointSet* pointSet, std::ofstream& out ) { WriteStartElement( XML_POINT_SET, out ); mitk::PointSet::PointsContainer* pointsContainer = pointSet->GetPointSet()->GetPoints(); mitk::PointSet::PointsContainer::Iterator it, end; for ( it = pointsContainer->Begin(); it != pointsContainer->End(); ++it ) { WriteStartElement( XML_POINT, out ); WriteStartElement( XML_ID, out ); WriteCharacterData( ConvertToString<int>( it->Index() ).c_str() , out ); WriteEndElement( XML_ID, out, false ); mitk::PointSet::PointType point = it->Value(); WriteStartElement( XML_X, out ); WriteCharacterData( ConvertToString<mitk::ScalarType>( point[ 0 ] ).c_str(), out ); WriteEndElement( XML_X, out, false ); WriteStartElement( XML_Y, out ); WriteCharacterData( ConvertToString<mitk::ScalarType>( point[ 1 ] ).c_str(), out ); WriteEndElement( XML_Y, out, false ); WriteStartElement( XML_Z, out ); WriteCharacterData( ConvertToString<mitk::ScalarType>( point[ 2 ] ).c_str(), out ); WriteEndElement( XML_Z, out, false ); WriteEndElement( XML_POINT, out ); } WriteEndElement( XML_POINT_SET, out ); } void mitk::PointSetWriter::ResizeInputs( const unsigned int& num ) { unsigned int prevNum = this->GetNumberOfInputs(); this->SetNumberOfInputs( num ); for ( unsigned int i = prevNum; i < num; ++i ) { this->SetNthInput( i, mitk::PointSet::New().GetPointer() ); } } void mitk::PointSetWriter::SetInput( InputType* pointSet ) { this->ProcessObject::SetNthInput( 0, pointSet ); } void mitk::PointSetWriter::SetInput( const unsigned int& id, InputType* pointSet ) { if ( id >= this->GetNumberOfInputs() ) this->ResizeInputs( id + 1 ); this->ProcessObject::SetNthInput( id, pointSet ); } mitk::PointSet* mitk::PointSetWriter::GetInput() { if ( this->GetNumberOfInputs() < 1 ) { return 0; } else { return dynamic_cast<InputType*> ( this->GetInput( 0 ) ); } } mitk::PointSet* mitk::PointSetWriter::GetInput( const unsigned int& num ) { return dynamic_cast<InputType*> ( this->ProcessObject::GetInput( num ) ); } template < typename T> std::string mitk::PointSetWriter::ConvertToString( T value ) { std::ostringstream o; if ( o << value ) return o.str(); else return "conversion error"; } void mitk::PointSetWriter::WriteXMLHeader( std::ofstream &file ) { file << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>"; } void mitk::PointSetWriter::WriteStartElement( const char *const tag, std::ofstream &file ) { file << std::endl; WriteIndent( file ); file << '<' << tag << '>'; m_IndentDepth++; } void mitk::PointSetWriter::WriteEndElement( const char *const tag, std::ofstream &file, const bool& indent ) { m_IndentDepth--; if ( indent ) { file << std::endl; WriteIndent( file ); } file << '<' << '/' << tag << '>'; } void mitk::PointSetWriter::WriteCharacterData( const char *const data, std::ofstream &file ) { file << data; } void mitk::PointSetWriter::WriteStartElement( std::string &tag, std::ofstream &file ) { WriteStartElement( tag.c_str(), file ); } void mitk::PointSetWriter::WriteEndElement( std::string &tag, std::ofstream &file, const bool& indent ) { WriteEndElement( tag.c_str(), file, indent ); } void mitk::PointSetWriter::WriteCharacterData( std::string &data, std::ofstream &file ) { WriteCharacterData( data.c_str(), file ); } void mitk::PointSetWriter::WriteIndent( std::ofstream& file ) { std::string spaces( m_IndentDepth * m_Indent, ' ' ); file << spaces.c_str(); } <|endoftext|>
<commit_before>/*********************************************************************** options.cpp - Implements the Option class hierarchy. Copyright (c) 2007 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #define MYSQLPP_NOT_HEADER #include "options.h" #include "dbdriver.h" namespace mysqlpp { #if !defined(DOXYGEN_IGNORE) // We're hiding all the Option subclass internals from Doxygen. All the // upper-level classes are documented fully, and each leaf class itself // is documented. It's just the ctors and set() methods we're refusing // to document over and over again. Option::Error CompressOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_OPT_COMPRESS) ? Option::err_NONE : Option::err_api_reject; } Option::Error ConnectTimeoutOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_OPT_CONNECT_TIMEOUT, &arg_) ? Option::err_NONE : Option::err_api_reject; } Option::Error FoundRowsOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(CLIENT_FOUND_ROWS, arg_) ? Option::err_NONE : Option::err_api_reject; } Option::Error GuessConnectionOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 40101 return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_OPT_GUESS_CONNECTION) ? Option::err_NONE : Option::err_api_reject; #else return Option::err_api_limit; #endif } Option::Error IgnoreSpaceOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(CLIENT_IGNORE_SPACE, arg_) ? Option::err_NONE : Option::err_api_reject; } Option::Error InitCommandOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_INIT_COMMAND, arg_.c_str()) ? Option::err_NONE : Option::err_api_reject; } Option::Error InteractiveOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(CLIENT_INTERACTIVE, arg_) ? Option::err_NONE : Option::err_api_reject; } Option::Error LocalFilesOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(CLIENT_LOCAL_FILES, arg_) ? Option::err_NONE : Option::err_api_reject; } Option::Error LocalInfileOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_OPT_LOCAL_INFILE, &arg_) ? Option::err_NONE : Option::err_api_reject; } Option::Error MultiResultsOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 40101 if (dbd->connected()) { return dbd->set_option(arg_ ? MYSQL_OPTION_MULTI_STATEMENTS_ON : MYSQL_OPTION_MULTI_STATEMENTS_OFF) ? Option::err_NONE : Option::err_api_reject; } else { return dbd->set_option(CLIENT_MULTI_RESULTS, arg_) ? Option::err_NONE : Option::err_api_reject; } #else return Option::err_api_limit; #endif } Option::Error MultiStatementsOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 40101 if (dbd->connected()) { return dbd->set_option(arg_ ? MYSQL_OPTION_MULTI_STATEMENTS_ON : MYSQL_OPTION_MULTI_STATEMENTS_OFF) ? Option::err_NONE : Option::err_api_reject; } else { return dbd->set_option(CLIENT_MULTI_STATEMENTS, arg_) ? Option::err_NONE : Option::err_api_reject; } #else return Option::err_api_limit; #endif } Option::Error NamedPipeOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_OPT_NAMED_PIPE) ? Option::err_NONE : Option::err_api_reject; } Option::Error NoSchemaOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(CLIENT_NO_SCHEMA, arg_) ? Option::err_NONE : Option::err_api_reject; } #if MYSQL_VERSION_ID > 40000 // only in 4.0 + Option::Error ProtocolOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_OPT_PROTOCOL, &arg_) ? Option::err_NONE : Option::err_api_reject; } #endif Option::Error ReadDefaultFileOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_READ_DEFAULT_FILE, arg_.c_str()) ? Option::err_NONE : Option::err_api_reject; } Option::Error ReadDefaultGroupOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_READ_DEFAULT_GROUP, arg_.c_str()) ? Option::err_NONE : Option::err_api_reject; } Option::Error ReadTimeoutOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 40101 return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_OPT_READ_TIMEOUT, &arg_) ? Option::err_NONE : Option::err_api_reject; #else return Option::err_api_limit; #endif } Option::Error ReconnectOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 50013 return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_OPT_RECONNECT, &arg_) ? Option::err_NONE : Option::err_api_reject; #else return Option::err_api_limit; #endif } Option::Error ReportDataTruncationOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 50003 return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_REPORT_DATA_TRUNCATION, &arg_) ? Option::err_NONE : Option::err_api_reject; #else return Option::err_api_limit; #endif } Option::Error SecureAuthOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 40101 return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_SECURE_AUTH, &arg_) ? Option::err_NONE : Option::err_api_reject; #else return Option::err_api_limit; #endif } Option::Error SetCharsetDirOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_SET_CHARSET_DIR, arg_.c_str()) ? Option::err_NONE : Option::err_api_reject; } Option::Error SetCharsetNameOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_SET_CHARSET_NAME, arg_.c_str()) ? Option::err_NONE : Option::err_api_reject; } Option::Error SetClientIpOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 40101 return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_SET_CLIENT_IP, arg_.c_str()) ? Option::err_NONE : Option::err_api_reject; #else return Option::err_api_limit; #endif } Option::Error SharedMemoryBaseNameOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 40100 return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_SHARED_MEMORY_BASE_NAME, arg_.c_str()) ? Option::err_NONE : Option::err_api_reject; #else return Option::err_api_limit; #endif } Option::Error SslOption::set(DBDriver* dbd) { #if defined(HAVE_MYSQL_SSL_SET) return dbd->connected() ? Option::err_connected : dbd->enable_ssl(key_.c_str(), cert_.c_str(), ca_.c_str(), capath_.c_str(), cipher_.c_str()) ? Option::err_NONE : Option::err_api_reject; #else return Option::err_api_limit; #endif } Option::Error UseEmbeddedConnectionOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 40101 return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_OPT_USE_EMBEDDED_CONNECTION) ? Option::err_NONE : Option::err_api_reject; #else return Option::err_api_limit; #endif } Option::Error UseRemoteConnectionOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 40101 return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_OPT_USE_REMOTE_CONNECTION) ? Option::err_NONE : Option::err_api_reject; #else return Option::err_api_limit; #endif } Option::Error WriteTimeoutOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 40101 return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_OPT_WRITE_TIMEOUT, &arg_) ? Option::err_NONE : Option::err_api_reject; #else return Option::err_api_limit; #endif } #endif // !defined(DOXYGEN_IGNORE) } // end namespace mysqlpp <commit_msg>Passing 0 to mysql_ssl_set() for SSL parameters not given when populating SslOption object instead of an empty string. Fixes bug #11796. Fix by Petteri Kiiskinen <iridian@cs.hut.fi><commit_after>/*********************************************************************** options.cpp - Implements the Option class hierarchy. Copyright (c) 2007 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #define MYSQLPP_NOT_HEADER #include "options.h" #include "dbdriver.h" namespace mysqlpp { #if !defined(DOXYGEN_IGNORE) // We're hiding all the Option subclass internals from Doxygen. All the // upper-level classes are documented fully, and each leaf class itself // is documented. It's just the ctors and set() methods we're refusing // to document over and over again. Option::Error CompressOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_OPT_COMPRESS) ? Option::err_NONE : Option::err_api_reject; } Option::Error ConnectTimeoutOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_OPT_CONNECT_TIMEOUT, &arg_) ? Option::err_NONE : Option::err_api_reject; } Option::Error FoundRowsOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(CLIENT_FOUND_ROWS, arg_) ? Option::err_NONE : Option::err_api_reject; } Option::Error GuessConnectionOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 40101 return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_OPT_GUESS_CONNECTION) ? Option::err_NONE : Option::err_api_reject; #else return Option::err_api_limit; #endif } Option::Error IgnoreSpaceOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(CLIENT_IGNORE_SPACE, arg_) ? Option::err_NONE : Option::err_api_reject; } Option::Error InitCommandOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_INIT_COMMAND, arg_.c_str()) ? Option::err_NONE : Option::err_api_reject; } Option::Error InteractiveOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(CLIENT_INTERACTIVE, arg_) ? Option::err_NONE : Option::err_api_reject; } Option::Error LocalFilesOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(CLIENT_LOCAL_FILES, arg_) ? Option::err_NONE : Option::err_api_reject; } Option::Error LocalInfileOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_OPT_LOCAL_INFILE, &arg_) ? Option::err_NONE : Option::err_api_reject; } Option::Error MultiResultsOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 40101 if (dbd->connected()) { return dbd->set_option(arg_ ? MYSQL_OPTION_MULTI_STATEMENTS_ON : MYSQL_OPTION_MULTI_STATEMENTS_OFF) ? Option::err_NONE : Option::err_api_reject; } else { return dbd->set_option(CLIENT_MULTI_RESULTS, arg_) ? Option::err_NONE : Option::err_api_reject; } #else return Option::err_api_limit; #endif } Option::Error MultiStatementsOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 40101 if (dbd->connected()) { return dbd->set_option(arg_ ? MYSQL_OPTION_MULTI_STATEMENTS_ON : MYSQL_OPTION_MULTI_STATEMENTS_OFF) ? Option::err_NONE : Option::err_api_reject; } else { return dbd->set_option(CLIENT_MULTI_STATEMENTS, arg_) ? Option::err_NONE : Option::err_api_reject; } #else return Option::err_api_limit; #endif } Option::Error NamedPipeOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_OPT_NAMED_PIPE) ? Option::err_NONE : Option::err_api_reject; } Option::Error NoSchemaOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(CLIENT_NO_SCHEMA, arg_) ? Option::err_NONE : Option::err_api_reject; } #if MYSQL_VERSION_ID > 40000 // only in 4.0 + Option::Error ProtocolOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_OPT_PROTOCOL, &arg_) ? Option::err_NONE : Option::err_api_reject; } #endif Option::Error ReadDefaultFileOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_READ_DEFAULT_FILE, arg_.c_str()) ? Option::err_NONE : Option::err_api_reject; } Option::Error ReadDefaultGroupOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_READ_DEFAULT_GROUP, arg_.c_str()) ? Option::err_NONE : Option::err_api_reject; } Option::Error ReadTimeoutOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 40101 return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_OPT_READ_TIMEOUT, &arg_) ? Option::err_NONE : Option::err_api_reject; #else return Option::err_api_limit; #endif } Option::Error ReconnectOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 50013 return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_OPT_RECONNECT, &arg_) ? Option::err_NONE : Option::err_api_reject; #else return Option::err_api_limit; #endif } Option::Error ReportDataTruncationOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 50003 return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_REPORT_DATA_TRUNCATION, &arg_) ? Option::err_NONE : Option::err_api_reject; #else return Option::err_api_limit; #endif } Option::Error SecureAuthOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 40101 return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_SECURE_AUTH, &arg_) ? Option::err_NONE : Option::err_api_reject; #else return Option::err_api_limit; #endif } Option::Error SetCharsetDirOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_SET_CHARSET_DIR, arg_.c_str()) ? Option::err_NONE : Option::err_api_reject; } Option::Error SetCharsetNameOption::set(DBDriver* dbd) { return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_SET_CHARSET_NAME, arg_.c_str()) ? Option::err_NONE : Option::err_api_reject; } Option::Error SetClientIpOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 40101 return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_SET_CLIENT_IP, arg_.c_str()) ? Option::err_NONE : Option::err_api_reject; #else return Option::err_api_limit; #endif } Option::Error SharedMemoryBaseNameOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 40100 return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_SHARED_MEMORY_BASE_NAME, arg_.c_str()) ? Option::err_NONE : Option::err_api_reject; #else return Option::err_api_limit; #endif } Option::Error SslOption::set(DBDriver* dbd) { #if defined(HAVE_MYSQL_SSL_SET) return dbd->connected() ? Option::err_connected : dbd->enable_ssl( key_.size() ? key_.c_str() : 0, cert_.size() ? cert_.c_str() : 0, ca_.size() ? ca_.c_str() : 0, capath_.size() ? capath_.c_str() : 0, cipher_.size() ? cipher_.c_str() : 0) ? Option::err_NONE : Option::err_api_reject; #else return Option::err_api_limit; #endif } Option::Error UseEmbeddedConnectionOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 40101 return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_OPT_USE_EMBEDDED_CONNECTION) ? Option::err_NONE : Option::err_api_reject; #else return Option::err_api_limit; #endif } Option::Error UseRemoteConnectionOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 40101 return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_OPT_USE_REMOTE_CONNECTION) ? Option::err_NONE : Option::err_api_reject; #else return Option::err_api_limit; #endif } Option::Error WriteTimeoutOption::set(DBDriver* dbd) { #if MYSQL_VERSION_ID >= 40101 return dbd->connected() ? Option::err_connected : dbd->set_option(MYSQL_OPT_WRITE_TIMEOUT, &arg_) ? Option::err_NONE : Option::err_api_reject; #else return Option::err_api_limit; #endif } #endif // !defined(DOXYGEN_IGNORE) } // end namespace mysqlpp <|endoftext|>
<commit_before>#ifndef GUARD_phatbooks_database_connection_hpp #define GUARD_phatbooks_database_connection_hpp /** \file phatbooks_database_connection.hpp * * \brief Header file pertaining to PhatbooksDatabaseConnection class. * * \author Matthew Harvey * \date 04 July 2012. * * Copyright (c) 2012, Matthew Harvey. All rights reserved. */ // TODO All the includes here thwart the compiler firewall // that was one benefit of PIMPLing the business object classes. // Think of a way around having to include the ..._impl classes. #include "account_type.hpp" #include "sqloxx/database_connection.hpp" #include "sqloxx/general_typedefs.hpp" #include <boost/bimap.hpp> #include <boost/scoped_ptr.hpp> #include <jewel/decimal.hpp> #include <string> namespace sqloxx { // Forward declaration template <typename T, typename Connection> class IdentityMap; } namespace phatbooks { // Forward declarations class BalanceCache; class AccountImpl; class CommodityImpl; class EntryImpl; class DraftJournalImpl; class OrdinaryJournalImpl; class RepeaterImpl; /** Phatbooks-specific database connection class. * See API documentation for sqloxx::DatabaseConnection, * for parts of API inherited from sqloxx::DatabaseConnection. */ class PhatbooksDatabaseConnection: public sqloxx::DatabaseConnection { public: /** * Exhibits the same throwing behaviour (if any) as * default constructor for sqloxx::DatabaseConnection. */ PhatbooksDatabaseConnection(); ~PhatbooksDatabaseConnection(); /** * @returns \c true if and only if \c p_name is the name of an Account * stored in the database. * * @param p_name name of Account. * * @throws SQLiteException or an exception derived therefrom, if * something goes wrong with the SQL involved in executing * the function. This might occur if \c p_name contains punctuation * marks, spaces or etc., or is a SQL keyword, so that it cannot validly * be a string parameter in a SQL statement. A SQLiteException or * derivative might also be thrown if the database connection is invalid * or the database corrupt. It is not guaranteed that these are the only * circumstances in which an exception might be thrown. */ bool has_account_named(std::string const& p_name); /** * @returns \c true if and only if \c p_name is the name of a * DraftJournalImpl stored in the database. * * @todo Document throwing behaviour. */ bool has_draft_journal_named(std::string const& p_name); /** * @returns a boost::bimap from AccountType to string, giving the * string name for each AccountType. * * @todo Determine and document throwing behaviour. */ boost::bimap<account_type::AccountType, std::string> account_types(); /** * @returns \c true if and only if \c p_abbreviation is the abbreviation * of a Commodity stored in the database. */ bool has_commodity_with_abbreviation(std::string const& p_abbreviation); /** * @returns \c true if and only if \c p_name is the name of a Commodity * stored in the database. */ bool has_commodity_named(std::string const& p_name); /** * Creates tables required for Phatbooks, and inserts rows * into certain tables to provide application-level data where * required. If the database already contains these tables, * the function does nothing. This function should always be * called after calling DatabaseConnection::open. * * @throws SQLiteException or some derivative thereof, if setup is * unsuccessful. */ void setup(); /** * Set degree of caching of objects loaded from database. * * Level 0 entails nil caching (except temporary caching required to * avoid * loading of duplicate objects). * * Level 5 entails some caching of objects of which there are only a few * instances expected to exist in the database. * * Level 10 entails maximum caching. * * If \e level is not one of the specific levels listed above, the effect * will be the same as the next lowest level that is listed above. * * When the caching level is changed from one significant level to another * significant level that is lower than the first, any objects of classes * that are not cached under the new level, that were cached under the old * level, that are cached at the time the level changes, are emptied from * the cache. * * @todo Determinate and document throwing behaviour. */ void set_caching_level(unsigned int level); /** * Class to provide restricted access to cache holding * Account balances. */ class BalanceCacheAttorney { public: friend class AccountImpl; friend class CommodityImpl; friend class EntryImpl; private: // Mark whole balance cache as stale static void mark_as_stale ( PhatbooksDatabaseConnection const& p_database_connection ); // Mark a particular Account in the balance cache as stale static void mark_as_stale ( PhatbooksDatabaseConnection const& p_database_connection, sqloxx::Id p_account_id ); // Retrieve the balance of an Account static jewel::Decimal balance ( PhatbooksDatabaseConnection const& p_database_connection, sqloxx::Id p_account_id ); }; friend class BalanceCacheAttorney; template<typename T> sqloxx::IdentityMap<T, PhatbooksDatabaseConnection>& identity_map(); private: bool setup_has_occurred(); void mark_setup_as_having_occurred(); BalanceCache* m_balance_cache; sqloxx::IdentityMap<AccountImpl, PhatbooksDatabaseConnection>* m_account_map; sqloxx::IdentityMap<CommodityImpl, PhatbooksDatabaseConnection>* m_commodity_map; sqloxx::IdentityMap<EntryImpl, PhatbooksDatabaseConnection>* m_entry_map; sqloxx::IdentityMap<OrdinaryJournalImpl, PhatbooksDatabaseConnection>* m_ordinary_journal_map; sqloxx::IdentityMap<DraftJournalImpl, PhatbooksDatabaseConnection>* m_draft_journal_map; sqloxx::IdentityMap<RepeaterImpl, PhatbooksDatabaseConnection>* m_repeater_map; }; // PhatbooksDatabaseConnection } // namespace phatbooks #endif // GUARD_phatbooks_database_connection_hpp <commit_msg>Updated a todo in phatbooks_database_connection.hpp.<commit_after>#ifndef GUARD_phatbooks_database_connection_hpp #define GUARD_phatbooks_database_connection_hpp /** \file phatbooks_database_connection.hpp * * \brief Header file pertaining to PhatbooksDatabaseConnection class. * * \author Matthew Harvey * \date 04 July 2012. * * Copyright (c) 2012, Matthew Harvey. All rights reserved. */ #include "account_type.hpp" #include "sqloxx/database_connection.hpp" #include "sqloxx/general_typedefs.hpp" #include <boost/bimap.hpp> #include <boost/scoped_ptr.hpp> #include <jewel/decimal.hpp> #include <string> namespace sqloxx { // Forward declaration template <typename T, typename Connection> class IdentityMap; } namespace phatbooks { // Forward declarations class BalanceCache; class AccountImpl; class CommodityImpl; class EntryImpl; class DraftJournalImpl; class OrdinaryJournalImpl; class RepeaterImpl; /** Phatbooks-specific database connection class. * See API documentation for sqloxx::DatabaseConnection, * for parts of API inherited from sqloxx::DatabaseConnection. */ class PhatbooksDatabaseConnection: public sqloxx::DatabaseConnection { public: /** * Exhibits the same throwing behaviour (if any) as * default constructor for sqloxx::DatabaseConnection. */ PhatbooksDatabaseConnection(); ~PhatbooksDatabaseConnection(); /** * @returns \c true if and only if \c p_name is the name of an Account * stored in the database. * * @param p_name name of Account. * * @throws SQLiteException or an exception derived therefrom, if * something goes wrong with the SQL involved in executing * the function. This might occur if \c p_name contains punctuation * marks, spaces or etc., or is a SQL keyword, so that it cannot validly * be a string parameter in a SQL statement. A SQLiteException or * derivative might also be thrown if the database connection is invalid * or the database corrupt. It is not guaranteed that these are the only * circumstances in which an exception might be thrown. */ bool has_account_named(std::string const& p_name); /** * @returns \c true if and only if \c p_name is the name of a * DraftJournalImpl stored in the database. * * @todo Document throwing behaviour. */ bool has_draft_journal_named(std::string const& p_name); /** * @returns a boost::bimap from AccountType to string, giving the * string name for each AccountType. * * @todo Determine and document throwing behaviour. */ boost::bimap<account_type::AccountType, std::string> account_types(); /** * @returns \c true if and only if \c p_abbreviation is the abbreviation * of a Commodity stored in the database. */ bool has_commodity_with_abbreviation(std::string const& p_abbreviation); /** * @returns \c true if and only if \c p_name is the name of a Commodity * stored in the database. */ bool has_commodity_named(std::string const& p_name); /** * Creates tables required for Phatbooks, and inserts rows * into certain tables to provide application-level data where * required. If the database already contains these tables, * the function does nothing. This function should always be * called after calling DatabaseConnection::open. * * @throws SQLiteException or some derivative thereof, if setup is * unsuccessful. */ void setup(); /** * Set degree of caching of objects loaded from database. * * Level 0 entails nil caching (except temporary caching required to * avoid * loading of duplicate objects). * * Level 5 entails some caching of objects of which there are only a few * instances expected to exist in the database. * * Level 10 entails maximum caching. * * If \e level is not one of the specific levels listed above, the effect * will be the same as the next lowest level that is listed above. * * When the caching level is changed from one significant level to another * significant level that is lower than the first, any objects of classes * that are not cached under the new level, that were cached under the old * level, that are cached at the time the level changes, are emptied from * the cache. * * @todo Determinate and document throwing behaviour. */ void set_caching_level(unsigned int level); /** * Class to provide restricted access to cache holding * Account balances. */ class BalanceCacheAttorney { public: friend class AccountImpl; friend class CommodityImpl; friend class EntryImpl; private: // Mark whole balance cache as stale static void mark_as_stale ( PhatbooksDatabaseConnection const& p_database_connection ); // Mark a particular Account in the balance cache as stale static void mark_as_stale ( PhatbooksDatabaseConnection const& p_database_connection, sqloxx::Id p_account_id ); // Retrieve the balance of an Account static jewel::Decimal balance ( PhatbooksDatabaseConnection const& p_database_connection, sqloxx::Id p_account_id ); }; friend class BalanceCacheAttorney; template<typename T> sqloxx::IdentityMap<T, PhatbooksDatabaseConnection>& identity_map(); private: bool setup_has_occurred(); void mark_setup_as_having_occurred(); BalanceCache* m_balance_cache; sqloxx::IdentityMap<AccountImpl, PhatbooksDatabaseConnection>* m_account_map; sqloxx::IdentityMap<CommodityImpl, PhatbooksDatabaseConnection>* m_commodity_map; sqloxx::IdentityMap<EntryImpl, PhatbooksDatabaseConnection>* m_entry_map; sqloxx::IdentityMap<OrdinaryJournalImpl, PhatbooksDatabaseConnection>* m_ordinary_journal_map; sqloxx::IdentityMap<DraftJournalImpl, PhatbooksDatabaseConnection>* m_draft_journal_map; sqloxx::IdentityMap<RepeaterImpl, PhatbooksDatabaseConnection>* m_repeater_map; }; // PhatbooksDatabaseConnection } // namespace phatbooks #endif // GUARD_phatbooks_database_connection_hpp <|endoftext|>
<commit_before>// Copyright (c) 2018-2021 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 <chainparams.h> #include <core_io.h> #include <psbt.h> #include <util/strencodings.h> #include <util/system.h> #include <external_signer.h> #include <stdexcept> #include <string> #include <vector> ExternalSigner::ExternalSigner(const std::string& command, const std::string chain, const std::string& fingerprint, const std::string name): m_command(command), m_chain(chain), m_fingerprint(fingerprint), m_name(name) {} const std::string ExternalSigner::NetworkArg() const { return " --chain " + m_chain; } bool ExternalSigner::Enumerate(const std::string& command, std::vector<ExternalSigner>& signers, const std::string chain) { // Call <command> enumerate const UniValue result = RunCommandParseJSON(command + " enumerate"); if (!result.isArray()) { throw std::runtime_error(strprintf("'%s' received invalid response, expected array of signers", command)); } for (UniValue signer : result.getValues()) { // Check for error const UniValue& error = find_value(signer, "error"); if (!error.isNull()) { if (!error.isStr()) { throw std::runtime_error(strprintf("'%s' error", command)); } throw std::runtime_error(strprintf("'%s' error: %s", command, error.getValStr())); } // Check if fingerprint is present const UniValue& fingerprint = find_value(signer, "fingerprint"); if (fingerprint.isNull()) { throw std::runtime_error(strprintf("'%s' received invalid response, missing signer fingerprint", command)); } const std::string fingerprintStr = fingerprint.get_str(); // Skip duplicate signer bool duplicate = false; for (const ExternalSigner& signer : signers) { if (signer.m_fingerprint.compare(fingerprintStr) == 0) duplicate = true; } if (duplicate) break; std::string name = ""; const UniValue& model_field = find_value(signer, "model"); if (model_field.isStr() && model_field.getValStr() != "") { name += model_field.getValStr(); } signers.push_back(ExternalSigner(command, chain, fingerprintStr, name)); } return true; } UniValue ExternalSigner::DisplayAddress(const std::string& descriptor) const { return RunCommandParseJSON(m_command + " --fingerprint \"" + m_fingerprint + "\"" + NetworkArg() + " displayaddress --desc \"" + descriptor + "\""); } UniValue ExternalSigner::GetDescriptors(const int account) { return RunCommandParseJSON(m_command + " --fingerprint \"" + m_fingerprint + "\"" + NetworkArg() + " getdescriptors --account " + strprintf("%d", account)); } bool ExternalSigner::SignTransaction(PartiallySignedTransaction& psbtx, std::string& error) { // Serialize the PSBT CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << psbtx; // Check if signer fingerprint matches any input master key fingerprint bool match = false; for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) { const PSBTInput& input = psbtx.inputs[i]; for (const auto& entry : input.hd_keypaths) { if (m_fingerprint == strprintf("%08x", ReadBE32(entry.second.fingerprint))) match = true; } } if (!match) { error = "Signer fingerprint " + m_fingerprint + " does not match any of the inputs:\n" + EncodeBase64(ssTx.str()); return false; } const std::string command = m_command + " --stdin --fingerprint \"" + m_fingerprint + "\"" + NetworkArg(); const std::string stdinStr = "signtx \"" + EncodeBase64(ssTx.str()) + "\""; const UniValue signer_result = RunCommandParseJSON(command, stdinStr); if (find_value(signer_result, "error").isStr()) { error = find_value(signer_result, "error").get_str(); return false; } if (!find_value(signer_result, "psbt").isStr()) { error = "Unexpected result from signer"; return false; } PartiallySignedTransaction signer_psbtx; std::string signer_psbt_error; if (!DecodeBase64PSBT(signer_psbtx, find_value(signer_result, "psbt").get_str(), signer_psbt_error)) { error = strprintf("TX decode failed %s", signer_psbt_error); return false; } psbtx = signer_psbtx; return true; } <commit_msg>external_signer: improve fingerprint matching logic (stop on first match)<commit_after>// Copyright (c) 2018-2021 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 <chainparams.h> #include <core_io.h> #include <psbt.h> #include <util/strencodings.h> #include <util/system.h> #include <external_signer.h> #include <algorithm> #include <stdexcept> #include <string> #include <vector> ExternalSigner::ExternalSigner(const std::string& command, const std::string chain, const std::string& fingerprint, const std::string name): m_command(command), m_chain(chain), m_fingerprint(fingerprint), m_name(name) {} const std::string ExternalSigner::NetworkArg() const { return " --chain " + m_chain; } bool ExternalSigner::Enumerate(const std::string& command, std::vector<ExternalSigner>& signers, const std::string chain) { // Call <command> enumerate const UniValue result = RunCommandParseJSON(command + " enumerate"); if (!result.isArray()) { throw std::runtime_error(strprintf("'%s' received invalid response, expected array of signers", command)); } for (UniValue signer : result.getValues()) { // Check for error const UniValue& error = find_value(signer, "error"); if (!error.isNull()) { if (!error.isStr()) { throw std::runtime_error(strprintf("'%s' error", command)); } throw std::runtime_error(strprintf("'%s' error: %s", command, error.getValStr())); } // Check if fingerprint is present const UniValue& fingerprint = find_value(signer, "fingerprint"); if (fingerprint.isNull()) { throw std::runtime_error(strprintf("'%s' received invalid response, missing signer fingerprint", command)); } const std::string fingerprintStr = fingerprint.get_str(); // Skip duplicate signer bool duplicate = false; for (const ExternalSigner& signer : signers) { if (signer.m_fingerprint.compare(fingerprintStr) == 0) duplicate = true; } if (duplicate) break; std::string name = ""; const UniValue& model_field = find_value(signer, "model"); if (model_field.isStr() && model_field.getValStr() != "") { name += model_field.getValStr(); } signers.push_back(ExternalSigner(command, chain, fingerprintStr, name)); } return true; } UniValue ExternalSigner::DisplayAddress(const std::string& descriptor) const { return RunCommandParseJSON(m_command + " --fingerprint \"" + m_fingerprint + "\"" + NetworkArg() + " displayaddress --desc \"" + descriptor + "\""); } UniValue ExternalSigner::GetDescriptors(const int account) { return RunCommandParseJSON(m_command + " --fingerprint \"" + m_fingerprint + "\"" + NetworkArg() + " getdescriptors --account " + strprintf("%d", account)); } bool ExternalSigner::SignTransaction(PartiallySignedTransaction& psbtx, std::string& error) { // Serialize the PSBT CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << psbtx; // Check if signer fingerprint matches any input master key fingerprint auto matches_signer_fingerprint = [&](const PSBTInput& input) { for (const auto& entry : input.hd_keypaths) { if (m_fingerprint == strprintf("%08x", ReadBE32(entry.second.fingerprint))) return true; } return false; }; if (!std::any_of(psbtx.inputs.begin(), psbtx.inputs.end(), matches_signer_fingerprint)) { error = "Signer fingerprint " + m_fingerprint + " does not match any of the inputs:\n" + EncodeBase64(ssTx.str()); return false; } const std::string command = m_command + " --stdin --fingerprint \"" + m_fingerprint + "\"" + NetworkArg(); const std::string stdinStr = "signtx \"" + EncodeBase64(ssTx.str()) + "\""; const UniValue signer_result = RunCommandParseJSON(command, stdinStr); if (find_value(signer_result, "error").isStr()) { error = find_value(signer_result, "error").get_str(); return false; } if (!find_value(signer_result, "psbt").isStr()) { error = "Unexpected result from signer"; return false; } PartiallySignedTransaction signer_psbtx; std::string signer_psbt_error; if (!DecodeBase64PSBT(signer_psbtx, find_value(signer_result, "psbt").get_str(), signer_psbt_error)) { error = strprintf("TX decode failed %s", signer_psbt_error); return false; } psbtx = signer_psbtx; return true; } <|endoftext|>
<commit_before>/* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #include "servicedirectoryclient.hpp" #include <qitype/objecttypebuilder.hpp> #include "servicedirectory_p.hpp" #include "tcptransportsocket.hpp" namespace qi { ServiceDirectoryClient::ServiceDirectoryClient() : _remoteObject(qi::Message::Service_ServiceDirectory) { _object = makeDynamicObjectPtr(&_remoteObject, false); } ServiceDirectoryClient::~ServiceDirectoryClient() { _object->disconnect(_addLink); _object->disconnect(_removeLink); } void ServiceDirectoryClient::onSDEventConnected(qi::Future<unsigned int> ret, qi::Future<unsigned int> fadd, qi::Future<unsigned int> frem, qi::Promise<bool> fco) { if (!fadd.isReady() || !frem.isReady()) return; if (fadd.hasError() || frem.hasError()) { std::string err; err = fadd.error(); if (!err.empty() && frem.hasError()) err += ". "; err += frem.error(); fco.setError(err); return; } _addLink = fadd.value(); _removeLink = frem.value(); fco.setValue(true); connected(); } void ServiceDirectoryClient::onMetaObjectFetched(qi::Future<void> future, qi::Promise<bool> promise) { if (future.hasError()) { promise.setError(future.error()); return; } boost::function<void (unsigned int, std::string)> f; //TODO: this should not be async f = boost::bind<void>(&ServiceDirectoryClient::onServiceAdded, this, _1, _2); qi::Future<unsigned int> fut1 = _object->connect("serviceAdded", f); f = boost::bind<void>(&ServiceDirectoryClient::onServiceRemoved, this, _1, _2); qi::Future<unsigned int> fut2 = _object->connect("serviceRemoved", f).async(); fut1.connect(boost::bind<void>(&ServiceDirectoryClient::onSDEventConnected, this, _1, fut1, fut2, promise)); fut2.connect(boost::bind<void>(&ServiceDirectoryClient::onSDEventConnected, this, _1, fut1, fut2, promise)); } void ServiceDirectoryClient::onSocketConnected(qi::FutureSync<bool> future, qi::Promise<bool> promise) { if (future.hasError()) { promise.setError(future.error()); return; } if (future.value() == false) { promise.setValue(false); return; } qi::Future<void> fut = _remoteObject.fetchMetaObject(); fut.connect(boost::bind<void>(&ServiceDirectoryClient::onMetaObjectFetched, this, _1, promise)); } //we ensure in that function that connect to all events are already setup when we said we are connect. //that way we cant be connected without being fully ready. qi::FutureSync<bool> ServiceDirectoryClient::connect(const qi::Url &serviceDirectoryURL) { if (isConnected()) { qiLogInfo("qi.Session") << "Session is already connected"; return qi::Future<bool>(false); } _sdSocket = qi::makeTransportSocket(serviceDirectoryURL.protocol()); if (!_sdSocket) return qi::Future<bool>(false); _sdSocketDisconnectedLink = _sdSocket->disconnected.connect(boost::bind<void>(&ServiceDirectoryClient::onSocketDisconnected, this, _1)); _remoteObject.setTransportSocket(_sdSocket); qi::Promise<bool> promise; qi::Future<bool> fut = _sdSocket->connect(serviceDirectoryURL); fut.connect(boost::bind<void>(&ServiceDirectoryClient::onSocketConnected, this, _1, promise)); return promise.future(); } static void sharedPtrHolder(TransportSocketPtr ptr) { } qi::FutureSync<void> ServiceDirectoryClient::close() { if (!_sdSocket) return qi::Future<void>(0); qi::Future<void> fut = _sdSocket->disconnect(); // Hold the socket shared ptr alive until the future returns. // otherwise, the destructor will block us until disconnect terminates fut.connect(boost::bind(&sharedPtrHolder, _sdSocket)); _sdSocket->disconnected.disconnect(_sdSocketDisconnectedLink); _sdSocket.reset(); return fut; } bool ServiceDirectoryClient::isConnected() const { return _sdSocket == 0 ? false : _sdSocket->isConnected(); } qi::Url ServiceDirectoryClient::url() const { return _sdSocket->url(); } void ServiceDirectoryClient::onServiceRemoved(unsigned int idx, const std::string &name) { qiLogVerbose("qi.ServiceDirectoryClient") << "ServiceDirectory: Service Removed #" << idx << ": " << name << std::endl; serviceRemoved(idx, name); } void ServiceDirectoryClient::onServiceAdded(unsigned int idx, const std::string &name) { qiLogVerbose("qi.ServiceDirectoryClient") << "ServiceDirectory: Service Added #" << idx << ": " << name << std::endl; serviceAdded(idx, name); } void ServiceDirectoryClient::onSocketDisconnected(int error) { disconnected(error); } qi::Future< std::vector<ServiceInfo> > ServiceDirectoryClient::services() { return _object->call< std::vector<ServiceInfo> >("services"); } qi::Future<ServiceInfo> ServiceDirectoryClient::service(const std::string &name) { return _object->call< ServiceInfo >("service", name); } qi::Future<unsigned int> ServiceDirectoryClient::registerService(const ServiceInfo &svcinfo) { return _object->call< unsigned int >("registerService", svcinfo); } qi::Future<void> ServiceDirectoryClient::unregisterService(const unsigned int &idx) { return _object->call<void>("unregisterService", idx); } qi::Future<void> ServiceDirectoryClient::serviceReady(const unsigned int &idx) { return _object->call<void>("serviceReady", idx); } } <commit_msg>Fix conditionnal jump or move<commit_after>/* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #include "servicedirectoryclient.hpp" #include <qitype/objecttypebuilder.hpp> #include "servicedirectory_p.hpp" #include "tcptransportsocket.hpp" namespace qi { ServiceDirectoryClient::ServiceDirectoryClient() : _remoteObject(qi::Message::Service_ServiceDirectory) , _addLink(0) , _removeLink(0) { _object = makeDynamicObjectPtr(&_remoteObject, false); } ServiceDirectoryClient::~ServiceDirectoryClient() { close(); } void ServiceDirectoryClient::onSDEventConnected(qi::Future<unsigned int> ret, qi::Future<unsigned int> fadd, qi::Future<unsigned int> frem, qi::Promise<bool> fco) { if (!fadd.isReady() || !frem.isReady()) return; if (fadd.hasError() || frem.hasError()) { std::string err; err = fadd.error(); if (!err.empty() && frem.hasError()) err += ". "; err += frem.error(); fco.setError(err); return; } _addLink = fadd.value(); _removeLink = frem.value(); fco.setValue(true); connected(); } void ServiceDirectoryClient::onMetaObjectFetched(qi::Future<void> future, qi::Promise<bool> promise) { if (future.hasError()) { promise.setError(future.error()); return; } boost::function<void (unsigned int, std::string)> f; //TODO: this should not be async f = boost::bind<void>(&ServiceDirectoryClient::onServiceAdded, this, _1, _2); qi::Future<unsigned int> fut1 = _object->connect("serviceAdded", f); f = boost::bind<void>(&ServiceDirectoryClient::onServiceRemoved, this, _1, _2); qi::Future<unsigned int> fut2 = _object->connect("serviceRemoved", f).async(); fut1.connect(boost::bind<void>(&ServiceDirectoryClient::onSDEventConnected, this, _1, fut1, fut2, promise)); fut2.connect(boost::bind<void>(&ServiceDirectoryClient::onSDEventConnected, this, _1, fut1, fut2, promise)); } void ServiceDirectoryClient::onSocketConnected(qi::FutureSync<bool> future, qi::Promise<bool> promise) { if (future.hasError()) { promise.setError(future.error()); return; } if (future.value() == false) { promise.setValue(false); return; } qi::Future<void> fut = _remoteObject.fetchMetaObject(); fut.connect(boost::bind<void>(&ServiceDirectoryClient::onMetaObjectFetched, this, _1, promise)); } //we ensure in that function that connect to all events are already setup when we said we are connect. //that way we cant be connected without being fully ready. qi::FutureSync<bool> ServiceDirectoryClient::connect(const qi::Url &serviceDirectoryURL) { if (isConnected()) { qiLogInfo("qi.Session") << "Session is already connected"; return qi::Future<bool>(false); } _sdSocket = qi::makeTransportSocket(serviceDirectoryURL.protocol()); if (!_sdSocket) return qi::Future<bool>(false); _sdSocketDisconnectedLink = _sdSocket->disconnected.connect(boost::bind<void>(&ServiceDirectoryClient::onSocketDisconnected, this, _1)); _remoteObject.setTransportSocket(_sdSocket); qi::Promise<bool> promise; qi::Future<bool> fut = _sdSocket->connect(serviceDirectoryURL); fut.connect(boost::bind<void>(&ServiceDirectoryClient::onSocketConnected, this, _1, promise)); return promise.future(); } static void sharedPtrHolder(TransportSocketPtr ptr) { } qi::FutureSync<void> ServiceDirectoryClient::close() { if (!_sdSocket) return qi::Future<void>(0); qi::Future<void> fut = _sdSocket->disconnect(); // Hold the socket shared ptr alive until the future returns. // otherwise, the destructor will block us until disconnect terminates fut.connect(boost::bind(&sharedPtrHolder, _sdSocket)); _sdSocket->disconnected.disconnect(_sdSocketDisconnectedLink); _sdSocket.reset(); return fut; } bool ServiceDirectoryClient::isConnected() const { return _sdSocket == 0 ? false : _sdSocket->isConnected(); } qi::Url ServiceDirectoryClient::url() const { return _sdSocket->url(); } void ServiceDirectoryClient::onServiceRemoved(unsigned int idx, const std::string &name) { qiLogVerbose("qi.ServiceDirectoryClient") << "ServiceDirectory: Service Removed #" << idx << ": " << name << std::endl; serviceRemoved(idx, name); } void ServiceDirectoryClient::onServiceAdded(unsigned int idx, const std::string &name) { qiLogVerbose("qi.ServiceDirectoryClient") << "ServiceDirectory: Service Added #" << idx << ": " << name << std::endl; serviceAdded(idx, name); } void ServiceDirectoryClient::onSocketDisconnected(int error) { disconnected(error); _object->disconnect(_addLink); _object->disconnect(_removeLink); } qi::Future< std::vector<ServiceInfo> > ServiceDirectoryClient::services() { return _object->call< std::vector<ServiceInfo> >("services"); } qi::Future<ServiceInfo> ServiceDirectoryClient::service(const std::string &name) { return _object->call< ServiceInfo >("service", name); } qi::Future<unsigned int> ServiceDirectoryClient::registerService(const ServiceInfo &svcinfo) { return _object->call< unsigned int >("registerService", svcinfo); } qi::Future<void> ServiceDirectoryClient::unregisterService(const unsigned int &idx) { return _object->call<void>("unregisterService", idx); } qi::Future<void> ServiceDirectoryClient::serviceReady(const unsigned int &idx) { return _object->call<void>("serviceReady", idx); } } <|endoftext|>
<commit_before>/** * @file /cost_map_visualisations/src/applications/service_relay.cpp */ /***************************************************************************** ** Includes *****************************************************************************/ #include <cstdlib> #include <ecl/command_line.hpp> #include <ros/ros.h> #include <cost_map.hpp> #include <cost_map_msgs/GetCostMap.h> #include <nav_msgs/OccupancyGrid.h> #include <string> /***************************************************************************** ** Main *****************************************************************************/ /** * Tunes into a cost map service and relays it as an Occupancy Grid. * * Mostly for demonstration/debugging purposes as you are usually * viewing a whole global costmap in rviz anyway. */ int main(int argc, char **argv) { /**************************************** ** Parsing ****************************************/ ecl::CmdLine cmd("Relays service provided cost maps to an occupancy grid publisher."); ecl::ValueArg<float> lengthArg("l","length","Length of a side of the costmap subwindow.", false, 2, "float", cmd); ecl::ValueArg<std::string> serviceNameArg("s","service_name","Service name to call.", false, "get_cost_map", "string", cmd); ecl::ValueArg<float> rateArg("r","rate","Rate at which to relay (hz).", false, 1, "float", cmd); ecl::ValueArg<std::string> layerNameArg("n","layer_name","Layer name to convert.", false, "obstacle_costs", "string", cmd); cmd.parse(argc, argv); /**************************************** ** Ros ****************************************/ ros::init(argc, argv, "cost_map_client"); ros::NodeHandle nodehandle("~"); bool persistent = true, latched = true; std::cout << "Looking up service: " << serviceNameArg.getValue() << std::endl; ros::ServiceClient get_cost_map = nodehandle.serviceClient<cost_map_msgs::GetCostMap>(serviceNameArg.getValue(), persistent); if ( !get_cost_map.waitForExistence(ros::Duration(3.0)) ) { ROS_ERROR_STREAM("Cost Map Service Relay : failed to find the GetCostMap service on " << nodehandle.resolveName(serviceNameArg.getValue(), true)); return EXIT_FAILURE; } ros::Publisher occupancy_grid_publisher = nodehandle.advertise<nav_msgs::OccupancyGrid>("occupancy_grid", 5, latched); /**************************************** ** Service Call/Relay Loop ****************************************/ cost_map_msgs::GetCostMap srv; srv.request.length_x = lengthArg.getValue(); srv.request.length_y = lengthArg.getValue(); std::string layer_name = layerNameArg.getValue(); ros::Rate rate(rateArg.getValue()); while ( ros::ok() ) { if (!get_cost_map.call(srv)) { ROS_ERROR_STREAM("Cost Map Service Relay : service call failed."); return EXIT_FAILURE; } nav_msgs::OccupancyGrid occupancy_grid_msg; cost_map::CostMap cost_map; cost_map::fromMessage(srv.response.map, cost_map); if ( cost_map.getLayers().size() == 1 ) { layer_name = cost_map.getLayers()[0]; } cost_map::toOccupancyGrid(cost_map, layer_name, occupancy_grid_msg); occupancy_grid_publisher.publish(occupancy_grid_msg); rate.sleep(); ros::spinOnce(); } return EXIT_SUCCESS; } <commit_msg>[cost_map] fix header reference<commit_after>/** * @file /cost_map_visualisations/src/applications/service_relay.cpp */ /***************************************************************************** ** Includes *****************************************************************************/ #include <cstdlib> #include <ecl/command_line.hpp> #include <ros/ros.h> #include <cost_map/cost_map.hpp> #include <cost_map_msgs/GetCostMap.h> #include <nav_msgs/OccupancyGrid.h> #include <string> /***************************************************************************** ** Main *****************************************************************************/ /** * Tunes into a cost map service and relays it as an Occupancy Grid. * * Mostly for demonstration/debugging purposes as you are usually * viewing a whole global costmap in rviz anyway. */ int main(int argc, char **argv) { /**************************************** ** Parsing ****************************************/ ecl::CmdLine cmd("Relays service provided cost maps to an occupancy grid publisher."); ecl::ValueArg<float> lengthArg("l","length","Length of a side of the costmap subwindow.", false, 2, "float", cmd); ecl::ValueArg<std::string> serviceNameArg("s","service_name","Service name to call.", false, "get_cost_map", "string", cmd); ecl::ValueArg<float> rateArg("r","rate","Rate at which to relay (hz).", false, 1, "float", cmd); ecl::ValueArg<std::string> layerNameArg("n","layer_name","Layer name to convert.", false, "obstacle_costs", "string", cmd); cmd.parse(argc, argv); /**************************************** ** Ros ****************************************/ ros::init(argc, argv, "cost_map_client"); ros::NodeHandle nodehandle("~"); bool persistent = true, latched = true; std::cout << "Looking up service: " << serviceNameArg.getValue() << std::endl; ros::ServiceClient get_cost_map = nodehandle.serviceClient<cost_map_msgs::GetCostMap>(serviceNameArg.getValue(), persistent); if ( !get_cost_map.waitForExistence(ros::Duration(3.0)) ) { ROS_ERROR_STREAM("Cost Map Service Relay : failed to find the GetCostMap service on " << nodehandle.resolveName(serviceNameArg.getValue(), true)); return EXIT_FAILURE; } ros::Publisher occupancy_grid_publisher = nodehandle.advertise<nav_msgs::OccupancyGrid>("occupancy_grid", 5, latched); /**************************************** ** Service Call/Relay Loop ****************************************/ cost_map_msgs::GetCostMap srv; srv.request.length_x = lengthArg.getValue(); srv.request.length_y = lengthArg.getValue(); std::string layer_name = layerNameArg.getValue(); ros::Rate rate(rateArg.getValue()); while ( ros::ok() ) { if (!get_cost_map.call(srv)) { ROS_ERROR_STREAM("Cost Map Service Relay : service call failed."); return EXIT_FAILURE; } nav_msgs::OccupancyGrid occupancy_grid_msg; cost_map::CostMap cost_map; cost_map::fromMessage(srv.response.map, cost_map); if ( cost_map.getLayers().size() == 1 ) { layer_name = cost_map.getLayers()[0]; } cost_map::toOccupancyGrid(cost_map, layer_name, occupancy_grid_msg); occupancy_grid_publisher.publish(occupancy_grid_msg); rate.sleep(); ros::spinOnce(); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "CAQrencode.h" #include "images/qrencode/qrencode.h" #include "platform/CADensityDpi.h" NS_CC_BEGIN CAImage* CAQrencode::createWithQRString(const std::string& string, unsigned int sideLength) { return CAQrencode::createWithQRString(string, sideLength, CAColor4B::WHITE, CAColor4B::BLACK); } CAImage* CAQrencode::createWithQRString(const std::string& string, unsigned int sideLength, const CAColor4B& backgroundColor) { return CAQrencode::createWithQRString(string, sideLength, backgroundColor, CAColor4B::BLACK); } #define PRINT_QRCODE(code, FUNC) for(int i = 0; i < code->width; ++i){for(int j = 0; j < code->width; ++j){if (code->data[j + i * code->width] & 1){FUNC(i, j);}}} CAImage* CAQrencode::createWithQRString(const std::string& string, unsigned int sideLength, const CAColor4B& backgroundColor, const CAColor4B& qrColor) { QRcode *code = QRcode_encodeString(string.c_str(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); float side = CrossApp::s_dip_to_px(1) > 1 ? CrossApp::s_dip_to_px(sideLength) : sideLength; int scale = std::ceil(side / code->width); int off = 0; int width = (code->width + off * 2) * scale; ssize_t length = width * width * 4; unsigned char* data = (unsigned char*)malloc(sizeof(unsigned char) * (length + 1)); for (ssize_t i = 0; i < length / 4; ++i) { data[i * 4 + 0] = backgroundColor.r; //R data[i * 4 + 1] = backgroundColor.g; //G data[i * 4 + 2] = backgroundColor.b; //B data[i * 4 + 3] = backgroundColor.a; //A } data[length] = '\0'; std::function<void(int i, int j)> func; if (qrColor.a != backgroundColor.a) { func = [&](int i, int j) { int h = 0, w = 0; do { unsigned long index = (w + (j + off) * scale) + (h + (i + off) * scale) * width; data[index * 4 + 0] = qrColor.r; //R data[index * 4 + 1] = qrColor.g; //G data[index * 4 + 2] = qrColor.b; //B data[index * 4 + 3] = qrColor.a; //A if (++w == scale) ++h, w = 0; if (h == scale) break;; } while (1); }; } else { func = [&](int i, int j) { int h = 0, w = 0; do { unsigned long index = (w + (j + off) * scale) + (h + (i + off) * scale) * width; data[index * 4 + 0] = qrColor.r; //R data[index * 4 + 1] = qrColor.g; //G data[index * 4 + 2] = qrColor.b; //B if (++w == scale) ++h, w = 0; if (h == scale) break;; } while (1); }; } PRINT_QRCODE(code, func); QRcode_free(code); CrossApp::CAData* ca_data = CrossApp::CAData::create(); ca_data->fastSet(data, length); return CAImage::createWithRawDataNoCache(ca_data, CAImage::PixelFormat::RGBA8888, width, width); } NS_CC_END <commit_msg>no message<commit_after>#include "CAQrencode.h" #include "images/qrencode/qrencode.h" #include "platform/CADensityDpi.h" NS_CC_BEGIN CAImage* CAQrencode::createWithQRString(const std::string& string, unsigned int sideLength) { return CAQrencode::createWithQRString(string, sideLength, CAColor4B::WHITE, CAColor4B::BLACK); } CAImage* CAQrencode::createWithQRString(const std::string& string, unsigned int sideLength, const CAColor4B& backgroundColor) { return CAQrencode::createWithQRString(string, sideLength, backgroundColor, CAColor4B::BLACK); } inline void QRcode_print(QRcode* code, const std::function<void(int i, int j)>& func) { int i = 0, j = 0; do { int index = j + i * code->width; if (code->data[index] & 1) func(i, j); if (++j == code->width) ++i, j = 0; if (i == code->width) break; } while (1); } CAImage* CAQrencode::createWithQRString(const std::string& string, unsigned int sideLength, const CAColor4B& backgroundColor, const CAColor4B& qrColor) { QRcode *code = QRcode_encodeString(string.c_str(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); float side = CrossApp::s_dip_to_px(1) > 1 ? CrossApp::s_dip_to_px(sideLength) : sideLength; int scale = std::ceil(side / code->width); int off = 0; int width = (code->width + off * 2) * scale; ssize_t length = width * width * 4; unsigned char* data = (unsigned char*)malloc(sizeof(unsigned char) * (length + 1)); for (ssize_t i = 0; i < length / 4; ++i) { data[i * 4 + 0] = backgroundColor.r; //R data[i * 4 + 1] = backgroundColor.g; //G data[i * 4 + 2] = backgroundColor.b; //B data[i * 4 + 3] = backgroundColor.a; //A } data[length] = '\0'; std::function<void(int i, int j)> func; if (qrColor.a != backgroundColor.a) { func = [&](int i, int j) { int h = 0, w = 0; do { unsigned long index = (w + (j + off) * scale) + (h + (i + off) * scale) * width; data[index * 4 + 0] = qrColor.r; //R data[index * 4 + 1] = qrColor.g; //G data[index * 4 + 2] = qrColor.b; //B data[index * 4 + 3] = qrColor.a; //A if (++w == scale) ++h, w = 0; if (h == scale) break;; } while (1); }; } else { func = [&](int i, int j) { int h = 0, w = 0; do { unsigned long index = (w + (j + off) * scale) + (h + (i + off) * scale) * width; data[index * 4 + 0] = qrColor.r; //R data[index * 4 + 1] = qrColor.g; //G data[index * 4 + 2] = qrColor.b; //B if (++w == scale) ++h, w = 0; if (h == scale) break; } while (1); }; } QRcode_print(code, func); QRcode_free(code); CrossApp::CAData* ca_data = CrossApp::CAData::create(); ca_data->fastSet(data, length); return CAImage::createWithRawDataNoCache(ca_data, CAImage::PixelFormat::RGBA8888, width, width); } NS_CC_END <|endoftext|>
<commit_before>/****************************************************************************** This source file is part of the tomviz project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "ExportDataReaction.h" #include <pqActiveObjects.h> #include <pqCoreUtilities.h> #include <pqProxyWidgetDialog.h> #include <vtkDataArray.h> #include <vtkImageData.h> #include <vtkNew.h> #include <vtkPointData.h> #include <vtkSMProxyManager.h> #include <vtkSMSessionProxyManager.h> #include <vtkSMWriterFactory.h> #include <vtkSmartPointer.h> #include <vtkTIFFWriter.h> #include <vtkTrivialProducer.h> #include <vtkUnsignedCharArray.h> #include "ActiveObjects.h" #include "ConvertToFloatOperator.h" #include "EmdFormat.h" #include "Module.h" #include "Utilities.h" #include <QDebug> #include <QDialog> #include <QFileDialog> #include <QFileInfo> #include <QRegularExpression> namespace tomviz { ExportDataReaction::ExportDataReaction(QAction* parentAction, Module* module) : pqReaction(parentAction), m_module(module) { connect(&ActiveObjects::instance(), SIGNAL(moduleChanged(Module*)), SLOT(updateEnableState())); updateEnableState(); } void ExportDataReaction::updateEnableState() { if (!m_module) { parentAction()->setEnabled(ActiveObjects::instance().activeModule() != nullptr); } else { parentAction()->setEnabled(true); } } void ExportDataReaction::onTriggered() { Module* module = m_module; if (!module) { module = ActiveObjects::instance().activeModule(); } if (!module) { return; } QString exportType = module->exportDataTypeString(); QStringList filters; if (exportType == "Volume") { filters << "TIFF format (*.tiff)" << "EMD format (*.emd *.hdf5)" << "CSV File (*.csv)" << "Exodus II File (*.e *.ex2 *.ex2v2 *.exo *.exoII *.exoii *.g)" << "Legacy VTK Files (*.vtk)" << "Meta Image Files (*.mhd)" << "ParaView Data Files (*.pvd)" << "VTK ImageData Files (*.vti)" << "XDMF Data File (*.xmf)" << "JSON Image Files (*.json)"; } else if (exportType == "Mesh") { filters << "STL Files (*.stl)" << "VTK PolyData files(*.vtp)"; } else if (exportType == "Image") { filters << "PNG Files (*.png)" << "JPEG Files (*.jpg *.jpeg)" << "TIFF Files (*.tiff)" << "VTK ImageData Files (*.vti)"; } QFileDialog dialog(nullptr); dialog.setFileMode(QFileDialog::AnyFile); dialog.setNameFilters(filters); dialog.setObjectName("FileOpenDialog-tomviz"); // avoid name collision? dialog.setAcceptMode(QFileDialog::AcceptSave); if (dialog.exec() == QDialog::Accepted) { QStringList filenames = dialog.selectedFiles(); QString format = dialog.selectedNameFilter(); QString filename = filenames[0]; int startPos = format.indexOf("(") + 1; int n = format.indexOf(")") - startPos; QString extensionString = format.mid(startPos, n); QStringList extensions = extensionString.split(QRegularExpression(" ?\\*"), QString::SkipEmptyParts); bool hasExtension = false; for (QString& str : extensions) { if (filename.endsWith(str)) { hasExtension = true; } } if (!hasExtension) { filename = QString("%1%2").arg(filename, extensions[0]); } exportData(filename); } } namespace { template <typename FromType, typename ToType> void convert(vtkDataArray* outArray, int nComps, int nTuples, void* data) { FromType* d = static_cast<FromType*>(data); ToType* a = static_cast<ToType*>(outArray->GetVoidPointer(0)); for (int i = 0; i < nComps * nTuples; ++i) { a[i] = static_cast<ToType>(d[i]); } } template <typename FromType> void convertToUnsignedChar(vtkDataArray* outArray, int nComps, int nTuples, void* data) { convert<FromType, unsigned char>(outArray, nComps, nTuples, data); } } bool ExportDataReaction::exportData(const QString& filename) { auto server = pqActiveObjects::instance().activeServer(); vtkSmartPointer<vtkDataObject> data = this->m_module->getDataToExport(); if (!server) { qCritical("No active server located."); return false; } QFileInfo info(filename); if (info.suffix() == "emd") { EmdFormat writer; auto image = vtkImageData::SafeDownCast(data); if (!image || !writer.write(filename.toLatin1().data(), image)) { qCritical() << "Failed to write out data."; return false; } else { return true; } } auto writerFactory = vtkSMProxyManager::GetProxyManager()->GetWriterFactory(); vtkSMSessionProxyManager* pxm = vtkSMProxyManager::GetProxyManager()->GetActiveSessionProxyManager(); vtkSmartPointer<vtkSMSourceProxy> producer; producer.TakeReference(vtkSMSourceProxy::SafeDownCast( pxm->NewProxy("sources", "TrivialProducer"))); vtkSmartPointer<vtkTrivialProducer> trivialProducer = vtkTrivialProducer::SafeDownCast(producer->GetClientSideObject()); trivialProducer->SetOutput(data); trivialProducer->UpdateInformation(); trivialProducer->Update(); producer->UpdatePipeline(); vtkSmartPointer<vtkSMProxy> proxy; proxy.TakeReference( writerFactory->CreateWriter(filename.toLatin1().data(), producer)); auto writer = vtkSMSourceProxy::SafeDownCast(proxy); if (!writer) { qCritical() << "Failed to create writer for: " << filename; return false; } // Convert to a data format the file type supports const char* writerName = writer->GetClientSideObject()->GetClassName(); auto imageData = vtkImageData::SafeDownCast(trivialProducer->GetOutputDataObject(0)); auto imageType = imageData->GetPointData()->GetScalars()->GetDataType(); if (strcmp(writerName, "vtkTIFFWriter") == 0 && imageType == VTK_DOUBLE) { vtkNew<vtkImageData> fImage; fImage->DeepCopy(imageData); ConvertToFloatOperator convertFloat; convertFloat.applyTransform(fImage); trivialProducer->SetOutput(fImage.Get()); trivialProducer->UpdateInformation(); trivialProducer->Update(); producer->UpdatePipeline(); } if ((strcmp(writerName, "vtkPNGWriter") == 0 && (imageType != VTK_UNSIGNED_CHAR || imageType != VTK_UNSIGNED_SHORT)) || (strcmp(writerName, "vtkJPEGWriter") == 0 && imageType != VTK_UNSIGNED_CHAR)) { std::cout << "File type does not support the current data type, converting " "to unsigned char" << std::endl; vtkNew<vtkImageData> newImage; newImage->DeepCopy(imageData); vtkDataArray* scalars = imageData->GetPointData()->GetScalars(); double range[2]; scalars->GetRange(range); vtkNew<vtkUnsignedCharArray> charArray; charArray->SetNumberOfComponents(scalars->GetNumberOfComponents()); charArray->SetNumberOfTuples(scalars->GetNumberOfTuples()); charArray->SetName(scalars->GetName()); switch (scalars->GetDataType()) { vtkTemplateMacro(convertToUnsignedChar<VTK_TT>( charArray.Get(), scalars->GetNumberOfComponents(), scalars->GetNumberOfTuples(), scalars->GetVoidPointer(0))); } newImage->GetPointData()->RemoveArray(scalars->GetName()); newImage->GetPointData()->SetScalars(charArray.Get()); trivialProducer->SetOutput(newImage.Get()); trivialProducer->UpdateInformation(); trivialProducer->Update(); producer->UpdatePipeline(); } pqProxyWidgetDialog dialog(writer, pqCoreUtilities::mainWidget()); dialog.setObjectName("WriterSettingsDialog"); dialog.setEnableSearchBar(true); dialog.setWindowTitle( QString("Configure Writer (%1)").arg(writer->GetXMLLabel())); // Check to see if this writer has any properties that can be configured by // the user. If it does, display the dialog. if (dialog.hasVisibleWidgets()) { dialog.exec(); if (dialog.result() == QDialog::Rejected) { // The user pressed Cancel so don't write return false; } } writer->UpdateVTKObjects(); writer->UpdatePipeline(); return true; } } <commit_msg>Rescale normalized floating point when converting to unsigned char<commit_after>/****************************************************************************** This source file is part of the tomviz project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "ExportDataReaction.h" #include <pqActiveObjects.h> #include <pqCoreUtilities.h> #include <pqProxyWidgetDialog.h> #include <vtkArrayCalculator.h> #include <vtkDataArray.h> #include <vtkImageData.h> #include <vtkNew.h> #include <vtkPointData.h> #include <vtkSMProxyManager.h> #include <vtkSMSessionProxyManager.h> #include <vtkSMWriterFactory.h> #include <vtkSmartPointer.h> #include <vtkTIFFWriter.h> #include <vtkTrivialProducer.h> #include <vtkUnsignedCharArray.h> #include "ActiveObjects.h" #include "ConvertToFloatOperator.h" #include "EmdFormat.h" #include "Module.h" #include "Utilities.h" #include <QDebug> #include <QDialog> #include <QFileDialog> #include <QFileInfo> #include <QRegularExpression> namespace tomviz { ExportDataReaction::ExportDataReaction(QAction* parentAction, Module* module) : pqReaction(parentAction), m_module(module) { connect(&ActiveObjects::instance(), SIGNAL(moduleChanged(Module*)), SLOT(updateEnableState())); updateEnableState(); } void ExportDataReaction::updateEnableState() { if (!m_module) { parentAction()->setEnabled(ActiveObjects::instance().activeModule() != nullptr); } else { parentAction()->setEnabled(true); } } void ExportDataReaction::onTriggered() { Module* module = m_module; if (!module) { module = ActiveObjects::instance().activeModule(); } if (!module) { return; } QString exportType = module->exportDataTypeString(); QStringList filters; if (exportType == "Volume") { filters << "TIFF format (*.tiff)" << "EMD format (*.emd *.hdf5)" << "CSV File (*.csv)" << "Exodus II File (*.e *.ex2 *.ex2v2 *.exo *.exoII *.exoii *.g)" << "Legacy VTK Files (*.vtk)" << "Meta Image Files (*.mhd)" << "ParaView Data Files (*.pvd)" << "VTK ImageData Files (*.vti)" << "XDMF Data File (*.xmf)" << "JSON Image Files (*.json)"; } else if (exportType == "Mesh") { filters << "STL Files (*.stl)" << "VTK PolyData files(*.vtp)"; } else if (exportType == "Image") { filters << "PNG Files (*.png)" << "JPEG Files (*.jpg *.jpeg)" << "TIFF Files (*.tiff)" << "VTK ImageData Files (*.vti)"; } QFileDialog dialog(nullptr); dialog.setFileMode(QFileDialog::AnyFile); dialog.setNameFilters(filters); dialog.setObjectName("FileOpenDialog-tomviz"); // avoid name collision? dialog.setAcceptMode(QFileDialog::AcceptSave); if (dialog.exec() == QDialog::Accepted) { QStringList filenames = dialog.selectedFiles(); QString format = dialog.selectedNameFilter(); QString filename = filenames[0]; int startPos = format.indexOf("(") + 1; int n = format.indexOf(")") - startPos; QString extensionString = format.mid(startPos, n); QStringList extensions = extensionString.split(QRegularExpression(" ?\\*"), QString::SkipEmptyParts); bool hasExtension = false; for (QString& str : extensions) { if (filename.endsWith(str)) { hasExtension = true; } } if (!hasExtension) { filename = QString("%1%2").arg(filename, extensions[0]); } exportData(filename); } } namespace { template <typename FromType, typename ToType> void convert(vtkDataArray* outArray, int nComps, int nTuples, void* data) { FromType* d = static_cast<FromType*>(data); ToType* a = static_cast<ToType*>(outArray->GetVoidPointer(0)); for (int i = 0; i < nComps * nTuples; ++i) { a[i] = static_cast<ToType>(d[i]); } } template <typename FromType> void convertToUnsignedChar(vtkDataArray* outArray, int nComps, int nTuples, void* data) { convert<FromType, unsigned char>(outArray, nComps, nTuples, data); } } bool ExportDataReaction::exportData(const QString& filename) { auto server = pqActiveObjects::instance().activeServer(); vtkSmartPointer<vtkDataObject> data = this->m_module->getDataToExport(); if (!server) { qCritical("No active server located."); return false; } QFileInfo info(filename); if (info.suffix() == "emd") { EmdFormat writer; auto image = vtkImageData::SafeDownCast(data); if (!image || !writer.write(filename.toLatin1().data(), image)) { qCritical() << "Failed to write out data."; return false; } else { return true; } } auto writerFactory = vtkSMProxyManager::GetProxyManager()->GetWriterFactory(); vtkSMSessionProxyManager* pxm = vtkSMProxyManager::GetProxyManager()->GetActiveSessionProxyManager(); vtkSmartPointer<vtkSMSourceProxy> producer; producer.TakeReference(vtkSMSourceProxy::SafeDownCast( pxm->NewProxy("sources", "TrivialProducer"))); vtkSmartPointer<vtkTrivialProducer> trivialProducer = vtkTrivialProducer::SafeDownCast(producer->GetClientSideObject()); trivialProducer->SetOutput(data); trivialProducer->UpdateInformation(); trivialProducer->Update(); producer->UpdatePipeline(); vtkSmartPointer<vtkSMProxy> proxy; proxy.TakeReference( writerFactory->CreateWriter(filename.toLatin1().data(), producer)); auto writer = vtkSMSourceProxy::SafeDownCast(proxy); if (!writer) { qCritical() << "Failed to create writer for: " << filename; return false; } // Convert to a data format the file type supports const char* writerName = writer->GetClientSideObject()->GetClassName(); auto imageData = vtkImageData::SafeDownCast(trivialProducer->GetOutputDataObject(0)); auto imageType = imageData->GetPointData()->GetScalars()->GetDataType(); if (strcmp(writerName, "vtkTIFFWriter") == 0 && imageType == VTK_DOUBLE) { vtkNew<vtkImageData> fImage; fImage->DeepCopy(imageData); ConvertToFloatOperator convertFloat; convertFloat.applyTransform(fImage); trivialProducer->SetOutput(fImage.Get()); trivialProducer->UpdateInformation(); trivialProducer->Update(); producer->UpdatePipeline(); } if ((strcmp(writerName, "vtkPNGWriter") == 0 && (imageType != VTK_UNSIGNED_CHAR || imageType != VTK_UNSIGNED_SHORT)) || (strcmp(writerName, "vtkJPEGWriter") == 0 && imageType != VTK_UNSIGNED_CHAR)) { std::cout << "File type does not support the current data type, converting " "to unsigned char" << std::endl; vtkNew<vtkImageData> newImage; newImage->DeepCopy(imageData); vtkSmartPointer<vtkDataArray> scalars = imageData->GetPointData()->GetScalars(); double range[2]; scalars->GetRange(range); if ((imageType == VTK_FLOAT || imageType == VTK_DOUBLE) && (range[0] >= 0 && range[1] <= 1)) { std::cout << "Converting normalized floating point values to integers in " "the range 0-255." << std::endl; vtkNew<vtkArrayCalculator> calc; calc->AddScalarVariable("scalars", scalars->GetName()); calc->SetFunction("floor(scalars*255 + 0.5)"); calc->SetResultArrayName("result"); calc->SetInputData(imageData); calc->Update(); scalars = calc->GetDataSetOutput()->GetPointData()->GetArray("result"); scalars->GetRange(range); } vtkNew<vtkUnsignedCharArray> charArray; charArray->SetNumberOfComponents(scalars->GetNumberOfComponents()); charArray->SetNumberOfTuples(scalars->GetNumberOfTuples()); charArray->SetName(scalars->GetName()); switch (scalars->GetDataType()) { vtkTemplateMacro(convertToUnsignedChar<VTK_TT>( charArray.Get(), scalars->GetNumberOfComponents(), scalars->GetNumberOfTuples(), scalars->GetVoidPointer(0))); } newImage->GetPointData()->RemoveArray(scalars->GetName()); newImage->GetPointData()->SetScalars(charArray.Get()); trivialProducer->SetOutput(newImage.Get()); trivialProducer->UpdateInformation(); trivialProducer->Update(); producer->UpdatePipeline(); } pqProxyWidgetDialog dialog(writer, pqCoreUtilities::mainWidget()); dialog.setObjectName("WriterSettingsDialog"); dialog.setEnableSearchBar(true); dialog.setWindowTitle( QString("Configure Writer (%1)").arg(writer->GetXMLLabel())); // Check to see if this writer has any properties that can be configured by // the user. If it does, display the dialog. if (dialog.hasVisibleWidgets()) { dialog.exec(); if (dialog.result() == QDialog::Rejected) { // The user pressed Cancel so don't write return false; } } writer->UpdateVTKObjects(); writer->UpdatePipeline(); return true; } } <|endoftext|>
<commit_before>//===-- sanitizer_win.cc --------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is shared between AddressSanitizer and ThreadSanitizer // run-time libraries and implements windows-specific functions from // sanitizer_libc.h. //===----------------------------------------------------------------------===// #include "sanitizer_platform.h" #if SANITIZER_WINDOWS #define WIN32_LEAN_AND_MEAN #define NOGDI #include <stdlib.h> #include <io.h> #include <windows.h> #include "sanitizer_common.h" #include "sanitizer_libc.h" #include "sanitizer_mutex.h" #include "sanitizer_placement_new.h" #include "sanitizer_stacktrace.h" namespace __sanitizer { #include "sanitizer_syscall_generic.inc" // --------------------- sanitizer_common.h uptr GetPageSize() { return 1U << 14; // FIXME: is this configurable? } uptr GetMmapGranularity() { return 1U << 16; // FIXME: is this configurable? } bool FileExists(const char *filename) { UNIMPLEMENTED(); } uptr internal_getpid() { return GetProcessId(GetCurrentProcess()); } // In contrast to POSIX, on Windows GetCurrentThreadId() // returns a system-unique identifier. uptr GetTid() { return GetCurrentThreadId(); } uptr GetThreadSelf() { return GetTid(); } void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top, uptr *stack_bottom) { CHECK(stack_top); CHECK(stack_bottom); MEMORY_BASIC_INFORMATION mbi; CHECK_NE(VirtualQuery(&mbi /* on stack */, &mbi, sizeof(mbi)), 0); // FIXME: is it possible for the stack to not be a single allocation? // Are these values what ASan expects to get (reserved, not committed; // including stack guard page) ? *stack_top = (uptr)mbi.BaseAddress + mbi.RegionSize; *stack_bottom = (uptr)mbi.AllocationBase; } void *MmapOrDie(uptr size, const char *mem_type) { void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (rv == 0) { Report("ERROR: Failed to allocate 0x%zx (%zd) bytes of %s\n", size, size, mem_type); CHECK("unable to mmap" && 0); } return rv; } void UnmapOrDie(void *addr, uptr size) { if (VirtualFree(addr, size, MEM_DECOMMIT) == 0) { Report("ERROR: Failed to deallocate 0x%zx (%zd) bytes at address %p\n", size, size, addr); CHECK("unable to unmap" && 0); } } void *MmapFixedNoReserve(uptr fixed_addr, uptr size) { // FIXME: is this really "NoReserve"? On Win32 this does not matter much, // but on Win64 it does. void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (p == 0) Report("ERROR: Failed to allocate 0x%zx (%zd) bytes at %p (%d)\n", size, size, fixed_addr, GetLastError()); return p; } void *MmapFixedOrDie(uptr fixed_addr, uptr size) { return MmapFixedNoReserve(fixed_addr, size); } void *Mprotect(uptr fixed_addr, uptr size) { return VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE | MEM_COMMIT, PAGE_NOACCESS); } void FlushUnneededShadowMemory(uptr addr, uptr size) { // This is almost useless on 32-bits. // FIXME: add madvice-analog when we move to 64-bits. } bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) { // FIXME: shall we do anything here on Windows? return true; } void *MapFileToMemory(const char *file_name, uptr *buff_size) { UNIMPLEMENTED(); } static const int kMaxEnvNameLength = 128; static const DWORD kMaxEnvValueLength = 32767; namespace { struct EnvVariable { char name[kMaxEnvNameLength]; char value[kMaxEnvValueLength]; }; } // namespace static const int kEnvVariables = 5; static EnvVariable env_vars[kEnvVariables]; static int num_env_vars; const char *GetEnv(const char *name) { // Note: this implementation caches the values of the environment variables // and limits their quantity. for (int i = 0; i < num_env_vars; i++) { if (0 == internal_strcmp(name, env_vars[i].name)) return env_vars[i].value; } CHECK_LT(num_env_vars, kEnvVariables); DWORD rv = GetEnvironmentVariableA(name, env_vars[num_env_vars].value, kMaxEnvValueLength); if (rv > 0 && rv < kMaxEnvValueLength) { CHECK_LT(internal_strlen(name), kMaxEnvNameLength); internal_strncpy(env_vars[num_env_vars].name, name, kMaxEnvNameLength); num_env_vars++; return env_vars[num_env_vars - 1].value; } return 0; } const char *GetPwd() { UNIMPLEMENTED(); } u32 GetUid() { UNIMPLEMENTED(); } void DumpProcessMap() { UNIMPLEMENTED(); } void DisableCoreDumper() { UNIMPLEMENTED(); } void ReExec() { UNIMPLEMENTED(); } void PrepareForSandboxing() { // Nothing here for now. } bool StackSizeIsUnlimited() { UNIMPLEMENTED(); } void SetStackSizeLimitInBytes(uptr limit) { UNIMPLEMENTED(); } void SleepForSeconds(int seconds) { Sleep(seconds * 1000); } void SleepForMillis(int millis) { Sleep(millis); } u64 NanoTime() { return 0; } u64 NanoTime() { return 0; } void Abort() { abort(); _exit(-1); // abort is not NORETURN on Windows. } #ifndef SANITIZER_GO int Atexit(void (*function)(void)) { return atexit(function); } #endif // ------------------ sanitizer_libc.h uptr internal_mmap(void *addr, uptr length, int prot, int flags, int fd, u64 offset) { UNIMPLEMENTED(); } uptr internal_munmap(void *addr, uptr length) { UNIMPLEMENTED(); } uptr internal_close(fd_t fd) { UNIMPLEMENTED(); } int internal_isatty(fd_t fd) { return _isatty(fd); } uptr internal_open(const char *filename, int flags) { UNIMPLEMENTED(); } uptr internal_open(const char *filename, int flags, u32 mode) { UNIMPLEMENTED(); } uptr OpenFile(const char *filename, bool write) { UNIMPLEMENTED(); } uptr internal_read(fd_t fd, void *buf, uptr count) { UNIMPLEMENTED(); } uptr internal_write(fd_t fd, const void *buf, uptr count) { if (fd != kStderrFd) UNIMPLEMENTED(); HANDLE err = GetStdHandle(STD_ERROR_HANDLE); if (err == 0) return 0; // FIXME: this might not work on some apps. DWORD ret; if (!WriteFile(err, buf, count, &ret, 0)) return 0; return ret; } uptr internal_stat(const char *path, void *buf) { UNIMPLEMENTED(); } uptr internal_lstat(const char *path, void *buf) { UNIMPLEMENTED(); } uptr internal_fstat(fd_t fd, void *buf) { UNIMPLEMENTED(); } uptr internal_filesize(fd_t fd) { UNIMPLEMENTED(); } uptr internal_dup2(int oldfd, int newfd) { UNIMPLEMENTED(); } uptr internal_readlink(const char *path, char *buf, uptr bufsize) { UNIMPLEMENTED(); } uptr internal_sched_yield() { Sleep(0); return 0; } void internal__exit(int exitcode) { _exit(exitcode); } // ---------------------- BlockingMutex ---------------- {{{1 const uptr LOCK_UNINITIALIZED = 0; const uptr LOCK_READY = (uptr)-1; BlockingMutex::BlockingMutex(LinkerInitialized li) { // FIXME: see comments in BlockingMutex::Lock() for the details. CHECK(li == LINKER_INITIALIZED || owner_ == LOCK_UNINITIALIZED); CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_)); InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_); owner_ = LOCK_READY; } BlockingMutex::BlockingMutex() { CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_)); InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_); owner_ = LOCK_READY; } void BlockingMutex::Lock() { if (owner_ == LOCK_UNINITIALIZED) { // FIXME: hm, global BlockingMutex objects are not initialized?!? // This might be a side effect of the clang+cl+link Frankenbuild... new(this) BlockingMutex((LinkerInitialized)(LINKER_INITIALIZED + 1)); // FIXME: If it turns out the linker doesn't invoke our // constructors, we should probably manually Lock/Unlock all the global // locks while we're starting in one thread to avoid double-init races. } EnterCriticalSection((LPCRITICAL_SECTION)opaque_storage_); CHECK_EQ(owner_, LOCK_READY); owner_ = GetThreadSelf(); } void BlockingMutex::Unlock() { CHECK_EQ(owner_, GetThreadSelf()); owner_ = LOCK_READY; LeaveCriticalSection((LPCRITICAL_SECTION)opaque_storage_); } void BlockingMutex::CheckLocked() { CHECK_EQ(owner_, GetThreadSelf()); } uptr GetTlsSize() { return 0; } void InitTlsSize() { } void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size, uptr *tls_addr, uptr *tls_size) { #ifdef SANITIZER_GO *stk_addr = 0; *stk_size = 0; *tls_addr = 0; *tls_size = 0; #else uptr stack_top, stack_bottom; GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom); *stk_addr = stack_bottom; *stk_size = stack_top - stack_bottom; *tls_addr = 0; *tls_size = 0; #endif } void GetStackTrace(StackTrace *stack, uptr max_s, uptr pc, uptr bp, uptr stack_top, uptr stack_bottom, bool fast) { (void)fast; (void)stack_top; (void)stack_bottom; stack->max_size = max_s; void *tmp[kStackTraceMax]; // FIXME: CaptureStackBackTrace might be too slow for us. // FIXME: Compare with StackWalk64. // FIXME: Look at LLVMUnhandledExceptionFilter in Signals.inc uptr cs_ret = CaptureStackBackTrace(1, stack->max_size, tmp, 0); uptr offset = 0; // Skip the RTL frames by searching for the PC in the stacktrace. // FIXME: this doesn't work well for the malloc/free stacks yet. for (uptr i = 0; i < cs_ret; i++) { if (pc != (uptr)tmp[i]) continue; offset = i; break; } stack->size = cs_ret - offset; for (uptr i = 0; i < stack->size; i++) stack->trace[i] = (uptr)tmp[i + offset]; } } // namespace __sanitizer #endif // _WIN32 <commit_msg>tsan: fix merge bug<commit_after>//===-- sanitizer_win.cc --------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is shared between AddressSanitizer and ThreadSanitizer // run-time libraries and implements windows-specific functions from // sanitizer_libc.h. //===----------------------------------------------------------------------===// #include "sanitizer_platform.h" #if SANITIZER_WINDOWS #define WIN32_LEAN_AND_MEAN #define NOGDI #include <stdlib.h> #include <io.h> #include <windows.h> #include "sanitizer_common.h" #include "sanitizer_libc.h" #include "sanitizer_mutex.h" #include "sanitizer_placement_new.h" #include "sanitizer_stacktrace.h" namespace __sanitizer { #include "sanitizer_syscall_generic.inc" // --------------------- sanitizer_common.h uptr GetPageSize() { return 1U << 14; // FIXME: is this configurable? } uptr GetMmapGranularity() { return 1U << 16; // FIXME: is this configurable? } bool FileExists(const char *filename) { UNIMPLEMENTED(); } uptr internal_getpid() { return GetProcessId(GetCurrentProcess()); } // In contrast to POSIX, on Windows GetCurrentThreadId() // returns a system-unique identifier. uptr GetTid() { return GetCurrentThreadId(); } uptr GetThreadSelf() { return GetTid(); } void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top, uptr *stack_bottom) { CHECK(stack_top); CHECK(stack_bottom); MEMORY_BASIC_INFORMATION mbi; CHECK_NE(VirtualQuery(&mbi /* on stack */, &mbi, sizeof(mbi)), 0); // FIXME: is it possible for the stack to not be a single allocation? // Are these values what ASan expects to get (reserved, not committed; // including stack guard page) ? *stack_top = (uptr)mbi.BaseAddress + mbi.RegionSize; *stack_bottom = (uptr)mbi.AllocationBase; } void *MmapOrDie(uptr size, const char *mem_type) { void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (rv == 0) { Report("ERROR: Failed to allocate 0x%zx (%zd) bytes of %s\n", size, size, mem_type); CHECK("unable to mmap" && 0); } return rv; } void UnmapOrDie(void *addr, uptr size) { if (VirtualFree(addr, size, MEM_DECOMMIT) == 0) { Report("ERROR: Failed to deallocate 0x%zx (%zd) bytes at address %p\n", size, size, addr); CHECK("unable to unmap" && 0); } } void *MmapFixedNoReserve(uptr fixed_addr, uptr size) { // FIXME: is this really "NoReserve"? On Win32 this does not matter much, // but on Win64 it does. void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (p == 0) Report("ERROR: Failed to allocate 0x%zx (%zd) bytes at %p (%d)\n", size, size, fixed_addr, GetLastError()); return p; } void *MmapFixedOrDie(uptr fixed_addr, uptr size) { return MmapFixedNoReserve(fixed_addr, size); } void *Mprotect(uptr fixed_addr, uptr size) { return VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE | MEM_COMMIT, PAGE_NOACCESS); } void FlushUnneededShadowMemory(uptr addr, uptr size) { // This is almost useless on 32-bits. // FIXME: add madvice-analog when we move to 64-bits. } bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) { // FIXME: shall we do anything here on Windows? return true; } void *MapFileToMemory(const char *file_name, uptr *buff_size) { UNIMPLEMENTED(); } static const int kMaxEnvNameLength = 128; static const DWORD kMaxEnvValueLength = 32767; namespace { struct EnvVariable { char name[kMaxEnvNameLength]; char value[kMaxEnvValueLength]; }; } // namespace static const int kEnvVariables = 5; static EnvVariable env_vars[kEnvVariables]; static int num_env_vars; const char *GetEnv(const char *name) { // Note: this implementation caches the values of the environment variables // and limits their quantity. for (int i = 0; i < num_env_vars; i++) { if (0 == internal_strcmp(name, env_vars[i].name)) return env_vars[i].value; } CHECK_LT(num_env_vars, kEnvVariables); DWORD rv = GetEnvironmentVariableA(name, env_vars[num_env_vars].value, kMaxEnvValueLength); if (rv > 0 && rv < kMaxEnvValueLength) { CHECK_LT(internal_strlen(name), kMaxEnvNameLength); internal_strncpy(env_vars[num_env_vars].name, name, kMaxEnvNameLength); num_env_vars++; return env_vars[num_env_vars - 1].value; } return 0; } const char *GetPwd() { UNIMPLEMENTED(); } u32 GetUid() { UNIMPLEMENTED(); } void DumpProcessMap() { UNIMPLEMENTED(); } void DisableCoreDumper() { UNIMPLEMENTED(); } void ReExec() { UNIMPLEMENTED(); } void PrepareForSandboxing() { // Nothing here for now. } bool StackSizeIsUnlimited() { UNIMPLEMENTED(); } void SetStackSizeLimitInBytes(uptr limit) { UNIMPLEMENTED(); } void SleepForSeconds(int seconds) { Sleep(seconds * 1000); } void SleepForMillis(int millis) { Sleep(millis); } u64 NanoTime() { return 0; } void Abort() { abort(); _exit(-1); // abort is not NORETURN on Windows. } #ifndef SANITIZER_GO int Atexit(void (*function)(void)) { return atexit(function); } #endif // ------------------ sanitizer_libc.h uptr internal_mmap(void *addr, uptr length, int prot, int flags, int fd, u64 offset) { UNIMPLEMENTED(); } uptr internal_munmap(void *addr, uptr length) { UNIMPLEMENTED(); } uptr internal_close(fd_t fd) { UNIMPLEMENTED(); } int internal_isatty(fd_t fd) { return _isatty(fd); } uptr internal_open(const char *filename, int flags) { UNIMPLEMENTED(); } uptr internal_open(const char *filename, int flags, u32 mode) { UNIMPLEMENTED(); } uptr OpenFile(const char *filename, bool write) { UNIMPLEMENTED(); } uptr internal_read(fd_t fd, void *buf, uptr count) { UNIMPLEMENTED(); } uptr internal_write(fd_t fd, const void *buf, uptr count) { if (fd != kStderrFd) UNIMPLEMENTED(); HANDLE err = GetStdHandle(STD_ERROR_HANDLE); if (err == 0) return 0; // FIXME: this might not work on some apps. DWORD ret; if (!WriteFile(err, buf, count, &ret, 0)) return 0; return ret; } uptr internal_stat(const char *path, void *buf) { UNIMPLEMENTED(); } uptr internal_lstat(const char *path, void *buf) { UNIMPLEMENTED(); } uptr internal_fstat(fd_t fd, void *buf) { UNIMPLEMENTED(); } uptr internal_filesize(fd_t fd) { UNIMPLEMENTED(); } uptr internal_dup2(int oldfd, int newfd) { UNIMPLEMENTED(); } uptr internal_readlink(const char *path, char *buf, uptr bufsize) { UNIMPLEMENTED(); } uptr internal_sched_yield() { Sleep(0); return 0; } void internal__exit(int exitcode) { _exit(exitcode); } // ---------------------- BlockingMutex ---------------- {{{1 const uptr LOCK_UNINITIALIZED = 0; const uptr LOCK_READY = (uptr)-1; BlockingMutex::BlockingMutex(LinkerInitialized li) { // FIXME: see comments in BlockingMutex::Lock() for the details. CHECK(li == LINKER_INITIALIZED || owner_ == LOCK_UNINITIALIZED); CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_)); InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_); owner_ = LOCK_READY; } BlockingMutex::BlockingMutex() { CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_)); InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_); owner_ = LOCK_READY; } void BlockingMutex::Lock() { if (owner_ == LOCK_UNINITIALIZED) { // FIXME: hm, global BlockingMutex objects are not initialized?!? // This might be a side effect of the clang+cl+link Frankenbuild... new(this) BlockingMutex((LinkerInitialized)(LINKER_INITIALIZED + 1)); // FIXME: If it turns out the linker doesn't invoke our // constructors, we should probably manually Lock/Unlock all the global // locks while we're starting in one thread to avoid double-init races. } EnterCriticalSection((LPCRITICAL_SECTION)opaque_storage_); CHECK_EQ(owner_, LOCK_READY); owner_ = GetThreadSelf(); } void BlockingMutex::Unlock() { CHECK_EQ(owner_, GetThreadSelf()); owner_ = LOCK_READY; LeaveCriticalSection((LPCRITICAL_SECTION)opaque_storage_); } void BlockingMutex::CheckLocked() { CHECK_EQ(owner_, GetThreadSelf()); } uptr GetTlsSize() { return 0; } void InitTlsSize() { } void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size, uptr *tls_addr, uptr *tls_size) { #ifdef SANITIZER_GO *stk_addr = 0; *stk_size = 0; *tls_addr = 0; *tls_size = 0; #else uptr stack_top, stack_bottom; GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom); *stk_addr = stack_bottom; *stk_size = stack_top - stack_bottom; *tls_addr = 0; *tls_size = 0; #endif } void GetStackTrace(StackTrace *stack, uptr max_s, uptr pc, uptr bp, uptr stack_top, uptr stack_bottom, bool fast) { (void)fast; (void)stack_top; (void)stack_bottom; stack->max_size = max_s; void *tmp[kStackTraceMax]; // FIXME: CaptureStackBackTrace might be too slow for us. // FIXME: Compare with StackWalk64. // FIXME: Look at LLVMUnhandledExceptionFilter in Signals.inc uptr cs_ret = CaptureStackBackTrace(1, stack->max_size, tmp, 0); uptr offset = 0; // Skip the RTL frames by searching for the PC in the stacktrace. // FIXME: this doesn't work well for the malloc/free stacks yet. for (uptr i = 0; i < cs_ret; i++) { if (pc != (uptr)tmp[i]) continue; offset = i; break; } stack->size = cs_ret - offset; for (uptr i = 0; i < stack->size; i++) stack->trace[i] = (uptr)tmp[i + offset]; } } // namespace __sanitizer #endif // _WIN32 <|endoftext|>
<commit_before>#include "vm.h" #include "opcodes.h" #include "sections.h" #include <cassert> #include <iostream> #define STR_MASK 0x8000000000000000 #define ARRAY_MASK 0x4000000000000000 #define MASK(MASK, V) ((V) | (MASK)) #define UNMASK(MASK, V) ((V) & ~(MASK)) #define IS_MASK(MASK, V) ((V) & (MASK)) #define MASK_STR(STR) MASK(STR_MASK, STR) #define UNMASK_STR(STR) UNMASK(STR_MASK, STR) #define IS_STR(STR) IS_MASK(STR_MASK, STR) #define MASK_ARRAY(ARRAY) MASK(ARRAY_MASK, ARRAY) #define UNMASK_ARRAY(ARRAY) UNMASK(ARRAY_MASK, ARRAY) #define IS_ARRAY(ARRAY) IS_MASK(ARRAY_MASK, ARRAY) #define JS_FUNCTION(FN_NAME) __used static uintptr_t FN_NAME(ceos::VM &vm, unsigned argv) #define EACH_ARG(IT) \ for (uintptr_t I = 0, IT; (IT = vm.arg(I)), I < argv; I++) #define BASIC_MATH(NAME, OP) \ JS_FUNCTION(NAME) { \ assert(argv == 2); \ \ return vm.arg(0) OP vm.arg(1); \ } BASIC_MATH(add, +) BASIC_MATH(sub, -) BASIC_MATH(mul, *) BASIC_MATH(div, /) BASIC_MATH(lt, <) BASIC_MATH(gt, >) BASIC_MATH(lte, <=) BASIC_MATH(gte, >=) BASIC_MATH(equals, ==) JS_FUNCTION(print) { for (unsigned i = 0; i < argv; i++) { uintptr_t arg = vm.arg(i); if (IS_STR(arg)) { std::cout << (reinterpret_cast<std::string *>(UNMASK_STR(arg)))->c_str() << "\n"; } else if (IS_ARRAY(arg)) { std::vector<uintptr_t> *array = reinterpret_cast<__typeof__(array)>(UNMASK_ARRAY(arg)); for (auto a : *array) { std::cout << a << " "; } std::cout << "\n"; } else { std::cout << static_cast<int>(arg) << "\n"; } } return 0; } JS_FUNCTION(list) { auto list = new std::vector<uintptr_t>(); EACH_ARG(arg) { list->push_back(arg); } return MASK_ARRAY(reinterpret_cast<uintptr_t>(list)); } #undef BASIC_MATH namespace ceos { void VM::registerBuiltins() { #define REGISTER(NAME) JSFunctionType NAME##_ = NAME; m_functionTable[#NAME] = (uintptr_t)NAME##_ REGISTER(print); REGISTER(list); REGISTER(add); REGISTER(sub); REGISTER(mul); REGISTER(div); REGISTER(lt); REGISTER(gt); REGISTER(lte); REGISTER(gte); REGISTER(equals); #undef REGISTER } void VM::execute() { auto header = read<int>(); // section marker assert(header == Section::Header); while (true) { auto section = read<int>(); if (pc > length) { return; } switch (section) { case Section::Strings: loadStrings(); break; case Section::Functions: loadFunctions(); for (unsigned i = 0; i < m_userFunctions.size(); i++) { Function *fn = &m_userFunctions[i]; m_functionTable[fn->name] = MASK_STR(reinterpret_cast<uintptr_t>(fn)); } break; case Section::Text: run(); break; } } } void VM::loadStrings() { while (true) { auto header = read<int>(); if (header == Section::Header) { break; } pc -= 4; char *str = readStr(); m_stringTable.push_back(str); } } void VM::loadFunctions() { auto initialHeader = read<int>(); assert(initialHeader == Section::FunctionHeader); while (true) { char *name = readStr(); auto nargs = read<int>(); m_userFunctions.push_back(Function(name, nargs, pc)); while (true) { auto opcode = read<int>(); if (opcode == Section::Header) { return; } else if (opcode == Section::FunctionHeader) { break; } } } } void VM::run() { while (true) { auto opcode = read<int>(); if (pc > length) { return; } switch (opcode) { case Opcode::push: { auto value = read<int>(); stack_push(value); break; } case Opcode::call: { int nargs = stack_pop(); uintptr_t fn_address = stack_pop(); --nargs; //pop'd the callee stack_push(pc); stack_push(nargs); stack_push(ebp); ebp = esp; uintptr_t ret; if (IS_STR(fn_address)) { Function *fn = reinterpret_cast<__typeof__(fn)>(UNMASK_STR(fn_address)); pc = fn->offset; break; } else { JSFunctionType fn = reinterpret_cast<__typeof__(fn)>(fn_address); ret = fn(*this, nargs); stack_push(ret); } } case Opcode::ret: { uintptr_t ret = stack_pop(); esp = ebp; ebp = stack_pop(); unsigned nargs = stack_pop(); auto ret_addr = stack_pop(); esp -= nargs; stack_push(ret); pc = ret_addr; break; } case Opcode::load_string: { auto stringID = read<int>(); stack_push(MASK_STR(reinterpret_cast<uintptr_t>(&m_stringTable[stringID]))); break; } case Opcode::lookup: { auto id = read<int>(); auto fnAddress = read<uintptr_t>(); if (!fnAddress) { auto fnName = m_stringTable[id]; fnAddress = m_functionTable[fnName]; memcpy(m_bytecode + pc - sizeof(uintptr_t), &fnAddress, sizeof(uintptr_t)); } stack_push(fnAddress); break; } case Opcode::jmp: { auto target = read<int>(); pc += target; break; } case Opcode::jz: { auto target = read<int>(); int value = static_cast<int>(stack_pop()); if (value == 0) { pc += target; } break; } case Opcode::push_arg: { auto index = read<int>(); stack_push(arg(index)); break; } default: std::cerr << "Unhandled opcode: " << Opcode::typeName(static_cast<Opcode::Type>(opcode)) << "\n"; throw; } } } } <commit_msg>Add `and` and `or`<commit_after>#include "vm.h" #include "opcodes.h" #include "sections.h" #include <cassert> #include <iostream> #define STR_MASK 0x8000000000000000 #define ARRAY_MASK 0x4000000000000000 #define MASK(MASK, V) ((V) | (MASK)) #define UNMASK(MASK, V) ((V) & ~(MASK)) #define IS_MASK(MASK, V) ((V) & (MASK)) #define MASK_STR(STR) MASK(STR_MASK, STR) #define UNMASK_STR(STR) UNMASK(STR_MASK, STR) #define IS_STR(STR) IS_MASK(STR_MASK, STR) #define MASK_ARRAY(ARRAY) MASK(ARRAY_MASK, ARRAY) #define UNMASK_ARRAY(ARRAY) UNMASK(ARRAY_MASK, ARRAY) #define IS_ARRAY(ARRAY) IS_MASK(ARRAY_MASK, ARRAY) #define JS_FUNCTION(FN_NAME) __used static uintptr_t FN_NAME(ceos::VM &vm, unsigned argv) #define EACH_ARG(IT) \ for (uintptr_t I = 0, IT; (IT = vm.arg(I)), I < argv; I++) #define BASIC_MATH(NAME, OP) \ JS_FUNCTION(NAME) { \ assert(argv == 2); \ \ return vm.arg(0) OP vm.arg(1); \ } BASIC_MATH(add, +) BASIC_MATH(sub, -) BASIC_MATH(mul, *) BASIC_MATH(div, /) BASIC_MATH(lt, <) BASIC_MATH(gt, >) BASIC_MATH(lte, <=) BASIC_MATH(gte, >=) BASIC_MATH(equals, ==) BASIC_MATH(_and, &&) BASIC_MATH(_or, ||) JS_FUNCTION(print) { for (unsigned i = 0; i < argv; i++) { uintptr_t arg = vm.arg(i); if (IS_STR(arg)) { std::cout << (reinterpret_cast<std::string *>(UNMASK_STR(arg)))->c_str() << "\n"; } else if (IS_ARRAY(arg)) { std::vector<uintptr_t> *array = reinterpret_cast<__typeof__(array)>(UNMASK_ARRAY(arg)); for (auto a : *array) { std::cout << a << " "; } std::cout << "\n"; } else { std::cout << static_cast<int>(arg) << "\n"; } } return 0; } JS_FUNCTION(list) { auto list = new std::vector<uintptr_t>(); EACH_ARG(arg) { list->push_back(arg); } return MASK_ARRAY(reinterpret_cast<uintptr_t>(list)); } #undef BASIC_MATH namespace ceos { void VM::registerBuiltins() { #define REGISTER(NAME, FN) JSFunctionType NAME##_ = FN; m_functionTable[#NAME] = (uintptr_t)NAME##_ REGISTER(print, print); REGISTER(list, list); REGISTER(add, add); REGISTER(sub, sub); REGISTER(mul, mul); REGISTER(div, div); REGISTER(lt, lt); REGISTER(gt, gt); REGISTER(lte, lte); REGISTER(gte, gte); REGISTER(equals, equals); REGISTER(and, _and); REGISTER(or, _or); #undef REGISTER } void VM::execute() { auto header = read<int>(); // section marker assert(header == Section::Header); while (true) { auto section = read<int>(); if (pc > length) { return; } switch (section) { case Section::Strings: loadStrings(); break; case Section::Functions: loadFunctions(); for (unsigned i = 0; i < m_userFunctions.size(); i++) { Function *fn = &m_userFunctions[i]; m_functionTable[fn->name] = MASK_STR(reinterpret_cast<uintptr_t>(fn)); } break; case Section::Text: run(); break; } } } void VM::loadStrings() { while (true) { auto header = read<int>(); if (header == Section::Header) { break; } pc -= 4; char *str = readStr(); m_stringTable.push_back(str); } } void VM::loadFunctions() { auto initialHeader = read<int>(); assert(initialHeader == Section::FunctionHeader); while (true) { char *name = readStr(); auto nargs = read<int>(); m_userFunctions.push_back(Function(name, nargs, pc)); while (true) { auto opcode = read<int>(); if (opcode == Section::Header) { return; } else if (opcode == Section::FunctionHeader) { break; } } } } void VM::run() { while (true) { auto opcode = read<int>(); if (pc > length) { return; } switch (opcode) { case Opcode::push: { auto value = read<int>(); stack_push(value); break; } case Opcode::call: { int nargs = stack_pop(); uintptr_t fn_address = stack_pop(); --nargs; //pop'd the callee stack_push(pc); stack_push(nargs); stack_push(ebp); ebp = esp; uintptr_t ret; if (IS_STR(fn_address)) { Function *fn = reinterpret_cast<__typeof__(fn)>(UNMASK_STR(fn_address)); pc = fn->offset; break; } else { JSFunctionType fn = reinterpret_cast<__typeof__(fn)>(fn_address); ret = fn(*this, nargs); stack_push(ret); } } case Opcode::ret: { uintptr_t ret = stack_pop(); esp = ebp; ebp = stack_pop(); unsigned nargs = stack_pop(); auto ret_addr = stack_pop(); esp -= nargs; stack_push(ret); pc = ret_addr; break; } case Opcode::load_string: { auto stringID = read<int>(); stack_push(MASK_STR(reinterpret_cast<uintptr_t>(&m_stringTable[stringID]))); break; } case Opcode::lookup: { auto id = read<int>(); auto fnAddress = read<uintptr_t>(); if (!fnAddress) { auto fnName = m_stringTable[id]; fnAddress = m_functionTable[fnName]; memcpy(m_bytecode + pc - sizeof(uintptr_t), &fnAddress, sizeof(uintptr_t)); } stack_push(fnAddress); break; } case Opcode::jmp: { auto target = read<int>(); pc += target; break; } case Opcode::jz: { auto target = read<int>(); int value = static_cast<int>(stack_pop()); if (value == 0) { pc += target; } break; } case Opcode::push_arg: { auto index = read<int>(); stack_push(arg(index)); break; } default: std::cerr << "Unhandled opcode: " << Opcode::typeName(static_cast<Opcode::Type>(opcode)) << "\n"; throw; } } } } <|endoftext|>
<commit_before>#include "Vision/RTSVisionManager.h" #include "EngineUtils.h" #include "Engine/GameInstance.h" #include "Engine/World.h" #include "GameFramework/PlayerController.h" #include "Kismet/GameplayStatics.h" #include "RTSGameMode.h" #include "RTSLog.h" #include "RTSOwnerComponent.h" #include "RTSPlayerState.h" #include "RTSTeamInfo.h" #include "Vision/RTSFogOfWarActor.h" #include "Vision/RTSVisibleActor.h" #include "Vision/RTSVisibleComponent.h" #include "Vision/RTSVisionComponent.h" #include "Vision/RTSVisionInfo.h" #include "Vision/RTSVisionVolume.h" ARTSVisionManager::ARTSVisionManager(const FObjectInitializer& ObjectInitializer /*= FObjectInitializer::Get()*/) : Super(ObjectInitializer) { PrimaryActorTick.bCanEverTick = true; PrimaryActorTick.bStartWithTickEnabled = true; } void ARTSVisionManager::Initialize() { UWorld* World = GetWorld(); // Find local player. APlayerController* FirstLocalPlayerController = GetGameInstance()->GetFirstLocalPlayerController(); if (IsValid(FirstLocalPlayerController)) { SetLocalPlayerState(FirstLocalPlayerController->GetPlayerState<ARTSPlayerState>()); } // Find manager and info actors. for (TActorIterator<AActor> It(World); It; ++It) { AActor* Actor = *It; if (IsValid(Actor)) { if (Actor->IsA(ARTSFogOfWarActor::StaticClass())) { FogOfWarActor = Cast<ARTSFogOfWarActor>(Actor); } else if (Actor->IsA(ARTSVisionInfo::StaticClass())) { ARTSVisionInfo* VisionInfo = Cast<ARTSVisionInfo>(Actor); VisionInfos.Add(VisionInfo); } else if (Actor->IsA(ARTSVisionVolume::StaticClass())) { VisionVolume = Cast<ARTSVisionVolume>(Actor); } } } if (IsValid(VisionVolume)) { VisionVolume->Initialize(); } for (ARTSVisionInfo* VisionInfo : VisionInfos) { VisionInfo->Initialize(VisionVolume); } if (IsValid(FogOfWarActor)) { FogOfWarActor->Initialize(VisionVolume); } // Discover initial vision actors. for (TActorIterator<AActor> It(GetWorld()); It; ++It) { AActor* Actor = *It; if (!IsValid(Actor)) { continue; } URTSVisibleComponent* VisibleComponent = Actor->FindComponentByClass<URTSVisibleComponent>(); if (IsValid(VisibleComponent)) { AddVisibleActor(Actor); } URTSVisionComponent* VisionComponent = Actor->FindComponentByClass<URTSVisionComponent>(); if (IsValid(VisionComponent)) { AddVisionActor(Actor); } } } void ARTSVisionManager::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); // Update unit vision. for (FRTSVisionActor& VisionActor : VisionActors) { UpdateVisionActor(VisionActor); } // Update unit visibility. for (FRTSVisibleActor& VisibleActor : VisibleActors) { if (!VisibleActor.IsActorValid()) { continue; } FIntVector TileLocation; if (IsValid(VisibleActor.VisionComponent)) { TileLocation = VisibleActor.VisionComponent->ActorLocationTile; } else { TileLocation = IsValid(VisionVolume) ? VisionVolume->WorldToTile(VisibleActor.Actor->GetActorLocation()) : FIntVector::ZeroValue; } if (GetNetMode() <= NM_ListenServer) { ARTSGameMode* GameMode = Cast<ARTSGameMode>(UGameplayStatics::GetGameMode(this)); // Update server vision. for (ARTSTeamInfo* Team : GameMode->GetTeams()) { // If friendly, always visible. if (VisibleActor.OwnerComponent && VisibleActor.OwnerComponent->GetPlayerOwner() && VisibleActor.OwnerComponent->GetPlayerOwner()->GetTeam() == Team) { for (AController* Player : Team->GetTeamMembers()) { // Set visibility according to team vision. VisibleActor.VisibleComponent->SetVisionStateForPlayer(Player, ERTSVisionState::VISION_Visible); } continue; } // Get matching vision info. if (VisionInfos.IsValidIndex(Team->GetTeamIndex())) { ARTSVisionInfo* TeamVision = VisionInfos[Team->GetTeamIndex()]; ERTSVisionState NewVision = TeamVision->GetVision(TileLocation.X, TileLocation.Y); for (AController* Player : Team->GetTeamMembers()) { // Set visibility according to team vision. VisibleActor.VisibleComponent->SetVisionStateForPlayer(Player, NewVision); } } else { UE_LOG(LogRTS, Warning, TEXT("No vision info available for team %i."), Team->GetTeamIndex()); } } } if (GetNetMode() >= NM_ListenServer) { // Update client vision. ERTSVisionState NewVision = IsValid(LocalVisionInfo) ? LocalVisionInfo->GetVision(TileLocation.X, TileLocation.Y) : ERTSVisionState::VISION_Visible; VisibleActor.VisibleComponent->SetClientVisionState(NewVision); } } } void ARTSVisionManager::SetLocalPlayerState(ARTSPlayerState* InLocalPlayerState) { LocalPlayerState = InLocalPlayerState; if (IsValid(InLocalPlayerState)) { UE_LOG(LogRTS, Log, TEXT("Using local player state %s."), *InLocalPlayerState->GetName()); } } void ARTSVisionManager::SetLocalVisionInfo(ARTSVisionInfo* InLocalVisionInfo) { if (!IsValid(InLocalVisionInfo)) { return; } LocalVisionInfo = InLocalVisionInfo; if (!VisionInfos.Contains(LocalVisionInfo)) { // It seems like this has been replicated after our initialization. VisionInfos.Add(LocalVisionInfo); LocalVisionInfo->Initialize(VisionVolume); } if (IsValid(FogOfWarActor)) { FogOfWarActor->SetupVisionInfo(LocalVisionInfo); } UE_LOG(LogRTS, Log, TEXT("Using local vision info %s."), *LocalVisionInfo->GetName()); } void ARTSVisionManager::AddVisibleActor(AActor* Actor) { for (int32 Index = 0; Index < VisibleActors.Num(); ++Index) { if (VisibleActors[Index].Actor == Actor) { // Already added. return; } } FRTSVisibleActor VisibleActor(Actor); if (!VisibleActor.IsActorValid()) { return; } VisibleActors.Add(VisibleActor); } void ARTSVisionManager::RemoveVisibleActor(AActor* Actor) { int32 IndexToRemove = -1; for (int32 Index = 0; Index < VisibleActors.Num(); ++Index) { if (VisibleActors[Index].Actor == Actor) { IndexToRemove = Index; break; } } if (VisibleActors.IsValidIndex(IndexToRemove)) { VisibleActors.RemoveAt(IndexToRemove); } } void ARTSVisionManager::AddVisionActor(AActor* Actor) { for (int32 Index = 0; Index < VisionActors.Num(); ++Index) { if (VisionActors[Index].Actor == Actor) { // Already added. return; } } FRTSVisionActor VisionActor(Actor); if (!VisionActor.IsActorValid()) { return; } VisionActors.Add(VisionActor); } void ARTSVisionManager::RemoveVisionActor(AActor* Actor) { int32 IndexToRemove = -1; for (int32 Index = 0; Index < VisionActors.Num(); ++Index) { if (VisionActors[Index].Actor == Actor) { IndexToRemove = Index; break; } } if (VisionActors.IsValidIndex(IndexToRemove)) { ResetVisionForActor(VisionActors[IndexToRemove]); VisionActors.RemoveAt(IndexToRemove); } } void ARTSVisionManager::UpdateVisionActor(const FRTSVisionActor& VisionActor) { if (VisionInfos.Num() == 0) { return; } if (!IsValid(LocalPlayerState)) { return; } for (ARTSVisionInfo* VisionInfo : VisionInfos) { if (!VisionInfo->IsInitialized()) { return; } } // We only need to update vision for actors who have moved onto a new tile. if (!VisionActor.IsActorValid()) { return; } FVector ActorLocationWorld = VisionActor.Actor->GetActorLocation(); FIntVector ActorLocationTile = VisionVolume->WorldToTile(ActorLocationWorld); int32 ActorLocationHeightLevel = VisionVolume->GetTileHeight(ActorLocationTile); if (VisionActor.VisionComponent->ActorLocationTile.X == ActorLocationTile.X && VisionActor.VisionComponent->ActorLocationTile.Y == ActorLocationTile.Y && VisionActor.VisionComponent->ActorLocationTile.Z == ActorLocationHeightLevel) { // Hasn't moved. return; } else { // Moved to new grid cell. VisionActor.VisionComponent->ActorLocationTile = ActorLocationTile; VisionActor.VisionComponent->ActorLocationTile.Z = ActorLocationHeightLevel; } ResetVisionForActor(VisionActor); // Apply vision. TArray<int32> CachedVisionTiles; for (ARTSVisionInfo* VisionInfo : VisionInfos) { VisionInfo->ApplyVisionForActor(VisionActor.Actor, CachedVisionTiles); } } void ARTSVisionManager::ResetVisionForActor(const FRTSVisionActor& VisionActor) { if (!VisionActor.IsActorValid()) { return; } // Reset vision. for (const FRTSVisionInfoTileList& VisionInfoTileList : VisionActor.VisionComponent->VisibleTiles) { VisionInfoTileList.VisionInfo->ResetVisionForActor(VisionActor.Actor); } VisionActor.VisionComponent->VisibleTiles.Empty(); } <commit_msg>Correctly calculate client-side vision state in standalone games.<commit_after>#include "Vision/RTSVisionManager.h" #include "EngineUtils.h" #include "Engine/GameInstance.h" #include "Engine/World.h" #include "GameFramework/PlayerController.h" #include "Kismet/GameplayStatics.h" #include "RTSGameMode.h" #include "RTSLog.h" #include "RTSOwnerComponent.h" #include "RTSPlayerState.h" #include "RTSTeamInfo.h" #include "Vision/RTSFogOfWarActor.h" #include "Vision/RTSVisibleActor.h" #include "Vision/RTSVisibleComponent.h" #include "Vision/RTSVisionComponent.h" #include "Vision/RTSVisionInfo.h" #include "Vision/RTSVisionVolume.h" ARTSVisionManager::ARTSVisionManager(const FObjectInitializer& ObjectInitializer /*= FObjectInitializer::Get()*/) : Super(ObjectInitializer) { PrimaryActorTick.bCanEverTick = true; PrimaryActorTick.bStartWithTickEnabled = true; } void ARTSVisionManager::Initialize() { UWorld* World = GetWorld(); // Find local player. APlayerController* FirstLocalPlayerController = GetGameInstance()->GetFirstLocalPlayerController(); if (IsValid(FirstLocalPlayerController)) { SetLocalPlayerState(FirstLocalPlayerController->GetPlayerState<ARTSPlayerState>()); } // Find manager and info actors. for (TActorIterator<AActor> It(World); It; ++It) { AActor* Actor = *It; if (IsValid(Actor)) { if (Actor->IsA(ARTSFogOfWarActor::StaticClass())) { FogOfWarActor = Cast<ARTSFogOfWarActor>(Actor); } else if (Actor->IsA(ARTSVisionInfo::StaticClass())) { ARTSVisionInfo* VisionInfo = Cast<ARTSVisionInfo>(Actor); VisionInfos.Add(VisionInfo); } else if (Actor->IsA(ARTSVisionVolume::StaticClass())) { VisionVolume = Cast<ARTSVisionVolume>(Actor); } } } if (IsValid(VisionVolume)) { VisionVolume->Initialize(); } for (ARTSVisionInfo* VisionInfo : VisionInfos) { VisionInfo->Initialize(VisionVolume); } if (IsValid(FogOfWarActor)) { FogOfWarActor->Initialize(VisionVolume); } // Discover initial vision actors. for (TActorIterator<AActor> It(GetWorld()); It; ++It) { AActor* Actor = *It; if (!IsValid(Actor)) { continue; } URTSVisibleComponent* VisibleComponent = Actor->FindComponentByClass<URTSVisibleComponent>(); if (IsValid(VisibleComponent)) { AddVisibleActor(Actor); } URTSVisionComponent* VisionComponent = Actor->FindComponentByClass<URTSVisionComponent>(); if (IsValid(VisionComponent)) { AddVisionActor(Actor); } } } void ARTSVisionManager::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); // Update unit vision. for (FRTSVisionActor& VisionActor : VisionActors) { UpdateVisionActor(VisionActor); } // Update unit visibility. for (FRTSVisibleActor& VisibleActor : VisibleActors) { if (!VisibleActor.IsActorValid()) { continue; } FIntVector TileLocation; if (IsValid(VisibleActor.VisionComponent)) { TileLocation = VisibleActor.VisionComponent->ActorLocationTile; } else { TileLocation = IsValid(VisionVolume) ? VisionVolume->WorldToTile(VisibleActor.Actor->GetActorLocation()) : FIntVector::ZeroValue; } if (GetNetMode() <= NM_ListenServer) { ARTSGameMode* GameMode = Cast<ARTSGameMode>(UGameplayStatics::GetGameMode(this)); // Update server vision. for (ARTSTeamInfo* Team : GameMode->GetTeams()) { // If friendly, always visible. if (VisibleActor.OwnerComponent && VisibleActor.OwnerComponent->GetPlayerOwner() && VisibleActor.OwnerComponent->GetPlayerOwner()->GetTeam() == Team) { for (AController* Player : Team->GetTeamMembers()) { // Set visibility according to team vision. VisibleActor.VisibleComponent->SetVisionStateForPlayer(Player, ERTSVisionState::VISION_Visible); } continue; } // Get matching vision info. if (VisionInfos.IsValidIndex(Team->GetTeamIndex())) { ARTSVisionInfo* TeamVision = VisionInfos[Team->GetTeamIndex()]; ERTSVisionState NewVision = TeamVision->GetVision(TileLocation.X, TileLocation.Y); for (AController* Player : Team->GetTeamMembers()) { // Set visibility according to team vision. VisibleActor.VisibleComponent->SetVisionStateForPlayer(Player, NewVision); } } else { UE_LOG(LogRTS, Warning, TEXT("No vision info available for team %i."), Team->GetTeamIndex()); } } } if (GetNetMode() != NM_DedicatedServer) { // Update client vision. ERTSVisionState NewVision = IsValid(LocalVisionInfo) ? LocalVisionInfo->GetVision(TileLocation.X, TileLocation.Y) : ERTSVisionState::VISION_Visible; VisibleActor.VisibleComponent->SetClientVisionState(NewVision); } } } void ARTSVisionManager::SetLocalPlayerState(ARTSPlayerState* InLocalPlayerState) { LocalPlayerState = InLocalPlayerState; if (IsValid(InLocalPlayerState)) { UE_LOG(LogRTS, Log, TEXT("Using local player state %s."), *InLocalPlayerState->GetName()); } } void ARTSVisionManager::SetLocalVisionInfo(ARTSVisionInfo* InLocalVisionInfo) { if (!IsValid(InLocalVisionInfo)) { return; } LocalVisionInfo = InLocalVisionInfo; if (!VisionInfos.Contains(LocalVisionInfo)) { // It seems like this has been replicated after our initialization. VisionInfos.Add(LocalVisionInfo); LocalVisionInfo->Initialize(VisionVolume); } if (IsValid(FogOfWarActor)) { FogOfWarActor->SetupVisionInfo(LocalVisionInfo); } UE_LOG(LogRTS, Log, TEXT("Using local vision info %s."), *LocalVisionInfo->GetName()); } void ARTSVisionManager::AddVisibleActor(AActor* Actor) { for (int32 Index = 0; Index < VisibleActors.Num(); ++Index) { if (VisibleActors[Index].Actor == Actor) { // Already added. return; } } FRTSVisibleActor VisibleActor(Actor); if (!VisibleActor.IsActorValid()) { return; } VisibleActors.Add(VisibleActor); } void ARTSVisionManager::RemoveVisibleActor(AActor* Actor) { int32 IndexToRemove = -1; for (int32 Index = 0; Index < VisibleActors.Num(); ++Index) { if (VisibleActors[Index].Actor == Actor) { IndexToRemove = Index; break; } } if (VisibleActors.IsValidIndex(IndexToRemove)) { VisibleActors.RemoveAt(IndexToRemove); } } void ARTSVisionManager::AddVisionActor(AActor* Actor) { for (int32 Index = 0; Index < VisionActors.Num(); ++Index) { if (VisionActors[Index].Actor == Actor) { // Already added. return; } } FRTSVisionActor VisionActor(Actor); if (!VisionActor.IsActorValid()) { return; } VisionActors.Add(VisionActor); } void ARTSVisionManager::RemoveVisionActor(AActor* Actor) { int32 IndexToRemove = -1; for (int32 Index = 0; Index < VisionActors.Num(); ++Index) { if (VisionActors[Index].Actor == Actor) { IndexToRemove = Index; break; } } if (VisionActors.IsValidIndex(IndexToRemove)) { ResetVisionForActor(VisionActors[IndexToRemove]); VisionActors.RemoveAt(IndexToRemove); } } void ARTSVisionManager::UpdateVisionActor(const FRTSVisionActor& VisionActor) { if (VisionInfos.Num() == 0) { return; } if (!IsValid(LocalPlayerState)) { return; } for (ARTSVisionInfo* VisionInfo : VisionInfos) { if (!VisionInfo->IsInitialized()) { return; } } // We only need to update vision for actors who have moved onto a new tile. if (!VisionActor.IsActorValid()) { return; } FVector ActorLocationWorld = VisionActor.Actor->GetActorLocation(); FIntVector ActorLocationTile = VisionVolume->WorldToTile(ActorLocationWorld); int32 ActorLocationHeightLevel = VisionVolume->GetTileHeight(ActorLocationTile); if (VisionActor.VisionComponent->ActorLocationTile.X == ActorLocationTile.X && VisionActor.VisionComponent->ActorLocationTile.Y == ActorLocationTile.Y && VisionActor.VisionComponent->ActorLocationTile.Z == ActorLocationHeightLevel) { // Hasn't moved. return; } else { // Moved to new grid cell. VisionActor.VisionComponent->ActorLocationTile = ActorLocationTile; VisionActor.VisionComponent->ActorLocationTile.Z = ActorLocationHeightLevel; } ResetVisionForActor(VisionActor); // Apply vision. TArray<int32> CachedVisionTiles; for (ARTSVisionInfo* VisionInfo : VisionInfos) { VisionInfo->ApplyVisionForActor(VisionActor.Actor, CachedVisionTiles); } } void ARTSVisionManager::ResetVisionForActor(const FRTSVisionActor& VisionActor) { if (!VisionActor.IsActorValid()) { return; } // Reset vision. for (const FRTSVisionInfoTileList& VisionInfoTileList : VisionActor.VisionComponent->VisibleTiles) { VisionInfoTileList.VisionInfo->ResetVisionForActor(VisionActor.Actor); } VisionActor.VisionComponent->VisibleTiles.Empty(); } <|endoftext|>
<commit_before>#include "../include/File.h" #include <vector> #include <ctype.h> #include <locale> using namespace std; const string tok = ";"; const string vars = "var"; const string consts = "const"; const string minitok = ","; const string equals = "="; const string affct = ":="; const string plusLut = "+"; const string minusLut = "-"; const string multiplyLut = "*"; const string divideLut = "/"; const string paro = "("; const string parf = ")"; File::File() { //ctor } void File::setPath(string link) { path = link; } File::~File() { } void File::openParse() { ifstream myfile; myfile.open (path.c_str()); if (myfile.is_open()) { string ligne; //variable contenant chaque ligne lue //cette boucle s'arrête dès qu'une erreur de lecture survient while ( getline( myfile, ligne ) ) { if(ligne != "") { vector<string> array; stringstream ss(ligne); string temp; while (ss >> temp) { // Tant que le mot n'a pas été consommé entièrement if(cleanWord(temp)) { array.push_back(temp); } else { Dismantle(&array,&temp); } } parsedFiles.push_back(array); } } myfile.close(); cleaning(); ParsingTest(); } else { throw 0; } } vector<string> File::getContinueParsedFile() { vector<string> continueParsedFile; for(unsigned int i=0; i<parsedFiles.size(); i++) { for(unsigned int j=0; j<parsedFiles[i].size(); j++) { continueParsedFile.push_back(parsedFiles[i][j]); } } return continueParsedFile; } vector<vector<string> > File::getParsedFiles() { return parsedFiles; } void File::ParsingTest() { for (unsigned int i = 0;i<parsedFiles.size();i++) { for (unsigned int j=0;j<parsedFiles[i].size();j++) { if (parsedFiles[i][j] != "") cout << parsedFiles[i][j] << endl; else cout << "NULL" << endl; } } } void File::cleaning() { for (unsigned int i = 0;i<parsedFiles.size();i++) { for (unsigned int j=0;j<parsedFiles[i].size();j++) { if (parsedFiles[i][j] == "") parsedFiles[i].erase(parsedFiles[i].begin()+j); } } } void File::Dismantle(vector<string>* array,string* temp) { if((*temp).find(affct)!=string::npos) { size_t found = (*temp).find(affct); if((*temp).substr(0,found) != "" && (*temp).substr(0,found)!=affct) { (*array).push_back((*temp).substr(0,found)); } (*array).push_back(affct); string remaining; remaining = (*temp).substr(found+2); if (remaining != "") { Dismantle(array,&remaining); } } else { size_t found = (*temp).find_first_of("+-*/=(),;"); if (found != std::string::npos) { string flush = ""; for(size_t found = 0;found<(*temp).size();found++) { if(!isalpha((*temp)[found])&&!isdigit((*temp)[found])) { if(flush!="") { (*array).push_back(flush); } flush =""; (*array).push_back(string(1,(*temp)[found])); } else { flush +=(*temp)[found]; } } // On flush ce qui reste (*array).push_back(flush); } else { (*array).push_back((*temp)); } } } bool File::cleanWord(string tested) { if (tested.find_first_of("+-*/=(),;") != string::npos || tested.find(affct) != string::npos ) { return false; } return true; } <commit_msg>file.cpp no test<commit_after>#include "../include/File.h" #include <vector> #include <ctype.h> #include <locale> using namespace std; const string tok = ";"; const string vars = "var"; const string consts = "const"; const string minitok = ","; const string equals = "="; const string affct = ":="; const string plusLut = "+"; const string minusLut = "-"; const string multiplyLut = "*"; const string divideLut = "/"; const string paro = "("; const string parf = ")"; File::File() { //ctor } void File::setPath(string link) { path = link; } File::~File() { } void File::openParse() { ifstream myfile; myfile.open (path.c_str()); if (myfile.is_open()) { string ligne; //variable contenant chaque ligne lue //cette boucle s'arrête dès qu'une erreur de lecture survient while ( getline( myfile, ligne ) ) { if(ligne != "") { vector<string> array; stringstream ss(ligne); string temp; while (ss >> temp) { // Tant que le mot n'a pas été consommé entièrement if(cleanWord(temp)) { array.push_back(temp); } else { Dismantle(&array,&temp); } } parsedFiles.push_back(array); } } myfile.close(); cleaning(); // FOR TEST PURPOSE ParsingTest(); } else { throw 0; } } vector<string> File::getContinueParsedFile() { vector<string> continueParsedFile; for(unsigned int i=0; i<parsedFiles.size(); i++) { for(unsigned int j=0; j<parsedFiles[i].size(); j++) { continueParsedFile.push_back(parsedFiles[i][j]); } } return continueParsedFile; } vector<vector<string> > File::getParsedFiles() { return parsedFiles; } void File::ParsingTest() { for (unsigned int i = 0;i<parsedFiles.size();i++) { for (unsigned int j=0;j<parsedFiles[i].size();j++) { if (parsedFiles[i][j] != "") cout << parsedFiles[i][j] << endl; else cout << "NULL" << endl; } } } void File::cleaning() { for (unsigned int i = 0;i<parsedFiles.size();i++) { for (unsigned int j=0;j<parsedFiles[i].size();j++) { if (parsedFiles[i][j] == "") parsedFiles[i].erase(parsedFiles[i].begin()+j); } } } void File::Dismantle(vector<string>* array,string* temp) { if((*temp).find(affct)!=string::npos) { size_t found = (*temp).find(affct); if((*temp).substr(0,found) != "" && (*temp).substr(0,found)!=affct) { (*array).push_back((*temp).substr(0,found)); } (*array).push_back(affct); string remaining; remaining = (*temp).substr(found+2); if (remaining != "") { Dismantle(array,&remaining); } } else { size_t found = (*temp).find_first_of("+-*/=(),;"); if (found != std::string::npos) { string flush = ""; for(size_t found = 0;found<(*temp).size();found++) { if(!isalpha((*temp)[found])&&!isdigit((*temp)[found])) { if(flush!="") { (*array).push_back(flush); } flush =""; (*array).push_back(string(1,(*temp)[found])); } else { flush +=(*temp)[found]; } } // On flush ce qui reste (*array).push_back(flush); } else { (*array).push_back((*temp)); } } } bool File::cleanWord(string tested) { if (tested.find_first_of("+-*/=(),;") != string::npos || tested.find(affct) != string::npos ) { return false; } return true; } <|endoftext|>
<commit_before>/** * Copyright (c) 2013, Timothy Stack * * 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 Timothy Stack 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file lnav_util.cc * * Dumping ground for useful functions with no other home. */ #include "config.h" #include <stdio.h> #include <ctype.h> #include "lnav_util.hh" #include "base/opt_util.hh" #include "base/result.h" #include "ansi_scrubber.hh" #include "fmt/format.h" using namespace std; std::string time_ago(time_t last_time, bool convert_local) { time_t delta, current_time = time(nullptr); const char *fmt; char buffer[64]; int amount; if (convert_local) { current_time = convert_log_time_to_local(current_time); } delta = current_time - last_time; if (delta < 0) { return "in the future"; } else if (delta < 60) { return "just now"; } else if (delta < (60 * 2)) { return "one minute ago"; } else if (delta < (60 * 60)) { fmt = "%d minutes ago"; amount = delta / 60; } else if (delta < (2 * 60 * 60)) { return "one hour ago"; } else if (delta < (24 * 60 * 60)) { fmt = "%d hours ago"; amount = delta / (60 * 60); } else if (delta < (2 * 24 * 60 * 60)) { return "one day ago"; } else if (delta < (365 * 24 * 60 * 60)) { fmt = "%d days ago"; amount = delta / (24 * 60 * 60); } else if (delta < (2 * 365 * 24 * 60 * 60)) { return "over a year ago"; } else { fmt = "over %d years ago"; amount = delta / (365 * 24 * 60 * 60); } snprintf(buffer, sizeof(buffer), fmt, amount); return std::string(buffer); } std::string precise_time_ago(const struct timeval &tv, bool convert_local) { struct timeval now, diff; gettimeofday(&now, nullptr); if (convert_local) { now.tv_sec = convert_log_time_to_local(now.tv_sec); } timersub(&now, &tv, &diff); if (diff.tv_sec < 0) { return time_ago(tv.tv_sec); } else if (diff.tv_sec <= 1) { return "a second ago"; } else if (diff.tv_sec < (10 * 60)) { char buf[64]; if (diff.tv_sec < 60) { snprintf(buf, sizeof(buf), "%2ld seconds ago", diff.tv_sec); } else { time_t seconds = diff.tv_sec % 60; time_t minutes = diff.tv_sec / 60; snprintf(buf, sizeof(buf), "%2ld minute%s and %2ld second%s ago", minutes, minutes > 1 ? "s" : "", seconds, seconds == 1 ? "" : "s"); } return string(buf); } else { return time_ago(tv.tv_sec, convert_local); } } bool change_to_parent_dir() { bool retval = false; char cwd[3] = ""; if (getcwd(cwd, sizeof(cwd)) == nullptr) { /* perror("getcwd"); */ } if (strcmp(cwd, "/") != 0) { if (chdir("..") == -1) { perror("chdir('..')"); } else { retval = true; } } return retval; } template<typename T> size_t strtonum(T &num_out, const char *string, size_t len) { size_t retval = 0; T sign = 1; num_out = 0; for (; retval < len && isspace(string[retval]); retval++); for (; retval < len && string[retval] == '-'; retval++) { sign *= -1; } for (; retval < len && string[retval] == '+'; retval++); for (; retval < len && isdigit(string[retval]); retval++) { num_out *= 10; num_out += string[retval] - '0'; } return retval; } template size_t strtonum<long long>(long long &num_out, const char *string, size_t len); template size_t strtonum<long>(long &num_out, const char *string, size_t len); template size_t strtonum<int>(int &num_out, const char *string, size_t len); string build_path(const vector<ghc::filesystem::path> &paths) { string retval; for (const auto &path : paths) { if (path.empty()) { continue; } if (!retval.empty()) { retval += ":"; } retval += path.string(); } auto env_path = getenv_opt("PATH"); if (env_path) { retval += ":" + string(*env_path); } return retval; } bool read_file(const ghc::filesystem::path &filename, string &out) { std::ifstream sql_file(filename.string()); if (sql_file) { out.assign((std::istreambuf_iterator<char>(sql_file)), std::istreambuf_iterator<char>()); return true; } return false; } Result<std::pair<ghc::filesystem::path, int>, std::string> open_temp_file(const ghc::filesystem::path &pattern) { auto pattern_str = pattern.string(); char pattern_copy[pattern_str.size() + 1]; int fd; strcpy(pattern_copy, pattern_str.c_str()); if ((fd = mkstemp(pattern_copy)) == -1) { return Err(fmt::format("unable to create temporary file: {} -- {}", pattern.string(), strerror(errno))); } return Ok(make_pair(ghc::filesystem::path(pattern_copy), fd)); } bool is_dev_null(const struct stat &st) { struct stat null_stat; stat("/dev/null", &null_stat); return st.st_dev == null_stat.st_dev && st.st_ino == null_stat.st_ino; } bool is_dev_null(int fd) { struct stat fd_stat; fstat(fd, &fd_stat); return is_dev_null(fd_stat); } std::string ok_prefix(std::string msg) { if (msg.empty()) { return msg; } return std::string(ANSI_COLOR(COLOR_GREEN) "\u2714" ANSI_NORM " ") + msg; } std::string err_prefix(const std::string msg) { if (msg.empty()) { return msg; } return std::string(ANSI_COLOR(COLOR_RED) "\u2718" ANSI_NORM " ") + msg; } Result<std::string, std::string> err_to_ok(const std::string msg) { return Ok(err_prefix(msg)); } <commit_msg>[lnav_util] fix ok/error msg rendering<commit_after>/** * Copyright (c) 2013, Timothy Stack * * 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 Timothy Stack 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file lnav_util.cc * * Dumping ground for useful functions with no other home. */ #include "config.h" #include <stdio.h> #include <ctype.h> #include "lnav_util.hh" #include "base/opt_util.hh" #include "base/result.h" #include "ansi_scrubber.hh" #include "fmt/format.h" #include "view_curses.hh" using namespace std; std::string time_ago(time_t last_time, bool convert_local) { time_t delta, current_time = time(nullptr); const char *fmt; char buffer[64]; int amount; if (convert_local) { current_time = convert_log_time_to_local(current_time); } delta = current_time - last_time; if (delta < 0) { return "in the future"; } else if (delta < 60) { return "just now"; } else if (delta < (60 * 2)) { return "one minute ago"; } else if (delta < (60 * 60)) { fmt = "%d minutes ago"; amount = delta / 60; } else if (delta < (2 * 60 * 60)) { return "one hour ago"; } else if (delta < (24 * 60 * 60)) { fmt = "%d hours ago"; amount = delta / (60 * 60); } else if (delta < (2 * 24 * 60 * 60)) { return "one day ago"; } else if (delta < (365 * 24 * 60 * 60)) { fmt = "%d days ago"; amount = delta / (24 * 60 * 60); } else if (delta < (2 * 365 * 24 * 60 * 60)) { return "over a year ago"; } else { fmt = "over %d years ago"; amount = delta / (365 * 24 * 60 * 60); } snprintf(buffer, sizeof(buffer), fmt, amount); return std::string(buffer); } std::string precise_time_ago(const struct timeval &tv, bool convert_local) { struct timeval now, diff; gettimeofday(&now, nullptr); if (convert_local) { now.tv_sec = convert_log_time_to_local(now.tv_sec); } timersub(&now, &tv, &diff); if (diff.tv_sec < 0) { return time_ago(tv.tv_sec); } else if (diff.tv_sec <= 1) { return "a second ago"; } else if (diff.tv_sec < (10 * 60)) { char buf[64]; if (diff.tv_sec < 60) { snprintf(buf, sizeof(buf), "%2ld seconds ago", diff.tv_sec); } else { time_t seconds = diff.tv_sec % 60; time_t minutes = diff.tv_sec / 60; snprintf(buf, sizeof(buf), "%2ld minute%s and %2ld second%s ago", minutes, minutes > 1 ? "s" : "", seconds, seconds == 1 ? "" : "s"); } return string(buf); } else { return time_ago(tv.tv_sec, convert_local); } } bool change_to_parent_dir() { bool retval = false; char cwd[3] = ""; if (getcwd(cwd, sizeof(cwd)) == nullptr) { /* perror("getcwd"); */ } if (strcmp(cwd, "/") != 0) { if (chdir("..") == -1) { perror("chdir('..')"); } else { retval = true; } } return retval; } template<typename T> size_t strtonum(T &num_out, const char *string, size_t len) { size_t retval = 0; T sign = 1; num_out = 0; for (; retval < len && isspace(string[retval]); retval++); for (; retval < len && string[retval] == '-'; retval++) { sign *= -1; } for (; retval < len && string[retval] == '+'; retval++); for (; retval < len && isdigit(string[retval]); retval++) { num_out *= 10; num_out += string[retval] - '0'; } return retval; } template size_t strtonum<long long>(long long &num_out, const char *string, size_t len); template size_t strtonum<long>(long &num_out, const char *string, size_t len); template size_t strtonum<int>(int &num_out, const char *string, size_t len); string build_path(const vector<ghc::filesystem::path> &paths) { string retval; for (const auto &path : paths) { if (path.empty()) { continue; } if (!retval.empty()) { retval += ":"; } retval += path.string(); } auto env_path = getenv_opt("PATH"); if (env_path) { retval += ":" + string(*env_path); } return retval; } bool read_file(const ghc::filesystem::path &filename, string &out) { std::ifstream sql_file(filename.string()); if (sql_file) { out.assign((std::istreambuf_iterator<char>(sql_file)), std::istreambuf_iterator<char>()); return true; } return false; } Result<std::pair<ghc::filesystem::path, int>, std::string> open_temp_file(const ghc::filesystem::path &pattern) { auto pattern_str = pattern.string(); char pattern_copy[pattern_str.size() + 1]; int fd; strcpy(pattern_copy, pattern_str.c_str()); if ((fd = mkstemp(pattern_copy)) == -1) { return Err(fmt::format("unable to create temporary file: {} -- {}", pattern.string(), strerror(errno))); } return Ok(make_pair(ghc::filesystem::path(pattern_copy), fd)); } bool is_dev_null(const struct stat &st) { struct stat null_stat; stat("/dev/null", &null_stat); return st.st_dev == null_stat.st_dev && st.st_ino == null_stat.st_ino; } bool is_dev_null(int fd) { struct stat fd_stat; fstat(fd, &fd_stat); return is_dev_null(fd_stat); } std::string ok_prefix(std::string msg) { if (msg.empty()) { return msg; } return std::string(ANSI_COLOR(COLOR_GREEN) "\u2714" ANSI_NORM " ") + msg; } std::string err_prefix(const std::string msg) { if (msg.empty()) { return msg; } return std::string(ANSI_COLOR(COLOR_RED) "\u2718" ANSI_NORM " ") + msg; } Result<std::string, std::string> err_to_ok(const std::string msg) { return Ok(err_prefix(msg)); } <|endoftext|>
<commit_before>// A small, simple heap manager based (loosely) on the startup heap // based on the startup heap manager from FreeBSD. // // Manages a fixed-size memory pool, supports malloc and free only. // No support for realloc. // // Allocates chunks in multiples of four bytes, with a four byte header // for each chunk. The overhead of each chunk is kept low by keeping pointers // as two byte offsets within the heap, rather than (4 or 8 byte) pointers. namespace { static pthread_mutex_t heap_mutex = PTHREAD_MUTEX_INITIALIZER; class mutexor { public: mutexor ( pthread_mutex_t *m ) : mtx_(m) { pthread_mutex_lock ( mtx_ ); } ~mutexor () { pthread_mutex_unlock ( mtx_ ); } private: mutexor ( const mutexor &rhs ); mutexor & operator = ( const mutexor &rhs ); pthread_mutex_t *mtx_; }; #define HEAP_SIZE 512 char heap [ HEAP_SIZE ]; typedef unsigned short heap_offset; typedef unsigned short heap_size; struct heap_node { heap_offset next_node; // offset into heap heap_size len; // size in units of "sizeof(heap_node)" }; static const heap_node *list_end = (heap_node *) ( &heap [ HEAP_SIZE ] ); // one past the end of the heap static heap_node *freelist = NULL; heap_node *node_from_offset ( const heap_offset offset ) throw() { return (heap_node *) ( heap + ( offset * sizeof (heap_node))); } heap_offset offset_from_node ( const heap_node *ptr ) throw() { return (((char *) ptr ) - heap) / sizeof (heap_node); } void init_heap () throw() { freelist = (heap_node *) heap; freelist->next_node = offset_from_node ( list_end ); freelist->len = HEAP_SIZE / sizeof (heap_node); } // How big a chunk we allocate size_t alloc_size (size_t len) throw() { return (len + sizeof(heap_node) - 1) / sizeof(heap_node) + 1; } bool is_fallback_ptr ( void *ptr ) throw() { return ptr >= heap && ptr < ( heap + HEAP_SIZE ); } void *fallback_malloc(size_t len) throw() { heap_node *p, *prev; const size_t nelems = alloc_size ( len ); mutexor mtx ( &heap_mutex ); if ( NULL == freelist ) init_heap (); // Walk the free list, looking for a "big enough" chunk for (p = freelist, prev = 0; p && p != list_end; prev = p, p = node_from_offset ( p->next_node)) { if (p->len > nelems) { // chunk is larger, shorten, and return the tail heap_node *q; p->len -= nelems; q = p + p->len; q->next_node = 0; q->len = nelems; return (void *) (q + 1); } if (p->len == nelems) { // exact size match if (prev == 0) freelist = node_from_offset(p->next_node); else prev->next_node = p->next_node; p->next_node = 0; return (void *) (p + 1); } } return NULL; // couldn't find a spot big enough } // Return the start of the next block heap_node *after ( struct heap_node *p ) throw() { return p + p->len; } void fallback_free (void *ptr) throw() { struct heap_node *cp = ((struct heap_node *) ptr) - 1; // retrieve the chunk struct heap_node *p, *prev; mutexor mtx ( &heap_mutex ); #ifdef DEBUG_FALLBACK_MALLOC std::cout << "Freeing item at " << offset_from_node ( cp ) << " of size " << cp->len << std::endl; #endif for (p = freelist, prev = 0; p && p != list_end; prev = p, p = node_from_offset (p->next_node)) { #ifdef DEBUG_FALLBACK_MALLOC std::cout << " p, cp, after (p), after(cp) " << offset_from_node ( p ) << ' ' << offset_from_node ( cp ) << ' ' << offset_from_node ( after ( p )) << ' ' << offset_from_node ( after ( cp )) << std::endl; #endif if ( after ( p ) == cp ) { #ifdef DEBUG_FALLBACK_MALLOC std::cout << " Appending onto chunk at " << offset_from_node ( p ) << std::endl; #endif p->len += cp->len; // make the free heap_node larger return; } else if ( after ( cp ) == p ) { // there's a free heap_node right after #ifdef DEBUG_FALLBACK_MALLOC std::cout << " Appending free chunk at " << offset_from_node ( p ) << std::endl; #endif cp->len += p->len; if ( prev == 0 ) { freelist = cp; cp->next_node = p->next_node; } else prev->next_node = offset_from_node(cp); return; } } // Nothing to merge with, add it to the start of the free list #ifdef DEBUG_FALLBACK_MALLOC std::cout << " Making new free list entry " << offset_from_node ( cp ) << std::endl; #endif cp->next_node = offset_from_node ( freelist ); freelist = cp; } #ifdef INSTRUMENT_FALLBACK_MALLOC size_t print_free_list () { struct heap_node *p, *prev; heap_size total_free = 0; if ( NULL == freelist ) init_heap (); for (p = freelist, prev = 0; p && p != list_end; prev = p, p = node_from_offset (p->next_node)) { std::cout << ( prev == 0 ? "" : " ") << "Offset: " << offset_from_node ( p ) << "\tsize: " << p->len << " Next: " << p->next_node << std::endl; total_free += p->len; } std::cout << "Total Free space: " << total_free << std::endl; return total_free; } #endif } <commit_msg>Added copyright header<commit_after>//===------------------------ fallback_malloc.cpp -------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // // // This file implements the a small heap for allocation of exception // in the situation where malloc fails. // http://www.codesourcery.com/public/cxx-abi/abi-eh.html (section 2.4.2) // //===----------------------------------------------------------------------===// // A small, simple heap manager based (loosely) on the startup heap // based on the startup heap manager from FreeBSD. // // Manages a fixed-size memory pool, supports malloc and free only. // No support for realloc. // // Allocates chunks in multiples of four bytes, with a four byte header // for each chunk. The overhead of each chunk is kept low by keeping pointers // as two byte offsets within the heap, rather than (4 or 8 byte) pointers. namespace { static pthread_mutex_t heap_mutex = PTHREAD_MUTEX_INITIALIZER; class mutexor { public: mutexor ( pthread_mutex_t *m ) : mtx_(m) { pthread_mutex_lock ( mtx_ ); } ~mutexor () { pthread_mutex_unlock ( mtx_ ); } private: mutexor ( const mutexor &rhs ); mutexor & operator = ( const mutexor &rhs ); pthread_mutex_t *mtx_; }; #define HEAP_SIZE 512 char heap [ HEAP_SIZE ]; typedef unsigned short heap_offset; typedef unsigned short heap_size; struct heap_node { heap_offset next_node; // offset into heap heap_size len; // size in units of "sizeof(heap_node)" }; static const heap_node *list_end = (heap_node *) ( &heap [ HEAP_SIZE ] ); // one past the end of the heap static heap_node *freelist = NULL; heap_node *node_from_offset ( const heap_offset offset ) throw() { return (heap_node *) ( heap + ( offset * sizeof (heap_node))); } heap_offset offset_from_node ( const heap_node *ptr ) throw() { return (((char *) ptr ) - heap) / sizeof (heap_node); } void init_heap () throw() { freelist = (heap_node *) heap; freelist->next_node = offset_from_node ( list_end ); freelist->len = HEAP_SIZE / sizeof (heap_node); } // How big a chunk we allocate size_t alloc_size (size_t len) throw() { return (len + sizeof(heap_node) - 1) / sizeof(heap_node) + 1; } bool is_fallback_ptr ( void *ptr ) throw() { return ptr >= heap && ptr < ( heap + HEAP_SIZE ); } void *fallback_malloc(size_t len) throw() { heap_node *p, *prev; const size_t nelems = alloc_size ( len ); mutexor mtx ( &heap_mutex ); if ( NULL == freelist ) init_heap (); // Walk the free list, looking for a "big enough" chunk for (p = freelist, prev = 0; p && p != list_end; prev = p, p = node_from_offset ( p->next_node)) { if (p->len > nelems) { // chunk is larger, shorten, and return the tail heap_node *q; p->len -= nelems; q = p + p->len; q->next_node = 0; q->len = nelems; return (void *) (q + 1); } if (p->len == nelems) { // exact size match if (prev == 0) freelist = node_from_offset(p->next_node); else prev->next_node = p->next_node; p->next_node = 0; return (void *) (p + 1); } } return NULL; // couldn't find a spot big enough } // Return the start of the next block heap_node *after ( struct heap_node *p ) throw() { return p + p->len; } void fallback_free (void *ptr) throw() { struct heap_node *cp = ((struct heap_node *) ptr) - 1; // retrieve the chunk struct heap_node *p, *prev; mutexor mtx ( &heap_mutex ); #ifdef DEBUG_FALLBACK_MALLOC std::cout << "Freeing item at " << offset_from_node ( cp ) << " of size " << cp->len << std::endl; #endif for (p = freelist, prev = 0; p && p != list_end; prev = p, p = node_from_offset (p->next_node)) { #ifdef DEBUG_FALLBACK_MALLOC std::cout << " p, cp, after (p), after(cp) " << offset_from_node ( p ) << ' ' << offset_from_node ( cp ) << ' ' << offset_from_node ( after ( p )) << ' ' << offset_from_node ( after ( cp )) << std::endl; #endif if ( after ( p ) == cp ) { #ifdef DEBUG_FALLBACK_MALLOC std::cout << " Appending onto chunk at " << offset_from_node ( p ) << std::endl; #endif p->len += cp->len; // make the free heap_node larger return; } else if ( after ( cp ) == p ) { // there's a free heap_node right after #ifdef DEBUG_FALLBACK_MALLOC std::cout << " Appending free chunk at " << offset_from_node ( p ) << std::endl; #endif cp->len += p->len; if ( prev == 0 ) { freelist = cp; cp->next_node = p->next_node; } else prev->next_node = offset_from_node(cp); return; } } // Nothing to merge with, add it to the start of the free list #ifdef DEBUG_FALLBACK_MALLOC std::cout << " Making new free list entry " << offset_from_node ( cp ) << std::endl; #endif cp->next_node = offset_from_node ( freelist ); freelist = cp; } #ifdef INSTRUMENT_FALLBACK_MALLOC size_t print_free_list () { struct heap_node *p, *prev; heap_size total_free = 0; if ( NULL == freelist ) init_heap (); for (p = freelist, prev = 0; p && p != list_end; prev = p, p = node_from_offset (p->next_node)) { std::cout << ( prev == 0 ? "" : " ") << "Offset: " << offset_from_node ( p ) << "\tsize: " << p->len << " Next: " << p->next_node << std::endl; total_free += p->len; } std::cout << "Total Free space: " << total_free << std::endl; return total_free; } #endif } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <sstream> #include "../../main/models/combination/RandomChoosingCombinedModel.h" #include "../../main/models/combination/RandomChoosingCombinedModelExpertUpdater.h" namespace { class DummyModel : public Model { public: void add(RecDat*){ add_counter_++; } int add_counter_ = 0; double prediction(RecDat*){ return my_prediction_; } double my_prediction_ = 0.5; void read(istream&){ read_counter_++; } int read_counter_ = 0; void write(ostream&){ write_counter_++; } int write_counter_ = 0; }; class TestRandomChoosingCombinedModel : public ::testing::Test { public: DummyModel model1, model2, model3; vector<RecDat*> rec_dats; ExperimentEnvironment experiment_environment; OnlineExperimentParameters experiment_parameters; TestRandomChoosingCombinedModel(){} virtual ~TestRandomChoosingCombinedModel(){} virtual void SetUp(){ model1.my_prediction_ = 1; model2.my_prediction_ = 2; model3.my_prediction_ = 3; experiment_parameters.random_seed = 231243; experiment_environment.set_parameters(&experiment_parameters); } RecDat* create_rec_dat(int user, int item, double time, double score){ RecDat* rec_dat = new RecDat; rec_dat -> user = user; rec_dat -> item = item; rec_dat -> time = time; rec_dat -> id = rec_dats.size(); rec_dat -> category = 0; rec_dat -> score = score; rec_dats.push_back(rec_dat); return rec_dat; } virtual void TearDown(){ for (vector<RecDat*>::iterator it = rec_dats.begin();it!=rec_dats.end();it++){ delete *it; } } }; class DummyEvaluator : public Evaluator { public: double get_score(RecDat*){ return my_score_; } double my_score_ = 0.5; }; class TestRandomChoosingCombinedModelExpertUpdater : public ::testing::Test { public: DummyModel model1, model2, model3; vector<RecDat*> rec_dats; ExperimentEnvironment experiment_environment; OnlineExperimentParameters experiment_parameters; TestRandomChoosingCombinedModelExpertUpdater(){} virtual ~TestRandomChoosingCombinedModelExpertUpdater(){} virtual void SetUp(){ model1.my_prediction_ = 1; model2.my_prediction_ = 2; model3.my_prediction_ = 3; experiment_parameters.random_seed = 231243; experiment_environment.set_parameters(&experiment_parameters); } RecDat* create_rec_dat(int user, int item, double time, double score){ RecDat* rec_dat = new RecDat; rec_dat -> user = user; rec_dat -> item = item; rec_dat -> time = time; rec_dat -> id = rec_dats.size(); rec_dat -> category = 0; rec_dat -> score = score; rec_dats.push_back(rec_dat); return rec_dat; } virtual void TearDown(){ for (vector<RecDat*>::iterator it = rec_dats.begin();it!=rec_dats.end();it++){ delete *it; } } }; } //namespace TEST_F(TestRandomChoosingCombinedModelExpertUpdater, weights){ RandomChoosingCombinedModelParameters params; RandomChoosingCombinedModel model(&params); model.add_model(&model1); model.add_model(&model2); model.add_model(&model3); model.set_experiment_environment(&experiment_environment); RandomChoosingCombinedModelExpertUpdaterParameters updater_params; updater_params.eta=0.1; updater_params.loss_type="other"; RandomChoosingCombinedModelExpertUpdater updater(&updater_params); updater.set_model(&model); vector<Evaluator*> evaluators; for(int i=0;i++;i<3){ evaluators.push_back(new DummyEvaluator); } updater.set_evaluators(evaluators); EXPECT_TRUE(model.initialize()); EXPECT_TRUE(updater.initialize()); EXPECT_TRUE(model.self_test()); EXPECT_TRUE(updater.self_test()); } TEST_F(TestRandomChoosingCombinedModel, add){ RandomChoosingCombinedModelParameters params; RandomChoosingCombinedModel model(&params); model.add_model(&model1); model.add_model(&model2); model.add_model(&model3); model.set_experiment_environment(&experiment_environment); EXPECT_TRUE(model.initialize()); EXPECT_TRUE(model.self_test()); model.add(create_rec_dat(1,2,10.0,1)); EXPECT_EQ(1,model1.add_counter_); EXPECT_EQ(1,model2.add_counter_); EXPECT_EQ(1,model3.add_counter_); model.add(create_rec_dat(2,2,10.0,1)); EXPECT_EQ(2,model1.add_counter_); EXPECT_EQ(2,model2.add_counter_); EXPECT_EQ(2,model3.add_counter_); model.add(create_rec_dat(2,3,10.0,1)); EXPECT_EQ(3,model1.add_counter_); EXPECT_EQ(3,model2.add_counter_); EXPECT_EQ(3,model3.add_counter_); } TEST_F(TestRandomChoosingCombinedModel, prediction_id_change){ RandomChoosingCombinedModelParameters params; RandomChoosingCombinedModel model(&params); model.add_model(&model1); model.add_model(&model2); model.add_model(&model3); model.set_experiment_environment(&experiment_environment); EXPECT_TRUE(model.initialize()); EXPECT_TRUE(model.self_test()); //initial distribution: 0.33 0.33 0.33 //id change -> generate new model, p of model eq = 0.33 int last_model = 0; int eq = 0; int all = 1000; for(int i=0;i<all;i++){ int pred = model.prediction(create_rec_dat(2,3,10.0,1)); if(pred==last_model) eq++; last_model = pred; } EXPECT_NEAR(all/3,eq,25); } TEST_F(TestRandomChoosingCombinedModel, prediction_user_change){ RandomChoosingCombinedModelParameters params; RandomChoosingCombinedModel model(&params); model.add_model(&model1); model.add_model(&model2); model.add_model(&model3); model.set_experiment_environment(&experiment_environment); EXPECT_TRUE(model.initialize()); EXPECT_TRUE(model.self_test()); //initial distribution: 0.33 0.33 0.33 //user change -> generate new model, p of model eq = 0.33 int last_model = 0; int eq = 0; int all = 1000; RecDat* rec_dat = create_rec_dat(2,3,10.0,1); for(int i=0;i<all;i++){ rec_dat->user = i; int pred = model.prediction(rec_dat); if(pred==last_model) eq++; last_model = pred; } EXPECT_NEAR(all/3,eq,25); } TEST_F(TestRandomChoosingCombinedModel, prediction_item_change){ RandomChoosingCombinedModelParameters params; RandomChoosingCombinedModel model(&params); model.add_model(&model1); model.add_model(&model2); model.add_model(&model3); model.set_experiment_environment(&experiment_environment); EXPECT_TRUE(model.initialize()); EXPECT_TRUE(model.self_test()); //initial distribution: 0.33 0.33 0.33 //item change -> do not generate new model int last_model = 0; int eq = 0; int all = 10; for(int j=0;j<10;j++){ RecDat* rec_dat = create_rec_dat(2,3,10.0,1); for(int i=0;i<all;i++){ rec_dat->item = i; int pred = model.prediction(rec_dat); if(pred==last_model) eq++; last_model = pred; } EXPECT_EQ(all-1,eq); eq = 0; last_model = 0; } } TEST_F(TestRandomChoosingCombinedModel, prediction_distribution){ RandomChoosingCombinedModelParameters params; RandomChoosingCombinedModel model(&params); model.add_model(&model1); model.add_model(&model2); model.add_model(&model3); model.set_experiment_environment(&experiment_environment); EXPECT_TRUE(model.initialize()); EXPECT_TRUE(model.self_test()); int all = 10000; vector<int> experienced_distribution(3); //distribution: 0.1 0.7 0.2 vector<double> expected_distribution = {0.1,0.7,0.2}; model.distribution_ = expected_distribution; //id change -> generate new model for(int i=0;i<all;i++){ uint pred = model.prediction(create_rec_dat(2,3,10.0,1))-1; ASSERT_LT(pred,3); experienced_distribution[pred]++; } for(int i=0;i<expected_distribution.size();i++){ EXPECT_NEAR(expected_distribution[i], (double)experienced_distribution[i]/all,0.05); } experienced_distribution.clear(); experienced_distribution.resize(3,0); //distribution: 0.3 0.3 0.1 (->0.3 0.3 0.4) model.distribution_ = {0.3,0.3,0.1}; expected_distribution = {0.3,0.3,0.4}; //id change -> generate new model for(int i=0;i<all;i++){ uint pred = model.prediction(create_rec_dat(2,3,10.0,1))-1; ASSERT_LT(pred,3); experienced_distribution[pred]++; } for(int i=0;i<expected_distribution.size();i++){ EXPECT_NEAR(expected_distribution[i], (double)experienced_distribution[i]/all,0.05); } } TEST_F(TestRandomChoosingCombinedModel, read_write){ RandomChoosingCombinedModelParameters params; RandomChoosingCombinedModel model(&params); model.add_model(&model1); model.add_model(&model2); model.add_model(&model3); model.set_experiment_environment(&experiment_environment); EXPECT_TRUE(model.initialize()); EXPECT_TRUE(model.self_test()); stringstream ss; model.write(ss); EXPECT_EQ(1,model1.write_counter_); EXPECT_EQ(1,model2.write_counter_); EXPECT_EQ(1,model3.write_counter_); model.read(ss); EXPECT_EQ(1,model1.read_counter_); EXPECT_EQ(1,model2.read_counter_); EXPECT_EQ(1,model3.read_counter_); } int main (int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Exp: test ok, failing<commit_after>#include <gtest/gtest.h> #include <sstream> #include "../../main/models/combination/RandomChoosingCombinedModel.h" #include "../../main/models/combination/RandomChoosingCombinedModelExpertUpdater.h" namespace { class DummyModel : public Model { public: void add(RecDat*){ add_counter_++; } int add_counter_ = 0; double prediction(RecDat*){ return my_prediction_; } double my_prediction_ = 0.5; void read(istream&){ read_counter_++; } int read_counter_ = 0; void write(ostream&){ write_counter_++; } int write_counter_ = 0; }; class TestRandomChoosingCombinedModel : public ::testing::Test { public: DummyModel model1, model2, model3; vector<RecDat*> rec_dats; ExperimentEnvironment experiment_environment; OnlineExperimentParameters experiment_parameters; TestRandomChoosingCombinedModel(){} virtual ~TestRandomChoosingCombinedModel(){} virtual void SetUp(){ model1.my_prediction_ = 1; model2.my_prediction_ = 2; model3.my_prediction_ = 3; experiment_parameters.random_seed = 231243; experiment_environment.set_parameters(&experiment_parameters); } RecDat* create_rec_dat(int user, int item, double time, double score){ RecDat* rec_dat = new RecDat; rec_dat -> user = user; rec_dat -> item = item; rec_dat -> time = time; rec_dat -> id = rec_dats.size(); rec_dat -> category = 0; rec_dat -> score = score; rec_dats.push_back(rec_dat); return rec_dat; } virtual void TearDown(){ for (vector<RecDat*>::iterator it = rec_dats.begin();it!=rec_dats.end();it++){ delete *it; } } }; class DummyEvaluator : public Evaluator { public: double get_score(RecDat*){ return my_score_; } double my_score_ = 0.5; }; class TestRandomChoosingCombinedModelExpertUpdater : public ::testing::Test { public: DummyModel model1, model2, model3; vector<RecDat*> rec_dats; ExperimentEnvironment experiment_environment; OnlineExperimentParameters experiment_parameters; TestRandomChoosingCombinedModelExpertUpdater(){} virtual ~TestRandomChoosingCombinedModelExpertUpdater(){} virtual void SetUp(){ model1.my_prediction_ = 1; model2.my_prediction_ = 2; model3.my_prediction_ = 3; experiment_parameters.random_seed = 231243; experiment_environment.set_parameters(&experiment_parameters); } RecDat* create_rec_dat(int user, int item, double time, double score){ RecDat* rec_dat = new RecDat; rec_dat -> user = user; rec_dat -> item = item; rec_dat -> time = time; rec_dat -> id = rec_dats.size(); rec_dat -> category = 0; rec_dat -> score = score; rec_dats.push_back(rec_dat); return rec_dat; } virtual void TearDown(){ for (vector<RecDat*>::iterator it = rec_dats.begin();it!=rec_dats.end();it++){ delete *it; } } }; } //namespace TEST_F(TestRandomChoosingCombinedModelExpertUpdater, weights){ RandomChoosingCombinedModelParameters params; RandomChoosingCombinedModel model(&params); model.add_model(&model1); model.add_model(&model2); model.add_model(&model3); model.set_experiment_environment(&experiment_environment); RandomChoosingCombinedModelExpertUpdaterParameters updater_params; updater_params.eta=0.1; updater_params.loss_type="other"; RandomChoosingCombinedModelExpertUpdater updater(&updater_params); updater.set_model(&model); vector<Evaluator*> evaluators; for(int i=0;i<3;i++){ DummyEvaluator* evaluator = new DummyEvaluator; evaluator->my_score_ = i+1; evaluators.push_back(evaluator); } updater.set_evaluators(evaluators); EXPECT_TRUE(model.initialize()); EXPECT_TRUE(updater.initialize()); EXPECT_TRUE(model.self_test()); EXPECT_TRUE(updater.self_test()); updater.update(create_rec_dat(1,2,10.0,1)); updater.update(create_rec_dat(1,3,10.0,1)); updater.update(create_rec_dat(1,4,10.0,1)); updater.update(create_rec_dat(1,5,10.0,1)); vector<int> predictions(4); for(int i=0;i<1000;i++){ double prediction = model.prediction(create_rec_dat(1,5,10.0,1)); EXPECT_LT(prediction,4.0); EXPECT_GE(prediction,0.0); predictions[prediction]++; } EXPECT_GT(predictions[1],predictions[2]); EXPECT_GT(predictions[2],predictions[3]); for(auto pred:predictions){ cerr << pred << " "; } cerr << endl; } TEST_F(TestRandomChoosingCombinedModel, add){ RandomChoosingCombinedModelParameters params; RandomChoosingCombinedModel model(&params); model.add_model(&model1); model.add_model(&model2); model.add_model(&model3); model.set_experiment_environment(&experiment_environment); EXPECT_TRUE(model.initialize()); EXPECT_TRUE(model.self_test()); model.add(create_rec_dat(1,2,10.0,1)); EXPECT_EQ(1,model1.add_counter_); EXPECT_EQ(1,model2.add_counter_); EXPECT_EQ(1,model3.add_counter_); model.add(create_rec_dat(2,2,10.0,1)); EXPECT_EQ(2,model1.add_counter_); EXPECT_EQ(2,model2.add_counter_); EXPECT_EQ(2,model3.add_counter_); model.add(create_rec_dat(2,3,10.0,1)); EXPECT_EQ(3,model1.add_counter_); EXPECT_EQ(3,model2.add_counter_); EXPECT_EQ(3,model3.add_counter_); } TEST_F(TestRandomChoosingCombinedModel, prediction_id_change){ RandomChoosingCombinedModelParameters params; RandomChoosingCombinedModel model(&params); model.add_model(&model1); model.add_model(&model2); model.add_model(&model3); model.set_experiment_environment(&experiment_environment); EXPECT_TRUE(model.initialize()); EXPECT_TRUE(model.self_test()); //initial distribution: 0.33 0.33 0.33 //id change -> generate new model, p of model eq = 0.33 int last_model = 0; int eq = 0; int all = 1000; for(int i=0;i<all;i++){ int pred = model.prediction(create_rec_dat(2,3,10.0,1)); if(pred==last_model) eq++; last_model = pred; } EXPECT_NEAR(all/3,eq,25); } TEST_F(TestRandomChoosingCombinedModel, prediction_user_change){ RandomChoosingCombinedModelParameters params; RandomChoosingCombinedModel model(&params); model.add_model(&model1); model.add_model(&model2); model.add_model(&model3); model.set_experiment_environment(&experiment_environment); EXPECT_TRUE(model.initialize()); EXPECT_TRUE(model.self_test()); //initial distribution: 0.33 0.33 0.33 //user change -> generate new model, p of model eq = 0.33 int last_model = 0; int eq = 0; int all = 1000; RecDat* rec_dat = create_rec_dat(2,3,10.0,1); for(int i=0;i<all;i++){ rec_dat->user = i; int pred = model.prediction(rec_dat); if(pred==last_model) eq++; last_model = pred; } EXPECT_NEAR(all/3,eq,25); } TEST_F(TestRandomChoosingCombinedModel, prediction_item_change){ RandomChoosingCombinedModelParameters params; RandomChoosingCombinedModel model(&params); model.add_model(&model1); model.add_model(&model2); model.add_model(&model3); model.set_experiment_environment(&experiment_environment); EXPECT_TRUE(model.initialize()); EXPECT_TRUE(model.self_test()); //initial distribution: 0.33 0.33 0.33 //item change -> do not generate new model int last_model = 0; int eq = 0; int all = 10; for(int j=0;j<10;j++){ RecDat* rec_dat = create_rec_dat(2,3,10.0,1); for(int i=0;i<all;i++){ rec_dat->item = i; int pred = model.prediction(rec_dat); if(pred==last_model) eq++; last_model = pred; } EXPECT_EQ(all-1,eq); eq = 0; last_model = 0; } } TEST_F(TestRandomChoosingCombinedModel, prediction_distribution){ RandomChoosingCombinedModelParameters params; RandomChoosingCombinedModel model(&params); model.add_model(&model1); model.add_model(&model2); model.add_model(&model3); model.set_experiment_environment(&experiment_environment); EXPECT_TRUE(model.initialize()); EXPECT_TRUE(model.self_test()); int all = 10000; vector<int> experienced_distribution(3); //distribution: 0.1 0.7 0.2 vector<double> expected_distribution = {0.1,0.7,0.2}; model.distribution_ = expected_distribution; //id change -> generate new model for(int i=0;i<all;i++){ uint pred = model.prediction(create_rec_dat(2,3,10.0,1))-1; ASSERT_LT(pred,3); experienced_distribution[pred]++; } for(int i=0;i<expected_distribution.size();i++){ EXPECT_NEAR(expected_distribution[i], (double)experienced_distribution[i]/all,0.05); } experienced_distribution.clear(); experienced_distribution.resize(3,0); //distribution: 0.3 0.3 0.1 (->0.3 0.3 0.4) model.distribution_ = {0.3,0.3,0.1}; expected_distribution = {0.3,0.3,0.4}; //id change -> generate new model for(int i=0;i<all;i++){ uint pred = model.prediction(create_rec_dat(2,3,10.0,1))-1; ASSERT_LT(pred,3); experienced_distribution[pred]++; } for(uint i=0;i<expected_distribution.size();i++){ EXPECT_NEAR(expected_distribution[i], (double)experienced_distribution[i]/all,0.05); } } TEST_F(TestRandomChoosingCombinedModel, read_write){ RandomChoosingCombinedModelParameters params; RandomChoosingCombinedModel model(&params); model.add_model(&model1); model.add_model(&model2); model.add_model(&model3); model.set_experiment_environment(&experiment_environment); EXPECT_TRUE(model.initialize()); EXPECT_TRUE(model.self_test()); stringstream ss; model.write(ss); EXPECT_EQ(1,model1.write_counter_); EXPECT_EQ(1,model2.write_counter_); EXPECT_EQ(1,model3.write_counter_); model.read(ss); EXPECT_EQ(1,model1.read_counter_); EXPECT_EQ(1,model2.read_counter_); EXPECT_EQ(1,model3.read_counter_); } int main (int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) [2016] [BTC.COM] 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 <stdlib.h> #include <stdio.h> #include <signal.h> #include <err.h> #include <errno.h> #include <unistd.h> #include <iostream> #include <boost/interprocess/sync/file_lock.hpp> #include <glog/logging.h> #include <libconfig.h++> #include "zmq.hpp" #include "Utils.h" #include "StatsHttpd.h" #include "RedisConnection.h" using namespace std; using namespace libconfig; std::shared_ptr<StatsServer> gStatsServer = nullptr; void handler(int sig) { if (gStatsServer) { gStatsServer->stop(); } } void usage() { fprintf(stderr, "Usage:\n\tstatshttpd -c \"statshttpd.cfg\" -l \"log_dir\"\n"); } std::shared_ptr<StatsServer> newStatsServer(const string &chainType, const char *kafkaBrokers, const char *kafkaShareTopic, const char *kafkaCommonEventsTopic, const string &httpdHost, unsigned short httpdPort, const MysqlConnectInfo *poolDBInfo, const RedisConnectInfo *redisInfo, const uint32_t redisConcurrency, const string &redisKeyPrefix, const int redisKeyExpire, const int redisPublishPolicy, const int redisIndexPolicy, const time_t kFlushDBInterval, const string &fileLastFlushTime, const int dupShareTrackingHeight) { if (chainType == "BTC") { return std::make_shared<StatsServerBitcoin>(kafkaBrokers, kafkaShareTopic, kafkaCommonEventsTopic, httpdHost, httpdPort, poolDBInfo, redisInfo, redisConcurrency, redisKeyPrefix, redisKeyExpire, redisPublishPolicy, redisIndexPolicy, kFlushDBInterval, fileLastFlushTime, nullptr); } else if (chainType == "ETH") { return std::make_shared<StatsServerEth>(kafkaBrokers, kafkaShareTopic, kafkaCommonEventsTopic, httpdHost, httpdPort, poolDBInfo, redisInfo, redisConcurrency, redisKeyPrefix, redisKeyExpire, redisPublishPolicy, redisIndexPolicy, kFlushDBInterval, fileLastFlushTime, std::make_shared<DuplicateShareCheckerEth>(dupShareTrackingHeight)); } else if (chainType == "BTM") { return std::make_shared<StatsServerBytom>(kafkaBrokers, kafkaShareTopic, kafkaCommonEventsTopic, httpdHost, httpdPort, poolDBInfo, kFlushDBInterval, fileLastFlushTime, std::make_shared<DuplicateShareCheckerBytom>(dupShareTrackingHeight)); } else { LOG(FATAL) << "newStatsServer: unknown chain type " << chainType; return nullptr; } } int main(int argc, char **argv) { char *optLogDir = NULL; char *optConf = NULL; int c; if (argc <= 1) { usage(); return 1; } while ((c = getopt(argc, argv, "c:l:h")) != -1) { switch (c) { case 'c': optConf = optarg; break; case 'l': optLogDir = optarg; break; case 'h': default: usage(); exit(0); } } // Initialize Google's logging library. google::InitGoogleLogging(argv[0]); FLAGS_log_dir = string(optLogDir); // Log messages at a level >= this flag are automatically sent to // stderr in addition to log files. FLAGS_stderrthreshold = 3; // 3: FATAL FLAGS_max_log_size = 100; // max log file size 100 MB FLAGS_logbuflevel = -1; // don't buffer logs FLAGS_stop_logging_if_full_disk = true; // Read the file. If there is an error, report it and exit. libconfig::Config cfg; try { cfg.readFile(optConf); } catch(const FileIOException &fioex) { std::cerr << "I/O error while reading file." << std::endl; return(EXIT_FAILURE); } catch(const ParseException &pex) { std::cerr << "Parse error at " << pex.getFile() << ":" << pex.getLine() << " - " << pex.getError() << std::endl; return(EXIT_FAILURE); } // lock cfg file: // you can't run more than one process with the same config file boost::interprocess::file_lock pidFileLock(optConf); if (pidFileLock.try_lock() == false) { LOG(FATAL) << "lock cfg file fail"; return(EXIT_FAILURE); } signal(SIGTERM, handler); signal(SIGINT, handler); try { bool useMysql = true; cfg.lookupValue("statshttpd.use_mysql", useMysql); bool useRedis = false; cfg.lookupValue("statshttpd.use_redis", useRedis); MysqlConnectInfo *poolDBInfo = nullptr; if (useMysql) { int32_t poolDBPort = 3306; cfg.lookupValue("pooldb.port", poolDBPort); poolDBInfo = new MysqlConnectInfo(cfg.lookup("pooldb.host"), poolDBPort, cfg.lookup("pooldb.username"), cfg.lookup("pooldb.password"), cfg.lookup("pooldb.dbname")); } RedisConnectInfo *redisInfo = nullptr; string redisKeyPrefix; int redisKeyExpire = 0; int redisPublishPolicy = 0; int redisIndexPolicy = 0; uint32_t redisConcurrency = 1; if (useRedis) { int32_t redisPort = 6379; cfg.lookupValue("redis.port", redisPort); redisInfo = new RedisConnectInfo(cfg.lookup("redis.host"), redisPort, cfg.lookup("redis.password")); cfg.lookupValue("redis.key_prefix", redisKeyPrefix); cfg.lookupValue("redis.key_expire", redisKeyExpire); cfg.lookupValue("redis.publish_policy", redisPublishPolicy); cfg.lookupValue("redis.index_policy", redisIndexPolicy); cfg.lookupValue("redis.concurrency", redisConcurrency); } string fileLastFlushTime; int32_t port = 8080; int32_t flushInterval = 20; int32_t dupShareTrackingHeight = 3; cfg.lookupValue("statshttpd.port", port); cfg.lookupValue("statshttpd.flush_db_interval", flushInterval); cfg.lookupValue("statshttpd.file_last_flush_time", fileLastFlushTime); cfg.lookupValue("dup_share_checker.tracking_height_number", dupShareTrackingHeight); gStatsServer = newStatsServer(cfg.lookup("statshttpd.chain_type"), cfg.lookup("kafka.brokers").c_str(), cfg.lookup("statshttpd.share_topic").c_str(), cfg.lookup("statshttpd.common_events_topic").c_str(), cfg.lookup("statshttpd.ip").c_str(), (unsigned short)port, poolDBInfo, redisInfo, redisConcurrency, redisKeyPrefix, redisKeyExpire, redisPublishPolicy, redisIndexPolicy, (time_t)flushInterval, fileLastFlushTime, dupShareTrackingHeight); if (gStatsServer->init()) { gStatsServer->run(); } } catch (std::exception & e) { LOG(FATAL) << "exception: " << e.what(); return 1; } google::ShutdownGoogleLogging(); return 0; } <commit_msg>Temporary fix compile error<commit_after>/* The MIT License (MIT) Copyright (c) [2016] [BTC.COM] 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 <stdlib.h> #include <stdio.h> #include <signal.h> #include <err.h> #include <errno.h> #include <unistd.h> #include <iostream> #include <boost/interprocess/sync/file_lock.hpp> #include <glog/logging.h> #include <libconfig.h++> #include "zmq.hpp" #include "Utils.h" #include "StatsHttpd.h" #include "RedisConnection.h" using namespace std; using namespace libconfig; std::shared_ptr<StatsServer> gStatsServer = nullptr; void handler(int sig) { if (gStatsServer) { gStatsServer->stop(); } } void usage() { fprintf(stderr, "Usage:\n\tstatshttpd -c \"statshttpd.cfg\" -l \"log_dir\"\n"); } std::shared_ptr<StatsServer> newStatsServer(const string &chainType, const char *kafkaBrokers, const char *kafkaShareTopic, const char *kafkaCommonEventsTopic, const string &httpdHost, unsigned short httpdPort, const MysqlConnectInfo *poolDBInfo, const RedisConnectInfo *redisInfo, const uint32_t redisConcurrency, const string &redisKeyPrefix, const int redisKeyExpire, const int redisPublishPolicy, const int redisIndexPolicy, const time_t kFlushDBInterval, const string &fileLastFlushTime, const int dupShareTrackingHeight) { if (chainType == "BTC") { return std::make_shared<StatsServerBitcoin>(kafkaBrokers, kafkaShareTopic, kafkaCommonEventsTopic, httpdHost, httpdPort, poolDBInfo, redisInfo, redisConcurrency, redisKeyPrefix, redisKeyExpire, redisPublishPolicy, redisIndexPolicy, kFlushDBInterval, fileLastFlushTime, nullptr); } else if (chainType == "ETH") { return std::make_shared<StatsServerEth>(kafkaBrokers, kafkaShareTopic, kafkaCommonEventsTopic, httpdHost, httpdPort, poolDBInfo, redisInfo, redisConcurrency, redisKeyPrefix, redisKeyExpire, redisPublishPolicy, redisIndexPolicy, kFlushDBInterval, fileLastFlushTime, std::make_shared<DuplicateShareCheckerEth>(dupShareTrackingHeight)); } // else if (chainType == "BTM") { // return std::make_shared<StatsServerBytom>(kafkaBrokers, kafkaShareTopic, kafkaCommonEventsTopic, // httpdHost, httpdPort, poolDBInfo, // kFlushDBInterval, fileLastFlushTime, // std::make_shared<DuplicateShareCheckerBytom>(dupShareTrackingHeight)); // } else { LOG(FATAL) << "newStatsServer: unknown chain type " << chainType; return nullptr; } } int main(int argc, char **argv) { char *optLogDir = NULL; char *optConf = NULL; int c; if (argc <= 1) { usage(); return 1; } while ((c = getopt(argc, argv, "c:l:h")) != -1) { switch (c) { case 'c': optConf = optarg; break; case 'l': optLogDir = optarg; break; case 'h': default: usage(); exit(0); } } // Initialize Google's logging library. google::InitGoogleLogging(argv[0]); FLAGS_log_dir = string(optLogDir); // Log messages at a level >= this flag are automatically sent to // stderr in addition to log files. FLAGS_stderrthreshold = 3; // 3: FATAL FLAGS_max_log_size = 100; // max log file size 100 MB FLAGS_logbuflevel = -1; // don't buffer logs FLAGS_stop_logging_if_full_disk = true; // Read the file. If there is an error, report it and exit. libconfig::Config cfg; try { cfg.readFile(optConf); } catch(const FileIOException &fioex) { std::cerr << "I/O error while reading file." << std::endl; return(EXIT_FAILURE); } catch(const ParseException &pex) { std::cerr << "Parse error at " << pex.getFile() << ":" << pex.getLine() << " - " << pex.getError() << std::endl; return(EXIT_FAILURE); } // lock cfg file: // you can't run more than one process with the same config file boost::interprocess::file_lock pidFileLock(optConf); if (pidFileLock.try_lock() == false) { LOG(FATAL) << "lock cfg file fail"; return(EXIT_FAILURE); } signal(SIGTERM, handler); signal(SIGINT, handler); try { bool useMysql = true; cfg.lookupValue("statshttpd.use_mysql", useMysql); bool useRedis = false; cfg.lookupValue("statshttpd.use_redis", useRedis); MysqlConnectInfo *poolDBInfo = nullptr; if (useMysql) { int32_t poolDBPort = 3306; cfg.lookupValue("pooldb.port", poolDBPort); poolDBInfo = new MysqlConnectInfo(cfg.lookup("pooldb.host"), poolDBPort, cfg.lookup("pooldb.username"), cfg.lookup("pooldb.password"), cfg.lookup("pooldb.dbname")); } RedisConnectInfo *redisInfo = nullptr; string redisKeyPrefix; int redisKeyExpire = 0; int redisPublishPolicy = 0; int redisIndexPolicy = 0; uint32_t redisConcurrency = 1; if (useRedis) { int32_t redisPort = 6379; cfg.lookupValue("redis.port", redisPort); redisInfo = new RedisConnectInfo(cfg.lookup("redis.host"), redisPort, cfg.lookup("redis.password")); cfg.lookupValue("redis.key_prefix", redisKeyPrefix); cfg.lookupValue("redis.key_expire", redisKeyExpire); cfg.lookupValue("redis.publish_policy", redisPublishPolicy); cfg.lookupValue("redis.index_policy", redisIndexPolicy); cfg.lookupValue("redis.concurrency", redisConcurrency); } string fileLastFlushTime; int32_t port = 8080; int32_t flushInterval = 20; int32_t dupShareTrackingHeight = 3; cfg.lookupValue("statshttpd.port", port); cfg.lookupValue("statshttpd.flush_db_interval", flushInterval); cfg.lookupValue("statshttpd.file_last_flush_time", fileLastFlushTime); cfg.lookupValue("dup_share_checker.tracking_height_number", dupShareTrackingHeight); gStatsServer = newStatsServer(cfg.lookup("statshttpd.chain_type"), cfg.lookup("kafka.brokers").c_str(), cfg.lookup("statshttpd.share_topic").c_str(), cfg.lookup("statshttpd.common_events_topic").c_str(), cfg.lookup("statshttpd.ip").c_str(), (unsigned short)port, poolDBInfo, redisInfo, redisConcurrency, redisKeyPrefix, redisKeyExpire, redisPublishPolicy, redisIndexPolicy, (time_t)flushInterval, fileLastFlushTime, dupShareTrackingHeight); if (gStatsServer->init()) { gStatsServer->run(); } } catch (std::exception & e) { LOG(FATAL) << "exception: " << e.what(); return 1; } google::ShutdownGoogleLogging(); return 0; } <|endoftext|>
<commit_before> #include <gtest/gtest.h> #include <aerial_autonomy/common/conversions.h> #include <aerial_autonomy/controller_connectors/rpyt_relative_pose_visual_servoing_connector.h> #include <aerial_autonomy/controllers/rpyt_based_relative_pose_controller.h> #include <aerial_autonomy/tests/test_utils.h> #include <aerial_autonomy/trackers/simple_tracker.h> #include <chrono> #include <quad_simulator_parser/quad_simulator.h> #include <thread> /** * @brief Namespace for UAV Simulator Hardware */ using namespace quad_simulator; using namespace test_utils; class RPYTRelativePoseVisualConnectorTests : public ::testing::Test { public: RPYTRelativePoseVisualConnectorTests() : goal_tolerance_position_(0.05), goal_tolerance_velocity_(0.1), goal_tolerance_yaw_(0.05), goal_tolerance_yaw_rate_(0.05), tracking_offset_transform_( tf::createQuaternionFromRPY(0, M_PI / 3, M_PI / 2), tf::Vector3(0, 0, 0)), thrust_gain_estimator_(0.18) { RPYTBasedRelativePoseControllerConfig config; auto velocity_relative_pose_config = config.mutable_velocity_based_relative_pose_controller_config(); auto position_controller_config = velocity_relative_pose_config ->mutable_velocity_based_position_controller_config(); position_controller_config->set_position_gain(1.0); position_controller_config->set_max_velocity(1.0); position_controller_config->set_yaw_gain(1.0); position_controller_config->set_max_yaw_rate(1.0); position_controller_config->set_yaw_i_gain(0.0); position_controller_config->set_position_i_gain(0.0); position_controller_config->set_position_saturation_value(0.0); position_controller_config->set_yaw_saturation_value(0.0); position_controller_config->mutable_position_controller_config() ->set_goal_yaw_tolerance(goal_tolerance_yaw_); auto position_tolerance = position_controller_config->mutable_position_controller_config() ->mutable_goal_position_tolerance(); position_tolerance->set_x(goal_tolerance_position_); position_tolerance->set_y(goal_tolerance_position_); position_tolerance->set_z(goal_tolerance_position_); auto rpyt_velocity_controller_config = config.mutable_rpyt_based_velocity_controller_config(); rpyt_velocity_controller_config->mutable_velocity_controller_config() ->set_goal_yaw_tolerance(goal_tolerance_yaw_); auto goal_velocity_tolerance = rpyt_velocity_controller_config->mutable_velocity_controller_config() ->mutable_goal_velocity_tolerance(); goal_velocity_tolerance->set_vx(goal_tolerance_velocity_); goal_velocity_tolerance->set_vy(goal_tolerance_velocity_); goal_velocity_tolerance->set_vz(goal_tolerance_velocity_); tf::Transform camera_transform = tf::Transform::getIdentity(); simple_tracker_.reset(new SimpleTracker(drone_hardware_, camera_transform)); controller_.reset(new RPYTBasedRelativePoseController( config, std::chrono::milliseconds(20))); visual_servoing_connector_.reset( new RPYTRelativePoseVisualServoingConnector( *simple_tracker_, drone_hardware_, *controller_, thrust_gain_estimator_, camera_transform, tracking_offset_transform_)); drone_hardware_.usePerfectTime(); } static void SetUpTestCase() { // Configure logging LogConfig log_config; log_config.set_directory("/tmp/data"); Log::instance().configure(log_config); DataStreamConfig data_config; data_config.set_stream_id("rpyt_relative_pose_visual_servoing_connector"); Log::instance().addDataStream(data_config); data_config.set_stream_id("velocity_based_position_controller"); Log::instance().addDataStream(data_config); data_config.set_stream_id("rpyt_based_velocity_controller"); Log::instance().addDataStream(data_config); data_config.set_stream_id("velocity_based_relative_pose_controller"); Log::instance().addDataStream(data_config); data_config.set_stream_id("thrust_gain_estimator"); Log::instance().addDataStream(data_config); data_config.set_stream_id("tracking_vector_estimator"); Log::instance().addDataStream(data_config); } void runUntilConvergence(const tf::Transform &tracked_pose, const PositionYaw &goal_relative_pose) { simple_tracker_->setTargetPoseGlobalFrame(tracked_pose); simple_tracker_->setTrackingIsValid(true); tf::Transform gravity_aligned_tracked_pose = tracked_pose * tracking_offset_transform_; double roll, pitch, yaw; gravity_aligned_tracked_pose.getBasis().getRPY(roll, pitch, yaw); gravity_aligned_tracked_pose.getBasis().setRPY(0, 0, yaw); // Fly quadrotor which sets the altitude to 0.5 drone_hardware_.setBatteryPercent(60); drone_hardware_.takeoff(); // Set goal tf::Transform goal_relative_pose_tf; conversions::positionYawToTf(goal_relative_pose, goal_relative_pose_tf); visual_servoing_connector_->setGoal(goal_relative_pose); // Run controller until inactive auto runController = [&]() { visual_servoing_connector_->run(); return visual_servoing_connector_->getStatus() == ControllerStatus::Active; }; ASSERT_FALSE(test_utils::waitUntilFalse()( runController, std::chrono::seconds(1), std::chrono::milliseconds(0))); // Check position is the goal position parsernode::common::quaddata sensor_data; drone_hardware_.getquaddata(sensor_data); tf::Transform quad_transform( tf::createQuaternionFromRPY(0, 0, sensor_data.rpydata.z), tf::Vector3(sensor_data.localpos.x, sensor_data.localpos.y, sensor_data.localpos.z)); ASSERT_TF_NEAR(quad_transform, gravity_aligned_tracked_pose * goal_relative_pose_tf, goal_tolerance_yaw_); ASSERT_EQ(visual_servoing_connector_->getStatus(), ControllerStatus::Completed); ASSERT_NEAR(thrust_gain_estimator_.getThrustGain(), 0.16, 1e-4); } QuadSimulator drone_hardware_; std::unique_ptr<RPYTBasedRelativePoseController> controller_; std::unique_ptr<SimpleTracker> simple_tracker_; std::unique_ptr<RPYTRelativePoseVisualServoingConnector> visual_servoing_connector_; double goal_tolerance_position_; double goal_tolerance_velocity_; double goal_tolerance_yaw_; double goal_tolerance_yaw_rate_; tf::Transform tracking_offset_transform_; ThrustGainEstimator thrust_gain_estimator_; }; TEST_F(RPYTRelativePoseVisualConnectorTests, Constructor) {} TEST_F(RPYTRelativePoseVisualConnectorTests, CriticalRun) { visual_servoing_connector_->setGoal(PositionYaw()); // make tracking invalid: simple_tracker_->setTrackingIsValid(false); // Run connector visual_servoing_connector_->run(); ASSERT_EQ(visual_servoing_connector_->getStatus(), ControllerStatus::Critical); } TEST_F(RPYTRelativePoseVisualConnectorTests, RunUntilConvergence) { // set tracking goal tf::Transform tracked_pose(tf::createQuaternionFromRPY(0, 0, -0.1), tf::Vector3(2, -0.5, 0.5)); PositionYaw goal_relative_pose(1, 0, 0, 0.5); runUntilConvergence(tracked_pose, goal_relative_pose); } TEST_F(RPYTRelativePoseVisualConnectorTests, RunUntilConvergenceNonZeroRollPitch) { // set tracking goal tf::Transform tracked_pose(tf::createQuaternionFromRPY(0.4, -0.6, -0.5), tf::Vector3(2, -0.5, 0.5)); PositionYaw goal_relative_pose(1, -1.5, 2, 0.5); runUntilConvergence(tracked_pose, goal_relative_pose); } TEST_F(RPYTRelativePoseVisualConnectorTests, TestViewingAngle) { tf::Transform object_pose_cam(tf::createQuaternionFromRPY(M_PI / 2, 0, 0), tf::Vector3(1, 0, 0)); ASSERT_NEAR(visual_servoing_connector_->getViewingAngle(object_pose_cam), M_PI / 2, 1e-8); object_pose_cam.setOrigin(tf::Vector3(0, 0, 1)); ASSERT_NEAR(visual_servoing_connector_->getViewingAngle(object_pose_cam), 0, 1e-8); object_pose_cam.setOrigin(tf::Vector3(0, 1, 1)); ASSERT_NEAR(visual_servoing_connector_->getViewingAngle(object_pose_cam), M_PI / 4, 1e-8); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Fix test<commit_after> #include <gtest/gtest.h> #include <aerial_autonomy/common/conversions.h> #include <aerial_autonomy/controller_connectors/rpyt_relative_pose_visual_servoing_connector.h> #include <aerial_autonomy/controllers/rpyt_based_relative_pose_controller.h> #include <aerial_autonomy/tests/test_utils.h> #include <aerial_autonomy/trackers/simple_tracker.h> #include <chrono> #include <quad_simulator_parser/quad_simulator.h> #include <thread> /** * @brief Namespace for UAV Simulator Hardware */ using namespace quad_simulator; using namespace test_utils; class RPYTRelativePoseVisualConnectorTests : public ::testing::Test { public: RPYTRelativePoseVisualConnectorTests() : goal_tolerance_position_(0.1), goal_tolerance_velocity_(0.1), goal_tolerance_yaw_(0.1), goal_tolerance_yaw_rate_(0.05), tracking_offset_transform_( tf::createQuaternionFromRPY(0, M_PI / 3, 0.2), tf::Vector3(0, 0, 0)), thrust_gain_estimator_(0.18) { RPYTBasedRelativePoseControllerConfig config; auto velocity_relative_pose_config = config.mutable_velocity_based_relative_pose_controller_config(); auto position_controller_config = velocity_relative_pose_config ->mutable_velocity_based_position_controller_config(); position_controller_config->set_position_gain(1.0); position_controller_config->set_max_velocity(1.0); position_controller_config->set_yaw_gain(1.0); position_controller_config->set_max_yaw_rate(1.0); position_controller_config->set_yaw_i_gain(0.0); position_controller_config->set_position_i_gain(0.0); position_controller_config->set_position_saturation_value(0.0); position_controller_config->set_yaw_saturation_value(0.0); position_controller_config->mutable_position_controller_config() ->set_goal_yaw_tolerance(goal_tolerance_yaw_); auto position_tolerance = position_controller_config->mutable_position_controller_config() ->mutable_goal_position_tolerance(); position_tolerance->set_x(goal_tolerance_position_); position_tolerance->set_y(goal_tolerance_position_); position_tolerance->set_z(goal_tolerance_position_); auto rpyt_velocity_controller_config = config.mutable_rpyt_based_velocity_controller_config(); rpyt_velocity_controller_config->mutable_velocity_controller_config() ->set_goal_yaw_tolerance(goal_tolerance_yaw_); auto goal_velocity_tolerance = rpyt_velocity_controller_config->mutable_velocity_controller_config() ->mutable_goal_velocity_tolerance(); goal_velocity_tolerance->set_vx(goal_tolerance_velocity_); goal_velocity_tolerance->set_vy(goal_tolerance_velocity_); goal_velocity_tolerance->set_vz(goal_tolerance_velocity_); tf::Transform camera_transform = tf::Transform::getIdentity(); simple_tracker_.reset(new SimpleTracker(drone_hardware_, camera_transform)); controller_.reset(new RPYTBasedRelativePoseController( config, std::chrono::milliseconds(20))); visual_servoing_connector_.reset( new RPYTRelativePoseVisualServoingConnector( *simple_tracker_, drone_hardware_, *controller_, thrust_gain_estimator_, camera_transform, tracking_offset_transform_)); drone_hardware_.usePerfectTime(); } static void SetUpTestCase() { // Configure logging LogConfig log_config; log_config.set_directory("/tmp/data"); Log::instance().configure(log_config); DataStreamConfig data_config; data_config.set_stream_id("rpyt_relative_pose_visual_servoing_connector"); Log::instance().addDataStream(data_config); data_config.set_stream_id("velocity_based_position_controller"); Log::instance().addDataStream(data_config); data_config.set_stream_id("rpyt_based_velocity_controller"); Log::instance().addDataStream(data_config); data_config.set_stream_id("velocity_based_relative_pose_controller"); Log::instance().addDataStream(data_config); data_config.set_stream_id("thrust_gain_estimator"); Log::instance().addDataStream(data_config); data_config.set_stream_id("tracking_vector_estimator"); Log::instance().addDataStream(data_config); } void runUntilConvergence(const tf::Transform &tracked_pose, const PositionYaw &goal_relative_pose) { simple_tracker_->setTargetPoseGlobalFrame(tracked_pose); simple_tracker_->setTrackingIsValid(true); tf::Transform gravity_aligned_tracked_pose = tracked_pose * tracking_offset_transform_; double roll, pitch, yaw; gravity_aligned_tracked_pose.getBasis().getRPY(roll, pitch, yaw); gravity_aligned_tracked_pose.getBasis().setRPY(0, 0, yaw); // Fly quadrotor which sets the altitude to 0.5 drone_hardware_.setBatteryPercent(60); drone_hardware_.takeoff(); // Set goal tf::Transform goal_relative_pose_tf; conversions::positionYawToTf(goal_relative_pose, goal_relative_pose_tf); visual_servoing_connector_->setGoal(goal_relative_pose); // Run controller until inactive auto runController = [&]() { visual_servoing_connector_->run(); return visual_servoing_connector_->getStatus() == ControllerStatus::Active; }; ASSERT_FALSE(test_utils::waitUntilFalse()( runController, std::chrono::seconds(1), std::chrono::milliseconds(0))); // Check position is the goal position parsernode::common::quaddata sensor_data; drone_hardware_.getquaddata(sensor_data); tf::Transform quad_transform( tf::createQuaternionFromRPY(0, 0, sensor_data.rpydata.z), tf::Vector3(sensor_data.localpos.x, sensor_data.localpos.y, sensor_data.localpos.z)); ASSERT_TF_NEAR(quad_transform, gravity_aligned_tracked_pose * goal_relative_pose_tf, goal_tolerance_yaw_); ASSERT_EQ(visual_servoing_connector_->getStatus(), ControllerStatus::Completed); ASSERT_NEAR(thrust_gain_estimator_.getThrustGain(), 0.16, 1e-4); } QuadSimulator drone_hardware_; std::unique_ptr<RPYTBasedRelativePoseController> controller_; std::unique_ptr<SimpleTracker> simple_tracker_; std::unique_ptr<RPYTRelativePoseVisualServoingConnector> visual_servoing_connector_; double goal_tolerance_position_; double goal_tolerance_velocity_; double goal_tolerance_yaw_; double goal_tolerance_yaw_rate_; tf::Transform tracking_offset_transform_; ThrustGainEstimator thrust_gain_estimator_; }; TEST_F(RPYTRelativePoseVisualConnectorTests, Constructor) {} TEST_F(RPYTRelativePoseVisualConnectorTests, CriticalRun) { visual_servoing_connector_->setGoal(PositionYaw()); // make tracking invalid: simple_tracker_->setTrackingIsValid(false); // Run connector visual_servoing_connector_->run(); ASSERT_EQ(visual_servoing_connector_->getStatus(), ControllerStatus::Critical); } TEST_F(RPYTRelativePoseVisualConnectorTests, RunUntilConvergence) { // set tracking goal tf::Transform tracked_pose(tf::createQuaternionFromRPY(0, 0, -0.1), tf::Vector3(2, -0.5, 0.5)); PositionYaw goal_relative_pose(1, 0, 0, 0.5); runUntilConvergence(tracked_pose, goal_relative_pose); } TEST_F(RPYTRelativePoseVisualConnectorTests, RunUntilConvergenceNonZeroRollPitch) { // set tracking goal tf::Transform tracked_pose(tf::createQuaternionFromRPY(0.4, -0.6, -0.5), tf::Vector3(2, -0.5, 0.5)); PositionYaw goal_relative_pose(1, -1.5, 2, 0.5); runUntilConvergence(tracked_pose, goal_relative_pose); } TEST_F(RPYTRelativePoseVisualConnectorTests, TestViewingAngle) { tf::Transform object_pose_cam(tf::createQuaternionFromRPY(M_PI / 2, 0, 0), tf::Vector3(1, 0, 0)); ASSERT_NEAR(visual_servoing_connector_->getViewingAngle(object_pose_cam), M_PI / 2, 1e-8); object_pose_cam.setOrigin(tf::Vector3(0, 0, 1)); ASSERT_NEAR(visual_servoing_connector_->getViewingAngle(object_pose_cam), 0, 1e-8); object_pose_cam.setOrigin(tf::Vector3(0, 1, 1)); ASSERT_NEAR(visual_servoing_connector_->getViewingAngle(object_pose_cam), M_PI / 4, 1e-8); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////// // // AliTPCTracking.C // // date: 22.08.2002 // author: Jiri Chudoba based on code of Jourij Belikov // version: 1.0 // description: // reconstructs of tracks in TPC inthe following steps: // TPC cluster finding // TPC track finding // input parameters: // Int_t nEvents ... nr of events to process // Int_t firstEventNr ... first event number (starts from 0) // Char_t* fileNameHits ... name of file with hits // Char_t* fileNameDigits .. name of file with TPC digits // Char_t* fileNameClusters .. name of file with TPC clusters (output) // Char_t* fileNameTracks .. name of file with TPC tracks (output) // // default file names correspond to pp production (2002-04) // // History: // // 03.03.2003 ... SetFieldFactor moved to AliTracker class and // LoadTPCParam moved to AliTPC class // TString replaced by Char_t* // // 20.11.2002 ... Changes due to a changed interface of AliTPCtracker. // Use Riostream.h instead of iostream.h // // 22.08.2002 ... first version // //////////////////////////////////////////////////////////////////////// #if !defined(__CINT__) || defined(__MAKECINT__) #include "Riostream.h" #include "TTree.h" #include "TSystem.h" #include "TArrayF.h" #include "TPC/alles.h" #include "TPC/AliTPCtracker.h" #include "TPC/AliTPCclusterer.h" #include "TPC/AliTPC.h" #include "STEER/AliRun.h" #include "STEER/AliHeader.h" #include "STEER/AliGenEventHeader.h" #include "STEER/AliMagF.h" #include "STEER/AliTracker.h" #endif Int_t gDEBUG = 2; Int_t TPCFindClusters(Int_t nEvents=1, Int_t firstEvent=0, Char_t* fileNameDigits="rfio:galiceSDR.root", Char_t* fileNameClusters="tpc.clusters.root"); Int_t TPCFindClusters(Int_t nEvents, Int_t firstEvent, TFile* fileDigits, TFile* fileClusters, AliTPCParam* paramTPC=0); Int_t TPCFindTracks(Int_t nEvents=1, Int_t firstEvent=0, Char_t* fileNameClusters="tpc.clusters.root", Char_t* fileNameTracks="tpc.tracks.root"); Int_t TPCFindTracks(Int_t nEvents, Int_t firstEvent, TFile* fileClusters, TFile* fileTracks, AliTPCParam* paramTPC=0); void FindVertex(Int_t iEvent, Double_t *vertex); void PrintVertex(TArrayF &primaryVertex); Int_t AliTPCTracking(Int_t nEvents=1, Int_t firstEvent=0, Char_t* fileNameHits="rfio:galice.root", Char_t* fileNameDigits="rfio:galiceSDR.root", Char_t* fileNameClusters="tpc.clusters.root", Char_t* fileNameTracks="tpc.tracks.root"); //////////////////////////////////////////////////////////////////////// Int_t AliTPCTracking( Int_t nEvents, Int_t firstEvent, Char_t* fileNameHits, Char_t* fileNameDigits, Char_t* fileNameClusters, Char_t* fileNameTracks) { AliTracker::SetFieldFactor(fileNameHits,kFALSE); // ********** Find TPC clusters *********** // if (TPCFindClusters(nEvents,firstEvent,fileNameDigits,fileNameClusters)) { cerr<<"Failed to get TPC clusters: !\n"; return 1; } // ********** Find TPC tracks *********** // if (TPCFindTracks(nEvents,firstEvent,fileNameClusters,fileNameTracks)) { cerr<<"Failed to get TPC tracks !\n"; return 2; } return 0; } //////////////////////////////////////////////////////////////////////// Int_t TPCFindClusters(Int_t nEvents, Int_t firstEvent, Char_t* fileNameDigits, Char_t* fileNameClusters) { Int_t rc; const Char_t *name="TPCFindClusters"; if (gDEBUG>1) cout<<name<<" starts...\n"; if (gDEBUG>1) gBenchmark->Start(name); TFile *fileClusters = TFile::Open(fileNameClusters,"recreate"); TFile *fileDigits = TFile::Open(fileNameDigits); if (!fileDigits->IsOpen()) { cerr<<"Cannnot open "<<fileNameDigits<<" !\n"; return 1; } if (!fileClusters->IsOpen()) { cerr<<"Cannnot open "<<fileNameClusters<<" !\n"; return 1; } rc = TPCFindClusters(nEvents,firstEvent,fileDigits,fileClusters); fileDigits->Close(); fileClusters->Close(); delete fileDigits; delete fileClusters; if (gDEBUG>1) gBenchmark->Stop(name); if (gDEBUG>1) gBenchmark->Show(name); return rc; } //////////////////////////////////////////////////////////////////////// Int_t TPCFindClusters(Int_t nEvents, Int_t firstEvent, TFile* fileDigits, TFile* fileClusters, AliTPCParam* paramTPC) { fileDigits->cd(); if (!paramTPC) paramTPC = AliTPC::LoadTPCParam(fileDigits); if (!paramTPC) return 1; for (Int_t iEvent = firstEvent; iEvent < firstEvent+nEvents; iEvent++){ if (gDEBUG > 2) cout<<"TPCFindClusters: event "<<iEvent<<endl; AliTPCclusterer::Digits2Clusters(paramTPC, fileClusters, iEvent); } return 0; } //////////////////////////////////////////////////////////////////////// Int_t TPCFindTracks(Int_t nEvents, Int_t firstEvent, Char_t* fileNameClusters, Char_t* fileNameTracks) { Int_t rc = 0; const Char_t *name="TPCFindTracks"; if (gDEBUG>1) cout<<name<<" starts"<<endl; if (gDEBUG>1) gBenchmark->Start(name); TFile *fileTracks = TFile::Open(fileNameTracks,"recreate"); TFile *fileClusters =TFile::Open(fileNameClusters); rc = TPCFindTracks(nEvents, firstEvent, fileClusters, fileTracks); fileClusters->Close(); fileTracks->Close(); delete fileClusters; delete fileTracks; if (gDEBUG>1) gBenchmark->Stop(name); if (gDEBUG>1) gBenchmark->Show(name); return rc; } //////////////////////////////////////////////////////////////////////// Int_t TPCFindTracks(Int_t nEvents, Int_t firstEvent, TFile *fileClusters, TFile * fileTracks, AliTPCParam* paramTPC) { Int_t rc = 0; if (!paramTPC) paramTPC = AliTPC::LoadTPCParam(fileClusters); if (!paramTPC) return 1; for (Int_t iEvent = firstEvent; iEvent < firstEvent+nEvents; iEvent++){ if (gDEBUG > 2) cout<<"TPCFindTracks: event "<<iEvent<<endl; AliTPCtracker *tracker = new AliTPCtracker(paramTPC); tracker->SetEventNumber(iEvent); Double_t vertex[3]; FindVertex(iEvent,vertex); tracker->SetVertex(vertex); fileClusters->cd(); rc = tracker->Clusters2Tracks(0,fileTracks); delete tracker; } return rc; } //////////////////////////////////////////////////////////////////////// void FindVertex(Int_t eventNr, Double_t *vertex) { vertex[0] = vertex[1] = vertex[2] = 0.; if (!gAlice) { cerr<<"gAlice was not found! Using vertex position (0,0,0).\n"; return; } gAlice->GetEvent(eventNr); AliHeader *header = gAlice->GetHeader(); if (!header) { cerr<<"header was not found!\n"; return; } AliGenEventHeader* genEventHeader = header->GenEventHeader(); if (!genEventHeader) { cerr<<"AliGenEventHeader was not found!\n"; return; } TArrayF primaryVertex(3); genEventHeader->PrimaryVertex(primaryVertex); PrintVertex(primaryVertex); vertex[0] = static_cast<Double_t>(primaryVertex[0]); vertex[1] = static_cast<Double_t>(primaryVertex[1]); vertex[2] = static_cast<Double_t>(primaryVertex[2]); // delete header; delete genEventHeader; return; } //////////////////////////////////////////////////////////////////////// void PrintVertex(TArrayF &primaryVertex) { cout <<"Vertex: " <<primaryVertex[0]<<" " <<primaryVertex[1]<<" " <<primaryVertex[2]<<" "<<endl; exit; } //////////////////////////////////////////////////////////////////////// <commit_msg>Option to use the new (V3) tracking (T.Kuhr)<commit_after>//////////////////////////////////////////////////////////////////////// // // AliTPCTracking.C // // date: 22.08.2002 // author: Jiri Chudoba based on code of Jourij Belikov // version: 1.0 // description: // reconstructs of tracks in TPC inthe following steps: // TPC cluster finding // TPC track finding // input parameters: // Int_t nEvents ... nr of events to process // Int_t firstEventNr ... first event number (starts from 0) // const char* fileNameHits ... name of file with hits // const char* fileNameDigits .. name of file with TPC digits // const char* fileNameClusters .. name of file with TPC clusters (output) // const char* fileNameTracks .. name of file with TPC tracks (output) // // default file names correspond to pp production (2002-04) // // History: // // 18.03.2003 ... Char_t* replaced by const char* // // 03.03.2003 ... SetFieldFactor moved to AliTracker class and // LoadTPCParam moved to AliTPC class // TString replaced by Char_t* // // 20.11.2002 ... Changes due to a changed interface of AliTPCtracker. // Use Riostream.h instead of iostream.h // // 22.08.2002 ... first version // //////////////////////////////////////////////////////////////////////// #if !defined(__CINT__) || defined(__MAKECINT__) #include "Riostream.h" #include "TFile.h" #include "TTree.h" #include "TBenchmark.h" #include "AliTPCtracker.h" #include "AliTPCtrackerMI.h" #include "AliTPCclusterer.h" #include "AliTPCclustererMI.h" #include "AliTPC.h" #include "AliRun.h" #include "AliHeader.h" #include "AliGenEventHeader.h" #include "AliTracker.h" #endif Int_t gDEBUG = 2; Int_t AliTPCTracking(Int_t nEvents=1, Int_t firstEvent=0, const char* fileNameHits="galice.root", const char* fileNameDigits="tpc.digits.root", const char* fileNameClusters="tpc.clusters.root", const char* fileNameTracks="tpc.tracks.root", Bool_t versionMI = kFALSE); Int_t TPCFindClusters(Int_t nEvents=1, Int_t firstEvent=0, const char* fileNameDigits="tpc.digits.root", const char* fileNameClusters="tpc.clusters.root", Bool_t versionMI = kFALSE); Int_t TPCFindClusters(Int_t nEvents, Int_t firstEvent, TFile* fileDigits, TFile* fileClusters, AliTPCParam* paramTPC=0); Int_t TPCFindClustersMI(Int_t nEvents, Int_t firstEvent, TFile* fileDigits, TFile* fileClusters, AliTPCParam* paramTPC=0); Int_t TPCFindTracks(Int_t nEvents=1, Int_t firstEvent=0, const char* fileNameClusters="tpc.clusters.root", const char* fileNameTracks="tpc.tracks.root", Bool_t versionMI = kFALSE); Int_t TPCFindTracks(Int_t nEvents, Int_t firstEvent, TFile* fileClusters, TFile* fileTracks, AliTPCParam* paramTPC=0); Int_t TPCFindTracksMI(Int_t nEvents, Int_t firstEvent, TFile* fileClusters, TFile* fileTracks, AliTPCParam* paramTPC=0); void FindVertex(Int_t iEvent, Double_t *vertex); void PrintVertex(TArrayF &primaryVertex); //////////////////////////////////////////////////////////////////////// Int_t AliTPCTracking( Int_t nEvents, Int_t firstEvent, const char* fileNameHits, const char* fileNameDigits, const char* fileNameClusters, const char* fileNameTracks, Bool_t versionMI) { AliTracker::SetFieldFactor(fileNameHits,kFALSE); // ********** Find TPC clusters *********** // if (fileNameDigits && fileNameClusters) { if (TPCFindClusters(nEvents,firstEvent,fileNameDigits,fileNameClusters,versionMI)) { cerr<<"Failed to get TPC clusters: !\n"; return 1; } } // ********** Find TPC tracks *********** // if (fileNameClusters && fileNameTracks) { if (TPCFindTracks(nEvents,firstEvent,fileNameClusters,fileNameTracks,versionMI)) { cerr<<"Failed to get TPC tracks !\n"; return 2; } } return 0; } //////////////////////////////////////////////////////////////////////// Int_t TPCFindClusters(Int_t nEvents, Int_t firstEvent, const char* fileNameDigits, const char* fileNameClusters, Bool_t versionMI) { Int_t rc; const Char_t *name="TPCFindClusters"; if (gDEBUG>1) cout<<name<<" starts...\n"; if (gDEBUG>1) gBenchmark->Start(name); TFile *fileClusters = TFile::Open(fileNameClusters,"recreate"); TFile *fileDigits = TFile::Open(fileNameDigits); if (!fileDigits->IsOpen()) { cerr<<"Cannnot open "<<fileNameDigits<<" !\n"; return 1; } if (!fileClusters->IsOpen()) { cerr<<"Cannnot open "<<fileNameClusters<<" !\n"; return 1; } if (versionMI) { rc = TPCFindClustersMI(nEvents,firstEvent,fileDigits,fileClusters); } else { rc = TPCFindClusters(nEvents,firstEvent,fileDigits,fileClusters); } fileDigits->Close(); fileClusters->Close(); delete fileDigits; delete fileClusters; if (gDEBUG>1) gBenchmark->Stop(name); if (gDEBUG>1) gBenchmark->Show(name); return rc; } //////////////////////////////////////////////////////////////////////// Int_t TPCFindClusters(Int_t nEvents, Int_t firstEvent, TFile* fileDigits, TFile* fileClusters, AliTPCParam* paramTPC) { fileDigits->cd(); if (!paramTPC) paramTPC = AliTPC::LoadTPCParam(fileDigits); if (!paramTPC) return 1; for (Int_t iEvent = firstEvent; iEvent < firstEvent+nEvents; iEvent++){ if (gDEBUG > 2) cout<<"TPCFindClusters: event "<<iEvent<<endl; AliTPCclusterer::Digits2Clusters(paramTPC, fileClusters, iEvent); } return 0; } //////////////////////////////////////////////////////////////////////// Int_t TPCFindClustersMI(Int_t nEvents, Int_t firstEvent, TFile* fileDigits, TFile* fileClusters, AliTPCParam* paramTPC) { fileDigits->cd(); if (!paramTPC) paramTPC = AliTPC::LoadTPCParam(fileDigits); if (!paramTPC) return 1; AliTPCclustererMI clusterer; for (Int_t iEvent = firstEvent; iEvent < firstEvent+nEvents; iEvent++){ if (gDEBUG > 2) cout<<"TPCFindClustersMI: event "<<iEvent<<endl; char treeName[100]; sprintf(treeName, "TreeD_75x40_100x60_150x60_%d", iEvent); TTree* input = (TTree*) fileDigits->Get(treeName); fileClusters->cd(); sprintf(treeName, "TreeC_TPC_%d", iEvent); TTree* output = new TTree(treeName, treeName); clusterer.SetInput(input); clusterer.SetOutput(output); clusterer.Digits2Clusters(paramTPC, iEvent); } return 0; } //////////////////////////////////////////////////////////////////////// Int_t TPCFindTracks(Int_t nEvents, Int_t firstEvent, const char* fileNameClusters, const char* fileNameTracks, Bool_t versionMI) { Int_t rc = 0; const Char_t *name="TPCFindTracks"; if (gDEBUG>1) cout<<name<<" starts"<<endl; if (gDEBUG>1) gBenchmark->Start(name); TFile *fileTracks = TFile::Open(fileNameTracks,"recreate"); TFile *fileClusters =TFile::Open(fileNameClusters); if (versionMI) { rc = TPCFindTracksMI(nEvents, firstEvent, fileClusters, fileTracks); } else { rc = TPCFindTracks(nEvents, firstEvent, fileClusters, fileTracks); } fileClusters->Close(); fileTracks->Close(); delete fileClusters; delete fileTracks; if (gDEBUG>1) gBenchmark->Stop(name); if (gDEBUG>1) gBenchmark->Show(name); return rc; } //////////////////////////////////////////////////////////////////////// Int_t TPCFindTracks(Int_t nEvents, Int_t firstEvent, TFile *fileClusters, TFile * fileTracks, AliTPCParam* paramTPC) { Int_t rc = 0; if (!paramTPC) paramTPC = AliTPC::LoadTPCParam(fileClusters); if (!paramTPC) return 1; for (Int_t iEvent = firstEvent; iEvent < firstEvent+nEvents; iEvent++){ if (gDEBUG > 2) cout<<"TPCFindTracks: event "<<iEvent<<endl; AliTPCtracker *tracker = new AliTPCtracker(paramTPC); tracker->SetEventNumber(iEvent); Double_t vertex[3]; FindVertex(iEvent,vertex); tracker->SetVertex(vertex); fileClusters->cd(); rc = tracker->Clusters2Tracks(0,fileTracks); delete tracker; } return rc; } //////////////////////////////////////////////////////////////////////// Int_t TPCFindTracksMI(Int_t nEvents, Int_t firstEvent, TFile *fileClusters, TFile * fileTracks, AliTPCParam* paramTPC) { Int_t rc = 0; if (!paramTPC) paramTPC = AliTPC::LoadTPCParam(fileClusters); if (!paramTPC) return 1; for (Int_t iEvent = firstEvent; iEvent < firstEvent+nEvents; iEvent++){ if (gDEBUG > 2) cout<<"TPCFindTracksMI: event "<<iEvent<<endl; AliTPCtrackerMI tracker(paramTPC, iEvent); rc = tracker.Clusters2Tracks(0, fileTracks); } return rc; } //////////////////////////////////////////////////////////////////////// void FindVertex(Int_t eventNr, Double_t *vertex) { vertex[0] = vertex[1] = vertex[2] = 0.; if (!gAlice) { cerr<<"gAlice was not found! Using vertex position (0,0,0).\n"; return; } gAlice->GetEvent(eventNr); AliHeader *header = gAlice->GetHeader(); if (!header) { cerr<<"header was not found!\n"; return; } AliGenEventHeader* genEventHeader = header->GenEventHeader(); if (!genEventHeader) { cerr<<"AliGenEventHeader was not found!\n"; return; } TArrayF primaryVertex(3); genEventHeader->PrimaryVertex(primaryVertex); PrintVertex(primaryVertex); vertex[0] = static_cast<Double_t>(primaryVertex[0]); vertex[1] = static_cast<Double_t>(primaryVertex[1]); vertex[2] = static_cast<Double_t>(primaryVertex[2]); // delete header; delete genEventHeader; return; } //////////////////////////////////////////////////////////////////////// void PrintVertex(TArrayF &primaryVertex) { cout <<"Vertex: " <<primaryVertex[0]<<" " <<primaryVertex[1]<<" " <<primaryVertex[2]<<" "<<endl; } //////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>/* * Unit tests for the Raft library. * * Copyright (C) 2017 Nextworks * Author: Vincenzo Maffione <v.maffione@gmail.com> * * This file is part of rlite. * * 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 <iostream> #include <list> #include <string> #include <cstdint> #include <cassert> #include <cstring> #include <functional> #include <queue> #include <random> #include <ctime> #include <memory> #include "rlite/cpputils.hpp" #include "rlite/raft.hpp" using namespace std; static string logfile(const string &replica) { return string("/tmp/raft_test_") + replica + "_log"; } static constexpr int kFirstCommand = 18; class TestReplica : public RaftSM { uint32_t output_counter = kFirstCommand; bool failed = false; list<string> peers; public: TestReplica() = default; RL_NONCOPIABLE(TestReplica); TestReplica(const std::string &smname, const ReplicaId &myname, std::string logname, const list<string> &others) : RaftSM(smname, myname, logname, /*cmd_size=*/sizeof(uint32_t), std::cerr, std::cout), peers(others) { } ~TestReplica() { shutdown(); } /* Apply a command to the replicated state machine. */ virtual int apply(const char *const serbuf) override { uint32_t cmd = *(reinterpret_cast<const uint32_t *>(serbuf)); if (++output_counter != cmd) { cout << "Mismatch: expected " << output_counter << ", got " << cmd << endl; return -1; } return 0; } /* Called to emulate failure of a replica. The replica won't receive * messages until respawn. */ void fail() { failed = true; } /* Is this replica alive? */ bool up() const { return !failed; } /* Called to emulate a replica trying to recover after failure. */ int respawn(RaftSMOutput *out) { failed = false; return init(peers, out); }; }; enum class TestEventType { RaftTimer = 0, ClientRequest, SMFailure, SMRespawn, }; struct TestEvent { TestEventType event_type; unsigned int abstime = 0; TestReplica *sm = nullptr; RaftTimerType ttype = RaftTimerType::Invalid; bool operator<(const TestEvent &o) const { return abstime < o.abstime; } bool operator>=(const TestEvent &o) const { return !(*this < o); } static uint32_t get_next_command() { return ++input_counter; } static TestEvent CreateTimerEvent(unsigned int t, TestReplica *_sm, RaftTimerType ty) { TestEvent e; e.event_type = TestEventType::RaftTimer; e.abstime = t; e.sm = _sm; e.ttype = ty; return e; } static TestEvent CreateRequestEvent(unsigned int t) { TestEvent e; e.event_type = TestEventType::ClientRequest; e.abstime = t; return e; } static TestEvent CreateFailureEvent(unsigned int t, TestReplica *_sm) { TestEvent e; e.event_type = TestEventType::SMFailure; e.abstime = t; e.sm = _sm; return e; } static TestEvent CreateRespawnEvent(unsigned int t, TestReplica *_sm) { TestEvent e; e.event_type = TestEventType::SMRespawn; e.abstime = t; e.sm = _sm; return e; } private: static uint32_t input_counter; }; uint32_t TestEvent::input_counter = kFirstCommand; int main() { list<string> names = {"r1", "r2", "r3", "r4", "r5"}; map<string, std::unique_ptr<TestReplica>> replicas; list<TestEvent> events; unsigned int t = 0; /* time */ const unsigned int t_max = 800; RaftSMOutput output; srand(time(0)); /* Clean up leftover logfiles, if any. */ for (const auto &local : names) { remove(logfile(local).c_str()); } /* Create and initialize all the replicas. */ for (const auto &local : names) { string logfilename = logfile(local); list<string> peers; std::unique_ptr<TestReplica> sm; for (const auto &peer : names) { if (peer != local) { peers.push_back(peer); } } sm = make_unique<TestReplica>( /*smname=*/local + "-sm", /*myname=*/local, logfilename, peers); if (sm->respawn(&output)) { return -1; } replicas[local] = std::move(sm); } /* Push some client submission, failures and respawn events. */ events.push_back(TestEvent::CreateRequestEvent(350)); events.push_back(TestEvent::CreateRequestEvent(360)); events.push_back(TestEvent::CreateFailureEvent(365, replicas["r3"].get())); events.push_back(TestEvent::CreateRequestEvent(370)); events.push_back(TestEvent::CreateRequestEvent(450)); events.push_back(TestEvent::CreateFailureEvent(450, replicas["r4"].get())); events.push_back(TestEvent::CreateRequestEvent(454)); events.push_back(TestEvent::CreateRequestEvent(455)); // events.push_back(TestEvent::CreateRespawnEvent(500, // replicas["r3"].get())); events.push_back(TestEvent::CreateRequestEvent(550)); events.push_back(TestEvent::CreateRequestEvent(560)); events.sort(); /* Stop the simulation when we are over-time or when we run out * of messages and events (except for the heartbeat timeouts). */ auto should_stop = [t, t_max, &output, &events]() -> bool { auto only_timeouts = [&events]() -> bool { for (const auto &e : events) { if (e.event_type != TestEventType::RaftTimer) { return false; } } return true; }; auto only_heartbeat_commands = [&output]() -> bool { for (const auto &c : output.timer_commands) { if (c.type != RaftTimerType::HeartBeat) { return false; } } return true; }; return t > t_max || (output.output_messages.empty() && only_heartbeat_commands() && only_timeouts()); }; while (!should_stop()) { list<TestEvent> postponed; unsigned int t_next = t + 1; RaftSMOutput output_next; cout << "| t = " << t << " |" << endl; /* Process current output messages. */ for (const auto &p : output.output_messages) { auto *rv = dynamic_cast<RaftRequestVote *>(p.second.get()); auto *rvr = dynamic_cast<RaftRequestVoteResp *>(p.second.get()); auto *ae = dynamic_cast<RaftAppendEntries *>(p.second.get()); auto *aer = dynamic_cast<RaftAppendEntriesResp *>(p.second.get()); int r = 0; assert(replicas.count(p.first)); if (!replicas[p.first]->up()) { /* Replica is currently down, we just drop this message. */ } else if (rv) { r = replicas[p.first]->request_vote_input(*rv, &output_next); } else if (rvr) { r = replicas[p.first]->request_vote_resp_input(*rvr, &output_next); } else if (ae) { r = replicas[p.first]->append_entries_input(*ae, &output_next); } else if (aer) { r = replicas[p.first]->append_entries_resp_input(*aer, &output_next); } else { assert(false); } if (r) { return r; } } /* Process current timer commands. */ for (const RaftTimerCmd &cmd : output.timer_commands) { for (auto it = events.begin(); it != events.end(); it++) { if (it->sm == cmd.sm && it->ttype == cmd.type) { events.erase(it); break; } } if (cmd.action == RaftTimerAction::Restart) { events.push_back(TestEvent::CreateTimerEvent( t + cmd.milliseconds, dynamic_cast<TestReplica *>(cmd.sm), cmd.type)); } else { assert(cmd.action == RaftTimerAction::Stop); } } /* Process all the timers expired so far, updating the associated * Raft state machine. */ events.sort(); while (!events.empty()) { const TestEvent &next = events.front(); if (t < next.abstime) { if (output_next.output_messages.empty() && output_next.timer_commands.empty() && postponed.empty()) { /* No need to go step by step, we can jump to the next * event. */ t_next = next.abstime; } break; } switch (next.event_type) { case TestEventType::RaftTimer: { /* This event is a timer firing. */ if (next.sm->up() && next.sm->timer_expired(next.ttype, &output_next)) { return -1; } break; } case TestEventType::ClientRequest: { /* This event is a client submission. */ bool submitted = false; for (const auto &kv : replicas) { if (kv.second->leader() && kv.second->up()) { uint32_t cmd = TestEvent::get_next_command(); LogIndex request_id; if (kv.second->submit(reinterpret_cast<char *>(&cmd), &request_id, &output_next)) { return -1; } submitted = true; cout << "Command " << cmd << " submitted" << endl; break; } } if (!submitted) { /* This can happen because no leader is currently elected * or because the current leader is down. */ postponed.push_back(TestEvent::CreateRequestEvent(t + 100)); cout << "Client request postponed (no leader)" << endl; } break; } case TestEventType::SMFailure: { next.sm->fail(); cout << "Replica " << next.sm->local_name() << " failed" << endl; break; } case TestEventType::SMRespawn: { next.sm->respawn(&output_next); cout << "Replica " << next.sm->local_name() << " respawn" << endl; break; } } events.pop_front(); } /* Append the 'postponed' list at the end of the events list. */ events.splice(events.end(), postponed); /* Update time and Raft state machine output. */ t = t_next; output = std::move(output_next); } return 0; } <commit_msg>lib: raft: test: add final check<commit_after>/* * Unit tests for the Raft library. * * Copyright (C) 2017 Nextworks * Author: Vincenzo Maffione <v.maffione@gmail.com> * * This file is part of rlite. * * 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 <iostream> #include <list> #include <string> #include <cstdint> #include <cassert> #include <cstring> #include <functional> #include <queue> #include <random> #include <ctime> #include <memory> #include "rlite/cpputils.hpp" #include "rlite/raft.hpp" using namespace std; static string logfile(const string &replica) { return string("/tmp/raft_test_") + replica + "_log"; } class TestReplica : public RaftSM { list<uint32_t> committed_commands; list<string> peers; bool failed = false; public: TestReplica() = default; RL_NONCOPIABLE(TestReplica); TestReplica(const std::string &smname, const ReplicaId &myname, std::string logname, const list<string> &others) : RaftSM(smname, myname, logname, /*cmd_size=*/sizeof(uint32_t), std::cerr, std::cout), peers(others) { } ~TestReplica() { shutdown(); } /* Apply a command to the replicated state machine. */ virtual int apply(const char *const serbuf) override { uint32_t cmd = *(reinterpret_cast<const uint32_t *>(serbuf)); committed_commands.push_back(cmd); return 0; } /* Called to emulate failure of a replica. The replica won't receive * messages until respawn. */ void fail() { failed = true; } /* Is this replica alive? */ bool up() const { return !failed; } /* Called to emulate a replica trying to recover after failure. */ int respawn(RaftSMOutput *out) { failed = false; return init(peers, out); }; bool check(uint32_t num_commands) const { uint32_t expected = 1; if (committed_commands.size() != num_commands) { return false; } for (auto cmd : committed_commands) { if (cmd != expected++) { return false; } } return true; } }; enum class TestEventType { RaftTimer = 0, ClientRequest, SMFailure, SMRespawn, }; struct TestEvent { TestEventType event_type; unsigned int abstime = 0; TestReplica *sm = nullptr; RaftTimerType ttype = RaftTimerType::Invalid; bool operator<(const TestEvent &o) const { return abstime < o.abstime; } bool operator>=(const TestEvent &o) const { return !(*this < o); } static TestEvent CreateTimerEvent(unsigned int t, TestReplica *_sm, RaftTimerType ty) { TestEvent e; e.event_type = TestEventType::RaftTimer; e.abstime = t; e.sm = _sm; e.ttype = ty; return e; } static TestEvent CreateRequestEvent(unsigned int t) { TestEvent e; e.event_type = TestEventType::ClientRequest; e.abstime = t; return e; } static TestEvent CreateFailureEvent(unsigned int t, TestReplica *_sm) { TestEvent e; e.event_type = TestEventType::SMFailure; e.abstime = t; e.sm = _sm; return e; } static TestEvent CreateRespawnEvent(unsigned int t, TestReplica *_sm) { TestEvent e; e.event_type = TestEventType::SMRespawn; e.abstime = t; e.sm = _sm; return e; } }; int main() { list<string> names = {"r1", "r2", "r3", "r4", "r5"}; map<string, std::unique_ptr<TestReplica>> replicas; list<TestEvent> events; unsigned int t = 0; /* time */ const unsigned int t_max = 800; uint32_t input_counter = 1; RaftSMOutput output; srand(time(0)); /* Clean up leftover logfiles, if any. */ for (const auto &local : names) { remove(logfile(local).c_str()); } /* Create and initialize all the replicas. */ for (const auto &local : names) { string logfilename = logfile(local); list<string> peers; std::unique_ptr<TestReplica> sm; for (const auto &peer : names) { if (peer != local) { peers.push_back(peer); } } sm = make_unique<TestReplica>( /*smname=*/local + "-sm", /*myname=*/local, logfilename, peers); if (sm->respawn(&output)) { return -1; } replicas[local] = std::move(sm); } /* Push some client submission, failures and respawn events. */ events.push_back(TestEvent::CreateRequestEvent(350)); events.push_back(TestEvent::CreateRequestEvent(360)); events.push_back(TestEvent::CreateFailureEvent(365, replicas["r3"].get())); events.push_back(TestEvent::CreateRequestEvent(370)); events.push_back(TestEvent::CreateRequestEvent(450)); events.push_back(TestEvent::CreateFailureEvent(450, replicas["r4"].get())); events.push_back(TestEvent::CreateRequestEvent(454)); events.push_back(TestEvent::CreateRequestEvent(455)); // events.push_back(TestEvent::CreateRespawnEvent(500, // replicas["r3"].get())); events.push_back(TestEvent::CreateRequestEvent(550)); events.push_back(TestEvent::CreateRequestEvent(560)); events.sort(); /* Stop the simulation when we are over-time or when we run out * of messages and events (except for the heartbeat timeouts). */ auto should_stop = [t, t_max, &output, &events]() -> bool { auto only_timeouts = [&events]() -> bool { for (const auto &e : events) { if (e.event_type != TestEventType::RaftTimer) { return false; } } return true; }; auto only_heartbeat_commands = [&output]() -> bool { for (const auto &c : output.timer_commands) { if (c.type != RaftTimerType::HeartBeat) { return false; } } return true; }; return t > t_max || (output.output_messages.empty() && only_heartbeat_commands() && only_timeouts()); }; while (!should_stop()) { list<TestEvent> postponed; unsigned int t_next = t + 1; RaftSMOutput output_next; cout << "| t = " << t << " |" << endl; /* Process current output messages. */ for (const auto &p : output.output_messages) { auto *rv = dynamic_cast<RaftRequestVote *>(p.second.get()); auto *rvr = dynamic_cast<RaftRequestVoteResp *>(p.second.get()); auto *ae = dynamic_cast<RaftAppendEntries *>(p.second.get()); auto *aer = dynamic_cast<RaftAppendEntriesResp *>(p.second.get()); int r = 0; assert(replicas.count(p.first)); if (!replicas[p.first]->up()) { /* Replica is currently down, we just drop this message. */ } else if (rv) { r = replicas[p.first]->request_vote_input(*rv, &output_next); } else if (rvr) { r = replicas[p.first]->request_vote_resp_input(*rvr, &output_next); } else if (ae) { r = replicas[p.first]->append_entries_input(*ae, &output_next); } else if (aer) { r = replicas[p.first]->append_entries_resp_input(*aer, &output_next); } else { assert(false); } if (r) { return r; } } /* Process current timer commands. */ for (const RaftTimerCmd &cmd : output.timer_commands) { for (auto it = events.begin(); it != events.end(); it++) { if (it->sm == cmd.sm && it->ttype == cmd.type) { events.erase(it); break; } } if (cmd.action == RaftTimerAction::Restart) { events.push_back(TestEvent::CreateTimerEvent( t + cmd.milliseconds, dynamic_cast<TestReplica *>(cmd.sm), cmd.type)); } else { assert(cmd.action == RaftTimerAction::Stop); } } /* Process all the timers expired so far, updating the associated * Raft state machine. */ events.sort(); while (!events.empty()) { const TestEvent &next = events.front(); if (t < next.abstime) { if (output_next.output_messages.empty() && output_next.timer_commands.empty() && postponed.empty()) { /* No need to go step by step, we can jump to the next * event. */ t_next = next.abstime; } break; } switch (next.event_type) { case TestEventType::RaftTimer: { /* This event is a timer firing. */ if (next.sm->up() && next.sm->timer_expired(next.ttype, &output_next)) { return -1; } break; } case TestEventType::ClientRequest: { /* This event is a client submission. */ bool submitted = false; for (const auto &kv : replicas) { if (kv.second->leader() && kv.second->up()) { uint32_t cmd = input_counter++; LogIndex request_id; if (kv.second->submit(reinterpret_cast<char *>(&cmd), &request_id, &output_next)) { return -1; } submitted = true; cout << "Command " << cmd << " submitted" << endl; break; } } if (!submitted) { /* This can happen because no leader is currently elected * or because the current leader is down. */ postponed.push_back(TestEvent::CreateRequestEvent(t + 100)); cout << "Client request postponed (no leader)" << endl; } break; } case TestEventType::SMFailure: { next.sm->fail(); cout << "Replica " << next.sm->local_name() << " failed" << endl; break; } case TestEventType::SMRespawn: { next.sm->respawn(&output_next); cout << "Replica " << next.sm->local_name() << " respawn" << endl; break; } } events.pop_front(); } /* Append the 'postponed' list at the end of the events list. */ events.splice(events.end(), postponed); /* Update time and Raft state machine output. */ t = t_next; output = std::move(output_next); } for (const auto &kv : replicas) { if (kv.second->up()) { cout << "Replica " << kv.first << " up, check " << std::boolalpha << kv.second->check(input_counter - 1) << endl; } } return 0; } <|endoftext|>
<commit_before>#include "stdafx.h" #include "UIGifButton.h" namespace DuiLib { CGifButtonUI::CGifButtonUI() :m_pGif(NULL) ,m_nPreUpdateDelay(0) ,m_isUpdateTime(false) { } CGifButtonUI::~CGifButtonUI() { m_pManager->KillTimer(this, GIF_TIMER_ID); if (m_pGif) { delete m_pGif; m_pGif = NULL; } } void CGifButtonUI::SetVisible( bool bVisible /*= true*/ ) { if(bVisible == false) m_pManager->KillTimer(this, GIF_TIMER_ID); CButtonUI::SetVisible(bVisible); } void CGifButtonUI::PaintStatusImage( HDC hDC ) { if(m_pGif) { TImageInfo* pImageInfo = NULL; if (m_isUpdateTime) { m_isUpdateTime = false; pImageInfo = m_pGif->GetNextFrameInfo(); } else { pImageInfo = m_pGif->GetCurrentFrameInfo(); } if (pImageInfo) { RECT rcBmpPart = {0}; RECT rcCorners = {0}; rcBmpPart.right = pImageInfo->nX; rcBmpPart.bottom = pImageInfo->nY; CRenderEngine::DrawImage(hDC,pImageInfo->hBitmap,m_rcItem, m_rcPaint,rcBmpPart,rcCorners,pImageInfo->alphaChannel,255); if (m_nPreUpdateDelay != pImageInfo->delay) { m_pManager->KillTimer(this, GIF_TIMER_ID); m_pManager->SetTimer(this, GIF_TIMER_ID, pImageInfo->delay); m_nPreUpdateDelay = pImageInfo->delay; } } } //ûgifͼƬ,ͨťһ else { if( IsFocused() ) m_uButtonState |= UISTATE_FOCUSED; else m_uButtonState &= ~ UISTATE_FOCUSED; if( !IsEnabled() ) m_uButtonState |= UISTATE_DISABLED; else m_uButtonState &= ~ UISTATE_DISABLED; if( (m_uButtonState & UISTATE_DISABLED) != 0 ) { //whmiao need finish diable image // if( !m_sDisabledImage.IsEmpty() ) // { // if( !DrawImage(hDC, (LPCTSTR)m_sDisabledImage)) // m_sDisabledImage.Empty(); // else // return; // } } else if( (m_uButtonState & UISTATE_PUSHED) != 0 ) { //whmiao need finish diable image // if( !m_sPushedImage.IsEmpty() ) // { // if( !DrawImage(hDC, (LPCTSTR)m_sPushedImage) ) // m_sPushedImage.Empty(); // else // return; // } } else if( (m_uButtonState & UISTATE_HOT) != 0 ) { //whmiao need finish diable image // if( !m_sHotImage.IsEmpty() ) // { // if( !DrawImage(hDC, (LPCTSTR)m_sHotImage) ) // m_sHotImage.Empty(); // else // return; // } } else if( (m_uButtonState & UISTATE_FOCUSED) != 0 ) { // if( !m_sFocusedImage.IsEmpty() ) // { // if( !DrawImage(hDC, (LPCTSTR)m_sFocusedImage) ) // m_sFocusedImage.Empty(); // else // return; // } } // if( !m_sNormalImage.IsEmpty() ) // { // if( !DrawImage(hDC, (LPCTSTR)m_sNormalImage) ) // m_sNormalImage.Empty(); // else // return; // } } } void CGifButtonUI::DoEvent( TEventUI& event ) { if( event.Type == UIEVENT_TIMER && event.wParam == GIF_TIMER_ID ) { m_isUpdateTime = true; Invalidate(); return; } CButtonUI::DoEvent(event); } void CGifButtonUI::SetAttribute( LPCTSTR pstrName, LPCTSTR pstrValue ) { if( _tcscmp(pstrName, _T("NormalGifFile")) == 0 ) { SetNormalGifFile(pstrValue); } CButtonUI::SetAttribute(pstrName,pstrValue); } void CGifButtonUI::SetNormalGifFile( LPCTSTR pstrName ) { if(pstrName == NULL) return; if (m_pGif) { m_pManager->KillTimer(this, GIF_TIMER_ID); m_nPreUpdateDelay = 0; delete m_pGif; m_pGif = NULL; } m_pGif = CRenderEngine::LoadGif(STRINGorID(pstrName),0, 0); Invalidate(); } }<commit_msg>GIfbutton 没有gif图像 做为正常CButton<commit_after>#include "stdafx.h" #include "UIGifButton.h" namespace DuiLib { CGifButtonUI::CGifButtonUI() :m_pGif(NULL) ,m_nPreUpdateDelay(0) ,m_isUpdateTime(false) { } CGifButtonUI::~CGifButtonUI() { m_pManager->KillTimer(this, GIF_TIMER_ID); if (m_pGif) { delete m_pGif; m_pGif = NULL; } } void CGifButtonUI::SetVisible( bool bVisible /*= true*/ ) { if(bVisible == false) m_pManager->KillTimer(this, GIF_TIMER_ID); CButtonUI::SetVisible(bVisible); } void CGifButtonUI::PaintStatusImage( HDC hDC ) { if(m_pGif) { TImageInfo* pImageInfo = NULL; if (m_isUpdateTime) { m_isUpdateTime = false; pImageInfo = m_pGif->GetNextFrameInfo(); } else { pImageInfo = m_pGif->GetCurrentFrameInfo(); } if (pImageInfo) { RECT rcBmpPart = {0}; RECT rcCorners = {0}; rcBmpPart.right = pImageInfo->nX; rcBmpPart.bottom = pImageInfo->nY; CRenderEngine::DrawImage(hDC,pImageInfo->hBitmap,m_rcItem, m_rcPaint,rcBmpPart,rcCorners,pImageInfo->alphaChannel,255); if (m_nPreUpdateDelay != pImageInfo->delay) { m_pManager->KillTimer(this, GIF_TIMER_ID); m_pManager->SetTimer(this, GIF_TIMER_ID, pImageInfo->delay); m_nPreUpdateDelay = pImageInfo->delay; } } } //ûgifͼƬ,ͨťһ else { CButtonUI::PaintStatusImage(hDC); } } void CGifButtonUI::DoEvent( TEventUI& event ) { if( event.Type == UIEVENT_TIMER && event.wParam == GIF_TIMER_ID ) { m_isUpdateTime = true; Invalidate(); return; } CButtonUI::DoEvent(event); } void CGifButtonUI::SetAttribute( LPCTSTR pstrName, LPCTSTR pstrValue ) { if( _tcscmp(pstrName, _T("NormalGifFile")) == 0 ) { SetNormalGifFile(pstrValue); } else { CButtonUI::SetAttribute(pstrName, pstrValue); } } void CGifButtonUI::SetNormalGifFile( LPCTSTR pstrName ) { if(pstrName == NULL) return; if (m_pGif) { m_pManager->KillTimer(this, GIF_TIMER_ID); m_nPreUpdateDelay = 0; delete m_pGif; m_pGif = NULL; } m_pGif = CRenderEngine::LoadGif(STRINGorID(pstrName),0, 0); Invalidate(); } }<|endoftext|>
<commit_before>#include <LibUtilities/BasicUtils/SessionReader.h> #include <LibUtilities/BasicUtils/MeshPartition.h> #include <LibUtilities/Communication/CommSerial.h> #include <iostream> using namespace std; using namespace Nektar; using namespace Nektar::LibUtilities; class BrokenComm : public CommSerial { public: LIB_UTILITIES_EXPORT BrokenComm(int argc, char* argv[], int size) : CommSerial(argc, argv) { m_size = size; m_type = "Broken parallel"; } LIB_UTILITIES_EXPORT BrokenComm(int size) : CommSerial(0, NULL) { m_size = size; m_type = "Broken parallel"; } LIB_UTILITIES_EXPORT virtual ~BrokenComm() {} void v_SplitComm(int pRows, int pColumns) { m_commRow = boost::shared_ptr<BrokenComm>(new BrokenComm(pColumns)); m_commColumn = boost::shared_ptr<BrokenComm>(new BrokenComm(pRows)); } }; int main(int argc, char *argv[]) { vector<string> filenames(1); filenames[0] = argv[argc-1]; CommSharedPtr vComm = boost::shared_ptr<BrokenComm>(new BrokenComm(argc, argv, 256)); LibUtilities::SessionReaderSharedPtr vSession = LibUtilities::SessionReader::CreateInstance(argc, argv, filenames, vComm); return 0; } <commit_msg>Make PartitionCheck utility a little more usable, start rename to PartitionAnalyse<commit_after>/////////////////////////////////////////////////////////////////////////////// // // File: PartitionCheck.cpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: Small utility to export histogram of partition sizes. // /////////////////////////////////////////////////////////////////////////////// #include <LibUtilities/BasicUtils/SessionReader.h> #include <LibUtilities/BasicUtils/MeshPartition.h> #include <LibUtilities/Communication/CommSerial.h> #include <iostream> using namespace std; using namespace Nektar; using namespace Nektar::LibUtilities; class FauxComm : public CommSerial { public: LIB_UTILITIES_EXPORT FauxComm(int argc, char* argv[], int size) : CommSerial(argc, argv) { m_size = size; m_type = "Faux parallel"; } LIB_UTILITIES_EXPORT FauxComm(int size) : CommSerial(0, NULL) { m_size = size; m_type = "Faux parallel"; } LIB_UTILITIES_EXPORT virtual ~FauxComm() {} void v_SplitComm(int pRows, int pColumns) { m_commRow = boost::shared_ptr<FauxComm>(new FauxComm(pColumns)); m_commColumn = boost::shared_ptr<FauxComm>(new FauxComm(pRows)); } }; int main(int argc, char *argv[]) { if (argc < 3) { cerr << "Usage: PartitionAnalyze <nproc> <xml file1> [xml file 2..n]" << endl; return 1; } int nParts = atoi(argv[1]); vector<string> filenames(argv + 2, argv + argc); CommSharedPtr vComm = boost::shared_ptr<FauxComm>( new FauxComm(argc, argv, nParts)); char **new_argv = new char*[argc]; new_argv[0] = strdup("PartitionAnalyze"); new_argv[1] = strdup("--part-info"); for (int i = 0; i < argc-2; ++i) { new_argv[i+2] = strdup(filenames[i].c_str()); } LibUtilities::SessionReaderSharedPtr vSession = LibUtilities::SessionReader::CreateInstance( argc, new_argv, filenames, vComm); return 0; } <|endoftext|>
<commit_before><commit_msg>added colors generation<commit_after><|endoftext|>
<commit_before>/* * * Copyright 2014, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <grpc/support/alloc.h> #include <grpc++/impl/call.h> #include <grpc++/client_context.h> #include <grpc++/channel_interface.h> #include "src/cpp/proto/proto_utils.h" namespace grpc { void CallOpBuffer::Reset(void* next_return_tag) { return_tag_ = next_return_tag; send_initial_metadata_ = false; initial_metadata_count_ = 0; gpr_free(initial_metadata_); recv_initial_metadata_ = nullptr; gpr_free(recv_initial_metadata_arr_.metadata); recv_initial_metadata_arr_ = {0, 0, nullptr}; send_message_ = nullptr; if (send_message_buf_) { grpc_byte_buffer_destroy(send_message_buf_); send_message_buf_ = nullptr; } recv_message_ = nullptr; if (recv_message_buf_) { grpc_byte_buffer_destroy(recv_message_buf_); recv_message_buf_ = nullptr; } client_send_close_ = false; recv_trailing_metadata_ = nullptr; recv_status_ = nullptr; gpr_free(recv_trailing_metadata_arr_.metadata); recv_trailing_metadata_arr_ = {0, 0, nullptr}; status_code_ = GRPC_STATUS_OK; gpr_free(status_details_); status_details_ = nullptr; status_details_capacity_ = 0; send_status_ = nullptr; trailing_metadata_count_ = 0; trailing_metadata_ = nullptr; } namespace { // TODO(yangg) if the map is changed before we send, the pointers will be a // mess. Make sure it does not happen. grpc_metadata* FillMetadataArray( std::multimap<grpc::string, grpc::string>* metadata) { if (metadata->empty()) { return nullptr; } grpc_metadata* metadata_array = (grpc_metadata*)gpr_malloc( metadata->size()* sizeof(grpc_metadata)); size_t i = 0; for (auto iter = metadata->cbegin(); iter != metadata->cend(); ++iter, ++i) { metadata_array[i].key = iter->first.c_str(); metadata_array[i].value = iter->second.c_str(); metadata_array[i].value_length = iter->second.size(); } return metadata_array; } void FillMetadataMap(grpc_metadata_array* arr, std::multimap<grpc::string, grpc::string>* metadata) { for (size_t i = 0; i < arr->count; i++) { // TODO(yangg) handle duplicates? metadata->insert(std::pair<grpc::string, grpc::string>( arr->metadata[i].key, {arr->metadata[i].value, arr->metadata[i].value_length})); } grpc_metadata_array_destroy(arr); grpc_metadata_array_init(arr); } } // namespace void CallOpBuffer::AddSendInitialMetadata( std::multimap<grpc::string, grpc::string>* metadata) { send_initial_metadata_ = true; initial_metadata_count_ = metadata->size(); initial_metadata_ = FillMetadataArray(metadata); } void CallOpBuffer::AddSendInitialMetadata(ClientContext *ctx) { AddSendInitialMetadata(&ctx->metadata_); } void CallOpBuffer::AddSendMessage(const google::protobuf::Message& message) { send_message_ = &message; } void CallOpBuffer::AddRecvMessage(google::protobuf::Message *message) { recv_message_ = message; } void CallOpBuffer::AddClientSendClose() { client_send_close_ = true; } void CallOpBuffer::AddClientRecvStatus( std::multimap<grpc::string, grpc::string>* metadata, Status *status) { recv_trailing_metadata_ = metadata; recv_status_ = status; } void CallOpBuffer::AddServerSendStatus( std::multimap<grpc::string, grpc::string>* metadata, const Status& status) { trailing_metadata_count_ = metadata->size(); trailing_metadata_ = FillMetadataArray(metadata); send_status_ = &status; } void CallOpBuffer::FillOps(grpc_op *ops, size_t *nops) { *nops = 0; if (send_initial_metadata_) { ops[*nops].op = GRPC_OP_SEND_INITIAL_METADATA; ops[*nops].data.send_initial_metadata.count = initial_metadata_count_; ops[*nops].data.send_initial_metadata.metadata = initial_metadata_; (*nops)++; } if (recv_initial_metadata_) { ops[*nops].op = GRPC_OP_RECV_INITIAL_METADATA; ops[*nops].data.recv_initial_metadata = &recv_initial_metadata_arr_; (*nops)++; } if (send_message_) { bool success = SerializeProto(*send_message_, &send_message_buf_); if (!success) { // TODO handle parse failure } ops[*nops].op = GRPC_OP_SEND_MESSAGE; ops[*nops].data.send_message = send_message_buf_; (*nops)++; } if (recv_message_) { ops[*nops].op = GRPC_OP_RECV_MESSAGE; ops[*nops].data.recv_message = &recv_message_buf_; (*nops)++; } if (client_send_close_) { ops[*nops].op = GRPC_OP_SEND_CLOSE_FROM_CLIENT; (*nops)++; } if (recv_status_) { ops[*nops].op = GRPC_OP_RECV_STATUS_ON_CLIENT; ops[*nops].data.recv_status_on_client.trailing_metadata = &recv_trailing_metadata_arr_; ops[*nops].data.recv_status_on_client.status = &status_code_; ops[*nops].data.recv_status_on_client.status_details = &status_details_; ops[*nops].data.recv_status_on_client.status_details_capacity = &status_details_capacity_; (*nops)++; } if (send_status_) { ops[*nops].op = GRPC_OP_SEND_STATUS_FROM_SERVER; ops[*nops].data.send_status_from_server.trailing_metadata_count = trailing_metadata_count_; ops[*nops].data.send_status_from_server.trailing_metadata = trailing_metadata_; ops[*nops].data.send_status_from_server.status = static_cast<grpc_status_code>(send_status_->code()); ops[*nops].data.send_status_from_server.status_details = send_status_->details().c_str(); (*nops)++; } } void CallOpBuffer::FinalizeResult(void **tag, bool *status) { // Release send buffers. if (send_message_buf_) { grpc_byte_buffer_destroy(send_message_buf_); send_message_buf_ = nullptr; } if (initial_metadata_) { gpr_free(initial_metadata_); initial_metadata_ = nullptr; } if (trailing_metadata_count_) { gpr_free(trailing_metadata_); trailing_metadata_ = nullptr; } // Set user-facing tag. *tag = return_tag_; // Process received initial metadata if (recv_initial_metadata_) { FillMetadataMap(&recv_initial_metadata_arr_, recv_initial_metadata_); } // Parse received message if any. if (recv_message_ && recv_message_buf_) { *status = DeserializeProto(recv_message_buf_, recv_message_); grpc_byte_buffer_destroy(recv_message_buf_); recv_message_buf_ = nullptr; } // Parse received status. if (recv_status_) { FillMetadataMap(&recv_trailing_metadata_arr_, recv_trailing_metadata_); *recv_status_ = Status( static_cast<StatusCode>(status_code_), status_details_ ? grpc::string(status_details_, status_details_capacity_) : grpc::string()); } } void CCallDeleter::operator()(grpc_call* c) { grpc_call_destroy(c); } Call::Call(grpc_call* call, CallHook *call_hook, CompletionQueue* cq) : call_hook_(call_hook), cq_(cq), call_(call) {} void Call::PerformOps(CallOpBuffer* buffer) { call_hook_->PerformOpsOnCall(buffer, this); } } // namespace grpc <commit_msg>Tweak metadata sending<commit_after>/* * * Copyright 2014, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <grpc/support/alloc.h> #include <grpc++/impl/call.h> #include <grpc++/client_context.h> #include <grpc++/channel_interface.h> #include "src/cpp/proto/proto_utils.h" namespace grpc { void CallOpBuffer::Reset(void* next_return_tag) { return_tag_ = next_return_tag; send_initial_metadata_ = false; initial_metadata_count_ = 0; gpr_free(initial_metadata_); recv_initial_metadata_ = nullptr; gpr_free(recv_initial_metadata_arr_.metadata); recv_initial_metadata_arr_ = {0, 0, nullptr}; send_message_ = nullptr; if (send_message_buf_) { grpc_byte_buffer_destroy(send_message_buf_); send_message_buf_ = nullptr; } recv_message_ = nullptr; if (recv_message_buf_) { grpc_byte_buffer_destroy(recv_message_buf_); recv_message_buf_ = nullptr; } client_send_close_ = false; recv_trailing_metadata_ = nullptr; recv_status_ = nullptr; gpr_free(recv_trailing_metadata_arr_.metadata); recv_trailing_metadata_arr_ = {0, 0, nullptr}; status_code_ = GRPC_STATUS_OK; gpr_free(status_details_); status_details_ = nullptr; status_details_capacity_ = 0; send_status_ = nullptr; trailing_metadata_count_ = 0; trailing_metadata_ = nullptr; } namespace { // TODO(yangg) if the map is changed before we send, the pointers will be a // mess. Make sure it does not happen. grpc_metadata* FillMetadataArray( std::multimap<grpc::string, grpc::string>* metadata) { if (metadata->empty()) { return nullptr; } grpc_metadata* metadata_array = (grpc_metadata*)gpr_malloc( metadata->size()* sizeof(grpc_metadata)); size_t i = 0; for (auto iter = metadata->cbegin(); iter != metadata->cend(); ++iter, ++i) { metadata_array[i].key = iter->first.c_str(); metadata_array[i].value = iter->second.c_str(); metadata_array[i].value_length = iter->second.size(); } return metadata_array; } void FillMetadataMap(grpc_metadata_array* arr, std::multimap<grpc::string, grpc::string>* metadata) { for (size_t i = 0; i < arr->count; i++) { // TODO(yangg) handle duplicates? metadata->insert(std::pair<grpc::string, grpc::string>( arr->metadata[i].key, {arr->metadata[i].value, arr->metadata[i].value_length})); } grpc_metadata_array_destroy(arr); grpc_metadata_array_init(arr); } } // namespace void CallOpBuffer::AddSendInitialMetadata( std::multimap<grpc::string, grpc::string>* metadata) { send_initial_metadata_ = true; initial_metadata_count_ = metadata->size(); initial_metadata_ = FillMetadataArray(metadata); } void CallOpBuffer::AddSendInitialMetadata(ClientContext *ctx) { AddSendInitialMetadata(&ctx->metadata_); } void CallOpBuffer::AddSendMessage(const google::protobuf::Message& message) { send_message_ = &message; } void CallOpBuffer::AddRecvMessage(google::protobuf::Message *message) { recv_message_ = message; } void CallOpBuffer::AddClientSendClose() { client_send_close_ = true; } void CallOpBuffer::AddClientRecvStatus( std::multimap<grpc::string, grpc::string>* metadata, Status *status) { recv_trailing_metadata_ = metadata; recv_status_ = status; } void CallOpBuffer::AddServerSendStatus( std::multimap<grpc::string, grpc::string>* metadata, const Status& status) { if (metadata != NULL) { trailing_metadata_count_ = metadata->size(); trailing_metadata_ = FillMetadataArray(metadata); } else { trailing_metadata_count_ = 0; } send_status_ = &status; } void CallOpBuffer::FillOps(grpc_op *ops, size_t *nops) { *nops = 0; if (send_initial_metadata_) { ops[*nops].op = GRPC_OP_SEND_INITIAL_METADATA; ops[*nops].data.send_initial_metadata.count = initial_metadata_count_; ops[*nops].data.send_initial_metadata.metadata = initial_metadata_; (*nops)++; } if (recv_initial_metadata_) { ops[*nops].op = GRPC_OP_RECV_INITIAL_METADATA; ops[*nops].data.recv_initial_metadata = &recv_initial_metadata_arr_; (*nops)++; } if (send_message_) { bool success = SerializeProto(*send_message_, &send_message_buf_); if (!success) { abort(); // TODO handle parse failure } ops[*nops].op = GRPC_OP_SEND_MESSAGE; ops[*nops].data.send_message = send_message_buf_; (*nops)++; } if (recv_message_) { ops[*nops].op = GRPC_OP_RECV_MESSAGE; ops[*nops].data.recv_message = &recv_message_buf_; (*nops)++; } if (client_send_close_) { ops[*nops].op = GRPC_OP_SEND_CLOSE_FROM_CLIENT; (*nops)++; } if (recv_status_) { ops[*nops].op = GRPC_OP_RECV_STATUS_ON_CLIENT; ops[*nops].data.recv_status_on_client.trailing_metadata = &recv_trailing_metadata_arr_; ops[*nops].data.recv_status_on_client.status = &status_code_; ops[*nops].data.recv_status_on_client.status_details = &status_details_; ops[*nops].data.recv_status_on_client.status_details_capacity = &status_details_capacity_; (*nops)++; } if (send_status_) { ops[*nops].op = GRPC_OP_SEND_STATUS_FROM_SERVER; ops[*nops].data.send_status_from_server.trailing_metadata_count = trailing_metadata_count_; ops[*nops].data.send_status_from_server.trailing_metadata = trailing_metadata_; ops[*nops].data.send_status_from_server.status = static_cast<grpc_status_code>(send_status_->code()); ops[*nops].data.send_status_from_server.status_details = send_status_->details().c_str(); (*nops)++; } } void CallOpBuffer::FinalizeResult(void **tag, bool *status) { // Release send buffers. if (send_message_buf_) { grpc_byte_buffer_destroy(send_message_buf_); send_message_buf_ = nullptr; } if (initial_metadata_) { gpr_free(initial_metadata_); initial_metadata_ = nullptr; } if (trailing_metadata_count_) { gpr_free(trailing_metadata_); trailing_metadata_ = nullptr; } // Set user-facing tag. *tag = return_tag_; // Process received initial metadata if (recv_initial_metadata_) { FillMetadataMap(&recv_initial_metadata_arr_, recv_initial_metadata_); } // Parse received message if any. if (recv_message_ && recv_message_buf_) { *status = DeserializeProto(recv_message_buf_, recv_message_); grpc_byte_buffer_destroy(recv_message_buf_); recv_message_buf_ = nullptr; } // Parse received status. if (recv_status_) { FillMetadataMap(&recv_trailing_metadata_arr_, recv_trailing_metadata_); *recv_status_ = Status( static_cast<StatusCode>(status_code_), status_details_ ? grpc::string(status_details_, status_details_capacity_) : grpc::string()); } } void CCallDeleter::operator()(grpc_call* c) { grpc_call_destroy(c); } Call::Call(grpc_call* call, CallHook *call_hook, CompletionQueue* cq) : call_hook_(call_hook), cq_(cq), call_(call) {} void Call::PerformOps(CallOpBuffer* buffer) { call_hook_->PerformOpsOnCall(buffer, this); } } // namespace grpc <|endoftext|>
<commit_before>#include "unlimited.h" #include "test/test_bitcoin.h" #include "../consensus/consensus.h" #include <boost/algorithm/string.hpp> #include <boost/test/unit_test.hpp> #include <boost/lexical_cast.hpp> using namespace std; // Defined in rpc_tests.cpp not bitcoin-cli.cpp extern UniValue CallRPC(string strMethod); BOOST_FIXTURE_TEST_SUITE(excessiveblock_test, TestingSetup) BOOST_AUTO_TEST_CASE(rpc_excessive) { BOOST_CHECK_NO_THROW(CallRPC("getexcessiveblock")); BOOST_CHECK_NO_THROW(CallRPC("getminingmaxblock")); BOOST_CHECK_THROW(CallRPC("setexcessiveblock not_uint"), runtime_error); BOOST_CHECK_THROW(CallRPC("setexcessiveblock 1000000 not_uint"), boost::bad_lexical_cast); BOOST_CHECK_THROW(CallRPC("setexcessiveblock 1000000 -1"), boost::bad_lexical_cast); BOOST_CHECK_THROW(CallRPC("setexcessiveblock -1 0"), boost::bad_lexical_cast); BOOST_CHECK_THROW(CallRPC("setexcessiveblock 1000 1"), runtime_error); BOOST_CHECK_NO_THROW(CallRPC("setminingmaxblock 1000")); BOOST_CHECK_NO_THROW(CallRPC("setexcessiveblock 1000 1")); BOOST_CHECK_THROW(CallRPC("setexcessiveblock 1000 0 0"), runtime_error); BOOST_CHECK_THROW(CallRPC("setminingmaxblock"), runtime_error); BOOST_CHECK_THROW(CallRPC("setminingmaxblock 100000"), runtime_error); BOOST_CHECK_THROW(CallRPC("setminingmaxblock not_uint"), boost::bad_lexical_cast); BOOST_CHECK_THROW(CallRPC("setminingmaxblock -1"), boost::bad_lexical_cast); BOOST_CHECK_THROW(CallRPC("setminingmaxblock 0"), runtime_error); BOOST_CHECK_THROW(CallRPC("setminingmaxblock 0 0"), runtime_error); BOOST_CHECK_NO_THROW(CallRPC("setminingmaxblock 1000")); BOOST_CHECK_NO_THROW(CallRPC("setminingmaxblock 101")); } BOOST_AUTO_TEST_CASE(buip005) { string exceptedEB; string exceptedAD; excessiveBlockSize = 1000000; excessiveAcceptDepth = 9999999; exceptedEB = "EB1"; exceptedAD = "AD9999999"; settingsToUserAgentString(); BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB, "EB ought to have been " << exceptedEB << " when excessiveBlockSize = " << excessiveBlockSize << " but was " << BUComments.front()); BOOST_CHECK_MESSAGE(BUComments.back() == exceptedAD, "AD ought to have been " << exceptedAD << " when excessiveBlockSize = " << excessiveAcceptDepth); excessiveBlockSize = 100000; excessiveAcceptDepth = 9999999 + 1; exceptedEB = "EB0.1"; exceptedAD = "AD9999999"; settingsToUserAgentString(); BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB, "EB ought to have been " << exceptedEB << " when excessiveBlockSize = " << excessiveBlockSize << " but was " << BUComments.front()); BOOST_CHECK_MESSAGE(BUComments.back() == exceptedAD, "AD ought to have been " << exceptedAD << " when excessiveBlockSize = " << excessiveAcceptDepth); excessiveBlockSize = 10000; exceptedEB = "EB0"; settingsToUserAgentString(); BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB, "EB ought to have been " << exceptedEB << " when excessiveBlockSize = " << excessiveBlockSize << " but was " << BUComments.front()); excessiveBlockSize = 150000; exceptedEB = "EB0.1"; settingsToUserAgentString(); BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB, "EB ought to have been rounded to " << exceptedEB << " when excessiveBlockSize = " << excessiveBlockSize << " but was " << BUComments.front()); excessiveBlockSize = 150000; exceptedEB = "EB0.1"; settingsToUserAgentString(); BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB, "EB ought to have been rounded to " << exceptedEB << " when excessiveBlockSize = " << excessiveBlockSize << " but was " << BUComments.front()); // set back to defaults excessiveBlockSize = 1000000; excessiveAcceptDepth = 4; } BOOST_AUTO_TEST_CASE(excessiveChecks) { CBlock block; excessiveBlockSize = 16000000; // Ignore excessive block size when checking sigops and block effort // Check sigops values // Maintain compatibility with the old sigops calculator for blocks <= 1MB BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE-1,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE-1,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(true == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE-1,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS+1,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(true == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS+1,100,100), "improper sigops"); // Check sigops > 1MB. BOOST_CHECK_MESSAGE(false == CheckExcessive(block,1000000+1,(blockSigopsPerMb.value*2),100,100), "improper sigops"); BOOST_CHECK_MESSAGE(true == CheckExcessive(block,1000000+1,(blockSigopsPerMb.value*2)+1,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(true == CheckExcessive(block,(2*1000000),(blockSigopsPerMb.value*2)+1,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(false == CheckExcessive(block,(2*1000000)+1,(blockSigopsPerMb.value*2)+1,100,100), "improper sigops"); // Check tx size values maxTxSize.value = DEFAULT_LARGEST_TRANSACTION; // Within a 1 MB block, a 1MB transaction is not excessive BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE,1,1,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE), "improper max tx"); // With a > 1 MB block, use the maxTxSize to determine BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE+1,1,1,maxTxSize.value), "improper max tx"); BOOST_CHECK_MESSAGE(true == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE+1,1,1,maxTxSize.value+1), "improper max tx"); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Added unit tests for emergent consesus validation functions.<commit_after>#include "unlimited.h" #include "test/test_bitcoin.h" #include "../consensus/consensus.h" #include <boost/algorithm/string.hpp> #include <boost/test/unit_test.hpp> #include <boost/lexical_cast.hpp> using namespace std; // Defined in rpc_tests.cpp not bitcoin-cli.cpp extern UniValue CallRPC(string strMethod); BOOST_FIXTURE_TEST_SUITE(excessiveblock_test, TestingSetup) BOOST_AUTO_TEST_CASE(rpc_excessive) { BOOST_CHECK_NO_THROW(CallRPC("getexcessiveblock")); BOOST_CHECK_NO_THROW(CallRPC("getminingmaxblock")); BOOST_CHECK_THROW(CallRPC("setexcessiveblock not_uint"), runtime_error); BOOST_CHECK_THROW(CallRPC("setexcessiveblock 1000000 not_uint"), boost::bad_lexical_cast); BOOST_CHECK_THROW(CallRPC("setexcessiveblock 1000000 -1"), boost::bad_lexical_cast); BOOST_CHECK_THROW(CallRPC("setexcessiveblock -1 0"), boost::bad_lexical_cast); BOOST_CHECK_THROW(CallRPC("setexcessiveblock 1000 1"), runtime_error); BOOST_CHECK_NO_THROW(CallRPC("setminingmaxblock 1000")); BOOST_CHECK_NO_THROW(CallRPC("setexcessiveblock 1000 1")); BOOST_CHECK_THROW(CallRPC("setexcessiveblock 1000 0 0"), runtime_error); BOOST_CHECK_THROW(CallRPC("setminingmaxblock"), runtime_error); BOOST_CHECK_THROW(CallRPC("setminingmaxblock 100000"), runtime_error); BOOST_CHECK_THROW(CallRPC("setminingmaxblock not_uint"), boost::bad_lexical_cast); BOOST_CHECK_THROW(CallRPC("setminingmaxblock -1"), boost::bad_lexical_cast); BOOST_CHECK_THROW(CallRPC("setminingmaxblock 0"), runtime_error); BOOST_CHECK_THROW(CallRPC("setminingmaxblock 0 0"), runtime_error); BOOST_CHECK_NO_THROW(CallRPC("setminingmaxblock 1000")); BOOST_CHECK_NO_THROW(CallRPC("setminingmaxblock 101")); } BOOST_AUTO_TEST_CASE(buip005) { string exceptedEB; string exceptedAD; excessiveBlockSize = 1000000; excessiveAcceptDepth = 9999999; exceptedEB = "EB1"; exceptedAD = "AD9999999"; settingsToUserAgentString(); BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB, "EB ought to have been " << exceptedEB << " when excessiveBlockSize = " << excessiveBlockSize << " but was " << BUComments.front()); BOOST_CHECK_MESSAGE(BUComments.back() == exceptedAD, "AD ought to have been " << exceptedAD << " when excessiveBlockSize = " << excessiveAcceptDepth); excessiveBlockSize = 100000; excessiveAcceptDepth = 9999999 + 1; exceptedEB = "EB0.1"; exceptedAD = "AD9999999"; settingsToUserAgentString(); BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB, "EB ought to have been " << exceptedEB << " when excessiveBlockSize = " << excessiveBlockSize << " but was " << BUComments.front()); BOOST_CHECK_MESSAGE(BUComments.back() == exceptedAD, "AD ought to have been " << exceptedAD << " when excessiveBlockSize = " << excessiveAcceptDepth); excessiveBlockSize = 10000; exceptedEB = "EB0"; settingsToUserAgentString(); BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB, "EB ought to have been " << exceptedEB << " when excessiveBlockSize = " << excessiveBlockSize << " but was " << BUComments.front()); excessiveBlockSize = 150000; exceptedEB = "EB0.1"; settingsToUserAgentString(); BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB, "EB ought to have been rounded to " << exceptedEB << " when excessiveBlockSize = " << excessiveBlockSize << " but was " << BUComments.front()); excessiveBlockSize = 150000; exceptedEB = "EB0.1"; settingsToUserAgentString(); BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB, "EB ought to have been rounded to " << exceptedEB << " when excessiveBlockSize = " << excessiveBlockSize << " but was " << BUComments.front()); // set back to defaults excessiveBlockSize = 1000000; excessiveAcceptDepth = 4; } BOOST_AUTO_TEST_CASE(excessiveChecks) { CBlock block; excessiveBlockSize = 16000000; // Ignore excessive block size when checking sigops and block effort // Check sigops values // Maintain compatibility with the old sigops calculator for blocks <= 1MB BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE-1,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE-1,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(true == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE-1,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS+1,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(true == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS+1,100,100), "improper sigops"); // Check sigops > 1MB. BOOST_CHECK_MESSAGE(false == CheckExcessive(block,1000000+1,(blockSigopsPerMb.value*2),100,100), "improper sigops"); BOOST_CHECK_MESSAGE(true == CheckExcessive(block,1000000+1,(blockSigopsPerMb.value*2)+1,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(true == CheckExcessive(block,(2*1000000),(blockSigopsPerMb.value*2)+1,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(false == CheckExcessive(block,(2*1000000)+1,(blockSigopsPerMb.value*2)+1,100,100), "improper sigops"); // Check tx size values maxTxSize.value = DEFAULT_LARGEST_TRANSACTION; // Within a 1 MB block, a 1MB transaction is not excessive BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE,1,1,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE), "improper max tx"); // With a > 1 MB block, use the maxTxSize to determine BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE+1,1,1,maxTxSize.value), "improper max tx"); BOOST_CHECK_MESSAGE(true == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE+1,1,1,maxTxSize.value+1), "improper max tx"); } BOOST_AUTO_TEST_CASE(check_validator_rule) { BOOST_CHECK( MiningAndExcessiveBlockValidatorRule(1000000, 1000000)); BOOST_CHECK( MiningAndExcessiveBlockValidatorRule(16000000, 1000000)); BOOST_CHECK( MiningAndExcessiveBlockValidatorRule(1000001, 1000000)); BOOST_CHECK( ! MiningAndExcessiveBlockValidatorRule(1000000, 1000001)); BOOST_CHECK( ! MiningAndExcessiveBlockValidatorRule(1000000, 16000000)); BOOST_CHECK( MiningAndExcessiveBlockValidatorRule(1357, 1357)); BOOST_CHECK( MiningAndExcessiveBlockValidatorRule(161616, 2222)); BOOST_CHECK( MiningAndExcessiveBlockValidatorRule(88889, 88888)); BOOST_CHECK( ! MiningAndExcessiveBlockValidatorRule(929292, 929293)); BOOST_CHECK( ! MiningAndExcessiveBlockValidatorRule(4, 234245)); } BOOST_AUTO_TEST_CASE(check_excessive_validator) { // fudge global variables.... maxGeneratedBlock = 1000000; excessiveBlockSize = 888; unsigned int tmpExcessive = 1000000; std::string str; str = ExcessiveBlockValidator(tmpExcessive, NULL, true); BOOST_CHECK(str.empty()); excessiveBlockSize = 888; str = ExcessiveBlockValidator(tmpExcessive, NULL, false); BOOST_CHECK(str.empty()); str = ExcessiveBlockValidator(tmpExcessive, (unsigned int *) 42, true); BOOST_CHECK(str.empty()); tmpExcessive = maxGeneratedBlock + 1; str = ExcessiveBlockValidator(tmpExcessive, NULL, true); BOOST_CHECK(str.empty()); excessiveBlockSize = 888; str = ExcessiveBlockValidator(tmpExcessive, NULL, false); BOOST_CHECK(str.empty()); str = ExcessiveBlockValidator(tmpExcessive, (unsigned int *) 42, true); BOOST_CHECK(str.empty()); tmpExcessive = maxGeneratedBlock - 1; str = ExcessiveBlockValidator(tmpExcessive, NULL, true); BOOST_CHECK(! str.empty()); str = ExcessiveBlockValidator(tmpExcessive, NULL, false); BOOST_CHECK(str.empty()); str = ExcessiveBlockValidator(tmpExcessive, (unsigned int *) 42, true); BOOST_CHECK(! str.empty()); } BOOST_AUTO_TEST_CASE(check_generated_block_validator) { // fudge global variables.... maxGeneratedBlock = 888; excessiveBlockSize = 1000000; uint64_t tmpMGB = 1000000; std::string str; str = MiningBlockSizeValidator(tmpMGB, NULL, true); BOOST_CHECK(str.empty()); maxGeneratedBlock = 8888881; str = MiningBlockSizeValidator(tmpMGB, NULL, false); BOOST_CHECK(str.empty()); str = MiningBlockSizeValidator(tmpMGB, (uint64_t *) 42, true); BOOST_CHECK(str.empty()); tmpMGB = excessiveBlockSize - 1; str = MiningBlockSizeValidator(tmpMGB, NULL, true); BOOST_CHECK(str.empty()); maxGeneratedBlock = 8888881; str = MiningBlockSizeValidator(tmpMGB, NULL, false); BOOST_CHECK(str.empty()); str = MiningBlockSizeValidator(tmpMGB, (uint64_t *) 42, true); BOOST_CHECK(str.empty()); tmpMGB = excessiveBlockSize + 1; str = MiningBlockSizeValidator(tmpMGB, NULL, true); BOOST_CHECK(! str.empty()); str = MiningBlockSizeValidator(tmpMGB, NULL, false); BOOST_CHECK(str.empty()); str = MiningBlockSizeValidator(tmpMGB, (uint64_t *) 42, true); BOOST_CHECK(! str.empty()); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>// Copyright 2013 The Flutter 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 "flutter/lib/ui/painting/single_frame_codec.h" #include "flutter/lib/ui/painting/frame_info.h" #include "flutter/lib/ui/ui_dart_state.h" #include "third_party/tonic/logging/dart_invoke.h" namespace flutter { SingleFrameCodec::SingleFrameCodec(ImageDecoder::ImageDescriptor descriptor) : status_(Status::kNew), descriptor_(std::move(descriptor)) {} SingleFrameCodec::~SingleFrameCodec() = default; int SingleFrameCodec::frameCount() const { return 1; } int SingleFrameCodec::repetitionCount() const { return 0; } Dart_Handle SingleFrameCodec::getNextFrame(Dart_Handle callback_handle) { if (!Dart_IsClosure(callback_handle)) { return tonic::ToDart("Callback must be a function"); } if (status_ == Status::kComplete) { tonic::DartInvoke(callback_handle, {tonic::ToDart(cached_frame_)}); return Dart_Null(); } // This has to be valid because this method is called from Dart. auto dart_state = UIDartState::Current(); pending_callbacks_.emplace_back(dart_state, callback_handle); if (status_ == Status::kInProgress) { // Another call to getNextFrame is in progress and will invoke the // pending callbacks when decoding completes. return Dart_Null(); } auto decoder = dart_state->GetImageDecoder(); if (!decoder) { return tonic::ToDart("Image decoder not available."); } auto raw_codec_wrapper = new DartPersistentValue( dart_state, Dart_HandleFromWeakPersistent(dart_wrapper())); // We dont want to to put the raw codec in a lambda capture because we have // to mutate (i.e destroy) it in the callback. Using MakeCopyable will create // a shared pointer for the captures which can be destroyed on any thread. But // we have to ensure that the DartPersistentValue is only destroyed on the UI // thread. decoder->Decode(descriptor_, [raw_codec_wrapper](auto image) { std::unique_ptr<DartPersistentValue> codec_wrapper(raw_codec_wrapper); auto state = codec_wrapper->dart_state().lock(); if (!state) { // This is probably because the isolate has been terminated before the // image could be decoded. return; } tonic::DartState::Scope scope(state.get()); SingleFrameCodec* codec = tonic::DartConverter<SingleFrameCodec*>::FromDart( codec_wrapper->value()); if (image.get()) { auto canvas_image = fml::MakeRefCounted<CanvasImage>(); canvas_image->set_image(std::move(image)); codec->cached_frame_ = fml::MakeRefCounted<FrameInfo>( std::move(canvas_image), 0 /* duration */); } // The cached frame is now available and should be returned to any future // callers. codec->status_ = Status::kComplete; // Invoke any callbacks that were provided before the frame was decoded. Dart_Handle frame = tonic::ToDart(codec->cached_frame_); for (const DartPersistentValue& callback : codec->pending_callbacks_) { tonic::DartInvoke(callback.value(), {frame}); } codec->pending_callbacks_.clear(); }); // The encoded data is no longer needed now that it has been handed off // to the decoder. descriptor_.data.reset(); status_ = Status::kInProgress; return Dart_Null(); } size_t SingleFrameCodec::GetAllocationSize() { const auto& data = descriptor_.data; const auto data_byte_size = data ? data->size() : 0; const auto frame_byte_size = (cached_frame_ && cached_frame_->image()) ? cached_frame_->image()->GetAllocationSize() : 0; return data_byte_size + frame_byte_size + sizeof(this); } } // namespace flutter <commit_msg>Ensure that the SingleFrameCodec stays alive until the ImageDecoder invokes its callback (#10297)<commit_after>// Copyright 2013 The Flutter 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 "flutter/lib/ui/painting/single_frame_codec.h" #include "flutter/lib/ui/painting/frame_info.h" #include "flutter/lib/ui/ui_dart_state.h" #include "third_party/tonic/logging/dart_invoke.h" namespace flutter { SingleFrameCodec::SingleFrameCodec(ImageDecoder::ImageDescriptor descriptor) : status_(Status::kNew), descriptor_(std::move(descriptor)) {} SingleFrameCodec::~SingleFrameCodec() = default; int SingleFrameCodec::frameCount() const { return 1; } int SingleFrameCodec::repetitionCount() const { return 0; } Dart_Handle SingleFrameCodec::getNextFrame(Dart_Handle callback_handle) { if (!Dart_IsClosure(callback_handle)) { return tonic::ToDart("Callback must be a function"); } if (status_ == Status::kComplete) { tonic::DartInvoke(callback_handle, {tonic::ToDart(cached_frame_)}); return Dart_Null(); } // This has to be valid because this method is called from Dart. auto dart_state = UIDartState::Current(); pending_callbacks_.emplace_back(dart_state, callback_handle); if (status_ == Status::kInProgress) { // Another call to getNextFrame is in progress and will invoke the // pending callbacks when decoding completes. return Dart_Null(); } auto decoder = dart_state->GetImageDecoder(); if (!decoder) { return tonic::ToDart("Image decoder not available."); } // The SingleFrameCodec must be deleted on the UI thread. Allocate a RefPtr // on the heap to ensure that the SingleFrameCodec remains alive until the // decoder callback is invoked on the UI thread. The callback can then // drop the reference. fml::RefPtr<SingleFrameCodec>* raw_codec_ref = new fml::RefPtr<SingleFrameCodec>(this); decoder->Decode(descriptor_, [raw_codec_ref](auto image) { std::unique_ptr<fml::RefPtr<SingleFrameCodec>> codec_ref(raw_codec_ref); fml::RefPtr<SingleFrameCodec> codec(std::move(*codec_ref)); auto state = codec->pending_callbacks_.front().dart_state().lock(); if (!state) { // This is probably because the isolate has been terminated before the // image could be decoded. return; } tonic::DartState::Scope scope(state.get()); if (image.get()) { auto canvas_image = fml::MakeRefCounted<CanvasImage>(); canvas_image->set_image(std::move(image)); codec->cached_frame_ = fml::MakeRefCounted<FrameInfo>( std::move(canvas_image), 0 /* duration */); } // The cached frame is now available and should be returned to any future // callers. codec->status_ = Status::kComplete; // Invoke any callbacks that were provided before the frame was decoded. Dart_Handle frame = tonic::ToDart(codec->cached_frame_); for (const DartPersistentValue& callback : codec->pending_callbacks_) { tonic::DartInvoke(callback.value(), {frame}); } codec->pending_callbacks_.clear(); }); // The encoded data is no longer needed now that it has been handed off // to the decoder. descriptor_.data.reset(); status_ = Status::kInProgress; return Dart_Null(); } size_t SingleFrameCodec::GetAllocationSize() { const auto& data = descriptor_.data; const auto data_byte_size = data ? data->size() : 0; const auto frame_byte_size = (cached_frame_ && cached_frame_->image()) ? cached_frame_->image()->GetAllocationSize() : 0; return data_byte_size + frame_byte_size + sizeof(this); } } // namespace flutter <|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.h" OSRM::OSRM( const ServerPaths & server_paths, const bool use_shared_memory ) : shm( boost::interprocess::open_or_create, "SharedBarriers", boost::interprocess::read_write ), use_shared_memory(use_shared_memory) { if( !use_shared_memory ) { SimpleLogger().Write() << "loading data into internal memory"; query_data_facade = new InternalDataFacade<QueryEdge::EdgeData>( server_paths ); } else { region = boost::interprocess::mapped_region( shm, //What to map boost::interprocess::read_write //Map it as read-write ); shm.truncate( sizeof(SharedBarriers) ); barrier = static_cast<SharedBarriers *>( region.get_address() ); SimpleLogger().Write() << "loading data from shared memory"; query_data_facade = new SharedDataFacade<QueryEdge::EdgeData>( server_paths ); } //The following plugins handle all requests. RegisterPlugin( new HelloWorldPlugin() ); RegisterPlugin( new LocatePlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); RegisterPlugin( new NearestPlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); RegisterPlugin( new TimestampPlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); RegisterPlugin( new ViaRoutePlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); } OSRM::~OSRM() { BOOST_FOREACH(PluginMap::value_type & plugin_pointer, plugin_map) { delete plugin_pointer.second; } } void OSRM::RegisterPlugin(BasePlugin * plugin) { SimpleLogger().Write() << "loaded plugin: " << plugin->GetDescriptor(); if( plugin_map.find(plugin->GetDescriptor()) != plugin_map.end() ) { delete plugin_map.find(plugin->GetDescriptor())->second; } plugin_map.emplace(plugin->GetDescriptor(), plugin); } void OSRM::RunQuery(RouteParameters & route_parameters, http::Reply & reply) { const PluginMap::const_iterator & iter = plugin_map.find( route_parameters.service ); if(plugin_map.end() != iter) { reply.status = http::Reply::ok; if( use_shared_memory ) { //TODO lock update pending //TODO lock query //TODO unlock update pending //TODO ++query_count //TODO unlock query //wait until we get the mutex and free it immediately //TODO: increment semaphore of querying processes boost::interprocess::scoped_lock< boost::interprocess::interprocess_mutex > lock(barrier->update_mutex); } iter->second->HandleRequest(route_parameters, reply ); if( use_shared_memory ) { //TODO unlock update pending //TODO --query_count //if (0 == query_count) { //TODO notify.all query_count 0 //} //TODO unlock query } } else { reply = http::Reply::stockReply(http::Reply::badRequest); } } <commit_msg>implement shared lock in query<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.h" OSRM::OSRM( const ServerPaths & server_paths, const bool use_shared_memory ) : shm( boost::interprocess::open_or_create, "SharedBarriers", boost::interprocess::read_write ), use_shared_memory(use_shared_memory) { if( !use_shared_memory ) { SimpleLogger().Write() << "loading data into internal memory"; query_data_facade = new InternalDataFacade<QueryEdge::EdgeData>( server_paths ); } else { region = boost::interprocess::mapped_region( shm, //What to map boost::interprocess::read_write //Map it as read-write ); shm.truncate( sizeof(SharedBarriers) ); barrier = static_cast<SharedBarriers *>( region.get_address() ); SimpleLogger().Write() << "loading data from shared memory"; query_data_facade = new SharedDataFacade<QueryEdge::EdgeData>( server_paths ); } //The following plugins handle all requests. RegisterPlugin( new HelloWorldPlugin() ); RegisterPlugin( new LocatePlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); RegisterPlugin( new NearestPlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); RegisterPlugin( new TimestampPlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); RegisterPlugin( new ViaRoutePlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); } OSRM::~OSRM() { BOOST_FOREACH(PluginMap::value_type & plugin_pointer, plugin_map) { delete plugin_pointer.second; } } void OSRM::RegisterPlugin(BasePlugin * plugin) { SimpleLogger().Write() << "loaded plugin: " << plugin->GetDescriptor(); if( plugin_map.find(plugin->GetDescriptor()) != plugin_map.end() ) { delete plugin_map.find(plugin->GetDescriptor())->second; } plugin_map.emplace(plugin->GetDescriptor(), plugin); } void OSRM::RunQuery(RouteParameters & route_parameters, http::Reply & reply) { const PluginMap::const_iterator & iter = plugin_map.find( route_parameters.service ); if(plugin_map.end() != iter) { reply.status = http::Reply::ok; if( use_shared_memory ) { // lock update pending boost::interprocess::scoped_lock< boost::interprocess::named_mutex > pending_lock(barrier->pending_update_mutex); // lock query boost::interprocess::scoped_lock< boost::interprocess::named_mutex > query_lock(barrier->query_mutex); // unlock update pending pending_lock.unlock(); // increment query count ++(barrier->number_of_queries); } iter->second->HandleRequest(route_parameters, reply ); if( use_shared_memory ) { // lock query boost::interprocess::scoped_lock< boost::interprocess::named_mutex > query_lock(barrier->query_mutex); // decrement query count --(barrier->number_of_queries); BOOST_ASSERT_MSG( 0 <= barrier->number_of_queries, "invalid number of queries" ); if (0 == barrier->number_of_queries) { // notify all processes that were waiting for this condition barrier->no_running_queries_condition.notify_all(); } } } else { reply = http::Reply::stockReply(http::Reply::badRequest); } } <|endoftext|>
<commit_before>/* c2ffi Copyright (C) 2013 Ryan Pavlik This file is part of c2ffi. c2ffi is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. c2ffi 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 c2ffi. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <map> #include <llvm/Support/raw_ostream.h> #include <llvm/Support/Host.h> #include <llvm/ADT/IntrusiveRefCntPtr.h> #include <clang/Basic/DiagnosticOptions.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Basic/TargetOptions.h> #include <clang/Basic/TargetInfo.h> #include <clang/Basic/FileManager.h> #include <clang/Basic/SourceManager.h> #include <clang/Lex/HeaderSearch.h> #include <clang/Lex/Preprocessor.h> #include <clang/Basic/Diagnostic.h> #include <clang/AST/ASTContext.h> #include <clang/AST/ASTConsumer.h> #include <clang/Parse/Parser.h> #include <clang/Parse/ParseAST.h> #include "c2ffi.h" #include "c2ffi/ast.h" using namespace c2ffi; static std::string value_to_string(clang::APValue *v) { std::string s; llvm::raw_string_ostream ss(s); if(v->isInt() && v->getInt().isSigned()) v->getInt().print(ss, true); else if(v->isInt()) v->getInt().print(ss, false); else if(v->isFloat()) ss << v->getFloat().convertToDouble(); ss.flush(); return s; } void C2FFIASTConsumer::HandleTopLevelDeclInObjCContainer(clang::DeclGroupRef d) { _od->write_comment("HandleTopLevelDeclInObjCContainer"); } bool C2FFIASTConsumer::HandleTopLevelDecl(clang::DeclGroupRef d) { clang::DeclGroupRef::iterator it; for(it = d.begin(); it != d.end(); it++) { Decl *decl = NULL; if((*it)->isInvalidDecl()) { std::cerr << "Skipping invalid Decl:" << std::endl; (*it)->dump(); continue; } if_cast(x, clang::VarDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::FunctionDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::RecordDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::EnumDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::TypedefDecl, *it) { decl = make_decl(x); } /* ObjC */ else if_cast(x, clang::ObjCInterfaceDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::ObjCCategoryDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::ObjCProtocolDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::ObjCImplementationDecl, *it) continue; else if_cast(x, clang::ObjCMethodDecl, *it) continue; /* Always should be last */ else if_cast(x, clang::NamedDecl, *it) { decl = make_decl(x); } else decl = make_decl(*it); if(decl) { decl->set_location(_ci, (*it)); if(_mid) _od->write_between(); else _mid = true; _od->write(*decl); delete decl; } } return true; } bool C2FFIASTConsumer::is_cur_decl(const clang::Decl *d) const { return _cur_decls.count(d); } Decl* C2FFIASTConsumer::make_decl(const clang::Decl *d, bool is_toplevel) { return new UnhandledDecl("", d->getDeclKindName()); } Decl* C2FFIASTConsumer::make_decl(const clang::NamedDecl *d, bool is_toplevel) { return new UnhandledDecl(d->getDeclName().getAsString(), d->getDeclKindName()); } Decl* C2FFIASTConsumer::make_decl(const clang::FunctionDecl *d, bool is_toplevel) { _cur_decls.insert(d); const clang::Type *return_type = d->getReturnType().getTypePtr(); FunctionDecl *fd = new FunctionDecl(d->getDeclName().getAsString(), Type::make_type(this, return_type), d->isVariadic()); for(clang::FunctionDecl::param_const_iterator i = d->param_begin(); i != d->param_end(); i++) { fd->add_field(this, *i); } return fd; } Decl* C2FFIASTConsumer::make_decl(const clang::VarDecl *d, bool is_toplevel) { clang::ASTContext &ctx = _ci.getASTContext(); clang::APValue *v = NULL; std::string name = d->getDeclName().getAsString(), value = ""; bool is_string = false; if(name.substr(0, 8) == "__c2ffi_") name = name.substr(8, std::string::npos); if(d->hasInit() && ((v = d->evaluateValue()) || (v = d->getEvaluatedValue()))) { if(v->isLValue()) { clang::APValue::LValueBase base = v->getLValueBase(); const clang::Expr *e = base.get<const clang::Expr*>(); if_const_cast(s, clang::StringLiteral, e) { value = s->getString(); is_string = true; } } else { value = value_to_string(v); } } Type *t = Type::make_type(this, d->getTypeSourceInfo()->getType().getTypePtr()); return new VarDecl(name, t, value, d->hasExternalStorage(), is_string); } Decl* C2FFIASTConsumer::make_decl(const clang::RecordDecl *d, bool is_toplevel) { std::string name = d->getDeclName().getAsString(); clang::ASTContext &ctx = _ci.getASTContext(); const clang::Type *t = d->getTypeForDecl(); if(is_toplevel && name == "") return NULL; _cur_decls.insert(d); RecordDecl *rd = new RecordDecl(name, d->isUnion()); if(!t->isIncompleteType()) { rd->set_bit_size(ctx.getTypeSize(t)); rd->set_bit_alignment(ctx.getTypeAlign(t)); } else { rd->set_bit_size(0); rd->set_bit_alignment(0); } if(name == "") { _anon_decls[d] = _anon_id; rd->set_id(_anon_id); _anon_id++; } for(clang::RecordDecl::field_iterator i = d->field_begin(); i != d->field_end(); i++) rd->add_field(this, *i); return rd; } bool is_underlying_valid(const clang::Type *t) { if_const_cast(e, clang::ElaboratedType, t) { return is_underlying_valid(e->getNamedType().getTypePtr()); } if_const_cast(rt, clang::RecordType, t) { if(rt->getDecl()->isInvalidDecl()) return false; } return true; } Decl* C2FFIASTConsumer::make_decl(const clang::TypedefDecl *d, bool is_toplevel) { const clang::Type *t = d->getTypeSourceInfo()->getType().getTypePtr(); if(is_underlying_valid(t)) { return new TypedefDecl(d->getDeclName().getAsString(), Type::make_type(this, t)); } else { std::cerr << "Skipping typedef to invalid type:" << std::endl; d->dump(); return NULL; } } Decl* C2FFIASTConsumer::make_decl(const clang::EnumDecl *d, bool is_toplevel) { std::string name = d->getDeclName().getAsString(); _cur_decls.insert(d); EnumDecl *decl = new EnumDecl(name); if(name == "") { _anon_decls[d] = _anon_id; decl->set_id(_anon_id); _anon_id++; } for(clang::EnumDecl::enumerator_iterator i = d->enumerator_begin(); i != d->enumerator_end(); i++) { const clang::EnumConstantDecl *ecd = (*i); decl->add_field(ecd->getDeclName().getAsString(), ecd->getInitVal().getLimitedValue()); } return decl; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCInterfaceDecl *d, bool is_toplevel) { const clang::ObjCInterfaceDecl *super = d->getSuperClass(); _cur_decls.insert(d); ObjCInterfaceDecl *r = new ObjCInterfaceDecl(d->getDeclName().getAsString(), super ? super->getDeclName().getAsString() : "", !d->hasDefinition()); for(clang::ObjCInterfaceDecl::protocol_iterator i = d->protocol_begin(); i != d->protocol_end(); i++) r->add_protocol((*i)->getDeclName().getAsString()); for(clang::ObjCInterfaceDecl::ivar_iterator i = d->ivar_begin(); i != d->ivar_end(); i++) { r->add_field(this, *i); } r->add_functions(this, d); return r; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCCategoryDecl *d, bool is_toplevel) { ObjCCategoryDecl *r = new ObjCCategoryDecl(d->getClassInterface()->getDeclName().getAsString(), d->getDeclName().getAsString()); _cur_decls.insert(d); r->add_functions(this, d); return r; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCProtocolDecl *d, bool is_toplevel) { ObjCProtocolDecl *r = new ObjCProtocolDecl(d->getDeclName().getAsString()); _cur_decls.insert(d); r->add_functions(this, d); return r; } unsigned int C2FFIASTConsumer::decl_id(const clang::Decl *d) const { ClangDeclIDMap::const_iterator it = _anon_decls.find(d); if(it != _anon_decls.end()) return it->second; else return 0; } <commit_msg>Fix for typedefs with __attribute__ ((__mode__ ...))<commit_after>/* c2ffi Copyright (C) 2013 Ryan Pavlik This file is part of c2ffi. c2ffi is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. c2ffi 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 c2ffi. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <map> #include <llvm/Support/raw_ostream.h> #include <llvm/Support/Host.h> #include <llvm/ADT/IntrusiveRefCntPtr.h> #include <clang/Basic/DiagnosticOptions.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Basic/TargetOptions.h> #include <clang/Basic/TargetInfo.h> #include <clang/Basic/FileManager.h> #include <clang/Basic/SourceManager.h> #include <clang/Lex/HeaderSearch.h> #include <clang/Lex/Preprocessor.h> #include <clang/Basic/Diagnostic.h> #include <clang/AST/ASTContext.h> #include <clang/AST/ASTConsumer.h> #include <clang/Parse/Parser.h> #include <clang/Parse/ParseAST.h> #include "c2ffi.h" #include "c2ffi/ast.h" using namespace c2ffi; static std::string value_to_string(clang::APValue *v) { std::string s; llvm::raw_string_ostream ss(s); if(v->isInt() && v->getInt().isSigned()) v->getInt().print(ss, true); else if(v->isInt()) v->getInt().print(ss, false); else if(v->isFloat()) ss << v->getFloat().convertToDouble(); ss.flush(); return s; } void C2FFIASTConsumer::HandleTopLevelDeclInObjCContainer(clang::DeclGroupRef d) { _od->write_comment("HandleTopLevelDeclInObjCContainer"); } bool C2FFIASTConsumer::HandleTopLevelDecl(clang::DeclGroupRef d) { clang::DeclGroupRef::iterator it; for(it = d.begin(); it != d.end(); it++) { Decl *decl = NULL; if((*it)->isInvalidDecl()) { std::cerr << "Skipping invalid Decl:" << std::endl; (*it)->dump(); continue; } if_cast(x, clang::VarDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::FunctionDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::RecordDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::EnumDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::TypedefDecl, *it) { decl = make_decl(x); } /* ObjC */ else if_cast(x, clang::ObjCInterfaceDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::ObjCCategoryDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::ObjCProtocolDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::ObjCImplementationDecl, *it) continue; else if_cast(x, clang::ObjCMethodDecl, *it) continue; /* Always should be last */ else if_cast(x, clang::NamedDecl, *it) { decl = make_decl(x); } else decl = make_decl(*it); if(decl) { decl->set_location(_ci, (*it)); if(_mid) _od->write_between(); else _mid = true; _od->write(*decl); delete decl; } } return true; } bool C2FFIASTConsumer::is_cur_decl(const clang::Decl *d) const { return _cur_decls.count(d); } Decl* C2FFIASTConsumer::make_decl(const clang::Decl *d, bool is_toplevel) { return new UnhandledDecl("", d->getDeclKindName()); } Decl* C2FFIASTConsumer::make_decl(const clang::NamedDecl *d, bool is_toplevel) { return new UnhandledDecl(d->getDeclName().getAsString(), d->getDeclKindName()); } Decl* C2FFIASTConsumer::make_decl(const clang::FunctionDecl *d, bool is_toplevel) { _cur_decls.insert(d); const clang::Type *return_type = d->getReturnType().getTypePtr(); FunctionDecl *fd = new FunctionDecl(d->getDeclName().getAsString(), Type::make_type(this, return_type), d->isVariadic()); for(clang::FunctionDecl::param_const_iterator i = d->param_begin(); i != d->param_end(); i++) { fd->add_field(this, *i); } return fd; } Decl* C2FFIASTConsumer::make_decl(const clang::VarDecl *d, bool is_toplevel) { clang::ASTContext &ctx = _ci.getASTContext(); clang::APValue *v = NULL; std::string name = d->getDeclName().getAsString(), value = ""; bool is_string = false; if(name.substr(0, 8) == "__c2ffi_") name = name.substr(8, std::string::npos); if(d->hasInit() && ((v = d->evaluateValue()) || (v = d->getEvaluatedValue()))) { if(v->isLValue()) { clang::APValue::LValueBase base = v->getLValueBase(); const clang::Expr *e = base.get<const clang::Expr*>(); if_const_cast(s, clang::StringLiteral, e) { value = s->getString(); is_string = true; } } else { value = value_to_string(v); } } Type *t = Type::make_type(this, d->getTypeSourceInfo()->getType().getTypePtr()); return new VarDecl(name, t, value, d->hasExternalStorage(), is_string); } Decl* C2FFIASTConsumer::make_decl(const clang::RecordDecl *d, bool is_toplevel) { std::string name = d->getDeclName().getAsString(); clang::ASTContext &ctx = _ci.getASTContext(); const clang::Type *t = d->getTypeForDecl(); if(is_toplevel && name == "") return NULL; _cur_decls.insert(d); RecordDecl *rd = new RecordDecl(name, d->isUnion()); if(!t->isIncompleteType()) { rd->set_bit_size(ctx.getTypeSize(t)); rd->set_bit_alignment(ctx.getTypeAlign(t)); } else { rd->set_bit_size(0); rd->set_bit_alignment(0); } if(name == "") { _anon_decls[d] = _anon_id; rd->set_id(_anon_id); _anon_id++; } for(clang::RecordDecl::field_iterator i = d->field_begin(); i != d->field_end(); i++) rd->add_field(this, *i); return rd; } bool is_underlying_valid(const clang::Type *t) { if_const_cast(e, clang::ElaboratedType, t) { return is_underlying_valid(e->getNamedType().getTypePtr()); } if_const_cast(rt, clang::RecordType, t) { if(rt->getDecl()->isInvalidDecl()) return false; } return true; } Decl* C2FFIASTConsumer::make_decl(const clang::TypedefDecl *d, bool is_toplevel) { const clang::Type *t = d->getUnderlyingType().getTypePtr(); if(is_underlying_valid(t)) { return new TypedefDecl(d->getDeclName().getAsString(), Type::make_type(this, t)); } else { std::cerr << "Skipping typedef to invalid type:" << std::endl; d->dump(); return NULL; } } Decl* C2FFIASTConsumer::make_decl(const clang::EnumDecl *d, bool is_toplevel) { std::string name = d->getDeclName().getAsString(); _cur_decls.insert(d); EnumDecl *decl = new EnumDecl(name); if(name == "") { _anon_decls[d] = _anon_id; decl->set_id(_anon_id); _anon_id++; } for(clang::EnumDecl::enumerator_iterator i = d->enumerator_begin(); i != d->enumerator_end(); i++) { const clang::EnumConstantDecl *ecd = (*i); decl->add_field(ecd->getDeclName().getAsString(), ecd->getInitVal().getLimitedValue()); } return decl; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCInterfaceDecl *d, bool is_toplevel) { const clang::ObjCInterfaceDecl *super = d->getSuperClass(); _cur_decls.insert(d); ObjCInterfaceDecl *r = new ObjCInterfaceDecl(d->getDeclName().getAsString(), super ? super->getDeclName().getAsString() : "", !d->hasDefinition()); for(clang::ObjCInterfaceDecl::protocol_iterator i = d->protocol_begin(); i != d->protocol_end(); i++) r->add_protocol((*i)->getDeclName().getAsString()); for(clang::ObjCInterfaceDecl::ivar_iterator i = d->ivar_begin(); i != d->ivar_end(); i++) { r->add_field(this, *i); } r->add_functions(this, d); return r; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCCategoryDecl *d, bool is_toplevel) { ObjCCategoryDecl *r = new ObjCCategoryDecl(d->getClassInterface()->getDeclName().getAsString(), d->getDeclName().getAsString()); _cur_decls.insert(d); r->add_functions(this, d); return r; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCProtocolDecl *d, bool is_toplevel) { ObjCProtocolDecl *r = new ObjCProtocolDecl(d->getDeclName().getAsString()); _cur_decls.insert(d); r->add_functions(this, d); return r; } unsigned int C2FFIASTConsumer::decl_id(const clang::Decl *d) const { ClangDeclIDMap::const_iterator it = _anon_decls.find(d); if(it != _anon_decls.end()) return it->second; else return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2016 Ansho Enigu #include "crypto/lamport.h" #include "crypto/ripemd160.h" #include "crypto/common.h" bool LAMPORT::checksig(unsigned char* data, char sig[160][20], char pubkey[320][20]) { bool messhashb[160]; unsigned char* messhash; CRIPEMD160().Write(&data, data.size()).Finalize(&messhash); memcpy(messhashb, messhash, sizeof(messhashb)); char _sig[160][20]; char _csig[160][20]; for(int i=0; i < 160; i++) { for(int o=0; o < 20; o++) { if(messhashb[i]) { _sig[i][o] = pubkey[2*i][o]; } else { _sig[i][o] = pubkey[(2*i)+1][o]; } } } unsigned char* sighop; for(int i=0; i < 160; i++) { CRIPEMD160().Write(&_sig[i], _sig[i].size()).Finalize(&sighop); memcpy(_csig[i], sighop, _csig[i].size()); } return sig == _csig; } char[320][20] LAMPORT::createsig(unsigned char* data, unsigned uint512_t prikey) { /* hash of the message */ bool messhashb[160]; unsigned char* messhash; CRIPEMD160().Write(&data, data.size()).Finalize(&messhash); /* creating true key from seed (the seed is used as the key by the user but it only is a form of compress key) */ valtype vchHash(true ? 20 : 32); CRIPEMD160().Write(&prikey, prikey.size()).Finalize(&vchHash); for(int i =0; i < 320; i++) { unsigned char* tempHash; CRIPEMD160().Write(&vchHash, prikey.size()).Write(&i, i.size()).Finalize(&tempHash); prikeys[i] = temphash; } /* the signing will happen uder this */ char sig[320][20]; memcpy(messhashb, messhash, sizeof(messhashb)); for(int i=0; i < 160; i++) { if(messhashb[i]) { sig[i] = prikeys[2*i]; } else { sig[i] = prikeys[(2*i)+1]; } } return sig; } <commit_msg>Update lamport.cpp<commit_after>// Copyright (c) 2016 Ansho Enigu #include "crypto/lamport.h" #include "crypto/ripemd160.h" #include "crypto/common.h" bool LAMPORT::checksig(unsigned char* data, char sig[160][20], char pubkey[320][20]) { bool messhashb[160]; unsigned char* messhash; CRIPEMD160().Write(&data, data.size()).Finalize(&messhash); memcpy(messhashb, messhash, sizeof(messhashb)); char _sig[160][20]; char _csig[160][20]; for(int i=0; i < 160; i++) { for(int o=0; o < 20; o++) { if(messhashb[i]) { _sig[i][o] = pubkey[2*i][o]; } else { _sig[i][o] = pubkey[(2*i)+1][o]; } } } unsigned char* sighop; for(int i=0; i < 160; i++) { CRIPEMD160().Write(&_sig[i], _sig[i].size()).Finalize(&sighop); memcpy(_csig[i], sighop, _csig[i].size()); } return sig == _csig; } char[320][20] LAMPORT::createsig(unsigned char* data, uint512_t prikey) { /* hash of the message */ bool messhashb[160]; unsigned char* messhash; CRIPEMD160().Write(&data, data.size()).Finalize(&messhash); /* creating true key from seed (the seed is used as the key by the user but it only is a form of compress key) */ valtype vchHash(true ? 20 : 32); CRIPEMD160().Write(&prikey, prikey.size()).Finalize(&vchHash); for(int i =0; i < 320; i++) { unsigned char* tempHash; CRIPEMD160().Write(&vchHash, prikey.size()).Write(&i, i.size()).Finalize(&tempHash); prikeys[i] = temphash; } /* the signing will happen uder this */ char sig[320][20]; memcpy(messhashb, messhash, sizeof(messhashb)); for(int i=0; i < 160; i++) { if(messhashb[i]) { sig[i] = prikeys[2*i]; } else { sig[i] = prikeys[(2*i)+1]; } } return sig; } <|endoftext|>
<commit_before>#include <fcntl.h> #include <stdio.h> #include <sys/stat.h> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> #include <errno.h> #define MAX_BUF 1024 #include <sstream> #include <iostream> #include <string> using namespace std; #include <boost/property_tree/json_parser.hpp> static int fd = -1; #include <signal.h> #include <stdio.h> void sigcatch(int) { if(fd > 0) { close(fd); } exit(0); } int main() { if (SIG_ERR == signal(SIGINT, sigcatch)) { printf("failed to set signal handler.n"); exit(1); } fd = socket( AF_LOCAL, SOCK_DGRAM, 0 ); struct sockaddr_un addr; bzero( &addr, sizeof(addr) ); addr.sun_family = AF_LOCAL; strcpy( addr.sun_path, "/tmp/mpu.6050.unix.domain" ); int use = 1; if (::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &use, sizeof(int)) < 0) { perror("setsockopt(SO_REUSEADDR) failed"); } if(::bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) { printf(" cannot bind socket: %d. \n",errno); close(fd); return 0; } char buf[MAX_BUF]; int degree = 90; while(degree >0) { socklen_t len = sizeof(addr); int ret = ::recvfrom(fd, buf, MAX_BUF, 0, (struct sockaddr *)&addr, &len); if(ret>0){ //printf("Received: %s\n", buf); string recvStr(buf,ret); std::cout << recvStr << std::endl; std::stringstream ss; ss << recvStr; boost::property_tree::ptree pt; boost::property_tree::read_json(ss, pt); std::cout << pt.get<double>("yaw") << std::endl; } else if (ret==0){ } else { printf("ret=<%d>\n",ret); } } close(fd); return 0; } <commit_msg>Update turn.cpp<commit_after>#include <fcntl.h> #include <stdio.h> #include <sys/stat.h> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> #include <errno.h> #define MAX_BUF 1024 #include <sstream> #include <iostream> #include <string> using namespace std; #include <boost/property_tree/json_parser.hpp> static int fd = -1; #include <signal.h> #include <stdio.h> void sigcatch(int) { if(fd > 0) { close(fd); } exit(0); } int main() { if (SIG_ERR == signal(SIGINT, sigcatch)) { printf("failed to set signal handler.n"); exit(1); } fd = socket( AF_LOCAL, SOCK_DGRAM, 0 ); struct sockaddr_un addr; bzero( &addr, sizeof(addr) ); addr.sun_family = AF_LOCAL; strcpy( addr.sun_path, "/tmp/mpu.6050.unix.domain" ); int use = 1; if (::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &use, sizeof(int)) < 0) { perror("setsockopt(SO_REUSEADDR) failed"); } if(::bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) { printf(" cannot bind socket: %d. \n",errno); close(fd); return 0; } char buf[MAX_BUF]; int degree = 90; while(degree >0) { socklen_t len = sizeof(addr); int ret = ::recvfrom(fd, buf, MAX_BUF, 0, (struct sockaddr *)&addr, &len); if(ret>0){ //printf("Received: %s\n", buf); string recvStr(buf,ret); std::cout << recvStr << std::endl; std::stringstream ss; ss << recvStr; try { boost::property_tree::ptree pt; boost::property_tree::read_json(ss, pt); std::cout << pt.get<double>("yaw") << std::endl; } catch(std::exception e) { std::cout << e.what() << std::endl; } } else if (ret==0){ } else { printf("ret=<%d>\n",ret); } } close(fd); return 0; } <|endoftext|>
<commit_before>/* c2ffi Copyright (C) 2013 Ryan Pavlik This file is part of c2ffi. c2ffi is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. c2ffi 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 c2ffi. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <map> #include <llvm/Support/raw_ostream.h> #include <llvm/Support/Host.h> #include <llvm/ADT/IntrusiveRefCntPtr.h> #include <clang/Basic/DiagnosticOptions.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Basic/TargetOptions.h> #include <clang/Basic/TargetInfo.h> #include <clang/Basic/FileManager.h> #include <clang/Basic/SourceManager.h> #include <clang/Lex/HeaderSearch.h> #include <clang/Lex/Preprocessor.h> #include <clang/Basic/Diagnostic.h> #include <clang/AST/ASTContext.h> #include <clang/AST/ASTConsumer.h> #include <clang/AST/DeclTemplate.h> #include <clang/AST/RecordLayout.h> #include <clang/Parse/Parser.h> #include <clang/Parse/ParseAST.h> #include "c2ffi.h" #include "c2ffi/ast.h" using namespace c2ffi; static std::string value_to_string(clang::APValue *v) { std::string s; llvm::raw_string_ostream ss(s); if(v->isInt() && v->getInt().isSigned()) v->getInt().print(ss, true); else if(v->isInt()) v->getInt().print(ss, false); else if(v->isFloat()) ss << v->getFloat().convertToDouble(); ss.flush(); return s; } void C2FFIASTConsumer::HandleTopLevelDeclInObjCContainer(clang::DeclGroupRef d) { _od->write_comment("HandleTopLevelDeclInObjCContainer"); } Decl* C2FFIASTConsumer::proc(const clang::Decl *d, Decl *decl) { if(!decl) return NULL; decl->set_ns(add_decl(_ns)); if(decl->location() == "") decl->set_location(_ci, d); if(_mid) _od->write_between(); else _mid = true; _od->write(*decl); return decl; } #define PROC decl = proc(d, make_decl(x)) void C2FFIASTConsumer::HandleDecl(clang::Decl *d, const clang::NamedDecl *ns) { Decl *decl = NULL; const clang::NamedDecl *old_ns = _ns; _ns = ns; if(d->isInvalidDecl()) { std::cerr << "Skipping invalid Decl:" << std::endl; d->dump(); return; } /* std::cerr << "DECL:" << std::endl; d->dump(); */ if_cast(x, clang::NamespaceDecl, d) { PROC; HandleNS(x); } else if_cast(x, clang::VarDecl, d) PROC; /* C/C++ */ else if_cast(x, clang::FieldDecl, d); else if_cast(x, clang::IndirectFieldDecl, d); else if_cast(x, clang::CXXMethodDecl, d); else if_cast(x, clang::FunctionTemplateDecl, d); else if_cast(x, clang::FunctionDecl, d) PROC; else if_cast(x, clang::CXXRecordDecl, d) { PROC; HandleDeclContext(x, x); } else if_cast(x, clang::RecordDecl, d) { PROC; HandleDeclContext(x, x); } else if_cast(x, clang::EnumDecl, d) PROC; else if_cast(x, clang::TypedefDecl, d) PROC; else if_cast(x, clang::ClassTemplateDecl, d); /* ObjC */ else if_cast(x, clang::ObjCInterfaceDecl, d) PROC; else if_cast(x, clang::ObjCCategoryDecl, d) PROC; else if_cast(x, clang::ObjCProtocolDecl, d) PROC; else if_cast(x, clang::ObjCImplementationDecl, d); else if_cast(x, clang::ObjCMethodDecl, d); /* Always should be last */ else if_cast(x, clang::NamedDecl, d) PROC; else decl = make_decl(d); if(decl) delete decl; _ns = old_ns; } void C2FFIASTConsumer::HandleNS(const clang::NamespaceDecl *ns) { HandleDeclContext(ns, ns); } void C2FFIASTConsumer::HandleDeclContext(const clang::DeclContext *dc, const clang::NamedDecl *ns) { clang::DeclContext::decl_iterator it; for(it = dc->decls_begin(); it != dc->decls_end(); ++it) HandleDecl(*it, ns); } bool C2FFIASTConsumer::HandleTopLevelDecl(clang::DeclGroupRef d) { clang::DeclGroupRef::iterator it; for(it = d.begin(); it != d.end(); ++it) HandleDecl(*it); return true; } void C2FFIASTConsumer::PostProcess() { if(!_config.template_output) return; std::ofstream &out = *_config.template_output; out << "#include \"" << _config.filename << "\"" << std::endl; for(ClangDeclSet::iterator i = _cxx_decls.begin(); i != _cxx_decls.end(); ++i) { const clang::Decl *d = (*i); if_const_cast(x, clang::ClassTemplateSpecializationDecl, d) { if(x->getSpecializationKind()) continue; if_const_cast(y, clang::ClassTemplatePartialSpecializationDecl, d) continue; write_template(x, out); } } } bool C2FFIASTConsumer::is_cur_decl(const clang::Decl *d) const { return _cur_decls.count(d); } Decl* C2FFIASTConsumer::make_decl(const clang::Decl *d, bool is_toplevel) { return new UnhandledDecl("", d->getDeclKindName()); } Decl* C2FFIASTConsumer::make_decl(const clang::NamedDecl *d, bool is_toplevel) { return new UnhandledDecl(d->getDeclName().getAsString(), d->getDeclKindName()); } Decl* C2FFIASTConsumer::make_decl(const clang::FunctionDecl *d, bool is_toplevel) { _cur_decls.insert(d); clang::FunctionTemplateSpecializationInfo *spec = d->getTemplateSpecializationInfo(); const clang::Type *return_type = d->getReturnType().getTypePtr(); FunctionDecl *fd = new FunctionDecl(this, d->getDeclName().getAsString(), Type::make_type(this, return_type), d->isVariadic(), d->isInlineSpecified(), d->getStorageClass(), (spec ? spec->TemplateArguments : NULL)); for(clang::FunctionDecl::param_const_iterator i = d->param_begin(); i != d->param_end(); i++) { fd->add_field(this, *i); } return fd; } Decl* C2FFIASTConsumer::make_decl(const clang::VarDecl *d, bool is_toplevel) { clang::ASTContext &ctx = _ci.getASTContext(); clang::APValue *v = NULL; std::string name = d->getDeclName().getAsString(); std::string value = ""; std::string loc = ""; bool is_string = false; if(name.substr(0, 8) == "__c2ffi_") { name = name.substr(8, std::string::npos); clang::Preprocessor &pp = _ci.getPreprocessor(); clang::IdentifierInfo &ii = pp.getIdentifierTable().get(llvm::StringRef(name)); const clang::MacroInfo *mi = pp.getMacroInfo(&ii); if(mi) loc = mi->getDefinitionLoc().printToString(_ci.getSourceManager()); } if(d->hasInit()) { if(!d->getType()->isDependentType()) { clang::EvaluatedStmt *stmt = d->ensureEvaluatedStmt(); clang::Expr *e = clang::cast<clang::Expr>(stmt->Value); if(!e->isValueDependent() && ((v = d->evaluateValue()) || (v = d->getEvaluatedValue()))) { if(v->isLValue()) { clang::APValue::LValueBase base = v->getLValueBase(); if(!base.isNull() && base.is<const clang::Expr*>()) { const clang::Expr *e = base.get<const clang::Expr*>(); if_const_cast(s, clang::StringLiteral, e) { value = s->getString(); is_string = true; } } } else { value = value_to_string(v); } } } } Type *t = Type::make_type(this, d->getTypeSourceInfo()->getType().getTypePtr()); VarDecl *cv = new VarDecl(name, t, value, d->hasExternalStorage(), is_string); if(loc != "") cv->set_location(loc); return cv; } Decl* C2FFIASTConsumer::make_decl(const clang::RecordDecl *d, bool is_toplevel) { std::string name = d->getDeclName().getAsString(); if(is_toplevel && name == "") return NULL; _cur_decls.insert(d); RecordDecl *rd = new RecordDecl(name, d->isUnion()); rd->fill_record_decl(this, d); return rd; } bool is_underlying_valid(const clang::Type *t) { if_const_cast(e, clang::ElaboratedType, t) { return is_underlying_valid(e->getNamedType().getTypePtr()); } if_const_cast(rt, clang::RecordType, t) { if(rt->getDecl()->isInvalidDecl()) return false; } return true; } Decl* C2FFIASTConsumer::make_decl(const clang::TypedefDecl *d, bool is_toplevel) { const clang::Type *t = d->getUnderlyingType().getTypePtr(); if(is_underlying_valid(t)) { return new TypedefDecl(d->getDeclName().getAsString(), Type::make_type(this, t)); } else { std::cerr << "Skipping typedef to invalid type:" << std::endl; d->dump(); return NULL; } } Decl* C2FFIASTConsumer::make_decl(const clang::EnumDecl *d, bool is_toplevel) { std::string name = d->getDeclName().getAsString(); _cur_decls.insert(d); EnumDecl *decl = new EnumDecl(name); if(name == "") { decl->set_id(add_decl(d)); } for(clang::EnumDecl::enumerator_iterator i = d->enumerator_begin(); i != d->enumerator_end(); ++i) { const clang::EnumConstantDecl *ecd = (*i); decl->add_field(ecd->getDeclName().getAsString(), ecd->getInitVal().getLimitedValue()); } return decl; } Decl* C2FFIASTConsumer::make_decl(const clang::CXXRecordDecl *d, bool is_toplevel) { if(!d->hasDefinition() || d->getDefinition()->isInvalidDecl()) return NULL; std::string name = d->getDeclName().getAsString(); const clang::TemplateArgumentList *template_args = NULL; if(is_toplevel && name == "") return NULL; if_const_cast(cts, clang::ClassTemplateSpecializationDecl, d) { template_args = &(cts->getTemplateArgs()); } bool dependent = d->isDependentType(); _cur_decls.insert(d); CXXRecordDecl *rd = new CXXRecordDecl(this, name, d->isUnion(), d->isClass(), template_args); rd->set_id(add_cxx_decl(d)); rd->add_functions(this, d); if(!dependent) { rd->fill_record_decl(this, d); const clang::ASTRecordLayout &layout = _ci.getASTContext().getASTRecordLayout(d); for(clang::CXXRecordDecl::base_class_const_iterator i = d->bases_begin(); i != d->bases_end(); ++i) { bool is_virtual = (*i).isVirtual(); const clang::CXXRecordDecl *decl = (*i).getType().getTypePtr()->getAsCXXRecordDecl(); int64_t offset = 0; if(is_virtual) offset = layout.getVBaseClassOffset(decl).getQuantity(); else offset = layout.getBaseClassOffset(decl).getQuantity(); rd->add_parent(decl->getNameAsString(), (CXXRecordDecl::Access)(*i).getAccessSpecifier(), offset, is_virtual); } } return rd; } Decl* C2FFIASTConsumer::make_decl(const clang::NamespaceDecl *d, bool is_toplevel) { CXXNamespaceDecl *ns = new CXXNamespaceDecl(d->getNameAsString()); ns->set_id(add_cxx_decl(d)); ns->set_ns(add_cxx_decl(_ns)); return ns; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCInterfaceDecl *d, bool is_toplevel) { const clang::ObjCInterfaceDecl *super = d->getSuperClass(); _cur_decls.insert(d); ObjCInterfaceDecl *r = new ObjCInterfaceDecl(d->getDeclName().getAsString(), super ? super->getDeclName().getAsString() : "", !d->hasDefinition()); for(clang::ObjCInterfaceDecl::protocol_iterator i = d->protocol_begin(); i != d->protocol_end(); i++) r->add_protocol((*i)->getDeclName().getAsString()); for(clang::ObjCInterfaceDecl::ivar_iterator i = d->ivar_begin(); i != d->ivar_end(); i++) { r->add_field(this, *i); } r->add_functions(this, d); return r; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCCategoryDecl *d, bool is_toplevel) { ObjCCategoryDecl *r = new ObjCCategoryDecl(d->getClassInterface()->getDeclName().getAsString(), d->getDeclName().getAsString()); _cur_decls.insert(d); r->add_functions(this, d); return r; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCProtocolDecl *d, bool is_toplevel) { ObjCProtocolDecl *r = new ObjCProtocolDecl(d->getDeclName().getAsString()); _cur_decls.insert(d); r->add_functions(this, d); return r; } unsigned int C2FFIASTConsumer::decl_id(const clang::Decl *d) const { ClangDeclIDMap::const_iterator it = _decl_map.find(d); if(it != _decl_map.end()) return it->second; else return 0; } <commit_msg>Quick hack to possibly work around #77, and stub the beginning of wchar_t etc support<commit_after>/* c2ffi Copyright (C) 2013 Ryan Pavlik This file is part of c2ffi. c2ffi is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. c2ffi 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 c2ffi. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <map> #include <llvm/Support/raw_ostream.h> #include <llvm/Support/Host.h> #include <llvm/ADT/IntrusiveRefCntPtr.h> #include <clang/Basic/DiagnosticOptions.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Basic/TargetOptions.h> #include <clang/Basic/TargetInfo.h> #include <clang/Basic/FileManager.h> #include <clang/Basic/SourceManager.h> #include <clang/Lex/HeaderSearch.h> #include <clang/Lex/Preprocessor.h> #include <clang/Basic/Diagnostic.h> #include <clang/AST/ASTContext.h> #include <clang/AST/ASTConsumer.h> #include <clang/AST/DeclTemplate.h> #include <clang/AST/RecordLayout.h> #include <clang/Parse/Parser.h> #include <clang/Parse/ParseAST.h> #include "c2ffi.h" #include "c2ffi/ast.h" using namespace c2ffi; static std::string value_to_string(clang::APValue *v) { std::string s; llvm::raw_string_ostream ss(s); if(v->isInt() && v->getInt().isSigned()) v->getInt().print(ss, true); else if(v->isInt()) v->getInt().print(ss, false); else if(v->isFloat()) ss << v->getFloat().convertToDouble(); ss.flush(); return s; } void C2FFIASTConsumer::HandleTopLevelDeclInObjCContainer(clang::DeclGroupRef d) { _od->write_comment("HandleTopLevelDeclInObjCContainer"); } Decl* C2FFIASTConsumer::proc(const clang::Decl *d, Decl *decl) { if(!decl) return NULL; decl->set_ns(add_decl(_ns)); if(decl->location() == "") decl->set_location(_ci, d); if(_mid) _od->write_between(); else _mid = true; _od->write(*decl); return decl; } #define PROC decl = proc(d, make_decl(x)) void C2FFIASTConsumer::HandleDecl(clang::Decl *d, const clang::NamedDecl *ns) { Decl *decl = NULL; const clang::NamedDecl *old_ns = _ns; _ns = ns; if(d->isInvalidDecl()) { std::cerr << "Skipping invalid Decl:" << std::endl; d->dump(); return; } /* std::cerr << "DECL:" << std::endl; d->dump(); */ if_cast(x, clang::NamespaceDecl, d) { PROC; HandleNS(x); } else if_cast(x, clang::VarDecl, d) PROC; /* C/C++ */ else if_cast(x, clang::FieldDecl, d); else if_cast(x, clang::IndirectFieldDecl, d); else if_cast(x, clang::CXXMethodDecl, d); else if_cast(x, clang::FunctionTemplateDecl, d); else if_cast(x, clang::FunctionDecl, d) PROC; else if_cast(x, clang::CXXRecordDecl, d) { PROC; HandleDeclContext(x, x); } else if_cast(x, clang::RecordDecl, d) { PROC; HandleDeclContext(x, x); } else if_cast(x, clang::EnumDecl, d) PROC; else if_cast(x, clang::TypedefDecl, d) PROC; else if_cast(x, clang::ClassTemplateDecl, d); /* ObjC */ else if_cast(x, clang::ObjCInterfaceDecl, d) PROC; else if_cast(x, clang::ObjCCategoryDecl, d) PROC; else if_cast(x, clang::ObjCProtocolDecl, d) PROC; else if_cast(x, clang::ObjCImplementationDecl, d); else if_cast(x, clang::ObjCMethodDecl, d); /* Always should be last */ else if_cast(x, clang::NamedDecl, d) PROC; else decl = make_decl(d); if(decl) delete decl; _ns = old_ns; } void C2FFIASTConsumer::HandleNS(const clang::NamespaceDecl *ns) { HandleDeclContext(ns, ns); } void C2FFIASTConsumer::HandleDeclContext(const clang::DeclContext *dc, const clang::NamedDecl *ns) { clang::DeclContext::decl_iterator it; for(it = dc->decls_begin(); it != dc->decls_end(); ++it) HandleDecl(*it, ns); } bool C2FFIASTConsumer::HandleTopLevelDecl(clang::DeclGroupRef d) { clang::DeclGroupRef::iterator it; for(it = d.begin(); it != d.end(); ++it) HandleDecl(*it); return true; } void C2FFIASTConsumer::PostProcess() { if(!_config.template_output) return; std::ofstream &out = *_config.template_output; out << "#include \"" << _config.filename << "\"" << std::endl; for(ClangDeclSet::iterator i = _cxx_decls.begin(); i != _cxx_decls.end(); ++i) { const clang::Decl *d = (*i); if_const_cast(x, clang::ClassTemplateSpecializationDecl, d) { if(x->getSpecializationKind()) continue; if_const_cast(y, clang::ClassTemplatePartialSpecializationDecl, d) continue; write_template(x, out); } } } bool C2FFIASTConsumer::is_cur_decl(const clang::Decl *d) const { return _cur_decls.count(d); } Decl* C2FFIASTConsumer::make_decl(const clang::Decl *d, bool is_toplevel) { return new UnhandledDecl("", d->getDeclKindName()); } Decl* C2FFIASTConsumer::make_decl(const clang::NamedDecl *d, bool is_toplevel) { return new UnhandledDecl(d->getDeclName().getAsString(), d->getDeclKindName()); } Decl* C2FFIASTConsumer::make_decl(const clang::FunctionDecl *d, bool is_toplevel) { _cur_decls.insert(d); clang::FunctionTemplateSpecializationInfo *spec = d->getTemplateSpecializationInfo(); const clang::Type *return_type = d->getReturnType().getTypePtr(); FunctionDecl *fd = new FunctionDecl(this, d->getDeclName().getAsString(), Type::make_type(this, return_type), d->isVariadic(), d->isInlineSpecified(), d->getStorageClass(), (spec ? spec->TemplateArguments : NULL)); for(clang::FunctionDecl::param_const_iterator i = d->param_begin(); i != d->param_end(); i++) { fd->add_field(this, *i); } return fd; } Decl* C2FFIASTConsumer::make_decl(const clang::VarDecl *d, bool is_toplevel) { clang::ASTContext &ctx = _ci.getASTContext(); clang::APValue *v = NULL; std::string name = d->getDeclName().getAsString(); std::string value = ""; std::string loc = ""; bool is_string = false; if(name.substr(0, 8) == "__c2ffi_") { name = name.substr(8, std::string::npos); clang::Preprocessor &pp = _ci.getPreprocessor(); clang::IdentifierInfo &ii = pp.getIdentifierTable().get(llvm::StringRef(name)); const clang::MacroInfo *mi = pp.getMacroInfo(&ii); if(mi) loc = mi->getDefinitionLoc().printToString(_ci.getSourceManager()); } if(d->hasInit()) { if(!d->getType()->isDependentType()) { clang::EvaluatedStmt *stmt = d->ensureEvaluatedStmt(); clang::Expr *e = clang::cast<clang::Expr>(stmt->Value); if(!e->isValueDependent() && ((v = d->evaluateValue()) || (v = d->getEvaluatedValue()))) { if(v->isLValue()) { clang::APValue::LValueBase base = v->getLValueBase(); if(!base.isNull() && base.is<const clang::Expr*>()) { const clang::Expr *e = base.get<const clang::Expr*>(); if_const_cast(s, clang::StringLiteral, e) { is_string = true; if(s->isAscii() || s->isUTF8()) { value = s->getString(); } else { } } } } else { value = value_to_string(v); } } } } Type *t = Type::make_type(this, d->getTypeSourceInfo()->getType().getTypePtr()); VarDecl *cv = new VarDecl(name, t, value, d->hasExternalStorage(), is_string); if(loc != "") cv->set_location(loc); return cv; } Decl* C2FFIASTConsumer::make_decl(const clang::RecordDecl *d, bool is_toplevel) { std::string name = d->getDeclName().getAsString(); if(is_toplevel && name == "") return NULL; _cur_decls.insert(d); RecordDecl *rd = new RecordDecl(name, d->isUnion()); rd->fill_record_decl(this, d); return rd; } bool is_underlying_valid(const clang::Type *t) { if_const_cast(e, clang::ElaboratedType, t) { return is_underlying_valid(e->getNamedType().getTypePtr()); } if_const_cast(rt, clang::RecordType, t) { if(rt->getDecl()->isInvalidDecl()) return false; } return true; } Decl* C2FFIASTConsumer::make_decl(const clang::TypedefDecl *d, bool is_toplevel) { const clang::Type *t = d->getUnderlyingType().getTypePtr(); if(is_underlying_valid(t)) { return new TypedefDecl(d->getDeclName().getAsString(), Type::make_type(this, t)); } else { std::cerr << "Skipping typedef to invalid type:" << std::endl; d->dump(); return NULL; } } Decl* C2FFIASTConsumer::make_decl(const clang::EnumDecl *d, bool is_toplevel) { std::string name = d->getDeclName().getAsString(); _cur_decls.insert(d); EnumDecl *decl = new EnumDecl(name); if(name == "") { decl->set_id(add_decl(d)); } for(clang::EnumDecl::enumerator_iterator i = d->enumerator_begin(); i != d->enumerator_end(); ++i) { const clang::EnumConstantDecl *ecd = (*i); decl->add_field(ecd->getDeclName().getAsString(), ecd->getInitVal().getLimitedValue()); } return decl; } Decl* C2FFIASTConsumer::make_decl(const clang::CXXRecordDecl *d, bool is_toplevel) { if(!d->hasDefinition() || d->getDefinition()->isInvalidDecl()) return NULL; std::string name = d->getDeclName().getAsString(); const clang::TemplateArgumentList *template_args = NULL; if(is_toplevel && name == "") return NULL; if_const_cast(cts, clang::ClassTemplateSpecializationDecl, d) { template_args = &(cts->getTemplateArgs()); } bool dependent = d->isDependentType(); _cur_decls.insert(d); CXXRecordDecl *rd = new CXXRecordDecl(this, name, d->isUnion(), d->isClass(), template_args); rd->set_id(add_cxx_decl(d)); rd->add_functions(this, d); if(!dependent) { rd->fill_record_decl(this, d); const clang::ASTRecordLayout &layout = _ci.getASTContext().getASTRecordLayout(d); for(clang::CXXRecordDecl::base_class_const_iterator i = d->bases_begin(); i != d->bases_end(); ++i) { bool is_virtual = (*i).isVirtual(); const clang::CXXRecordDecl *decl = (*i).getType().getTypePtr()->getAsCXXRecordDecl(); int64_t offset = 0; if(is_virtual) offset = layout.getVBaseClassOffset(decl).getQuantity(); else offset = layout.getBaseClassOffset(decl).getQuantity(); rd->add_parent(decl->getNameAsString(), (CXXRecordDecl::Access)(*i).getAccessSpecifier(), offset, is_virtual); } } return rd; } Decl* C2FFIASTConsumer::make_decl(const clang::NamespaceDecl *d, bool is_toplevel) { CXXNamespaceDecl *ns = new CXXNamespaceDecl(d->getNameAsString()); ns->set_id(add_cxx_decl(d)); ns->set_ns(add_cxx_decl(_ns)); return ns; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCInterfaceDecl *d, bool is_toplevel) { const clang::ObjCInterfaceDecl *super = d->getSuperClass(); _cur_decls.insert(d); ObjCInterfaceDecl *r = new ObjCInterfaceDecl(d->getDeclName().getAsString(), super ? super->getDeclName().getAsString() : "", !d->hasDefinition()); for(clang::ObjCInterfaceDecl::protocol_iterator i = d->protocol_begin(); i != d->protocol_end(); i++) r->add_protocol((*i)->getDeclName().getAsString()); for(clang::ObjCInterfaceDecl::ivar_iterator i = d->ivar_begin(); i != d->ivar_end(); i++) { r->add_field(this, *i); } r->add_functions(this, d); return r; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCCategoryDecl *d, bool is_toplevel) { ObjCCategoryDecl *r = new ObjCCategoryDecl(d->getClassInterface()->getDeclName().getAsString(), d->getDeclName().getAsString()); _cur_decls.insert(d); r->add_functions(this, d); return r; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCProtocolDecl *d, bool is_toplevel) { ObjCProtocolDecl *r = new ObjCProtocolDecl(d->getDeclName().getAsString()); _cur_decls.insert(d); r->add_functions(this, d); return r; } unsigned int C2FFIASTConsumer::decl_id(const clang::Decl *d) const { ClangDeclIDMap::const_iterator it = _decl_map.find(d); if(it != _decl_map.end()) return it->second; else return 0; } <|endoftext|>
<commit_before>/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2016, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #include "nav-precomp.h" // Precomp header #include <mrpt/nav/reactive/CWaypointsNavigator.h> #include <mrpt/poses/CPose2D.h> using namespace mrpt::nav; using namespace std; CWaypointsNavigator::CWaypointsNavigator(CRobot2NavInterface &robot_if) : CAbstractNavigator(robot_if), MAX_DISTANCE_TO_ALLOW_SKIP_WAYPOINT(-1.0), MIN_TIMESTEPS_CONFIRM_SKIP_WAYPOINTS(1) { } CWaypointsNavigator::~CWaypointsNavigator() { } void CWaypointsNavigator::navigateWaypoints( const TWaypointSequence & nav_request ) { MRPT_START mrpt::synch::CCriticalSectionLocker csl(&m_nav_waypoints_cs); m_waypoint_nav_status = TWaypointStatusSequence(); m_waypoint_nav_status.timestamp_nav_started = mrpt::system::now(); const size_t N = nav_request.waypoints.size(); ASSERTMSG_(N>0,"List of waypoints is empty!"); m_waypoint_nav_status.waypoints.resize(N); // Copy waypoints fields data, leave status fields to defaults: for (size_t i=0;i<N;i++) { ASSERT_( nav_request.waypoints[i].isValid() ); m_waypoint_nav_status.waypoints[i] = nav_request.waypoints[i]; } m_waypoint_nav_status.waypoint_index_current_goal = -1; // Not started yet. // The main loop navigationStep() will iterate over waypoints and send them to navigate() MRPT_END } void CWaypointsNavigator::getWaypointNavStatus(TWaypointStatusSequence & out_nav_status) const { // No need to lock mutex... out_nav_status = m_waypoint_nav_status; } void CWaypointsNavigator::cancel() { { mrpt::synch::CCriticalSectionLocker csl(&m_nav_waypoints_cs); m_waypoint_nav_status = TWaypointStatusSequence(); } CAbstractNavigator::cancel(); } void CWaypointsNavigator::navigationStep() { MRPT_START using mrpt::utils::square; // Call base navigation step to execute one-single waypoint navigation, as usual: CAbstractNavigator::navigationStep(); // This internally locks "m_nav_cs" // -------------------------------------- // Waypoint navigation algorithm // -------------------------------------- { mrpt::synch::CCriticalSectionLocker csl(&m_nav_waypoints_cs); TWaypointStatusSequence &wps = m_waypoint_nav_status; // shortcut to save typing if ( wps.waypoints.empty() || wps.final_goal_reached ) return; // No nav request is pending or it was canceled // 0) Get current robot pose: CAbstractNavigator::updateCurrentPoseAndSpeeds(); // 1) default policy: go thru WPs one by one const int prev_wp_index = wps.waypoint_index_current_goal; mrpt::math::TSegment2D robot_move_seg; robot_move_seg.point1.x = m_curPoseVel.pose.x; robot_move_seg.point1.y = m_curPoseVel.pose.y; if (wps.last_robot_pose.x==TWaypoint::INVALID_NUM) { robot_move_seg.point2 = robot_move_seg.point1; } else { robot_move_seg.point2.x = wps.last_robot_pose.x; robot_move_seg.point2.y = wps.last_robot_pose.y; } wps.last_robot_pose = m_curPoseVel.pose; // save for next iters if (wps.waypoint_index_current_goal>=0 && robot_move_seg.distance( wps.waypoints[wps.waypoint_index_current_goal].target ) < wps.waypoints[wps.waypoint_index_current_goal].allowed_distance ) { wps.waypoints[wps.waypoint_index_current_goal].reached = true; m_robot.sendWaypointReachedEvent(wps.waypoint_index_current_goal); // Was this the final goal?? if ( wps.waypoint_index_current_goal < int(wps.waypoints.size()-1) ) { wps.waypoint_index_current_goal++; } else { wps.final_goal_reached = true; } } // 2) More advanced policy: if available, use children class methods to decide // which is the best candidate for the next waypoint, if we can skip current one: if (!wps.final_goal_reached && wps.waypoint_index_current_goal >= 0) { const mrpt::poses::CPose2D robot_pose(m_curPoseVel.pose); int most_advanced_wp = wps.waypoint_index_current_goal; const int most_advanced_wp_at_begin = most_advanced_wp; for (int idx=wps.waypoint_index_current_goal;idx<(int)wps.waypoints.size();idx++) { if (idx<0) continue; // Is it reachable? mrpt::math::TPoint2D wp_local_wrt_robot; robot_pose.inverseComposePoint(wps.waypoints[idx].target, wp_local_wrt_robot); if (MAX_DISTANCE_TO_ALLOW_SKIP_WAYPOINT>0 && wp_local_wrt_robot.norm()>MAX_DISTANCE_TO_ALLOW_SKIP_WAYPOINT) continue; // Skip this one, it is too far away const bool is_reachable = this->impl_waypoint_is_reachable(wp_local_wrt_robot); if (is_reachable) { // Robustness filter: only skip to a future waypoint if it is seen as "reachable" during // a given number of timesteps: if (++wps.waypoints[idx].counter_seen_reachable > MIN_TIMESTEPS_CONFIRM_SKIP_WAYPOINTS) { most_advanced_wp = idx; } } // Is allowed to skip it? if (!wps.waypoints[idx].allow_skip) break; // Do not keep trying, since we are now allowed to skip this one. } if (most_advanced_wp>=0) { wps.waypoint_index_current_goal = most_advanced_wp; for (int k=most_advanced_wp_at_begin;k<most_advanced_wp;k++) { wps.waypoints[k].reached = true; m_robot.sendWaypointReachedEvent(k); } } } // Still not started and no better guess? Start with the first waypoint: if (wps.waypoint_index_current_goal<0) wps.waypoint_index_current_goal = 0; // 3) Should I request a new (single target) navigation command? // Only if the temporary goal changed: if (wps.waypoint_index_current_goal>=0 && prev_wp_index!=wps.waypoint_index_current_goal) { ASSERT_( wps.waypoint_index_current_goal < int(wps.waypoints.size()) ); TWaypointStatus &wp = wps.waypoints[wps.waypoint_index_current_goal]; const bool is_final_wp = ( (wps.waypoint_index_current_goal+1)==int(wps.waypoints.size()) ); m_robot.sendNewWaypointTargetEvent(wps.waypoint_index_current_goal); CAbstractNavigator::TNavigationParams nav_cmd; nav_cmd.target.x = wp.target.x; nav_cmd.target.y = wp.target.y; nav_cmd.target.phi = (wp.target_heading!=TWaypoint::INVALID_NUM ? wp.target_heading : .0); nav_cmd.targetAllowedDistance = wp.allowed_distance; nav_cmd.targetIsRelative = false; nav_cmd.targetIsIntermediaryWaypoint = !is_final_wp; this->navigate( &nav_cmd ); } } MRPT_END } void CWaypointsNavigator::loadWaypointsParamsConfigFile(const mrpt::utils::CConfigFileBase &cfg, const std::string &sectionName) { MRPT_LOAD_CONFIG_VAR(MAX_DISTANCE_TO_ALLOW_SKIP_WAYPOINT, double, cfg, sectionName); MRPT_LOAD_CONFIG_VAR(MIN_TIMESTEPS_CONFIRM_SKIP_WAYPOINTS, int, cfg, sectionName); } void CWaypointsNavigator::onStartNewNavigation() { } bool CWaypointsNavigator::isRelativePointReachable(const mrpt::math::TPoint2D &wp_local_wrt_robot) const { return impl_waypoint_is_reachable(wp_local_wrt_robot); } <commit_msg>fix order of end-of-nav and waypoint-reached events<commit_after>/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2016, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #include "nav-precomp.h" // Precomp header #include <mrpt/nav/reactive/CWaypointsNavigator.h> #include <mrpt/poses/CPose2D.h> using namespace mrpt::nav; using namespace std; CWaypointsNavigator::CWaypointsNavigator(CRobot2NavInterface &robot_if) : CAbstractNavigator(robot_if), MAX_DISTANCE_TO_ALLOW_SKIP_WAYPOINT(-1.0), MIN_TIMESTEPS_CONFIRM_SKIP_WAYPOINTS(1) { } CWaypointsNavigator::~CWaypointsNavigator() { } void CWaypointsNavigator::navigateWaypoints( const TWaypointSequence & nav_request ) { MRPT_START mrpt::synch::CCriticalSectionLocker csl(&m_nav_waypoints_cs); m_waypoint_nav_status = TWaypointStatusSequence(); m_waypoint_nav_status.timestamp_nav_started = mrpt::system::now(); const size_t N = nav_request.waypoints.size(); ASSERTMSG_(N>0,"List of waypoints is empty!"); m_waypoint_nav_status.waypoints.resize(N); // Copy waypoints fields data, leave status fields to defaults: for (size_t i=0;i<N;i++) { ASSERT_( nav_request.waypoints[i].isValid() ); m_waypoint_nav_status.waypoints[i] = nav_request.waypoints[i]; } m_waypoint_nav_status.waypoint_index_current_goal = -1; // Not started yet. // The main loop navigationStep() will iterate over waypoints and send them to navigate() MRPT_END } void CWaypointsNavigator::getWaypointNavStatus(TWaypointStatusSequence & out_nav_status) const { // No need to lock mutex... out_nav_status = m_waypoint_nav_status; } void CWaypointsNavigator::cancel() { { mrpt::synch::CCriticalSectionLocker csl(&m_nav_waypoints_cs); m_waypoint_nav_status = TWaypointStatusSequence(); } CAbstractNavigator::cancel(); } void CWaypointsNavigator::navigationStep() { MRPT_START using mrpt::utils::square; // -------------------------------------- // Waypoint navigation algorithm // -------------------------------------- { mrpt::synch::CCriticalSectionLocker csl(&m_nav_waypoints_cs); TWaypointStatusSequence &wps = m_waypoint_nav_status; // shortcut to save typing if ( wps.waypoints.empty() || wps.final_goal_reached ) return; // No nav request is pending or it was canceled // 0) Get current robot pose: CAbstractNavigator::updateCurrentPoseAndSpeeds(); // 1) default policy: go thru WPs one by one const int prev_wp_index = wps.waypoint_index_current_goal; mrpt::math::TSegment2D robot_move_seg; robot_move_seg.point1.x = m_curPoseVel.pose.x; robot_move_seg.point1.y = m_curPoseVel.pose.y; if (wps.last_robot_pose.x==TWaypoint::INVALID_NUM) { robot_move_seg.point2 = robot_move_seg.point1; } else { robot_move_seg.point2.x = wps.last_robot_pose.x; robot_move_seg.point2.y = wps.last_robot_pose.y; } wps.last_robot_pose = m_curPoseVel.pose; // save for next iters if (wps.waypoint_index_current_goal>=0 && robot_move_seg.distance( wps.waypoints[wps.waypoint_index_current_goal].target ) < wps.waypoints[wps.waypoint_index_current_goal].allowed_distance ) { wps.waypoints[wps.waypoint_index_current_goal].reached = true; m_robot.sendWaypointReachedEvent(wps.waypoint_index_current_goal); // Was this the final goal?? if ( wps.waypoint_index_current_goal < int(wps.waypoints.size()-1) ) { wps.waypoint_index_current_goal++; } else { wps.final_goal_reached = true; } } // 2) More advanced policy: if available, use children class methods to decide // which is the best candidate for the next waypoint, if we can skip current one: if (!wps.final_goal_reached && wps.waypoint_index_current_goal >= 0) { const mrpt::poses::CPose2D robot_pose(m_curPoseVel.pose); int most_advanced_wp = wps.waypoint_index_current_goal; const int most_advanced_wp_at_begin = most_advanced_wp; for (int idx=wps.waypoint_index_current_goal;idx<(int)wps.waypoints.size();idx++) { if (idx<0) continue; // Is it reachable? mrpt::math::TPoint2D wp_local_wrt_robot; robot_pose.inverseComposePoint(wps.waypoints[idx].target, wp_local_wrt_robot); if (MAX_DISTANCE_TO_ALLOW_SKIP_WAYPOINT>0 && wp_local_wrt_robot.norm()>MAX_DISTANCE_TO_ALLOW_SKIP_WAYPOINT) continue; // Skip this one, it is too far away const bool is_reachable = this->impl_waypoint_is_reachable(wp_local_wrt_robot); if (is_reachable) { // Robustness filter: only skip to a future waypoint if it is seen as "reachable" during // a given number of timesteps: if (++wps.waypoints[idx].counter_seen_reachable > MIN_TIMESTEPS_CONFIRM_SKIP_WAYPOINTS) { most_advanced_wp = idx; } } // Is allowed to skip it? if (!wps.waypoints[idx].allow_skip) break; // Do not keep trying, since we are now allowed to skip this one. } if (most_advanced_wp>=0) { wps.waypoint_index_current_goal = most_advanced_wp; for (int k=most_advanced_wp_at_begin;k<most_advanced_wp;k++) { wps.waypoints[k].reached = true; m_robot.sendWaypointReachedEvent(k); } } } // Still not started and no better guess? Start with the first waypoint: if (wps.waypoint_index_current_goal<0) wps.waypoint_index_current_goal = 0; // 3) Should I request a new (single target) navigation command? // Only if the temporary goal changed: if (wps.waypoint_index_current_goal>=0 && prev_wp_index!=wps.waypoint_index_current_goal) { ASSERT_( wps.waypoint_index_current_goal < int(wps.waypoints.size()) ); TWaypointStatus &wp = wps.waypoints[wps.waypoint_index_current_goal]; const bool is_final_wp = ( (wps.waypoint_index_current_goal+1)==int(wps.waypoints.size()) ); m_robot.sendNewWaypointTargetEvent(wps.waypoint_index_current_goal); CAbstractNavigator::TNavigationParams nav_cmd; nav_cmd.target.x = wp.target.x; nav_cmd.target.y = wp.target.y; nav_cmd.target.phi = (wp.target_heading!=TWaypoint::INVALID_NUM ? wp.target_heading : .0); nav_cmd.targetAllowedDistance = wp.allowed_distance; nav_cmd.targetIsRelative = false; nav_cmd.targetIsIntermediaryWaypoint = !is_final_wp; this->navigate( &nav_cmd ); } } // Note: navigationStep() called *after* waypoints part to get end-of-navigation events *after* // waypoints-related events: // Call base navigation step to execute one-single waypoint navigation, as usual: CAbstractNavigator::navigationStep(); // This internally locks "m_nav_cs" MRPT_END } void CWaypointsNavigator::loadWaypointsParamsConfigFile(const mrpt::utils::CConfigFileBase &cfg, const std::string &sectionName) { MRPT_LOAD_CONFIG_VAR(MAX_DISTANCE_TO_ALLOW_SKIP_WAYPOINT, double, cfg, sectionName); MRPT_LOAD_CONFIG_VAR(MIN_TIMESTEPS_CONFIRM_SKIP_WAYPOINTS, int, cfg, sectionName); } void CWaypointsNavigator::onStartNewNavigation() { } bool CWaypointsNavigator::isRelativePointReachable(const mrpt::math::TPoint2D &wp_local_wrt_robot) const { return impl_waypoint_is_reachable(wp_local_wrt_robot); } <|endoftext|>
<commit_before>/* Copyright (c) 2015 Michael C. Miller. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #if defined(ESP8266) #include <Arduino.h> #include <Servo.h> #define INVALID_SERVO 255 // flag indicating an invalid servo index const uint32_t c_CycleCompensation = 4; // compensation us to trim adjust for digitalWrite delays struct ServoInfo { uint8_t pin : 6; // a pin number from 0 to 63 uint8_t isActive : 1; // true if this channel is enabled, pin not pulsed if false }; struct ServoState { ServoInfo info; volatile uint16_t usPulse; }; #if !defined (SERVO_EXCLUDE_TIMER0) ServoTimer0 s_servoTimer0; #endif #if !defined (SERVO_EXCLUDE_TIMER1) ServoTimer1 s_servoTimer1; #endif static ServoState s_servos[MAX_SERVOS]; // static array of servo structures static uint8_t s_servoCount = 0; // the total number of attached s_servos // inconvenience macros #define SERVO_INDEX_TO_TIMER(servoIndex) ((ServoTimerSequence)(servoIndex / SERVOS_PER_TIMER)) // returns the timer controlling this servo #define SERVO_INDEX(timerId, channel) ((timerId * SERVOS_PER_TIMER) + channel) // macro to access servo index by timer and channel //------------------------------------------------------------------------------ // Interrupt handler template method that takes a class that implements // a standard set of methods for the timer abstraction //------------------------------------------------------------------------------ template <class T> void Servo_Handler(T* timer) { uint8_t servoIndex; // clear interrupt timer->ResetInterrupt(); if (timer->isEndOfCycle()) { timer->StartCycle(); } else { servoIndex = SERVO_INDEX(timer->timerId(), timer->getCurrentChannel()); if (servoIndex < s_servoCount && s_servos[servoIndex].info.isActive) { // pulse this channel low if activated digitalWrite(s_servos[servoIndex].info.pin, LOW); } timer->nextChannel(); } servoIndex = SERVO_INDEX(timer->timerId(), timer->getCurrentChannel()); if (servoIndex < s_servoCount && timer->getCurrentChannel() < SERVOS_PER_TIMER) { timer->SetPulseCompare(timer->usToTicks(s_servos[servoIndex].usPulse) - c_CycleCompensation); if (s_servos[servoIndex].info.isActive) { // check if activated digitalWrite(s_servos[servoIndex].info.pin, HIGH); // its an active channel so pulse it high } } else { // finished all channels so wait for the refresh period to expire before starting over // allow a few ticks to ensure the next match is not missed uint32_t refreshCompare = timer->usToTicks(REFRESH_INTERVAL); if ((timer->GetCycleCount() + c_CycleCompensation * 2) < refreshCompare) { timer->SetCycleCompare(refreshCompare - c_CycleCompensation); } else { // at least REFRESH_INTERVAL has elapsed timer->SetCycleCompare(timer->GetCycleCount() + c_CycleCompensation * 2); } timer->setEndOfCycle(); } } static void initISR(ServoTimerSequence timerId) { #if !defined (SERVO_EXCLUDE_TIMER0) if (timerId == ServoTimerSequence_Timer0) s_servoTimer0.InitInterrupt([]() {Servo_Handler<ServoTimer0>(&s_servoTimer0); }); #endif #if !defined (SERVO_EXCLUDE_TIMER1) if (timerId == ServoTimerSequence_Timer1) s_servoTimer1.InitInterrupt([]() {Servo_Handler<ServoTimer1>(&s_servoTimer1); }); #endif } static void finISR(ServoTimerSequence timerId) { #if !defined (SERVO_EXCLUDE_TIMER0) if (timerId == ServoTimerSequence_Timer0) s_servoTimer0.StopInterrupt(); #endif #if !defined (SERVO_EXCLUDE_TIMER1) if (timerId == ServoTimerSequence_Timer1) s_servoTimer1.StopInterrupt(); #endif } // returns true if any servo is active on this timer static boolean isTimerActive(ServoTimerSequence timerId) { for (uint8_t channel = 0; channel < SERVOS_PER_TIMER; channel++) { if (s_servos[SERVO_INDEX(timerId, channel)].info.isActive) { return true; } } return false; } //------------------------------------------------------------------- // Servo class methods Servo::Servo() { if (s_servoCount < MAX_SERVOS) { // assign a servo index to this instance _servoIndex = s_servoCount++; // store default values s_servos[_servoIndex].usPulse = DEFAULT_PULSE_WIDTH; } else { _servoIndex = INVALID_SERVO; // too many servos } } uint8_t Servo::attach(int pin) { return attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH); } uint8_t Servo::attach(int pin, int minUs, int maxUs) { ServoTimerSequence timerId; if (_servoIndex < MAX_SERVOS) { pinMode(pin, OUTPUT); // set servo pin to output digitalWrite(pin, LOW); s_servos[_servoIndex].info.pin = pin; // keep the min and max within 200-3000 us, these are extreme // ranges and should support extreme servos while maintaining // reasonable ranges _maxUs = max(250, min(3000, maxUs)); _minUs = max(200, min(_maxUs, minUs)); // initialize the timerId if it has not already been initialized timerId = SERVO_INDEX_TO_TIMER(_servoIndex); if (!isTimerActive(timerId)) { initISR(timerId); } s_servos[_servoIndex].info.isActive = true; // this must be set after the check for isTimerActive } return _servoIndex; } void Servo::detach() { ServoTimerSequence timerId; s_servos[_servoIndex].info.isActive = false; timerId = SERVO_INDEX_TO_TIMER(_servoIndex); if (!isTimerActive(timerId)) { finISR(timerId); } } void Servo::write(int value) { // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds) if (value < MIN_PULSE_WIDTH) { // assumed to be 0-180 degrees servo value = max(0, min(180, value)); value = map(value, 0, 180, _minUs, _maxUs); } writeMicroseconds(value); } void Servo::writeMicroseconds(int value) { // ensure channel is valid if ((_servoIndex < MAX_SERVOS)) { // ensure pulse width is valid value = max(_minUs, min(_maxUs, value)); s_servos[_servoIndex].usPulse = value; } } int Servo::read() // return the value as degrees { return map(readMicroseconds(), _minUs, _maxUs, 0, 180); } int Servo::readMicroseconds() { unsigned int pulsewidth; if (_servoIndex != INVALID_SERVO) { pulsewidth = s_servos[_servoIndex].usPulse; } else { pulsewidth = 0; } return pulsewidth; } bool Servo::attached() { return s_servos[_servoIndex].info.isActive; } #endif <commit_msg>Fix to Servo allowing write() to be called before attach()<commit_after>/* Copyright (c) 2015 Michael C. Miller. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #if defined(ESP8266) #include <Arduino.h> #include <Servo.h> #define INVALID_SERVO 255 // flag indicating an invalid servo index const uint32_t c_CycleCompensation = 4; // compensation us to trim adjust for digitalWrite delays struct ServoInfo { uint8_t pin : 6; // a pin number from 0 to 63 uint8_t isActive : 1; // true if this channel is enabled, pin not pulsed if false }; struct ServoState { ServoInfo info; volatile uint16_t usPulse; }; #if !defined (SERVO_EXCLUDE_TIMER0) ServoTimer0 s_servoTimer0; #endif #if !defined (SERVO_EXCLUDE_TIMER1) ServoTimer1 s_servoTimer1; #endif static ServoState s_servos[MAX_SERVOS]; // static array of servo structures static uint8_t s_servoCount = 0; // the total number of attached s_servos // inconvenience macros #define SERVO_INDEX_TO_TIMER(servoIndex) ((ServoTimerSequence)(servoIndex / SERVOS_PER_TIMER)) // returns the timer controlling this servo #define SERVO_INDEX(timerId, channel) ((timerId * SERVOS_PER_TIMER) + channel) // macro to access servo index by timer and channel //------------------------------------------------------------------------------ // Interrupt handler template method that takes a class that implements // a standard set of methods for the timer abstraction //------------------------------------------------------------------------------ template <class T> void Servo_Handler(T* timer) { uint8_t servoIndex; // clear interrupt timer->ResetInterrupt(); if (timer->isEndOfCycle()) { timer->StartCycle(); } else { servoIndex = SERVO_INDEX(timer->timerId(), timer->getCurrentChannel()); if (servoIndex < s_servoCount && s_servos[servoIndex].info.isActive) { // pulse this channel low if activated digitalWrite(s_servos[servoIndex].info.pin, LOW); } timer->nextChannel(); } servoIndex = SERVO_INDEX(timer->timerId(), timer->getCurrentChannel()); if (servoIndex < s_servoCount && timer->getCurrentChannel() < SERVOS_PER_TIMER) { timer->SetPulseCompare(timer->usToTicks(s_servos[servoIndex].usPulse) - c_CycleCompensation); if (s_servos[servoIndex].info.isActive) { // check if activated digitalWrite(s_servos[servoIndex].info.pin, HIGH); // its an active channel so pulse it high } } else { // finished all channels so wait for the refresh period to expire before starting over // allow a few ticks to ensure the next match is not missed uint32_t refreshCompare = timer->usToTicks(REFRESH_INTERVAL); if ((timer->GetCycleCount() + c_CycleCompensation * 2) < refreshCompare) { timer->SetCycleCompare(refreshCompare - c_CycleCompensation); } else { // at least REFRESH_INTERVAL has elapsed timer->SetCycleCompare(timer->GetCycleCount() + c_CycleCompensation * 2); } timer->setEndOfCycle(); } } static void initISR(ServoTimerSequence timerId) { #if !defined (SERVO_EXCLUDE_TIMER0) if (timerId == ServoTimerSequence_Timer0) s_servoTimer0.InitInterrupt([]() {Servo_Handler<ServoTimer0>(&s_servoTimer0); }); #endif #if !defined (SERVO_EXCLUDE_TIMER1) if (timerId == ServoTimerSequence_Timer1) s_servoTimer1.InitInterrupt([]() {Servo_Handler<ServoTimer1>(&s_servoTimer1); }); #endif } static void finISR(ServoTimerSequence timerId) { #if !defined (SERVO_EXCLUDE_TIMER0) if (timerId == ServoTimerSequence_Timer0) s_servoTimer0.StopInterrupt(); #endif #if !defined (SERVO_EXCLUDE_TIMER1) if (timerId == ServoTimerSequence_Timer1) s_servoTimer1.StopInterrupt(); #endif } // returns true if any servo is active on this timer static boolean isTimerActive(ServoTimerSequence timerId) { for (uint8_t channel = 0; channel < SERVOS_PER_TIMER; channel++) { if (s_servos[SERVO_INDEX(timerId, channel)].info.isActive) { return true; } } return false; } //------------------------------------------------------------------- // Servo class methods Servo::Servo() { if (s_servoCount < MAX_SERVOS) { // assign a servo index to this instance _servoIndex = s_servoCount++; // store default values s_servos[_servoIndex].usPulse = DEFAULT_PULSE_WIDTH; // set default _minUs and _maxUs incase write() is called before attach() _minUs = MIN_PULSE_WIDTH; _maxUs = MAX_PULSE_WIDTH; } else { _servoIndex = INVALID_SERVO; // too many servos } } uint8_t Servo::attach(int pin) { return attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH); } uint8_t Servo::attach(int pin, int minUs, int maxUs) { ServoTimerSequence timerId; if (_servoIndex < MAX_SERVOS) { pinMode(pin, OUTPUT); // set servo pin to output digitalWrite(pin, LOW); s_servos[_servoIndex].info.pin = pin; // keep the min and max within 200-3000 us, these are extreme // ranges and should support extreme servos while maintaining // reasonable ranges _maxUs = max(250, min(3000, maxUs)); _minUs = max(200, min(_maxUs, minUs)); // initialize the timerId if it has not already been initialized timerId = SERVO_INDEX_TO_TIMER(_servoIndex); if (!isTimerActive(timerId)) { initISR(timerId); } s_servos[_servoIndex].info.isActive = true; // this must be set after the check for isTimerActive } return _servoIndex; } void Servo::detach() { ServoTimerSequence timerId; s_servos[_servoIndex].info.isActive = false; timerId = SERVO_INDEX_TO_TIMER(_servoIndex); if (!isTimerActive(timerId)) { finISR(timerId); } } void Servo::write(int value) { // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds) if (value < MIN_PULSE_WIDTH) { // assumed to be 0-180 degrees servo value = max(0, min(180, value)); value = map(value, 0, 180, _minUs, _maxUs); } writeMicroseconds(value); } void Servo::writeMicroseconds(int value) { // ensure channel is valid if ((_servoIndex < MAX_SERVOS)) { // ensure pulse width is valid value = max(_minUs, min(_maxUs, value)); s_servos[_servoIndex].usPulse = value; } } int Servo::read() // return the value as degrees { return map(readMicroseconds(), _minUs, _maxUs, 0, 180); } int Servo::readMicroseconds() { unsigned int pulsewidth; if (_servoIndex != INVALID_SERVO) { pulsewidth = s_servos[_servoIndex].usPulse; } else { pulsewidth = 0; } return pulsewidth; } bool Servo::attached() { return s_servos[_servoIndex].info.isActive; } #endif <|endoftext|>
<commit_before>/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * See cxx source for full Copyright notice */ /* $Id$ */ /// By Laurent Aphecetche { cout << "Loading MUON libraries ..." << endl; gROOT->LoadMacro("${ALICE_ROOT}/MUON/loadlibs.C"); gInterpreter->ProcessLine("loadlibs()"); cout << "Setting include path ..." << endl; gSystem->SetIncludePath("-I${ALICE_ROOT}/include -I${ALICE_ROOT}/RAW -I${ALICE_ROOT}/MUON -I${ALICE_ROOT}/MUON/mapping"); } <commit_msg>Extended include path to cover all directories needed by all macros.<commit_after>/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * See cxx source for full Copyright notice */ /* $Id$ */ /// By Laurent Aphecetche { cout << "Loading MUON libraries ..." << endl; gROOT->LoadMacro("${ALICE_ROOT}/MUON/loadlibs.C"); gInterpreter->ProcessLine("loadlibs()"); cout << "Setting include path ..." << endl; TString includePath = "-I${ALICE_ROOT}/include "; includePath += "-I${ALICE_ROOT}/RAW "; includePath += "-I${ALICE_ROOT}/FASTSIM "; includePath += "-I${ALICE_ROOT}/EVGEN "; includePath += "-I${ALICE_ROOT}/SHUTTLE/TestShuttle "; includePath += "-I${ALICE_ROOT}/ITS "; includePath += "-I${ALICE_ROOT}/MUON "; includePath += "-I${ALICE_ROOT}/MUON/mapping"; gSystem->SetIncludePath(includePath.Data()); } <|endoftext|>
<commit_before>//===- DCE.cpp - Code to perform dead code elimination --------------------===// // // This file implements dead code elimination and basic block merging. // // Specifically, this: // * removes definitions with no uses (including unused constants) // * removes basic blocks with no predecessors // * merges a basic block into its predecessor if there is only one and the // predecessor only has one successor. // * Eliminates PHI nodes for basic blocks with a single predecessor // * Eliminates a basic block that only contains an unconditional branch // // TODO: This should REALLY be worklist driven instead of iterative. Right now, // we scan linearly through values, removing unused ones as we go. The problem // is that this may cause other earlier values to become unused. To make sure // that we get them all, we iterate until things stop changing. Instead, when // removing a value, recheck all of its operands to see if they are now unused. // Piece of cake, and more efficient as well. // // Note, this is not trivial, because we have to worry about invalidating // iterators. :( // //===----------------------------------------------------------------------===// #include "llvm/Optimizations/DCE.h" #include "llvm/Tools/STLExtras.h" #include "llvm/Module.h" #include "llvm/Method.h" #include "llvm/BasicBlock.h" #include "llvm/iTerminators.h" #include "llvm/iOther.h" #include "llvm/Assembly/Writer.h" #include "llvm/CFG.h" #include <algorithm> using namespace cfg; struct ConstPoolDCE { enum { EndOffs = 0 }; static bool isDCEable(const Value *) { return true; } }; struct BasicBlockDCE { enum { EndOffs = 1 }; static bool isDCEable(const Instruction *I) { return !I->hasSideEffects(); } }; template<class ValueSubclass, class ItemParentType, class DCEController> static bool RemoveUnusedDefs(ValueHolder<ValueSubclass, ItemParentType> &Vals, DCEController DCEControl) { bool Changed = false; typedef ValueHolder<ValueSubclass, ItemParentType> Container; int Offset = DCEController::EndOffs; for (Container::iterator DI = Vals.begin(); DI != Vals.end()-Offset; ) { // Look for un"used" definitions... if ((*DI)->use_empty() && DCEController::isDCEable(*DI)) { // Bye bye //cerr << "Removing: " << *DI; delete Vals.remove(DI); Changed = true; } else { ++DI; } } return Changed; } // RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only // a single predecessor. This means that the PHI node must only have a single // RHS value and can be eliminated. // // This routine is very simple because we know that PHI nodes must be the first // things in a basic block, if they are present. // static bool RemoveSingularPHIs(BasicBlock *BB) { pred_iterator PI(pred_begin(BB)); if (PI == pred_end(BB) || ++PI != pred_end(BB)) return false; // More than one predecessor... Instruction *I = BB->front(); if (!I->isPHINode()) return false; // No PHI nodes //cerr << "Killing PHIs from " << BB; //cerr << "Pred #0 = " << *pred_begin(BB); //cerr << "Method == " << BB->getParent(); do { PHINode *PN = (PHINode*)I; assert(PN->getNumOperands() == 2 && "PHI node should only have one value!"); Value *V = PN->getOperand(0); PN->replaceAllUsesWith(V); // Replace PHI node with its single value. delete BB->getInstList().remove(BB->begin()); I = BB->front(); } while (I->isPHINode()); return true; // Yes, we nuked at least one phi node } bool opt::DoRemoveUnusedConstants(SymTabValue *S) { bool Changed = false; ConstantPool &CP = S->getConstantPool(); for (ConstantPool::plane_iterator PI = CP.begin(); PI != CP.end(); ++PI) Changed |= RemoveUnusedDefs(**PI, ConstPoolDCE()); return Changed; } static void ReplaceUsesWithConstant(Instruction *I) { // Get the method level constant pool ConstantPool &CP = I->getParent()->getParent()->getConstantPool(); ConstPoolVal *CPV = 0; ConstantPool::PlaneType *P; if (!CP.getPlane(I->getType(), P)) { // Does plane exist? // Yes, is it empty? if (!P->empty()) CPV = P->front(); } if (CPV == 0) { // We don't have an existing constant to reuse. Just add one. CPV = ConstPoolVal::getNullConstant(I->getType()); // Create a new constant // Add the new value to the constant pool... CP.insert(CPV); } // Make all users of this instruction reference the constant instead I->replaceAllUsesWith(CPV); } // PropogatePredecessors - This gets "Succ" ready to have the predecessors from // "BB". This is a little tricky because "Succ" has PHI nodes, which need to // have extra slots added to them to hold the merge edges from BB's // predecessors. // // Assumption: BB is the single predecessor of Succ. // static void PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) { assert(Succ->front()->isPHINode() && "Only works on PHId BBs!"); // If there is more than one predecessor, and there are PHI nodes in // the successor, then we need to add incoming edges for the PHI nodes // const vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB)); BasicBlock::iterator I = Succ->begin(); do { // Loop over all of the PHI nodes in the successor BB PHINode *PN = (PHINode*)*I; Value *OldVal = PN->removeIncomingValue(BB); assert(OldVal && "No entry in PHI for Pred BB!"); for (vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), End = BBPreds.end(); PredI != End; ++PredI) { // Add an incoming value for each of the new incoming values... PN->addIncoming(OldVal, *PredI); } ++I; } while ((*I)->isPHINode()); } // SimplifyCFG - This function is used to do simplification of a CFG. For // example, it adjusts branches to branches to eliminate the extra hop, it // eliminates unreachable basic blocks, and does other "peephole" optimization // of the CFG. It returns true if a modification was made, and returns an // iterator that designates the first element remaining after the block that // was deleted. // // WARNING: The entry node of a method may not be simplified. // bool opt::SimplifyCFG(Method::iterator &BBIt) { assert(*BBIt && (*BBIt)->getParent() && "Block not embedded in method!"); BasicBlock *BB = *BBIt; Method *M = BB->getParent(); assert(BB->getTerminator() && "Degenerate basic block encountered!"); assert(BB->getParent()->front() != BB && "Can't Simplify entry block!"); // Remove basic blocks that have no predecessors... which are unreachable. if (pred_begin(BB) == pred_end(BB) && !BB->hasConstantPoolReferences()) { //cerr << "Removing BB: \n" << BB; // Loop through all of our successors and make sure they know that one // of their predecessors is going away. for_each(succ_begin(BB), succ_end(BB), std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB)); while (!BB->empty()) { Instruction *I = BB->back(); // If this instruction is used, replace uses with an arbitrary // constant value. Because control flow can't get here, we don't care // what we replace the value with. Note that since this block is // unreachable, and all values contained within it must dominate their // uses, that all uses will eventually be removed. if (!I->use_empty()) ReplaceUsesWithConstant(I); // Remove the instruction from the basic block delete BB->getInstList().pop_back(); } delete M->getBasicBlocks().remove(BBIt); return true; } // Check to see if this block has no instructions and only a single // successor. If so, replace block references with successor. succ_iterator SI(succ_begin(BB)); if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ? Instruction *I = BB->front(); if (I->isTerminator()) { // Terminator is the only instruction! BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor //cerr << "Killing Trivial BB: \n" << BB; if (Succ != BB) { // Arg, don't hurt infinite loops! if (Succ->front()->isPHINode()) { // If our successor has PHI nodes, then we need to update them to // include entries for BB's predecessors, not for BB itself. // PropogatePredecessorsForPHIs(BB, Succ); } BB->replaceAllUsesWith(Succ); BB = M->getBasicBlocks().remove(BBIt); if (BB->hasName() && !Succ->hasName()) // Transfer name if we can Succ->setName(BB->getName()); delete BB; // Delete basic block //cerr << "Method after removal: \n" << M; return true; } } } // Merge basic blocks into their predecessor if there is only one pred, // and if there is only one successor of the predecessor. pred_iterator PI(pred_begin(BB)); if (PI != pred_end(BB) && *PI != BB && // Not empty? Not same BB? ++PI == pred_end(BB) && !BB->hasConstantPoolReferences()) { BasicBlock *Pred = *pred_begin(BB); TerminatorInst *Term = Pred->getTerminator(); assert(Term != 0 && "malformed basic block without terminator!"); // Does the predecessor block only have a single successor? succ_iterator SI(succ_begin(Pred)); if (++SI == succ_end(Pred)) { //cerr << "Merging: " << BB << "into: " << Pred; // Delete the unconditianal branch from the predecessor... BasicBlock::iterator DI = Pred->end(); assert(Pred->getTerminator() && "Degenerate basic block encountered!"); // Empty bb??? delete Pred->getInstList().remove(--DI); // Destroy uncond branch // Move all definitions in the succecessor to the predecessor... while (!BB->empty()) { DI = BB->begin(); Instruction *Def = BB->getInstList().remove(DI); // Remove from front Pred->getInstList().push_back(Def); // Add to end... } // Remove basic block from the method... and advance iterator to the // next valid block... BB = M->getBasicBlocks().remove(BBIt); // Make all PHI nodes that refered to BB now refer to Pred as their // source... BB->replaceAllUsesWith(Pred); // Inherit predecessors name if it exists... if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName()); delete BB; // You ARE the weakest link... goodbye return true; } } return false; } static bool DoDCEPass(Method *M) { Method::iterator BBIt, BBEnd = M->end(); if (M->begin() == BBEnd) return false; // Nothing to do bool Changed = false; // Loop through now and remove instructions that have no uses... for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) { Changed |= RemoveUnusedDefs((*BBIt)->getInstList(), BasicBlockDCE()); Changed |= RemoveSingularPHIs(*BBIt); } // Loop over all of the basic blocks (except the first one) and remove them // if they are unneeded... // for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ) { if (opt::SimplifyCFG(BBIt)) { Changed = true; } else { ++BBIt; } } // Remove unused constants return Changed | opt::DoRemoveUnusedConstants(M); } // It is possible that we may require multiple passes over the code to fully // eliminate dead code. Iterate until we are done. // bool opt::DoDeadCodeElimination(Method *M) { bool Changed = false; while (DoDCEPass(M)) Changed = true; return Changed; } bool opt::DoDeadCodeElimination(Module *C) { bool Val = C->reduceApply(DoDeadCodeElimination); while (DoRemoveUnusedConstants(C)) Val = true; return Val; } <commit_msg>Don't clean out the type plane of the constant pool... this is a hack. FIXME<commit_after>//===- DCE.cpp - Code to perform dead code elimination --------------------===// // // This file implements dead code elimination and basic block merging. // // Specifically, this: // * removes definitions with no uses (including unused constants) // * removes basic blocks with no predecessors // * merges a basic block into its predecessor if there is only one and the // predecessor only has one successor. // * Eliminates PHI nodes for basic blocks with a single predecessor // * Eliminates a basic block that only contains an unconditional branch // // TODO: This should REALLY be worklist driven instead of iterative. Right now, // we scan linearly through values, removing unused ones as we go. The problem // is that this may cause other earlier values to become unused. To make sure // that we get them all, we iterate until things stop changing. Instead, when // removing a value, recheck all of its operands to see if they are now unused. // Piece of cake, and more efficient as well. // // Note, this is not trivial, because we have to worry about invalidating // iterators. :( // //===----------------------------------------------------------------------===// #include "llvm/Optimizations/DCE.h" #include "llvm/Tools/STLExtras.h" #include "llvm/Module.h" #include "llvm/Method.h" #include "llvm/BasicBlock.h" #include "llvm/iTerminators.h" #include "llvm/iOther.h" #include "llvm/Assembly/Writer.h" #include "llvm/CFG.h" #include <algorithm> using namespace cfg; struct ConstPoolDCE { enum { EndOffs = 0 }; static bool isDCEable(const ConstPoolVal *CPV) { // TODO: The bytecode writer requires that all used types are in the // constant pool for the current method. This is messy and is really // irritating. FIXME return CPV->getType() != Type::TypeTy; // Don't DCE Type plane constants! } }; struct BasicBlockDCE { enum { EndOffs = 1 }; static bool isDCEable(const Instruction *I) { return !I->hasSideEffects(); } }; template<class ValueSubclass, class ItemParentType, class DCEController> static bool RemoveUnusedDefs(ValueHolder<ValueSubclass, ItemParentType> &Vals, DCEController DCEControl) { bool Changed = false; typedef ValueHolder<ValueSubclass, ItemParentType> Container; int Offset = DCEController::EndOffs; for (Container::iterator DI = Vals.begin(); DI != Vals.end()-Offset; ) { // Look for un"used" definitions... if ((*DI)->use_empty() && DCEController::isDCEable(*DI)) { // Bye bye //cerr << "Removing: " << *DI; delete Vals.remove(DI); Changed = true; } else { ++DI; } } return Changed; } // RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only // a single predecessor. This means that the PHI node must only have a single // RHS value and can be eliminated. // // This routine is very simple because we know that PHI nodes must be the first // things in a basic block, if they are present. // static bool RemoveSingularPHIs(BasicBlock *BB) { pred_iterator PI(pred_begin(BB)); if (PI == pred_end(BB) || ++PI != pred_end(BB)) return false; // More than one predecessor... Instruction *I = BB->front(); if (!I->isPHINode()) return false; // No PHI nodes //cerr << "Killing PHIs from " << BB; //cerr << "Pred #0 = " << *pred_begin(BB); //cerr << "Method == " << BB->getParent(); do { PHINode *PN = (PHINode*)I; assert(PN->getNumOperands() == 2 && "PHI node should only have one value!"); Value *V = PN->getOperand(0); PN->replaceAllUsesWith(V); // Replace PHI node with its single value. delete BB->getInstList().remove(BB->begin()); I = BB->front(); } while (I->isPHINode()); return true; // Yes, we nuked at least one phi node } bool opt::DoRemoveUnusedConstants(SymTabValue *S) { bool Changed = false; ConstantPool &CP = S->getConstantPool(); for (ConstantPool::plane_iterator PI = CP.begin(); PI != CP.end(); ++PI) Changed |= RemoveUnusedDefs(**PI, ConstPoolDCE()); return Changed; } static void ReplaceUsesWithConstant(Instruction *I) { // Get the method level constant pool ConstantPool &CP = I->getParent()->getParent()->getConstantPool(); ConstPoolVal *CPV = 0; ConstantPool::PlaneType *P; if (!CP.getPlane(I->getType(), P)) { // Does plane exist? // Yes, is it empty? if (!P->empty()) CPV = P->front(); } if (CPV == 0) { // We don't have an existing constant to reuse. Just add one. CPV = ConstPoolVal::getNullConstant(I->getType()); // Create a new constant // Add the new value to the constant pool... CP.insert(CPV); } // Make all users of this instruction reference the constant instead I->replaceAllUsesWith(CPV); } // PropogatePredecessors - This gets "Succ" ready to have the predecessors from // "BB". This is a little tricky because "Succ" has PHI nodes, which need to // have extra slots added to them to hold the merge edges from BB's // predecessors. // // Assumption: BB is the single predecessor of Succ. // static void PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) { assert(Succ->front()->isPHINode() && "Only works on PHId BBs!"); // If there is more than one predecessor, and there are PHI nodes in // the successor, then we need to add incoming edges for the PHI nodes // const vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB)); BasicBlock::iterator I = Succ->begin(); do { // Loop over all of the PHI nodes in the successor BB PHINode *PN = (PHINode*)*I; Value *OldVal = PN->removeIncomingValue(BB); assert(OldVal && "No entry in PHI for Pred BB!"); for (vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), End = BBPreds.end(); PredI != End; ++PredI) { // Add an incoming value for each of the new incoming values... PN->addIncoming(OldVal, *PredI); } ++I; } while ((*I)->isPHINode()); } // SimplifyCFG - This function is used to do simplification of a CFG. For // example, it adjusts branches to branches to eliminate the extra hop, it // eliminates unreachable basic blocks, and does other "peephole" optimization // of the CFG. It returns true if a modification was made, and returns an // iterator that designates the first element remaining after the block that // was deleted. // // WARNING: The entry node of a method may not be simplified. // bool opt::SimplifyCFG(Method::iterator &BBIt) { assert(*BBIt && (*BBIt)->getParent() && "Block not embedded in method!"); BasicBlock *BB = *BBIt; Method *M = BB->getParent(); assert(BB->getTerminator() && "Degenerate basic block encountered!"); assert(BB->getParent()->front() != BB && "Can't Simplify entry block!"); // Remove basic blocks that have no predecessors... which are unreachable. if (pred_begin(BB) == pred_end(BB) && !BB->hasConstantPoolReferences()) { //cerr << "Removing BB: \n" << BB; // Loop through all of our successors and make sure they know that one // of their predecessors is going away. for_each(succ_begin(BB), succ_end(BB), std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB)); while (!BB->empty()) { Instruction *I = BB->back(); // If this instruction is used, replace uses with an arbitrary // constant value. Because control flow can't get here, we don't care // what we replace the value with. Note that since this block is // unreachable, and all values contained within it must dominate their // uses, that all uses will eventually be removed. if (!I->use_empty()) ReplaceUsesWithConstant(I); // Remove the instruction from the basic block delete BB->getInstList().pop_back(); } delete M->getBasicBlocks().remove(BBIt); return true; } // Check to see if this block has no instructions and only a single // successor. If so, replace block references with successor. succ_iterator SI(succ_begin(BB)); if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ? Instruction *I = BB->front(); if (I->isTerminator()) { // Terminator is the only instruction! BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor //cerr << "Killing Trivial BB: \n" << BB; if (Succ != BB) { // Arg, don't hurt infinite loops! if (Succ->front()->isPHINode()) { // If our successor has PHI nodes, then we need to update them to // include entries for BB's predecessors, not for BB itself. // PropogatePredecessorsForPHIs(BB, Succ); } BB->replaceAllUsesWith(Succ); BB = M->getBasicBlocks().remove(BBIt); if (BB->hasName() && !Succ->hasName()) // Transfer name if we can Succ->setName(BB->getName()); delete BB; // Delete basic block //cerr << "Method after removal: \n" << M; return true; } } } // Merge basic blocks into their predecessor if there is only one pred, // and if there is only one successor of the predecessor. pred_iterator PI(pred_begin(BB)); if (PI != pred_end(BB) && *PI != BB && // Not empty? Not same BB? ++PI == pred_end(BB) && !BB->hasConstantPoolReferences()) { BasicBlock *Pred = *pred_begin(BB); TerminatorInst *Term = Pred->getTerminator(); assert(Term != 0 && "malformed basic block without terminator!"); // Does the predecessor block only have a single successor? succ_iterator SI(succ_begin(Pred)); if (++SI == succ_end(Pred)) { //cerr << "Merging: " << BB << "into: " << Pred; // Delete the unconditianal branch from the predecessor... BasicBlock::iterator DI = Pred->end(); assert(Pred->getTerminator() && "Degenerate basic block encountered!"); // Empty bb??? delete Pred->getInstList().remove(--DI); // Destroy uncond branch // Move all definitions in the succecessor to the predecessor... while (!BB->empty()) { DI = BB->begin(); Instruction *Def = BB->getInstList().remove(DI); // Remove from front Pred->getInstList().push_back(Def); // Add to end... } // Remove basic block from the method... and advance iterator to the // next valid block... BB = M->getBasicBlocks().remove(BBIt); // Make all PHI nodes that refered to BB now refer to Pred as their // source... BB->replaceAllUsesWith(Pred); // Inherit predecessors name if it exists... if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName()); delete BB; // You ARE the weakest link... goodbye return true; } } return false; } static bool DoDCEPass(Method *M) { Method::iterator BBIt, BBEnd = M->end(); if (M->begin() == BBEnd) return false; // Nothing to do bool Changed = false; // Loop through now and remove instructions that have no uses... for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) { Changed |= RemoveUnusedDefs((*BBIt)->getInstList(), BasicBlockDCE()); Changed |= RemoveSingularPHIs(*BBIt); } // Loop over all of the basic blocks (except the first one) and remove them // if they are unneeded... // for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ) { if (opt::SimplifyCFG(BBIt)) { Changed = true; } else { ++BBIt; } } // Remove unused constants return Changed | opt::DoRemoveUnusedConstants(M); } // It is possible that we may require multiple passes over the code to fully // eliminate dead code. Iterate until we are done. // bool opt::DoDeadCodeElimination(Method *M) { bool Changed = false; while (DoDCEPass(M)) Changed = true; return Changed; } bool opt::DoDeadCodeElimination(Module *C) { bool Val = C->reduceApply(DoDeadCodeElimination); while (DoRemoveUnusedConstants(C)) Val = true; return Val; } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include <fstream> #include <sstream> #include <cstdlib> #include <vector> #include <thread> #include "common/log.h" #include "gfx/gl/driver.h" #include "gfx/camera.h" #include "gfx/object.h" #include "gfx/scene_node.h" #include "gfx/texture.h" #include "gfx/mesh.h" #include "glad/glad.h" #include "glfw3.h" #define GLM_FORCE_RADIANS #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "uv.h" #define CATCH_CONFIG_RUNNER #include "catch/catch.hpp" struct Command_Options { }; Command_Options parse_command_line(int argc, char**) { Command_Options opt; for(int i = 0; i < argc; ++i) { //auto option = argv[i]; } return opt; } int main(int argc, char** argv) { using namespace game; set_log_level(Log_Severity::Debug); uv_chdir("assets/"); // Initialize logger. Scoped_Log_Init log_init_raii_lock{}; // Parse command line arguments. auto options = parse_command_line(argc - 1, argv+1); // Init glfw. if(!glfwInit()) return EXIT_FAILURE; auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL); if(!window) { glfwTerminate(); return EXIT_FAILURE; } // Init context + load gl functions. glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); // Log glfw version. log_i("Initialized GLFW %", glfwGetVersionString()); int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR); int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR); int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION); // Log GL profile. log_i("OpenGL core profile %.%.%", maj, min, rev); // Hide the mouse and capture it glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); { // Make an OpenGL driver. gfx::gl::Driver driver{}; // Make an fps camera. auto cam = gfx::make_fps_camera(); cam.fp.pos = glm::vec3(0.0f, 0.0f, 25.0f); auto house = gfx::load_object("obj/house.obj", "mat/house.json"); prepare_object(driver, house); auto house_aabb = generate_aabb(*house.mesh); auto plane = gfx::load_object("obj/plane.obj", "mat/plane.json"); prepare_object(driver, plane); plane.model_matrix = glm::translate(plane.model_matrix, glm::vec3(0.0f,house_aabb.min.y,0.0f)); plane.model_matrix = glm::scale(plane.model_matrix, glm::vec3(5.0f, 1.0f, 7.0f)); plane.model_matrix = glm::translate(plane.model_matrix, glm::vec3(-0.5f, 0.0f, -0.5f)); int fps = 0; int time = glfwGetTime(); // Set up some pre-rendering state. driver.clear_color_value(Color{0x55, 0x66, 0x77}); driver.clear_depth_value(1.0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); while(!glfwWindowShouldClose(window)) { ++fps; glfwPollEvents(); if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { glfwSetWindowShouldClose(window, true); } double x, y; glfwGetCursorPos(window, &x, &y); cam.fp.pitch = y / 250.0; cam.fp.yaw = x / 250.0; driver.use_camera(cam); // Clear the screen driver.clear(); render_object(driver, house); render_object(driver, plane); glfwSwapBuffers(window); if(int(glfwGetTime()) != time) { time = glfwGetTime(); log_d("fps: %", fps); fps = 0; } } } glfwTerminate(); return 0; } <commit_msg>We're now using our nifty fps camera controller in the main(_fps.cpp) file.<commit_after>/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include <fstream> #include <sstream> #include <cstdlib> #include <vector> #include <thread> #include "common/log.h" #include "gfx/gl/driver.h" #include "gfx/camera.h" #include "gfx/object.h" #include "gfx/scene_node.h" #include "gfx/texture.h" #include "gfx/mesh.h" #include "fps/camera_controller.h" #include "glad/glad.h" #include "glfw3.h" #define GLM_FORCE_RADIANS #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "uv.h" #define CATCH_CONFIG_RUNNER #include "catch/catch.hpp" #define PI 3.141592653589793238463 struct Command_Options { }; Command_Options parse_command_line(int argc, char**) { Command_Options opt; for(int i = 0; i < argc; ++i) { //auto option = argv[i]; } return opt; } int main(int argc, char** argv) { using namespace game; set_log_level(Log_Severity::Debug); uv_chdir("assets/"); // Initialize logger. Scoped_Log_Init log_init_raii_lock{}; // Parse command line arguments. auto options = parse_command_line(argc - 1, argv+1); // Init glfw. if(!glfwInit()) return EXIT_FAILURE; auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL); if(!window) { glfwTerminate(); return EXIT_FAILURE; } // Init context + load gl functions. glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); // Log glfw version. log_i("Initialized GLFW %", glfwGetVersionString()); int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR); int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR); int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION); // Log GL profile. log_i("OpenGL core profile %.%.%", maj, min, rev); // Hide the mouse and capture it glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); { // Make an OpenGL driver. gfx::gl::Driver driver{}; // Make an fps camera. auto cam = gfx::make_fps_camera(); cam.fp.pos = glm::vec3(0.0f, 0.0f, 15.0f); auto cam_controller = fps::Camera_Controller{}; cam_controller.camera(cam); cam_controller.set_yaw_limit(PI / 2); cam_controller.set_pitch_limit(PI / 2); auto house = gfx::load_object("obj/house.obj", "mat/house.json"); prepare_object(driver, house); auto house_aabb = generate_aabb(*house.mesh); auto plane = gfx::load_object("obj/plane.obj", "mat/plane.json"); prepare_object(driver, plane); plane.model_matrix = glm::translate(plane.model_matrix, glm::vec3(0.0f,house_aabb.min.y,0.0f)); plane.model_matrix = glm::scale(plane.model_matrix, glm::vec3(5.0f, 1.0f, 7.0f)); plane.model_matrix = glm::translate(plane.model_matrix, glm::vec3(-0.5f, 0.0f, -0.5f)); int fps = 0; int time = glfwGetTime(); // Set up some pre-rendering state. driver.clear_color_value(Color{0x55, 0x66, 0x77}); driver.clear_depth_value(1.0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); double prev_x, prev_y; glfwPollEvents(); glfwGetCursorPos(window, &prev_x, &prev_y); while(!glfwWindowShouldClose(window)) { ++fps; glfwPollEvents(); if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { glfwSetWindowShouldClose(window, true); } double x, y; glfwGetCursorPos(window, &x, &y); cam_controller.apply_delta_pitch(y / 250.0 - prev_y / 250.0); cam_controller.apply_delta_yaw(x / 250.0 - prev_x / 250.0); prev_x = x, prev_y = y; driver.use_camera(cam); // Clear the screen driver.clear(); render_object(driver, house); render_object(driver, plane); glfwSwapBuffers(window); if(int(glfwGetTime()) != time) { time = glfwGetTime(); log_d("fps: %", fps); fps = 0; } } } glfwTerminate(); return 0; } <|endoftext|>
<commit_before><commit_msg>this counter is not needed in sw/.. view.cxx, thanks cppcheck<commit_after><|endoftext|>
<commit_before> #include "../common.h" #include "gamefw.h" #include <glm/gtc/matrix_projection.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/euler_angles.hpp> using namespace gamefw; Renderer::Renderer(const GLuint display_width, const GLuint display_height) : m_display_width((float) display_width), m_display_height((float) display_height), m_aspect_ratio((float) display_width / (float) display_height), m_camera(new Entity()) { initBuffers(display_width, display_height); m_camera->setName("Camera"); } Renderer::~Renderer() { glDeleteRenderbuffers(1, &m_depth_stencil_buffers.gbuffer); glDeleteRenderbuffers(1, &m_depth_stencil_buffers.pbuffer); glDeleteFramebuffers(1, &m_fbo.gbuffer); glDeleteFramebuffers(1, &m_fbo.pbuffer); glDeleteFramebuffers(1, &m_fbo.ppbuffer); // Delete manually allocated textures. shared_ptr<RenderJob> gbuffer_renderjob = m_gbuffer.getRenderJob(); glDeleteTextures(gbuffer_renderjob->m_num_textures, gbuffer_renderjob->m_textures); delete [] gbuffer_renderjob->m_textures; gbuffer_renderjob->m_num_textures = 0; shared_ptr<RenderJob> pbuffer_renderjob = m_pbuffer.getRenderJob(); glDeleteTextures(pbuffer_renderjob->m_num_textures, pbuffer_renderjob->m_textures); delete [] pbuffer_renderjob->m_textures; pbuffer_renderjob->m_num_textures = 0; shared_ptr<RenderJob> ppbuffer_renderjob = m_ppbuffer.getRenderJob(); // Shared textures with gbuffer. ppbuffer_renderjob->m_num_textures = 0; } void Renderer::createDepthStencilBuffer(GLuint* buffer, const GLuint width, const GLuint height) { glGenRenderbuffers(1, buffer); glBindRenderbuffer(GL_RENDERBUFFER, m_depth_stencil_buffers.gbuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH32F_STENCIL8, width, height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, m_depth_stencil_buffers.gbuffer); } void Renderer::texParametersForRenderTargets() const { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1000); } bool Renderer::checkFramebuffer() const { GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); string error = "Framebuffer object error: "; switch (status) { case GL_FRAMEBUFFER_UNDEFINED: LOG(logERROR) << error << "GL_FRAMEBUFFER_UNDEFINED"; break; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: LOG(logERROR) << error << "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"; break; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: LOG(logERROR) << error << "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"; break; case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: LOG(logERROR) << error << "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER"; break; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: LOG(logERROR) << error << "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER"; break; case GL_FRAMEBUFFER_UNSUPPORTED: LOG(logERROR) << error << "GL_FRAMEBUFFER_UNSUPPORTED"; break; case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: LOG(logERROR) << error << "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"; break; case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: LOG(logERROR) << error << "GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS"; break; } return status == GL_FRAMEBUFFER_COMPLETE; } void Renderer::createTexturesForFBO(shared_ptr<RenderJob> renderjob, const GLuint num_textures, const GLenum internalformats[], const GLuint size_divisor[], const GLenum types[]) { renderjob->m_textures = new GLuint[num_textures]; renderjob->m_num_textures = num_textures; glGenTextures(num_textures, renderjob->m_textures); for (int i = 0; i < num_textures; i++) { glBindTexture(GL_TEXTURE_2D, renderjob->m_textures[i]); texParametersForRenderTargets(); glTexImage2D( GL_TEXTURE_2D, 0, internalformats[i], m_display_width / size_divisor[i], m_display_height / size_divisor[i], 0, GL_RGB, types[i], 0 ); GLint attachment = GL_COLOR_ATTACHMENT0 + i; glFramebufferTexture(GL_FRAMEBUFFER, attachment, renderjob->m_textures[i], 0); } } void Renderer::initBuffers(const GLuint width, const GLuint height) { int num_textures = 4; // GBUFFER STAGE { m_gbuffer = Locator::getFileService().createEntity("gbuffer"); glGenFramebuffers(1, &m_fbo.gbuffer); glBindFramebuffer(GL_FRAMEBUFFER, m_fbo.gbuffer); glActiveTexture(GL_TEXTURE0); shared_ptr<RenderJob> gbuffer_renderjob = m_gbuffer.getRenderJob(); gbuffer_renderjob->m_textures = new GLuint[num_textures]; gbuffer_renderjob->m_num_textures = num_textures; glGenTextures(num_textures, gbuffer_renderjob->m_textures); for (int i = 0; i < num_textures; i++) { glBindTexture(GL_TEXTURE_2D, gbuffer_renderjob->m_textures[i]); texParametersForRenderTargets(); GLenum internalformat, type; switch (i) { case(renderjob_enums::OUTG_NORMAL): internalformat = GL_RGB16F; type = GL_FLOAT; break; case(renderjob_enums::OUTG_POSITION): internalformat = GL_RGB32F; type = GL_FLOAT; break; default: internalformat = GL_RGB8; type = GL_UNSIGNED_BYTE; break; } glTexImage2D( GL_TEXTURE_2D, 0, internalformat, width, height, 0, GL_RGB, type, 0 ); GLint attachment = GL_COLOR_ATTACHMENT0 + i; glFramebufferTexture(GL_FRAMEBUFFER, attachment, gbuffer_renderjob->m_textures[i], 0); } createDepthStencilBuffer(&m_depth_stencil_buffers.gbuffer, width, height); bool status = checkFramebuffer(); assert(status); GLenum draw_buffers[] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 }; glDrawBuffers(4, draw_buffers); glBindFramebuffer(GL_FRAMEBUFFER, 0); } // PBUFFER STAGE. { m_pbuffer = Locator::getFileService().createEntity("pbuffer"); glGenFramebuffers(1, &m_fbo.pbuffer); glBindFramebuffer(GL_FRAMEBUFFER, m_fbo.pbuffer); glActiveTexture(GL_TEXTURE0); shared_ptr<RenderJob> pbuffer_renderjob = m_pbuffer.getRenderJob(); pbuffer_renderjob->m_textures = new GLuint[num_textures]; pbuffer_renderjob->m_num_textures = num_textures; glGenTextures(num_textures, pbuffer_renderjob->m_textures); for (int i = 0; i < num_textures; i++) { glBindTexture(GL_TEXTURE_2D, pbuffer_renderjob->m_textures[i]); texParametersForRenderTargets(); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB8, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, 0 ); GLint attachment = GL_COLOR_ATTACHMENT0 + i; glFramebufferTexture(GL_FRAMEBUFFER, attachment, pbuffer_renderjob->m_textures[i], 0); } createDepthStencilBuffer(&m_depth_stencil_buffers.pbuffer, width, height); bool status = checkFramebuffer(); assert(status); GLenum draw_buffers[] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 }; glDrawBuffers(4, draw_buffers); glBindFramebuffer(GL_FRAMEBUFFER, 0); } // POSTPROCESSING STAGE { m_ppbuffer = Locator::getFileService().createEntity("ppbuffer"); shared_ptr<RenderJob> ppbuffer_renderjob = m_ppbuffer.getRenderJob(); // Use gbuffers diffuse and specular textures. m_fbo.ppbuffer = m_fbo.gbuffer; ppbuffer_renderjob->m_textures = m_gbuffer.getRenderJob()->m_textures; ppbuffer_renderjob->m_num_textures = 2; } } void Renderer::render() { glEnable(GL_DEPTH_TEST); renderGBuffers(); glDisable(GL_DEPTH_TEST); renderPBuffers(); renderPPBuffers(); glBindFramebuffer(GL_FRAMEBUFFER, 0); // Bind main window's framebuffer. glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); renderEntity(m_ppbuffer); } void Renderer::addToRenderQueue(const Entity& entity) { m_render_queue.push(&entity); } void Renderer::renderEntity(const Entity& entity) { shared_ptr<RenderJob> renderjob = entity.getRenderJob(); GLuint program_id = renderjob->getShaderProgramID(); glUseProgram(program_id); // Load textures. for (uint i = 0; i < renderjob->m_num_textures; i++) { glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, renderjob->m_textures[i]); string uniform_name("texture"); uniform_name += (char) '0' + i; GLint location = glGetUniformLocation(program_id, uniform_name.c_str()); glUniform1i(location, i); } // Bind material uniform block. if (renderjob->m_uniforms.materials != 0) { glBindBufferBase(GL_UNIFORM_BUFFER, renderjob_enums::MATERIAL, renderjob->m_uniforms.materials); } // Calculate and bind mvp. // Model orientation ... glm::mat4 model(glm::yawPitchRoll(entity.m_orientation.yaw, entity.m_orientation.pitch, entity.m_orientation.roll)); // ... + translation model[3] = glm::vec4(entity.m_position, 1.0); // Normal transform. glm::mat4 normalmatrix = glm::transpose(glm::inverse(model)); // View transform. glm::vec3 view_pos(0.0f, 0.0f, 0.0f); glm::mat4 view_orientation(glm::yawPitchRoll(0.0f, 0.0f, 0.0f)); glm::mat4 view(glm::translate(glm::mat4(1.0f), -view_pos) * view_orientation); // Projection transform glm::mat4 projection = glm::perspective(45.0f, m_aspect_ratio, 0.1f, 100.f); glm::mat4 mvp = projection * view * model; // Bind the matrices to uniforms. GLint location_mvp = glGetUniformLocation(program_id, "mvp"); glUniformMatrix4fv(location_mvp, 1, GL_FALSE, glm::value_ptr(mvp)); GLint location_model = glGetUniformLocation(program_id, "model"); glUniformMatrix4fv(location_model, 1, GL_FALSE, glm::value_ptr(model)); GLint location_normalmatrix = glGetUniformLocation(program_id, "normalmatrix"); glUniformMatrix4fv(location_normalmatrix, 1, GL_FALSE, glm::value_ptr(normalmatrix)); // Bind display height and width uniforms. GLint location_width = glGetUniformLocation(program_id, "display_width"); glUniform1f(location_width, m_display_width); GLint location_height = glGetUniformLocation(program_id, "display_height"); glUniform1f(location_height, m_display_height); glBindVertexArray(renderjob->m_buffer_objects.vao); glEnableVertexAttribArray(renderjob_enums::POSITION); glEnableVertexAttribArray(renderjob_enums::NORMAL); glEnableVertexAttribArray(renderjob_enums::TEXCOORD); glEnableVertexAttribArray(renderjob_enums::MATERIAL_IDX); glDrawElements(GL_TRIANGLES, renderjob->m_vertex_count, GL_UNSIGNED_SHORT, 0); glDisableVertexAttribArray(renderjob_enums::POSITION); glDisableVertexAttribArray(renderjob_enums::NORMAL); glDisableVertexAttribArray(renderjob_enums::TEXCOORD); glDisableVertexAttribArray(renderjob_enums::MATERIAL_IDX); // Cleanup. glBindVertexArray(0); glUseProgram(0); glBindBufferBase(GL_UNIFORM_BUFFER, renderjob_enums::MATERIAL, 0); } void Renderer::renderGBuffers() { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo.gbuffer); glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); while (!m_render_queue.empty()) { const Entity* current_entity = m_render_queue.front(); m_render_queue.pop(); renderEntity(*current_entity); } } void Renderer::renderPBuffers() { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo.pbuffer); glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); GLuint program_id = m_gbuffer.getRenderJob()->getShaderProgramID(); glUseProgram(program_id); glUniform3fv(glGetUniformLocation(program_id, "viewer_position"), 1, glm::value_ptr(m_camera->m_position)); renderEntity(m_gbuffer); } void gamefw::Renderer::renderPPBuffers() { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo.ppbuffer); glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); renderEntity(m_pbuffer); } <commit_msg>Refactor Renderer FBO texture generation.<commit_after> #include "../common.h" #include "gamefw.h" #include <glm/gtc/matrix_projection.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/euler_angles.hpp> using namespace gamefw; Renderer::Renderer(const GLuint display_width, const GLuint display_height) : m_display_width((float) display_width), m_display_height((float) display_height), m_aspect_ratio((float) display_width / (float) display_height), m_camera(new Entity()) { initBuffers(display_width, display_height); m_camera->setName("Camera"); } Renderer::~Renderer() { glDeleteRenderbuffers(1, &m_depth_stencil_buffers.gbuffer); glDeleteRenderbuffers(1, &m_depth_stencil_buffers.pbuffer); glDeleteFramebuffers(1, &m_fbo.gbuffer); glDeleteFramebuffers(1, &m_fbo.pbuffer); glDeleteFramebuffers(1, &m_fbo.ppbuffer); // Delete manually allocated textures. shared_ptr<RenderJob> gbuffer_renderjob = m_gbuffer.getRenderJob(); glDeleteTextures(gbuffer_renderjob->m_num_textures, gbuffer_renderjob->m_textures); delete [] gbuffer_renderjob->m_textures; gbuffer_renderjob->m_num_textures = 0; shared_ptr<RenderJob> pbuffer_renderjob = m_pbuffer.getRenderJob(); glDeleteTextures(pbuffer_renderjob->m_num_textures, pbuffer_renderjob->m_textures); delete [] pbuffer_renderjob->m_textures; pbuffer_renderjob->m_num_textures = 0; shared_ptr<RenderJob> ppbuffer_renderjob = m_ppbuffer.getRenderJob(); // Shared textures with gbuffer. ppbuffer_renderjob->m_num_textures = 0; } void Renderer::createDepthStencilBuffer(GLuint* buffer, const GLuint width, const GLuint height) { glGenRenderbuffers(1, buffer); glBindRenderbuffer(GL_RENDERBUFFER, m_depth_stencil_buffers.gbuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH32F_STENCIL8, width, height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, m_depth_stencil_buffers.gbuffer); } void Renderer::texParametersForRenderTargets() const { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1000); } bool Renderer::checkFramebuffer() const { GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); string error = "Framebuffer object error: "; switch (status) { case GL_FRAMEBUFFER_UNDEFINED: LOG(logERROR) << error << "GL_FRAMEBUFFER_UNDEFINED"; break; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: LOG(logERROR) << error << "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"; break; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: LOG(logERROR) << error << "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"; break; case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: LOG(logERROR) << error << "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER"; break; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: LOG(logERROR) << error << "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER"; break; case GL_FRAMEBUFFER_UNSUPPORTED: LOG(logERROR) << error << "GL_FRAMEBUFFER_UNSUPPORTED"; break; case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: LOG(logERROR) << error << "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"; break; case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: LOG(logERROR) << error << "GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS"; break; } return status == GL_FRAMEBUFFER_COMPLETE; } void Renderer::createTexturesForFBO(shared_ptr<RenderJob> renderjob, const GLuint num_textures, const GLenum internalformats[], const GLuint size_divisor[], const GLenum types[]) { renderjob->m_textures = new GLuint[num_textures]; renderjob->m_num_textures = num_textures; glGenTextures(num_textures, renderjob->m_textures); for (int i = 0; i < num_textures; i++) { glBindTexture(GL_TEXTURE_2D, renderjob->m_textures[i]); texParametersForRenderTargets(); glTexImage2D( GL_TEXTURE_2D, 0, internalformats[i], m_display_width / size_divisor[i], m_display_height / size_divisor[i], 0, GL_RGB, types[i], 0 ); GLint attachment = GL_COLOR_ATTACHMENT0 + i; glFramebufferTexture(GL_FRAMEBUFFER, attachment, renderjob->m_textures[i], 0); } } void Renderer::initBuffers(const GLuint width, const GLuint height) { int num_textures = 4; // GBUFFER STAGE { m_gbuffer = Locator::getFileService().createEntity("gbuffer"); glGenFramebuffers(1, &m_fbo.gbuffer); glBindFramebuffer(GL_FRAMEBUFFER, m_fbo.gbuffer); const GLenum internalformats[] = { GL_RGB8, GL_RGB8, GL_RGB16F, GL_RGB32F }; const GLuint size_divisor[] = {1, 1, 1, 1}; const GLenum types[] = { GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_FLOAT, GL_FLOAT }; glActiveTexture(GL_TEXTURE0); shared_ptr<RenderJob> gbuffer_renderjob = m_gbuffer.getRenderJob(); createTexturesForFBO(gbuffer_renderjob, num_textures, internalformats, size_divisor, types); createDepthStencilBuffer(&m_depth_stencil_buffers.gbuffer, width, height); bool status = checkFramebuffer(); assert(status); } // PBUFFER STAGE. { m_pbuffer = Locator::getFileService().createEntity("pbuffer"); glGenFramebuffers(1, &m_fbo.pbuffer); glBindFramebuffer(GL_FRAMEBUFFER, m_fbo.pbuffer); glActiveTexture(GL_TEXTURE0); shared_ptr<RenderJob> pbuffer_renderjob = m_pbuffer.getRenderJob(); const GLenum internalformats[] = { GL_RGB8, GL_RGB8, GL_RGB8, GL_RGB8 }; const GLuint size_divisors[] = {1, 1, 1, 1}; const GLenum types[] = { GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE }; createTexturesForFBO(pbuffer_renderjob, num_textures, internalformats, size_divisors, types ); createDepthStencilBuffer(&m_depth_stencil_buffers.pbuffer, width, height); bool status = checkFramebuffer(); assert(status); } // POSTPROCESSING STAGE { m_ppbuffer = Locator::getFileService().createEntity("ppbuffer"); shared_ptr<RenderJob> ppbuffer_renderjob = m_ppbuffer.getRenderJob(); // Use gbuffers diffuse and specular textures. m_fbo.ppbuffer = m_fbo.gbuffer; ppbuffer_renderjob->m_textures = m_gbuffer.getRenderJob()->m_textures; ppbuffer_renderjob->m_num_textures = 2; } // Assign draw buffers. GLenum draw_buffers[] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 }; glBindFramebuffer(GL_FRAMEBUFFER, m_fbo.gbuffer); glDrawBuffers(4, draw_buffers); glBindFramebuffer(GL_FRAMEBUFFER, m_fbo.pbuffer); glDrawBuffers(4, draw_buffers); glBindFramebuffer(GL_FRAMEBUFFER, m_fbo.ppbuffer); glDrawBuffers(4, draw_buffers); glBindFramebuffer(GL_FRAMEBUFFER, 0); } void Renderer::render() { glEnable(GL_DEPTH_TEST); renderGBuffers(); glDisable(GL_DEPTH_TEST); renderPBuffers(); renderPPBuffers(); glBindFramebuffer(GL_FRAMEBUFFER, 0); // Bind main window's framebuffer. glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); renderEntity(m_ppbuffer); } void Renderer::addToRenderQueue(const Entity& entity) { m_render_queue.push(&entity); } void Renderer::renderEntity(const Entity& entity) { shared_ptr<RenderJob> renderjob = entity.getRenderJob(); GLuint program_id = renderjob->getShaderProgramID(); glUseProgram(program_id); // Load textures. for (uint i = 0; i < renderjob->m_num_textures; i++) { glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, renderjob->m_textures[i]); string uniform_name("texture"); uniform_name += (char) '0' + i; GLint location = glGetUniformLocation(program_id, uniform_name.c_str()); glUniform1i(location, i); } // Bind material uniform block. if (renderjob->m_uniforms.materials != 0) { glBindBufferBase(GL_UNIFORM_BUFFER, renderjob_enums::MATERIAL, renderjob->m_uniforms.materials); } // Calculate and bind mvp. // Model orientation ... glm::mat4 model(glm::yawPitchRoll(entity.m_orientation.yaw, entity.m_orientation.pitch, entity.m_orientation.roll)); // ... + translation model[3] = glm::vec4(entity.m_position, 1.0); // Normal transform. glm::mat4 normalmatrix = glm::transpose(glm::inverse(model)); // View transform. glm::vec3 view_pos(0.0f, 0.0f, 0.0f); glm::mat4 view_orientation(glm::yawPitchRoll(0.0f, 0.0f, 0.0f)); glm::mat4 view(glm::translate(glm::mat4(1.0f), -view_pos) * view_orientation); // Projection transform glm::mat4 projection = glm::perspective(45.0f, m_aspect_ratio, 0.1f, 100.f); glm::mat4 mvp = projection * view * model; // Bind the matrices to uniforms. GLint location_mvp = glGetUniformLocation(program_id, "mvp"); glUniformMatrix4fv(location_mvp, 1, GL_FALSE, glm::value_ptr(mvp)); GLint location_model = glGetUniformLocation(program_id, "model"); glUniformMatrix4fv(location_model, 1, GL_FALSE, glm::value_ptr(model)); GLint location_normalmatrix = glGetUniformLocation(program_id, "normalmatrix"); glUniformMatrix4fv(location_normalmatrix, 1, GL_FALSE, glm::value_ptr(normalmatrix)); // Bind display height and width uniforms. GLint location_width = glGetUniformLocation(program_id, "display_width"); glUniform1f(location_width, m_display_width); GLint location_height = glGetUniformLocation(program_id, "display_height"); glUniform1f(location_height, m_display_height); glBindVertexArray(renderjob->m_buffer_objects.vao); glEnableVertexAttribArray(renderjob_enums::POSITION); glEnableVertexAttribArray(renderjob_enums::NORMAL); glEnableVertexAttribArray(renderjob_enums::TEXCOORD); glEnableVertexAttribArray(renderjob_enums::MATERIAL_IDX); glDrawElements(GL_TRIANGLES, renderjob->m_vertex_count, GL_UNSIGNED_SHORT, 0); glDisableVertexAttribArray(renderjob_enums::POSITION); glDisableVertexAttribArray(renderjob_enums::NORMAL); glDisableVertexAttribArray(renderjob_enums::TEXCOORD); glDisableVertexAttribArray(renderjob_enums::MATERIAL_IDX); // Cleanup. glBindVertexArray(0); glUseProgram(0); glBindBufferBase(GL_UNIFORM_BUFFER, renderjob_enums::MATERIAL, 0); } void Renderer::renderGBuffers() { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo.gbuffer); glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); while (!m_render_queue.empty()) { const Entity* current_entity = m_render_queue.front(); m_render_queue.pop(); renderEntity(*current_entity); } } void Renderer::renderPBuffers() { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo.pbuffer); glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); GLuint program_id = m_gbuffer.getRenderJob()->getShaderProgramID(); glUseProgram(program_id); glUniform3fv(glGetUniformLocation(program_id, "viewer_position"), 1, glm::value_ptr(m_camera->m_position)); renderEntity(m_gbuffer); } void gamefw::Renderer::renderPPBuffers() { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo.ppbuffer); glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); renderEntity(m_pbuffer); } <|endoftext|>
<commit_before>//=========================================== // Lumina-DE source code // Copyright (c) 2012-2015, Ken Moore // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #include "LClock.h" #include "LSession.h" #include <LuminaThemes.h> #include <LuminaXDG.h> LClock::LClock(QWidget *parent, QString id, bool horizontal) : LPPlugin(parent, id, horizontal){ button = new QToolButton(this); button->setAutoRaise(true); button->setToolButtonStyle(Qt::ToolButtonTextOnly); button->setStyleSheet("font-weight: bold;"); button->setPopupMode(QToolButton::DelayedPopup); //make sure it runs the update routine first button->setMenu(new QMenu()); connect(button, SIGNAL(clicked()), this, SLOT(openMenu())); connect(button->menu(), SIGNAL(aboutToHide()), this, SIGNAL(MenuClosed())); calendar = new QCalendarWidget(this); calAct = new QWidgetAction(this); calAct->setDefaultWidget(calendar); TZMenu = new QMenu(this); connect(TZMenu, SIGNAL(triggered(QAction*)), this, SLOT(ChangeTZ(QAction*)) ); //Now assemble the menu button->menu()->addAction(calAct); button->menu()->addMenu(TZMenu); this->layout()->setContentsMargins(0,0,0,0); //reserve some space on left/right this->layout()->addWidget(button); //Setup the timer timer = new QTimer(); //Load all the initial settings updateFormats(); LocaleChange(); ThemeChange(); OrientationChange(); //Now connect/start the timer connect(timer,SIGNAL(timeout()), this, SLOT(updateTime()) ); connect(QApplication::instance(), SIGNAL(SessionConfigChanged()), this, SLOT(updateFormats()) ); timer->start(); } LClock::~LClock(){ timer->stop(); delete timer; } void LClock::updateTime(bool adjustformat){ QDateTime CT = QDateTime::currentDateTime(); //Now update the display QString label; QString timelabel; QString datelabel; if(deftime){ timelabel = CT.time().toString(Qt::DefaultLocaleShortDate) ; } else{ timelabel=CT.toString(timefmt); } if(defdate){ datelabel = CT.date().toString(Qt::DefaultLocaleShortDate); } else{ datelabel = CT.toString(datefmt); } if(datetimeorder == "dateonly"){ label = datelabel; button->setToolTip(timelabel); }else if(datetimeorder == "timedate"){ label = timelabel + "\n" + datelabel; button->setToolTip(""); }else if(datetimeorder == "datetime"){ label = datelabel + "\n" + timelabel; button->setToolTip(""); }else{ label = timelabel; button->setToolTip(datelabel); } if( this->layout()->direction() == QBoxLayout::TopToBottom ){ //different routine for vertical text (need newlines instead of spaces) label.replace(" ","\n"); } if(adjustformat){ //Check the font/spacing for the display and adjust as necessary /*double efflines = label.count("\n")+1; //effective lines (with wordwrap) if( (button->fontMetrics().height()*efflines) > button->height() ){ //Force a pixel metric font size to fit everything int szH = qRound( (button->height() - button->fontMetrics().lineSpacing() )/efflines ); //Need to supply a *width* pixel, not a height metric int szW = qRound( (szH*button->fontMetrics().maxWidth())/( (double) button->fontMetrics().height()) ); qDebug() << "Change Clock font:" << button->height() << szH << szW << efflines << button->fontMetrics().height() << button->fontMetrics().lineSpacing(); button->setStyleSheet("font-weight: bold; font-size: "+QString::number(szW)+"px;"); }else{ button->setStyleSheet("font-weight: bold;"); }*/ } button->setText(label); } void LClock::updateFormats(){ qDebug() << "Updating clock format"; timefmt = LSession::handle()->sessionSettings()->value("TimeFormat","").toString(); datefmt = LSession::handle()->sessionSettings()->value("DateFormat","").toString(); deftime = timefmt.simplified().isEmpty(); defdate = datefmt.simplified().isEmpty(); //Adjust the timer interval based on the smallest unit displayed if(deftime){ timer->setInterval(500); } //1/2 second else if(timefmt.contains("z")){ timer->setInterval(1); } //every millisecond (smallest unit) else if(timefmt.contains("s")){ timer->setInterval(500); } //1/2 second else if(timefmt.contains("m")){ timer->setInterval(2000); } //2 seconds else{ timer->setInterval(1000); } //unknown format - use 1 second interval datetimeorder = LSession::handle()->sessionSettings()->value("DateTimeOrder", "timeonly").toString().toLower(); updateTime(true); } void LClock::updateMenu(){ QDateTime cdt = QDateTime::currentDateTime(); TZMenu->setTitle(QString(tr("Time Zone (%1)")).arg(cdt.timeZoneAbbreviation()) ); calendar->showToday(); //make sure the current month is visible calendar->setSelectedDate(QDate::currentDate()); //select the actual date for today } void LClock::openMenu(){ updateMenu(); button->showMenu(); } void LClock::closeMenu(){ button->menu()->hide(); } void LClock::ChangeTZ(QAction *act){ LTHEME::setCustomEnvSetting("TZ",act->whatsThis()); QTimer::singleShot(500, this, SLOT(updateTime()) ); } void LClock::LocaleChange(){ //Refresh all the time zone information TZMenu->clear(); TZMenu->addAction(tr("Use System Time")); TZMenu->addSeparator(); QList<QByteArray> TZList = QTimeZone::availableTimeZoneIds(); //Orgnize time zones for smaller menus (Continent/Country/City) // Note: id = Continent/City QStringList info; for(int i=0; i<TZList.length(); i++){ QTimeZone tz(TZList[i]); if(!QString(tz.id()).contains("/")){ continue; } info << "::::"+QString(tz.id()).section("/",0,0)+"::::"+QLocale::countryToString(tz.country())+"::::"+QString(tz.id()).section("/",1,100).replace("_"," ")+"::::"+QString(tz.id()); } //Now sort alphabetically info.sort(); //Now create the menu tree QString continent, country; //current continent/country QMenu *tmpC=0; //continent menu QMenu *tmpCM=0; //country menu for(int i=0; i<info.length(); i++){ //Check if different continent if(info[i].section("::::",1,1)!=continent){ if(tmpC!=0){ if(tmpCM!=0 && !tmpCM->isEmpty()){ tmpC->addMenu(tmpCM); } if(!tmpC->isEmpty()){ TZMenu->addMenu(tmpC); } } tmpC = new QMenu(this); tmpC->setTitle(info[i].section("::::",1,1)); tmpCM = new QMenu(this); tmpCM->setTitle(info[i].section("::::",2,2)); //Check if different country }else if(info[i].section("::::",2,2)!=country){ if(tmpC!=0 && tmpCM!=0 && !tmpCM->isEmpty()){ tmpC->addMenu(tmpCM); } tmpCM = new QMenu(this); tmpCM->setTitle(info[i].section("::::",2,2)); } //Now create the entry within the country menu if(tmpCM!=0){ QAction *act = new QAction(info[i].section("::::",3,3), this); act->setWhatsThis(info[i].section("::::",4,4) ); tmpCM->addAction(act); } //Save the values for the next run continent = info[i].section("::::",1,1); country = info[i].section("::::",2,2); if(i== info.length()-1){ //last go through - save all menus if(tmpCM!=0 && tmpC!=0 && !tmpCM->isEmpty()){ tmpC->addMenu(tmpCM); } if(tmpC!=0 && !tmpC->isEmpty()){ TZMenu->addMenu(tmpC); } } } //qDebug() << "Found Time Zones:" << TZList.length(); /*QDateTime cur = QDateTime::currentDateTime(); QMenu *tmpCM = 0; QString ccat; //current category QStringList catAbb; for(int i=0; i<TZList.length(); i++){ QTimeZone tmp(TZList[i]); QString abbr = tmp.abbreviation(cur); if(abbr.startsWith("UTC")){ continue; } //skip all the manual options at the end of the list if(QString(tmp.id()).section("/",0,0)!=ccat){ //New category - save the old one and start a new one if(!catAbb.isEmpty()){ catAbb.sort(); QMenu *tmpM = new QMenu(this); tmpM->setTitle(ccat); for(int j=0; j<catAbb.length(); j++){ QAction *act = new QAction(catAbb[j].section("::::",3,3)+" ("+catAbb[j].section("::::",1,1)+")",this); act->setWhatsThis(catAbb[j].section("::::",2,2)); tmpM->addAction(act); } TZMenu->addMenu(tmpM); } ccat = QString(tmp.id()).section("/",0,0); catAbb.clear(); } if(!catAbb.filter("::::"+abbr+"::::").isEmpty()){ continue; } //duplicate timezone/abbreviation for this cat catAbb << "::::"+abbr+"::::"+tmp.id()+"::::"+tmp.displayName(QTimeZone::GenericTime, QTimeZone::LongName); //add new abbreviation to the list } //Now add the last category to the menu if(tmpCM!=0 && !catAbb.isEmpty()){ catAbb.sort(); QMenu *tmpM = new QMenu(this); tmpM->setTitle(ccat); for(int j=0; j<catAbb.length(); j++){ QAction *act = new QAction(catAbb[j].section("::::",3,3)+" ("+catAbb[j].section("::::",1,1)+")",this); act->setWhatsThis(catAbb[j].section("::::",2,2)); tmpM->addAction(act); } TZMenu->addMenu(tmpM); }*/ } void LClock::ThemeChange(){ TZMenu->setIcon(LXDG::findIcon("clock","")); } void LClock::OrientationChange(){ if(this->layout()->direction()==QBoxLayout::LeftToRight){ this->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); button->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); }else{ this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); button->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); } updateTime(true); //re-adjust the font/spacings this->layout()->update(); } <commit_msg>For the clock plugin, add a smarter minimum width based on the time format chosen. This should prevent the clock from changing sizes regularly if the font is not mono-spaced or non-padded seconds/minutes is desired.<commit_after>//=========================================== // Lumina-DE source code // Copyright (c) 2012-2015, Ken Moore // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #include "LClock.h" #include "LSession.h" #include <LuminaThemes.h> #include <LuminaXDG.h> LClock::LClock(QWidget *parent, QString id, bool horizontal) : LPPlugin(parent, id, horizontal){ button = new QToolButton(this); button->setAutoRaise(true); button->setToolButtonStyle(Qt::ToolButtonTextOnly); button->setStyleSheet("font-weight: bold;"); button->setPopupMode(QToolButton::DelayedPopup); //make sure it runs the update routine first button->setMenu(new QMenu()); connect(button, SIGNAL(clicked()), this, SLOT(openMenu())); connect(button->menu(), SIGNAL(aboutToHide()), this, SIGNAL(MenuClosed())); calendar = new QCalendarWidget(this); calAct = new QWidgetAction(this); calAct->setDefaultWidget(calendar); TZMenu = new QMenu(this); connect(TZMenu, SIGNAL(triggered(QAction*)), this, SLOT(ChangeTZ(QAction*)) ); //Now assemble the menu button->menu()->addAction(calAct); button->menu()->addMenu(TZMenu); this->layout()->setContentsMargins(0,0,0,0); //reserve some space on left/right this->layout()->addWidget(button); //Setup the timer timer = new QTimer(); //Load all the initial settings updateFormats(); LocaleChange(); ThemeChange(); OrientationChange(); //Now connect/start the timer connect(timer,SIGNAL(timeout()), this, SLOT(updateTime()) ); connect(QApplication::instance(), SIGNAL(SessionConfigChanged()), this, SLOT(updateFormats()) ); timer->start(); } LClock::~LClock(){ timer->stop(); delete timer; } void LClock::updateTime(bool adjustformat){ QDateTime CT = QDateTime::currentDateTime(); //Now update the display QString label; QString timelabel; QString datelabel; if(deftime){ timelabel = CT.time().toString(Qt::DefaultLocaleShortDate) ; } else{ timelabel=CT.toString(timefmt); } if(defdate){ datelabel = CT.date().toString(Qt::DefaultLocaleShortDate); } else{ datelabel = CT.toString(datefmt); } if(datetimeorder == "dateonly"){ label = datelabel; button->setToolTip(timelabel); }else if(datetimeorder == "timedate"){ label = timelabel + "\n" + datelabel; button->setToolTip(""); }else if(datetimeorder == "datetime"){ label = datelabel + "\n" + timelabel; button->setToolTip(""); }else{ label = timelabel; button->setToolTip(datelabel); } if( this->layout()->direction() == QBoxLayout::TopToBottom ){ //different routine for vertical text (need newlines instead of spaces) label.replace(" ","\n"); } if(adjustformat){ //Check the font/spacing for the display and adjust as necessary /*double efflines = label.count("\n")+1; //effective lines (with wordwrap) if( (button->fontMetrics().height()*efflines) > button->height() ){ //Force a pixel metric font size to fit everything int szH = qRound( (button->height() - button->fontMetrics().lineSpacing() )/efflines ); //Need to supply a *width* pixel, not a height metric int szW = qRound( (szH*button->fontMetrics().maxWidth())/( (double) button->fontMetrics().height()) ); qDebug() << "Change Clock font:" << button->height() << szH << szW << efflines << button->fontMetrics().height() << button->fontMetrics().lineSpacing(); button->setStyleSheet("font-weight: bold; font-size: "+QString::number(szW)+"px;"); }else{ button->setStyleSheet("font-weight: bold;"); }*/ } button->setText(label); } void LClock::updateFormats(){ qDebug() << "Updating clock format"; timefmt = LSession::handle()->sessionSettings()->value("TimeFormat","").toString(); datefmt = LSession::handle()->sessionSettings()->value("DateFormat","").toString(); deftime = timefmt.simplified().isEmpty(); defdate = datefmt.simplified().isEmpty(); this->setMinimumSize(button->fontMetrics().width(timefmt+"MMM")+10, 5); //Adjust the timer interval based on the smallest unit displayed if(deftime){ timer->setInterval(500); } //1/2 second else if(timefmt.contains("z")){ timer->setInterval(1); } //every millisecond (smallest unit) else if(timefmt.contains("s")){ timer->setInterval(500); } //1/2 second else if(timefmt.contains("m")){ timer->setInterval(2000); } //2 seconds else{ timer->setInterval(1000); } //unknown format - use 1 second interval datetimeorder = LSession::handle()->sessionSettings()->value("DateTimeOrder", "timeonly").toString().toLower(); updateTime(true); } void LClock::updateMenu(){ QDateTime cdt = QDateTime::currentDateTime(); TZMenu->setTitle(QString(tr("Time Zone (%1)")).arg(cdt.timeZoneAbbreviation()) ); calendar->showToday(); //make sure the current month is visible calendar->setSelectedDate(QDate::currentDate()); //select the actual date for today } void LClock::openMenu(){ updateMenu(); button->showMenu(); } void LClock::closeMenu(){ button->menu()->hide(); } void LClock::ChangeTZ(QAction *act){ LTHEME::setCustomEnvSetting("TZ",act->whatsThis()); QTimer::singleShot(500, this, SLOT(updateTime()) ); } void LClock::LocaleChange(){ //Refresh all the time zone information TZMenu->clear(); TZMenu->addAction(tr("Use System Time")); TZMenu->addSeparator(); QList<QByteArray> TZList = QTimeZone::availableTimeZoneIds(); //Orgnize time zones for smaller menus (Continent/Country/City) // Note: id = Continent/City QStringList info; for(int i=0; i<TZList.length(); i++){ QTimeZone tz(TZList[i]); if(!QString(tz.id()).contains("/")){ continue; } info << "::::"+QString(tz.id()).section("/",0,0)+"::::"+QLocale::countryToString(tz.country())+"::::"+QString(tz.id()).section("/",1,100).replace("_"," ")+"::::"+QString(tz.id()); } //Now sort alphabetically info.sort(); //Now create the menu tree QString continent, country; //current continent/country QMenu *tmpC=0; //continent menu QMenu *tmpCM=0; //country menu for(int i=0; i<info.length(); i++){ //Check if different continent if(info[i].section("::::",1,1)!=continent){ if(tmpC!=0){ if(tmpCM!=0 && !tmpCM->isEmpty()){ tmpC->addMenu(tmpCM); } if(!tmpC->isEmpty()){ TZMenu->addMenu(tmpC); } } tmpC = new QMenu(this); tmpC->setTitle(info[i].section("::::",1,1)); tmpCM = new QMenu(this); tmpCM->setTitle(info[i].section("::::",2,2)); //Check if different country }else if(info[i].section("::::",2,2)!=country){ if(tmpC!=0 && tmpCM!=0 && !tmpCM->isEmpty()){ tmpC->addMenu(tmpCM); } tmpCM = new QMenu(this); tmpCM->setTitle(info[i].section("::::",2,2)); } //Now create the entry within the country menu if(tmpCM!=0){ QAction *act = new QAction(info[i].section("::::",3,3), this); act->setWhatsThis(info[i].section("::::",4,4) ); tmpCM->addAction(act); } //Save the values for the next run continent = info[i].section("::::",1,1); country = info[i].section("::::",2,2); if(i== info.length()-1){ //last go through - save all menus if(tmpCM!=0 && tmpC!=0 && !tmpCM->isEmpty()){ tmpC->addMenu(tmpCM); } if(tmpC!=0 && !tmpC->isEmpty()){ TZMenu->addMenu(tmpC); } } } } void LClock::ThemeChange(){ TZMenu->setIcon(LXDG::findIcon("clock","")); } void LClock::OrientationChange(){ if(this->layout()->direction()==QBoxLayout::LeftToRight){ this->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); button->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); }else{ this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); button->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); } updateTime(true); //re-adjust the font/spacings this->layout()->update(); } <|endoftext|>
<commit_before>/* Adapted from diffdrive gazebo plugin. Copyright (c) 2010, Daniel Hewlett, Antons Rebguns 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 <organization> 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 Antons Rebguns <email> ''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 Antons Rebguns <email> 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 <algorithm> #include <assert.h> #include <paladin_drcsim_plugins/joint_actuation_plugin.h> #include <common/common.h> #include <math/gzmath.h> #include <physics/physics.h> #include <sdf/sdf.h> #include <ros/ros.h> #include <tf/transform_broadcaster.h> #include <tf/transform_listener.h> #include <geometry_msgs/Twist.h> #include <nav_msgs/Odometry.h> #include <boost/bind.hpp> namespace gazebo { // Constructor JointActuationPlugin::JointActuationPlugin() { } // Destructor JointActuationPlugin::~JointActuationPlugin() { // Finalize the controller alive_ = false; queue_.clear(); queue_.disable(); rosnode_->shutdown(); callback_queue_thread_.join(); delete rosnode_; } // Load the controller void JointActuationPlugin::Load(physics::ModelPtr _parent, sdf::ElementPtr _sdf) { this->parent = _parent; this->world = _parent->GetWorld(); gzdbg << "plugin parent sensor name: " << parent->GetName() << "\n"; if (!this->parent) { gzthrow("Joint Actuation controller requires a Model as its parent"); } this->robotNamespace = ""; if (_sdf->HasElement("robotNamespace")) { this->robotNamespace = _sdf->GetElement("robotNamespace")->GetValueString() + "/"; } if (!_sdf->HasElement("topicName")) { ROS_WARN("Joint Actuation plugin missing <topicName>, defaults to ACTUATOR_CMDS"); this->topicName = "ACTUATOR_CMDS"; } else { this->topicName = _sdf->GetElement("topicName")->GetValueString(); } alive_ = true; ActuationCmdStruc zero_cmd; zero_cmd.value = 0; zero_cmd.start_time = 0; zero_cmd.duration = 0; zero_cmd.on_flag = false; for (unsigned int i = 0; i < this->parent->GetJointCount(); i ++) { joint = this->parent->GetJoint(i); std::string joint_name = joint->GetName(); _joint_actuation_values.insert(make_pair(joint_name, zero_cmd)); } // Initialize the ROS node and subscribe to joint actuation command topic int argc = 0; char** argv = NULL; ros::init(argc, argv, "joint_actuation_plugin", ros::init_options::NoSigintHandler | ros::init_options::AnonymousName); rosnode_ = new ros::NodeHandle(this->robotNamespace); ROS_INFO("starting joint_actuation_plugin in ns: %s", this->robotNamespace.c_str()); // ROS: Subscribe to the joint actuation command topic ros::SubscribeOptions so = ros::SubscribeOptions::create<atlas_gazebo_msgs::ActuatorCmd>(topicName, 1, boost::bind(&JointActuationPlugin::actuationCmdCallback, this, _1), ros::VoidPtr(), &queue_); sub_ = rosnode_->subscribe(so); // start custom queue for diff drive this->callback_queue_thread_ = boost::thread(boost::bind(&JointActuationPlugin::QueueThread, this)); // listen to the update event (broadcast every simulation iteration) this->updateConnection = event::Events::ConnectWorldUpdateStart(boost::bind(&JointActuationPlugin::UpdateChild, this)); } // Update the controller void JointActuationPlugin::UpdateChild() { //update forces of all joints that are active //if (this->world->IsPaused()) // this->world->SetPaused(false); // Loop through all Joints std::map<std::string, ActuationCmdStruc>::iterator it; for (unsigned int i = 0; i < this->parent->GetJointCount(); i ++) { std::string joint_name = this->parent->GetJoint(i)->GetName(); it=_joint_actuation_values.find(joint_name); // both time_now, duration and start_time must also in simTime. double time_now = this->world->GetSimTime().Double(); lock.lock(); double duration = it->second.duration; // in seconds double start_time = it->second.start_time; bool on_flag = it->second.on_flag; lock.unlock(); if(on_flag==true) // if flag is on { if (time_now <= start_time + duration) { this->parent->GetJoint(i)->SetForce(0,it->second.value); } else // duration has expired, so clear forces. (duration is reset if a new torque command is received) { //clear force this->parent->GetJoint(i)->SetForce(0,0); lock.lock(); it->second.on_flag = false; lock.unlock(); } } } // end for loop }// end update child. void JointActuationPlugin::actuationCmdCallback(const atlas_gazebo_msgs::ActuatorCmd::ConstPtr& cmd_msg) { //Double check that the msg is for the correct robot name (this->parent->getName()). if(cmd_msg->robot_name == this->parent->GetName()) { lock.lock(); int64_t t = cmd_msg->header.stamp.toNSec(); double msg_start_time = t*1e-9; // from nsec to sec //double msg_start_time = this->world->GetSimTime().Double(); // All timing is done relative to sim time. //for all joints in message update ActuationCmd Buffer. for (std::vector<int>::size_type i = 0; i != cmd_msg->actuator_name.size(); i++) { std::string joint_name = cmd_msg->actuator_name[i]; std::map<std::string, ActuationCmdStruc>::iterator it; it=_joint_actuation_values.find(joint_name); ActuationCmdStruc act_cmd; act_cmd.start_time = msg_start_time; // sim time when msg was received. act_cmd.value = cmd_msg->actuator_effort[i]; act_cmd.duration = cmd_msg->effort_duration[i]; act_cmd.on_flag = true; it->second = act_cmd; }// end for lock.unlock(); } } void JointActuationPlugin::QueueThread() { static const double timeout = 0.01; while (alive_ && rosnode_->ok()) { queue_.callAvailable(ros::WallDuration(timeout)); } } GZ_REGISTER_MODEL_PLUGIN(JointActuationPlugin) } <commit_msg>adding transport hints to joint actuation subscribe to enable tcpNodelay option and also increased timeout in callback queue to 0.1 from 0.01<commit_after>/* Adapted from diffdrive gazebo plugin. Copyright (c) 2010, Daniel Hewlett, Antons Rebguns 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 <organization> 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 Antons Rebguns <email> ''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 Antons Rebguns <email> 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 <algorithm> #include <assert.h> #include <paladin_drcsim_plugins/joint_actuation_plugin.h> #include <common/common.h> #include <math/gzmath.h> #include <physics/physics.h> #include <sdf/sdf.h> #include <ros/ros.h> #include <tf/transform_broadcaster.h> #include <tf/transform_listener.h> #include <geometry_msgs/Twist.h> #include <nav_msgs/Odometry.h> #include <boost/bind.hpp> namespace gazebo { // Constructor JointActuationPlugin::JointActuationPlugin() { } // Destructor JointActuationPlugin::~JointActuationPlugin() { // Finalize the controller alive_ = false; queue_.clear(); queue_.disable(); rosnode_->shutdown(); callback_queue_thread_.join(); delete rosnode_; } // Load the controller void JointActuationPlugin::Load(physics::ModelPtr _parent, sdf::ElementPtr _sdf) { this->parent = _parent; this->world = _parent->GetWorld(); gzdbg << "plugin parent sensor name: " << parent->GetName() << "\n"; if (!this->parent) { gzthrow("Joint Actuation controller requires a Model as its parent"); } this->robotNamespace = ""; if (_sdf->HasElement("robotNamespace")) { this->robotNamespace = _sdf->GetElement("robotNamespace")->GetValueString() + "/"; } if (!_sdf->HasElement("topicName")) { ROS_WARN("Joint Actuation plugin missing <topicName>, defaults to ACTUATOR_CMDS"); this->topicName = "ACTUATOR_CMDS"; } else { this->topicName = _sdf->GetElement("topicName")->GetValueString(); } alive_ = true; ActuationCmdStruc zero_cmd; zero_cmd.value = 0; zero_cmd.start_time = 0; zero_cmd.duration = 0; zero_cmd.on_flag = false; for (unsigned int i = 0; i < this->parent->GetJointCount(); i ++) { joint = this->parent->GetJoint(i); std::string joint_name = joint->GetName(); _joint_actuation_values.insert(make_pair(joint_name, zero_cmd)); } // Initialize the ROS node and subscribe to joint actuation command topic int argc = 0; char** argv = NULL; ros::init(argc, argv, "joint_actuation_plugin", ros::init_options::NoSigintHandler | ros::init_options::AnonymousName); rosnode_ = new ros::NodeHandle(this->robotNamespace); ROS_INFO("starting joint_actuation_plugin in ns: %s", this->robotNamespace.c_str()); // ROS: Subscribe to the joint actuation command topic ros::SubscribeOptions so = ros::SubscribeOptions::create<atlas_gazebo_msgs::ActuatorCmd>(topicName, 1, boost::bind(&JointActuationPlugin::actuationCmdCallback, this, _1), ros::VoidPtr(), &queue_); so.transport_hints = ros::TransportHints() .unreliable() .maxDatagramSize(1000) .tcpNoDelay(); sub_ = rosnode_->subscribe(so); // start custom queue for diff drive this->callback_queue_thread_ = boost::thread(boost::bind(&JointActuationPlugin::QueueThread, this)); // listen to the update event (broadcast every simulation iteration) this->updateConnection = event::Events::ConnectWorldUpdateStart(boost::bind(&JointActuationPlugin::UpdateChild, this)); } // Update the controller void JointActuationPlugin::UpdateChild() { //update forces of all joints that are active //if (this->world->IsPaused()) // this->world->SetPaused(false); // Loop through all Joints std::map<std::string, ActuationCmdStruc>::iterator it; for (unsigned int i = 0; i < this->parent->GetJointCount(); i ++) { std::string joint_name = this->parent->GetJoint(i)->GetName(); it=_joint_actuation_values.find(joint_name); // both time_now, duration and start_time must also in simTime. double time_now = this->world->GetSimTime().Double(); lock.lock(); double duration = it->second.duration; // in seconds double start_time = it->second.start_time; bool on_flag = it->second.on_flag; lock.unlock(); if(on_flag==true) // if flag is on { if (time_now <= start_time + duration) { this->parent->GetJoint(i)->SetForce(0,it->second.value); } else // duration has expired, so clear forces. (duration is reset if a new torque command is received) { //clear force this->parent->GetJoint(i)->SetForce(0,0); lock.lock(); it->second.on_flag = false; lock.unlock(); } } } // end for loop }// end update child. void JointActuationPlugin::actuationCmdCallback(const atlas_gazebo_msgs::ActuatorCmd::ConstPtr& cmd_msg) { //Double check that the msg is for the correct robot name (this->parent->getName()). if(cmd_msg->robot_name == this->parent->GetName()) { lock.lock(); int64_t t = cmd_msg->header.stamp.toNSec(); double msg_start_time = t*1e-9; // from nsec to sec //double msg_start_time = this->world->GetSimTime().Double(); // All timing is done relative to sim time. //for all joints in message update ActuationCmd Buffer. for (std::vector<int>::size_type i = 0; i != cmd_msg->actuator_name.size(); i++) { std::string joint_name = cmd_msg->actuator_name[i]; std::map<std::string, ActuationCmdStruc>::iterator it; it=_joint_actuation_values.find(joint_name); ActuationCmdStruc act_cmd; act_cmd.start_time = msg_start_time; // sim time when msg was received. act_cmd.value = cmd_msg->actuator_effort[i]; act_cmd.duration = cmd_msg->effort_duration[i]; act_cmd.on_flag = true; it->second = act_cmd; }// end for lock.unlock(); } } void JointActuationPlugin::QueueThread() { static const double timeout = 0.1; while (alive_ && rosnode_->ok()) { queue_.callAvailable(ros::WallDuration(timeout)); } } GZ_REGISTER_MODEL_PLUGIN(JointActuationPlugin) } <|endoftext|>
<commit_before>/* * Unit tests for the TTSampleMatrix Object for Jamoma DSP * Copyright © 2012, Tim Place & Nathan Wolek * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTSampleMatrix.h" TTErr TTSampleMatrix::test(TTValue& returnedTestInfo) { int errorCount = 0; int testAssertionCount = 0; // for tests TTUInt16 numChannels = 2; TTUInt16 numSamples = 50000; TTFloat32 duration = 1500; TTUInt32 test1Return, test2Return, test7Return, test8Return; TTFloat32 test3Return, test6Return; TTTestLog("Test resizing of the SampleMatrix..."); // TEST 1: can we set the number of channels? this->setAttributeValue(TT("numChannels"), numChannels); this->getAttributeValue(TT("numChannels"), test1Return); TTBoolean result = { numChannels == test1Return }; TTTestAssertion("numChannels is set properly", result, testAssertionCount, errorCount); if(!result) { TTTestLog("Expected a value of %i, but returned value was %i", numChannels, test1Return); } // TEST 2: can we set the number of samples? this->setAttributeValue(TT("lengthInSamples"), numSamples); this->getAttributeValue(TT("lengthInSamples"), test2Return); TTBoolean result2 = { numSamples == test2Return }; TTTestAssertion("lengthInSamples is set properly", result2, testAssertionCount, errorCount); if(!result2) { TTTestLog("Expected a value of %i, but returned value was %i", numSamples, test2Return); } // TEST 3: is the length in ms computed properly after setting length in samples? TTFloat32 computedDuration3 = (numSamples / this->mSampleRate) * 1000.; this->getAttributeValue(TT("length"), test3Return); TTBoolean result3 = TTTestFloatEquivalence(computedDuration3, test3Return); TTTestAssertion("after lengthInSamples is set, length (in ms) is correct", result3, testAssertionCount, errorCount); if(!result3) { TTTestLog("Expected a value of %f, but returned value was %f", computedDuration3, test3Return); } // TEST 4: is the matrix of samples the expected size? (lifted from TTMatrix.test.cpp) TTUInt32 computedDataSize4 = sizeof(TTFloat64) * numChannels * numSamples; TTBoolean result4 = { computedDataSize4 == this->mDataSize }; TTTestAssertion("correct amount of data storage calculated", result4, testAssertionCount, errorCount); if(!result4) { TTTestLog("Expected a value of %i, but returned value was %i", computedDataSize4, this->mDataSize); } // TEST 5: Is the component stride right? (lifted from TTMatrix.test.cpp) TTBoolean result5 = { sizeof(TTFloat64) == this->mComponentStride }; TTTestAssertion("correct byte-stride between values calculated", result5, testAssertionCount, errorCount); if(!result5) { TTTestLog("Expected a value of %i, but returned value was %i", sizeof(TTFloat64), this->mComponentStride); } // TEST 6: can we set the length in milliseconds? this->setAttributeValue(TT("length"), duration); this->getAttributeValue(TT("length"), test6Return); TTBoolean result6 = TTTestFloatEquivalence(duration, test6Return); TTTestAssertion("length (in ms) is set properly", result6, testAssertionCount, errorCount); if(!result6) { TTTestLog("Expected a value of %f, but returned value was %f", duration, test6Return); } // TEST 7: is the length in samples computed properly after setting length in ms? TTUInt32 computedSamples7 = TTUInt32(duration * this->mSampleRate * 0.001); this->getAttributeValue(TT("lengthInSamples"), test7Return); TTBoolean result7 = { computedSamples7 == test7Return }; TTTestAssertion("after length (in ms) is set, lengthInSamples is correct", result7, testAssertionCount, errorCount); if(!result7) { TTTestLog("Expected a value of %i, but returned value was %i", computedSamples7, test7Return); } // TEST 8 (REPEAT TEST 4 WITH NEW SIZE): is the matrix of samples the expected size? TTUInt32 computedDataSize8 = sizeof(TTFloat64) * numChannels * test7Return; TTBoolean result8 = { computedDataSize8 == this->mDataSize }; TTTestAssertion("correct amount of data storage calculated with new length", result8, testAssertionCount, errorCount); if(!result8) { TTTestLog("Expected a value of %i, but returned value was %i", computedDataSize8, this->mDataSize); } /* int badSampleCount = 0; TTAudioObjectPtr samplematrixObject = NULL; TTAudioSignalPtr input = NULL; TTAudioSignalPtr output = NULL; // TODO: test filling with sine wave // TODO: test scaling (applying gain) // TODO: test normalizing (with optional arg, and also without an optional arg) TTObjectInstantiate(TT("samplematrix"), &samplematrixObject, kTTVal1); TTObjectRelease(&input); TTObjectRelease(&output); TTObjectRelease(&samplematrixObject); */ // Wrap up the test results to pass back to whoever called this test return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); } <commit_msg>SampleMatrix: built tests for interpolation between samples<commit_after>/* * Unit tests for the TTSampleMatrix Object for Jamoma DSP * Copyright © 2012, Tim Place & Nathan Wolek * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTSampleMatrix.h" TTErr TTSampleMatrix::test(TTValue& returnedTestInfo) { int errorCount = 0; int testAssertionCount = 0; // for tests TTUInt16 numChannels = 2; TTUInt16 numSamples = 50000; TTFloat32 duration = 1500; TTUInt32 test9Index = 10; TTUInt32 test10Index = 11; TTUInt32 test1Return, test2Return, test7Return, test8Return; TTFloat32 test3Return, test6Return; TTSampleValue test9Return, test10Return, test11Return; TTTestLog("Test resizing of the SampleMatrix..."); // TEST 1: can we set the number of channels? this->setAttributeValue(TT("numChannels"), numChannels); this->getAttributeValue(TT("numChannels"), test1Return); TTBoolean result = { numChannels == test1Return }; TTTestAssertion("numChannels is set properly", result, testAssertionCount, errorCount); if(!result) { TTTestLog("Expected a value of %i, but returned value was %i", numChannels, test1Return); } // TEST 2: can we set the number of samples? this->setAttributeValue(TT("lengthInSamples"), numSamples); this->getAttributeValue(TT("lengthInSamples"), test2Return); TTBoolean result2 = { numSamples == test2Return }; TTTestAssertion("lengthInSamples is set properly", result2, testAssertionCount, errorCount); if(!result2) { TTTestLog("Expected a value of %i, but returned value was %i", numSamples, test2Return); } // TEST 3: is the length in ms computed properly after setting length in samples? TTFloat32 computedDuration3 = (numSamples / this->mSampleRate) * 1000.; this->getAttributeValue(TT("length"), test3Return); TTBoolean result3 = TTTestFloatEquivalence(computedDuration3, test3Return); TTTestAssertion("after lengthInSamples is set, length (in ms) is correct", result3, testAssertionCount, errorCount); if(!result3) { TTTestLog("Expected a value of %f, but returned value was %f", computedDuration3, test3Return); } // TEST 4: is the matrix of samples the expected size? (lifted from TTMatrix.test.cpp) TTUInt32 computedDataSize4 = sizeof(TTFloat64) * numChannels * numSamples; TTBoolean result4 = { computedDataSize4 == this->mDataSize }; TTTestAssertion("correct amount of data storage calculated", result4, testAssertionCount, errorCount); if(!result4) { TTTestLog("Expected a value of %i, but returned value was %i", computedDataSize4, this->mDataSize); } // TEST 5: Is the component stride right? (lifted from TTMatrix.test.cpp) TTBoolean result5 = { sizeof(TTFloat64) == this->mComponentStride }; TTTestAssertion("correct byte-stride between values calculated", result5, testAssertionCount, errorCount); if(!result5) { TTTestLog("Expected a value of %i, but returned value was %i", sizeof(TTFloat64), this->mComponentStride); } // TEST 6: can we set the length in milliseconds? this->setAttributeValue(TT("length"), duration); this->getAttributeValue(TT("length"), test6Return); TTBoolean result6 = TTTestFloatEquivalence(duration, test6Return); TTTestAssertion("length (in ms) is set properly", result6, testAssertionCount, errorCount); if(!result6) { TTTestLog("Expected a value of %f, but returned value was %f", duration, test6Return); } // TEST 7: is the length in samples computed properly after setting length in ms? TTUInt32 computedSamples7 = TTUInt32(duration * this->mSampleRate * 0.001); this->getAttributeValue(TT("lengthInSamples"), test7Return); TTBoolean result7 = { computedSamples7 == test7Return }; TTTestAssertion("after length (in ms) is set, lengthInSamples is correct", result7, testAssertionCount, errorCount); if(!result7) { TTTestLog("Expected a value of %i, but returned value was %i", computedSamples7, test7Return); } // TEST 8 (REPEAT TEST 4 WITH NEW SIZE): is the matrix of samples the expected size? TTUInt32 computedDataSize8 = sizeof(TTFloat64) * numChannels * test7Return; TTBoolean result8 = { computedDataSize8 == this->mDataSize }; TTTestAssertion("correct amount of data storage calculated with new length", result8, testAssertionCount, errorCount); if(!result8) { TTTestLog("Expected a value of %i, but returned value was %i", computedDataSize8, this->mDataSize); } // TEST 9 & 10: set the value of two consecutive samples TTSampleValue pokeValue9 = TTRandom64(); TTSampleValue pokeValue10 = TTRandom64(); this->poke(test9Index, 1, pokeValue9); this->poke(test10Index, 1, pokeValue10); this->peek(test9Index, 1, test9Return); this->peek(test10Index, 1, test10Return); TTBoolean result9 = { pokeValue9 == test9Return }; TTTestAssertion("set value one of two consecutive samples", result9, testAssertionCount, errorCount); if(!result9) { TTTestLog("Expected a value of %f, but returned value was %f", pokeValue9, test9Return); } TTBoolean result10 = { pokeValue10 == test10Return }; TTTestAssertion("set value two of two consecutive samples", result10, testAssertionCount, errorCount); if(!result10) { TTTestLog("Expected a value of %f, but returned value was %f", pokeValue10, test10Return); } // TEST 11: test for interpolation between two consecutive samples TTFloat64 computedInterpFraction = TTRandom64(); TTFloat64 computedInterpIndex = test9Index + computedInterpFraction; TTSampleValue computedInterpValue11 = (computedInterpFraction * pokeValue9) + ((1.0 - computedInterpFraction) * pokeValue10); this->peeki(computedInterpIndex, 1, test11Return); TTBoolean result11 = TTTestFloatEquivalence(computedInterpValue11, test11Return); TTTestAssertion("interpolate between two consecutive samples", result11, testAssertionCount, errorCount); if(!result11) { TTTestLog("Expected a value of %f, but returned value was %f", computedInterpValue11, test11Return); } /* int badSampleCount = 0; TTAudioObjectPtr samplematrixObject = NULL; TTAudioSignalPtr input = NULL; TTAudioSignalPtr output = NULL; // TODO: test filling with sine wave // TODO: test scaling (applying gain) // TODO: test normalizing (with optional arg, and also without an optional arg) TTObjectInstantiate(TT("samplematrix"), &samplematrixObject, kTTVal1); TTObjectRelease(&input); TTObjectRelease(&output); TTObjectRelease(&samplematrixObject); */ // Wrap up the test results to pass back to whoever called this test return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); } <|endoftext|>
<commit_before>#ifndef __JSON_HPP__ #define __JSON_HPP__ #include <cctype> #include <string> #include <vector> #include <regex> namespace JSON { using namespace std; struct Error {}; struct SyntaxError : public Error {}; struct LoadError : public Error {}; struct AccessError : public Error {}; template<typename _Value, char const ..._szName> struct Field { static char const s_szName; typedef _Value Type; }; template<char const ..._sz> struct FieldName {}; template<typename _Name, typename ..._Fields> struct GetFieldType {}; template<typename _Value, char const ..._szName, typename ..._OtherFields> struct GetFieldType<FieldName<_szName...>, Field<_Value, _szName...>, _OtherFields...> { typedef _Value Type; }; template<char const ..._szFieldName, typename _FirstField, typename ..._OtherFields> struct GetFieldType<FieldName<_szFieldName...>, _FirstField, _OtherFields...> { typedef typename GetFieldType<FieldName<_szFieldName...>, _OtherFields...>::Type Type; }; template<typename _Value, char const ..._szName> char const Field<_Value, _szName...>::s_szName = { _szName... }; template<typename ..._Fields> struct Object {}; template<typename _Field, typename ..._Fields> struct Getter {}; template<typename _Value, char const ..._szName, typename ..._OtherFields> struct Getter<Field<_Value, _szName...>, Field<_Value, _szName...>, _OtherFields...> { static _Value &Get(Object<Field<_Value, _szName...>, _OtherFields...> &rObject) { return rObject.m_Value; } static _Value const &Get(Object<Field<_Value, _szName...>, _OtherFields...> const &rObject) { return rObject.m_Value; } }; template<typename _Value, char const ..._szName, typename _FirstField, typename ..._OtherFields> struct Getter<Field<_Value, _szName...>, _FirstField, _OtherFields...> { static _Value &Get(Object<_FirstField, _OtherFields...> &rObject) { return Getter<Field<_Value, _szName...>, _OtherFields...>::Get(rObject); } static _Value const &Get(Object<_FirstField, _OtherFields...> const &rObject) { return Getter<Field<_Value, _szName...>, _FirstField, _OtherFields...>::Get(rObject); } }; template<> struct Object<> { Object() {} virtual ~Object() {} }; template<typename _Value, char const ..._szName, typename ..._OtherFields> struct Object<Field<_Value, _szName...>, _OtherFields...> : public Object<_OtherFields...> { static char const s_szName[]; _Value m_Value; Object() {} virtual ~Object() {} template<char const ..._szFieldName> typename GetFieldType<FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Type &Get() { return Getter<Field<_Value, _szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Get(*this); } template<char const ..._szFieldName> typename GetFieldType<FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Type const &Get() const { return Getter<Field<_Value, _szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Get(*this); } }; template<typename _Value, char const ..._szName, typename ..._OtherFields> char const Object<Field<_Value, _szName...>, _OtherFields...>::s_szName[] = { _szName... }; template<typename _Type> struct Loader { static _Type Load(istream &ris); }; template<> struct Loader<nullptr_t> { static nullptr_t Load(istream &ris) { // TODO throw Error(); } }; template<> struct Loader<bool> { static bool Load(istream &ris) { // TODO throw Error(); } }; template<> struct Loader<int> { static int Load(istream &ris) { // TODO throw Error(); } }; template<> struct Loader<unsigned int> { static unsigned int Load(istream &ris) { // TODO throw Error(); } }; template<> struct Loader<double> { static double Load(istream &ris) { // TODO throw Error(); } }; template<> struct Loader<string> { static string Load(istream &ris) { // TODO throw Error(); } }; template<typename ..._Fields> struct Loader<Object<_Fields...>> { static Object<_Fields...> Load(istream &ris) { // TODO throw Error(); } }; template<typename _Element> struct Loader<vector<_Element>> { static vector<_Element> Load(istream &ris) { // TODO throw Error(); } }; template<typename _Type> _Type Load(istream &ris) { return Loader<_Type>::Load(ris); } } #define UNPACK(sz) (sz)[0], ((sz)[0] > 0) ? UNPACK((sz) + 1) : 0 #endif <commit_msg>GetFieldType -> FieldType<commit_after>#ifndef __JSON_HPP__ #define __JSON_HPP__ #include <cctype> #include <string> #include <vector> #include <regex> namespace JSON { using namespace std; struct Error {}; struct SyntaxError : public Error {}; struct LoadError : public Error {}; struct AccessError : public Error {}; template<typename _Value, char const ..._szName> struct Field { static char const s_szName; typedef _Value Type; }; template<char const ..._sz> struct FieldName {}; template<typename _Name, typename ..._Fields> struct FieldType {}; template<typename _Value, char const ..._szName, typename ..._OtherFields> struct FieldType<FieldName<_szName...>, Field<_Value, _szName...>, _OtherFields...> { typedef _Value Type; }; template<char const ..._szFieldName, typename _FirstField, typename ..._OtherFields> struct FieldType<FieldName<_szFieldName...>, _FirstField, _OtherFields...> { typedef typename FieldType<FieldName<_szFieldName...>, _OtherFields...>::Type Type; }; template<typename _Value, char const ..._szName> char const Field<_Value, _szName...>::s_szName = { _szName... }; template<typename ..._Fields> struct Object {}; template<typename _Field, typename ..._Fields> struct Getter {}; template<typename _Value, char const ..._szName, typename ..._OtherFields> struct Getter<Field<_Value, _szName...>, Field<_Value, _szName...>, _OtherFields...> { static _Value &Get(Object<Field<_Value, _szName...>, _OtherFields...> &rObject) { return rObject.m_Value; } static _Value const &Get(Object<Field<_Value, _szName...>, _OtherFields...> const &rObject) { return rObject.m_Value; } }; template<typename _Value, char const ..._szName, typename _FirstField, typename ..._OtherFields> struct Getter<Field<_Value, _szName...>, _FirstField, _OtherFields...> { static _Value &Get(Object<_FirstField, _OtherFields...> &rObject) { return Getter<Field<_Value, _szName...>, _OtherFields...>::Get(rObject); } static _Value const &Get(Object<_FirstField, _OtherFields...> const &rObject) { return Getter<Field<_Value, _szName...>, _FirstField, _OtherFields...>::Get(rObject); } }; template<> struct Object<> { Object() {} virtual ~Object() {} }; template<typename _Value, char const ..._szName, typename ..._OtherFields> struct Object<Field<_Value, _szName...>, _OtherFields...> : public Object<_OtherFields...> { static char const s_szName[]; _Value m_Value; Object() {} virtual ~Object() {} template<char const ..._szFieldName> typename FieldType<FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Type &Get() { return Getter<Field<_Value, _szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Get(*this); } template<char const ..._szFieldName> typename FieldType<FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Type const &Get() const { return Getter<Field<_Value, _szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Get(*this); } }; template<typename _Value, char const ..._szName, typename ..._OtherFields> char const Object<Field<_Value, _szName...>, _OtherFields...>::s_szName[] = { _szName... }; template<typename _Type> struct Loader { static _Type Load(istream &ris); }; template<> struct Loader<nullptr_t> { static nullptr_t Load(istream &ris) { // TODO throw Error(); } }; template<> struct Loader<bool> { static bool Load(istream &ris) { // TODO throw Error(); } }; template<> struct Loader<int> { static int Load(istream &ris) { // TODO throw Error(); } }; template<> struct Loader<unsigned int> { static unsigned int Load(istream &ris) { // TODO throw Error(); } }; template<> struct Loader<double> { static double Load(istream &ris) { // TODO throw Error(); } }; template<> struct Loader<string> { static string Load(istream &ris) { // TODO throw Error(); } }; template<typename ..._Fields> struct Loader<Object<_Fields...>> { static Object<_Fields...> Load(istream &ris) { // TODO throw Error(); } }; template<typename _Element> struct Loader<vector<_Element>> { static vector<_Element> Load(istream &ris) { // TODO throw Error(); } }; template<typename _Type> _Type Load(istream &ris) { return Loader<_Type>::Load(ris); } } #define UNPACK(sz) (sz)[0], ((sz)[0] > 0) ? UNPACK((sz) + 1) : 0 #endif <|endoftext|>
<commit_before>#include "socket.h" #include "dialer.h" #include "listener.h" #include "exceptions.hpp" #include <vector> namespace nng { using std::placeholders::_1; using std::placeholders::_2; using std::placeholders::_3; using std::placeholders::_4; socket::socket(const nng_ctor_func& nng_ctor) : sid(0) , sender() , receiver() , messenger() , options() { const auto errnum = nng_ctor(&sid); THROW_NNG_EXCEPTION_EC(errnum); } socket::~socket() { close(); } void socket::close() { // Close is its own operation apart from Shutdown. const auto op = std::bind(&::nng_close, _1); const auto errnum = op(sid); THROW_NNG_EXCEPTION_IF_NOT_ONEOF(errnum, ec_eunknown, ec_enone); // Closed is closed. sid = 0; } void socket::shutdown() { // Shutdown is its own operation apart from Closed. const auto op = std::bind(&::nng_shutdown, _1); const auto errnum = op(sid); THROW_NNG_EXCEPTION_IF_NOT_ONEOF(errnum, ec_eunknown, ec_enone); // Which socket can still be in operation. } bool socket::is_open() const { return sid != 0; } // TODO: TBD: ditto ec handling... void socket::listen(const std::string& addr, flag_type flags) { const auto errnum = ::nng_listen(sid, addr.c_str(), nullptr, static_cast<int>(flags)); THROW_NNG_EXCEPTION_EC(errnum); } void socket::listen(const std::string& addr, listener* const lp, flag_type flags) { const auto errnum = ::nng_listen(sid, addr.c_str(), lp ? &(lp->lid) : nullptr, static_cast<int>(flags)); THROW_NNG_EXCEPTION_EC(errnum); } void socket::dial(const std::string& addr, flag_type flags) { const auto errnum = ::nng_dial(sid, addr.c_str(), nullptr, flags); THROW_NNG_EXCEPTION_EC(errnum); } void socket::dial(const std::string& addr, dialer* const dp, flag_type flags) { const auto errnum = ::nng_dial(sid, addr.c_str(), dp ? &(dp->did) : nullptr, static_cast<int>(flags)); THROW_NNG_EXCEPTION_EC(errnum); } template<class Buffer_> int send(int id, const Buffer_& buf, std::size_t sz, flag_type flags) { // &buf[0] ???? const auto errnum = ::nng_send(id, (void*)buf.data(), sz, static_cast<int>(flags)); THROW_NNG_EXCEPTION_EC(errnum); return errnum; } template<class Buffer_> int try_receive(int id, Buffer_& buf, std::size_t& sz, flag_type flags) { buf.resize(sz); // &buf[0] ???? const auto errnum = ::nng_recv(id, (void*)buf.data(), &sz, static_cast<int>(flags)); THROW_NNG_EXCEPTION_EC(errnum); return errnum; } void socket::send(binary_message_type* const bmp, flag_type flags) { auto* msgp = bmp->get_msgp(); const auto op = std::bind(&::nng_sendmsg, _1, _2, _3); const auto errnum = op(sid, msgp, static_cast<int>(flags)); /* Yes, this is not a mistake. Message passing semantics means that NNG assumes ownership of the message after passing. Effectively, this nullifies the message. */ // TODO: TBD: at least for now this seems reasonable: depending on the error code, we may or may not want to do this... if (!errnum) { bmp->on_sent(); } THROW_NNG_EXCEPTION_EC(errnum); } int socket::send(const buffer_vector_type* const bufp, flag_type flags) { return nng::send(sid, *bufp, bufp->size(), flags); } int socket::send(const buffer_vector_type* const bufp, size_type sz, flag_type flags) { return nng::send(sid, *bufp, sz, flags); } std::unique_ptr<socket::binary_message_type> socket::receive(flag_type flags) { auto bmup = std::make_unique<binary_message_type>(); try_receive(bmup.get(), flags); return bmup; } int socket::try_receive(binary_message_type* const bmp, flag_type flags) { /* So this is somewhat of a long way around, but it represents the cost of NNG message ownership semantics. The cost has to be paid at some point, either on the front side or the back side, so we pay for it here in additional semantics. */ ::nng_msg* msgp = nullptr; const auto errnum = ::nng_recvmsg(sid, &msgp, static_cast<int>(flags)); try { // Which we actually do want to set this one. THROW_NNG_EXCEPTION_EC(errnum); } catch (...) { // TODO: TBD: this is probably (PROBABLY) about as good as we can expect here... if (msgp) { ::nng_msg_free(msgp); } // Re-throw the exception after taking care of potential memory allocation. throw; } bmp->set_msgp(msgp); return errnum; } socket::buffer_vector_type socket::receive(size_type& sz, flag_type flags) { buffer_vector_type buf; try_receive(&buf, sz, flags); return buf; } int socket::try_receive(buffer_vector_type* const bufp, size_type& sz, flag_type flags) { return nng::try_receive(sid, *bufp, sz, flags); } // Convenience option wrappers. void socket::set_option(const std::string& name, const std::string& val, size_type sz) { const auto op = std::bind(&::nng_setopt, _1, _2, _3, _4); const auto errnum = ::nng_setopt(sid, name.c_str(), val.c_str(), sz); THROW_NNG_EXCEPTION_EC(errnum); } void socket::set_option(const std::string& name, const std::string& val) { const auto op = std::bind(&::nng_setopt, _1, _2, _3, _4); const auto errnum = ::nng_setopt(sid, name.c_str(), val.c_str(), val.length()); THROW_NNG_EXCEPTION_EC(errnum); } void socket::get_option(const std::string& name, std::string& val, size_type& sz) { const auto op = std::bind(&::nng_getopt, _1, _2, _3, _4); const auto errnum = op(sid, name.c_str(), (void*)&val[0], &sz); THROW_NNG_EXCEPTION_EC(errnum); // Do this because the C++ buffer does not appear to be honored quite right when working with the C buffers. val.resize(sz - 1); } void socket::get_option(const std::string& name, std::string& val) { const auto op = std::bind(&::nng_getopt, _1, _2, _3, _4); size_type sz = val.size(); const auto errnum = op(sid, name.c_str(), (void*)&val[0], &sz); THROW_NNG_EXCEPTION_EC(errnum); // Do this because the C++ buffer does not appear to be honored quite right when working with the C buffers. val.resize(sz - 1); } void socket::set_option(const std::string& name, const void* valp, size_type sz) { const auto op = std::bind(&::nng_setopt, _1, _2, _3, _4); const auto errnum = op(sid, name.c_str(), valp, sz); THROW_NNG_EXCEPTION_EC(errnum); } void socket::get_option(const std::string& name, void* val, size_type* szp) { const auto op = std::bind(&::nng_getopt, _1, _2, _3, _4); const auto errnum = op(sid, name.c_str(), val, szp); THROW_NNG_EXCEPTION_EC(errnum); } void socket::set_option_int(const std::string& name, int val) { const auto op = std::bind(&::nng_setopt_int, _1, _2, _3); const auto errnum = op(sid, name.c_str(), val); THROW_NNG_EXCEPTION_EC(errnum); } void socket::set_option_size(const std::string& name, size_type val) { const auto op = std::bind(&::nng_setopt_size, _1, _2, _3); const auto errnum = op(sid, name.c_str(), val); THROW_NNG_EXCEPTION_EC(errnum); } void socket::set_option_usec(const std::string& name, uint64_t val) { const auto op = std::bind(&::nng_setopt_usec, _1, _2, _3); const auto errnum = op(sid, name.c_str(), val); THROW_NNG_EXCEPTION_EC(errnum); } void socket::get_option_int(const std::string& name, int* valp) { const auto op = std::bind(&::nng_getopt_int, _1, _2, _3); const auto errnum = op(sid, name.c_str(), valp); THROW_NNG_EXCEPTION_EC(errnum); } void socket::get_option_size(const std::string& name, size_type* valp) { const auto op = std::bind(&::nng_getopt_size, _1, _2, _3); const auto errnum = op(sid, name.c_str(), valp); THROW_NNG_EXCEPTION_EC(errnum); } void socket::get_option_usec(const std::string& name, uint64_t* valp) { const auto op = std::bind(&::nng_getopt_usec, _1, _2, _3); const auto errnum = op(sid, name.c_str(), valp); THROW_NNG_EXCEPTION_EC(errnum); } protocol_type to_protocol_type(int value) { return static_cast<protocol_type>(value); } int to_int(const protocol_type value) { return static_cast<int>(value); } protocol_type socket::get_protocol() const { return to_protocol_type(::nng_protocol(sid)); } protocol_type socket::get_peer() const { return to_protocol_type(::nng_peer(sid)); } bool socket::is_protocol_configured() const { return get_protocol() != protocol_none; } bool socket::is_peer_configured() const { return get_peer() != protocol_none; } } <commit_msg>bindings were not the problem with IPC but I prefer the bindings to help with troubleshooting later on<commit_after>#include "socket.h" #include "dialer.h" #include "listener.h" #include "exceptions.hpp" #include <vector> namespace nng { using std::placeholders::_1; using std::placeholders::_2; using std::placeholders::_3; using std::placeholders::_4; socket::socket(const nng_ctor_func& nng_ctor) : sid(0) , sender() , receiver() , messenger() , options() { const auto errnum = nng_ctor(&sid); THROW_NNG_EXCEPTION_EC(errnum); } socket::~socket() { close(); } void socket::close() { // Close is its own operation apart from Shutdown. const auto op = std::bind(&::nng_close, _1); const auto errnum = op(sid); THROW_NNG_EXCEPTION_IF_NOT_ONEOF(errnum, ec_eunknown, ec_enone); // Closed is closed. sid = 0; } void socket::shutdown() { // Shutdown is its own operation apart from Closed. const auto op = std::bind(&::nng_shutdown, _1); const auto errnum = op(sid); THROW_NNG_EXCEPTION_IF_NOT_ONEOF(errnum, ec_eunknown, ec_enone); // Which socket can still be in operation. } bool socket::is_open() const { return sid != 0; } // TODO: TBD: ditto ec handling... void socket::listen(const std::string& addr, flag_type flags) { const auto& op = std::bind(&::nng_listen, _1, _2, _3, _4); const auto errnum = op(sid, addr.c_str(), nullptr, static_cast<int>(flags)); THROW_NNG_EXCEPTION_EC(errnum); } void socket::listen(const std::string& addr, listener* const lp, flag_type flags) { const auto& op = std::bind(&::nng_listen, _1, _2, _3, _4); const auto errnum = op(sid, addr.c_str(), lp ? &(lp->lid) : nullptr, static_cast<int>(flags)); THROW_NNG_EXCEPTION_EC(errnum); } void socket::dial(const std::string& addr, flag_type flags) { const auto& op = std::bind(&::nng_dial, _1, _2, _3, _4); const auto errnum = op(sid, addr.c_str(), nullptr, flags); THROW_NNG_EXCEPTION_EC(errnum); } void socket::dial(const std::string& addr, dialer* const dp, flag_type flags) { const auto& op = std::bind(&::nng_dial, _1, _2, _3, _4); const auto errnum = op(sid, addr.c_str(), dp ? &(dp->did) : nullptr, static_cast<int>(flags)); THROW_NNG_EXCEPTION_EC(errnum); } template<class Buffer_> int send(int id, const Buffer_& buf, std::size_t sz, flag_type flags) { // &buf[0] ???? const auto errnum = ::nng_send(id, (void*)buf.data(), sz, static_cast<int>(flags)); THROW_NNG_EXCEPTION_EC(errnum); return errnum; } template<class Buffer_> int try_receive(int id, Buffer_& buf, std::size_t& sz, flag_type flags) { buf.resize(sz); // &buf[0] ???? const auto errnum = ::nng_recv(id, (void*)buf.data(), &sz, static_cast<int>(flags)); THROW_NNG_EXCEPTION_EC(errnum); return errnum; } void socket::send(binary_message_type* const bmp, flag_type flags) { auto* msgp = bmp->get_msgp(); const auto op = std::bind(&::nng_sendmsg, _1, _2, _3); const auto errnum = op(sid, msgp, static_cast<int>(flags)); /* Yes, this is not a mistake. Message passing semantics means that NNG assumes ownership of the message after passing. Effectively, this nullifies the message. */ // TODO: TBD: at least for now this seems reasonable: depending on the error code, we may or may not want to do this... if (!errnum) { bmp->on_sent(); } THROW_NNG_EXCEPTION_EC(errnum); } int socket::send(const buffer_vector_type* const bufp, flag_type flags) { return nng::send(sid, *bufp, bufp->size(), flags); } int socket::send(const buffer_vector_type* const bufp, size_type sz, flag_type flags) { return nng::send(sid, *bufp, sz, flags); } std::unique_ptr<socket::binary_message_type> socket::receive(flag_type flags) { auto bmup = std::make_unique<binary_message_type>(); try_receive(bmup.get(), flags); return bmup; } int socket::try_receive(binary_message_type* const bmp, flag_type flags) { /* So this is somewhat of a long way around, but it represents the cost of NNG message ownership semantics. The cost has to be paid at some point, either on the front side or the back side, so we pay for it here in additional semantics. */ ::nng_msg* msgp = nullptr; const auto errnum = ::nng_recvmsg(sid, &msgp, static_cast<int>(flags)); try { // Which we actually do want to set this one. THROW_NNG_EXCEPTION_EC(errnum); } catch (...) { // TODO: TBD: this is probably (PROBABLY) about as good as we can expect here... if (msgp) { ::nng_msg_free(msgp); } // Re-throw the exception after taking care of potential memory allocation. throw; } bmp->set_msgp(msgp); return errnum; } socket::buffer_vector_type socket::receive(size_type& sz, flag_type flags) { buffer_vector_type buf; try_receive(&buf, sz, flags); return buf; } int socket::try_receive(buffer_vector_type* const bufp, size_type& sz, flag_type flags) { return nng::try_receive(sid, *bufp, sz, flags); } // Convenience option wrappers. void socket::set_option(const std::string& name, const std::string& val, size_type sz) { const auto op = std::bind(&::nng_setopt, _1, _2, _3, _4); const auto errnum = ::nng_setopt(sid, name.c_str(), val.c_str(), sz); THROW_NNG_EXCEPTION_EC(errnum); } void socket::set_option(const std::string& name, const std::string& val) { const auto op = std::bind(&::nng_setopt, _1, _2, _3, _4); const auto errnum = ::nng_setopt(sid, name.c_str(), val.c_str(), val.length()); THROW_NNG_EXCEPTION_EC(errnum); } void socket::get_option(const std::string& name, std::string& val, size_type& sz) { const auto op = std::bind(&::nng_getopt, _1, _2, _3, _4); const auto errnum = op(sid, name.c_str(), (void*)&val[0], &sz); THROW_NNG_EXCEPTION_EC(errnum); // Do this because the C++ buffer does not appear to be honored quite right when working with the C buffers. val.resize(sz - 1); } void socket::get_option(const std::string& name, std::string& val) { const auto op = std::bind(&::nng_getopt, _1, _2, _3, _4); size_type sz = val.size(); const auto errnum = op(sid, name.c_str(), (void*)&val[0], &sz); THROW_NNG_EXCEPTION_EC(errnum); // Do this because the C++ buffer does not appear to be honored quite right when working with the C buffers. val.resize(sz - 1); } void socket::set_option(const std::string& name, const void* valp, size_type sz) { const auto op = std::bind(&::nng_setopt, _1, _2, _3, _4); const auto errnum = op(sid, name.c_str(), valp, sz); THROW_NNG_EXCEPTION_EC(errnum); } void socket::get_option(const std::string& name, void* val, size_type* szp) { const auto op = std::bind(&::nng_getopt, _1, _2, _3, _4); const auto errnum = op(sid, name.c_str(), val, szp); THROW_NNG_EXCEPTION_EC(errnum); } void socket::set_option_int(const std::string& name, int val) { const auto op = std::bind(&::nng_setopt_int, _1, _2, _3); const auto errnum = op(sid, name.c_str(), val); THROW_NNG_EXCEPTION_EC(errnum); } void socket::set_option_size(const std::string& name, size_type val) { const auto op = std::bind(&::nng_setopt_size, _1, _2, _3); const auto errnum = op(sid, name.c_str(), val); THROW_NNG_EXCEPTION_EC(errnum); } void socket::set_option_usec(const std::string& name, uint64_t val) { const auto op = std::bind(&::nng_setopt_usec, _1, _2, _3); const auto errnum = op(sid, name.c_str(), val); THROW_NNG_EXCEPTION_EC(errnum); } void socket::get_option_int(const std::string& name, int* valp) { const auto op = std::bind(&::nng_getopt_int, _1, _2, _3); const auto errnum = op(sid, name.c_str(), valp); THROW_NNG_EXCEPTION_EC(errnum); } void socket::get_option_size(const std::string& name, size_type* valp) { const auto op = std::bind(&::nng_getopt_size, _1, _2, _3); const auto errnum = op(sid, name.c_str(), valp); THROW_NNG_EXCEPTION_EC(errnum); } void socket::get_option_usec(const std::string& name, uint64_t* valp) { const auto op = std::bind(&::nng_getopt_usec, _1, _2, _3); const auto errnum = op(sid, name.c_str(), valp); THROW_NNG_EXCEPTION_EC(errnum); } protocol_type to_protocol_type(int value) { return static_cast<protocol_type>(value); } int to_int(const protocol_type value) { return static_cast<int>(value); } protocol_type socket::get_protocol() const { return to_protocol_type(::nng_protocol(sid)); } protocol_type socket::get_peer() const { return to_protocol_type(::nng_peer(sid)); } bool socket::is_protocol_configured() const { return get_protocol() != protocol_none; } bool socket::is_peer_configured() const { return get_peer() != protocol_none; } } <|endoftext|>
<commit_before>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_RESOURCEREF_HPP #define NAZARA_RESOURCEREF_HPP #include <Nazara/Prerequesites.hpp> #include <Nazara/Core/RefCounted.hpp> #include <type_traits> template<typename T> class NzObjectRef { static_assert(std::is_base_of<NzRefCounted, T>::value, "ObjectRef shall only be used with RefCounted-derived type"); public: NzObjectRef(); NzObjectRef(T* object); NzObjectRef(const NzObjectRef& ref); template<typename U> NzObjectRef(const NzObjectRef<U>& ref); NzObjectRef(NzObjectRef&& ref) noexcept; ~NzObjectRef(); T* Get() const; bool IsValid() const; T* Release(); bool Reset(T* object = nullptr); NzObjectRef& Swap(NzObjectRef& ref); operator bool() const; operator T*() const; T* operator->() const; NzObjectRef& operator=(T* object); NzObjectRef& operator=(const NzObjectRef& ref); template<typename U> NzObjectRef& operator=(const NzObjectRef<U>& ref); NzObjectRef& operator=(NzObjectRef&& ref) noexcept; private: T* m_object; }; #include <Nazara/Core/ObjectRef.inl> #endif // NAZARA_RESOURCEREF_HPP <commit_msg>Core/ObjectRef: Remove static_assert<commit_after>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_RESOURCEREF_HPP #define NAZARA_RESOURCEREF_HPP #include <Nazara/Prerequesites.hpp> #include <Nazara/Core/RefCounted.hpp> #include <type_traits> template<typename T> class NzObjectRef { public: NzObjectRef(); NzObjectRef(T* object); NzObjectRef(const NzObjectRef& ref); template<typename U> NzObjectRef(const NzObjectRef<U>& ref); NzObjectRef(NzObjectRef&& ref) noexcept; ~NzObjectRef(); T* Get() const; bool IsValid() const; T* Release(); bool Reset(T* object = nullptr); NzObjectRef& Swap(NzObjectRef& ref); operator bool() const; operator T*() const; T* operator->() const; NzObjectRef& operator=(T* object); NzObjectRef& operator=(const NzObjectRef& ref); template<typename U> NzObjectRef& operator=(const NzObjectRef<U>& ref); NzObjectRef& operator=(NzObjectRef&& ref) noexcept; private: T* m_object; }; #include <Nazara/Core/ObjectRef.inl> #endif // NAZARA_RESOURCEREF_HPP <|endoftext|>
<commit_before>#ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #elif defined (HAVE_CONFIG_H) #include "config.h" #endif // ifdef HAVE_CMAKE_CONFIG #include <vector> #include <boost/filesystem.hpp> #include <dune/common/exceptions.hh> #include <dune/common/mpihelper.hh> #include <dune/common/timer.hh> #include <dune/grid/multiscale/provider/cube.hh> #include <dune/fem/misc/mpimanager.hh> #include <dune/fem/misc/gridwidth.hh> #include <dune/stuff/common/parameter/tree.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/grid/boundaryinfo.hh> #include <dune/stuff/discretefunction/norm.hh> #include <dune/stuff/function/expression.hh> #include <dune/detailed/solvers/stationary/linear/elliptic/model/default.hh> #include <dune/detailed/solvers/stationary/linear/elliptic/multiscale/semicontinuousgalerkin/dune-detailed-discretizations.hh> #include <dune/detailed/solvers/stationary/linear/elliptic/continuousgalerkin/dune-detailed-discretizations.hh> #ifdef POLORDER const int polOrder = POLORDER; #else const int polOrder = 1; #endif const std::string id = "stationary.linear.elliptic.ms.semidg.ddd"; using namespace Dune; /** \brief Creates a parameter file if it does not exist. Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary keys and values. \param[in] filename (Relative) path to the file. **/ void ensureParamFile(std::string filename) { // only write param file if there is none if (!boost::filesystem::exists(filename)) { std::ofstream file; file.open(filename); file << "[" << id << "]" << std::endl; file << "exact_solution.order = 2" << std::endl; file << "exact_solution.variable = x" << std::endl; file << "exact_solution.expression.0 = -0.5*x[0]*x[0] + 0.5*x[0]" << std::endl; file << "[grid.multiscale.provider.cube]" << std::endl; file << "lowerLeft = [0.0; 0.0; 0.0]" << std::endl; file << "upperRight = [1.0; 1.0; 1.0]" << std::endl; file << "numElements = [4; 4; 4]" << std::endl; file << "boundaryId = 7" << std::endl; // a cube from the factory gets the boundary ids 1 to 4 ind 2d and 1 to 6 in 3d (hopefully) file << "partitions = [2; 2; 2]" << std::endl; file << "filename = " << id << ".msGrid" << std::endl; file << "[detailed.solvers.stationary.linear.elliptic.model.default]" << std::endl; file << "diffusion.order = 0" << std::endl; file << "diffusion.variable = x" << std::endl; file << "diffusion.expression = [1.0; 1.0; 1.0]" << std::endl; file << "force.order = 0" << std::endl; file << "force.variable = x" << std::endl; file << "force.expression = [1.0; 1.0; 1.0]" << std::endl; file << "dirichlet.order = 0" << std::endl; file << "dirichlet.variable = x" << std::endl; file << "dirichlet.expression = [0.0; 0.0; 0.0]" << std::endl; file << "neumann.order = 0" << std::endl; file << "neumann.variable = x" << std::endl; file << "neumann.expression = [0.0; 0.0; 0.0]" << std::endl; file << "[detailed.solvers.stationary.linear.elliptic.multiscale.semicontinuousgalerkin]" << std::endl; file << "discretization.penaltyFactor = 10.0" << std::endl; file << "solve.type = eigen.bicgstab.incompletelut" << std::endl; file << "solve.maxIter = 5000" << std::endl; file << "solve.precision = 1e-12" << std::endl; file << "visualize.filename = " << id << ".solution" << std::endl; file << "visualize.name = solution" << std::endl; file.close(); } // only write param file if there is none } // void ensureParamFile() template< class MultiscaleDiscreteFunctionType, class OutStreamType > void compute_errors(Dune::ParameterTree& paramTree, const MultiscaleDiscreteFunctionType& discreteFunction, OutStreamType& out, std::string prefix = "") { // exact solution typedef typename MultiscaleDiscreteFunctionType::LocalDiscreteFunctionType DiscreteFunctionType; typedef typename DiscreteFunctionType::RangeFieldType RangeFieldType; typedef typename DiscreteFunctionType::DomainFieldType DomainFieldType; typedef Dune::Stuff::Function::Expression< DomainFieldType, DiscreteFunctionType::dimDomain, RangeFieldType, DiscreteFunctionType::dimRange > FunctionType; const FunctionType function(paramTree); const unsigned int functionOrder = paramTree.get("order", 100); // compute norms out << prefix << " norm | exact solution | discrete solution | error (abs) | error (rel)" << std::endl; out << prefix << "------+----------------+-------------------+-------------+-------------" << std::endl; const RangeFieldType L2_reference_norm = Dune::Stuff::DiscreteFunction::Norm::L2(*(discreteFunction.msGrid().globalGridPart()), function, functionOrder); out.precision(2); out << prefix << " L2 | " << std::setw(14) << std::scientific << L2_reference_norm << " | " << std::flush; const RangeFieldType L2_discrete_norm = Dune::Stuff::DiscreteFunction::Norm::L2(discreteFunction); out << std::setw(17) << std::scientific << L2_discrete_norm << " | " << std::flush; const RangeFieldType L2_difference = Dune::Stuff::DiscreteFunction::Norm::L2_difference(function, functionOrder, discreteFunction); out << std::setw(11) << std::scientific << L2_difference << " | " << std::flush; out << std::setw(11) << std::scientific << L2_difference/L2_reference_norm << std::endl; out << prefix << "------+----------------+-------------------+-------------+-------------" << std::endl; // const RangeFieldType h1_reference_norm = Dune::Stuff::DiscreteFunction::Norm::h1(referenceSolution); // out.precision(2); // out << prefix << " h1 | " << std::setw(9) << std::scientific << h1_reference_norm << " | " << std::flush; // const RangeFieldType h1_multiscale_norm = Dune::Stuff::DiscreteFunction::Norm::h1(multiscaleSolution); // out << std::setw(10) << std::scientific << h1_multiscale_norm << " | " << std::flush; // const RangeFieldType h1_difference = Dune::Stuff::DiscreteFunction::Norm::h1_difference(referenceSolution, multiscaleSolution); // out << std::setw(11) << std::scientific << h1_difference << " | " << std::flush; // out << std::setw(11) << std::scientific << h1_difference/h1_reference_norm << std::endl; // out << prefix << "------+-----------+------------+-------------+-------------" << std::endl; } // void compute_norms(...) int main(int argc, char** argv) { try { // mpi MPIManager::initialize(argc, argv); // parameter const std::string filename = id + ".param"; ensureParamFile(filename); Stuff::Common::ParameterTreeX paramTree(argc, argv, filename); // logger Stuff::Common::Logger().create(Stuff::Common::LOG_INFO | Stuff::Common::LOG_CONSOLE | Stuff::Common::LOG_DEBUG); Stuff::Common::LogStream& info = Stuff::Common::Logger().info(); Stuff::Common::LogStream& debug = Stuff::Common::Logger().debug(); // timer Dune::Timer timer; info << "setting up grid: " << std::endl; debug.suspend(); typedef Dune::grid::Multiscale::Provider::Cube<> GridProviderType; const GridProviderType gridProvider = GridProviderType::createFromParamTree(paramTree); typedef GridProviderType::MsGridType MsGridType; const Dune::shared_ptr< const MsGridType > msGrid = gridProvider.msGrid(); info << " took " << timer.elapsed() << " sec (has " << gridProvider.grid()->size(0) << " elements, " << msGrid->size() << " subdomain"; if (msGrid->size() > 1) info << "s"; info << " and a width of " << Dune::GridWidth::calcGridWidth(*(msGrid->globalGridPart())) << ")" << std::endl; debug.resume(); info << "visualizing grid... " << std::flush; timer.reset(); debug.suspend(); msGrid->visualize(paramTree.sub(GridProviderType::id()).get("filename", id + "_msGrid")); info << "done (took " << timer.elapsed() << " sek)" << std::endl; debug.resume(); info << "setting up model... " << std::flush; debug.suspend(); timer.reset(); const unsigned int DUNE_UNUSED(dimDomain) = GridProviderType::dim; const unsigned int DUNE_UNUSED(dimRange) = 1; typedef GridProviderType::CoordinateType::value_type DomainFieldType; typedef DomainFieldType RangeFieldType; typedef Detailed::Solvers::Stationary::Linear::Elliptic::Model::Default< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType; const shared_ptr< const ModelType > model(new ModelType(ModelType::createFromParamTree(paramTree))); typedef Stuff::Grid::BoundaryInfo::AllDirichlet BoundaryInfoType; const shared_ptr< const BoundaryInfoType > boundaryInfo(new BoundaryInfoType()); info << "done (took " << timer.elapsed() << " sec)" << std::endl; debug.resume(); // solver info << "initializing solver"; // info << ":" << std::endl; info << "... " << std::flush; debug.suspend(); timer.reset(); typedef Detailed::Solvers ::Stationary ::Linear ::Elliptic ::Multiscale ::SemicontinuousGalerkin::DuneDetailedDiscretizations< ModelType, MsGridType, BoundaryInfoType, polOrder > SolverType; const Stuff::Common::ParameterTreeX solverTree = paramTree.sub(SolverType::id()); const Stuff::Common::ParameterTreeX discretizationTree = solverTree.sub("discretization"); SolverType solver(model, msGrid, boundaryInfo, discretizationTree.get< RangeFieldType >("penaltyFactor")); solver.init(" ", debug); info << "done (took " << timer.elapsed() << " sec)" << std::endl; debug.resume(); info << "solving"; // info << ":" << std::endl; info << "... " << std::flush; debug.suspend(); timer.reset(); typedef SolverType::VectorBackendType VectorType; Dune::shared_ptr< std::vector< VectorType > > solution = solver.createVector(); solver.solve(*solution, solverTree.get("solve.type", "eigen.bicgstab.diagonal"), solverTree.get("solve.maxIter", 5000u), solverTree.get("solve.precision", 1e-12), " ", debug); info << "done (took " << timer.elapsed() << " sec)" << std::endl; debug.resume(); // info << "computing detailed reference solution... " << std::flush; // debug.suspend(); // timer.reset(); // typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::ContinuousGalerkin::DuneDetailedDiscretizations< // ModelType, // typename MsGridType::GlobalGridPartType, // BoundaryInfoType, // polOrder > // ReferenceSolverType; // ReferenceSolverType referenceSolver(model, msGrid->globalGridPart(), boundaryInfo); // referenceSolver.init(); // Dune::shared_ptr< VectorType > referenceSolution = referenceSolver.createVector(); // referenceSolver.solve(*referenceSolution, paramTree.sub(SolverType::id).sub("solve"), " ", debug); // info << "done (took " << timer.elapsed() << " sec)" << std::endl; // debug.resume(); info << "postprocessing"; // info << ":" << std::endl; info << "... " << std::flush; debug.suspend(); timer.reset(); solver.visualize(*solution, solverTree.get("visualize.filename", id + ".solution"), solverTree.get("visualize.name", "solution"), " ", debug); info << "done (took " << timer.elapsed() << " sec)" << std::endl; debug.resume(); // if (dimDomain == 1) { // info << "computing norms:" << std::endl; // debug.suspend(); // referenceSolver.visualize(*referenceSolution, // paramTree.sub(SolverType::id).sub("visualize").get("filename", id + ".solution") + "_reference", // paramTree.sub(SolverType::id).sub("visualize").get("name", "solution") + "_reference", // " ", // debug); // Dune::shared_ptr< typename SolverType::DiscreteFunctionType > discreteSolution = solver.createDiscreteFunction(*solution, "discrete_solution"); // debug.resume(); // compute_errors(paramTree.sub(id).sub("exact_solution"), // *discreteSolution, // info, " "); // } // if we came that far we can as well be happy about it return 0; } catch(Dune::Exception& e) { std::cerr << "Dune reported error: " << e.what() << std::endl; } catch(std::exception& e) { std::cerr << e.what() << std::endl; } catch( ... ) { std::cerr << "Unknown exception thrown!" << std::endl; } // try } // main <commit_msg>[examples...elliptic.ms.semidg...] update<commit_after>#ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #elif defined (HAVE_CONFIG_H) #include "config.h" #endif // ifdef HAVE_CMAKE_CONFIG #include <vector> #include <boost/filesystem.hpp> #include <dune/common/exceptions.hh> #include <dune/common/mpihelper.hh> #include <dune/common/timer.hh> #include <dune/grid/multiscale/provider/cube.hh> #include <dune/fem/misc/mpimanager.hh> #include <dune/fem/misc/gridwidth.hh> #include <dune/stuff/common/parameter/tree.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/grid/boundaryinfo.hh> #include <dune/stuff/discretefunction/norm.hh> #include <dune/stuff/function/expression.hh> #include <dune/detailed/solvers/stationary/linear/elliptic/model.hh> #include <dune/detailed/solvers/stationary/linear/elliptic/multiscale/semicontinuousgalerkin/dune-detailed-discretizations.hh> #include <dune/detailed/solvers/stationary/linear/elliptic/continuousgalerkin/dune-detailed-discretizations.hh> #ifdef POLORDER const int polOrder = POLORDER; #else const int polOrder = 1; #endif const std::string id = "stationary.linear.elliptic.ms.semidg.ddd"; using namespace Dune; using namespace Dune::Detailed::Solvers; /** \brief Creates a parameter file if it does not exist. Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary keys and values. \param[in] filename (Relative) path to the file. **/ void ensureParamFile(std::string filename) { // only write param file if there is none if (!boost::filesystem::exists(filename)) { std::ofstream file; file.open(filename); file << "[" << id << "]" << std::endl; file << "model = detailed.solvers.stationary.linear.elliptic.model.default" << std::endl; file << "exact_solution.order = 2" << std::endl; file << "exact_solution.variable = x" << std::endl; file << "exact_solution.expression.0 = -0.5*x[0]*x[0] + 0.5*x[0]" << std::endl; file << "[grid.multiscale.provider.cube]" << std::endl; file << "lowerLeft = [0.0; 0.0; 0.0]" << std::endl; file << "upperRight = [1.0; 1.0; 1.0]" << std::endl; file << "numElements = [4; 4; 4]" << std::endl; file << "boundaryId = 7" << std::endl; // a cube from the factory gets the boundary ids 1 to 4 ind 2d and 1 to 6 in 3d (hopefully) file << "partitions = [2; 2; 2]" << std::endl; file << "filename = " << id << ".msGrid" << std::endl; file << "[detailed.solvers.stationary.linear.elliptic.model.default]" << std::endl; file << "diffusion.order = 0" << std::endl; file << "diffusion.variable = x" << std::endl; file << "diffusion.expression = [1.0; 1.0; 1.0]" << std::endl; file << "force.order = 0" << std::endl; file << "force.variable = x" << std::endl; file << "force.expression = [1.0; 1.0; 1.0]" << std::endl; file << "dirichlet.order = 0" << std::endl; file << "dirichlet.variable = x" << std::endl; file << "dirichlet.expression = [0.0; 0.0; 0.0]" << std::endl; file << "neumann.order = 0" << std::endl; file << "neumann.variable = x" << std::endl; file << "neumann.expression = [0.0; 0.0; 0.0]" << std::endl; file << "[detailed.solvers.stationary.linear.elliptic.multiscale.semicontinuousgalerkin]" << std::endl; file << "discretization.penaltyFactor = 10.0" << std::endl; file << "solve.type = eigen.bicgstab.incompletelut" << std::endl; file << "solve.maxIter = 5000" << std::endl; file << "solve.precision = 1e-12" << std::endl; file << "visualize.filename = " << id << ".solution" << std::endl; file << "visualize.name = solution" << std::endl; file.close(); } // only write param file if there is none } // void ensureParamFile() template< class MultiscaleDiscreteFunctionType, class OutStreamType > void compute_errors(Dune::ParameterTree& paramTree, const MultiscaleDiscreteFunctionType& discreteFunction, OutStreamType& out, std::string prefix = "") { // exact solution typedef typename MultiscaleDiscreteFunctionType::LocalDiscreteFunctionType DiscreteFunctionType; typedef typename DiscreteFunctionType::RangeFieldType RangeFieldType; typedef typename DiscreteFunctionType::DomainFieldType DomainFieldType; typedef Dune::Stuff::Function::Expression< DomainFieldType, DiscreteFunctionType::dimDomain, RangeFieldType, DiscreteFunctionType::dimRange > FunctionType; const FunctionType function(paramTree); const unsigned int functionOrder = paramTree.get("order", 100); // compute norms out << prefix << " norm | exact solution | discrete solution | error (abs) | error (rel)" << std::endl; out << prefix << "------+----------------+-------------------+-------------+-------------" << std::endl; const RangeFieldType L2_reference_norm = Dune::Stuff::DiscreteFunction::Norm::L2(*(discreteFunction.msGrid().globalGridPart()), function, functionOrder); out.precision(2); out << prefix << " L2 | " << std::setw(14) << std::scientific << L2_reference_norm << " | " << std::flush; const RangeFieldType L2_discrete_norm = Dune::Stuff::DiscreteFunction::Norm::L2(discreteFunction); out << std::setw(17) << std::scientific << L2_discrete_norm << " | " << std::flush; const RangeFieldType L2_difference = Dune::Stuff::DiscreteFunction::Norm::L2_difference(function, functionOrder, discreteFunction); out << std::setw(11) << std::scientific << L2_difference << " | " << std::flush; out << std::setw(11) << std::scientific << L2_difference/L2_reference_norm << std::endl; out << prefix << "------+----------------+-------------------+-------------+-------------" << std::endl; // const RangeFieldType h1_reference_norm = Dune::Stuff::DiscreteFunction::Norm::h1(referenceSolution); // out.precision(2); // out << prefix << " h1 | " << std::setw(9) << std::scientific << h1_reference_norm << " | " << std::flush; // const RangeFieldType h1_multiscale_norm = Dune::Stuff::DiscreteFunction::Norm::h1(multiscaleSolution); // out << std::setw(10) << std::scientific << h1_multiscale_norm << " | " << std::flush; // const RangeFieldType h1_difference = Dune::Stuff::DiscreteFunction::Norm::h1_difference(referenceSolution, multiscaleSolution); // out << std::setw(11) << std::scientific << h1_difference << " | " << std::flush; // out << std::setw(11) << std::scientific << h1_difference/h1_reference_norm << std::endl; // out << prefix << "------+-----------+------------+-------------+-------------" << std::endl; } // void compute_norms(...) int main(int argc, char** argv) { try { // mpi MPIManager::initialize(argc, argv); // parameter const std::string filename = id + ".param"; ensureParamFile(filename); Stuff::Common::ParameterTreeX paramTree(argc, argv, filename); // logger Stuff::Common::Logger().create(Stuff::Common::LOG_INFO | Stuff::Common::LOG_CONSOLE | Stuff::Common::LOG_DEBUG); Stuff::Common::LogStream& info = Stuff::Common::Logger().info(); Stuff::Common::LogStream& debug = Stuff::Common::Logger().debug(); // timer Dune::Timer timer; info << "setting up grid: " << std::endl; debug.suspend(); typedef Dune::grid::Multiscale::Provider::Cube<> GridProviderType; const GridProviderType gridProvider = GridProviderType::createFromParamTree(paramTree); typedef GridProviderType::MsGridType MsGridType; const Dune::shared_ptr< const MsGridType > msGrid = gridProvider.msGrid(); info << " took " << timer.elapsed() << " sec (has " << gridProvider.grid()->size(0) << " elements, " << msGrid->size() << " subdomain"; if (msGrid->size() > 1) info << "s"; info << " and a width of " << Dune::GridWidth::calcGridWidth(*(msGrid->globalGridPart())) << ")" << std::endl; debug.resume(); info << "visualizing grid... " << std::flush; timer.reset(); debug.suspend(); msGrid->visualize(paramTree.sub(GridProviderType::id()).get("filename", id + "_msGrid")); info << "done (took " << timer.elapsed() << " sek)" << std::endl; debug.resume(); info << "setting up model... " << std::flush; debug.suspend(); timer.reset(); const unsigned int DUNE_UNUSED(dimDomain) = GridProviderType::dim; const unsigned int DUNE_UNUSED(dimRange) = 1; typedef GridProviderType::CoordinateType::value_type DomainFieldType; typedef DomainFieldType RangeFieldType; typedef Stationary::Linear::Elliptic::Model::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType; const std::string modelType = paramTree.get< std::string >(id + ".model"); const shared_ptr< const ModelType > model( Stationary::Linear::Elliptic::Model::create< DomainFieldType, dimDomain, RangeFieldType, dimRange >(modelType, paramTree)); typedef Stuff::Grid::BoundaryInfo::AllDirichlet BoundaryInfoType; const shared_ptr< const BoundaryInfoType > boundaryInfo(new BoundaryInfoType()); info << "done (took " << timer.elapsed() << " sec)" << std::endl; debug.resume(); // solver info << "initializing solver"; // info << ":" << std::endl; info << "... " << std::flush; debug.suspend(); timer.reset(); typedef Detailed::Solvers ::Stationary ::Linear ::Elliptic ::Multiscale ::SemicontinuousGalerkin::DuneDetailedDiscretizations< ModelType, MsGridType, BoundaryInfoType, polOrder > SolverType; const Stuff::Common::ParameterTreeX solverTree = paramTree.sub(SolverType::id()); const Stuff::Common::ParameterTreeX discretizationTree = solverTree.sub("discretization"); SolverType solver(model, msGrid, boundaryInfo, discretizationTree.get< RangeFieldType >("penaltyFactor")); solver.init(" ", debug); info << "done (took " << timer.elapsed() << " sec)" << std::endl; debug.resume(); info << "solving"; // info << ":" << std::endl; info << "... " << std::flush; debug.suspend(); timer.reset(); typedef SolverType::VectorBackendType VectorType; Dune::shared_ptr< std::vector< VectorType > > solution = solver.createVector(); solver.solve(*solution, solverTree.get("solve.type", "eigen.bicgstab.diagonal"), solverTree.get("solve.maxIter", 5000u), solverTree.get("solve.precision", 1e-12), " ", debug); info << "done (took " << timer.elapsed() << " sec)" << std::endl; debug.resume(); // info << "computing detailed reference solution... " << std::flush; // debug.suspend(); // timer.reset(); // typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::ContinuousGalerkin::DuneDetailedDiscretizations< // ModelType, // typename MsGridType::GlobalGridPartType, // BoundaryInfoType, // polOrder > // ReferenceSolverType; // ReferenceSolverType referenceSolver(model, msGrid->globalGridPart(), boundaryInfo); // referenceSolver.init(); // Dune::shared_ptr< VectorType > referenceSolution = referenceSolver.createVector(); // referenceSolver.solve(*referenceSolution, paramTree.sub(SolverType::id).sub("solve"), " ", debug); // info << "done (took " << timer.elapsed() << " sec)" << std::endl; // debug.resume(); info << "postprocessing"; // info << ":" << std::endl; info << "... " << std::flush; debug.suspend(); timer.reset(); solver.visualize(*solution, solverTree.get("visualize.filename", id + ".solution"), solverTree.get("visualize.name", "solution"), " ", debug); info << "done (took " << timer.elapsed() << " sec)" << std::endl; debug.resume(); // if (dimDomain == 1) { // info << "computing norms:" << std::endl; // debug.suspend(); // referenceSolver.visualize(*referenceSolution, // paramTree.sub(SolverType::id).sub("visualize").get("filename", id + ".solution") + "_reference", // paramTree.sub(SolverType::id).sub("visualize").get("name", "solution") + "_reference", // " ", // debug); // Dune::shared_ptr< typename SolverType::DiscreteFunctionType > discreteSolution = solver.createDiscreteFunction(*solution, "discrete_solution"); // debug.resume(); // compute_errors(paramTree.sub(id).sub("exact_solution"), // *discreteSolution, // info, " "); // } // if we came that far we can as well be happy about it return 0; } catch(Dune::Exception& e) { std::cerr << "Dune reported error: " << e.what() << std::endl; } catch(std::exception& e) { std::cerr << e.what() << std::endl; } catch( ... ) { std::cerr << "Unknown exception thrown!" << std::endl; } // try } // main <|endoftext|>
<commit_before>/* * ArmorObjectImplementation.cpp * * Created on: 02/08/2009 * Author: victor */ #include "ArmorObject.h" #include "server/zone/templates/tangible/ArmorObjectTemplate.h" #include "server/zone/objects/manufactureschematic/ManufactureSchematic.h" #include "server/zone/objects/tangible/weapon/WeaponObject.h" void ArmorObjectImplementation::initializeTransientMembers() { TangibleObjectImplementation::initializeTransientMembers(); setLoggingName("ArmorObject"); } void ArmorObjectImplementation::loadTemplateData(SharedObjectTemplate* templateData) { WearableObjectImplementation::loadTemplateData(templateData); if (!templateData->isArmorObjectTemplate()) return; ArmorObjectTemplate* armorTemplate = (ArmorObjectTemplate*) templateData; vulnerabilites = armorTemplate->getVulnerabilites(); healthEncumbrance = armorTemplate->getHealthEncumbrance(); actionEncumbrance = armorTemplate->getActionEncumbrance(); mindEncumbrance = armorTemplate->getMindEncumbrance(); rating = armorTemplate->getRating(); kinetic = armorTemplate->getKinetic(); energy = armorTemplate->getEnergy(); electricity = armorTemplate->getElectricity(); stun = armorTemplate->getStun(); blast = armorTemplate->getBlast(); heat = armorTemplate->getHeat(); cold = armorTemplate->getCold(); acid = armorTemplate->getAcid(); lightSaber = armorTemplate->getLightSaber(); specialBase = armorTemplate->getSpecialBase(); } void ArmorObjectImplementation::fillAttributeList(AttributeListMessage* alm, PlayerCreature* object) { WearableObjectImplementation::fillAttributeList(alm, object); if (socketsLeft() > 0) alm->insertAttribute("sockets", socketsLeft()); wearableSkillModMap.insertStatMods(alm); //Armor Rating if (rating == LIGHT) alm->insertAttribute("armorrating", "@obj_attr_n:armor_pierce_light"); //Light else if (rating == MEDIUM) alm->insertAttribute("armorrating", "@obj_attr_n:armor_pierce_medium"); //Medium else if (rating == HEAVY) alm->insertAttribute("armorrating", "@obj_attr_n:armor_pierce_heavy"); //Heavy else alm->insertAttribute("armorrating", "@obj_attr_n:armor_pierce_none"); //None //Check for special protections if (isSpecial(WeaponObject::KINETIC) && kinetic >= 0.5) { StringBuffer txt; txt << round(kinetic) << "%"; alm->insertAttribute("cat_armor_special_protection.armor_eff_kinetic", txt.toString()); } if (isSpecial(WeaponObject::ENERGY) && energy >= 0.5) { StringBuffer txt; txt << round(energy) << "%"; alm->insertAttribute("cat_armor_special_protection.armor_eff_energy", txt.toString()); } if (isSpecial(WeaponObject::ELECTRICITY) && electricity >= 0.5) { StringBuffer txt; txt << round(electricity) << "%"; alm->insertAttribute( "cat_armor_special_protection.armor_eff_elemental_electrical", txt.toString()); } if (isSpecial(WeaponObject::STUN) && stun >= 0.5) { StringBuffer txt; txt << round(stun) << "%"; alm->insertAttribute("cat_armor_special_protection.armor_eff_stun", txt.toString()); } if (isSpecial(WeaponObject::BLAST) && blast >= 0.5) { StringBuffer txt; txt << round(blast) << "%"; alm->insertAttribute("cat_armor_special_protection.armor_eff_blast", txt.toString()); } if (isSpecial(WeaponObject::HEAT) && heat >= 0.5) { StringBuffer txt; txt << round(heat) << "%"; alm->insertAttribute( "cat_armor_special_protection.armor_eff_elemental_heat", txt.toString()); } if (isSpecial(WeaponObject::COLD) && cold >= 0.5) { StringBuffer txt; txt << round(cold) << "%"; alm->insertAttribute( "cat_armor_special_protection.armor_eff_elemental_cold", txt.toString()); } if (isSpecial(WeaponObject::ACID) && acid >= 0.5) { StringBuffer txt; txt << round(acid) << "%"; alm->insertAttribute( "cat_armor_special_protection.armor_eff_elemental_acid", txt.toString()); } if (isSpecial(WeaponObject::LIGHTSABER) && lightSaber >= 0.5) { StringBuffer txt; txt << round(lightSaber) << "%"; alm->insertAttribute( "cat_armor_special_protection.armor_eff_restraint", txt.toString()); } //Check for Effectiveness protections(Normal) if (!isSpecial(WeaponObject::KINETIC) && kinetic >= 0.5) { StringBuffer txt; txt << round(kinetic) << "%"; alm->insertAttribute("cat_armor_effectiveness.armor_eff_kinetic", txt.toString()); } if (!isSpecial(WeaponObject::ENERGY) && energy >= 0.5) { StringBuffer txt; txt << round(energy) << "%"; alm->insertAttribute("cat_armor_effectiveness.armor_eff_energy", txt.toString()); } if (!isSpecial(WeaponObject::ELECTRICITY) && electricity >= 0.5) { StringBuffer txt; txt << round(electricity) << "%"; alm->insertAttribute( "cat_armor_effectiveness.armor_eff_elemental_electrical", txt.toString()); } if (!isSpecial(WeaponObject::STUN) && stun >= 0.5) { StringBuffer txt; txt << round(stun) << "%"; alm->insertAttribute("cat_armor_effectiveness.armor_eff_stun", txt.toString()); } if (!isSpecial(WeaponObject::BLAST) && blast >= 0.5) { StringBuffer txt; txt << round(blast) << "%"; alm->insertAttribute("cat_armor_effectiveness.armor_eff_blast", txt.toString()); } if (!isSpecial(WeaponObject::HEAT) && heat >= 0.5) { StringBuffer txt; txt << round(heat) << "%"; alm->insertAttribute( "cat_armor_effectiveness.armor_eff_elemental_heat", txt.toString()); } if (!isSpecial(WeaponObject::COLD) && cold >= 0.5) { StringBuffer txt; txt << round(cold) << "%"; alm->insertAttribute( "cat_armor_effectiveness.armor_eff_elemental_cold", txt.toString()); } if (!isSpecial(WeaponObject::ACID) && acid >= 0.5) { StringBuffer txt; txt << round(acid) << "%"; alm->insertAttribute( "cat_armor_effectiveness.armor_eff_elemental_acid", txt.toString()); } if (!isSpecial(WeaponObject::LIGHTSABER) && lightSaber >= 0.5) { StringBuffer txt; txt << round(lightSaber) << "%"; alm->insertAttribute("cat_armor_effectiveness.armor_eff_restraint", txt.toString()); } //Vulnerabilities if (kinetic < 0.5) alm->insertAttribute("cat_armor_vulnerability.armor_eff_kinetic", "-"); if (energy < 0.5) alm->insertAttribute("cat_armor_vulnerability.armor_eff_energy", "-"); if (electricity < 0.5) alm->insertAttribute( "cat_armor_vulnerability.armor_eff_elemental_electrical", "-"); if (stun < 0.5) alm->insertAttribute("cat_armor_vulnerability.armor_eff_stun", "-"); if (blast < 0.5) alm->insertAttribute("cat_armor_vulnerability.armor_eff_blast", "-"); if (heat < 0.5) alm->insertAttribute( "cat_armor_vulnerability.armor_eff_elemental_heat", "-"); if (cold < 0.5) alm->insertAttribute( "cat_armor_vulnerability.armor_eff_elemental_cold", "-"); if (acid < 0.5) alm->insertAttribute( "cat_armor_vulnerability.armor_eff_elemental_acid", "-"); if (lightSaber < 0.5) alm->insertAttribute("cat_armor_vulnerability.armor_eff_restraint", "-"); //Encumbrances alm->insertAttribute("cat_armor_encumbrance.health", healthEncumbrance); alm->insertAttribute("cat_armor_encumbrance.action", actionEncumbrance); alm->insertAttribute("cat_armor_encumbrance.mind", mindEncumbrance); if (craftersName != "") { alm->insertAttribute("crafter", craftersName); } if (craftersSerial != "") { alm->insertAttribute("serial_number", craftersSerial); } if (sliced) alm->insertAttribute("arm_attr", "@obj_attr_n:hacked"); } void ArmorObjectImplementation::updateCraftingValues(ManufactureSchematic* schematic) { WearableObjectImplementation::updateCraftingValues(schematic); /* * Incoming Values: Ranges: * sockets All depend on type of armor * hit_points * armor_effectiveness * armor_integrity * armor_health_encumbrance * armor_action_encumbrance * armor_mind_encumbrance * armor_rating * armor_special_type * armor_special_effectiveness * armor_special_integrity */ CraftingValues* craftingValues = schematic->getCraftingValues(); //craftingValues->toString(); if(schematic->getFirstCraftingUpdate()) { int special = craftingValues->getCurrentValue("armor_special_type"); specialResists = special; setRating((int) craftingValues->getCurrentValue("armor_rating")); setMaxCondition((int) craftingValues->getCurrentValue("armor_integrity")); setConditionDamage(0); } setHealthEncumbrance((int) craftingValues->getCurrentValue( "armor_health_encumbrance")); setActionEncumbrance((int) craftingValues->getCurrentValue( "armor_action_encumbrance")); setMindEncumbrance((int) craftingValues->getCurrentValue( "armor_mind_encumbrance")); float base = craftingValues->getCurrentValue("armor_effectiveness"); setProtection(schematic, WeaponObject::KINETIC, base); setProtection(schematic, WeaponObject::ENERGY, base); setProtection(schematic, WeaponObject::ELECTRICITY, base); setProtection(schematic, WeaponObject::STUN, base); setProtection(schematic, WeaponObject::BLAST, base); setProtection(schematic, WeaponObject::HEAT, base); setProtection(schematic, WeaponObject::COLD, base); setProtection(schematic, WeaponObject::ACID, base); setProtection(schematic, WeaponObject::LIGHTSABER, base); } void ArmorObjectImplementation::calculateSpecalProtection( ManufactureSchematic* schematic) { CraftingValues* craftingValues = schematic->getCraftingValues(); float base = craftingValues->getCurrentValue("armor_effectiveness"); float value, min, max, currentValue; String title = "exp_resistance"; String subtitle; //float min = craftingValues->getMinValue("armor_effectiveness"); //float max = craftingValues->getMaxValue("armor_effectiveness"); float currentPercentage = craftingValues->getCurrentPercentage("armor_effectiveness"); float maxPercentage = craftingValues->getMaxPercentage("armor_effectiveness"); int precision = craftingValues->getPrecision("armor_effectiveness"); for (int i = 0; i <= 8; ++i) { int type = pow(2,i); if(isSpecial(type)) { subtitle = getStringType(type); value = craftingValues->getCurrentValue(subtitle); min = 2; max = (value - min + (min * currentPercentage)) / currentPercentage; currentValue = (currentPercentage * (max - min)) + min; craftingValues->addExperimentalProperty(title, subtitle, min, max, precision, false); craftingValues->setMaxPercentage(subtitle, maxPercentage); craftingValues->setCurrentPercentage(subtitle, currentPercentage); craftingValues->setCurrentValue(subtitle, currentValue); } } } void ArmorObjectImplementation::setProtection(ManufactureSchematic* schematic, int type, float base) { CraftingValues* craftingValues = schematic->getCraftingValues(); float value = craftingValues->getCurrentValue(getStringType(type)); if (value == CraftingValues::VALUENOTFOUND && schematic->getFirstCraftingUpdate()) { craftingValues->lockValue(getStringType(type)); } if (value == CraftingValues::VALUENOTFOUND) { if (isVulnerable(type)) setProtectionValue(type, 0.0f); else setProtectionValue(type, base); } else { if (value + base > 80.0f) setProtectionValue(type, 80.0f); else setProtectionValue(type, value + base); } } String ArmorObjectImplementation::getStringType(int type) { switch(type) { case WeaponObject::KINETIC: return "kineticeffectiveness"; break; case WeaponObject::ENERGY: return "energyeffectiveness"; break; case WeaponObject::ELECTRICITY: return "electricaleffectiveness"; break; case WeaponObject::STUN: return "stuneffectiveness"; break; case WeaponObject::BLAST: return "blasteffectiveness"; break; case WeaponObject::HEAT: return "heateffectiveness"; break; case WeaponObject::COLD: return "coldeffectiveness"; break; case WeaponObject::ACID: return "acideffectiveness"; break; case WeaponObject::LIGHTSABER: return "restraineffectiveness"; break; default: return ""; } } void ArmorObjectImplementation::setProtectionValue(int type, float value) { if (type & WeaponObject::KINETIC) setKinetic(value); if (type & WeaponObject::ENERGY) setEnergy(value); if (type & WeaponObject::BLAST) setBlast(value); if (type & WeaponObject::STUN) setStun(value); if (type & WeaponObject::LIGHTSABER) setLightSaber(value); if (type & WeaponObject::HEAT) setHeat(value); if (type & WeaponObject::COLD) setCold(value); if (type & WeaponObject::ACID) setAcid(value); if (type & WeaponObject::ELECTRICITY) setElectricity(value); } <commit_msg>[Update] Armor Special Protection<commit_after>/* * ArmorObjectImplementation.cpp * * Created on: 02/08/2009 * Author: victor */ #include "ArmorObject.h" #include "server/zone/templates/tangible/ArmorObjectTemplate.h" #include "server/zone/objects/manufactureschematic/ManufactureSchematic.h" #include "server/zone/objects/tangible/weapon/WeaponObject.h" void ArmorObjectImplementation::initializeTransientMembers() { TangibleObjectImplementation::initializeTransientMembers(); setLoggingName("ArmorObject"); } void ArmorObjectImplementation::loadTemplateData(SharedObjectTemplate* templateData) { WearableObjectImplementation::loadTemplateData(templateData); if (!templateData->isArmorObjectTemplate()) return; ArmorObjectTemplate* armorTemplate = (ArmorObjectTemplate*) templateData; vulnerabilites = armorTemplate->getVulnerabilites(); healthEncumbrance = armorTemplate->getHealthEncumbrance(); actionEncumbrance = armorTemplate->getActionEncumbrance(); mindEncumbrance = armorTemplate->getMindEncumbrance(); rating = armorTemplate->getRating(); kinetic = armorTemplate->getKinetic(); energy = armorTemplate->getEnergy(); electricity = armorTemplate->getElectricity(); stun = armorTemplate->getStun(); blast = armorTemplate->getBlast(); heat = armorTemplate->getHeat(); cold = armorTemplate->getCold(); acid = armorTemplate->getAcid(); lightSaber = armorTemplate->getLightSaber(); specialBase = armorTemplate->getSpecialBase(); } void ArmorObjectImplementation::fillAttributeList(AttributeListMessage* alm, PlayerCreature* object) { WearableObjectImplementation::fillAttributeList(alm, object); if (socketsLeft() > 0) alm->insertAttribute("sockets", socketsLeft()); wearableSkillModMap.insertStatMods(alm); //Armor Rating if (rating == LIGHT) alm->insertAttribute("armorrating", "@obj_attr_n:armor_pierce_light"); //Light else if (rating == MEDIUM) alm->insertAttribute("armorrating", "@obj_attr_n:armor_pierce_medium"); //Medium else if (rating == HEAVY) alm->insertAttribute("armorrating", "@obj_attr_n:armor_pierce_heavy"); //Heavy else alm->insertAttribute("armorrating", "@obj_attr_n:armor_pierce_none"); //None //Check for special protections if (isSpecial(WeaponObject::KINETIC) && kinetic >= 0.5) { StringBuffer txt; txt << round(kinetic) << "%"; alm->insertAttribute("cat_armor_special_protection.armor_eff_kinetic", txt.toString()); } if (isSpecial(WeaponObject::ENERGY) && energy >= 0.5) { StringBuffer txt; txt << round(energy) << "%"; alm->insertAttribute("cat_armor_special_protection.armor_eff_energy", txt.toString()); } if (isSpecial(WeaponObject::ELECTRICITY) && electricity >= 0.5) { StringBuffer txt; txt << round(electricity) << "%"; alm->insertAttribute( "cat_armor_special_protection.armor_eff_elemental_electrical", txt.toString()); } if (isSpecial(WeaponObject::STUN) && stun >= 0.5) { StringBuffer txt; txt << round(stun) << "%"; alm->insertAttribute("cat_armor_special_protection.armor_eff_stun", txt.toString()); } if (isSpecial(WeaponObject::BLAST) && blast >= 0.5) { StringBuffer txt; txt << round(blast) << "%"; alm->insertAttribute("cat_armor_special_protection.armor_eff_blast", txt.toString()); } if (isSpecial(WeaponObject::HEAT) && heat >= 0.5) { StringBuffer txt; txt << round(heat) << "%"; alm->insertAttribute( "cat_armor_special_protection.armor_eff_elemental_heat", txt.toString()); } if (isSpecial(WeaponObject::COLD) && cold >= 0.5) { StringBuffer txt; txt << round(cold) << "%"; alm->insertAttribute( "cat_armor_special_protection.armor_eff_elemental_cold", txt.toString()); } if (isSpecial(WeaponObject::ACID) && acid >= 0.5) { StringBuffer txt; txt << round(acid) << "%"; alm->insertAttribute( "cat_armor_special_protection.armor_eff_elemental_acid", txt.toString()); } if (isSpecial(WeaponObject::LIGHTSABER) && lightSaber >= 0.5) { StringBuffer txt; txt << round(lightSaber) << "%"; alm->insertAttribute( "cat_armor_special_protection.armor_eff_restraint", txt.toString()); } //Check for Effectiveness protections(Normal) if (!isSpecial(WeaponObject::KINETIC) && kinetic >= 0.5) { StringBuffer txt; txt << round(kinetic) << "%"; alm->insertAttribute("cat_armor_effectiveness.armor_eff_kinetic", txt.toString()); } if (!isSpecial(WeaponObject::ENERGY) && energy >= 0.5) { StringBuffer txt; txt << round(energy) << "%"; alm->insertAttribute("cat_armor_effectiveness.armor_eff_energy", txt.toString()); } if (!isSpecial(WeaponObject::ELECTRICITY) && electricity >= 0.5) { StringBuffer txt; txt << round(electricity) << "%"; alm->insertAttribute( "cat_armor_effectiveness.armor_eff_elemental_electrical", txt.toString()); } if (!isSpecial(WeaponObject::STUN) && stun >= 0.5) { StringBuffer txt; txt << round(stun) << "%"; alm->insertAttribute("cat_armor_effectiveness.armor_eff_stun", txt.toString()); } if (!isSpecial(WeaponObject::BLAST) && blast >= 0.5) { StringBuffer txt; txt << round(blast) << "%"; alm->insertAttribute("cat_armor_effectiveness.armor_eff_blast", txt.toString()); } if (!isSpecial(WeaponObject::HEAT) && heat >= 0.5) { StringBuffer txt; txt << round(heat) << "%"; alm->insertAttribute( "cat_armor_effectiveness.armor_eff_elemental_heat", txt.toString()); } if (!isSpecial(WeaponObject::COLD) && cold >= 0.5) { StringBuffer txt; txt << round(cold) << "%"; alm->insertAttribute( "cat_armor_effectiveness.armor_eff_elemental_cold", txt.toString()); } if (!isSpecial(WeaponObject::ACID) && acid >= 0.5) { StringBuffer txt; txt << round(acid) << "%"; alm->insertAttribute( "cat_armor_effectiveness.armor_eff_elemental_acid", txt.toString()); } if (!isSpecial(WeaponObject::LIGHTSABER) && lightSaber >= 0.5) { StringBuffer txt; txt << round(lightSaber) << "%"; alm->insertAttribute("cat_armor_effectiveness.armor_eff_restraint", txt.toString()); } //Vulnerabilities if (kinetic < 0.5) alm->insertAttribute("cat_armor_vulnerability.armor_eff_kinetic", "-"); if (energy < 0.5) alm->insertAttribute("cat_armor_vulnerability.armor_eff_energy", "-"); if (electricity < 0.5) alm->insertAttribute( "cat_armor_vulnerability.armor_eff_elemental_electrical", "-"); if (stun < 0.5) alm->insertAttribute("cat_armor_vulnerability.armor_eff_stun", "-"); if (blast < 0.5) alm->insertAttribute("cat_armor_vulnerability.armor_eff_blast", "-"); if (heat < 0.5) alm->insertAttribute( "cat_armor_vulnerability.armor_eff_elemental_heat", "-"); if (cold < 0.5) alm->insertAttribute( "cat_armor_vulnerability.armor_eff_elemental_cold", "-"); if (acid < 0.5) alm->insertAttribute( "cat_armor_vulnerability.armor_eff_elemental_acid", "-"); if (lightSaber < 0.5) alm->insertAttribute("cat_armor_vulnerability.armor_eff_restraint", "-"); //Encumbrances alm->insertAttribute("cat_armor_encumbrance.health", healthEncumbrance); alm->insertAttribute("cat_armor_encumbrance.action", actionEncumbrance); alm->insertAttribute("cat_armor_encumbrance.mind", mindEncumbrance); if (craftersName != "") { alm->insertAttribute("crafter", craftersName); } if (craftersSerial != "") { alm->insertAttribute("serial_number", craftersSerial); } if (sliced) alm->insertAttribute("arm_attr", "@obj_attr_n:hacked"); } void ArmorObjectImplementation::updateCraftingValues(ManufactureSchematic* schematic) { WearableObjectImplementation::updateCraftingValues(schematic); /* * Incoming Values: Ranges: * sockets All depend on type of armor * hit_points * armor_effectiveness * armor_integrity * armor_health_encumbrance * armor_action_encumbrance * armor_mind_encumbrance * armor_rating * armor_special_type * armor_special_effectiveness * armor_special_integrity */ CraftingValues* craftingValues = schematic->getCraftingValues(); //craftingValues->toString(); if(schematic->getFirstCraftingUpdate()) { int special = craftingValues->getCurrentValue("armor_special_type"); specialResists = special; calculateSpecalProtection(schematic); setRating((int) craftingValues->getCurrentValue("armor_rating")); setMaxCondition((int) craftingValues->getCurrentValue("armor_integrity")); setConditionDamage(0); } setHealthEncumbrance((int) craftingValues->getCurrentValue( "armor_health_encumbrance")); setActionEncumbrance((int) craftingValues->getCurrentValue( "armor_action_encumbrance")); setMindEncumbrance((int) craftingValues->getCurrentValue( "armor_mind_encumbrance")); float base = craftingValues->getCurrentValue("armor_effectiveness"); setProtection(schematic, WeaponObject::KINETIC, base); setProtection(schematic, WeaponObject::ENERGY, base); setProtection(schematic, WeaponObject::ELECTRICITY, base); setProtection(schematic, WeaponObject::STUN, base); setProtection(schematic, WeaponObject::BLAST, base); setProtection(schematic, WeaponObject::HEAT, base); setProtection(schematic, WeaponObject::COLD, base); setProtection(schematic, WeaponObject::ACID, base); setProtection(schematic, WeaponObject::LIGHTSABER, base); } void ArmorObjectImplementation::calculateSpecalProtection( ManufactureSchematic* schematic) { CraftingValues* craftingValues = schematic->getCraftingValues(); float base = craftingValues->getCurrentValue("armor_effectiveness"); float value, min, max, currentValue; String title = "exp_resistance"; String subtitle; //float min = craftingValues->getMinValue("armor_effectiveness"); //float max = craftingValues->getMaxValue("armor_effectiveness"); float currentPercentage = craftingValues->getCurrentPercentage("armor_effectiveness"); float maxPercentage = craftingValues->getMaxPercentage("armor_effectiveness"); int precision = craftingValues->getPrecision("armor_effectiveness"); for (int i = 0; i <= 8; ++i) { int type = pow(2,i); if(isSpecial(type)) { subtitle = getStringType(type); value = craftingValues->getCurrentValue(subtitle); min = 2; max = (value - min + (min * currentPercentage)) / currentPercentage; currentValue = (currentPercentage * (max - min)) + min; craftingValues->addExperimentalProperty(title, subtitle, min, max, precision, false); craftingValues->setMaxPercentage(subtitle, maxPercentage); craftingValues->setCurrentPercentage(subtitle, currentPercentage); craftingValues->setCurrentValue(subtitle, currentValue); } } } void ArmorObjectImplementation::setProtection(ManufactureSchematic* schematic, int type, float base) { CraftingValues* craftingValues = schematic->getCraftingValues(); float value = craftingValues->getCurrentValue(getStringType(type)); if (value == CraftingValues::VALUENOTFOUND && schematic->getFirstCraftingUpdate()) { craftingValues->lockValue(getStringType(type)); } if (value == CraftingValues::VALUENOTFOUND) { if (isVulnerable(type)) setProtectionValue(type, 0.0f); else setProtectionValue(type, base); } else { if (value + base > 80.0f) setProtectionValue(type, 80.0f); else setProtectionValue(type, value + base); } } String ArmorObjectImplementation::getStringType(int type) { switch(type) { case WeaponObject::KINETIC: return "kineticeffectiveness"; break; case WeaponObject::ENERGY: return "energyeffectiveness"; break; case WeaponObject::ELECTRICITY: return "electricaleffectiveness"; break; case WeaponObject::STUN: return "stuneffectiveness"; break; case WeaponObject::BLAST: return "blasteffectiveness"; break; case WeaponObject::HEAT: return "heateffectiveness"; break; case WeaponObject::COLD: return "coldeffectiveness"; break; case WeaponObject::ACID: return "acideffectiveness"; break; case WeaponObject::LIGHTSABER: return "restraineffectiveness"; break; default: return ""; } } void ArmorObjectImplementation::setProtectionValue(int type, float value) { if (type & WeaponObject::KINETIC) setKinetic(value); if (type & WeaponObject::ENERGY) setEnergy(value); if (type & WeaponObject::BLAST) setBlast(value); if (type & WeaponObject::STUN) setStun(value); if (type & WeaponObject::LIGHTSABER) setLightSaber(value); if (type & WeaponObject::HEAT) setHeat(value); if (type & WeaponObject::COLD) setCold(value); if (type & WeaponObject::ACID) setAcid(value); if (type & WeaponObject::ELECTRICITY) setElectricity(value); } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2020 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file * \brief Implementation of a Convolutional Restricted Boltzmann Machine */ #pragma once #include <cstddef> #include <ctime> #include <random> #include "cpp_utils/assert.hpp" //Assertions #include "cpp_utils/stop_watch.hpp" //Performance counter #include "cpp_utils/maybe_parallel.hpp" #include "etl/etl.hpp" #include "standard_conv_rbm.hpp" //The base class #include "rbm_tmp.hpp" // static_if macros namespace dll { /*! * \brief Convolutional Restricted Boltzmann Machine * * This follows the definition of a CRBM by Honglak Lee. */ template <typename Derived, typename Desc> struct standard_crbm : public standard_conv_rbm<Derived, Desc> { using derived_t = Derived; ///< The derived type using desc = Desc; ///< The descriptor of the layer using weight = typename desc::weight; ///< The data type for this layer using this_type = standard_crbm<derived_t, desc>; ///< The type of this layer using base_type = standard_conv_rbm<Derived, desc>; ///< The base type using layer_t = this_type; ///< This layer's type using dyn_layer_t = typename desc::dyn_layer_t; ///< The dynamic version of this layer using input_one_t = typename rbm_base_traits<derived_t>::input_one_t; ///< The type of one input using output_one_t = typename rbm_base_traits<derived_t>::output_one_t; ///< The type of one output using input_t = typename rbm_base_traits<derived_t>::input_t; ///< The type of the input using output_t = typename rbm_base_traits<derived_t>::output_t; ///< The type of the output static constexpr unit_type visible_unit = desc::visible_unit; ///< The visible unit type static constexpr unit_type hidden_unit = desc::hidden_unit; ///< The hidden unit type standard_crbm() = default; // Make base class them participate in overload resolution using base_type::activate_hidden; using base_type::batch_activate_hidden; template <bool P = true, bool S = true, typename H1, typename H2, typename V1, typename V2> void activate_hidden(H1&& h_a, H2&& h_s, const V1& v_a, const V2& /*v_s*/) const { dll::auto_timer timer("crbm:activate_hidden"); static_assert(hidden_unit == unit_type::BINARY || is_relu(hidden_unit), "Invalid hidden unit type"); static_assert(P, "Computing S without P is not implemented"); as_derived().template validate_outputs<H1, H2>(); using namespace etl; // TODO This code is a huge mess! auto b_rep = as_derived().get_b_rep(); as_derived().reshape_h_a(h_a) = etl::conv_4d_valid_flipped(as_derived().reshape_v_a(v_a), as_derived().w); // Need to be done before h_a is computed! if constexpr (P && S && hidden_unit == unit_type::RELU) { h_s = max(logistic_noise(b_rep + h_a), 0.0); } if constexpr (P && S && hidden_unit == unit_type::RELU1) { h_s = min(max(ranged_noise(b_rep + h_a, 1.0), 0.0), 1.0); } if constexpr (P && S && hidden_unit == unit_type::RELU6) { h_s = min(max(ranged_noise(b_rep + h_a, 6.0), 0.0), 6.0); } if constexpr (P && hidden_unit == unit_type::BINARY && visible_unit == unit_type::BINARY) { h_a = etl::sigmoid(b_rep + h_a); } if constexpr (P && hidden_unit == unit_type::BINARY && visible_unit == unit_type::GAUSSIAN) { h_a = etl::sigmoid((1.0 / (0.1 * 0.1)) >> (b_rep + h_a)); } if constexpr (P && hidden_unit == unit_type::RELU) { h_a = max(b_rep + h_a, 0.0); } if constexpr (P && hidden_unit == unit_type::RELU1) { h_a = min(max(b_rep + h_a, 0.0), 1.0); } if constexpr (P && hidden_unit == unit_type::RELU6) { h_a = min(max(b_rep + h_a, 0.0), 6.0); } if constexpr (P && S && hidden_unit == unit_type::BINARY) { h_s = bernoulli(h_a); } // NaN checks if (P) { nan_check_deep(h_a); } if (S) { nan_check_deep(h_s); } } template<typename Input> void activate_hidden(output_one_t& h_a, const Input& input) const { activate_hidden<true, false>(h_a, h_a, input, input); } template <bool P = true, bool S = true, typename H1, typename H2, typename V1, typename V2> void activate_visible(const H1& /*h_a*/, const H2& h_s, V1&& v_a, V2&& v_s) const { dll::auto_timer timer("crbm:activate_visible"); static_assert(visible_unit == unit_type::BINARY || visible_unit == unit_type::GAUSSIAN, "Invalid visible unit type"); static_assert(P, "Computing S without P is not implemented"); as_derived().template validate_outputs<H1, H2>(); using namespace etl; // Note: we reuse v_a as a temporary here, before adding the biases as_derived().reshape_v_a(v_a) = etl::conv_4d_full(as_derived().reshape_h_a(h_s), as_derived().w); auto c_rep = as_derived().get_c_rep(); // Compute the activation probabilities if constexpr (P && visible_unit == unit_type::BINARY) { v_a = etl::sigmoid(c_rep + v_a); } if constexpr (P && visible_unit == unit_type::GAUSSIAN) { v_a = c_rep + v_a; } // Sample the values from the probabilities if constexpr (P && S && visible_unit == unit_type::BINARY) { v_s = bernoulli(v_a); } if constexpr (P && S && visible_unit == unit_type::GAUSSIAN) { v_s = normal_noise(v_a); } // NaN checks if (P) { nan_check_deep(v_a); } if (S) { nan_check_deep(v_s); } } template <bool P = true, bool S = true, typename H1, typename H2, typename V1, typename V2> void batch_activate_hidden(H1&& h_a, H2&& h_s, const V1& v_a, const V2& /*v_s*/) const { dll::auto_timer timer("crbm:batch_activate_hidden"); static_assert(hidden_unit == unit_type::BINARY || is_relu(hidden_unit), "Invalid hidden unit type"); static_assert(P, "Computing S without P is not implemented"); as_derived().template validate_outputs<H1, H2, 1>(); using namespace etl; // TODO This code is a huge mess! h_a = etl::conv_4d_valid_flipped(v_a, as_derived().w); auto b_rep = as_derived().get_batch_b_rep(v_a); // Need to be done before h_a is computed! if constexpr (P && S && hidden_unit == unit_type::RELU) { h_s = max(logistic_noise(b_rep + h_a), 0.0); } if constexpr (P && S && hidden_unit == unit_type::RELU1) { h_s = min(max(ranged_noise(b_rep + h_a, 1.0), 0.0), 1.0); } if constexpr (P && S && hidden_unit == unit_type::RELU6) { h_s = min(max(ranged_noise(b_rep + h_a, 6.0), 0.0), 6.0); } if constexpr (P && hidden_unit == unit_type::BINARY && visible_unit == unit_type::BINARY) { h_a = etl::sigmoid(b_rep + h_a); } if constexpr (P && hidden_unit == unit_type::BINARY && visible_unit == unit_type::GAUSSIAN) { h_a = etl::sigmoid((1.0 / (0.1 * 0.1)) >> (b_rep + h_a)); } if constexpr (P && hidden_unit == unit_type::RELU) { h_a = max(b_rep + h_a, 0.0); } if constexpr (P && hidden_unit == unit_type::RELU1) { h_a = min(max(b_rep + h_a, 0.0), 1.0); } if constexpr (P && hidden_unit == unit_type::RELU6) { h_a = min(max(b_rep + h_a, 0.0), 6.0); } if constexpr (P && S && hidden_unit == unit_type::BINARY) { h_s = bernoulli(h_a); } // NaN checks if (P) { nan_check_deep(h_a); } if (S) { nan_check_deep(h_s); } } template <bool P = true, bool S = true, typename H1, typename H2, typename V1, typename V2> void batch_activate_visible(const H1& /*h_a*/, const H2& h_s, V1&& v_a, V2&& v_s) const { dll::auto_timer timer("crbm:batch_activate_visible"); static_assert(visible_unit == unit_type::BINARY || visible_unit == unit_type::GAUSSIAN, "Invalid visible unit type"); static_assert(P, "Computing S without P is not implemented"); as_derived().template validate_outputs<H1, H2, 1>(); // Note: we reuse v_a as a temporary here, before adding the biases v_a = etl::conv_4d_full(h_s, as_derived().w); auto c_rep = as_derived().get_batch_c_rep(h_s); // Compute the activation probabilities if constexpr (P && visible_unit == unit_type::BINARY) { v_a = etl::sigmoid(c_rep + v_a); } if constexpr (P && visible_unit == unit_type::GAUSSIAN) { v_a = c_rep + v_a; } // Sample the values from the probabilities if constexpr (P && S && visible_unit == unit_type::BINARY) { v_s = bernoulli(v_a); } if constexpr (P && S && visible_unit == unit_type::GAUSSIAN) { v_s = normal_noise(v_a); } // NaN Checks if (P) { nan_check_deep(v_a); } if (S) { nan_check_deep(v_s); } } friend base_type; private: template<typename Input, typename Out> weight energy_impl(const Input& v, const Out& h) const { static_assert(etl::is_etl_expr<Out>, "energy_impl works with ETL expressions only"); auto rv = as_derived().reshape_v_a(v); auto tmp = as_derived().energy_tmp(); tmp = etl::conv_4d_valid_flipped(rv, as_derived().w); if constexpr (desc::visible_unit == unit_type::BINARY && desc::hidden_unit == unit_type::BINARY) { //Definition according to Honglak Lee //E(v,h) = - sum_k hk . (Wk*v) - sum_k bk sum_h hk - c sum_v v return -etl::sum(as_derived().c >> etl::sum_r(rv(0))) - etl::sum(as_derived().b >> etl::sum_r(h)) - etl::sum(h >> tmp(0)); } else if constexpr (desc::visible_unit == unit_type::GAUSSIAN && desc::hidden_unit == unit_type::BINARY) { //Definition according to Honglak Lee / Mixed with Gaussian //E(v,h) = - sum_k hk . (Wk*v) - sum_k bk sum_h hk - sum_v ((v - c) ^ 2 / 2) auto c_rep = as_derived().get_c_rep(); return -sum(etl::pow(rv(0) - c_rep, 2) / 2.0) - etl::sum(as_derived().b >> etl::sum_r(h)) - etl::sum(h >> tmp(0)); } else { return 0.0; } } template<typename Input> weight free_energy_impl(const Input& v) const { auto rv = as_derived().reshape_v_a(v); auto tmp = as_derived().energy_tmp(); tmp = etl::conv_4d_valid_flipped(rv, as_derived().w); if constexpr (desc::visible_unit == unit_type::BINARY && desc::hidden_unit == unit_type::BINARY) { //Definition computed from E(v,h) auto b_rep = as_derived().get_b_rep(); auto x = b_rep + tmp(0); return -etl::sum(as_derived().c >> etl::sum_r(rv(0))) - etl::sum(etl::log(1.0 + etl::exp(x))); } else if constexpr (desc::visible_unit == unit_type::GAUSSIAN && desc::hidden_unit == unit_type::BINARY) { //Definition computed from E(v,h) auto b_rep = as_derived().get_b_rep(); auto x = b_rep + tmp(0); auto c_rep = as_derived().get_c_rep(); return -sum(etl::pow(rv(0) - c_rep, 2) / 2.0) - etl::sum(etl::log(1.0 + etl::exp(x))); } else { return 0.0; } } /*! * \brief Returns a reference to the derived object, i.e. the object using the CRTP injector. * \return a reference to the derived object. */ derived_t& as_derived() { return *static_cast<derived_t*>(this); } /*! * \brief Returns a reference to the derived object, i.e. the object using the CRTP injector. * \return a reference to the derived object. */ const derived_t& as_derived() const { return *static_cast<const derived_t*>(this); } }; } //end of dll namespace <commit_msg>CRBM: Proper use of bias_add_4d<commit_after>//======================================================================= // Copyright (c) 2014-2020 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file * \brief Implementation of a Convolutional Restricted Boltzmann Machine */ #pragma once #include <cstddef> #include <ctime> #include <random> #include "cpp_utils/assert.hpp" //Assertions #include "cpp_utils/stop_watch.hpp" //Performance counter #include "cpp_utils/maybe_parallel.hpp" #include "etl/etl.hpp" #include "standard_conv_rbm.hpp" //The base class #include "rbm_tmp.hpp" // static_if macros namespace dll { /*! * \brief Convolutional Restricted Boltzmann Machine * * This follows the definition of a CRBM by Honglak Lee. */ template <typename Derived, typename Desc> struct standard_crbm : public standard_conv_rbm<Derived, Desc> { using derived_t = Derived; ///< The derived type using desc = Desc; ///< The descriptor of the layer using weight = typename desc::weight; ///< The data type for this layer using this_type = standard_crbm<derived_t, desc>; ///< The type of this layer using base_type = standard_conv_rbm<Derived, desc>; ///< The base type using layer_t = this_type; ///< This layer's type using dyn_layer_t = typename desc::dyn_layer_t; ///< The dynamic version of this layer using input_one_t = typename rbm_base_traits<derived_t>::input_one_t; ///< The type of one input using output_one_t = typename rbm_base_traits<derived_t>::output_one_t; ///< The type of one output using input_t = typename rbm_base_traits<derived_t>::input_t; ///< The type of the input using output_t = typename rbm_base_traits<derived_t>::output_t; ///< The type of the output static constexpr unit_type visible_unit = desc::visible_unit; ///< The visible unit type static constexpr unit_type hidden_unit = desc::hidden_unit; ///< The hidden unit type standard_crbm() = default; // Make base class them participate in overload resolution using base_type::activate_hidden; using base_type::batch_activate_hidden; template <bool P = true, bool S = true, typename H1, typename H2, typename V1, typename V2> void activate_hidden(H1&& h_a, H2&& h_s, const V1& v_a, const V2& /*v_s*/) const { dll::auto_timer timer("crbm:activate_hidden"); static_assert(hidden_unit == unit_type::BINARY || is_relu(hidden_unit), "Invalid hidden unit type"); static_assert(P, "Computing S without P is not implemented"); as_derived().template validate_outputs<H1, H2>(); using namespace etl; // TODO This code is a huge mess! auto b_rep = as_derived().get_b_rep(); as_derived().reshape_h_a(h_a) = etl::conv_4d_valid_flipped(as_derived().reshape_v_a(v_a), as_derived().w); // Need to be done before h_a is computed! if constexpr (P && S && hidden_unit == unit_type::RELU) { h_s = max(logistic_noise(b_rep + h_a), 0.0); } if constexpr (P && S && hidden_unit == unit_type::RELU1) { h_s = min(max(ranged_noise(b_rep + h_a, 1.0), 0.0), 1.0); } if constexpr (P && S && hidden_unit == unit_type::RELU6) { h_s = min(max(ranged_noise(b_rep + h_a, 6.0), 0.0), 6.0); } if constexpr (P && hidden_unit == unit_type::BINARY && visible_unit == unit_type::BINARY) { h_a = etl::sigmoid(b_rep + h_a); } if constexpr (P && hidden_unit == unit_type::BINARY && visible_unit == unit_type::GAUSSIAN) { h_a = etl::sigmoid((1.0 / (0.1 * 0.1)) >> (b_rep + h_a)); } if constexpr (P && hidden_unit == unit_type::RELU) { h_a = max(b_rep + h_a, 0.0); } if constexpr (P && hidden_unit == unit_type::RELU1) { h_a = min(max(b_rep + h_a, 0.0), 1.0); } if constexpr (P && hidden_unit == unit_type::RELU6) { h_a = min(max(b_rep + h_a, 0.0), 6.0); } if constexpr (P && S && hidden_unit == unit_type::BINARY) { h_s = bernoulli(h_a); } // NaN checks if (P) { nan_check_deep(h_a); } if (S) { nan_check_deep(h_s); } } template<typename Input> void activate_hidden(output_one_t& h_a, const Input& input) const { activate_hidden<true, false>(h_a, h_a, input, input); } template <bool P = true, bool S = true, typename H1, typename H2, typename V1, typename V2> void activate_visible(const H1& /*h_a*/, const H2& h_s, V1&& v_a, V2&& v_s) const { dll::auto_timer timer("crbm:activate_visible"); static_assert(visible_unit == unit_type::BINARY || visible_unit == unit_type::GAUSSIAN, "Invalid visible unit type"); static_assert(P, "Computing S without P is not implemented"); as_derived().template validate_outputs<H1, H2>(); using namespace etl; // Note: we reuse v_a as a temporary here, before adding the biases as_derived().reshape_v_a(v_a) = etl::conv_4d_full(as_derived().reshape_h_a(h_s), as_derived().w); auto c_rep = as_derived().get_c_rep(); // Compute the activation probabilities if constexpr (P && visible_unit == unit_type::BINARY) { v_a = etl::sigmoid(c_rep + v_a); } if constexpr (P && visible_unit == unit_type::GAUSSIAN) { v_a = c_rep + v_a; } // Sample the values from the probabilities if constexpr (P && S && visible_unit == unit_type::BINARY) { v_s = bernoulli(v_a); } if constexpr (P && S && visible_unit == unit_type::GAUSSIAN) { v_s = normal_noise(v_a); } // NaN checks if (P) { nan_check_deep(v_a); } if (S) { nan_check_deep(v_s); } } template <bool P = true, bool S = true, typename H1, typename H2, typename V1, typename V2> void batch_activate_hidden(H1&& h_a, H2&& h_s, const V1& v_a, const V2& /*v_s*/) const { dll::auto_timer timer("crbm:batch_activate_hidden"); static_assert(hidden_unit == unit_type::BINARY || is_relu(hidden_unit), "Invalid hidden unit type"); static_assert(P, "Computing S without P is not implemented"); as_derived().template validate_outputs<H1, H2, 1>(); using namespace etl; // TODO This code is a huge mess! h_a = etl::conv_4d_valid_flipped(v_a, as_derived().w); // Need to be done before h_a is computed! if constexpr (P && S && hidden_unit == unit_type::RELU) { h_s = max(logistic_noise(bias_add_4d(h_a, as_derived().b)), 0.0); } if constexpr (P && S && hidden_unit == unit_type::RELU1) { h_s = min(max(ranged_noise(bias_add_4d(h_a, as_derived().b), 1.0), 0.0), 1.0); } if constexpr (P && S && hidden_unit == unit_type::RELU6) { h_s = min(max(ranged_noise(bias_add_4d(h_a, as_derived().b), 6.0), 0.0), 6.0); } if constexpr (P && hidden_unit == unit_type::BINARY && visible_unit == unit_type::BINARY) { h_a = etl::sigmoid(bias_add_4d(h_a, as_derived().b)); } if constexpr (P && hidden_unit == unit_type::BINARY && visible_unit == unit_type::GAUSSIAN) { h_a = etl::sigmoid((1.0 / (0.1 * 0.1)) >> (bias_add_4d(h_a, as_derived().b))); } if constexpr (P && hidden_unit == unit_type::RELU) { h_a = max(bias_add_4d(h_a, as_derived().b), 0.0); } if constexpr (P && hidden_unit == unit_type::RELU1) { h_a = min(max(bias_add_4d(h_a, as_derived().b), 0.0), 1.0); } if constexpr (P && hidden_unit == unit_type::RELU6) { h_a = min(max(bias_add_4d(h_a, as_derived().b), 0.0), 6.0); } if constexpr (P && S && hidden_unit == unit_type::BINARY) { h_s = bernoulli(h_a); } // NaN checks if (P) { nan_check_deep(h_a); } if (S) { nan_check_deep(h_s); } } template <bool P = true, bool S = true, typename H1, typename H2, typename V1, typename V2> void batch_activate_visible(const H1& /*h_a*/, const H2& h_s, V1&& v_a, V2&& v_s) const { dll::auto_timer timer("crbm:batch_activate_visible"); static_assert(visible_unit == unit_type::BINARY || visible_unit == unit_type::GAUSSIAN, "Invalid visible unit type"); static_assert(P, "Computing S without P is not implemented"); as_derived().template validate_outputs<H1, H2, 1>(); // Note: we reuse v_a as a temporary here, before adding the biases v_a = etl::conv_4d_full(h_s, as_derived().w); // Compute the activation probabilities if constexpr (P && visible_unit == unit_type::BINARY) { v_a = etl::sigmoid(bias_add_4d(v_a, as_derived().c)); } if constexpr (P && visible_unit == unit_type::GAUSSIAN) { v_a = bias_add_4d(v_a, as_derived().c); } // Sample the values from the probabilities if constexpr (P && S && visible_unit == unit_type::BINARY) { v_s = bernoulli(v_a); } if constexpr (P && S && visible_unit == unit_type::GAUSSIAN) { v_s = normal_noise(v_a); } // NaN Checks if (P) { nan_check_deep(v_a); } if (S) { nan_check_deep(v_s); } } friend base_type; private: template<typename Input, typename Out> weight energy_impl(const Input& v, const Out& h) const { static_assert(etl::is_etl_expr<Out>, "energy_impl works with ETL expressions only"); auto rv = as_derived().reshape_v_a(v); auto tmp = as_derived().energy_tmp(); tmp = etl::conv_4d_valid_flipped(rv, as_derived().w); if constexpr (desc::visible_unit == unit_type::BINARY && desc::hidden_unit == unit_type::BINARY) { //Definition according to Honglak Lee //E(v,h) = - sum_k hk . (Wk*v) - sum_k bk sum_h hk - c sum_v v return -etl::sum(as_derived().c >> etl::sum_r(rv(0))) - etl::sum(as_derived().b >> etl::sum_r(h)) - etl::sum(h >> tmp(0)); } else if constexpr (desc::visible_unit == unit_type::GAUSSIAN && desc::hidden_unit == unit_type::BINARY) { //Definition according to Honglak Lee / Mixed with Gaussian //E(v,h) = - sum_k hk . (Wk*v) - sum_k bk sum_h hk - sum_v ((v - c) ^ 2 / 2) auto c_rep = as_derived().get_c_rep(); return -sum(etl::pow(rv(0) - c_rep, 2) / 2.0) - etl::sum(as_derived().b >> etl::sum_r(h)) - etl::sum(h >> tmp(0)); } else { return 0.0; } } template<typename Input> weight free_energy_impl(const Input& v) const { auto rv = as_derived().reshape_v_a(v); auto tmp = as_derived().energy_tmp(); tmp = etl::conv_4d_valid_flipped(rv, as_derived().w); if constexpr (desc::visible_unit == unit_type::BINARY && desc::hidden_unit == unit_type::BINARY) { //Definition computed from E(v,h) auto b_rep = as_derived().get_b_rep(); auto x = b_rep + tmp(0); return -etl::sum(as_derived().c >> etl::sum_r(rv(0))) - etl::sum(etl::log(1.0 + etl::exp(x))); } else if constexpr (desc::visible_unit == unit_type::GAUSSIAN && desc::hidden_unit == unit_type::BINARY) { //Definition computed from E(v,h) auto b_rep = as_derived().get_b_rep(); auto x = b_rep + tmp(0); auto c_rep = as_derived().get_c_rep(); return -sum(etl::pow(rv(0) - c_rep, 2) / 2.0) - etl::sum(etl::log(1.0 + etl::exp(x))); } else { return 0.0; } } /*! * \brief Returns a reference to the derived object, i.e. the object using the CRTP injector. * \return a reference to the derived object. */ derived_t& as_derived() { return *static_cast<derived_t*>(this); } /*! * \brief Returns a reference to the derived object, i.e. the object using the CRTP injector. * \return a reference to the derived object. */ const derived_t& as_derived() const { return *static_cast<const derived_t*>(this); } }; } //end of dll namespace <|endoftext|>
<commit_before>/// \file /// \ingroup tutorial_v7 /// /// \macro_code /// /// \date 2018-03-18 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /// \author Iliana Betsou #include "ROOT/RCanvas.hxx" #include "ROOT/RColor.hxx" #include "ROOT/RText.hxx" #include "ROOT/RLine.hxx" #include "ROOT/RPadPos.hxx" #include <string> void lineWidthNew() { using namespace ROOT::Experimental; auto canvas = RCanvas::Create("Canvas Title"); double num = 0.3; auto style = std::make_shared<RStyleNew>(); style->AddBlock("line").AddInt("line_style", 2).AddString("line_color_rgb", "4,5,6"); for (int i=10; i>0; i--){ num = num + 0.05; // current way to draw primitives - it always returns drawing options RPadPos pt(.3_normal, RPadLength::Normal(num)); auto optts = canvas->Draw(RText(pt, std::to_string(i))); optts->SetSize(13).SetAlign(32).SetFont(52); RPadPos pl1(.32_normal, RPadLength::Normal(num)); RPadPos pl2(.8_normal , RPadLength::Normal(num)); // new way of drawing - return drawable itself, which has all kind attributes auto line = canvas->DrawNew<RLineNew>(pl1, pl2); // change line width line->AttrLine().SetWidth(i); printf("Current line width %f\n", line->AttrLine().GetWidth()); // copy attributes auto attr = line->AttrLine(); printf("Attribute line width %f\n", attr.GetWidth()); // change attributes attr.SetWidth(i+1); line->AttrLine().Copy(attr); printf("Now line width %f\n", line->AttrLine().GetWidth()); // assign style object to the attribute - now "Visitor" can use style as well line->AttrLine().UseStyle(style); printf("Afetr applying RStyle: width %f style %d color %s\n", line->AttrLine().GetWidth(), line->AttrLine().GetStyle(), line->AttrLine().Color().AsSVG().c_str()); line->AttrLine().Color() = RColorNew(i+5, i+15, i+25); printf("Afetr setting color color %s\n", line->AttrLine().Color().AsSVG().c_str()); } // drawing of RLineNew not implemented, but attributes can be seen in JSON like: // of course, idea to have it much compact in JSON. For instance, I could "equipt" /* "fAttr" : { "_typename" : "ROOT::Experimental::RDrawableAttributes", "fContIO" : { "_typename" : "ROOT::Experimental::RDrawableAttributes::Record_t", "user_class" : "", "map" : {"_typename": "unordered_map<string,ROOT::Experimental::RDrawableAttributes::Value_t*>", "line_width": { "_typename" : "ROOT::Experimental::RDrawableAttributes::DoubleValue_t", "v" : 2 }} } } */ canvas->Show(); } <commit_msg>[rdrawable] provide example using new RLine implementation<commit_after>/// \file /// \ingroup tutorial_v7 /// /// \macro_code /// /// \date 2018-03-18 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /// \author Iliana Betsou #include "ROOT/RCanvas.hxx" #include "ROOT/RColor.hxx" #include "ROOT/RText.hxx" #include "ROOT/RLine.hxx" #include "ROOT/RPadPos.hxx" #include <string> void lineWidthNew() { using namespace ROOT::Experimental; auto canvas = RCanvas::Create("Canvas Title"); double num = 0.3; auto style = std::make_shared<RStyleNew>(); style->AddBlock("line").AddInt("line_style", 2).AddString("line_color_rgb", "4,5,6"); for (int i=10; i>0; i--){ num = num + 0.05; // current way to draw primitives - it always returns drawing options RPadPos pt(.3_normal, RPadLength::Normal(num)); auto optts = canvas->Draw(RText(pt, std::to_string(i))); optts->SetSize(13).SetAlign(32).SetFont(52); RPadPosNew pl1(RPadLengthNew::Normal(0.32), RPadLengthNew::Normal(num)); RPadPosNew pl2(RPadLengthNew::Normal(0.8), RPadLengthNew::Normal(num)); printf("pl1 horiz %f vert %f\n", pl1.Horiz().GetNormal(), pl1.Vert().GetNormal()); // new way of drawing - return drawable itself, which has all kind attributes auto line = canvas->DrawNew<RLineNew>(pl1, pl2); printf("line.P1 horiz %f vert %f\n", line->GetP1().Horiz().GetNormal(), line->GetP1().Vert().GetNormal()); // change line width line->AttrLine().SetWidth(i); printf("Current line width %f\n", line->AttrLine().GetWidth()); // copy attributes auto attr = line->AttrLine(); printf("Attribute line width %f\n", attr.GetWidth()); // change attributes attr.SetWidth(i+1); line->AttrLine().Copy(attr); printf("Now line width %f\n", line->AttrLine().GetWidth()); // assign style object to the attribute - now "Visitor" can use style as well line->AttrLine().UseStyle(style); printf("Afetr applying RStyle: width %f style %d color %s\n", line->AttrLine().GetWidth(), line->AttrLine().GetStyle(), line->AttrLine().Color().AsSVG().c_str()); line->AttrLine().Color() = RColorNew(i+5, i+15, i+25); printf("Afetr setting color color %s\n", line->AttrLine().Color().AsSVG().c_str()); auto col = line->AttrLine().Color(); printf("Extracting color %s has alfa %s\n", col.AsSVG().c_str(), col.HasAlfa() ? "true" : "false"); } // drawing of RLineNew not implemented, but attributes can be seen in JSON like: // of course, idea to have it much compact in JSON. For instance, I could "equipt" /* "fAttr" : { "_typename" : "ROOT::Experimental::RDrawableAttributes", "fContIO" : { "_typename" : "ROOT::Experimental::RDrawableAttributes::Record_t", "user_class" : "", "map" : {"_typename": "unordered_map<string,ROOT::Experimental::RDrawableAttributes::Value_t*>", "line_width": { "_typename" : "ROOT::Experimental::RDrawableAttributes::DoubleValue_t", "v" : 2 }} } } */ canvas->Show(); } <|endoftext|>
<commit_before>#include "controller.h" Controller::Controller() { } int Controller::setup_db() { return this->tagdb.open(); } int Controller::setup_reader() { return this->rfreader.init_spi(); } void Controller::main_loop() { uint8_t status; while(1) { status = this->rfreader.read_tag(); // status = TAG_OK; if (status == TAG_OK) { std::string mytag = this->rfreader.get_tag_str(); printf("tag(%i): %s\n", status, mytag.c_str()); this->tagdb.add_new(mytag); std::string playfile = this->tagdb.get_playfile(mytag); printf("playfile: %s\n", playfile.c_str()); } this->rfreader.halt(); usleep(200000); } } void Controller::close() { this->tagdb.close(); } std::string Controller::get_db_error() { return this->tagdb.get_error(); } <commit_msg>Controller: minor changes<commit_after>#include "controller.h" Controller::Controller() { } int Controller::setup_db() { return this->tagdb.open(); } int Controller::setup_reader() { return this->rfreader.init_spi(); } void Controller::main_loop() { uint8_t status; while(1) { status = this->rfreader.read_tag(); // status = TAG_OK; if (status == TAG_OK) { std::string mytag = this->rfreader.get_tag_str(); printf("tag: %s\n", mytag.c_str()); this->tagdb.add_new(mytag); tag_t mytag_info = this->tagdb.get_taginfo(mytag); printf("playfile: %s\n", mytag_info.playfile.c_str()); } this->rfreader.halt(); usleep(200000); } } void Controller::close() { this->tagdb.close(); } std::string Controller::get_db_error() { return this->tagdb.get_error(); } <|endoftext|>
<commit_before>// @(#)root/minuit2:$Id$ // Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * * Copyright (c) 2005 LCG ROOT Math team, CERN/PH-SFT * * * **********************************************************************/ #include "Minuit2/ModularFunctionMinimizer.h" #include "Minuit2/MinimumSeedGenerator.h" #include "Minuit2/AnalyticalGradientCalculator.h" #include "Minuit2/Numerical2PGradientCalculator.h" #include "Minuit2/MinimumBuilder.h" #include "Minuit2/MinimumSeed.h" #include "Minuit2/FunctionMinimum.h" #include "Minuit2/MnUserParameterState.h" #include "Minuit2/MnUserParameters.h" #include "Minuit2/MnUserCovariance.h" #include "Minuit2/MnUserTransformation.h" #include "Minuit2/MnUserFcn.h" #include "Minuit2/FCNBase.h" #include "Minuit2/FCNGradientBase.h" #include "Minuit2/MnStrategy.h" #include "Minuit2/MnHesse.h" #include "Minuit2/MnLineSearch.h" #include "Minuit2/MnParabolaPoint.h" #include "Minuit2/MnPrint.h" namespace ROOT { namespace Minuit2 { // #include "Minuit2/MnUserParametersPrint.h" FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNBase &fcn, const std::vector<double> &par, const std::vector<double> &err, unsigned int stra, unsigned int maxfcn, double toler) const { // minimize from FCNBase and std::vector of double's for parameter values and errors (step sizes) MnUserParameterState st(par, err); MnStrategy strategy(stra); return Minimize(fcn, st, strategy, maxfcn, toler); } FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNGradientBase &fcn, const std::vector<double> &par, const std::vector<double> &err, unsigned int stra, unsigned int maxfcn, double toler) const { // minimize from FCNGradientBase (use analytical gradient provided in FCN) // and std::vector of double's for parameter values and errors (step sizes) MnUserParameterState st(par, err); MnStrategy strategy(stra); return Minimize(fcn, st, strategy, maxfcn, toler); } // move nrow before cov to avoid ambiguities when using default parameters FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNBase &fcn, const std::vector<double> &par, unsigned int nrow, const std::vector<double> &cov, unsigned int stra, unsigned int maxfcn, double toler) const { // minimize from FCNBase using std::vector for parameter error and // an std::vector of size n*(n+1)/2 for the covariance matrix and n (rank of cov matrix) MnUserParameterState st(par, cov, nrow); MnStrategy strategy(stra); return Minimize(fcn, st, strategy, maxfcn, toler); } FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNGradientBase &fcn, const std::vector<double> &par, unsigned int nrow, const std::vector<double> &cov, unsigned int stra, unsigned int maxfcn, double toler) const { // minimize from FCNGradientBase (use analytical gradient provided in FCN) // using std::vector for parameter error and // an std::vector of size n*(n+1)/2 for the covariance matrix and n (rank of cov matrix) MnUserParameterState st(par, cov, nrow); MnStrategy strategy(stra); return Minimize(fcn, st, strategy, maxfcn, toler); } FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNBase &fcn, const MnUserParameters &upar, const MnStrategy &strategy, unsigned int maxfcn, double toler) const { // minimize from FCNBase and MnUserParameters object MnUserParameterState st(upar); return Minimize(fcn, st, strategy, maxfcn, toler); } FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNGradientBase &fcn, const MnUserParameters &upar, const MnStrategy &strategy, unsigned int maxfcn, double toler) const { // minimize from FCNGradientBase (use analytical gradient provided in FCN) and MnUserParameters object MnUserParameterState st(upar); return Minimize(fcn, st, strategy, maxfcn, toler); } FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNBase &fcn, const MnUserParameters &upar, const MnUserCovariance &cov, const MnStrategy &strategy, unsigned int maxfcn, double toler) const { // minimize from FCNBase and MnUserParameters and MnUserCovariance objects MnUserParameterState st(upar, cov); return Minimize(fcn, st, strategy, maxfcn, toler); } FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNGradientBase &fcn, const MnUserParameters &upar, const MnUserCovariance &cov, const MnStrategy &strategy, unsigned int maxfcn, double toler) const { // minimize from FCNGradientBase (use analytical gradient provided in FCN) and // MnUserParameters MnUserCovariance objects MnUserParameterState st(upar, cov); return Minimize(fcn, st, strategy, maxfcn, toler); } FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNBase &fcn, const MnUserParameterState &st, const MnStrategy &strategy, unsigned int maxfcn, double toler) const { // minimize from a FCNBase and a MnUserparameterState - interface used by all the previous ones // based on FCNBase. Create in this case a NumericalGradient calculator // Create the minuit FCN wrapper (MnUserFcn) containing the trasformation (int<->ext) // neeed MnUsserFcn for difference int-ext parameters MnUserFcn mfcn(fcn, st.Trafo()); Numerical2PGradientCalculator gc(mfcn, st.Trafo(), strategy); unsigned int npar = st.VariableParameters(); if (maxfcn == 0) maxfcn = 200 + 100 * npar + 5 * npar * npar; MinimumSeed mnseeds = SeedGenerator()(mfcn, gc, st, strategy); return Minimize(mfcn, gc, mnseeds, strategy, maxfcn, toler); } // use Gradient here FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNGradientBase &fcn, const MnUserParameterState &st, const MnStrategy &strategy, unsigned int maxfcn, double toler) const { // minimize from a FCNGradientBase and a MnUserparameterState - interface used by all the previous ones // based on FCNGradientBase. // Create in this acase an AnalyticalGradient calculator // Create the minuit FCN wrapper (MnUserFcn) containing the trasformation (int<->ext) MnUserFcn mfcn(fcn, st.Trafo()); AnalyticalGradientCalculator gc(fcn, st.Trafo()); unsigned int npar = st.VariableParameters(); if (maxfcn == 0) maxfcn = 200 + 100 * npar + 5 * npar * npar; MinimumSeed mnseeds = SeedGenerator()(mfcn, gc, st, strategy); return Minimize(mfcn, gc, mnseeds, strategy, maxfcn, toler); } FunctionMinimum ModularFunctionMinimizer::Minimize(const MnFcn &mfcn, const GradientCalculator &gc, const MinimumSeed &seed, const MnStrategy &strategy, unsigned int maxfcn, double toler) const { // Interface used by all the others for the minimization using the base MinimumBuilder class // According to the contained type of MinimumBuilder the right type will be used MnPrint print("ModularFunctionMinimizer"); const MinimumBuilder &mb = Builder(); // std::cout << typeid(&mb).Name() << std::endl; double effective_toler = toler * mfcn.Up(); // scale tolerance with Up() // avoid tolerance too smalls (than limits) double eps = MnMachinePrecision().Eps2(); if (effective_toler < eps) effective_toler = eps; // check if maxfcn is already exhausted // case already reached call limit if (mfcn.NumOfCalls() >= maxfcn) { print.Warn("Stop before iterating - call limit already exceeded"); return FunctionMinimum(seed, std::vector<MinimumState>(1, seed.State()), mfcn.Up(), FunctionMinimum::MnReachedCallLimit()); } return mb.Minimum(mfcn, gc, seed, strategy, maxfcn, effective_toler); } } // namespace Minuit2 } // namespace ROOT <commit_msg>When using externalGradient use still Numerical gradient as input to SeedGenerator<commit_after>// @(#)root/minuit2:$Id$ // Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * * Copyright (c) 2005 LCG ROOT Math team, CERN/PH-SFT * * * **********************************************************************/ #include "Minuit2/ModularFunctionMinimizer.h" #include "Minuit2/MinimumSeedGenerator.h" #include "Minuit2/AnalyticalGradientCalculator.h" #include "Minuit2/Numerical2PGradientCalculator.h" #include "Minuit2/MinimumBuilder.h" #include "Minuit2/MinimumSeed.h" #include "Minuit2/FunctionMinimum.h" #include "Minuit2/MnUserParameterState.h" #include "Minuit2/MnUserParameters.h" #include "Minuit2/MnUserCovariance.h" #include "Minuit2/MnUserTransformation.h" #include "Minuit2/MnUserFcn.h" #include "Minuit2/FCNBase.h" #include "Minuit2/FCNGradientBase.h" #include "Minuit2/MnStrategy.h" #include "Minuit2/MnHesse.h" #include "Minuit2/MnLineSearch.h" #include "Minuit2/MnParabolaPoint.h" #include "Minuit2/MnPrint.h" namespace ROOT { namespace Minuit2 { // #include "Minuit2/MnUserParametersPrint.h" FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNBase &fcn, const std::vector<double> &par, const std::vector<double> &err, unsigned int stra, unsigned int maxfcn, double toler) const { // minimize from FCNBase and std::vector of double's for parameter values and errors (step sizes) MnUserParameterState st(par, err); MnStrategy strategy(stra); return Minimize(fcn, st, strategy, maxfcn, toler); } FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNGradientBase &fcn, const std::vector<double> &par, const std::vector<double> &err, unsigned int stra, unsigned int maxfcn, double toler) const { // minimize from FCNGradientBase (use analytical gradient provided in FCN) // and std::vector of double's for parameter values and errors (step sizes) MnUserParameterState st(par, err); MnStrategy strategy(stra); return Minimize(fcn, st, strategy, maxfcn, toler); } // move nrow before cov to avoid ambiguities when using default parameters FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNBase &fcn, const std::vector<double> &par, unsigned int nrow, const std::vector<double> &cov, unsigned int stra, unsigned int maxfcn, double toler) const { // minimize from FCNBase using std::vector for parameter error and // an std::vector of size n*(n+1)/2 for the covariance matrix and n (rank of cov matrix) MnUserParameterState st(par, cov, nrow); MnStrategy strategy(stra); return Minimize(fcn, st, strategy, maxfcn, toler); } FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNGradientBase &fcn, const std::vector<double> &par, unsigned int nrow, const std::vector<double> &cov, unsigned int stra, unsigned int maxfcn, double toler) const { // minimize from FCNGradientBase (use analytical gradient provided in FCN) // using std::vector for parameter error and // an std::vector of size n*(n+1)/2 for the covariance matrix and n (rank of cov matrix) MnUserParameterState st(par, cov, nrow); MnStrategy strategy(stra); return Minimize(fcn, st, strategy, maxfcn, toler); } FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNBase &fcn, const MnUserParameters &upar, const MnStrategy &strategy, unsigned int maxfcn, double toler) const { // minimize from FCNBase and MnUserParameters object MnUserParameterState st(upar); return Minimize(fcn, st, strategy, maxfcn, toler); } FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNGradientBase &fcn, const MnUserParameters &upar, const MnStrategy &strategy, unsigned int maxfcn, double toler) const { // minimize from FCNGradientBase (use analytical gradient provided in FCN) and MnUserParameters object MnUserParameterState st(upar); return Minimize(fcn, st, strategy, maxfcn, toler); } FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNBase &fcn, const MnUserParameters &upar, const MnUserCovariance &cov, const MnStrategy &strategy, unsigned int maxfcn, double toler) const { // minimize from FCNBase and MnUserParameters and MnUserCovariance objects MnUserParameterState st(upar, cov); return Minimize(fcn, st, strategy, maxfcn, toler); } FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNGradientBase &fcn, const MnUserParameters &upar, const MnUserCovariance &cov, const MnStrategy &strategy, unsigned int maxfcn, double toler) const { // minimize from FCNGradientBase (use analytical gradient provided in FCN) and // MnUserParameters MnUserCovariance objects MnUserParameterState st(upar, cov); return Minimize(fcn, st, strategy, maxfcn, toler); } FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNBase &fcn, const MnUserParameterState &st, const MnStrategy &strategy, unsigned int maxfcn, double toler) const { // minimize from a FCNBase and a MnUserparameterState - interface used by all the previous ones // based on FCNBase. Create in this case a NumericalGradient calculator // Create the minuit FCN wrapper (MnUserFcn) containing the trasformation (int<->ext) // neeed MnUsserFcn for difference int-ext parameters MnUserFcn mfcn(fcn, st.Trafo()); Numerical2PGradientCalculator gc(mfcn, st.Trafo(), strategy); unsigned int npar = st.VariableParameters(); if (maxfcn == 0) maxfcn = 200 + 100 * npar + 5 * npar * npar; MinimumSeed mnseeds = SeedGenerator()(mfcn, gc, st, strategy); return Minimize(mfcn, gc, mnseeds, strategy, maxfcn, toler); } // use Gradient here FunctionMinimum ModularFunctionMinimizer::Minimize(const FCNGradientBase &fcn, const MnUserParameterState &st, const MnStrategy &strategy, unsigned int maxfcn, double toler) const { // minimize from a FCNGradientBase and a MnUserparameterState - interface used by all the previous ones // based on FCNGradientBase. // Create in this acase an AnalyticalGradient calculator // Create the minuit FCN wrapper (MnUserFcn) containing the trasformation (int<->ext) MnUserFcn mfcn(fcn, st.Trafo()); AnalyticalGradientCalculator gc(fcn, st.Trafo()); unsigned int npar = st.VariableParameters(); if (maxfcn == 0) maxfcn = 200 + 100 * npar + 5 * npar * npar; // use numerical gradient to compute initial derivatives for SeedGenerator Numerical2PGradientCalculator numgc(mfcn, st.Trafo(), strategy); MinimumSeed mnseeds = SeedGenerator()(mfcn, numgc, st, strategy); return Minimize(mfcn, gc, mnseeds, strategy, maxfcn, toler); } FunctionMinimum ModularFunctionMinimizer::Minimize(const MnFcn &mfcn, const GradientCalculator &gc, const MinimumSeed &seed, const MnStrategy &strategy, unsigned int maxfcn, double toler) const { // Interface used by all the others for the minimization using the base MinimumBuilder class // According to the contained type of MinimumBuilder the right type will be used MnPrint print("ModularFunctionMinimizer"); const MinimumBuilder &mb = Builder(); // std::cout << typeid(&mb).Name() << std::endl; double effective_toler = toler * mfcn.Up(); // scale tolerance with Up() // avoid tolerance too smalls (than limits) double eps = MnMachinePrecision().Eps2(); if (effective_toler < eps) effective_toler = eps; // check if maxfcn is already exhausted // case already reached call limit if (mfcn.NumOfCalls() >= maxfcn) { print.Warn("Stop before iterating - call limit already exceeded"); return FunctionMinimum(seed, std::vector<MinimumState>(1, seed.State()), mfcn.Up(), FunctionMinimum::MnReachedCallLimit()); } return mb.Minimum(mfcn, gc, seed, strategy, maxfcn, effective_toler); } } // namespace Minuit2 } // namespace ROOT <|endoftext|>
<commit_before>#include "cellmlmodelrepositorywindow.h" #include "internetfile.h" #include "ui_cellmlmodelrepositorywindow.h" #include <QDebug> namespace OpenCOR { namespace CellMLModelRepository { CellmlModelRepositoryWindow::CellmlModelRepositoryWindow(QWidget *pParent) : DockWidget(pParent), mUi(new Ui::CellmlModelRepositoryWindow) { // Set up the UI mUi->setupUi(this); // Retrieve the list of models in the CellML Model Repository as JSON code // from http://50.18.64.32/workspace/res/contents.json Core::InternetFile internetFile; QNetworkReply *res = internetFile.get("http://50.18.64.32/workspace/rest/contents.json"); qDebug(QString(res->readAll()).toLatin1().constData()); } CellmlModelRepositoryWindow::~CellmlModelRepositoryWindow() { // Delete the UI delete mUi; } void CellmlModelRepositoryWindow::retranslateUi() { // Retranslate the whole window mUi->retranslateUi(this); } } } <commit_msg>Very minor fix (was getting a warning on Linux and Mac OS X).<commit_after>#include "cellmlmodelrepositorywindow.h" #include "internetfile.h" #include "ui_cellmlmodelrepositorywindow.h" #include <QDebug> namespace OpenCOR { namespace CellMLModelRepository { CellmlModelRepositoryWindow::CellmlModelRepositoryWindow(QWidget *pParent) : DockWidget(pParent), mUi(new Ui::CellmlModelRepositoryWindow) { // Set up the UI mUi->setupUi(this); // Retrieve the list of models in the CellML Model Repository as JSON code // from http://50.18.64.32/workspace/res/contents.json Core::InternetFile internetFile; QNetworkReply *res = internetFile.get("http://50.18.64.32/workspace/rest/contents.json"); qDebug("%s", QString(res->readAll()).toLatin1().constData()); } CellmlModelRepositoryWindow::~CellmlModelRepositoryWindow() { // Delete the UI delete mUi; } void CellmlModelRepositoryWindow::retranslateUi() { // Retranslate the whole window mUi->retranslateUi(this); } } } <|endoftext|>
<commit_before>template<typename Key, typename Val> struct deamortized_map { deamortized_map(); struct Cell { Key key; Value val; }; Node { Cell data; Node *left, *right, *next; size_t height; }; Node * head; Cell * find(const Key&) const; Cell * insert(const Key&, const Val&); size_t size; }; template<typename Key, typename Val> struct insert_ans { bool success; typename deamortized_map<Key,Val>::Node *here, *ans; } template<typename Key, typename Val> insert_ans<Key,Val> node_insert(typename deamortized_map<Key,Val>::Node * root, const Key& key, const Val& val) { if (root->right && root->right->right && root->right->right->height == root->height) { typename deamortized_map<Key,Val>::Node * new_root = root->right; root->right = new_root->left; new_root->left = root; new_root->height += 1; return node_insert(new_root, key, val); } if (root) { if (key == root->key) return {false, root, root}; if (key < root->key) return node_insert } } // TODO: sentinel template<typename Key, typename Val> std::pair<bool,Node *> node_insert(typename deamortized_map<Key,Val>::Node * root, const Key& key, const Val& val) { if (not root) { auto * ans = new typename deamortized_map<Key,Val>::Node(); ans->data->key = key; ans->left = ans->right = ans->next = nullptr; ans->height = 0; return std::make_pair(true, ans); } if (key == root->data->key) { return std::make_pair(false, root); } if (key < root->data->key) { if (left_heavy(root)) { root = rotate_right(root); } root->left = node_insert(root->left, key, val).second; reheight(root); return root; } } template<typename Key, typename Val> typename deamortized_map<Key,Val>::Node * rotate_right(typename deamortized_map<Key,Val>::Node * root) { // single rotation: if ((not root->left->left) or (not root->left->right) or (root->left->left->height >= root->left->right->height)) { typename deamortized_map<Key,Val>::Node * const ans = root->left; root->left = ans->right; ans->right = root; reheight(root); reheight(ans); return ans; } else { // double rotation typename deamortized_map<Key,Val>::Node * const ans = root->left->right; root->left->right = ans->left; ans->left = root->left; root->left = ans->right; ans->right = root; reheight(ans->left); reheight(ans->right); reheight(ans); return ans; } } <commit_msg>Switch to AA trees for deamortized map<commit_after>#include <cstddef> #include <utility> #include <cstdlib> template<typename Key, typename Val> struct deamortized_map { struct Node { Key key; Val val; Node *left, *right; // tree structure Node *prev, *next; // for iterating std::size_t level; // for balance Node(const Key& key, const Val& val) : key(key), val(val), left(bottom()), right(bottom()), prev(NULL), next(NULL), level(1) {} }; // AA trees: static Node * skew(Node * root) { if (root->left->level == root->level) { // rotate right Node * ans = root->left; root->left = ans->right; ans->right = root; return ans; } return root; } static Node * split(Node * root) { if (root->right->right->level == root->level) { //rotate left Node * ans = root->right; root->right = ans->left; ans->left = root; ans->level += 1; return ans; } return root; } struct InsertAns { bool is_new; Node * location; Node * new_root; }; static InsertAns insert(const Key& key, const Val& val, Node * root) { if (0 == root->level) { InsertAns ans; // link up node later ans.location = new Node(key, val); ans.new_root = ans.location; ans.is_new = true; return ans; } InsertAns ans; if (key < root->key) ans = insert(key, val, root->left); else if (key < root->key) ans = insert(key, val, root->right); else { ans.is_new = false; ans.location = root; ans.new_root = root; } if (ans.is_new) { ans.new_root = skew(ans.new_root); ans.new_root = split(ans.new_root); } return ans; } static Node * find(const Key& key, const Node* const root) { if (0 == root->level) return NULL; if (key <= root->key) return root; if (key < root->key) return find(key, root->left); return find(key, root->right); } Node *head, *root; std::size_t size; deamortized_map() : head(NULL), root(bottom()), size(0) {} Node * find(const Key& key) const { return find(key, root); } std::pair<bool,Node*> insert(const Key& key, const Val& val) { InsertAns ia = insert(key, val, root); if (ia.is_new) { ia.location->next = head; ia.location->prev = NULL; head = ia.location; root = ia.new_root; ++size; } return make_pair(ia.is_new, ia.location); } static const Node * bottom() { static Node * ans = NULL; if (NULL == ans) { ans = malloc(sizeof(Node)); ans->left = ans->right = ans; ans->prev = ans->next = NULL; ans->level = 0; } return ans; } }; <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: i18n_im.hxx,v $ * * $Revision: 1.13 $ * * last change: $Author: rt $ $Date: 2005-09-09 12:40:19 $ * * 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 _SAL_I18N_INPUTMETHOD_HXX #define _SAL_I18N_INPUTMETHOD_HXX #ifndef _VCL_DLLAPI_H #include "dllapi.h" #endif extern "C" char* GetMethodName( XIMStyle nStyle, char *pBuf, int nBufSize); #define bUseInputMethodDefault True class VCL_DLLPUBLIC SalI18N_InputMethod { Bool mbUseable; // system supports locale as well as status // and preedit style ? Bool mbMultiLingual; // system supports iiimp XIM maMethod; XIMCallback maDestroyCallback; XIMStyles *mpStyles; public: Bool IsMultiLingual() { return mbMultiLingual; } Bool PosixLocale(); Bool UseMethod() { return mbUseable; } XIM GetMethod() { return maMethod; } void HandleDestroyIM(); Bool CreateMethod( Display *pDisplay ); XIMStyles *GetSupportedStyles() { return mpStyles; } Bool SetLocale( const char* pLocale = "" ); Bool FilterEvent( XEvent *pEvent, XLIB_Window window ); Bool AddConnectionWatch (Display *pDisplay, void *pConnectionHandler); #ifdef _USE_PRINT_EXTENSION_ void Invalidate() { mbUseable = False; } #endif SalI18N_InputMethod(); ~SalI18N_InputMethod(); }; #endif // _SAL_I18N_INPUTMETHOD_HXX <commit_msg>INTEGRATION: CWS vgbugs07 (1.13.606); FILE MERGED 2007/06/04 13:29:56 vg 1.13.606.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: i18n_im.hxx,v $ * * $Revision: 1.14 $ * * last change: $Author: hr $ $Date: 2007-06-27 20:39:26 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SAL_I18N_INPUTMETHOD_HXX #define _SAL_I18N_INPUTMETHOD_HXX #ifndef _VCL_DLLAPI_H #include <vcl/dllapi.h> #endif extern "C" char* GetMethodName( XIMStyle nStyle, char *pBuf, int nBufSize); #define bUseInputMethodDefault True class VCL_DLLPUBLIC SalI18N_InputMethod { Bool mbUseable; // system supports locale as well as status // and preedit style ? Bool mbMultiLingual; // system supports iiimp XIM maMethod; XIMCallback maDestroyCallback; XIMStyles *mpStyles; public: Bool IsMultiLingual() { return mbMultiLingual; } Bool PosixLocale(); Bool UseMethod() { return mbUseable; } XIM GetMethod() { return maMethod; } void HandleDestroyIM(); Bool CreateMethod( Display *pDisplay ); XIMStyles *GetSupportedStyles() { return mpStyles; } Bool SetLocale( const char* pLocale = "" ); Bool FilterEvent( XEvent *pEvent, XLIB_Window window ); Bool AddConnectionWatch (Display *pDisplay, void *pConnectionHandler); #ifdef _USE_PRINT_EXTENSION_ void Invalidate() { mbUseable = False; } #endif SalI18N_InputMethod(); ~SalI18N_InputMethod(); }; #endif // _SAL_I18N_INPUTMETHOD_HXX <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: saldata.hxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 17:05:41 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SV_SALDATA_HXX #define _SV_SALDATA_HXX // -=-= includes -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #include <signal.h> #ifndef _SALSTD_HXX #include <salstd.hxx> #endif #ifndef _SV_SVDATA_HXX #include <svdata.hxx> #endif #ifndef _SV_SALWTYPE_HXX #include <salwtype.hxx> #endif // -=-= forwards -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= class SalXLib; class SalDisplay; class SalInstance; class SalFrame; class SalPrinter; // -=-= typedefs -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #ifndef SIG_PF typedef void SIG_FUNC_TYP(int); typedef SIG_FUNC_TYP *SIG_TYP; #define SIG_PF SIG_TYP #endif DECLARE_LIST( SalDisplays, SalDisplay* ) #if defined SCO || defined LINUX || defined NETBSD || defined AIX || defined HPUX || defined FREEBSD #include <pthread.h> #else typedef unsigned int pthread_t; #endif // -=-= SalData =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= class SalData { char** argv_; int argc_; String aBinaryPath_; SALTIMERPROC pTimerProc_; // timer callback proc SIG_TYP sig_[30]; BOOL bNoExceptions_; SalXLib *pXLib_; SalDisplays SalDisplays_; SalDisplay *pDefDisp_; SalDisplay *pCurDisp_; pthread_t hMainThread_; public: SalInstance *pFirstInstance_; // pointer of first instance SalFrame *pFirstFrame_; // pointer of first frame public: SalData(); ~SalData(); void Init( int *pArgc, char *ppArgv[] ); inline const XubString &GetFileName() const { return aBinaryPath_; } inline USHORT GetCommandLineParamCount() const { return argc_; } XubString GetCommandLineParam( USHORT nParam ) const; long ShutDown() const; long Close() const; inline void XError( Display *pDisplay, XErrorEvent *pEvent ) const; SalDisplay *GetDisplay( Display *pDisplay ); inline SalDisplay *GetDisplay( long nDisplay ) const { return SalDisplays_.GetObject(nDisplay); } inline SalDisplay *GetDefDisp() const { return pDefDisp_; } inline SalDisplay *GetCurDisp() const { return pCurDisp_; } inline void SetDefDisp( SalDisplay *pDisp ) { pDefDisp_ = pDisp; } inline void SetCurDisp( SalDisplay *pDisp ) { pCurDisp_ = pDisp; } inline void Insert( SalDisplay *pDisplay ); inline void Remove( SalDisplay *pDisplay ); inline SalXLib *GetLib() const { return pXLib_; } inline pthread_t GetMainThread() const { return hMainThread_; } void StartTimer( ULONG nMS ); inline void StopTimer(); inline void SetCallback( SALTIMERPROC pProc ) { pTimerProc_ = pProc; } void Timeout() const; }; // -=-= inlines =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= inline void SetSalData( SalData* pData ) { ImplGetSVData()->mpSalData = (void*)pData; } inline SalData* GetSalData() { return (SalData*)ImplGetSVData()->mpSalData; } inline void SalData::Insert( SalDisplay *pDisplay ) { SalDisplays_.Insert( pDisplay ); } inline void SalData::Remove( SalDisplay *pDisplay ) { SalDisplays_.Remove( pDisplay ); } #ifdef _SV_SALDISP_HXX inline void SalData::XError( Display *pDisplay, XErrorEvent *pEvent ) const { pXLib_->XError( pDisplay, pEvent ); } #endif #endif // _SV_SALDATA_HXX <commit_msg>MutexReleaser moved here<commit_after>/************************************************************************* * * $RCSfile: saldata.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obr $ $Date: 2001-02-09 14:46:35 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SV_SALDATA_HXX #define _SV_SALDATA_HXX // -=-= includes -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #include <signal.h> #ifndef _SALSTD_HXX #include <salstd.hxx> #endif #ifndef _SV_SVDATA_HXX #include <svdata.hxx> #endif #ifndef _SV_SALWTYPE_HXX #include <salwtype.hxx> #endif #ifndef _SV_SALINST_HXX #include <salinst.hxx> #endif // -=-= forwards -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= class SalXLib; class SalDisplay; class SalInstance; class SalFrame; class SalPrinter; // -=-= typedefs -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #ifndef SIG_PF typedef void SIG_FUNC_TYP(int); typedef SIG_FUNC_TYP *SIG_TYP; #define SIG_PF SIG_TYP #endif DECLARE_LIST( SalDisplays, SalDisplay* ) #if defined SCO || defined LINUX || defined NETBSD || defined AIX || defined HPUX || defined FREEBSD #include <pthread.h> #else typedef unsigned int pthread_t; #endif // -=-= SalData =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= class SalData { char** argv_; int argc_; String aBinaryPath_; SALTIMERPROC pTimerProc_; // timer callback proc SIG_TYP sig_[30]; BOOL bNoExceptions_; SalXLib *pXLib_; SalDisplays SalDisplays_; SalDisplay *pDefDisp_; SalDisplay *pCurDisp_; pthread_t hMainThread_; public: SalInstance *pFirstInstance_; // pointer of first instance SalFrame *pFirstFrame_; // pointer of first frame public: SalData(); ~SalData(); void Init( int *pArgc, char *ppArgv[] ); inline const XubString &GetFileName() const { return aBinaryPath_; } inline USHORT GetCommandLineParamCount() const { return argc_; } XubString GetCommandLineParam( USHORT nParam ) const; long ShutDown() const; long Close() const; inline void XError( Display *pDisplay, XErrorEvent *pEvent ) const; SalDisplay *GetDisplay( Display *pDisplay ); inline SalDisplay *GetDisplay( long nDisplay ) const { return SalDisplays_.GetObject(nDisplay); } inline SalDisplay *GetDefDisp() const { return pDefDisp_; } inline SalDisplay *GetCurDisp() const { return pCurDisp_; } inline void SetDefDisp( SalDisplay *pDisp ) { pDefDisp_ = pDisp; } inline void SetCurDisp( SalDisplay *pDisp ) { pCurDisp_ = pDisp; } inline void Insert( SalDisplay *pDisplay ); inline void Remove( SalDisplay *pDisplay ); inline SalXLib *GetLib() const { return pXLib_; } inline pthread_t GetMainThread() const { return hMainThread_; } void StartTimer( ULONG nMS ); inline void StopTimer(); inline void SetCallback( SALTIMERPROC pProc ) { pTimerProc_ = pProc; } void Timeout() const; }; // -=-= inlines =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= inline void SetSalData( SalData* pData ) { ImplGetSVData()->mpSalData = (void*)pData; } inline SalData* GetSalData() { return (SalData*)ImplGetSVData()->mpSalData; } inline void SalData::Insert( SalDisplay *pDisplay ) { SalDisplays_.Insert( pDisplay ); } inline void SalData::Remove( SalDisplay *pDisplay ) { SalDisplays_.Remove( pDisplay ); } #ifdef _SV_SALDISP_HXX inline void SalData::XError( Display *pDisplay, XErrorEvent *pEvent ) const { pXLib_->XError( pDisplay, pEvent ); } #endif class YieldMutexReleaser { ULONG m_nYieldCount; SalYieldMutex* m_pSalInstYieldMutex; public: inline YieldMutexReleaser(); inline ~YieldMutexReleaser(); }; inline YieldMutexReleaser::YieldMutexReleaser() { SalData *pSalData = GetSalData(); m_pSalInstYieldMutex = pSalData->pFirstInstance_->maInstData.mpSalYieldMutex; ULONG i; if ( m_pSalInstYieldMutex->GetThreadId() == NAMESPACE_VOS(OThread)::getCurrentIdentifier() ) { m_nYieldCount = m_pSalInstYieldMutex->GetAcquireCount(); for ( i = 0; i < m_nYieldCount; i++ ) m_pSalInstYieldMutex->release(); } else m_nYieldCount = 0; } inline YieldMutexReleaser::~YieldMutexReleaser() { // Yield-Semaphore wieder holen while ( m_nYieldCount ) { m_pSalInstYieldMutex->acquire(); m_nYieldCount--; } } #endif // _SV_SALDATA_HXX <|endoftext|>
<commit_before>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrGLUtil.h" #include "SkMatrix.h" #include <stdio.h> void GrGLClearErr(const GrGLInterface* gl) { while (GR_GL_NO_ERROR != gl->fFunctions.fGetError()) {} } namespace { const char *get_error_string(uint32_t err) { switch (err) { case GR_GL_NO_ERROR: return ""; case GR_GL_INVALID_ENUM: return "Invalid Enum"; case GR_GL_INVALID_VALUE: return "Invalid Value"; case GR_GL_INVALID_OPERATION: return "Invalid Operation"; case GR_GL_OUT_OF_MEMORY: return "Out of Memory"; case GR_GL_CONTEXT_LOST: return "Context Lost"; } return "Unknown"; } } void GrGLCheckErr(const GrGLInterface* gl, const char* location, const char* call) { uint32_t err = GR_GL_GET_ERROR(gl); if (GR_GL_NO_ERROR != err) { SkDebugf("---- glGetError 0x%x(%s)", err, get_error_string(err)); if (location) { SkDebugf(" at\n\t%s", location); } if (call) { SkDebugf("\n\t\t%s", call); } SkDebugf("\n"); } } /////////////////////////////////////////////////////////////////////////////// #if GR_GL_LOG_CALLS bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START); #endif #if GR_GL_CHECK_ERROR bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START); #endif /////////////////////////////////////////////////////////////////////////////// GrGLStandard GrGLGetStandardInUseFromString(const char* versionString) { if (nullptr == versionString) { SkDebugf("nullptr GL version string."); return kNone_GrGLStandard; } int major, minor; // check for desktop int n = sscanf(versionString, "%d.%d", &major, &minor); if (2 == n) { return kGL_GrGLStandard; } // check for ES 1 char profile[2]; n = sscanf(versionString, "OpenGL ES-%c%c %d.%d", profile, profile+1, &major, &minor); if (4 == n) { // we no longer support ES1. return kNone_GrGLStandard; } // check for ES2 n = sscanf(versionString, "OpenGL ES %d.%d", &major, &minor); if (2 == n) { return kGLES_GrGLStandard; } return kNone_GrGLStandard; } void GrGLGetDriverInfo(GrGLStandard standard, GrGLVendor vendor, const char* rendererString, const char* versionString, GrGLDriver* outDriver, GrGLDriverVersion* outVersion) { int major, minor, rev, driverMajor, driverMinor; *outDriver = kUnknown_GrGLDriver; *outVersion = GR_GL_DRIVER_UNKNOWN_VER; // These null checks are for test GL contexts that return nullptr in their // glGetString implementation. if (!rendererString) { rendererString = ""; } if (!versionString) { versionString = ""; } if (0 == strcmp(rendererString, "Chromium")) { *outDriver = kChromium_GrGLDriver; return; } if (standard == kGL_GrGLStandard) { if (kNVIDIA_GrGLVendor == vendor) { *outDriver = kNVIDIA_GrGLDriver; int n = sscanf(versionString, "%d.%d.%d NVIDIA %d.%d", &major, &minor, &rev, &driverMajor, &driverMinor); // Some older NVIDIA drivers don't report the driver version. if (5 == n) { *outVersion = GR_GL_DRIVER_VER(driverMajor, driverMinor); } return; } int n = sscanf(versionString, "%d.%d Mesa %d.%d", &major, &minor, &driverMajor, &driverMinor); if (4 == n) { *outDriver = kMesa_GrGLDriver; *outVersion = GR_GL_DRIVER_VER(driverMajor, driverMinor); return; } } else { if (kNVIDIA_GrGLVendor == vendor) { *outDriver = kNVIDIA_GrGLDriver; int n = sscanf(versionString, "OpenGL ES %d.%d NVIDIA %d.%d", &major, &minor, &driverMajor, &driverMinor); // Some older NVIDIA drivers don't report the driver version. if (4 == n) { *outVersion = GR_GL_DRIVER_VER(driverMajor, driverMinor); } return; } int n = sscanf(versionString, "OpenGL ES %d.%d Mesa %d.%d", &major, &minor, &driverMajor, &driverMinor); if (4 == n) { *outDriver = kMesa_GrGLDriver; *outVersion = GR_GL_DRIVER_VER(driverMajor, driverMinor); return; } if (0 == strncmp("ANGLE", rendererString, 5)) { *outDriver = kANGLE_GrGLDriver; n = sscanf(versionString, "OpenGL ES %d.%d (ANGLE %d.%d", &major, &minor, &driverMajor, &driverMinor); if (4 == n) { *outVersion = GR_GL_DRIVER_VER(driverMajor, driverMinor); } return; } } if (kIntel_GrGLVendor == vendor) { // We presume we're on the Intel driver since it hasn't identified itself as Mesa. *outDriver = kIntel_GrGLDriver; } } GrGLVersion GrGLGetVersionFromString(const char* versionString) { if (nullptr == versionString) { SkDebugf("nullptr GL version string."); return GR_GL_INVALID_VER; } int major, minor; // check for mesa int mesaMajor, mesaMinor; int n = sscanf(versionString, "%d.%d Mesa %d.%d", &major, &minor, &mesaMajor, &mesaMinor); if (4 == n) { return GR_GL_VER(major, minor); } n = sscanf(versionString, "%d.%d", &major, &minor); if (2 == n) { return GR_GL_VER(major, minor); } char profile[2]; n = sscanf(versionString, "OpenGL ES-%c%c %d.%d", profile, profile+1, &major, &minor); if (4 == n) { return GR_GL_VER(major, minor); } n = sscanf(versionString, "OpenGL ES %d.%d", &major, &minor); if (2 == n) { return GR_GL_VER(major, minor); } return GR_GL_INVALID_VER; } GrGLSLVersion GrGLGetGLSLVersionFromString(const char* versionString) { if (nullptr == versionString) { SkDebugf("nullptr GLSL version string."); return GR_GLSL_INVALID_VER; } int major, minor; int n = sscanf(versionString, "%d.%d", &major, &minor); if (2 == n) { return GR_GLSL_VER(major, minor); } n = sscanf(versionString, "OpenGL ES GLSL ES %d.%d", &major, &minor); if (2 == n) { return GR_GLSL_VER(major, minor); } #ifdef SK_BUILD_FOR_ANDROID // android hack until the gpu vender updates their drivers n = sscanf(versionString, "OpenGL ES GLSL %d.%d", &major, &minor); if (2 == n) { return GR_GLSL_VER(major, minor); } #endif return GR_GLSL_INVALID_VER; } GrGLVendor GrGLGetVendorFromString(const char* vendorString) { if (vendorString) { if (0 == strcmp(vendorString, "ARM")) { return kARM_GrGLVendor; } if (0 == strcmp(vendorString, "Imagination Technologies")) { return kImagination_GrGLVendor; } if (0 == strncmp(vendorString, "Intel ", 6) || 0 == strcmp(vendorString, "Intel")) { return kIntel_GrGLVendor; } if (0 == strcmp(vendorString, "Qualcomm")) { return kQualcomm_GrGLVendor; } if (0 == strcmp(vendorString, "NVIDIA Corporation")) { return kNVIDIA_GrGLVendor; } if (0 == strcmp(vendorString, "ATI Technologies Inc.")) { return kATI_GrGLVendor; } } return kOther_GrGLVendor; } GrGLRenderer GrGLGetRendererFromString(const char* rendererString) { if (rendererString) { if (0 == strcmp(rendererString, "NVIDIA Tegra 3")) { return kTegra3_GrGLRenderer; } else if (0 == strcmp(rendererString, "NVIDIA Tegra")) { return kTegra2_GrGLRenderer; } int lastDigit; int n = sscanf(rendererString, "PowerVR SGX 54%d", &lastDigit); if (1 == n && lastDigit >= 0 && lastDigit <= 9) { return kPowerVR54x_GrGLRenderer; } // certain iOS devices also use PowerVR54x GPUs static const char kAppleA4Str[] = "Apple A4"; static const char kAppleA5Str[] = "Apple A5"; static const char kAppleA6Str[] = "Apple A6"; if (0 == strncmp(rendererString, kAppleA4Str, SK_ARRAY_COUNT(kAppleA4Str)-1) || 0 == strncmp(rendererString, kAppleA5Str, SK_ARRAY_COUNT(kAppleA5Str)-1) || 0 == strncmp(rendererString, kAppleA6Str, SK_ARRAY_COUNT(kAppleA6Str)-1)) { return kPowerVR54x_GrGLRenderer; } static const char kPowerVRRogueStr[] = "PowerVR Rogue"; static const char kAppleA7Str[] = "Apple A7"; static const char kAppleA8Str[] = "Apple A8"; if (0 == strncmp(rendererString, kPowerVRRogueStr, SK_ARRAY_COUNT(kPowerVRRogueStr)-1) || 0 == strncmp(rendererString, kAppleA7Str, SK_ARRAY_COUNT(kAppleA7Str)-1) || 0 == strncmp(rendererString, kAppleA8Str, SK_ARRAY_COUNT(kAppleA8Str)-1)) { return kPowerVRRogue_GrGLRenderer; } int adrenoNumber; n = sscanf(rendererString, "Adreno (TM) %d", &adrenoNumber); if (1 == n) { if (adrenoNumber >= 300) { if (adrenoNumber < 400) { return kAdreno3xx_GrGLRenderer; } if (adrenoNumber < 500) { return kAdreno4xx_GrGLRenderer; } if (adrenoNumber < 600) { return kAdreno5xx_GrGLRenderer; } } } if (0 == strcmp("Mesa Offscreen", rendererString)) { return kOSMesa_GrGLRenderer; } } return kOther_GrGLRenderer; } GrGLVersion GrGLGetVersion(const GrGLInterface* gl) { const GrGLubyte* v; GR_GL_CALL_RET(gl, v, GetString(GR_GL_VERSION)); return GrGLGetVersionFromString((const char*) v); } GrGLSLVersion GrGLGetGLSLVersion(const GrGLInterface* gl) { const GrGLubyte* v; GR_GL_CALL_RET(gl, v, GetString(GR_GL_SHADING_LANGUAGE_VERSION)); return GrGLGetGLSLVersionFromString((const char*) v); } GrGLVendor GrGLGetVendor(const GrGLInterface* gl) { const GrGLubyte* v; GR_GL_CALL_RET(gl, v, GetString(GR_GL_VENDOR)); return GrGLGetVendorFromString((const char*) v); } GrGLRenderer GrGLGetRenderer(const GrGLInterface* gl) { const GrGLubyte* v; GR_GL_CALL_RET(gl, v, GetString(GR_GL_RENDERER)); return GrGLGetRendererFromString((const char*) v); } GrGLenum GrToGLStencilFunc(GrStencilTest test) { static const GrGLenum gTable[kGrStencilTestCount] = { GR_GL_ALWAYS, // kAlways GR_GL_NEVER, // kNever GR_GL_GREATER, // kGreater GR_GL_GEQUAL, // kGEqual GR_GL_LESS, // kLess GR_GL_LEQUAL, // kLEqual GR_GL_EQUAL, // kEqual GR_GL_NOTEQUAL, // kNotEqual }; GR_STATIC_ASSERT(0 == (int)GrStencilTest::kAlways); GR_STATIC_ASSERT(1 == (int)GrStencilTest::kNever); GR_STATIC_ASSERT(2 == (int)GrStencilTest::kGreater); GR_STATIC_ASSERT(3 == (int)GrStencilTest::kGEqual); GR_STATIC_ASSERT(4 == (int)GrStencilTest::kLess); GR_STATIC_ASSERT(5 == (int)GrStencilTest::kLEqual); GR_STATIC_ASSERT(6 == (int)GrStencilTest::kEqual); GR_STATIC_ASSERT(7 == (int)GrStencilTest::kNotEqual); SkASSERT(test < (GrStencilTest)kGrStencilTestCount); return gTable[(int)test]; } <commit_msg>Detect Chrome either by renderer or version strings.<commit_after>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrGLUtil.h" #include "SkMatrix.h" #include <stdio.h> void GrGLClearErr(const GrGLInterface* gl) { while (GR_GL_NO_ERROR != gl->fFunctions.fGetError()) {} } namespace { const char *get_error_string(uint32_t err) { switch (err) { case GR_GL_NO_ERROR: return ""; case GR_GL_INVALID_ENUM: return "Invalid Enum"; case GR_GL_INVALID_VALUE: return "Invalid Value"; case GR_GL_INVALID_OPERATION: return "Invalid Operation"; case GR_GL_OUT_OF_MEMORY: return "Out of Memory"; case GR_GL_CONTEXT_LOST: return "Context Lost"; } return "Unknown"; } } void GrGLCheckErr(const GrGLInterface* gl, const char* location, const char* call) { uint32_t err = GR_GL_GET_ERROR(gl); if (GR_GL_NO_ERROR != err) { SkDebugf("---- glGetError 0x%x(%s)", err, get_error_string(err)); if (location) { SkDebugf(" at\n\t%s", location); } if (call) { SkDebugf("\n\t\t%s", call); } SkDebugf("\n"); } } /////////////////////////////////////////////////////////////////////////////// #if GR_GL_LOG_CALLS bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START); #endif #if GR_GL_CHECK_ERROR bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START); #endif /////////////////////////////////////////////////////////////////////////////// GrGLStandard GrGLGetStandardInUseFromString(const char* versionString) { if (nullptr == versionString) { SkDebugf("nullptr GL version string."); return kNone_GrGLStandard; } int major, minor; // check for desktop int n = sscanf(versionString, "%d.%d", &major, &minor); if (2 == n) { return kGL_GrGLStandard; } // check for ES 1 char profile[2]; n = sscanf(versionString, "OpenGL ES-%c%c %d.%d", profile, profile+1, &major, &minor); if (4 == n) { // we no longer support ES1. return kNone_GrGLStandard; } // check for ES2 n = sscanf(versionString, "OpenGL ES %d.%d", &major, &minor); if (2 == n) { return kGLES_GrGLStandard; } return kNone_GrGLStandard; } void GrGLGetDriverInfo(GrGLStandard standard, GrGLVendor vendor, const char* rendererString, const char* versionString, GrGLDriver* outDriver, GrGLDriverVersion* outVersion) { int major, minor, rev, driverMajor, driverMinor; *outDriver = kUnknown_GrGLDriver; *outVersion = GR_GL_DRIVER_UNKNOWN_VER; // These null checks are for test GL contexts that return nullptr in their // glGetString implementation. if (!rendererString) { rendererString = ""; } if (!versionString) { versionString = ""; } if (0 == strcmp(rendererString, "Chromium") || 2 == sscanf(versionString, "OpenGL ES %d.%d Chromium", &major, &minor)) { *outDriver = kChromium_GrGLDriver; return; } if (standard == kGL_GrGLStandard) { if (kNVIDIA_GrGLVendor == vendor) { *outDriver = kNVIDIA_GrGLDriver; int n = sscanf(versionString, "%d.%d.%d NVIDIA %d.%d", &major, &minor, &rev, &driverMajor, &driverMinor); // Some older NVIDIA drivers don't report the driver version. if (5 == n) { *outVersion = GR_GL_DRIVER_VER(driverMajor, driverMinor); } return; } int n = sscanf(versionString, "%d.%d Mesa %d.%d", &major, &minor, &driverMajor, &driverMinor); if (4 == n) { *outDriver = kMesa_GrGLDriver; *outVersion = GR_GL_DRIVER_VER(driverMajor, driverMinor); return; } } else { if (kNVIDIA_GrGLVendor == vendor) { *outDriver = kNVIDIA_GrGLDriver; int n = sscanf(versionString, "OpenGL ES %d.%d NVIDIA %d.%d", &major, &minor, &driverMajor, &driverMinor); // Some older NVIDIA drivers don't report the driver version. if (4 == n) { *outVersion = GR_GL_DRIVER_VER(driverMajor, driverMinor); } return; } int n = sscanf(versionString, "OpenGL ES %d.%d Mesa %d.%d", &major, &minor, &driverMajor, &driverMinor); if (4 == n) { *outDriver = kMesa_GrGLDriver; *outVersion = GR_GL_DRIVER_VER(driverMajor, driverMinor); return; } if (0 == strncmp("ANGLE", rendererString, 5)) { *outDriver = kANGLE_GrGLDriver; n = sscanf(versionString, "OpenGL ES %d.%d (ANGLE %d.%d", &major, &minor, &driverMajor, &driverMinor); if (4 == n) { *outVersion = GR_GL_DRIVER_VER(driverMajor, driverMinor); } return; } } if (kIntel_GrGLVendor == vendor) { // We presume we're on the Intel driver since it hasn't identified itself as Mesa. *outDriver = kIntel_GrGLDriver; } } GrGLVersion GrGLGetVersionFromString(const char* versionString) { if (nullptr == versionString) { SkDebugf("nullptr GL version string."); return GR_GL_INVALID_VER; } int major, minor; // check for mesa int mesaMajor, mesaMinor; int n = sscanf(versionString, "%d.%d Mesa %d.%d", &major, &minor, &mesaMajor, &mesaMinor); if (4 == n) { return GR_GL_VER(major, minor); } n = sscanf(versionString, "%d.%d", &major, &minor); if (2 == n) { return GR_GL_VER(major, minor); } char profile[2]; n = sscanf(versionString, "OpenGL ES-%c%c %d.%d", profile, profile+1, &major, &minor); if (4 == n) { return GR_GL_VER(major, minor); } n = sscanf(versionString, "OpenGL ES %d.%d", &major, &minor); if (2 == n) { return GR_GL_VER(major, minor); } return GR_GL_INVALID_VER; } GrGLSLVersion GrGLGetGLSLVersionFromString(const char* versionString) { if (nullptr == versionString) { SkDebugf("nullptr GLSL version string."); return GR_GLSL_INVALID_VER; } int major, minor; int n = sscanf(versionString, "%d.%d", &major, &minor); if (2 == n) { return GR_GLSL_VER(major, minor); } n = sscanf(versionString, "OpenGL ES GLSL ES %d.%d", &major, &minor); if (2 == n) { return GR_GLSL_VER(major, minor); } #ifdef SK_BUILD_FOR_ANDROID // android hack until the gpu vender updates their drivers n = sscanf(versionString, "OpenGL ES GLSL %d.%d", &major, &minor); if (2 == n) { return GR_GLSL_VER(major, minor); } #endif return GR_GLSL_INVALID_VER; } GrGLVendor GrGLGetVendorFromString(const char* vendorString) { if (vendorString) { if (0 == strcmp(vendorString, "ARM")) { return kARM_GrGLVendor; } if (0 == strcmp(vendorString, "Imagination Technologies")) { return kImagination_GrGLVendor; } if (0 == strncmp(vendorString, "Intel ", 6) || 0 == strcmp(vendorString, "Intel")) { return kIntel_GrGLVendor; } if (0 == strcmp(vendorString, "Qualcomm")) { return kQualcomm_GrGLVendor; } if (0 == strcmp(vendorString, "NVIDIA Corporation")) { return kNVIDIA_GrGLVendor; } if (0 == strcmp(vendorString, "ATI Technologies Inc.")) { return kATI_GrGLVendor; } } return kOther_GrGLVendor; } GrGLRenderer GrGLGetRendererFromString(const char* rendererString) { if (rendererString) { if (0 == strcmp(rendererString, "NVIDIA Tegra 3")) { return kTegra3_GrGLRenderer; } else if (0 == strcmp(rendererString, "NVIDIA Tegra")) { return kTegra2_GrGLRenderer; } int lastDigit; int n = sscanf(rendererString, "PowerVR SGX 54%d", &lastDigit); if (1 == n && lastDigit >= 0 && lastDigit <= 9) { return kPowerVR54x_GrGLRenderer; } // certain iOS devices also use PowerVR54x GPUs static const char kAppleA4Str[] = "Apple A4"; static const char kAppleA5Str[] = "Apple A5"; static const char kAppleA6Str[] = "Apple A6"; if (0 == strncmp(rendererString, kAppleA4Str, SK_ARRAY_COUNT(kAppleA4Str)-1) || 0 == strncmp(rendererString, kAppleA5Str, SK_ARRAY_COUNT(kAppleA5Str)-1) || 0 == strncmp(rendererString, kAppleA6Str, SK_ARRAY_COUNT(kAppleA6Str)-1)) { return kPowerVR54x_GrGLRenderer; } static const char kPowerVRRogueStr[] = "PowerVR Rogue"; static const char kAppleA7Str[] = "Apple A7"; static const char kAppleA8Str[] = "Apple A8"; if (0 == strncmp(rendererString, kPowerVRRogueStr, SK_ARRAY_COUNT(kPowerVRRogueStr)-1) || 0 == strncmp(rendererString, kAppleA7Str, SK_ARRAY_COUNT(kAppleA7Str)-1) || 0 == strncmp(rendererString, kAppleA8Str, SK_ARRAY_COUNT(kAppleA8Str)-1)) { return kPowerVRRogue_GrGLRenderer; } int adrenoNumber; n = sscanf(rendererString, "Adreno (TM) %d", &adrenoNumber); if (1 == n) { if (adrenoNumber >= 300) { if (adrenoNumber < 400) { return kAdreno3xx_GrGLRenderer; } if (adrenoNumber < 500) { return kAdreno4xx_GrGLRenderer; } if (adrenoNumber < 600) { return kAdreno5xx_GrGLRenderer; } } } if (0 == strcmp("Mesa Offscreen", rendererString)) { return kOSMesa_GrGLRenderer; } } return kOther_GrGLRenderer; } GrGLVersion GrGLGetVersion(const GrGLInterface* gl) { const GrGLubyte* v; GR_GL_CALL_RET(gl, v, GetString(GR_GL_VERSION)); return GrGLGetVersionFromString((const char*) v); } GrGLSLVersion GrGLGetGLSLVersion(const GrGLInterface* gl) { const GrGLubyte* v; GR_GL_CALL_RET(gl, v, GetString(GR_GL_SHADING_LANGUAGE_VERSION)); return GrGLGetGLSLVersionFromString((const char*) v); } GrGLVendor GrGLGetVendor(const GrGLInterface* gl) { const GrGLubyte* v; GR_GL_CALL_RET(gl, v, GetString(GR_GL_VENDOR)); return GrGLGetVendorFromString((const char*) v); } GrGLRenderer GrGLGetRenderer(const GrGLInterface* gl) { const GrGLubyte* v; GR_GL_CALL_RET(gl, v, GetString(GR_GL_RENDERER)); return GrGLGetRendererFromString((const char*) v); } GrGLenum GrToGLStencilFunc(GrStencilTest test) { static const GrGLenum gTable[kGrStencilTestCount] = { GR_GL_ALWAYS, // kAlways GR_GL_NEVER, // kNever GR_GL_GREATER, // kGreater GR_GL_GEQUAL, // kGEqual GR_GL_LESS, // kLess GR_GL_LEQUAL, // kLEqual GR_GL_EQUAL, // kEqual GR_GL_NOTEQUAL, // kNotEqual }; GR_STATIC_ASSERT(0 == (int)GrStencilTest::kAlways); GR_STATIC_ASSERT(1 == (int)GrStencilTest::kNever); GR_STATIC_ASSERT(2 == (int)GrStencilTest::kGreater); GR_STATIC_ASSERT(3 == (int)GrStencilTest::kGEqual); GR_STATIC_ASSERT(4 == (int)GrStencilTest::kLess); GR_STATIC_ASSERT(5 == (int)GrStencilTest::kLEqual); GR_STATIC_ASSERT(6 == (int)GrStencilTest::kEqual); GR_STATIC_ASSERT(7 == (int)GrStencilTest::kNotEqual); SkASSERT(test < (GrStencilTest)kGrStencilTestCount); return gTable[(int)test]; } <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg 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 author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/storage.hpp" #include <deque> #include "libtorrent/disk_io_thread.hpp" namespace libtorrent { disk_io_thread::disk_io_thread(int block_size) : m_abort(false) , m_queue_buffer_size(0) , m_pool(block_size) , m_disk_io_thread(boost::ref(*this)) {} disk_io_thread::~disk_io_thread() { boost::mutex::scoped_lock l(m_mutex); m_abort = true; m_signal.notify_all(); l.unlock(); m_disk_io_thread.join(); } // aborts read operations void disk_io_thread::stop(boost::intrusive_ptr<piece_manager> s) { boost::mutex::scoped_lock l(m_mutex); // read jobs are aborted, write and move jobs are syncronized for (std::deque<disk_io_job>::iterator i = m_jobs.begin(); i != m_jobs.end();) { if (i->storage != s) { ++i; continue; } if (i->action == disk_io_job::read) { i->callback(-1, *i); m_jobs.erase(i++); continue; } ++i; } m_signal.notify_all(); } bool range_overlap(int start1, int length1, int start2, int length2) { return (start1 <= start2 && start1 + length1 > start2) || (start2 <= start1 && start2 + length2 > start1); } namespace { bool operator<(disk_io_job const& lhs, disk_io_job const& rhs) { if (lhs.storage.get() < rhs.storage.get()) return true; if (lhs.storage.get() > rhs.storage.get()) return false; if (lhs.piece < rhs.piece) return true; if (lhs.piece > rhs.piece) return false; if (lhs.offset < rhs.offset) return true; // if (lhs.offset > rhs.offset) return false; return false; } } void disk_io_thread::add_job(disk_io_job const& j , boost::function<void(int, disk_io_job const&)> const& f) { assert(!j.callback); boost::mutex::scoped_lock l(m_mutex); std::deque<disk_io_job>::reverse_iterator i = m_jobs.rbegin(); if (j.action == disk_io_job::read) { // when we're reading, we may not skip // ahead of any write operation that overlaps // the region we're reading for (; i != m_jobs.rend(); ++i) { if (i->action == disk_io_job::read && *i < j) break; if (i->action == disk_io_job::write && i->storage == j.storage && i->piece == j.piece && range_overlap(i->offset, i->buffer_size , j.offset, j.buffer_size)) { // we have to stop, and we haven't // found a suitable place for this job // so just queue it up at the end i = m_jobs.rbegin(); break; } } } else if (j.action == disk_io_job::write) { for (; i != m_jobs.rend(); ++i) { if (i->action == disk_io_job::write && *i < j) { if (i != m_jobs.rbegin() && i.base()->storage.get() != j.storage.get()) i = m_jobs.rbegin(); break; } } } if (i == m_jobs.rend()) i = m_jobs.rbegin(); std::deque<disk_io_job>::iterator k = m_jobs.insert(i.base(), j); k->callback.swap(const_cast<boost::function<void(int, disk_io_job const&)>&>(f)); if (j.action == disk_io_job::write) m_queue_buffer_size += j.buffer_size; assert(j.storage.get()); m_signal.notify_all(); } char* disk_io_thread::allocate_buffer() { boost::mutex::scoped_lock l(m_mutex); return (char*)m_pool.ordered_malloc(); } void disk_io_thread::operator()() { for (;;) { boost::mutex::scoped_lock l(m_mutex); while (m_jobs.empty() && !m_abort) m_signal.wait(l); if (m_abort && m_jobs.empty()) return; boost::function<void(int, disk_io_job const&)> handler; handler.swap(m_jobs.front().callback); disk_io_job j = m_jobs.front(); m_jobs.pop_front(); m_queue_buffer_size -= j.buffer_size; l.unlock(); int ret = 0; try { // std::cerr << "DISK THREAD: executing job: " << j.action << std::endl; switch (j.action) { case disk_io_job::read: l.lock(); j.buffer = (char*)m_pool.ordered_malloc(); l.unlock(); if (j.buffer == 0) { ret = -1; j.str = "out of memory"; } else { ret = j.storage->read_impl(j.buffer, j.piece, j.offset , j.buffer_size); // simulates slow drives // usleep(300); } break; case disk_io_job::write: assert(j.buffer); j.storage->write_impl(j.buffer, j.piece, j.offset , j.buffer_size); // simulates a slow drive // usleep(300); break; case disk_io_job::hash: { sha1_hash h = j.storage->hash_for_piece_impl(j.piece); j.str.resize(20); std::memcpy(&j.str[0], &h[0], 20); } break; case disk_io_job::move_storage: ret = j.storage->move_storage_impl(j.str) ? 1 : 0; break; case disk_io_job::release_files: j.storage->release_files_impl(); break; } } catch (std::exception& e) { // std::cerr << "DISK THREAD: exception: " << e.what() << std::endl; j.str = e.what(); ret = -1; } // if (!handler) std::cerr << "DISK THREAD: no callback specified" << std::endl; // else std::cerr << "DISK THREAD: invoking callback" << std::endl; try { if (handler) handler(ret, j); } catch (std::exception&) {} if (j.buffer) m_pool.ordered_free(j.buffer); } } } <commit_msg>fixed mutex issue in disk io thread<commit_after>/* Copyright (c) 2007, Arvid Norberg 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 author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/storage.hpp" #include <deque> #include "libtorrent/disk_io_thread.hpp" namespace libtorrent { disk_io_thread::disk_io_thread(int block_size) : m_abort(false) , m_queue_buffer_size(0) , m_pool(block_size) , m_disk_io_thread(boost::ref(*this)) {} disk_io_thread::~disk_io_thread() { boost::mutex::scoped_lock l(m_mutex); m_abort = true; m_signal.notify_all(); l.unlock(); m_disk_io_thread.join(); } // aborts read operations void disk_io_thread::stop(boost::intrusive_ptr<piece_manager> s) { boost::mutex::scoped_lock l(m_mutex); // read jobs are aborted, write and move jobs are syncronized for (std::deque<disk_io_job>::iterator i = m_jobs.begin(); i != m_jobs.end();) { if (i->storage != s) { ++i; continue; } if (i->action == disk_io_job::read) { i->callback(-1, *i); m_jobs.erase(i++); continue; } ++i; } m_signal.notify_all(); } bool range_overlap(int start1, int length1, int start2, int length2) { return (start1 <= start2 && start1 + length1 > start2) || (start2 <= start1 && start2 + length2 > start1); } namespace { bool operator<(disk_io_job const& lhs, disk_io_job const& rhs) { if (lhs.storage.get() < rhs.storage.get()) return true; if (lhs.storage.get() > rhs.storage.get()) return false; if (lhs.piece < rhs.piece) return true; if (lhs.piece > rhs.piece) return false; if (lhs.offset < rhs.offset) return true; // if (lhs.offset > rhs.offset) return false; return false; } } void disk_io_thread::add_job(disk_io_job const& j , boost::function<void(int, disk_io_job const&)> const& f) { assert(!j.callback); boost::mutex::scoped_lock l(m_mutex); std::deque<disk_io_job>::reverse_iterator i = m_jobs.rbegin(); if (j.action == disk_io_job::read) { // when we're reading, we may not skip // ahead of any write operation that overlaps // the region we're reading for (; i != m_jobs.rend(); ++i) { if (i->action == disk_io_job::read && *i < j) break; if (i->action == disk_io_job::write && i->storage == j.storage && i->piece == j.piece && range_overlap(i->offset, i->buffer_size , j.offset, j.buffer_size)) { // we have to stop, and we haven't // found a suitable place for this job // so just queue it up at the end i = m_jobs.rbegin(); break; } } } else if (j.action == disk_io_job::write) { for (; i != m_jobs.rend(); ++i) { if (i->action == disk_io_job::write && *i < j) { if (i != m_jobs.rbegin() && i.base()->storage.get() != j.storage.get()) i = m_jobs.rbegin(); break; } } } if (i == m_jobs.rend()) i = m_jobs.rbegin(); std::deque<disk_io_job>::iterator k = m_jobs.insert(i.base(), j); k->callback.swap(const_cast<boost::function<void(int, disk_io_job const&)>&>(f)); if (j.action == disk_io_job::write) m_queue_buffer_size += j.buffer_size; assert(j.storage.get()); m_signal.notify_all(); } char* disk_io_thread::allocate_buffer() { boost::mutex::scoped_lock l(m_mutex); return (char*)m_pool.ordered_malloc(); } void disk_io_thread::operator()() { for (;;) { boost::mutex::scoped_lock l(m_mutex); while (m_jobs.empty() && !m_abort) m_signal.wait(l); if (m_abort && m_jobs.empty()) return; boost::function<void(int, disk_io_job const&)> handler; handler.swap(m_jobs.front().callback); disk_io_job j = m_jobs.front(); m_jobs.pop_front(); m_queue_buffer_size -= j.buffer_size; l.unlock(); int ret = 0; try { // std::cerr << "DISK THREAD: executing job: " << j.action << std::endl; switch (j.action) { case disk_io_job::read: l.lock(); j.buffer = (char*)m_pool.ordered_malloc(); l.unlock(); if (j.buffer == 0) { ret = -1; j.str = "out of memory"; } else { ret = j.storage->read_impl(j.buffer, j.piece, j.offset , j.buffer_size); // simulates slow drives // usleep(300); } break; case disk_io_job::write: assert(j.buffer); j.storage->write_impl(j.buffer, j.piece, j.offset , j.buffer_size); // simulates a slow drive // usleep(300); break; case disk_io_job::hash: { sha1_hash h = j.storage->hash_for_piece_impl(j.piece); j.str.resize(20); std::memcpy(&j.str[0], &h[0], 20); } break; case disk_io_job::move_storage: ret = j.storage->move_storage_impl(j.str) ? 1 : 0; break; case disk_io_job::release_files: j.storage->release_files_impl(); break; } } catch (std::exception& e) { // std::cerr << "DISK THREAD: exception: " << e.what() << std::endl; j.str = e.what(); ret = -1; } // if (!handler) std::cerr << "DISK THREAD: no callback specified" << std::endl; // else std::cerr << "DISK THREAD: invoking callback" << std::endl; try { if (handler) handler(ret, j); } catch (std::exception&) {} if (j.buffer) { l.lock(); m_pool.ordered_free(j.buffer); } } } } <|endoftext|>
<commit_before>#include "DataSetModel.hh" #include "DataSetItem.hh" #include "MetaTypes.hh" #include <QDebug> #include <QIcon> namespace aleph { namespace gui { DataSetModel::DataSetModel( QObject* parent ) : QAbstractItemModel( parent ) , _root( new DataSetItem( QString(), QVariant() ) ) { QList<DataSetItem*> topLevelItems = { new DataSetItem( tr("Persistence diagrams"), QVariant::fromValue( PersistenceDiagram() ), _root ), new DataSetItem( tr("Point clouds") , QVariant::fromValue( SimplicialComplex() ), _root ), new DataSetItem( tr("Simplicial complexes"), QVariant(), _root ) }; foreach( DataSetItem* item, topLevelItems ) _root->append( item ); } DataSetModel::~DataSetModel() { delete _root; } QModelIndex DataSetModel::parent( const QModelIndex& index ) const { if( !index.isValid() ) return QModelIndex(); auto child = static_cast<DataSetItem*>( index.internalPointer() ); auto parent = child->parent(); if( parent == _root ) return QModelIndex(); return this->createIndex( parent->row(), 0, parent ); } QModelIndex DataSetModel::index( int row, int column, const QModelIndex& parent ) const { if( !this->hasIndex( row, column, parent ) ) return QModelIndex(); DataSetItem* parentItem = nullptr; if( !parent.isValid() ) parentItem = _root; else parentItem = static_cast<DataSetItem*>( parent.internalPointer() ); auto child = parentItem->child( row ); if( child ) return this->createIndex( row, column, child ); else return QModelIndex(); } int DataSetModel::rowCount( const QModelIndex& parent ) const { DataSetItem* parentItem = nullptr; if( parent.column() > 0 ) return 0; if( !parent.isValid() ) parentItem = _root; else parentItem = static_cast<DataSetItem*>( parent.internalPointer() ); return parentItem->childCount(); } int DataSetModel::columnCount( const QModelIndex& parent ) const { if( parent.isValid() ) return static_cast<DataSetItem*>( parent.internalPointer() )->columnCount(); else return _root->columnCount(); } QVariant DataSetModel::headerData( int section, Qt::Orientation orientation, int role ) const { if( orientation == Qt::Horizontal && role == Qt::DisplayRole ) return DataSetItem::columnNames[section]; return QVariant(); } QVariant DataSetModel::data( const QModelIndex& index, int role ) const { if( !index.isValid() ) return QVariant(); DataSetItem* item = static_cast<DataSetItem*>( index.internalPointer() ); if( role == Qt::DecorationRole && index.column() == 0 && item->parent() == _root ) return QIcon::fromTheme( "folder" ); else if( role == Qt::DisplayRole ) return item->data( index.column() ); return QVariant(); } void DataSetModel::add( const QString& title, const QVariant& data ) { int id_PersistenceDiagram = qMetaTypeId<PersistenceDiagram>(); int id_SimplicialComplex = qMetaTypeId<SimplicialComplex>(); int userType = data.userType(); if( userType != id_PersistenceDiagram && userType != id_SimplicialComplex ) { qDebug() << "Ignoring unknown user type"; return; } for( int i = 0; i < _root->childCount(); i++ ) { auto child = _root->child( i ); if( child && child->type() == userType ) { qDebug() << "Found proper parent item; adding data"; child->append( new DataSetItem( title, data, child ) ); } } } } // namespace gui } // namespace aleph <commit_msg>Fixed addition of simplicial complexes to data set viewer<commit_after>#include "DataSetModel.hh" #include "DataSetItem.hh" #include "MetaTypes.hh" #include <QDebug> #include <QIcon> namespace aleph { namespace gui { DataSetModel::DataSetModel( QObject* parent ) : QAbstractItemModel( parent ) , _root( new DataSetItem( QString(), QVariant() ) ) { QList<DataSetItem*> topLevelItems = { new DataSetItem( tr("Persistence diagrams"), QVariant::fromValue( PersistenceDiagram() ), _root ), new DataSetItem( tr("Point clouds") , QVariant(), _root ), new DataSetItem( tr("Simplicial complexes"), QVariant::fromValue( SimplicialComplex() ), _root ) }; foreach( DataSetItem* item, topLevelItems ) _root->append( item ); } DataSetModel::~DataSetModel() { delete _root; } QModelIndex DataSetModel::parent( const QModelIndex& index ) const { if( !index.isValid() ) return QModelIndex(); auto child = static_cast<DataSetItem*>( index.internalPointer() ); auto parent = child->parent(); if( parent == _root ) return QModelIndex(); return this->createIndex( parent->row(), 0, parent ); } QModelIndex DataSetModel::index( int row, int column, const QModelIndex& parent ) const { if( !this->hasIndex( row, column, parent ) ) return QModelIndex(); DataSetItem* parentItem = nullptr; if( !parent.isValid() ) parentItem = _root; else parentItem = static_cast<DataSetItem*>( parent.internalPointer() ); auto child = parentItem->child( row ); if( child ) return this->createIndex( row, column, child ); else return QModelIndex(); } int DataSetModel::rowCount( const QModelIndex& parent ) const { DataSetItem* parentItem = nullptr; if( parent.column() > 0 ) return 0; if( !parent.isValid() ) parentItem = _root; else parentItem = static_cast<DataSetItem*>( parent.internalPointer() ); return parentItem->childCount(); } int DataSetModel::columnCount( const QModelIndex& parent ) const { if( parent.isValid() ) return static_cast<DataSetItem*>( parent.internalPointer() )->columnCount(); else return _root->columnCount(); } QVariant DataSetModel::headerData( int section, Qt::Orientation orientation, int role ) const { if( orientation == Qt::Horizontal && role == Qt::DisplayRole ) return DataSetItem::columnNames[section]; return QVariant(); } QVariant DataSetModel::data( const QModelIndex& index, int role ) const { if( !index.isValid() ) return QVariant(); DataSetItem* item = static_cast<DataSetItem*>( index.internalPointer() ); if( role == Qt::DecorationRole && index.column() == 0 && item->parent() == _root ) return QIcon::fromTheme( "folder" ); else if( role == Qt::DisplayRole ) return item->data( index.column() ); return QVariant(); } void DataSetModel::add( const QString& title, const QVariant& data ) { int id_PersistenceDiagram = qMetaTypeId<PersistenceDiagram>(); int id_SimplicialComplex = qMetaTypeId<SimplicialComplex>(); int userType = data.userType(); if( userType != id_PersistenceDiagram && userType != id_SimplicialComplex ) { qDebug() << "Ignoring unknown user type"; return; } for( int i = 0; i < _root->childCount(); i++ ) { auto child = _root->child( i ); if( child && child->type() == userType ) { qDebug() << "Found proper parent item; adding data"; child->append( new DataSetItem( title, data, child ) ); } } } } // namespace gui } // namespace aleph <|endoftext|>
<commit_before>#pragma once #include <mapbox/geojsonvt/types.hpp> namespace mapbox { namespace geojsonvt { struct Tile { mapbox::geometry::feature_collection<int16_t> features; uint32_t num_points = 0; uint32_t num_simplified = 0; }; namespace detail { class InternalTile { public: const uint8_t z; const uint32_t x; const uint32_t y; vt_features source_features; bool is_solid = false; mapbox::geometry::box<double> bbox = { { 2, 1 }, { -1, 0 } }; Tile tile; InternalTile(const vt_features& source, const uint8_t z_, const uint32_t x_, const uint32_t y_, const uint16_t extent_, const uint16_t buffer, const double tolerance_) : z(z_), x(x_), y(y_), z2(std::pow(2, z)), extent(extent_), tolerance(tolerance_), sq_tolerance(tolerance_ * tolerance_) { for (const auto& feature : source) { const auto& geom = feature.geometry; const auto& props = feature.properties; tile.num_points += feature.num_points; vt_geometry::visit(geom, [&] (const auto& g) { visit(transform(g), props); }); bbox.min.x = std::min(feature.bbox.min.x, bbox.min.x); bbox.min.y = std::min(feature.bbox.min.y, bbox.min.y); bbox.max.x = std::max(feature.bbox.max.x, bbox.max.x); bbox.max.y = std::max(feature.bbox.max.y, bbox.max.y); } is_solid = isSolid(buffer); } private: const double z2; const uint16_t extent; const double tolerance; const double sq_tolerance; bool isSolid(const uint16_t buffer) { if (tile.features.size() != 1) return false; const auto& geom = tile.features.front().geometry; if (!geom.is<mapbox::geometry::polygon<int16_t>>()) return false; const auto& rings = geom.get<mapbox::geometry::polygon<int16_t>>(); if (rings.size() > 1) return false; const auto& ring = rings.front(); if (ring.size() != 5) return false; const int16_t min = -static_cast<int16_t>(buffer); const int16_t max = static_cast<int16_t>(extent + buffer); for (const auto& p : ring) { if ((p.x != min && p.x != max) || (p.y != min && p.y != max)) return false; } return true; } void visit(const geometry::point<int16_t>& point, const property_map& props) { tile.features.push_back({ { point }, props }); } void visit(const geometry::line_string<int16_t>& line, const property_map& props) { if (!line.empty()) tile.features.push_back({ { line }, props }); } void visit(const geometry::polygon<int16_t>& polygon, const property_map& props) { if (!polygon.empty()) tile.features.push_back({ { polygon }, props }); } template <class T> void visit(const T& multi, const property_map& props) { switch (multi.size()) { case 0: break; case 1: tile.features.push_back({ { multi[0] }, props }); break; default: tile.features.push_back({ { multi }, props }); break; } } mapbox::geometry::point<int16_t> transform(const vt_point& p) { ++tile.num_simplified; return { static_cast<int16_t>(std::round((p.x * z2 - x) * extent)), static_cast<int16_t>(std::round((p.y * z2 - y) * extent)) }; } mapbox::geometry::multi_point<int16_t> transform(const vt_multi_point& points) { mapbox::geometry::multi_point<int16_t> result; result.reserve(points.size()); for (const auto& p : points) { result.push_back(transform(p)); } return result; } mapbox::geometry::line_string<int16_t> transform(const vt_line_string& line) { mapbox::geometry::line_string<int16_t> result; if (line.dist > tolerance) { for (const auto& p : line) { if (p.z > sq_tolerance) result.push_back(transform(p)); } } return result; } mapbox::geometry::linear_ring<int16_t> transform(const vt_linear_ring& ring) { mapbox::geometry::linear_ring<int16_t> result; if (ring.area > sq_tolerance) { for (const auto& p : ring) { if (p.z > sq_tolerance) result.push_back(transform(p)); } } return result; } mapbox::geometry::multi_line_string<int16_t> transform(const vt_multi_line_string& lines) { mapbox::geometry::multi_line_string<int16_t> result; for (const auto& line : lines) { if (line.dist > tolerance) result.push_back(transform(line)); } return result; } mapbox::geometry::polygon<int16_t> transform(const vt_polygon& rings) { mapbox::geometry::polygon<int16_t> result; for (const auto& ring : rings) { if (ring.area > sq_tolerance) result.push_back(transform(ring)); } return result; } mapbox::geometry::multi_polygon<int16_t> transform(const vt_multi_polygon& polygons) { mapbox::geometry::multi_polygon<int16_t> result; for (const auto& polygon : polygons) { const auto p = transform(polygon); if (!p.empty()) result.push_back(p); } return result; } }; } // namespace detail } // namespace geojsonvt } // namespace mapbox <commit_msg>Fewer copies<commit_after>#pragma once #include <mapbox/geojsonvt/types.hpp> namespace mapbox { namespace geojsonvt { struct Tile { mapbox::geometry::feature_collection<int16_t> features; uint32_t num_points = 0; uint32_t num_simplified = 0; }; namespace detail { class InternalTile { public: const uint8_t z; const uint32_t x; const uint32_t y; vt_features source_features; bool is_solid = false; mapbox::geometry::box<double> bbox = { { 2, 1 }, { -1, 0 } }; Tile tile; InternalTile(const vt_features& source, const uint8_t z_, const uint32_t x_, const uint32_t y_, const uint16_t extent_, const uint16_t buffer, const double tolerance_) : z(z_), x(x_), y(y_), z2(std::pow(2, z)), extent(extent_), tolerance(tolerance_), sq_tolerance(tolerance_ * tolerance_) { for (const auto& feature : source) { const auto& geom = feature.geometry; const auto& props = feature.properties; tile.num_points += feature.num_points; vt_geometry::visit(geom, [&] (const auto& g) { visit(transform(g), props); }); bbox.min.x = std::min(feature.bbox.min.x, bbox.min.x); bbox.min.y = std::min(feature.bbox.min.y, bbox.min.y); bbox.max.x = std::max(feature.bbox.max.x, bbox.max.x); bbox.max.y = std::max(feature.bbox.max.y, bbox.max.y); } is_solid = isSolid(buffer); } private: const double z2; const uint16_t extent; const double tolerance; const double sq_tolerance; bool isSolid(const uint16_t buffer) { if (tile.features.size() != 1) return false; const auto& geom = tile.features.front().geometry; if (!geom.is<mapbox::geometry::polygon<int16_t>>()) return false; const auto& rings = geom.get<mapbox::geometry::polygon<int16_t>>(); if (rings.size() > 1) return false; const auto& ring = rings.front(); if (ring.size() != 5) return false; const int16_t min = -static_cast<int16_t>(buffer); const int16_t max = static_cast<int16_t>(extent + buffer); for (const auto& p : ring) { if ((p.x != min && p.x != max) || (p.y != min && p.y != max)) return false; } return true; } void visit(geometry::point<int16_t>&& point, const property_map& props) { tile.features.push_back({ std::move(point), props }); } void visit(geometry::line_string<int16_t>&& line, const property_map& props) { if (!line.empty()) tile.features.push_back({ std::move(line), props }); } void visit(geometry::polygon<int16_t>&& polygon, const property_map& props) { if (!polygon.empty()) tile.features.push_back({ std::move(polygon), props }); } template <class T> void visit(T&& multi, const property_map& props) { switch (multi.size()) { case 0: break; case 1: tile.features.push_back({ std::move(multi[0]), props }); break; default: tile.features.push_back({ std::move(multi), props }); break; } } mapbox::geometry::point<int16_t> transform(const vt_point& p) { ++tile.num_simplified; return { static_cast<int16_t>(std::round((p.x * z2 - x) * extent)), static_cast<int16_t>(std::round((p.y * z2 - y) * extent)) }; } mapbox::geometry::multi_point<int16_t> transform(const vt_multi_point& points) { mapbox::geometry::multi_point<int16_t> result; result.reserve(points.size()); for (const auto& p : points) { result.push_back(transform(p)); } return result; } mapbox::geometry::line_string<int16_t> transform(const vt_line_string& line) { mapbox::geometry::line_string<int16_t> result; if (line.dist > tolerance) { for (const auto& p : line) { if (p.z > sq_tolerance) result.push_back(transform(p)); } } return result; } mapbox::geometry::linear_ring<int16_t> transform(const vt_linear_ring& ring) { mapbox::geometry::linear_ring<int16_t> result; if (ring.area > sq_tolerance) { for (const auto& p : ring) { if (p.z > sq_tolerance) result.push_back(transform(p)); } } return result; } mapbox::geometry::multi_line_string<int16_t> transform(const vt_multi_line_string& lines) { mapbox::geometry::multi_line_string<int16_t> result; for (const auto& line : lines) { if (line.dist > tolerance) result.push_back(transform(line)); } return result; } mapbox::geometry::polygon<int16_t> transform(const vt_polygon& rings) { mapbox::geometry::polygon<int16_t> result; for (const auto& ring : rings) { if (ring.area > sq_tolerance) result.push_back(transform(ring)); } return result; } mapbox::geometry::multi_polygon<int16_t> transform(const vt_multi_polygon& polygons) { mapbox::geometry::multi_polygon<int16_t> result; for (const auto& polygon : polygons) { const auto p = transform(polygon); if (!p.empty()) result.push_back(p); } return result; } }; } // namespace detail } // namespace geojsonvt } // namespace mapbox <|endoftext|>
<commit_before>/* Copyright (C) 2017 INRA * * 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, sublipnse, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef ORG_VLEPROJECT_BARYONYX_SOLVER_ITM_HPP #define ORG_VLEPROJECT_BARYONYX_SOLVER_ITM_HPP #include <baryonyx/core-compare> #include <baryonyx/core-out> #include <utility> namespace baryonyx { namespace itm { result inequalities_1coeff_wedelin_solve(const std::shared_ptr<context>& ctx, problem& pb); result inequalities_1coeff_wedelin_optimize(const std::shared_ptr<context>& ctx, problem& pb, int thread); result inequalities_Zcoeff_wedelin_solve(const std::shared_ptr<context>& ctx, problem& pb); result inequalities_Zcoeff_wedelin_optimize(const std::shared_ptr<context>& ctx, problem& pb, int thread); enum class floating_point_type { float_type, double_type, longdouble_type }; inline const char* floating_point_type_to_string(floating_point_type type) noexcept { static const char* ret[] = { "float", "double", "longdouble", }; switch (type) { case floating_point_type::float_type: return ret[0]; case floating_point_type::double_type: return ret[1]; case floating_point_type::longdouble_type: return ret[2]; default: return ret[0]; }; } inline floating_point_type get_floating_point_type(const std::shared_ptr<context>& ctx) noexcept { auto str = ctx->get_string_parameter("floating-point-type", "double"); if (str == "float") return floating_point_type::float_type; if (str == "longdouble") return floating_point_type::longdouble_type; return floating_point_type::double_type; } enum class constraint_order { none, reversing, random_sorting, infeasibility_decr, infeasibility_incr, }; inline const char* constraint_order_to_string(constraint_order type) noexcept { static const char* ret[] = { "none", "reversing", "random-sorting", "infeasibility-decr", "infeasibility-incr", }; switch (type) { case constraint_order::none: return ret[0]; case constraint_order::reversing: return ret[1]; case constraint_order::random_sorting: return ret[2]; case constraint_order::infeasibility_decr: return ret[3]; case constraint_order::infeasibility_incr: return ret[4]; default: return ret[0]; } } inline constraint_order get_constraint_order(const std::shared_ptr<context>& ctx) noexcept { auto str = ctx->get_string_parameter("constraint-order", "none"); if (str == "reversing") return constraint_order::reversing; if (str == "random-sorting") return constraint_order::random_sorting; if (str == "infeasibility-decr") return constraint_order::infeasibility_decr; if (str == "infeasibility-incr") return constraint_order::infeasibility_incr; return constraint_order::none; } struct parameters { parameters(const std::shared_ptr<context>& ctx) : preprocessing(ctx->get_string_parameter("preprocessing", "none")) , norm(ctx->get_string_parameter("norm", "inf")) , time_limit(ctx->get_real_parameter("time-limit", -1.0)) , theta(ctx->get_real_parameter("theta", 0.5)) , delta(ctx->get_real_parameter("delta", 0.01)) , kappa_min(ctx->get_real_parameter("kappa-min", 0.0)) , kappa_step(ctx->get_real_parameter("kappa-step", 1.e-3)) , kappa_max(ctx->get_real_parameter("kappa-max", 0.6)) , alpha(ctx->get_real_parameter("alpha", 1.0)) , pushing_k_factor(ctx->get_real_parameter("pushing-k-factor", 0.9)) , pushing_objective_amplifier( ctx->get_real_parameter("pushing-objective-amplifier", 5)) , pushes_limit(ctx->get_integer_parameter("pushes-limit", 10)) , pushing_iteration_limit( ctx->get_integer_parameter("pushing-iteration-limit", 20)) , limit(ctx->get_integer_parameter("limit", 1000)) , w(ctx->get_integer_parameter("w", 500)) , print_level(ctx->get_integer_parameter("print-level", 0)) , order(get_constraint_order(ctx)) , float_type(get_floating_point_type(ctx)) { if (limit < 0) limit = std::numeric_limits<int>::max(); ctx->info("solver parameters:\n" " - preprocessing: %s\n" " - constraint-order: %s\n" " - time-limit: %.10g\n" " - theta: %.10g\n" " - delta: %.10g\n" " - limit: %d\n" " - kappa: %.10g %.10g %.10g\n" " - alpha: %.10g\n" " - w: %d\n" " - norm: %s\n" " - print-level: %d\n" " - float-point-type: %s\n", preprocessing.c_str(), constraint_order_to_string(order), time_limit, theta, delta, limit, kappa_min, kappa_step, kappa_max, alpha, w, norm.c_str(), print_level, floating_point_type_to_string(float_type)); if (ctx->optimize()) ctx->info("optimizer parameters:\n" " - pushed-limit: %d\n" " - pushing-objective-amplifier: %.10g\n" " - pushing-iteration-limit: %d\n" " - pushing-k-factor: %.10g\n", pushes_limit, pushing_objective_amplifier, pushing_iteration_limit, pushing_k_factor); } std::string preprocessing; std::string norm; double time_limit; double theta; double delta; double kappa_min; double kappa_step; double kappa_max; double alpha; double pushing_k_factor; double pushing_objective_amplifier; int pushes_limit; int pushing_iteration_limit; int limit; int w; int print_level; constraint_order order; floating_point_type float_type; }; struct merged_constraint { merged_constraint(std::vector<function_element> elements_, int min_, int max_, int id_) : elements(std::move(elements_)) , min(min_) , max(max_) , id(id_) { } std::vector<function_element> elements; int min; int max; int id; }; std::vector<merged_constraint> make_merged_constraints(const std::shared_ptr<context>& ctx, const problem& pb, const parameters& p); } } #endif <commit_msg>itm: fix help imformation<commit_after>/* Copyright (C) 2017 INRA * * 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, sublipnse, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef ORG_VLEPROJECT_BARYONYX_SOLVER_ITM_HPP #define ORG_VLEPROJECT_BARYONYX_SOLVER_ITM_HPP #include <baryonyx/core-compare> #include <baryonyx/core-out> #include <utility> namespace baryonyx { namespace itm { result inequalities_1coeff_wedelin_solve(const std::shared_ptr<context>& ctx, problem& pb); result inequalities_1coeff_wedelin_optimize(const std::shared_ptr<context>& ctx, problem& pb, int thread); result inequalities_Zcoeff_wedelin_solve(const std::shared_ptr<context>& ctx, problem& pb); result inequalities_Zcoeff_wedelin_optimize(const std::shared_ptr<context>& ctx, problem& pb, int thread); enum class floating_point_type { float_type, double_type, longdouble_type }; inline const char* floating_point_type_to_string(floating_point_type type) noexcept { static const char* ret[] = { "float", "double", "longdouble", }; switch (type) { case floating_point_type::float_type: return ret[0]; case floating_point_type::double_type: return ret[1]; case floating_point_type::longdouble_type: return ret[2]; default: return ret[0]; }; } inline floating_point_type get_floating_point_type(const std::shared_ptr<context>& ctx) noexcept { auto str = ctx->get_string_parameter("floating-point-type", "double"); if (str == "float") return floating_point_type::float_type; if (str == "longdouble") return floating_point_type::longdouble_type; return floating_point_type::double_type; } enum class constraint_order { none, reversing, random_sorting, infeasibility_decr, infeasibility_incr, }; inline const char* constraint_order_to_string(constraint_order type) noexcept { static const char* ret[] = { "none", "reversing", "random-sorting", "infeasibility-decr", "infeasibility-incr", }; switch (type) { case constraint_order::none: return ret[0]; case constraint_order::reversing: return ret[1]; case constraint_order::random_sorting: return ret[2]; case constraint_order::infeasibility_decr: return ret[3]; case constraint_order::infeasibility_incr: return ret[4]; default: return ret[0]; } } inline constraint_order get_constraint_order(const std::shared_ptr<context>& ctx) noexcept { auto str = ctx->get_string_parameter("constraint-order", "none"); if (str == "reversing") return constraint_order::reversing; if (str == "random-sorting") return constraint_order::random_sorting; if (str == "infeasibility-decr") return constraint_order::infeasibility_decr; if (str == "infeasibility-incr") return constraint_order::infeasibility_incr; return constraint_order::none; } struct parameters { parameters(const std::shared_ptr<context>& ctx) : preprocessing(ctx->get_string_parameter("preprocessing", "none")) , norm(ctx->get_string_parameter("norm", "inf")) , time_limit(ctx->get_real_parameter("time-limit", -1.0)) , theta(ctx->get_real_parameter("theta", 0.5)) , delta(ctx->get_real_parameter("delta", 0.01)) , kappa_min(ctx->get_real_parameter("kappa-min", 0.0)) , kappa_step(ctx->get_real_parameter("kappa-step", 1.e-3)) , kappa_max(ctx->get_real_parameter("kappa-max", 0.6)) , alpha(ctx->get_real_parameter("alpha", 1.0)) , pushing_k_factor(ctx->get_real_parameter("pushing-k-factor", 0.9)) , pushing_objective_amplifier( ctx->get_real_parameter("pushing-objective-amplifier", 5)) , pushes_limit(ctx->get_integer_parameter("pushes-limit", 10)) , pushing_iteration_limit( ctx->get_integer_parameter("pushing-iteration-limit", 20)) , limit(ctx->get_integer_parameter("limit", 1000)) , w(ctx->get_integer_parameter("w", 500)) , print_level(ctx->get_integer_parameter("print-level", 0)) , order(get_constraint_order(ctx)) , float_type(get_floating_point_type(ctx)) { if (limit < 0) limit = std::numeric_limits<int>::max(); ctx->info("solver parameters:\n" " - preprocessing: %s\n" " - constraint-order: %s\n" " - time-limit: %.10g\n" " - theta: %.10g\n" " - delta: %.10g\n" " - limit: %d\n" " - kappa: %.10g %.10g %.10g\n" " - alpha: %.10g\n" " - w: %d\n" " - norm: %s\n" " - print-level: %d\n" " - floating-point-type: %s\n", preprocessing.c_str(), constraint_order_to_string(order), time_limit, theta, delta, limit, kappa_min, kappa_step, kappa_max, alpha, w, norm.c_str(), print_level, floating_point_type_to_string(float_type)); if (ctx->optimize()) ctx->info("optimizer parameters:\n" " - pushes-limit: %d\n" " - pushing-objective-amplifier: %.10g\n" " - pushing-iteration-limit: %d\n" " - pushing-k-factor: %.10g\n", pushes_limit, pushing_objective_amplifier, pushing_iteration_limit, pushing_k_factor); } std::string preprocessing; std::string norm; double time_limit; double theta; double delta; double kappa_min; double kappa_step; double kappa_max; double alpha; double pushing_k_factor; double pushing_objective_amplifier; int pushes_limit; int pushing_iteration_limit; int limit; int w; int print_level; constraint_order order; floating_point_type float_type; }; struct merged_constraint { merged_constraint(std::vector<function_element> elements_, int min_, int max_, int id_) : elements(std::move(elements_)) , min(min_) , max(max_) , id(id_) { } std::vector<function_element> elements; int min; int max; int id; }; std::vector<merged_constraint> make_merged_constraints(const std::shared_ptr<context>& ctx, const problem& pb, const parameters& p); } } #endif <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> #include "min_heap.hpp" #define LEFT_CHILD(i) ((i << 1) + 1) #define RIGHT_CHILD(i) ((i << 1) + 2) #define PARENT_ENTRY(i) ((i - 1) >> 1) template <class P, class V> MinHeap<P, V>::MinHeap(int size) { this->length = size; this->occupied = 0; this->map = (int *) calloc(size, sizeof(int)); this->array = (struct MinHeapElement<P, V> *) calloc(size, sizeof(MinHeapElement<P, V>)); for (int i = 0; i < size; i++) { this->map[i] = -1; } } template <class P, class V> MinHeap<P, V>::~MinHeap() { free(this->map); free(this->array); } template <class P, class V> void MinHeap<P, V>::swap(V ia, V ib) { MinHeapElement<P, V> *a, *b, tmp; a = this->array + ia; b = this->array + ib; tmp = *a; *a = *b; *b = tmp; this->map[b->value] = ib; this->map[a->value] = ia; } template <class P, class V> void MinHeap<P, V>::update(V index) { MinHeapElement<P, V> *elem, *parent; int parent_index; while (index > 0) { parent_index = PARENT_ENTRY(index); elem = this->array + index; parent = this->array + parent_index; if (elem->priority < parent->priority) { this->swap(index, parent_index); index = parent_index; } else { break; } } } template <class P, class V> void MinHeap<P, V>::decrease_raw(P priority, V value) { int index = this->map[value]; if (index != -1) { #pragma omp critical(min_heap_lock) { this->array[index].priority = priority; this->update(index); } } } template <class P, class V> bool MinHeap<P, V>::decrease(P priority, V value) { int index = this->map[value]; if (index != -1 && priority < this->array[index].priority) { #pragma omp critical(min_heap_lock) { this->array[index].priority = priority; this->update(index); } return true; } else { return false; } } template <class P, class V> void MinHeap<P, V>::insert(P priority, V value) { MinHeapElement<P, V> *elem; int index; index = this->occupied++; elem = this->array + index; elem->priority = priority; elem->value = value; this->map[value] = index; this->update(index); } template <class P, class V> V MinHeap<P, V>::extract() { MinHeapElement<P, V> *elem, *child_left, *child_right, *child_smallest; V rv = this->array[0].value, index, child_index; this->map[this->array[0].value] = -1; elem = this->array + --this->occupied; this->array[0].priority = elem->priority; this->array[0].value = elem->value; this->map[this->array[0].value] = 0; index = 0; while (index < this->occupied) { elem = this->array + index; if (LEFT_CHILD(index) < this->occupied) { child_left = this->array + LEFT_CHILD(index); } else { child_left = NULL; } if (RIGHT_CHILD(index) < this->occupied) { child_right = this->array + RIGHT_CHILD(index); } else { child_right = NULL; } if (child_right && child_right->priority < child_left->priority) { child_smallest = child_right; child_index = RIGHT_CHILD(index); } else if (child_right && child_left->priority <= child_right->priority) { child_smallest = child_left; child_index = LEFT_CHILD(index); } else if (child_left) { child_smallest = child_left; child_index = LEFT_CHILD(index); } else { break; } if (elem->priority > child_smallest->priority) { this->swap(index, child_index); index = child_index; } else { break; } } return rv; } template class MinHeap<float, int>; <commit_msg>Fix a typo in the min heap.<commit_after>#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> #include "min_heap.hpp" #define LEFT_CHILD(i) ((i << 1) + 1) #define RIGHT_CHILD(i) ((i << 1) + 2) #define PARENT_ENTRY(i) ((i - 1) >> 1) template <class P, class V> MinHeap<P, V>::MinHeap(int size) { this->length = size; this->occupied = 0; this->map = (int *) calloc(size, sizeof(int)); this->array = (MinHeapElement<P, V> *) calloc(size, sizeof(MinHeapElement<P, V>)); for (int i = 0; i < size; i++) { this->map[i] = -1; } } template <class P, class V> MinHeap<P, V>::~MinHeap() { free(this->map); free(this->array); } template <class P, class V> void MinHeap<P, V>::swap(V ia, V ib) { MinHeapElement<P, V> *a, *b, tmp; a = this->array + ia; b = this->array + ib; tmp = *a; *a = *b; *b = tmp; this->map[b->value] = ib; this->map[a->value] = ia; } template <class P, class V> void MinHeap<P, V>::update(V index) { MinHeapElement<P, V> *elem, *parent; int parent_index; while (index > 0) { parent_index = PARENT_ENTRY(index); elem = this->array + index; parent = this->array + parent_index; if (elem->priority < parent->priority) { this->swap(index, parent_index); index = parent_index; } else { break; } } } template <class P, class V> void MinHeap<P, V>::decrease_raw(P priority, V value) { int index = this->map[value]; if (index != -1) { #pragma omp critical(min_heap_lock) { this->array[index].priority = priority; this->update(index); } } } template <class P, class V> bool MinHeap<P, V>::decrease(P priority, V value) { int index = this->map[value]; if (index != -1 && priority < this->array[index].priority) { #pragma omp critical(min_heap_lock) { this->array[index].priority = priority; this->update(index); } return true; } else { return false; } } template <class P, class V> void MinHeap<P, V>::insert(P priority, V value) { MinHeapElement<P, V> *elem; int index; index = this->occupied++; elem = this->array + index; elem->priority = priority; elem->value = value; this->map[value] = index; this->update(index); } template <class P, class V> V MinHeap<P, V>::extract() { MinHeapElement<P, V> *elem, *child_left, *child_right, *child_smallest; V rv = this->array[0].value, index, child_index; this->map[this->array[0].value] = -1; elem = this->array + --this->occupied; this->array[0].priority = elem->priority; this->array[0].value = elem->value; this->map[this->array[0].value] = 0; index = 0; while (index < this->occupied) { elem = this->array + index; if (LEFT_CHILD(index) < this->occupied) { child_left = this->array + LEFT_CHILD(index); } else { child_left = NULL; } if (RIGHT_CHILD(index) < this->occupied) { child_right = this->array + RIGHT_CHILD(index); } else { child_right = NULL; } if (child_right && child_right->priority < child_left->priority) { child_smallest = child_right; child_index = RIGHT_CHILD(index); } else if (child_right && child_left->priority <= child_right->priority) { child_smallest = child_left; child_index = LEFT_CHILD(index); } else if (child_left) { child_smallest = child_left; child_index = LEFT_CHILD(index); } else { break; } if (elem->priority > child_smallest->priority) { this->swap(index, child_index); index = child_index; } else { break; } } return rv; } template class MinHeap<float, int>; <|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/monitor/common/can_checker_factory.h" #include "modules/monitor/hwmonitor/hw/esdcan/esdcan_checker.h" /** * @file: hw_checker_factory.cc */ namespace apollo { namespace monitor { using ::apollo::drivers::canbus::CANCardParameter; using ::apollo::monitor::HwCheckerInterface; using ::apollo::monitor::hw::EsdCanChecker; CanCheckerFactory::CanCheckerFactory() {} void CanCheckerFactory::RegisterCanCheckers() { Register(CANCardParameter::FAKE_CAN, []() -> HwCheckerInterface* { return new EsdCanChecker(); }); } std::unique_ptr<HwCheckerInterface> CanCheckerFactory::CreateCanChecker( const CANCardParameter& parameter) { auto factory = CreateObject(parameter.brand()); if (!factory) { AERROR << "Failed to create CAN checker with parameter: " << parameter.DebugString(); } return factory; } } // namespace monitor } // namespace apollo <commit_msg>Monitor: fix can_checker_factory<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/monitor/common/can_checker_factory.h" #include "modules/monitor/hwmonitor/hw/esdcan/esdcan_checker.h" /** * @file: hw_checker_factory.cc */ namespace apollo { namespace monitor { using ::apollo::drivers::canbus::CANCardParameter; using ::apollo::monitor::HwCheckerInterface; using ::apollo::monitor::hw::EsdCanChecker; CanCheckerFactory::CanCheckerFactory() {} void CanCheckerFactory::RegisterCanCheckers() { Register(CANCardParameter::ESD_CAN, []() -> HwCheckerInterface* { return new EsdCanChecker(); }); } std::unique_ptr<HwCheckerInterface> CanCheckerFactory::CreateCanChecker( const CANCardParameter& parameter) { auto factory = CreateObject(parameter.brand()); if (!factory) { AERROR << "Failed to create CAN checker with parameter: " << parameter.DebugString(); } return factory; } } // namespace monitor } // namespace apollo <|endoftext|>
<commit_before>/************************************************************************/ /* */ /* Copyright 1998-2002 by Ullrich Koethe */ /* Cognitive Systems Group, University of Hamburg, Germany */ /* */ /* This file is part of the VIGRA computer vision library. */ /* The VIGRA Website is */ /* http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/ */ /* Please direct questions, bug reports, and contributions to */ /* ullrich.koethe@iwr.uni-heidelberg.de or */ /* vigra@informatik.uni-hamburg.de */ /* */ /* Permission is hereby granted, free of charge, to any person */ /* obtaining a copy of this software and associated documentation */ /* files (the "Software"), to deal in the Software without */ /* restriction, including without limitation the rights to use, */ /* copy, modify, merge, publish, distribute, sublicense, and/or */ /* sell copies of the Software, and to permit persons to whom the */ /* Software is furnished to do so, subject to the following */ /* conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the */ /* Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */ /* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */ /* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */ /* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */ /* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */ /* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */ /* OTHER DEALINGS IN THE SOFTWARE. */ /* */ /************************************************************************/ #ifndef VIGRA_METAPROGRAMMING_HXX #define VIGRA_METAPROGRAMMING_HXX #include "config.hxx" #include <climits> #include <limits> namespace vigra { template <int N> class MetaInt { public: enum { value = N }; }; struct VigraTrueType { enum { asBool = true }; }; struct VigraFalseType { enum { asBool = false }; }; /** \addtogroup MultiArrayTags Multi-dimensional Array Tags Meta-programming tags to mark array's as strided or unstrided. */ //@{ /********************************************************/ /* */ /* StridedArrayTag */ /* */ /********************************************************/ /** tag for marking a MultiArray strided. <b>\#include</b> \<<a href="multi__array_8hxx-source.html">vigra/multi_array.hxx</a>\> Namespace: vigra */ struct StridedArrayTag {}; /********************************************************/ /* */ /* UnstridedArrayTag */ /* */ /********************************************************/ /** tag for marking a MultiArray unstrided. <b>\#include</b> \<<a href="multi__array_8hxx-source.html">vigra/multi_array.hxx</a>\> Namespace: vigra */ struct UnstridedArrayTag {}; template<class T> class TypeTraits { public: typedef VigraFalseType isConst; typedef VigraFalseType isPOD; typedef VigraFalseType isBuiltinType; }; #ifndef NO_PARTIAL_TEMPLATE_SPECIALIZATION template<class T> class TypeTraits<T const> : public TypeTraits<T> { public: typedef VigraTrueType isConst; }; template<class T> class TypeTraits<T *> { public: typedef VigraFalseType isConst; typedef VigraTrueType isPOD; typedef VigraTrueType isBuiltinType; }; template<class T> class TypeTraits<T const *> { public: typedef VigraFalseType isConst; typedef VigraTrueType isPOD; typedef VigraTrueType isBuiltinType; }; #endif // NO_PARTIAL_TEMPLATE_SPECIALIZATION namespace detail { template <int size> struct SizeToType; } // namespace detail #define VIGRA_TYPE_TRAITS(type, size) \ template<> \ class TypeTraits<type> \ { \ public: \ typedef VigraFalseType isConst; \ typedef VigraTrueType isPOD; \ typedef VigraTrueType isBuiltinType; \ typedef char TypeToSize[size]; \ }; \ \ namespace detail { \ TypeTraits<type>::TypeToSize * typeToSize(type); \ \ template <> \ struct SizeToType<size> \ { \ typedef type result; \ }; \ } VIGRA_TYPE_TRAITS(char, 1) VIGRA_TYPE_TRAITS(signed char, 2) VIGRA_TYPE_TRAITS(unsigned char, 3) VIGRA_TYPE_TRAITS(short, 4) VIGRA_TYPE_TRAITS(unsigned short, 5) VIGRA_TYPE_TRAITS(int, 6) VIGRA_TYPE_TRAITS(unsigned int, 7) VIGRA_TYPE_TRAITS(long, 8) VIGRA_TYPE_TRAITS(unsigned long, 9) VIGRA_TYPE_TRAITS(float, 10) VIGRA_TYPE_TRAITS(double, 11) VIGRA_TYPE_TRAITS(long double, 12) #ifdef LLONG_MAX VIGRA_TYPE_TRAITS(long long, 13) VIGRA_TYPE_TRAITS(unsigned long long, 14) #endif #undef VIGRA_TYPE_TRAITS //@} template <class A> struct Not; template <> struct Not<VigraTrueType> { typedef VigraFalseType result; static const bool boolResult = false; }; template <> struct Not<VigraFalseType> { typedef VigraTrueType result; static const bool boolResult = true; }; template <class L, class R> struct And; template <> struct And<VigraFalseType, VigraFalseType> { typedef VigraFalseType result; static const bool boolResult = false; }; template <> struct And<VigraFalseType, VigraTrueType> { typedef VigraFalseType result; static const bool boolResult = false; }; template <> struct And<VigraTrueType, VigraFalseType> { typedef VigraFalseType result; static const bool boolResult = false; }; template <> struct And<VigraTrueType, VigraTrueType> { typedef VigraTrueType result; static const bool boolResult = true; }; template <class L, class R> struct Or; template <> struct Or<VigraFalseType, VigraFalseType> { typedef VigraFalseType result; static const bool boolResult = false; }; template <> struct Or<VigraTrueType, VigraFalseType> { typedef VigraTrueType result; static const bool boolResult = true; }; template <> struct Or<VigraFalseType, VigraTrueType> { typedef VigraTrueType result; static const bool boolResult = true; }; template <> struct Or<VigraTrueType, VigraTrueType> { typedef VigraTrueType result; static const bool boolResult = true; }; #ifndef NO_PARTIAL_TEMPLATE_SPECIALIZATION template <class PREDICATE, class TRUECASE, class FALSECASE> struct If; template <class TRUECASE, class FALSECASE> struct If<VigraTrueType, TRUECASE, FALSECASE> { typedef TRUECASE type; }; template <class TRUECASE, class FALSECASE> struct If<VigraFalseType, TRUECASE, FALSECASE> { typedef FALSECASE type; }; template <bool PREDICATE, class TRUECASE, class FALSECASE> struct IfBool; template <class TRUECASE, class FALSECASE> struct IfBool<true, TRUECASE, FALSECASE> { typedef TRUECASE type; }; template <class TRUECASE, class FALSECASE> struct IfBool<false, TRUECASE, FALSECASE> { typedef FALSECASE type; }; template <class L, class R> struct IsSameType { typedef VigraFalseType result; static const bool boolResult = false; }; template <class T> struct IsSameType<T, T> { typedef VigraTrueType result; static const bool boolResult = true; }; template <class DERIVED, class BASE> struct IsDerivedFrom { typedef char falseResult[1]; typedef char trueResult[2]; static falseResult * testIsDerivedFrom(...); static trueResult * testIsDerivedFrom(BASE const *); enum { resultSize = sizeof(*testIsDerivedFrom((DERIVED const *)0)) }; static const bool boolResult = (resultSize == 2); typedef typename IfBool<boolResult, VigraTrueType, VigraFalseType>::type result; }; #endif // NO_PARTIAL_TEMPLATE_SPECIALIZATION } // namespace vigra #endif /* VIGRA_METAPROGRAMMING_HXX */ <commit_msg>added has_result_type; unified API of meta-ptogramming functions<commit_after>/************************************************************************/ /* */ /* Copyright 1998-2002 by Ullrich Koethe */ /* Cognitive Systems Group, University of Hamburg, Germany */ /* */ /* This file is part of the VIGRA computer vision library. */ /* The VIGRA Website is */ /* http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/ */ /* Please direct questions, bug reports, and contributions to */ /* ullrich.koethe@iwr.uni-heidelberg.de or */ /* vigra@informatik.uni-hamburg.de */ /* */ /* Permission is hereby granted, free of charge, to any person */ /* obtaining a copy of this software and associated documentation */ /* files (the "Software"), to deal in the Software without */ /* restriction, including without limitation the rights to use, */ /* copy, modify, merge, publish, distribute, sublicense, and/or */ /* sell copies of the Software, and to permit persons to whom the */ /* Software is furnished to do so, subject to the following */ /* conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the */ /* Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */ /* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */ /* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */ /* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */ /* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */ /* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */ /* OTHER DEALINGS IN THE SOFTWARE. */ /* */ /************************************************************************/ #ifndef VIGRA_METAPROGRAMMING_HXX #define VIGRA_METAPROGRAMMING_HXX #include "config.hxx" #include <climits> #include <limits> namespace vigra { template <int N> class MetaInt { public: enum { value = N }; }; struct VigraTrueType { enum { asBool = true }; }; struct VigraFalseType { enum { asBool = false }; }; /** \addtogroup MultiArrayTags Multi-dimensional Array Tags Meta-programming tags to mark array's as strided or unstrided. */ //@{ /********************************************************/ /* */ /* StridedArrayTag */ /* */ /********************************************************/ /** tag for marking a MultiArray strided. <b>\#include</b> \<<a href="multi__array_8hxx-source.html">vigra/multi_array.hxx</a>\> Namespace: vigra */ struct StridedArrayTag {}; /********************************************************/ /* */ /* UnstridedArrayTag */ /* */ /********************************************************/ /** tag for marking a MultiArray unstrided. <b>\#include</b> \<<a href="multi__array_8hxx-source.html">vigra/multi_array.hxx</a>\> Namespace: vigra */ struct UnstridedArrayTag {}; template<class T> class TypeTraits { public: typedef VigraFalseType isConst; typedef VigraFalseType isPOD; typedef VigraFalseType isBuiltinType; }; #ifndef NO_PARTIAL_TEMPLATE_SPECIALIZATION template<class T> class TypeTraits<T const> : public TypeTraits<T> { public: typedef VigraTrueType isConst; }; template<class T> class TypeTraits<T *> { public: typedef VigraFalseType isConst; typedef VigraTrueType isPOD; typedef VigraTrueType isBuiltinType; }; template<class T> class TypeTraits<T const *> { public: typedef VigraFalseType isConst; typedef VigraTrueType isPOD; typedef VigraTrueType isBuiltinType; }; #endif // NO_PARTIAL_TEMPLATE_SPECIALIZATION namespace detail { template <int size> struct SizeToType; } // namespace detail #define VIGRA_TYPE_TRAITS(type, size) \ template<> \ class TypeTraits<type> \ { \ public: \ typedef VigraFalseType isConst; \ typedef VigraTrueType isPOD; \ typedef VigraTrueType isBuiltinType; \ typedef char TypeToSize[size]; \ }; \ \ namespace detail { \ TypeTraits<type>::TypeToSize * typeToSize(type); \ \ template <> \ struct SizeToType<size> \ { \ typedef type result; \ }; \ } VIGRA_TYPE_TRAITS(char, 1) VIGRA_TYPE_TRAITS(signed char, 2) VIGRA_TYPE_TRAITS(unsigned char, 3) VIGRA_TYPE_TRAITS(short, 4) VIGRA_TYPE_TRAITS(unsigned short, 5) VIGRA_TYPE_TRAITS(int, 6) VIGRA_TYPE_TRAITS(unsigned int, 7) VIGRA_TYPE_TRAITS(long, 8) VIGRA_TYPE_TRAITS(unsigned long, 9) VIGRA_TYPE_TRAITS(float, 10) VIGRA_TYPE_TRAITS(double, 11) VIGRA_TYPE_TRAITS(long double, 12) #ifdef LLONG_MAX VIGRA_TYPE_TRAITS(long long, 13) VIGRA_TYPE_TRAITS(unsigned long long, 14) #endif #undef VIGRA_TYPE_TRAITS //@} template <class A> struct Not; template <> struct Not<VigraTrueType> { typedef VigraFalseType result; // deprecated static const bool boolResult = false; // deprecated typedef VigraFalseType type; static const bool value = false; }; template <> struct Not<VigraFalseType> { typedef VigraTrueType result; // deprecated static const bool boolResult = true; // deprecated typedef VigraTrueType type; static const bool value = true; }; template <class L, class R> struct And; template <> struct And<VigraFalseType, VigraFalseType> { typedef VigraFalseType result; // deprecated static const bool boolResult = false; // deprecated typedef VigraFalseType type; static const bool value = false; }; template <> struct And<VigraFalseType, VigraTrueType> { typedef VigraFalseType result; // deprecated static const bool boolResult = false; // deprecated typedef VigraFalseType type; static const bool value = false; }; template <> struct And<VigraTrueType, VigraFalseType> { typedef VigraFalseType result; // deprecated static const bool boolResult = false; // deprecated typedef VigraFalseType type; static const bool value = false; }; template <> struct And<VigraTrueType, VigraTrueType> { typedef VigraTrueType result; // deprecated static const bool boolResult = true; // deprecated typedef VigraTrueType type; static const bool value = true; }; template <class L, class R> struct Or; template <> struct Or<VigraFalseType, VigraFalseType> { typedef VigraFalseType result; // deprecated static const bool boolResult = false; // deprecated typedef VigraFalseType type; static const bool value = false; }; template <> struct Or<VigraTrueType, VigraFalseType> { typedef VigraTrueType result; // deprecated static const bool boolResult = true; // deprecated typedef VigraTrueType type; static const bool value = true; }; template <> struct Or<VigraFalseType, VigraTrueType> { typedef VigraTrueType result; // deprecated static const bool boolResult = true; // deprecated typedef VigraTrueType type; static const bool value = true; }; template <> struct Or<VigraTrueType, VigraTrueType> { typedef VigraTrueType result; // deprecated static const bool boolResult = true; // deprecated typedef VigraTrueType type; static const bool value = true; }; #ifndef NO_PARTIAL_TEMPLATE_SPECIALIZATION template <class PREDICATE, class TRUECASE, class FALSECASE> struct If; template <class TRUECASE, class FALSECASE> struct If<VigraTrueType, TRUECASE, FALSECASE> { typedef TRUECASE type; }; template <class TRUECASE, class FALSECASE> struct If<VigraFalseType, TRUECASE, FALSECASE> { typedef FALSECASE type; }; template <bool PREDICATE, class TRUECASE, class FALSECASE> struct IfBool; template <class TRUECASE, class FALSECASE> struct IfBool<true, TRUECASE, FALSECASE> { typedef TRUECASE type; }; template <class TRUECASE, class FALSECASE> struct IfBool<false, TRUECASE, FALSECASE> { typedef FALSECASE type; }; template <class L, class R> struct IsSameType { typedef VigraFalseType result; // deprecated static const bool boolResult = false; // deprecated typedef VigraFalseType type; static const bool value = false; }; template <class T> struct IsSameType<T, T> { typedef VigraTrueType result; // deprecated static const bool boolResult = true; // deprecated typedef VigraTrueType type; static const bool value = true; }; #endif // NO_PARTIAL_TEMPLATE_SPECIALIZATION template <class DERIVED, class BASE> struct IsDerivedFrom { typedef char falseResult[1]; typedef char trueResult[2]; static falseResult * testIsDerivedFrom(...); static trueResult * testIsDerivedFrom(BASE const *); enum { resultSize = sizeof(*testIsDerivedFrom((DERIVED const *)0)) }; static const bool value = (resultSize == 2); typedef typename IfBool<value, VigraTrueType, VigraFalseType>::type type; static const bool boolResult = value; // deprecated typedef type result; // deprecated }; template <class T> struct has_result_type { typedef char falseResult[1]; typedef char trueResult[2]; static falseResult * test(...); template <class U> static trueResult * test(U *, typename U::result_type * = 0); enum { resultSize = sizeof(*test((T*)0)) }; static const bool value = (resultSize == 2); typedef typename IfBool<value, VigraTrueType, VigraFalseType>::type type; }; } // namespace vigra #endif /* VIGRA_METAPROGRAMMING_HXX */ <|endoftext|>
<commit_before>#include "Matrix33.hpp" #include "Matrix44.hpp" #include "Vector3.hpp" using namespace coffeemill; typedef RealVector3 Realvec; typedef RealMatrix33 Matrix3; typedef RealMatrix44 Matrix4; int main() { Realvec v1; Realvec v2(1e0); Realvec v3(1e0, 2e0, 3e0); Realvec v4(v2); Realvec v5(v2 + v3); Realvec v6(v2 - v3); Realvec v7(v2*2e0); Realvec v8(2e0*v2); Realvec v9(v2/2e0); Realvec vv5; Realvec vv6; Realvec vv7; Realvec vv8; Realvec vv9; vv5 = v2 + v3; vv6 = v2 - v3; vv7 = v2 * 2e0; vv8 = 2e0 * v2; vv9 = v2 / 2e0; std::cout << "v1 : " << v1 << std::endl; std::cout << "v2(1e0) : " << v2 << std::endl; std::cout << "v3(1e0, 2e0, 3e0) : " << v3 << std::endl; std::cout << "v4(v2) : " << v4 << std::endl; std::cout << "v5(v2+v3) : " << v5 << std::endl; std::cout << "v6(v2-v3) : " << v6 << std::endl; std::cout << "v7(v2*2e0) : " << v7 << std::endl; std::cout << "v8(2e0*v2) : " << v8 << std::endl; std::cout << "v9(v2/2e0) : " << v9 << std::endl; std::cout << "v5 = v2 + v3 : " << vv5 << std::endl; std::cout << "v6 = v2 - v3 : " << vv6 << std::endl; std::cout << "v7 = v2 * 2e0 : " << vv7 << std::endl; std::cout << "v8 = 2e0 * v2 : " << vv8 << std::endl; std::cout << "v9 = v2 / 2e0 : " << vv9 << std::endl; std::cout << "length(v2) : " << length(v2) << std::endl; std::cout << "len_square(v2) : " << len_square(v2) << std::endl; std::cout << "dot_prod(v2, v3) : " << dot_prod(v2, v3) << std::endl; Realvec temp; temp = cross_prod(v2, v3); std::cout << "cross_prod(v2, v3) : " << cross_prod(v2, v3) << std::endl; // Matrix3 m1; // Matrix3 m2(2e0); // Matrix3 m4(m2); // Matrix3 m5(m2 + m2); // Matrix3 m6(m2 - m2); // Matrix3 m7(m2*2e0); // Matrix3 m8(2e0*m2); // Matrix3 m9(m2/2e0); // // std::cout << "m1 : " << std::endl << m1 << std::endl; // std::cout << "m2(1e0) : " << std::endl << m2 << std::endl; // std::cout << "m4(m2) : " << std::endl << m4 << std::endl; // std::cout << "m5(m2+m2) : " << std::endl << m5 << std::endl; // std::cout << "m6(m2-m2) : " << std::endl << m6 << std::endl; // std::cout << "m7(m2*2e0) : " << std::endl << m7 << std::endl; // std::cout << "m8(2e0*m2) : " << std::endl << m8 << std::endl; // std::cout << "m9(m2/2e0) : " << std::endl << m9 << std::endl; // // m5 = m2 + m2; // m6 = m2 - m2; // m7 = m2 * 2e0; // m8 = 2e0 * m2; // m9 = m2 / 2e0; // // std::cout << "m5 = m2 + m2 : "<< std::endl << m5 << std::endl; // std::cout << "m6 = m2 - m2 : "<< std::endl << m6 << std::endl; // std::cout << "m7 = m2 * 2e0 : "<< std::endl << m7 << std::endl; // std::cout << "m8 = 2e0 * m2 : "<< std::endl << m8 << std::endl; // std::cout << "m9 = m2 / 2e0 : "<< std::endl << m9 << std::endl; // // m1(0,0) = 1e0; // m1(0,1) = 1e0; // m1(0,2) = 1e0; // m1(1,1) = 1e0; // m1(1,2) = 1e0; // m1(2,2) = 1e0; // std::cout << "m1: " << std::endl << m1 << std::endl; // Matrix3 m3temp; // m3temp = m1 * m2; // std::cout << "m1 * m2" << std::endl << m3temp << std::endl; // Matrix3 m10(m1 * m2); // std::cout << "m10(m1*m2): " << std::endl << m10 << std::endl; Matrix4 m1; Matrix4 m2(2e0); Matrix4 m3(1e0); Matrix4 m4(m2); Matrix4 m5(m2 + m3); Matrix4 m6(m2 - m3); Matrix4 m7(m2*2e0); Matrix4 m8(2e0*m2); Matrix4 m9(m2/2e0); std::cout << "m1 : " << std::endl << m1 << std::endl; std::cout << "m2(1e0) : " << std::endl << m2 << std::endl; std::cout << "m4(m2) : " << std::endl << m4 << std::endl; std::cout << "m5(m2+m2) : " << std::endl << m5 << std::endl; std::cout << "m6(m2-m2) : " << std::endl << m6 << std::endl; std::cout << "m7(m2*2e0) : " << std::endl << m7 << std::endl; std::cout << "m8(2e0*m2) : " << std::endl << m8 << std::endl; std::cout << "m9(m2/2e0) : " << std::endl << m9 << std::endl; m5 = m2 + m2; m6 = m2 - m2; m7 = m2 * 2e0; m8 = 2e0 * m2; m9 = m2 / 2e0; std::cout << "m5 = m2 + m2 : " << std::endl << m5 << std::endl; std::cout << "m6 = m2 - m2 : " << std::endl << m6 << std::endl; std::cout << "m7 = m2 * 2e0 : " << std::endl << m7 << std::endl; std::cout << "m8 = 2e0 * m2 : " << std::endl << m8 << std::endl; std::cout << "m9 = m2 / 2e0 : " << std::endl << m9 << std::endl; m1(0,0) = 1e0; m1(0,1) = 1e0; m1(0,2) = 1e0; m1(0,3) = 1e0; m1(1,1) = 1e0; m1(1,2) = 1e0; m1(1,3) = 1e0; m1(2,2) = 1e0; m1(2,3) = 1e0; m1(3,3) = 1e0; std::cout << "m1: " << std::endl << m1 << std::endl; Matrix4 m4temp; m4temp = m1 * m2; std::cout << "m1 * m2" << std::endl << m4temp << std::endl; Matrix4 m10(m1 * m2); std::cout << "m10(m1*m2): " << std::endl << m10 << std::endl; return 0; } <commit_msg>testing<commit_after>#include "LinearAlgebra.hpp" using namespace coffeemill; int main() { Realvec v1; Realvec v2(1e0); Realvec v3(1e0, 2e0, 3e0); Realvec v4(v2); Realvec v5(v2 + v3); Realvec v6(v2 - v3); Realvec v7(v2*2e0); Realvec v8(2e0*v2); Realvec v9(v2/2e0); Realvec vv5; Realvec vv6; Realvec vv7; Realvec vv8; Realvec vv9; vv5 = v2 + v3; vv6 = v2 - v3; vv7 = v2 * 2e0; vv8 = 2e0 * v2; vv9 = v2 / 2e0; std::cout << "v1 : " << v1 << std::endl; std::cout << "v2(1e0) : " << v2 << std::endl; std::cout << "v3(1e0, 2e0, 3e0) : " << v3 << std::endl; std::cout << "v4(v2) : " << v4 << std::endl; std::cout << "v5(v2+v3) : " << v5 << std::endl; std::cout << "v6(v2-v3) : " << v6 << std::endl; std::cout << "v7(v2*2e0) : " << v7 << std::endl; std::cout << "v8(2e0*v2) : " << v8 << std::endl; std::cout << "v9(v2/2e0) : " << v9 << std::endl; std::cout << "v5 = v2 + v3 : " << vv5 << std::endl; std::cout << "v6 = v2 - v3 : " << vv6 << std::endl; std::cout << "v7 = v2 * 2e0 : " << vv7 << std::endl; std::cout << "v8 = 2e0 * v2 : " << vv8 << std::endl; std::cout << "v9 = v2 / 2e0 : " << vv9 << std::endl; std::cout << "length(v2) : " << length(v2) << std::endl; std::cout << "len_square(v2) : " << len_square(v2) << std::endl; std::cout << "dot_prod(v2, v3) : " << dot_prod(v2, v3) << std::endl; Realvec temp; temp = cross_prod(v2, v3); std::cout << "cross_prod(v2, v3) : " << temp << std::endl; // Matrix3 m1; // Matrix3 m2(2e0); // Matrix3 m4(m2); // Matrix3 m5(m2 + m2); // Matrix3 m6(m2 - m2); // Matrix3 m7(m2*2e0); // Matrix3 m8(2e0*m2); // Matrix3 m9(m2/2e0); // // std::cout << "m1 : " << std::endl << m1 << std::endl; // std::cout << "m2(1e0) : " << std::endl << m2 << std::endl; // std::cout << "m4(m2) : " << std::endl << m4 << std::endl; // std::cout << "m5(m2+m2) : " << std::endl << m5 << std::endl; // std::cout << "m6(m2-m2) : " << std::endl << m6 << std::endl; // std::cout << "m7(m2*2e0) : " << std::endl << m7 << std::endl; // std::cout << "m8(2e0*m2) : " << std::endl << m8 << std::endl; // std::cout << "m9(m2/2e0) : " << std::endl << m9 << std::endl; // // m5 = m2 + m2; // m6 = m2 - m2; // m7 = m2 * 2e0; // m8 = 2e0 * m2; // m9 = m2 / 2e0; // // std::cout << "m5 = m2 + m2 : "<< std::endl << m5 << std::endl; // std::cout << "m6 = m2 - m2 : "<< std::endl << m6 << std::endl; // std::cout << "m7 = m2 * 2e0 : "<< std::endl << m7 << std::endl; // std::cout << "m8 = 2e0 * m2 : "<< std::endl << m8 << std::endl; // std::cout << "m9 = m2 / 2e0 : "<< std::endl << m9 << std::endl; // // m1(0,0) = 1e0; // m1(0,1) = 1e0; // m1(0,2) = 1e0; // m1(1,1) = 1e0; // m1(1,2) = 1e0; // m1(2,2) = 1e0; // std::cout << "m1: " << std::endl << m1 << std::endl; // Matrix3 m3temp; // m3temp = m1 * m2; // std::cout << "m1 * m2" << std::endl << m3temp << std::endl; // Matrix3 m10(m1 * m2); // std::cout << "m10(m1*m2): " << std::endl << m10 << std::endl; Matrix4 m1; Matrix4 m2(2e0); Matrix4 m3(1e0); Matrix4 m4(m2); Matrix4 m5(m2 + m3); Matrix4 m6(m2 - m3); Matrix4 m7(m2*2e0); Matrix4 m8(2e0*m2); Matrix4 m9(m2/2e0); std::cout << "m1 : " << std::endl << m1 << std::endl; std::cout << "m2(1e0) : " << std::endl << m2 << std::endl; std::cout << "m4(m2) : " << std::endl << m4 << std::endl; std::cout << "m5(m2+m2) : " << std::endl << m5 << std::endl; std::cout << "m6(m2-m2) : " << std::endl << m6 << std::endl; std::cout << "m7(m2*2e0) : " << std::endl << m7 << std::endl; std::cout << "m8(2e0*m2) : " << std::endl << m8 << std::endl; std::cout << "m9(m2/2e0) : " << std::endl << m9 << std::endl; m5 = m2 + m2; m6 = m2 - m2; m7 = m2 * 2e0; m8 = 2e0 * m2; m9 = m2 / 2e0; std::cout << "m5 = m2 + m2 : " << std::endl << m5 << std::endl; std::cout << "m6 = m2 - m2 : " << std::endl << m6 << std::endl; std::cout << "m7 = m2 * 2e0 : " << std::endl << m7 << std::endl; std::cout << "m8 = 2e0 * m2 : " << std::endl << m8 << std::endl; std::cout << "m9 = m2 / 2e0 : " << std::endl << m9 << std::endl; m1(0,0) = 1e0; m1(0,1) = 1e0; m1(0,2) = 1e0; m1(0,3) = 1e0; m1(1,1) = 1e0; m1(1,2) = 1e0; m1(1,3) = 1e0; m1(2,2) = 1e0; m1(2,3) = 1e0; m1(3,3) = 1e0; std::cout << "m1: " << std::endl << m1 << std::endl; Matrix4 m4temp; m4temp = m1 * m2; std::cout << "m1 * m2" << std::endl << m4temp << std::endl; Matrix4 m10(m1 * m2); std::cout << "m10(m1*m2): " << std::endl << m10 << std::endl; return 0; } <|endoftext|>
<commit_before>/**@file GSM/SIP Mobility Management, GSM 04.08. */ /* * Copyright 2008, 2009, 2010, 2011 Free Software Foundation, Inc. * Copyright 2011 Range Networks, Inc. * * This software is distributed under the terms of the GNU Affero Public License. * See the COPYING file in the main directory for details. * * This use of this software may be subject to additional restrictions. * See the LEGAL file in the main directory for details. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <Timeval.h> #include "ControlCommon.h" #include "MobilityManagement.h" #include "SMSControl.h" #include "CallControl.h" #include "RRLPServer.h" #include <GSMLogicalChannel.h> #include <GSML3RRMessages.h> #include <GSML3MMMessages.h> #include <GSML3CCMessages.h> #include <GSMConfig.h> using namespace std; #include <SIPInterface.h> #include <SIPUtility.h> #include <SIPMessage.h> #include <SIPEngine.h> #include <SubscriberRegistry.h> using namespace SIP; #include <Regexp.h> #include <Logger.h> #undef WARNING using namespace GSM; using namespace Control; /** Controller for CM Service requests, dispatches out to multiple possible transaction controllers. */ void Control::CMServiceResponder(const L3CMServiceRequest* cmsrq, LogicalChannel* DCCH) { assert(cmsrq); assert(DCCH); LOG(INFO) << *cmsrq; switch (cmsrq->serviceType().type()) { case L3CMServiceType::MobileOriginatedCall: MOCStarter(cmsrq,DCCH); break; case L3CMServiceType::ShortMessage: MOSMSController(cmsrq,DCCH); break; default: LOG(NOTICE) << "service not supported for " << *cmsrq; // Cause 0x20 means "serivce not supported". DCCH->send(L3CMServiceReject(0x20)); DCCH->send(L3ChannelRelease()); } // The transaction may or may not be cleared, // depending on the assignment type. } /** Controller for the IMSI Detach transaction, GSM 04.08 4.3.4. */ void Control::IMSIDetachController(const L3IMSIDetachIndication* idi, LogicalChannel* DCCH) { assert(idi); assert(DCCH); LOG(INFO) << *idi; // The IMSI detach maps to a SIP unregister with the local Asterisk server. try { // FIXME -- Resolve TMSIs to IMSIs. if (idi->mobileID().type()==IMSIType) { SIPEngine engine(gConfig.getStr("SIP.Proxy.Registration").c_str(), idi->mobileID().digits()); engine.unregister(); } } catch(SIPTimeout) { LOG(ALERT) "SIP registration timed out. Is Asterisk running?"; } // No reponse required, so just close the channel. DCCH->send(L3ChannelRelease()); // Many handsets never complete the transaction. // So force a shutdown of the channel. DCCH->send(HARDRELEASE); } /** Send a given welcome message from a given short code. @return true if it was sent */ bool sendWelcomeMessage(const char* messageName, const char* shortCodeName, const char *IMSI, LogicalChannel* DCCH, const char *whiteListCode = NULL) { if (!gConfig.defines(messageName)) return false; LOG(INFO) << "sending " << messageName << " message to handset"; ostringstream message; message << gConfig.getStr(messageName) << " IMSI:" << IMSI; if (whiteListCode) { message << ", white-list code: " << whiteListCode; } // This returns when delivery is acked in L3. deliverSMSToMS( gConfig.getStr(shortCodeName).c_str(), message.str().c_str(), "text/plain", random()%7,DCCH); return true; } /** Controller for the Location Updating transaction, GSM 04.08 4.4.4. @param lur The location updating request. @param DCCH The Dm channel to the MS, which will be released by the function. */ void Control::LocationUpdatingController(const L3LocationUpdatingRequest* lur, LogicalChannel* DCCH) { assert(DCCH); assert(lur); LOG(INFO) << *lur; // The location updating request gets mapped to a SIP // registration with the Asterisk server. // We also allocate a new TMSI for every handset we encounter. // If the handset is allow to register it may receive a TMSI reassignment. // Resolve an IMSI and see if there's a pre-existing IMSI-TMSI mapping. // This operation will throw an exception, caught in a higher scope, // if it fails in the GSM domain. L3MobileIdentity mobileID = lur->mobileID(); bool sameLAI = (lur->LAI() == gBTS.LAI()); unsigned preexistingTMSI = resolveIMSI(sameLAI,mobileID,DCCH); const char *IMSI = mobileID.digits(); // IMSIAttach set to true if this is a new registration. bool IMSIAttach = (preexistingTMSI==0); // We assign generate a TMSI for every new phone we see, // even if we don't actually assign it. unsigned newTMSI = 0; if (!preexistingTMSI) newTMSI = gTMSITable.assign(IMSI,lur); // Try to register the IMSI. // This will be set true if registration succeeded in the SIP world. bool success = false; try { SIPEngine engine(gConfig.getStr("SIP.Proxy.Registration").c_str(),IMSI); LOG(DEBUG) << "waiting for registration of " << IMSI << " on " << gConfig.getStr("SIP.Proxy.Registration"); success = engine.Register(SIPEngine::SIPRegister); } catch(SIPTimeout) { LOG(ALERT) "SIP registration timed out. Is the proxy running at " << gConfig.getStr("SIP.Proxy.Registration"); // Reject with a "network failure" cause code, 0x11. DCCH->send(L3LocationUpdatingReject(0x11)); // HACK -- wait long enough for a response // FIXME -- Why are we doing this? sleep(4); // Release the channel and return. DCCH->send(L3ChannelRelease()); return; } // This allows us to configure Open Registration bool openRegistration = gConfig.defines("Control.LUR.OpenRegistration"); // Query for IMEI? if (gConfig.defines("Control.LUR.QueryIMEI")) { DCCH->send(L3IdentityRequest(IMEIType)); L3Message* msg = getMessage(DCCH); L3IdentityResponse *resp = dynamic_cast<L3IdentityResponse*>(msg); if (!resp) { if (msg) { LOG(WARNING) << "Unexpected message " << *msg; delete msg; } throw UnexpectedMessage(); } LOG(INFO) << *resp; string new_imei = resp->mobileID().digits(); if (!gTMSITable.IMEI(IMSI,new_imei.c_str())){ LOG(WARNING) << "failed access to TMSITable"; } //query subscriber registry for old imei, update if neccessary string name = string("IMSI") + IMSI; string old_imei = gSubscriberRegistry.imsiGet(name, "hardware"); //if we have a new imei and either there's no old one, or it is different... if (!new_imei.empty() && (old_imei.empty() || old_imei != new_imei)){ LOG(INFO) << "Updating IMSI" << IMSI << " to IMEI:" << new_imei; if (gSubscriberRegistry.imsiSet(name,"RRLPSupported", "1")) { LOG(INFO) << "SR RRLPSupported update problem"; } if (gSubscriberRegistry.imsiSet(name,"hardware", new_imei)) { LOG(INFO) << "SR hardware update problem"; } } delete msg; } // Query for classmark? if (IMSIAttach && gConfig.defines("Control.LUR.QueryClassmark")) { DCCH->send(L3ClassmarkEnquiry()); L3Message* msg = getMessage(DCCH); L3ClassmarkChange *resp = dynamic_cast<L3ClassmarkChange*>(msg); if (!resp) { if (msg) { LOG(WARNING) << "Unexpected message " << *msg; delete msg; } throw UnexpectedMessage(); } LOG(INFO) << *resp; const L3MobileStationClassmark2& classmark = resp->classmark(); if (!gTMSITable.classmark(IMSI,classmark)) LOG(WARNING) << "failed access to TMSITable"; delete msg; } // We fail closed unless we're configured otherwise if (!success && !openRegistration) { LOG(INFO) << "registration FAILED: " << mobileID; DCCH->send(L3LocationUpdatingReject(gConfig.getNum("Control.LUR.UnprovisionedRejectCause"))); if (!preexistingTMSI) { sendWelcomeMessage( "Control.LUR.FailedRegistration.Message", "Control.LUR.FailedRegistration.ShortCode", IMSI,DCCH); } // Release the channel and return. DCCH->send(L3ChannelRelease()); return; } // If success is true, we had a normal registration. // Otherwise, we are here because of open registration. // Either way, we're going to register a phone if we arrive here. if (success) { LOG(INFO) << "registration SUCCESS: " << mobileID; } else { LOG(INFO) << "registration ALLOWED: " << mobileID; } // Send the "short name" and time-of-day. if (IMSIAttach && gConfig.defines("GSM.Identity.ShortName")) { DCCH->send(L3MMInformation(gConfig.getStr("GSM.Identity.ShortName").c_str())); } // Accept. Make a TMSI assignment, too, if needed. if (preexistingTMSI || !gConfig.defines("Control.LUR.SendTMSIs")) { DCCH->send(L3LocationUpdatingAccept(gBTS.LAI())); } else { assert(newTMSI); DCCH->send(L3LocationUpdatingAccept(gBTS.LAI(),newTMSI)); // Wait for MM TMSI REALLOCATION COMPLETE (0x055b). L3Frame* resp = DCCH->recv(1000); // FIXME -- Actually check the response type. if (!resp) { LOG(NOTICE) << "no response to TMSI assignment"; } else { LOG(INFO) << *resp; } delete resp; } if (gConfig.defines("Control.LUR.QueryRRLP")) { // Query for RRLP if (!sendRRLP(mobileID, DCCH)) { LOG(INFO) << "RRLP request failed"; } } // If this is an IMSI attach, send a welcome message. if (IMSIAttach) { if (success) { sendWelcomeMessage( "Control.LUR.NormalRegistration.Message", "Control.LUR.NormalRegistration.ShortCode", IMSI, DCCH); } else { sendWelcomeMessage( "Control.LUR.OpenRegistration.Message", "Control.LUR.OpenRegistration.ShortCode", IMSI, DCCH); } } // Release the channel and return. DCCH->send(L3ChannelRelease()); return; } // vim: ts=4 sw=4 <commit_msg>adding regex back into MobilityManagement for OpenRegistration. It's in the manual, we should have it in the code.<commit_after>/**@file GSM/SIP Mobility Management, GSM 04.08. */ /* * Copyright 2008, 2009, 2010, 2011 Free Software Foundation, Inc. * Copyright 2011 Range Networks, Inc. * * This software is distributed under the terms of the GNU Affero Public License. * See the COPYING file in the main directory for details. * * This use of this software may be subject to additional restrictions. * See the LEGAL file in the main directory for details. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <Timeval.h> #include "ControlCommon.h" #include "MobilityManagement.h" #include "SMSControl.h" #include "CallControl.h" #include "RRLPServer.h" #include <GSMLogicalChannel.h> #include <GSML3RRMessages.h> #include <GSML3MMMessages.h> #include <GSML3CCMessages.h> #include <GSMConfig.h> using namespace std; #include <SIPInterface.h> #include <SIPUtility.h> #include <SIPMessage.h> #include <SIPEngine.h> #include <SubscriberRegistry.h> using namespace SIP; #include <Regexp.h> #include <Logger.h> #undef WARNING using namespace GSM; using namespace Control; /** Controller for CM Service requests, dispatches out to multiple possible transaction controllers. */ void Control::CMServiceResponder(const L3CMServiceRequest* cmsrq, LogicalChannel* DCCH) { assert(cmsrq); assert(DCCH); LOG(INFO) << *cmsrq; switch (cmsrq->serviceType().type()) { case L3CMServiceType::MobileOriginatedCall: MOCStarter(cmsrq,DCCH); break; case L3CMServiceType::ShortMessage: MOSMSController(cmsrq,DCCH); break; default: LOG(NOTICE) << "service not supported for " << *cmsrq; // Cause 0x20 means "serivce not supported". DCCH->send(L3CMServiceReject(0x20)); DCCH->send(L3ChannelRelease()); } // The transaction may or may not be cleared, // depending on the assignment type. } /** Controller for the IMSI Detach transaction, GSM 04.08 4.3.4. */ void Control::IMSIDetachController(const L3IMSIDetachIndication* idi, LogicalChannel* DCCH) { assert(idi); assert(DCCH); LOG(INFO) << *idi; // The IMSI detach maps to a SIP unregister with the local Asterisk server. try { // FIXME -- Resolve TMSIs to IMSIs. if (idi->mobileID().type()==IMSIType) { SIPEngine engine(gConfig.getStr("SIP.Proxy.Registration").c_str(), idi->mobileID().digits()); engine.unregister(); } } catch(SIPTimeout) { LOG(ALERT) "SIP registration timed out. Is Asterisk running?"; } // No reponse required, so just close the channel. DCCH->send(L3ChannelRelease()); // Many handsets never complete the transaction. // So force a shutdown of the channel. DCCH->send(HARDRELEASE); } /** Send a given welcome message from a given short code. @return true if it was sent */ bool sendWelcomeMessage(const char* messageName, const char* shortCodeName, const char *IMSI, LogicalChannel* DCCH, const char *whiteListCode = NULL) { if (!gConfig.defines(messageName)) return false; LOG(INFO) << "sending " << messageName << " message to handset"; ostringstream message; message << gConfig.getStr(messageName) << " IMSI:" << IMSI; if (whiteListCode) { message << ", white-list code: " << whiteListCode; } // This returns when delivery is acked in L3. deliverSMSToMS( gConfig.getStr(shortCodeName).c_str(), message.str().c_str(), "text/plain", random()%7,DCCH); return true; } /** Controller for the Location Updating transaction, GSM 04.08 4.4.4. @param lur The location updating request. @param DCCH The Dm channel to the MS, which will be released by the function. */ void Control::LocationUpdatingController(const L3LocationUpdatingRequest* lur, LogicalChannel* DCCH) { assert(DCCH); assert(lur); LOG(INFO) << *lur; // The location updating request gets mapped to a SIP // registration with the Asterisk server. // We also allocate a new TMSI for every handset we encounter. // If the handset is allow to register it may receive a TMSI reassignment. // Resolve an IMSI and see if there's a pre-existing IMSI-TMSI mapping. // This operation will throw an exception, caught in a higher scope, // if it fails in the GSM domain. L3MobileIdentity mobileID = lur->mobileID(); bool sameLAI = (lur->LAI() == gBTS.LAI()); unsigned preexistingTMSI = resolveIMSI(sameLAI,mobileID,DCCH); const char *IMSI = mobileID.digits(); // IMSIAttach set to true if this is a new registration. bool IMSIAttach = (preexistingTMSI==0); // We assign generate a TMSI for every new phone we see, // even if we don't actually assign it. unsigned newTMSI = 0; if (!preexistingTMSI) newTMSI = gTMSITable.assign(IMSI,lur); // Try to register the IMSI. // This will be set true if registration succeeded in the SIP world. bool success = false; try { SIPEngine engine(gConfig.getStr("SIP.Proxy.Registration").c_str(),IMSI); LOG(DEBUG) << "waiting for registration of " << IMSI << " on " << gConfig.getStr("SIP.Proxy.Registration"); success = engine.Register(SIPEngine::SIPRegister); } catch(SIPTimeout) { LOG(ALERT) "SIP registration timed out. Is the proxy running at " << gConfig.getStr("SIP.Proxy.Registration"); // Reject with a "network failure" cause code, 0x11. DCCH->send(L3LocationUpdatingReject(0x11)); // HACK -- wait long enough for a response // FIXME -- Why are we doing this? sleep(4); // Release the channel and return. DCCH->send(L3ChannelRelease()); return; } // This allows us to configure Open Registration bool openRegistration = false; if (gConfig.defines("Control.LUR.OpenRegistration")) { if (!gConfig.defines("Control.LUR.OpenRegistration.Message")) { gConfig.set("Control.LUR.OpenRegistration.Message","Welcome to the test network. Your IMSI is "); } Regexp rxp(gConfig.getStr("Control.LUR.OpenRegistration").c_str()); openRegistration = rxp.match(IMSI); if (gConfig.defines("Control.LUR.OpenRegistration.Reject")) { Regexp rxpReject(gConfig.getStr("Control.LUR.OpenRegistration.Reject").c_str()); bool openRegistrationReject = rxpReject.match(IMSI); openRegistration = openRegistration && !openRegistrationReject; } } // Query for IMEI? if (gConfig.defines("Control.LUR.QueryIMEI")) { DCCH->send(L3IdentityRequest(IMEIType)); L3Message* msg = getMessage(DCCH); L3IdentityResponse *resp = dynamic_cast<L3IdentityResponse*>(msg); if (!resp) { if (msg) { LOG(WARNING) << "Unexpected message " << *msg; delete msg; } throw UnexpectedMessage(); } LOG(INFO) << *resp; string new_imei = resp->mobileID().digits(); if (!gTMSITable.IMEI(IMSI,new_imei.c_str())){ LOG(WARNING) << "failed access to TMSITable"; } //query subscriber registry for old imei, update if neccessary string name = string("IMSI") + IMSI; string old_imei = gSubscriberRegistry.imsiGet(name, "hardware"); //if we have a new imei and either there's no old one, or it is different... if (!new_imei.empty() && (old_imei.empty() || old_imei != new_imei)){ LOG(INFO) << "Updating IMSI" << IMSI << " to IMEI:" << new_imei; if (gSubscriberRegistry.imsiSet(name,"RRLPSupported", "1")) { LOG(INFO) << "SR RRLPSupported update problem"; } if (gSubscriberRegistry.imsiSet(name,"hardware", new_imei)) { LOG(INFO) << "SR hardware update problem"; } } delete msg; } // Query for classmark? if (IMSIAttach && gConfig.defines("Control.LUR.QueryClassmark")) { DCCH->send(L3ClassmarkEnquiry()); L3Message* msg = getMessage(DCCH); L3ClassmarkChange *resp = dynamic_cast<L3ClassmarkChange*>(msg); if (!resp) { if (msg) { LOG(WARNING) << "Unexpected message " << *msg; delete msg; } throw UnexpectedMessage(); } LOG(INFO) << *resp; const L3MobileStationClassmark2& classmark = resp->classmark(); if (!gTMSITable.classmark(IMSI,classmark)) LOG(WARNING) << "failed access to TMSITable"; delete msg; } // We fail closed unless we're configured otherwise if (!success && !openRegistration) { LOG(INFO) << "registration FAILED: " << mobileID; DCCH->send(L3LocationUpdatingReject(gConfig.getNum("Control.LUR.UnprovisionedRejectCause"))); if (!preexistingTMSI) { sendWelcomeMessage( "Control.LUR.FailedRegistration.Message", "Control.LUR.FailedRegistration.ShortCode", IMSI,DCCH); } // Release the channel and return. DCCH->send(L3ChannelRelease()); return; } // If success is true, we had a normal registration. // Otherwise, we are here because of open registration. // Either way, we're going to register a phone if we arrive here. if (success) { LOG(INFO) << "registration SUCCESS: " << mobileID; } else { LOG(INFO) << "registration ALLOWED: " << mobileID; } // Send the "short name" and time-of-day. if (IMSIAttach && gConfig.defines("GSM.Identity.ShortName")) { DCCH->send(L3MMInformation(gConfig.getStr("GSM.Identity.ShortName").c_str())); } // Accept. Make a TMSI assignment, too, if needed. if (preexistingTMSI || !gConfig.defines("Control.LUR.SendTMSIs")) { DCCH->send(L3LocationUpdatingAccept(gBTS.LAI())); } else { assert(newTMSI); DCCH->send(L3LocationUpdatingAccept(gBTS.LAI(),newTMSI)); // Wait for MM TMSI REALLOCATION COMPLETE (0x055b). L3Frame* resp = DCCH->recv(1000); // FIXME -- Actually check the response type. if (!resp) { LOG(NOTICE) << "no response to TMSI assignment"; } else { LOG(INFO) << *resp; } delete resp; } if (gConfig.defines("Control.LUR.QueryRRLP")) { // Query for RRLP if (!sendRRLP(mobileID, DCCH)) { LOG(INFO) << "RRLP request failed"; } } // If this is an IMSI attach, send a welcome message. if (IMSIAttach) { if (success) { sendWelcomeMessage( "Control.LUR.NormalRegistration.Message", "Control.LUR.NormalRegistration.ShortCode", IMSI, DCCH); } else { sendWelcomeMessage( "Control.LUR.OpenRegistration.Message", "Control.LUR.OpenRegistration.ShortCode", IMSI, DCCH); } } // Release the channel and return. DCCH->send(L3ChannelRelease()); return; } // vim: ts=4 sw=4 <|endoftext|>
<commit_before>#include "Run.h" #include "InputContainer.h" Run::Run(std::string iTag) : mRunName(iTag) { Options runOptions = loadRunOptions(iTag); init(runOptions); } Run::Run(const Options& iOptions) { init(iOptions); } void Run::init(const Options& iOptions) { mRunOptions = iOptions; // Create input service mInputContainer = new InputContainer(Options("")); // Create a default data object // Each configuration needs its own data object, since a configuration can choose its own // input sources, downscaler, etc. However we to reuse the downscaler, etc for those // configurations that do not need customization. Therefore create a default data object that can // reused if needed. Options dataOptions0; dataOptions0.addOption("runName", mRunName); Options::copyOption("inputs", mRunOptions, dataOptions0); Options::copyOption("qcs", mRunOptions, dataOptions0); if(!dataOptions0.hasValue("inputs")) { std::stringstream ss; ss << "Cannot initialize data object. 'inputs' option not provided for run '" << mRunName << "'"; Global::logger->write(ss.str(), Logger::error); } mDefaultData = new Data(dataOptions0, mInputContainer); // Get variable/configurations std::map<std::string, std::vector<std::string> > varConfs; std::map<std::string, std::vector<std::string> > varMetrics; loadVarConfs(mRunOptions, varConfs, varMetrics, mVariables); // Loop over all variables for(int v = 0; v < mVariables.size(); v++) { std::string variable = mVariables[v]; // Loop over all configurations std::vector<std::string> configurations = varConfs[variable]; for(int c = 0; c < configurations.size(); c++) { // Set up options for configuration Options configOptions; Configuration::getOptions(configurations[c], configOptions); //////////////////////////////////////// // Pass run options to configurations // //////////////////////////////////////// Options::copyOption("offsets", mRunOptions, configOptions); // This is needed by the parameter estimation if(!configOptions.hasValue("parameterIo")) { Options::copyOption("parameterIo", mRunOptions, configOptions); } if(!configOptions.hasValue("inputs")) { Options::copyOption("inputs", mRunOptions, configOptions); } if(!configOptions.hasValue("numOffsetsSpreadObs")) { Options::copyOption("numOffsetsSpreadObs", mRunOptions, configOptions); } Options::copyOption("numDaysParameterSearch", mRunOptions, configOptions); if(!configOptions.hasValue("region")) { // Set up how to choose which obs to use in parameter estimation Options::copyOption("region", mRunOptions, configOptions); } // Pass down which output offsets we are producing for Options::copyOption("offsets", mRunOptions, configOptions); //////////////////////////////////////// // Create data for this configuration // //////////////////////////////////////// Data* data; if(configOptions.hasValue("inputs") || configOptions.hasValue("qcs") || configOptions.hasValue("downscaler")) { // Create custom data object. NOTE: If any of options are cutomized by configuration, // then the downscaler and qcs cannot be reused, since their cached values // may be incorrect // Initialize with default, then overwrite Options dataOptions = dataOptions0; dataOptions.addOption("runName", mRunName); Options::copyOption("inputs", configOptions, dataOptions); // Only copy if it is there Options::copyOption("qcs", configOptions, dataOptions); if(!dataOptions.hasValue("inputs")) { std::stringstream ss; ss << "Cannot initialize data object. 'inputs' neither provided for run '" << mRunName << "' nor for configuration '" << configurations[c] << "'."; Global::logger->write(ss.str(), Logger::error); } data = new Data(dataOptions, mInputContainer); mConfigDatas.push_back(data); } else { // No need to create a custom data object, use the default one data = mDefaultData; } Configuration* conf = Configuration::getScheme(configOptions, *data); mVarConfs[variable].push_back(conf); } // Metrics std::vector<std::string> metrics = varMetrics[variable]; for(int m = 0; m < metrics.size(); m++) { Metric* metric = Metric::getScheme(metrics[m], *mDefaultData); mMetrics[variable].push_back(metric); } } // Outputs std::vector<std::string> outputsString; mRunOptions.getValues("outputs", outputsString); for(int i = 0; i < outputsString.size(); i++) { Output* output = Output::getScheme(outputsString[i], *mDefaultData); mOutputs.push_back(output); } // Debug int debug; if(!mRunOptions.getValue("debug", debug)) { debug = 0; } Global::logger->setMaxLevel((Logger::Level) debug); ////////////// // Location // ////////////// std::string locationSetTag; if(mRunOptions.getValue("locationTag", locationSetTag)) { Input* input = mInputContainer->getInput(locationSetTag); mLocations = input->getLocations(); delete input; } else { // Assume that we want to forecast for locations where have obs Input* input = mDefaultData->getObsInput(); if(input != NULL) { mLocations = input->getLocations(); } } if(mLocations.size() == 0) { std::stringstream ss; ss << "Run: No locations to produce forecasts for are defined for run '" << mRunName << "'. Either add an observation dataset to the run's 'inputs' option, " << "or use the 'locationTag' option to specify which dataset to use locations from."; Global::logger->write(ss.str(), Logger::error); } std::vector<int> useLocations; if(mRunOptions.getValues("locations", useLocations)) { std::vector<Location> temp = mLocations; mLocations.clear(); for(int k = 0; k < (int) temp.size(); k++) { for(int i = 0; i < (int) useLocations.size(); i++) { if(temp[k].getId() == useLocations[i]) { mLocations.push_back(temp[k]); } } } if(mLocations.size() == 0) { std::stringstream ss; ss << "No valid locations selected by 'locations' run option"; Global::logger->write(ss.str(), Logger::error); } } ///////////// // Offsets // ///////////// if(mRunOptions.getValues("offsets", mOffsets)) { std::stringstream ss; ss << "Using offsets from run specifications"; Global::logger->write(ss.str(), Logger::critical); } else { Input* input; std::string offsetSetTag; if(mRunOptions.getValue("offsetTag", offsetSetTag)) { input = mInputContainer->getInput(offsetSetTag); } else { // Default to main forecast set, because ... input = mDefaultData->getInput(); } std::stringstream ss; ss << "Using offsets from dataset " << input->getName(); Global::logger->write(ss.str(), Logger::status); mOffsets = input->getOffsets(); delete input; } } Run::~Run() { delete mInputContainer; delete mDefaultData; for(int i = 0; i < mConfigDatas.size(); i++) { delete mConfigDatas[i]; } } Options Run::loadRunOptions(std::string iTag) const { int dotPosition = -1; for(int i = 0; i < iTag.size(); i++) { if(iTag[i] == '.') dotPosition = i; } std::string filename; std::string tag; if(dotPosition == -1) { std::stringstream ss; ss << Namelist::getDefaultLocation() << "default/runs.nl"; filename = ss.str(); tag = iTag; } else { assert(dotPosition != 0); std::string folder = iTag.substr(0,dotPosition); tag = iTag.substr(dotPosition+1);//, iTag.size()-2); std::stringstream ss; ss << Namelist::getDefaultLocation() << folder << "/runs" << ".nl"; filename = ss.str(); } Namelist nlRuns(filename); std::string optString = nlRuns.findLine(tag); if(optString == "") { std::stringstream ss; ss << "Run " << iTag << " does not exist"; Global::logger->write(ss.str(), Logger::error); } return Options(optString); } void Run::loadVarConfs(const Options& iRunOptions, std::map<std::string, std::vector<std::string> >& iVarConfs, std::map<std::string, std::vector<std::string> >& iMetrics, std::vector<std::string>& iVariables) const { // Variable-configurations std::vector<std::string> varConfs; std::set<std::string> variables; iRunOptions.getValues("varconfs", varConfs); if(varConfs.size() == 0) { Global::logger->write("No variable/configurations specified for this run", Logger::error); } for(int v = 0; v < (int) varConfs.size(); v++) { std::string currVarConf = varConfs[v]; // Read from file int dotPosition = -1; for(int i = 0; i < currVarConf.size(); i++) { if(currVarConf[i] == '.') dotPosition = i; } std::string folder; std::string tag; if(dotPosition == -1) { folder = "default"; tag = currVarConf; } else { assert(dotPosition != 0); folder = currVarConf.substr(0,dotPosition); tag = currVarConf.substr(dotPosition+1);//, iTag.size()-2); } Namelist nlVarConfs("varconfs", folder); std::string line = nlVarConfs.findLine(tag); if(line == "") { std::stringstream ss; ss << "Variable/Configuration '" << tag << "' does not exist"; Global::logger->write(ss.str(), Logger::error); } Options opt(line); // Variable std::string variable; opt.getRequiredValue("variable", variable); variables.insert(variable); // Configuration std::vector<std::string> configurations; opt.getRequiredValues("configurations", configurations); for(int i = 0; i < configurations.size(); i++) iVarConfs[variable].push_back(configurations[i]); // Set up metrics std::vector<std::string> metricTags; opt.getValues("metrics", metricTags); for(int i = 0; i < metricTags.size(); i++) iMetrics[variable].push_back(metricTags[i]); } iVariables = std::vector<std::string>(variables.begin(), variables.end()); } void Run::getRunOptions(Options& iOptions) const { iOptions = mRunOptions; } std::vector<Output*> Run::getOutputs() const { return mOutputs; } Data* Run::getData() const { return mDefaultData; } std::vector<Location> Run::getLocations() const { return mLocations; } std::vector<float> Run::getOffsets() const { return mOffsets; } std::vector<std::string> Run::getVariables() const { return mVariables; } std::vector<Configuration*> Run::getConfigurations(const std::string& iVariable) const { std::vector<Configuration*> configurations; std::map<std::string, std::vector<Configuration*> >::const_iterator it = mVarConfs.find(iVariable); if(it == mVarConfs.end()) { std::stringstream ss; ss << "Run: No configuration specified for variable " << iVariable; Global::logger->write(ss.str(), Logger::debug); } else { configurations = it->second; } return configurations; } std::vector<Configuration*> Run::getConfigurations() const { std::vector<Configuration*> configurations; std::map<std::string, std::vector<Configuration*> >::const_iterator it; for(it = mVarConfs.begin(); it != mVarConfs.end(); it++) { for(int i = 0; i < it->second.size(); i++) { configurations.push_back(it->second[i]); } } return configurations; } std::vector<Metric*> Run::getMetrics(const std::string& iVariable) const { std::vector<Metric*> metrics; std::map<std::string, std::vector<Metric*> >::const_iterator it = mMetrics.find(iVariable); if(it == mMetrics.end()) { std::stringstream ss; ss << "Run: No metrics specified for variable " << iVariable; Global::logger->write(ss.str(), Logger::debug); } else { metrics = it->second; } return metrics; } <commit_msg>Fixes bug where the Run accidentally deletes inputs<commit_after>#include "Run.h" #include "InputContainer.h" Run::Run(std::string iTag) : mRunName(iTag) { Options runOptions = loadRunOptions(iTag); init(runOptions); } Run::Run(const Options& iOptions) { init(iOptions); } void Run::init(const Options& iOptions) { mRunOptions = iOptions; // Create input service mInputContainer = new InputContainer(Options("")); // Create a default data object // Each configuration needs its own data object, since a configuration can choose its own // input sources, downscaler, etc. However we to reuse the downscaler, etc for those // configurations that do not need customization. Therefore create a default data object that can // reused if needed. Options dataOptions0; dataOptions0.addOption("runName", mRunName); Options::copyOption("inputs", mRunOptions, dataOptions0); Options::copyOption("qcs", mRunOptions, dataOptions0); if(!dataOptions0.hasValue("inputs")) { std::stringstream ss; ss << "Cannot initialize data object. 'inputs' option not provided for run '" << mRunName << "'"; Global::logger->write(ss.str(), Logger::error); } mDefaultData = new Data(dataOptions0, mInputContainer); // Get variable/configurations std::map<std::string, std::vector<std::string> > varConfs; std::map<std::string, std::vector<std::string> > varMetrics; loadVarConfs(mRunOptions, varConfs, varMetrics, mVariables); // Loop over all variables for(int v = 0; v < mVariables.size(); v++) { std::string variable = mVariables[v]; // Loop over all configurations std::vector<std::string> configurations = varConfs[variable]; for(int c = 0; c < configurations.size(); c++) { // Set up options for configuration Options configOptions; Configuration::getOptions(configurations[c], configOptions); //////////////////////////////////////// // Pass run options to configurations // //////////////////////////////////////// Options::copyOption("offsets", mRunOptions, configOptions); // This is needed by the parameter estimation if(!configOptions.hasValue("parameterIo")) { Options::copyOption("parameterIo", mRunOptions, configOptions); } if(!configOptions.hasValue("inputs")) { Options::copyOption("inputs", mRunOptions, configOptions); } if(!configOptions.hasValue("numOffsetsSpreadObs")) { Options::copyOption("numOffsetsSpreadObs", mRunOptions, configOptions); } Options::copyOption("numDaysParameterSearch", mRunOptions, configOptions); if(!configOptions.hasValue("region")) { // Set up how to choose which obs to use in parameter estimation Options::copyOption("region", mRunOptions, configOptions); } // Pass down which output offsets we are producing for Options::copyOption("offsets", mRunOptions, configOptions); //////////////////////////////////////// // Create data for this configuration // //////////////////////////////////////// Data* data; if(configOptions.hasValue("inputs") || configOptions.hasValue("qcs") || configOptions.hasValue("downscaler")) { // Create custom data object. NOTE: If any of options are cutomized by configuration, // then the downscaler and qcs cannot be reused, since their cached values // may be incorrect // Initialize with default, then overwrite Options dataOptions = dataOptions0; dataOptions.addOption("runName", mRunName); Options::copyOption("inputs", configOptions, dataOptions); // Only copy if it is there Options::copyOption("qcs", configOptions, dataOptions); if(!dataOptions.hasValue("inputs")) { std::stringstream ss; ss << "Cannot initialize data object. 'inputs' neither provided for run '" << mRunName << "' nor for configuration '" << configurations[c] << "'."; Global::logger->write(ss.str(), Logger::error); } data = new Data(dataOptions, mInputContainer); mConfigDatas.push_back(data); } else { // No need to create a custom data object, use the default one data = mDefaultData; } Configuration* conf = Configuration::getScheme(configOptions, *data); mVarConfs[variable].push_back(conf); } // Metrics std::vector<std::string> metrics = varMetrics[variable]; for(int m = 0; m < metrics.size(); m++) { Metric* metric = Metric::getScheme(metrics[m], *mDefaultData); mMetrics[variable].push_back(metric); } } // Outputs std::vector<std::string> outputsString; mRunOptions.getValues("outputs", outputsString); for(int i = 0; i < outputsString.size(); i++) { Output* output = Output::getScheme(outputsString[i], *mDefaultData); mOutputs.push_back(output); } // Debug int debug; if(!mRunOptions.getValue("debug", debug)) { debug = 0; } Global::logger->setMaxLevel((Logger::Level) debug); ////////////// // Location // ////////////// std::string locationSetTag; if(mRunOptions.getValue("locationTag", locationSetTag)) { Input* input = mInputContainer->getInput(locationSetTag); mLocations = input->getLocations(); } else { // Assume that we want to forecast for locations where have obs Input* input = mDefaultData->getObsInput(); if(input != NULL) { mLocations = input->getLocations(); } } if(mLocations.size() == 0) { std::stringstream ss; ss << "Run: No locations to produce forecasts for are defined for run '" << mRunName << "'. Either add an observation dataset to the run's 'inputs' option, " << "or use the 'locationTag' option to specify which dataset to use locations from."; Global::logger->write(ss.str(), Logger::error); } std::vector<int> useLocations; if(mRunOptions.getValues("locations", useLocations)) { std::vector<Location> temp = mLocations; mLocations.clear(); for(int k = 0; k < (int) temp.size(); k++) { for(int i = 0; i < (int) useLocations.size(); i++) { if(temp[k].getId() == useLocations[i]) { mLocations.push_back(temp[k]); } } } if(mLocations.size() == 0) { std::stringstream ss; ss << "No valid locations selected by 'locations' run option"; Global::logger->write(ss.str(), Logger::error); } } ///////////// // Offsets // ///////////// if(mRunOptions.getValues("offsets", mOffsets)) { std::stringstream ss; ss << "Using offsets from run specifications"; Global::logger->write(ss.str(), Logger::critical); } else { Input* input; std::string offsetSetTag; if(mRunOptions.getValue("offsetTag", offsetSetTag)) { input = mInputContainer->getInput(offsetSetTag); } else { // Default to main forecast set, because ... input = mDefaultData->getInput(); } std::stringstream ss; ss << "Using offsets from dataset " << input->getName(); Global::logger->write(ss.str(), Logger::status); mOffsets = input->getOffsets(); } } Run::~Run() { delete mInputContainer; delete mDefaultData; for(int i = 0; i < mConfigDatas.size(); i++) { delete mConfigDatas[i]; } } Options Run::loadRunOptions(std::string iTag) const { int dotPosition = -1; for(int i = 0; i < iTag.size(); i++) { if(iTag[i] == '.') dotPosition = i; } std::string filename; std::string tag; if(dotPosition == -1) { std::stringstream ss; ss << Namelist::getDefaultLocation() << "default/runs.nl"; filename = ss.str(); tag = iTag; } else { assert(dotPosition != 0); std::string folder = iTag.substr(0,dotPosition); tag = iTag.substr(dotPosition+1);//, iTag.size()-2); std::stringstream ss; ss << Namelist::getDefaultLocation() << folder << "/runs" << ".nl"; filename = ss.str(); } Namelist nlRuns(filename); std::string optString = nlRuns.findLine(tag); if(optString == "") { std::stringstream ss; ss << "Run " << iTag << " does not exist"; Global::logger->write(ss.str(), Logger::error); } return Options(optString); } void Run::loadVarConfs(const Options& iRunOptions, std::map<std::string, std::vector<std::string> >& iVarConfs, std::map<std::string, std::vector<std::string> >& iMetrics, std::vector<std::string>& iVariables) const { // Variable-configurations std::vector<std::string> varConfs; std::set<std::string> variables; iRunOptions.getValues("varconfs", varConfs); if(varConfs.size() == 0) { Global::logger->write("No variable/configurations specified for this run", Logger::error); } for(int v = 0; v < (int) varConfs.size(); v++) { std::string currVarConf = varConfs[v]; // Read from file int dotPosition = -1; for(int i = 0; i < currVarConf.size(); i++) { if(currVarConf[i] == '.') dotPosition = i; } std::string folder; std::string tag; if(dotPosition == -1) { folder = "default"; tag = currVarConf; } else { assert(dotPosition != 0); folder = currVarConf.substr(0,dotPosition); tag = currVarConf.substr(dotPosition+1);//, iTag.size()-2); } Namelist nlVarConfs("varconfs", folder); std::string line = nlVarConfs.findLine(tag); if(line == "") { std::stringstream ss; ss << "Variable/Configuration '" << tag << "' does not exist"; Global::logger->write(ss.str(), Logger::error); } Options opt(line); // Variable std::string variable; opt.getRequiredValue("variable", variable); variables.insert(variable); // Configuration std::vector<std::string> configurations; opt.getRequiredValues("configurations", configurations); for(int i = 0; i < configurations.size(); i++) iVarConfs[variable].push_back(configurations[i]); // Set up metrics std::vector<std::string> metricTags; opt.getValues("metrics", metricTags); for(int i = 0; i < metricTags.size(); i++) iMetrics[variable].push_back(metricTags[i]); } iVariables = std::vector<std::string>(variables.begin(), variables.end()); } void Run::getRunOptions(Options& iOptions) const { iOptions = mRunOptions; } std::vector<Output*> Run::getOutputs() const { return mOutputs; } Data* Run::getData() const { return mDefaultData; } std::vector<Location> Run::getLocations() const { return mLocations; } std::vector<float> Run::getOffsets() const { return mOffsets; } std::vector<std::string> Run::getVariables() const { return mVariables; } std::vector<Configuration*> Run::getConfigurations(const std::string& iVariable) const { std::vector<Configuration*> configurations; std::map<std::string, std::vector<Configuration*> >::const_iterator it = mVarConfs.find(iVariable); if(it == mVarConfs.end()) { std::stringstream ss; ss << "Run: No configuration specified for variable " << iVariable; Global::logger->write(ss.str(), Logger::debug); } else { configurations = it->second; } return configurations; } std::vector<Configuration*> Run::getConfigurations() const { std::vector<Configuration*> configurations; std::map<std::string, std::vector<Configuration*> >::const_iterator it; for(it = mVarConfs.begin(); it != mVarConfs.end(); it++) { for(int i = 0; i < it->second.size(); i++) { configurations.push_back(it->second[i]); } } return configurations; } std::vector<Metric*> Run::getMetrics(const std::string& iVariable) const { std::vector<Metric*> metrics; std::map<std::string, std::vector<Metric*> >::const_iterator it = mMetrics.find(iVariable); if(it == mMetrics.end()) { std::stringstream ss; ss << "Run: No metrics specified for variable " << iVariable; Global::logger->write(ss.str(), Logger::debug); } else { metrics = it->second; } return metrics; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: atom.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2006-06-19 14:08:09 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <unotools/atom.hxx> using namespace utl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::util; #define NMSP_UTIL ::com::sun::star::util AtomProvider::AtomProvider() { m_nAtoms = 1; } AtomProvider::~AtomProvider() { } int AtomProvider::getAtom( const ::rtl::OUString& rString, sal_Bool bCreate ) { ::std::hash_map< ::rtl::OUString, int, ::rtl::OUStringHash >::iterator it = m_aAtomMap.find( rString ); if( it != m_aAtomMap.end() ) return it->second; if( ! bCreate ) return INVALID_ATOM; m_aAtomMap[ rString ] = m_nAtoms; m_aStringMap[ m_nAtoms ] = rString; m_nAtoms++; return m_nAtoms-1; } void AtomProvider::getAll( ::std::list< ::utl::AtomDescription >& atoms ) { atoms.clear(); ::std::hash_map< ::rtl::OUString, int, ::rtl::OUStringHash >::const_iterator it = m_aAtomMap.begin(); ::utl::AtomDescription aDesc; while( it != m_aAtomMap.end() ) { aDesc.atom = it->second; aDesc.description = it->first; atoms.push_back( aDesc ); ++it; } } void AtomProvider::getRecent( int atom, ::std::list< ::utl::AtomDescription >& atoms ) { atoms.clear(); ::std::hash_map< ::rtl::OUString, int, ::rtl::OUStringHash >::const_iterator it = m_aAtomMap.begin(); ::utl::AtomDescription aDesc; while( it != m_aAtomMap.end() ) { if( it->second > atom ) { aDesc.atom = it->second; aDesc.description = it->first; atoms.push_back( aDesc ); } ++it; } } const ::rtl::OUString& AtomProvider::getString( int nAtom ) const { static ::rtl::OUString aEmpty; ::std::hash_map< int, ::rtl::OUString, ::std::hash< int > >::const_iterator it = m_aStringMap.find( nAtom ); return it == m_aStringMap.end() ? aEmpty : it->second; } void AtomProvider::overrideAtom( int atom, const ::rtl::OUString& description ) { m_aAtomMap[ description ] = atom; m_aStringMap[ atom ] = description; if( m_nAtoms <= atom ) m_nAtoms=atom+1; } sal_Bool AtomProvider::hasAtom( int atom ) const { return m_aStringMap.find( atom ) != m_aStringMap.end() ? sal_True : sal_False; } // ----------------------------------------------------------------------- MultiAtomProvider::MultiAtomProvider() { } MultiAtomProvider::~MultiAtomProvider() { for( ::std::hash_map< int, AtomProvider*, ::std::hash< int > >::iterator it = m_aAtomLists.begin(); it != m_aAtomLists.end(); ++it ) delete it->second; } sal_Bool MultiAtomProvider::insertAtomClass( int atomClass ) { ::std::hash_map< int, AtomProvider*, ::std::hash< int > >::iterator it = m_aAtomLists.find( atomClass ); if( it != m_aAtomLists.end() ) return sal_False; m_aAtomLists[ atomClass ] = new AtomProvider(); return sal_True; } int MultiAtomProvider::getAtom( int atomClass, const ::rtl::OUString& rString, sal_Bool bCreate ) { ::std::hash_map< int, AtomProvider*, ::std::hash< int > >::iterator it = m_aAtomLists.find( atomClass ); if( it != m_aAtomLists.end() ) return it->second->getAtom( rString, bCreate ); if( bCreate ) { AtomProvider* pNewClass; m_aAtomLists[ atomClass ] = pNewClass = new AtomProvider(); return pNewClass->getAtom( rString, bCreate ); } return INVALID_ATOM; } int MultiAtomProvider::getLastAtom( int atomClass ) const { ::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass ); return it != m_aAtomLists.end() ? it->second->getLastAtom() : INVALID_ATOM; } void MultiAtomProvider::getRecent( int atomClass, int atom, ::std::list< ::utl::AtomDescription >& atoms ) { ::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass ); if( it != m_aAtomLists.end() ) it->second->getRecent( atom, atoms ); else atoms.clear(); } const ::rtl::OUString& MultiAtomProvider::getString( int atomClass, int atom ) const { ::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass ); if( it != m_aAtomLists.end() ) return it->second->getString( atom ); static ::rtl::OUString aEmpty; return aEmpty; } sal_Bool MultiAtomProvider::hasAtom( int atomClass, int atom ) const { ::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass ); return it != m_aAtomLists.end() ? it->second->hasAtom( atom ) : sal_False; } void MultiAtomProvider::getClass( int atomClass, ::std::list< ::utl::AtomDescription >& atoms) const { ::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass ); if( it != m_aAtomLists.end() ) it->second->getAll( atoms ); else atoms.clear(); } void MultiAtomProvider::overrideAtom( int atomClass, int atom, const ::rtl::OUString& description ) { ::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass ); if( it == m_aAtomLists.end() ) m_aAtomLists[ atomClass ] = new AtomProvider(); m_aAtomLists[ atomClass ]->overrideAtom( atom, description ); } // ----------------------------------------------------------------------- AtomServer::AtomServer() { } AtomServer::~AtomServer() { } sal_Int32 AtomServer::getAtom( sal_Int32 atomClass, const ::rtl::OUString& description, sal_Bool create ) throw() { ::osl::Guard< ::osl::Mutex > guard( m_aMutex ); return m_aProvider.getAtom( atomClass, description, create ); } Sequence< Sequence< NMSP_UTIL::AtomDescription > > AtomServer::getClasses( const Sequence< sal_Int32 >& atomClasses ) throw() { ::osl::Guard< ::osl::Mutex > guard( m_aMutex ); Sequence< Sequence< NMSP_UTIL::AtomDescription > > aRet( atomClasses.getLength() ); for( int i = 0; i < atomClasses.getLength(); i++ ) { aRet.getArray()[i] = getClass( atomClasses.getConstArray()[i] ); } return aRet; } Sequence< NMSP_UTIL::AtomDescription > AtomServer::getClass( sal_Int32 atomClass ) throw() { ::osl::Guard< ::osl::Mutex > guard( m_aMutex ); ::std::list< ::utl::AtomDescription > atoms; m_aProvider.getClass( atomClass, atoms ); Sequence< NMSP_UTIL::AtomDescription > aRet( atoms.size() ); for( int i = aRet.getLength()-1; i >= 0; i-- ) { aRet.getArray()[i].atom = atoms.back().atom; aRet.getArray()[i].description = atoms.back().description; atoms.pop_back(); } return aRet; } Sequence< NMSP_UTIL::AtomDescription > AtomServer::getRecentAtoms( sal_Int32 atomClass, sal_Int32 atom ) throw() { ::osl::Guard< ::osl::Mutex > guard( m_aMutex ); ::std::list< ::utl::AtomDescription > atoms; m_aProvider.getRecent( atomClass, atom, atoms ); Sequence< NMSP_UTIL::AtomDescription > aRet( atoms.size() ); for( int i = aRet.getLength()-1; i >= 0; i-- ) { aRet.getArray()[i].atom = atoms.back().atom; aRet.getArray()[i].description = atoms.back().description; atoms.pop_back(); } return aRet; } Sequence< ::rtl::OUString > AtomServer::getAtomDescriptions( const Sequence< AtomClassRequest >& atoms ) throw() { ::osl::Guard< ::osl::Mutex > guard( m_aMutex ); int nStrings = 0, i; for( i = 0; i < atoms.getLength(); i++ ) nStrings += atoms.getConstArray()[ i ].atoms.getLength(); Sequence< ::rtl::OUString > aRet( nStrings ); for( i = 0, nStrings = 0; i < atoms.getLength(); i++ ) { const AtomClassRequest& rRequest = atoms.getConstArray()[i]; for( int n = 0; n < rRequest.atoms.getLength(); n++ ) aRet.getArray()[ nStrings++ ] = m_aProvider.getString( rRequest.atomClass, rRequest.atoms.getConstArray()[ n ] ); } return aRet; } // ----------------------------------------------------------------------- AtomClient::AtomClient( const Reference< XAtomServer >& xServer ) : m_xServer( xServer ) { } AtomClient::~AtomClient() { } int AtomClient::getAtom( int atomClass, const ::rtl::OUString& description, sal_Bool bCreate ) { int nAtom = m_aProvider.getAtom( atomClass, description, sal_False ); if( nAtom == INVALID_ATOM && bCreate ) { try { nAtom = m_xServer->getAtom( atomClass, description, bCreate ); } catch( RuntimeException& ) { return INVALID_ATOM; } if( nAtom != INVALID_ATOM ) m_aProvider.overrideAtom( atomClass, nAtom, description ); } return nAtom; } const ::rtl::OUString& AtomClient::getString( int atomClass, int atom ) { static ::rtl::OUString aEmpty; if( ! m_aProvider.hasAtom( atomClass, atom ) ) { Sequence< NMSP_UTIL::AtomDescription > aSeq; try { aSeq = m_xServer->getRecentAtoms( atomClass, m_aProvider.getLastAtom( atomClass ) ); } catch( RuntimeException& ) { return aEmpty; } const NMSP_UTIL::AtomDescription* pDescriptions = aSeq.getConstArray(); for( int i = 0; i < aSeq.getLength(); i++ ) m_aProvider.overrideAtom( atomClass, pDescriptions[i].atom, pDescriptions[i].description ); if( ! m_aProvider.hasAtom( atomClass, atom ) ) { // holes may occur by the above procedure! Sequence< AtomClassRequest > aReq( 1 ); aReq.getArray()[0].atomClass = atomClass; aReq.getArray()[0].atoms.realloc( 1 ); aReq.getArray()[0].atoms.getArray()[0] = atom; Sequence< ::rtl::OUString > aRet; try { aRet = m_xServer->getAtomDescriptions( aReq ); } catch( RuntimeException& ) { return aEmpty; } if( aRet.getLength() == 1 ) m_aProvider.overrideAtom( atomClass, atom, aRet.getConstArray()[0] ); } } return m_aProvider.getString( atomClass, atom ); } void AtomClient::updateAtomClasses( const Sequence< sal_Int32 >& atomClasses ) { Sequence< Sequence< NMSP_UTIL::AtomDescription > > aUpdate; try { aUpdate = m_xServer->getClasses( atomClasses ); } catch( RuntimeException& ) { return; } for( int i = 0; i < atomClasses.getLength(); i++ ) { int nClass = atomClasses.getConstArray()[i]; const Sequence< NMSP_UTIL::AtomDescription >& rClass = aUpdate.getConstArray()[i]; const NMSP_UTIL::AtomDescription* pDesc = rClass.getConstArray(); for( int n = 0; n < rClass.getLength(); n++, pDesc++ ) m_aProvider.overrideAtom( nClass, pDesc->atom, pDesc->description ); } } <commit_msg>INTEGRATION: CWS pchfix02 (1.8.16); FILE MERGED 2006/09/01 17:56:23 kaib 1.8.16.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: atom.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: obo $ $Date: 2006-09-17 01:26:43 $ * * 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_unotools.hxx" #include <unotools/atom.hxx> using namespace utl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::util; #define NMSP_UTIL ::com::sun::star::util AtomProvider::AtomProvider() { m_nAtoms = 1; } AtomProvider::~AtomProvider() { } int AtomProvider::getAtom( const ::rtl::OUString& rString, sal_Bool bCreate ) { ::std::hash_map< ::rtl::OUString, int, ::rtl::OUStringHash >::iterator it = m_aAtomMap.find( rString ); if( it != m_aAtomMap.end() ) return it->second; if( ! bCreate ) return INVALID_ATOM; m_aAtomMap[ rString ] = m_nAtoms; m_aStringMap[ m_nAtoms ] = rString; m_nAtoms++; return m_nAtoms-1; } void AtomProvider::getAll( ::std::list< ::utl::AtomDescription >& atoms ) { atoms.clear(); ::std::hash_map< ::rtl::OUString, int, ::rtl::OUStringHash >::const_iterator it = m_aAtomMap.begin(); ::utl::AtomDescription aDesc; while( it != m_aAtomMap.end() ) { aDesc.atom = it->second; aDesc.description = it->first; atoms.push_back( aDesc ); ++it; } } void AtomProvider::getRecent( int atom, ::std::list< ::utl::AtomDescription >& atoms ) { atoms.clear(); ::std::hash_map< ::rtl::OUString, int, ::rtl::OUStringHash >::const_iterator it = m_aAtomMap.begin(); ::utl::AtomDescription aDesc; while( it != m_aAtomMap.end() ) { if( it->second > atom ) { aDesc.atom = it->second; aDesc.description = it->first; atoms.push_back( aDesc ); } ++it; } } const ::rtl::OUString& AtomProvider::getString( int nAtom ) const { static ::rtl::OUString aEmpty; ::std::hash_map< int, ::rtl::OUString, ::std::hash< int > >::const_iterator it = m_aStringMap.find( nAtom ); return it == m_aStringMap.end() ? aEmpty : it->second; } void AtomProvider::overrideAtom( int atom, const ::rtl::OUString& description ) { m_aAtomMap[ description ] = atom; m_aStringMap[ atom ] = description; if( m_nAtoms <= atom ) m_nAtoms=atom+1; } sal_Bool AtomProvider::hasAtom( int atom ) const { return m_aStringMap.find( atom ) != m_aStringMap.end() ? sal_True : sal_False; } // ----------------------------------------------------------------------- MultiAtomProvider::MultiAtomProvider() { } MultiAtomProvider::~MultiAtomProvider() { for( ::std::hash_map< int, AtomProvider*, ::std::hash< int > >::iterator it = m_aAtomLists.begin(); it != m_aAtomLists.end(); ++it ) delete it->second; } sal_Bool MultiAtomProvider::insertAtomClass( int atomClass ) { ::std::hash_map< int, AtomProvider*, ::std::hash< int > >::iterator it = m_aAtomLists.find( atomClass ); if( it != m_aAtomLists.end() ) return sal_False; m_aAtomLists[ atomClass ] = new AtomProvider(); return sal_True; } int MultiAtomProvider::getAtom( int atomClass, const ::rtl::OUString& rString, sal_Bool bCreate ) { ::std::hash_map< int, AtomProvider*, ::std::hash< int > >::iterator it = m_aAtomLists.find( atomClass ); if( it != m_aAtomLists.end() ) return it->second->getAtom( rString, bCreate ); if( bCreate ) { AtomProvider* pNewClass; m_aAtomLists[ atomClass ] = pNewClass = new AtomProvider(); return pNewClass->getAtom( rString, bCreate ); } return INVALID_ATOM; } int MultiAtomProvider::getLastAtom( int atomClass ) const { ::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass ); return it != m_aAtomLists.end() ? it->second->getLastAtom() : INVALID_ATOM; } void MultiAtomProvider::getRecent( int atomClass, int atom, ::std::list< ::utl::AtomDescription >& atoms ) { ::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass ); if( it != m_aAtomLists.end() ) it->second->getRecent( atom, atoms ); else atoms.clear(); } const ::rtl::OUString& MultiAtomProvider::getString( int atomClass, int atom ) const { ::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass ); if( it != m_aAtomLists.end() ) return it->second->getString( atom ); static ::rtl::OUString aEmpty; return aEmpty; } sal_Bool MultiAtomProvider::hasAtom( int atomClass, int atom ) const { ::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass ); return it != m_aAtomLists.end() ? it->second->hasAtom( atom ) : sal_False; } void MultiAtomProvider::getClass( int atomClass, ::std::list< ::utl::AtomDescription >& atoms) const { ::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass ); if( it != m_aAtomLists.end() ) it->second->getAll( atoms ); else atoms.clear(); } void MultiAtomProvider::overrideAtom( int atomClass, int atom, const ::rtl::OUString& description ) { ::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass ); if( it == m_aAtomLists.end() ) m_aAtomLists[ atomClass ] = new AtomProvider(); m_aAtomLists[ atomClass ]->overrideAtom( atom, description ); } // ----------------------------------------------------------------------- AtomServer::AtomServer() { } AtomServer::~AtomServer() { } sal_Int32 AtomServer::getAtom( sal_Int32 atomClass, const ::rtl::OUString& description, sal_Bool create ) throw() { ::osl::Guard< ::osl::Mutex > guard( m_aMutex ); return m_aProvider.getAtom( atomClass, description, create ); } Sequence< Sequence< NMSP_UTIL::AtomDescription > > AtomServer::getClasses( const Sequence< sal_Int32 >& atomClasses ) throw() { ::osl::Guard< ::osl::Mutex > guard( m_aMutex ); Sequence< Sequence< NMSP_UTIL::AtomDescription > > aRet( atomClasses.getLength() ); for( int i = 0; i < atomClasses.getLength(); i++ ) { aRet.getArray()[i] = getClass( atomClasses.getConstArray()[i] ); } return aRet; } Sequence< NMSP_UTIL::AtomDescription > AtomServer::getClass( sal_Int32 atomClass ) throw() { ::osl::Guard< ::osl::Mutex > guard( m_aMutex ); ::std::list< ::utl::AtomDescription > atoms; m_aProvider.getClass( atomClass, atoms ); Sequence< NMSP_UTIL::AtomDescription > aRet( atoms.size() ); for( int i = aRet.getLength()-1; i >= 0; i-- ) { aRet.getArray()[i].atom = atoms.back().atom; aRet.getArray()[i].description = atoms.back().description; atoms.pop_back(); } return aRet; } Sequence< NMSP_UTIL::AtomDescription > AtomServer::getRecentAtoms( sal_Int32 atomClass, sal_Int32 atom ) throw() { ::osl::Guard< ::osl::Mutex > guard( m_aMutex ); ::std::list< ::utl::AtomDescription > atoms; m_aProvider.getRecent( atomClass, atom, atoms ); Sequence< NMSP_UTIL::AtomDescription > aRet( atoms.size() ); for( int i = aRet.getLength()-1; i >= 0; i-- ) { aRet.getArray()[i].atom = atoms.back().atom; aRet.getArray()[i].description = atoms.back().description; atoms.pop_back(); } return aRet; } Sequence< ::rtl::OUString > AtomServer::getAtomDescriptions( const Sequence< AtomClassRequest >& atoms ) throw() { ::osl::Guard< ::osl::Mutex > guard( m_aMutex ); int nStrings = 0, i; for( i = 0; i < atoms.getLength(); i++ ) nStrings += atoms.getConstArray()[ i ].atoms.getLength(); Sequence< ::rtl::OUString > aRet( nStrings ); for( i = 0, nStrings = 0; i < atoms.getLength(); i++ ) { const AtomClassRequest& rRequest = atoms.getConstArray()[i]; for( int n = 0; n < rRequest.atoms.getLength(); n++ ) aRet.getArray()[ nStrings++ ] = m_aProvider.getString( rRequest.atomClass, rRequest.atoms.getConstArray()[ n ] ); } return aRet; } // ----------------------------------------------------------------------- AtomClient::AtomClient( const Reference< XAtomServer >& xServer ) : m_xServer( xServer ) { } AtomClient::~AtomClient() { } int AtomClient::getAtom( int atomClass, const ::rtl::OUString& description, sal_Bool bCreate ) { int nAtom = m_aProvider.getAtom( atomClass, description, sal_False ); if( nAtom == INVALID_ATOM && bCreate ) { try { nAtom = m_xServer->getAtom( atomClass, description, bCreate ); } catch( RuntimeException& ) { return INVALID_ATOM; } if( nAtom != INVALID_ATOM ) m_aProvider.overrideAtom( atomClass, nAtom, description ); } return nAtom; } const ::rtl::OUString& AtomClient::getString( int atomClass, int atom ) { static ::rtl::OUString aEmpty; if( ! m_aProvider.hasAtom( atomClass, atom ) ) { Sequence< NMSP_UTIL::AtomDescription > aSeq; try { aSeq = m_xServer->getRecentAtoms( atomClass, m_aProvider.getLastAtom( atomClass ) ); } catch( RuntimeException& ) { return aEmpty; } const NMSP_UTIL::AtomDescription* pDescriptions = aSeq.getConstArray(); for( int i = 0; i < aSeq.getLength(); i++ ) m_aProvider.overrideAtom( atomClass, pDescriptions[i].atom, pDescriptions[i].description ); if( ! m_aProvider.hasAtom( atomClass, atom ) ) { // holes may occur by the above procedure! Sequence< AtomClassRequest > aReq( 1 ); aReq.getArray()[0].atomClass = atomClass; aReq.getArray()[0].atoms.realloc( 1 ); aReq.getArray()[0].atoms.getArray()[0] = atom; Sequence< ::rtl::OUString > aRet; try { aRet = m_xServer->getAtomDescriptions( aReq ); } catch( RuntimeException& ) { return aEmpty; } if( aRet.getLength() == 1 ) m_aProvider.overrideAtom( atomClass, atom, aRet.getConstArray()[0] ); } } return m_aProvider.getString( atomClass, atom ); } void AtomClient::updateAtomClasses( const Sequence< sal_Int32 >& atomClasses ) { Sequence< Sequence< NMSP_UTIL::AtomDescription > > aUpdate; try { aUpdate = m_xServer->getClasses( atomClasses ); } catch( RuntimeException& ) { return; } for( int i = 0; i < atomClasses.getLength(); i++ ) { int nClass = atomClasses.getConstArray()[i]; const Sequence< NMSP_UTIL::AtomDescription >& rClass = aUpdate.getConstArray()[i]; const NMSP_UTIL::AtomDescription* pDesc = rClass.getConstArray(); for( int n = 0; n < rClass.getLength(); n++, pDesc++ ) m_aProvider.overrideAtom( nClass, pDesc->atom, pDesc->description ); } } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkTestingMacros.h> #include <mitkTestFixture.h> #include "mitkIOUtil.h" #include <cmath> #include <mitkGIFFirstOrderNumericStatistics.h> class mitkGIFFirstOrderNumericStatisticsTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkGIFFirstOrderNumericStatisticsTestSuite); MITK_TEST(ImageDescription_PhantomTest); CPPUNIT_TEST_SUITE_END(); private: mitk::Image::Pointer m_IBSI_Phantom_Image_Small; mitk::Image::Pointer m_IBSI_Phantom_Image_Large; mitk::Image::Pointer m_IBSI_Phantom_Mask_Small; mitk::Image::Pointer m_IBSI_Phantom_Mask_Large; public: void setUp(void) override { m_IBSI_Phantom_Image_Small = mitk::IOUtil::Load<mitk::Image>(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Small.nrrd")); m_IBSI_Phantom_Image_Large = mitk::IOUtil::Load<mitk::Image>(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Large.nrrd")); m_IBSI_Phantom_Mask_Small = mitk::IOUtil::Load<mitk::Image>(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Small.nrrd")); m_IBSI_Phantom_Mask_Large = mitk::IOUtil::Load<mitk::Image>(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Large.nrrd")); } void ImageDescription_PhantomTest() { mitk::GIFFirstOrderNumericStatistics::Pointer featureCalculator = mitk::GIFFirstOrderNumericStatistics::New(); featureCalculator->SetUseBinsize(true); featureCalculator->SetBinsize(1.0); featureCalculator->SetUseMinimumIntensity(true); featureCalculator->SetUseMaximumIntensity(true); featureCalculator->SetMinimumIntensity(0.5); featureCalculator->SetMaximumIntensity(6.5); auto featureList = featureCalculator->CalculateFeatures(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large); std::map<std::string, double> results; for (auto valuePair : featureList) { MITK_INFO << valuePair.first << " : " << valuePair.second; results[valuePair.first] = valuePair.second; } CPPUNIT_ASSERT_EQUAL_MESSAGE("Image Diagnostics should calculate 46 features.", std::size_t(46), featureList.size()); // These values are obtained by a run of the filter. // The might be wrong! CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Mean Value should be 2.15 with Large IBSI Phantom Image", 2.15, results["First Order Histogram::Mean Value"], 0.01); // These values are taken from the IBSI Initiative to ensure compatibility // The values are given with an accuracy of 0.01 CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Histogram::Mean Index should be 2.15 with Large IBSI Phantom Image", 2.15, results["First Order Histogram::Mean Index"], 0.01); } }; MITK_TEST_SUITE_REGISTRATION(mitkGIFFirstOrderNumericStatistics )<commit_msg>All relevant tested<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkTestingMacros.h> #include <mitkTestFixture.h> #include "mitkIOUtil.h" #include <cmath> #include <mitkGIFFirstOrderNumericStatistics.h> class mitkGIFFirstOrderNumericStatisticsTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkGIFFirstOrderNumericStatisticsTestSuite); MITK_TEST(ImageDescription_PhantomTest); CPPUNIT_TEST_SUITE_END(); private: mitk::Image::Pointer m_IBSI_Phantom_Image_Small; mitk::Image::Pointer m_IBSI_Phantom_Image_Large; mitk::Image::Pointer m_IBSI_Phantom_Mask_Small; mitk::Image::Pointer m_IBSI_Phantom_Mask_Large; public: void setUp(void) override { m_IBSI_Phantom_Image_Small = mitk::IOUtil::Load<mitk::Image>(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Small.nrrd")); m_IBSI_Phantom_Image_Large = mitk::IOUtil::Load<mitk::Image>(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Large.nrrd")); m_IBSI_Phantom_Mask_Small = mitk::IOUtil::Load<mitk::Image>(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Small.nrrd")); m_IBSI_Phantom_Mask_Large = mitk::IOUtil::Load<mitk::Image>(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Large.nrrd")); } void ImageDescription_PhantomTest() { mitk::GIFFirstOrderNumericStatistics::Pointer featureCalculator = mitk::GIFFirstOrderNumericStatistics::New(); featureCalculator->SetUseBinsize(true); featureCalculator->SetBinsize(1.0); featureCalculator->SetUseMinimumIntensity(true); featureCalculator->SetUseMaximumIntensity(true); featureCalculator->SetMinimumIntensity(0.5); featureCalculator->SetMaximumIntensity(6.5); auto featureList = featureCalculator->CalculateFeatures(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large); std::map<std::string, double> results; for (auto valuePair : featureList) { MITK_INFO << valuePair.first << " : " << valuePair.second; results[valuePair.first] = valuePair.second; } CPPUNIT_ASSERT_EQUAL_MESSAGE("Image Diagnostics should calculate 50 features.", std::size_t(50), featureList.size()); // These values are obtained by a run of the filter. // The might be wrong! CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Mean with Large IBSI Phantom Image", 2.15, results["First Order Numeric::Mean"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Variance with Large IBSI Phantom Image", 3.05, results["First Order Numeric::Variance"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Skewness with Large IBSI Phantom Image", 1.08, results["First Order Numeric::Skewness"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Excess kurtosis with Large IBSI Phantom Image", -0.355, results["First Order Numeric::Excess kurtosis"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Median with Large IBSI Phantom Image", 1, results["First Order Numeric::Median"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Minimum with Large IBSI Phantom Image", 1, results["First Order Numeric::Minimum"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::10th Percentile with Large IBSI Phantom Image", 1, results["First Order Numeric::10th Percentile"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::90th Percentile with Large IBSI Phantom Image", 4, results["First Order Numeric::90th Percentile"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Maximum with Large IBSI Phantom Image", 6, results["First Order Numeric::Maximum"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Interquantile range with Large IBSI Phantom Image", 3, results["First Order Numeric::Interquantile range"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Range with Large IBSI Phantom Image", 5, results["First Order Numeric::Range"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Mean absolute deviation with Large IBSI Phantom Image", 1.55, results["First Order Numeric::Mean absolute deviation"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Robust mean absolute deviation with Large IBSI Phantom Image", 1.11, results["First Order Numeric::Robust mean absolute deviation"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Median absolute deviation with Large IBSI Phantom Image", 1.15, results["First Order Numeric::Median absolute deviation"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Coefficient of variation with Large IBSI Phantom Image", 0.812, results["First Order Numeric::Coefficient of variation"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Quantile coefficient of dispersion with Large IBSI Phantom Image", 0.6, results["First Order Numeric::Quantile coefficient of dispersion"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Energy with Large IBSI Phantom Image", 567, results["First Order Numeric::Energy"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Root mean square with Large IBSI Phantom Image", 2.77, results["First Order Numeric::Root mean square"], 0.01); // These values are taken from the IBSI Initiative to ensure compatibility // The values are given with an accuracy of 0.01 CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Standard Deviation with Large IBSI Phantom Image", 1.74513, results["First Order Numeric::Standard Deviation"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Kurtosis with Large IBSI Phantom Image", 2.64538, results["First Order Numeric::Kurtosis"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Robust mean with Large IBSI Phantom Image", 1.74627, results["First Order Numeric::Robust mean"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Robust variance with Large IBSI Phantom Image", 1.65204, results["First Order Numeric::Robust variance"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Covered image intensity range with Large IBSI Phantom Image", 1.2, results["First Order Numeric::Covered image intensity range"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Mode index with Large IBSI Phantom Image",0 , results["First Order Numeric::Mode index"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Mode value with Large IBSI Phantom Image", 1, results["First Order Numeric::Mode value"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Mode probability with Large IBSI Phantom Image", 0.675676, results["First Order Numeric::Mode probability"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Entropy with Large IBSI Phantom Image", -1.26561, results["First Order Numeric::Entropy"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Uniformtiy with Large IBSI Phantom Image", 0.512418, results["First Order Numeric::Uniformtiy"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Number of voxels with Large IBSI Phantom Image", 74 , results["First Order Numeric::Number of voxels"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Sum of voxels with Large IBSI Phantom Image", 159, results["First Order Numeric::Sum of voxels"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Voxel space with Large IBSI Phantom Image", 8, results["First Order Numeric::Voxel space"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Voxel volume with Large IBSI Phantom Image", 8, results["First Order Numeric::Voxel volume"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("First Order Numeric::Image Dimension with Large IBSI Phantom Image", 3, results["First Order Numeric::Image Dimension"], 0.01); } }; MITK_TEST_SUITE_REGISTRATION(mitkGIFFirstOrderNumericStatistics )<|endoftext|>
<commit_before>#ifdef ENABLE_LLVM #if RBX_LLVM_API_VER >= 302 #include <llvm/DataLayout.h> #else #include <llvm/Target/TargetData.h> #endif #include <llvm/Transforms/Scalar.h> #include "llvm/state.hpp" #include "llvm/jit_context.hpp" #include "llvm/jit_runtime.hpp" #include "llvm/jit_memory_manager.hpp" #include "llvm/passes.hpp" #include "machine_code.hpp" using namespace llvm; namespace autogen_types { void makeLLVMModuleContents(llvm::Module* module); } namespace rubinius { Context::Context(LLVMState* ls) : ls_(ls) , root_info_(0) , inlined_block_(false) , inline_depth_(0) , rds_(new jit::RuntimeDataHolder) , function_(0) , vm_(0) , out_args_(0) , counter_(0) { VoidTy = Type::getVoidTy(ctx_); Int1Ty = Type::getInt1Ty(ctx_); Int8Ty = Type::getInt8Ty(ctx_); Int16Ty = Type::getInt16Ty(ctx_); Int32Ty = Type::getInt32Ty(ctx_); Int64Ty = Type::getInt64Ty(ctx_); #ifdef IS_X8664 IntPtrTy = Int64Ty; #else IntPtrTy = Int32Ty; #endif VoidPtrTy = llvm::PointerType::getUnqual(Int8Ty); FloatTy = Type::getFloatTy(ctx_); DoubleTy = Type::getDoubleTy(ctx_); Int8PtrTy = llvm::PointerType::getUnqual(Int8Ty); Zero = llvm::ConstantInt::get(Int32Ty, 0); One = llvm::ConstantInt::get(Int32Ty, 1); module_ = new llvm::Module("rubinius", ctx_); autogen_types::makeLLVMModuleContents(module_); llvm::EngineBuilder factory(module_); factory.setAllocateGVsWithCode(false); memory_ = new jit::RubiniusRequestJITMemoryManager(ls->memory()); factory.setJITMemoryManager(memory_); #if RBX_LLVM_API_VER > 300 llvm::TargetOptions opts; opts.NoFramePointerElim = true; opts.NoFramePointerElimNonLeaf = true; factory.setTargetOptions(opts); #endif engine_ = factory.create(); builder_ = new llvm::PassManagerBuilder(); builder_->OptLevel = 2; passes_ = new llvm::FunctionPassManager(module_); #if RBX_LLVM_API_VER >= 302 module_->setDataLayout(engine_->getDataLayout()->getStringRepresentation()); passes_->add(new llvm::DataLayout(*engine_->getDataLayout())); #else module_->setDataLayout(engine_->getTargetData()->getStringRepresentation()); passes_->add(new llvm::TargetData(*engine_->getTargetData())); #endif builder_->populateFunctionPassManager(*passes_); // Eliminate unnecessary alloca. passes_->add(createPromoteMemoryToRegisterPass()); // Do simple "peephole" optimizations and bit-twiddling optzns. passes_->add(createInstructionCombiningPass()); // Reassociate expressions. passes_->add(createReassociatePass()); // Eliminate Common SubExpressions. passes_->add(createGVNPass()); passes_->add(createDeadStoreEliminationPass()); passes_->add(createInstructionCombiningPass()); // Simplify the control flow graph (deleting unreachable blocks, etc). passes_->add(createCFGSimplificationPass()); passes_->add(create_rubinius_alias_analysis()); passes_->add(createGVNPass()); // passes_->add(createCFGSimplificationPass()); passes_->add(createDeadStoreEliminationPass()); // passes_->add(createVerifierPass()); passes_->add(createScalarReplAggregatesPass()); passes_->add(create_overflow_folding_pass()); passes_->add(create_guard_eliminator_pass()); passes_->add(createCFGSimplificationPass()); passes_->add(createInstructionCombiningPass()); passes_->add(createScalarReplAggregatesPass()); passes_->add(createDeadStoreEliminationPass()); passes_->add(createCFGSimplificationPass()); passes_->add(createInstructionCombiningPass()); passes_->doInitialization(); ObjTy = ptr_type("Object"); profiling_ = new GlobalVariable( *module_, Int1Ty, false, GlobalVariable::ExternalLinkage, 0, "profiling_flag"); metadata_id_ = ctx_.getMDKindID("rbx-classid"); } Context::~Context() { delete builder_; delete passes_; delete engine_; // Memory is cleaned up by the engine memory_ = NULL; } void* Context::native_function() { void* addr = memory_->generatedFunction(); memory_->resetGeneratedFunction(); engine_->freeMachineCodeForFunction(function_); // Nuke the Function from the module function_->replaceAllUsesWith(UndefValue::get(function_->getType())); function_->removeFromParent(); return addr; } llvm::Type* Context::ptr_type(std::string name) { std::string full_name = std::string("struct.rubinius::") + name; return llvm::PointerType::getUnqual( module_->getTypeByName(full_name)); } llvm::Type* Context::type(std::string name) { std::string full_name = std::string("struct.rubinius::") + name; return module_->getTypeByName(full_name); } void Context::init_variables(llvm::IRBuilder<>& b) { counter_ = b.CreateAlloca(Int32Ty, 0, "counter_alloca"); out_args_ = b.CreateAlloca(type("Arguments"), 0, "out_args"); } void Context::add_runtime_data(jit::RuntimeData* rd) { rds_->add_runtime_data(rd); } std::ostream& Context::inline_log(const char* header) { std::ostream& l = ls_->log(); for(int i = 0; i <= inline_depth_; i++) { l << "|"; } l << " " << header << ": "; return l; } void Context::info(const char* msg) { if(!ls_->config().jit_inline_debug) return; std::ostream& l = ls_->log(); for(int i = 0; i <= inline_depth_ - 1; i++) { l << "|"; } l << "+ " << msg << "\n"; } std::ostream& Context::info_log(const char* header) { std::ostream& l = ls_->log(); for(int i = 0; i <= inline_depth_ - 1; i++) { l << "|"; } l << "+ " << header << ": "; return l; } } #endif <commit_msg>Move include to pickup version numbers<commit_after>#ifdef ENABLE_LLVM #include "llvm/state.hpp" #include "llvm/jit_context.hpp" #include "llvm/jit_runtime.hpp" #include "llvm/jit_memory_manager.hpp" #include "llvm/passes.hpp" #include "machine_code.hpp" #if RBX_LLVM_API_VER >= 302 #include <llvm/DataLayout.h> #else #include <llvm/Target/TargetData.h> #endif #include <llvm/Transforms/Scalar.h> using namespace llvm; namespace autogen_types { void makeLLVMModuleContents(llvm::Module* module); } namespace rubinius { Context::Context(LLVMState* ls) : ls_(ls) , root_info_(0) , inlined_block_(false) , inline_depth_(0) , rds_(new jit::RuntimeDataHolder) , function_(0) , vm_(0) , out_args_(0) , counter_(0) { VoidTy = Type::getVoidTy(ctx_); Int1Ty = Type::getInt1Ty(ctx_); Int8Ty = Type::getInt8Ty(ctx_); Int16Ty = Type::getInt16Ty(ctx_); Int32Ty = Type::getInt32Ty(ctx_); Int64Ty = Type::getInt64Ty(ctx_); #ifdef IS_X8664 IntPtrTy = Int64Ty; #else IntPtrTy = Int32Ty; #endif VoidPtrTy = llvm::PointerType::getUnqual(Int8Ty); FloatTy = Type::getFloatTy(ctx_); DoubleTy = Type::getDoubleTy(ctx_); Int8PtrTy = llvm::PointerType::getUnqual(Int8Ty); Zero = llvm::ConstantInt::get(Int32Ty, 0); One = llvm::ConstantInt::get(Int32Ty, 1); module_ = new llvm::Module("rubinius", ctx_); autogen_types::makeLLVMModuleContents(module_); llvm::EngineBuilder factory(module_); factory.setAllocateGVsWithCode(false); memory_ = new jit::RubiniusRequestJITMemoryManager(ls->memory()); factory.setJITMemoryManager(memory_); #if RBX_LLVM_API_VER > 300 llvm::TargetOptions opts; opts.NoFramePointerElim = true; opts.NoFramePointerElimNonLeaf = true; factory.setTargetOptions(opts); #endif engine_ = factory.create(); builder_ = new llvm::PassManagerBuilder(); builder_->OptLevel = 2; passes_ = new llvm::FunctionPassManager(module_); #if RBX_LLVM_API_VER >= 302 module_->setDataLayout(engine_->getDataLayout()->getStringRepresentation()); passes_->add(new llvm::DataLayout(*engine_->getDataLayout())); #else module_->setDataLayout(engine_->getTargetData()->getStringRepresentation()); passes_->add(new llvm::TargetData(*engine_->getTargetData())); #endif builder_->populateFunctionPassManager(*passes_); // Eliminate unnecessary alloca. passes_->add(createPromoteMemoryToRegisterPass()); // Do simple "peephole" optimizations and bit-twiddling optzns. passes_->add(createInstructionCombiningPass()); // Reassociate expressions. passes_->add(createReassociatePass()); // Eliminate Common SubExpressions. passes_->add(createGVNPass()); passes_->add(createDeadStoreEliminationPass()); passes_->add(createInstructionCombiningPass()); // Simplify the control flow graph (deleting unreachable blocks, etc). passes_->add(createCFGSimplificationPass()); passes_->add(create_rubinius_alias_analysis()); passes_->add(createGVNPass()); // passes_->add(createCFGSimplificationPass()); passes_->add(createDeadStoreEliminationPass()); // passes_->add(createVerifierPass()); passes_->add(createScalarReplAggregatesPass()); passes_->add(create_overflow_folding_pass()); passes_->add(create_guard_eliminator_pass()); passes_->add(createCFGSimplificationPass()); passes_->add(createInstructionCombiningPass()); passes_->add(createScalarReplAggregatesPass()); passes_->add(createDeadStoreEliminationPass()); passes_->add(createCFGSimplificationPass()); passes_->add(createInstructionCombiningPass()); passes_->doInitialization(); ObjTy = ptr_type("Object"); profiling_ = new GlobalVariable( *module_, Int1Ty, false, GlobalVariable::ExternalLinkage, 0, "profiling_flag"); metadata_id_ = ctx_.getMDKindID("rbx-classid"); } Context::~Context() { delete builder_; delete passes_; delete engine_; // Memory is cleaned up by the engine memory_ = NULL; } void* Context::native_function() { void* addr = memory_->generatedFunction(); memory_->resetGeneratedFunction(); engine_->freeMachineCodeForFunction(function_); // Nuke the Function from the module function_->replaceAllUsesWith(UndefValue::get(function_->getType())); function_->removeFromParent(); return addr; } llvm::Type* Context::ptr_type(std::string name) { std::string full_name = std::string("struct.rubinius::") + name; return llvm::PointerType::getUnqual( module_->getTypeByName(full_name)); } llvm::Type* Context::type(std::string name) { std::string full_name = std::string("struct.rubinius::") + name; return module_->getTypeByName(full_name); } void Context::init_variables(llvm::IRBuilder<>& b) { counter_ = b.CreateAlloca(Int32Ty, 0, "counter_alloca"); out_args_ = b.CreateAlloca(type("Arguments"), 0, "out_args"); } void Context::add_runtime_data(jit::RuntimeData* rd) { rds_->add_runtime_data(rd); } std::ostream& Context::inline_log(const char* header) { std::ostream& l = ls_->log(); for(int i = 0; i <= inline_depth_; i++) { l << "|"; } l << " " << header << ": "; return l; } void Context::info(const char* msg) { if(!ls_->config().jit_inline_debug) return; std::ostream& l = ls_->log(); for(int i = 0; i <= inline_depth_ - 1; i++) { l << "|"; } l << "+ " << msg << "\n"; } std::ostream& Context::info_log(const char* header) { std::ostream& l = ls_->log(); for(int i = 0; i <= inline_depth_ - 1; i++) { l << "|"; } l << "+ " << header << ": "; return l; } } #endif <|endoftext|>
<commit_before>// Copyright (c) 2018 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "providertx.h" #include "specialtx.h" #include "deterministicmns.h" #include "hash.h" #include "clientversion.h" #include "streams.h" #include "messagesigner.h" #include "chainparams.h" #include "validation.h" #include "univalue.h" #include "core_io.h" #include "script/standard.h" #include "base58.h" template <typename ProTx> static bool CheckService(const uint256& proTxHash, const ProTx& proTx, const CBlockIndex* pindexPrev, CValidationState& state) { if (proTx.nProtocolVersion < MIN_PROTX_PROTO_VERSION || proTx.nProtocolVersion > MAX_PROTX_PROTO_VERSION) return state.DoS(10, false, REJECT_INVALID, "bad-protx-proto-version"); if (!proTx.addr.IsValid()) return state.DoS(10, false, REJECT_INVALID, "bad-protx-addr"); if (Params().NetworkIDString() != CBaseChainParams::REGTEST && !proTx.addr.IsRoutable()) return state.DoS(10, false, REJECT_INVALID, "bad-protx-addr"); if (!proTx.addr.IsIPv4()) return state.DoS(10, false, REJECT_INVALID, "bad-protx-addr"); if (pindexPrev) { auto mnList = deterministicMNManager->GetListForBlock(pindexPrev->GetBlockHash()); if (mnList.HasUniqueProperty(proTx.addr) && mnList.GetUniquePropertyMN(proTx.addr)->proTxHash != proTxHash) { return state.DoS(10, false, REJECT_DUPLICATE, "bad-protx-dup-addr"); } } return true; } template <typename ProTx> static bool CheckInputsHashAndSig(const CTransaction &tx, const ProTx& proTx, const CKeyID &keyID, CValidationState& state) { uint256 inputsHash = CalcTxInputsHash(tx); if (inputsHash != proTx.inputsHash) return state.DoS(100, false, REJECT_INVALID, "bad-protx-inputs-hash"); std::string strError; if (!CHashSigner::VerifyHash(::SerializeHash(proTx), keyID, proTx.vchSig, strError)) return state.DoS(100, false, REJECT_INVALID, "bad-protx-sig", false, strError); return true; } bool CheckProRegTx(const CTransaction& tx, const CBlockIndex* pindexPrev, CValidationState& state) { AssertLockHeld(cs_main); CProRegTx ptx; if (!GetTxPayload(tx, ptx)) return state.DoS(100, false, REJECT_INVALID, "bad-tx-payload"); if (ptx.nVersion > CProRegTx::CURRENT_VERSION) return state.DoS(100, false, REJECT_INVALID, "bad-protx-version"); if (ptx.nCollateralIndex >= tx.vout.size()) return state.DoS(10, false, REJECT_INVALID, "bad-protx-collateral-index"); if (tx.vout[ptx.nCollateralIndex].nValue != 1000 * COIN) return state.DoS(10, false, REJECT_INVALID, "bad-protx-collateral"); if (ptx.keyIDOwner.IsNull() || ptx.keyIDOperator.IsNull() || ptx.keyIDVoting.IsNull()) return state.DoS(10, false, REJECT_INVALID, "bad-protx-key-null"); // we may support P2SH later, but restrict it for now (while in transitioning phase from old MN list to deterministic list) if (!ptx.scriptPayout.IsPayToPublicKeyHash()) return state.DoS(10, false, REJECT_INVALID, "bad-protx-payee"); // This is a temporary restriction that will be lifted later // It is required while we are transitioning from the old MN list to the deterministic list if (tx.vout[ptx.nCollateralIndex].scriptPubKey != ptx.scriptPayout) return state.DoS(10, false, REJECT_INVALID, "bad-protx-payee-collateral"); // It's allowed to set addr/protocolVersion to 0, which will put the MN into PoSe-banned state and require a ProUpServTx to be issues later // If any of both is set, it must be valid however if ((ptx.addr != CService() || ptx.nProtocolVersion != 0) && !CheckService(tx.GetHash(), ptx, pindexPrev, state)) return false; if (ptx.nOperatorReward > 10000) return state.DoS(10, false, REJECT_INVALID, "bad-protx-operator-reward"); if (pindexPrev) { auto mnList = deterministicMNManager->GetListForBlock(pindexPrev->GetBlockHash()); if (mnList.HasUniqueProperty(ptx.keyIDOwner) || mnList.HasUniqueProperty(ptx.keyIDOperator)) { return state.DoS(10, false, REJECT_DUPLICATE, "bad-protx-dup-key"); } if (!deterministicMNManager->IsDeterministicMNsSporkActive(pindexPrev->nHeight)) { if (ptx.keyIDOwner != ptx.keyIDOperator || ptx.keyIDOwner != ptx.keyIDVoting) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-key-not-same"); } } } if (!CheckInputsHashAndSig(tx, ptx, ptx.keyIDOwner, state)) return false; return true; } std::string CProRegTx::ToString() const { CTxDestination dest; std::string payee = "unknown"; if (ExtractDestination(scriptPayout, dest)) { payee = CBitcoinAddress(dest).ToString(); } return strprintf("CProRegTx(nVersion=%d, nProtocolVersion=%d, nCollateralIndex=%d, addr=%s, nOperatorReward=%f, keyIDOwner=%s, keyIDOperator=%s, keyIDVoting=%s, scriptPayout=%s)", nVersion, nProtocolVersion, nCollateralIndex, addr.ToString(), (double)nOperatorReward / 100, keyIDOwner.ToString(), keyIDOperator.ToString(), keyIDVoting.ToString(), payee); } void CProRegTx::ToJson(UniValue& obj) const { obj.clear(); obj.setObject(); obj.push_back(Pair("version", nVersion)); obj.push_back(Pair("protocolVersion", nProtocolVersion)); obj.push_back(Pair("collateralIndex", (int)nCollateralIndex)); obj.push_back(Pair("service", addr.ToString(false))); obj.push_back(Pair("keyIDOwner", keyIDOwner.ToString())); obj.push_back(Pair("keyIDOperator", keyIDOperator.ToString())); obj.push_back(Pair("keyIDVoting", keyIDVoting.ToString())); CTxDestination dest; if (ExtractDestination(scriptPayout, dest)) { CBitcoinAddress bitcoinAddress(dest); obj.push_back(Pair("payoutAddress", bitcoinAddress.ToString())); } obj.push_back(Pair("operatorReward", (double)nOperatorReward / 100)); obj.push_back(Pair("inputsHash", inputsHash.ToString())); } bool IsProTxCollateral(const CTransaction& tx, uint32_t n) { return GetProTxCollateralIndex(tx) == n; } uint32_t GetProTxCollateralIndex(const CTransaction& tx) { if (tx.nVersion < 3 || tx.nType != TRANSACTION_PROVIDER_REGISTER) return (uint32_t) - 1; CProRegTx proTx; if (!GetTxPayload(tx, proTx)) assert(false); return proTx.nCollateralIndex; } <commit_msg>Split keyIDMasternode into keyIDOwner/keyIDOperator/keyIDVoting (#2248)<commit_after>// Copyright (c) 2018 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "providertx.h" #include "specialtx.h" #include "deterministicmns.h" #include "hash.h" #include "clientversion.h" #include "streams.h" #include "messagesigner.h" #include "chainparams.h" #include "validation.h" #include "univalue.h" #include "core_io.h" #include "script/standard.h" #include "base58.h" template <typename ProTx> static bool CheckService(const uint256& proTxHash, const ProTx& proTx, const CBlockIndex* pindexPrev, CValidationState& state) { if (proTx.nProtocolVersion < MIN_PROTX_PROTO_VERSION || proTx.nProtocolVersion > MAX_PROTX_PROTO_VERSION) return state.DoS(10, false, REJECT_INVALID, "bad-protx-proto-version"); if (!proTx.addr.IsValid()) return state.DoS(10, false, REJECT_INVALID, "bad-protx-addr"); if (Params().NetworkIDString() != CBaseChainParams::REGTEST && !proTx.addr.IsRoutable()) return state.DoS(10, false, REJECT_INVALID, "bad-protx-addr"); if (!proTx.addr.IsIPv4()) return state.DoS(10, false, REJECT_INVALID, "bad-protx-addr"); if (pindexPrev) { auto mnList = deterministicMNManager->GetListForBlock(pindexPrev->GetBlockHash()); if (mnList.HasUniqueProperty(proTx.addr) && mnList.GetUniquePropertyMN(proTx.addr)->proTxHash != proTxHash) { return state.DoS(10, false, REJECT_DUPLICATE, "bad-protx-dup-addr"); } } return true; } template <typename ProTx> static bool CheckInputsHashAndSig(const CTransaction &tx, const ProTx& proTx, const CKeyID &keyID, CValidationState& state) { uint256 inputsHash = CalcTxInputsHash(tx); if (inputsHash != proTx.inputsHash) return state.DoS(100, false, REJECT_INVALID, "bad-protx-inputs-hash"); std::string strError; if (!CHashSigner::VerifyHash(::SerializeHash(proTx), keyID, proTx.vchSig, strError)) return state.DoS(100, false, REJECT_INVALID, "bad-protx-sig", false, strError); return true; } bool CheckProRegTx(const CTransaction& tx, const CBlockIndex* pindexPrev, CValidationState& state) { AssertLockHeld(cs_main); CProRegTx ptx; if (!GetTxPayload(tx, ptx)) return state.DoS(100, false, REJECT_INVALID, "bad-tx-payload"); if (ptx.nVersion > CProRegTx::CURRENT_VERSION) return state.DoS(100, false, REJECT_INVALID, "bad-protx-version"); if (ptx.nCollateralIndex >= tx.vout.size()) return state.DoS(10, false, REJECT_INVALID, "bad-protx-collateral-index"); if (tx.vout[ptx.nCollateralIndex].nValue != 1000 * COIN) return state.DoS(10, false, REJECT_INVALID, "bad-protx-collateral"); if (ptx.keyIDOwner.IsNull() || ptx.keyIDOperator.IsNull() || ptx.keyIDVoting.IsNull()) return state.DoS(10, false, REJECT_INVALID, "bad-protx-key-null"); // we may support P2SH later, but restrict it for now (while in transitioning phase from old MN list to deterministic list) if (!ptx.scriptPayout.IsPayToPublicKeyHash()) return state.DoS(10, false, REJECT_INVALID, "bad-protx-payee"); CTxDestination payoutDest; if (!ExtractDestination(ptx.scriptPayout, payoutDest)) { // should not happen as we checked script types before return state.DoS(10, false, REJECT_INVALID, "bad-protx-payee-dest"); } // don't allow reuse of collateral key for other keys (don't allow people to put the collateral key onto an online server) if (payoutDest == CTxDestination(ptx.keyIDOwner) || payoutDest == CTxDestination(ptx.keyIDOperator) || payoutDest == CTxDestination(ptx.keyIDVoting)) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-payee-reuse"); } // This is a temporary restriction that will be lifted later // It is required while we are transitioning from the old MN list to the deterministic list if (tx.vout[ptx.nCollateralIndex].scriptPubKey != ptx.scriptPayout) return state.DoS(10, false, REJECT_INVALID, "bad-protx-payee-collateral"); // It's allowed to set addr/protocolVersion to 0, which will put the MN into PoSe-banned state and require a ProUpServTx to be issues later // If any of both is set, it must be valid however if ((ptx.addr != CService() || ptx.nProtocolVersion != 0) && !CheckService(tx.GetHash(), ptx, pindexPrev, state)) return false; if (ptx.nOperatorReward > 10000) return state.DoS(10, false, REJECT_INVALID, "bad-protx-operator-reward"); if (pindexPrev) { auto mnList = deterministicMNManager->GetListForBlock(pindexPrev->GetBlockHash()); if (mnList.HasUniqueProperty(ptx.keyIDOwner) || mnList.HasUniqueProperty(ptx.keyIDOperator)) { return state.DoS(10, false, REJECT_DUPLICATE, "bad-protx-dup-key"); } if (!deterministicMNManager->IsDeterministicMNsSporkActive(pindexPrev->nHeight)) { if (ptx.keyIDOwner != ptx.keyIDOperator || ptx.keyIDOwner != ptx.keyIDVoting) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-key-not-same"); } } } if (!CheckInputsHashAndSig(tx, ptx, ptx.keyIDOwner, state)) return false; return true; } std::string CProRegTx::ToString() const { CTxDestination dest; std::string payee = "unknown"; if (ExtractDestination(scriptPayout, dest)) { payee = CBitcoinAddress(dest).ToString(); } return strprintf("CProRegTx(nVersion=%d, nProtocolVersion=%d, nCollateralIndex=%d, addr=%s, nOperatorReward=%f, keyIDOwner=%s, keyIDOperator=%s, keyIDVoting=%s, scriptPayout=%s)", nVersion, nProtocolVersion, nCollateralIndex, addr.ToString(), (double)nOperatorReward / 100, keyIDOwner.ToString(), keyIDOperator.ToString(), keyIDVoting.ToString(), payee); } void CProRegTx::ToJson(UniValue& obj) const { obj.clear(); obj.setObject(); obj.push_back(Pair("version", nVersion)); obj.push_back(Pair("protocolVersion", nProtocolVersion)); obj.push_back(Pair("collateralIndex", (int)nCollateralIndex)); obj.push_back(Pair("service", addr.ToString(false))); obj.push_back(Pair("keyIDOwner", keyIDOwner.ToString())); obj.push_back(Pair("keyIDOperator", keyIDOperator.ToString())); obj.push_back(Pair("keyIDVoting", keyIDVoting.ToString())); CTxDestination dest; if (ExtractDestination(scriptPayout, dest)) { CBitcoinAddress bitcoinAddress(dest); obj.push_back(Pair("payoutAddress", bitcoinAddress.ToString())); } obj.push_back(Pair("operatorReward", (double)nOperatorReward / 100)); obj.push_back(Pair("inputsHash", inputsHash.ToString())); } bool IsProTxCollateral(const CTransaction& tx, uint32_t n) { return GetProTxCollateralIndex(tx) == n; } uint32_t GetProTxCollateralIndex(const CTransaction& tx) { if (tx.nVersion < 3 || tx.nType != TRANSACTION_PROVIDER_REGISTER) return (uint32_t) - 1; CProRegTx proTx; if (!GetTxPayload(tx, proTx)) assert(false); return proTx.nCollateralIndex; } <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg 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 author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <cctype> #include <algorithm> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/optional.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/identify_client.hpp" #include "libtorrent/fingerprint.hpp" namespace { using namespace libtorrent; int decode_digit(char c) { if (std::isdigit(c)) return c - '0'; return unsigned(c) - 'A' + 10; } // takes a peer id and returns a valid boost::optional // object if the peer id matched the azureus style encoding // the returned fingerprint contains information about the // client's id boost::optional<fingerprint> parse_az_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0') || (id[3] < '0') || (id[4] < '0') || (id[5] < '0') || (id[6] < '0') || id[7] != '-') return boost::optional<fingerprint>(); ret.name[0] = id[1]; ret.name[1] = id[2]; ret.major_version = decode_digit(id[3]); ret.minor_version = decode_digit(id[4]); ret.revision_version = decode_digit(id[5]); ret.tag_version = decode_digit(id[6]); return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a shadow-style // identification boost::optional<fingerprint> parse_shadow_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (!std::isalnum(id[0])) return boost::optional<fingerprint>(); if (std::equal(id.begin()+4, id.begin()+6, "--")) { if ((id[1] < '0') || (id[2] < '0') || (id[3] < '0')) return boost::optional<fingerprint>(); ret.major_version = decode_digit(id[1]); ret.minor_version = decode_digit(id[2]); ret.revision_version = decode_digit(id[3]); } else { if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127) return boost::optional<fingerprint>(); ret.major_version = id[1]; ret.minor_version = id[2]; ret.revision_version = id[3]; } ret.name[0] = id[0]; ret.name[1] = 0; ret.tag_version = 0; return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a mainline-style // identification boost::optional<fingerprint> parse_mainline_style(const peer_id& id) { char ids[21]; std::copy(id.begin(), id.end(), ids); ids[20] = 0; fingerprint ret("..", 0, 0, 0, 0); ret.name[1] = 0; ret.tag_version = 0; if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version , &ret.revision_version) != 4 || !std::isprint(ret.name[0])) return boost::optional<fingerprint>(); return boost::optional<fingerprint>(ret); } typedef std::pair<char const*, char const*> map_entry; // only support BitTorrentSpecification // must be ordered alphabetically map_entry name_map[] = { map_entry("A", "ABC") , map_entry("A~", "Ares") , map_entry("AG", "Ares") , map_entry("AR", "Arctic Torrent") , map_entry("AV", "Avicora") , map_entry("AX", "BitPump") , map_entry("AZ", "Azureus") , map_entry("BB", "BitBuddy") , map_entry("BC", "BitComet") , map_entry("BF", "Bitflu") , map_entry("BG", "BTG") , map_entry("BR", "BitRocket") , map_entry("BS", "BTSlave") , map_entry("BX", "BittorrentX") , map_entry("CD", "Enhanced CTorrent") , map_entry("CT", "CTorrent") , map_entry("DE", "Deluge Torrent") , map_entry("ES", "electric sheep") , map_entry("EB", "EBit") , map_entry("HL", "Halite") , map_entry("HN", "Hydranode") , map_entry("KT", "KTorrent") , map_entry("LK", "Linkage") , map_entry("LP", "lphant") , map_entry("LT", "libtorrent") , map_entry("M", "Mainline") , map_entry("ML", "MLDonkey") , map_entry("MO", "Mono Torrent") , map_entry("MP", "MooPolice") , map_entry("MT", "Moonlight Torrent") , map_entry("O", "Osprey Permaseed") , map_entry("PD", "Pando") , map_entry("QT", "Qt 4") , map_entry("R", "Tribler") , map_entry("S", "Shadow") , map_entry("S~", "Shareaza (beta)") , map_entry("SB", "Swiftbit") , map_entry("SN", "ShareNet") , map_entry("SS", "SwarmScope") , map_entry("SZ", "Shareaza") , map_entry("T", "BitTornado") , map_entry("TN", "Torrent.NET") , map_entry("TR", "Transmission") , map_entry("TS", "TorrentStorm") , map_entry("TT", "TuoTu") , map_entry("U", "UPnP") , map_entry("UL", "uLeecher") , map_entry("UT", "MicroTorrent") , map_entry("XT", "XanTorrent") , map_entry("XX", "Xtorrent") , map_entry("ZT", "ZipTorrent") , map_entry("lt", "libTorrent (libtorrent.rakshasa.no/)") , map_entry("pX", "pHoeniX") , map_entry("qB", "qBittorrent") }; bool compare_first_string(map_entry const& lhs, map_entry const& rhs) { return lhs.first[0] < rhs.first[0] || ((lhs.first[0] == rhs.first[0]) && (lhs.first[1] < rhs.first[1])); } std::string lookup(fingerprint const& f) { std::stringstream identity; const int size = sizeof(name_map)/sizeof(name_map[0]); map_entry* i = std::lower_bound(name_map, name_map + size , map_entry(f.name, ""), &compare_first_string); #ifndef NDEBUG for (int i = 1; i < size; ++i) { assert(compare_first_string(name_map[i-1] , name_map[i])); } #endif if (i < name_map + size && std::equal(f.name, f.name + 2, i->first)) identity << i->second; else { identity << f.name[0]; if (f.name[1] != 0) identity << f.name[1]; } identity << " " << (int)f.major_version << "." << (int)f.minor_version << "." << (int)f.revision_version; if (f.name[1] != 0) identity << "." << (int)f.tag_version; return identity.str(); } bool find_string(unsigned char const* id, char const* search) { return std::equal(search, search + std::strlen(search), id); } } namespace libtorrent { boost::optional<fingerprint> client_fingerprint(peer_id const& p) { // look for azureus style id boost::optional<fingerprint> f; f = parse_az_style(p); if (f) return f; // look for shadow style id f = parse_shadow_style(p); if (f) return f; // look for mainline style id f = parse_mainline_style(p); if (f) return f; return f; } std::string identify_client(peer_id const& p) { peer_id::const_iterator PID = p.begin(); boost::optional<fingerprint> f; if (p.is_all_zeros()) return "Unknown"; // ---------------------- // non standard encodings // ---------------------- if (find_string(PID, "Deadman Walking-")) return "Deadman"; if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2"; if (find_string(PID, "DansClient")) return "XanTorrent"; if (find_string(PID + 4, "btfans")) return "SimpleBT"; if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II"; if (find_string(PID, "P87.P---")) return "Bittorrent Plus!"; if (find_string(PID, "S587Plus")) return "Bittorrent Plus!"; if (find_string(PID, "martini")) return "Martini Man"; if (find_string(PID, "Plus---")) return "Bittorrent Plus"; if (find_string(PID, "turbobt")) return "TurboBT"; if (find_string(PID, "a00---0")) return "Swarmy"; if (find_string(PID, "a02---0")) return "Swarmy"; if (find_string(PID, "T00---0")) return "Teeweety"; if (find_string(PID, "BTDWV-")) return "Deadman Walking"; if (find_string(PID + 2, "BS")) return "BitSpirit"; if (find_string(PID, "btuga")) return "BTugaXP"; if (find_string(PID, "oernu")) return "BTugaXP"; if (find_string(PID, "Mbrst")) return "Burst!"; if (find_string(PID, "Plus")) return "Plus!"; if (find_string(PID, "-Qt-")) return "Qt"; if (find_string(PID, "exbc")) return "BitComet"; if (find_string(PID, "-G3")) return "G3 Torrent"; if (find_string(PID, "XBT")) return "XBT"; if (find_string(PID, "OP")) return "Opera"; if (find_string(PID, "-BOW") && PID[7] == '-') return "Bits on Wheels " + std::string(PID + 4, PID + 7); if (find_string(PID, "eX")) { std::string user(PID + 2, PID + 14); return std::string("eXeem ('") + user.c_str() + "')"; } if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97")) return "Experimental 3.2.1b2"; if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0")) return "Experimental 3.1"; // look for azureus style id f = parse_az_style(p); if (f) return lookup(*f); // look for shadow style id f = parse_shadow_style(p); if (f) return lookup(*f); // look for mainline style id f = parse_mainline_style(p); if (f) return lookup(*f); if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0")) return "Generic"; std::string unknown("Unknown ["); for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i) { unknown += std::isprint(*i)?*i:'.'; } unknown += "]"; return unknown; } } <commit_msg>cleanup and added another known peer-id<commit_after>/* Copyright (c) 2003, Arvid Norberg 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 author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <cctype> #include <algorithm> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/optional.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/identify_client.hpp" #include "libtorrent/fingerprint.hpp" namespace { using namespace libtorrent; int decode_digit(char c) { if (std::isdigit(c)) return c - '0'; return unsigned(c) - 'A' + 10; } // takes a peer id and returns a valid boost::optional // object if the peer id matched the azureus style encoding // the returned fingerprint contains information about the // client's id boost::optional<fingerprint> parse_az_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0') || (id[3] < '0') || (id[4] < '0') || (id[5] < '0') || (id[6] < '0') || id[7] != '-') return boost::optional<fingerprint>(); ret.name[0] = id[1]; ret.name[1] = id[2]; ret.major_version = decode_digit(id[3]); ret.minor_version = decode_digit(id[4]); ret.revision_version = decode_digit(id[5]); ret.tag_version = decode_digit(id[6]); return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a shadow-style // identification boost::optional<fingerprint> parse_shadow_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (!std::isalnum(id[0])) return boost::optional<fingerprint>(); if (std::equal(id.begin()+4, id.begin()+6, "--")) { if ((id[1] < '0') || (id[2] < '0') || (id[3] < '0')) return boost::optional<fingerprint>(); ret.major_version = decode_digit(id[1]); ret.minor_version = decode_digit(id[2]); ret.revision_version = decode_digit(id[3]); } else { if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127) return boost::optional<fingerprint>(); ret.major_version = id[1]; ret.minor_version = id[2]; ret.revision_version = id[3]; } ret.name[0] = id[0]; ret.name[1] = 0; ret.tag_version = 0; return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a mainline-style // identification boost::optional<fingerprint> parse_mainline_style(const peer_id& id) { char ids[21]; std::copy(id.begin(), id.end(), ids); ids[20] = 0; fingerprint ret("..", 0, 0, 0, 0); ret.name[1] = 0; ret.tag_version = 0; if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version , &ret.revision_version) != 4 || !std::isprint(ret.name[0])) return boost::optional<fingerprint>(); return boost::optional<fingerprint>(ret); } struct map_entry { char const* id; char const* name; }; // only support BitTorrentSpecification // must be ordered alphabetically map_entry name_map[] = { {"A", "ABC"} , {"AG", "Ares"} , {"AR", "Arctic Torrent"} , {"AV", "Avicora"} , {"AX", "BitPump"} , {"AZ", "Azureus"} , {"A~", "Ares"} , {"BB", "BitBuddy"} , {"BC", "BitComet"} , {"BF", "Bitflu"} , {"BG", "BTG"} , {"BR", "BitRocket"} , {"BS", "BTSlave"} , {"BX", "BittorrentX"} , {"CD", "Enhanced CTorrent"} , {"CT", "CTorrent"} , {"DE", "Deluge Torrent"} , {"EB", "EBit"} , {"ES", "electric sheep"} , {"HL", "Halite"} , {"HN", "Hydranode"} , {"KT", "KTorrent"} , {"LK", "Linkage"} , {"LP", "lphant"} , {"LT", "libtorrent"} , {"M", "Mainline"} , {"ML", "MLDonkey"} , {"MO", "Mono Torrent"} , {"MP", "MooPolice"} , {"MT", "Moonlight Torrent"} , {"O", "Osprey Permaseed"} , {"PD", "Pando"} , {"Q", "BTQueue"} , {"QT", "Qt 4"} , {"R", "Tribler"} , {"S", "Shadow"} , {"SB", "Swiftbit"} , {"SN", "ShareNet"} , {"SS", "SwarmScope"} , {"SZ", "Shareaza"} , {"S~", "Shareaza (beta}"} , {"T", "BitTornado"} , {"TN", "Torrent.NET"} , {"TR", "Transmission"} , {"TS", "TorrentStorm"} , {"TT", "TuoTu"} , {"U", "UPnP"} , {"UL", "uLeecher"} , {"UT", "MicroTorrent"} , {"XT", "XanTorrent"} , {"XX", "Xtorrent"} , {"ZT", "ZipTorrent"} , {"lt", "libTorrent (libtorrent.rakshasa.no/}"} , {"pX", "pHoeniX"} , {"qB", "qBittorrent"} }; bool compare_id(map_entry const& lhs, map_entry const& rhs) { return lhs.id[0] < rhs.id[0] || ((lhs.id[0] == rhs.id[0]) && (lhs.id[1] < rhs.id[1])); } std::string lookup(fingerprint const& f) { std::stringstream identity; const int size = sizeof(name_map)/sizeof(name_map[0]); map_entry tmp = {f.name, ""}; map_entry* i = std::lower_bound(name_map, name_map + size , tmp, &compare_id); #ifndef NDEBUG for (int i = 1; i < size; ++i) { assert(compare_id(name_map[i-1] , name_map[i])); } #endif if (i < name_map + size && std::equal(f.name, f.name + 2, i->id)) identity << i->name; else { identity << f.name[0]; if (f.name[1] != 0) identity << f.name[1]; } identity << " " << (int)f.major_version << "." << (int)f.minor_version << "." << (int)f.revision_version; if (f.name[1] != 0) identity << "." << (int)f.tag_version; return identity.str(); } bool find_string(unsigned char const* id, char const* search) { return std::equal(search, search + std::strlen(search), id); } } namespace libtorrent { boost::optional<fingerprint> client_fingerprint(peer_id const& p) { // look for azureus style id boost::optional<fingerprint> f; f = parse_az_style(p); if (f) return f; // look for shadow style id f = parse_shadow_style(p); if (f) return f; // look for mainline style id f = parse_mainline_style(p); if (f) return f; return f; } std::string identify_client(peer_id const& p) { peer_id::const_iterator PID = p.begin(); boost::optional<fingerprint> f; if (p.is_all_zeros()) return "Unknown"; // ---------------------- // non standard encodings // ---------------------- if (find_string(PID, "Deadman Walking-")) return "Deadman"; if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2"; if (find_string(PID, "DansClient")) return "XanTorrent"; if (find_string(PID + 4, "btfans")) return "SimpleBT"; if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II"; if (find_string(PID, "P87.P---")) return "Bittorrent Plus!"; if (find_string(PID, "S587Plus")) return "Bittorrent Plus!"; if (find_string(PID, "martini")) return "Martini Man"; if (find_string(PID, "Plus---")) return "Bittorrent Plus"; if (find_string(PID, "turbobt")) return "TurboBT"; if (find_string(PID, "a00---0")) return "Swarmy"; if (find_string(PID, "a02---0")) return "Swarmy"; if (find_string(PID, "T00---0")) return "Teeweety"; if (find_string(PID, "BTDWV-")) return "Deadman Walking"; if (find_string(PID + 2, "BS")) return "BitSpirit"; if (find_string(PID, "btuga")) return "BTugaXP"; if (find_string(PID, "oernu")) return "BTugaXP"; if (find_string(PID, "Mbrst")) return "Burst!"; if (find_string(PID, "Plus")) return "Plus!"; if (find_string(PID, "-Qt-")) return "Qt"; if (find_string(PID, "exbc")) return "BitComet"; if (find_string(PID, "-G3")) return "G3 Torrent"; if (find_string(PID, "XBT")) return "XBT"; if (find_string(PID, "OP")) return "Opera"; if (find_string(PID, "-BOW") && PID[7] == '-') return "Bits on Wheels " + std::string(PID + 4, PID + 7); if (find_string(PID, "eX")) { std::string user(PID + 2, PID + 14); return std::string("eXeem ('") + user.c_str() + "')"; } if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97")) return "Experimental 3.2.1b2"; if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0")) return "Experimental 3.1"; // look for azureus style id f = parse_az_style(p); if (f) return lookup(*f); // look for shadow style id f = parse_shadow_style(p); if (f) return lookup(*f); // look for mainline style id f = parse_mainline_style(p); if (f) return lookup(*f); if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0")) return "Generic"; std::string unknown("Unknown ["); for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i) { unknown += std::isprint(*i)?*i:'.'; } unknown += "]"; return unknown; } } <|endoftext|>
<commit_before>/** * \file * \brief DynamicThreadBase class header * * \author Copyright (C) 2015-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_DYNAMICTHREADBASE_HPP_ #define INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_DYNAMICTHREADBASE_HPP_ #include "distortos/DynamicSignalsReceiver.hpp" #include "distortos/DynamicThreadParameters.hpp" #include "distortos/ThreadCommon.hpp" #include "distortos/internal/memory/storageDeleter.hpp" namespace distortos { #ifdef CONFIG_THREAD_DETACH_ENABLE class DynamicThread; #endif // def CONFIG_THREAD_DETACH_ENABLE namespace internal { /** * \brief DynamicThreadBase class is a type-erased interface for thread that has dynamic storage for bound function, * stack and internal DynamicSignalsReceiver object. * * If thread detachment is enabled (CONFIG_THREAD_DETACH_ENABLE is defined) then this class is dynamically allocated by * DynamicThread - which allows it to be "detached". Otherwise - if thread detachment is disabled * (CONFIG_THREAD_DETACH_ENABLE is not defined) - DynamicThread just inherits from this class. */ class DynamicThreadBase : public ThreadCommon { public: #ifdef CONFIG_THREAD_DETACH_ENABLE /** * \brief DynamicThreadBase's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] owner is a reference to owner DynamicThread object * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThreadBase(size_t stackSize, bool canReceiveSignals, size_t queuedSignals, size_t signalActions, uint8_t priority, SchedulingPolicy schedulingPolicy, DynamicThread& owner, Function&& function, Args&&... args); #else // !def CONFIG_THREAD_DETACH_ENABLE /** * \brief DynamicThreadBase's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThreadBase(size_t stackSize, bool canReceiveSignals, size_t queuedSignals, size_t signalActions, uint8_t priority, SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args); /** * \brief DynamicThreadBase's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] parameters is a DynamicThreadParameters struct with thread parameters * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThreadBase(const DynamicThreadParameters parameters, Function&& function, Args&&... args) : DynamicThreadBase{parameters.stackSize, parameters.canReceiveSignals, parameters.queuedSignals, parameters.signalActions, parameters.priority, parameters.schedulingPolicy, std::forward<Function>(function), std::forward<Args>(args)...} { } #endif // !def CONFIG_THREAD_DETACH_ENABLE #ifdef CONFIG_THREAD_DETACH_ENABLE /** * \brief Detaches the thread. * * Similar to std::thread::detach() - http://en.cppreference.com/w/cpp/thread/thread/detach * Similar to POSIX pthread_detach() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_detach.html * * Detaches the executing thread from the Thread object, allowing execution to continue independently. All resources * allocated for the thread will be deallocated when the thread terminates. * * \return 0 on success, error code otherwise: * - EINVAL - this thread is already detached; */ int detach() override; #endif // def CONFIG_THREAD_DETACH_ENABLE /** * \brief Starts the thread. * * This operation can be performed on threads in "New" state only. * * \return 0 on success, error code otherwise: * - error codes returned by ThreadCommon::startInternal(); */ int start() { #ifdef CONFIG_THREAD_DETACH_ENABLE return ThreadCommon::startInternal(run, preTerminationHook, terminationHook); #else // !def CONFIG_THREAD_DETACH_ENABLE return ThreadCommon::startInternal(run, nullptr, terminationHook); #endif // !def CONFIG_THREAD_DETACH_ENABLE } DynamicThreadBase(const DynamicThreadBase&) = delete; DynamicThreadBase(DynamicThreadBase&&) = default; const DynamicThreadBase& operator=(const DynamicThreadBase&) = delete; DynamicThreadBase& operator=(DynamicThreadBase&&) = delete; protected: #ifdef CONFIG_THREAD_DETACH_ENABLE /** * \brief Pre-termination hook function of thread * * If thread is detached, locks object used for deferred deletion. * * \param [in] thread is a reference to Thread object, this must be DynamicThreadBase! */ static void preTerminationHook(Thread& thread); /** * \brief Termination hook function of thread * * Calls ThreadCommon::terminationHook() and - if thread is detached - schedules itself for deferred deletion. * * \param [in] thread is a reference to Thread object, this must be DynamicThreadBase! */ static void terminationHook(Thread& thread); #endif // def CONFIG_THREAD_DETACH_ENABLE private: /** * \brief Thread's "run" function. * * Executes bound function object. * * \param [in] thread is a reference to Thread object, this must be DynamicThreadBase! */ static void run(Thread& thread); /// internal DynamicSignalsReceiver object DynamicSignalsReceiver dynamicSignalsReceiver_; /// bound function object std::function<void()> boundFunction_; #ifdef CONFIG_THREAD_DETACH_ENABLE /// pointer to owner DynamicThread object, nullptr if thread is detached DynamicThread* owner_; #endif // def CONFIG_THREAD_DETACH_ENABLE }; #ifdef CONFIG_THREAD_DETACH_ENABLE template<typename Function, typename... Args> DynamicThreadBase::DynamicThreadBase(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, DynamicThread& owner, Function&& function, Args&&... args) : ThreadCommon{{{new uint8_t[stackSize + stackGuardSize], storageDeleter<uint8_t>}, stackSize + stackGuardSize}, priority, schedulingPolicy, nullptr, canReceiveSignals == true ? &dynamicSignalsReceiver_ : nullptr}, dynamicSignalsReceiver_{canReceiveSignals == true ? queuedSignals : 0, canReceiveSignals == true ? signalActions : 0}, boundFunction_{std::bind(std::forward<Function>(function), std::forward<Args>(args)...)}, owner_{&owner} { } #else // !def CONFIG_THREAD_DETACH_ENABLE template<typename Function, typename... Args> DynamicThreadBase::DynamicThreadBase(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) : ThreadCommon{{{new uint8_t[stackSize + stackGuardSize], storageDeleter<uint8_t>}, stackSize + stackGuardSize}, priority, schedulingPolicy, nullptr, canReceiveSignals == true ? &dynamicSignalsReceiver_ : nullptr}, dynamicSignalsReceiver_{canReceiveSignals == true ? queuedSignals : 0, canReceiveSignals == true ? signalActions : 0}, boundFunction_{std::bind(std::forward<Function>(function), std::forward<Args>(args)...)} { } #endif // !def CONFIG_THREAD_DETACH_ENABLE } // namespace internal } // namespace distortos #endif // INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_DYNAMICTHREADBASE_HPP_ <commit_msg>Add static_assert() to check alignment of dynamically allocated memory<commit_after>/** * \file * \brief DynamicThreadBase class header * * \author Copyright (C) 2015-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_DYNAMICTHREADBASE_HPP_ #define INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_DYNAMICTHREADBASE_HPP_ #include "distortos/DynamicSignalsReceiver.hpp" #include "distortos/DynamicThreadParameters.hpp" #include "distortos/ThreadCommon.hpp" #include "distortos/internal/memory/storageDeleter.hpp" namespace distortos { #ifdef CONFIG_THREAD_DETACH_ENABLE class DynamicThread; #endif // def CONFIG_THREAD_DETACH_ENABLE namespace internal { /** * \brief DynamicThreadBase class is a type-erased interface for thread that has dynamic storage for bound function, * stack and internal DynamicSignalsReceiver object. * * If thread detachment is enabled (CONFIG_THREAD_DETACH_ENABLE is defined) then this class is dynamically allocated by * DynamicThread - which allows it to be "detached". Otherwise - if thread detachment is disabled * (CONFIG_THREAD_DETACH_ENABLE is not defined) - DynamicThread just inherits from this class. */ class DynamicThreadBase : public ThreadCommon { public: #ifdef CONFIG_THREAD_DETACH_ENABLE /** * \brief DynamicThreadBase's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] owner is a reference to owner DynamicThread object * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThreadBase(size_t stackSize, bool canReceiveSignals, size_t queuedSignals, size_t signalActions, uint8_t priority, SchedulingPolicy schedulingPolicy, DynamicThread& owner, Function&& function, Args&&... args); #else // !def CONFIG_THREAD_DETACH_ENABLE /** * \brief DynamicThreadBase's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThreadBase(size_t stackSize, bool canReceiveSignals, size_t queuedSignals, size_t signalActions, uint8_t priority, SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args); /** * \brief DynamicThreadBase's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] parameters is a DynamicThreadParameters struct with thread parameters * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThreadBase(const DynamicThreadParameters parameters, Function&& function, Args&&... args) : DynamicThreadBase{parameters.stackSize, parameters.canReceiveSignals, parameters.queuedSignals, parameters.signalActions, parameters.priority, parameters.schedulingPolicy, std::forward<Function>(function), std::forward<Args>(args)...} { } #endif // !def CONFIG_THREAD_DETACH_ENABLE #ifdef CONFIG_THREAD_DETACH_ENABLE /** * \brief Detaches the thread. * * Similar to std::thread::detach() - http://en.cppreference.com/w/cpp/thread/thread/detach * Similar to POSIX pthread_detach() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_detach.html * * Detaches the executing thread from the Thread object, allowing execution to continue independently. All resources * allocated for the thread will be deallocated when the thread terminates. * * \return 0 on success, error code otherwise: * - EINVAL - this thread is already detached; */ int detach() override; #endif // def CONFIG_THREAD_DETACH_ENABLE /** * \brief Starts the thread. * * This operation can be performed on threads in "New" state only. * * \return 0 on success, error code otherwise: * - error codes returned by ThreadCommon::startInternal(); */ int start() { #ifdef CONFIG_THREAD_DETACH_ENABLE return ThreadCommon::startInternal(run, preTerminationHook, terminationHook); #else // !def CONFIG_THREAD_DETACH_ENABLE return ThreadCommon::startInternal(run, nullptr, terminationHook); #endif // !def CONFIG_THREAD_DETACH_ENABLE } DynamicThreadBase(const DynamicThreadBase&) = delete; DynamicThreadBase(DynamicThreadBase&&) = default; const DynamicThreadBase& operator=(const DynamicThreadBase&) = delete; DynamicThreadBase& operator=(DynamicThreadBase&&) = delete; protected: #ifdef CONFIG_THREAD_DETACH_ENABLE /** * \brief Pre-termination hook function of thread * * If thread is detached, locks object used for deferred deletion. * * \param [in] thread is a reference to Thread object, this must be DynamicThreadBase! */ static void preTerminationHook(Thread& thread); /** * \brief Termination hook function of thread * * Calls ThreadCommon::terminationHook() and - if thread is detached - schedules itself for deferred deletion. * * \param [in] thread is a reference to Thread object, this must be DynamicThreadBase! */ static void terminationHook(Thread& thread); #endif // def CONFIG_THREAD_DETACH_ENABLE private: /** * \brief Thread's "run" function. * * Executes bound function object. * * \param [in] thread is a reference to Thread object, this must be DynamicThreadBase! */ static void run(Thread& thread); /// internal DynamicSignalsReceiver object DynamicSignalsReceiver dynamicSignalsReceiver_; /// bound function object std::function<void()> boundFunction_; #ifdef CONFIG_THREAD_DETACH_ENABLE /// pointer to owner DynamicThread object, nullptr if thread is detached DynamicThread* owner_; #endif // def CONFIG_THREAD_DETACH_ENABLE }; static_assert(alignof(max_align_t) >= CONFIG_ARCHITECTURE_STACK_ALIGNMENT, "Alignment of dynamically allocated memory is too low!"); #ifdef CONFIG_THREAD_DETACH_ENABLE template<typename Function, typename... Args> DynamicThreadBase::DynamicThreadBase(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, DynamicThread& owner, Function&& function, Args&&... args) : ThreadCommon{{{new uint8_t[stackSize + stackGuardSize], storageDeleter<uint8_t>}, stackSize + stackGuardSize}, priority, schedulingPolicy, nullptr, canReceiveSignals == true ? &dynamicSignalsReceiver_ : nullptr}, dynamicSignalsReceiver_{canReceiveSignals == true ? queuedSignals : 0, canReceiveSignals == true ? signalActions : 0}, boundFunction_{std::bind(std::forward<Function>(function), std::forward<Args>(args)...)}, owner_{&owner} { } #else // !def CONFIG_THREAD_DETACH_ENABLE template<typename Function, typename... Args> DynamicThreadBase::DynamicThreadBase(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) : ThreadCommon{{{new uint8_t[stackSize + stackGuardSize], storageDeleter<uint8_t>}, stackSize + stackGuardSize}, priority, schedulingPolicy, nullptr, canReceiveSignals == true ? &dynamicSignalsReceiver_ : nullptr}, dynamicSignalsReceiver_{canReceiveSignals == true ? queuedSignals : 0, canReceiveSignals == true ? signalActions : 0}, boundFunction_{std::bind(std::forward<Function>(function), std::forward<Args>(args)...)} { } #endif // !def CONFIG_THREAD_DETACH_ENABLE } // namespace internal } // namespace distortos #endif // INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_DYNAMICTHREADBASE_HPP_ <|endoftext|>
<commit_before>#include "aes.hpp" int aes::setKey(char *_key) { for(int i = 0; i < Nk; i++) { for(int j = 0; j < 4; j++) { key[i*4+(3-j)] = _key[i*4+j]; } } return expandKey(); } int aes::expandKey() { for(int i = 0; i < Nk; i++) { roundKey[i] = (key[4*i]) | (key[4*i+1] << 8) | (key[4*i+2] << 16) | (key[4*i+3] << 24); } for(int i = Nk; i < (Nb*(Nr+1)); i++) { uint32_t temp = roundKey[i-1]; if( i % Nk == 0 ) { printf("\n"); printf("\t %08x -> %08x -> %08x", temp, rotWord(temp, 1), subWord(rotWord(temp, 1))); temp = subWord(rotWord(temp, 1)) ^ (rcon[i/Nk] << 24); printf(" -> %08x\n", temp); } roundKey[i] = roundKey[i-Nk] ^ temp; } return 0; } uint8_t aes::rotByte(uint8_t input, int n) { return __rolb(input, n); } uint32_t aes::rotWord(uint32_t input, int n) { uint32_t output = (input << 8) | ((input >> 24) & 0xff); return output; } uint32_t aes::subWord(uint32_t input) { uint8_t byte; uint32_t output = 0; for(int i = 0; i < 4; i++) { byte = 0xff & ( input >> (i*8) ); output |= (s_fwd_aes[byte] << (i*8)); } return output; } std::string aes::printRoundKeys(void) { std::string output; for(int i = 0; i < (Nr+1); i++) { for(int j = 0; j < Nb; j++) { output.push_back(printf("%d : %08x ", i*Nb+j, roundKey[i*Nb + j])); } output.push_back(printf("\n")); } return output; } std::string aes::printKey(void) { std::string output; for(int i = 0; i < Nk*4; i++) { output.push_back(printf("%02x ", key[i])); } return output; } int aes::shiftRow(uint32_t *msg) { uint32_t tmp[4]; for(int i = 1; i < 4; i++) { for(int j = 0; j < i; j++) { tmp[j] = msg[4*i+j]; } for(int j = 0; j < 4-i; j++) { msg[4*i+j] = msg[4*i+j+i]; } for(int j = 4-i; j < 4; j++) { msg[4*i+j] = tmp[j-4+i]; } } return 0; } int aes::encryptBlock(uint32_t *msg) { for(int j = 0; j < Nb; j++) { msg[j] = (msg[j] ^ roundKey[j]); } for(int i = 1; i < Nr; i++) { for(int j = 0; j < Nb; j++) { msg[j] = subWord(msg[j]); } shiftRow(msg); mixCol(msg); for(int j = 0; j < Nb; j++) { msg[j] = msg[j] ^ roundKey[j]; } } return 0; } <commit_msg>shiftRow was wrong<commit_after>#include "aes.hpp" int aes::setKey(char *_key) { for(int i = 0; i < Nk; i++) { for(int j = 0; j < 4; j++) { key[i*4+(3-j)] = _key[i*4+j]; } } return expandKey(); } int aes::expandKey() { for(int i = 0; i < Nk; i++) { roundKey[i] = (key[4*i]) | (key[4*i+1] << 8) | (key[4*i+2] << 16) | (key[4*i+3] << 24); } for(int i = Nk; i < (Nb*(Nr+1)); i++) { uint32_t temp = roundKey[i-1]; if( i % Nk == 0 ) { printf("\n"); printf("\t %08x -> %08x -> %08x", temp, rotWord(temp, 1), subWord(rotWord(temp, 1))); temp = subWord(rotWord(temp, 1)) ^ (rcon[i/Nk] << 24); printf(" -> %08x\n", temp); } roundKey[i] = roundKey[i-Nk] ^ temp; } return 0; } uint8_t aes::rotByte(uint8_t input, int n) { return __rolb(input, n); } uint32_t aes::rotWord(uint32_t input, int n) { uint32_t output = (input << 8) | ((input >> 24) & 0xff); return output; } uint32_t aes::subWord(uint32_t input) { uint8_t byte; uint32_t output = 0; for(int i = 0; i < 4; i++) { byte = 0xff & ( input >> (i*8) ); output |= (s_fwd_aes[byte] << (i*8)); } return output; } std::string aes::printRoundKeys(void) { std::string output; for(int i = 0; i < (Nr+1); i++) { for(int j = 0; j < Nb; j++) { output.push_back(printf("%d : %08x ", i*Nb+j, roundKey[i*Nb + j])); } output.push_back(printf("\n")); } return output; } std::string aes::printKey(void) { std::string output; for(int i = 0; i < Nk*4; i++) { output.push_back(printf("%02x ", key[i])); } return output; } int aes::shiftRow(uint32_t *msg) { } int aes::encryptBlock(uint32_t *msg) { for(int j = 0; j < Nb; j++) { msg[j] = (msg[j] ^ roundKey[j]); } for(int i = 1; i < Nr; i++) { for(int j = 0; j < Nb; j++) { msg[j] = subWord(msg[j]); } shiftRow(msg); mixCol(msg); for(int j = 0; j < Nb; j++) { msg[j] = msg[j] ^ roundKey[j]; } } return 0; } <|endoftext|>
<commit_before>#include"all_defines.hpp" #include"aio.hpp" #include"heaps.hpp" #include"types.hpp" #include"objects.hpp" #include"processes.hpp" #include"workers.hpp" #include"bytecodes.hpp" #include"symbols.hpp" /*Generic code for AIO*/ /*This contains code that is shared across AIO implementations*/ /*internal function for sending a message to a process*/ /* preconditions: stack.top() = message to send postconditions: stack.top() has been popped */ static inline void send_message_to(Process* P, ProcessStack& stack) { /*prepare message*/ ValueHolderRef m; ValueHolder::copy_object(m, stack.top()); stack.pop(); bool is_waiting = 0; /*keep sending until we definitely go through any locks or whatnot*/ while(!P->receive_message(m, is_waiting)) /*do nothing*/; if(is_waiting) { workers->workqueue_push(P); } } ProcessInvoker::ProcessInvoker(Process* nP) : P(nP) { } ProcessInvoker::~ProcessInvoker() { } void ProcessInvoker::io_respond( Process& host, boost::shared_ptr<Event>& event, boost::shared_ptr<std::vector<unsigned char> >& dat) { Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ HlEvent* ev = hp.create<HlEvent>(); ev->p = event; stack.push(Object::to_ref<Generic*>(ev)); /*any data?*/ if(!dat || dat->size() == 0) { stack.push(Object::nil()); } else { BinObj* e = BinObj::create(hp, dat); stack.push(Object::to_ref<Generic*>(e)); } bytecode_cons(host, stack); send_message_to(P, stack); } void ProcessInvoker::nil_respond( Process& host, boost::shared_ptr<Event>& event) { Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ HlEvent* ev = hp.create<HlEvent>(); ev->p = event; stack.push(Object::to_ref<Generic*>(ev)); stack.push(Object::nil()); bytecode_cons(host, stack); send_message_to(P, stack); } void ProcessInvoker::accept_respond( Process& host, boost::shared_ptr<Event>& event, boost::shared_ptr<IOPort>& new_socket){ Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ HlEvent* ev = hp.create<HlEvent>(); ev->p = event; stack.push(Object::to_ref<Generic*>(ev)); HlIOPort* io = hp.create<HlIOPort>(); io->p = new_socket; stack.push(Object::to_ref<Generic*>(io)); bytecode_cons(host, stack); send_message_to(P, stack); } void ProcessInvoker::connect_respond( Process& host, boost::shared_ptr<Event>& event, boost::shared_ptr<IOPort>& new_socket) { Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ HlEvent* ev = hp.create<HlEvent>(); ev->p = event; stack.push(Object::to_ref<Generic*>(ev)); HlIOPort* io = hp.create<HlIOPort>(); io->p = new_socket; stack.push(Object::to_ref<Generic*>(io)); bytecode_cons(host, stack); send_message_to(P, stack); } void ProcessInvoker::sleep_respond( Process& host, boost::shared_ptr<Event>& event, size_t time) { Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ HlEvent* ev = hp.create<HlEvent>(); ev->p = event; stack.push(Object::to_ref<Generic*>(ev)); stack.push(Object::to_ref<int>(time)); bytecode_cons(host, stack); send_message_to(P, stack); } void ProcessInvoker::error_respond( Process& host, boost::shared_ptr<Event>& event, std::string const& msg) { Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ HlEvent* ev = hp.create<HlEvent>(); ev->p = event; stack.push(Object::to_ref<Generic*>(ev)); /*slow lookup is OK, we don't expect error handling to be fast. */ stack.push(Object::to_ref(symbols->lookup("<hl>i/o"))); /*assume ASCII string for now*/ for(size_t i = 0; i < msg.size(); ++i) { stack.push(Object::to_ref(UnicodeChar(msg[i]))); } HlString::stack_create(hp, stack, msg.size()); bytecode_tag(host, stack); bytecode_cons(host, stack); send_message_to(P, stack); } <commit_msg>src/aio.cpp: notes on problem with process-level GC and arbitrarily pushing a process onto the workqueue<commit_after>#include"all_defines.hpp" #include"aio.hpp" #include"heaps.hpp" #include"types.hpp" #include"objects.hpp" #include"processes.hpp" #include"workers.hpp" #include"bytecodes.hpp" #include"symbols.hpp" /*Generic code for AIO*/ /*This contains code that is shared across AIO implementations*/ /*internal function for sending a message to a process*/ /* preconditions: stack.top() = message to send postconditions: stack.top() has been popped */ static inline void send_message_to(Process* P, ProcessStack& stack) { /*prepare message*/ ValueHolderRef m; ValueHolder::copy_object(m, stack.top()); stack.pop(); bool is_waiting = 0; /*keep sending until we definitely go through any locks or whatnot*/ while(!P->receive_message(m, is_waiting)) /*do nothing*/; if(is_waiting) { /*TODO: must have a way of determining if we are in process-level GC. The process-level GC must first blacken the process before it can be safely pushed on the workqueue. */ workers->workqueue_push(P); } } ProcessInvoker::ProcessInvoker(Process* nP) : P(nP) { } ProcessInvoker::~ProcessInvoker() { } void ProcessInvoker::io_respond( Process& host, boost::shared_ptr<Event>& event, boost::shared_ptr<std::vector<unsigned char> >& dat) { Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ HlEvent* ev = hp.create<HlEvent>(); ev->p = event; stack.push(Object::to_ref<Generic*>(ev)); /*any data?*/ if(!dat || dat->size() == 0) { stack.push(Object::nil()); } else { BinObj* e = BinObj::create(hp, dat); stack.push(Object::to_ref<Generic*>(e)); } bytecode_cons(host, stack); send_message_to(P, stack); } void ProcessInvoker::nil_respond( Process& host, boost::shared_ptr<Event>& event) { Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ HlEvent* ev = hp.create<HlEvent>(); ev->p = event; stack.push(Object::to_ref<Generic*>(ev)); stack.push(Object::nil()); bytecode_cons(host, stack); send_message_to(P, stack); } void ProcessInvoker::accept_respond( Process& host, boost::shared_ptr<Event>& event, boost::shared_ptr<IOPort>& new_socket){ Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ HlEvent* ev = hp.create<HlEvent>(); ev->p = event; stack.push(Object::to_ref<Generic*>(ev)); HlIOPort* io = hp.create<HlIOPort>(); io->p = new_socket; stack.push(Object::to_ref<Generic*>(io)); bytecode_cons(host, stack); send_message_to(P, stack); } void ProcessInvoker::connect_respond( Process& host, boost::shared_ptr<Event>& event, boost::shared_ptr<IOPort>& new_socket) { Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ HlEvent* ev = hp.create<HlEvent>(); ev->p = event; stack.push(Object::to_ref<Generic*>(ev)); HlIOPort* io = hp.create<HlIOPort>(); io->p = new_socket; stack.push(Object::to_ref<Generic*>(io)); bytecode_cons(host, stack); send_message_to(P, stack); } void ProcessInvoker::sleep_respond( Process& host, boost::shared_ptr<Event>& event, size_t time) { Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ HlEvent* ev = hp.create<HlEvent>(); ev->p = event; stack.push(Object::to_ref<Generic*>(ev)); stack.push(Object::to_ref<int>(time)); bytecode_cons(host, stack); send_message_to(P, stack); } void ProcessInvoker::error_respond( Process& host, boost::shared_ptr<Event>& event, std::string const& msg) { Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ HlEvent* ev = hp.create<HlEvent>(); ev->p = event; stack.push(Object::to_ref<Generic*>(ev)); /*slow lookup is OK, we don't expect error handling to be fast. */ stack.push(Object::to_ref(symbols->lookup("<hl>i/o"))); /*assume ASCII string for now*/ for(size_t i = 0; i < msg.size(); ++i) { stack.push(Object::to_ref(UnicodeChar(msg[i]))); } HlString::stack_create(hp, stack, msg.size()); bytecode_tag(host, stack); bytecode_cons(host, stack); send_message_to(P, stack); } <|endoftext|>
<commit_before>#include"all_defines.hpp" #include"aio.hpp" #include"heaps.hpp" #include"types.hpp" #include"objects.hpp" #include"processes.hpp" #include"workers.hpp" #include"bytecodes.hpp" #include"symbols.hpp" /*Generic code for AIO*/ /*This contains code that is shared across AIO implementations*/ /*internal function for sending a message to a process*/ /* preconditions: stack.top() = message to send postconditions: stack.top() has been popped */ static inline void send_message_to(Process& host, Process* P, ProcessStack& stack) { /*prepare message*/ ValueHolderRef m; ValueHolder::copy_object(m, stack.top()); stack.pop(); bool is_waiting = 0; /*keep sending until we definitely go through any locks or whatnot*/ while(!P->receive_message(m, is_waiting)) /*do nothing*/; if(is_waiting) { /*Use multipush on the hosting process to push the processes on the workqueue when the hosting process' timeslice expires. */ host.add_to_multipush(P); } } ProcessInvoker::ProcessInvoker(Process* nP) : P(nP) { } ProcessInvoker::~ProcessInvoker() { } void ProcessInvoker::io_respond( Process& host, boost::shared_ptr<Event>& event, boost::shared_ptr<std::vector<unsigned char> >& dat) { Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ HlEvent* ev = hp.create<HlEvent>(); ev->p = event; stack.push(Object::to_ref<Generic*>(ev)); /*any data?*/ if(!dat || dat->size() == 0) { stack.push(Object::nil()); } else { BinObj* e = BinObj::create(hp, dat); stack.push(Object::to_ref<Generic*>(e)); } bytecode_cons(host, stack); send_message_to(host, P, stack); } void ProcessInvoker::nil_respond( Process& host, boost::shared_ptr<Event>& event) { Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ HlEvent* ev = hp.create<HlEvent>(); ev->p = event; stack.push(Object::to_ref<Generic*>(ev)); stack.push(Object::nil()); bytecode_cons(host, stack); send_message_to(host, P, stack); } void ProcessInvoker::accept_respond( Process& host, boost::shared_ptr<Event>& event, boost::shared_ptr<IOPort>& new_socket) { Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ HlEvent* ev = hp.create<HlEvent>(); ev->p = event; stack.push(Object::to_ref<Generic*>(ev)); HlIOPort* io = hp.create<HlIOPort>(); io->p = new_socket; stack.push(Object::to_ref<Generic*>(io)); bytecode_cons(host, stack); send_message_to(host, P, stack); } void ProcessInvoker::connect_respond( Process& host, boost::shared_ptr<Event>& event, boost::shared_ptr<IOPort>& new_socket) { Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ HlEvent* ev = hp.create<HlEvent>(); ev->p = event; stack.push(Object::to_ref<Generic*>(ev)); HlIOPort* io = hp.create<HlIOPort>(); io->p = new_socket; stack.push(Object::to_ref<Generic*>(io)); bytecode_cons(host, stack); send_message_to(host, P, stack); } void ProcessInvoker::sleep_respond( Process& host, boost::shared_ptr<Event>& event, size_t time) { Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ HlEvent* ev = hp.create<HlEvent>(); ev->p = event; stack.push(Object::to_ref<Generic*>(ev)); stack.push(Object::to_ref<int>(time)); bytecode_cons(host, stack); send_message_to(host, P, stack); } void ProcessInvoker::error_respond( Process& host, boost::shared_ptr<Event>& event, std::string const& msg) { Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ HlEvent* ev = hp.create<HlEvent>(); ev->p = event; stack.push(Object::to_ref<Generic*>(ev)); /*slow lookup is OK, we don't expect error handling to be fast. */ stack.push(Object::to_ref(symbols->lookup("<hl>i/o"))); /*assume ASCII string for now*/ for(size_t i = 0; i < msg.size(); ++i) { stack.push(Object::to_ref(UnicodeChar(msg[i]))); } HlString::stack_create(hp, stack, msg.size()); bytecode_tag(host, stack); bytecode_cons(host, stack); send_message_to(host, P, stack); } <commit_msg>src/aio.cpp: Changed to properly create the HlEvent by also binding the process to send to<commit_after>#include"all_defines.hpp" #include"aio.hpp" #include"heaps.hpp" #include"types.hpp" #include"objects.hpp" #include"processes.hpp" #include"workers.hpp" #include"bytecodes.hpp" #include"symbols.hpp" /*Generic code for AIO*/ /*This contains code that is shared across AIO implementations*/ /*internal function for sending a message to a process*/ /* preconditions: stack.top() = message to send postconditions: stack.top() has been popped */ static inline void send_message_to(Process& host, Process* P, ProcessStack& stack) { /*prepare message*/ ValueHolderRef m; ValueHolder::copy_object(m, stack.top()); stack.pop(); bool is_waiting = 0; /*keep sending until we definitely go through any locks or whatnot*/ while(!P->receive_message(m, is_waiting)) /*do nothing*/; if(is_waiting) { /*Use multipush on the hosting process to push the processes on the workqueue when the hosting process' timeslice expires. */ host.add_to_multipush(P); } } ProcessInvoker::ProcessInvoker(Process* nP) : P(nP) { } ProcessInvoker::~ProcessInvoker() { } static inline void recreate_event_push( Heap& hp, ProcessStack& stack, boost::shared_ptr<Event>& event, Process* P) { { HlPid *pid = hp.create<HlPid>(); pid->process = P; stack.push(Object::to_ref<Generic*>(pid)); } HlEvent* ev = hp.create<HlEvent>(); ev->p = event; ev->hl_pid = stack.top(); stack.pop(); stack.push(Object::to_ref<Generic*>(ev)); } void ProcessInvoker::io_respond( Process& host, boost::shared_ptr<Event>& event, boost::shared_ptr<std::vector<unsigned char> >& dat) { Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ recreate_event_push(hp, stack, event, P); /*any data?*/ if(!dat || dat->size() == 0) { stack.push(Object::nil()); } else { BinObj* e = BinObj::create(hp, dat); stack.push(Object::to_ref<Generic*>(e)); } bytecode_cons(host, stack); send_message_to(host, P, stack); } void ProcessInvoker::nil_respond( Process& host, boost::shared_ptr<Event>& event) { Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ recreate_event_push(hp, stack, event, P); stack.push(Object::nil()); bytecode_cons(host, stack); send_message_to(host, P, stack); } void ProcessInvoker::accept_respond( Process& host, boost::shared_ptr<Event>& event, boost::shared_ptr<IOPort>& new_socket) { Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ recreate_event_push(hp, stack, event, P); HlIOPort* io = hp.create<HlIOPort>(); io->p = new_socket; stack.push(Object::to_ref<Generic*>(io)); bytecode_cons(host, stack); send_message_to(host, P, stack); } void ProcessInvoker::connect_respond( Process& host, boost::shared_ptr<Event>& event, boost::shared_ptr<IOPort>& new_socket) { Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ recreate_event_push(hp, stack, event, P); HlIOPort* io = hp.create<HlIOPort>(); io->p = new_socket; stack.push(Object::to_ref<Generic*>(io)); bytecode_cons(host, stack); send_message_to(host, P, stack); } void ProcessInvoker::sleep_respond( Process& host, boost::shared_ptr<Event>& event, size_t time) { Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ recreate_event_push(hp, stack, event, P); stack.push(Object::to_ref<int>(time)); bytecode_cons(host, stack); send_message_to(host, P, stack); } void ProcessInvoker::error_respond( Process& host, boost::shared_ptr<Event>& event, std::string const& msg) { Heap& hp = host; ProcessStack& stack = host.stack; /*build objects*/ recreate_event_push(hp, stack, event, P); /*slow lookup is OK, we don't expect error handling to be fast. */ stack.push(Object::to_ref(symbols->lookup("<hl>i/o"))); /*assume ASCII string for now*/ for(size_t i = 0; i < msg.size(); ++i) { stack.push(Object::to_ref(UnicodeChar(msg[i]))); } HlString::stack_create(hp, stack, msg.size()); bytecode_tag(host, stack); bytecode_cons(host, stack); send_message_to(host, P, stack); } <|endoftext|>
<commit_before>#include "ant.hpp" extern int debug; Ant::Ant(Graph *graph, double alpha, double beta, double gamma, unsigned max_solution_length) : graph(graph) , alpha(alpha) , beta(beta) , gamma(gamma) , max_solution_length(max_solution_length) , solution(NULL) , generator() {} void Ant::traverse_graph() { bool term_condition = true; set_beginning_position(); while(term_condition) { term_condition = term_condition && move(); if (debug >= 5) { cout << *solution << endl; } } } void Ant::free_solution() { if (solution) { delete solution; solution = NULL; } } void Ant::set_beginning_position() { vector<Node*> nodes = graph->get_nodes(); vector<double> distribution; distribution.reserve(nodes.size()); for(unsigned i = 0; i < nodes.size(); ++i) { distribution.push_back(graph->rate_node_as_first(nodes[i])); } for (unsigned i = 1; i < nodes.size(); ++i) { distribution[i] += distribution[i - 1]; } int choice = generator.roulette(distribution); current_node = nodes[choice]; solution = new Solution(graph->get_size(), current_node); } bool Ant::move() { Edge *chosen_edge = choose_edge(); if (chosen_edge == NULL) return false; step(chosen_edge); return true; } void Ant::step(Edge *edge) { this->current_node = solution->add_edge(edge); } double Ant::heuristic_attrictiveness(Edge *choice) { unsigned no_visits = solution->get_no_visits(current_node); return max(0.0, 1 + choice->get_weight() - gamma * no_visits); } double Ant::probability_of_choice(Edge *choice) { return pow(choice->get_pheromones(), alpha) * pow(heuristic_attrictiveness(choice), beta); } bool Ant::can_choose_edge(Edge *edge) { return (solution->get_cummulated_length(edge) <= this->max_solution_length); } void Ant::filter_choices(vector<Edge *> &potential_choices) { unsigned i = this->current_node->get_index(); for (unsigned j = 0, len = graph->get_size(); j < len; ++j) { Edge *edge = graph->get_edge(i, j); if ((i != j) && can_choose_edge(edge)) { potential_choices.push_back(edge); } } } Edge* Ant::choose_edge() { vector<Edge *> potential_choices; filter_choices(potential_choices); unsigned size = potential_choices.size(); if (size == 0) return NULL; vector<double> distribution; distribution.reserve(size); for (unsigned i = 0; i < size; ++i) { distribution.push_back(probability_of_choice(potential_choices[i])); } if (debug >= 5) { cout << "distribution:\t"; for (unsigned i = 0, len = potential_choices.size(); i < len; ++i) { Edge *choice = potential_choices[i]; cout << choice->get_n2()->get_index() << " => (" << distribution[i] << ", "; cout << "ph: " << choice->get_pheromones() << ", "; cout << "h: " << heuristic_attrictiveness(choice) << ")\t"; } cout << endl; } for (unsigned i = 1; i < size; ++i) { distribution[i] += distribution[i - 1]; } int choice = generator.roulette(distribution); return potential_choices[choice]; } <commit_msg>Critical bug<commit_after>#include "ant.hpp" extern int debug; Ant::Ant(Graph *graph, double alpha, double beta, double gamma, unsigned max_solution_length) : graph(graph) , alpha(alpha) , beta(beta) , gamma(gamma) , max_solution_length(max_solution_length) , solution(NULL) , generator() {} void Ant::traverse_graph() { bool term_condition = true; set_beginning_position(); while(term_condition) { term_condition = term_condition && move(); if (debug >= 5) { cout << *solution << endl; } } } void Ant::free_solution() { if (solution) { delete solution; solution = NULL; } } void Ant::set_beginning_position() { vector<Node*> nodes = graph->get_nodes(); vector<double> distribution; distribution.reserve(nodes.size()); for(unsigned i = 0; i < nodes.size(); ++i) { distribution.push_back(graph->rate_node_as_first(nodes[i])); } for (unsigned i = 1; i < nodes.size(); ++i) { distribution[i] += distribution[i - 1]; } int choice = generator.roulette(distribution); current_node = nodes[choice]; solution = new Solution(graph->get_size(), current_node); } bool Ant::move() { Edge *chosen_edge = choose_edge(); if (chosen_edge == NULL) return false; step(chosen_edge); return true; } void Ant::step(Edge *edge) { this->current_node = solution->add_edge(edge); } double Ant::heuristic_attrictiveness(Edge *choice) { unsigned no_visits = solution->get_no_visits(choice->get_n2()); return max(0.0, 1 + choice->get_normalized_weight() - gamma * no_visits); } double Ant::probability_of_choice(Edge *choice) { return pow(choice->get_pheromones(), alpha) * pow(heuristic_attrictiveness(choice), beta); } bool Ant::can_choose_edge(Edge *edge) { return (solution->get_cummulated_length(edge) <= this->max_solution_length); } void Ant::filter_choices(vector<Edge *> &potential_choices) { unsigned i = this->current_node->get_index(); for (unsigned j = 0, len = graph->get_size(); j < len; ++j) { Edge *edge = graph->get_edge(i, j); if ((i != j) && can_choose_edge(edge)) { potential_choices.push_back(edge); } } } Edge* Ant::choose_edge() { vector<Edge *> potential_choices; filter_choices(potential_choices); unsigned size = potential_choices.size(); if (size == 0) return NULL; vector<double> distribution; distribution.reserve(size); for (unsigned i = 0; i < size; ++i) { distribution.push_back(probability_of_choice(potential_choices[i])); } if (debug >= 5) { cout << "distribution:\t"; for (unsigned i = 0, len = potential_choices.size(); i < len; ++i) { Edge *choice = potential_choices[i]; cout << choice->get_n2()->get_index() << " => (" << distribution[i] << ", "; cout << "ph: " << choice->get_pheromones() << ", "; cout << "h: " << heuristic_attrictiveness(choice) << ")\t"; } cout << endl; } for (unsigned i = 1; i < size; ++i) { distribution[i] += distribution[i - 1]; } int choice = generator.roulette(distribution); return potential_choices[choice]; } <|endoftext|>
<commit_before>#include "app.h" #include <memory> #include <utility> #include <cmath> #include "platform.h" #include "view/view.h" #include "GLES2/gl2.h" #include "EGL/egl.h" #include "EGL/eglext.h" std::shared_ptr<View> m_view; void initialize() { logMsg("%s\n", "initialize"); // Create view m_view = std::make_shared<View>(); // // // Set up openGL state glDisable(GL_BLEND); glDisable(GL_STENCIL_TEST); glEnable(GL_DEPTH_TEST); glClearDepthf(1.0); glDepthRangef(0.0, 1.0); glDepthMask(GL_TRUE); glDepthFunc(GL_LEQUAL); glEnable(GL_CULL_FACE); glFrontFace(GL_CCW); glCullFace(GL_BACK); glClearColor(0.3f, 0.3f, 0.3f, 1.0f); logMsg("%s\n", "finish initialize"); } void resize(int _newWidth, int _newHeight) { logMsg("%s\n", "resize"); glViewport(0, 0, _newWidth, _newHeight); if (m_view) { m_view->setAspect(_newWidth, _newHeight); } } void update(float _dt) { } void render() { // Set up openGL for new frame glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glm::dmat4 view = m_view->getViewMatrix(); glm::dmat4 viewProj = m_view->getViewProjectionMatrix(); // // // TODO: This error checking is incomplete and only marginally useful // 1. We need to continue calling glGetError until no error states remain // 2. Repeating an error message 60 times per second is not useful, try to consolidate GLenum glError = glGetError(); if (glError) { logMsg("GL Error %d!!!\n", glError); } } void teardown() { // TODO: Release resources! }<commit_msg>view issue<commit_after>#include "app.h" #include "GLES2/gl2.h" #include "EGL/egl.h" #include "EGL/eglext.h" #include <memory> #include <utility> #include <cmath> #include "platform.h" #include "view/view.h" std::shared_ptr<View> m_view; void initialize() { logMsg("%s\n", "initialize"); // Create view m_view = std::make_shared<View>(); // // // Set up openGL state glDisable(GL_BLEND); glDisable(GL_STENCIL_TEST); glEnable(GL_DEPTH_TEST); glClearDepthf(1.0); glDepthRangef(0.0, 1.0); glDepthMask(GL_TRUE); glDepthFunc(GL_LEQUAL); glEnable(GL_CULL_FACE); glFrontFace(GL_CCW); glCullFace(GL_BACK); glClearColor(0.3f, 0.3f, 0.3f, 1.0f); logMsg("%s\n", "finish initialize"); } void resize(int _newWidth, int _newHeight) { logMsg("%s\n", "resize"); glViewport(0, 0, _newWidth, _newHeight); if (m_view) { m_view->setAspect(_newWidth, _newHeight); } } void update(float _dt) { } void render() { // Set up openGL for new frame glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // glm::dmat4 view = m_view->getViewMatrix(); // glm::dmat4 viewProj = m_view->getViewProjectionMatrix(); // // // TODO: This error checking is incomplete and only marginally useful // 1. We need to continue calling glGetError until no error states remain // 2. Repeating an error message 60 times per second is not useful, try to consolidate GLenum glError = glGetError(); if (glError) { logMsg("GL Error %d!!!\n", glError); } } void teardown() { // TODO: Release resources! }<|endoftext|>
<commit_before>/* * Copyright (c) 2000-2005 The Regents of The University of Michigan * 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 copyright holders 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. * * Authors: Steve Raasch * Nathan Binkert * Steve Reinhardt */ /// /// @file sim/main.cc /// #include <Python.h> // must be before system headers... see Python docs #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <libgen.h> #include <stdlib.h> #include <signal.h> #include <getopt.h> #include <list> #include <string> #include <vector> #include "base/callback.hh" #include "base/inifile.hh" #include "base/misc.hh" #include "base/output.hh" #include "base/pollevent.hh" #include "base/statistics.hh" #include "base/str.hh" #include "base/time.hh" #include "cpu/base.hh" #include "cpu/smt.hh" #include "mem/mem_object.hh" #include "mem/port.hh" #include "sim/async.hh" #include "sim/builder.hh" #include "sim/host.hh" #include "sim/serialize.hh" #include "sim/sim_events.hh" #include "sim/sim_exit.hh" #include "sim/sim_object.hh" #include "sim/stat_control.hh" #include "sim/stats.hh" #include "sim/root.hh" using namespace std; // See async.h. volatile bool async_event = false; volatile bool async_dump = false; volatile bool async_dumpreset = false; volatile bool async_exit = false; volatile bool async_io = false; volatile bool async_alarm = false; /// Stats signal handler. void dumpStatsHandler(int sigtype) { async_event = true; async_dump = true; } void dumprstStatsHandler(int sigtype) { async_event = true; async_dumpreset = true; } /// Exit signal handler. void exitNowHandler(int sigtype) { async_event = true; async_exit = true; } /// Abort signal handler. void abortHandler(int sigtype) { cerr << "Program aborted at cycle " << curTick << endl; #if TRACING_ON // dump trace buffer, if there is one Trace::theLog.dump(cerr); #endif } extern "C" { void init_cc_main(); } int main(int argc, char **argv) { signal(SIGFPE, SIG_IGN); // may occur on misspeculated paths signal(SIGTRAP, SIG_IGN); signal(SIGUSR1, dumpStatsHandler); // dump intermediate stats signal(SIGUSR2, dumprstStatsHandler); // dump and reset stats signal(SIGINT, exitNowHandler); // dump final stats and exit signal(SIGABRT, abortHandler); Py_SetProgramName(argv[0]); // default path to m5 python code is the currently executing // file... Python ZipImporter will find embedded zip archive. // The M5_ARCHIVE environment variable can be used to override this. char *m5_archive = getenv("M5_ARCHIVE"); string pythonpath = m5_archive ? m5_archive : argv[0]; char *oldpath = getenv("PYTHONPATH"); if (oldpath != NULL) { pythonpath += ":"; pythonpath += oldpath; } if (setenv("PYTHONPATH", pythonpath.c_str(), true) == -1) fatal("setenv: %s\n", strerror(errno)); // initialize embedded Python interpreter Py_Initialize(); PySys_SetArgv(argc, argv); // initialize SWIG 'cc_main' module init_cc_main(); PyRun_SimpleString("import m5"); PyRun_SimpleString("m5.main()"); // clean up Python intepreter. Py_Finalize(); } void setOutputDir(const string &dir) { simout.setDirectory(dir); } IniFile inifile; SimObject * createSimObject(const string &name) { return SimObjectClass::createObject(inifile, name); } /** * Pointer to the Python function that maps names to SimObjects. */ PyObject *resolveFunc = NULL; /** * Convert a pointer to the Python object that SWIG wraps around a C++ * SimObject pointer back to the actual C++ pointer. See main.i. */ extern "C" SimObject *convertSwigSimObjectPtr(PyObject *); SimObject * resolveSimObject(const string &name) { PyObject *pyPtr = PyEval_CallFunction(resolveFunc, "(s)", name.c_str()); if (pyPtr == NULL) { PyErr_Print(); panic("resolveSimObject: failure on call to Python for %s", name); } SimObject *simObj = convertSwigSimObjectPtr(pyPtr); if (simObj == NULL) panic("resolveSimObject: failure on pointer conversion for %s", name); return simObj; } /** * Load config.ini into C++ database. Exported to Python via SWIG; * invoked from m5.instantiate(). */ void loadIniFile(PyObject *_resolveFunc) { resolveFunc = _resolveFunc; configStream = simout.find("config.out"); // The configuration database is now complete; start processing it. inifile.load("config.ini"); // Initialize statistics database Stats::InitSimStats(); } /** * Look up a MemObject port. Helper function for connectPorts(). */ Port * lookupPort(SimObject *so, const std::string &name, int i) { MemObject *mo = dynamic_cast<MemObject *>(so); if (mo == NULL) { warn("error casting SimObject %s to MemObject", so->name()); return NULL; } Port *p = mo->getPort(name, i); if (p == NULL) warn("error looking up port %s on object %s", name, so->name()); return p; } /** * Connect the described MemObject ports. Called from Python via SWIG. */ int connectPorts(SimObject *o1, const std::string &name1, int i1, SimObject *o2, const std::string &name2, int i2) { Port *p1 = lookupPort(o1, name1, i1); Port *p2 = lookupPort(o2, name2, i2); if (p1 == NULL || p2 == NULL) { warn("connectPorts: port lookup error"); return 0; } p1->setPeer(p2); p2->setPeer(p1); return 1; } /** * Do final initialization steps after object construction but before * start of simulation. */ void finalInit() { // Parse and check all non-config-hierarchy parameters. ParamContext::parseAllContexts(inifile); ParamContext::checkAllContexts(); // Echo all parameter settings to stats file as well. ParamContext::showAllContexts(*configStream); // Do a second pass to finish initializing the sim objects SimObject::initAll(); // Restore checkpointed state, if any. #if 0 configHierarchy.unserializeSimObjects(); #endif SimObject::regAllStats(); // Check to make sure that the stats package is properly initialized Stats::check(); // Reset to put the stats in a consistent state. Stats::reset(); SimStartup(); } /** Simulate for num_cycles additional cycles. If num_cycles is -1 * (the default), do not limit simulation; some other event must * terminate the loop. Exported to Python via SWIG. * @return The SimLoopExitEvent that caused the loop to exit. */ SimLoopExitEvent * simulate(Tick num_cycles = -1) { warn("Entering event queue @ %d. Starting simulation...\n", curTick); // Fix up num_cycles. Special default value -1 means simulate // "forever"... schedule event at MaxTick just to be safe. // Otherwise it's a delta for additional cycles to simulate past // curTick, and thus must be non-negative. if (num_cycles == -1) num_cycles = MaxTick; else if (num_cycles < 0) fatal("simulate: num_cycles must be >= 0 (was %d)\n", num_cycles); else num_cycles = curTick + num_cycles; Event *limit_event = new SimLoopExitEvent(num_cycles, "simulate() limit reached"); while (1) { // there should always be at least one event (the SimLoopExitEvent // we just scheduled) in the queue assert(!mainEventQueue.empty()); assert(curTick <= mainEventQueue.nextTick() && "event scheduled in the past"); // forward current cycle to the time of the first event on the // queue curTick = mainEventQueue.nextTick(); Event *exit_event = mainEventQueue.serviceOne(); if (exit_event != NULL) { // hit some kind of exit event; return to Python // event must be subclass of SimLoopExitEvent... SimLoopExitEvent *se_event = dynamic_cast<SimLoopExitEvent *>(exit_event); if (se_event == NULL) panic("Bogus exit event class!"); // if we didn't hit limit_event, delete it if (se_event != limit_event) { assert(limit_event->scheduled()); limit_event->deschedule(); delete limit_event; } return se_event; } if (async_event) { async_event = false; if (async_dump) { async_dump = false; using namespace Stats; SetupEvent(Dump, curTick); } if (async_dumpreset) { async_dumpreset = false; using namespace Stats; SetupEvent(Dump | Reset, curTick); } if (async_exit) { async_exit = false; exitSimLoop("user interrupt received"); } if (async_io || async_alarm) { async_io = false; async_alarm = false; pollQueue.service(); } } } // not reached... only exit is return on SimLoopExitEvent } Event * createCountedDrain() { return new CountedDrainEvent(); } void cleanupCountedDrain(Event *counted_drain) { CountedDrainEvent *event = dynamic_cast<CountedDrainEvent *>(counted_drain); if (event == NULL) { fatal("Called cleanupCountedDrain() on an event that was not " "a CountedDrainEvent."); } assert(event->getCount() == 0); delete event; } void serializeAll(const std::string &cpt_dir) { Serializable::serializeAll(cpt_dir); } void unserializeAll(const std::string &cpt_dir) { Serializable::unserializeAll(cpt_dir); } /** * Queue of C++ callbacks to invoke on simulator exit. */ CallbackQueue exitCallbacks; /** * Register an exit callback. */ void registerExitCallback(Callback *callback) { exitCallbacks.add(callback); } BaseCPU * convertToBaseCPUPtr(SimObject *obj) { BaseCPU *ptr = dynamic_cast<BaseCPU *>(obj); if (ptr == NULL) warn("Casting to BaseCPU pointer failed"); return ptr; } /** * Do C++ simulator exit processing. Exported to SWIG to be invoked * when simulator terminates via Python's atexit mechanism. */ void doExitCleanup() { exitCallbacks.process(); exitCallbacks.clear(); cout.flush(); ParamContext::cleanupAllContexts(); // print simulation stats Stats::DumpNow(); } <commit_msg>Get the path to load the ini file from. I'm not sure if this fix is needed in other places as well.<commit_after>/* * Copyright (c) 2000-2005 The Regents of The University of Michigan * 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 copyright holders 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. * * Authors: Steve Raasch * Nathan Binkert * Steve Reinhardt */ /// /// @file sim/main.cc /// #include <Python.h> // must be before system headers... see Python docs #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <libgen.h> #include <stdlib.h> #include <signal.h> #include <getopt.h> #include <list> #include <string> #include <vector> #include "base/callback.hh" #include "base/inifile.hh" #include "base/misc.hh" #include "base/output.hh" #include "base/pollevent.hh" #include "base/statistics.hh" #include "base/str.hh" #include "base/time.hh" #include "cpu/base.hh" #include "cpu/smt.hh" #include "mem/mem_object.hh" #include "mem/port.hh" #include "sim/async.hh" #include "sim/builder.hh" #include "sim/host.hh" #include "sim/serialize.hh" #include "sim/sim_events.hh" #include "sim/sim_exit.hh" #include "sim/sim_object.hh" #include "sim/stat_control.hh" #include "sim/stats.hh" #include "sim/root.hh" using namespace std; // See async.h. volatile bool async_event = false; volatile bool async_dump = false; volatile bool async_dumpreset = false; volatile bool async_exit = false; volatile bool async_io = false; volatile bool async_alarm = false; /// Stats signal handler. void dumpStatsHandler(int sigtype) { async_event = true; async_dump = true; } void dumprstStatsHandler(int sigtype) { async_event = true; async_dumpreset = true; } /// Exit signal handler. void exitNowHandler(int sigtype) { async_event = true; async_exit = true; } /// Abort signal handler. void abortHandler(int sigtype) { cerr << "Program aborted at cycle " << curTick << endl; #if TRACING_ON // dump trace buffer, if there is one Trace::theLog.dump(cerr); #endif } extern "C" { void init_cc_main(); } int main(int argc, char **argv) { signal(SIGFPE, SIG_IGN); // may occur on misspeculated paths signal(SIGTRAP, SIG_IGN); signal(SIGUSR1, dumpStatsHandler); // dump intermediate stats signal(SIGUSR2, dumprstStatsHandler); // dump and reset stats signal(SIGINT, exitNowHandler); // dump final stats and exit signal(SIGABRT, abortHandler); Py_SetProgramName(argv[0]); // default path to m5 python code is the currently executing // file... Python ZipImporter will find embedded zip archive. // The M5_ARCHIVE environment variable can be used to override this. char *m5_archive = getenv("M5_ARCHIVE"); string pythonpath = m5_archive ? m5_archive : argv[0]; char *oldpath = getenv("PYTHONPATH"); if (oldpath != NULL) { pythonpath += ":"; pythonpath += oldpath; } if (setenv("PYTHONPATH", pythonpath.c_str(), true) == -1) fatal("setenv: %s\n", strerror(errno)); // initialize embedded Python interpreter Py_Initialize(); PySys_SetArgv(argc, argv); // initialize SWIG 'cc_main' module init_cc_main(); PyRun_SimpleString("import m5"); PyRun_SimpleString("m5.main()"); // clean up Python intepreter. Py_Finalize(); } void setOutputDir(const string &dir) { simout.setDirectory(dir); } IniFile inifile; SimObject * createSimObject(const string &name) { return SimObjectClass::createObject(inifile, name); } /** * Pointer to the Python function that maps names to SimObjects. */ PyObject *resolveFunc = NULL; /** * Convert a pointer to the Python object that SWIG wraps around a C++ * SimObject pointer back to the actual C++ pointer. See main.i. */ extern "C" SimObject *convertSwigSimObjectPtr(PyObject *); SimObject * resolveSimObject(const string &name) { PyObject *pyPtr = PyEval_CallFunction(resolveFunc, "(s)", name.c_str()); if (pyPtr == NULL) { PyErr_Print(); panic("resolveSimObject: failure on call to Python for %s", name); } SimObject *simObj = convertSwigSimObjectPtr(pyPtr); if (simObj == NULL) panic("resolveSimObject: failure on pointer conversion for %s", name); return simObj; } /** * Load config.ini into C++ database. Exported to Python via SWIG; * invoked from m5.instantiate(). */ void loadIniFile(PyObject *_resolveFunc) { resolveFunc = _resolveFunc; configStream = simout.find("config.out"); // The configuration database is now complete; start processing it. inifile.load(simout.resolve("config.ini")); // Initialize statistics database Stats::InitSimStats(); } /** * Look up a MemObject port. Helper function for connectPorts(). */ Port * lookupPort(SimObject *so, const std::string &name, int i) { MemObject *mo = dynamic_cast<MemObject *>(so); if (mo == NULL) { warn("error casting SimObject %s to MemObject", so->name()); return NULL; } Port *p = mo->getPort(name, i); if (p == NULL) warn("error looking up port %s on object %s", name, so->name()); return p; } /** * Connect the described MemObject ports. Called from Python via SWIG. */ int connectPorts(SimObject *o1, const std::string &name1, int i1, SimObject *o2, const std::string &name2, int i2) { Port *p1 = lookupPort(o1, name1, i1); Port *p2 = lookupPort(o2, name2, i2); if (p1 == NULL || p2 == NULL) { warn("connectPorts: port lookup error"); return 0; } p1->setPeer(p2); p2->setPeer(p1); return 1; } /** * Do final initialization steps after object construction but before * start of simulation. */ void finalInit() { // Parse and check all non-config-hierarchy parameters. ParamContext::parseAllContexts(inifile); ParamContext::checkAllContexts(); // Echo all parameter settings to stats file as well. ParamContext::showAllContexts(*configStream); // Do a second pass to finish initializing the sim objects SimObject::initAll(); // Restore checkpointed state, if any. #if 0 configHierarchy.unserializeSimObjects(); #endif SimObject::regAllStats(); // Check to make sure that the stats package is properly initialized Stats::check(); // Reset to put the stats in a consistent state. Stats::reset(); SimStartup(); } /** Simulate for num_cycles additional cycles. If num_cycles is -1 * (the default), do not limit simulation; some other event must * terminate the loop. Exported to Python via SWIG. * @return The SimLoopExitEvent that caused the loop to exit. */ SimLoopExitEvent * simulate(Tick num_cycles = -1) { warn("Entering event queue @ %d. Starting simulation...\n", curTick); // Fix up num_cycles. Special default value -1 means simulate // "forever"... schedule event at MaxTick just to be safe. // Otherwise it's a delta for additional cycles to simulate past // curTick, and thus must be non-negative. if (num_cycles == -1) num_cycles = MaxTick; else if (num_cycles < 0) fatal("simulate: num_cycles must be >= 0 (was %d)\n", num_cycles); else num_cycles = curTick + num_cycles; Event *limit_event = new SimLoopExitEvent(num_cycles, "simulate() limit reached"); while (1) { // there should always be at least one event (the SimLoopExitEvent // we just scheduled) in the queue assert(!mainEventQueue.empty()); assert(curTick <= mainEventQueue.nextTick() && "event scheduled in the past"); // forward current cycle to the time of the first event on the // queue curTick = mainEventQueue.nextTick(); Event *exit_event = mainEventQueue.serviceOne(); if (exit_event != NULL) { // hit some kind of exit event; return to Python // event must be subclass of SimLoopExitEvent... SimLoopExitEvent *se_event = dynamic_cast<SimLoopExitEvent *>(exit_event); if (se_event == NULL) panic("Bogus exit event class!"); // if we didn't hit limit_event, delete it if (se_event != limit_event) { assert(limit_event->scheduled()); limit_event->deschedule(); delete limit_event; } return se_event; } if (async_event) { async_event = false; if (async_dump) { async_dump = false; using namespace Stats; SetupEvent(Dump, curTick); } if (async_dumpreset) { async_dumpreset = false; using namespace Stats; SetupEvent(Dump | Reset, curTick); } if (async_exit) { async_exit = false; exitSimLoop("user interrupt received"); } if (async_io || async_alarm) { async_io = false; async_alarm = false; pollQueue.service(); } } } // not reached... only exit is return on SimLoopExitEvent } Event * createCountedDrain() { return new CountedDrainEvent(); } void cleanupCountedDrain(Event *counted_drain) { CountedDrainEvent *event = dynamic_cast<CountedDrainEvent *>(counted_drain); if (event == NULL) { fatal("Called cleanupCountedDrain() on an event that was not " "a CountedDrainEvent."); } assert(event->getCount() == 0); delete event; } void serializeAll(const std::string &cpt_dir) { Serializable::serializeAll(cpt_dir); } void unserializeAll(const std::string &cpt_dir) { Serializable::unserializeAll(cpt_dir); } /** * Queue of C++ callbacks to invoke on simulator exit. */ CallbackQueue exitCallbacks; /** * Register an exit callback. */ void registerExitCallback(Callback *callback) { exitCallbacks.add(callback); } BaseCPU * convertToBaseCPUPtr(SimObject *obj) { BaseCPU *ptr = dynamic_cast<BaseCPU *>(obj); if (ptr == NULL) warn("Casting to BaseCPU pointer failed"); return ptr; } /** * Do C++ simulator exit processing. Exported to SWIG to be invoked * when simulator terminates via Python's atexit mechanism. */ void doExitCleanup() { exitCallbacks.process(); exitCallbacks.clear(); cout.flush(); ParamContext::cleanupAllContexts(); // print simulation stats Stats::DumpNow(); } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright (c) 2016 Sergey Alexandrov * * 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 <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> // In OpenCV 3 imwrite has been moved to imgcodecs module #if CV_MAJOR_VERSION >= 3 #include <opencv2/imgcodecs/imgcodecs.hpp> #endif #include <radical/radiometric_response.h> #include "utils/plot_radiometric_response.h" #include "utils/program_options.h" class Options : public OptionsBase { public: std::string r_response; bool save = false; protected: virtual void addOptions(boost::program_options::options_description& desc) override { namespace po = boost::program_options; desc.add_options()("save,s", po::bool_switch(&save), "Save to PNG file"); } virtual void addPositional(boost::program_options::options_description& desc, boost::program_options::positional_options_description& positional) override { namespace po = boost::program_options; desc.add_options()("crf", po::value<std::string>(&r_response), "Calibration file with radiometric response"); positional.add("crf", 1); } virtual void printHelp() override { std::cout << "Usage: display_radiometric_response [options] <radiometric-response>" << std::endl; std::cout << "" << std::endl; std::cout << "Visualizes radiometric response stored in a calibration file." << std::endl; std::cout << "" << std::endl; std::cout << "With the --save option the displayed image will also be written to the disk." << std::endl; std::cout << "File name is constructed by appending \".png\" to the input file path." << std::endl; std::cout << "" << std::endl; } }; int main(int argc, const char** argv) { Options options; if (!options.parse(argc, argv)) return 1; radical::RadiometricResponse rr(options.r_response); auto min_radiance = rr.inverseMap(cv::Vec3b(0, 0, 0)); auto max_radiance = rr.inverseMap(cv::Vec3b(255, 255, 255)); std::cout << "Loaded radiometric response from file \"" << options.r_response << "\"" << std::endl; std::cout << "Irradiance range: " << min_radiance << " - " << max_radiance << std::endl; auto plot = utils::plotRadiometricResponse(rr); if (options.save) { auto output = options.r_response + ".png"; cv::imwrite(output, plot); std::cout << "Saved radiometric response visualization to file \"" << output << "\"" << std::endl; } cv::imshow("Radiometric response", plot); cv::waitKey(-1); return 0; } <commit_msg>With --save option do not show radiometric response on the screen<commit_after>/****************************************************************************** * Copyright (c) 2016 Sergey Alexandrov * * 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 <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> // In OpenCV 3 imwrite has been moved to imgcodecs module #if CV_MAJOR_VERSION >= 3 #include <opencv2/imgcodecs/imgcodecs.hpp> #endif #include <radical/radiometric_response.h> #include "utils/plot_radiometric_response.h" #include "utils/program_options.h" class Options : public OptionsBase { public: std::string r_response; bool save = false; protected: virtual void addOptions(boost::program_options::options_description& desc) override { namespace po = boost::program_options; desc.add_options()("save,s", po::bool_switch(&save), "Save to PNG file and exit"); } virtual void addPositional(boost::program_options::options_description& desc, boost::program_options::positional_options_description& positional) override { namespace po = boost::program_options; desc.add_options()("crf", po::value<std::string>(&r_response), "Calibration file with radiometric response"); positional.add("crf", 1); } virtual void printHelp() override { std::cout << "Usage: display_radiometric_response [options] <radiometric-response>" << std::endl; std::cout << "" << std::endl; std::cout << "Plots radiometric response stored in a calibration file and displays it on the screen." << std::endl; std::cout << "" << std::endl; std::cout << "With the --save option the plot will be written to the disk instead of showing on the screen." << std::endl; std::cout << "Output file name is constructed by appending \".png\" to the input file path." << std::endl; std::cout << "" << std::endl; } }; int main(int argc, const char** argv) { Options options; if (!options.parse(argc, argv)) return 1; radical::RadiometricResponse rr(options.r_response); auto min_radiance = rr.inverseMap(cv::Vec3b(0, 0, 0)); auto max_radiance = rr.inverseMap(cv::Vec3b(255, 255, 255)); std::cout << "Loaded radiometric response from file \"" << options.r_response << "\"" << std::endl; std::cout << "Irradiance range: " << min_radiance << " - " << max_radiance << std::endl; auto plot = utils::plotRadiometricResponse(rr); if (options.save) { auto output = options.r_response + ".png"; cv::imwrite(output, plot); std::cout << "Saved radiometric response visualization to file \"" << output << "\"" << std::endl; } else { cv::imshow("Radiometric response", plot); cv::waitKey(-1); } return 0; } <|endoftext|>
<commit_before>// // SString.cpp // DataStruct // // Created by haozhu on 2017/6/10. // Copyright © 2017年 neu. All rights reserved. // //串采用定长顺序存储结构 //SString是数组类型,故不需引用类型 #include "SString.hpp" <commit_msg>完成串的部分操作方法<commit_after>// // SString.cpp // DataStruct // // Created by haozhu on 2017/6/10. // Copyright © 2017年 neu. All rights reserved. // //串采用定长顺序存储结构 //SString是数组类型,故不需引用类型 #include "SString.hpp" //生成一个其值等于chars的串T Status StrAssign(SString T, char *chars){ if (strlen(chars)>MAXSTRLEN) { //要保存的串超过了T的长度 return ERROR; }else{ T[0] = strlen(chars); //串T的第一个位置保存字符串的长度 for (int i=1; i<=T[0]; i++) { T[i] = *(chars+i-1); } return OK; } } //由串S复制得串T Status StrCopy(SString T, SString S){ for (int i=0; i<S[0]; i++) { T[i] = S[i]; } return OK; } //若串为空串则返回True,否则返回False Status StrEmpty(SString T){ if (T[0]) { return FALSE; }else{ return TRUE; } } //返回串T的长度 int StrLength(SString T){ return T[0]; } //若串T,S存在,若T>S, 返回值>0,T=S,返回值=0,T<S,返回值<0 int StrCompare(SString T, SString S){ for (int i=1; i<=T[0]&&i<=S[0]; i++) { if (T[i]!=S[i]) { return T[i]-S[i]; } } return T[0]-S[0]; } //将S清为空串 Status CleanStr(SString T){ T[0] = 0; //令串长等于0 return OK; } //用T返回由S1和S2联结而成的新串,若未截断,返回True,否则返回False Status Concat(SString T, SString S1, SString S2){ if (S1[0]+S2[0]<=MAXSTRLEN) { //字符串未截断 T[0] = S1[0]+S2[0]; for (int i=1; i<=S1[0]; i++) { T[i] = S1[i]; } for (int i=1; i<=S2[0]; i++) { T[S1[0]+i] = S2[i]; } return OK; }else{ //字符串截断 T[0] = MAXSTRLEN; for (int i=1; i<=S1[0]&&i<=MAXSTRLEN; i++) { T[i] = S1[i]; } for (int i=1; i<=MAXSTRLEN-S1[0]; i++) { T[S1[0]+i] = S2[i]; //进入了这个循环说明MAXSTRLEN-S1[0]>=1 } return FALSE; } } //用sub串返回串T的第pos个字符起长度为len的子串 Status SubString(SString T, SString sub, int pos, int len){ if (pos<1||pos>T[0]||len<0||pos+len-1>T[0]) { return ERROR; } for (int i=1; i<=len; i++) { sub[i] = T[pos+len-1]; } sub[0] = len; return OK; //我的写法 int to; if (pos+len-1>MAXSTRLEN) { to = MAXSTRLEN; }else{ to = pos+len-1; } for (int i=pos,j=1; i<=to&&j<=MAXSTRLEN; i++,j++) { sub[j] = T[i]; } return OK; } <|endoftext|>
<commit_before>/* * * Copyright 2018 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. * */ #include <grpc/support/port_platform.h> #include "src/core/lib/security/security_connector/ssl/ssl_security_connector.h" #include <stdbool.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/string_util.h> #include "src/core/ext/transport/chttp2/alpn/alpn.h" #include "src/core/lib/channel/handshaker.h" #include "src/core/lib/gpr/host_port.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/security/context/security_context.h" #include "src/core/lib/security/credentials/credentials.h" #include "src/core/lib/security/credentials/ssl/ssl_credentials.h" #include "src/core/lib/security/security_connector/load_system_roots.h" #include "src/core/lib/security/security_connector/ssl_utils.h" #include "src/core/lib/security/transport/security_handshaker.h" #include "src/core/tsi/ssl_transport_security.h" #include "src/core/tsi/transport_security.h" namespace { class grpc_ssl_channel_security_connector final : public grpc_channel_security_connector { public: grpc_ssl_channel_security_connector( grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, const grpc_ssl_config* config, const char* target_name, const char* overridden_target_name) : grpc_channel_security_connector(GRPC_SSL_URL_SCHEME, std::move(channel_creds), std::move(request_metadata_creds)), overridden_target_name_(overridden_target_name == nullptr ? nullptr : gpr_strdup(overridden_target_name)), verify_options_(&config->verify_options) { char* port; gpr_split_host_port(target_name, &target_name_, &port); gpr_free(port); } ~grpc_ssl_channel_security_connector() override { tsi_ssl_client_handshaker_factory_unref(client_handshaker_factory_); if (target_name_ != nullptr) gpr_free(target_name_); if (overridden_target_name_ != nullptr) gpr_free(overridden_target_name_); } grpc_security_status InitializeHandshakerFactory( const grpc_ssl_config* config, tsi_ssl_session_cache* ssl_session_cache) { return grpc_ssl_tsi_client_handshaker_factory_init( config->pem_key_cert_pair, config->pem_root_certs, ssl_session_cache, &client_handshaker_factory_); } void add_handshakers(grpc_pollset_set* interested_parties, grpc_core::HandshakeManager* handshake_mgr) override { // Instantiate TSI handshaker. tsi_handshaker* tsi_hs = nullptr; tsi_result result = tsi_ssl_client_handshaker_factory_create_handshaker( client_handshaker_factory_, overridden_target_name_ != nullptr ? overridden_target_name_ : target_name_, &tsi_hs); if (result != TSI_OK) { gpr_log(GPR_ERROR, "Handshaker creation failed with error %s.", tsi_result_to_string(result)); return; } // Create handshakers. handshake_mgr->Add(grpc_core::SecurityHandshakerCreate(tsi_hs, this)); } void check_peer(tsi_peer peer, grpc_endpoint* ep, grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, grpc_closure* on_peer_checked) override { const char* target_name = overridden_target_name_ != nullptr ? overridden_target_name_ : target_name_; grpc_error* error = grpc_ssl_check_alpn(&peer); if (error == GRPC_ERROR_NONE) { error = grpc_ssl_check_peer_name(target_name, &peer); if (error == GRPC_ERROR_NONE) { if (verify_options_->verify_peer_callback != nullptr) { const tsi_peer_property* p = tsi_peer_get_property_by_name(&peer, TSI_X509_PEM_CERT_PROPERTY); if (p == nullptr) { error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Cannot check peer: missing pem cert property."); } else { char* peer_pem = static_cast<char*>(gpr_malloc(p->value.length + 1)); memcpy(peer_pem, p->value.data, p->value.length); peer_pem[p->value.length] = '\0'; int callback_status = verify_options_->verify_peer_callback( target_name, peer_pem, verify_options_->verify_peer_callback_userdata); gpr_free(peer_pem); if (callback_status) { char* msg; gpr_asprintf(&msg, "Verify peer callback returned a failure (%d)", callback_status); error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); } } } *auth_context = grpc_ssl_peer_to_auth_context(&peer); } } GRPC_CLOSURE_SCHED(on_peer_checked, error); tsi_peer_destruct(&peer); } int cmp(const grpc_security_connector* other_sc) const override { auto* other = reinterpret_cast<const grpc_ssl_channel_security_connector*>(other_sc); int c = channel_security_connector_cmp(other); if (c != 0) return c; return grpc_ssl_cmp_target_name(target_name_, other->target_name_, overridden_target_name_, other->overridden_target_name_); } bool check_call_host(const char* host, grpc_auth_context* auth_context, grpc_closure* on_call_host_checked, grpc_error** error) override { return grpc_ssl_check_call_host(host, target_name_, overridden_target_name_, auth_context, on_call_host_checked, error); } void cancel_check_call_host(grpc_closure* on_call_host_checked, grpc_error* error) override { GRPC_ERROR_UNREF(error); } private: tsi_ssl_client_handshaker_factory* client_handshaker_factory_; char* target_name_; char* overridden_target_name_; const verify_peer_options* verify_options_; }; class grpc_ssl_server_security_connector : public grpc_server_security_connector { public: grpc_ssl_server_security_connector( grpc_core::RefCountedPtr<grpc_server_credentials> server_creds) : grpc_server_security_connector(GRPC_SSL_URL_SCHEME, std::move(server_creds)) {} ~grpc_ssl_server_security_connector() override { tsi_ssl_server_handshaker_factory_unref(server_handshaker_factory_); } bool has_cert_config_fetcher() const { return static_cast<const grpc_ssl_server_credentials*>(server_creds()) ->has_cert_config_fetcher(); } const tsi_ssl_server_handshaker_factory* server_handshaker_factory() const { return server_handshaker_factory_; } grpc_security_status InitializeHandshakerFactory() { grpc_security_status retval = GRPC_SECURITY_OK; if (has_cert_config_fetcher()) { // Load initial credentials from certificate_config_fetcher: if (!try_fetch_ssl_server_credentials()) { gpr_log(GPR_ERROR, "Failed loading SSL server credentials from fetcher."); retval = GRPC_SECURITY_ERROR; } } else { auto* server_credentials = static_cast<const grpc_ssl_server_credentials*>(server_creds()); retval = grpc_ssl_tsi_server_handshaker_factory_init( server_credentials->config().pem_key_cert_pairs, server_credentials->config().num_key_cert_pairs, server_credentials->config().pem_root_certs, server_credentials->config().client_certificate_request, &server_handshaker_factory_); } return retval; } void add_handshakers(grpc_pollset_set* interested_parties, grpc_core::HandshakeManager* handshake_mgr) override { // Instantiate TSI handshaker. try_fetch_ssl_server_credentials(); tsi_handshaker* tsi_hs = nullptr; tsi_result result = tsi_ssl_server_handshaker_factory_create_handshaker( server_handshaker_factory_, &tsi_hs); if (result != TSI_OK) { gpr_log(GPR_ERROR, "Handshaker creation failed with error %s.", tsi_result_to_string(result)); return; } // Create handshakers. handshake_mgr->Add(grpc_core::SecurityHandshakerCreate(tsi_hs, this)); } void check_peer(tsi_peer peer, grpc_endpoint* ep, grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, grpc_closure* on_peer_checked) override { grpc_error* error = grpc_ssl_check_alpn(&peer); *auth_context = grpc_ssl_peer_to_auth_context(&peer); tsi_peer_destruct(&peer); GRPC_CLOSURE_SCHED(on_peer_checked, error); } int cmp(const grpc_security_connector* other) const override { return server_security_connector_cmp( static_cast<const grpc_server_security_connector*>(other)); } private: /* Attempts to fetch the server certificate config if a callback is available. * Current certificate config will continue to be used if the callback returns * an error. Returns true if new credentials were sucessfully loaded. */ bool try_fetch_ssl_server_credentials() { grpc_ssl_server_certificate_config* certificate_config = nullptr; bool status; if (!has_cert_config_fetcher()) return false; grpc_ssl_server_credentials* server_creds = static_cast<grpc_ssl_server_credentials*>(this->mutable_server_creds()); grpc_ssl_certificate_config_reload_status cb_result = server_creds->FetchCertConfig(&certificate_config); if (cb_result == GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED) { gpr_log(GPR_DEBUG, "No change in SSL server credentials."); status = false; } else if (cb_result == GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_NEW) { status = try_replace_server_handshaker_factory(certificate_config); } else { // Log error, continue using previously-loaded credentials. gpr_log(GPR_ERROR, "Failed fetching new server credentials, continuing to " "use previously-loaded credentials."); status = false; } if (certificate_config != nullptr) { grpc_ssl_server_certificate_config_destroy(certificate_config); } return status; } /* Attempts to replace the server_handshaker_factory with a new factory using * the provided grpc_ssl_server_certificate_config. Should new factory * creation fail, the existing factory will not be replaced. Returns true on * success (new factory created). */ bool try_replace_server_handshaker_factory( const grpc_ssl_server_certificate_config* config) { if (config == nullptr) { gpr_log(GPR_ERROR, "Server certificate config callback returned invalid (NULL) " "config."); return false; } tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs = grpc_convert_grpc_to_tsi_cert_pairs(config->pem_key_cert_pairs, config->num_key_cert_pairs); const grpc_ssl_server_credentials* server_credentials = static_cast<const grpc_ssl_server_credentials*>(this->server_creds()); tsi_ssl_server_handshaker_factory* new_handshaker_factory = nullptr; grpc_security_status retval = grpc_ssl_tsi_server_handshaker_factory_init( pem_key_cert_pairs, config->num_key_cert_pairs, config->pem_root_certs, server_credentials->config().client_certificate_request, &new_handshaker_factory); gpr_free(pem_key_cert_pairs); if (retval != GRPC_SECURITY_OK) { return false; } set_server_handshaker_factory(new_handshaker_factory); return true; } void set_server_handshaker_factory( tsi_ssl_server_handshaker_factory* new_factory) { if (server_handshaker_factory_) { tsi_ssl_server_handshaker_factory_unref(server_handshaker_factory_); } server_handshaker_factory_ = new_factory; } tsi_ssl_server_handshaker_factory* server_handshaker_factory_ = nullptr; }; } // namespace grpc_core::RefCountedPtr<grpc_channel_security_connector> grpc_ssl_channel_security_connector_create( grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, const grpc_ssl_config* config, const char* target_name, const char* overridden_target_name, tsi_ssl_session_cache* ssl_session_cache) { if (config == nullptr || target_name == nullptr) { gpr_log(GPR_ERROR, "An ssl channel needs a config and a target name."); return nullptr; } grpc_core::RefCountedPtr<grpc_ssl_channel_security_connector> c = grpc_core::MakeRefCounted<grpc_ssl_channel_security_connector>( std::move(channel_creds), std::move(request_metadata_creds), config, target_name, overridden_target_name); const grpc_security_status result = c->InitializeHandshakerFactory(config, ssl_session_cache); if (result != GRPC_SECURITY_OK) { return nullptr; } return c; } grpc_core::RefCountedPtr<grpc_server_security_connector> grpc_ssl_server_security_connector_create( grpc_core::RefCountedPtr<grpc_server_credentials> server_credentials) { GPR_ASSERT(server_credentials != nullptr); grpc_core::RefCountedPtr<grpc_ssl_server_security_connector> c = grpc_core::MakeRefCounted<grpc_ssl_server_security_connector>( std::move(server_credentials)); const grpc_security_status retval = c->InitializeHandshakerFactory(); if (retval != GRPC_SECURITY_OK) { return nullptr; } return c; } <commit_msg>fail-fast if no pem root certs are available.<commit_after>/* * * Copyright 2018 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. * */ #include <grpc/support/port_platform.h> #include "src/core/lib/security/security_connector/ssl/ssl_security_connector.h" #include <stdbool.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/string_util.h> #include "src/core/ext/transport/chttp2/alpn/alpn.h" #include "src/core/lib/channel/handshaker.h" #include "src/core/lib/gpr/host_port.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/security/context/security_context.h" #include "src/core/lib/security/credentials/credentials.h" #include "src/core/lib/security/credentials/ssl/ssl_credentials.h" #include "src/core/lib/security/security_connector/load_system_roots.h" #include "src/core/lib/security/security_connector/ssl_utils.h" #include "src/core/lib/security/transport/security_handshaker.h" #include "src/core/tsi/ssl_transport_security.h" #include "src/core/tsi/transport_security.h" namespace { class grpc_ssl_channel_security_connector final : public grpc_channel_security_connector { public: grpc_ssl_channel_security_connector( grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, const grpc_ssl_config* config, const char* target_name, const char* overridden_target_name) : grpc_channel_security_connector(GRPC_SSL_URL_SCHEME, std::move(channel_creds), std::move(request_metadata_creds)), overridden_target_name_(overridden_target_name == nullptr ? nullptr : gpr_strdup(overridden_target_name)), verify_options_(&config->verify_options) { char* port; gpr_split_host_port(target_name, &target_name_, &port); gpr_free(port); } ~grpc_ssl_channel_security_connector() override { tsi_ssl_client_handshaker_factory_unref(client_handshaker_factory_); if (target_name_ != nullptr) gpr_free(target_name_); if (overridden_target_name_ != nullptr) gpr_free(overridden_target_name_); } grpc_security_status InitializeHandshakerFactory( const grpc_ssl_config* config, tsi_ssl_session_cache* ssl_session_cache) { return grpc_ssl_tsi_client_handshaker_factory_init( config->pem_key_cert_pair, config->pem_root_certs, ssl_session_cache, &client_handshaker_factory_); } void add_handshakers(grpc_pollset_set* interested_parties, grpc_core::HandshakeManager* handshake_mgr) override { // Instantiate TSI handshaker. tsi_handshaker* tsi_hs = nullptr; tsi_result result = tsi_ssl_client_handshaker_factory_create_handshaker( client_handshaker_factory_, overridden_target_name_ != nullptr ? overridden_target_name_ : target_name_, &tsi_hs); if (result != TSI_OK) { gpr_log(GPR_ERROR, "Handshaker creation failed with error %s.", tsi_result_to_string(result)); return; } // Create handshakers. handshake_mgr->Add(grpc_core::SecurityHandshakerCreate(tsi_hs, this)); } void check_peer(tsi_peer peer, grpc_endpoint* ep, grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, grpc_closure* on_peer_checked) override { const char* target_name = overridden_target_name_ != nullptr ? overridden_target_name_ : target_name_; grpc_error* error = grpc_ssl_check_alpn(&peer); if (error == GRPC_ERROR_NONE) { error = grpc_ssl_check_peer_name(target_name, &peer); if (error == GRPC_ERROR_NONE) { if (verify_options_->verify_peer_callback != nullptr) { const tsi_peer_property* p = tsi_peer_get_property_by_name(&peer, TSI_X509_PEM_CERT_PROPERTY); if (p == nullptr) { error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Cannot check peer: missing pem cert property."); } else { char* peer_pem = static_cast<char*>(gpr_malloc(p->value.length + 1)); memcpy(peer_pem, p->value.data, p->value.length); peer_pem[p->value.length] = '\0'; int callback_status = verify_options_->verify_peer_callback( target_name, peer_pem, verify_options_->verify_peer_callback_userdata); gpr_free(peer_pem); if (callback_status) { char* msg; gpr_asprintf(&msg, "Verify peer callback returned a failure (%d)", callback_status); error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); } } } *auth_context = grpc_ssl_peer_to_auth_context(&peer); } } GRPC_CLOSURE_SCHED(on_peer_checked, error); tsi_peer_destruct(&peer); } int cmp(const grpc_security_connector* other_sc) const override { auto* other = reinterpret_cast<const grpc_ssl_channel_security_connector*>(other_sc); int c = channel_security_connector_cmp(other); if (c != 0) return c; return grpc_ssl_cmp_target_name(target_name_, other->target_name_, overridden_target_name_, other->overridden_target_name_); } bool check_call_host(const char* host, grpc_auth_context* auth_context, grpc_closure* on_call_host_checked, grpc_error** error) override { return grpc_ssl_check_call_host(host, target_name_, overridden_target_name_, auth_context, on_call_host_checked, error); } void cancel_check_call_host(grpc_closure* on_call_host_checked, grpc_error* error) override { GRPC_ERROR_UNREF(error); } private: tsi_ssl_client_handshaker_factory* client_handshaker_factory_; char* target_name_; char* overridden_target_name_; const verify_peer_options* verify_options_; }; class grpc_ssl_server_security_connector : public grpc_server_security_connector { public: grpc_ssl_server_security_connector( grpc_core::RefCountedPtr<grpc_server_credentials> server_creds) : grpc_server_security_connector(GRPC_SSL_URL_SCHEME, std::move(server_creds)) {} ~grpc_ssl_server_security_connector() override { tsi_ssl_server_handshaker_factory_unref(server_handshaker_factory_); } bool has_cert_config_fetcher() const { return static_cast<const grpc_ssl_server_credentials*>(server_creds()) ->has_cert_config_fetcher(); } const tsi_ssl_server_handshaker_factory* server_handshaker_factory() const { return server_handshaker_factory_; } grpc_security_status InitializeHandshakerFactory() { grpc_security_status retval = GRPC_SECURITY_OK; if (has_cert_config_fetcher()) { // Load initial credentials from certificate_config_fetcher: if (!try_fetch_ssl_server_credentials()) { gpr_log(GPR_ERROR, "Failed loading SSL server credentials from fetcher."); retval = GRPC_SECURITY_ERROR; } } else { auto* server_credentials = static_cast<const grpc_ssl_server_credentials*>(server_creds()); retval = grpc_ssl_tsi_server_handshaker_factory_init( server_credentials->config().pem_key_cert_pairs, server_credentials->config().num_key_cert_pairs, server_credentials->config().pem_root_certs, server_credentials->config().client_certificate_request, &server_handshaker_factory_); } return retval; } void add_handshakers(grpc_pollset_set* interested_parties, grpc_core::HandshakeManager* handshake_mgr) override { // Instantiate TSI handshaker. try_fetch_ssl_server_credentials(); tsi_handshaker* tsi_hs = nullptr; tsi_result result = tsi_ssl_server_handshaker_factory_create_handshaker( server_handshaker_factory_, &tsi_hs); if (result != TSI_OK) { gpr_log(GPR_ERROR, "Handshaker creation failed with error %s.", tsi_result_to_string(result)); return; } // Create handshakers. handshake_mgr->Add(grpc_core::SecurityHandshakerCreate(tsi_hs, this)); } void check_peer(tsi_peer peer, grpc_endpoint* ep, grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, grpc_closure* on_peer_checked) override { grpc_error* error = grpc_ssl_check_alpn(&peer); *auth_context = grpc_ssl_peer_to_auth_context(&peer); tsi_peer_destruct(&peer); GRPC_CLOSURE_SCHED(on_peer_checked, error); } int cmp(const grpc_security_connector* other) const override { return server_security_connector_cmp( static_cast<const grpc_server_security_connector*>(other)); } private: /* Attempts to fetch the server certificate config if a callback is available. * Current certificate config will continue to be used if the callback returns * an error. Returns true if new credentials were sucessfully loaded. */ bool try_fetch_ssl_server_credentials() { grpc_ssl_server_certificate_config* certificate_config = nullptr; bool status; if (!has_cert_config_fetcher()) return false; grpc_ssl_server_credentials* server_creds = static_cast<grpc_ssl_server_credentials*>(this->mutable_server_creds()); grpc_ssl_certificate_config_reload_status cb_result = server_creds->FetchCertConfig(&certificate_config); if (cb_result == GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED) { gpr_log(GPR_DEBUG, "No change in SSL server credentials."); status = false; } else if (cb_result == GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_NEW) { status = try_replace_server_handshaker_factory(certificate_config); } else { // Log error, continue using previously-loaded credentials. gpr_log(GPR_ERROR, "Failed fetching new server credentials, continuing to " "use previously-loaded credentials."); status = false; } if (certificate_config != nullptr) { grpc_ssl_server_certificate_config_destroy(certificate_config); } return status; } /* Attempts to replace the server_handshaker_factory with a new factory using * the provided grpc_ssl_server_certificate_config. Should new factory * creation fail, the existing factory will not be replaced. Returns true on * success (new factory created). */ bool try_replace_server_handshaker_factory( const grpc_ssl_server_certificate_config* config) { if (config == nullptr) { gpr_log(GPR_ERROR, "Server certificate config callback returned invalid (NULL) " "config."); return false; } tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs = grpc_convert_grpc_to_tsi_cert_pairs(config->pem_key_cert_pairs, config->num_key_cert_pairs); const grpc_ssl_server_credentials* server_credentials = static_cast<const grpc_ssl_server_credentials*>(this->server_creds()); tsi_ssl_server_handshaker_factory* new_handshaker_factory = nullptr; grpc_security_status retval = grpc_ssl_tsi_server_handshaker_factory_init( pem_key_cert_pairs, config->num_key_cert_pairs, config->pem_root_certs, server_credentials->config().client_certificate_request, &new_handshaker_factory); gpr_free(pem_key_cert_pairs); if (retval != GRPC_SECURITY_OK) { return false; } set_server_handshaker_factory(new_handshaker_factory); return true; } void set_server_handshaker_factory( tsi_ssl_server_handshaker_factory* new_factory) { if (server_handshaker_factory_) { tsi_ssl_server_handshaker_factory_unref(server_handshaker_factory_); } server_handshaker_factory_ = new_factory; } tsi_ssl_server_handshaker_factory* server_handshaker_factory_ = nullptr; }; } // namespace grpc_core::RefCountedPtr<grpc_channel_security_connector> grpc_ssl_channel_security_connector_create( grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, const grpc_ssl_config* config, const char* target_name, const char* overridden_target_name, tsi_ssl_session_cache* ssl_session_cache) { if (config == nullptr || target_name == nullptr) { gpr_log(GPR_ERROR, "An ssl channel needs a config and a target name."); return nullptr; } if (config->pem_root_certs == nullptr && grpc_core::DefaultSslRootStore::GetPemRootCerts() == nullptr) { gpr_log(GPR_ERROR, "Could not get pem root certs."); return nullptr; } grpc_core::RefCountedPtr<grpc_ssl_channel_security_connector> c = grpc_core::MakeRefCounted<grpc_ssl_channel_security_connector>( std::move(channel_creds), std::move(request_metadata_creds), config, target_name, overridden_target_name); const grpc_security_status result = c->InitializeHandshakerFactory(config, ssl_session_cache); if (result != GRPC_SECURITY_OK) { return nullptr; } return c; } grpc_core::RefCountedPtr<grpc_server_security_connector> grpc_ssl_server_security_connector_create( grpc_core::RefCountedPtr<grpc_server_credentials> server_credentials) { GPR_ASSERT(server_credentials != nullptr); grpc_core::RefCountedPtr<grpc_ssl_server_security_connector> c = grpc_core::MakeRefCounted<grpc_ssl_server_security_connector>( std::move(server_credentials)); const grpc_security_status retval = c->InitializeHandshakerFactory(); if (retval != GRPC_SECURITY_OK) { return nullptr; } return c; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/nvdimm_utils.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ <commit_msg>Adds STR entry and exit functions to support NVDIMM<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/nvdimm_utils.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file nvdimm_utils.H /// @brief Subroutines to support nvdimm backup/restore process /// // *HWP HWP Owner: Tsung Yeung <tyeung@us.ibm.com> // *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <generic/memory/lib/utils/find.H> namespace mss { namespace nvdimm { /// /// @brief Helper for self_refresh_exit(). /// @tparam T the target type associated with this subroutine /// @param[in] i_target the target associated with this subroutine /// @return FAPI2_RC_SUCCESS iff setup was successful /// @note Uses memdiag to read the port to force CKE back to high. /// Stolen from mss_lab_memdiags.C /// template< fapi2::TargetType T > fapi2::ReturnCode self_refresh_exit_helper( const fapi2::Target<T>& i_target ); /// /// @brief Disable refresh and put target into self-refresh /// @tparam T the target type associated with this subroutine /// @param[in] i_target the target associated with this subroutine /// @return FAPI2_RC_SUCCESS iff setup was successful /// template< fapi2::TargetType T > fapi2::ReturnCode self_refresh_entry( const fapi2::Target<T>& i_target ); /// /// @brief Take the target out of self-refresh and restart refresh /// @tparam T the target type associated with this subroutine /// @param[in] i_target the target associated with this subroutine /// @return FAPI2_RC_SUCCESS iff setup was successful /// template< fapi2::TargetType T > fapi2::ReturnCode self_refresh_exit( const fapi2::Target<T>& i_target ); /// /// @brief Latch write vref at per-dram basis /// @tparam T the target type associated with this subroutine /// @param[in] i_target the target associated with this subroutine /// @return FAPI2_RC_SUCCESS iff setup was successful /// template< fapi2::TargetType T > fapi2::ReturnCode pda_vref_latch( const fapi2::Target<T>& i_target ); /// /// @brief Full post-restore transition for NVDIMM /// @tparam T the target type associated with this subroutine /// @param[in] i_target the target associated with this subroutine /// @return FAPI2_RC_SUCCESS iff setup was successful /// template< fapi2::TargetType T > fapi2::ReturnCode post_restore_transition( const fapi2::Target<T>& i_target ); }//ns nvdimm }//ns mss <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtLocation module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qdeclarativeresultmodelbase_p.h" QDeclarativeResultModelBase::QDeclarativeResultModelBase(QObject *parent) : QDeclarativeSearchModelBase(parent) { QHash<int, QByteArray> roles = roleNames(); roles.insert(DistanceRole, "distance"); roles.insert(PlaceRole, "place"); setRoleNames(roles); } QDeclarativeGeoServiceProvider* QDeclarativeResultModelBase::favoritesPlugin() const { return m_favoritesPlugin; } void QDeclarativeResultModelBase::setFavoritesPlugin(QDeclarativeGeoServiceProvider *plugin) { if (m_favoritesPlugin == plugin) return; m_favoritesPlugin = plugin; emit favoritesPluginChanged(); } QVariantMap QDeclarativeResultModelBase::favoritesMatchParameters() const { return m_matchParameters; } void QDeclarativeResultModelBase::setFavoritesMatchParameters(const QVariantMap &parameters) { if (m_matchParameters == parameters) return; m_matchParameters = parameters; emit favoritesMatchParametersChanged(); } void QDeclarativeResultModelBase::clearData() { qDeleteAll(m_places); m_places.clear(); m_results.clear(); } int QDeclarativeResultModelBase::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return m_results.count(); } QVariant QDeclarativeResultModelBase::data(int index, const QString &role) const { QModelIndex modelIndex = createIndex(index, 0); return data(modelIndex, roleNames().key(role.toLatin1())); } QVariant QDeclarativeResultModelBase::data(const QModelIndex &index, int role) const { if (index.row() > m_results.count()) return QVariant(); const QPlaceSearchResult &result = m_results.at(index.row()); switch (role) { case Qt::DisplayRole: if (result.type() == QPlaceSearchResult::PlaceResult) return m_places.at(index.row())->name(); else return QVariant(); case DistanceRole: return result.distance(); case PlaceRole: return QVariant::fromValue(static_cast<QObject *>(m_places.at(index.row()))); default: return QVariant(); } } void QDeclarativeResultModelBase::queryFinished() { if (!m_reply) return; QPlaceReply *reply = m_reply; m_reply = 0; if (reply->error() != QPlaceReply::NoError) { m_resultsBuffer.clear(); updateLayout(); setStatus(Error, reply->errorString()); reply->deleteLater(); } if (reply->type() == QPlaceReply::SearchReply) { QPlaceSearchReply *searchReply = qobject_cast<QPlaceSearchReply *>(reply); Q_ASSERT(searchReply); m_resultsBuffer = searchReply->results(); reply->deleteLater(); if (!m_favoritesPlugin) { updateLayout(); setStatus(Ready); } else { QGeoServiceProvider *serviceProvider = m_favoritesPlugin->sharedGeoServiceProvider(); if (!serviceProvider) { updateLayout(); setStatus(Error, QLatin1String("Favorites plugin returns a null QGeoServiceProvider instance")); } QPlaceManager *favoritesManager = serviceProvider->placeManager(); if (!favoritesManager) { updateLayout(); setStatus(Error, QLatin1String("Favorites plugin returns a null QPlaceManager")); } QPlaceMatchRequest request; if (m_matchParameters.isEmpty()) { if (!m_plugin) { reply->deleteLater(); setStatus(Error, QLatin1String("Plugin not assigned")); return; } QVariantMap params; params.insert(QPlaceMatchRequest::AlternativeId, QString::fromLatin1("x_id_") + m_plugin->name()); request.setParameters(params); } else { request.setParameters(m_matchParameters); } request.setResults(m_resultsBuffer); m_reply = favoritesManager->matchingPlaces(request); connect(m_reply, SIGNAL(finished()), this, SLOT(queryFinished())); } } else if (reply->type() == QPlaceReply::MatchReply){ QPlaceMatchReply *matchReply = qobject_cast<QPlaceMatchReply *>(reply); Q_ASSERT(matchReply); updateLayout(matchReply->places()); setStatus(Ready); reply->deleteLater(); } else { setStatus(Error, QLatin1String("Unknown reply type")); reply->deleteLater(); } } //Note: m_results buffer should be correctly populated before //calling this function void QDeclarativeResultModelBase::updateLayout(const QList<QPlace> &favoritePlaces) { int oldRowCount = rowCount(); beginResetModel(); clearData(); m_results = m_resultsBuffer; m_resultsBuffer.clear(); for (int i=0 ;i < m_results.count(); ++i) { QDeclarativePlace *place = new QDeclarativePlace(m_results.at(i).place(),plugin(), this); m_places.append(place); if ((favoritePlaces.count() == m_results.count()) && favoritePlaces.at(i) != QPlace()) m_places[i]->setFavorite(new QDeclarativePlace(favoritePlaces.at(i), m_favoritesPlugin, m_places[i])); } endResetModel(); if (m_results.count() != oldRowCount) emit rowCountChanged(); } <commit_msg>Fix crash due to uninitialised data member.<commit_after>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtLocation module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qdeclarativeresultmodelbase_p.h" QDeclarativeResultModelBase::QDeclarativeResultModelBase(QObject *parent) : QDeclarativeSearchModelBase(parent), m_favoritesPlugin(0) { QHash<int, QByteArray> roles = roleNames(); roles.insert(DistanceRole, "distance"); roles.insert(PlaceRole, "place"); setRoleNames(roles); } QDeclarativeGeoServiceProvider* QDeclarativeResultModelBase::favoritesPlugin() const { return m_favoritesPlugin; } void QDeclarativeResultModelBase::setFavoritesPlugin(QDeclarativeGeoServiceProvider *plugin) { if (m_favoritesPlugin == plugin) return; m_favoritesPlugin = plugin; emit favoritesPluginChanged(); } QVariantMap QDeclarativeResultModelBase::favoritesMatchParameters() const { return m_matchParameters; } void QDeclarativeResultModelBase::setFavoritesMatchParameters(const QVariantMap &parameters) { if (m_matchParameters == parameters) return; m_matchParameters = parameters; emit favoritesMatchParametersChanged(); } void QDeclarativeResultModelBase::clearData() { qDeleteAll(m_places); m_places.clear(); m_results.clear(); } int QDeclarativeResultModelBase::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return m_results.count(); } QVariant QDeclarativeResultModelBase::data(int index, const QString &role) const { QModelIndex modelIndex = createIndex(index, 0); return data(modelIndex, roleNames().key(role.toLatin1())); } QVariant QDeclarativeResultModelBase::data(const QModelIndex &index, int role) const { if (index.row() > m_results.count()) return QVariant(); const QPlaceSearchResult &result = m_results.at(index.row()); switch (role) { case Qt::DisplayRole: if (result.type() == QPlaceSearchResult::PlaceResult) return m_places.at(index.row())->name(); else return QVariant(); case DistanceRole: return result.distance(); case PlaceRole: return QVariant::fromValue(static_cast<QObject *>(m_places.at(index.row()))); default: return QVariant(); } } void QDeclarativeResultModelBase::queryFinished() { if (!m_reply) return; QPlaceReply *reply = m_reply; m_reply = 0; if (reply->error() != QPlaceReply::NoError) { m_resultsBuffer.clear(); updateLayout(); setStatus(Error, reply->errorString()); reply->deleteLater(); } if (reply->type() == QPlaceReply::SearchReply) { QPlaceSearchReply *searchReply = qobject_cast<QPlaceSearchReply *>(reply); Q_ASSERT(searchReply); m_resultsBuffer = searchReply->results(); reply->deleteLater(); if (!m_favoritesPlugin) { updateLayout(); setStatus(Ready); } else { QGeoServiceProvider *serviceProvider = m_favoritesPlugin->sharedGeoServiceProvider(); if (!serviceProvider) { updateLayout(); setStatus(Error, QLatin1String("Favorites plugin returns a null QGeoServiceProvider instance")); } QPlaceManager *favoritesManager = serviceProvider->placeManager(); if (!favoritesManager) { updateLayout(); setStatus(Error, QLatin1String("Favorites plugin returns a null QPlaceManager")); } QPlaceMatchRequest request; if (m_matchParameters.isEmpty()) { if (!m_plugin) { reply->deleteLater(); setStatus(Error, QLatin1String("Plugin not assigned")); return; } QVariantMap params; params.insert(QPlaceMatchRequest::AlternativeId, QString::fromLatin1("x_id_") + m_plugin->name()); request.setParameters(params); } else { request.setParameters(m_matchParameters); } request.setResults(m_resultsBuffer); m_reply = favoritesManager->matchingPlaces(request); connect(m_reply, SIGNAL(finished()), this, SLOT(queryFinished())); } } else if (reply->type() == QPlaceReply::MatchReply){ QPlaceMatchReply *matchReply = qobject_cast<QPlaceMatchReply *>(reply); Q_ASSERT(matchReply); updateLayout(matchReply->places()); setStatus(Ready); reply->deleteLater(); } else { setStatus(Error, QLatin1String("Unknown reply type")); reply->deleteLater(); } } //Note: m_results buffer should be correctly populated before //calling this function void QDeclarativeResultModelBase::updateLayout(const QList<QPlace> &favoritePlaces) { int oldRowCount = rowCount(); beginResetModel(); clearData(); m_results = m_resultsBuffer; m_resultsBuffer.clear(); for (int i=0 ;i < m_results.count(); ++i) { QDeclarativePlace *place = new QDeclarativePlace(m_results.at(i).place(),plugin(), this); m_places.append(place); if ((favoritePlaces.count() == m_results.count()) && favoritePlaces.at(i) != QPlace()) m_places[i]->setFavorite(new QDeclarativePlace(favoritePlaces.at(i), m_favoritesPlugin, m_places[i])); } endResetModel(); if (m_results.count() != oldRowCount) emit rowCountChanged(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "Symbian Foundation License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ #include "testconfiguration.h" #include <stdio.h> // XML configuration elements const char setupElement[] = "setup"; const char contactElement[] = "contact"; const char testElement[] = "test"; const char logElement[] = "log"; // XML configuration attriputes const char nameAttr[] = "name"; const char saveAttr[] = "save"; const char typeAttr[] = "type"; const char loggingAttr[] = "logging"; // XML configuration values const char valueYes[] = "yes"; const char valueNo[] = "no"; const char valuePerformanceTest[] = "0"; const char valueNormalTest[] = "1"; // ----------------------------------------------------------------------------- // TestConfiguration::TestConfiguration // ----------------------------------------------------------------------------- // TestConfiguration::TestConfiguration() : mSaveContact(true), mPerformanceTest(true), mLogToFile(false) { } // ----------------------------------------------------------------------------- // TestConfiguration::TestConfiguration // ----------------------------------------------------------------------------- // TestConfiguration::~TestConfiguration() { } // ----------------------------------------------------------------------------- // TestResultXmlParser::parse // ----------------------------------------------------------------------------- // int TestConfiguration::parse(const QString& fileName) { QFile file(fileName); QXmlInputSource inputSource(&file); QXmlSimpleReader reader; reader.setContentHandler(this); return reader.parse(inputSource); } // ----------------------------------------------------------------------------- // TestConfiguration::startElement // ----------------------------------------------------------------------------- // bool TestConfiguration::startElement( const QString& /*namespaceURI*/, const QString& /*localName*/, const QString& qName, const QXmlAttributes& atts) { if( qName == setupElement) { mTestName = atts.value(nameAttr); } else if (qName == contactElement) { mSaveContact = atts.value(saveAttr).contains(valueYes, Qt::CaseInsensitive); } else if (qName == testElement) { mPerformanceTest = atts.value(typeAttr).contains(valuePerformanceTest, Qt::CaseInsensitive); } else if (qName == logElement) { mLogToFile = atts.value(loggingAttr).contains(valueYes, Qt::CaseInsensitive); } return true; } // End of File. <commit_msg>Fix for arm compilation warnings<commit_after>/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "Symbian Foundation License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ #include "testconfiguration.h" #include <stdio.h> // XML configuration elements const char setupElement[] = "setup"; const char contactElement[] = "contact"; const char testElement[] = "test"; const char logElement[] = "log"; // XML configuration attriputes const char nameAttr[] = "name"; const char saveAttr[] = "save"; const char typeAttr[] = "type"; const char loggingAttr[] = "logging"; // XML configuration values const char valueYes[] = "yes"; const char valuePerformanceTest[] = "0"; // ----------------------------------------------------------------------------- // TestConfiguration::TestConfiguration // ----------------------------------------------------------------------------- // TestConfiguration::TestConfiguration() : mSaveContact(true), mPerformanceTest(true), mLogToFile(false) { } // ----------------------------------------------------------------------------- // TestConfiguration::TestConfiguration // ----------------------------------------------------------------------------- // TestConfiguration::~TestConfiguration() { } // ----------------------------------------------------------------------------- // TestResultXmlParser::parse // ----------------------------------------------------------------------------- // int TestConfiguration::parse(const QString& fileName) { QFile file(fileName); QXmlInputSource inputSource(&file); QXmlSimpleReader reader; reader.setContentHandler(this); return reader.parse(inputSource); } // ----------------------------------------------------------------------------- // TestConfiguration::startElement // ----------------------------------------------------------------------------- // bool TestConfiguration::startElement( const QString& /*namespaceURI*/, const QString& /*localName*/, const QString& qName, const QXmlAttributes& atts) { if( qName == setupElement) { mTestName = atts.value(nameAttr); } else if (qName == contactElement) { mSaveContact = atts.value(saveAttr).contains(valueYes, Qt::CaseInsensitive); } else if (qName == testElement) { mPerformanceTest = atts.value(typeAttr).contains(valuePerformanceTest, Qt::CaseInsensitive); } else if (qName == logElement) { mLogToFile = atts.value(loggingAttr).contains(valueYes, Qt::CaseInsensitive); } return true; } // End of File. <|endoftext|>
<commit_before>#include <sys/errno.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/uio.h> #include <errno.h> #include <limits.h> #include <signal.h> #include <unistd.h> #include <common/buffer.h> #include <common/limits.h> #include <event/action.h> #include <event/callback.h> #include <event/event_system.h> #include <io/io_system.h> #define IO_READ_BUFFER_SIZE 65536 IOSystem::Handle::Handle(int fd, Channel *owner) : log_("/io/system/handle"), fd_(fd), owner_(owner), close_callback_(NULL), close_action_(NULL), read_amount_(0), read_buffer_(), read_callback_(NULL), read_action_(NULL), write_buffer_(), write_callback_(NULL), write_action_(NULL) { } IOSystem::Handle::~Handle() { ASSERT(fd_ == -1); ASSERT(close_action_ == NULL); ASSERT(close_callback_ == NULL); ASSERT(read_action_ == NULL); ASSERT(read_callback_ == NULL); ASSERT(write_action_ == NULL); ASSERT(write_callback_ == NULL); } void IOSystem::Handle::close_callback(void) { close_action_->cancel(); close_action_ = NULL; ASSERT(fd_ != -1); int rv = ::close(fd_); if (rv == -1) { switch (errno) { case EAGAIN: close_action_ = close_schedule(); break; default: close_callback_->event(Event(Event::Error, errno)); Action *a = EventSystem::instance()->schedule(close_callback_); close_action_ = a; close_callback_ = NULL; break; } return; } fd_ = -1; close_callback_->event(Event(Event::Done, 0)); Action *a = EventSystem::instance()->schedule(close_callback_); close_action_ = a; close_callback_ = NULL; } void IOSystem::Handle::close_cancel(void) { ASSERT(close_action_ != NULL); close_action_->cancel(); close_action_ = NULL; if (close_callback_ != NULL) { delete close_callback_; close_callback_ = NULL; } } Action * IOSystem::Handle::close_schedule(void) { ASSERT(close_action_ == NULL); Callback *cb = callback(this, &IOSystem::Handle::close_callback); Action *a = EventSystem::instance()->schedule(cb); return (a); } void IOSystem::Handle::read_callback(Event e) { read_action_->cancel(); read_action_ = NULL; switch (e.type_) { case Event::EOS: case Event::Done: break; case Event::Error: { DEBUG(log_) << "Poll returned error: " << e; read_callback_->event(e); Action *a = EventSystem::instance()->schedule(read_callback_); read_action_ = a; read_callback_ = NULL; return; } default: HALT(log_) << "Unexpected event: " << e; } size_t rlen; if (read_amount_ == 0) rlen = IO_READ_BUFFER_SIZE; else { rlen = read_amount_ - read_buffer_.length(); ASSERT(rlen != 0); if (rlen > IO_READ_BUFFER_SIZE) rlen = IO_READ_BUFFER_SIZE; } /* * A bit of discussion is warranted on this: * * In tack, IOV_MAX BufferSegments are allocated and read in to with * readv(2), and then the lengths are adjusted and the ones that are * empty are freed. It's also possible to set the expected lengths * first (and only allocate * roundup(rlen, BUFFER_SEGMENT_SIZE) / BUFFER_SEGMENT_SIZE * BufferSegments, though really IOV_MAX (or some chosen number) seems * a bit better since most of our reads right now are read_amount_==0) * and put them into a Buffer and trim the leftovers, which is a bit * nicer. * * Since our read_amount_ is usually 0, though, we're kind of at the * mercy chance (well, not really) as to how much data we will read, * which means a sizable amount of thrashing of memory; allocating and * freeing BufferSegments. * * By comparison, stack space is cheap in userland and allocating 64K * of it here is pretty painless. Reading to it is fast and then * copying only what we need into BufferSegments isn't very costly. * Indeed, since readv can't sparsely-populate each data pointer, it * has to do some data shuffling, already. Benchmarking would be a * good idea, but it seems like there are arguments both ways. Of * course, tack is very fast and this code path hasn't been thrashed * half so much. When tack is adjusted to use the IO system and Pipes * in the future, if performance degradation is noticeable, perhaps * it will worth it to switch. For now, absence any idea of the real * read sizes in the wild, doing nothing and not thrashing memory is * decidedly more appealing. */ uint8_t data[IO_READ_BUFFER_SIZE]; ssize_t len = ::read(fd_, data, sizeof data); if (len == -1) { switch (errno) { case EAGAIN: read_action_ = read_schedule(); break; default: read_callback_->event(Event(Event::Error, errno, read_buffer_)); Action *a = EventSystem::instance()->schedule(read_callback_); read_action_ = a; read_callback_ = NULL; read_buffer_.clear(); read_amount_ = 0; break; } return; } /* * XXX * If we get an EOS from EventPoll, should we just terminate after that * one read? How can we tell how much data is still available to be * read? Will we get it all in one read? Eventually, one would expect * to get a read with a length of 0, or an error, but will kevent even * continue to fire off read events? */ if (len == 0) { read_callback_->event(Event(Event::EOS, 0, read_buffer_)); Action *a = EventSystem::instance()->schedule(read_callback_); read_action_ = a; read_callback_ = NULL; read_buffer_.clear(); read_amount_ = 0; return; } read_buffer_.append(data, len); read_action_ = read_schedule(); } void IOSystem::Handle::read_cancel(void) { ASSERT(read_action_ != NULL); read_action_->cancel(); read_action_ = NULL; if (read_callback_ != NULL) { delete read_callback_; read_callback_ = NULL; } } Action * IOSystem::Handle::read_schedule(void) { ASSERT(read_action_ == NULL); if (!read_buffer_.empty() && read_buffer_.length() >= read_amount_) { if (read_amount_ == 0) read_amount_ = read_buffer_.length(); read_callback_->event(Event(Event::Done, 0, Buffer(read_buffer_, read_amount_))); Action *a = EventSystem::instance()->schedule(read_callback_); read_callback_ = NULL; read_buffer_.skip(read_amount_); read_amount_ = 0; return (a); } EventCallback *cb = callback(this, &IOSystem::Handle::read_callback); Action *a = EventSystem::instance()->poll(EventPoll::Readable, fd_, cb); return (a); } void IOSystem::Handle::write_callback(Event e) { write_action_->cancel(); write_action_ = NULL; switch (e.type_) { case Event::Done: break; case Event::Error: { DEBUG(log_) << "Poll returned error: " << e; write_callback_->event(e); Action *a = EventSystem::instance()->schedule(write_callback_); write_action_ = a; write_callback_ = NULL; return; } default: HALT(log_) << "Unexpected event: " << e; } /* XXX This doesn't handle UDP nicely. Right? */ /* XXX If a UDP packet is > IOV_MAX segments, this will break it. */ struct iovec iov[IOV_MAX]; size_t iovcnt = write_buffer_.fill_iovec(iov, IOV_MAX); ssize_t len = ::writev(fd_, iov, iovcnt); if (len == -1) { switch (errno) { case EAGAIN: write_action_ = write_schedule(); break; default: write_callback_->event(Event(Event::Error, errno)); Action *a = EventSystem::instance()->schedule(write_callback_); write_action_ = a; write_callback_ = NULL; break; } return; } write_buffer_.skip(len); if (write_buffer_.empty()) { write_callback_->event(Event(Event::Done, 0)); Action *a = EventSystem::instance()->schedule(write_callback_); write_action_ = a; write_callback_ = NULL; return; } write_action_ = write_schedule(); } void IOSystem::Handle::write_cancel(void) { ASSERT(write_action_ != NULL); write_action_->cancel(); write_action_ = NULL; if (write_callback_ != NULL) { delete write_callback_; write_callback_ = NULL; } } Action * IOSystem::Handle::write_schedule(void) { ASSERT(write_action_ == NULL); EventCallback *cb = callback(this, &IOSystem::Handle::write_callback); Action *a = EventSystem::instance()->poll(EventPoll::Writable, fd_, cb); return (a); } IOSystem::IOSystem(void) : log_("/io/system"), handle_map_() { /* * Prepare system to handle IO. */ INFO(log_) << "Starting IO system."; /* * Disable SIGPIPE. * * Because errors are returned asynchronously and may occur at any time, * there may be a pending write to a file descriptor which has * previously thrown an error. There are changes that could be made to * the scheduler to work around this, but they are not desirable. */ if (::signal(SIGPIPE, SIG_IGN) == SIG_ERR) HALT(log_) << "Could not disable SIGPIPE."; /* * Up the file descriptor limit. * * Probably this should be configurable, but there's no harm on modern * systems and for the performance-critical applications using the IO * system, more file descriptors is better. */ struct rlimit rlim; int rv = ::getrlimit(RLIMIT_NOFILE, &rlim); if (rv == 0) { if (rlim.rlim_cur < rlim.rlim_max) { rlim.rlim_cur = rlim.rlim_max; rv = ::setrlimit(RLIMIT_NOFILE, &rlim); if (rv == -1) { INFO(log_) << "Unable to increase file descriptor limit."; } } } else { INFO(log_) << "Unable to get file descriptor limit."; } } IOSystem::~IOSystem() { ASSERT(handle_map_.empty()); } void IOSystem::attach(int fd, Channel *owner) { ASSERT(handle_map_.find(handle_key_t(fd, owner)) == handle_map_.end()); handle_map_[handle_key_t(fd, owner)] = new IOSystem::Handle(fd, owner); } void IOSystem::detach(int fd, Channel *owner) { handle_map_t::iterator it; IOSystem::Handle *h; it = handle_map_.find(handle_key_t(fd, owner)); ASSERT(it != handle_map_.end()); h = it->second; ASSERT(h != NULL); ASSERT(h->owner_ == owner); handle_map_.erase(it); delete h; } Action * IOSystem::close(int fd, Channel *owner, EventCallback *cb) { IOSystem::Handle *h; h = handle_map_[handle_key_t(fd, owner)]; ASSERT(h != NULL); ASSERT(h->close_callback_ == NULL); ASSERT(h->close_action_ == NULL); ASSERT(h->read_callback_ == NULL); ASSERT(h->read_action_ == NULL); ASSERT(h->write_callback_ == NULL); ASSERT(h->write_action_ == NULL); ASSERT(h->fd_ != -1); h->close_callback_ = cb; h->close_action_ = h->close_schedule(); return (cancellation(h, &IOSystem::Handle::close_cancel)); } Action * IOSystem::read(int fd, Channel *owner, size_t amount, EventCallback *cb) { IOSystem::Handle *h; h = handle_map_[handle_key_t(fd, owner)]; ASSERT(h != NULL); ASSERT(h->read_callback_ == NULL); ASSERT(h->read_action_ == NULL); h->read_amount_ = amount; h->read_callback_ = cb; h->read_action_ = h->read_schedule(); return (cancellation(h, &IOSystem::Handle::read_cancel)); } Action * IOSystem::write(int fd, Channel *owner, Buffer *buffer, EventCallback *cb) { IOSystem::Handle *h; h = handle_map_[handle_key_t(fd, owner)]; ASSERT(h != NULL); ASSERT(h->write_callback_ == NULL); ASSERT(h->write_action_ == NULL); ASSERT(h->write_buffer_.empty()); ASSERT(!buffer->empty()); h->write_buffer_.append(buffer); buffer->clear(); h->write_callback_ = cb; h->write_action_ = h->write_schedule(); return (cancellation(h, &IOSystem::Handle::write_cancel)); } <commit_msg>Reword a comment.<commit_after>#include <sys/errno.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/uio.h> #include <errno.h> #include <limits.h> #include <signal.h> #include <unistd.h> #include <common/buffer.h> #include <common/limits.h> #include <event/action.h> #include <event/callback.h> #include <event/event_system.h> #include <io/io_system.h> #define IO_READ_BUFFER_SIZE 65536 IOSystem::Handle::Handle(int fd, Channel *owner) : log_("/io/system/handle"), fd_(fd), owner_(owner), close_callback_(NULL), close_action_(NULL), read_amount_(0), read_buffer_(), read_callback_(NULL), read_action_(NULL), write_buffer_(), write_callback_(NULL), write_action_(NULL) { } IOSystem::Handle::~Handle() { ASSERT(fd_ == -1); ASSERT(close_action_ == NULL); ASSERT(close_callback_ == NULL); ASSERT(read_action_ == NULL); ASSERT(read_callback_ == NULL); ASSERT(write_action_ == NULL); ASSERT(write_callback_ == NULL); } void IOSystem::Handle::close_callback(void) { close_action_->cancel(); close_action_ = NULL; ASSERT(fd_ != -1); int rv = ::close(fd_); if (rv == -1) { switch (errno) { case EAGAIN: close_action_ = close_schedule(); break; default: close_callback_->event(Event(Event::Error, errno)); Action *a = EventSystem::instance()->schedule(close_callback_); close_action_ = a; close_callback_ = NULL; break; } return; } fd_ = -1; close_callback_->event(Event(Event::Done, 0)); Action *a = EventSystem::instance()->schedule(close_callback_); close_action_ = a; close_callback_ = NULL; } void IOSystem::Handle::close_cancel(void) { ASSERT(close_action_ != NULL); close_action_->cancel(); close_action_ = NULL; if (close_callback_ != NULL) { delete close_callback_; close_callback_ = NULL; } } Action * IOSystem::Handle::close_schedule(void) { ASSERT(close_action_ == NULL); Callback *cb = callback(this, &IOSystem::Handle::close_callback); Action *a = EventSystem::instance()->schedule(cb); return (a); } void IOSystem::Handle::read_callback(Event e) { read_action_->cancel(); read_action_ = NULL; switch (e.type_) { case Event::EOS: case Event::Done: break; case Event::Error: { DEBUG(log_) << "Poll returned error: " << e; read_callback_->event(e); Action *a = EventSystem::instance()->schedule(read_callback_); read_action_ = a; read_callback_ = NULL; return; } default: HALT(log_) << "Unexpected event: " << e; } size_t rlen; if (read_amount_ == 0) rlen = IO_READ_BUFFER_SIZE; else { rlen = read_amount_ - read_buffer_.length(); ASSERT(rlen != 0); if (rlen > IO_READ_BUFFER_SIZE) rlen = IO_READ_BUFFER_SIZE; } /* * A bit of discussion is warranted on this: * * In tack, IOV_MAX BufferSegments are allocated and read in to with * readv(2), and then the lengths are adjusted and the ones that are * empty are freed. It's also possible to set the expected lengths * first (and only allocate * roundup(rlen, BUFFER_SEGMENT_SIZE) / BUFFER_SEGMENT_SIZE * BufferSegments, though really IOV_MAX (or some chosen number) seems * a bit better since most of our reads right now are read_amount_==0) * and put them into a Buffer and trim the leftovers, which is a bit * nicer. * * Since our read_amount_ is usually 0, though, we're kind of at the * mercy chance (well, not really) as to how much data we will read, * which means a sizable amount of thrashing of memory; allocating and * freeing BufferSegments. * * By comparison, stack space is cheap in userland and allocating 64K * of it here is pretty painless. Reading to it is fast and then * copying only what we need into BufferSegments isn't very costly. * Indeed, since readv can't sparsely-populate each data pointer, it * has to do some data shuffling, already. Benchmarking would be a * good idea, but it seems like there are arguments both ways. Of * course, tack is very fast and this code path hasn't been thrashed * half so much. When tack is adjusted to use the IO system and Pipes * in the future, if performance degradation is noticeable, perhaps * it will worth it to switch. For now, absence any idea of the real * read sizes in the wild, doing nothing and not thrashing memory is * decidedly more appealing. */ uint8_t data[IO_READ_BUFFER_SIZE]; ssize_t len = ::read(fd_, data, sizeof data); if (len == -1) { switch (errno) { case EAGAIN: read_action_ = read_schedule(); break; default: read_callback_->event(Event(Event::Error, errno, read_buffer_)); Action *a = EventSystem::instance()->schedule(read_callback_); read_action_ = a; read_callback_ = NULL; read_buffer_.clear(); read_amount_ = 0; break; } return; } /* * XXX * If we get a short read from readv and detected EOS from EventPoll is * that good enough, instead? We can keep reading until we get a 0, sure, * but if things other than network conditions influence whether reads * would block (and whether non-blocking reads return), there could be * more data waiting, and so we shouldn't just use a short read as an * indicator? */ if (len == 0) { read_callback_->event(Event(Event::EOS, 0, read_buffer_)); Action *a = EventSystem::instance()->schedule(read_callback_); read_action_ = a; read_callback_ = NULL; read_buffer_.clear(); read_amount_ = 0; return; } read_buffer_.append(data, len); read_action_ = read_schedule(); } void IOSystem::Handle::read_cancel(void) { ASSERT(read_action_ != NULL); read_action_->cancel(); read_action_ = NULL; if (read_callback_ != NULL) { delete read_callback_; read_callback_ = NULL; } } Action * IOSystem::Handle::read_schedule(void) { ASSERT(read_action_ == NULL); if (!read_buffer_.empty() && read_buffer_.length() >= read_amount_) { if (read_amount_ == 0) read_amount_ = read_buffer_.length(); read_callback_->event(Event(Event::Done, 0, Buffer(read_buffer_, read_amount_))); Action *a = EventSystem::instance()->schedule(read_callback_); read_callback_ = NULL; read_buffer_.skip(read_amount_); read_amount_ = 0; return (a); } EventCallback *cb = callback(this, &IOSystem::Handle::read_callback); Action *a = EventSystem::instance()->poll(EventPoll::Readable, fd_, cb); return (a); } void IOSystem::Handle::write_callback(Event e) { write_action_->cancel(); write_action_ = NULL; switch (e.type_) { case Event::Done: break; case Event::Error: { DEBUG(log_) << "Poll returned error: " << e; write_callback_->event(e); Action *a = EventSystem::instance()->schedule(write_callback_); write_action_ = a; write_callback_ = NULL; return; } default: HALT(log_) << "Unexpected event: " << e; } /* XXX This doesn't handle UDP nicely. Right? */ /* XXX If a UDP packet is > IOV_MAX segments, this will break it. */ struct iovec iov[IOV_MAX]; size_t iovcnt = write_buffer_.fill_iovec(iov, IOV_MAX); ssize_t len = ::writev(fd_, iov, iovcnt); if (len == -1) { switch (errno) { case EAGAIN: write_action_ = write_schedule(); break; default: write_callback_->event(Event(Event::Error, errno)); Action *a = EventSystem::instance()->schedule(write_callback_); write_action_ = a; write_callback_ = NULL; break; } return; } write_buffer_.skip(len); if (write_buffer_.empty()) { write_callback_->event(Event(Event::Done, 0)); Action *a = EventSystem::instance()->schedule(write_callback_); write_action_ = a; write_callback_ = NULL; return; } write_action_ = write_schedule(); } void IOSystem::Handle::write_cancel(void) { ASSERT(write_action_ != NULL); write_action_->cancel(); write_action_ = NULL; if (write_callback_ != NULL) { delete write_callback_; write_callback_ = NULL; } } Action * IOSystem::Handle::write_schedule(void) { ASSERT(write_action_ == NULL); EventCallback *cb = callback(this, &IOSystem::Handle::write_callback); Action *a = EventSystem::instance()->poll(EventPoll::Writable, fd_, cb); return (a); } IOSystem::IOSystem(void) : log_("/io/system"), handle_map_() { /* * Prepare system to handle IO. */ INFO(log_) << "Starting IO system."; /* * Disable SIGPIPE. * * Because errors are returned asynchronously and may occur at any time, * there may be a pending write to a file descriptor which has * previously thrown an error. There are changes that could be made to * the scheduler to work around this, but they are not desirable. */ if (::signal(SIGPIPE, SIG_IGN) == SIG_ERR) HALT(log_) << "Could not disable SIGPIPE."; /* * Up the file descriptor limit. * * Probably this should be configurable, but there's no harm on modern * systems and for the performance-critical applications using the IO * system, more file descriptors is better. */ struct rlimit rlim; int rv = ::getrlimit(RLIMIT_NOFILE, &rlim); if (rv == 0) { if (rlim.rlim_cur < rlim.rlim_max) { rlim.rlim_cur = rlim.rlim_max; rv = ::setrlimit(RLIMIT_NOFILE, &rlim); if (rv == -1) { INFO(log_) << "Unable to increase file descriptor limit."; } } } else { INFO(log_) << "Unable to get file descriptor limit."; } } IOSystem::~IOSystem() { ASSERT(handle_map_.empty()); } void IOSystem::attach(int fd, Channel *owner) { ASSERT(handle_map_.find(handle_key_t(fd, owner)) == handle_map_.end()); handle_map_[handle_key_t(fd, owner)] = new IOSystem::Handle(fd, owner); } void IOSystem::detach(int fd, Channel *owner) { handle_map_t::iterator it; IOSystem::Handle *h; it = handle_map_.find(handle_key_t(fd, owner)); ASSERT(it != handle_map_.end()); h = it->second; ASSERT(h != NULL); ASSERT(h->owner_ == owner); handle_map_.erase(it); delete h; } Action * IOSystem::close(int fd, Channel *owner, EventCallback *cb) { IOSystem::Handle *h; h = handle_map_[handle_key_t(fd, owner)]; ASSERT(h != NULL); ASSERT(h->close_callback_ == NULL); ASSERT(h->close_action_ == NULL); ASSERT(h->read_callback_ == NULL); ASSERT(h->read_action_ == NULL); ASSERT(h->write_callback_ == NULL); ASSERT(h->write_action_ == NULL); ASSERT(h->fd_ != -1); h->close_callback_ = cb; h->close_action_ = h->close_schedule(); return (cancellation(h, &IOSystem::Handle::close_cancel)); } Action * IOSystem::read(int fd, Channel *owner, size_t amount, EventCallback *cb) { IOSystem::Handle *h; h = handle_map_[handle_key_t(fd, owner)]; ASSERT(h != NULL); ASSERT(h->read_callback_ == NULL); ASSERT(h->read_action_ == NULL); h->read_amount_ = amount; h->read_callback_ = cb; h->read_action_ = h->read_schedule(); return (cancellation(h, &IOSystem::Handle::read_cancel)); } Action * IOSystem::write(int fd, Channel *owner, Buffer *buffer, EventCallback *cb) { IOSystem::Handle *h; h = handle_map_[handle_key_t(fd, owner)]; ASSERT(h != NULL); ASSERT(h->write_callback_ == NULL); ASSERT(h->write_action_ == NULL); ASSERT(h->write_buffer_.empty()); ASSERT(!buffer->empty()); h->write_buffer_.append(buffer); buffer->clear(); h->write_callback_ = cb; h->write_action_ = h->write_schedule(); return (cancellation(h, &IOSystem::Handle::write_cancel)); } <|endoftext|>
<commit_before>#include "layers/icp.h" #include "pcl/registration/registration.h" #include "pcl/registration/icp.h" #include <Eigen/Dense> ///< to enable OpenCV's eigen2cv() #include <opencv2/core/eigen.hpp> ///< for eigen2cv(), preceeded be #include <Eigen/Dense> #include "core/exception.h" #include "core/layerconfig.h" #include "core/pcl_utils.h" #include "core/signal.h" #include "core/stl.h" #include "layers/layerfactory.h" #include "ts/ts.h" #include "ts/layer_assertions.h" using namespace std; using namespace cv; using namespace pcl; using namespace sem; namespace { #ifdef __WITH_PCL // test normally const string NAME_INPUT_POINT_CLOUD_SRC = "src"; ///< key to source cloud const string NAME_INPUT_POINT_CLOUD_TARGET = "target"; ///< key to target cloud const string NAME_OUTPUT_SCORE = "score"; ///< key to fitness score const string NAME_OUTPUT_CONVERGENCE = "c"; ///< key to convergence result const string NAME_OUTPUT_TRANSFORMATION = "transf"; ///< key to optional final tansformation class ICPInitTest : public ::testing::Test { protected: virtual void SetUp() { cfg_ = LayerConfig(); cfg_.Params(params_); io_names_ = LayerIONames(); io_names_.Input(ICP::KEY_INPUT_POINT_CLOUD_SRC , NAME_INPUT_POINT_CLOUD_SRC); io_names_.Input(ICP::KEY_INPUT_POINT_CLOUD_TARGET, NAME_INPUT_POINT_CLOUD_TARGET); io_names_.Output(ICP::KEY_OUTPUT_CONVERGENCE , NAME_OUTPUT_CONVERGENCE); io_names_.Output(ICP::KEY_OUTPUT_SCORE , NAME_OUTPUT_SCORE); io_names_.Output(ICP::KEY_OUTPUT_TRANSFORMATION , NAME_OUTPUT_TRANSFORMATION); } virtual void TearDown() { params_.clear(); } // members PTree params_; LayerConfig cfg_; LayerIONames io_names_; }; TEST_F(ICPInitTest, Constructor) { EXPECT_NO_THROW(ICP to); EXPECT_NO_THROW(ICP to(cfg_)); } TEST_F(ICPInitTest, MissingParams) { cfg_.Params(PTree()); EXPECT_NO_THROW(ICP to(cfg_)); ICP to; EXPECT_NO_THROW(to.Reset(cfg_)); EXPECT_NO_THROW(to.Reconfigure(cfg_)); } TEST_F(ICPInitTest, MissingRequiredIONames) { shared_ptr<base_Layer> to_ptr(new ICP()); // pointer to test object EXPECT_THROW(to_ptr->IONames(LayerIONames()), ExceptionKeyError); map<string, pair<bool, string> > io_pairs; // false for input, true for output io_pairs[ICP::KEY_INPUT_POINT_CLOUD_SRC ] = make_pair(0, NAME_INPUT_POINT_CLOUD_SRC); io_pairs[ICP::KEY_INPUT_POINT_CLOUD_TARGET ] = make_pair(0, NAME_INPUT_POINT_CLOUD_TARGET); io_pairs[ICP::KEY_OUTPUT_CONVERGENCE ] = make_pair(1, NAME_OUTPUT_CONVERGENCE); io_pairs[ICP::KEY_OUTPUT_SCORE ] = make_pair(1, NAME_OUTPUT_SCORE); io_pairs[ICP::KEY_OUTPUT_TRANSFORMATION ] = make_pair(1, NAME_OUTPUT_TRANSFORMATION); ValidateRequiredIONames(io_pairs, to_ptr); } TEST_F(ICPInitTest, CreateWithFactory) { shared_ptr<base_Layer> to_ptr = LayerFactory::CreateShared("ICP", cfg_, io_names_); EXPECT_TRUE(bool(to_ptr)); } /** * @brief Test the live methods assuming a sucessful initialization */ class ICPTest : public ICPInitTest { protected: virtual void SetUp() { ICPInitTest::SetUp(); to_ = LayerFactory::CreateShared("ICP", cfg_, io_names_); cloud_in_.reset(new PointCloudXYZ); // Fill in the CloudIn data cloud_in_->width = 5; cloud_in_->height = 1; cloud_in_->is_dense = false; cloud_in_->points.resize(cloud_in_->width * cloud_in_->height); for(size_t i=0; i < cloud_in_->points.size(); ++i) { cloud_in_->points[i].x = 1024 * rand () / (RAND_MAX + 1.0f); cloud_in_->points[i].y = 1024 * rand () / (RAND_MAX + 1.0f); cloud_in_->points[i].z = 1024 * rand () / (RAND_MAX + 1.0f); } // target.x = in.x + constant cloud_target_.reset(new PointCloudXYZ); *cloud_target_ = *cloud_in_; for(size_t i=0; i < cloud_in_->points.size (); ++i) { cloud_target_->points[i].x += 0.7f; } sig_.Append(NAME_INPUT_POINT_CLOUD_SRC, PointCloud2Mat(cloud_in_)); sig_.Append(NAME_INPUT_POINT_CLOUD_TARGET, PointCloud2Mat(cloud_target_)); } virtual void TearDown() { ICPInitTest::TearDown(); } shared_ptr<base_Layer> to_; ///< pointer to test object Signal sig_; PointCloudXYZ::Ptr cloud_in_; PointCloudXYZ::Ptr cloud_target_; }; TEST_F(ICPTest, ActivateAndResponse) { to_->Activate(sig_); EXPECT_FALSE(sig_.Exists(NAME_OUTPUT_CONVERGENCE)); EXPECT_FALSE(sig_.Exists(NAME_OUTPUT_SCORE)); EXPECT_FALSE(sig_.Exists(NAME_OUTPUT_TRANSFORMATION)); to_->Response(sig_); EXPECT_TRUE(sig_.Exists(NAME_OUTPUT_CONVERGENCE)); EXPECT_TRUE(sig_.Exists(NAME_OUTPUT_SCORE)); EXPECT_TRUE(sig_.Exists(NAME_OUTPUT_TRANSFORMATION)); // check response // convergence: ASSERT_TRUE(icp.hasConverged()) << "this test needs to converge"; EXPECT_MAT_DIMS_EQ(sig_.MostRecent(NAME_OUTPUT_CONVERGENCE), Size2i(1, 1)) << "Expecting Mat of single element for convergence."; EXPECT_EQ(sig_.MostRecent(NAME_OUTPUT_CONVERGENCE).at<float>(0)==1.f, icp.hasConverged()) << "Mismatched convergence."; // fitness score EXPECT_MAT_DIMS_EQ(sig_.MostRecent(NAME_OUTPUT_SCORE), Size2i(1, 1)) << "Expecting Mat of single element for fitness score."; EXPECT_FLOAT_EQ(sig_.MostRecent(NAME_OUTPUT_SCORE).at<float>(0), static_cast<float>(icp.getFitnessScore())) << "Mismatched fitness score."; // final transformation matrix estimated by registration method Mat1f transformation_expected; eigen2cv(icp.getFinalTransformation(), transformation_expected); Mat1f transformation_actual = sig_.MostRecent(NAME_OUTPUT_TRANSFORMATION); EXPECT_MAT_EQ(transformation_expected, transformation_actual) << "Mismatch in final transformation"; // more detailed check of transformation matrix EXPECT_EQ(transformation_actual.rows, transformation_actual.cols) << "Expecting square matrix"; for(int i=0; i<transformation_actual.rows; i++) { EXPECT_FLOAT_EQ(1.f, transformation_actual(i, i)) << "Expecting diagonal of 1's"; } } #else // __WITH_PCL #warning "Skipping building ICP layer unittests" #endif // __WITH_PCL } // annonymous namespace for test fixtures <commit_msg>test ICP activation in a scenario where it would not converge<commit_after>#include "layers/icp.h" #include "pcl/registration/registration.h" #include "pcl/registration/icp.h" #include <Eigen/Dense> ///< to enable OpenCV's eigen2cv() #include <opencv2/core/eigen.hpp> ///< for eigen2cv(), preceeded be #include <Eigen/Dense> #include "core/exception.h" #include "core/layerconfig.h" #include "core/pcl_utils.h" #include "core/signal.h" #include "core/stl.h" #include "layers/layerfactory.h" #include "ts/ts.h" #include "ts/layer_assertions.h" using namespace std; using namespace cv; using namespace pcl; using namespace sem; namespace { #ifdef __WITH_PCL // test normally const string NAME_INPUT_POINT_CLOUD_SRC = "src"; ///< key to source cloud const string NAME_INPUT_POINT_CLOUD_TARGET = "target"; ///< key to target cloud const string NAME_OUTPUT_SCORE = "score"; ///< key to fitness score const string NAME_OUTPUT_CONVERGENCE = "c"; ///< key to convergence result const string NAME_OUTPUT_TRANSFORMATION = "transf"; ///< key to optional final tansformation class ICPInitTest : public ::testing::Test { protected: virtual void SetUp() { cfg_ = LayerConfig(); cfg_.Params(params_); io_names_ = LayerIONames(); io_names_.Input(ICP::KEY_INPUT_POINT_CLOUD_SRC , NAME_INPUT_POINT_CLOUD_SRC); io_names_.Input(ICP::KEY_INPUT_POINT_CLOUD_TARGET, NAME_INPUT_POINT_CLOUD_TARGET); io_names_.Output(ICP::KEY_OUTPUT_CONVERGENCE , NAME_OUTPUT_CONVERGENCE); io_names_.Output(ICP::KEY_OUTPUT_SCORE , NAME_OUTPUT_SCORE); io_names_.Output(ICP::KEY_OUTPUT_TRANSFORMATION , NAME_OUTPUT_TRANSFORMATION); } virtual void TearDown() { params_.clear(); } // members PTree params_; LayerConfig cfg_; LayerIONames io_names_; }; TEST_F(ICPInitTest, Constructor) { EXPECT_NO_THROW(ICP to); EXPECT_NO_THROW(ICP to(cfg_)); } TEST_F(ICPInitTest, MissingParams) { cfg_.Params(PTree()); EXPECT_NO_THROW(ICP to(cfg_)); ICP to; EXPECT_NO_THROW(to.Reset(cfg_)); EXPECT_NO_THROW(to.Reconfigure(cfg_)); } TEST_F(ICPInitTest, MissingRequiredIONames) { shared_ptr<base_Layer> to_ptr(new ICP()); // pointer to test object EXPECT_THROW(to_ptr->IONames(LayerIONames()), ExceptionKeyError); map<string, pair<bool, string> > io_pairs; // false for input, true for output io_pairs[ICP::KEY_INPUT_POINT_CLOUD_SRC ] = make_pair(0, NAME_INPUT_POINT_CLOUD_SRC); io_pairs[ICP::KEY_INPUT_POINT_CLOUD_TARGET ] = make_pair(0, NAME_INPUT_POINT_CLOUD_TARGET); io_pairs[ICP::KEY_OUTPUT_CONVERGENCE ] = make_pair(1, NAME_OUTPUT_CONVERGENCE); io_pairs[ICP::KEY_OUTPUT_SCORE ] = make_pair(1, NAME_OUTPUT_SCORE); io_pairs[ICP::KEY_OUTPUT_TRANSFORMATION ] = make_pair(1, NAME_OUTPUT_TRANSFORMATION); ValidateRequiredIONames(io_pairs, to_ptr); } TEST_F(ICPInitTest, CreateWithFactory) { shared_ptr<base_Layer> to_ptr = LayerFactory::CreateShared("ICP", cfg_, io_names_); EXPECT_TRUE(bool(to_ptr)); } /** * @brief Test the live methods assuming a sucessful initialization */ class ICPTest : public ICPInitTest { protected: virtual void SetUp() { ICPInitTest::SetUp(); to_ = LayerFactory::CreateShared("ICP", cfg_, io_names_); cloud_in_.reset(new PointCloudXYZ); // Fill in the CloudIn data cloud_in_->width = 5; cloud_in_->height = 1; cloud_in_->is_dense = false; cloud_in_->points.resize(cloud_in_->width * cloud_in_->height); for(size_t i=0; i < cloud_in_->points.size(); ++i) { cloud_in_->points[i].x = 1024 * rand () / (RAND_MAX + 1.0f); cloud_in_->points[i].y = 1024 * rand () / (RAND_MAX + 1.0f); cloud_in_->points[i].z = 1024 * rand () / (RAND_MAX + 1.0f); } // target.x = in.x + constant cloud_target_.reset(new PointCloudXYZ); *cloud_target_ = *cloud_in_; for(size_t i=0; i < cloud_in_->points.size (); ++i) { cloud_target_->points[i].x += 0.7f; } sig_.Append(NAME_INPUT_POINT_CLOUD_SRC, PointCloud2Mat(cloud_in_)); sig_.Append(NAME_INPUT_POINT_CLOUD_TARGET, PointCloud2Mat(cloud_target_)); } virtual void TearDown() { ICPInitTest::TearDown(); } shared_ptr<base_Layer> to_; ///< pointer to test object Signal sig_; PointCloudXYZ::Ptr cloud_in_; PointCloudXYZ::Ptr cloud_target_; }; /** * @brief Compare Layer ICP with PCL's ICP routines */ TEST_F(ICPTest, ActivateAndResponse) { IterativeClosestPoint<PointXYZ, PointXYZ> icp; icp.setInputSource(cloud_in_); icp.setInputTarget(cloud_target_); PointCloudXYZ fin; icp.align(fin); to_->Activate(sig_); EXPECT_FALSE(sig_.Exists(NAME_OUTPUT_CONVERGENCE)); EXPECT_FALSE(sig_.Exists(NAME_OUTPUT_SCORE)); EXPECT_FALSE(sig_.Exists(NAME_OUTPUT_TRANSFORMATION)); to_->Response(sig_); EXPECT_TRUE(sig_.Exists(NAME_OUTPUT_CONVERGENCE)); EXPECT_TRUE(sig_.Exists(NAME_OUTPUT_SCORE)); EXPECT_TRUE(sig_.Exists(NAME_OUTPUT_TRANSFORMATION)); // check response // convergence: ASSERT_TRUE(icp.hasConverged()) << "this test needs to converge"; EXPECT_MAT_DIMS_EQ(sig_.MostRecent(NAME_OUTPUT_CONVERGENCE), Size2i(1, 1)) << "Expecting Mat of single element for convergence."; EXPECT_EQ(sig_.MostRecent(NAME_OUTPUT_CONVERGENCE).at<float>(0)==1.f, icp.hasConverged()) << "Mismatched convergence."; // fitness score EXPECT_MAT_DIMS_EQ(sig_.MostRecent(NAME_OUTPUT_SCORE), Size2i(1, 1)) << "Expecting Mat of single element for fitness score."; EXPECT_FLOAT_EQ(sig_.MostRecent(NAME_OUTPUT_SCORE).at<float>(0), static_cast<float>(icp.getFitnessScore())) << "Mismatched fitness score."; // final transformation matrix estimated by registration method Mat1f transformation_expected; eigen2cv(icp.getFinalTransformation(), transformation_expected); Mat1f transformation_actual = sig_.MostRecent(NAME_OUTPUT_TRANSFORMATION); EXPECT_MAT_EQ(transformation_expected, transformation_actual) << "Mismatch in final transformation"; // more detailed check of transformation matrix EXPECT_EQ(transformation_actual.rows, transformation_actual.cols) << "Expecting square matrix"; for(int i=0; i<transformation_actual.rows; i++) { EXPECT_FLOAT_EQ(1.f, transformation_actual(i, i)) << "Expecting diagonal of 1's"; } } /** * @brief Pick a scenario that would not converge */ TEST_F(ICPTest, NoConvergence) { Mat1f in = Mat1f::zeros(1, 3); Mat1f target = in.clone(); sig_.Append(NAME_INPUT_POINT_CLOUD_SRC, in); sig_.Append(NAME_INPUT_POINT_CLOUD_TARGET, target); to_->Activate(sig_); to_->Response(sig_); EXPECT_TRUE(sig_.Exists(NAME_OUTPUT_CONVERGENCE)); EXPECT_TRUE(sig_.Exists(NAME_OUTPUT_SCORE)); EXPECT_TRUE(sig_.Exists(NAME_OUTPUT_TRANSFORMATION)); // check response // convergence: EXPECT_FALSE(sig_.MostRecent(NAME_OUTPUT_CONVERGENCE).at<float>(0)==1.f) << "Not expecting convergence."; // fitness score EXPECT_MAT_EQ(sig_.MostRecent(NAME_OUTPUT_SCORE), Mat1f(1, 1, 0.f)) << "Expecting zero score."; // more detailed check of transformation matrix, expecting a diagonal matrix Mat1f diagonal(4, 4, 0.f); for(int i=0; i<diagonal.rows; i++) { diagonal(i, i) = 1.f; } EXPECT_MAT_EQ(sig_.MostRecent(NAME_OUTPUT_TRANSFORMATION), diagonal) << "Expecting diagonal matrix when convergence fails."; } #else // __WITH_PCL #warning "Skipping building ICP layer unittests" #endif // __WITH_PCL } // annonymous namespace for test fixtures <|endoftext|>
<commit_before>/* * Copyright (C) 2008 Barracuda Networks, Inc. * * 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 WITHANY 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 "devices.h" #include <QSize> #include <QStringList> #include <gst/gst.h> #include <gst/interfaces/propertyprobe.h> #include "deviceenum/deviceenum.h" namespace PsiMedia { class GstDeviceProbeValue { public: QString id; QString name; }; static QList<GstDeviceProbeValue> device_probe(GstElement *e) { GObjectClass *klass = G_OBJECT_GET_CLASS(e); if(!g_object_class_find_property(klass, "device") || !GST_IS_PROPERTY_PROBE(e)) return QList<GstDeviceProbeValue>(); GstPropertyProbe *probe = GST_PROPERTY_PROBE(e); if(!probe) return QList<GstDeviceProbeValue>(); const GParamSpec *pspec = gst_property_probe_get_property(probe, "device"); if(!pspec) return QList<GstDeviceProbeValue>(); QList<GstDeviceProbeValue> out; GValueArray *list = gst_property_probe_probe_and_get_values(probe, pspec); if(list) { for(int n = 0; n < (int)list->n_values; ++n) { GValue *i = g_value_array_get_nth(list, n); // FIXME: "device" isn't always a string gchar *name; g_object_set(G_OBJECT(e), "device", g_value_get_string(i), NULL); g_object_get(G_OBJECT(e), "device-name", &name, NULL); GstDeviceProbeValue dev; dev.id = QString::fromUtf8(g_value_get_string(i)); dev.name = QString::fromUtf8(name); g_free(name); out += dev; } g_value_array_free(list); } return out; } static bool element_should_use_probe(const QString &element_name) { // we can enumerate devices in two ways. one is via gst propery // probing and the other is through our own DeviceEnum code. // since gst property probing is "the future", we'll take a // probe-by-default approach, and only use DeviceEnum for specific // elements // these should use DeviceEnum if(element_name == "alsasrc" || element_name == "alsasink" || element_name == "v4lsrc" || element_name == "v4l2src" || element_name == "osxaudiosrc" || element_name == "osxaudiosink" || element_name == "directsoundsrc" || element_name == "directsoundsink" || element_name == "ksvideosrc") { return false; } // all else probe else return true; } static QList<DeviceEnum::Item> device_enum(const QString &driver, PDevice::Type type) { if(type == PDevice::AudioOut) return DeviceEnum::audioOutputItems(driver); else if(type == PDevice::AudioIn) return DeviceEnum::audioInputItems(driver); else // PDevice::VideoIn return DeviceEnum::videoInputItems(driver); } static QString id_part_escape(const QString &in) { QString out; for(int n = 0; n < in.length(); ++n) { if(in[n] == '\\') out += "\\\\"; else if(in[n] == ',') out += "\\c"; else out += in[n]; } return out; } static QString id_part_unescape(const QString &in) { QString out; for(int n = 0; n < in.length(); ++n) { if(in[n] == '\\') { if(n + 1 >= in.length()) return QString(); ++n; if(in[n] == '\\') out += '\\'; else if(in[n] == 'c') out += ','; else return QString(); } else out += in[n]; } return out; } static QString resolution_to_string(const QSize &size) { return QString::number(size.width()) + 'x' + QString::number(size.height()); } static QSize string_to_resolution(const QString &in) { int at = in.indexOf('x'); if(at == -1) return QSize(); QString ws = in.mid(0, at); QString hs = in.mid(at + 1); bool ok; int w = ws.toInt(&ok); if(!ok) return QSize(); int h = hs.toInt(&ok); if(!ok) return QSize(); return QSize(w, h); } static QString encode_id(const QStringList &in) { QStringList list = in; for(int n = 0; n < list.count(); ++n) list[n] = id_part_escape(list[n]); return list.join(","); } static QStringList decode_id(const QString &in) { QStringList list = in.split(','); for(int n = 0; n < list.count(); ++n) list[n] = id_part_unescape(list[n]); return list; } static QString element_name_for_driver(const QString &driver, PDevice::Type type) { QString element_name; if(driver == "alsa") { if(type == PDevice::AudioOut) element_name = "alsasink"; else if(type == PDevice::AudioIn) element_name = "alsasrc"; } else if(driver == "osxaudio") { if(type == PDevice::AudioOut) element_name = "osxaudiosink"; else if(type == PDevice::AudioIn) element_name = "osxaudiosrc"; } else if(driver == "osxvideo") { if(type == PDevice::VideoIn) element_name = "osxvideosrc"; } else if(driver == "v4l") { if(type == PDevice::VideoIn) element_name = "v4lsrc"; } else if(driver == "v4l2") { if(type == PDevice::VideoIn) element_name = "v4l2src"; } else if(driver == "directsound") { if(type == PDevice::AudioOut) element_name = "directsoundsink"; else if(type == PDevice::AudioIn) element_name = "directsoundsrc"; } else if(driver == "winks") { if(type == PDevice::VideoIn) element_name = "ksvideosrc"; } return element_name; } // check to see that the necessary sources/sinks are available static QStringList check_supported_drivers(const QStringList &drivers, PDevice::Type type) { QStringList out; foreach(const QString &driver, drivers) { QString element_name = element_name_for_driver(driver, type); if(element_name.isEmpty()) continue; GstElement *e = gst_element_factory_make(element_name.toLatin1().data(), NULL); if(e) { out += driver; g_object_unref(G_OBJECT(e)); } } return out; } static GstElement *make_element_with_device(const QString &element_name, const QString &device_id) { GstElement *e = gst_element_factory_make(element_name.toLatin1().data(), NULL); if(!e) return 0; if(!device_id.isEmpty()) { // FIXME: is there a better way to determine if "device" is a string or int? if(element_name == "osxaudiosrc" || element_name == "osxaudiosink") g_object_set(G_OBJECT(e), "device", device_id.toInt(), NULL); else g_object_set(G_OBJECT(e), "device", device_id.toLatin1().data(), NULL); } return e; } static bool test_video(const QString &element_name, const QString &device_id) { GstElement *e = make_element_with_device(element_name, device_id); if(!e) return false; gst_element_set_state(e, GST_STATE_PAUSED); int ret = gst_element_get_state(e, NULL, NULL, GST_CLOCK_TIME_NONE); // 'ret' has our answer, so we can free up the element now gst_element_set_state(e, GST_STATE_NULL); gst_element_get_state(e, NULL, NULL, GST_CLOCK_TIME_NONE); g_object_unref(G_OBJECT(e)); if(ret != GST_STATE_CHANGE_SUCCESS && ret != GST_STATE_CHANGE_NO_PREROLL) return false; return true; } // for elements that we can't enumerate devices for, we need a way to ensure // that at least the default device works // FIXME: why do we have both this function and test_video() ? static bool test_element(const QString &element_name) { GstElement *e = gst_element_factory_make(element_name.toLatin1().data(), NULL); if(!e) return 0; gst_element_set_state(e, GST_STATE_READY); int ret = gst_element_get_state(e, NULL, NULL, GST_CLOCK_TIME_NONE); gst_element_set_state(e, GST_STATE_NULL); gst_element_get_state(e, NULL, NULL, GST_CLOCK_TIME_NONE); g_object_unref(G_OBJECT(e)); if(ret != GST_STATE_CHANGE_SUCCESS) return false; return true; } static QList<GstDevice> devices_for_drivers(const QStringList &drivers, PDevice::Type type) { QList<GstDevice> out; QStringList supportedDrivers = check_supported_drivers(drivers, type); foreach(const QString &driver, supportedDrivers) { QString element_name = element_name_for_driver(driver, type); if(element_should_use_probe(element_name)) { GstElement *e = gst_element_factory_make(element_name.toLatin1().data(), NULL); QList<GstDeviceProbeValue> list = device_probe(e); g_object_unref(G_OBJECT(e)); bool first = true; foreach(const GstDeviceProbeValue &i, list) { GstDevice dev; dev.name = i.name + QString(" (%1)").arg(driver); dev.isDefault = first; QStringList parts; parts += driver; parts += i.id; dev.id = encode_id(parts); out += dev; first = false; } } else { QList<DeviceEnum::Item> list = device_enum(driver, type); bool first = true; foreach(const DeviceEnum::Item &i, list) { if(type == PDevice::VideoIn && (element_name == "v4lsrc" || element_name == "v4l2src")) { if(!test_video(element_name, i.id)) continue; } else if(element_name == "directsoundsrc" || element_name == "directsoundsink" || element_name == "ksvideosrc" || element_name == "osxvideosrc") { if(!test_element(element_name)) continue; } GstDevice dev; dev.name = i.name + QString(" (%1)").arg(i.driver); dev.isDefault = first; QStringList parts; parts += i.driver; parts += i.id; if(!i.explicitCaptureSize.isNull()) parts += resolution_to_string(i.explicitCaptureSize); dev.id = encode_id(parts); out += dev; first = false; } } } return out; } QList<GstDevice> devices_list(PDevice::Type type) { QStringList drivers; if(type == PDevice::AudioOut) { drivers << "alsa" << "osxaudio" << "directsound"; } else if(type == PDevice::AudioIn) { drivers << "alsa" << "osxaudio" << "directsound"; } else // PDevice::VideoIn { drivers << "v4l" << "v4l2" << "osxvideo" << "winks"; } return devices_for_drivers(drivers, type); } GstElement *devices_makeElement(const QString &id, PDevice::Type type, QSize *captureSize) { QStringList parts = decode_id(id); if(parts.count() < 2) return 0; QString driver = parts[0]; QString device_id = parts[1]; QString element_name = element_name_for_driver(driver, type); if(element_name.isEmpty()) return 0; GstElement *e = make_element_with_device(element_name, device_id); if(!e) return 0; gst_element_set_state(e, GST_STATE_READY); int ret = gst_element_get_state(e, NULL, NULL, GST_CLOCK_TIME_NONE); if(ret != GST_STATE_CHANGE_SUCCESS) { g_object_unref(G_OBJECT(e)); return 0; } if(parts.count() >= 3 && captureSize) *captureSize = string_to_resolution(parts[2]); return e; } } <commit_msg>temporary workaround for v4l2src...<commit_after>/* * Copyright (C) 2008 Barracuda Networks, Inc. * * 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 WITHANY 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 "devices.h" #include <QSize> #include <QStringList> #include <gst/gst.h> #include <gst/interfaces/propertyprobe.h> #include "deviceenum/deviceenum.h" namespace PsiMedia { class GstDeviceProbeValue { public: QString id; QString name; }; static QList<GstDeviceProbeValue> device_probe(GstElement *e) { GObjectClass *klass = G_OBJECT_GET_CLASS(e); if(!g_object_class_find_property(klass, "device") || !GST_IS_PROPERTY_PROBE(e)) return QList<GstDeviceProbeValue>(); GstPropertyProbe *probe = GST_PROPERTY_PROBE(e); if(!probe) return QList<GstDeviceProbeValue>(); const GParamSpec *pspec = gst_property_probe_get_property(probe, "device"); if(!pspec) return QList<GstDeviceProbeValue>(); QList<GstDeviceProbeValue> out; GValueArray *list = gst_property_probe_probe_and_get_values(probe, pspec); if(list) { for(int n = 0; n < (int)list->n_values; ++n) { GValue *i = g_value_array_get_nth(list, n); // FIXME: "device" isn't always a string gchar *name; g_object_set(G_OBJECT(e), "device", g_value_get_string(i), NULL); g_object_get(G_OBJECT(e), "device-name", &name, NULL); GstDeviceProbeValue dev; dev.id = QString::fromUtf8(g_value_get_string(i)); dev.name = QString::fromUtf8(name); g_free(name); out += dev; } g_value_array_free(list); } return out; } static bool element_should_use_probe(const QString &element_name) { // we can enumerate devices in two ways. one is via gst propery // probing and the other is through our own DeviceEnum code. // since gst property probing is "the future", we'll take a // probe-by-default approach, and only use DeviceEnum for specific // elements // these should use DeviceEnum if(element_name == "alsasrc" || element_name == "alsasink" || element_name == "v4lsrc" || element_name == "v4l2src" || element_name == "osxaudiosrc" || element_name == "osxaudiosink" || element_name == "directsoundsrc" || element_name == "directsoundsink" || element_name == "ksvideosrc") { return false; } // all else probe else return true; } static QList<DeviceEnum::Item> device_enum(const QString &driver, PDevice::Type type) { if(type == PDevice::AudioOut) return DeviceEnum::audioOutputItems(driver); else if(type == PDevice::AudioIn) return DeviceEnum::audioInputItems(driver); else // PDevice::VideoIn return DeviceEnum::videoInputItems(driver); } static QString id_part_escape(const QString &in) { QString out; for(int n = 0; n < in.length(); ++n) { if(in[n] == '\\') out += "\\\\"; else if(in[n] == ',') out += "\\c"; else out += in[n]; } return out; } static QString id_part_unescape(const QString &in) { QString out; for(int n = 0; n < in.length(); ++n) { if(in[n] == '\\') { if(n + 1 >= in.length()) return QString(); ++n; if(in[n] == '\\') out += '\\'; else if(in[n] == 'c') out += ','; else return QString(); } else out += in[n]; } return out; } static QString resolution_to_string(const QSize &size) { return QString::number(size.width()) + 'x' + QString::number(size.height()); } static QSize string_to_resolution(const QString &in) { int at = in.indexOf('x'); if(at == -1) return QSize(); QString ws = in.mid(0, at); QString hs = in.mid(at + 1); bool ok; int w = ws.toInt(&ok); if(!ok) return QSize(); int h = hs.toInt(&ok); if(!ok) return QSize(); return QSize(w, h); } static QString encode_id(const QStringList &in) { QStringList list = in; for(int n = 0; n < list.count(); ++n) list[n] = id_part_escape(list[n]); return list.join(","); } static QStringList decode_id(const QString &in) { QStringList list = in.split(','); for(int n = 0; n < list.count(); ++n) list[n] = id_part_unescape(list[n]); return list; } static QString element_name_for_driver(const QString &driver, PDevice::Type type) { QString element_name; if(driver == "alsa") { if(type == PDevice::AudioOut) element_name = "alsasink"; else if(type == PDevice::AudioIn) element_name = "alsasrc"; } else if(driver == "osxaudio") { if(type == PDevice::AudioOut) element_name = "osxaudiosink"; else if(type == PDevice::AudioIn) element_name = "osxaudiosrc"; } else if(driver == "osxvideo") { if(type == PDevice::VideoIn) element_name = "osxvideosrc"; } else if(driver == "v4l") { if(type == PDevice::VideoIn) element_name = "v4lsrc"; } else if(driver == "v4l2") { if(type == PDevice::VideoIn) element_name = "v4l2src"; } else if(driver == "directsound") { if(type == PDevice::AudioOut) element_name = "directsoundsink"; else if(type == PDevice::AudioIn) element_name = "directsoundsrc"; } else if(driver == "winks") { if(type == PDevice::VideoIn) element_name = "ksvideosrc"; } return element_name; } // check to see that the necessary sources/sinks are available static QStringList check_supported_drivers(const QStringList &drivers, PDevice::Type type) { QStringList out; foreach(const QString &driver, drivers) { QString element_name = element_name_for_driver(driver, type); if(element_name.isEmpty()) continue; GstElement *e = gst_element_factory_make(element_name.toLatin1().data(), NULL); if(e) { out += driver; g_object_unref(G_OBJECT(e)); } } return out; } static GstElement *make_element_with_device(const QString &element_name, const QString &device_id) { GstElement *e = gst_element_factory_make(element_name.toLatin1().data(), NULL); if(!e) return 0; if(!device_id.isEmpty()) { // FIXME: is there a better way to determine if "device" is a string or int? if(element_name == "osxaudiosrc" || element_name == "osxaudiosink") g_object_set(G_OBJECT(e), "device", device_id.toInt(), NULL); else g_object_set(G_OBJECT(e), "device", device_id.toLatin1().data(), NULL); } return e; } static bool test_video(const QString &element_name, const QString &device_id) { GstElement *e = make_element_with_device(element_name, device_id); if(!e) return false; gst_element_set_state(e, GST_STATE_PAUSED); int ret = gst_element_get_state(e, NULL, NULL, GST_CLOCK_TIME_NONE); // 'ret' has our answer, so we can free up the element now gst_element_set_state(e, GST_STATE_NULL); gst_element_get_state(e, NULL, NULL, GST_CLOCK_TIME_NONE); g_object_unref(G_OBJECT(e)); if(ret != GST_STATE_CHANGE_SUCCESS && ret != GST_STATE_CHANGE_NO_PREROLL) return false; return true; } // for elements that we can't enumerate devices for, we need a way to ensure // that at least the default device works // FIXME: why do we have both this function and test_video() ? static bool test_element(const QString &element_name) { GstElement *e = gst_element_factory_make(element_name.toLatin1().data(), NULL); if(!e) return 0; gst_element_set_state(e, GST_STATE_READY); int ret = gst_element_get_state(e, NULL, NULL, GST_CLOCK_TIME_NONE); gst_element_set_state(e, GST_STATE_NULL); gst_element_get_state(e, NULL, NULL, GST_CLOCK_TIME_NONE); g_object_unref(G_OBJECT(e)); if(ret != GST_STATE_CHANGE_SUCCESS) return false; return true; } static QList<GstDevice> devices_for_drivers(const QStringList &drivers, PDevice::Type type) { QList<GstDevice> out; QStringList supportedDrivers = check_supported_drivers(drivers, type); foreach(const QString &driver, supportedDrivers) { QString element_name = element_name_for_driver(driver, type); if(element_should_use_probe(element_name)) { GstElement *e = gst_element_factory_make(element_name.toLatin1().data(), NULL); QList<GstDeviceProbeValue> list = device_probe(e); g_object_unref(G_OBJECT(e)); bool first = true; foreach(const GstDeviceProbeValue &i, list) { GstDevice dev; dev.name = i.name + QString(" (%1)").arg(driver); dev.isDefault = first; QStringList parts; parts += driver; parts += i.id; dev.id = encode_id(parts); out += dev; first = false; } } else { QList<DeviceEnum::Item> list = device_enum(driver, type); bool first = true; foreach(const DeviceEnum::Item &i, list) { if(type == PDevice::VideoIn && (element_name == "v4lsrc" || element_name == "v4l2src")) { if(!test_video(element_name, i.id)) continue; } else if(element_name == "directsoundsrc" || element_name == "directsoundsink" || element_name == "ksvideosrc" || element_name == "osxvideosrc") { if(!test_element(element_name)) continue; } GstDevice dev; dev.name = i.name + QString(" (%1)").arg(i.driver); dev.isDefault = first; QStringList parts; parts += i.driver; parts += i.id; if(!i.explicitCaptureSize.isNull()) parts += resolution_to_string(i.explicitCaptureSize); dev.id = encode_id(parts); out += dev; first = false; } } } return out; } QList<GstDevice> devices_list(PDevice::Type type) { QStringList drivers; if(type == PDevice::AudioOut) { drivers << "alsa" << "osxaudio" << "directsound"; } else if(type == PDevice::AudioIn) { drivers << "alsa" << "osxaudio" << "directsound"; } else // PDevice::VideoIn { drivers << "v4l" << "v4l2" << "osxvideo" << "winks"; } return devices_for_drivers(drivers, type); } GstElement *devices_makeElement(const QString &id, PDevice::Type type, QSize *captureSize) { QStringList parts = decode_id(id); if(parts.count() < 2) return 0; QString driver = parts[0]; QString device_id = parts[1]; QString element_name = element_name_for_driver(driver, type); if(element_name.isEmpty()) return 0; GstElement *e = make_element_with_device(element_name, device_id); if(!e) return 0; // FIXME: we don't set v4l2src to the READY state because it may break // the element in jpeg mode. this is really a bug in gstreamer or // lower that should be fixed... if(element_name != "v4l2src") { gst_element_set_state(e, GST_STATE_READY); int ret = gst_element_get_state(e, NULL, NULL, GST_CLOCK_TIME_NONE); if(ret != GST_STATE_CHANGE_SUCCESS) { g_object_unref(G_OBJECT(e)); return 0; } } if(parts.count() >= 3 && captureSize) *captureSize = string_to_resolution(parts[2]); return e; } } <|endoftext|>
<commit_before>#ifndef OCTARINE_LANG #define OCTARINE_LANG // Table of contents // ## 00 Macro Definitions // ## 10 Includes // ## 20 Type declarations and typedefs // ## 30 Function declarations // ## 40 Type definitions // ## 50 Function definitions // ## 60 C API // ## 00 Macro Definitions #ifdef _WIN32 #define WINDOWS #ifdef _DEBUG #define DEBUG #endif #ifdef _WIN64 #define OCT64 #else #define OCT32 #endif #elif defined (__APPLE__) #define MACOSX #ifdef __LP64__ #define OCT64 #else #define OCT32 #endif #else #define LINUX #ifndef NDEBUG #define DEBUG #endif #ifdef __LP64__ #define OCT64 #else #define OCT32 #endif #endif #define True 1 #define False 0 // ## 10 Includes #ifdef WINDOWS #include <Windows.h> #else #include <inttypes.h> #include <pthread.h> #endif #include <unordered_map> #include <unordered_set> #include <vector> #include <algorithm> #include <mutex> namespace octarine { // ## 20 Type declarations and typedefs #ifdef WINDOWS typedef __int8 I8; typedef unsigned __int8 U8; typedef __int16 I16; typedef unsigned __int16 U16; typedef __int32 I32; typedef unsigned __int32 U32; typedef __int64 I64; typedef unsigned __int64 U64; #else typedef int8_t I8; typedef uint8_t U8; typedef int16_t I16; typedef uint16_t U16; typedef int32_t I32; typedef uint32_t U32; typedef int64_t I64; typedef uint64_t U64; #endif typedef float F32; typedef double F64; typedef U8 Bool; typedef I32 Char; #ifdef OCT64 typedef I64 Word; typedef U64 Uword; #else typedef I32 Word; typedef U32 Uword; #endif typedef void* Address; struct FunctionT; typedef FunctionT* Function; struct MemoryManagerT; typedef MemoryManagerT* MemoryManager; struct NamespaceT; typedef NamespaceT* Namespace; struct ObjectT; typedef ObjectT* Object; struct ReaderT; typedef ReaderT* Reader; struct RuntimeT; typedef RuntimeT* Runtime; struct StringT; typedef StringT* String; struct ThreadContextT; typedef ThreadContextT* ThreadContext; struct TypeT; typedef TypeT* Type; struct ExceptionT; typedef ExceptionT* Exception; // ## 30 Function declarations static MemoryManager createMemoryManager(); static void destroyMemoryManager(MemoryManager mm); static Object allocRaw(MemoryManager mm, Uword size); static Object alloc(ThreadContext tc, MemoryManager mm, Type t); static Namespace createNamespace(ThreadContext tc, String name); static Object bind(ThreadContext tc, Namespace ns, String name, Object obj); static Type getNamespaceType(Runtime rt); static Bool equals(ThreadContext tc, Namespace ns, Object obj); static Type getType(ThreadContext tc, Object obj); static Uword hash(ThreadContext tc, Object o); static Bool equals(ThreadContext tc, Object o1, Object o2); static String makeShared(ThreadContext tc, String s); static Namespace makeShared(ThreadContext tc, Namespace s); static Runtime createRuntime(); static void destroyRuntime(Runtime rt); static void registerFunction(ThreadContext tc, Namespace ns, Function f); static Object eval(ThreadContext tc, String source); static Object intern(ThreadContext tc, Object o); static String createString(ThreadContext tc, const char* cstr); static Uword hash(ThreadContext tc, String s); static Bool equals(ThreadContext tc, String s1, String s2); static ThreadContext createThreadContext(Runtime rt, MemoryManager mm, Namespace initialNs); static void destroyThreadContext(ThreadContext tc); static ThreadContext getThreadContext(); static Runtime getRuntime(ThreadContext tc); static MemoryManager getMemoryManager(ThreadContext tc); static Namespace getNamespace(ThreadContext tc); static Namespace setNamespace(ThreadContext tc, Namespace ns); static Exception createException(ThreadContext tc, String message); static String getMessage(ThreadContext tc, Exception e); // ## 40 Type definitions // STL Integration } namespace std { template <> struct hash<octarine::String> { size_t operator()(const octarine::String& s) const { return octarine::hash(octarine::getThreadContext(), s); } }; template<> struct equal_to<octarine::String> { bool operator()(const octarine::String& s1, const octarine::String& s2) const { return octarine::equals(octarine::getThreadContext(), s1, s2) == True ? true : false; } }; template<> struct hash<octarine::Object> { size_t operator()(const octarine::Object& o) const { return octarine::hash(octarine::getThreadContext(), o); } }; template<> struct equal_to<octarine::Object> { bool operator()(const octarine::Object& o1, const octarine::Object& o2) { return octarine::equals(octarine::getThreadContext(), o1, o2) == True ? true : false; } }; } namespace octarine { // Platform support class TLS { private: #ifdef WINDOWS DWORD threadLocalStorage; #elif defined (MACOSX) pthread_key_t threadLocalStorage; #else #endif public: TLS() { #ifdef WINDOWS threadLocalStorage = TlsAlloc(); #elif defined (MACOSX) pthread_key_create(&threadLocalStorage, nullptr); #else #endif } ~TLS() { #ifdef WINDOWS TlsFree(threadLocalStorage); #elif defined (MACOSX) pthread_key_delete(threadLocalStorage); #else #endif } void set(void* value) { #ifdef WINDOWS TlsSetValue(threadLocalStorage, value); #elif defined (MACOSX) pthread_setspecific(threadLocalStorage, value); #else #endif } void* get() { #ifdef WINDOWS return TlsGetValue(threadLocalStorage); #elif defined (MACOSX) return pthread_getspecific(threadLocalStorage); #else #endif } }; // Octarine types struct MemoryManagerT { Uword hello; }; struct NamespaceT { String name; }; struct StringT { Uword length; U8* utf8data; // Just use platform strings? }; struct BuiltInTypes { Type namespaceType; }; struct ThreadContextT { Runtime runtime; MemoryManager memoryManager; Namespace currentNs; }; struct RuntimeT { std::mutex namespaceMutex; std::unordered_map<String, Namespace> namespaces; std::mutex threadContextMutex; std::vector<ThreadContext> threadContexts; std::mutex internedObjectsMutex; std::unordered_set<Object> internedObjects; BuiltInTypes builtInTypes; }; // ## 50 Function definitions // Global thread local var for getting at the current thread context when it is impossible // to pass it along. For example when integrating with the STL or in callbacks from C code. static TLS tls; static MemoryManager createMemoryManager() { MemoryManager mm = new MemoryManagerT; return mm; } static void destroyMemoryManager(MemoryManager mm) { delete mm; } static Object allocRaw(MemoryManager mm, Uword size) { // TODO: allocate space for Object header as well and return pointer // to memory after the header. return (Object)::operator new(size); } static Object alloc(ThreadContext tc, MemoryManager mm, Type t) { return nullptr; } static Namespace createNamespace(ThreadContext tc, String name) { MemoryManager mm = getMemoryManager(tc); Runtime rt = getRuntime(tc); Namespace ns = (Namespace) allocRaw(mm, sizeof(NamespaceT)); ns->name = name; rt->namespaces[name] = ns; return makeShared(tc, ns); } static Object bind(ThreadContext tc, Namespace ns, String name, Object obj) { } static Type getNamespaceType(Runtime rt) { return rt->builtInTypes.namespaceType; } static Bool equals(ThreadContext tc, Namespace ns, Object obj) { } static Type getType(ThreadContext tc, Object obj) { } static Uword hash(ThreadContext tc, Object o) { } static Bool equals(ThreadContext tc, Object o1, Object o2) { } static String makeShared(ThreadContext tc, String s) { } static Namespace makeShared(ThreadContext tc, Namespace s) { return nullptr; } static Runtime createRuntime() { Runtime rt = new RuntimeT; // Create main thread context, with its own memory manager ThreadContext mainTc = createThreadContext(rt, createMemoryManager(), nullptr); rt->threadContexts.push_back(mainTc); // Create main namespace setNamespace(mainTc, createNamespace(mainTc, createString(mainTc, "octarine"))); return rt; } static void destroyRuntime(Runtime rt) { std::for_each(rt->threadContexts.begin(), rt->threadContexts.end(), destroyThreadContext); delete rt; } static void registerFunction(ThreadContext tc, Namespace ns, Function f) { } static Object eval(ThreadContext tc, String source) { } static Object intern(ThreadContext tc, Object o) { Runtime rt = getRuntime(tc); std::lock_guard<std::mutex> lock(rt->internedObjectsMutex); std::unordered_set<Object>::const_iterator i = rt->internedObjects.find(o); if (i == rt->internedObjects.end()) { // Not found, copy to global memory and insert. return nullptr; } else { return *i; } } static String createString(ThreadContext tc, const char* cstr) { return nullptr; } static Uword hash(ThreadContext tc, String s) { return 0; } static Bool equals(ThreadContext tc, String s1, String s2) { return False; } static ThreadContext createThreadContext(Runtime rt, MemoryManager mm, Namespace initialNs) { ThreadContext tc = (ThreadContext) allocRaw(mm, sizeof(ThreadContextT)); tc->runtime = rt; tc->memoryManager = mm; tc->currentNs = initialNs; tls.set(tc); return tc; } static void destroyThreadContext(ThreadContext tc) { tls.set(nullptr); destroyMemoryManager(tc->memoryManager); } static ThreadContext getThreadContext() { return (ThreadContext) tls.get(); } static Runtime getRuntime(ThreadContext tc) { return tc->runtime; } static MemoryManager getMemoryManager(ThreadContext tc) { return tc->memoryManager; } static Namespace getNamespace(ThreadContext tc) { return tc->currentNs; } static Namespace setNamespace(ThreadContext tc, Namespace ns) { Namespace old = tc->currentNs; tc->currentNs = ns; return old; } static Exception createException(ThreadContext tc, String message) { } static String getMessage(ThreadContext tc, Exception e) { } } // ## 60 C API #endif <commit_msg>add more code<commit_after>#ifndef OCTARINE_LANG #define OCTARINE_LANG // Table of contents // ## 00 Macro Definitions // ## 10 Includes // ## 20 Type declarations and typedefs // ## 30 Function declarations // ## 40 Type definitions // ## 50 Function definitions // ## 60 C API // ## 00 Macro Definitions #ifdef _WIN32 #define WINDOWS #ifdef _DEBUG #define DEBUG #endif #ifdef _WIN64 #define OCT64 #else #define OCT32 #endif #elif defined (__APPLE__) #define MACOSX #ifdef __LP64__ #define OCT64 #else #define OCT32 #endif #else #define LINUX #ifndef NDEBUG #define DEBUG #endif #ifdef __LP64__ #define OCT64 #else #define OCT32 #endif #endif #define True 1 #define False 0 // ## 10 Includes #ifdef WINDOWS #include <Windows.h> #else #include <inttypes.h> #include <pthread.h> #endif #include <unordered_map> #include <unordered_set> #include <vector> #include <algorithm> #include <mutex> namespace octarine { // ## 20 Type declarations and typedefs #ifdef WINDOWS typedef __int8 I8; typedef unsigned __int8 U8; typedef __int16 I16; typedef unsigned __int16 U16; typedef __int32 I32; typedef unsigned __int32 U32; typedef __int64 I64; typedef unsigned __int64 U64; #else typedef int8_t I8; typedef uint8_t U8; typedef int16_t I16; typedef uint16_t U16; typedef int32_t I32; typedef uint32_t U32; typedef int64_t I64; typedef uint64_t U64; #endif typedef float F32; typedef double F64; typedef U8 Bool; typedef I32 Char; #ifdef OCT64 typedef I64 Word; typedef U64 Uword; #else typedef I32 Word; typedef U32 Uword; #endif typedef void* Address; struct FunctionT; typedef FunctionT* Function; struct SharedMemoryManagerT; typedef SharedMemoryManagerT* SharedMemoryManager; struct ThreadMemoryManagerT; typedef ThreadMemoryManagerT* ThreadMemoryManager; struct NamespaceT; typedef NamespaceT* Namespace; struct ObjectT; typedef ObjectT* Object; struct ReaderT; typedef ReaderT* Reader; struct RuntimeT; typedef RuntimeT* Runtime; struct StringT; typedef StringT* String; struct ThreadContextT; typedef ThreadContextT* ThreadContext; struct TypeT; typedef TypeT* Type; struct ExceptionT; typedef ExceptionT* Exception; // ## 30 Function declarations static Uword getSize(ThreadContext tc, Type t); static SharedMemoryManager createSharedMemoryManager(); static void destroySharedMemoryManager(SharedMemoryManager mm); static ThreadMemoryManager createThreadMemoryManager(); static void destroyThreadMemoryManager(ThreadMemoryManager mm); static Object allocRaw(ThreadMemoryManager mm, Uword size); static Object alloc(ThreadContext tc, ThreadMemoryManager mm, Type t); static Object allocRaw(SharedMemoryManager mm, Uword size); static Object alloc(ThreadContext tc, SharedMemoryManager mm, Type t); static Namespace createNamespace(ThreadContext tc, String name); static Object bind(ThreadContext tc, Namespace ns, String name, Object obj); static Type getNamespaceType(Runtime rt); static Bool equals(ThreadContext tc, Namespace ns, Object obj); static Type getType(ThreadContext tc, Object obj); static Uword hash(ThreadContext tc, Object o); static Bool equals(ThreadContext tc, Object o1, Object o2); static String makeShared(ThreadContext tc, String s); static Namespace makeShared(ThreadContext tc, Namespace s); static Runtime createRuntime(); static void destroyRuntime(Runtime rt); static void registerFunction(ThreadContext tc, Namespace ns, Function f); static Object eval(ThreadContext tc, String source); static Object intern(ThreadContext tc, Object o); static String createString(ThreadContext tc, const char* cstr); static Uword hash(ThreadContext tc, String s); static Bool equals(ThreadContext tc, String s1, String s2); static ThreadContext createThreadContext(Runtime rt, ThreadMemoryManager mm, Namespace initialNs); static void destroyThreadContext(ThreadContext tc); static ThreadContext getThreadContext(); static Runtime getRuntime(ThreadContext tc); static ThreadMemoryManager getThreadMemoryManager(ThreadContext tc); static Namespace getNamespace(ThreadContext tc); static Namespace setNamespace(ThreadContext tc, Namespace ns); static Exception createException(ThreadContext tc, String message); static String getMessage(ThreadContext tc, Exception e); // ## 40 Type definitions // STL Integration } namespace std { template <> struct hash<octarine::String> { size_t operator()(const octarine::String& s) const { return octarine::hash(octarine::getThreadContext(), s); } }; template<> struct equal_to<octarine::String> { bool operator()(const octarine::String& s1, const octarine::String& s2) const { return octarine::equals(octarine::getThreadContext(), s1, s2) == True ? true : false; } }; template<> struct hash<octarine::Object> { size_t operator()(const octarine::Object& o) const { return octarine::hash(octarine::getThreadContext(), o); } }; template<> struct equal_to<octarine::Object> { bool operator()(const octarine::Object& o1, const octarine::Object& o2) { return octarine::equals(octarine::getThreadContext(), o1, o2) == True ? true : false; } }; } namespace octarine { // Platform support class TLS { private: #ifdef WINDOWS DWORD threadLocalStorage; #elif defined (MACOSX) pthread_key_t threadLocalStorage; #else #endif public: TLS() { #ifdef WINDOWS threadLocalStorage = TlsAlloc(); #elif defined (MACOSX) pthread_key_create(&threadLocalStorage, nullptr); #else #endif } ~TLS() { #ifdef WINDOWS TlsFree(threadLocalStorage); #elif defined (MACOSX) pthread_key_delete(threadLocalStorage); #else #endif } void set(void* value) { #ifdef WINDOWS TlsSetValue(threadLocalStorage, value); #elif defined (MACOSX) pthread_setspecific(threadLocalStorage, value); #else #endif } void* get() { #ifdef WINDOWS return TlsGetValue(threadLocalStorage); #elif defined (MACOSX) return pthread_getspecific(threadLocalStorage); #else #endif } }; // Octarine types struct TypeT { Uword size; }; struct ObjectHeader { Type type; U8 object[0]; }; struct SharedMemoryManagerT { Uword hello; }; struct ThreadMemoryManagerT { Uword hello; }; struct NamespaceT { String name; }; struct StringT { Uword length; U8* utf8data; // Just use platform strings? }; struct BuiltInTypes { Type namespaceType; }; struct ThreadContextT { Runtime runtime; ThreadMemoryManager ThreadMemoryManager; Namespace currentNs; }; struct RuntimeT { SharedMemoryManager SharedMemoryManager; std::mutex namespaceMutex; std::unordered_map<String, Namespace> namespaces; std::mutex threadContextMutex; std::vector<ThreadContext> threadContexts; std::mutex internedObjectsMutex; std::unordered_set<Object> internedObjects; BuiltInTypes builtInTypes; }; // ## 50 Function definitions // Global thread local var for getting at the current thread context when it is impossible // to pass it along. For example when integrating with the STL or in callbacks from C code. static TLS tls; static Uword getSize(ThreadContext tc, Type t) { return t->size; } static SharedMemoryManager createSharedMemoryManager() { SharedMemoryManager mm = new SharedMemoryManagerT; return mm; } static void destroySharedMemoryManager(SharedMemoryManager mm) { delete mm; } static ThreadMemoryManager createThreadMemoryManager() { ThreadMemoryManager mm = new ThreadMemoryManagerT; return mm; } static void destroyThreadMemoryManager(ThreadMemoryManager mm) { delete mm; } static Object allocRaw(SharedMemoryManager mm, Uword size) { Uword allocSize = sizeof(ObjectHeader) + size; ObjectHeader* oh = (ObjectHeader*)::operator new(allocSize); oh->type = nullptr; return (Object) &oh->object; } static Object alloc(ThreadContext tc, SharedMemoryManager mm, Type t) { Uword allocSize = sizeof(ObjectHeader) + getSize(tc, t); ObjectHeader* oh = (ObjectHeader*)::operator new(allocSize); oh->type = t; return (Object) &oh->object; } static Object allocRaw(ThreadMemoryManager mm, Uword size) { Uword allocSize = sizeof(ObjectHeader) + size; ObjectHeader* oh = (ObjectHeader*)::operator new(allocSize); oh->type = nullptr; return (Object) &oh->object; } static Object alloc(ThreadContext tc, ThreadMemoryManager mm, Type t) { Uword allocSize = sizeof(ObjectHeader) + getSize(tc, t); ObjectHeader* oh = (ObjectHeader*)::operator new(allocSize); oh->type = t; return (Object) &oh->object; } static Namespace createNamespace(ThreadContext tc, String name) { ThreadMemoryManager mm = getThreadMemoryManager(tc); Runtime rt = getRuntime(tc); Namespace ns = (Namespace) allocRaw(mm, sizeof(NamespaceT)); ns->name = name; rt->namespaces[name] = ns; return makeShared(tc, ns); } static Object bind(ThreadContext tc, Namespace ns, String name, Object obj) { } static Type getNamespaceType(Runtime rt) { return rt->builtInTypes.namespaceType; } static Bool equals(ThreadContext tc, Namespace ns, Object obj) { } static Type getType(ThreadContext tc, Object obj) { } static Uword hash(ThreadContext tc, Object o) { } static Bool equals(ThreadContext tc, Object o1, Object o2) { } static String makeShared(ThreadContext tc, String s) { } static Namespace makeShared(ThreadContext tc, Namespace s) { } static Runtime createRuntime() { Runtime rt = new RuntimeT; // Create main thread context, with its own memory manager ThreadContext mainTc = createThreadContext(rt, createThreadMemoryManager(), nullptr); rt->threadContexts.push_back(mainTc); // Create main namespace setNamespace(mainTc, createNamespace(mainTc, createString(mainTc, "octarine"))); return rt; } static void destroyRuntime(Runtime rt) { std::for_each(rt->threadContexts.begin(), rt->threadContexts.end(), destroyThreadContext); delete rt; } static void registerFunction(ThreadContext tc, Namespace ns, Function f) { } static Object eval(ThreadContext tc, String source) { } static Object intern(ThreadContext tc, Object o) { Runtime rt = getRuntime(tc); std::lock_guard<std::mutex> lock(rt->internedObjectsMutex); std::unordered_set<Object>::const_iterator i = rt->internedObjects.find(o); if (i == rt->internedObjects.end()) { // Not found, copy to global memory and insert. return nullptr; } else { return *i; } } static String createString(ThreadContext tc, const char* cstr) { return nullptr; } static Uword hash(ThreadContext tc, String s) { return 0; } static Bool equals(ThreadContext tc, String s1, String s2) { return False; } static ThreadContext createThreadContext(Runtime rt, ThreadMemoryManager mm, Namespace initialNs) { ThreadContext tc = (ThreadContext) allocRaw(mm, sizeof(ThreadContextT)); tc->runtime = rt; tc->ThreadMemoryManager = mm; tc->currentNs = initialNs; tls.set(tc); return tc; } static void destroyThreadContext(ThreadContext tc) { tls.set(nullptr); destroyThreadMemoryManager(tc->ThreadMemoryManager); } static ThreadContext getThreadContext() { return (ThreadContext) tls.get(); } static Runtime getRuntime(ThreadContext tc) { return tc->runtime; } static ThreadMemoryManager getThreadMemoryManager(ThreadContext tc) { return tc->ThreadMemoryManager; } static Namespace getNamespace(ThreadContext tc) { return tc->currentNs; } static Namespace setNamespace(ThreadContext tc, Namespace ns) { Namespace old = tc->currentNs; tc->currentNs = ns; return old; } static Exception createException(ThreadContext tc, String message) { } static String getMessage(ThreadContext tc, Exception e) { } } // ## 60 C API #endif <|endoftext|>
<commit_before>/* Copyright (c) 2015, Project OSRM contributors 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. */ #ifndef MAP_MATCHING_HPP #define MAP_MATCHING_HPP #include "routing_base.hpp" #include "../data_structures/coordinate_calculation.hpp" #include "../data_structures/hidden_markov_model.hpp" #include "../util/matching_debug_info.hpp" #include "../util/simple_logger.hpp" #include "../util/json_util.hpp" #include "../util/json_logger.hpp" #include <osrm/json_container.hpp> #include <variant/variant.hpp> #include <fstream> #include <algorithm> #include <iomanip> #include <numeric> namespace osrm { namespace matching { struct SubMatching { std::vector<PhantomNode> nodes; std::vector<unsigned> indices; double length; double confidence; }; using CandidateList = std::vector<std::pair<PhantomNode, double>>; using CandidateLists = std::vector<CandidateList>; using HMM = HiddenMarkovModel<CandidateLists>; using SubMatchingList = std::vector<SubMatching>; constexpr static const unsigned MAX_BROKEN_STATES = 6; constexpr static const unsigned MAX_BROKEN_TIME = 30; constexpr static const double default_beta = 10.0; constexpr static const double default_sigma_z = 4.07; } } // implements a hidden markov model map matching algorithm template <class DataFacadeT> class MapMatching final : public BasicRoutingInterface<DataFacadeT, MapMatching<DataFacadeT>> { using super = BasicRoutingInterface<DataFacadeT, MapMatching<DataFacadeT>>; using QueryHeap = SearchEngineData::QueryHeap; SearchEngineData &engine_working_data; public: MapMatching(DataFacadeT *facade, SearchEngineData &engine_working_data) : super(facade), engine_working_data(engine_working_data) { } void operator()(const osrm::matching::CandidateLists &candidates_list, const std::vector<FixedPointCoordinate> &trace_coordinates, const std::vector<unsigned> &trace_timestamps, const double matching_beta, const double gps_precision, osrm::matching::SubMatchingList &sub_matchings) const { BOOST_ASSERT(candidates_list.size() > 0); // TODO replace default values with table lookup based on sampling frequency EmissionLogProbability emission_log_probability( gps_precision > 0 ? gps_precision : osrm::matching::default_sigma_z); TransitionLogProbability transition_log_probability( matching_beta > 0 ? matching_beta : osrm::matching::default_beta); osrm::matching::HMM model(candidates_list, emission_log_probability); unsigned initial_timestamp = model.initialize(0); if (initial_timestamp == osrm::matching::INVALID_STATE) { return; } MatchingDebugInfo matching_debug(osrm::json::Logger::get()); matching_debug.initialize(candidates_list); unsigned breakage_begin = std::numeric_limits<unsigned>::max(); std::vector<unsigned> split_points; std::vector<unsigned> prev_unbroken_timestamps; prev_unbroken_timestamps.reserve(candidates_list.size()); prev_unbroken_timestamps.push_back(initial_timestamp); for (auto t = initial_timestamp + 1; t < candidates_list.size(); ++t) { // breakage recover has removed all previous good points bool trace_split = prev_unbroken_timestamps.size() < 1; // use temporal information if available to determine a split if (trace_timestamps.size() > 0) { trace_split = trace_split || (trace_timestamps[t] - trace_timestamps[prev_unbroken_timestamps.back()] > osrm::matching::MAX_BROKEN_TIME); } else { trace_split = trace_split || (t - prev_unbroken_timestamps.back() > osrm::matching::MAX_BROKEN_STATES); } if (trace_split) { unsigned split_index = t; if (breakage_begin != std::numeric_limits<unsigned>::max()) { split_index = breakage_begin; breakage_begin = std::numeric_limits<unsigned>::max(); } split_points.push_back(split_index); // note: this preserves everything before split_index model.clear(split_index); unsigned new_start = model.initialize(split_index); // no new start was found -> stop viterbi calculation if (new_start == osrm::matching::INVALID_STATE) { break; } prev_unbroken_timestamps.clear(); prev_unbroken_timestamps.push_back(new_start); // Important: We potentially go back here! // However since t > new_start >= breakge_begin // we can only reset trace_coordindates.size() times. t = new_start + 1; } unsigned prev_unbroken_timestamp = prev_unbroken_timestamps.back(); const auto &prev_viterbi = model.viterbi[prev_unbroken_timestamp]; const auto &prev_pruned = model.pruned[prev_unbroken_timestamp]; const auto &prev_unbroken_timestamps_list = candidates_list[prev_unbroken_timestamp]; const auto &prev_coordinate = trace_coordinates[prev_unbroken_timestamp]; auto &current_viterbi = model.viterbi[t]; auto &current_pruned = model.pruned[t]; auto &current_parents = model.parents[t]; auto &current_lengths = model.path_lengths[t]; const auto &current_timestamps_list = candidates_list[t]; const auto &current_coordinate = trace_coordinates[t]; engine_working_data.InitializeOrClearFirstThreadLocalStorage( super::facade->GetNumberOfNodes()); engine_working_data.InitializeOrClearSecondThreadLocalStorage( super::facade->GetNumberOfNodes()); QueryHeap &forward_heap = *(engine_working_data.forward_heap_1); QueryHeap &reverse_heap = *(engine_working_data.reverse_heap_1); // compute d_t for this timestamp and the next one for (auto s = 0u; s < prev_viterbi.size(); ++s) { if (prev_pruned[s]) continue; for (auto s_prime = 0u; s_prime < current_viterbi.size(); ++s_prime) { // how likely is candidate s_prime at time t to be emitted? const double emission_pr = emission_log_probability(candidates_list[t][s_prime].second); double new_value = prev_viterbi[s] + emission_pr; if (current_viterbi[s_prime] > new_value) { continue; } forward_heap.Clear(); reverse_heap.Clear(); // get distance diff between loc1/2 and locs/s_prime const auto network_distance = super::get_network_distance( forward_heap, reverse_heap, prev_unbroken_timestamps_list[s].first, current_timestamps_list[s_prime].first); const auto great_circle_distance = coordinate_calculation::great_circle_distance(prev_coordinate, current_coordinate); const auto d_t = std::abs(network_distance - great_circle_distance); // very low probability transition -> prune if (d_t > 500) { continue; } const double transition_pr = transition_log_probability(d_t); new_value += transition_pr; matching_debug.add_transition_info(prev_unbroken_timestamp, t, s, s_prime, prev_viterbi[s], emission_pr, transition_pr, network_distance, great_circle_distance); if (new_value > current_viterbi[s_prime]) { current_viterbi[s_prime] = new_value; current_parents[s_prime] = std::make_pair(prev_unbroken_timestamp, s); current_lengths[s_prime] = network_distance; current_pruned[s_prime] = false; model.breakage[t] = false; } } } if (model.breakage[t]) { // save start of breakage -> we need this as split point if (t < breakage_begin) { breakage_begin = t; } BOOST_ASSERT(prev_unbroken_timestamps.size() > 0); // remove both ends of the breakage prev_unbroken_timestamps.pop_back(); } else { prev_unbroken_timestamps.push_back(t); } } matching_debug.set_viterbi(model.viterbi, model.pruned); if (prev_unbroken_timestamps.size() > 0) { split_points.push_back(prev_unbroken_timestamps.back() + 1); } unsigned sub_matching_begin = initial_timestamp; for (const unsigned sub_matching_end : split_points) { osrm::matching::SubMatching matching; // find real end of trace // not sure if this is really needed unsigned parent_timestamp_index = sub_matching_end - 1; while (parent_timestamp_index >= sub_matching_begin && model.breakage[parent_timestamp_index]) { parent_timestamp_index--; } // matchings that only consist of one candidate are invalid if (parent_timestamp_index - sub_matching_begin + 1 < 2) { sub_matching_begin = sub_matching_end; continue; } // loop through the columns, and only compare the last entry auto max_element_iter = std::max_element(model.viterbi[parent_timestamp_index].begin(), model.viterbi[parent_timestamp_index].end()); unsigned parent_candidate_index = std::distance(model.viterbi[parent_timestamp_index].begin(), max_element_iter); std::deque<std::pair<unsigned, unsigned>> reconstructed_indices; while (parent_timestamp_index > sub_matching_begin) { if (model.breakage[parent_timestamp_index]) { continue; } reconstructed_indices.emplace_front(parent_timestamp_index, parent_candidate_index); const auto &next = model.parents[parent_timestamp_index][parent_candidate_index]; parent_timestamp_index = next.first; parent_candidate_index = next.second; } reconstructed_indices.emplace_front(parent_timestamp_index, parent_candidate_index); if (reconstructed_indices.size() < 2) { sub_matching_begin = sub_matching_end; continue; } matching.length = 0.0f; matching.nodes.resize(reconstructed_indices.size()); matching.indices.resize(reconstructed_indices.size()); for (auto i = 0u; i < reconstructed_indices.size(); ++i) { auto timestamp_index = reconstructed_indices[i].first; auto location_index = reconstructed_indices[i].second; matching.indices[i] = timestamp_index; matching.nodes[i] = candidates_list[timestamp_index][location_index].first; matching.length += model.path_lengths[timestamp_index][location_index]; matching_debug.add_chosen(timestamp_index, location_index); } sub_matchings.push_back(matching); sub_matching_begin = sub_matching_end; } matching_debug.add_breakage(model.breakage); } }; //[1] "Hidden Markov Map Matching Through Noise and Sparseness"; P. Newson and J. Krumm; 2009; ACM // GIS #endif /* MAP_MATCHING_HPP */ <commit_msg>several copyedits to brush up code<commit_after>/* Copyright (c) 2015, Project OSRM contributors 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. */ #ifndef MAP_MATCHING_HPP #define MAP_MATCHING_HPP #include "routing_base.hpp" #include "../data_structures/coordinate_calculation.hpp" #include "../data_structures/hidden_markov_model.hpp" #include "../util/matching_debug_info.hpp" #include "../util/json_logger.hpp" #include <variant/variant.hpp> #include <algorithm> #include <iomanip> #include <numeric> namespace osrm { namespace matching { struct SubMatching { std::vector<PhantomNode> nodes; std::vector<unsigned> indices; double length; double confidence; }; using CandidateList = std::vector<std::pair<PhantomNode, double>>; using CandidateLists = std::vector<CandidateList>; using HMM = HiddenMarkovModel<CandidateLists>; using SubMatchingList = std::vector<SubMatching>; constexpr static const unsigned MAX_BROKEN_STATES = 6; constexpr static const unsigned MAX_BROKEN_TIME = 30; constexpr static const double default_beta = 10.0; constexpr static const double default_sigma_z = 4.07; } } // implements a hidden markov model map matching algorithm template <class DataFacadeT> class MapMatching final : public BasicRoutingInterface<DataFacadeT, MapMatching<DataFacadeT>> { using super = BasicRoutingInterface<DataFacadeT, MapMatching<DataFacadeT>>; using QueryHeap = SearchEngineData::QueryHeap; SearchEngineData &engine_working_data; public: MapMatching(DataFacadeT *facade, SearchEngineData &engine_working_data) : super(facade), engine_working_data(engine_working_data) { } void operator()(const osrm::matching::CandidateLists &candidates_list, const std::vector<FixedPointCoordinate> &trace_coordinates, const std::vector<unsigned> &trace_timestamps, const double matching_beta, const double gps_precision, osrm::matching::SubMatchingList &sub_matchings) const { BOOST_ASSERT(!candidates_list.empty()); // TODO replace default values with table lookup based on sampling frequency EmissionLogProbability emission_log_probability( gps_precision > 0. ? gps_precision : osrm::matching::default_sigma_z); TransitionLogProbability transition_log_probability( matching_beta > 0. ? matching_beta : osrm::matching::default_beta); osrm::matching::HMM model(candidates_list, emission_log_probability); unsigned initial_timestamp = model.initialize(0); if (initial_timestamp == osrm::matching::INVALID_STATE) { return; } MatchingDebugInfo matching_debug(osrm::json::Logger::get()); matching_debug.initialize(candidates_list); unsigned breakage_begin = std::numeric_limits<unsigned>::max(); std::vector<unsigned> split_points; std::vector<unsigned> prev_unbroken_timestamps; prev_unbroken_timestamps.reserve(candidates_list.size()); prev_unbroken_timestamps.push_back(initial_timestamp); for (auto t = initial_timestamp + 1; t < candidates_list.size(); ++t) { // breakage recover has removed all previous good points bool trace_split = prev_unbroken_timestamps.empty(); // use temporal information if available to determine a split if (!trace_timestamps.empty()) { trace_split = trace_split || (trace_timestamps[t] - trace_timestamps[prev_unbroken_timestamps.back()] > osrm::matching::MAX_BROKEN_TIME); } else { trace_split = trace_split || (t - prev_unbroken_timestamps.back() > osrm::matching::MAX_BROKEN_STATES); } if (trace_split) { unsigned split_index = t; if (breakage_begin != std::numeric_limits<unsigned>::max()) { split_index = breakage_begin; breakage_begin = std::numeric_limits<unsigned>::max(); } split_points.push_back(split_index); // note: this preserves everything before split_index model.clear(split_index); unsigned new_start = model.initialize(split_index); // no new start was found -> stop viterbi calculation if (new_start == osrm::matching::INVALID_STATE) { break; } prev_unbroken_timestamps.clear(); prev_unbroken_timestamps.push_back(new_start); // Important: We potentially go back here! // However since t > new_start >= breakge_begin // we can only reset trace_coordindates.size() times. t = new_start + 1; } BOOST_ASSERT(!prev_unbroken_timestamps.empty()); const unsigned prev_unbroken_timestamp = prev_unbroken_timestamps.back(); const auto &prev_viterbi = model.viterbi[prev_unbroken_timestamp]; const auto &prev_pruned = model.pruned[prev_unbroken_timestamp]; const auto &prev_unbroken_timestamps_list = candidates_list[prev_unbroken_timestamp]; const auto &prev_coordinate = trace_coordinates[prev_unbroken_timestamp]; auto &current_viterbi = model.viterbi[t]; auto &current_pruned = model.pruned[t]; auto &current_parents = model.parents[t]; auto &current_lengths = model.path_lengths[t]; const auto &current_timestamps_list = candidates_list[t]; const auto &current_coordinate = trace_coordinates[t]; engine_working_data.InitializeOrClearFirstThreadLocalStorage( super::facade->GetNumberOfNodes()); engine_working_data.InitializeOrClearSecondThreadLocalStorage( super::facade->GetNumberOfNodes()); QueryHeap &forward_heap = *(engine_working_data.forward_heap_1); QueryHeap &reverse_heap = *(engine_working_data.reverse_heap_1); // compute d_t for this timestamp and the next one for (const auto s : osrm::irange<std::size_t>(0u, prev_viterbi.size())) { if (prev_pruned[s]) { continue; } for (const auto s_prime : osrm::irange<std::size_t>(0u, current_viterbi.size())) { // how likely is candidate s_prime at time t to be emitted? const double emission_pr = emission_log_probability(candidates_list[t][s_prime].second); double new_value = prev_viterbi[s] + emission_pr; if (current_viterbi[s_prime] > new_value) { continue; } forward_heap.Clear(); reverse_heap.Clear(); // get distance diff between loc1/2 and locs/s_prime const auto network_distance = super::get_network_distance( forward_heap, reverse_heap, prev_unbroken_timestamps_list[s].first, current_timestamps_list[s_prime].first); const auto great_circle_distance = coordinate_calculation::great_circle_distance(prev_coordinate, current_coordinate); const auto d_t = std::abs(network_distance - great_circle_distance); // very low probability transition -> prune if (d_t > 500) { continue; } const double transition_pr = transition_log_probability(d_t); new_value += transition_pr; matching_debug.add_transition_info(prev_unbroken_timestamp, t, s, s_prime, prev_viterbi[s], emission_pr, transition_pr, network_distance, great_circle_distance); if (new_value > current_viterbi[s_prime]) { current_viterbi[s_prime] = new_value; current_parents[s_prime] = std::make_pair(prev_unbroken_timestamp, s); current_lengths[s_prime] = network_distance; current_pruned[s_prime] = false; model.breakage[t] = false; } } } if (model.breakage[t]) { // save start of breakage -> we need this as split point if (t < breakage_begin) { breakage_begin = t; } BOOST_ASSERT(prev_unbroken_timestamps.size() > 0); // remove both ends of the breakage prev_unbroken_timestamps.pop_back(); } else { prev_unbroken_timestamps.push_back(t); } } matching_debug.set_viterbi(model.viterbi, model.pruned); if (!prev_unbroken_timestamps.empty()) { split_points.push_back(prev_unbroken_timestamps.back() + 1); } unsigned sub_matching_begin = initial_timestamp; for (const unsigned sub_matching_end : split_points) { osrm::matching::SubMatching matching; // find real end of trace // not sure if this is really needed unsigned parent_timestamp_index = sub_matching_end - 1; while (parent_timestamp_index >= sub_matching_begin && model.breakage[parent_timestamp_index]) { parent_timestamp_index--; } // matchings that only consist of one candidate are invalid if (parent_timestamp_index - sub_matching_begin + 1 < 2) { sub_matching_begin = sub_matching_end; continue; } // loop through the columns, and only compare the last entry const auto max_element_iter = std::max_element(model.viterbi[parent_timestamp_index].begin(), model.viterbi[parent_timestamp_index].end()); unsigned parent_candidate_index = std::distance(model.viterbi[parent_timestamp_index].begin(), max_element_iter); std::deque<std::pair<unsigned, unsigned>> reconstructed_indices; while (parent_timestamp_index > sub_matching_begin) { if (model.breakage[parent_timestamp_index]) { continue; } reconstructed_indices.emplace_front(parent_timestamp_index, parent_candidate_index); const auto &next = model.parents[parent_timestamp_index][parent_candidate_index]; parent_timestamp_index = next.first; parent_candidate_index = next.second; } reconstructed_indices.emplace_front(parent_timestamp_index, parent_candidate_index); if (reconstructed_indices.size() < 2) { sub_matching_begin = sub_matching_end; continue; } matching.length = 0.0f; matching.nodes.resize(reconstructed_indices.size()); matching.indices.resize(reconstructed_indices.size()); for (const auto i : osrm::irange<std::size_t>(0u, reconstructed_indices.size())) { auto timestamp_index = reconstructed_indices[i].first; auto location_index = reconstructed_indices[i].second; matching.indices[i] = timestamp_index; matching.nodes[i] = candidates_list[timestamp_index][location_index].first; matching.length += model.path_lengths[timestamp_index][location_index]; matching_debug.add_chosen(timestamp_index, location_index); } sub_matchings.push_back(matching); sub_matching_begin = sub_matching_end; } matching_debug.add_breakage(model.breakage); } }; //[1] "Hidden Markov Map Matching Through Noise and Sparseness"; P. Newson and J. Krumm; 2009; ACM // GIS #endif /* MAP_MATCHING_HPP */ <|endoftext|>
<commit_before>/* * Copyright (c) 2013 Eugene Lazin <4lazin@gmail.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include "storage.h" #include "util.h" #include <stdexcept> #include <algorithm> #include <atomic> #include <sstream> #include <cassert> #include <apr_general.h> #include <apr_mmap.h> #include <log4cxx/logger.h> #include <log4cxx/logmanager.h> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> namespace Akumuli { static log4cxx::LoggerPtr s_logger_ = log4cxx::LogManager::getLogger("Akumuli.Storage"); //----------------------------------Volume---------------------------------------------- Volume::Volume(const char* file_name) : mmap_(file_name) { mmap_.throw_if_bad(); // panic if can't mmap volume page_ = reinterpret_cast<PageHeader*>(mmap_.get_pointer()); } PageHeader* Volume::get_page() const noexcept { return page_; } PageHeader* Volume::reallocate_disc_space() { uint32_t page_id = page_->page_id; uint32_t overwrites_count = page_->overwrites_count; PageType page_type = page_->type; mmap_.remap_file_destructive(); page_ = new (mmap_.get_pointer()) PageHeader(page_type, 0, mmap_.get_size(), page_id); page_->overwrites_count = overwrites_count; return page_; } //----------------------------------Storage--------------------------------------------- Storage::Storage(const char* file_name) { /* Exception, thrown from this c-tor means that something really bad * happend and we it's impossible to open this storage, for example - * because metadata file is corrupted, or volume is missed on disc. */ // 1. Read json file boost::property_tree::ptree ptree; // NOTE: there is a known bug in boost 1.49 - https://svn.boost.org/trac/boost/ticket/6785 // FIX: sed -i -e 's/std::make_pair(c.name, Str(b, e))/std::make_pair(c.name, Ptree(Str(b, e)))/' json_parser_read.hpp boost::property_tree::json_parser::read_json(file_name, ptree); // 2. Read volumes int num_volumes = ptree.get_child("num_volumes").get_value(0); if (num_volumes == 0) { throw std::runtime_error("Invalid storage"); } std::vector<std::string> volume_names(num_volumes); for(auto child_node: ptree.get_child("volumes")) { auto volume_index = child_node.second.get_child("index").get_value_optional<int>(); auto volume_path = child_node.second.get_child("path").get_value_optional<std::string>(); if (volume_index && volume_path) { volume_names.at(*volume_index) = *volume_path; } else { throw std::runtime_error("Invalid storage, bad volume link"); } } // check result for(std::string const& path: volume_names) { if (path.empty()) throw std::runtime_error("Invalid storage, one of the volumes is missing"); } // create volumes list for(auto path: volume_names) { Volume* vol = new Volume(path.c_str()); volumes_.push_back(vol); } // volume with maximal overwrites_count and minimal index must be active int max_index = -1; int64_t max_overwrites = -1; for(int i = 0; i < num_volumes; i++) { PageHeader* page = volumes_.at(i)->get_page(); if (static_cast<int64_t>(page->overwrites_count) >= max_overwrites) { max_overwrites = static_cast<int64_t>(page->overwrites_count); max_index = i; } } active_volume_ = volumes_.at(max_index); active_page_ = active_volume_->get_page(); } // Reading void Storage::find_entry(ParamId param, TimeStamp timestamp) { int64_t raw_time = timestamp.precise; } // Writing //! commit changes void Storage::commit() { // TODO: volume->flush() } //! write data int Storage::write(Entry const& entry) { // FIXME: this code intentionaly single threaded while(true) { int status = active_page_->add_entry(entry); switch (status) { case AKU_WRITE_STATUS_OVERFLOW: // select next page in round robin order active_volume_index_++; active_volume_ = volumes_[active_volume_index_ % volumes_.size()]; active_page_ = active_volume_->reallocate_disc_space(); active_page_->clear(); break; default: return status; }; } } int Storage::write(Entry2 const& entry) { // FIXME: this code intentionaly left single threaded while(true) { int status = active_page_->add_entry(entry); switch (status) { case AKU_WRITE_STATUS_OVERFLOW: // select next page in round robin order active_volume_index_++; active_volume_ = volumes_[active_volume_index_ % volumes_.size()]; active_page_ = active_volume_->reallocate_disc_space(); active_page_->clear(); break; default: return status; }; } } /** This function creates file with specified size */ static apr_status_t create_file(const char* file_name, uint64_t size) { apr_status_t status; int success_count = 0; apr_pool_t* mem_pool = NULL; apr_file_t* file = NULL; status = apr_pool_create(&mem_pool, NULL); if (status == APR_SUCCESS) { success_count++; // Create new file status = apr_file_open(&file, file_name, APR_CREATE|APR_WRITE, APR_OS_DEFAULT, mem_pool); if (status == APR_SUCCESS) { success_count++; // Truncate file status = apr_file_trunc(file, size); if (status == APR_SUCCESS) success_count++; } } if (status != APR_SUCCESS) { char error_message[0x100]; apr_strerror(status, error_message, 0x100); LOG4CXX_ERROR(s_logger_, "Can't create file, error " << error_message << " on step " << success_count); } switch(success_count) { case 3: case 2: status = apr_file_close(file); case 1: apr_pool_destroy(mem_pool); case 0: // even apr pool is not created break; } return status; } /** This function creates one of the page files with specified * name and index. */ static apr_status_t create_page_file(const char* file_name, uint32_t page_index) { apr_status_t status; int64_t size = AKU_MAX_PAGE_SIZE; status = create_file(file_name, size); if (status != APR_SUCCESS) { LOG4CXX_ERROR(s_logger_, "Can't create page file " << file_name); return status; } MemoryMappedFile mfile(file_name); if (mfile.is_bad()) return mfile.status_code(); // Create index page auto index_ptr = mfile.get_pointer(); auto index_page = new (index_ptr) PageHeader(PageType::Index, 0, AKU_MAX_PAGE_SIZE, page_index); // FIXME: revisit - is it actually needed? // Activate the first page if (page_index == 0) { index_page->clear(); } return status; } /** Create page files, return list of statuses. */ static std::vector<apr_status_t> create_page_files(std::vector<std::string> const& targets) { std::vector<apr_status_t> results(targets.size(), APR_SUCCESS); for (size_t ix = 0; ix < targets.size(); ix++) { apr_status_t res = create_page_file(targets[ix].c_str(), ix); results[ix] = res; } return results; } static std::vector<apr_status_t> delete_files(const std::vector<std::string>& targets, const std::vector<apr_status_t>& statuses) { if (targets.size() != statuses.size()) { throw std::logic_error("Sizes of targets and statuses doesn't match"); } apr_pool_t* mem_pool = NULL; int op_count = 0; apr_status_t status = apr_pool_create(&mem_pool, NULL); std::vector<apr_status_t> results; if (status == APR_SUCCESS) { op_count++; for(auto ix = 0; ix < targets.size(); ix++) { const std::string& target = targets[ix]; if (statuses[ix] == APR_SUCCESS) { LOG4CXX_INFO(s_logger_, "Removing " << target); status = apr_file_remove(target.c_str(), mem_pool); results.push_back(status); if (status != APR_SUCCESS) { char error_message[1024]; apr_strerror(status, error_message, 1024); LOG4CXX_ERROR(s_logger_, "Error [" << error_message << "] while deleting a file " << target); } } else { LOG4CXX_INFO(s_logger_, "Target " << target << " doesn't need to be removed"); } } } if (op_count) { apr_pool_destroy(mem_pool); } return results; } /** This function creates metadata file - root of the storage system. * This page contains creation date and time, number of pages, * all the page file names and they order. */ static apr_status_t create_metadata_page( const char* file_name , std::vector<std::string> const& page_file_names) { try { boost::property_tree::ptree root; auto now = apr_time_now(); char date_time[0x100]; apr_rfc822_date(date_time, now); root.add("creation_time", date_time); root.add("num_volumes", page_file_names.size()); boost::property_tree::ptree volumes_list; for(size_t i = 0; i < page_file_names.size(); i++) { boost::property_tree::ptree page_desc; page_desc.add("index", i); page_desc.add("path", page_file_names[i]); volumes_list.push_back(std::make_pair("", page_desc)); } root.add_child("volumes", volumes_list); boost::property_tree::json_parser::write_json(file_name, root); } catch(const std::exception& err) { LOG4CXX_ERROR(s_logger_, "Can't generate JSON file " << file_name << ", the error is: " << err.what()); return APR_EGENERAL; } return APR_SUCCESS; } apr_status_t Storage::new_storage( const char* file_name , const char* metadata_path , const char* volumes_path , int num_pages ) { apr_pool_t* mempool; apr_status_t status = apr_pool_create(&mempool, NULL); if (status != APR_SUCCESS) return status; // calculate list of page-file names std::vector<std::string> page_names; for (int ix = 0; ix < num_pages; ix++) { std::stringstream stream; stream << file_name << "_" << ix << ".volume"; char* path = nullptr; std::string volume_file_name = stream.str(); status = apr_filepath_merge(&path, volumes_path, volume_file_name.c_str(), APR_FILEPATH_NATIVE, mempool); if (status != APR_SUCCESS) { auto error_message = apr_error_message(status); LOG4CXX_ERROR(s_logger_, "Invalid volumes path: " << error_message); apr_pool_destroy(mempool); throw AprException(status, error_message.c_str()); } page_names.push_back(path); } apr_pool_clear(mempool); std::vector<apr_status_t> page_creation_statuses = create_page_files(page_names); for(auto creation_status: page_creation_statuses) { if (creation_status != APR_SUCCESS) { LOG4CXX_ERROR(s_logger_, "Not all pages successfullly created. Cleaning up."); apr_pool_destroy(mempool); delete_files(page_names, page_creation_statuses); return creation_status; } } std::stringstream stream; stream << file_name << ".akumuli"; char* path = nullptr; std::string metadata_file_name = stream.str(); status = apr_filepath_merge(&path, metadata_path, metadata_file_name.c_str(), APR_FILEPATH_NATIVE, mempool); if (status != APR_SUCCESS) { auto error_message = apr_error_message(status); LOG4CXX_ERROR(s_logger_, "Invalid metadata path: " << error_message); apr_pool_destroy(mempool); throw AprException(status, error_message.c_str()); } status = create_metadata_page(path, page_names); apr_pool_destroy(mempool); return status; } } <commit_msg>Pages overwrite order fixed<commit_after>/* * Copyright (c) 2013 Eugene Lazin <4lazin@gmail.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include "storage.h" #include "util.h" #include <stdexcept> #include <algorithm> #include <atomic> #include <sstream> #include <cassert> #include <apr_general.h> #include <apr_mmap.h> #include <log4cxx/logger.h> #include <log4cxx/logmanager.h> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> namespace Akumuli { static log4cxx::LoggerPtr s_logger_ = log4cxx::LogManager::getLogger("Akumuli.Storage"); //----------------------------------Volume---------------------------------------------- Volume::Volume(const char* file_name) : mmap_(file_name) { mmap_.throw_if_bad(); // panic if can't mmap volume page_ = reinterpret_cast<PageHeader*>(mmap_.get_pointer()); } PageHeader* Volume::get_page() const noexcept { return page_; } PageHeader* Volume::reallocate_disc_space() { uint32_t page_id = page_->page_id; uint32_t overwrites_count = page_->overwrites_count; PageType page_type = page_->type; mmap_.remap_file_destructive(); page_ = new (mmap_.get_pointer()) PageHeader(page_type, 0, mmap_.get_size(), page_id); page_->overwrites_count = overwrites_count; return page_; } //----------------------------------Storage--------------------------------------------- Storage::Storage(const char* file_name) { /* Exception, thrown from this c-tor means that something really bad * happend and we it's impossible to open this storage, for example - * because metadata file is corrupted, or volume is missed on disc. */ // 1. Read json file boost::property_tree::ptree ptree; // NOTE: there is a known bug in boost 1.49 - https://svn.boost.org/trac/boost/ticket/6785 // FIX: sed -i -e 's/std::make_pair(c.name, Str(b, e))/std::make_pair(c.name, Ptree(Str(b, e)))/' json_parser_read.hpp boost::property_tree::json_parser::read_json(file_name, ptree); // 2. Read volumes int num_volumes = ptree.get_child("num_volumes").get_value(0); if (num_volumes == 0) { throw std::runtime_error("Invalid storage"); } std::vector<std::string> volume_names(num_volumes); for(auto child_node: ptree.get_child("volumes")) { auto volume_index = child_node.second.get_child("index").get_value_optional<int>(); auto volume_path = child_node.second.get_child("path").get_value_optional<std::string>(); if (volume_index && volume_path) { volume_names.at(*volume_index) = *volume_path; } else { throw std::runtime_error("Invalid storage, bad volume link"); } } // check result for(std::string const& path: volume_names) { if (path.empty()) throw std::runtime_error("Invalid storage, one of the volumes is missing"); } // create volumes list for(auto path: volume_names) { Volume* vol = new Volume(path.c_str()); volumes_.push_back(vol); } // volume with max overwrites_count and max index must be active int max_index = -1; int64_t max_overwrites = -1; for(int i = 0; i < num_volumes; i++) { PageHeader* page = volumes_.at(i)->get_page(); if (static_cast<int64_t>(page->overwrites_count) >= max_overwrites) { max_overwrites = static_cast<int64_t>(page->overwrites_count); max_index = i; } } active_volume_index_ = max_index; active_volume_ = volumes_.at(max_index); active_page_ = active_volume_->get_page(); } // Reading void Storage::find_entry(ParamId param, TimeStamp timestamp) { int64_t raw_time = timestamp.precise; } // Writing //! commit changes void Storage::commit() { // TODO: volume->flush() } //! write data int Storage::write(Entry const& entry) { // FIXME: this code intentionaly single threaded while(true) { int status = active_page_->add_entry(entry); switch (status) { case AKU_WRITE_STATUS_OVERFLOW: // select next page in round robin order active_volume_index_++; active_volume_ = volumes_[active_volume_index_ % volumes_.size()]; active_page_ = active_volume_->reallocate_disc_space(); active_page_->clear(); break; default: return status; }; } } int Storage::write(Entry2 const& entry) { // FIXME: this code intentionaly left single threaded while(true) { int status = active_page_->add_entry(entry); switch (status) { case AKU_WRITE_STATUS_OVERFLOW: // select next page in round robin order active_volume_index_++; active_volume_ = volumes_[active_volume_index_ % volumes_.size()]; active_page_ = active_volume_->reallocate_disc_space(); active_page_->clear(); break; default: return status; }; } } /** This function creates file with specified size */ static apr_status_t create_file(const char* file_name, uint64_t size) { apr_status_t status; int success_count = 0; apr_pool_t* mem_pool = NULL; apr_file_t* file = NULL; status = apr_pool_create(&mem_pool, NULL); if (status == APR_SUCCESS) { success_count++; // Create new file status = apr_file_open(&file, file_name, APR_CREATE|APR_WRITE, APR_OS_DEFAULT, mem_pool); if (status == APR_SUCCESS) { success_count++; // Truncate file status = apr_file_trunc(file, size); if (status == APR_SUCCESS) success_count++; } } if (status != APR_SUCCESS) { char error_message[0x100]; apr_strerror(status, error_message, 0x100); LOG4CXX_ERROR(s_logger_, "Can't create file, error " << error_message << " on step " << success_count); } switch(success_count) { case 3: case 2: status = apr_file_close(file); case 1: apr_pool_destroy(mem_pool); case 0: // even apr pool is not created break; } return status; } /** This function creates one of the page files with specified * name and index. */ static apr_status_t create_page_file(const char* file_name, uint32_t page_index) { apr_status_t status; int64_t size = AKU_MAX_PAGE_SIZE; status = create_file(file_name, size); if (status != APR_SUCCESS) { LOG4CXX_ERROR(s_logger_, "Can't create page file " << file_name); return status; } MemoryMappedFile mfile(file_name); if (mfile.is_bad()) return mfile.status_code(); // Create index page auto index_ptr = mfile.get_pointer(); auto index_page = new (index_ptr) PageHeader(PageType::Index, 0, AKU_MAX_PAGE_SIZE, page_index); // FIXME: revisit - is it actually needed? // Activate the first page if (page_index == 0) { index_page->clear(); } return status; } /** Create page files, return list of statuses. */ static std::vector<apr_status_t> create_page_files(std::vector<std::string> const& targets) { std::vector<apr_status_t> results(targets.size(), APR_SUCCESS); for (size_t ix = 0; ix < targets.size(); ix++) { apr_status_t res = create_page_file(targets[ix].c_str(), ix); results[ix] = res; } return results; } static std::vector<apr_status_t> delete_files(const std::vector<std::string>& targets, const std::vector<apr_status_t>& statuses) { if (targets.size() != statuses.size()) { throw std::logic_error("Sizes of targets and statuses doesn't match"); } apr_pool_t* mem_pool = NULL; int op_count = 0; apr_status_t status = apr_pool_create(&mem_pool, NULL); std::vector<apr_status_t> results; if (status == APR_SUCCESS) { op_count++; for(auto ix = 0; ix < targets.size(); ix++) { const std::string& target = targets[ix]; if (statuses[ix] == APR_SUCCESS) { LOG4CXX_INFO(s_logger_, "Removing " << target); status = apr_file_remove(target.c_str(), mem_pool); results.push_back(status); if (status != APR_SUCCESS) { char error_message[1024]; apr_strerror(status, error_message, 1024); LOG4CXX_ERROR(s_logger_, "Error [" << error_message << "] while deleting a file " << target); } } else { LOG4CXX_INFO(s_logger_, "Target " << target << " doesn't need to be removed"); } } } if (op_count) { apr_pool_destroy(mem_pool); } return results; } /** This function creates metadata file - root of the storage system. * This page contains creation date and time, number of pages, * all the page file names and they order. */ static apr_status_t create_metadata_page( const char* file_name , std::vector<std::string> const& page_file_names) { try { boost::property_tree::ptree root; auto now = apr_time_now(); char date_time[0x100]; apr_rfc822_date(date_time, now); root.add("creation_time", date_time); root.add("num_volumes", page_file_names.size()); boost::property_tree::ptree volumes_list; for(size_t i = 0; i < page_file_names.size(); i++) { boost::property_tree::ptree page_desc; page_desc.add("index", i); page_desc.add("path", page_file_names[i]); volumes_list.push_back(std::make_pair("", page_desc)); } root.add_child("volumes", volumes_list); boost::property_tree::json_parser::write_json(file_name, root); } catch(const std::exception& err) { LOG4CXX_ERROR(s_logger_, "Can't generate JSON file " << file_name << ", the error is: " << err.what()); return APR_EGENERAL; } return APR_SUCCESS; } apr_status_t Storage::new_storage( const char* file_name , const char* metadata_path , const char* volumes_path , int num_pages ) { apr_pool_t* mempool; apr_status_t status = apr_pool_create(&mempool, NULL); if (status != APR_SUCCESS) return status; // calculate list of page-file names std::vector<std::string> page_names; for (int ix = 0; ix < num_pages; ix++) { std::stringstream stream; stream << file_name << "_" << ix << ".volume"; char* path = nullptr; std::string volume_file_name = stream.str(); status = apr_filepath_merge(&path, volumes_path, volume_file_name.c_str(), APR_FILEPATH_NATIVE, mempool); if (status != APR_SUCCESS) { auto error_message = apr_error_message(status); LOG4CXX_ERROR(s_logger_, "Invalid volumes path: " << error_message); apr_pool_destroy(mempool); throw AprException(status, error_message.c_str()); } page_names.push_back(path); } apr_pool_clear(mempool); std::vector<apr_status_t> page_creation_statuses = create_page_files(page_names); for(auto creation_status: page_creation_statuses) { if (creation_status != APR_SUCCESS) { LOG4CXX_ERROR(s_logger_, "Not all pages successfullly created. Cleaning up."); apr_pool_destroy(mempool); delete_files(page_names, page_creation_statuses); return creation_status; } } std::stringstream stream; stream << file_name << ".akumuli"; char* path = nullptr; std::string metadata_file_name = stream.str(); status = apr_filepath_merge(&path, metadata_path, metadata_file_name.c_str(), APR_FILEPATH_NATIVE, mempool); if (status != APR_SUCCESS) { auto error_message = apr_error_message(status); LOG4CXX_ERROR(s_logger_, "Invalid metadata path: " << error_message); apr_pool_destroy(mempool); throw AprException(status, error_message.c_str()); } status = create_metadata_page(path, page_names); apr_pool_destroy(mempool); return status; } } <|endoftext|>
<commit_before>#include "databaseconnectiondatadialog.hxx" #include <apps/app/app.hxx> #include <apps/app/settings.hxx> #include <ui/widgets/gridgroupbox.hxx> #include <ui/widgets/databaseconnectionstatuslabel.hxx> #include <ui/widgets/fieldlabel.hxx> #include <ui/widgets/hostnameedit.hxx> PROJECT_NAMESPACE_BEGIN WIDGETS_NAMESPACE_BEGIN DatabaseConnectionDataDialog::DatabaseConnectionDataDialog(QWidget *p) : VerticalDialog(QObject::tr("Database Connection"), p) { m_cd = APP_NAMESPACE::Settings().loadConnectionData(); auto status = createStatusWidget<DatabaseConnectionStatusLabel>(); status->onDatabaseStatusChanged(PGCONN_NAMESPACE::Connection::ConnectionStates::Disconnected, tr("Not connected.")); createWidgets(); createButtons(); } void DatabaseConnectionDataDialog::accept() { APP_NAMESPACE::Settings s; s.saveConnectionData(m_cd); done(QDialog::Accepted); } void DatabaseConnectionDataDialog::createWidgets() { m_box = createContentWidget<GridGroupBox>(); m_box->setTitle(tr("&Database Connection Database")); m_host = m_box->createLabelledSingleRowWidget<HostNameEdit>(tr("&Host"), QString::fromStdString(m_cd.hostName())); } WIDGETS_NAMESPACE_END PROJECT_NAMESPACE_END <commit_msg>added HostEdit<commit_after>#include "databaseconnectiondatadialog.hxx" #include <apps/app/app.hxx> #include <apps/app/settings.hxx> #include <ui/widgets/gridgroupbox.hxx> #include <ui/widgets/databaseconnectionstatuslabel.hxx> #include <ui/widgets/fieldlabel.hxx> #include <ui/widgets/hostnameedit.hxx> PROJECT_NAMESPACE_BEGIN WIDGETS_NAMESPACE_BEGIN DatabaseConnectionDataDialog::DatabaseConnectionDataDialog(QWidget *p) : VerticalDialog(QObject::tr("Database Connection"), p) { m_cd = APP_NAMESPACE::Settings().loadConnectionData(); auto status = createStatusWidget<DatabaseConnectionStatusLabel>(); status->onDatabaseStatusChanged(PGCONN_NAMESPACE::Connection::ConnectionStates::Disconnected, tr("Not connected.")); createWidgets(); createButtons(); } void DatabaseConnectionDataDialog::accept() { APP_NAMESPACE::Settings s; s.saveConnectionData(m_cd); done(QDialog::Accepted); } void DatabaseConnectionDataDialog::createWidgets() { m_box = createContentWidget<GridGroupBox>(); m_box->setTitle(tr("&Database Connection Database")); m_host = m_box->createLabelledSingleRowWidget<HostNameEdit>(tr("&Host"), QString::fromStdString(m_cd.hostName())); connect(m_host, &QLineEdit::textChanged, [=](const QString& val) { m_cd.setHostName(val.toStdString()); }); } WIDGETS_NAMESPACE_END PROJECT_NAMESPACE_END <|endoftext|>
<commit_before>// // Copyright (c) 2008 Advanced Micro Devices, Inc. All rights reserved. // #ifndef WITHOUT_HSA_BACKEND #include <string> #include <sstream> #include <fstream> #include <iostream> #include "os/os.hpp" #include "rocdevice.hpp" #include "rocprogram.hpp" #if defined(WITH_LIGHTNING_COMPILER) #include "opencl1.2-c.amdgcn.inc" #include "opencl2.0-c.amdgcn.inc" #else // !defined(WITH_LIGHTNING_COMPILER) #include "roccompilerlib.hpp" #endif // !defined(WITH_LIGHTNING_COMPILER) #include "utils/options.hpp" #include <cstdio> #if defined(ATI_OS_LINUX) #include <dlfcn.h> #include <libgen.h> #endif // defined(ATI_OS_LINUX) #if defined(WITH_LIGHTNING_COMPILER) static std::string llvmBin_(amd::Os::getEnvironment("LLVM_BIN")); #endif // defined(WITH_LIGHTNING_COMPILER) //CLC_IN_PROCESS_CHANGE extern int openclFrontEnd(const char* cmdline, std::string*, std::string* typeInfo = NULL); namespace roc { /* Temporary log function for the compiler library */ static void logFunction(const char* msg, size_t size) { std::cout<< "Compiler Log: " << msg << std::endl; } static int programsCount = 0; #if defined(WITH_LIGHTNING_COMPILER) bool HSAILProgram::compileImpl_LC( const std::string& sourceCode, const std::vector<const std::string*>& headers, const char** headerIncludeNames, amd::option::Options* options) { using namespace amd::opencl_driver; std::auto_ptr<Compiler> C(newCompilerInstance()); std::vector<Data*> inputs; if (options->isDumpFlagSet(amd::option::DUMP_CL)) { std::ofstream f(options->getDumpFileName(".cl").c_str(), std::ios::trunc); if(f.is_open()) { f << "/* Compiler options:\n" << options->origOptionStr << "\n*/\n\n" << sourceCode; } else { buildLog_ += "Warning: opening the file to dump the OpenCL source failed.\n"; } } Data* input = C->NewBufferReference(DT_CL, sourceCode.c_str(), sourceCode.length()); if (input == NULL) { buildLog_ += "Error while creating data from source code"; return false; } inputs.push_back(input); //Find the temp folder for the OS std::string tempFolder = amd::Os::getEnvironment("TEMP"); if (tempFolder.empty()) { tempFolder = amd::Os::getEnvironment("TMP"); if (tempFolder.empty()) { tempFolder = WINDOWS_SWITCH(".","/tmp");; } } //Iterate through each source code and dump it into tmp std::fstream f; std::vector<std::string> headerFileNames(headers.size()); std::vector<std::string> newDirs; for (size_t i = 0; i < headers.size(); ++i) { std::string headerPath = tempFolder; std::string headerIncludeName(headerIncludeNames[i]); // replace / in path with current os's file separator if ( amd::Os::fileSeparator() != '/') { for (std::string::iterator it = headerIncludeName.begin(), end = headerIncludeName.end(); it != end; ++it) { if (*it == '/') *it = amd::Os::fileSeparator(); } } size_t pos = headerIncludeName.rfind(amd::Os::fileSeparator()); if (pos != std::string::npos) { headerPath += amd::Os::fileSeparator(); headerPath += headerIncludeName.substr(0, pos); headerIncludeName = headerIncludeName.substr(pos+1); } if (!amd::Os::pathExists(headerPath)) { bool ret = amd::Os::createPath(headerPath); assert(ret && "failed creating path!"); newDirs.push_back(headerPath); } std::string headerFullName = headerPath + amd::Os::fileSeparator() + headerIncludeName; headerFileNames[i] = headerFullName; f.open(headerFullName.c_str(), std::fstream::out); //Should we allow asserts assert(!f.fail() && "failed creating header file!"); f.write(headers[i]->c_str(), headers[i]->length()); f.close(); Data* inc = C->NewFileReference(DT_CL_HEADER, headerFileNames[i]); if (inc == NULL) { buildLog_ += "Error while creating data from headers"; return false; } inputs.push_back(inc); } //Set the options for the compiler std::ostringstream ostrstr; std::copy(options->clangOptions.begin(), options->clangOptions.end(), std::ostream_iterator<std::string>(ostrstr, " ")); std::string driverOptions(ostrstr.str()); //Set the include path for the temp folder that contains the includes if(!headers.empty()) { driverOptions.append(" -I"); driverOptions.append(tempFolder); } const char* xLang = options->oVariables->XLang; if (xLang != NULL && strcmp(xLang, "cl")) { buildLog_ += "Unsupported OpenCL language.\n"; } //FIXME_Nikolay: the program manager should be setting the language //driverOptions.append(" -x cl"); //FIXME_Nikolay: the program manager shouls be setting the cl-std. -Xclang //is not necessary, we add it to overridde the flag set in the comp driver. driverOptions.append(" -Xclang -cl-std=").append(options->oVariables->CLStd); std::ostringstream optLevel; optLevel << " -O" << options->oVariables->OptLevel; driverOptions.append(optLevel.str()); //FIXME_lmoriche: has the CL option been validated? uint clVer = (options->oVariables->CLStd[2] - '0') * 100 + (options->oVariables->CLStd[4] - '0') * 10; std::pair<const void*, size_t> hdr; switch(clVer) { case 120: hdr = std::make_pair(opencl1_2_c_amdgcn, opencl1_2_c_amdgcn_size); break; case 200: hdr = std::make_pair(opencl2_0_c_amdgcn, opencl2_0_c_amdgcn_size); break; default: buildLog_ += "Unsupported requested OpenCL C version (-cl-std).\n"; return false; } File* pch = C->NewTempFile(DT_CL_HEADER); if (pch == NULL || !pch->WriteData((const char*) hdr.first, hdr.second)) { buildLog_ += "Error while opening the opencl-c header "; return false; } driverOptions.append(" -include-pch " + pch->Name()); driverOptions.append(" -Xclang -fno-validate-pch"); driverOptions.append(" -isysroot " + llvmBin_ + "/../../include"); driverOptions.append(hsailOptions(options)); if (clVer >= 200) { std::stringstream opts; //Add only for CL2.0 and later opts << " -D" << "CL_DEVICE_MAX_GLOBAL_VARIABLE_SIZE=" << device().info().maxGlobalVariableSize_; driverOptions.append(opts.str()); } Buffer* output = C->NewBuffer(DT_LLVM_BC); if (output == NULL) { buildLog_ += "Error while creating buffer for the LLVM bitcode"; return false; } // Tokenize the options string into a vector of strings std::istringstream istrstr(driverOptions); std::istream_iterator<std::string> sit(istrstr), end; std::vector<std::string> params(sit, end); // Compile source to IR bool ret = C->CompileToLLVMBitcode(inputs, output, params); buildLog_ += C->Output(); if (!ret) { buildLog_ += "Error while compiling opencl source: Compiling CL to IR"; return false; } llvmBinary_.assign(output->Buf().data(), output->Size()); elfSectionType_ = amd::OclElf::LLVMIR; if (options->isDumpFlagSet(amd::option::DUMP_BC_ORIGINAL)) { std::ofstream f(options->getDumpFileName("_original.bc").c_str(), std::ios::trunc); if(f.is_open()) { f.write(llvmBinary_.data(), llvmBinary_.size()); } else { buildLog_ += "Warning: opening the file to dump the compiled IR failed.\n"; } } if (clBinary()->saveSOURCE()) { clBinary()->elfOut()->addSection( amd::OclElf::SOURCE, sourceCode.data(), sourceCode.size()); } if (clBinary()->saveLLVMIR()) { clBinary()->elfOut()->addSection( amd::OclElf::LLVMIR, llvmBinary_.data(), llvmBinary_.size(), false); // store the original compile options clBinary()->storeCompileOptions(compileOptions_); } return true; } #endif // defined(WITH_LIGHTNING_COMPILER) bool HSAILProgram::compileImpl( const std::string& sourceCode, const std::vector<const std::string*>& headers, const char** headerIncludeNames, amd::option::Options* options) { #if defined(WITH_LIGHTNING_COMPILER) return compileImpl_LC(sourceCode, headers, headerIncludeNames, options); #else // !defined(WITH_LIGHTNING_COMPILER) acl_error errorCode; aclTargetInfo target; //Defaulting to bonaire //Todo (sramalin) : Query the device for asic type- //Defaulting to Bonair for now. target = g_complibApi._aclGetTargetInfo(LP64_SWITCH("hsail","hsail64"), "Bonaire", &errorCode); //end if asic info is ready // We dump the source code for each program (param: headers) // into their filenames (headerIncludeNames) into the TEMP // folder specific to the OS and add the include path while // compiling //Find the temp folder for the OS std::string tempFolder = amd::Os::getEnvironment("TEMP"); if (tempFolder.empty()) { tempFolder = amd::Os::getEnvironment("TMP"); if (tempFolder.empty()) { tempFolder = WINDOWS_SWITCH(".","/tmp");; } } //Iterate through each source code and dump it into tmp std::fstream f; std::vector<std::string> headerFileNames(headers.size()); std::vector<std::string> newDirs; for (size_t i = 0; i < headers.size(); ++i) { std::string headerPath = tempFolder; std::string headerIncludeName(headerIncludeNames[i]); // replace / in path with current os's file separator if ( amd::Os::fileSeparator() != '/') { for (std::string::iterator it = headerIncludeName.begin(), end = headerIncludeName.end(); it != end; ++it) { if (*it == '/') *it = amd::Os::fileSeparator(); } } size_t pos = headerIncludeName.rfind(amd::Os::fileSeparator()); if (pos != std::string::npos) { headerPath += amd::Os::fileSeparator(); headerPath += headerIncludeName.substr(0, pos); headerIncludeName = headerIncludeName.substr(pos+1); } if (!amd::Os::pathExists(headerPath)) { bool ret = amd::Os::createPath(headerPath); assert(ret && "failed creating path!"); newDirs.push_back(headerPath); } std::string headerFullName = headerPath + amd::Os::fileSeparator() + headerIncludeName; headerFileNames[i] = headerFullName; f.open(headerFullName.c_str(), std::fstream::out); //Should we allow asserts assert(!f.fail() && "failed creating header file!"); f.write(headers[i]->c_str(), headers[i]->length()); f.close(); } //Create Binary binaryElf_ = g_complibApi._aclBinaryInit(sizeof(aclBinary), &target, &binOpts_, &errorCode); if( errorCode!=ACL_SUCCESS ) { buildLog_ += "Error while compiling opencl source:\ aclBinary init failure \n"; LogWarning("aclBinaryInit failed"); return false; } //Insert opencl into binary errorCode = g_complibApi._aclInsertSection(device().compiler(), binaryElf_, sourceCode.c_str(), strlen(sourceCode.c_str()), aclSOURCE); if ( errorCode != ACL_SUCCESS ) { buildLog_ += "Error while converting to BRIG: \ Inserting openCl Source \n"; } //Set the options for the compiler //Set the include path for the temp folder that contains the includes if(!headers.empty()) { this->compileOptions_.append(" -I"); this->compileOptions_.append(tempFolder); } //Add only for CL2.0 and later if (options->oVariables->CLStd[2] >= '2') { std::stringstream opts; opts << " -D" << "CL_DEVICE_MAX_GLOBAL_VARIABLE_SIZE=" << device().info().maxGlobalVariableSize_; compileOptions_.append(opts.str()); } //Compile source to IR this->compileOptions_.append(hsailOptions(options)); errorCode = g_complibApi._aclCompile(device().compiler(), binaryElf_, //"-Wf,--support_all_extensions", this->compileOptions_.c_str(), ACL_TYPE_OPENCL, ACL_TYPE_LLVMIR_BINARY, logFunction); buildLog_ += g_complibApi._aclGetCompilerLog(device().compiler()); if( errorCode!=ACL_SUCCESS ) { LogWarning("aclCompile failed"); buildLog_ += "Error while compiling \ opencl source: Compiling CL to IR"; return false; } // Save the binary in the interface class saveBinaryAndSetType(TYPE_COMPILED); return true; #endif // !defined(WITH_LIGHTNING_COMPILER) } #if defined(WITH_LIGHTNING_COMPILER) #if defined(ATI_OS_LINUX) static pthread_once_t once = PTHREAD_ONCE_INIT; static void checkLLVM_BIN() { if (llvmBin_.empty()) { Dl_info info; if (dladdr((const void*)&amd::Device::init, &info)) { llvmBin_ = dirname(strdup(info.dli_fname)); size_t pos = llvmBin_.rfind("lib"); if (pos != std::string::npos) { llvmBin_.replace(pos, 3, "bin"); } } } #if defined(DEBUG) std::string clangExe(llvmBin_ + "/clang"); struct stat buf; if (stat(clangExe.c_str(), &buf)) { std::string msg("Could not find the Clang binary in " + llvmBin_); LogWarning(msg.c_str()); } #endif // defined(DEBUG) } #endif // defined(ATI_OS_LINUX) std::auto_ptr<amd::opencl_driver::Compiler> HSAILProgram::newCompilerInstance() { #if defined(ATI_OS_LINUX) pthread_once(&once, checkLLVM_BIN); #endif // defined(ATI_OS_LINUX) return std::auto_ptr<amd::opencl_driver::Compiler>( amd::opencl_driver::CompilerFactory().CreateAMDGPUCompiler(llvmBin_)); } #endif // defined(WITH_LIGHTNING_COMPILER) } // namespace roc #endif // WITHOUT_GPU_BACKEND <commit_msg>P4 to Git Change 1310397 by lmoriche@lmoriche_opencl_dev on 2016/09/02 13:55:00<commit_after>// // Copyright (c) 2008 Advanced Micro Devices, Inc. All rights reserved. // #ifndef WITHOUT_HSA_BACKEND #include <string> #include <sstream> #include <fstream> #include <iostream> #include "os/os.hpp" #include "rocdevice.hpp" #include "rocprogram.hpp" #if defined(WITH_LIGHTNING_COMPILER) #include "opencl1.2-c.amdgcn.inc" #include "opencl2.0-c.amdgcn.inc" #else // !defined(WITH_LIGHTNING_COMPILER) #include "roccompilerlib.hpp" #endif // !defined(WITH_LIGHTNING_COMPILER) #include "utils/options.hpp" #include <cstdio> #if defined(ATI_OS_LINUX) #include <dlfcn.h> #include <libgen.h> #endif // defined(ATI_OS_LINUX) #if defined(WITH_LIGHTNING_COMPILER) static std::string llvmBin_(amd::Os::getEnvironment("LLVM_BIN")); #endif // defined(WITH_LIGHTNING_COMPILER) //CLC_IN_PROCESS_CHANGE extern int openclFrontEnd(const char* cmdline, std::string*, std::string* typeInfo = NULL); namespace roc { /* Temporary log function for the compiler library */ static void logFunction(const char* msg, size_t size) { std::cout<< "Compiler Log: " << msg << std::endl; } static int programsCount = 0; #if defined(WITH_LIGHTNING_COMPILER) bool HSAILProgram::compileImpl_LC( const std::string& sourceCode, const std::vector<const std::string*>& headers, const char** headerIncludeNames, amd::option::Options* options) { using namespace amd::opencl_driver; std::auto_ptr<Compiler> C(newCompilerInstance()); std::vector<Data*> inputs; if (options->isDumpFlagSet(amd::option::DUMP_CL)) { std::ofstream f(options->getDumpFileName(".cl").c_str(), std::ios::trunc); if(f.is_open()) { f << "/* Compiler options:\n" << options->origOptionStr << "\n*/\n\n" << sourceCode; } else { buildLog_ += "Warning: opening the file to dump the OpenCL source failed.\n"; } } Data* input = C->NewBufferReference(DT_CL, sourceCode.c_str(), sourceCode.length()); if (input == NULL) { buildLog_ += "Error while creating data from source code"; return false; } inputs.push_back(input); //Find the temp folder for the OS std::string tempFolder = amd::Os::getEnvironment("TEMP"); if (tempFolder.empty()) { tempFolder = amd::Os::getEnvironment("TMP"); if (tempFolder.empty()) { tempFolder = WINDOWS_SWITCH(".","/tmp");; } } //Iterate through each source code and dump it into tmp std::fstream f; std::vector<std::string> headerFileNames(headers.size()); std::vector<std::string> newDirs; for (size_t i = 0; i < headers.size(); ++i) { std::string headerPath = tempFolder; std::string headerIncludeName(headerIncludeNames[i]); // replace / in path with current os's file separator if ( amd::Os::fileSeparator() != '/') { for (std::string::iterator it = headerIncludeName.begin(), end = headerIncludeName.end(); it != end; ++it) { if (*it == '/') *it = amd::Os::fileSeparator(); } } size_t pos = headerIncludeName.rfind(amd::Os::fileSeparator()); if (pos != std::string::npos) { headerPath += amd::Os::fileSeparator(); headerPath += headerIncludeName.substr(0, pos); headerIncludeName = headerIncludeName.substr(pos+1); } if (!amd::Os::pathExists(headerPath)) { bool ret = amd::Os::createPath(headerPath); assert(ret && "failed creating path!"); newDirs.push_back(headerPath); } std::string headerFullName = headerPath + amd::Os::fileSeparator() + headerIncludeName; headerFileNames[i] = headerFullName; f.open(headerFullName.c_str(), std::fstream::out); //Should we allow asserts assert(!f.fail() && "failed creating header file!"); f.write(headers[i]->c_str(), headers[i]->length()); f.close(); Data* inc = C->NewFileReference(DT_CL_HEADER, headerFileNames[i]); if (inc == NULL) { buildLog_ += "Error while creating data from headers"; return false; } inputs.push_back(inc); } //Set the options for the compiler std::ostringstream ostrstr; std::copy(options->clangOptions.begin(), options->clangOptions.end(), std::ostream_iterator<std::string>(ostrstr, " ")); std::string driverOptions(ostrstr.str()); //Set the include path for the temp folder that contains the includes if(!headers.empty()) { driverOptions.append(" -I"); driverOptions.append(tempFolder); } const char* xLang = options->oVariables->XLang; if (xLang != NULL && strcmp(xLang, "cl")) { buildLog_ += "Unsupported OpenCL language.\n"; } //FIXME_Nikolay: the program manager should be setting the language //driverOptions.append(" -x cl"); //FIXME_Nikolay: the program manager shouls be setting the cl-std. -Xclang //is not necessary, we add it to overridde the flag set in the comp driver. driverOptions.append(" -Xclang -cl-std=").append(options->oVariables->CLStd); std::ostringstream optLevel; optLevel << " -O" << options->oVariables->OptLevel; driverOptions.append(optLevel.str()); //FIXME_lmoriche: has the CL option been validated? uint clVer = (options->oVariables->CLStd[2] - '0') * 100 + (options->oVariables->CLStd[4] - '0') * 10; std::pair<const void*, size_t> hdr; switch(clVer) { case 120: hdr = std::make_pair(opencl1_2_c_amdgcn, opencl1_2_c_amdgcn_size); break; case 200: hdr = std::make_pair(opencl2_0_c_amdgcn, opencl2_0_c_amdgcn_size); break; default: buildLog_ += "Unsupported requested OpenCL C version (-cl-std).\n"; return false; } File* pch = C->NewTempFile(DT_CL_HEADER); if (pch == NULL || !pch->WriteData((const char*) hdr.first, hdr.second)) { buildLog_ += "Error while opening the opencl-c header "; return false; } driverOptions.append(" -include-pch " + pch->Name()); driverOptions.append(" -Xclang -fno-validate-pch"); driverOptions.append(hsailOptions(options)); if (clVer >= 200) { std::stringstream opts; //Add only for CL2.0 and later opts << " -D" << "CL_DEVICE_MAX_GLOBAL_VARIABLE_SIZE=" << device().info().maxGlobalVariableSize_; driverOptions.append(opts.str()); } Buffer* output = C->NewBuffer(DT_LLVM_BC); if (output == NULL) { buildLog_ += "Error while creating buffer for the LLVM bitcode"; return false; } // Tokenize the options string into a vector of strings std::istringstream istrstr(driverOptions); std::istream_iterator<std::string> sit(istrstr), end; std::vector<std::string> params(sit, end); // Compile source to IR bool ret = C->CompileToLLVMBitcode(inputs, output, params); buildLog_ += C->Output(); if (!ret) { buildLog_ += "Error while compiling opencl source: Compiling CL to IR"; return false; } llvmBinary_.assign(output->Buf().data(), output->Size()); elfSectionType_ = amd::OclElf::LLVMIR; if (options->isDumpFlagSet(amd::option::DUMP_BC_ORIGINAL)) { std::ofstream f(options->getDumpFileName("_original.bc").c_str(), std::ios::trunc); if(f.is_open()) { f.write(llvmBinary_.data(), llvmBinary_.size()); } else { buildLog_ += "Warning: opening the file to dump the compiled IR failed.\n"; } } if (clBinary()->saveSOURCE()) { clBinary()->elfOut()->addSection( amd::OclElf::SOURCE, sourceCode.data(), sourceCode.size()); } if (clBinary()->saveLLVMIR()) { clBinary()->elfOut()->addSection( amd::OclElf::LLVMIR, llvmBinary_.data(), llvmBinary_.size(), false); // store the original compile options clBinary()->storeCompileOptions(compileOptions_); } return true; } #endif // defined(WITH_LIGHTNING_COMPILER) bool HSAILProgram::compileImpl( const std::string& sourceCode, const std::vector<const std::string*>& headers, const char** headerIncludeNames, amd::option::Options* options) { #if defined(WITH_LIGHTNING_COMPILER) return compileImpl_LC(sourceCode, headers, headerIncludeNames, options); #else // !defined(WITH_LIGHTNING_COMPILER) acl_error errorCode; aclTargetInfo target; //Defaulting to bonaire //Todo (sramalin) : Query the device for asic type- //Defaulting to Bonair for now. target = g_complibApi._aclGetTargetInfo(LP64_SWITCH("hsail","hsail64"), "Bonaire", &errorCode); //end if asic info is ready // We dump the source code for each program (param: headers) // into their filenames (headerIncludeNames) into the TEMP // folder specific to the OS and add the include path while // compiling //Find the temp folder for the OS std::string tempFolder = amd::Os::getEnvironment("TEMP"); if (tempFolder.empty()) { tempFolder = amd::Os::getEnvironment("TMP"); if (tempFolder.empty()) { tempFolder = WINDOWS_SWITCH(".","/tmp");; } } //Iterate through each source code and dump it into tmp std::fstream f; std::vector<std::string> headerFileNames(headers.size()); std::vector<std::string> newDirs; for (size_t i = 0; i < headers.size(); ++i) { std::string headerPath = tempFolder; std::string headerIncludeName(headerIncludeNames[i]); // replace / in path with current os's file separator if ( amd::Os::fileSeparator() != '/') { for (std::string::iterator it = headerIncludeName.begin(), end = headerIncludeName.end(); it != end; ++it) { if (*it == '/') *it = amd::Os::fileSeparator(); } } size_t pos = headerIncludeName.rfind(amd::Os::fileSeparator()); if (pos != std::string::npos) { headerPath += amd::Os::fileSeparator(); headerPath += headerIncludeName.substr(0, pos); headerIncludeName = headerIncludeName.substr(pos+1); } if (!amd::Os::pathExists(headerPath)) { bool ret = amd::Os::createPath(headerPath); assert(ret && "failed creating path!"); newDirs.push_back(headerPath); } std::string headerFullName = headerPath + amd::Os::fileSeparator() + headerIncludeName; headerFileNames[i] = headerFullName; f.open(headerFullName.c_str(), std::fstream::out); //Should we allow asserts assert(!f.fail() && "failed creating header file!"); f.write(headers[i]->c_str(), headers[i]->length()); f.close(); } //Create Binary binaryElf_ = g_complibApi._aclBinaryInit(sizeof(aclBinary), &target, &binOpts_, &errorCode); if( errorCode!=ACL_SUCCESS ) { buildLog_ += "Error while compiling opencl source:\ aclBinary init failure \n"; LogWarning("aclBinaryInit failed"); return false; } //Insert opencl into binary errorCode = g_complibApi._aclInsertSection(device().compiler(), binaryElf_, sourceCode.c_str(), strlen(sourceCode.c_str()), aclSOURCE); if ( errorCode != ACL_SUCCESS ) { buildLog_ += "Error while converting to BRIG: \ Inserting openCl Source \n"; } //Set the options for the compiler //Set the include path for the temp folder that contains the includes if(!headers.empty()) { this->compileOptions_.append(" -I"); this->compileOptions_.append(tempFolder); } //Add only for CL2.0 and later if (options->oVariables->CLStd[2] >= '2') { std::stringstream opts; opts << " -D" << "CL_DEVICE_MAX_GLOBAL_VARIABLE_SIZE=" << device().info().maxGlobalVariableSize_; compileOptions_.append(opts.str()); } //Compile source to IR this->compileOptions_.append(hsailOptions(options)); errorCode = g_complibApi._aclCompile(device().compiler(), binaryElf_, //"-Wf,--support_all_extensions", this->compileOptions_.c_str(), ACL_TYPE_OPENCL, ACL_TYPE_LLVMIR_BINARY, logFunction); buildLog_ += g_complibApi._aclGetCompilerLog(device().compiler()); if( errorCode!=ACL_SUCCESS ) { LogWarning("aclCompile failed"); buildLog_ += "Error while compiling \ opencl source: Compiling CL to IR"; return false; } // Save the binary in the interface class saveBinaryAndSetType(TYPE_COMPILED); return true; #endif // !defined(WITH_LIGHTNING_COMPILER) } #if defined(WITH_LIGHTNING_COMPILER) #if defined(ATI_OS_LINUX) static pthread_once_t once = PTHREAD_ONCE_INIT; static void checkLLVM_BIN() { if (llvmBin_.empty()) { Dl_info info; if (dladdr((const void*)&amd::Device::init, &info)) { llvmBin_ = dirname(strdup(info.dli_fname)); size_t pos = llvmBin_.rfind("lib"); if (pos != std::string::npos) { llvmBin_.replace(pos, 3, "bin"); } } } #if defined(DEBUG) std::string clangExe(llvmBin_ + "/clang"); struct stat buf; if (stat(clangExe.c_str(), &buf)) { std::string msg("Could not find the Clang binary in " + llvmBin_); LogWarning(msg.c_str()); } #endif // defined(DEBUG) } #endif // defined(ATI_OS_LINUX) std::auto_ptr<amd::opencl_driver::Compiler> HSAILProgram::newCompilerInstance() { #if defined(ATI_OS_LINUX) pthread_once(&once, checkLLVM_BIN); #endif // defined(ATI_OS_LINUX) return std::auto_ptr<amd::opencl_driver::Compiler>( amd::opencl_driver::CompilerFactory().CreateAMDGPUCompiler(llvmBin_)); } #endif // defined(WITH_LIGHTNING_COMPILER) } // namespace roc #endif // WITHOUT_GPU_BACKEND <|endoftext|>
<commit_before>#include "blackhole/formatter/json.hpp" #include <array> #include <boost/variant/apply_visitor.hpp> #ifndef RAPIDJSON_HAS_STDSTRING #define RAPIDJSON_HAS_STDSTRING 1 #endif #include <rapidjson/document.h> #include <rapidjson/stringbuffer.h> #include <rapidjson/writer.h> #include <rapidjson/pointer.h> #include "blackhole/record.hpp" #include "blackhole/extensions/writer.hpp" #include "blackhole/detail/attribute.hpp" #include "blackhole/detail/unimplemented.hpp" namespace blackhole { namespace formatter { namespace { struct visitor_t { typedef void result_type; rapidjson::Value& node; rapidjson::MemoryPoolAllocator<>& allocator; const string_view& name; auto operator()(std::nullptr_t) -> void { node.AddMember(rapidjson::StringRef(name.data(), name.size()), rapidjson::kNullType, allocator); } auto operator()(bool value) -> void { node.AddMember(rapidjson::StringRef(name.data(), name.size()), value, allocator); } auto operator()(std::int64_t value) -> void { node.AddMember(rapidjson::StringRef(name.data(), name.size()), value, allocator); } auto operator()(std::uint64_t value) -> void { node.AddMember(rapidjson::StringRef(name.data(), name.size()), value, allocator); } auto operator()(double value) -> void { node.AddMember(rapidjson::StringRef(name.data(), name.size()), value, allocator); } auto operator()(const string_view& value) -> void { node.AddMember(rapidjson::StringRef(name.data(), name.size()), rapidjson::StringRef(value.data(), value.size()), allocator); } }; template<typename Map, typename F> inline auto find(const Map& map, const typename Map::key_type& key, const F& fn) -> typename Map::mapped_type { const auto it = map.find(key); if (it == map.end()) { return fn(); } else { return it->second; } } /// A RapidJSON Stream concept implementation required to avoid intermediate buffer allocation. struct stream_t { typedef char Ch; writer_t& wr; /// Writes a character directly into the underlying buffer. auto Put(Ch c) -> void { wr.inner << c; } /// Does nothing, because there is no intermediate buffer. auto Flush() -> void {} }; template<typename> class builder; } // namespace class json_t::factory_t { public: // A JSON routing pointer for attributes that weren't mentioned in `routing` map. rapidjson::Pointer rest; // Routing map from attribute name to its JSON pointer. std::unordered_map<std::string, rapidjson::Pointer> routing; factory_t() : rest("") {} factory_t(routing_t routing) : rest(routing.unspecified) { for (const auto& route : routing.specified) { for (const auto& name : route.second) { this->routing.insert({name, rapidjson::Pointer(route.first)}); } } } template<typename Document> auto get(const string_view& name, Document& root) -> rapidjson::Value& { const auto& route = find(routing, name.to_string(), [&]() -> const rapidjson::Pointer& { return rest; }); return route.GetWithDefault(root, rapidjson::kObjectType); } template<typename Document> auto create(Document& root, const record_t& record) -> builder<Document>; }; template<typename Document> class json_t::builder { Document& root; const record_t& record; factory_t& factory; public: builder(Document& root, const record_t& record, factory_t& factory) : root(root), record(record), factory(factory) {} auto message() -> void { apply("message", record.message()); } auto severity() -> void { apply("severity", static_cast<std::int64_t>(record.severity())); } auto timestamp() -> void { apply("timestamp", std::chrono::duration_cast< std::chrono::microseconds >(record.timestamp().time_since_epoch()).count()); } auto build(writer_t& writer) -> void { stream_t stream{writer}; rapidjson::Writer<stream_t> wr(stream); root.Accept(wr); } auto attributes() -> void { // TODO: Make flattened range // TODO: Make uniqued range. for (const auto& attributes : record.attributes()) { for (const auto& attribute : attributes.get()) { apply(attribute.first, attribute.second); } } } private: template<typename T> auto apply(const string_view& name, const T& value) -> void { visitor_t visitor{factory.get(name, root), root.GetAllocator(), name}; visitor(value); } auto apply(const string_view& name, const attribute::view_t& value) -> void { visitor_t visitor{factory.get(name, root), root.GetAllocator(), name}; boost::apply_visitor(visitor, value.inner().value); } }; template<typename Document> auto json_t::factory_t::create(Document& root, const record_t& record) -> builder<Document> { return builder<Document>{root, record, *this}; } json_t::json_t() : factory(new factory_t) {} json_t::json_t(routing_t routing) : factory(new factory_t(std::move(routing))) {} json_t::~json_t() {} auto json_t::format(const record_t& record, writer_t& writer) -> void { typedef rapidjson::GenericDocument< rapidjson::UTF8<>, rapidjson::MemoryPoolAllocator<>, rapidjson::MemoryPoolAllocator<> > document_type; std::array<char, 4096> value_buffer; std::array<char, 1024> parse_buffer; rapidjson::MemoryPoolAllocator<> value_allocator(value_buffer.data(), value_buffer.size()); rapidjson::MemoryPoolAllocator<> parse_allocator(parse_buffer.data(), parse_buffer.size()); document_type root(&value_allocator, parse_buffer.size(), &parse_allocator); root.SetObject(); // TODO: Try to use `AutoUTF<>` or `AutoUTFOutputStream` for UTF-8 validation. auto builder = factory->create(root, record); builder.message(); builder.severity(); builder.timestamp(); builder.attributes(); builder.build(writer); // TODO: Add newline if required. Obtained through config. // if (config.newline) { // writer << '\n'; // } } } // namespace formatter } // namespace blackhole <commit_msg>refactor(formatter/json): reuse the code<commit_after>#include "blackhole/formatter/json.hpp" #include <array> #include <boost/variant/apply_visitor.hpp> #ifndef RAPIDJSON_HAS_STDSTRING #define RAPIDJSON_HAS_STDSTRING 1 #endif #include <rapidjson/document.h> #include <rapidjson/stringbuffer.h> #include <rapidjson/writer.h> #include <rapidjson/pointer.h> #include "blackhole/record.hpp" #include "blackhole/extensions/writer.hpp" #include "blackhole/detail/attribute.hpp" #include "blackhole/detail/unimplemented.hpp" namespace blackhole { namespace formatter { namespace { struct visitor_t { typedef void result_type; rapidjson::Value& node; rapidjson::MemoryPoolAllocator<>& allocator; const string_view& name; auto operator()(std::nullptr_t) -> void { node.AddMember(rapidjson::StringRef(name.data(), name.size()), rapidjson::kNullType, allocator); } // For `bool`, `std::int64_t`, `std::uint64_t` and `double` types. template<typename T> auto operator()(T value) -> void { static_assert( std::is_same<T, bool>::value || std::is_same<T, std::int64_t>::value || std::is_same<T, std::uint64_t>::value || std::is_same<T, double>::value, "type mismatch"); node.AddMember(rapidjson::StringRef(name.data(), name.size()), value, allocator); } auto operator()(const string_view& value) -> void { node.AddMember(rapidjson::StringRef(name.data(), name.size()), rapidjson::StringRef(value.data(), value.size()), allocator); } }; template<typename Map, typename F> inline auto find(const Map& map, const typename Map::key_type& key, const F& fn) -> typename Map::mapped_type { const auto it = map.find(key); if (it == map.end()) { return fn(); } else { return it->second; } } /// A RapidJSON Stream concept implementation required to avoid intermediate buffer allocation. struct stream_t { typedef char Ch; writer_t& wr; /// Writes a character directly into the underlying buffer. auto Put(Ch c) -> void { wr.inner << c; } /// Does nothing, because there is no intermediate buffer. auto Flush() -> void {} }; template<typename> class builder; } // namespace class json_t::factory_t { public: // A JSON routing pointer for attributes that weren't mentioned in `routing` map. rapidjson::Pointer rest; // Routing map from attribute name to its JSON pointer. std::unordered_map<std::string, rapidjson::Pointer> routing; factory_t() : rest("") {} factory_t(routing_t routing) : rest(routing.unspecified) { for (const auto& route : routing.specified) { for (const auto& name : route.second) { this->routing.insert({name, rapidjson::Pointer(route.first)}); } } } template<typename Document> auto get(const string_view& name, Document& root) -> rapidjson::Value& { const auto& route = find(routing, name.to_string(), [&]() -> const rapidjson::Pointer& { return rest; }); return route.GetWithDefault(root, rapidjson::kObjectType); } template<typename Document> auto create(Document& root, const record_t& record) -> builder<Document>; }; template<typename Document> class json_t::builder { Document& root; const record_t& record; factory_t& factory; public: builder(Document& root, const record_t& record, factory_t& factory) : root(root), record(record), factory(factory) {} auto message() -> void { apply("message", record.message()); } auto severity() -> void { apply("severity", static_cast<std::int64_t>(record.severity())); } auto timestamp() -> void { apply("timestamp", std::chrono::duration_cast< std::chrono::microseconds >(record.timestamp().time_since_epoch()).count()); } auto build(writer_t& writer) -> void { stream_t stream{writer}; rapidjson::Writer<stream_t> wr(stream); root.Accept(wr); } auto attributes() -> void { // TODO: Make flattened range // TODO: Make uniqued range. for (const auto& attributes : record.attributes()) { for (const auto& attribute : attributes.get()) { apply(attribute.first, attribute.second); } } } private: template<typename T> auto apply(const string_view& name, const T& value) -> void { visitor_t visitor{factory.get(name, root), root.GetAllocator(), name}; visitor(value); } auto apply(const string_view& name, const attribute::view_t& value) -> void { visitor_t visitor{factory.get(name, root), root.GetAllocator(), name}; boost::apply_visitor(visitor, value.inner().value); } }; template<typename Document> auto json_t::factory_t::create(Document& root, const record_t& record) -> builder<Document> { return builder<Document>{root, record, *this}; } json_t::json_t() : factory(new factory_t) {} json_t::json_t(routing_t routing) : factory(new factory_t(std::move(routing))) {} json_t::~json_t() {} auto json_t::format(const record_t& record, writer_t& writer) -> void { typedef rapidjson::GenericDocument< rapidjson::UTF8<>, rapidjson::MemoryPoolAllocator<>, rapidjson::MemoryPoolAllocator<> > document_type; std::array<char, 4096> value_buffer; std::array<char, 1024> parse_buffer; rapidjson::MemoryPoolAllocator<> value_allocator(value_buffer.data(), value_buffer.size()); rapidjson::MemoryPoolAllocator<> parse_allocator(parse_buffer.data(), parse_buffer.size()); document_type root(&value_allocator, parse_buffer.size(), &parse_allocator); root.SetObject(); // TODO: Try to use `AutoUTF<>` or `AutoUTFOutputStream` for UTF-8 validation. auto builder = factory->create(root, record); builder.message(); builder.severity(); builder.timestamp(); builder.attributes(); builder.build(writer); // TODO: Add newline if required. Obtained through config. // if (config.newline) { // writer << '\n'; // } } } // namespace formatter } // namespace blackhole <|endoftext|>